/src/llvm-project/clang/lib/CodeGen/CoverageMappingGen.cpp
Line | Count | Source (jump to first uncovered line) |
1 | | //===--- CoverageMappingGen.cpp - Coverage mapping generation ---*- C++ -*-===// |
2 | | // |
3 | | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
4 | | // See https://llvm.org/LICENSE.txt for license information. |
5 | | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
6 | | // |
7 | | //===----------------------------------------------------------------------===// |
8 | | // |
9 | | // Instrumentation-based code coverage mapping generator |
10 | | // |
11 | | //===----------------------------------------------------------------------===// |
12 | | |
13 | | #include "CoverageMappingGen.h" |
14 | | #include "CodeGenFunction.h" |
15 | | #include "clang/AST/StmtVisitor.h" |
16 | | #include "clang/Basic/Diagnostic.h" |
17 | | #include "clang/Basic/FileManager.h" |
18 | | #include "clang/Frontend/FrontendDiagnostic.h" |
19 | | #include "clang/Lex/Lexer.h" |
20 | | #include "llvm/ADT/SmallSet.h" |
21 | | #include "llvm/ADT/StringExtras.h" |
22 | | #include "llvm/ProfileData/Coverage/CoverageMapping.h" |
23 | | #include "llvm/ProfileData/Coverage/CoverageMappingReader.h" |
24 | | #include "llvm/ProfileData/Coverage/CoverageMappingWriter.h" |
25 | | #include "llvm/ProfileData/InstrProfReader.h" |
26 | | #include "llvm/Support/FileSystem.h" |
27 | | #include "llvm/Support/Path.h" |
28 | | #include <optional> |
29 | | |
30 | | // This selects the coverage mapping format defined when `InstrProfData.inc` |
31 | | // is textually included. |
32 | | #define COVMAP_V3 |
33 | | |
34 | | static llvm::cl::opt<bool> EmptyLineCommentCoverage( |
35 | | "emptyline-comment-coverage", |
36 | | llvm::cl::desc("Emit emptylines and comment lines as skipped regions (only " |
37 | | "disable it on test)"), |
38 | | llvm::cl::init(true), llvm::cl::Hidden); |
39 | | |
40 | | static llvm::cl::opt<bool> SystemHeadersCoverage( |
41 | | "system-headers-coverage", |
42 | | llvm::cl::desc("Enable collecting coverage from system headers"), |
43 | | llvm::cl::init(false), llvm::cl::Hidden); |
44 | | |
45 | | using namespace clang; |
46 | | using namespace CodeGen; |
47 | | using namespace llvm::coverage; |
48 | | |
49 | | CoverageSourceInfo * |
50 | 0 | CoverageMappingModuleGen::setUpCoverageCallbacks(Preprocessor &PP) { |
51 | 0 | CoverageSourceInfo *CoverageInfo = |
52 | 0 | new CoverageSourceInfo(PP.getSourceManager()); |
53 | 0 | PP.addPPCallbacks(std::unique_ptr<PPCallbacks>(CoverageInfo)); |
54 | 0 | if (EmptyLineCommentCoverage) { |
55 | 0 | PP.addCommentHandler(CoverageInfo); |
56 | 0 | PP.setEmptylineHandler(CoverageInfo); |
57 | 0 | PP.setPreprocessToken(true); |
58 | 0 | PP.setTokenWatcher([CoverageInfo](clang::Token Tok) { |
59 | | // Update previous token location. |
60 | 0 | CoverageInfo->PrevTokLoc = Tok.getLocation(); |
61 | 0 | if (Tok.getKind() != clang::tok::eod) |
62 | 0 | CoverageInfo->updateNextTokLoc(Tok.getLocation()); |
63 | 0 | }); |
64 | 0 | } |
65 | 0 | return CoverageInfo; |
66 | 0 | } |
67 | | |
68 | | void CoverageSourceInfo::AddSkippedRange(SourceRange Range, |
69 | 0 | SkippedRange::Kind RangeKind) { |
70 | 0 | if (EmptyLineCommentCoverage && !SkippedRanges.empty() && |
71 | 0 | PrevTokLoc == SkippedRanges.back().PrevTokLoc && |
72 | 0 | SourceMgr.isWrittenInSameFile(SkippedRanges.back().Range.getEnd(), |
73 | 0 | Range.getBegin())) |
74 | 0 | SkippedRanges.back().Range.setEnd(Range.getEnd()); |
75 | 0 | else |
76 | 0 | SkippedRanges.push_back({Range, RangeKind, PrevTokLoc}); |
77 | 0 | } |
78 | | |
79 | 0 | void CoverageSourceInfo::SourceRangeSkipped(SourceRange Range, SourceLocation) { |
80 | 0 | AddSkippedRange(Range, SkippedRange::PPIfElse); |
81 | 0 | } |
82 | | |
83 | 0 | void CoverageSourceInfo::HandleEmptyline(SourceRange Range) { |
84 | 0 | AddSkippedRange(Range, SkippedRange::EmptyLine); |
85 | 0 | } |
86 | | |
87 | 0 | bool CoverageSourceInfo::HandleComment(Preprocessor &PP, SourceRange Range) { |
88 | 0 | AddSkippedRange(Range, SkippedRange::Comment); |
89 | 0 | return false; |
90 | 0 | } |
91 | | |
92 | 0 | void CoverageSourceInfo::updateNextTokLoc(SourceLocation Loc) { |
93 | 0 | if (!SkippedRanges.empty() && SkippedRanges.back().NextTokLoc.isInvalid()) |
94 | 0 | SkippedRanges.back().NextTokLoc = Loc; |
95 | 0 | } |
96 | | |
97 | | namespace { |
98 | | using MCDCConditionID = CounterMappingRegion::MCDCConditionID; |
99 | | using MCDCParameters = CounterMappingRegion::MCDCParameters; |
100 | | |
101 | | /// A region of source code that can be mapped to a counter. |
102 | | class SourceMappingRegion { |
103 | | /// Primary Counter that is also used for Branch Regions for "True" branches. |
104 | | Counter Count; |
105 | | |
106 | | /// Secondary Counter used for Branch Regions for "False" branches. |
107 | | std::optional<Counter> FalseCount; |
108 | | |
109 | | /// Parameters used for Modified Condition/Decision Coverage |
110 | | MCDCParameters MCDCParams; |
111 | | |
112 | | /// The region's starting location. |
113 | | std::optional<SourceLocation> LocStart; |
114 | | |
115 | | /// The region's ending location. |
116 | | std::optional<SourceLocation> LocEnd; |
117 | | |
118 | | /// Whether this region is a gap region. The count from a gap region is set |
119 | | /// as the line execution count if there are no other regions on the line. |
120 | | bool GapRegion; |
121 | | |
122 | | public: |
123 | | SourceMappingRegion(Counter Count, std::optional<SourceLocation> LocStart, |
124 | | std::optional<SourceLocation> LocEnd, |
125 | | bool GapRegion = false) |
126 | 0 | : Count(Count), LocStart(LocStart), LocEnd(LocEnd), GapRegion(GapRegion) { |
127 | 0 | } |
128 | | |
129 | | SourceMappingRegion(Counter Count, std::optional<Counter> FalseCount, |
130 | | MCDCParameters MCDCParams, |
131 | | std::optional<SourceLocation> LocStart, |
132 | | std::optional<SourceLocation> LocEnd, |
133 | | bool GapRegion = false) |
134 | | : Count(Count), FalseCount(FalseCount), MCDCParams(MCDCParams), |
135 | 0 | LocStart(LocStart), LocEnd(LocEnd), GapRegion(GapRegion) {} |
136 | | |
137 | | SourceMappingRegion(MCDCParameters MCDCParams, |
138 | | std::optional<SourceLocation> LocStart, |
139 | | std::optional<SourceLocation> LocEnd) |
140 | | : MCDCParams(MCDCParams), LocStart(LocStart), LocEnd(LocEnd), |
141 | 0 | GapRegion(false) {} |
142 | | |
143 | 0 | const Counter &getCounter() const { return Count; } |
144 | | |
145 | 0 | const Counter &getFalseCounter() const { |
146 | 0 | assert(FalseCount && "Region has no alternate counter"); |
147 | 0 | return *FalseCount; |
148 | 0 | } |
149 | | |
150 | 0 | void setCounter(Counter C) { Count = C; } |
151 | | |
152 | 0 | bool hasStartLoc() const { return LocStart.has_value(); } |
153 | | |
154 | 0 | void setStartLoc(SourceLocation Loc) { LocStart = Loc; } |
155 | | |
156 | 0 | SourceLocation getBeginLoc() const { |
157 | 0 | assert(LocStart && "Region has no start location"); |
158 | 0 | return *LocStart; |
159 | 0 | } |
160 | | |
161 | 0 | bool hasEndLoc() const { return LocEnd.has_value(); } |
162 | | |
163 | 0 | void setEndLoc(SourceLocation Loc) { |
164 | 0 | assert(Loc.isValid() && "Setting an invalid end location"); |
165 | 0 | LocEnd = Loc; |
166 | 0 | } |
167 | | |
168 | 0 | SourceLocation getEndLoc() const { |
169 | 0 | assert(LocEnd && "Region has no end location"); |
170 | 0 | return *LocEnd; |
171 | 0 | } |
172 | | |
173 | 0 | bool isGap() const { return GapRegion; } |
174 | | |
175 | 0 | void setGap(bool Gap) { GapRegion = Gap; } |
176 | | |
177 | 0 | bool isBranch() const { return FalseCount.has_value(); } |
178 | | |
179 | 0 | bool isMCDCDecision() const { return MCDCParams.NumConditions != 0; } |
180 | | |
181 | 0 | const MCDCParameters &getMCDCParams() const { return MCDCParams; } |
182 | | }; |
183 | | |
184 | | /// Spelling locations for the start and end of a source region. |
185 | | struct SpellingRegion { |
186 | | /// The line where the region starts. |
187 | | unsigned LineStart; |
188 | | |
189 | | /// The column where the region starts. |
190 | | unsigned ColumnStart; |
191 | | |
192 | | /// The line where the region ends. |
193 | | unsigned LineEnd; |
194 | | |
195 | | /// The column where the region ends. |
196 | | unsigned ColumnEnd; |
197 | | |
198 | | SpellingRegion(SourceManager &SM, SourceLocation LocStart, |
199 | 0 | SourceLocation LocEnd) { |
200 | 0 | LineStart = SM.getSpellingLineNumber(LocStart); |
201 | 0 | ColumnStart = SM.getSpellingColumnNumber(LocStart); |
202 | 0 | LineEnd = SM.getSpellingLineNumber(LocEnd); |
203 | 0 | ColumnEnd = SM.getSpellingColumnNumber(LocEnd); |
204 | 0 | } |
205 | | |
206 | | SpellingRegion(SourceManager &SM, SourceMappingRegion &R) |
207 | 0 | : SpellingRegion(SM, R.getBeginLoc(), R.getEndLoc()) {} |
208 | | |
209 | | /// Check if the start and end locations appear in source order, i.e |
210 | | /// top->bottom, left->right. |
211 | 0 | bool isInSourceOrder() const { |
212 | 0 | return (LineStart < LineEnd) || |
213 | 0 | (LineStart == LineEnd && ColumnStart <= ColumnEnd); |
214 | 0 | } |
215 | | }; |
216 | | |
217 | | /// Provides the common functionality for the different |
218 | | /// coverage mapping region builders. |
219 | | class CoverageMappingBuilder { |
220 | | public: |
221 | | CoverageMappingModuleGen &CVM; |
222 | | SourceManager &SM; |
223 | | const LangOptions &LangOpts; |
224 | | |
225 | | private: |
226 | | /// Map of clang's FileIDs to IDs used for coverage mapping. |
227 | | llvm::SmallDenseMap<FileID, std::pair<unsigned, SourceLocation>, 8> |
228 | | FileIDMapping; |
229 | | |
230 | | public: |
231 | | /// The coverage mapping regions for this function |
232 | | llvm::SmallVector<CounterMappingRegion, 32> MappingRegions; |
233 | | /// The source mapping regions for this function. |
234 | | std::vector<SourceMappingRegion> SourceRegions; |
235 | | |
236 | | /// A set of regions which can be used as a filter. |
237 | | /// |
238 | | /// It is produced by emitExpansionRegions() and is used in |
239 | | /// emitSourceRegions() to suppress producing code regions if |
240 | | /// the same area is covered by expansion regions. |
241 | | typedef llvm::SmallSet<std::pair<SourceLocation, SourceLocation>, 8> |
242 | | SourceRegionFilter; |
243 | | |
244 | | CoverageMappingBuilder(CoverageMappingModuleGen &CVM, SourceManager &SM, |
245 | | const LangOptions &LangOpts) |
246 | 0 | : CVM(CVM), SM(SM), LangOpts(LangOpts) {} |
247 | | |
248 | | /// Return the precise end location for the given token. |
249 | 0 | SourceLocation getPreciseTokenLocEnd(SourceLocation Loc) { |
250 | | // We avoid getLocForEndOfToken here, because it doesn't do what we want for |
251 | | // macro locations, which we just treat as expanded files. |
252 | 0 | unsigned TokLen = |
253 | 0 | Lexer::MeasureTokenLength(SM.getSpellingLoc(Loc), SM, LangOpts); |
254 | 0 | return Loc.getLocWithOffset(TokLen); |
255 | 0 | } |
256 | | |
257 | | /// Return the start location of an included file or expanded macro. |
258 | 0 | SourceLocation getStartOfFileOrMacro(SourceLocation Loc) { |
259 | 0 | if (Loc.isMacroID()) |
260 | 0 | return Loc.getLocWithOffset(-SM.getFileOffset(Loc)); |
261 | 0 | return SM.getLocForStartOfFile(SM.getFileID(Loc)); |
262 | 0 | } |
263 | | |
264 | | /// Return the end location of an included file or expanded macro. |
265 | 0 | SourceLocation getEndOfFileOrMacro(SourceLocation Loc) { |
266 | 0 | if (Loc.isMacroID()) |
267 | 0 | return Loc.getLocWithOffset(SM.getFileIDSize(SM.getFileID(Loc)) - |
268 | 0 | SM.getFileOffset(Loc)); |
269 | 0 | return SM.getLocForEndOfFile(SM.getFileID(Loc)); |
270 | 0 | } |
271 | | |
272 | | /// Find out where the current file is included or macro is expanded. |
273 | 0 | SourceLocation getIncludeOrExpansionLoc(SourceLocation Loc) { |
274 | 0 | return Loc.isMacroID() ? SM.getImmediateExpansionRange(Loc).getBegin() |
275 | 0 | : SM.getIncludeLoc(SM.getFileID(Loc)); |
276 | 0 | } |
277 | | |
278 | | /// Return true if \c Loc is a location in a built-in macro. |
279 | 0 | bool isInBuiltin(SourceLocation Loc) { |
280 | 0 | return SM.getBufferName(SM.getSpellingLoc(Loc)) == "<built-in>"; |
281 | 0 | } |
282 | | |
283 | | /// Check whether \c Loc is included or expanded from \c Parent. |
284 | 0 | bool isNestedIn(SourceLocation Loc, FileID Parent) { |
285 | 0 | do { |
286 | 0 | Loc = getIncludeOrExpansionLoc(Loc); |
287 | 0 | if (Loc.isInvalid()) |
288 | 0 | return false; |
289 | 0 | } while (!SM.isInFileID(Loc, Parent)); |
290 | 0 | return true; |
291 | 0 | } |
292 | | |
293 | | /// Get the start of \c S ignoring macro arguments and builtin macros. |
294 | 0 | SourceLocation getStart(const Stmt *S) { |
295 | 0 | SourceLocation Loc = S->getBeginLoc(); |
296 | 0 | while (SM.isMacroArgExpansion(Loc) || isInBuiltin(Loc)) |
297 | 0 | Loc = SM.getImmediateExpansionRange(Loc).getBegin(); |
298 | 0 | return Loc; |
299 | 0 | } |
300 | | |
301 | | /// Get the end of \c S ignoring macro arguments and builtin macros. |
302 | 0 | SourceLocation getEnd(const Stmt *S) { |
303 | 0 | SourceLocation Loc = S->getEndLoc(); |
304 | 0 | while (SM.isMacroArgExpansion(Loc) || isInBuiltin(Loc)) |
305 | 0 | Loc = SM.getImmediateExpansionRange(Loc).getBegin(); |
306 | 0 | return getPreciseTokenLocEnd(Loc); |
307 | 0 | } |
308 | | |
309 | | /// Find the set of files we have regions for and assign IDs |
310 | | /// |
311 | | /// Fills \c Mapping with the virtual file mapping needed to write out |
312 | | /// coverage and collects the necessary file information to emit source and |
313 | | /// expansion regions. |
314 | 0 | void gatherFileIDs(SmallVectorImpl<unsigned> &Mapping) { |
315 | 0 | FileIDMapping.clear(); |
316 | |
|
317 | 0 | llvm::SmallSet<FileID, 8> Visited; |
318 | 0 | SmallVector<std::pair<SourceLocation, unsigned>, 8> FileLocs; |
319 | 0 | for (const auto &Region : SourceRegions) { |
320 | 0 | SourceLocation Loc = Region.getBeginLoc(); |
321 | 0 | FileID File = SM.getFileID(Loc); |
322 | 0 | if (!Visited.insert(File).second) |
323 | 0 | continue; |
324 | | |
325 | | // Do not map FileID's associated with system headers unless collecting |
326 | | // coverage from system headers is explicitly enabled. |
327 | 0 | if (!SystemHeadersCoverage && SM.isInSystemHeader(SM.getSpellingLoc(Loc))) |
328 | 0 | continue; |
329 | | |
330 | 0 | unsigned Depth = 0; |
331 | 0 | for (SourceLocation Parent = getIncludeOrExpansionLoc(Loc); |
332 | 0 | Parent.isValid(); Parent = getIncludeOrExpansionLoc(Parent)) |
333 | 0 | ++Depth; |
334 | 0 | FileLocs.push_back(std::make_pair(Loc, Depth)); |
335 | 0 | } |
336 | 0 | llvm::stable_sort(FileLocs, llvm::less_second()); |
337 | |
|
338 | 0 | for (const auto &FL : FileLocs) { |
339 | 0 | SourceLocation Loc = FL.first; |
340 | 0 | FileID SpellingFile = SM.getDecomposedSpellingLoc(Loc).first; |
341 | 0 | auto Entry = SM.getFileEntryRefForID(SpellingFile); |
342 | 0 | if (!Entry) |
343 | 0 | continue; |
344 | | |
345 | 0 | FileIDMapping[SM.getFileID(Loc)] = std::make_pair(Mapping.size(), Loc); |
346 | 0 | Mapping.push_back(CVM.getFileID(*Entry)); |
347 | 0 | } |
348 | 0 | } |
349 | | |
350 | | /// Get the coverage mapping file ID for \c Loc. |
351 | | /// |
352 | | /// If such file id doesn't exist, return std::nullopt. |
353 | 0 | std::optional<unsigned> getCoverageFileID(SourceLocation Loc) { |
354 | 0 | auto Mapping = FileIDMapping.find(SM.getFileID(Loc)); |
355 | 0 | if (Mapping != FileIDMapping.end()) |
356 | 0 | return Mapping->second.first; |
357 | 0 | return std::nullopt; |
358 | 0 | } |
359 | | |
360 | | /// This shrinks the skipped range if it spans a line that contains a |
361 | | /// non-comment token. If shrinking the skipped range would make it empty, |
362 | | /// this returns std::nullopt. |
363 | | /// Note this function can potentially be expensive because |
364 | | /// getSpellingLineNumber uses getLineNumber, which is expensive. |
365 | | std::optional<SpellingRegion> adjustSkippedRange(SourceManager &SM, |
366 | | SourceLocation LocStart, |
367 | | SourceLocation LocEnd, |
368 | | SourceLocation PrevTokLoc, |
369 | 0 | SourceLocation NextTokLoc) { |
370 | 0 | SpellingRegion SR{SM, LocStart, LocEnd}; |
371 | 0 | SR.ColumnStart = 1; |
372 | 0 | if (PrevTokLoc.isValid() && SM.isWrittenInSameFile(LocStart, PrevTokLoc) && |
373 | 0 | SR.LineStart == SM.getSpellingLineNumber(PrevTokLoc)) |
374 | 0 | SR.LineStart++; |
375 | 0 | if (NextTokLoc.isValid() && SM.isWrittenInSameFile(LocEnd, NextTokLoc) && |
376 | 0 | SR.LineEnd == SM.getSpellingLineNumber(NextTokLoc)) { |
377 | 0 | SR.LineEnd--; |
378 | 0 | SR.ColumnEnd++; |
379 | 0 | } |
380 | 0 | if (SR.isInSourceOrder()) |
381 | 0 | return SR; |
382 | 0 | return std::nullopt; |
383 | 0 | } |
384 | | |
385 | | /// Gather all the regions that were skipped by the preprocessor |
386 | | /// using the constructs like #if or comments. |
387 | 0 | void gatherSkippedRegions() { |
388 | | /// An array of the minimum lineStarts and the maximum lineEnds |
389 | | /// for mapping regions from the appropriate source files. |
390 | 0 | llvm::SmallVector<std::pair<unsigned, unsigned>, 8> FileLineRanges; |
391 | 0 | FileLineRanges.resize( |
392 | 0 | FileIDMapping.size(), |
393 | 0 | std::make_pair(std::numeric_limits<unsigned>::max(), 0)); |
394 | 0 | for (const auto &R : MappingRegions) { |
395 | 0 | FileLineRanges[R.FileID].first = |
396 | 0 | std::min(FileLineRanges[R.FileID].first, R.LineStart); |
397 | 0 | FileLineRanges[R.FileID].second = |
398 | 0 | std::max(FileLineRanges[R.FileID].second, R.LineEnd); |
399 | 0 | } |
400 | |
|
401 | 0 | auto SkippedRanges = CVM.getSourceInfo().getSkippedRanges(); |
402 | 0 | for (auto &I : SkippedRanges) { |
403 | 0 | SourceRange Range = I.Range; |
404 | 0 | auto LocStart = Range.getBegin(); |
405 | 0 | auto LocEnd = Range.getEnd(); |
406 | 0 | assert(SM.isWrittenInSameFile(LocStart, LocEnd) && |
407 | 0 | "region spans multiple files"); |
408 | | |
409 | 0 | auto CovFileID = getCoverageFileID(LocStart); |
410 | 0 | if (!CovFileID) |
411 | 0 | continue; |
412 | 0 | std::optional<SpellingRegion> SR; |
413 | 0 | if (I.isComment()) |
414 | 0 | SR = adjustSkippedRange(SM, LocStart, LocEnd, I.PrevTokLoc, |
415 | 0 | I.NextTokLoc); |
416 | 0 | else if (I.isPPIfElse() || I.isEmptyLine()) |
417 | 0 | SR = {SM, LocStart, LocEnd}; |
418 | |
|
419 | 0 | if (!SR) |
420 | 0 | continue; |
421 | 0 | auto Region = CounterMappingRegion::makeSkipped( |
422 | 0 | *CovFileID, SR->LineStart, SR->ColumnStart, SR->LineEnd, |
423 | 0 | SR->ColumnEnd); |
424 | | // Make sure that we only collect the regions that are inside |
425 | | // the source code of this function. |
426 | 0 | if (Region.LineStart >= FileLineRanges[*CovFileID].first && |
427 | 0 | Region.LineEnd <= FileLineRanges[*CovFileID].second) |
428 | 0 | MappingRegions.push_back(Region); |
429 | 0 | } |
430 | 0 | } |
431 | | |
432 | | /// Generate the coverage counter mapping regions from collected |
433 | | /// source regions. |
434 | 0 | void emitSourceRegions(const SourceRegionFilter &Filter) { |
435 | 0 | for (const auto &Region : SourceRegions) { |
436 | 0 | assert(Region.hasEndLoc() && "incomplete region"); |
437 | | |
438 | 0 | SourceLocation LocStart = Region.getBeginLoc(); |
439 | 0 | assert(SM.getFileID(LocStart).isValid() && "region in invalid file"); |
440 | | |
441 | | // Ignore regions from system headers unless collecting coverage from |
442 | | // system headers is explicitly enabled. |
443 | 0 | if (!SystemHeadersCoverage && |
444 | 0 | SM.isInSystemHeader(SM.getSpellingLoc(LocStart))) |
445 | 0 | continue; |
446 | | |
447 | 0 | auto CovFileID = getCoverageFileID(LocStart); |
448 | | // Ignore regions that don't have a file, such as builtin macros. |
449 | 0 | if (!CovFileID) |
450 | 0 | continue; |
451 | | |
452 | 0 | SourceLocation LocEnd = Region.getEndLoc(); |
453 | 0 | assert(SM.isWrittenInSameFile(LocStart, LocEnd) && |
454 | 0 | "region spans multiple files"); |
455 | | |
456 | | // Don't add code regions for the area covered by expansion regions. |
457 | | // This not only suppresses redundant regions, but sometimes prevents |
458 | | // creating regions with wrong counters if, for example, a statement's |
459 | | // body ends at the end of a nested macro. |
460 | 0 | if (Filter.count(std::make_pair(LocStart, LocEnd))) |
461 | 0 | continue; |
462 | | |
463 | | // Find the spelling locations for the mapping region. |
464 | 0 | SpellingRegion SR{SM, LocStart, LocEnd}; |
465 | 0 | assert(SR.isInSourceOrder() && "region start and end out of order"); |
466 | | |
467 | 0 | if (Region.isGap()) { |
468 | 0 | MappingRegions.push_back(CounterMappingRegion::makeGapRegion( |
469 | 0 | Region.getCounter(), *CovFileID, SR.LineStart, SR.ColumnStart, |
470 | 0 | SR.LineEnd, SR.ColumnEnd)); |
471 | 0 | } else if (Region.isBranch()) { |
472 | 0 | MappingRegions.push_back(CounterMappingRegion::makeBranchRegion( |
473 | 0 | Region.getCounter(), Region.getFalseCounter(), |
474 | 0 | Region.getMCDCParams(), *CovFileID, SR.LineStart, SR.ColumnStart, |
475 | 0 | SR.LineEnd, SR.ColumnEnd)); |
476 | 0 | } else if (Region.isMCDCDecision()) { |
477 | 0 | MappingRegions.push_back(CounterMappingRegion::makeDecisionRegion( |
478 | 0 | Region.getMCDCParams(), *CovFileID, SR.LineStart, SR.ColumnStart, |
479 | 0 | SR.LineEnd, SR.ColumnEnd)); |
480 | 0 | } else { |
481 | 0 | MappingRegions.push_back(CounterMappingRegion::makeRegion( |
482 | 0 | Region.getCounter(), *CovFileID, SR.LineStart, SR.ColumnStart, |
483 | 0 | SR.LineEnd, SR.ColumnEnd)); |
484 | 0 | } |
485 | 0 | } |
486 | 0 | } |
487 | | |
488 | | /// Generate expansion regions for each virtual file we've seen. |
489 | 0 | SourceRegionFilter emitExpansionRegions() { |
490 | 0 | SourceRegionFilter Filter; |
491 | 0 | for (const auto &FM : FileIDMapping) { |
492 | 0 | SourceLocation ExpandedLoc = FM.second.second; |
493 | 0 | SourceLocation ParentLoc = getIncludeOrExpansionLoc(ExpandedLoc); |
494 | 0 | if (ParentLoc.isInvalid()) |
495 | 0 | continue; |
496 | | |
497 | 0 | auto ParentFileID = getCoverageFileID(ParentLoc); |
498 | 0 | if (!ParentFileID) |
499 | 0 | continue; |
500 | 0 | auto ExpandedFileID = getCoverageFileID(ExpandedLoc); |
501 | 0 | assert(ExpandedFileID && "expansion in uncovered file"); |
502 | | |
503 | 0 | SourceLocation LocEnd = getPreciseTokenLocEnd(ParentLoc); |
504 | 0 | assert(SM.isWrittenInSameFile(ParentLoc, LocEnd) && |
505 | 0 | "region spans multiple files"); |
506 | 0 | Filter.insert(std::make_pair(ParentLoc, LocEnd)); |
507 | |
|
508 | 0 | SpellingRegion SR{SM, ParentLoc, LocEnd}; |
509 | 0 | assert(SR.isInSourceOrder() && "region start and end out of order"); |
510 | 0 | MappingRegions.push_back(CounterMappingRegion::makeExpansion( |
511 | 0 | *ParentFileID, *ExpandedFileID, SR.LineStart, SR.ColumnStart, |
512 | 0 | SR.LineEnd, SR.ColumnEnd)); |
513 | 0 | } |
514 | 0 | return Filter; |
515 | 0 | } |
516 | | }; |
517 | | |
518 | | /// Creates unreachable coverage regions for the functions that |
519 | | /// are not emitted. |
520 | | struct EmptyCoverageMappingBuilder : public CoverageMappingBuilder { |
521 | | EmptyCoverageMappingBuilder(CoverageMappingModuleGen &CVM, SourceManager &SM, |
522 | | const LangOptions &LangOpts) |
523 | 0 | : CoverageMappingBuilder(CVM, SM, LangOpts) {} |
524 | | |
525 | 0 | void VisitDecl(const Decl *D) { |
526 | 0 | if (!D->hasBody()) |
527 | 0 | return; |
528 | 0 | auto Body = D->getBody(); |
529 | 0 | SourceLocation Start = getStart(Body); |
530 | 0 | SourceLocation End = getEnd(Body); |
531 | 0 | if (!SM.isWrittenInSameFile(Start, End)) { |
532 | | // Walk up to find the common ancestor. |
533 | | // Correct the locations accordingly. |
534 | 0 | FileID StartFileID = SM.getFileID(Start); |
535 | 0 | FileID EndFileID = SM.getFileID(End); |
536 | 0 | while (StartFileID != EndFileID && !isNestedIn(End, StartFileID)) { |
537 | 0 | Start = getIncludeOrExpansionLoc(Start); |
538 | 0 | assert(Start.isValid() && |
539 | 0 | "Declaration start location not nested within a known region"); |
540 | 0 | StartFileID = SM.getFileID(Start); |
541 | 0 | } |
542 | 0 | while (StartFileID != EndFileID) { |
543 | 0 | End = getPreciseTokenLocEnd(getIncludeOrExpansionLoc(End)); |
544 | 0 | assert(End.isValid() && |
545 | 0 | "Declaration end location not nested within a known region"); |
546 | 0 | EndFileID = SM.getFileID(End); |
547 | 0 | } |
548 | 0 | } |
549 | 0 | SourceRegions.emplace_back(Counter(), Start, End); |
550 | 0 | } |
551 | | |
552 | | /// Write the mapping data to the output stream |
553 | 0 | void write(llvm::raw_ostream &OS) { |
554 | 0 | SmallVector<unsigned, 16> FileIDMapping; |
555 | 0 | gatherFileIDs(FileIDMapping); |
556 | 0 | emitSourceRegions(SourceRegionFilter()); |
557 | |
|
558 | 0 | if (MappingRegions.empty()) |
559 | 0 | return; |
560 | | |
561 | 0 | CoverageMappingWriter Writer(FileIDMapping, std::nullopt, MappingRegions); |
562 | 0 | Writer.write(OS); |
563 | 0 | } |
564 | | }; |
565 | | |
566 | | /// A wrapper object for maintaining stacks to track the resursive AST visitor |
567 | | /// walks for the purpose of assigning IDs to leaf-level conditions measured by |
568 | | /// MC/DC. The object is created with a reference to the MCDCBitmapMap that was |
569 | | /// created during the initial AST walk. The presence of a bitmap associated |
570 | | /// with a boolean expression (top-level logical operator nest) indicates that |
571 | | /// the boolean expression qualified for MC/DC. The resulting condition IDs |
572 | | /// are preserved in a map reference that is also provided during object |
573 | | /// creation. |
574 | | struct MCDCCoverageBuilder { |
575 | | |
576 | | /// The AST walk recursively visits nested logical-AND or logical-OR binary |
577 | | /// operator nodes and then visits their LHS and RHS children nodes. As this |
578 | | /// happens, the algorithm will assign IDs to each operator's LHS and RHS side |
579 | | /// as the walk moves deeper into the nest. At each level of the recursive |
580 | | /// nest, the LHS and RHS may actually correspond to larger subtrees (not |
581 | | /// leaf-conditions). If this is the case, when that node is visited, the ID |
582 | | /// assigned to the subtree is re-assigned to its LHS, and a new ID is given |
583 | | /// to its RHS. At the end of the walk, all leaf-level conditions will have a |
584 | | /// unique ID -- keep in mind that the final set of IDs may not be in |
585 | | /// numerical order from left to right. |
586 | | /// |
587 | | /// Example: "x = (A && B) || (C && D) || (D && F)" |
588 | | /// |
589 | | /// Visit Depth1: |
590 | | /// (A && B) || (C && D) || (D && F) |
591 | | /// ^-------LHS--------^ ^-RHS--^ |
592 | | /// ID=1 ID=2 |
593 | | /// |
594 | | /// Visit LHS-Depth2: |
595 | | /// (A && B) || (C && D) |
596 | | /// ^-LHS--^ ^-RHS--^ |
597 | | /// ID=1 ID=3 |
598 | | /// |
599 | | /// Visit LHS-Depth3: |
600 | | /// (A && B) |
601 | | /// LHS RHS |
602 | | /// ID=1 ID=4 |
603 | | /// |
604 | | /// Visit RHS-Depth3: |
605 | | /// (C && D) |
606 | | /// LHS RHS |
607 | | /// ID=3 ID=5 |
608 | | /// |
609 | | /// Visit RHS-Depth2: (D && F) |
610 | | /// LHS RHS |
611 | | /// ID=2 ID=6 |
612 | | /// |
613 | | /// Visit Depth1: |
614 | | /// (A && B) || (C && D) || (D && F) |
615 | | /// ID=1 ID=4 ID=3 ID=5 ID=2 ID=6 |
616 | | /// |
617 | | /// A node ID of '0' always means MC/DC isn't being tracked. |
618 | | /// |
619 | | /// As the AST walk proceeds recursively, the algorithm will also use stacks |
620 | | /// to track the IDs of logical-AND and logical-OR operations on the RHS so |
621 | | /// that it can be determined which nodes are executed next, depending on how |
622 | | /// a LHS or RHS of a logical-AND or logical-OR is evaluated. This |
623 | | /// information relies on the assigned IDs and are embedded within the |
624 | | /// coverage region IDs of each branch region associated with a leaf-level |
625 | | /// condition. This information helps the visualization tool reconstruct all |
626 | | /// possible test vectors for the purposes of MC/DC analysis. if a "next" node |
627 | | /// ID is '0', it means it's the end of the test vector. The following rules |
628 | | /// are used: |
629 | | /// |
630 | | /// For logical-AND ("LHS && RHS"): |
631 | | /// - If LHS is TRUE, execution goes to the RHS node. |
632 | | /// - If LHS is FALSE, execution goes to the LHS node of the next logical-OR. |
633 | | /// If that does not exist, execution exits (ID == 0). |
634 | | /// |
635 | | /// - If RHS is TRUE, execution goes to LHS node of the next logical-AND. |
636 | | /// If that does not exist, execution exits (ID == 0). |
637 | | /// - If RHS is FALSE, execution goes to the LHS node of the next logical-OR. |
638 | | /// If that does not exist, execution exits (ID == 0). |
639 | | /// |
640 | | /// For logical-OR ("LHS || RHS"): |
641 | | /// - If LHS is TRUE, execution goes to the LHS node of the next logical-AND. |
642 | | /// If that does not exist, execution exits (ID == 0). |
643 | | /// - If LHS is FALSE, execution goes to the RHS node. |
644 | | /// |
645 | | /// - If RHS is TRUE, execution goes to LHS node of the next logical-AND. |
646 | | /// If that does not exist, execution exits (ID == 0). |
647 | | /// - If RHS is FALSE, execution goes to the LHS node of the next logical-OR. |
648 | | /// If that does not exist, execution exits (ID == 0). |
649 | | /// |
650 | | /// Finally, the condition IDs are also used when instrumenting the code to |
651 | | /// indicate a unique offset into a temporary bitmap that represents the true |
652 | | /// or false evaluation of that particular condition. |
653 | | /// |
654 | | /// NOTE regarding the use of CodeGenFunction::stripCond(). Even though, for |
655 | | /// simplicity, parentheses and unary logical-NOT operators are considered |
656 | | /// part of their underlying condition for both MC/DC and branch coverage, the |
657 | | /// condition IDs themselves are assigned and tracked using the underlying |
658 | | /// condition itself. This is done solely for consistency since parentheses |
659 | | /// and logical-NOTs are ignored when checking whether the condition is |
660 | | /// actually an instrumentable condition. This can also make debugging a bit |
661 | | /// easier. |
662 | | |
663 | | private: |
664 | | CodeGenModule &CGM; |
665 | | |
666 | | llvm::SmallVector<MCDCConditionID> AndRHS; |
667 | | llvm::SmallVector<MCDCConditionID> OrRHS; |
668 | | llvm::SmallVector<const BinaryOperator *> NestLevel; |
669 | | llvm::DenseMap<const Stmt *, MCDCConditionID> &CondIDs; |
670 | | llvm::DenseMap<const Stmt *, unsigned> &MCDCBitmapMap; |
671 | | MCDCConditionID NextID = 1; |
672 | | bool NotMapped = false; |
673 | | |
674 | | /// Is this a logical-AND operation? |
675 | 0 | bool isLAnd(const BinaryOperator *E) const { |
676 | 0 | return E->getOpcode() == BO_LAnd; |
677 | 0 | } |
678 | | |
679 | | /// Push an ID onto the corresponding RHS stack. |
680 | 0 | void pushRHS(const BinaryOperator *E) { |
681 | 0 | llvm::SmallVector<MCDCConditionID> &rhs = isLAnd(E) ? AndRHS : OrRHS; |
682 | 0 | rhs.push_back(CondIDs[CodeGenFunction::stripCond(E->getRHS())]); |
683 | 0 | } |
684 | | |
685 | | /// Pop an ID from the corresponding RHS stack. |
686 | 0 | void popRHS(const BinaryOperator *E) { |
687 | 0 | llvm::SmallVector<MCDCConditionID> &rhs = isLAnd(E) ? AndRHS : OrRHS; |
688 | 0 | if (!rhs.empty()) |
689 | 0 | rhs.pop_back(); |
690 | 0 | } |
691 | | |
692 | | /// If the expected ID is on top, pop it off the corresponding RHS stack. |
693 | 0 | void popRHSifTop(const BinaryOperator *E) { |
694 | 0 | if (!OrRHS.empty() && CondIDs[E] == OrRHS.back()) |
695 | 0 | OrRHS.pop_back(); |
696 | 0 | else if (!AndRHS.empty() && CondIDs[E] == AndRHS.back()) |
697 | 0 | AndRHS.pop_back(); |
698 | 0 | } |
699 | | |
700 | | public: |
701 | | MCDCCoverageBuilder(CodeGenModule &CGM, |
702 | | llvm::DenseMap<const Stmt *, MCDCConditionID> &CondIDMap, |
703 | | llvm::DenseMap<const Stmt *, unsigned> &MCDCBitmapMap) |
704 | 0 | : CGM(CGM), CondIDs(CondIDMap), MCDCBitmapMap(MCDCBitmapMap) {} |
705 | | |
706 | | /// Return the ID of the RHS of the next, upper nest-level logical-OR. |
707 | 0 | MCDCConditionID getNextLOrCondID() const { |
708 | 0 | return OrRHS.empty() ? 0 : OrRHS.back(); |
709 | 0 | } |
710 | | |
711 | | /// Return the ID of the RHS of the next, upper nest-level logical-AND. |
712 | 0 | MCDCConditionID getNextLAndCondID() const { |
713 | 0 | return AndRHS.empty() ? 0 : AndRHS.back(); |
714 | 0 | } |
715 | | |
716 | | /// Return the ID of a given condition. |
717 | 0 | MCDCConditionID getCondID(const Expr *Cond) const { |
718 | 0 | auto I = CondIDs.find(CodeGenFunction::stripCond(Cond)); |
719 | 0 | if (I == CondIDs.end()) |
720 | 0 | return 0; |
721 | 0 | else |
722 | 0 | return I->second; |
723 | 0 | } |
724 | | |
725 | | /// Push the binary operator statement to track the nest level and assign IDs |
726 | | /// to the operator's LHS and RHS. The RHS may be a larger subtree that is |
727 | | /// broken up on successive levels. |
728 | 0 | void pushAndAssignIDs(const BinaryOperator *E) { |
729 | 0 | if (!CGM.getCodeGenOpts().MCDCCoverage) |
730 | 0 | return; |
731 | | |
732 | | // If binary expression is disqualified, don't do mapping. |
733 | 0 | if (NestLevel.empty() && |
734 | 0 | !MCDCBitmapMap.contains(CodeGenFunction::stripCond(E))) |
735 | 0 | NotMapped = true; |
736 | | |
737 | | // Push Stmt on 'NestLevel' stack to keep track of nest location. |
738 | 0 | NestLevel.push_back(E); |
739 | | |
740 | | // Don't go any further if we don't need to map condition IDs. |
741 | 0 | if (NotMapped) |
742 | 0 | return; |
743 | | |
744 | | // If the operator itself has an assigned ID, this means it represents a |
745 | | // larger subtree. In this case, pop its ID out of the RHS stack and |
746 | | // assign that ID to its LHS node. Its RHS will receive a new ID. |
747 | 0 | if (CondIDs.contains(CodeGenFunction::stripCond(E))) { |
748 | | // If Stmt has an ID, assign its ID to LHS |
749 | 0 | CondIDs[CodeGenFunction::stripCond(E->getLHS())] = CondIDs[E]; |
750 | | |
751 | | // Since the operator's LHS assumes the operator's same ID, pop the |
752 | | // operator from the RHS stack so that if LHS short-circuits, it won't be |
753 | | // incorrectly re-used as the node executed next. |
754 | 0 | popRHSifTop(E); |
755 | 0 | } else { |
756 | | // Otherwise, assign ID+1 to LHS. |
757 | 0 | CondIDs[CodeGenFunction::stripCond(E->getLHS())] = NextID++; |
758 | 0 | } |
759 | | |
760 | | // Assign ID+1 to RHS. |
761 | 0 | CondIDs[CodeGenFunction::stripCond(E->getRHS())] = NextID++; |
762 | | |
763 | | // Push ID of Stmt's RHS so that LHS nodes know about it |
764 | 0 | pushRHS(E); |
765 | 0 | } |
766 | | |
767 | | /// Pop the binary operator from the next level. If the walk is at the top of |
768 | | /// the next, assign the total number of conditions. |
769 | 0 | unsigned popAndReturnCondCount(const BinaryOperator *E) { |
770 | 0 | if (!CGM.getCodeGenOpts().MCDCCoverage) |
771 | 0 | return 0; |
772 | | |
773 | 0 | unsigned TotalConds = 0; |
774 | | |
775 | | // Pop Stmt from 'NestLevel' stack. |
776 | 0 | assert(NestLevel.back() == E); |
777 | 0 | NestLevel.pop_back(); |
778 | | |
779 | | // Reset state if not doing mapping. |
780 | 0 | if (NestLevel.empty() && NotMapped) { |
781 | 0 | NotMapped = false; |
782 | 0 | return 0; |
783 | 0 | } |
784 | | |
785 | | // Pop RHS ID. |
786 | 0 | popRHS(E); |
787 | | |
788 | | // If at the parent (NestLevel=0), set conds and reset. |
789 | 0 | if (NestLevel.empty()) { |
790 | 0 | TotalConds = NextID - 1; |
791 | | |
792 | | // Reset ID back to beginning. |
793 | 0 | NextID = 1; |
794 | 0 | } |
795 | 0 | return TotalConds; |
796 | 0 | } |
797 | | }; |
798 | | |
799 | | /// A StmtVisitor that creates coverage mapping regions which map |
800 | | /// from the source code locations to the PGO counters. |
801 | | struct CounterCoverageMappingBuilder |
802 | | : public CoverageMappingBuilder, |
803 | | public ConstStmtVisitor<CounterCoverageMappingBuilder> { |
804 | | /// The map of statements to count values. |
805 | | llvm::DenseMap<const Stmt *, unsigned> &CounterMap; |
806 | | |
807 | | /// The map of statements to bitmap coverage object values. |
808 | | llvm::DenseMap<const Stmt *, unsigned> &MCDCBitmapMap; |
809 | | |
810 | | /// A stack of currently live regions. |
811 | | llvm::SmallVector<SourceMappingRegion> RegionStack; |
812 | | |
813 | | /// An object to manage MCDC regions. |
814 | | MCDCCoverageBuilder MCDCBuilder; |
815 | | |
816 | | CounterExpressionBuilder Builder; |
817 | | |
818 | | /// A location in the most recently visited file or macro. |
819 | | /// |
820 | | /// This is used to adjust the active source regions appropriately when |
821 | | /// expressions cross file or macro boundaries. |
822 | | SourceLocation MostRecentLocation; |
823 | | |
824 | | /// Whether the visitor at a terminate statement. |
825 | | bool HasTerminateStmt = false; |
826 | | |
827 | | /// Gap region counter after terminate statement. |
828 | | Counter GapRegionCounter; |
829 | | |
830 | | /// Return a counter for the subtraction of \c RHS from \c LHS |
831 | 0 | Counter subtractCounters(Counter LHS, Counter RHS, bool Simplify = true) { |
832 | 0 | return Builder.subtract(LHS, RHS, Simplify); |
833 | 0 | } |
834 | | |
835 | | /// Return a counter for the sum of \c LHS and \c RHS. |
836 | 0 | Counter addCounters(Counter LHS, Counter RHS, bool Simplify = true) { |
837 | 0 | return Builder.add(LHS, RHS, Simplify); |
838 | 0 | } |
839 | | |
840 | | Counter addCounters(Counter C1, Counter C2, Counter C3, |
841 | 0 | bool Simplify = true) { |
842 | 0 | return addCounters(addCounters(C1, C2, Simplify), C3, Simplify); |
843 | 0 | } |
844 | | |
845 | | /// Return the region counter for the given statement. |
846 | | /// |
847 | | /// This should only be called on statements that have a dedicated counter. |
848 | 0 | Counter getRegionCounter(const Stmt *S) { |
849 | 0 | return Counter::getCounter(CounterMap[S]); |
850 | 0 | } |
851 | | |
852 | 0 | unsigned getRegionBitmap(const Stmt *S) { return MCDCBitmapMap[S]; } |
853 | | |
854 | | /// Push a region onto the stack. |
855 | | /// |
856 | | /// Returns the index on the stack where the region was pushed. This can be |
857 | | /// used with popRegions to exit a "scope", ending the region that was pushed. |
858 | | size_t pushRegion(Counter Count, |
859 | | std::optional<SourceLocation> StartLoc = std::nullopt, |
860 | | std::optional<SourceLocation> EndLoc = std::nullopt, |
861 | | std::optional<Counter> FalseCount = std::nullopt, |
862 | | MCDCConditionID ID = 0, MCDCConditionID TrueID = 0, |
863 | 0 | MCDCConditionID FalseID = 0) { |
864 | |
|
865 | 0 | if (StartLoc && !FalseCount) { |
866 | 0 | MostRecentLocation = *StartLoc; |
867 | 0 | } |
868 | | |
869 | | // If either of these locations is invalid, something elsewhere in the |
870 | | // compiler has broken. |
871 | 0 | assert((!StartLoc || StartLoc->isValid()) && "Start location is not valid"); |
872 | 0 | assert((!EndLoc || EndLoc->isValid()) && "End location is not valid"); |
873 | | |
874 | | // However, we can still recover without crashing. |
875 | | // If either location is invalid, set it to std::nullopt to avoid |
876 | | // letting users of RegionStack think that region has a valid start/end |
877 | | // location. |
878 | 0 | if (StartLoc && StartLoc->isInvalid()) |
879 | 0 | StartLoc = std::nullopt; |
880 | 0 | if (EndLoc && EndLoc->isInvalid()) |
881 | 0 | EndLoc = std::nullopt; |
882 | 0 | RegionStack.emplace_back(Count, FalseCount, |
883 | 0 | MCDCParameters{0, 0, ID, TrueID, FalseID}, |
884 | 0 | StartLoc, EndLoc); |
885 | |
|
886 | 0 | return RegionStack.size() - 1; |
887 | 0 | } |
888 | | |
889 | | size_t pushRegion(unsigned BitmapIdx, unsigned Conditions, |
890 | | std::optional<SourceLocation> StartLoc = std::nullopt, |
891 | 0 | std::optional<SourceLocation> EndLoc = std::nullopt) { |
892 | |
|
893 | 0 | RegionStack.emplace_back(MCDCParameters{BitmapIdx, Conditions}, StartLoc, |
894 | 0 | EndLoc); |
895 | |
|
896 | 0 | return RegionStack.size() - 1; |
897 | 0 | } |
898 | | |
899 | 0 | size_t locationDepth(SourceLocation Loc) { |
900 | 0 | size_t Depth = 0; |
901 | 0 | while (Loc.isValid()) { |
902 | 0 | Loc = getIncludeOrExpansionLoc(Loc); |
903 | 0 | Depth++; |
904 | 0 | } |
905 | 0 | return Depth; |
906 | 0 | } |
907 | | |
908 | | /// Pop regions from the stack into the function's list of regions. |
909 | | /// |
910 | | /// Adds all regions from \c ParentIndex to the top of the stack to the |
911 | | /// function's \c SourceRegions. |
912 | 0 | void popRegions(size_t ParentIndex) { |
913 | 0 | assert(RegionStack.size() >= ParentIndex && "parent not in stack"); |
914 | 0 | while (RegionStack.size() > ParentIndex) { |
915 | 0 | SourceMappingRegion &Region = RegionStack.back(); |
916 | 0 | if (Region.hasStartLoc() && |
917 | 0 | (Region.hasEndLoc() || RegionStack[ParentIndex].hasEndLoc())) { |
918 | 0 | SourceLocation StartLoc = Region.getBeginLoc(); |
919 | 0 | SourceLocation EndLoc = Region.hasEndLoc() |
920 | 0 | ? Region.getEndLoc() |
921 | 0 | : RegionStack[ParentIndex].getEndLoc(); |
922 | 0 | bool isBranch = Region.isBranch(); |
923 | 0 | size_t StartDepth = locationDepth(StartLoc); |
924 | 0 | size_t EndDepth = locationDepth(EndLoc); |
925 | 0 | while (!SM.isWrittenInSameFile(StartLoc, EndLoc)) { |
926 | 0 | bool UnnestStart = StartDepth >= EndDepth; |
927 | 0 | bool UnnestEnd = EndDepth >= StartDepth; |
928 | 0 | if (UnnestEnd) { |
929 | | // The region ends in a nested file or macro expansion. If the |
930 | | // region is not a branch region, create a separate region for each |
931 | | // expansion, and for all regions, update the EndLoc. Branch |
932 | | // regions should not be split in order to keep a straightforward |
933 | | // correspondance between the region and its associated branch |
934 | | // condition, even if the condition spans multiple depths. |
935 | 0 | SourceLocation NestedLoc = getStartOfFileOrMacro(EndLoc); |
936 | 0 | assert(SM.isWrittenInSameFile(NestedLoc, EndLoc)); |
937 | | |
938 | 0 | if (!isBranch && !isRegionAlreadyAdded(NestedLoc, EndLoc)) |
939 | 0 | SourceRegions.emplace_back(Region.getCounter(), NestedLoc, |
940 | 0 | EndLoc); |
941 | |
|
942 | 0 | EndLoc = getPreciseTokenLocEnd(getIncludeOrExpansionLoc(EndLoc)); |
943 | 0 | if (EndLoc.isInvalid()) |
944 | 0 | llvm::report_fatal_error( |
945 | 0 | "File exit not handled before popRegions"); |
946 | 0 | EndDepth--; |
947 | 0 | } |
948 | 0 | if (UnnestStart) { |
949 | | // The region ends in a nested file or macro expansion. If the |
950 | | // region is not a branch region, create a separate region for each |
951 | | // expansion, and for all regions, update the StartLoc. Branch |
952 | | // regions should not be split in order to keep a straightforward |
953 | | // correspondance between the region and its associated branch |
954 | | // condition, even if the condition spans multiple depths. |
955 | 0 | SourceLocation NestedLoc = getEndOfFileOrMacro(StartLoc); |
956 | 0 | assert(SM.isWrittenInSameFile(StartLoc, NestedLoc)); |
957 | | |
958 | 0 | if (!isBranch && !isRegionAlreadyAdded(StartLoc, NestedLoc)) |
959 | 0 | SourceRegions.emplace_back(Region.getCounter(), StartLoc, |
960 | 0 | NestedLoc); |
961 | |
|
962 | 0 | StartLoc = getIncludeOrExpansionLoc(StartLoc); |
963 | 0 | if (StartLoc.isInvalid()) |
964 | 0 | llvm::report_fatal_error( |
965 | 0 | "File exit not handled before popRegions"); |
966 | 0 | StartDepth--; |
967 | 0 | } |
968 | 0 | } |
969 | 0 | Region.setStartLoc(StartLoc); |
970 | 0 | Region.setEndLoc(EndLoc); |
971 | |
|
972 | 0 | if (!isBranch) { |
973 | 0 | MostRecentLocation = EndLoc; |
974 | | // If this region happens to span an entire expansion, we need to |
975 | | // make sure we don't overlap the parent region with it. |
976 | 0 | if (StartLoc == getStartOfFileOrMacro(StartLoc) && |
977 | 0 | EndLoc == getEndOfFileOrMacro(EndLoc)) |
978 | 0 | MostRecentLocation = getIncludeOrExpansionLoc(EndLoc); |
979 | 0 | } |
980 | |
|
981 | 0 | assert(SM.isWrittenInSameFile(Region.getBeginLoc(), EndLoc)); |
982 | 0 | assert(SpellingRegion(SM, Region).isInSourceOrder()); |
983 | 0 | SourceRegions.push_back(Region); |
984 | 0 | } |
985 | 0 | RegionStack.pop_back(); |
986 | 0 | } |
987 | 0 | } |
988 | | |
989 | | /// Return the currently active region. |
990 | 0 | SourceMappingRegion &getRegion() { |
991 | 0 | assert(!RegionStack.empty() && "statement has no region"); |
992 | 0 | return RegionStack.back(); |
993 | 0 | } |
994 | | |
995 | | /// Propagate counts through the children of \p S if \p VisitChildren is true. |
996 | | /// Otherwise, only emit a count for \p S itself. |
997 | | Counter propagateCounts(Counter TopCount, const Stmt *S, |
998 | 0 | bool VisitChildren = true) { |
999 | 0 | SourceLocation StartLoc = getStart(S); |
1000 | 0 | SourceLocation EndLoc = getEnd(S); |
1001 | 0 | size_t Index = pushRegion(TopCount, StartLoc, EndLoc); |
1002 | 0 | if (VisitChildren) |
1003 | 0 | Visit(S); |
1004 | 0 | Counter ExitCount = getRegion().getCounter(); |
1005 | 0 | popRegions(Index); |
1006 | | |
1007 | | // The statement may be spanned by an expansion. Make sure we handle a file |
1008 | | // exit out of this expansion before moving to the next statement. |
1009 | 0 | if (SM.isBeforeInTranslationUnit(StartLoc, S->getBeginLoc())) |
1010 | 0 | MostRecentLocation = EndLoc; |
1011 | |
|
1012 | 0 | return ExitCount; |
1013 | 0 | } |
1014 | | |
1015 | | /// Determine whether the given condition can be constant folded. |
1016 | 0 | bool ConditionFoldsToBool(const Expr *Cond) { |
1017 | 0 | Expr::EvalResult Result; |
1018 | 0 | return (Cond->EvaluateAsInt(Result, CVM.getCodeGenModule().getContext())); |
1019 | 0 | } |
1020 | | |
1021 | | /// Create a Branch Region around an instrumentable condition for coverage |
1022 | | /// and add it to the function's SourceRegions. A branch region tracks a |
1023 | | /// "True" counter and a "False" counter for boolean expressions that |
1024 | | /// result in the generation of a branch. |
1025 | | void createBranchRegion(const Expr *C, Counter TrueCnt, Counter FalseCnt, |
1026 | | MCDCConditionID ID = 0, MCDCConditionID TrueID = 0, |
1027 | 0 | MCDCConditionID FalseID = 0) { |
1028 | | // Check for NULL conditions. |
1029 | 0 | if (!C) |
1030 | 0 | return; |
1031 | | |
1032 | | // Ensure we are an instrumentable condition (i.e. no "&&" or "||"). Push |
1033 | | // region onto RegionStack but immediately pop it (which adds it to the |
1034 | | // function's SourceRegions) because it doesn't apply to any other source |
1035 | | // code other than the Condition. |
1036 | 0 | if (CodeGenFunction::isInstrumentedCondition(C)) { |
1037 | | // If a condition can fold to true or false, the corresponding branch |
1038 | | // will be removed. Create a region with both counters hard-coded to |
1039 | | // zero. This allows us to visualize them in a special way. |
1040 | | // Alternatively, we can prevent any optimization done via |
1041 | | // constant-folding by ensuring that ConstantFoldsToSimpleInteger() in |
1042 | | // CodeGenFunction.c always returns false, but that is very heavy-handed. |
1043 | 0 | if (ConditionFoldsToBool(C)) |
1044 | 0 | popRegions(pushRegion(Counter::getZero(), getStart(C), getEnd(C), |
1045 | 0 | Counter::getZero(), ID, TrueID, FalseID)); |
1046 | 0 | else |
1047 | | // Otherwise, create a region with the True counter and False counter. |
1048 | 0 | popRegions(pushRegion(TrueCnt, getStart(C), getEnd(C), FalseCnt, ID, |
1049 | 0 | TrueID, FalseID)); |
1050 | 0 | } |
1051 | 0 | } |
1052 | | |
1053 | | /// Create a Decision Region with a BitmapIdx and number of Conditions. This |
1054 | | /// type of region "contains" branch regions, one for each of the conditions. |
1055 | | /// The visualization tool will group everything together. |
1056 | 0 | void createDecisionRegion(const Expr *C, unsigned BitmapIdx, unsigned Conds) { |
1057 | 0 | popRegions(pushRegion(BitmapIdx, Conds, getStart(C), getEnd(C))); |
1058 | 0 | } |
1059 | | |
1060 | | /// Create a Branch Region around a SwitchCase for code coverage |
1061 | | /// and add it to the function's SourceRegions. |
1062 | | void createSwitchCaseRegion(const SwitchCase *SC, Counter TrueCnt, |
1063 | 0 | Counter FalseCnt) { |
1064 | | // Push region onto RegionStack but immediately pop it (which adds it to |
1065 | | // the function's SourceRegions) because it doesn't apply to any other |
1066 | | // source other than the SwitchCase. |
1067 | 0 | popRegions(pushRegion(TrueCnt, getStart(SC), SC->getColonLoc(), FalseCnt)); |
1068 | 0 | } |
1069 | | |
1070 | | /// Check whether a region with bounds \c StartLoc and \c EndLoc |
1071 | | /// is already added to \c SourceRegions. |
1072 | | bool isRegionAlreadyAdded(SourceLocation StartLoc, SourceLocation EndLoc, |
1073 | 0 | bool isBranch = false) { |
1074 | 0 | return llvm::any_of( |
1075 | 0 | llvm::reverse(SourceRegions), [&](const SourceMappingRegion &Region) { |
1076 | 0 | return Region.getBeginLoc() == StartLoc && |
1077 | 0 | Region.getEndLoc() == EndLoc && Region.isBranch() == isBranch; |
1078 | 0 | }); |
1079 | 0 | } |
1080 | | |
1081 | | /// Adjust the most recently visited location to \c EndLoc. |
1082 | | /// |
1083 | | /// This should be used after visiting any statements in non-source order. |
1084 | 0 | void adjustForOutOfOrderTraversal(SourceLocation EndLoc) { |
1085 | 0 | MostRecentLocation = EndLoc; |
1086 | | // The code region for a whole macro is created in handleFileExit() when |
1087 | | // it detects exiting of the virtual file of that macro. If we visited |
1088 | | // statements in non-source order, we might already have such a region |
1089 | | // added, for example, if a body of a loop is divided among multiple |
1090 | | // macros. Avoid adding duplicate regions in such case. |
1091 | 0 | if (getRegion().hasEndLoc() && |
1092 | 0 | MostRecentLocation == getEndOfFileOrMacro(MostRecentLocation) && |
1093 | 0 | isRegionAlreadyAdded(getStartOfFileOrMacro(MostRecentLocation), |
1094 | 0 | MostRecentLocation, getRegion().isBranch())) |
1095 | 0 | MostRecentLocation = getIncludeOrExpansionLoc(MostRecentLocation); |
1096 | 0 | } |
1097 | | |
1098 | | /// Adjust regions and state when \c NewLoc exits a file. |
1099 | | /// |
1100 | | /// If moving from our most recently tracked location to \c NewLoc exits any |
1101 | | /// files, this adjusts our current region stack and creates the file regions |
1102 | | /// for the exited file. |
1103 | 0 | void handleFileExit(SourceLocation NewLoc) { |
1104 | 0 | if (NewLoc.isInvalid() || |
1105 | 0 | SM.isWrittenInSameFile(MostRecentLocation, NewLoc)) |
1106 | 0 | return; |
1107 | | |
1108 | | // If NewLoc is not in a file that contains MostRecentLocation, walk up to |
1109 | | // find the common ancestor. |
1110 | 0 | SourceLocation LCA = NewLoc; |
1111 | 0 | FileID ParentFile = SM.getFileID(LCA); |
1112 | 0 | while (!isNestedIn(MostRecentLocation, ParentFile)) { |
1113 | 0 | LCA = getIncludeOrExpansionLoc(LCA); |
1114 | 0 | if (LCA.isInvalid() || SM.isWrittenInSameFile(LCA, MostRecentLocation)) { |
1115 | | // Since there isn't a common ancestor, no file was exited. We just need |
1116 | | // to adjust our location to the new file. |
1117 | 0 | MostRecentLocation = NewLoc; |
1118 | 0 | return; |
1119 | 0 | } |
1120 | 0 | ParentFile = SM.getFileID(LCA); |
1121 | 0 | } |
1122 | | |
1123 | 0 | llvm::SmallSet<SourceLocation, 8> StartLocs; |
1124 | 0 | std::optional<Counter> ParentCounter; |
1125 | 0 | for (SourceMappingRegion &I : llvm::reverse(RegionStack)) { |
1126 | 0 | if (!I.hasStartLoc()) |
1127 | 0 | continue; |
1128 | 0 | SourceLocation Loc = I.getBeginLoc(); |
1129 | 0 | if (!isNestedIn(Loc, ParentFile)) { |
1130 | 0 | ParentCounter = I.getCounter(); |
1131 | 0 | break; |
1132 | 0 | } |
1133 | | |
1134 | 0 | while (!SM.isInFileID(Loc, ParentFile)) { |
1135 | | // The most nested region for each start location is the one with the |
1136 | | // correct count. We avoid creating redundant regions by stopping once |
1137 | | // we've seen this region. |
1138 | 0 | if (StartLocs.insert(Loc).second) { |
1139 | 0 | if (I.isBranch()) |
1140 | 0 | SourceRegions.emplace_back( |
1141 | 0 | I.getCounter(), I.getFalseCounter(), |
1142 | 0 | MCDCParameters{0, 0, I.getMCDCParams().ID, |
1143 | 0 | I.getMCDCParams().TrueID, |
1144 | 0 | I.getMCDCParams().FalseID}, |
1145 | 0 | Loc, getEndOfFileOrMacro(Loc), I.isBranch()); |
1146 | 0 | else |
1147 | 0 | SourceRegions.emplace_back(I.getCounter(), Loc, |
1148 | 0 | getEndOfFileOrMacro(Loc)); |
1149 | 0 | } |
1150 | 0 | Loc = getIncludeOrExpansionLoc(Loc); |
1151 | 0 | } |
1152 | 0 | I.setStartLoc(getPreciseTokenLocEnd(Loc)); |
1153 | 0 | } |
1154 | |
|
1155 | 0 | if (ParentCounter) { |
1156 | | // If the file is contained completely by another region and doesn't |
1157 | | // immediately start its own region, the whole file gets a region |
1158 | | // corresponding to the parent. |
1159 | 0 | SourceLocation Loc = MostRecentLocation; |
1160 | 0 | while (isNestedIn(Loc, ParentFile)) { |
1161 | 0 | SourceLocation FileStart = getStartOfFileOrMacro(Loc); |
1162 | 0 | if (StartLocs.insert(FileStart).second) { |
1163 | 0 | SourceRegions.emplace_back(*ParentCounter, FileStart, |
1164 | 0 | getEndOfFileOrMacro(Loc)); |
1165 | 0 | assert(SpellingRegion(SM, SourceRegions.back()).isInSourceOrder()); |
1166 | 0 | } |
1167 | 0 | Loc = getIncludeOrExpansionLoc(Loc); |
1168 | 0 | } |
1169 | 0 | } |
1170 | |
|
1171 | 0 | MostRecentLocation = NewLoc; |
1172 | 0 | } |
1173 | | |
1174 | | /// Ensure that \c S is included in the current region. |
1175 | 0 | void extendRegion(const Stmt *S) { |
1176 | 0 | SourceMappingRegion &Region = getRegion(); |
1177 | 0 | SourceLocation StartLoc = getStart(S); |
1178 | |
|
1179 | 0 | handleFileExit(StartLoc); |
1180 | 0 | if (!Region.hasStartLoc()) |
1181 | 0 | Region.setStartLoc(StartLoc); |
1182 | 0 | } |
1183 | | |
1184 | | /// Mark \c S as a terminator, starting a zero region. |
1185 | 0 | void terminateRegion(const Stmt *S) { |
1186 | 0 | extendRegion(S); |
1187 | 0 | SourceMappingRegion &Region = getRegion(); |
1188 | 0 | SourceLocation EndLoc = getEnd(S); |
1189 | 0 | if (!Region.hasEndLoc()) |
1190 | 0 | Region.setEndLoc(EndLoc); |
1191 | 0 | pushRegion(Counter::getZero()); |
1192 | 0 | HasTerminateStmt = true; |
1193 | 0 | } |
1194 | | |
1195 | | /// Find a valid gap range between \p AfterLoc and \p BeforeLoc. |
1196 | | std::optional<SourceRange> findGapAreaBetween(SourceLocation AfterLoc, |
1197 | 0 | SourceLocation BeforeLoc) { |
1198 | | // If AfterLoc is in function-like macro, use the right parenthesis |
1199 | | // location. |
1200 | 0 | if (AfterLoc.isMacroID()) { |
1201 | 0 | FileID FID = SM.getFileID(AfterLoc); |
1202 | 0 | const SrcMgr::ExpansionInfo *EI = &SM.getSLocEntry(FID).getExpansion(); |
1203 | 0 | if (EI->isFunctionMacroExpansion()) |
1204 | 0 | AfterLoc = EI->getExpansionLocEnd(); |
1205 | 0 | } |
1206 | |
|
1207 | 0 | size_t StartDepth = locationDepth(AfterLoc); |
1208 | 0 | size_t EndDepth = locationDepth(BeforeLoc); |
1209 | 0 | while (!SM.isWrittenInSameFile(AfterLoc, BeforeLoc)) { |
1210 | 0 | bool UnnestStart = StartDepth >= EndDepth; |
1211 | 0 | bool UnnestEnd = EndDepth >= StartDepth; |
1212 | 0 | if (UnnestEnd) { |
1213 | 0 | assert(SM.isWrittenInSameFile(getStartOfFileOrMacro(BeforeLoc), |
1214 | 0 | BeforeLoc)); |
1215 | | |
1216 | 0 | BeforeLoc = getIncludeOrExpansionLoc(BeforeLoc); |
1217 | 0 | assert(BeforeLoc.isValid()); |
1218 | 0 | EndDepth--; |
1219 | 0 | } |
1220 | 0 | if (UnnestStart) { |
1221 | 0 | assert(SM.isWrittenInSameFile(AfterLoc, |
1222 | 0 | getEndOfFileOrMacro(AfterLoc))); |
1223 | | |
1224 | 0 | AfterLoc = getIncludeOrExpansionLoc(AfterLoc); |
1225 | 0 | assert(AfterLoc.isValid()); |
1226 | 0 | AfterLoc = getPreciseTokenLocEnd(AfterLoc); |
1227 | 0 | assert(AfterLoc.isValid()); |
1228 | 0 | StartDepth--; |
1229 | 0 | } |
1230 | 0 | } |
1231 | 0 | AfterLoc = getPreciseTokenLocEnd(AfterLoc); |
1232 | | // If the start and end locations of the gap are both within the same macro |
1233 | | // file, the range may not be in source order. |
1234 | 0 | if (AfterLoc.isMacroID() || BeforeLoc.isMacroID()) |
1235 | 0 | return std::nullopt; |
1236 | 0 | if (!SM.isWrittenInSameFile(AfterLoc, BeforeLoc) || |
1237 | 0 | !SpellingRegion(SM, AfterLoc, BeforeLoc).isInSourceOrder()) |
1238 | 0 | return std::nullopt; |
1239 | 0 | return {{AfterLoc, BeforeLoc}}; |
1240 | 0 | } |
1241 | | |
1242 | | /// Emit a gap region between \p StartLoc and \p EndLoc with the given count. |
1243 | | void fillGapAreaWithCount(SourceLocation StartLoc, SourceLocation EndLoc, |
1244 | 0 | Counter Count) { |
1245 | 0 | if (StartLoc == EndLoc) |
1246 | 0 | return; |
1247 | 0 | assert(SpellingRegion(SM, StartLoc, EndLoc).isInSourceOrder()); |
1248 | 0 | handleFileExit(StartLoc); |
1249 | 0 | size_t Index = pushRegion(Count, StartLoc, EndLoc); |
1250 | 0 | getRegion().setGap(true); |
1251 | 0 | handleFileExit(EndLoc); |
1252 | 0 | popRegions(Index); |
1253 | 0 | } |
1254 | | |
1255 | | /// Keep counts of breaks and continues inside loops. |
1256 | | struct BreakContinue { |
1257 | | Counter BreakCount; |
1258 | | Counter ContinueCount; |
1259 | | }; |
1260 | | SmallVector<BreakContinue, 8> BreakContinueStack; |
1261 | | |
1262 | | CounterCoverageMappingBuilder( |
1263 | | CoverageMappingModuleGen &CVM, |
1264 | | llvm::DenseMap<const Stmt *, unsigned> &CounterMap, |
1265 | | llvm::DenseMap<const Stmt *, unsigned> &MCDCBitmapMap, |
1266 | | llvm::DenseMap<const Stmt *, MCDCConditionID> &CondIDMap, |
1267 | | SourceManager &SM, const LangOptions &LangOpts) |
1268 | | : CoverageMappingBuilder(CVM, SM, LangOpts), CounterMap(CounterMap), |
1269 | | MCDCBitmapMap(MCDCBitmapMap), |
1270 | 0 | MCDCBuilder(CVM.getCodeGenModule(), CondIDMap, MCDCBitmapMap) {} |
1271 | | |
1272 | | /// Write the mapping data to the output stream |
1273 | 0 | void write(llvm::raw_ostream &OS) { |
1274 | 0 | llvm::SmallVector<unsigned, 8> VirtualFileMapping; |
1275 | 0 | gatherFileIDs(VirtualFileMapping); |
1276 | 0 | SourceRegionFilter Filter = emitExpansionRegions(); |
1277 | 0 | emitSourceRegions(Filter); |
1278 | 0 | gatherSkippedRegions(); |
1279 | |
|
1280 | 0 | if (MappingRegions.empty()) |
1281 | 0 | return; |
1282 | | |
1283 | 0 | CoverageMappingWriter Writer(VirtualFileMapping, Builder.getExpressions(), |
1284 | 0 | MappingRegions); |
1285 | 0 | Writer.write(OS); |
1286 | 0 | } |
1287 | | |
1288 | 0 | void VisitStmt(const Stmt *S) { |
1289 | 0 | if (S->getBeginLoc().isValid()) |
1290 | 0 | extendRegion(S); |
1291 | 0 | const Stmt *LastStmt = nullptr; |
1292 | 0 | bool SaveTerminateStmt = HasTerminateStmt; |
1293 | 0 | HasTerminateStmt = false; |
1294 | 0 | GapRegionCounter = Counter::getZero(); |
1295 | 0 | for (const Stmt *Child : S->children()) |
1296 | 0 | if (Child) { |
1297 | | // If last statement contains terminate statements, add a gap area |
1298 | | // between the two statements. Skipping attributed statements, because |
1299 | | // they don't have valid start location. |
1300 | 0 | if (LastStmt && HasTerminateStmt && !isa<AttributedStmt>(Child)) { |
1301 | 0 | auto Gap = findGapAreaBetween(getEnd(LastStmt), getStart(Child)); |
1302 | 0 | if (Gap) |
1303 | 0 | fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), |
1304 | 0 | GapRegionCounter); |
1305 | 0 | SaveTerminateStmt = true; |
1306 | 0 | HasTerminateStmt = false; |
1307 | 0 | } |
1308 | 0 | this->Visit(Child); |
1309 | 0 | LastStmt = Child; |
1310 | 0 | } |
1311 | 0 | if (SaveTerminateStmt) |
1312 | 0 | HasTerminateStmt = true; |
1313 | 0 | handleFileExit(getEnd(S)); |
1314 | 0 | } |
1315 | | |
1316 | 0 | void VisitDecl(const Decl *D) { |
1317 | 0 | Stmt *Body = D->getBody(); |
1318 | | |
1319 | | // Do not propagate region counts into system headers unless collecting |
1320 | | // coverage from system headers is explicitly enabled. |
1321 | 0 | if (!SystemHeadersCoverage && Body && |
1322 | 0 | SM.isInSystemHeader(SM.getSpellingLoc(getStart(Body)))) |
1323 | 0 | return; |
1324 | | |
1325 | | // Do not visit the artificial children nodes of defaulted methods. The |
1326 | | // lexer may not be able to report back precise token end locations for |
1327 | | // these children nodes (llvm.org/PR39822), and moreover users will not be |
1328 | | // able to see coverage for them. |
1329 | 0 | Counter BodyCounter = getRegionCounter(Body); |
1330 | 0 | bool Defaulted = false; |
1331 | 0 | if (auto *Method = dyn_cast<CXXMethodDecl>(D)) |
1332 | 0 | Defaulted = Method->isDefaulted(); |
1333 | 0 | if (auto *Ctor = dyn_cast<CXXConstructorDecl>(D)) { |
1334 | 0 | for (auto *Initializer : Ctor->inits()) { |
1335 | 0 | if (Initializer->isWritten()) { |
1336 | 0 | auto *Init = Initializer->getInit(); |
1337 | 0 | if (getStart(Init).isValid() && getEnd(Init).isValid()) |
1338 | 0 | propagateCounts(BodyCounter, Init); |
1339 | 0 | } |
1340 | 0 | } |
1341 | 0 | } |
1342 | |
|
1343 | 0 | propagateCounts(BodyCounter, Body, |
1344 | 0 | /*VisitChildren=*/!Defaulted); |
1345 | 0 | assert(RegionStack.empty() && "Regions entered but never exited"); |
1346 | 0 | } |
1347 | | |
1348 | 0 | void VisitReturnStmt(const ReturnStmt *S) { |
1349 | 0 | extendRegion(S); |
1350 | 0 | if (S->getRetValue()) |
1351 | 0 | Visit(S->getRetValue()); |
1352 | 0 | terminateRegion(S); |
1353 | 0 | } |
1354 | | |
1355 | 0 | void VisitCoroutineBodyStmt(const CoroutineBodyStmt *S) { |
1356 | 0 | extendRegion(S); |
1357 | 0 | Visit(S->getBody()); |
1358 | 0 | } |
1359 | | |
1360 | 0 | void VisitCoreturnStmt(const CoreturnStmt *S) { |
1361 | 0 | extendRegion(S); |
1362 | 0 | if (S->getOperand()) |
1363 | 0 | Visit(S->getOperand()); |
1364 | 0 | terminateRegion(S); |
1365 | 0 | } |
1366 | | |
1367 | 0 | void VisitCXXThrowExpr(const CXXThrowExpr *E) { |
1368 | 0 | extendRegion(E); |
1369 | 0 | if (E->getSubExpr()) |
1370 | 0 | Visit(E->getSubExpr()); |
1371 | 0 | terminateRegion(E); |
1372 | 0 | } |
1373 | | |
1374 | 0 | void VisitGotoStmt(const GotoStmt *S) { terminateRegion(S); } |
1375 | | |
1376 | 0 | void VisitLabelStmt(const LabelStmt *S) { |
1377 | 0 | Counter LabelCount = getRegionCounter(S); |
1378 | 0 | SourceLocation Start = getStart(S); |
1379 | | // We can't extendRegion here or we risk overlapping with our new region. |
1380 | 0 | handleFileExit(Start); |
1381 | 0 | pushRegion(LabelCount, Start); |
1382 | 0 | Visit(S->getSubStmt()); |
1383 | 0 | } |
1384 | | |
1385 | 0 | void VisitBreakStmt(const BreakStmt *S) { |
1386 | 0 | assert(!BreakContinueStack.empty() && "break not in a loop or switch!"); |
1387 | 0 | BreakContinueStack.back().BreakCount = addCounters( |
1388 | 0 | BreakContinueStack.back().BreakCount, getRegion().getCounter()); |
1389 | | // FIXME: a break in a switch should terminate regions for all preceding |
1390 | | // case statements, not just the most recent one. |
1391 | 0 | terminateRegion(S); |
1392 | 0 | } |
1393 | | |
1394 | 0 | void VisitContinueStmt(const ContinueStmt *S) { |
1395 | 0 | assert(!BreakContinueStack.empty() && "continue stmt not in a loop!"); |
1396 | 0 | BreakContinueStack.back().ContinueCount = addCounters( |
1397 | 0 | BreakContinueStack.back().ContinueCount, getRegion().getCounter()); |
1398 | 0 | terminateRegion(S); |
1399 | 0 | } |
1400 | | |
1401 | 0 | void VisitCallExpr(const CallExpr *E) { |
1402 | 0 | VisitStmt(E); |
1403 | | |
1404 | | // Terminate the region when we hit a noreturn function. |
1405 | | // (This is helpful dealing with switch statements.) |
1406 | 0 | QualType CalleeType = E->getCallee()->getType(); |
1407 | 0 | if (getFunctionExtInfo(*CalleeType).getNoReturn()) |
1408 | 0 | terminateRegion(E); |
1409 | 0 | } |
1410 | | |
1411 | 0 | void VisitWhileStmt(const WhileStmt *S) { |
1412 | 0 | extendRegion(S); |
1413 | |
|
1414 | 0 | Counter ParentCount = getRegion().getCounter(); |
1415 | 0 | Counter BodyCount = getRegionCounter(S); |
1416 | | |
1417 | | // Handle the body first so that we can get the backedge count. |
1418 | 0 | BreakContinueStack.push_back(BreakContinue()); |
1419 | 0 | extendRegion(S->getBody()); |
1420 | 0 | Counter BackedgeCount = propagateCounts(BodyCount, S->getBody()); |
1421 | 0 | BreakContinue BC = BreakContinueStack.pop_back_val(); |
1422 | |
|
1423 | 0 | bool BodyHasTerminateStmt = HasTerminateStmt; |
1424 | 0 | HasTerminateStmt = false; |
1425 | | |
1426 | | // Go back to handle the condition. |
1427 | 0 | Counter CondCount = |
1428 | 0 | addCounters(ParentCount, BackedgeCount, BC.ContinueCount); |
1429 | 0 | propagateCounts(CondCount, S->getCond()); |
1430 | 0 | adjustForOutOfOrderTraversal(getEnd(S)); |
1431 | | |
1432 | | // The body count applies to the area immediately after the increment. |
1433 | 0 | auto Gap = findGapAreaBetween(S->getRParenLoc(), getStart(S->getBody())); |
1434 | 0 | if (Gap) |
1435 | 0 | fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount); |
1436 | |
|
1437 | 0 | Counter OutCount = |
1438 | 0 | addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount)); |
1439 | 0 | if (OutCount != ParentCount) { |
1440 | 0 | pushRegion(OutCount); |
1441 | 0 | GapRegionCounter = OutCount; |
1442 | 0 | if (BodyHasTerminateStmt) |
1443 | 0 | HasTerminateStmt = true; |
1444 | 0 | } |
1445 | | |
1446 | | // Create Branch Region around condition. |
1447 | 0 | createBranchRegion(S->getCond(), BodyCount, |
1448 | 0 | subtractCounters(CondCount, BodyCount)); |
1449 | 0 | } |
1450 | | |
1451 | 0 | void VisitDoStmt(const DoStmt *S) { |
1452 | 0 | extendRegion(S); |
1453 | |
|
1454 | 0 | Counter ParentCount = getRegion().getCounter(); |
1455 | 0 | Counter BodyCount = getRegionCounter(S); |
1456 | |
|
1457 | 0 | BreakContinueStack.push_back(BreakContinue()); |
1458 | 0 | extendRegion(S->getBody()); |
1459 | 0 | Counter BackedgeCount = |
1460 | 0 | propagateCounts(addCounters(ParentCount, BodyCount), S->getBody()); |
1461 | 0 | BreakContinue BC = BreakContinueStack.pop_back_val(); |
1462 | |
|
1463 | 0 | bool BodyHasTerminateStmt = HasTerminateStmt; |
1464 | 0 | HasTerminateStmt = false; |
1465 | |
|
1466 | 0 | Counter CondCount = addCounters(BackedgeCount, BC.ContinueCount); |
1467 | 0 | propagateCounts(CondCount, S->getCond()); |
1468 | |
|
1469 | 0 | Counter OutCount = |
1470 | 0 | addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount)); |
1471 | 0 | if (OutCount != ParentCount) { |
1472 | 0 | pushRegion(OutCount); |
1473 | 0 | GapRegionCounter = OutCount; |
1474 | 0 | } |
1475 | | |
1476 | | // Create Branch Region around condition. |
1477 | 0 | createBranchRegion(S->getCond(), BodyCount, |
1478 | 0 | subtractCounters(CondCount, BodyCount)); |
1479 | |
|
1480 | 0 | if (BodyHasTerminateStmt) |
1481 | 0 | HasTerminateStmt = true; |
1482 | 0 | } |
1483 | | |
1484 | 0 | void VisitForStmt(const ForStmt *S) { |
1485 | 0 | extendRegion(S); |
1486 | 0 | if (S->getInit()) |
1487 | 0 | Visit(S->getInit()); |
1488 | |
|
1489 | 0 | Counter ParentCount = getRegion().getCounter(); |
1490 | 0 | Counter BodyCount = getRegionCounter(S); |
1491 | | |
1492 | | // The loop increment may contain a break or continue. |
1493 | 0 | if (S->getInc()) |
1494 | 0 | BreakContinueStack.emplace_back(); |
1495 | | |
1496 | | // Handle the body first so that we can get the backedge count. |
1497 | 0 | BreakContinueStack.emplace_back(); |
1498 | 0 | extendRegion(S->getBody()); |
1499 | 0 | Counter BackedgeCount = propagateCounts(BodyCount, S->getBody()); |
1500 | 0 | BreakContinue BodyBC = BreakContinueStack.pop_back_val(); |
1501 | |
|
1502 | 0 | bool BodyHasTerminateStmt = HasTerminateStmt; |
1503 | 0 | HasTerminateStmt = false; |
1504 | | |
1505 | | // The increment is essentially part of the body but it needs to include |
1506 | | // the count for all the continue statements. |
1507 | 0 | BreakContinue IncrementBC; |
1508 | 0 | if (const Stmt *Inc = S->getInc()) { |
1509 | 0 | propagateCounts(addCounters(BackedgeCount, BodyBC.ContinueCount), Inc); |
1510 | 0 | IncrementBC = BreakContinueStack.pop_back_val(); |
1511 | 0 | } |
1512 | | |
1513 | | // Go back to handle the condition. |
1514 | 0 | Counter CondCount = addCounters( |
1515 | 0 | addCounters(ParentCount, BackedgeCount, BodyBC.ContinueCount), |
1516 | 0 | IncrementBC.ContinueCount); |
1517 | 0 | if (const Expr *Cond = S->getCond()) { |
1518 | 0 | propagateCounts(CondCount, Cond); |
1519 | 0 | adjustForOutOfOrderTraversal(getEnd(S)); |
1520 | 0 | } |
1521 | | |
1522 | | // The body count applies to the area immediately after the increment. |
1523 | 0 | auto Gap = findGapAreaBetween(S->getRParenLoc(), getStart(S->getBody())); |
1524 | 0 | if (Gap) |
1525 | 0 | fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount); |
1526 | |
|
1527 | 0 | Counter OutCount = addCounters(BodyBC.BreakCount, IncrementBC.BreakCount, |
1528 | 0 | subtractCounters(CondCount, BodyCount)); |
1529 | 0 | if (OutCount != ParentCount) { |
1530 | 0 | pushRegion(OutCount); |
1531 | 0 | GapRegionCounter = OutCount; |
1532 | 0 | if (BodyHasTerminateStmt) |
1533 | 0 | HasTerminateStmt = true; |
1534 | 0 | } |
1535 | | |
1536 | | // Create Branch Region around condition. |
1537 | 0 | createBranchRegion(S->getCond(), BodyCount, |
1538 | 0 | subtractCounters(CondCount, BodyCount)); |
1539 | 0 | } |
1540 | | |
1541 | 0 | void VisitCXXForRangeStmt(const CXXForRangeStmt *S) { |
1542 | 0 | extendRegion(S); |
1543 | 0 | if (S->getInit()) |
1544 | 0 | Visit(S->getInit()); |
1545 | 0 | Visit(S->getLoopVarStmt()); |
1546 | 0 | Visit(S->getRangeStmt()); |
1547 | |
|
1548 | 0 | Counter ParentCount = getRegion().getCounter(); |
1549 | 0 | Counter BodyCount = getRegionCounter(S); |
1550 | |
|
1551 | 0 | BreakContinueStack.push_back(BreakContinue()); |
1552 | 0 | extendRegion(S->getBody()); |
1553 | 0 | Counter BackedgeCount = propagateCounts(BodyCount, S->getBody()); |
1554 | 0 | BreakContinue BC = BreakContinueStack.pop_back_val(); |
1555 | |
|
1556 | 0 | bool BodyHasTerminateStmt = HasTerminateStmt; |
1557 | 0 | HasTerminateStmt = false; |
1558 | | |
1559 | | // The body count applies to the area immediately after the range. |
1560 | 0 | auto Gap = findGapAreaBetween(S->getRParenLoc(), getStart(S->getBody())); |
1561 | 0 | if (Gap) |
1562 | 0 | fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount); |
1563 | |
|
1564 | 0 | Counter LoopCount = |
1565 | 0 | addCounters(ParentCount, BackedgeCount, BC.ContinueCount); |
1566 | 0 | Counter OutCount = |
1567 | 0 | addCounters(BC.BreakCount, subtractCounters(LoopCount, BodyCount)); |
1568 | 0 | if (OutCount != ParentCount) { |
1569 | 0 | pushRegion(OutCount); |
1570 | 0 | GapRegionCounter = OutCount; |
1571 | 0 | if (BodyHasTerminateStmt) |
1572 | 0 | HasTerminateStmt = true; |
1573 | 0 | } |
1574 | | |
1575 | | // Create Branch Region around condition. |
1576 | 0 | createBranchRegion(S->getCond(), BodyCount, |
1577 | 0 | subtractCounters(LoopCount, BodyCount)); |
1578 | 0 | } |
1579 | | |
1580 | 0 | void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) { |
1581 | 0 | extendRegion(S); |
1582 | 0 | Visit(S->getElement()); |
1583 | |
|
1584 | 0 | Counter ParentCount = getRegion().getCounter(); |
1585 | 0 | Counter BodyCount = getRegionCounter(S); |
1586 | |
|
1587 | 0 | BreakContinueStack.push_back(BreakContinue()); |
1588 | 0 | extendRegion(S->getBody()); |
1589 | 0 | Counter BackedgeCount = propagateCounts(BodyCount, S->getBody()); |
1590 | 0 | BreakContinue BC = BreakContinueStack.pop_back_val(); |
1591 | | |
1592 | | // The body count applies to the area immediately after the collection. |
1593 | 0 | auto Gap = findGapAreaBetween(S->getRParenLoc(), getStart(S->getBody())); |
1594 | 0 | if (Gap) |
1595 | 0 | fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount); |
1596 | |
|
1597 | 0 | Counter LoopCount = |
1598 | 0 | addCounters(ParentCount, BackedgeCount, BC.ContinueCount); |
1599 | 0 | Counter OutCount = |
1600 | 0 | addCounters(BC.BreakCount, subtractCounters(LoopCount, BodyCount)); |
1601 | 0 | if (OutCount != ParentCount) { |
1602 | 0 | pushRegion(OutCount); |
1603 | 0 | GapRegionCounter = OutCount; |
1604 | 0 | } |
1605 | 0 | } |
1606 | | |
1607 | 0 | void VisitSwitchStmt(const SwitchStmt *S) { |
1608 | 0 | extendRegion(S); |
1609 | 0 | if (S->getInit()) |
1610 | 0 | Visit(S->getInit()); |
1611 | 0 | Visit(S->getCond()); |
1612 | |
|
1613 | 0 | BreakContinueStack.push_back(BreakContinue()); |
1614 | |
|
1615 | 0 | const Stmt *Body = S->getBody(); |
1616 | 0 | extendRegion(Body); |
1617 | 0 | if (const auto *CS = dyn_cast<CompoundStmt>(Body)) { |
1618 | 0 | if (!CS->body_empty()) { |
1619 | | // Make a region for the body of the switch. If the body starts with |
1620 | | // a case, that case will reuse this region; otherwise, this covers |
1621 | | // the unreachable code at the beginning of the switch body. |
1622 | 0 | size_t Index = pushRegion(Counter::getZero(), getStart(CS)); |
1623 | 0 | getRegion().setGap(true); |
1624 | 0 | Visit(Body); |
1625 | | |
1626 | | // Set the end for the body of the switch, if it isn't already set. |
1627 | 0 | for (size_t i = RegionStack.size(); i != Index; --i) { |
1628 | 0 | if (!RegionStack[i - 1].hasEndLoc()) |
1629 | 0 | RegionStack[i - 1].setEndLoc(getEnd(CS->body_back())); |
1630 | 0 | } |
1631 | |
|
1632 | 0 | popRegions(Index); |
1633 | 0 | } |
1634 | 0 | } else |
1635 | 0 | propagateCounts(Counter::getZero(), Body); |
1636 | 0 | BreakContinue BC = BreakContinueStack.pop_back_val(); |
1637 | |
|
1638 | 0 | if (!BreakContinueStack.empty()) |
1639 | 0 | BreakContinueStack.back().ContinueCount = addCounters( |
1640 | 0 | BreakContinueStack.back().ContinueCount, BC.ContinueCount); |
1641 | |
|
1642 | 0 | Counter ParentCount = getRegion().getCounter(); |
1643 | 0 | Counter ExitCount = getRegionCounter(S); |
1644 | 0 | SourceLocation ExitLoc = getEnd(S); |
1645 | 0 | pushRegion(ExitCount); |
1646 | 0 | GapRegionCounter = ExitCount; |
1647 | | |
1648 | | // Ensure that handleFileExit recognizes when the end location is located |
1649 | | // in a different file. |
1650 | 0 | MostRecentLocation = getStart(S); |
1651 | 0 | handleFileExit(ExitLoc); |
1652 | | |
1653 | | // Create a Branch Region around each Case. Subtract the case's |
1654 | | // counter from the Parent counter to track the "False" branch count. |
1655 | 0 | Counter CaseCountSum; |
1656 | 0 | bool HasDefaultCase = false; |
1657 | 0 | const SwitchCase *Case = S->getSwitchCaseList(); |
1658 | 0 | for (; Case; Case = Case->getNextSwitchCase()) { |
1659 | 0 | HasDefaultCase = HasDefaultCase || isa<DefaultStmt>(Case); |
1660 | 0 | CaseCountSum = |
1661 | 0 | addCounters(CaseCountSum, getRegionCounter(Case), /*Simplify=*/false); |
1662 | 0 | createSwitchCaseRegion( |
1663 | 0 | Case, getRegionCounter(Case), |
1664 | 0 | subtractCounters(ParentCount, getRegionCounter(Case))); |
1665 | 0 | } |
1666 | | // Simplify is skipped while building the counters above: it can get really |
1667 | | // slow on top of switches with thousands of cases. Instead, trigger |
1668 | | // simplification by adding zero to the last counter. |
1669 | 0 | CaseCountSum = addCounters(CaseCountSum, Counter::getZero()); |
1670 | | |
1671 | | // If no explicit default case exists, create a branch region to represent |
1672 | | // the hidden branch, which will be added later by the CodeGen. This region |
1673 | | // will be associated with the switch statement's condition. |
1674 | 0 | if (!HasDefaultCase) { |
1675 | 0 | Counter DefaultTrue = subtractCounters(ParentCount, CaseCountSum); |
1676 | 0 | Counter DefaultFalse = subtractCounters(ParentCount, DefaultTrue); |
1677 | 0 | createBranchRegion(S->getCond(), DefaultTrue, DefaultFalse); |
1678 | 0 | } |
1679 | 0 | } |
1680 | | |
1681 | 0 | void VisitSwitchCase(const SwitchCase *S) { |
1682 | 0 | extendRegion(S); |
1683 | |
|
1684 | 0 | SourceMappingRegion &Parent = getRegion(); |
1685 | |
|
1686 | 0 | Counter Count = addCounters(Parent.getCounter(), getRegionCounter(S)); |
1687 | | // Reuse the existing region if it starts at our label. This is typical of |
1688 | | // the first case in a switch. |
1689 | 0 | if (Parent.hasStartLoc() && Parent.getBeginLoc() == getStart(S)) |
1690 | 0 | Parent.setCounter(Count); |
1691 | 0 | else |
1692 | 0 | pushRegion(Count, getStart(S)); |
1693 | |
|
1694 | 0 | GapRegionCounter = Count; |
1695 | |
|
1696 | 0 | if (const auto *CS = dyn_cast<CaseStmt>(S)) { |
1697 | 0 | Visit(CS->getLHS()); |
1698 | 0 | if (const Expr *RHS = CS->getRHS()) |
1699 | 0 | Visit(RHS); |
1700 | 0 | } |
1701 | 0 | Visit(S->getSubStmt()); |
1702 | 0 | } |
1703 | | |
1704 | 0 | void VisitIfStmt(const IfStmt *S) { |
1705 | 0 | extendRegion(S); |
1706 | 0 | if (S->getInit()) |
1707 | 0 | Visit(S->getInit()); |
1708 | | |
1709 | | // Extend into the condition before we propagate through it below - this is |
1710 | | // needed to handle macros that generate the "if" but not the condition. |
1711 | 0 | if (!S->isConsteval()) |
1712 | 0 | extendRegion(S->getCond()); |
1713 | |
|
1714 | 0 | Counter ParentCount = getRegion().getCounter(); |
1715 | | |
1716 | | // If this is "if !consteval" the then-branch will never be taken, we don't |
1717 | | // need to change counter |
1718 | 0 | Counter ThenCount = |
1719 | 0 | S->isNegatedConsteval() ? ParentCount : getRegionCounter(S); |
1720 | |
|
1721 | 0 | if (!S->isConsteval()) { |
1722 | | // Emitting a counter for the condition makes it easier to interpret the |
1723 | | // counter for the body when looking at the coverage. |
1724 | 0 | propagateCounts(ParentCount, S->getCond()); |
1725 | | |
1726 | | // The 'then' count applies to the area immediately after the condition. |
1727 | 0 | std::optional<SourceRange> Gap = |
1728 | 0 | findGapAreaBetween(S->getRParenLoc(), getStart(S->getThen())); |
1729 | 0 | if (Gap) |
1730 | 0 | fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), ThenCount); |
1731 | 0 | } |
1732 | |
|
1733 | 0 | extendRegion(S->getThen()); |
1734 | 0 | Counter OutCount = propagateCounts(ThenCount, S->getThen()); |
1735 | | |
1736 | | // If this is "if consteval" the else-branch will never be taken, we don't |
1737 | | // need to change counter |
1738 | 0 | Counter ElseCount = S->isNonNegatedConsteval() |
1739 | 0 | ? ParentCount |
1740 | 0 | : subtractCounters(ParentCount, ThenCount); |
1741 | |
|
1742 | 0 | if (const Stmt *Else = S->getElse()) { |
1743 | 0 | bool ThenHasTerminateStmt = HasTerminateStmt; |
1744 | 0 | HasTerminateStmt = false; |
1745 | | // The 'else' count applies to the area immediately after the 'then'. |
1746 | 0 | std::optional<SourceRange> Gap = |
1747 | 0 | findGapAreaBetween(getEnd(S->getThen()), getStart(Else)); |
1748 | 0 | if (Gap) |
1749 | 0 | fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), ElseCount); |
1750 | 0 | extendRegion(Else); |
1751 | 0 | OutCount = addCounters(OutCount, propagateCounts(ElseCount, Else)); |
1752 | |
|
1753 | 0 | if (ThenHasTerminateStmt) |
1754 | 0 | HasTerminateStmt = true; |
1755 | 0 | } else |
1756 | 0 | OutCount = addCounters(OutCount, ElseCount); |
1757 | |
|
1758 | 0 | if (OutCount != ParentCount) { |
1759 | 0 | pushRegion(OutCount); |
1760 | 0 | GapRegionCounter = OutCount; |
1761 | 0 | } |
1762 | |
|
1763 | 0 | if (!S->isConsteval()) { |
1764 | | // Create Branch Region around condition. |
1765 | 0 | createBranchRegion(S->getCond(), ThenCount, |
1766 | 0 | subtractCounters(ParentCount, ThenCount)); |
1767 | 0 | } |
1768 | 0 | } |
1769 | | |
1770 | 0 | void VisitCXXTryStmt(const CXXTryStmt *S) { |
1771 | 0 | extendRegion(S); |
1772 | | // Handle macros that generate the "try" but not the rest. |
1773 | 0 | extendRegion(S->getTryBlock()); |
1774 | |
|
1775 | 0 | Counter ParentCount = getRegion().getCounter(); |
1776 | 0 | propagateCounts(ParentCount, S->getTryBlock()); |
1777 | |
|
1778 | 0 | for (unsigned I = 0, E = S->getNumHandlers(); I < E; ++I) |
1779 | 0 | Visit(S->getHandler(I)); |
1780 | |
|
1781 | 0 | Counter ExitCount = getRegionCounter(S); |
1782 | 0 | pushRegion(ExitCount); |
1783 | 0 | } |
1784 | | |
1785 | 0 | void VisitCXXCatchStmt(const CXXCatchStmt *S) { |
1786 | 0 | propagateCounts(getRegionCounter(S), S->getHandlerBlock()); |
1787 | 0 | } |
1788 | | |
1789 | 0 | void VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) { |
1790 | 0 | extendRegion(E); |
1791 | |
|
1792 | 0 | Counter ParentCount = getRegion().getCounter(); |
1793 | 0 | Counter TrueCount = getRegionCounter(E); |
1794 | |
|
1795 | 0 | propagateCounts(ParentCount, E->getCond()); |
1796 | 0 | Counter OutCount; |
1797 | |
|
1798 | 0 | if (!isa<BinaryConditionalOperator>(E)) { |
1799 | | // The 'then' count applies to the area immediately after the condition. |
1800 | 0 | auto Gap = |
1801 | 0 | findGapAreaBetween(E->getQuestionLoc(), getStart(E->getTrueExpr())); |
1802 | 0 | if (Gap) |
1803 | 0 | fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), TrueCount); |
1804 | |
|
1805 | 0 | extendRegion(E->getTrueExpr()); |
1806 | 0 | OutCount = propagateCounts(TrueCount, E->getTrueExpr()); |
1807 | 0 | } |
1808 | |
|
1809 | 0 | extendRegion(E->getFalseExpr()); |
1810 | 0 | OutCount = addCounters( |
1811 | 0 | OutCount, propagateCounts(subtractCounters(ParentCount, TrueCount), |
1812 | 0 | E->getFalseExpr())); |
1813 | |
|
1814 | 0 | if (OutCount != ParentCount) { |
1815 | 0 | pushRegion(OutCount); |
1816 | 0 | GapRegionCounter = OutCount; |
1817 | 0 | } |
1818 | | |
1819 | | // Create Branch Region around condition. |
1820 | 0 | createBranchRegion(E->getCond(), TrueCount, |
1821 | 0 | subtractCounters(ParentCount, TrueCount)); |
1822 | 0 | } |
1823 | | |
1824 | 0 | void VisitBinLAnd(const BinaryOperator *E) { |
1825 | | // Keep track of Binary Operator and assign MCDC condition IDs |
1826 | 0 | MCDCBuilder.pushAndAssignIDs(E); |
1827 | |
|
1828 | 0 | extendRegion(E->getLHS()); |
1829 | 0 | propagateCounts(getRegion().getCounter(), E->getLHS()); |
1830 | 0 | handleFileExit(getEnd(E->getLHS())); |
1831 | | |
1832 | | // Counter tracks the right hand side of a logical and operator. |
1833 | 0 | extendRegion(E->getRHS()); |
1834 | 0 | propagateCounts(getRegionCounter(E), E->getRHS()); |
1835 | | |
1836 | | // Process Binary Operator and create MCDC Decision Region if top-level |
1837 | 0 | unsigned NumConds = 0; |
1838 | 0 | if ((NumConds = MCDCBuilder.popAndReturnCondCount(E))) |
1839 | 0 | createDecisionRegion(E, getRegionBitmap(E), NumConds); |
1840 | | |
1841 | | // Extract the RHS's Execution Counter. |
1842 | 0 | Counter RHSExecCnt = getRegionCounter(E); |
1843 | | |
1844 | | // Extract the RHS's "True" Instance Counter. |
1845 | 0 | Counter RHSTrueCnt = getRegionCounter(E->getRHS()); |
1846 | | |
1847 | | // Extract the Parent Region Counter. |
1848 | 0 | Counter ParentCnt = getRegion().getCounter(); |
1849 | | |
1850 | | // Extract the MCDC condition IDs (returns 0 if not needed). |
1851 | 0 | MCDCConditionID NextOrID = MCDCBuilder.getNextLOrCondID(); |
1852 | 0 | MCDCConditionID NextAndID = MCDCBuilder.getNextLAndCondID(); |
1853 | 0 | MCDCConditionID LHSid = MCDCBuilder.getCondID(E->getLHS()); |
1854 | 0 | MCDCConditionID RHSid = MCDCBuilder.getCondID(E->getRHS()); |
1855 | | |
1856 | | // Create Branch Region around LHS condition. |
1857 | | // MC/DC: For "LHS && RHS" |
1858 | | // - If LHS is TRUE, execution goes to the RHS. |
1859 | | // - If LHS is FALSE, execution goes to the LHS of the next logical-OR. |
1860 | | // If that does not exist, execution exits (ID == 0). |
1861 | 0 | createBranchRegion(E->getLHS(), RHSExecCnt, |
1862 | 0 | subtractCounters(ParentCnt, RHSExecCnt), LHSid, RHSid, |
1863 | 0 | NextOrID); |
1864 | | |
1865 | | // Create Branch Region around RHS condition. |
1866 | | // MC/DC: For "LHS && RHS" |
1867 | | // - If RHS is TRUE, execution goes to LHS of the next logical-AND. |
1868 | | // If that does not exist, execution exits (ID == 0). |
1869 | | // - If RHS is FALSE, execution goes to the LHS of the next logical-OR. |
1870 | | // If that does not exist, execution exits (ID == 0). |
1871 | 0 | createBranchRegion(E->getRHS(), RHSTrueCnt, |
1872 | 0 | subtractCounters(RHSExecCnt, RHSTrueCnt), RHSid, |
1873 | 0 | NextAndID, NextOrID); |
1874 | 0 | } |
1875 | | |
1876 | | // Determine whether the right side of OR operation need to be visited. |
1877 | 0 | bool shouldVisitRHS(const Expr *LHS) { |
1878 | 0 | bool LHSIsTrue = false; |
1879 | 0 | bool LHSIsConst = false; |
1880 | 0 | if (!LHS->isValueDependent()) |
1881 | 0 | LHSIsConst = LHS->EvaluateAsBooleanCondition( |
1882 | 0 | LHSIsTrue, CVM.getCodeGenModule().getContext()); |
1883 | 0 | return !LHSIsConst || (LHSIsConst && !LHSIsTrue); |
1884 | 0 | } |
1885 | | |
1886 | 0 | void VisitBinLOr(const BinaryOperator *E) { |
1887 | | // Keep track of Binary Operator and assign MCDC condition IDs |
1888 | 0 | MCDCBuilder.pushAndAssignIDs(E); |
1889 | |
|
1890 | 0 | extendRegion(E->getLHS()); |
1891 | 0 | Counter OutCount = propagateCounts(getRegion().getCounter(), E->getLHS()); |
1892 | 0 | handleFileExit(getEnd(E->getLHS())); |
1893 | | |
1894 | | // Counter tracks the right hand side of a logical or operator. |
1895 | 0 | extendRegion(E->getRHS()); |
1896 | 0 | propagateCounts(getRegionCounter(E), E->getRHS()); |
1897 | | |
1898 | | // Process Binary Operator and create MCDC Decision Region if top-level |
1899 | 0 | unsigned NumConds = 0; |
1900 | 0 | if ((NumConds = MCDCBuilder.popAndReturnCondCount(E))) |
1901 | 0 | createDecisionRegion(E, getRegionBitmap(E), NumConds); |
1902 | | |
1903 | | // Extract the RHS's Execution Counter. |
1904 | 0 | Counter RHSExecCnt = getRegionCounter(E); |
1905 | | |
1906 | | // Extract the RHS's "False" Instance Counter. |
1907 | 0 | Counter RHSFalseCnt = getRegionCounter(E->getRHS()); |
1908 | |
|
1909 | 0 | if (!shouldVisitRHS(E->getLHS())) { |
1910 | 0 | GapRegionCounter = OutCount; |
1911 | 0 | } |
1912 | | |
1913 | | // Extract the Parent Region Counter. |
1914 | 0 | Counter ParentCnt = getRegion().getCounter(); |
1915 | | |
1916 | | // Extract the MCDC condition IDs (returns 0 if not needed). |
1917 | 0 | MCDCConditionID NextOrID = MCDCBuilder.getNextLOrCondID(); |
1918 | 0 | MCDCConditionID NextAndID = MCDCBuilder.getNextLAndCondID(); |
1919 | 0 | MCDCConditionID LHSid = MCDCBuilder.getCondID(E->getLHS()); |
1920 | 0 | MCDCConditionID RHSid = MCDCBuilder.getCondID(E->getRHS()); |
1921 | | |
1922 | | // Create Branch Region around LHS condition. |
1923 | | // MC/DC: For "LHS || RHS" |
1924 | | // - If LHS is TRUE, execution goes to the LHS of the next logical-AND. |
1925 | | // If that does not exist, execution exits (ID == 0). |
1926 | | // - If LHS is FALSE, execution goes to the RHS. |
1927 | 0 | createBranchRegion(E->getLHS(), subtractCounters(ParentCnt, RHSExecCnt), |
1928 | 0 | RHSExecCnt, LHSid, NextAndID, RHSid); |
1929 | | |
1930 | | // Create Branch Region around RHS condition. |
1931 | | // MC/DC: For "LHS || RHS" |
1932 | | // - If RHS is TRUE, execution goes to LHS of the next logical-AND. |
1933 | | // If that does not exist, execution exits (ID == 0). |
1934 | | // - If RHS is FALSE, execution goes to the LHS of the next logical-OR. |
1935 | | // If that does not exist, execution exits (ID == 0). |
1936 | 0 | createBranchRegion(E->getRHS(), subtractCounters(RHSExecCnt, RHSFalseCnt), |
1937 | 0 | RHSFalseCnt, RHSid, NextAndID, NextOrID); |
1938 | 0 | } |
1939 | | |
1940 | 0 | void VisitLambdaExpr(const LambdaExpr *LE) { |
1941 | | // Lambdas are treated as their own functions for now, so we shouldn't |
1942 | | // propagate counts into them. |
1943 | 0 | } |
1944 | | |
1945 | 0 | void VisitPseudoObjectExpr(const PseudoObjectExpr *POE) { |
1946 | | // Just visit syntatic expression as this is what users actually write. |
1947 | 0 | VisitStmt(POE->getSyntacticForm()); |
1948 | 0 | } |
1949 | | |
1950 | 0 | void VisitOpaqueValueExpr(const OpaqueValueExpr* OVE) { |
1951 | 0 | Visit(OVE->getSourceExpr()); |
1952 | 0 | } |
1953 | | }; |
1954 | | |
1955 | | } // end anonymous namespace |
1956 | | |
1957 | | static void dump(llvm::raw_ostream &OS, StringRef FunctionName, |
1958 | | ArrayRef<CounterExpression> Expressions, |
1959 | 0 | ArrayRef<CounterMappingRegion> Regions) { |
1960 | 0 | OS << FunctionName << ":\n"; |
1961 | 0 | CounterMappingContext Ctx(Expressions); |
1962 | 0 | for (const auto &R : Regions) { |
1963 | 0 | OS.indent(2); |
1964 | 0 | switch (R.Kind) { |
1965 | 0 | case CounterMappingRegion::CodeRegion: |
1966 | 0 | break; |
1967 | 0 | case CounterMappingRegion::ExpansionRegion: |
1968 | 0 | OS << "Expansion,"; |
1969 | 0 | break; |
1970 | 0 | case CounterMappingRegion::SkippedRegion: |
1971 | 0 | OS << "Skipped,"; |
1972 | 0 | break; |
1973 | 0 | case CounterMappingRegion::GapRegion: |
1974 | 0 | OS << "Gap,"; |
1975 | 0 | break; |
1976 | 0 | case CounterMappingRegion::BranchRegion: |
1977 | 0 | case CounterMappingRegion::MCDCBranchRegion: |
1978 | 0 | OS << "Branch,"; |
1979 | 0 | break; |
1980 | 0 | case CounterMappingRegion::MCDCDecisionRegion: |
1981 | 0 | OS << "Decision,"; |
1982 | 0 | break; |
1983 | 0 | } |
1984 | | |
1985 | 0 | OS << "File " << R.FileID << ", " << R.LineStart << ":" << R.ColumnStart |
1986 | 0 | << " -> " << R.LineEnd << ":" << R.ColumnEnd << " = "; |
1987 | |
|
1988 | 0 | if (R.Kind == CounterMappingRegion::MCDCDecisionRegion) { |
1989 | 0 | OS << "M:" << R.MCDCParams.BitmapIdx; |
1990 | 0 | OS << ", C:" << R.MCDCParams.NumConditions; |
1991 | 0 | } else { |
1992 | 0 | Ctx.dump(R.Count, OS); |
1993 | |
|
1994 | 0 | if (R.Kind == CounterMappingRegion::BranchRegion || |
1995 | 0 | R.Kind == CounterMappingRegion::MCDCBranchRegion) { |
1996 | 0 | OS << ", "; |
1997 | 0 | Ctx.dump(R.FalseCount, OS); |
1998 | 0 | } |
1999 | 0 | } |
2000 | |
|
2001 | 0 | if (R.Kind == CounterMappingRegion::MCDCBranchRegion) { |
2002 | 0 | OS << " [" << R.MCDCParams.ID << "," << R.MCDCParams.TrueID; |
2003 | 0 | OS << "," << R.MCDCParams.FalseID << "] "; |
2004 | 0 | } |
2005 | |
|
2006 | 0 | if (R.Kind == CounterMappingRegion::ExpansionRegion) |
2007 | 0 | OS << " (Expanded file = " << R.ExpandedFileID << ")"; |
2008 | 0 | OS << "\n"; |
2009 | 0 | } |
2010 | 0 | } |
2011 | | |
2012 | | CoverageMappingModuleGen::CoverageMappingModuleGen( |
2013 | | CodeGenModule &CGM, CoverageSourceInfo &SourceInfo) |
2014 | 0 | : CGM(CGM), SourceInfo(SourceInfo) {} |
2015 | | |
2016 | 0 | std::string CoverageMappingModuleGen::getCurrentDirname() { |
2017 | 0 | if (!CGM.getCodeGenOpts().CoverageCompilationDir.empty()) |
2018 | 0 | return CGM.getCodeGenOpts().CoverageCompilationDir; |
2019 | | |
2020 | 0 | SmallString<256> CWD; |
2021 | 0 | llvm::sys::fs::current_path(CWD); |
2022 | 0 | return CWD.str().str(); |
2023 | 0 | } |
2024 | | |
2025 | 0 | std::string CoverageMappingModuleGen::normalizeFilename(StringRef Filename) { |
2026 | 0 | llvm::SmallString<256> Path(Filename); |
2027 | 0 | llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true); |
2028 | | |
2029 | | /// Traverse coverage prefix map in reverse order because prefix replacements |
2030 | | /// are applied in reverse order starting from the last one when multiple |
2031 | | /// prefix replacement options are provided. |
2032 | 0 | for (const auto &[From, To] : |
2033 | 0 | llvm::reverse(CGM.getCodeGenOpts().CoveragePrefixMap)) { |
2034 | 0 | if (llvm::sys::path::replace_path_prefix(Path, From, To)) |
2035 | 0 | break; |
2036 | 0 | } |
2037 | 0 | return Path.str().str(); |
2038 | 0 | } |
2039 | | |
2040 | | static std::string getInstrProfSection(const CodeGenModule &CGM, |
2041 | 0 | llvm::InstrProfSectKind SK) { |
2042 | 0 | return llvm::getInstrProfSectionName( |
2043 | 0 | SK, CGM.getContext().getTargetInfo().getTriple().getObjectFormat()); |
2044 | 0 | } |
2045 | | |
2046 | | void CoverageMappingModuleGen::emitFunctionMappingRecord( |
2047 | 0 | const FunctionInfo &Info, uint64_t FilenamesRef) { |
2048 | 0 | llvm::LLVMContext &Ctx = CGM.getLLVMContext(); |
2049 | | |
2050 | | // Assign a name to the function record. This is used to merge duplicates. |
2051 | 0 | std::string FuncRecordName = "__covrec_" + llvm::utohexstr(Info.NameHash); |
2052 | | |
2053 | | // A dummy description for a function included-but-not-used in a TU can be |
2054 | | // replaced by full description provided by a different TU. The two kinds of |
2055 | | // descriptions play distinct roles: therefore, assign them different names |
2056 | | // to prevent `linkonce_odr` merging. |
2057 | 0 | if (Info.IsUsed) |
2058 | 0 | FuncRecordName += "u"; |
2059 | | |
2060 | | // Create the function record type. |
2061 | 0 | const uint64_t NameHash = Info.NameHash; |
2062 | 0 | const uint64_t FuncHash = Info.FuncHash; |
2063 | 0 | const std::string &CoverageMapping = Info.CoverageMapping; |
2064 | 0 | #define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) LLVMType, |
2065 | 0 | llvm::Type *FunctionRecordTypes[] = { |
2066 | 0 | #include "llvm/ProfileData/InstrProfData.inc" |
2067 | 0 | }; |
2068 | 0 | auto *FunctionRecordTy = |
2069 | 0 | llvm::StructType::get(Ctx, ArrayRef(FunctionRecordTypes), |
2070 | 0 | /*isPacked=*/true); |
2071 | | |
2072 | | // Create the function record constant. |
2073 | 0 | #define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) Init, |
2074 | 0 | llvm::Constant *FunctionRecordVals[] = { |
2075 | 0 | #include "llvm/ProfileData/InstrProfData.inc" |
2076 | 0 | }; |
2077 | 0 | auto *FuncRecordConstant = |
2078 | 0 | llvm::ConstantStruct::get(FunctionRecordTy, ArrayRef(FunctionRecordVals)); |
2079 | | |
2080 | | // Create the function record global. |
2081 | 0 | auto *FuncRecord = new llvm::GlobalVariable( |
2082 | 0 | CGM.getModule(), FunctionRecordTy, /*isConstant=*/true, |
2083 | 0 | llvm::GlobalValue::LinkOnceODRLinkage, FuncRecordConstant, |
2084 | 0 | FuncRecordName); |
2085 | 0 | FuncRecord->setVisibility(llvm::GlobalValue::HiddenVisibility); |
2086 | 0 | FuncRecord->setSection(getInstrProfSection(CGM, llvm::IPSK_covfun)); |
2087 | 0 | FuncRecord->setAlignment(llvm::Align(8)); |
2088 | 0 | if (CGM.supportsCOMDAT()) |
2089 | 0 | FuncRecord->setComdat(CGM.getModule().getOrInsertComdat(FuncRecordName)); |
2090 | | |
2091 | | // Make sure the data doesn't get deleted. |
2092 | 0 | CGM.addUsedGlobal(FuncRecord); |
2093 | 0 | } |
2094 | | |
2095 | | void CoverageMappingModuleGen::addFunctionMappingRecord( |
2096 | | llvm::GlobalVariable *NamePtr, StringRef NameValue, uint64_t FuncHash, |
2097 | 0 | const std::string &CoverageMapping, bool IsUsed) { |
2098 | 0 | const uint64_t NameHash = llvm::IndexedInstrProf::ComputeHash(NameValue); |
2099 | 0 | FunctionRecords.push_back({NameHash, FuncHash, CoverageMapping, IsUsed}); |
2100 | |
|
2101 | 0 | if (!IsUsed) |
2102 | 0 | FunctionNames.push_back(NamePtr); |
2103 | |
|
2104 | 0 | if (CGM.getCodeGenOpts().DumpCoverageMapping) { |
2105 | | // Dump the coverage mapping data for this function by decoding the |
2106 | | // encoded data. This allows us to dump the mapping regions which were |
2107 | | // also processed by the CoverageMappingWriter which performs |
2108 | | // additional minimization operations such as reducing the number of |
2109 | | // expressions. |
2110 | 0 | llvm::SmallVector<std::string, 16> FilenameStrs; |
2111 | 0 | std::vector<StringRef> Filenames; |
2112 | 0 | std::vector<CounterExpression> Expressions; |
2113 | 0 | std::vector<CounterMappingRegion> Regions; |
2114 | 0 | FilenameStrs.resize(FileEntries.size() + 1); |
2115 | 0 | FilenameStrs[0] = normalizeFilename(getCurrentDirname()); |
2116 | 0 | for (const auto &Entry : FileEntries) { |
2117 | 0 | auto I = Entry.second; |
2118 | 0 | FilenameStrs[I] = normalizeFilename(Entry.first.getName()); |
2119 | 0 | } |
2120 | 0 | ArrayRef<std::string> FilenameRefs = llvm::ArrayRef(FilenameStrs); |
2121 | 0 | RawCoverageMappingReader Reader(CoverageMapping, FilenameRefs, Filenames, |
2122 | 0 | Expressions, Regions); |
2123 | 0 | if (Reader.read()) |
2124 | 0 | return; |
2125 | 0 | dump(llvm::outs(), NameValue, Expressions, Regions); |
2126 | 0 | } |
2127 | 0 | } |
2128 | | |
2129 | 0 | void CoverageMappingModuleGen::emit() { |
2130 | 0 | if (FunctionRecords.empty()) |
2131 | 0 | return; |
2132 | 0 | llvm::LLVMContext &Ctx = CGM.getLLVMContext(); |
2133 | 0 | auto *Int32Ty = llvm::Type::getInt32Ty(Ctx); |
2134 | | |
2135 | | // Create the filenames and merge them with coverage mappings |
2136 | 0 | llvm::SmallVector<std::string, 16> FilenameStrs; |
2137 | 0 | FilenameStrs.resize(FileEntries.size() + 1); |
2138 | | // The first filename is the current working directory. |
2139 | 0 | FilenameStrs[0] = normalizeFilename(getCurrentDirname()); |
2140 | 0 | for (const auto &Entry : FileEntries) { |
2141 | 0 | auto I = Entry.second; |
2142 | 0 | FilenameStrs[I] = normalizeFilename(Entry.first.getName()); |
2143 | 0 | } |
2144 | |
|
2145 | 0 | std::string Filenames; |
2146 | 0 | { |
2147 | 0 | llvm::raw_string_ostream OS(Filenames); |
2148 | 0 | CoverageFilenamesSectionWriter(FilenameStrs).write(OS); |
2149 | 0 | } |
2150 | 0 | auto *FilenamesVal = |
2151 | 0 | llvm::ConstantDataArray::getString(Ctx, Filenames, false); |
2152 | 0 | const int64_t FilenamesRef = llvm::IndexedInstrProf::ComputeHash(Filenames); |
2153 | | |
2154 | | // Emit the function records. |
2155 | 0 | for (const FunctionInfo &Info : FunctionRecords) |
2156 | 0 | emitFunctionMappingRecord(Info, FilenamesRef); |
2157 | |
|
2158 | 0 | const unsigned NRecords = 0; |
2159 | 0 | const size_t FilenamesSize = Filenames.size(); |
2160 | 0 | const unsigned CoverageMappingSize = 0; |
2161 | 0 | llvm::Type *CovDataHeaderTypes[] = { |
2162 | 0 | #define COVMAP_HEADER(Type, LLVMType, Name, Init) LLVMType, |
2163 | 0 | #include "llvm/ProfileData/InstrProfData.inc" |
2164 | 0 | }; |
2165 | 0 | auto CovDataHeaderTy = |
2166 | 0 | llvm::StructType::get(Ctx, ArrayRef(CovDataHeaderTypes)); |
2167 | 0 | llvm::Constant *CovDataHeaderVals[] = { |
2168 | 0 | #define COVMAP_HEADER(Type, LLVMType, Name, Init) Init, |
2169 | 0 | #include "llvm/ProfileData/InstrProfData.inc" |
2170 | 0 | }; |
2171 | 0 | auto CovDataHeaderVal = |
2172 | 0 | llvm::ConstantStruct::get(CovDataHeaderTy, ArrayRef(CovDataHeaderVals)); |
2173 | | |
2174 | | // Create the coverage data record |
2175 | 0 | llvm::Type *CovDataTypes[] = {CovDataHeaderTy, FilenamesVal->getType()}; |
2176 | 0 | auto CovDataTy = llvm::StructType::get(Ctx, ArrayRef(CovDataTypes)); |
2177 | 0 | llvm::Constant *TUDataVals[] = {CovDataHeaderVal, FilenamesVal}; |
2178 | 0 | auto CovDataVal = llvm::ConstantStruct::get(CovDataTy, ArrayRef(TUDataVals)); |
2179 | 0 | auto CovData = new llvm::GlobalVariable( |
2180 | 0 | CGM.getModule(), CovDataTy, true, llvm::GlobalValue::PrivateLinkage, |
2181 | 0 | CovDataVal, llvm::getCoverageMappingVarName()); |
2182 | |
|
2183 | 0 | CovData->setSection(getInstrProfSection(CGM, llvm::IPSK_covmap)); |
2184 | 0 | CovData->setAlignment(llvm::Align(8)); |
2185 | | |
2186 | | // Make sure the data doesn't get deleted. |
2187 | 0 | CGM.addUsedGlobal(CovData); |
2188 | | // Create the deferred function records array |
2189 | 0 | if (!FunctionNames.empty()) { |
2190 | 0 | auto NamesArrTy = llvm::ArrayType::get(llvm::PointerType::getUnqual(Ctx), |
2191 | 0 | FunctionNames.size()); |
2192 | 0 | auto NamesArrVal = llvm::ConstantArray::get(NamesArrTy, FunctionNames); |
2193 | | // This variable will *NOT* be emitted to the object file. It is used |
2194 | | // to pass the list of names referenced to codegen. |
2195 | 0 | new llvm::GlobalVariable(CGM.getModule(), NamesArrTy, true, |
2196 | 0 | llvm::GlobalValue::InternalLinkage, NamesArrVal, |
2197 | 0 | llvm::getCoverageUnusedNamesVarName()); |
2198 | 0 | } |
2199 | 0 | } |
2200 | | |
2201 | 0 | unsigned CoverageMappingModuleGen::getFileID(FileEntryRef File) { |
2202 | 0 | auto It = FileEntries.find(File); |
2203 | 0 | if (It != FileEntries.end()) |
2204 | 0 | return It->second; |
2205 | 0 | unsigned FileID = FileEntries.size() + 1; |
2206 | 0 | FileEntries.insert(std::make_pair(File, FileID)); |
2207 | 0 | return FileID; |
2208 | 0 | } |
2209 | | |
2210 | | void CoverageMappingGen::emitCounterMapping(const Decl *D, |
2211 | 0 | llvm::raw_ostream &OS) { |
2212 | 0 | assert(CounterMap && MCDCBitmapMap); |
2213 | 0 | CounterCoverageMappingBuilder Walker(CVM, *CounterMap, *MCDCBitmapMap, |
2214 | 0 | *CondIDMap, SM, LangOpts); |
2215 | 0 | Walker.VisitDecl(D); |
2216 | 0 | Walker.write(OS); |
2217 | 0 | } |
2218 | | |
2219 | | void CoverageMappingGen::emitEmptyMapping(const Decl *D, |
2220 | 0 | llvm::raw_ostream &OS) { |
2221 | 0 | EmptyCoverageMappingBuilder Walker(CVM, SM, LangOpts); |
2222 | 0 | Walker.VisitDecl(D); |
2223 | 0 | Walker.write(OS); |
2224 | 0 | } |