blob: f2e051c615b52f003805de743d26a4d0ee63b768 [file] [log] [blame]
Alex Lorenzee024992014-08-04 18:41:51 +00001//===--- CoverageMappingGen.cpp - Coverage mapping generation ---*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Instrumentation-based code coverage mapping generator
11//
12//===----------------------------------------------------------------------===//
13
14#include "CoverageMappingGen.h"
15#include "CodeGenFunction.h"
16#include "clang/AST/StmtVisitor.h"
17#include "clang/Lex/Lexer.h"
Vedant Kumarbc6b80a2016-01-28 17:52:18 +000018#include "llvm/ADT/SmallSet.h"
Vedant Kumarca3326c2016-01-21 19:25:35 +000019#include "llvm/ADT/StringExtras.h"
Justin Bognerbf42cfd2015-02-18 21:24:51 +000020#include "llvm/ADT/Optional.h"
Easwaran Ramanb014ee42016-04-29 18:53:16 +000021#include "llvm/ProfileData/Coverage/CoverageMapping.h"
22#include "llvm/ProfileData/Coverage/CoverageMappingReader.h"
23#include "llvm/ProfileData/Coverage/CoverageMappingWriter.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000024#include "llvm/ProfileData/InstrProfReader.h"
Alex Lorenzee024992014-08-04 18:41:51 +000025#include "llvm/Support/FileSystem.h"
Vedant Kumar14f8fb62016-07-18 21:01:27 +000026#include "llvm/Support/Path.h"
Alex Lorenzee024992014-08-04 18:41:51 +000027
28using namespace clang;
29using namespace CodeGen;
30using namespace llvm::coverage;
31
32void CoverageSourceInfo::SourceRangeSkipped(SourceRange Range) {
33 SkippedRanges.push_back(Range);
34}
35
36namespace {
37
38/// \brief A region of source code that can be mapped to a counter.
Justin Bogner09c71792014-10-01 03:33:49 +000039class SourceMappingRegion {
Alex Lorenzee024992014-08-04 18:41:51 +000040 Counter Count;
41
Alex Lorenzee024992014-08-04 18:41:51 +000042 /// \brief The region's starting location.
Justin Bognerbf42cfd2015-02-18 21:24:51 +000043 Optional<SourceLocation> LocStart;
Alex Lorenzee024992014-08-04 18:41:51 +000044
45 /// \brief The region's ending location.
Justin Bognerbf42cfd2015-02-18 21:24:51 +000046 Optional<SourceLocation> LocEnd;
Alex Lorenzee024992014-08-04 18:41:51 +000047
Justin Bogner09c71792014-10-01 03:33:49 +000048public:
Justin Bognerbf42cfd2015-02-18 21:24:51 +000049 SourceMappingRegion(Counter Count, Optional<SourceLocation> LocStart,
Vedant Kumara7764ad2017-08-05 00:34:10 +000050 Optional<SourceLocation> LocEnd)
51 : Count(Count), LocStart(LocStart), LocEnd(LocEnd) {}
Alex Lorenzee024992014-08-04 18:41:51 +000052
Justin Bogner09c71792014-10-01 03:33:49 +000053 const Counter &getCounter() const { return Count; }
54
Justin Bognerbf42cfd2015-02-18 21:24:51 +000055 void setCounter(Counter C) { Count = C; }
Justin Bogner09c71792014-10-01 03:33:49 +000056
Justin Bognerbf42cfd2015-02-18 21:24:51 +000057 bool hasStartLoc() const { return LocStart.hasValue(); }
58
59 void setStartLoc(SourceLocation Loc) { LocStart = Loc; }
60
Craig Topper462c77b2015-09-26 05:10:14 +000061 SourceLocation getStartLoc() const {
Justin Bognerbf42cfd2015-02-18 21:24:51 +000062 assert(LocStart && "Region has no start location");
63 return *LocStart;
Justin Bogner09c71792014-10-01 03:33:49 +000064 }
65
Justin Bognerbf42cfd2015-02-18 21:24:51 +000066 bool hasEndLoc() const { return LocEnd.hasValue(); }
Alex Lorenzee024992014-08-04 18:41:51 +000067
Justin Bognerbf42cfd2015-02-18 21:24:51 +000068 void setEndLoc(SourceLocation Loc) { LocEnd = Loc; }
Alex Lorenzee024992014-08-04 18:41:51 +000069
Craig Topper462c77b2015-09-26 05:10:14 +000070 SourceLocation getEndLoc() const {
Justin Bognerbf42cfd2015-02-18 21:24:51 +000071 assert(LocEnd && "Region has no end location");
72 return *LocEnd;
Alex Lorenzee024992014-08-04 18:41:51 +000073 }
74};
75
Vedant Kumard7369642017-07-27 02:20:25 +000076/// Spelling locations for the start and end of a source region.
77struct SpellingRegion {
78 /// The line where the region starts.
79 unsigned LineStart;
80
81 /// The column where the region starts.
82 unsigned ColumnStart;
83
84 /// The line where the region ends.
85 unsigned LineEnd;
86
87 /// The column where the region ends.
88 unsigned ColumnEnd;
89
90 SpellingRegion(SourceManager &SM, SourceLocation LocStart,
91 SourceLocation LocEnd) {
92 LineStart = SM.getSpellingLineNumber(LocStart);
93 ColumnStart = SM.getSpellingColumnNumber(LocStart);
94 LineEnd = SM.getSpellingLineNumber(LocEnd);
95 ColumnEnd = SM.getSpellingColumnNumber(LocEnd);
96 }
97
98 /// Check if the start and end locations appear in source order, i.e
99 /// top->bottom, left->right.
100 bool isInSourceOrder() const {
101 return (LineStart < LineEnd) ||
102 (LineStart == LineEnd && ColumnStart <= ColumnEnd);
103 }
104};
105
Alex Lorenzee024992014-08-04 18:41:51 +0000106/// \brief Provides the common functionality for the different
107/// coverage mapping region builders.
108class CoverageMappingBuilder {
109public:
110 CoverageMappingModuleGen &CVM;
111 SourceManager &SM;
112 const LangOptions &LangOpts;
113
114private:
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000115 /// \brief Map of clang's FileIDs to IDs used for coverage mapping.
116 llvm::SmallDenseMap<FileID, std::pair<unsigned, SourceLocation>, 8>
117 FileIDMapping;
Alex Lorenzee024992014-08-04 18:41:51 +0000118
119public:
Alex Lorenzee024992014-08-04 18:41:51 +0000120 /// \brief The coverage mapping regions for this function
121 llvm::SmallVector<CounterMappingRegion, 32> MappingRegions;
122 /// \brief The source mapping regions for this function.
Justin Bognerf59329b2014-10-01 03:33:52 +0000123 std::vector<SourceMappingRegion> SourceRegions;
Alex Lorenzee024992014-08-04 18:41:51 +0000124
Igor Kudrinfc05ee32016-08-31 07:04:16 +0000125 /// \brief A set of regions which can be used as a filter.
126 ///
127 /// It is produced by emitExpansionRegions() and is used in
128 /// emitSourceRegions() to suppress producing code regions if
129 /// the same area is covered by expansion regions.
130 typedef llvm::SmallSet<std::pair<SourceLocation, SourceLocation>, 8>
131 SourceRegionFilter;
132
Alex Lorenzee024992014-08-04 18:41:51 +0000133 CoverageMappingBuilder(CoverageMappingModuleGen &CVM, SourceManager &SM,
134 const LangOptions &LangOpts)
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000135 : CVM(CVM), SM(SM), LangOpts(LangOpts) {}
Alex Lorenzee024992014-08-04 18:41:51 +0000136
137 /// \brief Return the precise end location for the given token.
138 SourceLocation getPreciseTokenLocEnd(SourceLocation Loc) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000139 // We avoid getLocForEndOfToken here, because it doesn't do what we want for
140 // macro locations, which we just treat as expanded files.
141 unsigned TokLen =
142 Lexer::MeasureTokenLength(SM.getSpellingLoc(Loc), SM, LangOpts);
143 return Loc.getLocWithOffset(TokLen);
Alex Lorenzee024992014-08-04 18:41:51 +0000144 }
145
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000146 /// \brief Return the start location of an included file or expanded macro.
147 SourceLocation getStartOfFileOrMacro(SourceLocation Loc) {
148 if (Loc.isMacroID())
149 return Loc.getLocWithOffset(-SM.getFileOffset(Loc));
150 return SM.getLocForStartOfFile(SM.getFileID(Loc));
Alex Lorenzee024992014-08-04 18:41:51 +0000151 }
152
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000153 /// \brief Return the end location of an included file or expanded macro.
154 SourceLocation getEndOfFileOrMacro(SourceLocation Loc) {
155 if (Loc.isMacroID())
156 return Loc.getLocWithOffset(SM.getFileIDSize(SM.getFileID(Loc)) -
Justin Bognerf14b2072015-03-25 04:13:49 +0000157 SM.getFileOffset(Loc));
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000158 return SM.getLocForEndOfFile(SM.getFileID(Loc));
159 }
160
161 /// \brief Find out where the current file is included or macro is expanded.
162 SourceLocation getIncludeOrExpansionLoc(SourceLocation Loc) {
163 return Loc.isMacroID() ? SM.getImmediateExpansionRange(Loc).first
164 : SM.getIncludeLoc(SM.getFileID(Loc));
165 }
166
Justin Bogner682bfbf2015-05-14 22:14:10 +0000167 /// \brief Return true if \c Loc is a location in a built-in macro.
168 bool isInBuiltin(SourceLocation Loc) {
Mehdi Amini99d1b292016-10-01 16:38:28 +0000169 return SM.getBufferName(SM.getSpellingLoc(Loc)) == "<built-in>";
Justin Bogner682bfbf2015-05-14 22:14:10 +0000170 }
171
Igor Kudrind9e1a612016-06-07 10:07:51 +0000172 /// \brief Check whether \c Loc is included or expanded from \c Parent.
173 bool isNestedIn(SourceLocation Loc, FileID Parent) {
174 do {
175 Loc = getIncludeOrExpansionLoc(Loc);
176 if (Loc.isInvalid())
177 return false;
178 } while (!SM.isInFileID(Loc, Parent));
179 return true;
180 }
181
Justin Bogner682bfbf2015-05-14 22:14:10 +0000182 /// \brief Get the start of \c S ignoring macro arguments and builtin macros.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000183 SourceLocation getStart(const Stmt *S) {
184 SourceLocation Loc = S->getLocStart();
Justin Bogner682bfbf2015-05-14 22:14:10 +0000185 while (SM.isMacroArgExpansion(Loc) || isInBuiltin(Loc))
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000186 Loc = SM.getImmediateExpansionRange(Loc).first;
187 return Loc;
188 }
189
Justin Bogner682bfbf2015-05-14 22:14:10 +0000190 /// \brief Get the end of \c S ignoring macro arguments and builtin macros.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000191 SourceLocation getEnd(const Stmt *S) {
192 SourceLocation Loc = S->getLocEnd();
Justin Bogner682bfbf2015-05-14 22:14:10 +0000193 while (SM.isMacroArgExpansion(Loc) || isInBuiltin(Loc))
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000194 Loc = SM.getImmediateExpansionRange(Loc).first;
Justin Bognerf14b2072015-03-25 04:13:49 +0000195 return getPreciseTokenLocEnd(Loc);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000196 }
197
198 /// \brief Find the set of files we have regions for and assign IDs
199 ///
200 /// Fills \c Mapping with the virtual file mapping needed to write out
201 /// coverage and collects the necessary file information to emit source and
202 /// expansion regions.
203 void gatherFileIDs(SmallVectorImpl<unsigned> &Mapping) {
204 FileIDMapping.clear();
205
Vedant Kumarbc6b80a2016-01-28 17:52:18 +0000206 llvm::SmallSet<FileID, 8> Visited;
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000207 SmallVector<std::pair<SourceLocation, unsigned>, 8> FileLocs;
208 for (const auto &Region : SourceRegions) {
209 SourceLocation Loc = Region.getStartLoc();
210 FileID File = SM.getFileID(Loc);
Vedant Kumarbc6b80a2016-01-28 17:52:18 +0000211 if (!Visited.insert(File).second)
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000212 continue;
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000213
Vedant Kumar93205af2016-07-11 22:57:46 +0000214 // Do not map FileID's associated with system headers.
215 if (SM.isInSystemHeader(SM.getSpellingLoc(Loc)))
216 continue;
217
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000218 unsigned Depth = 0;
219 for (SourceLocation Parent = getIncludeOrExpansionLoc(Loc);
Yaron Kerened1fe5d2015-10-03 05:15:57 +0000220 Parent.isValid(); Parent = getIncludeOrExpansionLoc(Parent))
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000221 ++Depth;
222 FileLocs.push_back(std::make_pair(Loc, Depth));
223 }
224 std::stable_sort(FileLocs.begin(), FileLocs.end(), llvm::less_second());
225
226 for (const auto &FL : FileLocs) {
227 SourceLocation Loc = FL.first;
228 FileID SpellingFile = SM.getDecomposedSpellingLoc(Loc).first;
229 auto Entry = SM.getFileEntryForID(SpellingFile);
230 if (!Entry)
231 continue;
232
233 FileIDMapping[SM.getFileID(Loc)] = std::make_pair(Mapping.size(), Loc);
234 Mapping.push_back(CVM.getFileID(Entry));
235 }
236 }
237
238 /// \brief Get the coverage mapping file ID for \c Loc.
239 ///
240 /// If such file id doesn't exist, return None.
241 Optional<unsigned> getCoverageFileID(SourceLocation Loc) {
242 auto Mapping = FileIDMapping.find(SM.getFileID(Loc));
Justin Bogner903678c2015-01-24 20:22:32 +0000243 if (Mapping != FileIDMapping.end())
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000244 return Mapping->second.first;
245 return None;
Alex Lorenzee024992014-08-04 18:41:51 +0000246 }
247
Alex Lorenzee024992014-08-04 18:41:51 +0000248 /// \brief Gather all the regions that were skipped by the preprocessor
249 /// using the constructs like #if.
250 void gatherSkippedRegions() {
251 /// An array of the minimum lineStarts and the maximum lineEnds
252 /// for mapping regions from the appropriate source files.
253 llvm::SmallVector<std::pair<unsigned, unsigned>, 8> FileLineRanges;
254 FileLineRanges.resize(
255 FileIDMapping.size(),
256 std::make_pair(std::numeric_limits<unsigned>::max(), 0));
257 for (const auto &R : MappingRegions) {
258 FileLineRanges[R.FileID].first =
259 std::min(FileLineRanges[R.FileID].first, R.LineStart);
260 FileLineRanges[R.FileID].second =
261 std::max(FileLineRanges[R.FileID].second, R.LineEnd);
262 }
263
264 auto SkippedRanges = CVM.getSourceInfo().getSkippedRanges();
265 for (const auto &I : SkippedRanges) {
266 auto LocStart = I.getBegin();
267 auto LocEnd = I.getEnd();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000268 assert(SM.isWrittenInSameFile(LocStart, LocEnd) &&
269 "region spans multiple files");
Alex Lorenzee024992014-08-04 18:41:51 +0000270
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000271 auto CovFileID = getCoverageFileID(LocStart);
Justin Bogner903678c2015-01-24 20:22:32 +0000272 if (!CovFileID)
Alex Lorenzee024992014-08-04 18:41:51 +0000273 continue;
Vedant Kumard7369642017-07-27 02:20:25 +0000274 SpellingRegion SR{SM, LocStart, LocEnd};
Justin Bognerfd34280b2015-02-03 23:59:48 +0000275 auto Region = CounterMappingRegion::makeSkipped(
Vedant Kumard7369642017-07-27 02:20:25 +0000276 *CovFileID, SR.LineStart, SR.ColumnStart, SR.LineEnd, SR.ColumnEnd);
Alex Lorenzee024992014-08-04 18:41:51 +0000277 // Make sure that we only collect the regions that are inside
278 // the souce code of this function.
Justin Bogner903678c2015-01-24 20:22:32 +0000279 if (Region.LineStart >= FileLineRanges[*CovFileID].first &&
280 Region.LineEnd <= FileLineRanges[*CovFileID].second)
Alex Lorenzee024992014-08-04 18:41:51 +0000281 MappingRegions.push_back(Region);
282 }
283 }
284
Alex Lorenzee024992014-08-04 18:41:51 +0000285 /// \brief Generate the coverage counter mapping regions from collected
286 /// source regions.
Igor Kudrinfc05ee32016-08-31 07:04:16 +0000287 void emitSourceRegions(const SourceRegionFilter &Filter) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000288 for (const auto &Region : SourceRegions) {
289 assert(Region.hasEndLoc() && "incomplete region");
Alex Lorenzee024992014-08-04 18:41:51 +0000290
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000291 SourceLocation LocStart = Region.getStartLoc();
Yaron Keren8b563662015-10-03 10:46:20 +0000292 assert(SM.getFileID(LocStart).isValid() && "region in invalid file");
Justin Bognerf59329b2014-10-01 03:33:52 +0000293
Vedant Kumar93205af2016-07-11 22:57:46 +0000294 // Ignore regions from system headers.
295 if (SM.isInSystemHeader(SM.getSpellingLoc(LocStart)))
296 continue;
297
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000298 auto CovFileID = getCoverageFileID(LocStart);
299 // Ignore regions that don't have a file, such as builtin macros.
300 if (!CovFileID)
Alex Lorenzee024992014-08-04 18:41:51 +0000301 continue;
302
Justin Bognerf14b2072015-03-25 04:13:49 +0000303 SourceLocation LocEnd = Region.getEndLoc();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000304 assert(SM.isWrittenInSameFile(LocStart, LocEnd) &&
305 "region spans multiple files");
306
Igor Kudrinfc05ee32016-08-31 07:04:16 +0000307 // Don't add code regions for the area covered by expansion regions.
308 // This not only suppresses redundant regions, but sometimes prevents
309 // creating regions with wrong counters if, for example, a statement's
310 // body ends at the end of a nested macro.
311 if (Filter.count(std::make_pair(LocStart, LocEnd)))
312 continue;
313
Vedant Kumard7369642017-07-27 02:20:25 +0000314 // Find the spelling locations for the mapping region.
315 SpellingRegion SR{SM, LocStart, LocEnd};
316 assert(SR.isInSourceOrder() && "region start and end out of order");
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000317 MappingRegions.push_back(CounterMappingRegion::makeRegion(
Vedant Kumard7369642017-07-27 02:20:25 +0000318 Region.getCounter(), *CovFileID, SR.LineStart, SR.ColumnStart,
319 SR.LineEnd, SR.ColumnEnd));
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000320 }
321 }
322
323 /// \brief Generate expansion regions for each virtual file we've seen.
Igor Kudrinfc05ee32016-08-31 07:04:16 +0000324 SourceRegionFilter emitExpansionRegions() {
325 SourceRegionFilter Filter;
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000326 for (const auto &FM : FileIDMapping) {
327 SourceLocation ExpandedLoc = FM.second.second;
328 SourceLocation ParentLoc = getIncludeOrExpansionLoc(ExpandedLoc);
329 if (ParentLoc.isInvalid())
Alex Lorenzee024992014-08-04 18:41:51 +0000330 continue;
331
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000332 auto ParentFileID = getCoverageFileID(ParentLoc);
333 if (!ParentFileID)
334 continue;
335 auto ExpandedFileID = getCoverageFileID(ExpandedLoc);
336 assert(ExpandedFileID && "expansion in uncovered file");
337
338 SourceLocation LocEnd = getPreciseTokenLocEnd(ParentLoc);
339 assert(SM.isWrittenInSameFile(ParentLoc, LocEnd) &&
340 "region spans multiple files");
Igor Kudrinfc05ee32016-08-31 07:04:16 +0000341 Filter.insert(std::make_pair(ParentLoc, LocEnd));
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000342
Vedant Kumard7369642017-07-27 02:20:25 +0000343 SpellingRegion SR{SM, ParentLoc, LocEnd};
344 assert(SR.isInSourceOrder() && "region start and end out of order");
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000345 MappingRegions.push_back(CounterMappingRegion::makeExpansion(
Vedant Kumard7369642017-07-27 02:20:25 +0000346 *ParentFileID, *ExpandedFileID, SR.LineStart, SR.ColumnStart,
347 SR.LineEnd, SR.ColumnEnd));
Alex Lorenzee024992014-08-04 18:41:51 +0000348 }
Igor Kudrinfc05ee32016-08-31 07:04:16 +0000349 return Filter;
Alex Lorenzee024992014-08-04 18:41:51 +0000350 }
351};
352
353/// \brief Creates unreachable coverage regions for the functions that
354/// are not emitted.
355struct EmptyCoverageMappingBuilder : public CoverageMappingBuilder {
356 EmptyCoverageMappingBuilder(CoverageMappingModuleGen &CVM, SourceManager &SM,
357 const LangOptions &LangOpts)
358 : CoverageMappingBuilder(CVM, SM, LangOpts) {}
359
360 void VisitDecl(const Decl *D) {
361 if (!D->hasBody())
362 return;
363 auto Body = D->getBody();
Igor Kudrind9e1a612016-06-07 10:07:51 +0000364 SourceLocation Start = getStart(Body);
365 SourceLocation End = getEnd(Body);
366 if (!SM.isWrittenInSameFile(Start, End)) {
367 // Walk up to find the common ancestor.
368 // Correct the locations accordingly.
369 FileID StartFileID = SM.getFileID(Start);
370 FileID EndFileID = SM.getFileID(End);
371 while (StartFileID != EndFileID && !isNestedIn(End, StartFileID)) {
372 Start = getIncludeOrExpansionLoc(Start);
373 assert(Start.isValid() &&
374 "Declaration start location not nested within a known region");
375 StartFileID = SM.getFileID(Start);
376 }
377 while (StartFileID != EndFileID) {
378 End = getPreciseTokenLocEnd(getIncludeOrExpansionLoc(End));
379 assert(End.isValid() &&
380 "Declaration end location not nested within a known region");
381 EndFileID = SM.getFileID(End);
382 }
383 }
384 SourceRegions.emplace_back(Counter(), Start, End);
Alex Lorenzee024992014-08-04 18:41:51 +0000385 }
386
387 /// \brief Write the mapping data to the output stream
388 void write(llvm::raw_ostream &OS) {
Alex Lorenzee024992014-08-04 18:41:51 +0000389 SmallVector<unsigned, 16> FileIDMapping;
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000390 gatherFileIDs(FileIDMapping);
Igor Kudrinfc05ee32016-08-31 07:04:16 +0000391 emitSourceRegions(SourceRegionFilter());
Alex Lorenzee024992014-08-04 18:41:51 +0000392
Vedant Kumarefd319a2016-07-26 00:24:59 +0000393 if (MappingRegions.empty())
394 return;
395
Craig Topper5fc8fc22014-08-27 06:28:36 +0000396 CoverageMappingWriter Writer(FileIDMapping, None, MappingRegions);
Alex Lorenzee024992014-08-04 18:41:51 +0000397 Writer.write(OS);
398 }
399};
400
401/// \brief A StmtVisitor that creates coverage mapping regions which map
402/// from the source code locations to the PGO counters.
403struct CounterCoverageMappingBuilder
404 : public CoverageMappingBuilder,
405 public ConstStmtVisitor<CounterCoverageMappingBuilder> {
406 /// \brief The map of statements to count values.
407 llvm::DenseMap<const Stmt *, unsigned> &CounterMap;
408
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000409 /// \brief A stack of currently live regions.
410 std::vector<SourceMappingRegion> RegionStack;
Alex Lorenzee024992014-08-04 18:41:51 +0000411
412 CounterExpressionBuilder Builder;
413
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000414 /// \brief A location in the most recently visited file or macro.
415 ///
416 /// This is used to adjust the active source regions appropriately when
417 /// expressions cross file or macro boundaries.
418 SourceLocation MostRecentLocation;
419
420 /// \brief Return a counter for the subtraction of \c RHS from \c LHS
Alex Lorenzee024992014-08-04 18:41:51 +0000421 Counter subtractCounters(Counter LHS, Counter RHS) {
422 return Builder.subtract(LHS, RHS);
423 }
424
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000425 /// \brief Return a counter for the sum of \c LHS and \c RHS.
Alex Lorenzee024992014-08-04 18:41:51 +0000426 Counter addCounters(Counter LHS, Counter RHS) {
427 return Builder.add(LHS, RHS);
428 }
429
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000430 Counter addCounters(Counter C1, Counter C2, Counter C3) {
431 return addCounters(addCounters(C1, C2), C3);
432 }
433
Alex Lorenzee024992014-08-04 18:41:51 +0000434 /// \brief Return the region counter for the given statement.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000435 ///
Alex Lorenzee024992014-08-04 18:41:51 +0000436 /// This should only be called on statements that have a dedicated counter.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000437 Counter getRegionCounter(const Stmt *S) {
438 return Counter::getCounter(CounterMap[S]);
Alex Lorenzee024992014-08-04 18:41:51 +0000439 }
440
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000441 /// \brief Push a region onto the stack.
442 ///
443 /// Returns the index on the stack where the region was pushed. This can be
444 /// used with popRegions to exit a "scope", ending the region that was pushed.
445 size_t pushRegion(Counter Count, Optional<SourceLocation> StartLoc = None,
446 Optional<SourceLocation> EndLoc = None) {
Vedant Kumara7764ad2017-08-05 00:34:10 +0000447 if (StartLoc)
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000448 MostRecentLocation = *StartLoc;
449 RegionStack.emplace_back(Count, StartLoc, EndLoc);
Alex Lorenzee024992014-08-04 18:41:51 +0000450
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000451 return RegionStack.size() - 1;
Alex Lorenzee024992014-08-04 18:41:51 +0000452 }
453
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000454 /// \brief Pop regions from the stack into the function's list of regions.
455 ///
456 /// Adds all regions from \c ParentIndex to the top of the stack to the
457 /// function's \c SourceRegions.
458 void popRegions(size_t ParentIndex) {
459 assert(RegionStack.size() >= ParentIndex && "parent not in stack");
460 while (RegionStack.size() > ParentIndex) {
461 SourceMappingRegion &Region = RegionStack.back();
462 if (Region.hasStartLoc()) {
463 SourceLocation StartLoc = Region.getStartLoc();
464 SourceLocation EndLoc = Region.hasEndLoc()
465 ? Region.getEndLoc()
466 : RegionStack[ParentIndex].getEndLoc();
467 while (!SM.isWrittenInSameFile(StartLoc, EndLoc)) {
468 // The region ends in a nested file or macro expansion. Create a
469 // separate region for each expansion.
470 SourceLocation NestedLoc = getStartOfFileOrMacro(EndLoc);
471 assert(SM.isWrittenInSameFile(NestedLoc, EndLoc));
472
Igor Kudrin8545dae2016-08-29 11:48:50 +0000473 if (!isRegionAlreadyAdded(NestedLoc, EndLoc))
474 SourceRegions.emplace_back(Region.getCounter(), NestedLoc, EndLoc);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000475
Justin Bognerf14b2072015-03-25 04:13:49 +0000476 EndLoc = getPreciseTokenLocEnd(getIncludeOrExpansionLoc(EndLoc));
Justin Bognerdceaaad2015-07-17 23:31:21 +0000477 if (EndLoc.isInvalid())
478 llvm::report_fatal_error("File exit not handled before popRegions");
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000479 }
480 Region.setEndLoc(EndLoc);
481
482 MostRecentLocation = EndLoc;
483 // If this region happens to span an entire expansion, we need to make
484 // sure we don't overlap the parent region with it.
485 if (StartLoc == getStartOfFileOrMacro(StartLoc) &&
486 EndLoc == getEndOfFileOrMacro(EndLoc))
487 MostRecentLocation = getIncludeOrExpansionLoc(EndLoc);
488
489 assert(SM.isWrittenInSameFile(Region.getStartLoc(), EndLoc));
Craig Topperf36a5c42015-09-26 05:10:16 +0000490 SourceRegions.push_back(Region);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000491 }
492 RegionStack.pop_back();
493 }
Alex Lorenzee024992014-08-04 18:41:51 +0000494 }
495
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000496 /// \brief Return the currently active region.
497 SourceMappingRegion &getRegion() {
498 assert(!RegionStack.empty() && "statement has no region");
499 return RegionStack.back();
500 }
Alex Lorenzee024992014-08-04 18:41:51 +0000501
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000502 /// \brief Propagate counts through the children of \c S.
503 Counter propagateCounts(Counter TopCount, const Stmt *S) {
Vedant Kumar78386962017-07-27 02:20:20 +0000504 SourceLocation StartLoc = getStart(S);
505 SourceLocation EndLoc = getEnd(S);
506 size_t Index = pushRegion(TopCount, StartLoc, EndLoc);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000507 Visit(S);
508 Counter ExitCount = getRegion().getCounter();
509 popRegions(Index);
Vedant Kumar39f01972016-02-08 19:25:45 +0000510
511 // The statement may be spanned by an expansion. Make sure we handle a file
512 // exit out of this expansion before moving to the next statement.
Vedant Kumar78386962017-07-27 02:20:20 +0000513 if (SM.isBeforeInTranslationUnit(StartLoc, S->getLocStart()))
514 MostRecentLocation = EndLoc;
Vedant Kumar39f01972016-02-08 19:25:45 +0000515
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000516 return ExitCount;
517 }
Alex Lorenzee024992014-08-04 18:41:51 +0000518
Igor Kudrin0a7c9d12016-05-04 15:38:26 +0000519 /// \brief Check whether a region with bounds \c StartLoc and \c EndLoc
520 /// is already added to \c SourceRegions.
521 bool isRegionAlreadyAdded(SourceLocation StartLoc, SourceLocation EndLoc) {
522 return SourceRegions.rend() !=
523 std::find_if(SourceRegions.rbegin(), SourceRegions.rend(),
524 [&](const SourceMappingRegion &Region) {
525 return Region.getStartLoc() == StartLoc &&
526 Region.getEndLoc() == EndLoc;
527 });
528 }
529
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000530 /// \brief Adjust the most recently visited location to \c EndLoc.
531 ///
532 /// This should be used after visiting any statements in non-source order.
533 void adjustForOutOfOrderTraversal(SourceLocation EndLoc) {
534 MostRecentLocation = EndLoc;
Igor Kudrin0a7c9d12016-05-04 15:38:26 +0000535 // The code region for a whole macro is created in handleFileExit() when
536 // it detects exiting of the virtual file of that macro. If we visited
537 // statements in non-source order, we might already have such a region
538 // added, for example, if a body of a loop is divided among multiple
539 // macros. Avoid adding duplicate regions in such case.
Justin Bogner96ae73f2015-05-01 19:23:34 +0000540 if (getRegion().hasEndLoc() &&
Igor Kudrin0a7c9d12016-05-04 15:38:26 +0000541 MostRecentLocation == getEndOfFileOrMacro(MostRecentLocation) &&
542 isRegionAlreadyAdded(getStartOfFileOrMacro(MostRecentLocation),
543 MostRecentLocation))
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000544 MostRecentLocation = getIncludeOrExpansionLoc(MostRecentLocation);
545 }
Alex Lorenzee024992014-08-04 18:41:51 +0000546
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000547 /// \brief Adjust regions and state when \c NewLoc exits a file.
548 ///
549 /// If moving from our most recently tracked location to \c NewLoc exits any
550 /// files, this adjusts our current region stack and creates the file regions
551 /// for the exited file.
552 void handleFileExit(SourceLocation NewLoc) {
Justin Bognere44dd6d2015-06-23 20:29:09 +0000553 if (NewLoc.isInvalid() ||
554 SM.isWrittenInSameFile(MostRecentLocation, NewLoc))
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000555 return;
556
557 // If NewLoc is not in a file that contains MostRecentLocation, walk up to
558 // find the common ancestor.
559 SourceLocation LCA = NewLoc;
560 FileID ParentFile = SM.getFileID(LCA);
561 while (!isNestedIn(MostRecentLocation, ParentFile)) {
562 LCA = getIncludeOrExpansionLoc(LCA);
563 if (LCA.isInvalid() || SM.isWrittenInSameFile(LCA, MostRecentLocation)) {
564 // Since there isn't a common ancestor, no file was exited. We just need
565 // to adjust our location to the new file.
566 MostRecentLocation = NewLoc;
567 return;
568 }
569 ParentFile = SM.getFileID(LCA);
Alex Lorenzee024992014-08-04 18:41:51 +0000570 }
571
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000572 llvm::SmallSet<SourceLocation, 8> StartLocs;
573 Optional<Counter> ParentCounter;
Pete Cooper57d3f142015-07-30 17:22:52 +0000574 for (SourceMappingRegion &I : llvm::reverse(RegionStack)) {
575 if (!I.hasStartLoc())
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000576 continue;
Pete Cooper57d3f142015-07-30 17:22:52 +0000577 SourceLocation Loc = I.getStartLoc();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000578 if (!isNestedIn(Loc, ParentFile)) {
Pete Cooper57d3f142015-07-30 17:22:52 +0000579 ParentCounter = I.getCounter();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000580 break;
581 }
Alex Lorenzee024992014-08-04 18:41:51 +0000582
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000583 while (!SM.isInFileID(Loc, ParentFile)) {
584 // The most nested region for each start location is the one with the
585 // correct count. We avoid creating redundant regions by stopping once
586 // we've seen this region.
587 if (StartLocs.insert(Loc).second)
Pete Cooper57d3f142015-07-30 17:22:52 +0000588 SourceRegions.emplace_back(I.getCounter(), Loc,
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000589 getEndOfFileOrMacro(Loc));
590 Loc = getIncludeOrExpansionLoc(Loc);
591 }
Pete Cooper57d3f142015-07-30 17:22:52 +0000592 I.setStartLoc(getPreciseTokenLocEnd(Loc));
Alex Lorenzee024992014-08-04 18:41:51 +0000593 }
594
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000595 if (ParentCounter) {
596 // If the file is contained completely by another region and doesn't
597 // immediately start its own region, the whole file gets a region
598 // corresponding to the parent.
599 SourceLocation Loc = MostRecentLocation;
600 while (isNestedIn(Loc, ParentFile)) {
601 SourceLocation FileStart = getStartOfFileOrMacro(Loc);
602 if (StartLocs.insert(FileStart).second)
603 SourceRegions.emplace_back(*ParentCounter, FileStart,
604 getEndOfFileOrMacro(Loc));
605 Loc = getIncludeOrExpansionLoc(Loc);
606 }
Alex Lorenzee024992014-08-04 18:41:51 +0000607 }
608
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000609 MostRecentLocation = NewLoc;
610 }
Alex Lorenzee024992014-08-04 18:41:51 +0000611
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000612 /// \brief Ensure that \c S is included in the current region.
613 void extendRegion(const Stmt *S) {
614 SourceMappingRegion &Region = getRegion();
615 SourceLocation StartLoc = getStart(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000616
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000617 handleFileExit(StartLoc);
618 if (!Region.hasStartLoc())
619 Region.setStartLoc(StartLoc);
620 }
621
622 /// \brief Mark \c S as a terminator, starting a zero region.
623 void terminateRegion(const Stmt *S) {
624 extendRegion(S);
625 SourceMappingRegion &Region = getRegion();
626 if (!Region.hasEndLoc())
627 Region.setEndLoc(getEnd(S));
628 pushRegion(Counter::getZero());
629 }
Alex Lorenzee024992014-08-04 18:41:51 +0000630
631 /// \brief Keep counts of breaks and continues inside loops.
632 struct BreakContinue {
633 Counter BreakCount;
634 Counter ContinueCount;
635 };
636 SmallVector<BreakContinue, 8> BreakContinueStack;
637
638 CounterCoverageMappingBuilder(
639 CoverageMappingModuleGen &CVM,
Justin Bognere5ee6c52014-10-02 16:44:01 +0000640 llvm::DenseMap<const Stmt *, unsigned> &CounterMap, SourceManager &SM,
Alex Lorenzee024992014-08-04 18:41:51 +0000641 const LangOptions &LangOpts)
Vedant Kumara7764ad2017-08-05 00:34:10 +0000642 : CoverageMappingBuilder(CVM, SM, LangOpts), CounterMap(CounterMap) {}
Alex Lorenzee024992014-08-04 18:41:51 +0000643
644 /// \brief Write the mapping data to the output stream
645 void write(llvm::raw_ostream &OS) {
Alex Lorenzee024992014-08-04 18:41:51 +0000646 llvm::SmallVector<unsigned, 8> VirtualFileMapping;
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000647 gatherFileIDs(VirtualFileMapping);
Igor Kudrinfc05ee32016-08-31 07:04:16 +0000648 SourceRegionFilter Filter = emitExpansionRegions();
649 emitSourceRegions(Filter);
Alex Lorenzee024992014-08-04 18:41:51 +0000650 gatherSkippedRegions();
651
Vedant Kumarefd319a2016-07-26 00:24:59 +0000652 if (MappingRegions.empty())
653 return;
654
Justin Bogner4da909b2015-02-03 21:35:49 +0000655 CoverageMappingWriter Writer(VirtualFileMapping, Builder.getExpressions(),
656 MappingRegions);
Alex Lorenzee024992014-08-04 18:41:51 +0000657 Writer.write(OS);
658 }
659
Alex Lorenzee024992014-08-04 18:41:51 +0000660 void VisitStmt(const Stmt *S) {
Yaron Kerened1fe5d2015-10-03 05:15:57 +0000661 if (S->getLocStart().isValid())
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000662 extendRegion(S);
Benjamin Kramer642f1732015-07-02 21:03:14 +0000663 for (const Stmt *Child : S->children())
664 if (Child)
665 this->Visit(Child);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000666 handleFileExit(getEnd(S));
Alex Lorenzee024992014-08-04 18:41:51 +0000667 }
668
Alex Lorenzee024992014-08-04 18:41:51 +0000669 void VisitDecl(const Decl *D) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000670 Stmt *Body = D->getBody();
Vedant Kumarefd319a2016-07-26 00:24:59 +0000671
672 // Do not propagate region counts into system headers.
673 if (Body && SM.isInSystemHeader(SM.getSpellingLoc(getStart(Body))))
674 return;
675
Vedant Kumara7764ad2017-08-05 00:34:10 +0000676 propagateCounts(getRegionCounter(Body), Body);
Alex Lorenzee024992014-08-04 18:41:51 +0000677 }
678
679 void VisitReturnStmt(const ReturnStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000680 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000681 if (S->getRetValue())
682 Visit(S->getRetValue());
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000683 terminateRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000684 }
685
Justin Bognerf959feb2015-04-28 06:31:55 +0000686 void VisitCXXThrowExpr(const CXXThrowExpr *E) {
687 extendRegion(E);
688 if (E->getSubExpr())
689 Visit(E->getSubExpr());
690 terminateRegion(E);
691 }
692
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000693 void VisitGotoStmt(const GotoStmt *S) { terminateRegion(S); }
Alex Lorenzee024992014-08-04 18:41:51 +0000694
695 void VisitLabelStmt(const LabelStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000696 SourceLocation Start = getStart(S);
697 // We can't extendRegion here or we risk overlapping with our new region.
698 handleFileExit(Start);
699 pushRegion(getRegionCounter(S), Start);
Alex Lorenzee024992014-08-04 18:41:51 +0000700 Visit(S->getSubStmt());
701 }
702
703 void VisitBreakStmt(const BreakStmt *S) {
Alex Lorenzee024992014-08-04 18:41:51 +0000704 assert(!BreakContinueStack.empty() && "break not in a loop or switch!");
705 BreakContinueStack.back().BreakCount = addCounters(
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000706 BreakContinueStack.back().BreakCount, getRegion().getCounter());
Eli Friedman7f53fbfc2017-08-02 23:22:50 +0000707 // FIXME: a break in a switch should terminate regions for all preceding
708 // case statements, not just the most recent one.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000709 terminateRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000710 }
711
712 void VisitContinueStmt(const ContinueStmt *S) {
Alex Lorenzee024992014-08-04 18:41:51 +0000713 assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
714 BreakContinueStack.back().ContinueCount = addCounters(
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000715 BreakContinueStack.back().ContinueCount, getRegion().getCounter());
716 terminateRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000717 }
718
Eli Friedman181dfe42017-08-08 20:10:14 +0000719 void VisitCallExpr(const CallExpr *E) {
720 VisitStmt(E);
721
722 // Terminate the region when we hit a noreturn function.
723 // (This is helpful dealing with switch statements.)
724 QualType CalleeType = E->getCallee()->getType();
725 if (getFunctionExtInfo(*CalleeType).getNoReturn())
726 terminateRegion(E);
727 }
728
Alex Lorenzee024992014-08-04 18:41:51 +0000729 void VisitWhileStmt(const WhileStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000730 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000731
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000732 Counter ParentCount = getRegion().getCounter();
733 Counter BodyCount = getRegionCounter(S);
734
735 // Handle the body first so that we can get the backedge count.
736 BreakContinueStack.push_back(BreakContinue());
737 extendRegion(S->getBody());
738 Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
Alex Lorenzee024992014-08-04 18:41:51 +0000739 BreakContinue BC = BreakContinueStack.pop_back_val();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000740
741 // Go back to handle the condition.
742 Counter CondCount =
743 addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
744 propagateCounts(CondCount, S->getCond());
745 adjustForOutOfOrderTraversal(getEnd(S));
746
747 Counter OutCount =
748 addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount));
749 if (OutCount != ParentCount)
750 pushRegion(OutCount);
Alex Lorenzee024992014-08-04 18:41:51 +0000751 }
752
753 void VisitDoStmt(const DoStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000754 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000755
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000756 Counter ParentCount = getRegion().getCounter();
757 Counter BodyCount = getRegionCounter(S);
758
759 BreakContinueStack.push_back(BreakContinue());
760 extendRegion(S->getBody());
761 Counter BackedgeCount =
762 propagateCounts(addCounters(ParentCount, BodyCount), S->getBody());
Alex Lorenzee024992014-08-04 18:41:51 +0000763 BreakContinue BC = BreakContinueStack.pop_back_val();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000764
765 Counter CondCount = addCounters(BackedgeCount, BC.ContinueCount);
766 propagateCounts(CondCount, S->getCond());
767
768 Counter OutCount =
769 addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount));
770 if (OutCount != ParentCount)
771 pushRegion(OutCount);
Alex Lorenzee024992014-08-04 18:41:51 +0000772 }
773
774 void VisitForStmt(const ForStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000775 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000776 if (S->getInit())
777 Visit(S->getInit());
778
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000779 Counter ParentCount = getRegion().getCounter();
780 Counter BodyCount = getRegionCounter(S);
781
782 // Handle the body first so that we can get the backedge count.
Alex Lorenzee024992014-08-04 18:41:51 +0000783 BreakContinueStack.push_back(BreakContinue());
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000784 extendRegion(S->getBody());
785 Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
786 BreakContinue BC = BreakContinueStack.pop_back_val();
Alex Lorenzee024992014-08-04 18:41:51 +0000787
788 // The increment is essentially part of the body but it needs to include
789 // the count for all the continue statements.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000790 if (const Stmt *Inc = S->getInc())
791 propagateCounts(addCounters(BackedgeCount, BC.ContinueCount), Inc);
792
793 // Go back to handle the condition.
794 Counter CondCount =
795 addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
796 if (const Expr *Cond = S->getCond()) {
797 propagateCounts(CondCount, Cond);
798 adjustForOutOfOrderTraversal(getEnd(S));
Alex Lorenzee024992014-08-04 18:41:51 +0000799 }
800
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000801 Counter OutCount =
802 addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount));
803 if (OutCount != ParentCount)
804 pushRegion(OutCount);
Alex Lorenzee024992014-08-04 18:41:51 +0000805 }
806
807 void VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000808 extendRegion(S);
809 Visit(S->getLoopVarStmt());
Alex Lorenzee024992014-08-04 18:41:51 +0000810 Visit(S->getRangeStmt());
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000811
812 Counter ParentCount = getRegion().getCounter();
813 Counter BodyCount = getRegionCounter(S);
814
Alex Lorenzee024992014-08-04 18:41:51 +0000815 BreakContinueStack.push_back(BreakContinue());
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000816 extendRegion(S->getBody());
817 Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
Alex Lorenzee024992014-08-04 18:41:51 +0000818 BreakContinue BC = BreakContinueStack.pop_back_val();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000819
Justin Bogner15874322015-04-30 21:31:02 +0000820 Counter LoopCount =
821 addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
822 Counter OutCount =
823 addCounters(BC.BreakCount, subtractCounters(LoopCount, BodyCount));
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000824 if (OutCount != ParentCount)
825 pushRegion(OutCount);
Alex Lorenzee024992014-08-04 18:41:51 +0000826 }
827
828 void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000829 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000830 Visit(S->getElement());
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000831
832 Counter ParentCount = getRegion().getCounter();
833 Counter BodyCount = getRegionCounter(S);
834
Alex Lorenzee024992014-08-04 18:41:51 +0000835 BreakContinueStack.push_back(BreakContinue());
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000836 extendRegion(S->getBody());
837 Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
Alex Lorenzee024992014-08-04 18:41:51 +0000838 BreakContinue BC = BreakContinueStack.pop_back_val();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000839
Justin Bogner15874322015-04-30 21:31:02 +0000840 Counter LoopCount =
841 addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
842 Counter OutCount =
843 addCounters(BC.BreakCount, subtractCounters(LoopCount, BodyCount));
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000844 if (OutCount != ParentCount)
845 pushRegion(OutCount);
Alex Lorenzee024992014-08-04 18:41:51 +0000846 }
847
848 void VisitSwitchStmt(const SwitchStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000849 extendRegion(S);
Vedant Kumarf2a6ec52016-10-14 23:38:13 +0000850 if (S->getInit())
851 Visit(S->getInit());
Alex Lorenzee024992014-08-04 18:41:51 +0000852 Visit(S->getCond());
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000853
Alex Lorenzee024992014-08-04 18:41:51 +0000854 BreakContinueStack.push_back(BreakContinue());
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000855
856 const Stmt *Body = S->getBody();
857 extendRegion(Body);
858 if (const auto *CS = dyn_cast<CompoundStmt>(Body)) {
859 if (!CS->body_empty()) {
Eli Friedman7f53fbfc2017-08-02 23:22:50 +0000860 // Make a region for the body of the switch. If the body starts with
861 // a case, that case will reuse this region; otherwise, this covers
862 // the unreachable code at the beginning of the switch body.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000863 size_t Index =
Eli Friedman7f53fbfc2017-08-02 23:22:50 +0000864 pushRegion(Counter::getZero(), getStart(CS->body_front()));
Richard Trieub5841332015-04-15 01:21:42 +0000865 for (const auto *Child : CS->children())
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000866 Visit(Child);
Eli Friedman7f53fbfc2017-08-02 23:22:50 +0000867
868 // Set the end for the body of the switch, if it isn't already set.
869 for (size_t i = RegionStack.size(); i != Index; --i) {
870 if (!RegionStack[i - 1].hasEndLoc())
871 RegionStack[i - 1].setEndLoc(getEnd(CS->body_back()));
872 }
873
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000874 popRegions(Index);
Alex Lorenzee024992014-08-04 18:41:51 +0000875 }
Vedant Kumar87ea3b02016-05-31 20:35:12 +0000876 } else
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000877 propagateCounts(Counter::getZero(), Body);
Alex Lorenzee024992014-08-04 18:41:51 +0000878 BreakContinue BC = BreakContinueStack.pop_back_val();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000879
Alex Lorenzee024992014-08-04 18:41:51 +0000880 if (!BreakContinueStack.empty())
881 BreakContinueStack.back().ContinueCount = addCounters(
882 BreakContinueStack.back().ContinueCount, BC.ContinueCount);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000883
884 Counter ExitCount = getRegionCounter(S);
Vedant Kumar38364822016-05-31 18:06:19 +0000885 SourceLocation ExitLoc = getEnd(S);
Alex Lorenz08780522016-09-27 23:30:36 +0000886 pushRegion(ExitCount);
887
888 // Ensure that handleFileExit recognizes when the end location is located
889 // in a different file.
890 MostRecentLocation = getStart(S);
Vedant Kumar38364822016-05-31 18:06:19 +0000891 handleFileExit(ExitLoc);
Alex Lorenzee024992014-08-04 18:41:51 +0000892 }
893
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000894 void VisitSwitchCase(const SwitchCase *S) {
895 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000896
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000897 SourceMappingRegion &Parent = getRegion();
898
899 Counter Count = addCounters(Parent.getCounter(), getRegionCounter(S));
900 // Reuse the existing region if it starts at our label. This is typical of
901 // the first case in a switch.
902 if (Parent.hasStartLoc() && Parent.getStartLoc() == getStart(S))
903 Parent.setCounter(Count);
904 else
905 pushRegion(Count, getStart(S));
906
Sanjay Patel376c06c2015-12-24 21:11:29 +0000907 if (const auto *CS = dyn_cast<CaseStmt>(S)) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000908 Visit(CS->getLHS());
909 if (const Expr *RHS = CS->getRHS())
910 Visit(RHS);
911 }
Alex Lorenzee024992014-08-04 18:41:51 +0000912 Visit(S->getSubStmt());
913 }
914
915 void VisitIfStmt(const IfStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000916 extendRegion(S);
Vedant Kumar9d2a16b2016-10-14 23:38:16 +0000917 if (S->getInit())
918 Visit(S->getInit());
919
Justin Bogner055ebc32015-06-16 06:24:15 +0000920 // Extend into the condition before we propagate through it below - this is
921 // needed to handle macros that generate the "if" but not the condition.
922 extendRegion(S->getCond());
Alex Lorenzee024992014-08-04 18:41:51 +0000923
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000924 Counter ParentCount = getRegion().getCounter();
925 Counter ThenCount = getRegionCounter(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000926
Justin Bogner91f2e3c2015-02-19 03:10:30 +0000927 // Emitting a counter for the condition makes it easier to interpret the
928 // counter for the body when looking at the coverage.
929 propagateCounts(ParentCount, S->getCond());
930
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000931 extendRegion(S->getThen());
932 Counter OutCount = propagateCounts(ThenCount, S->getThen());
933
934 Counter ElseCount = subtractCounters(ParentCount, ThenCount);
935 if (const Stmt *Else = S->getElse()) {
936 extendRegion(S->getElse());
937 OutCount = addCounters(OutCount, propagateCounts(ElseCount, Else));
938 } else
939 OutCount = addCounters(OutCount, ElseCount);
940
941 if (OutCount != ParentCount)
942 pushRegion(OutCount);
Alex Lorenzee024992014-08-04 18:41:51 +0000943 }
944
945 void VisitCXXTryStmt(const CXXTryStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000946 extendRegion(S);
Vedant Kumar049908b2016-06-22 19:57:58 +0000947 // Handle macros that generate the "try" but not the rest.
948 extendRegion(S->getTryBlock());
949
950 Counter ParentCount = getRegion().getCounter();
951 propagateCounts(ParentCount, S->getTryBlock());
952
Alex Lorenzee024992014-08-04 18:41:51 +0000953 for (unsigned I = 0, E = S->getNumHandlers(); I < E; ++I)
954 Visit(S->getHandler(I));
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000955
956 Counter ExitCount = getRegionCounter(S);
957 pushRegion(ExitCount);
Alex Lorenzee024992014-08-04 18:41:51 +0000958 }
959
960 void VisitCXXCatchStmt(const CXXCatchStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000961 propagateCounts(getRegionCounter(S), S->getHandlerBlock());
Alex Lorenzee024992014-08-04 18:41:51 +0000962 }
963
964 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000965 extendRegion(E);
Alex Lorenzee024992014-08-04 18:41:51 +0000966
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000967 Counter ParentCount = getRegion().getCounter();
968 Counter TrueCount = getRegionCounter(E);
Alex Lorenzee024992014-08-04 18:41:51 +0000969
Justin Bognere3654ce2015-04-24 23:37:57 +0000970 Visit(E->getCond());
971
972 if (!isa<BinaryConditionalOperator>(E)) {
973 extendRegion(E->getTrueExpr());
974 propagateCounts(TrueCount, E->getTrueExpr());
975 }
976 extendRegion(E->getFalseExpr());
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000977 propagateCounts(subtractCounters(ParentCount, TrueCount),
978 E->getFalseExpr());
Alex Lorenzee024992014-08-04 18:41:51 +0000979 }
980
981 void VisitBinLAnd(const BinaryOperator *E) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000982 extendRegion(E);
Alex Lorenzee024992014-08-04 18:41:51 +0000983 Visit(E->getLHS());
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000984
985 extendRegion(E->getRHS());
986 propagateCounts(getRegionCounter(E), E->getRHS());
Alex Lorenzee024992014-08-04 18:41:51 +0000987 }
988
989 void VisitBinLOr(const BinaryOperator *E) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000990 extendRegion(E);
Alex Lorenzee024992014-08-04 18:41:51 +0000991 Visit(E->getLHS());
Alex Lorenzee024992014-08-04 18:41:51 +0000992
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000993 extendRegion(E->getRHS());
994 propagateCounts(getRegionCounter(E), E->getRHS());
Alex Lorenz01a0d062014-08-20 17:10:56 +0000995 }
Justin Bognerc1091022015-02-24 04:13:56 +0000996
997 void VisitLambdaExpr(const LambdaExpr *LE) {
998 // Lambdas are treated as their own functions for now, so we shouldn't
999 // propagate counts into them.
1000 }
Alex Lorenzee024992014-08-04 18:41:51 +00001001};
Alex Lorenzee024992014-08-04 18:41:51 +00001002
Xinliang David Li1f39fcf2017-04-14 04:14:29 +00001003std::string getCoverageSection(const CodeGenModule &CGM) {
Vedant Kumar8a767a42017-04-15 00:10:05 +00001004 return llvm::getInstrProfSectionName(
1005 llvm::IPSK_covmap,
1006 CGM.getContext().getTargetInfo().getTriple().getObjectFormat());
Alex Lorenzee024992014-08-04 18:41:51 +00001007}
1008
Vedant Kumar14f8fb62016-07-18 21:01:27 +00001009std::string normalizeFilename(StringRef Filename) {
1010 llvm::SmallString<256> Path(Filename);
Vedant Kumar14f8fb62016-07-18 21:01:27 +00001011 llvm::sys::fs::make_absolute(Path);
Vedant Kumard04929d2016-07-18 22:32:02 +00001012 llvm::sys::path::remove_dots(Path, /*remove_dot_dots=*/true);
Vedant Kumar14f8fb62016-07-18 21:01:27 +00001013 return Path.str().str();
1014}
1015
1016} // end anonymous namespace
1017
Justin Bognera432d172015-02-03 00:20:24 +00001018static void dump(llvm::raw_ostream &OS, StringRef FunctionName,
1019 ArrayRef<CounterExpression> Expressions,
1020 ArrayRef<CounterMappingRegion> Regions) {
1021 OS << FunctionName << ":\n";
1022 CounterMappingContext Ctx(Expressions);
1023 for (const auto &R : Regions) {
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00001024 OS.indent(2);
1025 switch (R.Kind) {
1026 case CounterMappingRegion::CodeRegion:
1027 break;
1028 case CounterMappingRegion::ExpansionRegion:
1029 OS << "Expansion,";
1030 break;
1031 case CounterMappingRegion::SkippedRegion:
1032 OS << "Skipped,";
1033 break;
1034 }
1035
Justin Bogner4da909b2015-02-03 21:35:49 +00001036 OS << "File " << R.FileID << ", " << R.LineStart << ":" << R.ColumnStart
1037 << " -> " << R.LineEnd << ":" << R.ColumnEnd << " = ";
Justin Bognerf69dc342015-01-23 23:46:13 +00001038 Ctx.dump(R.Count, OS);
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00001039 if (R.Kind == CounterMappingRegion::ExpansionRegion)
Justin Bogner4da909b2015-02-03 21:35:49 +00001040 OS << " (Expanded file = " << R.ExpandedFileID << ")";
1041 OS << "\n";
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00001042 }
1043}
1044
Alex Lorenzee024992014-08-04 18:41:51 +00001045void CoverageMappingModuleGen::addFunctionMappingRecord(
Xinliang David Li2129ae52016-01-07 20:05:55 +00001046 llvm::GlobalVariable *NamePtr, StringRef NameValue, uint64_t FuncHash,
Xinliang David Li848da132016-01-19 00:49:06 +00001047 const std::string &CoverageMapping, bool IsUsed) {
Alex Lorenzee024992014-08-04 18:41:51 +00001048 llvm::LLVMContext &Ctx = CGM.getLLVMContext();
Alex Lorenzee024992014-08-04 18:41:51 +00001049 if (!FunctionRecordTy) {
Xinliang David Li2129ae52016-01-07 20:05:55 +00001050#define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) LLVMType,
Xinliang David Lia026a432015-11-05 05:46:39 +00001051 llvm::Type *FunctionRecordTypes[] = {
1052 #include "llvm/ProfileData/InstrProfData.inc"
1053 };
Alex Lorenzee024992014-08-04 18:41:51 +00001054 FunctionRecordTy =
Justin Bogner4dc5adc2015-07-02 20:47:25 +00001055 llvm::StructType::get(Ctx, makeArrayRef(FunctionRecordTypes),
1056 /*isPacked=*/true);
Alex Lorenzee024992014-08-04 18:41:51 +00001057 }
1058
Xinliang David Lia026a432015-11-05 05:46:39 +00001059 #define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) Init,
Alex Lorenzee024992014-08-04 18:41:51 +00001060 llvm::Constant *FunctionRecordVals[] = {
Xinliang David Lia026a432015-11-05 05:46:39 +00001061 #include "llvm/ProfileData/InstrProfData.inc"
1062 };
Alex Lorenzee024992014-08-04 18:41:51 +00001063 FunctionRecords.push_back(llvm::ConstantStruct::get(
1064 FunctionRecordTy, makeArrayRef(FunctionRecordVals)));
Xinliang David Li848da132016-01-19 00:49:06 +00001065 if (!IsUsed)
Xinliang David Li2129ae52016-01-07 20:05:55 +00001066 FunctionNames.push_back(
1067 llvm::ConstantExpr::getBitCast(NamePtr, llvm::Type::getInt8PtrTy(Ctx)));
Vedant Kumarca3326c2016-01-21 19:25:35 +00001068 CoverageMappings.push_back(CoverageMapping);
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00001069
1070 if (CGM.getCodeGenOpts().DumpCoverageMapping) {
1071 // Dump the coverage mapping data for this function by decoding the
1072 // encoded data. This allows us to dump the mapping regions which were
1073 // also processed by the CoverageMappingWriter which performs
1074 // additional minimization operations such as reducing the number of
1075 // expressions.
1076 std::vector<StringRef> Filenames;
1077 std::vector<CounterExpression> Expressions;
1078 std::vector<CounterMappingRegion> Regions;
Jordan Roseb31ee812016-11-07 17:28:04 +00001079 llvm::SmallVector<std::string, 16> FilenameStrs;
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00001080 llvm::SmallVector<StringRef, 16> FilenameRefs;
Jordan Roseb31ee812016-11-07 17:28:04 +00001081 FilenameStrs.resize(FileEntries.size());
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00001082 FilenameRefs.resize(FileEntries.size());
Jordan Roseb31ee812016-11-07 17:28:04 +00001083 for (const auto &Entry : FileEntries) {
1084 auto I = Entry.second;
1085 FilenameStrs[I] = normalizeFilename(Entry.first->getName());
1086 FilenameRefs[I] = FilenameStrs[I];
1087 }
Justin Bognera432d172015-02-03 00:20:24 +00001088 RawCoverageMappingReader Reader(CoverageMapping, FilenameRefs, Filenames,
1089 Expressions, Regions);
1090 if (Reader.read())
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00001091 return;
Xinliang David Lia026a432015-11-05 05:46:39 +00001092 dump(llvm::outs(), NameValue, Expressions, Regions);
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00001093 }
Alex Lorenzee024992014-08-04 18:41:51 +00001094}
1095
1096void CoverageMappingModuleGen::emit() {
1097 if (FunctionRecords.empty())
1098 return;
1099 llvm::LLVMContext &Ctx = CGM.getLLVMContext();
1100 auto *Int32Ty = llvm::Type::getInt32Ty(Ctx);
1101
1102 // Create the filenames and merge them with coverage mappings
1103 llvm::SmallVector<std::string, 16> FilenameStrs;
Vedant Kumar9e324dd2016-06-29 05:33:09 +00001104 llvm::SmallVector<StringRef, 16> FilenameRefs;
Alex Lorenzee024992014-08-04 18:41:51 +00001105 FilenameStrs.resize(FileEntries.size());
Vedant Kumar9e324dd2016-06-29 05:33:09 +00001106 FilenameRefs.resize(FileEntries.size());
Alex Lorenzee024992014-08-04 18:41:51 +00001107 for (const auto &Entry : FileEntries) {
Alex Lorenzee024992014-08-04 18:41:51 +00001108 auto I = Entry.second;
Vedant Kumar14f8fb62016-07-18 21:01:27 +00001109 FilenameStrs[I] = normalizeFilename(Entry.first->getName());
Vedant Kumar9e324dd2016-06-29 05:33:09 +00001110 FilenameRefs[I] = FilenameStrs[I];
Alex Lorenzee024992014-08-04 18:41:51 +00001111 }
1112
Vedant Kumar9e324dd2016-06-29 05:33:09 +00001113 std::string FilenamesAndCoverageMappings;
1114 llvm::raw_string_ostream OS(FilenamesAndCoverageMappings);
1115 CoverageFilenamesSectionWriter(FilenameRefs).write(OS);
1116 std::string RawCoverageMappings =
1117 llvm::join(CoverageMappings.begin(), CoverageMappings.end(), "");
1118 OS << RawCoverageMappings;
1119 size_t CoverageMappingSize = RawCoverageMappings.size();
1120 size_t FilenamesSize = OS.str().size() - CoverageMappingSize;
1121 // Append extra zeroes if necessary to ensure that the size of the filenames
1122 // and coverage mappings is a multiple of 8.
1123 if (size_t Rem = OS.str().size() % 8) {
1124 CoverageMappingSize += 8 - Rem;
1125 for (size_t I = 0, S = 8 - Rem; I < S; ++I)
1126 OS << '\0';
Alex Lorenzee024992014-08-04 18:41:51 +00001127 }
1128 auto *FilenamesAndMappingsVal =
Vedant Kumar9e324dd2016-06-29 05:33:09 +00001129 llvm::ConstantDataArray::getString(Ctx, OS.str(), false);
Alex Lorenzee024992014-08-04 18:41:51 +00001130
1131 // Create the deferred function records array
1132 auto RecordsTy =
1133 llvm::ArrayType::get(FunctionRecordTy, FunctionRecords.size());
1134 auto RecordsVal = llvm::ConstantArray::get(RecordsTy, FunctionRecords);
1135
Xinliang David Li20b188c2016-01-03 19:25:54 +00001136 llvm::Type *CovDataHeaderTypes[] = {
1137#define COVMAP_HEADER(Type, LLVMType, Name, Init) LLVMType,
1138#include "llvm/ProfileData/InstrProfData.inc"
1139 };
1140 auto CovDataHeaderTy =
1141 llvm::StructType::get(Ctx, makeArrayRef(CovDataHeaderTypes));
1142 llvm::Constant *CovDataHeaderVals[] = {
1143#define COVMAP_HEADER(Type, LLVMType, Name, Init) Init,
1144#include "llvm/ProfileData/InstrProfData.inc"
1145 };
1146 auto CovDataHeaderVal = llvm::ConstantStruct::get(
1147 CovDataHeaderTy, makeArrayRef(CovDataHeaderVals));
1148
Alex Lorenzee024992014-08-04 18:41:51 +00001149 // Create the coverage data record
Xinliang David Li20b188c2016-01-03 19:25:54 +00001150 llvm::Type *CovDataTypes[] = {CovDataHeaderTy, RecordsTy,
1151 FilenamesAndMappingsVal->getType()};
Alex Lorenzee024992014-08-04 18:41:51 +00001152 auto CovDataTy = llvm::StructType::get(Ctx, makeArrayRef(CovDataTypes));
Xinliang David Li20b188c2016-01-03 19:25:54 +00001153 llvm::Constant *TUDataVals[] = {CovDataHeaderVal, RecordsVal,
1154 FilenamesAndMappingsVal};
Alex Lorenzee024992014-08-04 18:41:51 +00001155 auto CovDataVal =
1156 llvm::ConstantStruct::get(CovDataTy, makeArrayRef(TUDataVals));
Xinliang David Li20b188c2016-01-03 19:25:54 +00001157 auto CovData = new llvm::GlobalVariable(
1158 CGM.getModule(), CovDataTy, true, llvm::GlobalValue::InternalLinkage,
1159 CovDataVal, llvm::getCoverageMappingVarName());
Alex Lorenzee024992014-08-04 18:41:51 +00001160
1161 CovData->setSection(getCoverageSection(CGM));
1162 CovData->setAlignment(8);
1163
1164 // Make sure the data doesn't get deleted.
1165 CGM.addUsedGlobal(CovData);
Xinliang David Li2129ae52016-01-07 20:05:55 +00001166 // Create the deferred function records array
1167 if (!FunctionNames.empty()) {
1168 auto NamesArrTy = llvm::ArrayType::get(llvm::Type::getInt8PtrTy(Ctx),
1169 FunctionNames.size());
1170 auto NamesArrVal = llvm::ConstantArray::get(NamesArrTy, FunctionNames);
1171 // This variable will *NOT* be emitted to the object file. It is used
1172 // to pass the list of names referenced to codegen.
1173 new llvm::GlobalVariable(CGM.getModule(), NamesArrTy, true,
1174 llvm::GlobalValue::InternalLinkage, NamesArrVal,
Xinliang David Li7077f0a2016-01-20 00:24:52 +00001175 llvm::getCoverageUnusedNamesVarName());
Xinliang David Li2129ae52016-01-07 20:05:55 +00001176 }
Alex Lorenzee024992014-08-04 18:41:51 +00001177}
1178
1179unsigned CoverageMappingModuleGen::getFileID(const FileEntry *File) {
1180 auto It = FileEntries.find(File);
1181 if (It != FileEntries.end())
1182 return It->second;
1183 unsigned FileID = FileEntries.size();
1184 FileEntries.insert(std::make_pair(File, FileID));
1185 return FileID;
1186}
1187
1188void CoverageMappingGen::emitCounterMapping(const Decl *D,
1189 llvm::raw_ostream &OS) {
1190 assert(CounterMap);
Justin Bognere5ee6c52014-10-02 16:44:01 +00001191 CounterCoverageMappingBuilder Walker(CVM, *CounterMap, SM, LangOpts);
Alex Lorenzee024992014-08-04 18:41:51 +00001192 Walker.VisitDecl(D);
1193 Walker.write(OS);
1194}
1195
1196void CoverageMappingGen::emitEmptyMapping(const Decl *D,
1197 llvm::raw_ostream &OS) {
1198 EmptyCoverageMappingBuilder Walker(CVM, SM, LangOpts);
1199 Walker.VisitDecl(D);
1200 Walker.write(OS);
1201}