1 //===--- CoverageMappingGen.cpp - Coverage mapping generation ---*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Instrumentation-based code coverage mapping generator
12 //===----------------------------------------------------------------------===//
14 #include "CoverageMappingGen.h"
15 #include "CodeGenFunction.h"
16 #include "clang/AST/StmtVisitor.h"
17 #include "clang/Lex/Lexer.h"
18 #include "llvm/ADT/SmallSet.h"
19 #include "llvm/ADT/StringExtras.h"
20 #include "llvm/ADT/Optional.h"
21 #include "llvm/ProfileData/Coverage/CoverageMapping.h"
22 #include "llvm/ProfileData/Coverage/CoverageMappingReader.h"
23 #include "llvm/ProfileData/Coverage/CoverageMappingWriter.h"
24 #include "llvm/ProfileData/InstrProfReader.h"
25 #include "llvm/Support/FileSystem.h"
26 #include "llvm/Support/Path.h"
28 using namespace clang;
29 using namespace CodeGen;
30 using namespace llvm::coverage;
32 void CoverageSourceInfo::SourceRangeSkipped(SourceRange Range, SourceLocation) {
33 SkippedRanges.push_back(Range);
38 /// A region of source code that can be mapped to a counter.
39 class SourceMappingRegion {
42 /// The region's starting location.
43 Optional<SourceLocation> LocStart;
45 /// The region's ending location.
46 Optional<SourceLocation> LocEnd;
48 /// Whether this region should be emitted after its parent is emitted.
51 /// Whether this region is a gap region. The count from a gap region is set
52 /// as the line execution count if there are no other regions on the line.
56 SourceMappingRegion(Counter Count, Optional<SourceLocation> LocStart,
57 Optional<SourceLocation> LocEnd, bool DeferRegion = false,
58 bool GapRegion = false)
59 : Count(Count), LocStart(LocStart), LocEnd(LocEnd),
60 DeferRegion(DeferRegion), GapRegion(GapRegion) {}
62 const Counter &getCounter() const { return Count; }
64 void setCounter(Counter C) { Count = C; }
66 bool hasStartLoc() const { return LocStart.hasValue(); }
68 void setStartLoc(SourceLocation Loc) { LocStart = Loc; }
70 SourceLocation getStartLoc() const LLVM_READONLY { return getBeginLoc(); }
71 SourceLocation getBeginLoc() const {
72 assert(LocStart && "Region has no start location");
76 bool hasEndLoc() const { return LocEnd.hasValue(); }
78 void setEndLoc(SourceLocation Loc) {
79 assert(Loc.isValid() && "Setting an invalid end location");
83 SourceLocation getEndLoc() const {
84 assert(LocEnd && "Region has no end location");
88 bool isDeferred() const { return DeferRegion; }
90 void setDeferred(bool Deferred) { DeferRegion = Deferred; }
92 bool isGap() const { return GapRegion; }
94 void setGap(bool Gap) { GapRegion = Gap; }
97 /// Spelling locations for the start and end of a source region.
98 struct SpellingRegion {
99 /// The line where the region starts.
102 /// The column where the region starts.
103 unsigned ColumnStart;
105 /// The line where the region ends.
108 /// The column where the region ends.
111 SpellingRegion(SourceManager &SM, SourceLocation LocStart,
112 SourceLocation LocEnd) {
113 LineStart = SM.getSpellingLineNumber(LocStart);
114 ColumnStart = SM.getSpellingColumnNumber(LocStart);
115 LineEnd = SM.getSpellingLineNumber(LocEnd);
116 ColumnEnd = SM.getSpellingColumnNumber(LocEnd);
119 SpellingRegion(SourceManager &SM, SourceMappingRegion &R)
120 : SpellingRegion(SM, R.getStartLoc(), R.getEndLoc()) {}
122 /// Check if the start and end locations appear in source order, i.e
123 /// top->bottom, left->right.
124 bool isInSourceOrder() const {
125 return (LineStart < LineEnd) ||
126 (LineStart == LineEnd && ColumnStart <= ColumnEnd);
130 /// Provides the common functionality for the different
131 /// coverage mapping region builders.
132 class CoverageMappingBuilder {
134 CoverageMappingModuleGen &CVM;
136 const LangOptions &LangOpts;
139 /// Map of clang's FileIDs to IDs used for coverage mapping.
140 llvm::SmallDenseMap<FileID, std::pair<unsigned, SourceLocation>, 8>
144 /// The coverage mapping regions for this function
145 llvm::SmallVector<CounterMappingRegion, 32> MappingRegions;
146 /// The source mapping regions for this function.
147 std::vector<SourceMappingRegion> SourceRegions;
149 /// A set of regions which can be used as a filter.
151 /// It is produced by emitExpansionRegions() and is used in
152 /// emitSourceRegions() to suppress producing code regions if
153 /// the same area is covered by expansion regions.
154 typedef llvm::SmallSet<std::pair<SourceLocation, SourceLocation>, 8>
157 CoverageMappingBuilder(CoverageMappingModuleGen &CVM, SourceManager &SM,
158 const LangOptions &LangOpts)
159 : CVM(CVM), SM(SM), LangOpts(LangOpts) {}
161 /// Return the precise end location for the given token.
162 SourceLocation getPreciseTokenLocEnd(SourceLocation Loc) {
163 // We avoid getLocForEndOfToken here, because it doesn't do what we want for
164 // macro locations, which we just treat as expanded files.
166 Lexer::MeasureTokenLength(SM.getSpellingLoc(Loc), SM, LangOpts);
167 return Loc.getLocWithOffset(TokLen);
170 /// Return the start location of an included file or expanded macro.
171 SourceLocation getStartOfFileOrMacro(SourceLocation Loc) {
173 return Loc.getLocWithOffset(-SM.getFileOffset(Loc));
174 return SM.getLocForStartOfFile(SM.getFileID(Loc));
177 /// Return the end location of an included file or expanded macro.
178 SourceLocation getEndOfFileOrMacro(SourceLocation Loc) {
180 return Loc.getLocWithOffset(SM.getFileIDSize(SM.getFileID(Loc)) -
181 SM.getFileOffset(Loc));
182 return SM.getLocForEndOfFile(SM.getFileID(Loc));
185 /// Find out where the current file is included or macro is expanded.
186 SourceLocation getIncludeOrExpansionLoc(SourceLocation Loc) {
187 return Loc.isMacroID() ? SM.getImmediateExpansionRange(Loc).getBegin()
188 : SM.getIncludeLoc(SM.getFileID(Loc));
191 /// Return true if \c Loc is a location in a built-in macro.
192 bool isInBuiltin(SourceLocation Loc) {
193 return SM.getBufferName(SM.getSpellingLoc(Loc)) == "<built-in>";
196 /// Check whether \c Loc is included or expanded from \c Parent.
197 bool isNestedIn(SourceLocation Loc, FileID Parent) {
199 Loc = getIncludeOrExpansionLoc(Loc);
202 } while (!SM.isInFileID(Loc, Parent));
206 /// Get the start of \c S ignoring macro arguments and builtin macros.
207 SourceLocation getStart(const Stmt *S) {
208 SourceLocation Loc = S->getLocStart();
209 while (SM.isMacroArgExpansion(Loc) || isInBuiltin(Loc))
210 Loc = SM.getImmediateExpansionRange(Loc).getBegin();
214 /// Get the end of \c S ignoring macro arguments and builtin macros.
215 SourceLocation getEnd(const Stmt *S) {
216 SourceLocation Loc = S->getLocEnd();
217 while (SM.isMacroArgExpansion(Loc) || isInBuiltin(Loc))
218 Loc = SM.getImmediateExpansionRange(Loc).getBegin();
219 return getPreciseTokenLocEnd(Loc);
222 /// Find the set of files we have regions for and assign IDs
224 /// Fills \c Mapping with the virtual file mapping needed to write out
225 /// coverage and collects the necessary file information to emit source and
226 /// expansion regions.
227 void gatherFileIDs(SmallVectorImpl<unsigned> &Mapping) {
228 FileIDMapping.clear();
230 llvm::SmallSet<FileID, 8> Visited;
231 SmallVector<std::pair<SourceLocation, unsigned>, 8> FileLocs;
232 for (const auto &Region : SourceRegions) {
233 SourceLocation Loc = Region.getStartLoc();
234 FileID File = SM.getFileID(Loc);
235 if (!Visited.insert(File).second)
238 // Do not map FileID's associated with system headers.
239 if (SM.isInSystemHeader(SM.getSpellingLoc(Loc)))
243 for (SourceLocation Parent = getIncludeOrExpansionLoc(Loc);
244 Parent.isValid(); Parent = getIncludeOrExpansionLoc(Parent))
246 FileLocs.push_back(std::make_pair(Loc, Depth));
248 std::stable_sort(FileLocs.begin(), FileLocs.end(), llvm::less_second());
250 for (const auto &FL : FileLocs) {
251 SourceLocation Loc = FL.first;
252 FileID SpellingFile = SM.getDecomposedSpellingLoc(Loc).first;
253 auto Entry = SM.getFileEntryForID(SpellingFile);
257 FileIDMapping[SM.getFileID(Loc)] = std::make_pair(Mapping.size(), Loc);
258 Mapping.push_back(CVM.getFileID(Entry));
262 /// Get the coverage mapping file ID for \c Loc.
264 /// If such file id doesn't exist, return None.
265 Optional<unsigned> getCoverageFileID(SourceLocation Loc) {
266 auto Mapping = FileIDMapping.find(SM.getFileID(Loc));
267 if (Mapping != FileIDMapping.end())
268 return Mapping->second.first;
272 /// Gather all the regions that were skipped by the preprocessor
273 /// using the constructs like #if.
274 void gatherSkippedRegions() {
275 /// An array of the minimum lineStarts and the maximum lineEnds
276 /// for mapping regions from the appropriate source files.
277 llvm::SmallVector<std::pair<unsigned, unsigned>, 8> FileLineRanges;
278 FileLineRanges.resize(
279 FileIDMapping.size(),
280 std::make_pair(std::numeric_limits<unsigned>::max(), 0));
281 for (const auto &R : MappingRegions) {
282 FileLineRanges[R.FileID].first =
283 std::min(FileLineRanges[R.FileID].first, R.LineStart);
284 FileLineRanges[R.FileID].second =
285 std::max(FileLineRanges[R.FileID].second, R.LineEnd);
288 auto SkippedRanges = CVM.getSourceInfo().getSkippedRanges();
289 for (const auto &I : SkippedRanges) {
290 auto LocStart = I.getBegin();
291 auto LocEnd = I.getEnd();
292 assert(SM.isWrittenInSameFile(LocStart, LocEnd) &&
293 "region spans multiple files");
295 auto CovFileID = getCoverageFileID(LocStart);
298 SpellingRegion SR{SM, LocStart, LocEnd};
299 auto Region = CounterMappingRegion::makeSkipped(
300 *CovFileID, SR.LineStart, SR.ColumnStart, SR.LineEnd, SR.ColumnEnd);
301 // Make sure that we only collect the regions that are inside
302 // the source code of this function.
303 if (Region.LineStart >= FileLineRanges[*CovFileID].first &&
304 Region.LineEnd <= FileLineRanges[*CovFileID].second)
305 MappingRegions.push_back(Region);
309 /// Generate the coverage counter mapping regions from collected
311 void emitSourceRegions(const SourceRegionFilter &Filter) {
312 for (const auto &Region : SourceRegions) {
313 assert(Region.hasEndLoc() && "incomplete region");
315 SourceLocation LocStart = Region.getStartLoc();
316 assert(SM.getFileID(LocStart).isValid() && "region in invalid file");
318 // Ignore regions from system headers.
319 if (SM.isInSystemHeader(SM.getSpellingLoc(LocStart)))
322 auto CovFileID = getCoverageFileID(LocStart);
323 // Ignore regions that don't have a file, such as builtin macros.
327 SourceLocation LocEnd = Region.getEndLoc();
328 assert(SM.isWrittenInSameFile(LocStart, LocEnd) &&
329 "region spans multiple files");
331 // Don't add code regions for the area covered by expansion regions.
332 // This not only suppresses redundant regions, but sometimes prevents
333 // creating regions with wrong counters if, for example, a statement's
334 // body ends at the end of a nested macro.
335 if (Filter.count(std::make_pair(LocStart, LocEnd)))
338 // Find the spelling locations for the mapping region.
339 SpellingRegion SR{SM, LocStart, LocEnd};
340 assert(SR.isInSourceOrder() && "region start and end out of order");
342 if (Region.isGap()) {
343 MappingRegions.push_back(CounterMappingRegion::makeGapRegion(
344 Region.getCounter(), *CovFileID, SR.LineStart, SR.ColumnStart,
345 SR.LineEnd, SR.ColumnEnd));
347 MappingRegions.push_back(CounterMappingRegion::makeRegion(
348 Region.getCounter(), *CovFileID, SR.LineStart, SR.ColumnStart,
349 SR.LineEnd, SR.ColumnEnd));
354 /// Generate expansion regions for each virtual file we've seen.
355 SourceRegionFilter emitExpansionRegions() {
356 SourceRegionFilter Filter;
357 for (const auto &FM : FileIDMapping) {
358 SourceLocation ExpandedLoc = FM.second.second;
359 SourceLocation ParentLoc = getIncludeOrExpansionLoc(ExpandedLoc);
360 if (ParentLoc.isInvalid())
363 auto ParentFileID = getCoverageFileID(ParentLoc);
366 auto ExpandedFileID = getCoverageFileID(ExpandedLoc);
367 assert(ExpandedFileID && "expansion in uncovered file");
369 SourceLocation LocEnd = getPreciseTokenLocEnd(ParentLoc);
370 assert(SM.isWrittenInSameFile(ParentLoc, LocEnd) &&
371 "region spans multiple files");
372 Filter.insert(std::make_pair(ParentLoc, LocEnd));
374 SpellingRegion SR{SM, ParentLoc, LocEnd};
375 assert(SR.isInSourceOrder() && "region start and end out of order");
376 MappingRegions.push_back(CounterMappingRegion::makeExpansion(
377 *ParentFileID, *ExpandedFileID, SR.LineStart, SR.ColumnStart,
378 SR.LineEnd, SR.ColumnEnd));
384 /// Creates unreachable coverage regions for the functions that
386 struct EmptyCoverageMappingBuilder : public CoverageMappingBuilder {
387 EmptyCoverageMappingBuilder(CoverageMappingModuleGen &CVM, SourceManager &SM,
388 const LangOptions &LangOpts)
389 : CoverageMappingBuilder(CVM, SM, LangOpts) {}
391 void VisitDecl(const Decl *D) {
394 auto Body = D->getBody();
395 SourceLocation Start = getStart(Body);
396 SourceLocation End = getEnd(Body);
397 if (!SM.isWrittenInSameFile(Start, End)) {
398 // Walk up to find the common ancestor.
399 // Correct the locations accordingly.
400 FileID StartFileID = SM.getFileID(Start);
401 FileID EndFileID = SM.getFileID(End);
402 while (StartFileID != EndFileID && !isNestedIn(End, StartFileID)) {
403 Start = getIncludeOrExpansionLoc(Start);
404 assert(Start.isValid() &&
405 "Declaration start location not nested within a known region");
406 StartFileID = SM.getFileID(Start);
408 while (StartFileID != EndFileID) {
409 End = getPreciseTokenLocEnd(getIncludeOrExpansionLoc(End));
410 assert(End.isValid() &&
411 "Declaration end location not nested within a known region");
412 EndFileID = SM.getFileID(End);
415 SourceRegions.emplace_back(Counter(), Start, End);
418 /// Write the mapping data to the output stream
419 void write(llvm::raw_ostream &OS) {
420 SmallVector<unsigned, 16> FileIDMapping;
421 gatherFileIDs(FileIDMapping);
422 emitSourceRegions(SourceRegionFilter());
424 if (MappingRegions.empty())
427 CoverageMappingWriter Writer(FileIDMapping, None, MappingRegions);
432 /// A StmtVisitor that creates coverage mapping regions which map
433 /// from the source code locations to the PGO counters.
434 struct CounterCoverageMappingBuilder
435 : public CoverageMappingBuilder,
436 public ConstStmtVisitor<CounterCoverageMappingBuilder> {
437 /// The map of statements to count values.
438 llvm::DenseMap<const Stmt *, unsigned> &CounterMap;
440 /// A stack of currently live regions.
441 std::vector<SourceMappingRegion> RegionStack;
443 /// The currently deferred region: its end location and count can be set once
444 /// its parent has been popped from the region stack.
445 Optional<SourceMappingRegion> DeferredRegion;
447 CounterExpressionBuilder Builder;
449 /// A location in the most recently visited file or macro.
451 /// This is used to adjust the active source regions appropriately when
452 /// expressions cross file or macro boundaries.
453 SourceLocation MostRecentLocation;
455 /// Location of the last terminated region.
456 Optional<std::pair<SourceLocation, size_t>> LastTerminatedRegion;
458 /// Return a counter for the subtraction of \c RHS from \c LHS
459 Counter subtractCounters(Counter LHS, Counter RHS) {
460 return Builder.subtract(LHS, RHS);
463 /// Return a counter for the sum of \c LHS and \c RHS.
464 Counter addCounters(Counter LHS, Counter RHS) {
465 return Builder.add(LHS, RHS);
468 Counter addCounters(Counter C1, Counter C2, Counter C3) {
469 return addCounters(addCounters(C1, C2), C3);
472 /// Return the region counter for the given statement.
474 /// This should only be called on statements that have a dedicated counter.
475 Counter getRegionCounter(const Stmt *S) {
476 return Counter::getCounter(CounterMap[S]);
479 /// Push a region onto the stack.
481 /// Returns the index on the stack where the region was pushed. This can be
482 /// used with popRegions to exit a "scope", ending the region that was pushed.
483 size_t pushRegion(Counter Count, Optional<SourceLocation> StartLoc = None,
484 Optional<SourceLocation> EndLoc = None) {
486 MostRecentLocation = *StartLoc;
487 completeDeferred(Count, MostRecentLocation);
489 RegionStack.emplace_back(Count, StartLoc, EndLoc);
491 return RegionStack.size() - 1;
494 /// Complete any pending deferred region by setting its end location and
495 /// count, and then pushing it onto the region stack.
496 size_t completeDeferred(Counter Count, SourceLocation DeferredEndLoc) {
497 size_t Index = RegionStack.size();
501 // Consume the pending region.
502 SourceMappingRegion DR = DeferredRegion.getValue();
503 DeferredRegion = None;
505 // If the region ends in an expansion, find the expansion site.
506 FileID StartFile = SM.getFileID(DR.getStartLoc());
507 if (SM.getFileID(DeferredEndLoc) != StartFile) {
508 if (isNestedIn(DeferredEndLoc, StartFile)) {
510 DeferredEndLoc = getIncludeOrExpansionLoc(DeferredEndLoc);
511 } while (StartFile != SM.getFileID(DeferredEndLoc));
517 // The parent of this deferred region ends where the containing decl ends,
518 // so the region isn't useful.
519 if (DR.getStartLoc() == DeferredEndLoc)
522 // If we're visiting statements in non-source order (e.g switch cases or
523 // a loop condition) we can't construct a sensible deferred region.
524 if (!SpellingRegion(SM, DR.getStartLoc(), DeferredEndLoc).isInSourceOrder())
528 DR.setCounter(Count);
529 DR.setEndLoc(DeferredEndLoc);
530 handleFileExit(DeferredEndLoc);
531 RegionStack.push_back(DR);
535 /// Complete a deferred region created after a terminated region at the
537 void completeTopLevelDeferredRegion(Counter Count,
538 SourceLocation DeferredEndLoc) {
539 if (DeferredRegion || !LastTerminatedRegion)
542 if (LastTerminatedRegion->second != RegionStack.size())
545 SourceLocation Start = LastTerminatedRegion->first;
546 if (SM.getFileID(Start) != SM.getMainFileID())
549 SourceMappingRegion DR = RegionStack.back();
550 DR.setStartLoc(Start);
551 DR.setDeferred(false);
553 completeDeferred(Count, DeferredEndLoc);
556 size_t locationDepth(SourceLocation Loc) {
558 while (Loc.isValid()) {
559 Loc = getIncludeOrExpansionLoc(Loc);
565 /// Pop regions from the stack into the function's list of regions.
567 /// Adds all regions from \c ParentIndex to the top of the stack to the
568 /// function's \c SourceRegions.
569 void popRegions(size_t ParentIndex) {
570 assert(RegionStack.size() >= ParentIndex && "parent not in stack");
571 bool ParentOfDeferredRegion = false;
572 while (RegionStack.size() > ParentIndex) {
573 SourceMappingRegion &Region = RegionStack.back();
574 if (Region.hasStartLoc()) {
575 SourceLocation StartLoc = Region.getStartLoc();
576 SourceLocation EndLoc = Region.hasEndLoc()
578 : RegionStack[ParentIndex].getEndLoc();
579 size_t StartDepth = locationDepth(StartLoc);
580 size_t EndDepth = locationDepth(EndLoc);
581 while (!SM.isWrittenInSameFile(StartLoc, EndLoc)) {
582 bool UnnestStart = StartDepth >= EndDepth;
583 bool UnnestEnd = EndDepth >= StartDepth;
585 // The region ends in a nested file or macro expansion. Create a
586 // separate region for each expansion.
587 SourceLocation NestedLoc = getStartOfFileOrMacro(EndLoc);
588 assert(SM.isWrittenInSameFile(NestedLoc, EndLoc));
590 if (!isRegionAlreadyAdded(NestedLoc, EndLoc))
591 SourceRegions.emplace_back(Region.getCounter(), NestedLoc, EndLoc);
593 EndLoc = getPreciseTokenLocEnd(getIncludeOrExpansionLoc(EndLoc));
594 if (EndLoc.isInvalid())
595 llvm::report_fatal_error("File exit not handled before popRegions");
599 // The region begins in a nested file or macro expansion. Create a
600 // separate region for each expansion.
601 SourceLocation NestedLoc = getEndOfFileOrMacro(StartLoc);
602 assert(SM.isWrittenInSameFile(StartLoc, NestedLoc));
604 if (!isRegionAlreadyAdded(StartLoc, NestedLoc))
605 SourceRegions.emplace_back(Region.getCounter(), StartLoc, NestedLoc);
607 StartLoc = getIncludeOrExpansionLoc(StartLoc);
608 if (StartLoc.isInvalid())
609 llvm::report_fatal_error("File exit not handled before popRegions");
613 Region.setStartLoc(StartLoc);
614 Region.setEndLoc(EndLoc);
616 MostRecentLocation = EndLoc;
617 // If this region happens to span an entire expansion, we need to make
618 // sure we don't overlap the parent region with it.
619 if (StartLoc == getStartOfFileOrMacro(StartLoc) &&
620 EndLoc == getEndOfFileOrMacro(EndLoc))
621 MostRecentLocation = getIncludeOrExpansionLoc(EndLoc);
623 assert(SM.isWrittenInSameFile(Region.getStartLoc(), EndLoc));
624 assert(SpellingRegion(SM, Region).isInSourceOrder());
625 SourceRegions.push_back(Region);
627 if (ParentOfDeferredRegion) {
628 ParentOfDeferredRegion = false;
630 // If there's an existing deferred region, keep the old one, because
631 // it means there are two consecutive returns (or a similar pattern).
632 if (!DeferredRegion.hasValue() &&
633 // File IDs aren't gathered within macro expansions, so it isn't
634 // useful to try and create a deferred region inside of one.
637 SourceMappingRegion(Counter::getZero(), EndLoc, None);
639 } else if (Region.isDeferred()) {
640 assert(!ParentOfDeferredRegion && "Consecutive deferred regions");
641 ParentOfDeferredRegion = true;
643 RegionStack.pop_back();
645 // If the zero region pushed after the last terminated region no longer
646 // exists, clear its cached information.
647 if (LastTerminatedRegion &&
648 RegionStack.size() < LastTerminatedRegion->second)
649 LastTerminatedRegion = None;
651 assert(!ParentOfDeferredRegion && "Deferred region with no parent");
654 /// Return the currently active region.
655 SourceMappingRegion &getRegion() {
656 assert(!RegionStack.empty() && "statement has no region");
657 return RegionStack.back();
660 /// Propagate counts through the children of \c S.
661 Counter propagateCounts(Counter TopCount, const Stmt *S) {
662 SourceLocation StartLoc = getStart(S);
663 SourceLocation EndLoc = getEnd(S);
664 size_t Index = pushRegion(TopCount, StartLoc, EndLoc);
666 Counter ExitCount = getRegion().getCounter();
669 // The statement may be spanned by an expansion. Make sure we handle a file
670 // exit out of this expansion before moving to the next statement.
671 if (SM.isBeforeInTranslationUnit(StartLoc, S->getLocStart()))
672 MostRecentLocation = EndLoc;
677 /// Check whether a region with bounds \c StartLoc and \c EndLoc
678 /// is already added to \c SourceRegions.
679 bool isRegionAlreadyAdded(SourceLocation StartLoc, SourceLocation EndLoc) {
680 return SourceRegions.rend() !=
681 std::find_if(SourceRegions.rbegin(), SourceRegions.rend(),
682 [&](const SourceMappingRegion &Region) {
683 return Region.getStartLoc() == StartLoc &&
684 Region.getEndLoc() == EndLoc;
688 /// Adjust the most recently visited location to \c EndLoc.
690 /// This should be used after visiting any statements in non-source order.
691 void adjustForOutOfOrderTraversal(SourceLocation EndLoc) {
692 MostRecentLocation = EndLoc;
693 // The code region for a whole macro is created in handleFileExit() when
694 // it detects exiting of the virtual file of that macro. If we visited
695 // statements in non-source order, we might already have such a region
696 // added, for example, if a body of a loop is divided among multiple
697 // macros. Avoid adding duplicate regions in such case.
698 if (getRegion().hasEndLoc() &&
699 MostRecentLocation == getEndOfFileOrMacro(MostRecentLocation) &&
700 isRegionAlreadyAdded(getStartOfFileOrMacro(MostRecentLocation),
702 MostRecentLocation = getIncludeOrExpansionLoc(MostRecentLocation);
705 /// Adjust regions and state when \c NewLoc exits a file.
707 /// If moving from our most recently tracked location to \c NewLoc exits any
708 /// files, this adjusts our current region stack and creates the file regions
709 /// for the exited file.
710 void handleFileExit(SourceLocation NewLoc) {
711 if (NewLoc.isInvalid() ||
712 SM.isWrittenInSameFile(MostRecentLocation, NewLoc))
715 // If NewLoc is not in a file that contains MostRecentLocation, walk up to
716 // find the common ancestor.
717 SourceLocation LCA = NewLoc;
718 FileID ParentFile = SM.getFileID(LCA);
719 while (!isNestedIn(MostRecentLocation, ParentFile)) {
720 LCA = getIncludeOrExpansionLoc(LCA);
721 if (LCA.isInvalid() || SM.isWrittenInSameFile(LCA, MostRecentLocation)) {
722 // Since there isn't a common ancestor, no file was exited. We just need
723 // to adjust our location to the new file.
724 MostRecentLocation = NewLoc;
727 ParentFile = SM.getFileID(LCA);
730 llvm::SmallSet<SourceLocation, 8> StartLocs;
731 Optional<Counter> ParentCounter;
732 for (SourceMappingRegion &I : llvm::reverse(RegionStack)) {
733 if (!I.hasStartLoc())
735 SourceLocation Loc = I.getStartLoc();
736 if (!isNestedIn(Loc, ParentFile)) {
737 ParentCounter = I.getCounter();
741 while (!SM.isInFileID(Loc, ParentFile)) {
742 // The most nested region for each start location is the one with the
743 // correct count. We avoid creating redundant regions by stopping once
744 // we've seen this region.
745 if (StartLocs.insert(Loc).second)
746 SourceRegions.emplace_back(I.getCounter(), Loc,
747 getEndOfFileOrMacro(Loc));
748 Loc = getIncludeOrExpansionLoc(Loc);
750 I.setStartLoc(getPreciseTokenLocEnd(Loc));
754 // If the file is contained completely by another region and doesn't
755 // immediately start its own region, the whole file gets a region
756 // corresponding to the parent.
757 SourceLocation Loc = MostRecentLocation;
758 while (isNestedIn(Loc, ParentFile)) {
759 SourceLocation FileStart = getStartOfFileOrMacro(Loc);
760 if (StartLocs.insert(FileStart).second) {
761 SourceRegions.emplace_back(*ParentCounter, FileStart,
762 getEndOfFileOrMacro(Loc));
763 assert(SpellingRegion(SM, SourceRegions.back()).isInSourceOrder());
765 Loc = getIncludeOrExpansionLoc(Loc);
769 MostRecentLocation = NewLoc;
772 /// Ensure that \c S is included in the current region.
773 void extendRegion(const Stmt *S) {
774 SourceMappingRegion &Region = getRegion();
775 SourceLocation StartLoc = getStart(S);
777 handleFileExit(StartLoc);
778 if (!Region.hasStartLoc())
779 Region.setStartLoc(StartLoc);
781 completeDeferred(Region.getCounter(), StartLoc);
784 /// Mark \c S as a terminator, starting a zero region.
785 void terminateRegion(const Stmt *S) {
787 SourceMappingRegion &Region = getRegion();
788 SourceLocation EndLoc = getEnd(S);
789 if (!Region.hasEndLoc())
790 Region.setEndLoc(EndLoc);
791 pushRegion(Counter::getZero());
792 auto &ZeroRegion = getRegion();
793 ZeroRegion.setDeferred(true);
794 LastTerminatedRegion = {EndLoc, RegionStack.size()};
797 /// Find a valid gap range between \p AfterLoc and \p BeforeLoc.
798 Optional<SourceRange> findGapAreaBetween(SourceLocation AfterLoc,
799 SourceLocation BeforeLoc) {
800 // If the start and end locations of the gap are both within the same macro
801 // file, the range may not be in source order.
802 if (AfterLoc.isMacroID() || BeforeLoc.isMacroID())
804 if (!SM.isWrittenInSameFile(AfterLoc, BeforeLoc))
806 return {{AfterLoc, BeforeLoc}};
809 /// Find the source range after \p AfterStmt and before \p BeforeStmt.
810 Optional<SourceRange> findGapAreaBetween(const Stmt *AfterStmt,
811 const Stmt *BeforeStmt) {
812 return findGapAreaBetween(getPreciseTokenLocEnd(getEnd(AfterStmt)),
813 getStart(BeforeStmt));
816 /// Emit a gap region between \p StartLoc and \p EndLoc with the given count.
817 void fillGapAreaWithCount(SourceLocation StartLoc, SourceLocation EndLoc,
819 if (StartLoc == EndLoc)
821 assert(SpellingRegion(SM, StartLoc, EndLoc).isInSourceOrder());
822 handleFileExit(StartLoc);
823 size_t Index = pushRegion(Count, StartLoc, EndLoc);
824 getRegion().setGap(true);
825 handleFileExit(EndLoc);
829 /// Keep counts of breaks and continues inside loops.
830 struct BreakContinue {
832 Counter ContinueCount;
834 SmallVector<BreakContinue, 8> BreakContinueStack;
836 CounterCoverageMappingBuilder(
837 CoverageMappingModuleGen &CVM,
838 llvm::DenseMap<const Stmt *, unsigned> &CounterMap, SourceManager &SM,
839 const LangOptions &LangOpts)
840 : CoverageMappingBuilder(CVM, SM, LangOpts), CounterMap(CounterMap),
841 DeferredRegion(None) {}
843 /// Write the mapping data to the output stream
844 void write(llvm::raw_ostream &OS) {
845 llvm::SmallVector<unsigned, 8> VirtualFileMapping;
846 gatherFileIDs(VirtualFileMapping);
847 SourceRegionFilter Filter = emitExpansionRegions();
848 assert(!DeferredRegion && "Deferred region never completed");
849 emitSourceRegions(Filter);
850 gatherSkippedRegions();
852 if (MappingRegions.empty())
855 CoverageMappingWriter Writer(VirtualFileMapping, Builder.getExpressions(),
860 void VisitStmt(const Stmt *S) {
861 if (S->getLocStart().isValid())
863 for (const Stmt *Child : S->children())
866 handleFileExit(getEnd(S));
869 void VisitDecl(const Decl *D) {
870 assert(!DeferredRegion && "Deferred region never completed");
872 Stmt *Body = D->getBody();
874 // Do not propagate region counts into system headers.
875 if (Body && SM.isInSystemHeader(SM.getSpellingLoc(getStart(Body))))
878 propagateCounts(getRegionCounter(Body), Body);
879 assert(RegionStack.empty() && "Regions entered but never exited");
881 // Discard the last uncompleted deferred region in a decl, if one exists.
882 // This prevents lines at the end of a function containing only whitespace
883 // or closing braces from being marked as uncovered.
884 DeferredRegion = None;
887 void VisitReturnStmt(const ReturnStmt *S) {
889 if (S->getRetValue())
890 Visit(S->getRetValue());
894 void VisitCXXThrowExpr(const CXXThrowExpr *E) {
897 Visit(E->getSubExpr());
901 void VisitGotoStmt(const GotoStmt *S) { terminateRegion(S); }
903 void VisitLabelStmt(const LabelStmt *S) {
904 Counter LabelCount = getRegionCounter(S);
905 SourceLocation Start = getStart(S);
906 completeTopLevelDeferredRegion(LabelCount, Start);
907 completeDeferred(LabelCount, Start);
908 // We can't extendRegion here or we risk overlapping with our new region.
909 handleFileExit(Start);
910 pushRegion(LabelCount, Start);
911 Visit(S->getSubStmt());
914 void VisitBreakStmt(const BreakStmt *S) {
915 assert(!BreakContinueStack.empty() && "break not in a loop or switch!");
916 BreakContinueStack.back().BreakCount = addCounters(
917 BreakContinueStack.back().BreakCount, getRegion().getCounter());
918 // FIXME: a break in a switch should terminate regions for all preceding
919 // case statements, not just the most recent one.
923 void VisitContinueStmt(const ContinueStmt *S) {
924 assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
925 BreakContinueStack.back().ContinueCount = addCounters(
926 BreakContinueStack.back().ContinueCount, getRegion().getCounter());
930 void VisitCallExpr(const CallExpr *E) {
933 // Terminate the region when we hit a noreturn function.
934 // (This is helpful dealing with switch statements.)
935 QualType CalleeType = E->getCallee()->getType();
936 if (getFunctionExtInfo(*CalleeType).getNoReturn())
940 void VisitWhileStmt(const WhileStmt *S) {
943 Counter ParentCount = getRegion().getCounter();
944 Counter BodyCount = getRegionCounter(S);
946 // Handle the body first so that we can get the backedge count.
947 BreakContinueStack.push_back(BreakContinue());
948 extendRegion(S->getBody());
949 Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
950 BreakContinue BC = BreakContinueStack.pop_back_val();
952 // Go back to handle the condition.
954 addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
955 propagateCounts(CondCount, S->getCond());
956 adjustForOutOfOrderTraversal(getEnd(S));
958 // The body count applies to the area immediately after the increment.
959 auto Gap = findGapAreaBetween(S->getCond(), S->getBody());
961 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
964 addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount));
965 if (OutCount != ParentCount)
966 pushRegion(OutCount);
969 void VisitDoStmt(const DoStmt *S) {
972 Counter ParentCount = getRegion().getCounter();
973 Counter BodyCount = getRegionCounter(S);
975 BreakContinueStack.push_back(BreakContinue());
976 extendRegion(S->getBody());
977 Counter BackedgeCount =
978 propagateCounts(addCounters(ParentCount, BodyCount), S->getBody());
979 BreakContinue BC = BreakContinueStack.pop_back_val();
981 Counter CondCount = addCounters(BackedgeCount, BC.ContinueCount);
982 propagateCounts(CondCount, S->getCond());
985 addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount));
986 if (OutCount != ParentCount)
987 pushRegion(OutCount);
990 void VisitForStmt(const ForStmt *S) {
995 Counter ParentCount = getRegion().getCounter();
996 Counter BodyCount = getRegionCounter(S);
998 // The loop increment may contain a break or continue.
1000 BreakContinueStack.emplace_back();
1002 // Handle the body first so that we can get the backedge count.
1003 BreakContinueStack.emplace_back();
1004 extendRegion(S->getBody());
1005 Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
1006 BreakContinue BodyBC = BreakContinueStack.pop_back_val();
1008 // The increment is essentially part of the body but it needs to include
1009 // the count for all the continue statements.
1010 BreakContinue IncrementBC;
1011 if (const Stmt *Inc = S->getInc()) {
1012 propagateCounts(addCounters(BackedgeCount, BodyBC.ContinueCount), Inc);
1013 IncrementBC = BreakContinueStack.pop_back_val();
1016 // Go back to handle the condition.
1017 Counter CondCount = addCounters(
1018 addCounters(ParentCount, BackedgeCount, BodyBC.ContinueCount),
1019 IncrementBC.ContinueCount);
1020 if (const Expr *Cond = S->getCond()) {
1021 propagateCounts(CondCount, Cond);
1022 adjustForOutOfOrderTraversal(getEnd(S));
1025 // The body count applies to the area immediately after the increment.
1026 auto Gap = findGapAreaBetween(getPreciseTokenLocEnd(S->getRParenLoc()),
1027 getStart(S->getBody()));
1029 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1031 Counter OutCount = addCounters(BodyBC.BreakCount, IncrementBC.BreakCount,
1032 subtractCounters(CondCount, BodyCount));
1033 if (OutCount != ParentCount)
1034 pushRegion(OutCount);
1037 void VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
1039 Visit(S->getLoopVarStmt());
1040 Visit(S->getRangeStmt());
1042 Counter ParentCount = getRegion().getCounter();
1043 Counter BodyCount = getRegionCounter(S);
1045 BreakContinueStack.push_back(BreakContinue());
1046 extendRegion(S->getBody());
1047 Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
1048 BreakContinue BC = BreakContinueStack.pop_back_val();
1050 // The body count applies to the area immediately after the range.
1051 auto Gap = findGapAreaBetween(getPreciseTokenLocEnd(S->getRParenLoc()),
1052 getStart(S->getBody()));
1054 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1057 addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
1059 addCounters(BC.BreakCount, subtractCounters(LoopCount, BodyCount));
1060 if (OutCount != ParentCount)
1061 pushRegion(OutCount);
1064 void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) {
1066 Visit(S->getElement());
1068 Counter ParentCount = getRegion().getCounter();
1069 Counter BodyCount = getRegionCounter(S);
1071 BreakContinueStack.push_back(BreakContinue());
1072 extendRegion(S->getBody());
1073 Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
1074 BreakContinue BC = BreakContinueStack.pop_back_val();
1076 // The body count applies to the area immediately after the collection.
1077 auto Gap = findGapAreaBetween(getPreciseTokenLocEnd(S->getRParenLoc()),
1078 getStart(S->getBody()));
1080 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1083 addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
1085 addCounters(BC.BreakCount, subtractCounters(LoopCount, BodyCount));
1086 if (OutCount != ParentCount)
1087 pushRegion(OutCount);
1090 void VisitSwitchStmt(const SwitchStmt *S) {
1093 Visit(S->getInit());
1094 Visit(S->getCond());
1096 BreakContinueStack.push_back(BreakContinue());
1098 const Stmt *Body = S->getBody();
1100 if (const auto *CS = dyn_cast<CompoundStmt>(Body)) {
1101 if (!CS->body_empty()) {
1102 // Make a region for the body of the switch. If the body starts with
1103 // a case, that case will reuse this region; otherwise, this covers
1104 // the unreachable code at the beginning of the switch body.
1106 pushRegion(Counter::getZero(), getStart(CS->body_front()));
1107 for (const auto *Child : CS->children())
1110 // Set the end for the body of the switch, if it isn't already set.
1111 for (size_t i = RegionStack.size(); i != Index; --i) {
1112 if (!RegionStack[i - 1].hasEndLoc())
1113 RegionStack[i - 1].setEndLoc(getEnd(CS->body_back()));
1119 propagateCounts(Counter::getZero(), Body);
1120 BreakContinue BC = BreakContinueStack.pop_back_val();
1122 if (!BreakContinueStack.empty())
1123 BreakContinueStack.back().ContinueCount = addCounters(
1124 BreakContinueStack.back().ContinueCount, BC.ContinueCount);
1126 Counter ExitCount = getRegionCounter(S);
1127 SourceLocation ExitLoc = getEnd(S);
1128 pushRegion(ExitCount);
1130 // Ensure that handleFileExit recognizes when the end location is located
1131 // in a different file.
1132 MostRecentLocation = getStart(S);
1133 handleFileExit(ExitLoc);
1136 void VisitSwitchCase(const SwitchCase *S) {
1139 SourceMappingRegion &Parent = getRegion();
1141 Counter Count = addCounters(Parent.getCounter(), getRegionCounter(S));
1142 // Reuse the existing region if it starts at our label. This is typical of
1143 // the first case in a switch.
1144 if (Parent.hasStartLoc() && Parent.getStartLoc() == getStart(S))
1145 Parent.setCounter(Count);
1147 pushRegion(Count, getStart(S));
1149 if (const auto *CS = dyn_cast<CaseStmt>(S)) {
1150 Visit(CS->getLHS());
1151 if (const Expr *RHS = CS->getRHS())
1154 Visit(S->getSubStmt());
1157 void VisitIfStmt(const IfStmt *S) {
1160 Visit(S->getInit());
1162 // Extend into the condition before we propagate through it below - this is
1163 // needed to handle macros that generate the "if" but not the condition.
1164 extendRegion(S->getCond());
1166 Counter ParentCount = getRegion().getCounter();
1167 Counter ThenCount = getRegionCounter(S);
1169 // Emitting a counter for the condition makes it easier to interpret the
1170 // counter for the body when looking at the coverage.
1171 propagateCounts(ParentCount, S->getCond());
1173 // The 'then' count applies to the area immediately after the condition.
1174 auto Gap = findGapAreaBetween(S->getCond(), S->getThen());
1176 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), ThenCount);
1178 extendRegion(S->getThen());
1179 Counter OutCount = propagateCounts(ThenCount, S->getThen());
1181 Counter ElseCount = subtractCounters(ParentCount, ThenCount);
1182 if (const Stmt *Else = S->getElse()) {
1183 // The 'else' count applies to the area immediately after the 'then'.
1184 Gap = findGapAreaBetween(S->getThen(), Else);
1186 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), ElseCount);
1188 OutCount = addCounters(OutCount, propagateCounts(ElseCount, Else));
1190 OutCount = addCounters(OutCount, ElseCount);
1192 if (OutCount != ParentCount)
1193 pushRegion(OutCount);
1196 void VisitCXXTryStmt(const CXXTryStmt *S) {
1198 // Handle macros that generate the "try" but not the rest.
1199 extendRegion(S->getTryBlock());
1201 Counter ParentCount = getRegion().getCounter();
1202 propagateCounts(ParentCount, S->getTryBlock());
1204 for (unsigned I = 0, E = S->getNumHandlers(); I < E; ++I)
1205 Visit(S->getHandler(I));
1207 Counter ExitCount = getRegionCounter(S);
1208 pushRegion(ExitCount);
1211 void VisitCXXCatchStmt(const CXXCatchStmt *S) {
1212 propagateCounts(getRegionCounter(S), S->getHandlerBlock());
1215 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
1218 Counter ParentCount = getRegion().getCounter();
1219 Counter TrueCount = getRegionCounter(E);
1221 Visit(E->getCond());
1223 if (!isa<BinaryConditionalOperator>(E)) {
1224 // The 'then' count applies to the area immediately after the condition.
1226 findGapAreaBetween(E->getQuestionLoc(), getStart(E->getTrueExpr()));
1228 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), TrueCount);
1230 extendRegion(E->getTrueExpr());
1231 propagateCounts(TrueCount, E->getTrueExpr());
1234 extendRegion(E->getFalseExpr());
1235 propagateCounts(subtractCounters(ParentCount, TrueCount),
1239 void VisitBinLAnd(const BinaryOperator *E) {
1240 extendRegion(E->getLHS());
1241 propagateCounts(getRegion().getCounter(), E->getLHS());
1242 handleFileExit(getEnd(E->getLHS()));
1244 extendRegion(E->getRHS());
1245 propagateCounts(getRegionCounter(E), E->getRHS());
1248 void VisitBinLOr(const BinaryOperator *E) {
1249 extendRegion(E->getLHS());
1250 propagateCounts(getRegion().getCounter(), E->getLHS());
1251 handleFileExit(getEnd(E->getLHS()));
1253 extendRegion(E->getRHS());
1254 propagateCounts(getRegionCounter(E), E->getRHS());
1257 void VisitLambdaExpr(const LambdaExpr *LE) {
1258 // Lambdas are treated as their own functions for now, so we shouldn't
1259 // propagate counts into them.
1263 std::string getCoverageSection(const CodeGenModule &CGM) {
1264 return llvm::getInstrProfSectionName(
1266 CGM.getContext().getTargetInfo().getTriple().getObjectFormat());
1269 std::string normalizeFilename(StringRef Filename) {
1270 llvm::SmallString<256> Path(Filename);
1271 llvm::sys::fs::make_absolute(Path);
1272 llvm::sys::path::remove_dots(Path, /*remove_dot_dots=*/true);
1273 return Path.str().str();
1276 } // end anonymous namespace
1278 static void dump(llvm::raw_ostream &OS, StringRef FunctionName,
1279 ArrayRef<CounterExpression> Expressions,
1280 ArrayRef<CounterMappingRegion> Regions) {
1281 OS << FunctionName << ":\n";
1282 CounterMappingContext Ctx(Expressions);
1283 for (const auto &R : Regions) {
1286 case CounterMappingRegion::CodeRegion:
1288 case CounterMappingRegion::ExpansionRegion:
1291 case CounterMappingRegion::SkippedRegion:
1294 case CounterMappingRegion::GapRegion:
1299 OS << "File " << R.FileID << ", " << R.LineStart << ":" << R.ColumnStart
1300 << " -> " << R.LineEnd << ":" << R.ColumnEnd << " = ";
1301 Ctx.dump(R.Count, OS);
1302 if (R.Kind == CounterMappingRegion::ExpansionRegion)
1303 OS << " (Expanded file = " << R.ExpandedFileID << ")";
1308 void CoverageMappingModuleGen::addFunctionMappingRecord(
1309 llvm::GlobalVariable *NamePtr, StringRef NameValue, uint64_t FuncHash,
1310 const std::string &CoverageMapping, bool IsUsed) {
1311 llvm::LLVMContext &Ctx = CGM.getLLVMContext();
1312 if (!FunctionRecordTy) {
1313 #define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) LLVMType,
1314 llvm::Type *FunctionRecordTypes[] = {
1315 #include "llvm/ProfileData/InstrProfData.inc"
1318 llvm::StructType::get(Ctx, makeArrayRef(FunctionRecordTypes),
1322 #define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) Init,
1323 llvm::Constant *FunctionRecordVals[] = {
1324 #include "llvm/ProfileData/InstrProfData.inc"
1326 FunctionRecords.push_back(llvm::ConstantStruct::get(
1327 FunctionRecordTy, makeArrayRef(FunctionRecordVals)));
1329 FunctionNames.push_back(
1330 llvm::ConstantExpr::getBitCast(NamePtr, llvm::Type::getInt8PtrTy(Ctx)));
1331 CoverageMappings.push_back(CoverageMapping);
1333 if (CGM.getCodeGenOpts().DumpCoverageMapping) {
1334 // Dump the coverage mapping data for this function by decoding the
1335 // encoded data. This allows us to dump the mapping regions which were
1336 // also processed by the CoverageMappingWriter which performs
1337 // additional minimization operations such as reducing the number of
1339 std::vector<StringRef> Filenames;
1340 std::vector<CounterExpression> Expressions;
1341 std::vector<CounterMappingRegion> Regions;
1342 llvm::SmallVector<std::string, 16> FilenameStrs;
1343 llvm::SmallVector<StringRef, 16> FilenameRefs;
1344 FilenameStrs.resize(FileEntries.size());
1345 FilenameRefs.resize(FileEntries.size());
1346 for (const auto &Entry : FileEntries) {
1347 auto I = Entry.second;
1348 FilenameStrs[I] = normalizeFilename(Entry.first->getName());
1349 FilenameRefs[I] = FilenameStrs[I];
1351 RawCoverageMappingReader Reader(CoverageMapping, FilenameRefs, Filenames,
1352 Expressions, Regions);
1355 dump(llvm::outs(), NameValue, Expressions, Regions);
1359 void CoverageMappingModuleGen::emit() {
1360 if (FunctionRecords.empty())
1362 llvm::LLVMContext &Ctx = CGM.getLLVMContext();
1363 auto *Int32Ty = llvm::Type::getInt32Ty(Ctx);
1365 // Create the filenames and merge them with coverage mappings
1366 llvm::SmallVector<std::string, 16> FilenameStrs;
1367 llvm::SmallVector<StringRef, 16> FilenameRefs;
1368 FilenameStrs.resize(FileEntries.size());
1369 FilenameRefs.resize(FileEntries.size());
1370 for (const auto &Entry : FileEntries) {
1371 auto I = Entry.second;
1372 FilenameStrs[I] = normalizeFilename(Entry.first->getName());
1373 FilenameRefs[I] = FilenameStrs[I];
1376 std::string FilenamesAndCoverageMappings;
1377 llvm::raw_string_ostream OS(FilenamesAndCoverageMappings);
1378 CoverageFilenamesSectionWriter(FilenameRefs).write(OS);
1379 std::string RawCoverageMappings =
1380 llvm::join(CoverageMappings.begin(), CoverageMappings.end(), "");
1381 OS << RawCoverageMappings;
1382 size_t CoverageMappingSize = RawCoverageMappings.size();
1383 size_t FilenamesSize = OS.str().size() - CoverageMappingSize;
1384 // Append extra zeroes if necessary to ensure that the size of the filenames
1385 // and coverage mappings is a multiple of 8.
1386 if (size_t Rem = OS.str().size() % 8) {
1387 CoverageMappingSize += 8 - Rem;
1388 OS.write_zeros(8 - Rem);
1390 auto *FilenamesAndMappingsVal =
1391 llvm::ConstantDataArray::getString(Ctx, OS.str(), false);
1393 // Create the deferred function records array
1395 llvm::ArrayType::get(FunctionRecordTy, FunctionRecords.size());
1396 auto RecordsVal = llvm::ConstantArray::get(RecordsTy, FunctionRecords);
1398 llvm::Type *CovDataHeaderTypes[] = {
1399 #define COVMAP_HEADER(Type, LLVMType, Name, Init) LLVMType,
1400 #include "llvm/ProfileData/InstrProfData.inc"
1402 auto CovDataHeaderTy =
1403 llvm::StructType::get(Ctx, makeArrayRef(CovDataHeaderTypes));
1404 llvm::Constant *CovDataHeaderVals[] = {
1405 #define COVMAP_HEADER(Type, LLVMType, Name, Init) Init,
1406 #include "llvm/ProfileData/InstrProfData.inc"
1408 auto CovDataHeaderVal = llvm::ConstantStruct::get(
1409 CovDataHeaderTy, makeArrayRef(CovDataHeaderVals));
1411 // Create the coverage data record
1412 llvm::Type *CovDataTypes[] = {CovDataHeaderTy, RecordsTy,
1413 FilenamesAndMappingsVal->getType()};
1414 auto CovDataTy = llvm::StructType::get(Ctx, makeArrayRef(CovDataTypes));
1415 llvm::Constant *TUDataVals[] = {CovDataHeaderVal, RecordsVal,
1416 FilenamesAndMappingsVal};
1418 llvm::ConstantStruct::get(CovDataTy, makeArrayRef(TUDataVals));
1419 auto CovData = new llvm::GlobalVariable(
1420 CGM.getModule(), CovDataTy, true, llvm::GlobalValue::InternalLinkage,
1421 CovDataVal, llvm::getCoverageMappingVarName());
1423 CovData->setSection(getCoverageSection(CGM));
1424 CovData->setAlignment(8);
1426 // Make sure the data doesn't get deleted.
1427 CGM.addUsedGlobal(CovData);
1428 // Create the deferred function records array
1429 if (!FunctionNames.empty()) {
1430 auto NamesArrTy = llvm::ArrayType::get(llvm::Type::getInt8PtrTy(Ctx),
1431 FunctionNames.size());
1432 auto NamesArrVal = llvm::ConstantArray::get(NamesArrTy, FunctionNames);
1433 // This variable will *NOT* be emitted to the object file. It is used
1434 // to pass the list of names referenced to codegen.
1435 new llvm::GlobalVariable(CGM.getModule(), NamesArrTy, true,
1436 llvm::GlobalValue::InternalLinkage, NamesArrVal,
1437 llvm::getCoverageUnusedNamesVarName());
1441 unsigned CoverageMappingModuleGen::getFileID(const FileEntry *File) {
1442 auto It = FileEntries.find(File);
1443 if (It != FileEntries.end())
1445 unsigned FileID = FileEntries.size();
1446 FileEntries.insert(std::make_pair(File, FileID));
1450 void CoverageMappingGen::emitCounterMapping(const Decl *D,
1451 llvm::raw_ostream &OS) {
1453 CounterCoverageMappingBuilder Walker(CVM, *CounterMap, SM, LangOpts);
1454 Walker.VisitDecl(D);
1458 void CoverageMappingGen::emitEmptyMapping(const Decl *D,
1459 llvm::raw_ostream &OS) {
1460 EmptyCoverageMappingBuilder Walker(CVM, SM, LangOpts);
1461 Walker.VisitDecl(D);