blob: c5495de3b5660cbd532b85f541b58bdfa7e7f792 [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,
50 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
Alex Lorenzee024992014-08-04 18:41:51 +000076/// \brief Provides the common functionality for the different
77/// coverage mapping region builders.
78class CoverageMappingBuilder {
79public:
80 CoverageMappingModuleGen &CVM;
81 SourceManager &SM;
82 const LangOptions &LangOpts;
83
84private:
Justin Bognerbf42cfd2015-02-18 21:24:51 +000085 /// \brief Map of clang's FileIDs to IDs used for coverage mapping.
86 llvm::SmallDenseMap<FileID, std::pair<unsigned, SourceLocation>, 8>
87 FileIDMapping;
Alex Lorenzee024992014-08-04 18:41:51 +000088
89public:
Alex Lorenzee024992014-08-04 18:41:51 +000090 /// \brief The coverage mapping regions for this function
91 llvm::SmallVector<CounterMappingRegion, 32> MappingRegions;
92 /// \brief The source mapping regions for this function.
Justin Bognerf59329b2014-10-01 03:33:52 +000093 std::vector<SourceMappingRegion> SourceRegions;
Alex Lorenzee024992014-08-04 18:41:51 +000094
95 CoverageMappingBuilder(CoverageMappingModuleGen &CVM, SourceManager &SM,
96 const LangOptions &LangOpts)
Justin Bognerbf42cfd2015-02-18 21:24:51 +000097 : CVM(CVM), SM(SM), LangOpts(LangOpts) {}
Alex Lorenzee024992014-08-04 18:41:51 +000098
99 /// \brief Return the precise end location for the given token.
100 SourceLocation getPreciseTokenLocEnd(SourceLocation Loc) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000101 // We avoid getLocForEndOfToken here, because it doesn't do what we want for
102 // macro locations, which we just treat as expanded files.
103 unsigned TokLen =
104 Lexer::MeasureTokenLength(SM.getSpellingLoc(Loc), SM, LangOpts);
105 return Loc.getLocWithOffset(TokLen);
Alex Lorenzee024992014-08-04 18:41:51 +0000106 }
107
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000108 /// \brief Return the start location of an included file or expanded macro.
109 SourceLocation getStartOfFileOrMacro(SourceLocation Loc) {
110 if (Loc.isMacroID())
111 return Loc.getLocWithOffset(-SM.getFileOffset(Loc));
112 return SM.getLocForStartOfFile(SM.getFileID(Loc));
Alex Lorenzee024992014-08-04 18:41:51 +0000113 }
114
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000115 /// \brief Return the end location of an included file or expanded macro.
116 SourceLocation getEndOfFileOrMacro(SourceLocation Loc) {
117 if (Loc.isMacroID())
118 return Loc.getLocWithOffset(SM.getFileIDSize(SM.getFileID(Loc)) -
Justin Bognerf14b2072015-03-25 04:13:49 +0000119 SM.getFileOffset(Loc));
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000120 return SM.getLocForEndOfFile(SM.getFileID(Loc));
121 }
122
123 /// \brief Find out where the current file is included or macro is expanded.
124 SourceLocation getIncludeOrExpansionLoc(SourceLocation Loc) {
125 return Loc.isMacroID() ? SM.getImmediateExpansionRange(Loc).first
126 : SM.getIncludeLoc(SM.getFileID(Loc));
127 }
128
Justin Bogner682bfbf2015-05-14 22:14:10 +0000129 /// \brief Return true if \c Loc is a location in a built-in macro.
130 bool isInBuiltin(SourceLocation Loc) {
131 return strcmp(SM.getBufferName(SM.getSpellingLoc(Loc)), "<built-in>") == 0;
132 }
133
Igor Kudrind9e1a612016-06-07 10:07:51 +0000134 /// \brief Check whether \c Loc is included or expanded from \c Parent.
135 bool isNestedIn(SourceLocation Loc, FileID Parent) {
136 do {
137 Loc = getIncludeOrExpansionLoc(Loc);
138 if (Loc.isInvalid())
139 return false;
140 } while (!SM.isInFileID(Loc, Parent));
141 return true;
142 }
143
Justin Bogner682bfbf2015-05-14 22:14:10 +0000144 /// \brief Get the start of \c S ignoring macro arguments and builtin macros.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000145 SourceLocation getStart(const Stmt *S) {
146 SourceLocation Loc = S->getLocStart();
Justin Bogner682bfbf2015-05-14 22:14:10 +0000147 while (SM.isMacroArgExpansion(Loc) || isInBuiltin(Loc))
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000148 Loc = SM.getImmediateExpansionRange(Loc).first;
149 return Loc;
150 }
151
Justin Bogner682bfbf2015-05-14 22:14:10 +0000152 /// \brief Get the end of \c S ignoring macro arguments and builtin macros.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000153 SourceLocation getEnd(const Stmt *S) {
154 SourceLocation Loc = S->getLocEnd();
Justin Bogner682bfbf2015-05-14 22:14:10 +0000155 while (SM.isMacroArgExpansion(Loc) || isInBuiltin(Loc))
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000156 Loc = SM.getImmediateExpansionRange(Loc).first;
Justin Bognerf14b2072015-03-25 04:13:49 +0000157 return getPreciseTokenLocEnd(Loc);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000158 }
159
160 /// \brief Find the set of files we have regions for and assign IDs
161 ///
162 /// Fills \c Mapping with the virtual file mapping needed to write out
163 /// coverage and collects the necessary file information to emit source and
164 /// expansion regions.
165 void gatherFileIDs(SmallVectorImpl<unsigned> &Mapping) {
166 FileIDMapping.clear();
167
Vedant Kumarbc6b80a2016-01-28 17:52:18 +0000168 llvm::SmallSet<FileID, 8> Visited;
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000169 SmallVector<std::pair<SourceLocation, unsigned>, 8> FileLocs;
170 for (const auto &Region : SourceRegions) {
171 SourceLocation Loc = Region.getStartLoc();
172 FileID File = SM.getFileID(Loc);
Vedant Kumarbc6b80a2016-01-28 17:52:18 +0000173 if (!Visited.insert(File).second)
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000174 continue;
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000175
Vedant Kumar93205af2016-07-11 22:57:46 +0000176 // Do not map FileID's associated with system headers.
177 if (SM.isInSystemHeader(SM.getSpellingLoc(Loc)))
178 continue;
179
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000180 unsigned Depth = 0;
181 for (SourceLocation Parent = getIncludeOrExpansionLoc(Loc);
Yaron Kerened1fe5d2015-10-03 05:15:57 +0000182 Parent.isValid(); Parent = getIncludeOrExpansionLoc(Parent))
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000183 ++Depth;
184 FileLocs.push_back(std::make_pair(Loc, Depth));
185 }
186 std::stable_sort(FileLocs.begin(), FileLocs.end(), llvm::less_second());
187
188 for (const auto &FL : FileLocs) {
189 SourceLocation Loc = FL.first;
190 FileID SpellingFile = SM.getDecomposedSpellingLoc(Loc).first;
191 auto Entry = SM.getFileEntryForID(SpellingFile);
192 if (!Entry)
193 continue;
194
195 FileIDMapping[SM.getFileID(Loc)] = std::make_pair(Mapping.size(), Loc);
196 Mapping.push_back(CVM.getFileID(Entry));
197 }
198 }
199
200 /// \brief Get the coverage mapping file ID for \c Loc.
201 ///
202 /// If such file id doesn't exist, return None.
203 Optional<unsigned> getCoverageFileID(SourceLocation Loc) {
204 auto Mapping = FileIDMapping.find(SM.getFileID(Loc));
Justin Bogner903678c2015-01-24 20:22:32 +0000205 if (Mapping != FileIDMapping.end())
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000206 return Mapping->second.first;
207 return None;
Alex Lorenzee024992014-08-04 18:41:51 +0000208 }
209
Alex Lorenzee024992014-08-04 18:41:51 +0000210 /// \brief Gather all the regions that were skipped by the preprocessor
211 /// using the constructs like #if.
212 void gatherSkippedRegions() {
213 /// An array of the minimum lineStarts and the maximum lineEnds
214 /// for mapping regions from the appropriate source files.
215 llvm::SmallVector<std::pair<unsigned, unsigned>, 8> FileLineRanges;
216 FileLineRanges.resize(
217 FileIDMapping.size(),
218 std::make_pair(std::numeric_limits<unsigned>::max(), 0));
219 for (const auto &R : MappingRegions) {
220 FileLineRanges[R.FileID].first =
221 std::min(FileLineRanges[R.FileID].first, R.LineStart);
222 FileLineRanges[R.FileID].second =
223 std::max(FileLineRanges[R.FileID].second, R.LineEnd);
224 }
225
226 auto SkippedRanges = CVM.getSourceInfo().getSkippedRanges();
227 for (const auto &I : SkippedRanges) {
228 auto LocStart = I.getBegin();
229 auto LocEnd = I.getEnd();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000230 assert(SM.isWrittenInSameFile(LocStart, LocEnd) &&
231 "region spans multiple files");
Alex Lorenzee024992014-08-04 18:41:51 +0000232
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000233 auto CovFileID = getCoverageFileID(LocStart);
Justin Bogner903678c2015-01-24 20:22:32 +0000234 if (!CovFileID)
Alex Lorenzee024992014-08-04 18:41:51 +0000235 continue;
236 unsigned LineStart = SM.getSpellingLineNumber(LocStart);
237 unsigned ColumnStart = SM.getSpellingColumnNumber(LocStart);
238 unsigned LineEnd = SM.getSpellingLineNumber(LocEnd);
239 unsigned ColumnEnd = SM.getSpellingColumnNumber(LocEnd);
Justin Bognerfd34280b2015-02-03 23:59:48 +0000240 auto Region = CounterMappingRegion::makeSkipped(
241 *CovFileID, LineStart, ColumnStart, LineEnd, ColumnEnd);
Alex Lorenzee024992014-08-04 18:41:51 +0000242 // Make sure that we only collect the regions that are inside
243 // the souce code of this function.
Justin Bogner903678c2015-01-24 20:22:32 +0000244 if (Region.LineStart >= FileLineRanges[*CovFileID].first &&
245 Region.LineEnd <= FileLineRanges[*CovFileID].second)
Alex Lorenzee024992014-08-04 18:41:51 +0000246 MappingRegions.push_back(Region);
247 }
248 }
249
Alex Lorenzee024992014-08-04 18:41:51 +0000250 /// \brief Generate the coverage counter mapping regions from collected
251 /// source regions.
252 void emitSourceRegions() {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000253 for (const auto &Region : SourceRegions) {
254 assert(Region.hasEndLoc() && "incomplete region");
Alex Lorenzee024992014-08-04 18:41:51 +0000255
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000256 SourceLocation LocStart = Region.getStartLoc();
Yaron Keren8b563662015-10-03 10:46:20 +0000257 assert(SM.getFileID(LocStart).isValid() && "region in invalid file");
Justin Bognerf59329b2014-10-01 03:33:52 +0000258
Vedant Kumar93205af2016-07-11 22:57:46 +0000259 // Ignore regions from system headers.
260 if (SM.isInSystemHeader(SM.getSpellingLoc(LocStart)))
261 continue;
262
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000263 auto CovFileID = getCoverageFileID(LocStart);
264 // Ignore regions that don't have a file, such as builtin macros.
265 if (!CovFileID)
Alex Lorenzee024992014-08-04 18:41:51 +0000266 continue;
267
Justin Bognerf14b2072015-03-25 04:13:49 +0000268 SourceLocation LocEnd = Region.getEndLoc();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000269 assert(SM.isWrittenInSameFile(LocStart, LocEnd) &&
270 "region spans multiple files");
271
Justin Bognerf59329b2014-10-01 03:33:52 +0000272 // Find the spilling locations for the mapping region.
Alex Lorenzee024992014-08-04 18:41:51 +0000273 unsigned LineStart = SM.getSpellingLineNumber(LocStart);
274 unsigned ColumnStart = SM.getSpellingColumnNumber(LocStart);
275 unsigned LineEnd = SM.getSpellingLineNumber(LocEnd);
276 unsigned ColumnEnd = SM.getSpellingColumnNumber(LocEnd);
277
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000278 assert(LineStart <= LineEnd && "region start and end out of order");
279 MappingRegions.push_back(CounterMappingRegion::makeRegion(
280 Region.getCounter(), *CovFileID, LineStart, ColumnStart, LineEnd,
281 ColumnEnd));
282 }
283 }
284
285 /// \brief Generate expansion regions for each virtual file we've seen.
286 void emitExpansionRegions() {
287 for (const auto &FM : FileIDMapping) {
288 SourceLocation ExpandedLoc = FM.second.second;
289 SourceLocation ParentLoc = getIncludeOrExpansionLoc(ExpandedLoc);
290 if (ParentLoc.isInvalid())
Alex Lorenzee024992014-08-04 18:41:51 +0000291 continue;
292
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000293 auto ParentFileID = getCoverageFileID(ParentLoc);
294 if (!ParentFileID)
295 continue;
296 auto ExpandedFileID = getCoverageFileID(ExpandedLoc);
297 assert(ExpandedFileID && "expansion in uncovered file");
298
299 SourceLocation LocEnd = getPreciseTokenLocEnd(ParentLoc);
300 assert(SM.isWrittenInSameFile(ParentLoc, LocEnd) &&
301 "region spans multiple files");
302
303 unsigned LineStart = SM.getSpellingLineNumber(ParentLoc);
304 unsigned ColumnStart = SM.getSpellingColumnNumber(ParentLoc);
305 unsigned LineEnd = SM.getSpellingLineNumber(LocEnd);
306 unsigned ColumnEnd = SM.getSpellingColumnNumber(LocEnd);
307
308 MappingRegions.push_back(CounterMappingRegion::makeExpansion(
309 *ParentFileID, *ExpandedFileID, LineStart, ColumnStart, LineEnd,
Justin Bognerfd34280b2015-02-03 23:59:48 +0000310 ColumnEnd));
Alex Lorenzee024992014-08-04 18:41:51 +0000311 }
312 }
313};
314
315/// \brief Creates unreachable coverage regions for the functions that
316/// are not emitted.
317struct EmptyCoverageMappingBuilder : public CoverageMappingBuilder {
318 EmptyCoverageMappingBuilder(CoverageMappingModuleGen &CVM, SourceManager &SM,
319 const LangOptions &LangOpts)
320 : CoverageMappingBuilder(CVM, SM, LangOpts) {}
321
322 void VisitDecl(const Decl *D) {
323 if (!D->hasBody())
324 return;
325 auto Body = D->getBody();
Igor Kudrind9e1a612016-06-07 10:07:51 +0000326 SourceLocation Start = getStart(Body);
327 SourceLocation End = getEnd(Body);
328 if (!SM.isWrittenInSameFile(Start, End)) {
329 // Walk up to find the common ancestor.
330 // Correct the locations accordingly.
331 FileID StartFileID = SM.getFileID(Start);
332 FileID EndFileID = SM.getFileID(End);
333 while (StartFileID != EndFileID && !isNestedIn(End, StartFileID)) {
334 Start = getIncludeOrExpansionLoc(Start);
335 assert(Start.isValid() &&
336 "Declaration start location not nested within a known region");
337 StartFileID = SM.getFileID(Start);
338 }
339 while (StartFileID != EndFileID) {
340 End = getPreciseTokenLocEnd(getIncludeOrExpansionLoc(End));
341 assert(End.isValid() &&
342 "Declaration end location not nested within a known region");
343 EndFileID = SM.getFileID(End);
344 }
345 }
346 SourceRegions.emplace_back(Counter(), Start, End);
Alex Lorenzee024992014-08-04 18:41:51 +0000347 }
348
349 /// \brief Write the mapping data to the output stream
350 void write(llvm::raw_ostream &OS) {
Alex Lorenzee024992014-08-04 18:41:51 +0000351 SmallVector<unsigned, 16> FileIDMapping;
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000352 gatherFileIDs(FileIDMapping);
353 emitSourceRegions();
Alex Lorenzee024992014-08-04 18:41:51 +0000354
Craig Topper5fc8fc22014-08-27 06:28:36 +0000355 CoverageMappingWriter Writer(FileIDMapping, None, MappingRegions);
Alex Lorenzee024992014-08-04 18:41:51 +0000356 Writer.write(OS);
357 }
358};
359
360/// \brief A StmtVisitor that creates coverage mapping regions which map
361/// from the source code locations to the PGO counters.
362struct CounterCoverageMappingBuilder
363 : public CoverageMappingBuilder,
364 public ConstStmtVisitor<CounterCoverageMappingBuilder> {
365 /// \brief The map of statements to count values.
366 llvm::DenseMap<const Stmt *, unsigned> &CounterMap;
367
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000368 /// \brief A stack of currently live regions.
369 std::vector<SourceMappingRegion> RegionStack;
Alex Lorenzee024992014-08-04 18:41:51 +0000370
371 CounterExpressionBuilder Builder;
372
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000373 /// \brief A location in the most recently visited file or macro.
374 ///
375 /// This is used to adjust the active source regions appropriately when
376 /// expressions cross file or macro boundaries.
377 SourceLocation MostRecentLocation;
378
379 /// \brief Return a counter for the subtraction of \c RHS from \c LHS
Alex Lorenzee024992014-08-04 18:41:51 +0000380 Counter subtractCounters(Counter LHS, Counter RHS) {
381 return Builder.subtract(LHS, RHS);
382 }
383
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000384 /// \brief Return a counter for the sum of \c LHS and \c RHS.
Alex Lorenzee024992014-08-04 18:41:51 +0000385 Counter addCounters(Counter LHS, Counter RHS) {
386 return Builder.add(LHS, RHS);
387 }
388
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000389 Counter addCounters(Counter C1, Counter C2, Counter C3) {
390 return addCounters(addCounters(C1, C2), C3);
391 }
392
Alex Lorenzee024992014-08-04 18:41:51 +0000393 /// \brief Return the region counter for the given statement.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000394 ///
Alex Lorenzee024992014-08-04 18:41:51 +0000395 /// This should only be called on statements that have a dedicated counter.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000396 Counter getRegionCounter(const Stmt *S) {
397 return Counter::getCounter(CounterMap[S]);
Alex Lorenzee024992014-08-04 18:41:51 +0000398 }
399
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000400 /// \brief Push a region onto the stack.
401 ///
402 /// Returns the index on the stack where the region was pushed. This can be
403 /// used with popRegions to exit a "scope", ending the region that was pushed.
404 size_t pushRegion(Counter Count, Optional<SourceLocation> StartLoc = None,
405 Optional<SourceLocation> EndLoc = None) {
406 if (StartLoc)
407 MostRecentLocation = *StartLoc;
408 RegionStack.emplace_back(Count, StartLoc, EndLoc);
Alex Lorenzee024992014-08-04 18:41:51 +0000409
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000410 return RegionStack.size() - 1;
Alex Lorenzee024992014-08-04 18:41:51 +0000411 }
412
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000413 /// \brief Pop regions from the stack into the function's list of regions.
414 ///
415 /// Adds all regions from \c ParentIndex to the top of the stack to the
416 /// function's \c SourceRegions.
417 void popRegions(size_t ParentIndex) {
418 assert(RegionStack.size() >= ParentIndex && "parent not in stack");
419 while (RegionStack.size() > ParentIndex) {
420 SourceMappingRegion &Region = RegionStack.back();
421 if (Region.hasStartLoc()) {
422 SourceLocation StartLoc = Region.getStartLoc();
423 SourceLocation EndLoc = Region.hasEndLoc()
424 ? Region.getEndLoc()
425 : RegionStack[ParentIndex].getEndLoc();
426 while (!SM.isWrittenInSameFile(StartLoc, EndLoc)) {
427 // The region ends in a nested file or macro expansion. Create a
428 // separate region for each expansion.
429 SourceLocation NestedLoc = getStartOfFileOrMacro(EndLoc);
430 assert(SM.isWrittenInSameFile(NestedLoc, EndLoc));
431
432 SourceRegions.emplace_back(Region.getCounter(), NestedLoc, EndLoc);
433
Justin Bognerf14b2072015-03-25 04:13:49 +0000434 EndLoc = getPreciseTokenLocEnd(getIncludeOrExpansionLoc(EndLoc));
Justin Bognerdceaaad2015-07-17 23:31:21 +0000435 if (EndLoc.isInvalid())
436 llvm::report_fatal_error("File exit not handled before popRegions");
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000437 }
438 Region.setEndLoc(EndLoc);
439
440 MostRecentLocation = EndLoc;
441 // If this region happens to span an entire expansion, we need to make
442 // sure we don't overlap the parent region with it.
443 if (StartLoc == getStartOfFileOrMacro(StartLoc) &&
444 EndLoc == getEndOfFileOrMacro(EndLoc))
445 MostRecentLocation = getIncludeOrExpansionLoc(EndLoc);
446
447 assert(SM.isWrittenInSameFile(Region.getStartLoc(), EndLoc));
Craig Topperf36a5c42015-09-26 05:10:16 +0000448 SourceRegions.push_back(Region);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000449 }
450 RegionStack.pop_back();
451 }
Alex Lorenzee024992014-08-04 18:41:51 +0000452 }
453
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000454 /// \brief Return the currently active region.
455 SourceMappingRegion &getRegion() {
456 assert(!RegionStack.empty() && "statement has no region");
457 return RegionStack.back();
458 }
Alex Lorenzee024992014-08-04 18:41:51 +0000459
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000460 /// \brief Propagate counts through the children of \c S.
461 Counter propagateCounts(Counter TopCount, const Stmt *S) {
462 size_t Index = pushRegion(TopCount, getStart(S), getEnd(S));
463 Visit(S);
464 Counter ExitCount = getRegion().getCounter();
465 popRegions(Index);
Vedant Kumar39f01972016-02-08 19:25:45 +0000466
467 // The statement may be spanned by an expansion. Make sure we handle a file
468 // exit out of this expansion before moving to the next statement.
469 if (SM.isBeforeInTranslationUnit(getStart(S), S->getLocStart()))
470 MostRecentLocation = getEnd(S);
471
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000472 return ExitCount;
473 }
Alex Lorenzee024992014-08-04 18:41:51 +0000474
Igor Kudrin0a7c9d12016-05-04 15:38:26 +0000475 /// \brief Check whether a region with bounds \c StartLoc and \c EndLoc
476 /// is already added to \c SourceRegions.
477 bool isRegionAlreadyAdded(SourceLocation StartLoc, SourceLocation EndLoc) {
478 return SourceRegions.rend() !=
479 std::find_if(SourceRegions.rbegin(), SourceRegions.rend(),
480 [&](const SourceMappingRegion &Region) {
481 return Region.getStartLoc() == StartLoc &&
482 Region.getEndLoc() == EndLoc;
483 });
484 }
485
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000486 /// \brief Adjust the most recently visited location to \c EndLoc.
487 ///
488 /// This should be used after visiting any statements in non-source order.
489 void adjustForOutOfOrderTraversal(SourceLocation EndLoc) {
490 MostRecentLocation = EndLoc;
Igor Kudrin0a7c9d12016-05-04 15:38:26 +0000491 // The code region for a whole macro is created in handleFileExit() when
492 // it detects exiting of the virtual file of that macro. If we visited
493 // statements in non-source order, we might already have such a region
494 // added, for example, if a body of a loop is divided among multiple
495 // macros. Avoid adding duplicate regions in such case.
Justin Bogner96ae73f2015-05-01 19:23:34 +0000496 if (getRegion().hasEndLoc() &&
Igor Kudrin0a7c9d12016-05-04 15:38:26 +0000497 MostRecentLocation == getEndOfFileOrMacro(MostRecentLocation) &&
498 isRegionAlreadyAdded(getStartOfFileOrMacro(MostRecentLocation),
499 MostRecentLocation))
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000500 MostRecentLocation = getIncludeOrExpansionLoc(MostRecentLocation);
501 }
Alex Lorenzee024992014-08-04 18:41:51 +0000502
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000503 /// \brief Adjust regions and state when \c NewLoc exits a file.
504 ///
505 /// If moving from our most recently tracked location to \c NewLoc exits any
506 /// files, this adjusts our current region stack and creates the file regions
507 /// for the exited file.
508 void handleFileExit(SourceLocation NewLoc) {
Justin Bognere44dd6d2015-06-23 20:29:09 +0000509 if (NewLoc.isInvalid() ||
510 SM.isWrittenInSameFile(MostRecentLocation, NewLoc))
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000511 return;
512
513 // If NewLoc is not in a file that contains MostRecentLocation, walk up to
514 // find the common ancestor.
515 SourceLocation LCA = NewLoc;
516 FileID ParentFile = SM.getFileID(LCA);
517 while (!isNestedIn(MostRecentLocation, ParentFile)) {
518 LCA = getIncludeOrExpansionLoc(LCA);
519 if (LCA.isInvalid() || SM.isWrittenInSameFile(LCA, MostRecentLocation)) {
520 // Since there isn't a common ancestor, no file was exited. We just need
521 // to adjust our location to the new file.
522 MostRecentLocation = NewLoc;
523 return;
524 }
525 ParentFile = SM.getFileID(LCA);
Alex Lorenzee024992014-08-04 18:41:51 +0000526 }
527
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000528 llvm::SmallSet<SourceLocation, 8> StartLocs;
529 Optional<Counter> ParentCounter;
Pete Cooper57d3f142015-07-30 17:22:52 +0000530 for (SourceMappingRegion &I : llvm::reverse(RegionStack)) {
531 if (!I.hasStartLoc())
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000532 continue;
Pete Cooper57d3f142015-07-30 17:22:52 +0000533 SourceLocation Loc = I.getStartLoc();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000534 if (!isNestedIn(Loc, ParentFile)) {
Pete Cooper57d3f142015-07-30 17:22:52 +0000535 ParentCounter = I.getCounter();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000536 break;
537 }
Alex Lorenzee024992014-08-04 18:41:51 +0000538
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000539 while (!SM.isInFileID(Loc, ParentFile)) {
540 // The most nested region for each start location is the one with the
541 // correct count. We avoid creating redundant regions by stopping once
542 // we've seen this region.
543 if (StartLocs.insert(Loc).second)
Pete Cooper57d3f142015-07-30 17:22:52 +0000544 SourceRegions.emplace_back(I.getCounter(), Loc,
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000545 getEndOfFileOrMacro(Loc));
546 Loc = getIncludeOrExpansionLoc(Loc);
547 }
Pete Cooper57d3f142015-07-30 17:22:52 +0000548 I.setStartLoc(getPreciseTokenLocEnd(Loc));
Alex Lorenzee024992014-08-04 18:41:51 +0000549 }
550
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000551 if (ParentCounter) {
552 // If the file is contained completely by another region and doesn't
553 // immediately start its own region, the whole file gets a region
554 // corresponding to the parent.
555 SourceLocation Loc = MostRecentLocation;
556 while (isNestedIn(Loc, ParentFile)) {
557 SourceLocation FileStart = getStartOfFileOrMacro(Loc);
558 if (StartLocs.insert(FileStart).second)
559 SourceRegions.emplace_back(*ParentCounter, FileStart,
560 getEndOfFileOrMacro(Loc));
561 Loc = getIncludeOrExpansionLoc(Loc);
562 }
Alex Lorenzee024992014-08-04 18:41:51 +0000563 }
564
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000565 MostRecentLocation = NewLoc;
566 }
Alex Lorenzee024992014-08-04 18:41:51 +0000567
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000568 /// \brief Ensure that \c S is included in the current region.
569 void extendRegion(const Stmt *S) {
570 SourceMappingRegion &Region = getRegion();
571 SourceLocation StartLoc = getStart(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000572
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000573 handleFileExit(StartLoc);
574 if (!Region.hasStartLoc())
575 Region.setStartLoc(StartLoc);
576 }
577
578 /// \brief Mark \c S as a terminator, starting a zero region.
579 void terminateRegion(const Stmt *S) {
580 extendRegion(S);
581 SourceMappingRegion &Region = getRegion();
582 if (!Region.hasEndLoc())
583 Region.setEndLoc(getEnd(S));
584 pushRegion(Counter::getZero());
585 }
Alex Lorenzee024992014-08-04 18:41:51 +0000586
587 /// \brief Keep counts of breaks and continues inside loops.
588 struct BreakContinue {
589 Counter BreakCount;
590 Counter ContinueCount;
591 };
592 SmallVector<BreakContinue, 8> BreakContinueStack;
593
594 CounterCoverageMappingBuilder(
595 CoverageMappingModuleGen &CVM,
Justin Bognere5ee6c52014-10-02 16:44:01 +0000596 llvm::DenseMap<const Stmt *, unsigned> &CounterMap, SourceManager &SM,
Alex Lorenzee024992014-08-04 18:41:51 +0000597 const LangOptions &LangOpts)
Justin Bognere5ee6c52014-10-02 16:44:01 +0000598 : CoverageMappingBuilder(CVM, SM, LangOpts), CounterMap(CounterMap) {}
Alex Lorenzee024992014-08-04 18:41:51 +0000599
600 /// \brief Write the mapping data to the output stream
601 void write(llvm::raw_ostream &OS) {
Alex Lorenzee024992014-08-04 18:41:51 +0000602 llvm::SmallVector<unsigned, 8> VirtualFileMapping;
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000603 gatherFileIDs(VirtualFileMapping);
604 emitSourceRegions();
605 emitExpansionRegions();
Alex Lorenzee024992014-08-04 18:41:51 +0000606 gatherSkippedRegions();
607
Justin Bogner4da909b2015-02-03 21:35:49 +0000608 CoverageMappingWriter Writer(VirtualFileMapping, Builder.getExpressions(),
609 MappingRegions);
Alex Lorenzee024992014-08-04 18:41:51 +0000610 Writer.write(OS);
611 }
612
Alex Lorenzee024992014-08-04 18:41:51 +0000613 void VisitStmt(const Stmt *S) {
Yaron Kerened1fe5d2015-10-03 05:15:57 +0000614 if (S->getLocStart().isValid())
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000615 extendRegion(S);
Benjamin Kramer642f1732015-07-02 21:03:14 +0000616 for (const Stmt *Child : S->children())
617 if (Child)
618 this->Visit(Child);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000619 handleFileExit(getEnd(S));
Alex Lorenzee024992014-08-04 18:41:51 +0000620 }
621
Alex Lorenzee024992014-08-04 18:41:51 +0000622 void VisitDecl(const Decl *D) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000623 Stmt *Body = D->getBody();
624 propagateCounts(getRegionCounter(Body), Body);
Alex Lorenzee024992014-08-04 18:41:51 +0000625 }
626
627 void VisitReturnStmt(const ReturnStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000628 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000629 if (S->getRetValue())
630 Visit(S->getRetValue());
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000631 terminateRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000632 }
633
Justin Bognerf959feb2015-04-28 06:31:55 +0000634 void VisitCXXThrowExpr(const CXXThrowExpr *E) {
635 extendRegion(E);
636 if (E->getSubExpr())
637 Visit(E->getSubExpr());
638 terminateRegion(E);
639 }
640
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000641 void VisitGotoStmt(const GotoStmt *S) { terminateRegion(S); }
Alex Lorenzee024992014-08-04 18:41:51 +0000642
643 void VisitLabelStmt(const LabelStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000644 SourceLocation Start = getStart(S);
645 // We can't extendRegion here or we risk overlapping with our new region.
646 handleFileExit(Start);
647 pushRegion(getRegionCounter(S), Start);
Alex Lorenzee024992014-08-04 18:41:51 +0000648 Visit(S->getSubStmt());
649 }
650
651 void VisitBreakStmt(const BreakStmt *S) {
Alex Lorenzee024992014-08-04 18:41:51 +0000652 assert(!BreakContinueStack.empty() && "break not in a loop or switch!");
653 BreakContinueStack.back().BreakCount = addCounters(
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000654 BreakContinueStack.back().BreakCount, getRegion().getCounter());
655 terminateRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000656 }
657
658 void VisitContinueStmt(const ContinueStmt *S) {
Alex Lorenzee024992014-08-04 18:41:51 +0000659 assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
660 BreakContinueStack.back().ContinueCount = addCounters(
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000661 BreakContinueStack.back().ContinueCount, getRegion().getCounter());
662 terminateRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000663 }
664
665 void VisitWhileStmt(const WhileStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000666 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000667
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000668 Counter ParentCount = getRegion().getCounter();
669 Counter BodyCount = getRegionCounter(S);
670
671 // Handle the body first so that we can get the backedge count.
672 BreakContinueStack.push_back(BreakContinue());
673 extendRegion(S->getBody());
674 Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
Alex Lorenzee024992014-08-04 18:41:51 +0000675 BreakContinue BC = BreakContinueStack.pop_back_val();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000676
677 // Go back to handle the condition.
678 Counter CondCount =
679 addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
680 propagateCounts(CondCount, S->getCond());
681 adjustForOutOfOrderTraversal(getEnd(S));
682
683 Counter OutCount =
684 addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount));
685 if (OutCount != ParentCount)
686 pushRegion(OutCount);
Alex Lorenzee024992014-08-04 18:41:51 +0000687 }
688
689 void VisitDoStmt(const DoStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000690 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000691
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000692 Counter ParentCount = getRegion().getCounter();
693 Counter BodyCount = getRegionCounter(S);
694
695 BreakContinueStack.push_back(BreakContinue());
696 extendRegion(S->getBody());
697 Counter BackedgeCount =
698 propagateCounts(addCounters(ParentCount, BodyCount), S->getBody());
Alex Lorenzee024992014-08-04 18:41:51 +0000699 BreakContinue BC = BreakContinueStack.pop_back_val();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000700
701 Counter CondCount = addCounters(BackedgeCount, BC.ContinueCount);
702 propagateCounts(CondCount, S->getCond());
703
704 Counter OutCount =
705 addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount));
706 if (OutCount != ParentCount)
707 pushRegion(OutCount);
Alex Lorenzee024992014-08-04 18:41:51 +0000708 }
709
710 void VisitForStmt(const ForStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000711 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000712 if (S->getInit())
713 Visit(S->getInit());
714
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000715 Counter ParentCount = getRegion().getCounter();
716 Counter BodyCount = getRegionCounter(S);
717
718 // Handle the body first so that we can get the backedge count.
Alex Lorenzee024992014-08-04 18:41:51 +0000719 BreakContinueStack.push_back(BreakContinue());
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000720 extendRegion(S->getBody());
721 Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
722 BreakContinue BC = BreakContinueStack.pop_back_val();
Alex Lorenzee024992014-08-04 18:41:51 +0000723
724 // The increment is essentially part of the body but it needs to include
725 // the count for all the continue statements.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000726 if (const Stmt *Inc = S->getInc())
727 propagateCounts(addCounters(BackedgeCount, BC.ContinueCount), Inc);
728
729 // Go back to handle the condition.
730 Counter CondCount =
731 addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
732 if (const Expr *Cond = S->getCond()) {
733 propagateCounts(CondCount, Cond);
734 adjustForOutOfOrderTraversal(getEnd(S));
Alex Lorenzee024992014-08-04 18:41:51 +0000735 }
736
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000737 Counter OutCount =
738 addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount));
739 if (OutCount != ParentCount)
740 pushRegion(OutCount);
Alex Lorenzee024992014-08-04 18:41:51 +0000741 }
742
743 void VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000744 extendRegion(S);
745 Visit(S->getLoopVarStmt());
Alex Lorenzee024992014-08-04 18:41:51 +0000746 Visit(S->getRangeStmt());
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000747
748 Counter ParentCount = getRegion().getCounter();
749 Counter BodyCount = getRegionCounter(S);
750
Alex Lorenzee024992014-08-04 18:41:51 +0000751 BreakContinueStack.push_back(BreakContinue());
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000752 extendRegion(S->getBody());
753 Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
Alex Lorenzee024992014-08-04 18:41:51 +0000754 BreakContinue BC = BreakContinueStack.pop_back_val();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000755
Justin Bogner15874322015-04-30 21:31:02 +0000756 Counter LoopCount =
757 addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
758 Counter OutCount =
759 addCounters(BC.BreakCount, subtractCounters(LoopCount, BodyCount));
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000760 if (OutCount != ParentCount)
761 pushRegion(OutCount);
Alex Lorenzee024992014-08-04 18:41:51 +0000762 }
763
764 void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000765 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000766 Visit(S->getElement());
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000767
768 Counter ParentCount = getRegion().getCounter();
769 Counter BodyCount = getRegionCounter(S);
770
Alex Lorenzee024992014-08-04 18:41:51 +0000771 BreakContinueStack.push_back(BreakContinue());
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000772 extendRegion(S->getBody());
773 Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
Alex Lorenzee024992014-08-04 18:41:51 +0000774 BreakContinue BC = BreakContinueStack.pop_back_val();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000775
Justin Bogner15874322015-04-30 21:31:02 +0000776 Counter LoopCount =
777 addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
778 Counter OutCount =
779 addCounters(BC.BreakCount, subtractCounters(LoopCount, BodyCount));
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000780 if (OutCount != ParentCount)
781 pushRegion(OutCount);
Alex Lorenzee024992014-08-04 18:41:51 +0000782 }
783
784 void VisitSwitchStmt(const SwitchStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000785 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000786 Visit(S->getCond());
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000787
Alex Lorenzee024992014-08-04 18:41:51 +0000788 BreakContinueStack.push_back(BreakContinue());
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000789
790 const Stmt *Body = S->getBody();
791 extendRegion(Body);
792 if (const auto *CS = dyn_cast<CompoundStmt>(Body)) {
793 if (!CS->body_empty()) {
794 // The body of the switch needs a zero region so that fallthrough counts
795 // behave correctly, but it would be misleading to include the braces of
796 // the compound statement in the zeroed area, so we need to handle this
797 // specially.
798 size_t Index =
799 pushRegion(Counter::getZero(), getStart(CS->body_front()),
800 getEnd(CS->body_back()));
Richard Trieub5841332015-04-15 01:21:42 +0000801 for (const auto *Child : CS->children())
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000802 Visit(Child);
803 popRegions(Index);
Alex Lorenzee024992014-08-04 18:41:51 +0000804 }
Vedant Kumar87ea3b02016-05-31 20:35:12 +0000805 } else
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000806 propagateCounts(Counter::getZero(), Body);
Alex Lorenzee024992014-08-04 18:41:51 +0000807 BreakContinue BC = BreakContinueStack.pop_back_val();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000808
Alex Lorenzee024992014-08-04 18:41:51 +0000809 if (!BreakContinueStack.empty())
810 BreakContinueStack.back().ContinueCount = addCounters(
811 BreakContinueStack.back().ContinueCount, BC.ContinueCount);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000812
813 Counter ExitCount = getRegionCounter(S);
Vedant Kumar38364822016-05-31 18:06:19 +0000814 SourceLocation ExitLoc = getEnd(S);
815 pushRegion(ExitCount, getStart(S), ExitLoc);
816 handleFileExit(ExitLoc);
Alex Lorenzee024992014-08-04 18:41:51 +0000817 }
818
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000819 void VisitSwitchCase(const SwitchCase *S) {
820 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000821
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000822 SourceMappingRegion &Parent = getRegion();
823
824 Counter Count = addCounters(Parent.getCounter(), getRegionCounter(S));
825 // Reuse the existing region if it starts at our label. This is typical of
826 // the first case in a switch.
827 if (Parent.hasStartLoc() && Parent.getStartLoc() == getStart(S))
828 Parent.setCounter(Count);
829 else
830 pushRegion(Count, getStart(S));
831
Sanjay Patel376c06c2015-12-24 21:11:29 +0000832 if (const auto *CS = dyn_cast<CaseStmt>(S)) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000833 Visit(CS->getLHS());
834 if (const Expr *RHS = CS->getRHS())
835 Visit(RHS);
836 }
Alex Lorenzee024992014-08-04 18:41:51 +0000837 Visit(S->getSubStmt());
838 }
839
840 void VisitIfStmt(const IfStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000841 extendRegion(S);
Justin Bogner055ebc32015-06-16 06:24:15 +0000842 // Extend into the condition before we propagate through it below - this is
843 // needed to handle macros that generate the "if" but not the condition.
844 extendRegion(S->getCond());
Alex Lorenzee024992014-08-04 18:41:51 +0000845
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000846 Counter ParentCount = getRegion().getCounter();
847 Counter ThenCount = getRegionCounter(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000848
Justin Bogner91f2e3c2015-02-19 03:10:30 +0000849 // Emitting a counter for the condition makes it easier to interpret the
850 // counter for the body when looking at the coverage.
851 propagateCounts(ParentCount, S->getCond());
852
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000853 extendRegion(S->getThen());
854 Counter OutCount = propagateCounts(ThenCount, S->getThen());
855
856 Counter ElseCount = subtractCounters(ParentCount, ThenCount);
857 if (const Stmt *Else = S->getElse()) {
858 extendRegion(S->getElse());
859 OutCount = addCounters(OutCount, propagateCounts(ElseCount, Else));
860 } else
861 OutCount = addCounters(OutCount, ElseCount);
862
863 if (OutCount != ParentCount)
864 pushRegion(OutCount);
Alex Lorenzee024992014-08-04 18:41:51 +0000865 }
866
867 void VisitCXXTryStmt(const CXXTryStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000868 extendRegion(S);
Vedant Kumar049908b2016-06-22 19:57:58 +0000869 // Handle macros that generate the "try" but not the rest.
870 extendRegion(S->getTryBlock());
871
872 Counter ParentCount = getRegion().getCounter();
873 propagateCounts(ParentCount, S->getTryBlock());
874
Alex Lorenzee024992014-08-04 18:41:51 +0000875 for (unsigned I = 0, E = S->getNumHandlers(); I < E; ++I)
876 Visit(S->getHandler(I));
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000877
878 Counter ExitCount = getRegionCounter(S);
879 pushRegion(ExitCount);
Alex Lorenzee024992014-08-04 18:41:51 +0000880 }
881
882 void VisitCXXCatchStmt(const CXXCatchStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000883 propagateCounts(getRegionCounter(S), S->getHandlerBlock());
Alex Lorenzee024992014-08-04 18:41:51 +0000884 }
885
886 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000887 extendRegion(E);
Alex Lorenzee024992014-08-04 18:41:51 +0000888
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000889 Counter ParentCount = getRegion().getCounter();
890 Counter TrueCount = getRegionCounter(E);
Alex Lorenzee024992014-08-04 18:41:51 +0000891
Justin Bognere3654ce2015-04-24 23:37:57 +0000892 Visit(E->getCond());
893
894 if (!isa<BinaryConditionalOperator>(E)) {
895 extendRegion(E->getTrueExpr());
896 propagateCounts(TrueCount, E->getTrueExpr());
897 }
898 extendRegion(E->getFalseExpr());
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000899 propagateCounts(subtractCounters(ParentCount, TrueCount),
900 E->getFalseExpr());
Alex Lorenzee024992014-08-04 18:41:51 +0000901 }
902
903 void VisitBinLAnd(const BinaryOperator *E) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000904 extendRegion(E);
Alex Lorenzee024992014-08-04 18:41:51 +0000905 Visit(E->getLHS());
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000906
907 extendRegion(E->getRHS());
908 propagateCounts(getRegionCounter(E), E->getRHS());
Alex Lorenzee024992014-08-04 18:41:51 +0000909 }
910
911 void VisitBinLOr(const BinaryOperator *E) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000912 extendRegion(E);
Alex Lorenzee024992014-08-04 18:41:51 +0000913 Visit(E->getLHS());
Alex Lorenzee024992014-08-04 18:41:51 +0000914
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000915 extendRegion(E->getRHS());
916 propagateCounts(getRegionCounter(E), E->getRHS());
Alex Lorenz01a0d062014-08-20 17:10:56 +0000917 }
Justin Bognerc1091022015-02-24 04:13:56 +0000918
919 void VisitLambdaExpr(const LambdaExpr *LE) {
920 // Lambdas are treated as their own functions for now, so we shouldn't
921 // propagate counts into them.
922 }
Alex Lorenzee024992014-08-04 18:41:51 +0000923};
Alex Lorenzee024992014-08-04 18:41:51 +0000924
Vedant Kumar14f8fb62016-07-18 21:01:27 +0000925bool isMachO(const CodeGenModule &CGM) {
Alex Lorenzee024992014-08-04 18:41:51 +0000926 return CGM.getTarget().getTriple().isOSBinFormatMachO();
927}
928
Vedant Kumar14f8fb62016-07-18 21:01:27 +0000929StringRef getCoverageSection(const CodeGenModule &CGM) {
Xinliang David Li03711cb2015-10-22 22:25:11 +0000930 return llvm::getInstrProfCoverageSectionName(isMachO(CGM));
Alex Lorenzee024992014-08-04 18:41:51 +0000931}
932
Vedant Kumar14f8fb62016-07-18 21:01:27 +0000933std::string normalizeFilename(StringRef Filename) {
934 llvm::SmallString<256> Path(Filename);
935 llvm::sys::path::remove_dots(Path, /*remove_dot_dots=*/true);
936 llvm::sys::fs::make_absolute(Path);
937 return Path.str().str();
938}
939
940} // end anonymous namespace
941
Justin Bognera432d172015-02-03 00:20:24 +0000942static void dump(llvm::raw_ostream &OS, StringRef FunctionName,
943 ArrayRef<CounterExpression> Expressions,
944 ArrayRef<CounterMappingRegion> Regions) {
945 OS << FunctionName << ":\n";
946 CounterMappingContext Ctx(Expressions);
947 for (const auto &R : Regions) {
Alex Lorenzf2cf38e2014-08-08 23:41:24 +0000948 OS.indent(2);
949 switch (R.Kind) {
950 case CounterMappingRegion::CodeRegion:
951 break;
952 case CounterMappingRegion::ExpansionRegion:
953 OS << "Expansion,";
954 break;
955 case CounterMappingRegion::SkippedRegion:
956 OS << "Skipped,";
957 break;
958 }
959
Justin Bogner4da909b2015-02-03 21:35:49 +0000960 OS << "File " << R.FileID << ", " << R.LineStart << ":" << R.ColumnStart
961 << " -> " << R.LineEnd << ":" << R.ColumnEnd << " = ";
Justin Bognerf69dc342015-01-23 23:46:13 +0000962 Ctx.dump(R.Count, OS);
Alex Lorenzf2cf38e2014-08-08 23:41:24 +0000963 if (R.Kind == CounterMappingRegion::ExpansionRegion)
Justin Bogner4da909b2015-02-03 21:35:49 +0000964 OS << " (Expanded file = " << R.ExpandedFileID << ")";
965 OS << "\n";
Alex Lorenzf2cf38e2014-08-08 23:41:24 +0000966 }
967}
968
Alex Lorenzee024992014-08-04 18:41:51 +0000969void CoverageMappingModuleGen::addFunctionMappingRecord(
Xinliang David Li2129ae52016-01-07 20:05:55 +0000970 llvm::GlobalVariable *NamePtr, StringRef NameValue, uint64_t FuncHash,
Xinliang David Li848da132016-01-19 00:49:06 +0000971 const std::string &CoverageMapping, bool IsUsed) {
Alex Lorenzee024992014-08-04 18:41:51 +0000972 llvm::LLVMContext &Ctx = CGM.getLLVMContext();
Alex Lorenzee024992014-08-04 18:41:51 +0000973 if (!FunctionRecordTy) {
Xinliang David Li2129ae52016-01-07 20:05:55 +0000974#define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) LLVMType,
Xinliang David Lia026a432015-11-05 05:46:39 +0000975 llvm::Type *FunctionRecordTypes[] = {
976 #include "llvm/ProfileData/InstrProfData.inc"
977 };
Alex Lorenzee024992014-08-04 18:41:51 +0000978 FunctionRecordTy =
Justin Bogner4dc5adc2015-07-02 20:47:25 +0000979 llvm::StructType::get(Ctx, makeArrayRef(FunctionRecordTypes),
980 /*isPacked=*/true);
Alex Lorenzee024992014-08-04 18:41:51 +0000981 }
982
Xinliang David Lia026a432015-11-05 05:46:39 +0000983 #define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) Init,
Alex Lorenzee024992014-08-04 18:41:51 +0000984 llvm::Constant *FunctionRecordVals[] = {
Xinliang David Lia026a432015-11-05 05:46:39 +0000985 #include "llvm/ProfileData/InstrProfData.inc"
986 };
Alex Lorenzee024992014-08-04 18:41:51 +0000987 FunctionRecords.push_back(llvm::ConstantStruct::get(
988 FunctionRecordTy, makeArrayRef(FunctionRecordVals)));
Xinliang David Li848da132016-01-19 00:49:06 +0000989 if (!IsUsed)
Xinliang David Li2129ae52016-01-07 20:05:55 +0000990 FunctionNames.push_back(
991 llvm::ConstantExpr::getBitCast(NamePtr, llvm::Type::getInt8PtrTy(Ctx)));
Vedant Kumarca3326c2016-01-21 19:25:35 +0000992 CoverageMappings.push_back(CoverageMapping);
Alex Lorenzf2cf38e2014-08-08 23:41:24 +0000993
994 if (CGM.getCodeGenOpts().DumpCoverageMapping) {
995 // Dump the coverage mapping data for this function by decoding the
996 // encoded data. This allows us to dump the mapping regions which were
997 // also processed by the CoverageMappingWriter which performs
998 // additional minimization operations such as reducing the number of
999 // expressions.
1000 std::vector<StringRef> Filenames;
1001 std::vector<CounterExpression> Expressions;
1002 std::vector<CounterMappingRegion> Regions;
1003 llvm::SmallVector<StringRef, 16> FilenameRefs;
1004 FilenameRefs.resize(FileEntries.size());
1005 for (const auto &Entry : FileEntries)
Vedant Kumar14f8fb62016-07-18 21:01:27 +00001006 FilenameRefs[Entry.second] = normalizeFilename(Entry.first->getName());
Justin Bognera432d172015-02-03 00:20:24 +00001007 RawCoverageMappingReader Reader(CoverageMapping, FilenameRefs, Filenames,
1008 Expressions, Regions);
1009 if (Reader.read())
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00001010 return;
Xinliang David Lia026a432015-11-05 05:46:39 +00001011 dump(llvm::outs(), NameValue, Expressions, Regions);
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00001012 }
Alex Lorenzee024992014-08-04 18:41:51 +00001013}
1014
1015void CoverageMappingModuleGen::emit() {
1016 if (FunctionRecords.empty())
1017 return;
1018 llvm::LLVMContext &Ctx = CGM.getLLVMContext();
1019 auto *Int32Ty = llvm::Type::getInt32Ty(Ctx);
1020
1021 // Create the filenames and merge them with coverage mappings
1022 llvm::SmallVector<std::string, 16> FilenameStrs;
Vedant Kumar9e324dd2016-06-29 05:33:09 +00001023 llvm::SmallVector<StringRef, 16> FilenameRefs;
Alex Lorenzee024992014-08-04 18:41:51 +00001024 FilenameStrs.resize(FileEntries.size());
Vedant Kumar9e324dd2016-06-29 05:33:09 +00001025 FilenameRefs.resize(FileEntries.size());
Alex Lorenzee024992014-08-04 18:41:51 +00001026 for (const auto &Entry : FileEntries) {
Alex Lorenzee024992014-08-04 18:41:51 +00001027 auto I = Entry.second;
Vedant Kumar14f8fb62016-07-18 21:01:27 +00001028 FilenameStrs[I] = normalizeFilename(Entry.first->getName());
Vedant Kumar9e324dd2016-06-29 05:33:09 +00001029 FilenameRefs[I] = FilenameStrs[I];
Alex Lorenzee024992014-08-04 18:41:51 +00001030 }
1031
Vedant Kumar9e324dd2016-06-29 05:33:09 +00001032 std::string FilenamesAndCoverageMappings;
1033 llvm::raw_string_ostream OS(FilenamesAndCoverageMappings);
1034 CoverageFilenamesSectionWriter(FilenameRefs).write(OS);
1035 std::string RawCoverageMappings =
1036 llvm::join(CoverageMappings.begin(), CoverageMappings.end(), "");
1037 OS << RawCoverageMappings;
1038 size_t CoverageMappingSize = RawCoverageMappings.size();
1039 size_t FilenamesSize = OS.str().size() - CoverageMappingSize;
1040 // Append extra zeroes if necessary to ensure that the size of the filenames
1041 // and coverage mappings is a multiple of 8.
1042 if (size_t Rem = OS.str().size() % 8) {
1043 CoverageMappingSize += 8 - Rem;
1044 for (size_t I = 0, S = 8 - Rem; I < S; ++I)
1045 OS << '\0';
Alex Lorenzee024992014-08-04 18:41:51 +00001046 }
1047 auto *FilenamesAndMappingsVal =
Vedant Kumar9e324dd2016-06-29 05:33:09 +00001048 llvm::ConstantDataArray::getString(Ctx, OS.str(), false);
Alex Lorenzee024992014-08-04 18:41:51 +00001049
1050 // Create the deferred function records array
1051 auto RecordsTy =
1052 llvm::ArrayType::get(FunctionRecordTy, FunctionRecords.size());
1053 auto RecordsVal = llvm::ConstantArray::get(RecordsTy, FunctionRecords);
1054
Xinliang David Li20b188c2016-01-03 19:25:54 +00001055 llvm::Type *CovDataHeaderTypes[] = {
1056#define COVMAP_HEADER(Type, LLVMType, Name, Init) LLVMType,
1057#include "llvm/ProfileData/InstrProfData.inc"
1058 };
1059 auto CovDataHeaderTy =
1060 llvm::StructType::get(Ctx, makeArrayRef(CovDataHeaderTypes));
1061 llvm::Constant *CovDataHeaderVals[] = {
1062#define COVMAP_HEADER(Type, LLVMType, Name, Init) Init,
1063#include "llvm/ProfileData/InstrProfData.inc"
1064 };
1065 auto CovDataHeaderVal = llvm::ConstantStruct::get(
1066 CovDataHeaderTy, makeArrayRef(CovDataHeaderVals));
1067
Alex Lorenzee024992014-08-04 18:41:51 +00001068 // Create the coverage data record
Xinliang David Li20b188c2016-01-03 19:25:54 +00001069 llvm::Type *CovDataTypes[] = {CovDataHeaderTy, RecordsTy,
1070 FilenamesAndMappingsVal->getType()};
Alex Lorenzee024992014-08-04 18:41:51 +00001071 auto CovDataTy = llvm::StructType::get(Ctx, makeArrayRef(CovDataTypes));
Xinliang David Li20b188c2016-01-03 19:25:54 +00001072 llvm::Constant *TUDataVals[] = {CovDataHeaderVal, RecordsVal,
1073 FilenamesAndMappingsVal};
Alex Lorenzee024992014-08-04 18:41:51 +00001074 auto CovDataVal =
1075 llvm::ConstantStruct::get(CovDataTy, makeArrayRef(TUDataVals));
Xinliang David Li20b188c2016-01-03 19:25:54 +00001076 auto CovData = new llvm::GlobalVariable(
1077 CGM.getModule(), CovDataTy, true, llvm::GlobalValue::InternalLinkage,
1078 CovDataVal, llvm::getCoverageMappingVarName());
Alex Lorenzee024992014-08-04 18:41:51 +00001079
1080 CovData->setSection(getCoverageSection(CGM));
1081 CovData->setAlignment(8);
1082
1083 // Make sure the data doesn't get deleted.
1084 CGM.addUsedGlobal(CovData);
Xinliang David Li2129ae52016-01-07 20:05:55 +00001085 // Create the deferred function records array
1086 if (!FunctionNames.empty()) {
1087 auto NamesArrTy = llvm::ArrayType::get(llvm::Type::getInt8PtrTy(Ctx),
1088 FunctionNames.size());
1089 auto NamesArrVal = llvm::ConstantArray::get(NamesArrTy, FunctionNames);
1090 // This variable will *NOT* be emitted to the object file. It is used
1091 // to pass the list of names referenced to codegen.
1092 new llvm::GlobalVariable(CGM.getModule(), NamesArrTy, true,
1093 llvm::GlobalValue::InternalLinkage, NamesArrVal,
Xinliang David Li7077f0a2016-01-20 00:24:52 +00001094 llvm::getCoverageUnusedNamesVarName());
Xinliang David Li2129ae52016-01-07 20:05:55 +00001095 }
Alex Lorenzee024992014-08-04 18:41:51 +00001096}
1097
1098unsigned CoverageMappingModuleGen::getFileID(const FileEntry *File) {
1099 auto It = FileEntries.find(File);
1100 if (It != FileEntries.end())
1101 return It->second;
1102 unsigned FileID = FileEntries.size();
1103 FileEntries.insert(std::make_pair(File, FileID));
1104 return FileID;
1105}
1106
1107void CoverageMappingGen::emitCounterMapping(const Decl *D,
1108 llvm::raw_ostream &OS) {
1109 assert(CounterMap);
Justin Bognere5ee6c52014-10-02 16:44:01 +00001110 CounterCoverageMappingBuilder Walker(CVM, *CounterMap, SM, LangOpts);
Alex Lorenzee024992014-08-04 18:41:51 +00001111 Walker.VisitDecl(D);
1112 Walker.write(OS);
1113}
1114
1115void CoverageMappingGen::emitEmptyMapping(const Decl *D,
1116 llvm::raw_ostream &OS) {
1117 EmptyCoverageMappingBuilder Walker(CVM, SM, LangOpts);
1118 Walker.VisitDecl(D);
1119 Walker.write(OS);
1120}