blob: fca17264e8fc4a9138f12ea46c1c152dd5763e54 [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;
Justin Bogner96ae73f2015-05-01 19:23:34 +0000450 // Avoid adding duplicate regions if we have a completed region on the top
451 // of the stack and are adjusting to the end of a virtual file.
452 if (getRegion().hasEndLoc() &&
453 MostRecentLocation == getEndOfFileOrMacro(MostRecentLocation))
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000454 MostRecentLocation = getIncludeOrExpansionLoc(MostRecentLocation);
455 }
Alex Lorenzee024992014-08-04 18:41:51 +0000456
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000457 /// \brief Check whether \c Loc is included or expanded from \c Parent.
458 bool isNestedIn(SourceLocation Loc, FileID Parent) {
459 do {
460 Loc = getIncludeOrExpansionLoc(Loc);
461 if (Loc.isInvalid())
462 return false;
463 } while (!SM.isInFileID(Loc, Parent));
464 return true;
465 }
466
467 /// \brief Adjust regions and state when \c NewLoc exits a file.
468 ///
469 /// If moving from our most recently tracked location to \c NewLoc exits any
470 /// files, this adjusts our current region stack and creates the file regions
471 /// for the exited file.
472 void handleFileExit(SourceLocation NewLoc) {
473 if (SM.isWrittenInSameFile(MostRecentLocation, NewLoc))
474 return;
475
476 // If NewLoc is not in a file that contains MostRecentLocation, walk up to
477 // find the common ancestor.
478 SourceLocation LCA = NewLoc;
479 FileID ParentFile = SM.getFileID(LCA);
480 while (!isNestedIn(MostRecentLocation, ParentFile)) {
481 LCA = getIncludeOrExpansionLoc(LCA);
482 if (LCA.isInvalid() || SM.isWrittenInSameFile(LCA, MostRecentLocation)) {
483 // Since there isn't a common ancestor, no file was exited. We just need
484 // to adjust our location to the new file.
485 MostRecentLocation = NewLoc;
486 return;
487 }
488 ParentFile = SM.getFileID(LCA);
Alex Lorenzee024992014-08-04 18:41:51 +0000489 }
490
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000491 llvm::SmallSet<SourceLocation, 8> StartLocs;
492 Optional<Counter> ParentCounter;
493 for (auto I = RegionStack.rbegin(), E = RegionStack.rend(); I != E; ++I) {
494 if (!I->hasStartLoc())
495 continue;
496 SourceLocation Loc = I->getStartLoc();
497 if (!isNestedIn(Loc, ParentFile)) {
498 ParentCounter = I->getCounter();
499 break;
500 }
Alex Lorenzee024992014-08-04 18:41:51 +0000501
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000502 while (!SM.isInFileID(Loc, ParentFile)) {
503 // The most nested region for each start location is the one with the
504 // correct count. We avoid creating redundant regions by stopping once
505 // we've seen this region.
506 if (StartLocs.insert(Loc).second)
507 SourceRegions.emplace_back(I->getCounter(), Loc,
508 getEndOfFileOrMacro(Loc));
509 Loc = getIncludeOrExpansionLoc(Loc);
510 }
511 I->setStartLoc(getPreciseTokenLocEnd(Loc));
Alex Lorenzee024992014-08-04 18:41:51 +0000512 }
513
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000514 if (ParentCounter) {
515 // If the file is contained completely by another region and doesn't
516 // immediately start its own region, the whole file gets a region
517 // corresponding to the parent.
518 SourceLocation Loc = MostRecentLocation;
519 while (isNestedIn(Loc, ParentFile)) {
520 SourceLocation FileStart = getStartOfFileOrMacro(Loc);
521 if (StartLocs.insert(FileStart).second)
522 SourceRegions.emplace_back(*ParentCounter, FileStart,
523 getEndOfFileOrMacro(Loc));
524 Loc = getIncludeOrExpansionLoc(Loc);
525 }
Alex Lorenzee024992014-08-04 18:41:51 +0000526 }
527
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000528 MostRecentLocation = NewLoc;
529 }
Alex Lorenzee024992014-08-04 18:41:51 +0000530
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000531 /// \brief Ensure that \c S is included in the current region.
532 void extendRegion(const Stmt *S) {
533 SourceMappingRegion &Region = getRegion();
534 SourceLocation StartLoc = getStart(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000535
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000536 handleFileExit(StartLoc);
537 if (!Region.hasStartLoc())
538 Region.setStartLoc(StartLoc);
539 }
540
541 /// \brief Mark \c S as a terminator, starting a zero region.
542 void terminateRegion(const Stmt *S) {
543 extendRegion(S);
544 SourceMappingRegion &Region = getRegion();
545 if (!Region.hasEndLoc())
546 Region.setEndLoc(getEnd(S));
547 pushRegion(Counter::getZero());
548 }
Alex Lorenzee024992014-08-04 18:41:51 +0000549
550 /// \brief Keep counts of breaks and continues inside loops.
551 struct BreakContinue {
552 Counter BreakCount;
553 Counter ContinueCount;
554 };
555 SmallVector<BreakContinue, 8> BreakContinueStack;
556
557 CounterCoverageMappingBuilder(
558 CoverageMappingModuleGen &CVM,
Justin Bognere5ee6c52014-10-02 16:44:01 +0000559 llvm::DenseMap<const Stmt *, unsigned> &CounterMap, SourceManager &SM,
Alex Lorenzee024992014-08-04 18:41:51 +0000560 const LangOptions &LangOpts)
Justin Bognere5ee6c52014-10-02 16:44:01 +0000561 : CoverageMappingBuilder(CVM, SM, LangOpts), CounterMap(CounterMap) {}
Alex Lorenzee024992014-08-04 18:41:51 +0000562
563 /// \brief Write the mapping data to the output stream
564 void write(llvm::raw_ostream &OS) {
Alex Lorenzee024992014-08-04 18:41:51 +0000565 llvm::SmallVector<unsigned, 8> VirtualFileMapping;
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000566 gatherFileIDs(VirtualFileMapping);
567 emitSourceRegions();
568 emitExpansionRegions();
Alex Lorenzee024992014-08-04 18:41:51 +0000569 gatherSkippedRegions();
570
Justin Bogner4da909b2015-02-03 21:35:49 +0000571 CoverageMappingWriter Writer(VirtualFileMapping, Builder.getExpressions(),
572 MappingRegions);
Alex Lorenzee024992014-08-04 18:41:51 +0000573 Writer.write(OS);
574 }
575
Alex Lorenzee024992014-08-04 18:41:51 +0000576 void VisitStmt(const Stmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000577 if (!S->getLocStart().isInvalid())
578 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000579 for (Stmt::const_child_range I = S->children(); I; ++I) {
580 if (*I)
581 this->Visit(*I);
582 }
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000583 handleFileExit(getEnd(S));
Alex Lorenzee024992014-08-04 18:41:51 +0000584 }
585
Alex Lorenzee024992014-08-04 18:41:51 +0000586 void VisitDecl(const Decl *D) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000587 Stmt *Body = D->getBody();
588 propagateCounts(getRegionCounter(Body), Body);
Alex Lorenzee024992014-08-04 18:41:51 +0000589 }
590
591 void VisitReturnStmt(const ReturnStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000592 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000593 if (S->getRetValue())
594 Visit(S->getRetValue());
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000595 terminateRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000596 }
597
Justin Bognerf959feb2015-04-28 06:31:55 +0000598 void VisitCXXThrowExpr(const CXXThrowExpr *E) {
599 extendRegion(E);
600 if (E->getSubExpr())
601 Visit(E->getSubExpr());
602 terminateRegion(E);
603 }
604
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000605 void VisitGotoStmt(const GotoStmt *S) { terminateRegion(S); }
Alex Lorenzee024992014-08-04 18:41:51 +0000606
607 void VisitLabelStmt(const LabelStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000608 SourceLocation Start = getStart(S);
609 // We can't extendRegion here or we risk overlapping with our new region.
610 handleFileExit(Start);
611 pushRegion(getRegionCounter(S), Start);
Alex Lorenzee024992014-08-04 18:41:51 +0000612 Visit(S->getSubStmt());
613 }
614
615 void VisitBreakStmt(const BreakStmt *S) {
Alex Lorenzee024992014-08-04 18:41:51 +0000616 assert(!BreakContinueStack.empty() && "break not in a loop or switch!");
617 BreakContinueStack.back().BreakCount = addCounters(
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000618 BreakContinueStack.back().BreakCount, getRegion().getCounter());
619 terminateRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000620 }
621
622 void VisitContinueStmt(const ContinueStmt *S) {
Alex Lorenzee024992014-08-04 18:41:51 +0000623 assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
624 BreakContinueStack.back().ContinueCount = addCounters(
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000625 BreakContinueStack.back().ContinueCount, getRegion().getCounter());
626 terminateRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000627 }
628
629 void VisitWhileStmt(const WhileStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000630 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000631
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000632 Counter ParentCount = getRegion().getCounter();
633 Counter BodyCount = getRegionCounter(S);
634
635 // Handle the body first so that we can get the backedge count.
636 BreakContinueStack.push_back(BreakContinue());
637 extendRegion(S->getBody());
638 Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
Alex Lorenzee024992014-08-04 18:41:51 +0000639 BreakContinue BC = BreakContinueStack.pop_back_val();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000640
641 // Go back to handle the condition.
642 Counter CondCount =
643 addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
644 propagateCounts(CondCount, S->getCond());
645 adjustForOutOfOrderTraversal(getEnd(S));
646
647 Counter OutCount =
648 addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount));
649 if (OutCount != ParentCount)
650 pushRegion(OutCount);
Alex Lorenzee024992014-08-04 18:41:51 +0000651 }
652
653 void VisitDoStmt(const DoStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000654 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000655
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000656 Counter ParentCount = getRegion().getCounter();
657 Counter BodyCount = getRegionCounter(S);
658
659 BreakContinueStack.push_back(BreakContinue());
660 extendRegion(S->getBody());
661 Counter BackedgeCount =
662 propagateCounts(addCounters(ParentCount, BodyCount), S->getBody());
Alex Lorenzee024992014-08-04 18:41:51 +0000663 BreakContinue BC = BreakContinueStack.pop_back_val();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000664
665 Counter CondCount = addCounters(BackedgeCount, BC.ContinueCount);
666 propagateCounts(CondCount, S->getCond());
667
668 Counter OutCount =
669 addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount));
670 if (OutCount != ParentCount)
671 pushRegion(OutCount);
Alex Lorenzee024992014-08-04 18:41:51 +0000672 }
673
674 void VisitForStmt(const ForStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000675 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000676 if (S->getInit())
677 Visit(S->getInit());
678
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000679 Counter ParentCount = getRegion().getCounter();
680 Counter BodyCount = getRegionCounter(S);
681
682 // Handle the body first so that we can get the backedge count.
Alex Lorenzee024992014-08-04 18:41:51 +0000683 BreakContinueStack.push_back(BreakContinue());
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000684 extendRegion(S->getBody());
685 Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
686 BreakContinue BC = BreakContinueStack.pop_back_val();
Alex Lorenzee024992014-08-04 18:41:51 +0000687
688 // The increment is essentially part of the body but it needs to include
689 // the count for all the continue statements.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000690 if (const Stmt *Inc = S->getInc())
691 propagateCounts(addCounters(BackedgeCount, BC.ContinueCount), Inc);
692
693 // Go back to handle the condition.
694 Counter CondCount =
695 addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
696 if (const Expr *Cond = S->getCond()) {
697 propagateCounts(CondCount, Cond);
698 adjustForOutOfOrderTraversal(getEnd(S));
Alex Lorenzee024992014-08-04 18:41:51 +0000699 }
700
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000701 Counter OutCount =
702 addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount));
703 if (OutCount != ParentCount)
704 pushRegion(OutCount);
Alex Lorenzee024992014-08-04 18:41:51 +0000705 }
706
707 void VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000708 extendRegion(S);
709 Visit(S->getLoopVarStmt());
Alex Lorenzee024992014-08-04 18:41:51 +0000710 Visit(S->getRangeStmt());
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000711
712 Counter ParentCount = getRegion().getCounter();
713 Counter BodyCount = getRegionCounter(S);
714
Alex Lorenzee024992014-08-04 18:41:51 +0000715 BreakContinueStack.push_back(BreakContinue());
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000716 extendRegion(S->getBody());
717 Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
Alex Lorenzee024992014-08-04 18:41:51 +0000718 BreakContinue BC = BreakContinueStack.pop_back_val();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000719
Justin Bogner15874322015-04-30 21:31:02 +0000720 Counter LoopCount =
721 addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
722 Counter OutCount =
723 addCounters(BC.BreakCount, subtractCounters(LoopCount, BodyCount));
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000724 if (OutCount != ParentCount)
725 pushRegion(OutCount);
Alex Lorenzee024992014-08-04 18:41:51 +0000726 }
727
728 void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000729 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000730 Visit(S->getElement());
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000731
732 Counter ParentCount = getRegion().getCounter();
733 Counter BodyCount = getRegionCounter(S);
734
Alex Lorenzee024992014-08-04 18:41:51 +0000735 BreakContinueStack.push_back(BreakContinue());
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000736 extendRegion(S->getBody());
737 Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
Alex Lorenzee024992014-08-04 18:41:51 +0000738 BreakContinue BC = BreakContinueStack.pop_back_val();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000739
Justin Bogner15874322015-04-30 21:31:02 +0000740 Counter LoopCount =
741 addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
742 Counter OutCount =
743 addCounters(BC.BreakCount, subtractCounters(LoopCount, BodyCount));
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000744 if (OutCount != ParentCount)
745 pushRegion(OutCount);
Alex Lorenzee024992014-08-04 18:41:51 +0000746 }
747
748 void VisitSwitchStmt(const SwitchStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000749 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000750 Visit(S->getCond());
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000751
Alex Lorenzee024992014-08-04 18:41:51 +0000752 BreakContinueStack.push_back(BreakContinue());
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000753
754 const Stmt *Body = S->getBody();
755 extendRegion(Body);
756 if (const auto *CS = dyn_cast<CompoundStmt>(Body)) {
757 if (!CS->body_empty()) {
758 // The body of the switch needs a zero region so that fallthrough counts
759 // behave correctly, but it would be misleading to include the braces of
760 // the compound statement in the zeroed area, so we need to handle this
761 // specially.
762 size_t Index =
763 pushRegion(Counter::getZero(), getStart(CS->body_front()),
764 getEnd(CS->body_back()));
Richard Trieub5841332015-04-15 01:21:42 +0000765 for (const auto *Child : CS->children())
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000766 Visit(Child);
767 popRegions(Index);
Alex Lorenzee024992014-08-04 18:41:51 +0000768 }
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000769 } else
770 propagateCounts(Counter::getZero(), Body);
Alex Lorenzee024992014-08-04 18:41:51 +0000771 BreakContinue BC = BreakContinueStack.pop_back_val();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000772
Alex Lorenzee024992014-08-04 18:41:51 +0000773 if (!BreakContinueStack.empty())
774 BreakContinueStack.back().ContinueCount = addCounters(
775 BreakContinueStack.back().ContinueCount, BC.ContinueCount);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000776
777 Counter ExitCount = getRegionCounter(S);
778 pushRegion(ExitCount);
Alex Lorenzee024992014-08-04 18:41:51 +0000779 }
780
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000781 void VisitSwitchCase(const SwitchCase *S) {
782 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000783
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000784 SourceMappingRegion &Parent = getRegion();
785
786 Counter Count = addCounters(Parent.getCounter(), getRegionCounter(S));
787 // Reuse the existing region if it starts at our label. This is typical of
788 // the first case in a switch.
789 if (Parent.hasStartLoc() && Parent.getStartLoc() == getStart(S))
790 Parent.setCounter(Count);
791 else
792 pushRegion(Count, getStart(S));
793
794 if (const CaseStmt *CS = dyn_cast<CaseStmt>(S)) {
795 Visit(CS->getLHS());
796 if (const Expr *RHS = CS->getRHS())
797 Visit(RHS);
798 }
Alex Lorenzee024992014-08-04 18:41:51 +0000799 Visit(S->getSubStmt());
800 }
801
802 void VisitIfStmt(const IfStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000803 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000804
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000805 Counter ParentCount = getRegion().getCounter();
806 Counter ThenCount = getRegionCounter(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000807
Justin Bogner91f2e3c2015-02-19 03:10:30 +0000808 // Emitting a counter for the condition makes it easier to interpret the
809 // counter for the body when looking at the coverage.
810 propagateCounts(ParentCount, S->getCond());
811
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000812 extendRegion(S->getThen());
813 Counter OutCount = propagateCounts(ThenCount, S->getThen());
814
815 Counter ElseCount = subtractCounters(ParentCount, ThenCount);
816 if (const Stmt *Else = S->getElse()) {
817 extendRegion(S->getElse());
818 OutCount = addCounters(OutCount, propagateCounts(ElseCount, Else));
819 } else
820 OutCount = addCounters(OutCount, ElseCount);
821
822 if (OutCount != ParentCount)
823 pushRegion(OutCount);
Alex Lorenzee024992014-08-04 18:41:51 +0000824 }
825
826 void VisitCXXTryStmt(const CXXTryStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000827 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000828 Visit(S->getTryBlock());
829 for (unsigned I = 0, E = S->getNumHandlers(); I < E; ++I)
830 Visit(S->getHandler(I));
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000831
832 Counter ExitCount = getRegionCounter(S);
833 pushRegion(ExitCount);
Alex Lorenzee024992014-08-04 18:41:51 +0000834 }
835
836 void VisitCXXCatchStmt(const CXXCatchStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000837 extendRegion(S);
838 propagateCounts(getRegionCounter(S), S->getHandlerBlock());
Alex Lorenzee024992014-08-04 18:41:51 +0000839 }
840
841 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000842 extendRegion(E);
Alex Lorenzee024992014-08-04 18:41:51 +0000843
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000844 Counter ParentCount = getRegion().getCounter();
845 Counter TrueCount = getRegionCounter(E);
Alex Lorenzee024992014-08-04 18:41:51 +0000846
Justin Bognere3654ce2015-04-24 23:37:57 +0000847 Visit(E->getCond());
848
849 if (!isa<BinaryConditionalOperator>(E)) {
850 extendRegion(E->getTrueExpr());
851 propagateCounts(TrueCount, E->getTrueExpr());
852 }
853 extendRegion(E->getFalseExpr());
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000854 propagateCounts(subtractCounters(ParentCount, TrueCount),
855 E->getFalseExpr());
Alex Lorenzee024992014-08-04 18:41:51 +0000856 }
857
858 void VisitBinLAnd(const BinaryOperator *E) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000859 extendRegion(E);
Alex Lorenzee024992014-08-04 18:41:51 +0000860 Visit(E->getLHS());
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000861
862 extendRegion(E->getRHS());
863 propagateCounts(getRegionCounter(E), E->getRHS());
Alex Lorenzee024992014-08-04 18:41:51 +0000864 }
865
866 void VisitBinLOr(const BinaryOperator *E) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000867 extendRegion(E);
Alex Lorenzee024992014-08-04 18:41:51 +0000868 Visit(E->getLHS());
Alex Lorenzee024992014-08-04 18:41:51 +0000869
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000870 extendRegion(E->getRHS());
871 propagateCounts(getRegionCounter(E), E->getRHS());
Alex Lorenz01a0d062014-08-20 17:10:56 +0000872 }
Justin Bognerc1091022015-02-24 04:13:56 +0000873
874 void VisitLambdaExpr(const LambdaExpr *LE) {
875 // Lambdas are treated as their own functions for now, so we shouldn't
876 // propagate counts into them.
877 }
Alex Lorenzee024992014-08-04 18:41:51 +0000878};
879}
880
881static bool isMachO(const CodeGenModule &CGM) {
882 return CGM.getTarget().getTriple().isOSBinFormatMachO();
883}
884
885static StringRef getCoverageSection(const CodeGenModule &CGM) {
886 return isMachO(CGM) ? "__DATA,__llvm_covmap" : "__llvm_covmap";
887}
888
Justin Bognera432d172015-02-03 00:20:24 +0000889static void dump(llvm::raw_ostream &OS, StringRef FunctionName,
890 ArrayRef<CounterExpression> Expressions,
891 ArrayRef<CounterMappingRegion> Regions) {
892 OS << FunctionName << ":\n";
893 CounterMappingContext Ctx(Expressions);
894 for (const auto &R : Regions) {
Alex Lorenzf2cf38e2014-08-08 23:41:24 +0000895 OS.indent(2);
896 switch (R.Kind) {
897 case CounterMappingRegion::CodeRegion:
898 break;
899 case CounterMappingRegion::ExpansionRegion:
900 OS << "Expansion,";
901 break;
902 case CounterMappingRegion::SkippedRegion:
903 OS << "Skipped,";
904 break;
905 }
906
Justin Bogner4da909b2015-02-03 21:35:49 +0000907 OS << "File " << R.FileID << ", " << R.LineStart << ":" << R.ColumnStart
908 << " -> " << R.LineEnd << ":" << R.ColumnEnd << " = ";
Justin Bognerf69dc342015-01-23 23:46:13 +0000909 Ctx.dump(R.Count, OS);
Alex Lorenzf2cf38e2014-08-08 23:41:24 +0000910 if (R.Kind == CounterMappingRegion::ExpansionRegion)
Justin Bogner4da909b2015-02-03 21:35:49 +0000911 OS << " (Expanded file = " << R.ExpandedFileID << ")";
912 OS << "\n";
Alex Lorenzf2cf38e2014-08-08 23:41:24 +0000913 }
914}
915
Alex Lorenzee024992014-08-04 18:41:51 +0000916void CoverageMappingModuleGen::addFunctionMappingRecord(
Alex Lorenzf2cf38e2014-08-08 23:41:24 +0000917 llvm::GlobalVariable *FunctionName, StringRef FunctionNameValue,
Alex Lorenz1d45c5b2014-08-21 19:25:27 +0000918 uint64_t FunctionHash, const std::string &CoverageMapping) {
Alex Lorenzee024992014-08-04 18:41:51 +0000919 llvm::LLVMContext &Ctx = CGM.getLLVMContext();
920 auto *Int32Ty = llvm::Type::getInt32Ty(Ctx);
Alex Lorenz1d45c5b2014-08-21 19:25:27 +0000921 auto *Int64Ty = llvm::Type::getInt64Ty(Ctx);
Alex Lorenzee024992014-08-04 18:41:51 +0000922 auto *Int8PtrTy = llvm::Type::getInt8PtrTy(Ctx);
923 if (!FunctionRecordTy) {
Alex Lorenz1d45c5b2014-08-21 19:25:27 +0000924 llvm::Type *FunctionRecordTypes[] = {Int8PtrTy, Int32Ty, Int32Ty, Int64Ty};
Alex Lorenzee024992014-08-04 18:41:51 +0000925 FunctionRecordTy =
926 llvm::StructType::get(Ctx, makeArrayRef(FunctionRecordTypes));
927 }
928
929 llvm::Constant *FunctionRecordVals[] = {
930 llvm::ConstantExpr::getBitCast(FunctionName, Int8PtrTy),
Alex Lorenzf2cf38e2014-08-08 23:41:24 +0000931 llvm::ConstantInt::get(Int32Ty, FunctionNameValue.size()),
Alex Lorenz1d45c5b2014-08-21 19:25:27 +0000932 llvm::ConstantInt::get(Int32Ty, CoverageMapping.size()),
933 llvm::ConstantInt::get(Int64Ty, FunctionHash)};
Alex Lorenzee024992014-08-04 18:41:51 +0000934 FunctionRecords.push_back(llvm::ConstantStruct::get(
935 FunctionRecordTy, makeArrayRef(FunctionRecordVals)));
936 CoverageMappings += CoverageMapping;
Alex Lorenzf2cf38e2014-08-08 23:41:24 +0000937
938 if (CGM.getCodeGenOpts().DumpCoverageMapping) {
939 // Dump the coverage mapping data for this function by decoding the
940 // encoded data. This allows us to dump the mapping regions which were
941 // also processed by the CoverageMappingWriter which performs
942 // additional minimization operations such as reducing the number of
943 // expressions.
944 std::vector<StringRef> Filenames;
945 std::vector<CounterExpression> Expressions;
946 std::vector<CounterMappingRegion> Regions;
947 llvm::SmallVector<StringRef, 16> FilenameRefs;
948 FilenameRefs.resize(FileEntries.size());
949 for (const auto &Entry : FileEntries)
950 FilenameRefs[Entry.second] = Entry.first->getName();
Justin Bognera432d172015-02-03 00:20:24 +0000951 RawCoverageMappingReader Reader(CoverageMapping, FilenameRefs, Filenames,
952 Expressions, Regions);
953 if (Reader.read())
Alex Lorenzf2cf38e2014-08-08 23:41:24 +0000954 return;
Justin Bognera432d172015-02-03 00:20:24 +0000955 dump(llvm::outs(), FunctionNameValue, Expressions, Regions);
Alex Lorenzf2cf38e2014-08-08 23:41:24 +0000956 }
Alex Lorenzee024992014-08-04 18:41:51 +0000957}
958
959void CoverageMappingModuleGen::emit() {
960 if (FunctionRecords.empty())
961 return;
962 llvm::LLVMContext &Ctx = CGM.getLLVMContext();
963 auto *Int32Ty = llvm::Type::getInt32Ty(Ctx);
964
965 // Create the filenames and merge them with coverage mappings
966 llvm::SmallVector<std::string, 16> FilenameStrs;
967 llvm::SmallVector<StringRef, 16> FilenameRefs;
968 FilenameStrs.resize(FileEntries.size());
969 FilenameRefs.resize(FileEntries.size());
970 for (const auto &Entry : FileEntries) {
971 llvm::SmallString<256> Path(Entry.first->getName());
972 llvm::sys::fs::make_absolute(Path);
973
974 auto I = Entry.second;
Richard Trieud1ffdda2015-04-30 23:13:52 +0000975 FilenameStrs[I] = std::string(Path.begin(), Path.end());
Alex Lorenzee024992014-08-04 18:41:51 +0000976 FilenameRefs[I] = FilenameStrs[I];
977 }
978
979 std::string FilenamesAndCoverageMappings;
980 llvm::raw_string_ostream OS(FilenamesAndCoverageMappings);
981 CoverageFilenamesSectionWriter(FilenameRefs).write(OS);
982 OS << CoverageMappings;
983 size_t CoverageMappingSize = CoverageMappings.size();
984 size_t FilenamesSize = OS.str().size() - CoverageMappingSize;
985 // Append extra zeroes if necessary to ensure that the size of the filenames
986 // and coverage mappings is a multiple of 8.
987 if (size_t Rem = OS.str().size() % 8) {
988 CoverageMappingSize += 8 - Rem;
989 for (size_t I = 0, S = 8 - Rem; I < S; ++I)
990 OS << '\0';
991 }
992 auto *FilenamesAndMappingsVal =
993 llvm::ConstantDataArray::getString(Ctx, OS.str(), false);
994
995 // Create the deferred function records array
996 auto RecordsTy =
997 llvm::ArrayType::get(FunctionRecordTy, FunctionRecords.size());
998 auto RecordsVal = llvm::ConstantArray::get(RecordsTy, FunctionRecords);
999
1000 // Create the coverage data record
1001 llvm::Type *CovDataTypes[] = {Int32Ty, Int32Ty,
1002 Int32Ty, Int32Ty,
1003 RecordsTy, FilenamesAndMappingsVal->getType()};
1004 auto CovDataTy = llvm::StructType::get(Ctx, makeArrayRef(CovDataTypes));
1005 llvm::Constant *TUDataVals[] = {
1006 llvm::ConstantInt::get(Int32Ty, FunctionRecords.size()),
1007 llvm::ConstantInt::get(Int32Ty, FilenamesSize),
1008 llvm::ConstantInt::get(Int32Ty, CoverageMappingSize),
1009 llvm::ConstantInt::get(Int32Ty,
1010 /*Version=*/CoverageMappingVersion1),
1011 RecordsVal, FilenamesAndMappingsVal};
1012 auto CovDataVal =
1013 llvm::ConstantStruct::get(CovDataTy, makeArrayRef(TUDataVals));
1014 auto CovData = new llvm::GlobalVariable(CGM.getModule(), CovDataTy, true,
1015 llvm::GlobalValue::InternalLinkage,
1016 CovDataVal,
1017 "__llvm_coverage_mapping");
1018
1019 CovData->setSection(getCoverageSection(CGM));
1020 CovData->setAlignment(8);
1021
1022 // Make sure the data doesn't get deleted.
1023 CGM.addUsedGlobal(CovData);
1024}
1025
1026unsigned CoverageMappingModuleGen::getFileID(const FileEntry *File) {
1027 auto It = FileEntries.find(File);
1028 if (It != FileEntries.end())
1029 return It->second;
1030 unsigned FileID = FileEntries.size();
1031 FileEntries.insert(std::make_pair(File, FileID));
1032 return FileID;
1033}
1034
1035void CoverageMappingGen::emitCounterMapping(const Decl *D,
1036 llvm::raw_ostream &OS) {
1037 assert(CounterMap);
Justin Bognere5ee6c52014-10-02 16:44:01 +00001038 CounterCoverageMappingBuilder Walker(CVM, *CounterMap, SM, LangOpts);
Alex Lorenzee024992014-08-04 18:41:51 +00001039 Walker.VisitDecl(D);
1040 Walker.write(OS);
1041}
1042
1043void CoverageMappingGen::emitEmptyMapping(const Decl *D,
1044 llvm::raw_ostream &OS) {
1045 EmptyCoverageMappingBuilder Walker(CVM, SM, LangOpts);
1046 Walker.VisitDecl(D);
1047 Walker.write(OS);
1048}