clang 22.0.0git
CoverageMappingGen.cpp
Go to the documentation of this file.
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 "CodeGenPGO.h"
19#include "clang/Lex/Lexer.h"
20#include "llvm/ADT/DenseSet.h"
21#include "llvm/ADT/SmallSet.h"
22#include "llvm/ADT/StringExtras.h"
23#include "llvm/ProfileData/Coverage/CoverageMapping.h"
24#include "llvm/ProfileData/Coverage/CoverageMappingReader.h"
25#include "llvm/ProfileData/Coverage/CoverageMappingWriter.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
34namespace llvm {
35cl::opt<bool>
36 EnableSingleByteCoverage("enable-single-byte-coverage",
37 llvm::cl::ZeroOrMore,
38 llvm::cl::desc("Enable single byte coverage"),
39 llvm::cl::Hidden, llvm::cl::init(false));
40} // namespace llvm
41
42static llvm::cl::opt<bool> EmptyLineCommentCoverage(
43 "emptyline-comment-coverage",
44 llvm::cl::desc("Emit emptylines and comment lines as skipped regions (only "
45 "disable it on test)"),
46 llvm::cl::init(true), llvm::cl::Hidden);
47
48namespace llvm::coverage {
50 "system-headers-coverage",
51 cl::desc("Enable collecting coverage from system headers"), cl::init(false),
52 cl::Hidden);
53}
54
55using namespace clang;
56using namespace CodeGen;
57using namespace llvm::coverage;
58
61 CoverageSourceInfo *CoverageInfo =
63 PP.addPPCallbacks(std::unique_ptr<PPCallbacks>(CoverageInfo));
65 PP.addCommentHandler(CoverageInfo);
66 PP.setEmptylineHandler(CoverageInfo);
67 PP.setPreprocessToken(true);
68 PP.setTokenWatcher([CoverageInfo](clang::Token Tok) {
69 // Update previous token location.
70 CoverageInfo->PrevTokLoc = Tok.getLocation();
71 if (Tok.getKind() != clang::tok::eod)
72 CoverageInfo->updateNextTokLoc(Tok.getLocation());
73 });
74 }
75 return CoverageInfo;
76}
77
79 SkippedRange::Kind RangeKind) {
80 if (EmptyLineCommentCoverage && !SkippedRanges.empty() &&
81 PrevTokLoc == SkippedRanges.back().PrevTokLoc &&
82 SourceMgr.isWrittenInSameFile(SkippedRanges.back().Range.getEnd(),
83 Range.getBegin()))
84 SkippedRanges.back().Range.setEnd(Range.getEnd());
85 else
86 SkippedRanges.push_back({Range, RangeKind, PrevTokLoc});
87}
88
92
96
101
103 if (!SkippedRanges.empty() && SkippedRanges.back().NextTokLoc.isInvalid())
104 SkippedRanges.back().NextTokLoc = Loc;
105}
106
107namespace {
108/// A region of source code that can be mapped to a counter.
109class SourceMappingRegion {
110 /// Primary Counter that is also used for Branch Regions for "True" branches.
111 Counter Count;
112
113 /// Secondary Counter used for Branch Regions for "False" branches.
114 std::optional<Counter> FalseCount;
115
116 /// Parameters used for Modified Condition/Decision Coverage
117 mcdc::Parameters MCDCParams;
118
119 /// The region's starting location.
120 std::optional<SourceLocation> LocStart;
121
122 /// The region's ending location.
123 std::optional<SourceLocation> LocEnd;
124
125 /// Whether this region is a gap region. The count from a gap region is set
126 /// as the line execution count if there are no other regions on the line.
127 bool GapRegion;
128
129 /// Whetever this region is skipped ('if constexpr' or 'if consteval' untaken
130 /// branch, or anything skipped but not empty line / comments)
131 bool SkippedRegion;
132
133public:
134 SourceMappingRegion(Counter Count, std::optional<SourceLocation> LocStart,
135 std::optional<SourceLocation> LocEnd,
136 bool GapRegion = false)
137 : Count(Count), LocStart(LocStart), LocEnd(LocEnd), GapRegion(GapRegion),
138 SkippedRegion(false) {}
139
140 SourceMappingRegion(Counter Count, std::optional<Counter> FalseCount,
141 mcdc::Parameters MCDCParams,
142 std::optional<SourceLocation> LocStart,
143 std::optional<SourceLocation> LocEnd,
144 bool GapRegion = false)
145 : Count(Count), FalseCount(FalseCount), MCDCParams(MCDCParams),
146 LocStart(LocStart), LocEnd(LocEnd), GapRegion(GapRegion),
147 SkippedRegion(false) {}
148
149 SourceMappingRegion(mcdc::Parameters MCDCParams,
150 std::optional<SourceLocation> LocStart,
151 std::optional<SourceLocation> LocEnd)
152 : MCDCParams(MCDCParams), LocStart(LocStart), LocEnd(LocEnd),
153 GapRegion(false), SkippedRegion(false) {}
154
155 const Counter &getCounter() const { return Count; }
156
157 const Counter &getFalseCounter() const {
158 assert(FalseCount && "Region has no alternate counter");
159 return *FalseCount;
160 }
161
162 void setCounter(Counter C) { Count = C; }
163
164 bool hasStartLoc() const { return LocStart.has_value(); }
165
166 void setStartLoc(SourceLocation Loc) { LocStart = Loc; }
167
168 SourceLocation getBeginLoc() const {
169 assert(LocStart && "Region has no start location");
170 return *LocStart;
171 }
172
173 bool hasEndLoc() const { return LocEnd.has_value(); }
174
175 void setEndLoc(SourceLocation Loc) {
176 assert(Loc.isValid() && "Setting an invalid end location");
177 LocEnd = Loc;
178 }
179
180 SourceLocation getEndLoc() const {
181 assert(LocEnd && "Region has no end location");
182 return *LocEnd;
183 }
184
185 bool isGap() const { return GapRegion; }
186
187 void setGap(bool Gap) { GapRegion = Gap; }
188
189 bool isSkipped() const { return SkippedRegion; }
190
191 void setSkipped(bool Skipped) { SkippedRegion = Skipped; }
192
193 bool isBranch() const { return FalseCount.has_value(); }
194
195 bool isMCDCBranch() const {
196 return std::holds_alternative<mcdc::BranchParameters>(MCDCParams);
197 }
198
199 const auto &getMCDCBranchParams() const {
200 return mcdc::getParams<const mcdc::BranchParameters>(MCDCParams);
201 }
202
203 bool isMCDCDecision() const {
204 return std::holds_alternative<mcdc::DecisionParameters>(MCDCParams);
205 }
206
207 const auto &getMCDCDecisionParams() const {
208 return mcdc::getParams<const mcdc::DecisionParameters>(MCDCParams);
209 }
210
211 const mcdc::Parameters &getMCDCParams() const { return MCDCParams; }
212
213 void resetMCDCParams() { MCDCParams = mcdc::Parameters(); }
214};
215
216/// Spelling locations for the start and end of a source region.
217struct SpellingRegion {
218 /// The line where the region starts.
219 unsigned LineStart;
220
221 /// The column where the region starts.
222 unsigned ColumnStart;
223
224 /// The line where the region ends.
225 unsigned LineEnd;
226
227 /// The column where the region ends.
228 unsigned ColumnEnd;
229
230 SpellingRegion(SourceManager &SM, SourceLocation LocStart,
231 SourceLocation LocEnd) {
232 LineStart = SM.getSpellingLineNumber(LocStart);
233 ColumnStart = SM.getSpellingColumnNumber(LocStart);
234 LineEnd = SM.getSpellingLineNumber(LocEnd);
235 ColumnEnd = SM.getSpellingColumnNumber(LocEnd);
236 }
237
238 SpellingRegion(SourceManager &SM, SourceMappingRegion &R)
239 : SpellingRegion(SM, R.getBeginLoc(), R.getEndLoc()) {}
240
241 /// Check if the start and end locations appear in source order, i.e
242 /// top->bottom, left->right.
243 bool isInSourceOrder() const {
244 return (LineStart < LineEnd) ||
245 (LineStart == LineEnd && ColumnStart <= ColumnEnd);
246 }
247};
248
249/// Provides the common functionality for the different
250/// coverage mapping region builders.
251class CoverageMappingBuilder {
252public:
253 CoverageMappingModuleGen &CVM;
254 SourceManager &SM;
255 const LangOptions &LangOpts;
256
257private:
258 /// Map of clang's FileIDs to IDs used for coverage mapping.
259 llvm::SmallDenseMap<FileID, std::pair<unsigned, SourceLocation>, 8>
260 FileIDMapping;
261
262public:
263 /// The coverage mapping regions for this function
264 llvm::SmallVector<CounterMappingRegion, 32> MappingRegions;
265 /// The source mapping regions for this function.
266 std::vector<SourceMappingRegion> SourceRegions;
267
268 /// A set of regions which can be used as a filter.
269 ///
270 /// It is produced by emitExpansionRegions() and is used in
271 /// emitSourceRegions() to suppress producing code regions if
272 /// the same area is covered by expansion regions.
273 typedef llvm::SmallSet<std::pair<SourceLocation, SourceLocation>, 8>
274 SourceRegionFilter;
275
276 CoverageMappingBuilder(CoverageMappingModuleGen &CVM, SourceManager &SM,
277 const LangOptions &LangOpts)
278 : CVM(CVM), SM(SM), LangOpts(LangOpts) {}
279
280 /// Return the precise end location for the given token.
281 SourceLocation getPreciseTokenLocEnd(SourceLocation Loc) {
282 // We avoid getLocForEndOfToken here, because it doesn't do what we want for
283 // macro locations, which we just treat as expanded files.
284 unsigned TokLen =
285 Lexer::MeasureTokenLength(SM.getSpellingLoc(Loc), SM, LangOpts);
286 return Loc.getLocWithOffset(TokLen);
287 }
288
289 /// Return the start location of an included file or expanded macro.
290 SourceLocation getStartOfFileOrMacro(SourceLocation Loc) {
291 if (Loc.isMacroID())
292 return Loc.getLocWithOffset(-SM.getFileOffset(Loc));
293 return SM.getLocForStartOfFile(SM.getFileID(Loc));
294 }
295
296 /// Return the end location of an included file or expanded macro.
297 SourceLocation getEndOfFileOrMacro(SourceLocation Loc) {
298 if (Loc.isMacroID())
299 return Loc.getLocWithOffset(SM.getFileIDSize(SM.getFileID(Loc)) -
300 SM.getFileOffset(Loc));
301 return SM.getLocForEndOfFile(SM.getFileID(Loc));
302 }
303
304 /// Find out where a macro is expanded. If the immediate result is a
305 /// <scratch space>, keep looking until the result isn't. Return a pair of
306 /// \c SourceLocation. The first object is always the begin sloc of found
307 /// result. The second should be checked by the caller: if it has value, it's
308 /// the end sloc of the found result. Otherwise the while loop didn't get
309 /// executed, which means the location wasn't changed and the caller has to
310 /// learn the end sloc from somewhere else.
311 std::pair<SourceLocation, std::optional<SourceLocation>>
312 getNonScratchExpansionLoc(SourceLocation Loc) {
313 std::optional<SourceLocation> EndLoc = std::nullopt;
314 while (Loc.isMacroID() &&
315 SM.isWrittenInScratchSpace(SM.getSpellingLoc(Loc))) {
316 auto ExpansionRange = SM.getImmediateExpansionRange(Loc);
317 Loc = ExpansionRange.getBegin();
318 EndLoc = ExpansionRange.getEnd();
319 }
320 return std::make_pair(Loc, EndLoc);
321 }
322
323 /// Find out where the current file is included or macro is expanded. If
324 /// \c AcceptScratch is set to false, keep looking for expansions until the
325 /// found sloc is not a <scratch space>.
326 SourceLocation getIncludeOrExpansionLoc(SourceLocation Loc,
327 bool AcceptScratch = true) {
328 if (!Loc.isMacroID())
329 return SM.getIncludeLoc(SM.getFileID(Loc));
330 Loc = SM.getImmediateExpansionRange(Loc).getBegin();
331 if (AcceptScratch)
332 return Loc;
333 return getNonScratchExpansionLoc(Loc).first;
334 }
335
336 /// Return true if \c Loc is a location in a built-in macro.
337 bool isInBuiltin(SourceLocation Loc) {
338 return SM.getBufferName(SM.getSpellingLoc(Loc)) == "<built-in>";
339 }
340
341 /// Check whether \c Loc is included or expanded from \c Parent.
342 bool isNestedIn(SourceLocation Loc, FileID Parent) {
343 do {
344 Loc = getIncludeOrExpansionLoc(Loc);
345 if (Loc.isInvalid())
346 return false;
347 } while (!SM.isInFileID(Loc, Parent));
348 return true;
349 }
350
351 /// Get the start of \c S ignoring macro arguments and builtin macros.
352 SourceLocation getStart(const Stmt *S) {
353 SourceLocation Loc = S->getBeginLoc();
354 while (SM.isMacroArgExpansion(Loc) || isInBuiltin(Loc))
355 Loc = SM.getImmediateExpansionRange(Loc).getBegin();
356 return Loc;
357 }
358
359 /// Get the end of \c S ignoring macro arguments and builtin macros.
360 SourceLocation getEnd(const Stmt *S) {
361 SourceLocation Loc = S->getEndLoc();
362 while (SM.isMacroArgExpansion(Loc) || isInBuiltin(Loc))
363 Loc = SM.getImmediateExpansionRange(Loc).getBegin();
364 return getPreciseTokenLocEnd(Loc);
365 }
366
367 /// Find the set of files we have regions for and assign IDs
368 ///
369 /// Fills \c Mapping with the virtual file mapping needed to write out
370 /// coverage and collects the necessary file information to emit source and
371 /// expansion regions.
372 void gatherFileIDs(SmallVectorImpl<unsigned> &Mapping) {
373 FileIDMapping.clear();
374
375 llvm::SmallSet<FileID, 8> Visited;
376 SmallVector<std::pair<SourceLocation, unsigned>, 8> FileLocs;
377 for (auto &Region : SourceRegions) {
378 SourceLocation Loc = Region.getBeginLoc();
379
380 // Replace Region with its definition if it is in <scratch space>.
381 auto NonScratchExpansionLoc = getNonScratchExpansionLoc(Loc);
382 auto EndLoc = NonScratchExpansionLoc.second;
383 if (EndLoc.has_value()) {
384 Loc = NonScratchExpansionLoc.first;
385 Region.setStartLoc(Loc);
386 Region.setEndLoc(EndLoc.value());
387 }
388
389 // Replace Loc with FileLoc if it is expanded with system headers.
390 if (!SystemHeadersCoverage && SM.isInSystemMacro(Loc)) {
391 auto BeginLoc = SM.getSpellingLoc(Loc);
392 auto EndLoc = SM.getSpellingLoc(Region.getEndLoc());
393 if (SM.isWrittenInSameFile(BeginLoc, EndLoc)) {
394 Loc = SM.getFileLoc(Loc);
395 Region.setStartLoc(Loc);
396 Region.setEndLoc(SM.getFileLoc(Region.getEndLoc()));
397 }
398 }
399
400 FileID File = SM.getFileID(Loc);
401 if (!Visited.insert(File).second)
402 continue;
403
404 assert(SystemHeadersCoverage ||
405 !SM.isInSystemHeader(SM.getSpellingLoc(Loc)));
406
407 unsigned Depth = 0;
408 for (SourceLocation Parent = getIncludeOrExpansionLoc(Loc);
409 Parent.isValid(); Parent = getIncludeOrExpansionLoc(Parent))
410 ++Depth;
411 FileLocs.push_back(std::make_pair(Loc, Depth));
412 }
413 llvm::stable_sort(FileLocs, llvm::less_second());
414
415 for (const auto &FL : FileLocs) {
416 SourceLocation Loc = FL.first;
417 FileID SpellingFile = SM.getDecomposedSpellingLoc(Loc).first;
418 auto Entry = SM.getFileEntryRefForID(SpellingFile);
419 if (!Entry)
420 continue;
421
422 FileIDMapping[SM.getFileID(Loc)] = std::make_pair(Mapping.size(), Loc);
423 Mapping.push_back(CVM.getFileID(*Entry));
424 }
425 }
426
427 /// Get the coverage mapping file ID for \c Loc.
428 ///
429 /// If such file id doesn't exist, return std::nullopt.
430 std::optional<unsigned> getCoverageFileID(SourceLocation Loc) {
431 auto Mapping = FileIDMapping.find(SM.getFileID(Loc));
432 if (Mapping != FileIDMapping.end())
433 return Mapping->second.first;
434 return std::nullopt;
435 }
436
437 /// This shrinks the skipped range if it spans a line that contains a
438 /// non-comment token. If shrinking the skipped range would make it empty,
439 /// this returns std::nullopt.
440 /// Note this function can potentially be expensive because
441 /// getSpellingLineNumber uses getLineNumber, which is expensive.
442 std::optional<SpellingRegion> adjustSkippedRange(SourceManager &SM,
443 SourceLocation LocStart,
444 SourceLocation LocEnd,
445 SourceLocation PrevTokLoc,
446 SourceLocation NextTokLoc) {
447 SpellingRegion SR{SM, LocStart, LocEnd};
448 SR.ColumnStart = 1;
449 if (PrevTokLoc.isValid() && SM.isWrittenInSameFile(LocStart, PrevTokLoc) &&
450 SR.LineStart == SM.getSpellingLineNumber(PrevTokLoc))
451 SR.LineStart++;
452 if (NextTokLoc.isValid() && SM.isWrittenInSameFile(LocEnd, NextTokLoc) &&
453 SR.LineEnd == SM.getSpellingLineNumber(NextTokLoc)) {
454 SR.LineEnd--;
455 SR.ColumnEnd++;
456 }
457 if (SR.isInSourceOrder())
458 return SR;
459 return std::nullopt;
460 }
461
462 /// Gather all the regions that were skipped by the preprocessor
463 /// using the constructs like #if or comments.
464 void gatherSkippedRegions() {
465 /// An array of the minimum lineStarts and the maximum lineEnds
466 /// for mapping regions from the appropriate source files.
467 llvm::SmallVector<std::pair<unsigned, unsigned>, 8> FileLineRanges;
468 FileLineRanges.resize(
469 FileIDMapping.size(),
470 std::make_pair(std::numeric_limits<unsigned>::max(), 0));
471 for (const auto &R : MappingRegions) {
472 FileLineRanges[R.FileID].first =
473 std::min(FileLineRanges[R.FileID].first, R.LineStart);
474 FileLineRanges[R.FileID].second =
475 std::max(FileLineRanges[R.FileID].second, R.LineEnd);
476 }
477
478 auto SkippedRanges = CVM.getSourceInfo().getSkippedRanges();
479 for (auto &I : SkippedRanges) {
480 SourceRange Range = I.Range;
481 auto LocStart = Range.getBegin();
482 auto LocEnd = Range.getEnd();
483 assert(SM.isWrittenInSameFile(LocStart, LocEnd) &&
484 "region spans multiple files");
485
486 auto CovFileID = getCoverageFileID(LocStart);
487 if (!CovFileID)
488 continue;
489 std::optional<SpellingRegion> SR;
490 if (I.isComment())
491 SR = adjustSkippedRange(SM, LocStart, LocEnd, I.PrevTokLoc,
492 I.NextTokLoc);
493 else if (I.isPPIfElse() || I.isEmptyLine())
494 SR = {SM, LocStart, LocEnd};
495
496 if (!SR)
497 continue;
498 auto Region = CounterMappingRegion::makeSkipped(
499 *CovFileID, SR->LineStart, SR->ColumnStart, SR->LineEnd,
500 SR->ColumnEnd);
501 // Make sure that we only collect the regions that are inside
502 // the source code of this function.
503 if (Region.LineStart >= FileLineRanges[*CovFileID].first &&
504 Region.LineEnd <= FileLineRanges[*CovFileID].second)
505 MappingRegions.push_back(Region);
506 }
507 }
508
509 /// Generate the coverage counter mapping regions from collected
510 /// source regions.
511 void emitSourceRegions(const SourceRegionFilter &Filter) {
512 for (const auto &Region : SourceRegions) {
513 assert(Region.hasEndLoc() && "incomplete region");
514
515 SourceLocation LocStart = Region.getBeginLoc();
516 assert(SM.getFileID(LocStart).isValid() && "region in invalid file");
517
518 // Ignore regions from system headers unless collecting coverage from
519 // system headers is explicitly enabled.
521 SM.isInSystemHeader(SM.getSpellingLoc(LocStart))) {
522 assert(!Region.isMCDCBranch() && !Region.isMCDCDecision() &&
523 "Don't suppress the condition in system headers");
524 continue;
525 }
526
527 auto CovFileID = getCoverageFileID(LocStart);
528 // Ignore regions that don't have a file, such as builtin macros.
529 if (!CovFileID) {
530 assert(!Region.isMCDCBranch() && !Region.isMCDCDecision() &&
531 "Don't suppress the condition in non-file regions");
532 continue;
533 }
534
535 SourceLocation LocEnd = Region.getEndLoc();
536 assert(SM.isWrittenInSameFile(LocStart, LocEnd) &&
537 "region spans multiple files");
538
539 // Don't add code regions for the area covered by expansion regions.
540 // This not only suppresses redundant regions, but sometimes prevents
541 // creating regions with wrong counters if, for example, a statement's
542 // body ends at the end of a nested macro.
543 if (Filter.count(std::make_pair(LocStart, LocEnd))) {
544 assert(!Region.isMCDCBranch() && !Region.isMCDCDecision() &&
545 "Don't suppress the condition");
546 continue;
547 }
548
549 // Find the spelling locations for the mapping region.
550 SpellingRegion SR{SM, LocStart, LocEnd};
551 assert(SR.isInSourceOrder() && "region start and end out of order");
552
553 if (Region.isGap()) {
554 MappingRegions.push_back(CounterMappingRegion::makeGapRegion(
555 Region.getCounter(), *CovFileID, SR.LineStart, SR.ColumnStart,
556 SR.LineEnd, SR.ColumnEnd));
557 } else if (Region.isSkipped()) {
558 MappingRegions.push_back(CounterMappingRegion::makeSkipped(
559 *CovFileID, SR.LineStart, SR.ColumnStart, SR.LineEnd,
560 SR.ColumnEnd));
561 } else if (Region.isBranch()) {
562 MappingRegions.push_back(CounterMappingRegion::makeBranchRegion(
563 Region.getCounter(), Region.getFalseCounter(), *CovFileID,
564 SR.LineStart, SR.ColumnStart, SR.LineEnd, SR.ColumnEnd,
565 Region.getMCDCParams()));
566 } else if (Region.isMCDCDecision()) {
567 MappingRegions.push_back(CounterMappingRegion::makeDecisionRegion(
568 Region.getMCDCDecisionParams(), *CovFileID, SR.LineStart,
569 SR.ColumnStart, SR.LineEnd, SR.ColumnEnd));
570 } else {
571 MappingRegions.push_back(CounterMappingRegion::makeRegion(
572 Region.getCounter(), *CovFileID, SR.LineStart, SR.ColumnStart,
573 SR.LineEnd, SR.ColumnEnd));
574 }
575 }
576 }
577
578 /// Generate expansion regions for each virtual file we've seen.
579 SourceRegionFilter emitExpansionRegions() {
580 SourceRegionFilter Filter;
581 for (const auto &FM : FileIDMapping) {
582 SourceLocation ExpandedLoc = FM.second.second;
583 SourceLocation ParentLoc = getIncludeOrExpansionLoc(ExpandedLoc, false);
584 if (ParentLoc.isInvalid())
585 continue;
586
587 auto ParentFileID = getCoverageFileID(ParentLoc);
588 if (!ParentFileID)
589 continue;
590 auto ExpandedFileID = getCoverageFileID(ExpandedLoc);
591 assert(ExpandedFileID && "expansion in uncovered file");
592
593 SourceLocation LocEnd = getPreciseTokenLocEnd(ParentLoc);
594 assert(SM.isWrittenInSameFile(ParentLoc, LocEnd) &&
595 "region spans multiple files");
596 Filter.insert(std::make_pair(ParentLoc, LocEnd));
597
598 SpellingRegion SR{SM, ParentLoc, LocEnd};
599 assert(SR.isInSourceOrder() && "region start and end out of order");
600 MappingRegions.push_back(CounterMappingRegion::makeExpansion(
601 *ParentFileID, *ExpandedFileID, SR.LineStart, SR.ColumnStart,
602 SR.LineEnd, SR.ColumnEnd));
603 }
604 return Filter;
605 }
606};
607
608/// Creates unreachable coverage regions for the functions that
609/// are not emitted.
610struct EmptyCoverageMappingBuilder : public CoverageMappingBuilder {
611 EmptyCoverageMappingBuilder(CoverageMappingModuleGen &CVM, SourceManager &SM,
612 const LangOptions &LangOpts)
613 : CoverageMappingBuilder(CVM, SM, LangOpts) {}
614
615 void VisitDecl(const Decl *D) {
616 if (!D->hasBody())
617 return;
618 auto Body = D->getBody();
619 SourceLocation Start = getStart(Body);
620 SourceLocation End = getEnd(Body);
621 if (!SM.isWrittenInSameFile(Start, End)) {
622 // Walk up to find the common ancestor.
623 // Correct the locations accordingly.
624 FileID StartFileID = SM.getFileID(Start);
625 FileID EndFileID = SM.getFileID(End);
626 while (StartFileID != EndFileID && !isNestedIn(End, StartFileID)) {
627 Start = getIncludeOrExpansionLoc(Start);
628 assert(Start.isValid() &&
629 "Declaration start location not nested within a known region");
630 StartFileID = SM.getFileID(Start);
631 }
632 while (StartFileID != EndFileID) {
633 End = getPreciseTokenLocEnd(getIncludeOrExpansionLoc(End));
634 assert(End.isValid() &&
635 "Declaration end location not nested within a known region");
636 EndFileID = SM.getFileID(End);
637 }
638 }
639 SourceRegions.emplace_back(Counter(), Start, End);
640 }
641
642 /// Write the mapping data to the output stream
643 void write(llvm::raw_ostream &OS) {
644 SmallVector<unsigned, 16> FileIDMapping;
645 gatherFileIDs(FileIDMapping);
646 emitSourceRegions(SourceRegionFilter());
647
648 if (MappingRegions.empty())
649 return;
650
651 CoverageMappingWriter Writer(FileIDMapping, {}, MappingRegions);
652 Writer.write(OS);
653 }
654};
655
656/// A wrapper object for maintaining stacks to track the resursive AST visitor
657/// walks for the purpose of assigning IDs to leaf-level conditions measured by
658/// MC/DC. The object is created with a reference to the MCDCBitmapMap that was
659/// created during the initial AST walk. The presence of a bitmap associated
660/// with a boolean expression (top-level logical operator nest) indicates that
661/// the boolean expression qualified for MC/DC. The resulting condition IDs
662/// are preserved in a map reference that is also provided during object
663/// creation.
664struct MCDCCoverageBuilder {
665
666 /// The AST walk recursively visits nested logical-AND or logical-OR binary
667 /// operator nodes and then visits their LHS and RHS children nodes. As this
668 /// happens, the algorithm will assign IDs to each operator's LHS and RHS side
669 /// as the walk moves deeper into the nest. At each level of the recursive
670 /// nest, the LHS and RHS may actually correspond to larger subtrees (not
671 /// leaf-conditions). If this is the case, when that node is visited, the ID
672 /// assigned to the subtree is re-assigned to its LHS, and a new ID is given
673 /// to its RHS. At the end of the walk, all leaf-level conditions will have a
674 /// unique ID -- keep in mind that the final set of IDs may not be in
675 /// numerical order from left to right.
676 ///
677 /// Example: "x = (A && B) || (C && D) || (D && F)"
678 ///
679 /// Visit Depth1:
680 /// (A && B) || (C && D) || (D && F)
681 /// ^-------LHS--------^ ^-RHS--^
682 /// ID=1 ID=2
683 ///
684 /// Visit LHS-Depth2:
685 /// (A && B) || (C && D)
686 /// ^-LHS--^ ^-RHS--^
687 /// ID=1 ID=3
688 ///
689 /// Visit LHS-Depth3:
690 /// (A && B)
691 /// LHS RHS
692 /// ID=1 ID=4
693 ///
694 /// Visit RHS-Depth3:
695 /// (C && D)
696 /// LHS RHS
697 /// ID=3 ID=5
698 ///
699 /// Visit RHS-Depth2: (D && F)
700 /// LHS RHS
701 /// ID=2 ID=6
702 ///
703 /// Visit Depth1:
704 /// (A && B) || (C && D) || (D && F)
705 /// ID=1 ID=4 ID=3 ID=5 ID=2 ID=6
706 ///
707 /// A node ID of '0' always means MC/DC isn't being tracked.
708 ///
709 /// As the AST walk proceeds recursively, the algorithm will also use a stack
710 /// to track the IDs of logical-AND and logical-OR operations on the RHS so
711 /// that it can be determined which nodes are executed next, depending on how
712 /// a LHS or RHS of a logical-AND or logical-OR is evaluated. This
713 /// information relies on the assigned IDs and are embedded within the
714 /// coverage region IDs of each branch region associated with a leaf-level
715 /// condition. This information helps the visualization tool reconstruct all
716 /// possible test vectors for the purposes of MC/DC analysis. If a "next" node
717 /// ID is '0', it means it's the end of the test vector. The following rules
718 /// are used:
719 ///
720 /// For logical-AND ("LHS && RHS"):
721 /// - If LHS is TRUE, execution goes to the RHS node.
722 /// - If LHS is FALSE, execution goes to the LHS node of the next logical-OR.
723 /// If that does not exist, execution exits (ID == 0).
724 ///
725 /// - If RHS is TRUE, execution goes to LHS node of the next logical-AND.
726 /// If that does not exist, execution exits (ID == 0).
727 /// - If RHS is FALSE, execution goes to the LHS node of the next logical-OR.
728 /// If that does not exist, execution exits (ID == 0).
729 ///
730 /// For logical-OR ("LHS || RHS"):
731 /// - If LHS is TRUE, execution goes to the LHS node of the next logical-AND.
732 /// If that does not exist, execution exits (ID == 0).
733 /// - If LHS is FALSE, execution goes to the RHS node.
734 ///
735 /// - If RHS is TRUE, execution goes to LHS node of the next logical-AND.
736 /// If that does not exist, execution exits (ID == 0).
737 /// - If RHS is FALSE, execution goes to the LHS node of the next logical-OR.
738 /// If that does not exist, execution exits (ID == 0).
739 ///
740 /// Finally, the condition IDs are also used when instrumenting the code to
741 /// indicate a unique offset into a temporary bitmap that represents the true
742 /// or false evaluation of that particular condition.
743 ///
744 /// NOTE regarding the use of CodeGenFunction::stripCond(). Even though, for
745 /// simplicity, parentheses and unary logical-NOT operators are considered
746 /// part of their underlying condition for both MC/DC and branch coverage, the
747 /// condition IDs themselves are assigned and tracked using the underlying
748 /// condition itself. This is done solely for consistency since parentheses
749 /// and logical-NOTs are ignored when checking whether the condition is
750 /// actually an instrumentable condition. This can also make debugging a bit
751 /// easier.
752
753private:
754 CodeGenModule &CGM;
755
756 llvm::SmallVector<mcdc::ConditionIDs> DecisionStack;
757 MCDC::State &MCDCState;
758 const Stmt *DecisionStmt = nullptr;
759 mcdc::ConditionID NextID = 0;
760 bool NotMapped = false;
761
762 /// Represent a sentinel value as a pair of final decisions for the bottom
763 // of DecisionStack.
764 static constexpr mcdc::ConditionIDs DecisionStackSentinel{-1, -1};
765
766 /// Is this a logical-AND operation?
767 bool isLAnd(const BinaryOperator *E) const {
768 return E->getOpcode() == BO_LAnd;
769 }
770
771public:
772 MCDCCoverageBuilder(CodeGenModule &CGM, MCDC::State &MCDCState)
773 : CGM(CGM), DecisionStack(1, DecisionStackSentinel),
774 MCDCState(MCDCState) {}
775
776 /// Return whether the build of the control flow map is at the top-level
777 /// (root) of a logical operator nest in a boolean expression prior to the
778 /// assignment of condition IDs.
779 bool isIdle() const { return (NextID == 0 && !NotMapped); }
780
781 /// Return whether any IDs have been assigned in the build of the control
782 /// flow map, indicating that the map is being generated for this boolean
783 /// expression.
784 bool isBuilding() const { return (NextID > 0); }
785
786 /// Set the given condition's ID.
787 void setCondID(const Expr *Cond, mcdc::ConditionID ID) {
789 DecisionStmt};
790 }
791
792 /// Return the ID of a given condition.
793 mcdc::ConditionID getCondID(const Expr *Cond) const {
794 auto I = MCDCState.BranchByStmt.find(CodeGenFunction::stripCond(Cond));
795 if (I == MCDCState.BranchByStmt.end())
796 return -1;
797 else
798 return I->second.ID;
799 }
800
801 /// Return the LHS Decision ([0,0] if not set).
802 const mcdc::ConditionIDs &back() const { return DecisionStack.back(); }
803
804 /// Push the binary operator statement to track the nest level and assign IDs
805 /// to the operator's LHS and RHS. The RHS may be a larger subtree that is
806 /// broken up on successive levels.
807 void pushAndAssignIDs(const BinaryOperator *E) {
808 if (!CGM.getCodeGenOpts().MCDCCoverage)
809 return;
810
811 // If binary expression is disqualified, don't do mapping.
812 if (!isBuilding() &&
813 !MCDCState.DecisionByStmt.contains(CodeGenFunction::stripCond(E)))
814 NotMapped = true;
815
816 // Don't go any further if we don't need to map condition IDs.
817 if (NotMapped)
818 return;
819
820 if (NextID == 0) {
821 DecisionStmt = E;
822 assert(MCDCState.DecisionByStmt.contains(E));
823 }
824
825 const mcdc::ConditionIDs &ParentDecision = DecisionStack.back();
826
827 // If the operator itself has an assigned ID, this means it represents a
828 // larger subtree. In this case, assign that ID to its LHS node. Its RHS
829 // will receive a new ID below. Otherwise, assign ID+1 to LHS.
830 if (MCDCState.BranchByStmt.contains(CodeGenFunction::stripCond(E)))
831 setCondID(E->getLHS(), getCondID(E));
832 else
833 setCondID(E->getLHS(), NextID++);
834
835 // Assign a ID+1 for the RHS.
836 mcdc::ConditionID RHSid = NextID++;
837 setCondID(E->getRHS(), RHSid);
838
839 // Push the LHS decision IDs onto the DecisionStack.
840 if (isLAnd(E))
841 DecisionStack.push_back({ParentDecision[false], RHSid});
842 else
843 DecisionStack.push_back({RHSid, ParentDecision[true]});
844 }
845
846 /// Pop and return the LHS Decision ([0,0] if not set).
847 mcdc::ConditionIDs pop() {
848 if (!CGM.getCodeGenOpts().MCDCCoverage || NotMapped)
849 return DecisionStackSentinel;
850
851 assert(DecisionStack.size() > 1);
852 return DecisionStack.pop_back_val();
853 }
854
855 /// Return the total number of conditions and reset the state. The number of
856 /// conditions is zero if the expression isn't mapped.
857 unsigned getTotalConditionsAndReset(const BinaryOperator *E) {
858 if (!CGM.getCodeGenOpts().MCDCCoverage)
859 return 0;
860
861 assert(!isIdle());
862 assert(DecisionStack.size() == 1);
863
864 // Reset state if not doing mapping.
865 if (NotMapped) {
866 NotMapped = false;
867 assert(NextID == 0);
868 return 0;
869 }
870
871 // Set number of conditions and reset.
872 unsigned TotalConds = NextID;
873
874 // Reset ID back to beginning.
875 NextID = 0;
876
877 return TotalConds;
878 }
879};
880
881/// A StmtVisitor that creates coverage mapping regions which map
882/// from the source code locations to the PGO counters.
883struct CounterCoverageMappingBuilder
884 : public CoverageMappingBuilder,
885 public ConstStmtVisitor<CounterCoverageMappingBuilder> {
886 /// The map of statements to count values.
887 llvm::DenseMap<const Stmt *, CounterPair> &CounterMap;
888
889 MCDC::State &MCDCState;
890
891 /// A stack of currently live regions.
892 llvm::SmallVector<SourceMappingRegion> RegionStack;
893
894 /// Set if the Expr should be handled as a leaf even if it is kind of binary
895 /// logical ops (&&, ||).
896 llvm::DenseSet<const Stmt *> LeafExprSet;
897
898 /// An object to manage MCDC regions.
899 MCDCCoverageBuilder MCDCBuilder;
900
901 CounterExpressionBuilder Builder;
902
903 /// A location in the most recently visited file or macro.
904 ///
905 /// This is used to adjust the active source regions appropriately when
906 /// expressions cross file or macro boundaries.
907 SourceLocation MostRecentLocation;
908
909 /// Whether the visitor at a terminate statement.
910 bool HasTerminateStmt = false;
911
912 /// Gap region counter after terminate statement.
913 Counter GapRegionCounter;
914
915 /// Return a counter for the subtraction of \c RHS from \c LHS
916 Counter subtractCounters(Counter LHS, Counter RHS, bool Simplify = true) {
918 "cannot add counters when single byte coverage mode is enabled");
919 return Builder.subtract(LHS, RHS, Simplify);
920 }
921
922 /// Return a counter for the sum of \c LHS and \c RHS.
923 Counter addCounters(Counter LHS, Counter RHS, bool Simplify = true) {
924 return Builder.add(LHS, RHS, Simplify);
925 }
926
927 Counter addCounters(Counter C1, Counter C2, Counter C3,
928 bool Simplify = true) {
929 return addCounters(addCounters(C1, C2, Simplify), C3, Simplify);
930 }
931
932 /// Return the region counter for the given statement.
933 ///
934 /// This should only be called on statements that have a dedicated counter.
935 Counter getRegionCounter(const Stmt *S) {
936 return Counter::getCounter(CounterMap[S].Executed);
937 }
938
939 struct BranchCounterPair {
940 Counter Executed; ///< The Counter previously assigned.
941 Counter Skipped; ///< An expression (Parent-Executed), or equivalent to it.
942 };
943
944 /// Retrieve or assign the pair of Counter(s).
945 ///
946 /// This returns BranchCounterPair {Executed, Skipped}.
947 /// Executed is the Counter associated with S assigned by an earlier
948 /// CounterMapping pass.
949 /// Skipped may be an expression (Executed - ParentCnt) or newly
950 /// assigned Counter in EnableSingleByteCoverage, as subtract
951 /// expressions are not available in this mode.
952 ///
953 /// \param S Key to the CounterMap
954 /// \param ParentCnt The Counter representing how many times S is evaluated.
955 /// \param SkipCntForOld (To be removed later) Optional fake Counter
956 /// to override Skipped for adjustment of
957 /// expressions in the old behavior of
958 /// EnableSingleByteCoverage that is unaware of
959 /// Branch coverage.
960 BranchCounterPair
961 getBranchCounterPair(const Stmt *S, Counter ParentCnt,
962 std::optional<Counter> SkipCntForOld = std::nullopt) {
963 Counter ExecCnt = getRegionCounter(S);
964
965 // The old behavior of SingleByte is unaware of Branches.
966 // Will be pruned after the migration of SingleByte.
968 assert(SkipCntForOld &&
969 "SingleByte must provide SkipCntForOld as a fake Skipped count.");
970 return {ExecCnt, *SkipCntForOld};
971 }
972
973 return {ExecCnt, Builder.subtract(ParentCnt, ExecCnt)};
974 }
975
976 bool IsCounterEqual(Counter OutCount, Counter ParentCount) {
977 if (OutCount == ParentCount)
978 return true;
979
980 return false;
981 }
982
983 /// Push a region onto the stack.
984 ///
985 /// Returns the index on the stack where the region was pushed. This can be
986 /// used with popRegions to exit a "scope", ending the region that was pushed.
987 size_t pushRegion(Counter Count,
988 std::optional<SourceLocation> StartLoc = std::nullopt,
989 std::optional<SourceLocation> EndLoc = std::nullopt,
990 std::optional<Counter> FalseCount = std::nullopt,
991 const mcdc::Parameters &BranchParams = std::monostate()) {
992
993 if (StartLoc && !FalseCount) {
994 MostRecentLocation = *StartLoc;
995 }
996
997 // If either of these locations is invalid, something elsewhere in the
998 // compiler has broken.
999 assert((!StartLoc || StartLoc->isValid()) && "Start location is not valid");
1000 assert((!EndLoc || EndLoc->isValid()) && "End location is not valid");
1001
1002 // However, we can still recover without crashing.
1003 // If either location is invalid, set it to std::nullopt to avoid
1004 // letting users of RegionStack think that region has a valid start/end
1005 // location.
1006 if (StartLoc && StartLoc->isInvalid())
1007 StartLoc = std::nullopt;
1008 if (EndLoc && EndLoc->isInvalid())
1009 EndLoc = std::nullopt;
1010 RegionStack.emplace_back(Count, FalseCount, BranchParams, StartLoc, EndLoc);
1011
1012 return RegionStack.size() - 1;
1013 }
1014
1015 size_t pushRegion(const mcdc::DecisionParameters &DecisionParams,
1016 std::optional<SourceLocation> StartLoc = std::nullopt,
1017 std::optional<SourceLocation> EndLoc = std::nullopt) {
1018
1019 RegionStack.emplace_back(DecisionParams, StartLoc, EndLoc);
1020
1021 return RegionStack.size() - 1;
1022 }
1023
1024 size_t locationDepth(SourceLocation Loc) {
1025 size_t Depth = 0;
1026 while (Loc.isValid()) {
1027 Loc = getIncludeOrExpansionLoc(Loc);
1028 Depth++;
1029 }
1030 return Depth;
1031 }
1032
1033 /// Pop regions from the stack into the function's list of regions.
1034 ///
1035 /// Adds all regions from \c ParentIndex to the top of the stack to the
1036 /// function's \c SourceRegions.
1037 void popRegions(size_t ParentIndex) {
1038 assert(RegionStack.size() >= ParentIndex && "parent not in stack");
1039 while (RegionStack.size() > ParentIndex) {
1040 SourceMappingRegion &Region = RegionStack.back();
1041 if (Region.hasStartLoc() &&
1042 (Region.hasEndLoc() || RegionStack[ParentIndex].hasEndLoc())) {
1043 SourceLocation StartLoc = Region.getBeginLoc();
1044 SourceLocation EndLoc = Region.hasEndLoc()
1045 ? Region.getEndLoc()
1046 : RegionStack[ParentIndex].getEndLoc();
1047 bool isBranch = Region.isBranch();
1048 size_t StartDepth = locationDepth(StartLoc);
1049 size_t EndDepth = locationDepth(EndLoc);
1050 while (!SM.isWrittenInSameFile(StartLoc, EndLoc)) {
1051 bool UnnestStart = StartDepth >= EndDepth;
1052 bool UnnestEnd = EndDepth >= StartDepth;
1053 if (UnnestEnd) {
1054 // The region ends in a nested file or macro expansion. If the
1055 // region is not a branch region, create a separate region for each
1056 // expansion, and for all regions, update the EndLoc. Branch
1057 // regions should not be split in order to keep a straightforward
1058 // correspondance between the region and its associated branch
1059 // condition, even if the condition spans multiple depths.
1060 SourceLocation NestedLoc = getStartOfFileOrMacro(EndLoc);
1061 assert(SM.isWrittenInSameFile(NestedLoc, EndLoc));
1062
1063 if (!isBranch && !isRegionAlreadyAdded(NestedLoc, EndLoc))
1064 SourceRegions.emplace_back(Region.getCounter(), NestedLoc,
1065 EndLoc);
1066
1067 EndLoc = getPreciseTokenLocEnd(getIncludeOrExpansionLoc(EndLoc));
1068 if (EndLoc.isInvalid())
1069 llvm::report_fatal_error(
1070 "File exit not handled before popRegions");
1071 EndDepth--;
1072 }
1073 if (UnnestStart) {
1074 // The region ends in a nested file or macro expansion. If the
1075 // region is not a branch region, create a separate region for each
1076 // expansion, and for all regions, update the StartLoc. Branch
1077 // regions should not be split in order to keep a straightforward
1078 // correspondance between the region and its associated branch
1079 // condition, even if the condition spans multiple depths.
1080 SourceLocation NestedLoc = getEndOfFileOrMacro(StartLoc);
1081 assert(SM.isWrittenInSameFile(StartLoc, NestedLoc));
1082
1083 if (!isBranch && !isRegionAlreadyAdded(StartLoc, NestedLoc))
1084 SourceRegions.emplace_back(Region.getCounter(), StartLoc,
1085 NestedLoc);
1086
1087 StartLoc = getIncludeOrExpansionLoc(StartLoc);
1088 if (StartLoc.isInvalid())
1089 llvm::report_fatal_error(
1090 "File exit not handled before popRegions");
1091 StartDepth--;
1092 }
1093 }
1094 Region.setStartLoc(StartLoc);
1095 Region.setEndLoc(EndLoc);
1096
1097 if (!isBranch) {
1098 MostRecentLocation = EndLoc;
1099 // If this region happens to span an entire expansion, we need to
1100 // make sure we don't overlap the parent region with it.
1101 if (StartLoc == getStartOfFileOrMacro(StartLoc) &&
1102 EndLoc == getEndOfFileOrMacro(EndLoc))
1103 MostRecentLocation = getIncludeOrExpansionLoc(EndLoc);
1104 }
1105
1106 assert(SM.isWrittenInSameFile(Region.getBeginLoc(), EndLoc));
1107 assert(SpellingRegion(SM, Region).isInSourceOrder());
1108 SourceRegions.push_back(Region);
1109 }
1110 RegionStack.pop_back();
1111 }
1112 }
1113
1114 /// Return the currently active region.
1115 SourceMappingRegion &getRegion() {
1116 assert(!RegionStack.empty() && "statement has no region");
1117 return RegionStack.back();
1118 }
1119
1120 /// Propagate counts through the children of \p S if \p VisitChildren is true.
1121 /// Otherwise, only emit a count for \p S itself.
1122 Counter propagateCounts(Counter TopCount, const Stmt *S,
1123 bool VisitChildren = true) {
1124 SourceLocation StartLoc = getStart(S);
1125 SourceLocation EndLoc = getEnd(S);
1126 size_t Index = pushRegion(TopCount, StartLoc, EndLoc);
1127 if (VisitChildren)
1128 Visit(S);
1129 Counter ExitCount = getRegion().getCounter();
1130 popRegions(Index);
1131
1132 // The statement may be spanned by an expansion. Make sure we handle a file
1133 // exit out of this expansion before moving to the next statement.
1134 if (SM.isBeforeInTranslationUnit(StartLoc, S->getBeginLoc()))
1135 MostRecentLocation = EndLoc;
1136
1137 return ExitCount;
1138 }
1139
1140 /// Create a Branch Region around an instrumentable condition for coverage
1141 /// and add it to the function's SourceRegions. A branch region tracks a
1142 /// "True" counter and a "False" counter for boolean expressions that
1143 /// result in the generation of a branch.
1144 void createBranchRegion(const Expr *C, Counter TrueCnt, Counter FalseCnt,
1145 const mcdc::ConditionIDs &Conds = {}) {
1146 // Check for NULL conditions.
1147 if (!C)
1148 return;
1149
1150 // Ensure we are an instrumentable condition (i.e. no "&&" or "||"). Push
1151 // region onto RegionStack but immediately pop it (which adds it to the
1152 // function's SourceRegions) because it doesn't apply to any other source
1153 // code other than the Condition.
1154 // With !SystemHeadersCoverage, binary logical ops in system headers may be
1155 // treated as instrumentable conditions.
1157 LeafExprSet.count(CodeGenFunction::stripCond(C))) {
1158 mcdc::Parameters BranchParams;
1159 mcdc::ConditionID ID = MCDCBuilder.getCondID(C);
1160 if (ID >= 0)
1161 BranchParams = mcdc::BranchParameters{ID, Conds};
1162
1163 // If a condition can fold to true or false, the corresponding branch
1164 // will be removed. Create a region with both counters hard-coded to
1165 // zero. This allows us to visualize them in a special way.
1166 // Alternatively, we can prevent any optimization done via
1167 // constant-folding by ensuring that ConstantFoldsToSimpleInteger() in
1168 // CodeGenFunction.c always returns false, but that is very heavy-handed.
1169 Expr::EvalResult Result;
1170 if (C->EvaluateAsInt(Result, CVM.getCodeGenModule().getContext())) {
1171 if (Result.Val.getInt().getBoolValue())
1172 FalseCnt = Counter::getZero();
1173 else
1174 TrueCnt = Counter::getZero();
1175 }
1176 popRegions(
1177 pushRegion(TrueCnt, getStart(C), getEnd(C), FalseCnt, BranchParams));
1178 }
1179 }
1180
1181 /// Create a Decision Region with a BitmapIdx and number of Conditions. This
1182 /// type of region "contains" branch regions, one for each of the conditions.
1183 /// The visualization tool will group everything together.
1184 void createDecisionRegion(const Expr *C,
1185 const mcdc::DecisionParameters &DecisionParams) {
1186 popRegions(pushRegion(DecisionParams, getStart(C), getEnd(C)));
1187 }
1188
1189 /// Create a Branch Region around a SwitchCase for code coverage
1190 /// and add it to the function's SourceRegions.
1191 /// Returns Counter that corresponds to SC.
1192 Counter createSwitchCaseRegion(const SwitchCase *SC, Counter ParentCount) {
1193 // Push region onto RegionStack but immediately pop it (which adds it to
1194 // the function's SourceRegions) because it doesn't apply to any other
1195 // source other than the SwitchCase.
1196 Counter TrueCnt = getRegionCounter(SC);
1197 popRegions(pushRegion(TrueCnt, getStart(SC), SC->getColonLoc(),
1198 subtractCounters(ParentCount, TrueCnt)));
1199 return TrueCnt;
1200 }
1201
1202 /// Check whether a region with bounds \c StartLoc and \c EndLoc
1203 /// is already added to \c SourceRegions.
1204 bool isRegionAlreadyAdded(SourceLocation StartLoc, SourceLocation EndLoc,
1205 bool isBranch = false) {
1206 return llvm::any_of(
1207 llvm::reverse(SourceRegions), [&](const SourceMappingRegion &Region) {
1208 return Region.getBeginLoc() == StartLoc &&
1209 Region.getEndLoc() == EndLoc && Region.isBranch() == isBranch;
1210 });
1211 }
1212
1213 /// Adjust the most recently visited location to \c EndLoc.
1214 ///
1215 /// This should be used after visiting any statements in non-source order.
1216 void adjustForOutOfOrderTraversal(SourceLocation EndLoc) {
1217 MostRecentLocation = EndLoc;
1218 // The code region for a whole macro is created in handleFileExit() when
1219 // it detects exiting of the virtual file of that macro. If we visited
1220 // statements in non-source order, we might already have such a region
1221 // added, for example, if a body of a loop is divided among multiple
1222 // macros. Avoid adding duplicate regions in such case.
1223 if (getRegion().hasEndLoc() &&
1224 MostRecentLocation == getEndOfFileOrMacro(MostRecentLocation) &&
1225 isRegionAlreadyAdded(getStartOfFileOrMacro(MostRecentLocation),
1226 MostRecentLocation, getRegion().isBranch()))
1227 MostRecentLocation = getIncludeOrExpansionLoc(MostRecentLocation);
1228 }
1229
1230 /// Adjust regions and state when \c NewLoc exits a file.
1231 ///
1232 /// If moving from our most recently tracked location to \c NewLoc exits any
1233 /// files, this adjusts our current region stack and creates the file regions
1234 /// for the exited file.
1235 void handleFileExit(SourceLocation NewLoc) {
1236 if (NewLoc.isInvalid() ||
1237 SM.isWrittenInSameFile(MostRecentLocation, NewLoc))
1238 return;
1239
1240 // If NewLoc is not in a file that contains MostRecentLocation, walk up to
1241 // find the common ancestor.
1242 SourceLocation LCA = NewLoc;
1243 FileID ParentFile = SM.getFileID(LCA);
1244 while (!isNestedIn(MostRecentLocation, ParentFile)) {
1245 LCA = getIncludeOrExpansionLoc(LCA);
1246 if (LCA.isInvalid() || SM.isWrittenInSameFile(LCA, MostRecentLocation)) {
1247 // Since there isn't a common ancestor, no file was exited. We just need
1248 // to adjust our location to the new file.
1249 MostRecentLocation = NewLoc;
1250 return;
1251 }
1252 ParentFile = SM.getFileID(LCA);
1253 }
1254
1255 llvm::SmallSet<SourceLocation, 8> StartLocs;
1256 std::optional<Counter> ParentCounter;
1257 for (SourceMappingRegion &I : llvm::reverse(RegionStack)) {
1258 if (!I.hasStartLoc())
1259 continue;
1260 SourceLocation Loc = I.getBeginLoc();
1261 if (!isNestedIn(Loc, ParentFile)) {
1262 ParentCounter = I.getCounter();
1263 break;
1264 }
1265
1266 while (!SM.isInFileID(Loc, ParentFile)) {
1267 // The most nested region for each start location is the one with the
1268 // correct count. We avoid creating redundant regions by stopping once
1269 // we've seen this region.
1270 if (StartLocs.insert(Loc).second) {
1271 if (I.isBranch())
1272 SourceRegions.emplace_back(I.getCounter(), I.getFalseCounter(),
1273 I.getMCDCParams(), Loc,
1274 getEndOfFileOrMacro(Loc), I.isBranch());
1275 else
1276 SourceRegions.emplace_back(I.getCounter(), Loc,
1277 getEndOfFileOrMacro(Loc));
1278 }
1279 Loc = getIncludeOrExpansionLoc(Loc);
1280 }
1281 I.setStartLoc(getPreciseTokenLocEnd(Loc));
1282 }
1283
1284 if (ParentCounter) {
1285 // If the file is contained completely by another region and doesn't
1286 // immediately start its own region, the whole file gets a region
1287 // corresponding to the parent.
1288 SourceLocation Loc = MostRecentLocation;
1289 while (isNestedIn(Loc, ParentFile)) {
1290 SourceLocation FileStart = getStartOfFileOrMacro(Loc);
1291 if (StartLocs.insert(FileStart).second) {
1292 SourceRegions.emplace_back(*ParentCounter, FileStart,
1293 getEndOfFileOrMacro(Loc));
1294 assert(SpellingRegion(SM, SourceRegions.back()).isInSourceOrder());
1295 }
1296 Loc = getIncludeOrExpansionLoc(Loc);
1297 }
1298 }
1299
1300 MostRecentLocation = NewLoc;
1301 }
1302
1303 /// Ensure that \c S is included in the current region.
1304 void extendRegion(const Stmt *S) {
1305 SourceMappingRegion &Region = getRegion();
1306 SourceLocation StartLoc = getStart(S);
1307
1308 handleFileExit(StartLoc);
1309 if (!Region.hasStartLoc())
1310 Region.setStartLoc(StartLoc);
1311 }
1312
1313 /// Mark \c S as a terminator, starting a zero region.
1314 void terminateRegion(const Stmt *S) {
1315 extendRegion(S);
1316 SourceMappingRegion &Region = getRegion();
1317 SourceLocation EndLoc = getEnd(S);
1318 if (!Region.hasEndLoc())
1319 Region.setEndLoc(EndLoc);
1320 pushRegion(Counter::getZero());
1321 HasTerminateStmt = true;
1322 }
1323
1324 /// Find a valid gap range between \p AfterLoc and \p BeforeLoc.
1325 std::optional<SourceRange> findGapAreaBetween(SourceLocation AfterLoc,
1326 SourceLocation BeforeLoc) {
1327 // Some statements (like AttributedStmt and ImplicitValueInitExpr) don't
1328 // have valid source locations. Do not emit a gap region if this is the case
1329 // in either AfterLoc end or BeforeLoc end.
1330 if (AfterLoc.isInvalid() || BeforeLoc.isInvalid())
1331 return std::nullopt;
1332
1333 // If AfterLoc is in function-like macro, use the right parenthesis
1334 // location.
1335 if (AfterLoc.isMacroID()) {
1336 FileID FID = SM.getFileID(AfterLoc);
1337 const SrcMgr::ExpansionInfo *EI = &SM.getSLocEntry(FID).getExpansion();
1338 if (EI->isFunctionMacroExpansion())
1339 AfterLoc = EI->getExpansionLocEnd();
1340 }
1341
1342 size_t StartDepth = locationDepth(AfterLoc);
1343 size_t EndDepth = locationDepth(BeforeLoc);
1344 while (!SM.isWrittenInSameFile(AfterLoc, BeforeLoc)) {
1345 bool UnnestStart = StartDepth >= EndDepth;
1346 bool UnnestEnd = EndDepth >= StartDepth;
1347 if (UnnestEnd) {
1348 assert(SM.isWrittenInSameFile(getStartOfFileOrMacro(BeforeLoc),
1349 BeforeLoc));
1350
1351 BeforeLoc = getIncludeOrExpansionLoc(BeforeLoc);
1352 assert(BeforeLoc.isValid());
1353 EndDepth--;
1354 }
1355 if (UnnestStart) {
1356 assert(SM.isWrittenInSameFile(AfterLoc,
1357 getEndOfFileOrMacro(AfterLoc)));
1358
1359 AfterLoc = getIncludeOrExpansionLoc(AfterLoc);
1360 assert(AfterLoc.isValid());
1361 AfterLoc = getPreciseTokenLocEnd(AfterLoc);
1362 assert(AfterLoc.isValid());
1363 StartDepth--;
1364 }
1365 }
1366 AfterLoc = getPreciseTokenLocEnd(AfterLoc);
1367 // If the start and end locations of the gap are both within the same macro
1368 // file, the range may not be in source order.
1369 if (AfterLoc.isMacroID() || BeforeLoc.isMacroID())
1370 return std::nullopt;
1371 if (!SM.isWrittenInSameFile(AfterLoc, BeforeLoc) ||
1372 !SpellingRegion(SM, AfterLoc, BeforeLoc).isInSourceOrder())
1373 return std::nullopt;
1374 return {{AfterLoc, BeforeLoc}};
1375 }
1376
1377 /// Emit a gap region between \p StartLoc and \p EndLoc with the given count.
1378 void fillGapAreaWithCount(SourceLocation StartLoc, SourceLocation EndLoc,
1379 Counter Count) {
1380 if (StartLoc == EndLoc)
1381 return;
1382 assert(SpellingRegion(SM, StartLoc, EndLoc).isInSourceOrder());
1383 handleFileExit(StartLoc);
1384 size_t Index = pushRegion(Count, StartLoc, EndLoc);
1385 getRegion().setGap(true);
1386 handleFileExit(EndLoc);
1387 popRegions(Index);
1388 }
1389
1390 /// Find a valid range starting with \p StartingLoc and ending before \p
1391 /// BeforeLoc.
1392 std::optional<SourceRange> findAreaStartingFromTo(SourceLocation StartingLoc,
1393 SourceLocation BeforeLoc) {
1394 // If StartingLoc is in function-like macro, use its start location.
1395 if (StartingLoc.isMacroID()) {
1396 FileID FID = SM.getFileID(StartingLoc);
1397 const SrcMgr::ExpansionInfo *EI = &SM.getSLocEntry(FID).getExpansion();
1398 if (EI->isFunctionMacroExpansion())
1399 StartingLoc = EI->getExpansionLocStart();
1400 }
1401
1402 size_t StartDepth = locationDepth(StartingLoc);
1403 size_t EndDepth = locationDepth(BeforeLoc);
1404 while (!SM.isWrittenInSameFile(StartingLoc, BeforeLoc)) {
1405 bool UnnestStart = StartDepth >= EndDepth;
1406 bool UnnestEnd = EndDepth >= StartDepth;
1407 if (UnnestEnd) {
1408 assert(SM.isWrittenInSameFile(getStartOfFileOrMacro(BeforeLoc),
1409 BeforeLoc));
1410
1411 BeforeLoc = getIncludeOrExpansionLoc(BeforeLoc);
1412 assert(BeforeLoc.isValid());
1413 EndDepth--;
1414 }
1415 if (UnnestStart) {
1416 assert(SM.isWrittenInSameFile(StartingLoc,
1417 getStartOfFileOrMacro(StartingLoc)));
1418
1419 StartingLoc = getIncludeOrExpansionLoc(StartingLoc);
1420 assert(StartingLoc.isValid());
1421 StartDepth--;
1422 }
1423 }
1424 // If the start and end locations of the gap are both within the same macro
1425 // file, the range may not be in source order.
1426 if (StartingLoc.isMacroID() || BeforeLoc.isMacroID())
1427 return std::nullopt;
1428 if (!SM.isWrittenInSameFile(StartingLoc, BeforeLoc) ||
1429 !SpellingRegion(SM, StartingLoc, BeforeLoc).isInSourceOrder())
1430 return std::nullopt;
1431 return {{StartingLoc, BeforeLoc}};
1432 }
1433
1434 void markSkipped(SourceLocation StartLoc, SourceLocation BeforeLoc) {
1435 const auto Skipped = findAreaStartingFromTo(StartLoc, BeforeLoc);
1436
1437 if (!Skipped)
1438 return;
1439
1440 const auto NewStartLoc = Skipped->getBegin();
1441 const auto EndLoc = Skipped->getEnd();
1442
1443 if (NewStartLoc == EndLoc)
1444 return;
1445 assert(SpellingRegion(SM, NewStartLoc, EndLoc).isInSourceOrder());
1446 handleFileExit(NewStartLoc);
1447 size_t Index = pushRegion(Counter{}, NewStartLoc, EndLoc);
1448 getRegion().setSkipped(true);
1449 handleFileExit(EndLoc);
1450 popRegions(Index);
1451 }
1452
1453 /// Keep counts of breaks and continues inside loops.
1454 struct BreakContinue {
1455 Counter BreakCount;
1456 Counter ContinueCount;
1457 };
1458 SmallVector<BreakContinue, 8> BreakContinueStack;
1459
1460 CounterCoverageMappingBuilder(
1461 CoverageMappingModuleGen &CVM,
1462 llvm::DenseMap<const Stmt *, CounterPair> &CounterMap,
1463 MCDC::State &MCDCState, SourceManager &SM, const LangOptions &LangOpts)
1464 : CoverageMappingBuilder(CVM, SM, LangOpts), CounterMap(CounterMap),
1465 MCDCState(MCDCState), MCDCBuilder(CVM.getCodeGenModule(), MCDCState) {}
1466
1467 /// Write the mapping data to the output stream
1468 void write(llvm::raw_ostream &OS) {
1469 llvm::SmallVector<unsigned, 8> VirtualFileMapping;
1470 gatherFileIDs(VirtualFileMapping);
1471 SourceRegionFilter Filter = emitExpansionRegions();
1472 emitSourceRegions(Filter);
1473 gatherSkippedRegions();
1474
1475 if (MappingRegions.empty())
1476 return;
1477
1478 CoverageMappingWriter Writer(VirtualFileMapping, Builder.getExpressions(),
1479 MappingRegions);
1480 Writer.write(OS);
1481 }
1482
1483 void VisitStmt(const Stmt *S) {
1484 if (S->getBeginLoc().isValid())
1485 extendRegion(S);
1486 const Stmt *LastStmt = nullptr;
1487 bool SaveTerminateStmt = HasTerminateStmt;
1488 HasTerminateStmt = false;
1489 GapRegionCounter = Counter::getZero();
1490 for (const Stmt *Child : S->children())
1491 if (Child) {
1492 // If last statement contains terminate statements, add a gap area
1493 // between the two statements.
1494 if (LastStmt && HasTerminateStmt) {
1495 auto Gap = findGapAreaBetween(getEnd(LastStmt), getStart(Child));
1496 if (Gap)
1497 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(),
1498 GapRegionCounter);
1499 SaveTerminateStmt = true;
1500 HasTerminateStmt = false;
1501 }
1502 this->Visit(Child);
1503 LastStmt = Child;
1504 }
1505 if (SaveTerminateStmt)
1506 HasTerminateStmt = true;
1507 handleFileExit(getEnd(S));
1508 }
1509
1510 void VisitStmtExpr(const StmtExpr *E) {
1511 Visit(E->getSubStmt());
1512 // Any region termination (such as a noreturn CallExpr) within the statement
1513 // expression has been handled by visiting the sub-statement. The visitor
1514 // cannot be at a terminate statement leaving the statement expression.
1515 HasTerminateStmt = false;
1516 }
1517
1518 void VisitDecl(const Decl *D) {
1519 Stmt *Body = D->getBody();
1520
1521 // Do not propagate region counts into system headers unless collecting
1522 // coverage from system headers is explicitly enabled.
1523 if (!SystemHeadersCoverage && Body &&
1524 SM.isInSystemHeader(SM.getSpellingLoc(getStart(Body))))
1525 return;
1526
1527 // Do not visit the artificial children nodes of defaulted methods. The
1528 // lexer may not be able to report back precise token end locations for
1529 // these children nodes (llvm.org/PR39822), and moreover users will not be
1530 // able to see coverage for them.
1531 Counter BodyCounter = getRegionCounter(Body);
1532 bool Defaulted = false;
1533 if (auto *Method = dyn_cast<CXXMethodDecl>(D))
1534 Defaulted = Method->isDefaulted();
1535 if (auto *Ctor = dyn_cast<CXXConstructorDecl>(D)) {
1536 for (auto *Initializer : Ctor->inits()) {
1537 if (Initializer->isWritten()) {
1538 auto *Init = Initializer->getInit();
1539 if (getStart(Init).isValid() && getEnd(Init).isValid())
1540 propagateCounts(BodyCounter, Init);
1541 }
1542 }
1543 }
1544
1545 propagateCounts(BodyCounter, Body,
1546 /*VisitChildren=*/!Defaulted);
1547 assert(RegionStack.empty() && "Regions entered but never exited");
1548 }
1549
1550 void VisitReturnStmt(const ReturnStmt *S) {
1551 extendRegion(S);
1552 if (S->getRetValue())
1553 Visit(S->getRetValue());
1554 terminateRegion(S);
1555 }
1556
1557 void VisitCoroutineBodyStmt(const CoroutineBodyStmt *S) {
1558 extendRegion(S);
1559 Visit(S->getBody());
1560 }
1561
1562 void VisitCoreturnStmt(const CoreturnStmt *S) {
1563 extendRegion(S);
1564 if (S->getOperand())
1565 Visit(S->getOperand());
1566 terminateRegion(S);
1567 }
1568
1569 void VisitCoroutineSuspendExpr(const CoroutineSuspendExpr *E) {
1570 Visit(E->getOperand());
1571 }
1572
1573 void VisitCXXThrowExpr(const CXXThrowExpr *E) {
1574 extendRegion(E);
1575 if (E->getSubExpr())
1576 Visit(E->getSubExpr());
1577 terminateRegion(E);
1578 }
1579
1580 void VisitGotoStmt(const GotoStmt *S) { terminateRegion(S); }
1581
1582 void VisitLabelStmt(const LabelStmt *S) {
1583 Counter LabelCount = getRegionCounter(S);
1584 SourceLocation Start = getStart(S);
1585 // We can't extendRegion here or we risk overlapping with our new region.
1586 handleFileExit(Start);
1587 pushRegion(LabelCount, Start);
1588 Visit(S->getSubStmt());
1589 }
1590
1591 void VisitBreakStmt(const BreakStmt *S) {
1592 assert(!BreakContinueStack.empty() && "break not in a loop or switch!");
1594 BreakContinueStack.back().BreakCount = addCounters(
1595 BreakContinueStack.back().BreakCount, getRegion().getCounter());
1596 // FIXME: a break in a switch should terminate regions for all preceding
1597 // case statements, not just the most recent one.
1598 terminateRegion(S);
1599 }
1600
1601 void VisitContinueStmt(const ContinueStmt *S) {
1602 assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
1604 BreakContinueStack.back().ContinueCount = addCounters(
1605 BreakContinueStack.back().ContinueCount, getRegion().getCounter());
1606 terminateRegion(S);
1607 }
1608
1609 void VisitCallExpr(const CallExpr *E) {
1610 VisitStmt(E);
1611
1612 // Terminate the region when we hit a noreturn function.
1613 // (This is helpful dealing with switch statements.)
1614 QualType CalleeType = E->getCallee()->getType();
1615 if (getFunctionExtInfo(*CalleeType).getNoReturn())
1616 terminateRegion(E);
1617 }
1618
1619 void VisitWhileStmt(const WhileStmt *S) {
1620 extendRegion(S);
1621
1622 Counter ParentCount = getRegion().getCounter();
1623 Counter BodyCount = llvm::EnableSingleByteCoverage
1624 ? getRegionCounter(S->getBody())
1625 : getRegionCounter(S);
1626
1627 // Handle the body first so that we can get the backedge count.
1628 BreakContinueStack.push_back(BreakContinue());
1629 extendRegion(S->getBody());
1630 Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
1631 BreakContinue BC = BreakContinueStack.pop_back_val();
1632
1633 bool BodyHasTerminateStmt = HasTerminateStmt;
1634 HasTerminateStmt = false;
1635
1636 // Go back to handle the condition.
1637 Counter CondCount =
1639 ? getRegionCounter(S->getCond())
1640 : addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
1641 auto BranchCount = getBranchCounterPair(S, CondCount, getRegionCounter(S));
1642 assert(BranchCount.Executed.isZero() || BranchCount.Executed == BodyCount ||
1644
1645 propagateCounts(CondCount, S->getCond());
1646 adjustForOutOfOrderTraversal(getEnd(S));
1647
1648 // The body count applies to the area immediately after the increment.
1649 auto Gap = findGapAreaBetween(S->getRParenLoc(), getStart(S->getBody()));
1650 if (Gap)
1651 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1652
1653 assert(
1655 (BC.BreakCount.isZero() && BranchCount.Skipped == getRegionCounter(S)));
1656 Counter OutCount = addCounters(BC.BreakCount, BranchCount.Skipped);
1657 if (!IsCounterEqual(OutCount, ParentCount)) {
1658 pushRegion(OutCount);
1659 GapRegionCounter = OutCount;
1660 if (BodyHasTerminateStmt)
1661 HasTerminateStmt = true;
1662 }
1663
1664 // Create Branch Region around condition.
1666 createBranchRegion(S->getCond(), BodyCount, BranchCount.Skipped);
1667 }
1668
1669 void VisitDoStmt(const DoStmt *S) {
1670 extendRegion(S);
1671
1672 Counter ParentCount = getRegion().getCounter();
1673 Counter BodyCount = llvm::EnableSingleByteCoverage
1674 ? getRegionCounter(S->getBody())
1675 : getRegionCounter(S);
1676
1677 BreakContinueStack.push_back(BreakContinue());
1678 extendRegion(S->getBody());
1679
1680 Counter BackedgeCount;
1682 propagateCounts(BodyCount, S->getBody());
1683 else
1684 BackedgeCount =
1685 propagateCounts(addCounters(ParentCount, BodyCount), S->getBody());
1686
1687 BreakContinue BC = BreakContinueStack.pop_back_val();
1688
1689 bool BodyHasTerminateStmt = HasTerminateStmt;
1690 HasTerminateStmt = false;
1691
1692 Counter CondCount = llvm::EnableSingleByteCoverage
1693 ? getRegionCounter(S->getCond())
1694 : addCounters(BackedgeCount, BC.ContinueCount);
1695 auto BranchCount = getBranchCounterPair(S, CondCount, getRegionCounter(S));
1696 assert(BranchCount.Executed.isZero() || BranchCount.Executed == BodyCount ||
1698
1699 propagateCounts(CondCount, S->getCond());
1700
1701 assert(
1703 (BC.BreakCount.isZero() && BranchCount.Skipped == getRegionCounter(S)));
1704 Counter OutCount = addCounters(BC.BreakCount, BranchCount.Skipped);
1705 if (!IsCounterEqual(OutCount, ParentCount)) {
1706 pushRegion(OutCount);
1707 GapRegionCounter = OutCount;
1708 if (BodyHasTerminateStmt)
1709 HasTerminateStmt = true;
1710 }
1711
1712 // Create Branch Region around condition.
1714 createBranchRegion(S->getCond(), BodyCount, BranchCount.Skipped);
1715 }
1716
1717 void VisitForStmt(const ForStmt *S) {
1718 extendRegion(S);
1719 if (S->getInit())
1720 Visit(S->getInit());
1721
1722 Counter ParentCount = getRegion().getCounter();
1723 Counter BodyCount = llvm::EnableSingleByteCoverage
1724 ? getRegionCounter(S->getBody())
1725 : getRegionCounter(S);
1726
1727 // The loop increment may contain a break or continue.
1728 if (S->getInc())
1729 BreakContinueStack.emplace_back();
1730
1731 // Handle the body first so that we can get the backedge count.
1732 BreakContinueStack.emplace_back();
1733 extendRegion(S->getBody());
1734 Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
1735 BreakContinue BodyBC = BreakContinueStack.pop_back_val();
1736
1737 bool BodyHasTerminateStmt = HasTerminateStmt;
1738 HasTerminateStmt = false;
1739
1740 // The increment is essentially part of the body but it needs to include
1741 // the count for all the continue statements.
1742 BreakContinue IncrementBC;
1743 if (const Stmt *Inc = S->getInc()) {
1744 Counter IncCount;
1745 if (llvm::EnableSingleByteCoverage)
1746 IncCount = getRegionCounter(S->getInc());
1747 else
1748 IncCount = addCounters(BackedgeCount, BodyBC.ContinueCount);
1749 propagateCounts(IncCount, Inc);
1750 IncrementBC = BreakContinueStack.pop_back_val();
1751 }
1752
1753 // Go back to handle the condition.
1754 Counter CondCount =
1756 ? getRegionCounter(S->getCond())
1757 : addCounters(
1758 addCounters(ParentCount, BackedgeCount, BodyBC.ContinueCount),
1759 IncrementBC.ContinueCount);
1760 auto BranchCount = getBranchCounterPair(S, CondCount, getRegionCounter(S));
1761 assert(BranchCount.Executed.isZero() || BranchCount.Executed == BodyCount ||
1763
1764 if (const Expr *Cond = S->getCond()) {
1765 propagateCounts(CondCount, Cond);
1766 adjustForOutOfOrderTraversal(getEnd(S));
1767 }
1768
1769 // The body count applies to the area immediately after the increment.
1770 auto Gap = findGapAreaBetween(S->getRParenLoc(), getStart(S->getBody()));
1771 if (Gap)
1772 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1773
1775 (BodyBC.BreakCount.isZero() && IncrementBC.BreakCount.isZero()));
1776 Counter OutCount = addCounters(BodyBC.BreakCount, IncrementBC.BreakCount,
1777 BranchCount.Skipped);
1778 if (!IsCounterEqual(OutCount, ParentCount)) {
1779 pushRegion(OutCount);
1780 GapRegionCounter = OutCount;
1781 if (BodyHasTerminateStmt)
1782 HasTerminateStmt = true;
1783 }
1784
1785 // Create Branch Region around condition.
1787 createBranchRegion(S->getCond(), BodyCount, BranchCount.Skipped);
1788 }
1789
1790 void VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
1791 extendRegion(S);
1792 if (S->getInit())
1793 Visit(S->getInit());
1794 Visit(S->getLoopVarStmt());
1795 Visit(S->getRangeStmt());
1796
1797 Counter ParentCount = getRegion().getCounter();
1798 Counter BodyCount = llvm::EnableSingleByteCoverage
1799 ? getRegionCounter(S->getBody())
1800 : getRegionCounter(S);
1801
1802 BreakContinueStack.push_back(BreakContinue());
1803 extendRegion(S->getBody());
1804 Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
1805 BreakContinue BC = BreakContinueStack.pop_back_val();
1806
1807 bool BodyHasTerminateStmt = HasTerminateStmt;
1808 HasTerminateStmt = false;
1809
1810 // The body count applies to the area immediately after the range.
1811 auto Gap = findGapAreaBetween(S->getRParenLoc(), getStart(S->getBody()));
1812 if (Gap)
1813 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1814
1815 Counter LoopCount =
1816 addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
1817 auto BranchCount = getBranchCounterPair(S, LoopCount, getRegionCounter(S));
1818 assert(BranchCount.Executed.isZero() || BranchCount.Executed == BodyCount ||
1820 assert(
1822 (BC.BreakCount.isZero() && BranchCount.Skipped == getRegionCounter(S)));
1823
1824 Counter OutCount = addCounters(BC.BreakCount, BranchCount.Skipped);
1825 if (!IsCounterEqual(OutCount, ParentCount)) {
1826 pushRegion(OutCount);
1827 GapRegionCounter = OutCount;
1828 if (BodyHasTerminateStmt)
1829 HasTerminateStmt = true;
1830 }
1831
1832 // Create Branch Region around condition.
1834 createBranchRegion(S->getCond(), BodyCount, BranchCount.Skipped);
1835 }
1836
1837 void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) {
1838 extendRegion(S);
1839 Visit(S->getElement());
1840
1841 Counter ParentCount = getRegion().getCounter();
1842 Counter BodyCount = getRegionCounter(S);
1843
1844 BreakContinueStack.push_back(BreakContinue());
1845 extendRegion(S->getBody());
1846 Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
1847 BreakContinue BC = BreakContinueStack.pop_back_val();
1848
1849 // The body count applies to the area immediately after the collection.
1850 auto Gap = findGapAreaBetween(S->getRParenLoc(), getStart(S->getBody()));
1851 if (Gap)
1852 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1853
1854 Counter LoopCount =
1855 addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
1856 auto BranchCount = getBranchCounterPair(S, LoopCount);
1857 assert(BranchCount.Executed.isZero() || BranchCount.Executed == BodyCount);
1858 Counter OutCount = addCounters(BC.BreakCount, BranchCount.Skipped);
1859 if (!IsCounterEqual(OutCount, ParentCount)) {
1860 pushRegion(OutCount);
1861 GapRegionCounter = OutCount;
1862 }
1863 }
1864
1865 void VisitSwitchStmt(const SwitchStmt *S) {
1866 extendRegion(S);
1867 if (S->getInit())
1868 Visit(S->getInit());
1869 Visit(S->getCond());
1870
1871 BreakContinueStack.push_back(BreakContinue());
1872
1873 const Stmt *Body = S->getBody();
1874 extendRegion(Body);
1875 if (const auto *CS = dyn_cast<CompoundStmt>(Body)) {
1876 if (!CS->body_empty()) {
1877 // Make a region for the body of the switch. If the body starts with
1878 // a case, that case will reuse this region; otherwise, this covers
1879 // the unreachable code at the beginning of the switch body.
1880 size_t Index = pushRegion(Counter::getZero(), getStart(CS));
1881 getRegion().setGap(true);
1882 Visit(Body);
1883
1884 // Set the end for the body of the switch, if it isn't already set.
1885 for (size_t i = RegionStack.size(); i != Index; --i) {
1886 if (!RegionStack[i - 1].hasEndLoc())
1887 RegionStack[i - 1].setEndLoc(getEnd(CS->body_back()));
1888 }
1889
1890 popRegions(Index);
1891 }
1892 } else
1893 propagateCounts(Counter::getZero(), Body);
1894 BreakContinue BC = BreakContinueStack.pop_back_val();
1895
1896 if (!BreakContinueStack.empty() && !llvm::EnableSingleByteCoverage)
1897 BreakContinueStack.back().ContinueCount = addCounters(
1898 BreakContinueStack.back().ContinueCount, BC.ContinueCount);
1899
1900 Counter ParentCount = getRegion().getCounter();
1901 Counter ExitCount = getRegionCounter(S);
1902 SourceLocation ExitLoc = getEnd(S);
1903 pushRegion(ExitCount);
1904 GapRegionCounter = ExitCount;
1905
1906 // Ensure that handleFileExit recognizes when the end location is located
1907 // in a different file.
1908 MostRecentLocation = getStart(S);
1909 handleFileExit(ExitLoc);
1910
1911 // When single byte coverage mode is enabled, do not create branch region by
1912 // early returning.
1914 return;
1915
1916 // Create a Branch Region around each Case. Subtract the case's
1917 // counter from the Parent counter to track the "False" branch count.
1918 Counter CaseCountSum;
1919 bool HasDefaultCase = false;
1920 const SwitchCase *Case = S->getSwitchCaseList();
1921 for (; Case; Case = Case->getNextSwitchCase()) {
1922 HasDefaultCase = HasDefaultCase || isa<DefaultStmt>(Case);
1923 auto CaseCount = createSwitchCaseRegion(Case, ParentCount);
1924 CaseCountSum = addCounters(CaseCountSum, CaseCount, /*Simplify=*/false);
1925 }
1926 // If no explicit default case exists, create a branch region to represent
1927 // the hidden branch, which will be added later by the CodeGen. This region
1928 // will be associated with the switch statement's condition.
1929 if (!HasDefaultCase) {
1930 // Simplify is skipped while building the counters above: it can get
1931 // really slow on top of switches with thousands of cases. Instead,
1932 // trigger simplification by adding zero to the last counter.
1933 CaseCountSum =
1934 addCounters(CaseCountSum, Counter::getZero(), /*Simplify=*/true);
1935
1936 // This is considered as the False count on SwitchStmt.
1937 Counter SwitchFalse = subtractCounters(ParentCount, CaseCountSum);
1938 createBranchRegion(S->getCond(), CaseCountSum, SwitchFalse);
1939 }
1940 }
1941
1942 void VisitSwitchCase(const SwitchCase *S) {
1943 extendRegion(S);
1944
1945 SourceMappingRegion &Parent = getRegion();
1946 Counter Count = llvm::EnableSingleByteCoverage
1947 ? getRegionCounter(S)
1948 : addCounters(Parent.getCounter(), getRegionCounter(S));
1949
1950 // Reuse the existing region if it starts at our label. This is typical of
1951 // the first case in a switch.
1952 if (Parent.hasStartLoc() && Parent.getBeginLoc() == getStart(S))
1953 Parent.setCounter(Count);
1954 else
1955 pushRegion(Count, getStart(S));
1956
1957 GapRegionCounter = Count;
1958
1959 if (const auto *CS = dyn_cast<CaseStmt>(S)) {
1960 Visit(CS->getLHS());
1961 if (const Expr *RHS = CS->getRHS())
1962 Visit(RHS);
1963 }
1964 Visit(S->getSubStmt());
1965 }
1966
1967 void coverIfConsteval(const IfStmt *S) {
1968 assert(S->isConsteval());
1969
1970 const auto *Then = S->getThen();
1971 const auto *Else = S->getElse();
1972
1973 // It's better for llvm-cov to create a new region with same counter
1974 // so line-coverage can be properly calculated for lines containing
1975 // a skipped region (without it the line is marked uncovered)
1976 const Counter ParentCount = getRegion().getCounter();
1977
1978 extendRegion(S);
1979
1980 if (S->isNegatedConsteval()) {
1981 // ignore 'if consteval'
1982 markSkipped(S->getIfLoc(), getStart(Then));
1983 propagateCounts(ParentCount, Then);
1984
1985 if (Else) {
1986 // ignore 'else <else>'
1987 markSkipped(getEnd(Then), getEnd(Else));
1988 }
1989 } else {
1990 assert(S->isNonNegatedConsteval());
1991 // ignore 'if consteval <then> [else]'
1992 markSkipped(S->getIfLoc(), Else ? getStart(Else) : getEnd(Then));
1993
1994 if (Else)
1995 propagateCounts(ParentCount, Else);
1996 }
1997 }
1998
1999 void coverIfConstexpr(const IfStmt *S) {
2000 assert(S->isConstexpr());
2001
2002 // evaluate constant condition...
2003 const bool isTrue =
2004 S->getCond()
2006 .getBoolValue();
2007
2008 extendRegion(S);
2009
2010 // I'm using 'propagateCounts' later as new region is better and allows me
2011 // to properly calculate line coverage in llvm-cov utility
2012 const Counter ParentCount = getRegion().getCounter();
2013
2014 // ignore 'if constexpr ('
2015 SourceLocation startOfSkipped = S->getIfLoc();
2016
2017 if (const auto *Init = S->getInit()) {
2018 const auto start = getStart(Init);
2019 const auto end = getEnd(Init);
2020
2021 // this check is to make sure typedef here which doesn't have valid source
2022 // location won't crash it
2023 if (start.isValid() && end.isValid()) {
2024 markSkipped(startOfSkipped, start);
2025 propagateCounts(ParentCount, Init);
2026 startOfSkipped = getEnd(Init);
2027 }
2028 }
2029
2030 const auto *Then = S->getThen();
2031 const auto *Else = S->getElse();
2032
2033 if (isTrue) {
2034 // ignore '<condition>)'
2035 markSkipped(startOfSkipped, getStart(Then));
2036 propagateCounts(ParentCount, Then);
2037
2038 if (Else)
2039 // ignore 'else <else>'
2040 markSkipped(getEnd(Then), getEnd(Else));
2041 } else {
2042 // ignore '<condition>) <then> [else]'
2043 markSkipped(startOfSkipped, Else ? getStart(Else) : getEnd(Then));
2044
2045 if (Else)
2046 propagateCounts(ParentCount, Else);
2047 }
2048 }
2049
2050 void VisitIfStmt(const IfStmt *S) {
2051 // "if constexpr" and "if consteval" are not normal conditional statements,
2052 // their discarded statement should be skipped
2053 if (S->isConsteval())
2054 return coverIfConsteval(S);
2055 else if (S->isConstexpr())
2056 return coverIfConstexpr(S);
2057
2058 extendRegion(S);
2059 if (S->getInit())
2060 Visit(S->getInit());
2061
2062 // Extend into the condition before we propagate through it below - this is
2063 // needed to handle macros that generate the "if" but not the condition.
2064 extendRegion(S->getCond());
2065
2066 Counter ParentCount = getRegion().getCounter();
2067 auto [ThenCount, ElseCount] =
2069 ? BranchCounterPair{getRegionCounter(S->getThen()),
2070 (S->getElse() ? getRegionCounter(S->getElse())
2071 : Counter::getZero())}
2072 : getBranchCounterPair(S, ParentCount));
2073
2074 // Emitting a counter for the condition makes it easier to interpret the
2075 // counter for the body when looking at the coverage.
2076 propagateCounts(ParentCount, S->getCond());
2077
2078 // The 'then' count applies to the area immediately after the condition.
2079 std::optional<SourceRange> Gap =
2080 findGapAreaBetween(S->getRParenLoc(), getStart(S->getThen()));
2081 if (Gap)
2082 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), ThenCount);
2083
2084 extendRegion(S->getThen());
2085 Counter OutCount = propagateCounts(ThenCount, S->getThen());
2086
2087 if (const Stmt *Else = S->getElse()) {
2088 bool ThenHasTerminateStmt = HasTerminateStmt;
2089 HasTerminateStmt = false;
2090 // The 'else' count applies to the area immediately after the 'then'.
2091 std::optional<SourceRange> Gap =
2092 findGapAreaBetween(getEnd(S->getThen()), getStart(Else));
2093 if (Gap)
2094 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), ElseCount);
2095 extendRegion(Else);
2096
2097 Counter ElseOutCount = propagateCounts(ElseCount, Else);
2099 OutCount = addCounters(OutCount, ElseOutCount);
2100
2101 if (ThenHasTerminateStmt)
2102 HasTerminateStmt = true;
2104 OutCount = addCounters(OutCount, ElseCount);
2105
2107 OutCount = getRegionCounter(S);
2108
2109 if (!IsCounterEqual(OutCount, ParentCount)) {
2110 pushRegion(OutCount);
2111 GapRegionCounter = OutCount;
2112 }
2113
2115 // Create Branch Region around condition.
2116 createBranchRegion(S->getCond(), ThenCount, ElseCount);
2117 }
2118
2119 void VisitCXXTryStmt(const CXXTryStmt *S) {
2120 extendRegion(S);
2121 // Handle macros that generate the "try" but not the rest.
2122 extendRegion(S->getTryBlock());
2123
2124 Counter ParentCount = getRegion().getCounter();
2125 propagateCounts(ParentCount, S->getTryBlock());
2126
2127 for (unsigned I = 0, E = S->getNumHandlers(); I < E; ++I)
2128 Visit(S->getHandler(I));
2129
2130 Counter ExitCount = getRegionCounter(S);
2131 pushRegion(ExitCount);
2132 }
2133
2134 void VisitCXXCatchStmt(const CXXCatchStmt *S) {
2135 propagateCounts(getRegionCounter(S), S->getHandlerBlock());
2136 }
2137
2138 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
2139 extendRegion(E);
2140
2141 Counter ParentCount = getRegion().getCounter();
2142 auto [TrueCount, FalseCount] =
2144 ? BranchCounterPair{getRegionCounter(E->getTrueExpr()),
2145 getRegionCounter(E->getFalseExpr())}
2146 : getBranchCounterPair(E, ParentCount));
2147 Counter OutCount;
2148
2149 if (const auto *BCO = dyn_cast<BinaryConditionalOperator>(E)) {
2150 propagateCounts(ParentCount, BCO->getCommon());
2151 OutCount = TrueCount;
2152 } else {
2153 propagateCounts(ParentCount, E->getCond());
2154 // The 'then' count applies to the area immediately after the condition.
2155 auto Gap =
2156 findGapAreaBetween(E->getQuestionLoc(), getStart(E->getTrueExpr()));
2157 if (Gap)
2158 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), TrueCount);
2159
2160 extendRegion(E->getTrueExpr());
2161 OutCount = propagateCounts(TrueCount, E->getTrueExpr());
2162 }
2163
2164 extendRegion(E->getFalseExpr());
2165 Counter FalseOutCount = propagateCounts(FalseCount, E->getFalseExpr());
2167 OutCount = getRegionCounter(E);
2168 else
2169 OutCount = addCounters(OutCount, FalseOutCount);
2170
2171 if (!IsCounterEqual(OutCount, ParentCount)) {
2172 pushRegion(OutCount);
2173 GapRegionCounter = OutCount;
2174 }
2175
2176 // Create Branch Region around condition.
2178 createBranchRegion(E->getCond(), TrueCount, FalseCount);
2179 }
2180
2181 void createOrCancelDecision(const BinaryOperator *E, unsigned Since) {
2182 unsigned NumConds = MCDCBuilder.getTotalConditionsAndReset(E);
2183 if (NumConds == 0)
2184 return;
2185
2186 // Extract [ID, Conds] to construct the graph.
2187 llvm::SmallVector<mcdc::ConditionIDs> CondIDs(NumConds);
2188 for (const auto &SR : ArrayRef(SourceRegions).slice(Since)) {
2189 if (SR.isMCDCBranch()) {
2190 auto [ID, Conds] = SR.getMCDCBranchParams();
2191 CondIDs[ID] = Conds;
2192 }
2193 }
2194
2195 // Construct the graph and calculate `Indices`.
2196 mcdc::TVIdxBuilder Builder(CondIDs);
2197 unsigned NumTVs = Builder.NumTestVectors;
2198 unsigned MaxTVs = CVM.getCodeGenModule().getCodeGenOpts().MCDCMaxTVs;
2199 assert(MaxTVs < mcdc::TVIdxBuilder::HardMaxTVs);
2200
2201 if (NumTVs > MaxTVs) {
2202 // NumTVs exceeds MaxTVs -- warn and cancel the Decision.
2203 cancelDecision(E, Since, NumTVs, MaxTVs);
2204 return;
2205 }
2206
2207 // Update the state for CodeGenPGO
2208 assert(MCDCState.DecisionByStmt.contains(E));
2209 MCDCState.DecisionByStmt[E] = {
2210 MCDCState.BitmapBits, // Top
2211 std::move(Builder.Indices),
2212 };
2213
2214 auto DecisionParams = mcdc::DecisionParameters{
2215 MCDCState.BitmapBits += NumTVs, // Tail
2216 NumConds,
2217 };
2218
2219 // Create MCDC Decision Region.
2220 createDecisionRegion(E, DecisionParams);
2221 }
2222
2223 // Warn and cancel the Decision.
2224 void cancelDecision(const BinaryOperator *E, unsigned Since, int NumTVs,
2225 int MaxTVs) {
2226 auto &Diag = CVM.getCodeGenModule().getDiags();
2227 Diag.Report(E->getBeginLoc(), diag::warn_pgo_test_vector_limit)
2228 << NumTVs << MaxTVs;
2229
2230 // Restore MCDCBranch to Branch.
2231 for (auto &SR : MutableArrayRef(SourceRegions).slice(Since)) {
2232 assert(!SR.isMCDCDecision() && "Decision shouldn't be seen here");
2233 if (SR.isMCDCBranch())
2234 SR.resetMCDCParams();
2235 }
2236
2237 // Tell CodeGenPGO not to instrument.
2238 MCDCState.DecisionByStmt.erase(E);
2239 }
2240
2241 /// Check if E belongs to system headers.
2242 bool isExprInSystemHeader(const BinaryOperator *E) const {
2243 return (!SystemHeadersCoverage &&
2244 SM.isInSystemHeader(SM.getSpellingLoc(E->getOperatorLoc())) &&
2245 SM.isInSystemHeader(SM.getSpellingLoc(E->getBeginLoc())) &&
2246 SM.isInSystemHeader(SM.getSpellingLoc(E->getEndLoc())));
2247 }
2248
2249 void VisitBinLAnd(const BinaryOperator *E) {
2250 if (isExprInSystemHeader(E)) {
2251 LeafExprSet.insert(E);
2252 return;
2253 }
2254
2255 bool IsRootNode = MCDCBuilder.isIdle();
2256
2257 unsigned SourceRegionsSince = SourceRegions.size();
2258
2259 // Keep track of Binary Operator and assign MCDC condition IDs.
2260 MCDCBuilder.pushAndAssignIDs(E);
2261
2262 extendRegion(E->getLHS());
2263 propagateCounts(getRegion().getCounter(), E->getLHS());
2264 handleFileExit(getEnd(E->getLHS()));
2265
2266 // Track LHS True/False Decision.
2267 const auto DecisionLHS = MCDCBuilder.pop();
2268
2269 if (auto Gap =
2270 findGapAreaBetween(getEnd(E->getLHS()), getStart(E->getRHS()))) {
2271 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), getRegionCounter(E));
2272 }
2273
2274 // Counter tracks the right hand side of a logical and operator.
2275 extendRegion(E->getRHS());
2276 propagateCounts(getRegionCounter(E), E->getRHS());
2277
2279 return;
2280
2281 // Track RHS True/False Decision.
2282 const auto DecisionRHS = MCDCBuilder.back();
2283
2284 // Extract the Parent Region Counter.
2285 Counter ParentCnt = getRegion().getCounter();
2286
2287 // Extract the RHS's Execution Counter.
2288 auto [RHSExecCnt, LHSExitCnt] = getBranchCounterPair(E, ParentCnt);
2289
2290 // Extract the RHS's "True" Instance Counter.
2291 auto [RHSTrueCnt, RHSExitCnt] =
2292 getBranchCounterPair(E->getRHS(), RHSExecCnt);
2293
2294 // Create Branch Region around LHS condition.
2295 createBranchRegion(E->getLHS(), RHSExecCnt, LHSExitCnt, DecisionLHS);
2296
2297 // Create Branch Region around RHS condition.
2298 createBranchRegion(E->getRHS(), RHSTrueCnt, RHSExitCnt, DecisionRHS);
2299
2300 // Create MCDC Decision Region if at top-level (root).
2301 if (IsRootNode)
2302 createOrCancelDecision(E, SourceRegionsSince);
2303 }
2304
2305 // Determine whether the right side of OR operation need to be visited.
2306 bool shouldVisitRHS(const Expr *LHS) {
2307 bool LHSIsTrue = false;
2308 bool LHSIsConst = false;
2309 if (!LHS->isValueDependent())
2310 LHSIsConst = LHS->EvaluateAsBooleanCondition(
2311 LHSIsTrue, CVM.getCodeGenModule().getContext());
2312 return !LHSIsConst || (LHSIsConst && !LHSIsTrue);
2313 }
2314
2315 void VisitBinLOr(const BinaryOperator *E) {
2316 if (isExprInSystemHeader(E)) {
2317 LeafExprSet.insert(E);
2318 return;
2319 }
2320
2321 bool IsRootNode = MCDCBuilder.isIdle();
2322
2323 unsigned SourceRegionsSince = SourceRegions.size();
2324
2325 // Keep track of Binary Operator and assign MCDC condition IDs.
2326 MCDCBuilder.pushAndAssignIDs(E);
2327
2328 extendRegion(E->getLHS());
2329 Counter OutCount = propagateCounts(getRegion().getCounter(), E->getLHS());
2330 handleFileExit(getEnd(E->getLHS()));
2331
2332 // Track LHS True/False Decision.
2333 const auto DecisionLHS = MCDCBuilder.pop();
2334
2335 if (auto Gap =
2336 findGapAreaBetween(getEnd(E->getLHS()), getStart(E->getRHS()))) {
2337 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), getRegionCounter(E));
2338 }
2339
2340 // Counter tracks the right hand side of a logical or operator.
2341 extendRegion(E->getRHS());
2342 propagateCounts(getRegionCounter(E), E->getRHS());
2343
2345 return;
2346
2347 // Track RHS True/False Decision.
2348 const auto DecisionRHS = MCDCBuilder.back();
2349
2350 // Extract the Parent Region Counter.
2351 Counter ParentCnt = getRegion().getCounter();
2352
2353 // Extract the RHS's Execution Counter.
2354 auto [RHSExecCnt, LHSExitCnt] = getBranchCounterPair(E, ParentCnt);
2355
2356 // Extract the RHS's "False" Instance Counter.
2357 auto [RHSFalseCnt, RHSExitCnt] =
2358 getBranchCounterPair(E->getRHS(), RHSExecCnt);
2359
2360 if (!shouldVisitRHS(E->getLHS())) {
2361 GapRegionCounter = OutCount;
2362 }
2363
2364 // Create Branch Region around LHS condition.
2365 createBranchRegion(E->getLHS(), LHSExitCnt, RHSExecCnt, DecisionLHS);
2366
2367 // Create Branch Region around RHS condition.
2368 createBranchRegion(E->getRHS(), RHSExitCnt, RHSFalseCnt, DecisionRHS);
2369
2370 // Create MCDC Decision Region if at top-level (root).
2371 if (IsRootNode)
2372 createOrCancelDecision(E, SourceRegionsSince);
2373 }
2374
2375 void VisitLambdaExpr(const LambdaExpr *LE) {
2376 // Lambdas are treated as their own functions for now, so we shouldn't
2377 // propagate counts into them.
2378 }
2379
2380 void VisitArrayInitLoopExpr(const ArrayInitLoopExpr *AILE) {
2381 Visit(AILE->getCommonExpr()->getSourceExpr());
2382 }
2383
2384 void VisitPseudoObjectExpr(const PseudoObjectExpr *POE) {
2385 // Just visit syntatic expression as this is what users actually write.
2386 VisitStmt(POE->getSyntacticForm());
2387 }
2388
2389 void VisitOpaqueValueExpr(const OpaqueValueExpr* OVE) {
2390 if (OVE->isUnique())
2391 Visit(OVE->getSourceExpr());
2392 }
2393};
2394
2395} // end anonymous namespace
2396
2397static void dump(llvm::raw_ostream &OS, StringRef FunctionName,
2398 ArrayRef<CounterExpression> Expressions,
2400 OS << FunctionName << ":\n";
2401 CounterMappingContext Ctx(Expressions);
2402 for (const auto &R : Regions) {
2403 OS.indent(2);
2404 switch (R.Kind) {
2405 case CounterMappingRegion::CodeRegion:
2406 break;
2407 case CounterMappingRegion::ExpansionRegion:
2408 OS << "Expansion,";
2409 break;
2410 case CounterMappingRegion::SkippedRegion:
2411 OS << "Skipped,";
2412 break;
2413 case CounterMappingRegion::GapRegion:
2414 OS << "Gap,";
2415 break;
2416 case CounterMappingRegion::BranchRegion:
2417 case CounterMappingRegion::MCDCBranchRegion:
2418 OS << "Branch,";
2419 break;
2420 case CounterMappingRegion::MCDCDecisionRegion:
2421 OS << "Decision,";
2422 break;
2423 }
2424
2425 OS << "File " << R.FileID << ", " << R.LineStart << ":" << R.ColumnStart
2426 << " -> " << R.LineEnd << ":" << R.ColumnEnd << " = ";
2427
2428 if (const auto *DecisionParams =
2429 std::get_if<mcdc::DecisionParameters>(&R.MCDCParams)) {
2430 OS << "M:" << DecisionParams->BitmapIdx;
2431 OS << ", C:" << DecisionParams->NumConditions;
2432 } else {
2433 Ctx.dump(R.Count, OS);
2434
2435 if (R.isBranch()) {
2436 OS << ", ";
2437 Ctx.dump(R.FalseCount, OS);
2438 }
2439 }
2440
2441 if (const auto *BranchParams =
2442 std::get_if<mcdc::BranchParameters>(&R.MCDCParams)) {
2443 OS << " [" << BranchParams->ID + 1 << ","
2444 << BranchParams->Conds[true] + 1;
2445 OS << "," << BranchParams->Conds[false] + 1 << "] ";
2446 }
2447
2448 if (R.Kind == CounterMappingRegion::ExpansionRegion)
2449 OS << " (Expanded file = " << R.ExpandedFileID << ")";
2450 OS << "\n";
2451 }
2452}
2453
2455 CodeGenModule &CGM, CoverageSourceInfo &SourceInfo)
2456 : CGM(CGM), SourceInfo(SourceInfo) {}
2457
2458std::string CoverageMappingModuleGen::getCurrentDirname() {
2460}
2461
2462std::string CoverageMappingModuleGen::normalizeFilename(StringRef Filename) {
2463 llvm::SmallString<256> Path(Filename);
2464 llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
2465
2466 /// Traverse coverage prefix map in reverse order because prefix replacements
2467 /// are applied in reverse order starting from the last one when multiple
2468 /// prefix replacement options are provided.
2469 for (const auto &[From, To] :
2470 llvm::reverse(CGM.getCodeGenOpts().CoveragePrefixMap)) {
2471 if (llvm::sys::path::replace_path_prefix(Path, From, To))
2472 break;
2473 }
2474 return Path.str().str();
2475}
2476
2477static std::string getInstrProfSection(const CodeGenModule &CGM,
2478 llvm::InstrProfSectKind SK) {
2479 return llvm::getInstrProfSectionName(
2480 SK, CGM.getContext().getTargetInfo().getTriple().getObjectFormat());
2481}
2482
2483void CoverageMappingModuleGen::emitFunctionMappingRecord(
2484 const FunctionInfo &Info, uint64_t FilenamesRef) {
2485 llvm::LLVMContext &Ctx = CGM.getLLVMContext();
2486
2487 // Assign a name to the function record. This is used to merge duplicates.
2488 std::string FuncRecordName = "__covrec_" + llvm::utohexstr(Info.NameHash);
2489
2490 // A dummy description for a function included-but-not-used in a TU can be
2491 // replaced by full description provided by a different TU. The two kinds of
2492 // descriptions play distinct roles: therefore, assign them different names
2493 // to prevent `linkonce_odr` merging.
2494 if (Info.IsUsed)
2495 FuncRecordName += "u";
2496
2497 // Create the function record type.
2498 const uint64_t NameHash = Info.NameHash;
2499 const uint64_t FuncHash = Info.FuncHash;
2500 const std::string &CoverageMapping = Info.CoverageMapping;
2501#define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) LLVMType,
2502 llvm::Type *FunctionRecordTypes[] = {
2503#include "llvm/ProfileData/InstrProfData.inc"
2504 };
2505 auto *FunctionRecordTy =
2506 llvm::StructType::get(Ctx, ArrayRef(FunctionRecordTypes),
2507 /*isPacked=*/true);
2508
2509 // Create the function record constant.
2510#define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) Init,
2511 llvm::Constant *FunctionRecordVals[] = {
2512 #include "llvm/ProfileData/InstrProfData.inc"
2513 };
2514 auto *FuncRecordConstant =
2515 llvm::ConstantStruct::get(FunctionRecordTy, ArrayRef(FunctionRecordVals));
2516
2517 // Create the function record global.
2518 auto *FuncRecord = new llvm::GlobalVariable(
2519 CGM.getModule(), FunctionRecordTy, /*isConstant=*/true,
2520 llvm::GlobalValue::LinkOnceODRLinkage, FuncRecordConstant,
2521 FuncRecordName);
2522 FuncRecord->setVisibility(llvm::GlobalValue::HiddenVisibility);
2523 FuncRecord->setSection(getInstrProfSection(CGM, llvm::IPSK_covfun));
2524 FuncRecord->setAlignment(llvm::Align(8));
2525 if (CGM.supportsCOMDAT())
2526 FuncRecord->setComdat(CGM.getModule().getOrInsertComdat(FuncRecordName));
2527
2528 // Make sure the data doesn't get deleted.
2529 CGM.addUsedGlobal(FuncRecord);
2530}
2531
2533 llvm::GlobalVariable *NamePtr, StringRef NameValue, uint64_t FuncHash,
2534 const std::string &CoverageMapping, bool IsUsed) {
2535 const uint64_t NameHash = llvm::IndexedInstrProf::ComputeHash(NameValue);
2536 FunctionRecords.push_back({NameHash, FuncHash, CoverageMapping, IsUsed});
2537
2538 if (!IsUsed)
2539 FunctionNames.push_back(NamePtr);
2540
2541 if (CGM.getCodeGenOpts().DumpCoverageMapping) {
2542 // Dump the coverage mapping data for this function by decoding the
2543 // encoded data. This allows us to dump the mapping regions which were
2544 // also processed by the CoverageMappingWriter which performs
2545 // additional minimization operations such as reducing the number of
2546 // expressions.
2548 std::vector<StringRef> Filenames;
2549 std::vector<CounterExpression> Expressions;
2550 std::vector<CounterMappingRegion> Regions;
2551 FilenameStrs.resize(FileEntries.size() + 1);
2552 FilenameStrs[0] = normalizeFilename(getCurrentDirname());
2553 for (const auto &Entry : FileEntries) {
2554 auto I = Entry.second;
2555 FilenameStrs[I] = normalizeFilename(Entry.first.getName());
2556 }
2557 ArrayRef<std::string> FilenameRefs = llvm::ArrayRef(FilenameStrs);
2558 RawCoverageMappingReader Reader(CoverageMapping, FilenameRefs, Filenames,
2559 Expressions, Regions);
2560 if (Reader.read())
2561 return;
2562 dump(llvm::outs(), NameValue, Expressions, Regions);
2563 }
2564}
2565
2567 if (FunctionRecords.empty())
2568 return;
2569 llvm::LLVMContext &Ctx = CGM.getLLVMContext();
2570 auto *Int32Ty = llvm::Type::getInt32Ty(Ctx);
2571
2572 // Create the filenames and merge them with coverage mappings
2574 FilenameStrs.resize(FileEntries.size() + 1);
2575 // The first filename is the current working directory.
2576 FilenameStrs[0] = normalizeFilename(getCurrentDirname());
2577 for (const auto &Entry : FileEntries) {
2578 auto I = Entry.second;
2579 FilenameStrs[I] = normalizeFilename(Entry.first.getName());
2580 }
2581
2582 std::string Filenames;
2583 {
2584 llvm::raw_string_ostream OS(Filenames);
2585 CoverageFilenamesSectionWriter(FilenameStrs).write(OS);
2586 }
2587 auto *FilenamesVal =
2588 llvm::ConstantDataArray::getString(Ctx, Filenames, false);
2589 const int64_t FilenamesRef = llvm::IndexedInstrProf::ComputeHash(Filenames);
2590
2591 // Emit the function records.
2592 for (const FunctionInfo &Info : FunctionRecords)
2593 emitFunctionMappingRecord(Info, FilenamesRef);
2594
2595 const unsigned NRecords = 0;
2596 const size_t FilenamesSize = Filenames.size();
2597 const unsigned CoverageMappingSize = 0;
2598 llvm::Type *CovDataHeaderTypes[] = {
2599#define COVMAP_HEADER(Type, LLVMType, Name, Init) LLVMType,
2600#include "llvm/ProfileData/InstrProfData.inc"
2601 };
2602 auto CovDataHeaderTy =
2603 llvm::StructType::get(Ctx, ArrayRef(CovDataHeaderTypes));
2604 llvm::Constant *CovDataHeaderVals[] = {
2605#define COVMAP_HEADER(Type, LLVMType, Name, Init) Init,
2606#include "llvm/ProfileData/InstrProfData.inc"
2607 };
2608 auto CovDataHeaderVal =
2609 llvm::ConstantStruct::get(CovDataHeaderTy, ArrayRef(CovDataHeaderVals));
2610
2611 // Create the coverage data record
2612 llvm::Type *CovDataTypes[] = {CovDataHeaderTy, FilenamesVal->getType()};
2613 auto CovDataTy = llvm::StructType::get(Ctx, ArrayRef(CovDataTypes));
2614 llvm::Constant *TUDataVals[] = {CovDataHeaderVal, FilenamesVal};
2615 auto CovDataVal = llvm::ConstantStruct::get(CovDataTy, ArrayRef(TUDataVals));
2616 auto CovData = new llvm::GlobalVariable(
2617 CGM.getModule(), CovDataTy, true, llvm::GlobalValue::PrivateLinkage,
2618 CovDataVal, llvm::getCoverageMappingVarName());
2619
2620 CovData->setSection(getInstrProfSection(CGM, llvm::IPSK_covmap));
2621 CovData->setAlignment(llvm::Align(8));
2622
2623 // Make sure the data doesn't get deleted.
2624 CGM.addUsedGlobal(CovData);
2625 // Create the deferred function records array
2626 if (!FunctionNames.empty()) {
2627 auto AddrSpace = FunctionNames.front()->getType()->getPointerAddressSpace();
2628 auto NamesArrTy = llvm::ArrayType::get(
2629 llvm::PointerType::get(Ctx, AddrSpace), FunctionNames.size());
2630 auto NamesArrVal = llvm::ConstantArray::get(NamesArrTy, FunctionNames);
2631 // This variable will *NOT* be emitted to the object file. It is used
2632 // to pass the list of names referenced to codegen.
2633 new llvm::GlobalVariable(CGM.getModule(), NamesArrTy, true,
2634 llvm::GlobalValue::InternalLinkage, NamesArrVal,
2635 llvm::getCoverageUnusedNamesVarName());
2636 }
2637}
2638
2640 return FileEntries.try_emplace(File, FileEntries.size() + 1).first->second;
2641}
2642
2644 llvm::raw_ostream &OS) {
2645 assert(CounterMap && MCDCState);
2646 CounterCoverageMappingBuilder Walker(CVM, *CounterMap, *MCDCState, SM,
2647 LangOpts);
2648 Walker.VisitDecl(D);
2649 Walker.write(OS);
2650}
2651
2653 llvm::raw_ostream &OS) {
2654 EmptyCoverageMappingBuilder Walker(CVM, SM, LangOpts);
2655 Walker.VisitDecl(D);
2656 Walker.write(OS);
2657}
Defines the Diagnostic-related interfaces.
static const MemRegion * getRegion(const CallEvent &Call, const MutexDescriptor &Descriptor, bool IsLock)
static std::string getInstrProfSection(const CodeGenModule &CGM, llvm::InstrProfSectKind SK)
static void dump(llvm::raw_ostream &OS, StringRef FunctionName, ArrayRef< CounterExpression > Expressions, ArrayRef< CounterMappingRegion > Regions)
static llvm::cl::opt< bool > EmptyLineCommentCoverage("emptyline-comment-coverage", llvm::cl::desc("Emit emptylines and comment lines as skipped regions (only " "disable it on test)"), llvm::cl::init(true), llvm::cl::Hidden)
Token Tok
The Token.
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
#define SM(sm)
const TargetInfo & getTargetInfo() const
Definition ASTContext.h:909
Expr * getCond() const
getCond - Return the expression representing the condition for the ?
Definition Expr.h:4531
Expr * getTrueExpr() const
getTrueExpr - Return the subexpression representing the value of the expression if the condition eval...
Definition Expr.h:4537
SourceLocation getQuestionLoc() const
Definition Expr.h:4380
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression representing the value of the expression if the condition eva...
Definition Expr.h:4543
OpaqueValueExpr * getCommonExpr() const
Get the common subexpression shared by all initializations (the source array).
Definition Expr.h:5983
Expr * getLHS() const
Definition Expr.h:4088
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.h:4093
SourceLocation getOperatorLoc() const
Definition Expr.h:4080
Expr * getRHS() const
Definition Expr.h:4090
SourceLocation getEndLoc() const LLVM_READONLY
Definition Expr.h:4096
Opcode getOpcode() const
Definition Expr.h:4083
Stmt * getHandlerBlock() const
Definition StmtCXX.h:51
DeclStmt * getLoopVarStmt()
Definition StmtCXX.h:169
DeclStmt * getRangeStmt()
Definition StmtCXX.h:162
SourceLocation getRParenLoc() const
Definition StmtCXX.h:205
const Expr * getSubExpr() const
Definition ExprCXX.h:1228
CXXCatchStmt * getHandler(unsigned i)
Definition StmtCXX.h:108
unsigned getNumHandlers() const
Definition StmtCXX.h:107
CompoundStmt * getTryBlock()
Definition StmtCXX.h:100
Expr * getCallee()
Definition Expr.h:3090
llvm::SmallVector< std::pair< std::string, std::string >, 0 > CoveragePrefixMap
Prefix replacement map for source-based code coverage to remap source file paths in coverage mapping.
std::string CoverageCompilationDir
The string to embed in coverage mapping as the current working directory.
static bool isInstrumentedCondition(const Expr *C)
isInstrumentedCondition - Determine whether the given condition is an instrumentable condition (i....
static const Expr * stripCond(const Expr *C)
Ignore parentheses and logical-NOT to track conditions consistently.
This class organizes the cross-function state that is used while generating LLVM code.
DiagnosticsEngine & getDiags() const
ASTContext & getContext() const
const CodeGenOptions & getCodeGenOpts() const
void emitEmptyMapping(const Decl *D, llvm::raw_ostream &OS)
Emit the coverage mapping data for an unused function.
void emitCounterMapping(const Decl *D, llvm::raw_ostream &OS)
Emit the coverage mapping data which maps the regions of code to counters that will be used to find t...
void addFunctionMappingRecord(llvm::GlobalVariable *FunctionName, StringRef FunctionNameValue, uint64_t FunctionHash, const std::string &CoverageMapping, bool IsUsed=true)
Add a function's coverage mapping record to the collection of the function mapping records.
CoverageSourceInfo & getSourceInfo() const
static CoverageSourceInfo * setUpCoverageCallbacks(Preprocessor &PP)
CoverageMappingModuleGen(CodeGenModule &CGM, CoverageSourceInfo &SourceInfo)
void emit()
Emit the coverage mapping data for a translation unit.
CodeGenModule & getCodeGenModule()
Return an interface into CodeGenModule.
unsigned getFileID(FileEntryRef File)
Return the coverage mapping translation unit file id for the given file.
Expr * getOperand() const
Retrieve the operand of the 'co_return' statement.
Definition StmtCXX.h:497
CompoundStmt * getBody() const
Retrieve the body of the coroutine as written.
Definition StmtCXX.h:380
Expr * getOperand() const
Definition ExprCXX.h:5324
Stores additional source code information like skipped ranges which is required by the coverage mappi...
void SourceRangeSkipped(SourceRange Range, SourceLocation EndifLoc) override
Hook called when a source range is skipped.
void updateNextTokLoc(SourceLocation Loc)
void AddSkippedRange(SourceRange Range, SkippedRange::Kind RangeKind)
std::vector< SkippedRange > & getSkippedRanges()
bool HandleComment(Preprocessor &PP, SourceRange Range) override
void HandleEmptyline(SourceRange Range) override
virtual Stmt * getBody() const
getBody - If this Decl represents a declaration for a body of code, such as a function or method defi...
Definition DeclBase.h:1087
virtual bool hasBody() const
Returns true if this Decl represents a declaration for a body of code, such as a function or method d...
Definition DeclBase.h:1093
Stmt * getBody()
Definition Stmt.h:2848
Expr * getCond()
Definition Stmt.h:2841
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:177
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx) const
EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded integer.
bool EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsBooleanCondition - Return true if this is a constant which we can fold and convert to a boo...
QualType getType() const
Definition Expr.h:144
A reference to a FileEntry that includes the name of the file as it was accessed by the FileManager's...
Definition FileEntry.h:57
bool isValid() const
Stmt * getInit()
Definition Stmt.h:2894
SourceLocation getRParenLoc() const
Definition Stmt.h:2939
Stmt * getBody()
Definition Stmt.h:2923
Expr * getInc()
Definition Stmt.h:2922
Expr * getCond()
Definition Stmt.h:2921
Stmt * getThen()
Definition Stmt.h:2339
SourceLocation getIfLoc() const
Definition Stmt.h:2416
Stmt * getInit()
Definition Stmt.h:2400
bool isNonNegatedConsteval() const
Definition Stmt.h:2435
Expr * getCond()
Definition Stmt.h:2327
bool isConstexpr() const
Definition Stmt.h:2443
bool isNegatedConsteval() const
Definition Stmt.h:2439
Stmt * getElse()
Definition Stmt.h:2348
SourceLocation getRParenLoc() const
Definition Stmt.h:2470
bool isConsteval() const
Definition Stmt.h:2430
Stmt * getSubStmt()
Definition Stmt.h:2159
static unsigned MeasureTokenLength(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts)
MeasureTokenLength - Relex the token at the specified location and return its length in bytes in the ...
Definition Lexer.cpp:498
SourceLocation getRParenLoc() const
Definition StmtObjC.h:54
Expr * getSourceExpr() const
The source expression of an opaque value expression is the expression which originally generated the ...
Definition Expr.h:1228
bool isUnique() const
Definition Expr.h:1236
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
void addCommentHandler(CommentHandler *Handler)
Add the specified comment handler to the preprocessor.
void addPPCallbacks(std::unique_ptr< PPCallbacks > C)
SourceManager & getSourceManager() const
void setPreprocessToken(bool Preprocess)
void setTokenWatcher(llvm::unique_function< void(const clang::Token &)> F)
Register a function that would be called on each token in the final expanded token stream.
void setEmptylineHandler(EmptylineHandler *Handler)
Set empty line handler.
Expr * getSyntacticForm()
Return the syntactic form of this expression, i.e.
Definition Expr.h:6793
Expr * getRetValue()
Definition Stmt.h:3178
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
SourceLocation getLocWithOffset(IntTy Offset) const
Return a source location with the specified offset from this SourceLocation.
A trivial tuple used to represent a source range.
SourceLocation getExpansionLocStart() const
SourceLocation getExpansionLocEnd() const
CompoundStmt * getSubStmt()
Definition Expr.h:4612
SourceLocation getEndLoc() const LLVM_READONLY
Definition Stmt.cpp:362
child_range children()
Definition Stmt.cpp:299
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:350
Stmt * getSubStmt()
Definition Stmt.h:2104
SourceLocation getColonLoc() const
Definition Stmt.h:1890
const SwitchCase * getNextSwitchCase() const
Definition Stmt.h:1884
Expr * getCond()
Definition Stmt.h:2563
Stmt * getBody()
Definition Stmt.h:2575
Stmt * getInit()
Definition Stmt.h:2580
SwitchCase * getSwitchCaseList()
Definition Stmt.h:2631
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Token - This structure provides full information about a lexed token.
Definition Token.h:36
Expr * getCond()
Definition Stmt.h:2740
SourceLocation getRParenLoc() const
Definition Stmt.h:2798
Stmt * getBody()
Definition Stmt.h:2752
@ Decl
The l-value was an access to a declared entity or something equivalently strong, like the address of ...
Definition CGValue.h:146
llvm::cl::opt< std::string > Filter
The JSON file list parser is used to communicate input to InstallAPI.
bool isa(CodeGen::Address addr)
Definition Address.h:330
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
FunctionType::ExtInfo getFunctionExtInfo(const Type &t)
Definition TypeBase.h:8428
Expr * Cond
};
@ Result
The result type of a method or function.
Definition TypeBase.h:905
unsigned long uint64_t
cl::opt< bool > SystemHeadersCoverage
Diagnostic wrappers for TextAPI types for error reporting.
Definition Dominators.h:30
cl::opt< bool > EnableSingleByteCoverage
#define false
Definition stdbool.h:26
llvm::DenseMap< const Stmt *, Branch > BranchByStmt
Definition MCDCState.h:44
llvm::DenseMap< const Stmt *, Decision > DecisionByStmt
Definition MCDCState.h:37
Morty Proxy This is a proxified and sanitized view of the page, visit original site.