blob: 73afeda357255b127f99b4d23b25f4092dfd0ced [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"
Justin Bognerbf42cfd2015-02-18 21:24:51 +000018#include "llvm/ADT/Optional.h"
Alex Lorenzee024992014-08-04 18:41:51 +000019#include "llvm/ProfileData/CoverageMapping.h"
Alex Lorenzf2cf38e2014-08-08 23:41:24 +000020#include "llvm/ProfileData/CoverageMappingReader.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000021#include "llvm/ProfileData/CoverageMappingWriter.h"
22#include "llvm/ProfileData/InstrProfReader.h"
Alex Lorenzee024992014-08-04 18:41:51 +000023#include "llvm/Support/FileSystem.h"
24
25using namespace clang;
26using namespace CodeGen;
27using namespace llvm::coverage;
28
29void CoverageSourceInfo::SourceRangeSkipped(SourceRange Range) {
30 SkippedRanges.push_back(Range);
31}
32
33namespace {
34
35/// \brief A region of source code that can be mapped to a counter.
Justin Bogner09c71792014-10-01 03:33:49 +000036class SourceMappingRegion {
Alex Lorenzee024992014-08-04 18:41:51 +000037 Counter Count;
38
Alex Lorenzee024992014-08-04 18:41:51 +000039 /// \brief The region's starting location.
Justin Bognerbf42cfd2015-02-18 21:24:51 +000040 Optional<SourceLocation> LocStart;
Alex Lorenzee024992014-08-04 18:41:51 +000041
42 /// \brief The region's ending location.
Justin Bognerbf42cfd2015-02-18 21:24:51 +000043 Optional<SourceLocation> LocEnd;
Alex Lorenzee024992014-08-04 18:41:51 +000044
Justin Bogner09c71792014-10-01 03:33:49 +000045public:
Justin Bognerbf42cfd2015-02-18 21:24:51 +000046 SourceMappingRegion(Counter Count, Optional<SourceLocation> LocStart,
47 Optional<SourceLocation> LocEnd)
48 : Count(Count), LocStart(LocStart), LocEnd(LocEnd) {}
Alex Lorenzee024992014-08-04 18:41:51 +000049
Justin Bognerbf42cfd2015-02-18 21:24:51 +000050 SourceMappingRegion(SourceMappingRegion &&Region)
51 : Count(std::move(Region.Count)), LocStart(std::move(Region.LocStart)),
52 LocEnd(std::move(Region.LocEnd)) {}
53
54 SourceMappingRegion &operator=(SourceMappingRegion &&RHS) {
55 Count = std::move(RHS.Count);
56 LocStart = std::move(RHS.LocStart);
57 LocEnd = std::move(RHS.LocEnd);
58 return *this;
59 }
Justin Bogner09c71792014-10-01 03:33:49 +000060
61 const Counter &getCounter() const { return Count; }
62
Justin Bognerbf42cfd2015-02-18 21:24:51 +000063 void setCounter(Counter C) { Count = C; }
Justin Bogner09c71792014-10-01 03:33:49 +000064
Justin Bognerbf42cfd2015-02-18 21:24:51 +000065 bool hasStartLoc() const { return LocStart.hasValue(); }
66
67 void setStartLoc(SourceLocation Loc) { LocStart = Loc; }
68
69 const SourceLocation &getStartLoc() const {
70 assert(LocStart && "Region has no start location");
71 return *LocStart;
Justin Bogner09c71792014-10-01 03:33:49 +000072 }
73
Justin Bognerbf42cfd2015-02-18 21:24:51 +000074 bool hasEndLoc() const { return LocEnd.hasValue(); }
Alex Lorenzee024992014-08-04 18:41:51 +000075
Justin Bognerbf42cfd2015-02-18 21:24:51 +000076 void setEndLoc(SourceLocation Loc) { LocEnd = Loc; }
Alex Lorenzee024992014-08-04 18:41:51 +000077
Justin Bognerbf42cfd2015-02-18 21:24:51 +000078 const SourceLocation &getEndLoc() const {
79 assert(LocEnd && "Region has no end location");
80 return *LocEnd;
Alex Lorenzee024992014-08-04 18:41:51 +000081 }
82};
83
Alex Lorenzee024992014-08-04 18:41:51 +000084/// \brief Provides the common functionality for the different
85/// coverage mapping region builders.
86class CoverageMappingBuilder {
87public:
88 CoverageMappingModuleGen &CVM;
89 SourceManager &SM;
90 const LangOptions &LangOpts;
91
92private:
Justin Bognerbf42cfd2015-02-18 21:24:51 +000093 /// \brief Map of clang's FileIDs to IDs used for coverage mapping.
94 llvm::SmallDenseMap<FileID, std::pair<unsigned, SourceLocation>, 8>
95 FileIDMapping;
Alex Lorenzee024992014-08-04 18:41:51 +000096
97public:
Alex Lorenzee024992014-08-04 18:41:51 +000098 /// \brief The coverage mapping regions for this function
99 llvm::SmallVector<CounterMappingRegion, 32> MappingRegions;
100 /// \brief The source mapping regions for this function.
Justin Bognerf59329b2014-10-01 03:33:52 +0000101 std::vector<SourceMappingRegion> SourceRegions;
Alex Lorenzee024992014-08-04 18:41:51 +0000102
103 CoverageMappingBuilder(CoverageMappingModuleGen &CVM, SourceManager &SM,
104 const LangOptions &LangOpts)
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000105 : CVM(CVM), SM(SM), LangOpts(LangOpts) {}
Alex Lorenzee024992014-08-04 18:41:51 +0000106
107 /// \brief Return the precise end location for the given token.
108 SourceLocation getPreciseTokenLocEnd(SourceLocation Loc) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000109 // We avoid getLocForEndOfToken here, because it doesn't do what we want for
110 // macro locations, which we just treat as expanded files.
111 unsigned TokLen =
112 Lexer::MeasureTokenLength(SM.getSpellingLoc(Loc), SM, LangOpts);
113 return Loc.getLocWithOffset(TokLen);
Alex Lorenzee024992014-08-04 18:41:51 +0000114 }
115
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000116 /// \brief Return the start location of an included file or expanded macro.
117 SourceLocation getStartOfFileOrMacro(SourceLocation Loc) {
118 if (Loc.isMacroID())
119 return Loc.getLocWithOffset(-SM.getFileOffset(Loc));
120 return SM.getLocForStartOfFile(SM.getFileID(Loc));
Alex Lorenzee024992014-08-04 18:41:51 +0000121 }
122
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000123 /// \brief Return the end location of an included file or expanded macro.
124 SourceLocation getEndOfFileOrMacro(SourceLocation Loc) {
125 if (Loc.isMacroID())
126 return Loc.getLocWithOffset(SM.getFileIDSize(SM.getFileID(Loc)) -
Justin Bognerf14b2072015-03-25 04:13:49 +0000127 SM.getFileOffset(Loc));
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000128 return SM.getLocForEndOfFile(SM.getFileID(Loc));
129 }
130
131 /// \brief Find out where the current file is included or macro is expanded.
132 SourceLocation getIncludeOrExpansionLoc(SourceLocation Loc) {
133 return Loc.isMacroID() ? SM.getImmediateExpansionRange(Loc).first
134 : SM.getIncludeLoc(SM.getFileID(Loc));
135 }
136
137 /// \brief Get the start of \c S ignoring macro argument locations.
138 SourceLocation getStart(const Stmt *S) {
139 SourceLocation Loc = S->getLocStart();
140 while (SM.isMacroArgExpansion(Loc))
141 Loc = SM.getImmediateExpansionRange(Loc).first;
142 return Loc;
143 }
144
145 /// \brief Get the end of \c S ignoring macro argument locations.
146 SourceLocation getEnd(const Stmt *S) {
147 SourceLocation Loc = S->getLocEnd();
148 while (SM.isMacroArgExpansion(Loc))
149 Loc = SM.getImmediateExpansionRange(Loc).first;
Justin Bognerf14b2072015-03-25 04:13:49 +0000150 return getPreciseTokenLocEnd(Loc);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000151 }
152
153 /// \brief Find the set of files we have regions for and assign IDs
154 ///
155 /// Fills \c Mapping with the virtual file mapping needed to write out
156 /// coverage and collects the necessary file information to emit source and
157 /// expansion regions.
158 void gatherFileIDs(SmallVectorImpl<unsigned> &Mapping) {
159 FileIDMapping.clear();
160
161 SmallVector<FileID, 8> Visited;
162 SmallVector<std::pair<SourceLocation, unsigned>, 8> FileLocs;
163 for (const auto &Region : SourceRegions) {
164 SourceLocation Loc = Region.getStartLoc();
165 FileID File = SM.getFileID(Loc);
166 if (std::find(Visited.begin(), Visited.end(), File) != Visited.end())
167 continue;
168 Visited.push_back(File);
169
170 unsigned Depth = 0;
171 for (SourceLocation Parent = getIncludeOrExpansionLoc(Loc);
172 !Parent.isInvalid(); Parent = getIncludeOrExpansionLoc(Parent))
173 ++Depth;
174 FileLocs.push_back(std::make_pair(Loc, Depth));
175 }
176 std::stable_sort(FileLocs.begin(), FileLocs.end(), llvm::less_second());
177
178 for (const auto &FL : FileLocs) {
179 SourceLocation Loc = FL.first;
180 FileID SpellingFile = SM.getDecomposedSpellingLoc(Loc).first;
181 auto Entry = SM.getFileEntryForID(SpellingFile);
182 if (!Entry)
183 continue;
184
185 FileIDMapping[SM.getFileID(Loc)] = std::make_pair(Mapping.size(), Loc);
186 Mapping.push_back(CVM.getFileID(Entry));
187 }
188 }
189
190 /// \brief Get the coverage mapping file ID for \c Loc.
191 ///
192 /// If such file id doesn't exist, return None.
193 Optional<unsigned> getCoverageFileID(SourceLocation Loc) {
194 auto Mapping = FileIDMapping.find(SM.getFileID(Loc));
Justin Bogner903678c2015-01-24 20:22:32 +0000195 if (Mapping != FileIDMapping.end())
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000196 return Mapping->second.first;
197 return None;
Alex Lorenzee024992014-08-04 18:41:51 +0000198 }
199
200 /// \brief Return true if the given clang's file id has a corresponding
201 /// coverage file id.
202 bool hasExistingCoverageFileID(FileID File) const {
203 return FileIDMapping.count(File);
204 }
205
206 /// \brief Gather all the regions that were skipped by the preprocessor
207 /// using the constructs like #if.
208 void gatherSkippedRegions() {
209 /// An array of the minimum lineStarts and the maximum lineEnds
210 /// for mapping regions from the appropriate source files.
211 llvm::SmallVector<std::pair<unsigned, unsigned>, 8> FileLineRanges;
212 FileLineRanges.resize(
213 FileIDMapping.size(),
214 std::make_pair(std::numeric_limits<unsigned>::max(), 0));
215 for (const auto &R : MappingRegions) {
216 FileLineRanges[R.FileID].first =
217 std::min(FileLineRanges[R.FileID].first, R.LineStart);
218 FileLineRanges[R.FileID].second =
219 std::max(FileLineRanges[R.FileID].second, R.LineEnd);
220 }
221
222 auto SkippedRanges = CVM.getSourceInfo().getSkippedRanges();
223 for (const auto &I : SkippedRanges) {
224 auto LocStart = I.getBegin();
225 auto LocEnd = I.getEnd();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000226 assert(SM.isWrittenInSameFile(LocStart, LocEnd) &&
227 "region spans multiple files");
Alex Lorenzee024992014-08-04 18:41:51 +0000228
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000229 auto CovFileID = getCoverageFileID(LocStart);
Justin Bogner903678c2015-01-24 20:22:32 +0000230 if (!CovFileID)
Alex Lorenzee024992014-08-04 18:41:51 +0000231 continue;
232 unsigned LineStart = SM.getSpellingLineNumber(LocStart);
233 unsigned ColumnStart = SM.getSpellingColumnNumber(LocStart);
234 unsigned LineEnd = SM.getSpellingLineNumber(LocEnd);
235 unsigned ColumnEnd = SM.getSpellingColumnNumber(LocEnd);
Justin Bognerfd34280b2015-02-03 23:59:48 +0000236 auto Region = CounterMappingRegion::makeSkipped(
237 *CovFileID, LineStart, ColumnStart, LineEnd, ColumnEnd);
Alex Lorenzee024992014-08-04 18:41:51 +0000238 // Make sure that we only collect the regions that are inside
239 // the souce code of this function.
Justin Bogner903678c2015-01-24 20:22:32 +0000240 if (Region.LineStart >= FileLineRanges[*CovFileID].first &&
241 Region.LineEnd <= FileLineRanges[*CovFileID].second)
Alex Lorenzee024992014-08-04 18:41:51 +0000242 MappingRegions.push_back(Region);
243 }
244 }
245
Alex Lorenzee024992014-08-04 18:41:51 +0000246 /// \brief Generate the coverage counter mapping regions from collected
247 /// source regions.
248 void emitSourceRegions() {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000249 for (const auto &Region : SourceRegions) {
250 assert(Region.hasEndLoc() && "incomplete region");
Alex Lorenzee024992014-08-04 18:41:51 +0000251
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000252 SourceLocation LocStart = Region.getStartLoc();
253 assert(!SM.getFileID(LocStart).isInvalid() && "region in invalid file");
Justin Bognerf59329b2014-10-01 03:33:52 +0000254
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000255 auto CovFileID = getCoverageFileID(LocStart);
256 // Ignore regions that don't have a file, such as builtin macros.
257 if (!CovFileID)
Alex Lorenzee024992014-08-04 18:41:51 +0000258 continue;
259
Justin Bognerf14b2072015-03-25 04:13:49 +0000260 SourceLocation LocEnd = Region.getEndLoc();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000261 assert(SM.isWrittenInSameFile(LocStart, LocEnd) &&
262 "region spans multiple files");
263
Justin Bognerf59329b2014-10-01 03:33:52 +0000264 // Find the spilling locations for the mapping region.
Alex Lorenzee024992014-08-04 18:41:51 +0000265 unsigned LineStart = SM.getSpellingLineNumber(LocStart);
266 unsigned ColumnStart = SM.getSpellingColumnNumber(LocStart);
267 unsigned LineEnd = SM.getSpellingLineNumber(LocEnd);
268 unsigned ColumnEnd = SM.getSpellingColumnNumber(LocEnd);
269
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000270 assert(LineStart <= LineEnd && "region start and end out of order");
271 MappingRegions.push_back(CounterMappingRegion::makeRegion(
272 Region.getCounter(), *CovFileID, LineStart, ColumnStart, LineEnd,
273 ColumnEnd));
274 }
275 }
276
277 /// \brief Generate expansion regions for each virtual file we've seen.
278 void emitExpansionRegions() {
279 for (const auto &FM : FileIDMapping) {
280 SourceLocation ExpandedLoc = FM.second.second;
281 SourceLocation ParentLoc = getIncludeOrExpansionLoc(ExpandedLoc);
282 if (ParentLoc.isInvalid())
Alex Lorenzee024992014-08-04 18:41:51 +0000283 continue;
284
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000285 auto ParentFileID = getCoverageFileID(ParentLoc);
286 if (!ParentFileID)
287 continue;
288 auto ExpandedFileID = getCoverageFileID(ExpandedLoc);
289 assert(ExpandedFileID && "expansion in uncovered file");
290
291 SourceLocation LocEnd = getPreciseTokenLocEnd(ParentLoc);
292 assert(SM.isWrittenInSameFile(ParentLoc, LocEnd) &&
293 "region spans multiple files");
294
295 unsigned LineStart = SM.getSpellingLineNumber(ParentLoc);
296 unsigned ColumnStart = SM.getSpellingColumnNumber(ParentLoc);
297 unsigned LineEnd = SM.getSpellingLineNumber(LocEnd);
298 unsigned ColumnEnd = SM.getSpellingColumnNumber(LocEnd);
299
300 MappingRegions.push_back(CounterMappingRegion::makeExpansion(
301 *ParentFileID, *ExpandedFileID, LineStart, ColumnStart, LineEnd,
Justin Bognerfd34280b2015-02-03 23:59:48 +0000302 ColumnEnd));
Alex Lorenzee024992014-08-04 18:41:51 +0000303 }
304 }
305};
306
307/// \brief Creates unreachable coverage regions for the functions that
308/// are not emitted.
309struct EmptyCoverageMappingBuilder : public CoverageMappingBuilder {
310 EmptyCoverageMappingBuilder(CoverageMappingModuleGen &CVM, SourceManager &SM,
311 const LangOptions &LangOpts)
312 : CoverageMappingBuilder(CVM, SM, LangOpts) {}
313
314 void VisitDecl(const Decl *D) {
315 if (!D->hasBody())
316 return;
317 auto Body = D->getBody();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000318 SourceRegions.emplace_back(Counter(), getStart(Body), getEnd(Body));
Alex Lorenzee024992014-08-04 18:41:51 +0000319 }
320
321 /// \brief Write the mapping data to the output stream
322 void write(llvm::raw_ostream &OS) {
Alex Lorenzee024992014-08-04 18:41:51 +0000323 SmallVector<unsigned, 16> FileIDMapping;
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000324 gatherFileIDs(FileIDMapping);
325 emitSourceRegions();
Alex Lorenzee024992014-08-04 18:41:51 +0000326
Craig Topper5fc8fc22014-08-27 06:28:36 +0000327 CoverageMappingWriter Writer(FileIDMapping, None, MappingRegions);
Alex Lorenzee024992014-08-04 18:41:51 +0000328 Writer.write(OS);
329 }
330};
331
332/// \brief A StmtVisitor that creates coverage mapping regions which map
333/// from the source code locations to the PGO counters.
334struct CounterCoverageMappingBuilder
335 : public CoverageMappingBuilder,
336 public ConstStmtVisitor<CounterCoverageMappingBuilder> {
337 /// \brief The map of statements to count values.
338 llvm::DenseMap<const Stmt *, unsigned> &CounterMap;
339
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000340 /// \brief A stack of currently live regions.
341 std::vector<SourceMappingRegion> RegionStack;
Alex Lorenzee024992014-08-04 18:41:51 +0000342
343 CounterExpressionBuilder Builder;
344
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000345 /// \brief A location in the most recently visited file or macro.
346 ///
347 /// This is used to adjust the active source regions appropriately when
348 /// expressions cross file or macro boundaries.
349 SourceLocation MostRecentLocation;
350
351 /// \brief Return a counter for the subtraction of \c RHS from \c LHS
Alex Lorenzee024992014-08-04 18:41:51 +0000352 Counter subtractCounters(Counter LHS, Counter RHS) {
353 return Builder.subtract(LHS, RHS);
354 }
355
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000356 /// \brief Return a counter for the sum of \c LHS and \c RHS.
Alex Lorenzee024992014-08-04 18:41:51 +0000357 Counter addCounters(Counter LHS, Counter RHS) {
358 return Builder.add(LHS, RHS);
359 }
360
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000361 Counter addCounters(Counter C1, Counter C2, Counter C3) {
362 return addCounters(addCounters(C1, C2), C3);
363 }
364
365 Counter addCounters(Counter C1, Counter C2, Counter C3, Counter C4) {
366 return addCounters(addCounters(C1, C2, C3), C4);
367 }
368
Alex Lorenzee024992014-08-04 18:41:51 +0000369 /// \brief Return the region counter for the given statement.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000370 ///
Alex Lorenzee024992014-08-04 18:41:51 +0000371 /// This should only be called on statements that have a dedicated counter.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000372 Counter getRegionCounter(const Stmt *S) {
373 return Counter::getCounter(CounterMap[S]);
Alex Lorenzee024992014-08-04 18:41:51 +0000374 }
375
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000376 /// \brief Push a region onto the stack.
377 ///
378 /// Returns the index on the stack where the region was pushed. This can be
379 /// used with popRegions to exit a "scope", ending the region that was pushed.
380 size_t pushRegion(Counter Count, Optional<SourceLocation> StartLoc = None,
381 Optional<SourceLocation> EndLoc = None) {
382 if (StartLoc)
383 MostRecentLocation = *StartLoc;
384 RegionStack.emplace_back(Count, StartLoc, EndLoc);
Alex Lorenzee024992014-08-04 18:41:51 +0000385
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000386 return RegionStack.size() - 1;
Alex Lorenzee024992014-08-04 18:41:51 +0000387 }
388
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000389 /// \brief Pop regions from the stack into the function's list of regions.
390 ///
391 /// Adds all regions from \c ParentIndex to the top of the stack to the
392 /// function's \c SourceRegions.
393 void popRegions(size_t ParentIndex) {
394 assert(RegionStack.size() >= ParentIndex && "parent not in stack");
395 while (RegionStack.size() > ParentIndex) {
396 SourceMappingRegion &Region = RegionStack.back();
397 if (Region.hasStartLoc()) {
398 SourceLocation StartLoc = Region.getStartLoc();
399 SourceLocation EndLoc = Region.hasEndLoc()
400 ? Region.getEndLoc()
401 : RegionStack[ParentIndex].getEndLoc();
402 while (!SM.isWrittenInSameFile(StartLoc, EndLoc)) {
403 // The region ends in a nested file or macro expansion. Create a
404 // separate region for each expansion.
405 SourceLocation NestedLoc = getStartOfFileOrMacro(EndLoc);
406 assert(SM.isWrittenInSameFile(NestedLoc, EndLoc));
407
408 SourceRegions.emplace_back(Region.getCounter(), NestedLoc, EndLoc);
409
Justin Bognerf14b2072015-03-25 04:13:49 +0000410 EndLoc = getPreciseTokenLocEnd(getIncludeOrExpansionLoc(EndLoc));
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000411 assert(!EndLoc.isInvalid() &&
412 "File exit was not handled before popRegions");
413 }
414 Region.setEndLoc(EndLoc);
415
416 MostRecentLocation = EndLoc;
417 // If this region happens to span an entire expansion, we need to make
418 // sure we don't overlap the parent region with it.
419 if (StartLoc == getStartOfFileOrMacro(StartLoc) &&
420 EndLoc == getEndOfFileOrMacro(EndLoc))
421 MostRecentLocation = getIncludeOrExpansionLoc(EndLoc);
422
423 assert(SM.isWrittenInSameFile(Region.getStartLoc(), EndLoc));
424 SourceRegions.push_back(std::move(Region));
425 }
426 RegionStack.pop_back();
427 }
Alex Lorenzee024992014-08-04 18:41:51 +0000428 }
429
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000430 /// \brief Return the currently active region.
431 SourceMappingRegion &getRegion() {
432 assert(!RegionStack.empty() && "statement has no region");
433 return RegionStack.back();
434 }
Alex Lorenzee024992014-08-04 18:41:51 +0000435
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000436 /// \brief Propagate counts through the children of \c S.
437 Counter propagateCounts(Counter TopCount, const Stmt *S) {
438 size_t Index = pushRegion(TopCount, getStart(S), getEnd(S));
439 Visit(S);
440 Counter ExitCount = getRegion().getCounter();
441 popRegions(Index);
442 return ExitCount;
443 }
Alex Lorenzee024992014-08-04 18:41:51 +0000444
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000445 /// \brief Adjust the most recently visited location to \c EndLoc.
446 ///
447 /// This should be used after visiting any statements in non-source order.
448 void adjustForOutOfOrderTraversal(SourceLocation EndLoc) {
449 MostRecentLocation = EndLoc;
450 if (MostRecentLocation == getEndOfFileOrMacro(MostRecentLocation))
451 MostRecentLocation = getIncludeOrExpansionLoc(MostRecentLocation);
452 }
Alex Lorenzee024992014-08-04 18:41:51 +0000453
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000454 /// \brief Check whether \c Loc is included or expanded from \c Parent.
455 bool isNestedIn(SourceLocation Loc, FileID Parent) {
456 do {
457 Loc = getIncludeOrExpansionLoc(Loc);
458 if (Loc.isInvalid())
459 return false;
460 } while (!SM.isInFileID(Loc, Parent));
461 return true;
462 }
463
464 /// \brief Adjust regions and state when \c NewLoc exits a file.
465 ///
466 /// If moving from our most recently tracked location to \c NewLoc exits any
467 /// files, this adjusts our current region stack and creates the file regions
468 /// for the exited file.
469 void handleFileExit(SourceLocation NewLoc) {
470 if (SM.isWrittenInSameFile(MostRecentLocation, NewLoc))
471 return;
472
473 // If NewLoc is not in a file that contains MostRecentLocation, walk up to
474 // find the common ancestor.
475 SourceLocation LCA = NewLoc;
476 FileID ParentFile = SM.getFileID(LCA);
477 while (!isNestedIn(MostRecentLocation, ParentFile)) {
478 LCA = getIncludeOrExpansionLoc(LCA);
479 if (LCA.isInvalid() || SM.isWrittenInSameFile(LCA, MostRecentLocation)) {
480 // Since there isn't a common ancestor, no file was exited. We just need
481 // to adjust our location to the new file.
482 MostRecentLocation = NewLoc;
483 return;
484 }
485 ParentFile = SM.getFileID(LCA);
Alex Lorenzee024992014-08-04 18:41:51 +0000486 }
487
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000488 llvm::SmallSet<SourceLocation, 8> StartLocs;
489 Optional<Counter> ParentCounter;
490 for (auto I = RegionStack.rbegin(), E = RegionStack.rend(); I != E; ++I) {
491 if (!I->hasStartLoc())
492 continue;
493 SourceLocation Loc = I->getStartLoc();
494 if (!isNestedIn(Loc, ParentFile)) {
495 ParentCounter = I->getCounter();
496 break;
497 }
Alex Lorenzee024992014-08-04 18:41:51 +0000498
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000499 while (!SM.isInFileID(Loc, ParentFile)) {
500 // The most nested region for each start location is the one with the
501 // correct count. We avoid creating redundant regions by stopping once
502 // we've seen this region.
503 if (StartLocs.insert(Loc).second)
504 SourceRegions.emplace_back(I->getCounter(), Loc,
505 getEndOfFileOrMacro(Loc));
506 Loc = getIncludeOrExpansionLoc(Loc);
507 }
508 I->setStartLoc(getPreciseTokenLocEnd(Loc));
Alex Lorenzee024992014-08-04 18:41:51 +0000509 }
510
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000511 if (ParentCounter) {
512 // If the file is contained completely by another region and doesn't
513 // immediately start its own region, the whole file gets a region
514 // corresponding to the parent.
515 SourceLocation Loc = MostRecentLocation;
516 while (isNestedIn(Loc, ParentFile)) {
517 SourceLocation FileStart = getStartOfFileOrMacro(Loc);
518 if (StartLocs.insert(FileStart).second)
519 SourceRegions.emplace_back(*ParentCounter, FileStart,
520 getEndOfFileOrMacro(Loc));
521 Loc = getIncludeOrExpansionLoc(Loc);
522 }
Alex Lorenzee024992014-08-04 18:41:51 +0000523 }
524
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000525 MostRecentLocation = NewLoc;
526 }
Alex Lorenzee024992014-08-04 18:41:51 +0000527
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000528 /// \brief Ensure that \c S is included in the current region.
529 void extendRegion(const Stmt *S) {
530 SourceMappingRegion &Region = getRegion();
531 SourceLocation StartLoc = getStart(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000532
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000533 handleFileExit(StartLoc);
534 if (!Region.hasStartLoc())
535 Region.setStartLoc(StartLoc);
536 }
537
538 /// \brief Mark \c S as a terminator, starting a zero region.
539 void terminateRegion(const Stmt *S) {
540 extendRegion(S);
541 SourceMappingRegion &Region = getRegion();
542 if (!Region.hasEndLoc())
543 Region.setEndLoc(getEnd(S));
544 pushRegion(Counter::getZero());
545 }
Alex Lorenzee024992014-08-04 18:41:51 +0000546
547 /// \brief Keep counts of breaks and continues inside loops.
548 struct BreakContinue {
549 Counter BreakCount;
550 Counter ContinueCount;
551 };
552 SmallVector<BreakContinue, 8> BreakContinueStack;
553
554 CounterCoverageMappingBuilder(
555 CoverageMappingModuleGen &CVM,
Justin Bognere5ee6c52014-10-02 16:44:01 +0000556 llvm::DenseMap<const Stmt *, unsigned> &CounterMap, SourceManager &SM,
Alex Lorenzee024992014-08-04 18:41:51 +0000557 const LangOptions &LangOpts)
Justin Bognere5ee6c52014-10-02 16:44:01 +0000558 : CoverageMappingBuilder(CVM, SM, LangOpts), CounterMap(CounterMap) {}
Alex Lorenzee024992014-08-04 18:41:51 +0000559
560 /// \brief Write the mapping data to the output stream
561 void write(llvm::raw_ostream &OS) {
Alex Lorenzee024992014-08-04 18:41:51 +0000562 llvm::SmallVector<unsigned, 8> VirtualFileMapping;
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000563 gatherFileIDs(VirtualFileMapping);
564 emitSourceRegions();
565 emitExpansionRegions();
Alex Lorenzee024992014-08-04 18:41:51 +0000566 gatherSkippedRegions();
567
Justin Bogner4da909b2015-02-03 21:35:49 +0000568 CoverageMappingWriter Writer(VirtualFileMapping, Builder.getExpressions(),
569 MappingRegions);
Alex Lorenzee024992014-08-04 18:41:51 +0000570 Writer.write(OS);
571 }
572
Alex Lorenzee024992014-08-04 18:41:51 +0000573 void VisitStmt(const Stmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000574 if (!S->getLocStart().isInvalid())
575 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000576 for (Stmt::const_child_range I = S->children(); I; ++I) {
577 if (*I)
578 this->Visit(*I);
579 }
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000580 handleFileExit(getEnd(S));
Alex Lorenzee024992014-08-04 18:41:51 +0000581 }
582
Alex Lorenzee024992014-08-04 18:41:51 +0000583 void VisitDecl(const Decl *D) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000584 Stmt *Body = D->getBody();
585 propagateCounts(getRegionCounter(Body), Body);
Alex Lorenzee024992014-08-04 18:41:51 +0000586 }
587
588 void VisitReturnStmt(const ReturnStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000589 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000590 if (S->getRetValue())
591 Visit(S->getRetValue());
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000592 terminateRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000593 }
594
Justin Bognerf959feb2015-04-28 06:31:55 +0000595 void VisitCXXThrowExpr(const CXXThrowExpr *E) {
596 extendRegion(E);
597 if (E->getSubExpr())
598 Visit(E->getSubExpr());
599 terminateRegion(E);
600 }
601
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000602 void VisitGotoStmt(const GotoStmt *S) { terminateRegion(S); }
Alex Lorenzee024992014-08-04 18:41:51 +0000603
604 void VisitLabelStmt(const LabelStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000605 SourceLocation Start = getStart(S);
606 // We can't extendRegion here or we risk overlapping with our new region.
607 handleFileExit(Start);
608 pushRegion(getRegionCounter(S), Start);
Alex Lorenzee024992014-08-04 18:41:51 +0000609 Visit(S->getSubStmt());
610 }
611
612 void VisitBreakStmt(const BreakStmt *S) {
Alex Lorenzee024992014-08-04 18:41:51 +0000613 assert(!BreakContinueStack.empty() && "break not in a loop or switch!");
614 BreakContinueStack.back().BreakCount = addCounters(
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000615 BreakContinueStack.back().BreakCount, getRegion().getCounter());
616 terminateRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000617 }
618
619 void VisitContinueStmt(const ContinueStmt *S) {
Alex Lorenzee024992014-08-04 18:41:51 +0000620 assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
621 BreakContinueStack.back().ContinueCount = addCounters(
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000622 BreakContinueStack.back().ContinueCount, getRegion().getCounter());
623 terminateRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000624 }
625
626 void VisitWhileStmt(const WhileStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000627 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000628
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000629 Counter ParentCount = getRegion().getCounter();
630 Counter BodyCount = getRegionCounter(S);
631
632 // Handle the body first so that we can get the backedge count.
633 BreakContinueStack.push_back(BreakContinue());
634 extendRegion(S->getBody());
635 Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
Alex Lorenzee024992014-08-04 18:41:51 +0000636 BreakContinue BC = BreakContinueStack.pop_back_val();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000637
638 // Go back to handle the condition.
639 Counter CondCount =
640 addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
641 propagateCounts(CondCount, S->getCond());
642 adjustForOutOfOrderTraversal(getEnd(S));
643
644 Counter OutCount =
645 addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount));
646 if (OutCount != ParentCount)
647 pushRegion(OutCount);
Alex Lorenzee024992014-08-04 18:41:51 +0000648 }
649
650 void VisitDoStmt(const DoStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000651 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000652
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000653 Counter ParentCount = getRegion().getCounter();
654 Counter BodyCount = getRegionCounter(S);
655
656 BreakContinueStack.push_back(BreakContinue());
657 extendRegion(S->getBody());
658 Counter BackedgeCount =
659 propagateCounts(addCounters(ParentCount, BodyCount), S->getBody());
Alex Lorenzee024992014-08-04 18:41:51 +0000660 BreakContinue BC = BreakContinueStack.pop_back_val();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000661
662 Counter CondCount = addCounters(BackedgeCount, BC.ContinueCount);
663 propagateCounts(CondCount, S->getCond());
664
665 Counter OutCount =
666 addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount));
667 if (OutCount != ParentCount)
668 pushRegion(OutCount);
Alex Lorenzee024992014-08-04 18:41:51 +0000669 }
670
671 void VisitForStmt(const ForStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000672 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000673 if (S->getInit())
674 Visit(S->getInit());
675
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000676 Counter ParentCount = getRegion().getCounter();
677 Counter BodyCount = getRegionCounter(S);
678
679 // Handle the body first so that we can get the backedge count.
Alex Lorenzee024992014-08-04 18:41:51 +0000680 BreakContinueStack.push_back(BreakContinue());
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000681 extendRegion(S->getBody());
682 Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
683 BreakContinue BC = BreakContinueStack.pop_back_val();
Alex Lorenzee024992014-08-04 18:41:51 +0000684
685 // The increment is essentially part of the body but it needs to include
686 // the count for all the continue statements.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000687 if (const Stmt *Inc = S->getInc())
688 propagateCounts(addCounters(BackedgeCount, BC.ContinueCount), Inc);
689
690 // Go back to handle the condition.
691 Counter CondCount =
692 addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
693 if (const Expr *Cond = S->getCond()) {
694 propagateCounts(CondCount, Cond);
695 adjustForOutOfOrderTraversal(getEnd(S));
Alex Lorenzee024992014-08-04 18:41:51 +0000696 }
697
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000698 Counter OutCount =
699 addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount));
700 if (OutCount != ParentCount)
701 pushRegion(OutCount);
Alex Lorenzee024992014-08-04 18:41:51 +0000702 }
703
704 void VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000705 extendRegion(S);
706 Visit(S->getLoopVarStmt());
Alex Lorenzee024992014-08-04 18:41:51 +0000707 Visit(S->getRangeStmt());
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000708
709 Counter ParentCount = getRegion().getCounter();
710 Counter BodyCount = getRegionCounter(S);
711
Alex Lorenzee024992014-08-04 18:41:51 +0000712 BreakContinueStack.push_back(BreakContinue());
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000713 extendRegion(S->getBody());
714 Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
Alex Lorenzee024992014-08-04 18:41:51 +0000715 BreakContinue BC = BreakContinueStack.pop_back_val();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000716
717 Counter OutCount = addCounters(ParentCount, BC.BreakCount, BC.ContinueCount,
718 subtractCounters(BodyCount, BackedgeCount));
719 if (OutCount != ParentCount)
720 pushRegion(OutCount);
Alex Lorenzee024992014-08-04 18:41:51 +0000721 }
722
723 void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000724 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000725 Visit(S->getElement());
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000726
727 Counter ParentCount = getRegion().getCounter();
728 Counter BodyCount = getRegionCounter(S);
729
Alex Lorenzee024992014-08-04 18:41:51 +0000730 BreakContinueStack.push_back(BreakContinue());
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000731 extendRegion(S->getBody());
732 Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
Alex Lorenzee024992014-08-04 18:41:51 +0000733 BreakContinue BC = BreakContinueStack.pop_back_val();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000734
735 Counter OutCount = addCounters(ParentCount, BC.BreakCount, BC.ContinueCount,
736 subtractCounters(BodyCount, BackedgeCount));
737 if (OutCount != ParentCount)
738 pushRegion(OutCount);
Alex Lorenzee024992014-08-04 18:41:51 +0000739 }
740
741 void VisitSwitchStmt(const SwitchStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000742 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000743 Visit(S->getCond());
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000744
Alex Lorenzee024992014-08-04 18:41:51 +0000745 BreakContinueStack.push_back(BreakContinue());
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000746
747 const Stmt *Body = S->getBody();
748 extendRegion(Body);
749 if (const auto *CS = dyn_cast<CompoundStmt>(Body)) {
750 if (!CS->body_empty()) {
751 // The body of the switch needs a zero region so that fallthrough counts
752 // behave correctly, but it would be misleading to include the braces of
753 // the compound statement in the zeroed area, so we need to handle this
754 // specially.
755 size_t Index =
756 pushRegion(Counter::getZero(), getStart(CS->body_front()),
757 getEnd(CS->body_back()));
Richard Trieub5841332015-04-15 01:21:42 +0000758 for (const auto *Child : CS->children())
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000759 Visit(Child);
760 popRegions(Index);
Alex Lorenzee024992014-08-04 18:41:51 +0000761 }
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000762 } else
763 propagateCounts(Counter::getZero(), Body);
Alex Lorenzee024992014-08-04 18:41:51 +0000764 BreakContinue BC = BreakContinueStack.pop_back_val();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000765
Alex Lorenzee024992014-08-04 18:41:51 +0000766 if (!BreakContinueStack.empty())
767 BreakContinueStack.back().ContinueCount = addCounters(
768 BreakContinueStack.back().ContinueCount, BC.ContinueCount);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000769
770 Counter ExitCount = getRegionCounter(S);
771 pushRegion(ExitCount);
Alex Lorenzee024992014-08-04 18:41:51 +0000772 }
773
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000774 void VisitSwitchCase(const SwitchCase *S) {
775 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000776
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000777 SourceMappingRegion &Parent = getRegion();
778
779 Counter Count = addCounters(Parent.getCounter(), getRegionCounter(S));
780 // Reuse the existing region if it starts at our label. This is typical of
781 // the first case in a switch.
782 if (Parent.hasStartLoc() && Parent.getStartLoc() == getStart(S))
783 Parent.setCounter(Count);
784 else
785 pushRegion(Count, getStart(S));
786
787 if (const CaseStmt *CS = dyn_cast<CaseStmt>(S)) {
788 Visit(CS->getLHS());
789 if (const Expr *RHS = CS->getRHS())
790 Visit(RHS);
791 }
Alex Lorenzee024992014-08-04 18:41:51 +0000792 Visit(S->getSubStmt());
793 }
794
795 void VisitIfStmt(const IfStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000796 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000797
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000798 Counter ParentCount = getRegion().getCounter();
799 Counter ThenCount = getRegionCounter(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000800
Justin Bogner91f2e3c2015-02-19 03:10:30 +0000801 // Emitting a counter for the condition makes it easier to interpret the
802 // counter for the body when looking at the coverage.
803 propagateCounts(ParentCount, S->getCond());
804
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000805 extendRegion(S->getThen());
806 Counter OutCount = propagateCounts(ThenCount, S->getThen());
807
808 Counter ElseCount = subtractCounters(ParentCount, ThenCount);
809 if (const Stmt *Else = S->getElse()) {
810 extendRegion(S->getElse());
811 OutCount = addCounters(OutCount, propagateCounts(ElseCount, Else));
812 } else
813 OutCount = addCounters(OutCount, ElseCount);
814
815 if (OutCount != ParentCount)
816 pushRegion(OutCount);
Alex Lorenzee024992014-08-04 18:41:51 +0000817 }
818
819 void VisitCXXTryStmt(const CXXTryStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000820 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000821 Visit(S->getTryBlock());
822 for (unsigned I = 0, E = S->getNumHandlers(); I < E; ++I)
823 Visit(S->getHandler(I));
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000824
825 Counter ExitCount = getRegionCounter(S);
826 pushRegion(ExitCount);
Alex Lorenzee024992014-08-04 18:41:51 +0000827 }
828
829 void VisitCXXCatchStmt(const CXXCatchStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000830 extendRegion(S);
831 propagateCounts(getRegionCounter(S), S->getHandlerBlock());
Alex Lorenzee024992014-08-04 18:41:51 +0000832 }
833
834 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000835 extendRegion(E);
Alex Lorenzee024992014-08-04 18:41:51 +0000836
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000837 Counter ParentCount = getRegion().getCounter();
838 Counter TrueCount = getRegionCounter(E);
Alex Lorenzee024992014-08-04 18:41:51 +0000839
Justin Bognere3654ce2015-04-24 23:37:57 +0000840 Visit(E->getCond());
841
842 if (!isa<BinaryConditionalOperator>(E)) {
843 extendRegion(E->getTrueExpr());
844 propagateCounts(TrueCount, E->getTrueExpr());
845 }
846 extendRegion(E->getFalseExpr());
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000847 propagateCounts(subtractCounters(ParentCount, TrueCount),
848 E->getFalseExpr());
Alex Lorenzee024992014-08-04 18:41:51 +0000849 }
850
851 void VisitBinLAnd(const BinaryOperator *E) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000852 extendRegion(E);
Alex Lorenzee024992014-08-04 18:41:51 +0000853 Visit(E->getLHS());
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000854
855 extendRegion(E->getRHS());
856 propagateCounts(getRegionCounter(E), E->getRHS());
Alex Lorenzee024992014-08-04 18:41:51 +0000857 }
858
859 void VisitBinLOr(const BinaryOperator *E) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000860 extendRegion(E);
Alex Lorenzee024992014-08-04 18:41:51 +0000861 Visit(E->getLHS());
Alex Lorenzee024992014-08-04 18:41:51 +0000862
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000863 extendRegion(E->getRHS());
864 propagateCounts(getRegionCounter(E), E->getRHS());
Alex Lorenz01a0d062014-08-20 17:10:56 +0000865 }
Justin Bognerc1091022015-02-24 04:13:56 +0000866
867 void VisitLambdaExpr(const LambdaExpr *LE) {
868 // Lambdas are treated as their own functions for now, so we shouldn't
869 // propagate counts into them.
870 }
Alex Lorenzee024992014-08-04 18:41:51 +0000871};
872}
873
874static bool isMachO(const CodeGenModule &CGM) {
875 return CGM.getTarget().getTriple().isOSBinFormatMachO();
876}
877
878static StringRef getCoverageSection(const CodeGenModule &CGM) {
879 return isMachO(CGM) ? "__DATA,__llvm_covmap" : "__llvm_covmap";
880}
881
Justin Bognera432d172015-02-03 00:20:24 +0000882static void dump(llvm::raw_ostream &OS, StringRef FunctionName,
883 ArrayRef<CounterExpression> Expressions,
884 ArrayRef<CounterMappingRegion> Regions) {
885 OS << FunctionName << ":\n";
886 CounterMappingContext Ctx(Expressions);
887 for (const auto &R : Regions) {
Alex Lorenzf2cf38e2014-08-08 23:41:24 +0000888 OS.indent(2);
889 switch (R.Kind) {
890 case CounterMappingRegion::CodeRegion:
891 break;
892 case CounterMappingRegion::ExpansionRegion:
893 OS << "Expansion,";
894 break;
895 case CounterMappingRegion::SkippedRegion:
896 OS << "Skipped,";
897 break;
898 }
899
Justin Bogner4da909b2015-02-03 21:35:49 +0000900 OS << "File " << R.FileID << ", " << R.LineStart << ":" << R.ColumnStart
901 << " -> " << R.LineEnd << ":" << R.ColumnEnd << " = ";
Justin Bognerf69dc342015-01-23 23:46:13 +0000902 Ctx.dump(R.Count, OS);
Alex Lorenzf2cf38e2014-08-08 23:41:24 +0000903 if (R.Kind == CounterMappingRegion::ExpansionRegion)
Justin Bogner4da909b2015-02-03 21:35:49 +0000904 OS << " (Expanded file = " << R.ExpandedFileID << ")";
905 OS << "\n";
Alex Lorenzf2cf38e2014-08-08 23:41:24 +0000906 }
907}
908
Alex Lorenzee024992014-08-04 18:41:51 +0000909void CoverageMappingModuleGen::addFunctionMappingRecord(
Alex Lorenzf2cf38e2014-08-08 23:41:24 +0000910 llvm::GlobalVariable *FunctionName, StringRef FunctionNameValue,
Alex Lorenz1d45c5b2014-08-21 19:25:27 +0000911 uint64_t FunctionHash, const std::string &CoverageMapping) {
Alex Lorenzee024992014-08-04 18:41:51 +0000912 llvm::LLVMContext &Ctx = CGM.getLLVMContext();
913 auto *Int32Ty = llvm::Type::getInt32Ty(Ctx);
Alex Lorenz1d45c5b2014-08-21 19:25:27 +0000914 auto *Int64Ty = llvm::Type::getInt64Ty(Ctx);
Alex Lorenzee024992014-08-04 18:41:51 +0000915 auto *Int8PtrTy = llvm::Type::getInt8PtrTy(Ctx);
916 if (!FunctionRecordTy) {
Alex Lorenz1d45c5b2014-08-21 19:25:27 +0000917 llvm::Type *FunctionRecordTypes[] = {Int8PtrTy, Int32Ty, Int32Ty, Int64Ty};
Alex Lorenzee024992014-08-04 18:41:51 +0000918 FunctionRecordTy =
919 llvm::StructType::get(Ctx, makeArrayRef(FunctionRecordTypes));
920 }
921
922 llvm::Constant *FunctionRecordVals[] = {
923 llvm::ConstantExpr::getBitCast(FunctionName, Int8PtrTy),
Alex Lorenzf2cf38e2014-08-08 23:41:24 +0000924 llvm::ConstantInt::get(Int32Ty, FunctionNameValue.size()),
Alex Lorenz1d45c5b2014-08-21 19:25:27 +0000925 llvm::ConstantInt::get(Int32Ty, CoverageMapping.size()),
926 llvm::ConstantInt::get(Int64Ty, FunctionHash)};
Alex Lorenzee024992014-08-04 18:41:51 +0000927 FunctionRecords.push_back(llvm::ConstantStruct::get(
928 FunctionRecordTy, makeArrayRef(FunctionRecordVals)));
929 CoverageMappings += CoverageMapping;
Alex Lorenzf2cf38e2014-08-08 23:41:24 +0000930
931 if (CGM.getCodeGenOpts().DumpCoverageMapping) {
932 // Dump the coverage mapping data for this function by decoding the
933 // encoded data. This allows us to dump the mapping regions which were
934 // also processed by the CoverageMappingWriter which performs
935 // additional minimization operations such as reducing the number of
936 // expressions.
937 std::vector<StringRef> Filenames;
938 std::vector<CounterExpression> Expressions;
939 std::vector<CounterMappingRegion> Regions;
940 llvm::SmallVector<StringRef, 16> FilenameRefs;
941 FilenameRefs.resize(FileEntries.size());
942 for (const auto &Entry : FileEntries)
943 FilenameRefs[Entry.second] = Entry.first->getName();
Justin Bognera432d172015-02-03 00:20:24 +0000944 RawCoverageMappingReader Reader(CoverageMapping, FilenameRefs, Filenames,
945 Expressions, Regions);
946 if (Reader.read())
Alex Lorenzf2cf38e2014-08-08 23:41:24 +0000947 return;
Justin Bognera432d172015-02-03 00:20:24 +0000948 dump(llvm::outs(), FunctionNameValue, Expressions, Regions);
Alex Lorenzf2cf38e2014-08-08 23:41:24 +0000949 }
Alex Lorenzee024992014-08-04 18:41:51 +0000950}
951
952void CoverageMappingModuleGen::emit() {
953 if (FunctionRecords.empty())
954 return;
955 llvm::LLVMContext &Ctx = CGM.getLLVMContext();
956 auto *Int32Ty = llvm::Type::getInt32Ty(Ctx);
957
958 // Create the filenames and merge them with coverage mappings
959 llvm::SmallVector<std::string, 16> FilenameStrs;
960 llvm::SmallVector<StringRef, 16> FilenameRefs;
961 FilenameStrs.resize(FileEntries.size());
962 FilenameRefs.resize(FileEntries.size());
963 for (const auto &Entry : FileEntries) {
964 llvm::SmallString<256> Path(Entry.first->getName());
965 llvm::sys::fs::make_absolute(Path);
966
967 auto I = Entry.second;
968 FilenameStrs[I] = std::move(std::string(Path.begin(), Path.end()));
969 FilenameRefs[I] = FilenameStrs[I];
970 }
971
972 std::string FilenamesAndCoverageMappings;
973 llvm::raw_string_ostream OS(FilenamesAndCoverageMappings);
974 CoverageFilenamesSectionWriter(FilenameRefs).write(OS);
975 OS << CoverageMappings;
976 size_t CoverageMappingSize = CoverageMappings.size();
977 size_t FilenamesSize = OS.str().size() - CoverageMappingSize;
978 // Append extra zeroes if necessary to ensure that the size of the filenames
979 // and coverage mappings is a multiple of 8.
980 if (size_t Rem = OS.str().size() % 8) {
981 CoverageMappingSize += 8 - Rem;
982 for (size_t I = 0, S = 8 - Rem; I < S; ++I)
983 OS << '\0';
984 }
985 auto *FilenamesAndMappingsVal =
986 llvm::ConstantDataArray::getString(Ctx, OS.str(), false);
987
988 // Create the deferred function records array
989 auto RecordsTy =
990 llvm::ArrayType::get(FunctionRecordTy, FunctionRecords.size());
991 auto RecordsVal = llvm::ConstantArray::get(RecordsTy, FunctionRecords);
992
993 // Create the coverage data record
994 llvm::Type *CovDataTypes[] = {Int32Ty, Int32Ty,
995 Int32Ty, Int32Ty,
996 RecordsTy, FilenamesAndMappingsVal->getType()};
997 auto CovDataTy = llvm::StructType::get(Ctx, makeArrayRef(CovDataTypes));
998 llvm::Constant *TUDataVals[] = {
999 llvm::ConstantInt::get(Int32Ty, FunctionRecords.size()),
1000 llvm::ConstantInt::get(Int32Ty, FilenamesSize),
1001 llvm::ConstantInt::get(Int32Ty, CoverageMappingSize),
1002 llvm::ConstantInt::get(Int32Ty,
1003 /*Version=*/CoverageMappingVersion1),
1004 RecordsVal, FilenamesAndMappingsVal};
1005 auto CovDataVal =
1006 llvm::ConstantStruct::get(CovDataTy, makeArrayRef(TUDataVals));
1007 auto CovData = new llvm::GlobalVariable(CGM.getModule(), CovDataTy, true,
1008 llvm::GlobalValue::InternalLinkage,
1009 CovDataVal,
1010 "__llvm_coverage_mapping");
1011
1012 CovData->setSection(getCoverageSection(CGM));
1013 CovData->setAlignment(8);
1014
1015 // Make sure the data doesn't get deleted.
1016 CGM.addUsedGlobal(CovData);
1017}
1018
1019unsigned CoverageMappingModuleGen::getFileID(const FileEntry *File) {
1020 auto It = FileEntries.find(File);
1021 if (It != FileEntries.end())
1022 return It->second;
1023 unsigned FileID = FileEntries.size();
1024 FileEntries.insert(std::make_pair(File, FileID));
1025 return FileID;
1026}
1027
1028void CoverageMappingGen::emitCounterMapping(const Decl *D,
1029 llvm::raw_ostream &OS) {
1030 assert(CounterMap);
Justin Bognere5ee6c52014-10-02 16:44:01 +00001031 CounterCoverageMappingBuilder Walker(CVM, *CounterMap, SM, LangOpts);
Alex Lorenzee024992014-08-04 18:41:51 +00001032 Walker.VisitDecl(D);
1033 Walker.write(OS);
1034}
1035
1036void CoverageMappingGen::emitEmptyMapping(const Decl *D,
1037 llvm::raw_ostream &OS) {
1038 EmptyCoverageMappingBuilder Walker(CVM, SM, LangOpts);
1039 Walker.VisitDecl(D);
1040 Walker.write(OS);
1041}