1 //===--- CoverageMappingGen.cpp - Coverage mapping generation ---*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // Instrumentation-based code coverage mapping generator
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "CoverageMappingGen.h"
14 #include "CodeGenFunction.h"
15 #include "clang/AST/StmtVisitor.h"
16 #include "clang/Basic/Diagnostic.h"
17 #include "clang/Basic/FileManager.h"
18 #include "clang/Frontend/FrontendDiagnostic.h"
19 #include "clang/Lex/Lexer.h"
20 #include "llvm/ADT/Optional.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/ProfileData/InstrProfReader.h"
27 #include "llvm/Support/FileSystem.h"
28 #include "llvm/Support/Path.h"
29 
30 // This selects the coverage mapping format defined when `InstrProfData.inc`
31 // is textually included.
32 #define COVMAP_V3
33 
34 static llvm::cl::opt<bool> EmptyLineCommentCoverage(
35     "emptyline-comment-coverage",
36     llvm::cl::desc("Emit emptylines and comment lines as skipped regions (only "
37                    "disable it on test)"),
38     llvm::cl::init(true), llvm::cl::Hidden);
39 
40 using namespace clang;
41 using namespace CodeGen;
42 using namespace llvm::coverage;
43 
44 CoverageSourceInfo *
45 CoverageMappingModuleGen::setUpCoverageCallbacks(Preprocessor &PP) {
46   CoverageSourceInfo *CoverageInfo =
47       new CoverageSourceInfo(PP.getSourceManager());
48   PP.addPPCallbacks(std::unique_ptr<PPCallbacks>(CoverageInfo));
49   if (EmptyLineCommentCoverage) {
50     PP.addCommentHandler(CoverageInfo);
51     PP.setEmptylineHandler(CoverageInfo);
52     PP.setPreprocessToken(true);
53     PP.setTokenWatcher([CoverageInfo](clang::Token Tok) {
54       // Update previous token location.
55       CoverageInfo->PrevTokLoc = Tok.getLocation();
56       if (Tok.getKind() != clang::tok::eod)
57         CoverageInfo->updateNextTokLoc(Tok.getLocation());
58     });
59   }
60   return CoverageInfo;
61 }
62 
63 void CoverageSourceInfo::AddSkippedRange(SourceRange Range) {
64   if (EmptyLineCommentCoverage && !SkippedRanges.empty() &&
65       PrevTokLoc == SkippedRanges.back().PrevTokLoc &&
66       SourceMgr.isWrittenInSameFile(SkippedRanges.back().Range.getEnd(),
67                                     Range.getBegin()))
68     SkippedRanges.back().Range.setEnd(Range.getEnd());
69   else
70     SkippedRanges.push_back({Range, PrevTokLoc});
71 }
72 
73 void CoverageSourceInfo::SourceRangeSkipped(SourceRange Range, SourceLocation) {
74   AddSkippedRange(Range);
75 }
76 
77 void CoverageSourceInfo::HandleEmptyline(SourceRange Range) {
78   AddSkippedRange(Range);
79 }
80 
81 bool CoverageSourceInfo::HandleComment(Preprocessor &PP, SourceRange Range) {
82   AddSkippedRange(Range);
83   return false;
84 }
85 
86 void CoverageSourceInfo::updateNextTokLoc(SourceLocation Loc) {
87   if (!SkippedRanges.empty() && SkippedRanges.back().NextTokLoc.isInvalid())
88     SkippedRanges.back().NextTokLoc = Loc;
89 }
90 
91 namespace {
92 
93 /// A region of source code that can be mapped to a counter.
94 class SourceMappingRegion {
95   /// Primary Counter that is also used for Branch Regions for "True" branches.
96   Counter Count;
97 
98   /// Secondary Counter used for Branch Regions for "False" branches.
99   Optional<Counter> FalseCount;
100 
101   /// The region's starting location.
102   Optional<SourceLocation> LocStart;
103 
104   /// The region's ending location.
105   Optional<SourceLocation> LocEnd;
106 
107   /// Whether this region should be emitted after its parent is emitted.
108   bool DeferRegion;
109 
110   /// Whether this region is a gap region. The count from a gap region is set
111   /// as the line execution count if there are no other regions on the line.
112   bool GapRegion;
113 
114 public:
115   SourceMappingRegion(Counter Count, Optional<SourceLocation> LocStart,
116                       Optional<SourceLocation> LocEnd, bool DeferRegion = false,
117                       bool GapRegion = false)
118       : Count(Count), LocStart(LocStart), LocEnd(LocEnd),
119         DeferRegion(DeferRegion), GapRegion(GapRegion) {}
120 
121   SourceMappingRegion(Counter Count, Optional<Counter> FalseCount,
122                       Optional<SourceLocation> LocStart,
123                       Optional<SourceLocation> LocEnd, bool DeferRegion = false,
124                       bool GapRegion = false)
125       : Count(Count), FalseCount(FalseCount), LocStart(LocStart),
126         LocEnd(LocEnd), DeferRegion(DeferRegion), GapRegion(GapRegion) {}
127 
128   const Counter &getCounter() const { return Count; }
129 
130   const Counter &getFalseCounter() const {
131     assert(FalseCount && "Region has no alternate counter");
132     return *FalseCount;
133   }
134 
135   void setCounter(Counter C) { Count = C; }
136 
137   bool hasStartLoc() const { return LocStart.hasValue(); }
138 
139   void setStartLoc(SourceLocation Loc) { LocStart = Loc; }
140 
141   SourceLocation getBeginLoc() const {
142     assert(LocStart && "Region has no start location");
143     return *LocStart;
144   }
145 
146   bool hasEndLoc() const { return LocEnd.hasValue(); }
147 
148   void setEndLoc(SourceLocation Loc) {
149     assert(Loc.isValid() && "Setting an invalid end location");
150     LocEnd = Loc;
151   }
152 
153   SourceLocation getEndLoc() const {
154     assert(LocEnd && "Region has no end location");
155     return *LocEnd;
156   }
157 
158   bool isDeferred() const { return DeferRegion; }
159 
160   void setDeferred(bool Deferred) { DeferRegion = Deferred; }
161 
162   bool isGap() const { return GapRegion; }
163 
164   void setGap(bool Gap) { GapRegion = Gap; }
165 
166   bool isBranch() const { return FalseCount.hasValue(); }
167 };
168 
169 /// Spelling locations for the start and end of a source region.
170 struct SpellingRegion {
171   /// The line where the region starts.
172   unsigned LineStart;
173 
174   /// The column where the region starts.
175   unsigned ColumnStart;
176 
177   /// The line where the region ends.
178   unsigned LineEnd;
179 
180   /// The column where the region ends.
181   unsigned ColumnEnd;
182 
183   SpellingRegion(SourceManager &SM, SourceLocation LocStart,
184                  SourceLocation LocEnd) {
185     LineStart = SM.getSpellingLineNumber(LocStart);
186     ColumnStart = SM.getSpellingColumnNumber(LocStart);
187     LineEnd = SM.getSpellingLineNumber(LocEnd);
188     ColumnEnd = SM.getSpellingColumnNumber(LocEnd);
189   }
190 
191   SpellingRegion(SourceManager &SM, SourceMappingRegion &R)
192       : SpellingRegion(SM, R.getBeginLoc(), R.getEndLoc()) {}
193 
194   /// Check if the start and end locations appear in source order, i.e
195   /// top->bottom, left->right.
196   bool isInSourceOrder() const {
197     return (LineStart < LineEnd) ||
198            (LineStart == LineEnd && ColumnStart <= ColumnEnd);
199   }
200 };
201 
202 /// Provides the common functionality for the different
203 /// coverage mapping region builders.
204 class CoverageMappingBuilder {
205 public:
206   CoverageMappingModuleGen &CVM;
207   SourceManager &SM;
208   const LangOptions &LangOpts;
209 
210 private:
211   /// Map of clang's FileIDs to IDs used for coverage mapping.
212   llvm::SmallDenseMap<FileID, std::pair<unsigned, SourceLocation>, 8>
213       FileIDMapping;
214 
215 public:
216   /// The coverage mapping regions for this function
217   llvm::SmallVector<CounterMappingRegion, 32> MappingRegions;
218   /// The source mapping regions for this function.
219   std::vector<SourceMappingRegion> SourceRegions;
220 
221   /// A set of regions which can be used as a filter.
222   ///
223   /// It is produced by emitExpansionRegions() and is used in
224   /// emitSourceRegions() to suppress producing code regions if
225   /// the same area is covered by expansion regions.
226   typedef llvm::SmallSet<std::pair<SourceLocation, SourceLocation>, 8>
227       SourceRegionFilter;
228 
229   CoverageMappingBuilder(CoverageMappingModuleGen &CVM, SourceManager &SM,
230                          const LangOptions &LangOpts)
231       : CVM(CVM), SM(SM), LangOpts(LangOpts) {}
232 
233   /// Return the precise end location for the given token.
234   SourceLocation getPreciseTokenLocEnd(SourceLocation Loc) {
235     // We avoid getLocForEndOfToken here, because it doesn't do what we want for
236     // macro locations, which we just treat as expanded files.
237     unsigned TokLen =
238         Lexer::MeasureTokenLength(SM.getSpellingLoc(Loc), SM, LangOpts);
239     return Loc.getLocWithOffset(TokLen);
240   }
241 
242   /// Return the start location of an included file or expanded macro.
243   SourceLocation getStartOfFileOrMacro(SourceLocation Loc) {
244     if (Loc.isMacroID())
245       return Loc.getLocWithOffset(-SM.getFileOffset(Loc));
246     return SM.getLocForStartOfFile(SM.getFileID(Loc));
247   }
248 
249   /// Return the end location of an included file or expanded macro.
250   SourceLocation getEndOfFileOrMacro(SourceLocation Loc) {
251     if (Loc.isMacroID())
252       return Loc.getLocWithOffset(SM.getFileIDSize(SM.getFileID(Loc)) -
253                                   SM.getFileOffset(Loc));
254     return SM.getLocForEndOfFile(SM.getFileID(Loc));
255   }
256 
257   /// Find out where the current file is included or macro is expanded.
258   SourceLocation getIncludeOrExpansionLoc(SourceLocation Loc) {
259     return Loc.isMacroID() ? SM.getImmediateExpansionRange(Loc).getBegin()
260                            : SM.getIncludeLoc(SM.getFileID(Loc));
261   }
262 
263   /// Return true if \c Loc is a location in a built-in macro.
264   bool isInBuiltin(SourceLocation Loc) {
265     return SM.getBufferName(SM.getSpellingLoc(Loc)) == "<built-in>";
266   }
267 
268   /// Check whether \c Loc is included or expanded from \c Parent.
269   bool isNestedIn(SourceLocation Loc, FileID Parent) {
270     do {
271       Loc = getIncludeOrExpansionLoc(Loc);
272       if (Loc.isInvalid())
273         return false;
274     } while (!SM.isInFileID(Loc, Parent));
275     return true;
276   }
277 
278   /// Get the start of \c S ignoring macro arguments and builtin macros.
279   SourceLocation getStart(const Stmt *S) {
280     SourceLocation Loc = S->getBeginLoc();
281     while (SM.isMacroArgExpansion(Loc) || isInBuiltin(Loc))
282       Loc = SM.getImmediateExpansionRange(Loc).getBegin();
283     return Loc;
284   }
285 
286   /// Get the end of \c S ignoring macro arguments and builtin macros.
287   SourceLocation getEnd(const Stmt *S) {
288     SourceLocation Loc = S->getEndLoc();
289     while (SM.isMacroArgExpansion(Loc) || isInBuiltin(Loc))
290       Loc = SM.getImmediateExpansionRange(Loc).getBegin();
291     return getPreciseTokenLocEnd(Loc);
292   }
293 
294   /// Find the set of files we have regions for and assign IDs
295   ///
296   /// Fills \c Mapping with the virtual file mapping needed to write out
297   /// coverage and collects the necessary file information to emit source and
298   /// expansion regions.
299   void gatherFileIDs(SmallVectorImpl<unsigned> &Mapping) {
300     FileIDMapping.clear();
301 
302     llvm::SmallSet<FileID, 8> Visited;
303     SmallVector<std::pair<SourceLocation, unsigned>, 8> FileLocs;
304     for (const auto &Region : SourceRegions) {
305       SourceLocation Loc = Region.getBeginLoc();
306       FileID File = SM.getFileID(Loc);
307       if (!Visited.insert(File).second)
308         continue;
309 
310       // Do not map FileID's associated with system headers.
311       if (SM.isInSystemHeader(SM.getSpellingLoc(Loc)))
312         continue;
313 
314       unsigned Depth = 0;
315       for (SourceLocation Parent = getIncludeOrExpansionLoc(Loc);
316            Parent.isValid(); Parent = getIncludeOrExpansionLoc(Parent))
317         ++Depth;
318       FileLocs.push_back(std::make_pair(Loc, Depth));
319     }
320     llvm::stable_sort(FileLocs, llvm::less_second());
321 
322     for (const auto &FL : FileLocs) {
323       SourceLocation Loc = FL.first;
324       FileID SpellingFile = SM.getDecomposedSpellingLoc(Loc).first;
325       auto Entry = SM.getFileEntryForID(SpellingFile);
326       if (!Entry)
327         continue;
328 
329       FileIDMapping[SM.getFileID(Loc)] = std::make_pair(Mapping.size(), Loc);
330       Mapping.push_back(CVM.getFileID(Entry));
331     }
332   }
333 
334   /// Get the coverage mapping file ID for \c Loc.
335   ///
336   /// If such file id doesn't exist, return None.
337   Optional<unsigned> getCoverageFileID(SourceLocation Loc) {
338     auto Mapping = FileIDMapping.find(SM.getFileID(Loc));
339     if (Mapping != FileIDMapping.end())
340       return Mapping->second.first;
341     return None;
342   }
343 
344   /// This shrinks the skipped range if it spans a line that contains a
345   /// non-comment token. If shrinking the skipped range would make it empty,
346   /// this returns None.
347   Optional<SpellingRegion> adjustSkippedRange(SourceManager &SM,
348                                               SourceLocation LocStart,
349                                               SourceLocation LocEnd,
350                                               SourceLocation PrevTokLoc,
351                                               SourceLocation NextTokLoc) {
352     SpellingRegion SR{SM, LocStart, LocEnd};
353     SR.ColumnStart = 1;
354     if (PrevTokLoc.isValid() && SM.isWrittenInSameFile(LocStart, PrevTokLoc) &&
355         SR.LineStart == SM.getSpellingLineNumber(PrevTokLoc))
356       SR.LineStart++;
357     if (NextTokLoc.isValid() && SM.isWrittenInSameFile(LocEnd, NextTokLoc) &&
358         SR.LineEnd == SM.getSpellingLineNumber(NextTokLoc)) {
359       SR.LineEnd--;
360       SR.ColumnEnd++;
361     }
362     if (SR.isInSourceOrder())
363       return SR;
364     return None;
365   }
366 
367   /// Gather all the regions that were skipped by the preprocessor
368   /// using the constructs like #if or comments.
369   void gatherSkippedRegions() {
370     /// An array of the minimum lineStarts and the maximum lineEnds
371     /// for mapping regions from the appropriate source files.
372     llvm::SmallVector<std::pair<unsigned, unsigned>, 8> FileLineRanges;
373     FileLineRanges.resize(
374         FileIDMapping.size(),
375         std::make_pair(std::numeric_limits<unsigned>::max(), 0));
376     for (const auto &R : MappingRegions) {
377       FileLineRanges[R.FileID].first =
378           std::min(FileLineRanges[R.FileID].first, R.LineStart);
379       FileLineRanges[R.FileID].second =
380           std::max(FileLineRanges[R.FileID].second, R.LineEnd);
381     }
382 
383     auto SkippedRanges = CVM.getSourceInfo().getSkippedRanges();
384     for (auto &I : SkippedRanges) {
385       SourceRange Range = I.Range;
386       auto LocStart = Range.getBegin();
387       auto LocEnd = Range.getEnd();
388       assert(SM.isWrittenInSameFile(LocStart, LocEnd) &&
389              "region spans multiple files");
390 
391       auto CovFileID = getCoverageFileID(LocStart);
392       if (!CovFileID)
393         continue;
394       Optional<SpellingRegion> SR =
395           adjustSkippedRange(SM, LocStart, LocEnd, I.PrevTokLoc, I.NextTokLoc);
396       if (!SR.hasValue())
397         continue;
398       auto Region = CounterMappingRegion::makeSkipped(
399           *CovFileID, SR->LineStart, SR->ColumnStart, SR->LineEnd,
400           SR->ColumnEnd);
401       // Make sure that we only collect the regions that are inside
402       // the source code of this function.
403       if (Region.LineStart >= FileLineRanges[*CovFileID].first &&
404           Region.LineEnd <= FileLineRanges[*CovFileID].second)
405         MappingRegions.push_back(Region);
406     }
407   }
408 
409   /// Generate the coverage counter mapping regions from collected
410   /// source regions.
411   void emitSourceRegions(const SourceRegionFilter &Filter) {
412     for (const auto &Region : SourceRegions) {
413       assert(Region.hasEndLoc() && "incomplete region");
414 
415       SourceLocation LocStart = Region.getBeginLoc();
416       assert(SM.getFileID(LocStart).isValid() && "region in invalid file");
417 
418       // Ignore regions from system headers.
419       if (SM.isInSystemHeader(SM.getSpellingLoc(LocStart)))
420         continue;
421 
422       auto CovFileID = getCoverageFileID(LocStart);
423       // Ignore regions that don't have a file, such as builtin macros.
424       if (!CovFileID)
425         continue;
426 
427       SourceLocation LocEnd = Region.getEndLoc();
428       assert(SM.isWrittenInSameFile(LocStart, LocEnd) &&
429              "region spans multiple files");
430 
431       // Don't add code regions for the area covered by expansion regions.
432       // This not only suppresses redundant regions, but sometimes prevents
433       // creating regions with wrong counters if, for example, a statement's
434       // body ends at the end of a nested macro.
435       if (Filter.count(std::make_pair(LocStart, LocEnd)))
436         continue;
437 
438       // Find the spelling locations for the mapping region.
439       SpellingRegion SR{SM, LocStart, LocEnd};
440       assert(SR.isInSourceOrder() && "region start and end out of order");
441 
442       if (Region.isGap()) {
443         MappingRegions.push_back(CounterMappingRegion::makeGapRegion(
444             Region.getCounter(), *CovFileID, SR.LineStart, SR.ColumnStart,
445             SR.LineEnd, SR.ColumnEnd));
446       } else if (Region.isBranch()) {
447         MappingRegions.push_back(CounterMappingRegion::makeBranchRegion(
448             Region.getCounter(), Region.getFalseCounter(), *CovFileID,
449             SR.LineStart, SR.ColumnStart, SR.LineEnd, SR.ColumnEnd));
450       } else {
451         MappingRegions.push_back(CounterMappingRegion::makeRegion(
452             Region.getCounter(), *CovFileID, SR.LineStart, SR.ColumnStart,
453             SR.LineEnd, SR.ColumnEnd));
454       }
455     }
456   }
457 
458   /// Generate expansion regions for each virtual file we've seen.
459   SourceRegionFilter emitExpansionRegions() {
460     SourceRegionFilter Filter;
461     for (const auto &FM : FileIDMapping) {
462       SourceLocation ExpandedLoc = FM.second.second;
463       SourceLocation ParentLoc = getIncludeOrExpansionLoc(ExpandedLoc);
464       if (ParentLoc.isInvalid())
465         continue;
466 
467       auto ParentFileID = getCoverageFileID(ParentLoc);
468       if (!ParentFileID)
469         continue;
470       auto ExpandedFileID = getCoverageFileID(ExpandedLoc);
471       assert(ExpandedFileID && "expansion in uncovered file");
472 
473       SourceLocation LocEnd = getPreciseTokenLocEnd(ParentLoc);
474       assert(SM.isWrittenInSameFile(ParentLoc, LocEnd) &&
475              "region spans multiple files");
476       Filter.insert(std::make_pair(ParentLoc, LocEnd));
477 
478       SpellingRegion SR{SM, ParentLoc, LocEnd};
479       assert(SR.isInSourceOrder() && "region start and end out of order");
480       MappingRegions.push_back(CounterMappingRegion::makeExpansion(
481           *ParentFileID, *ExpandedFileID, SR.LineStart, SR.ColumnStart,
482           SR.LineEnd, SR.ColumnEnd));
483     }
484     return Filter;
485   }
486 };
487 
488 /// Creates unreachable coverage regions for the functions that
489 /// are not emitted.
490 struct EmptyCoverageMappingBuilder : public CoverageMappingBuilder {
491   EmptyCoverageMappingBuilder(CoverageMappingModuleGen &CVM, SourceManager &SM,
492                               const LangOptions &LangOpts)
493       : CoverageMappingBuilder(CVM, SM, LangOpts) {}
494 
495   void VisitDecl(const Decl *D) {
496     if (!D->hasBody())
497       return;
498     auto Body = D->getBody();
499     SourceLocation Start = getStart(Body);
500     SourceLocation End = getEnd(Body);
501     if (!SM.isWrittenInSameFile(Start, End)) {
502       // Walk up to find the common ancestor.
503       // Correct the locations accordingly.
504       FileID StartFileID = SM.getFileID(Start);
505       FileID EndFileID = SM.getFileID(End);
506       while (StartFileID != EndFileID && !isNestedIn(End, StartFileID)) {
507         Start = getIncludeOrExpansionLoc(Start);
508         assert(Start.isValid() &&
509                "Declaration start location not nested within a known region");
510         StartFileID = SM.getFileID(Start);
511       }
512       while (StartFileID != EndFileID) {
513         End = getPreciseTokenLocEnd(getIncludeOrExpansionLoc(End));
514         assert(End.isValid() &&
515                "Declaration end location not nested within a known region");
516         EndFileID = SM.getFileID(End);
517       }
518     }
519     SourceRegions.emplace_back(Counter(), Start, End);
520   }
521 
522   /// Write the mapping data to the output stream
523   void write(llvm::raw_ostream &OS) {
524     SmallVector<unsigned, 16> FileIDMapping;
525     gatherFileIDs(FileIDMapping);
526     emitSourceRegions(SourceRegionFilter());
527 
528     if (MappingRegions.empty())
529       return;
530 
531     CoverageMappingWriter Writer(FileIDMapping, None, MappingRegions);
532     Writer.write(OS);
533   }
534 };
535 
536 /// A StmtVisitor that creates coverage mapping regions which map
537 /// from the source code locations to the PGO counters.
538 struct CounterCoverageMappingBuilder
539     : public CoverageMappingBuilder,
540       public ConstStmtVisitor<CounterCoverageMappingBuilder> {
541   /// The map of statements to count values.
542   llvm::DenseMap<const Stmt *, unsigned> &CounterMap;
543 
544   /// A stack of currently live regions.
545   std::vector<SourceMappingRegion> RegionStack;
546 
547   /// The currently deferred region: its end location and count can be set once
548   /// its parent has been popped from the region stack.
549   Optional<SourceMappingRegion> DeferredRegion;
550 
551   CounterExpressionBuilder Builder;
552 
553   /// A location in the most recently visited file or macro.
554   ///
555   /// This is used to adjust the active source regions appropriately when
556   /// expressions cross file or macro boundaries.
557   SourceLocation MostRecentLocation;
558 
559   /// Location of the last terminated region.
560   Optional<std::pair<SourceLocation, size_t>> LastTerminatedRegion;
561 
562   /// Return a counter for the subtraction of \c RHS from \c LHS
563   Counter subtractCounters(Counter LHS, Counter RHS) {
564     return Builder.subtract(LHS, RHS);
565   }
566 
567   /// Return a counter for the sum of \c LHS and \c RHS.
568   Counter addCounters(Counter LHS, Counter RHS) {
569     return Builder.add(LHS, RHS);
570   }
571 
572   Counter addCounters(Counter C1, Counter C2, Counter C3) {
573     return addCounters(addCounters(C1, C2), C3);
574   }
575 
576   /// Return the region counter for the given statement.
577   ///
578   /// This should only be called on statements that have a dedicated counter.
579   Counter getRegionCounter(const Stmt *S) {
580     return Counter::getCounter(CounterMap[S]);
581   }
582 
583   /// Push a region onto the stack.
584   ///
585   /// Returns the index on the stack where the region was pushed. This can be
586   /// used with popRegions to exit a "scope", ending the region that was pushed.
587   size_t pushRegion(Counter Count, Optional<SourceLocation> StartLoc = None,
588                     Optional<SourceLocation> EndLoc = None,
589                     Optional<Counter> FalseCount = None) {
590 
591     if (StartLoc && !FalseCount.hasValue()) {
592       MostRecentLocation = *StartLoc;
593       completeDeferred(Count, MostRecentLocation);
594     }
595 
596     RegionStack.emplace_back(Count, FalseCount, StartLoc, EndLoc,
597                              FalseCount.hasValue());
598 
599     return RegionStack.size() - 1;
600   }
601 
602   /// Complete any pending deferred region by setting its end location and
603   /// count, and then pushing it onto the region stack.
604   size_t completeDeferred(Counter Count, SourceLocation DeferredEndLoc) {
605     size_t Index = RegionStack.size();
606     if (!DeferredRegion)
607       return Index;
608 
609     // Consume the pending region.
610     SourceMappingRegion DR = DeferredRegion.getValue();
611     DeferredRegion = None;
612 
613     // If the region ends in an expansion, find the expansion site.
614     FileID StartFile = SM.getFileID(DR.getBeginLoc());
615     if (SM.getFileID(DeferredEndLoc) != StartFile) {
616       if (isNestedIn(DeferredEndLoc, StartFile)) {
617         do {
618           DeferredEndLoc = getIncludeOrExpansionLoc(DeferredEndLoc);
619         } while (StartFile != SM.getFileID(DeferredEndLoc));
620       } else {
621         return Index;
622       }
623     }
624 
625     // The parent of this deferred region ends where the containing decl ends,
626     // so the region isn't useful.
627     if (DR.getBeginLoc() == DeferredEndLoc)
628       return Index;
629 
630     // If we're visiting statements in non-source order (e.g switch cases or
631     // a loop condition) we can't construct a sensible deferred region.
632     if (!SpellingRegion(SM, DR.getBeginLoc(), DeferredEndLoc).isInSourceOrder())
633       return Index;
634 
635     DR.setGap(true);
636     DR.setCounter(Count);
637     DR.setEndLoc(DeferredEndLoc);
638     handleFileExit(DeferredEndLoc);
639     RegionStack.push_back(DR);
640     return Index;
641   }
642 
643   /// Complete a deferred region created after a terminated region at the
644   /// top-level.
645   void completeTopLevelDeferredRegion(Counter Count,
646                                       SourceLocation DeferredEndLoc) {
647     if (DeferredRegion || !LastTerminatedRegion)
648       return;
649 
650     if (LastTerminatedRegion->second != RegionStack.size())
651       return;
652 
653     SourceLocation Start = LastTerminatedRegion->first;
654     if (SM.getFileID(Start) != SM.getMainFileID())
655       return;
656 
657     SourceMappingRegion DR = RegionStack.back();
658     DR.setStartLoc(Start);
659     DR.setDeferred(false);
660     DeferredRegion = DR;
661     completeDeferred(Count, DeferredEndLoc);
662   }
663 
664   size_t locationDepth(SourceLocation Loc) {
665     size_t Depth = 0;
666     while (Loc.isValid()) {
667       Loc = getIncludeOrExpansionLoc(Loc);
668       Depth++;
669     }
670     return Depth;
671   }
672 
673   /// Pop regions from the stack into the function's list of regions.
674   ///
675   /// Adds all regions from \c ParentIndex to the top of the stack to the
676   /// function's \c SourceRegions.
677   void popRegions(size_t ParentIndex) {
678     assert(RegionStack.size() >= ParentIndex && "parent not in stack");
679     bool ParentOfDeferredRegion = false;
680     while (RegionStack.size() > ParentIndex) {
681       SourceMappingRegion &Region = RegionStack.back();
682       if (Region.hasStartLoc()) {
683         SourceLocation StartLoc = Region.getBeginLoc();
684         SourceLocation EndLoc = Region.hasEndLoc()
685                                     ? Region.getEndLoc()
686                                     : RegionStack[ParentIndex].getEndLoc();
687         bool isBranch = Region.isBranch();
688         size_t StartDepth = locationDepth(StartLoc);
689         size_t EndDepth = locationDepth(EndLoc);
690         while (!SM.isWrittenInSameFile(StartLoc, EndLoc)) {
691           bool UnnestStart = StartDepth >= EndDepth;
692           bool UnnestEnd = EndDepth >= StartDepth;
693           if (UnnestEnd) {
694             // The region ends in a nested file or macro expansion. If the
695             // region is not a branch region, create a separate region for each
696             // expansion, and for all regions, update the EndLoc. Branch
697             // regions should not be split in order to keep a straightforward
698             // correspondance between the region and its associated branch
699             // condition, even if the condition spans multiple depths.
700             SourceLocation NestedLoc = getStartOfFileOrMacro(EndLoc);
701             assert(SM.isWrittenInSameFile(NestedLoc, EndLoc));
702 
703             if (!isBranch && !isRegionAlreadyAdded(NestedLoc, EndLoc))
704               SourceRegions.emplace_back(Region.getCounter(), NestedLoc,
705                                          EndLoc);
706 
707             EndLoc = getPreciseTokenLocEnd(getIncludeOrExpansionLoc(EndLoc));
708             if (EndLoc.isInvalid())
709               llvm::report_fatal_error(
710                   "File exit not handled before popRegions");
711             EndDepth--;
712           }
713           if (UnnestStart) {
714             // The region ends in a nested file or macro expansion. If the
715             // region is not a branch region, create a separate region for each
716             // expansion, and for all regions, update the StartLoc. Branch
717             // regions should not be split in order to keep a straightforward
718             // correspondance between the region and its associated branch
719             // condition, even if the condition spans multiple depths.
720             SourceLocation NestedLoc = getEndOfFileOrMacro(StartLoc);
721             assert(SM.isWrittenInSameFile(StartLoc, NestedLoc));
722 
723             if (!isBranch && !isRegionAlreadyAdded(StartLoc, NestedLoc))
724               SourceRegions.emplace_back(Region.getCounter(), StartLoc,
725                                          NestedLoc);
726 
727             StartLoc = getIncludeOrExpansionLoc(StartLoc);
728             if (StartLoc.isInvalid())
729               llvm::report_fatal_error(
730                   "File exit not handled before popRegions");
731             StartDepth--;
732           }
733         }
734         Region.setStartLoc(StartLoc);
735         Region.setEndLoc(EndLoc);
736 
737         if (!isBranch) {
738           MostRecentLocation = EndLoc;
739           // If this region happens to span an entire expansion, we need to
740           // make sure we don't overlap the parent region with it.
741           if (StartLoc == getStartOfFileOrMacro(StartLoc) &&
742               EndLoc == getEndOfFileOrMacro(EndLoc))
743             MostRecentLocation = getIncludeOrExpansionLoc(EndLoc);
744         }
745 
746         assert(SM.isWrittenInSameFile(Region.getBeginLoc(), EndLoc));
747         assert(SpellingRegion(SM, Region).isInSourceOrder());
748         SourceRegions.push_back(Region);
749 
750         if (ParentOfDeferredRegion) {
751           ParentOfDeferredRegion = false;
752 
753           // If there's an existing deferred region, keep the old one, because
754           // it means there are two consecutive returns (or a similar pattern).
755           if (!DeferredRegion.hasValue() &&
756               // File IDs aren't gathered within macro expansions, so it isn't
757               // useful to try and create a deferred region inside of one.
758               !EndLoc.isMacroID())
759             DeferredRegion =
760                 SourceMappingRegion(Counter::getZero(), EndLoc, None);
761         }
762       } else if (Region.isDeferred()) {
763         assert(!ParentOfDeferredRegion && "Consecutive deferred regions");
764         ParentOfDeferredRegion = true;
765       }
766       RegionStack.pop_back();
767 
768       // If the zero region pushed after the last terminated region no longer
769       // exists, clear its cached information.
770       if (LastTerminatedRegion &&
771           RegionStack.size() < LastTerminatedRegion->second)
772         LastTerminatedRegion = None;
773     }
774     assert(!ParentOfDeferredRegion && "Deferred region with no parent");
775   }
776 
777   /// Return the currently active region.
778   SourceMappingRegion &getRegion() {
779     assert(!RegionStack.empty() && "statement has no region");
780     return RegionStack.back();
781   }
782 
783   /// Propagate counts through the children of \p S if \p VisitChildren is true.
784   /// Otherwise, only emit a count for \p S itself.
785   Counter propagateCounts(Counter TopCount, const Stmt *S,
786                           bool VisitChildren = true) {
787     SourceLocation StartLoc = getStart(S);
788     SourceLocation EndLoc = getEnd(S);
789     size_t Index = pushRegion(TopCount, StartLoc, EndLoc);
790     if (VisitChildren)
791       Visit(S);
792     Counter ExitCount = getRegion().getCounter();
793     popRegions(Index);
794 
795     // The statement may be spanned by an expansion. Make sure we handle a file
796     // exit out of this expansion before moving to the next statement.
797     if (SM.isBeforeInTranslationUnit(StartLoc, S->getBeginLoc()))
798       MostRecentLocation = EndLoc;
799 
800     return ExitCount;
801   }
802 
803   /// Determine whether the given condition can be constant folded.
804   bool ConditionFoldsToBool(const Expr *Cond) {
805     Expr::EvalResult Result;
806     return (Cond->EvaluateAsInt(Result, CVM.getCodeGenModule().getContext()));
807   }
808 
809   /// Create a Branch Region around an instrumentable condition for coverage
810   /// and add it to the function's SourceRegions.  A branch region tracks a
811   /// "True" counter and a "False" counter for boolean expressions that
812   /// result in the generation of a branch.
813   void createBranchRegion(const Expr *C, Counter TrueCnt, Counter FalseCnt) {
814     // Check for NULL conditions.
815     if (!C)
816       return;
817 
818     // Ensure we are an instrumentable condition (i.e. no "&&" or "||").  Push
819     // region onto RegionStack but immediately pop it (which adds it to the
820     // function's SourceRegions) because it doesn't apply to any other source
821     // code other than the Condition.
822     if (CodeGenFunction::isInstrumentedCondition(C)) {
823       // If a condition can fold to true or false, the corresponding branch
824       // will be removed.  Create a region with both counters hard-coded to
825       // zero. This allows us to visualize them in a special way.
826       // Alternatively, we can prevent any optimization done via
827       // constant-folding by ensuring that ConstantFoldsToSimpleInteger() in
828       // CodeGenFunction.c always returns false, but that is very heavy-handed.
829       if (ConditionFoldsToBool(C))
830         popRegions(pushRegion(Counter::getZero(), getStart(C), getEnd(C),
831                               Counter::getZero()));
832       else
833         // Otherwise, create a region with the True counter and False counter.
834         popRegions(pushRegion(TrueCnt, getStart(C), getEnd(C), FalseCnt));
835     }
836   }
837 
838   /// Create a Branch Region around a SwitchCase for code coverage
839   /// and add it to the function's SourceRegions.
840   void createSwitchCaseRegion(const SwitchCase *SC, Counter TrueCnt,
841                               Counter FalseCnt) {
842     // Push region onto RegionStack but immediately pop it (which adds it to
843     // the function's SourceRegions) because it doesn't apply to any other
844     // source other than the SwitchCase.
845     popRegions(pushRegion(TrueCnt, getStart(SC), SC->getColonLoc(), FalseCnt));
846   }
847 
848   /// Check whether a region with bounds \c StartLoc and \c EndLoc
849   /// is already added to \c SourceRegions.
850   bool isRegionAlreadyAdded(SourceLocation StartLoc, SourceLocation EndLoc,
851                             bool isBranch = false) {
852     return SourceRegions.rend() !=
853            std::find_if(SourceRegions.rbegin(), SourceRegions.rend(),
854                         [&](const SourceMappingRegion &Region) {
855                           return Region.getBeginLoc() == StartLoc &&
856                                  Region.getEndLoc() == EndLoc &&
857                                  Region.isBranch() == isBranch;
858                         });
859   }
860 
861   /// Adjust the most recently visited location to \c EndLoc.
862   ///
863   /// This should be used after visiting any statements in non-source order.
864   void adjustForOutOfOrderTraversal(SourceLocation EndLoc) {
865     MostRecentLocation = EndLoc;
866     // The code region for a whole macro is created in handleFileExit() when
867     // it detects exiting of the virtual file of that macro. If we visited
868     // statements in non-source order, we might already have such a region
869     // added, for example, if a body of a loop is divided among multiple
870     // macros. Avoid adding duplicate regions in such case.
871     if (getRegion().hasEndLoc() &&
872         MostRecentLocation == getEndOfFileOrMacro(MostRecentLocation) &&
873         isRegionAlreadyAdded(getStartOfFileOrMacro(MostRecentLocation),
874                              MostRecentLocation, getRegion().isBranch()))
875       MostRecentLocation = getIncludeOrExpansionLoc(MostRecentLocation);
876   }
877 
878   /// Adjust regions and state when \c NewLoc exits a file.
879   ///
880   /// If moving from our most recently tracked location to \c NewLoc exits any
881   /// files, this adjusts our current region stack and creates the file regions
882   /// for the exited file.
883   void handleFileExit(SourceLocation NewLoc) {
884     if (NewLoc.isInvalid() ||
885         SM.isWrittenInSameFile(MostRecentLocation, NewLoc))
886       return;
887 
888     // If NewLoc is not in a file that contains MostRecentLocation, walk up to
889     // find the common ancestor.
890     SourceLocation LCA = NewLoc;
891     FileID ParentFile = SM.getFileID(LCA);
892     while (!isNestedIn(MostRecentLocation, ParentFile)) {
893       LCA = getIncludeOrExpansionLoc(LCA);
894       if (LCA.isInvalid() || SM.isWrittenInSameFile(LCA, MostRecentLocation)) {
895         // Since there isn't a common ancestor, no file was exited. We just need
896         // to adjust our location to the new file.
897         MostRecentLocation = NewLoc;
898         return;
899       }
900       ParentFile = SM.getFileID(LCA);
901     }
902 
903     llvm::SmallSet<SourceLocation, 8> StartLocs;
904     Optional<Counter> ParentCounter;
905     for (SourceMappingRegion &I : llvm::reverse(RegionStack)) {
906       if (!I.hasStartLoc())
907         continue;
908       SourceLocation Loc = I.getBeginLoc();
909       if (!isNestedIn(Loc, ParentFile)) {
910         ParentCounter = I.getCounter();
911         break;
912       }
913 
914       while (!SM.isInFileID(Loc, ParentFile)) {
915         // The most nested region for each start location is the one with the
916         // correct count. We avoid creating redundant regions by stopping once
917         // we've seen this region.
918         if (StartLocs.insert(Loc).second) {
919           if (I.isBranch())
920             SourceRegions.emplace_back(I.getCounter(), I.getFalseCounter(), Loc,
921                                        getEndOfFileOrMacro(Loc), I.isBranch());
922           else
923             SourceRegions.emplace_back(I.getCounter(), Loc,
924                                        getEndOfFileOrMacro(Loc));
925         }
926         Loc = getIncludeOrExpansionLoc(Loc);
927       }
928       I.setStartLoc(getPreciseTokenLocEnd(Loc));
929     }
930 
931     if (ParentCounter) {
932       // If the file is contained completely by another region and doesn't
933       // immediately start its own region, the whole file gets a region
934       // corresponding to the parent.
935       SourceLocation Loc = MostRecentLocation;
936       while (isNestedIn(Loc, ParentFile)) {
937         SourceLocation FileStart = getStartOfFileOrMacro(Loc);
938         if (StartLocs.insert(FileStart).second) {
939           SourceRegions.emplace_back(*ParentCounter, FileStart,
940                                      getEndOfFileOrMacro(Loc));
941           assert(SpellingRegion(SM, SourceRegions.back()).isInSourceOrder());
942         }
943         Loc = getIncludeOrExpansionLoc(Loc);
944       }
945     }
946 
947     MostRecentLocation = NewLoc;
948   }
949 
950   /// Ensure that \c S is included in the current region.
951   void extendRegion(const Stmt *S) {
952     SourceMappingRegion &Region = getRegion();
953     SourceLocation StartLoc = getStart(S);
954 
955     handleFileExit(StartLoc);
956     if (!Region.hasStartLoc())
957       Region.setStartLoc(StartLoc);
958 
959     completeDeferred(Region.getCounter(), StartLoc);
960   }
961 
962   /// Mark \c S as a terminator, starting a zero region.
963   void terminateRegion(const Stmt *S) {
964     extendRegion(S);
965     SourceMappingRegion &Region = getRegion();
966     SourceLocation EndLoc = getEnd(S);
967     if (!Region.hasEndLoc())
968       Region.setEndLoc(EndLoc);
969     pushRegion(Counter::getZero());
970     auto &ZeroRegion = getRegion();
971     ZeroRegion.setDeferred(true);
972     LastTerminatedRegion = {EndLoc, RegionStack.size()};
973   }
974 
975   /// Find a valid gap range between \p AfterLoc and \p BeforeLoc.
976   Optional<SourceRange> findGapAreaBetween(SourceLocation AfterLoc,
977                                            SourceLocation BeforeLoc) {
978     size_t StartDepth = locationDepth(AfterLoc);
979     size_t EndDepth = locationDepth(BeforeLoc);
980     while (!SM.isWrittenInSameFile(AfterLoc, BeforeLoc)) {
981       bool UnnestStart = StartDepth >= EndDepth;
982       bool UnnestEnd = EndDepth >= StartDepth;
983       if (UnnestEnd) {
984         assert(SM.isWrittenInSameFile(getStartOfFileOrMacro(BeforeLoc),
985                                       BeforeLoc));
986 
987         BeforeLoc = getIncludeOrExpansionLoc(BeforeLoc);
988         assert(BeforeLoc.isValid());
989         EndDepth--;
990       }
991       if (UnnestStart) {
992         assert(SM.isWrittenInSameFile(AfterLoc,
993                                       getEndOfFileOrMacro(AfterLoc)));
994 
995         AfterLoc = getIncludeOrExpansionLoc(AfterLoc);
996         assert(AfterLoc.isValid());
997         AfterLoc = getPreciseTokenLocEnd(AfterLoc);
998         assert(AfterLoc.isValid());
999         StartDepth--;
1000       }
1001     }
1002     AfterLoc = getPreciseTokenLocEnd(AfterLoc);
1003     // If the start and end locations of the gap are both within the same macro
1004     // file, the range may not be in source order.
1005     if (AfterLoc.isMacroID() || BeforeLoc.isMacroID())
1006       return None;
1007     if (!SM.isWrittenInSameFile(AfterLoc, BeforeLoc))
1008       return None;
1009     return {{AfterLoc, BeforeLoc}};
1010   }
1011 
1012   /// Emit a gap region between \p StartLoc and \p EndLoc with the given count.
1013   void fillGapAreaWithCount(SourceLocation StartLoc, SourceLocation EndLoc,
1014                             Counter Count) {
1015     if (StartLoc == EndLoc)
1016       return;
1017     assert(SpellingRegion(SM, StartLoc, EndLoc).isInSourceOrder());
1018     handleFileExit(StartLoc);
1019     size_t Index = pushRegion(Count, StartLoc, EndLoc);
1020     getRegion().setGap(true);
1021     handleFileExit(EndLoc);
1022     popRegions(Index);
1023   }
1024 
1025   /// Keep counts of breaks and continues inside loops.
1026   struct BreakContinue {
1027     Counter BreakCount;
1028     Counter ContinueCount;
1029   };
1030   SmallVector<BreakContinue, 8> BreakContinueStack;
1031 
1032   CounterCoverageMappingBuilder(
1033       CoverageMappingModuleGen &CVM,
1034       llvm::DenseMap<const Stmt *, unsigned> &CounterMap, SourceManager &SM,
1035       const LangOptions &LangOpts)
1036       : CoverageMappingBuilder(CVM, SM, LangOpts), CounterMap(CounterMap),
1037         DeferredRegion(None) {}
1038 
1039   /// Write the mapping data to the output stream
1040   void write(llvm::raw_ostream &OS) {
1041     llvm::SmallVector<unsigned, 8> VirtualFileMapping;
1042     gatherFileIDs(VirtualFileMapping);
1043     SourceRegionFilter Filter = emitExpansionRegions();
1044     assert(!DeferredRegion && "Deferred region never completed");
1045     emitSourceRegions(Filter);
1046     gatherSkippedRegions();
1047 
1048     if (MappingRegions.empty())
1049       return;
1050 
1051     CoverageMappingWriter Writer(VirtualFileMapping, Builder.getExpressions(),
1052                                  MappingRegions);
1053     Writer.write(OS);
1054   }
1055 
1056   void VisitStmt(const Stmt *S) {
1057     if (S->getBeginLoc().isValid())
1058       extendRegion(S);
1059     for (const Stmt *Child : S->children())
1060       if (Child)
1061         this->Visit(Child);
1062     handleFileExit(getEnd(S));
1063   }
1064 
1065   void VisitDecl(const Decl *D) {
1066     assert(!DeferredRegion && "Deferred region never completed");
1067 
1068     Stmt *Body = D->getBody();
1069 
1070     // Do not propagate region counts into system headers.
1071     if (Body && SM.isInSystemHeader(SM.getSpellingLoc(getStart(Body))))
1072       return;
1073 
1074     // Do not visit the artificial children nodes of defaulted methods. The
1075     // lexer may not be able to report back precise token end locations for
1076     // these children nodes (llvm.org/PR39822), and moreover users will not be
1077     // able to see coverage for them.
1078     bool Defaulted = false;
1079     if (auto *Method = dyn_cast<CXXMethodDecl>(D))
1080       Defaulted = Method->isDefaulted();
1081 
1082     propagateCounts(getRegionCounter(Body), Body,
1083                     /*VisitChildren=*/!Defaulted);
1084     assert(RegionStack.empty() && "Regions entered but never exited");
1085 
1086     // Discard the last uncompleted deferred region in a decl, if one exists.
1087     // This prevents lines at the end of a function containing only whitespace
1088     // or closing braces from being marked as uncovered.
1089     DeferredRegion = None;
1090   }
1091 
1092   void VisitReturnStmt(const ReturnStmt *S) {
1093     extendRegion(S);
1094     if (S->getRetValue())
1095       Visit(S->getRetValue());
1096     terminateRegion(S);
1097   }
1098 
1099   void VisitCoroutineBodyStmt(const CoroutineBodyStmt *S) {
1100     extendRegion(S);
1101     Visit(S->getBody());
1102   }
1103 
1104   void VisitCoreturnStmt(const CoreturnStmt *S) {
1105     extendRegion(S);
1106     if (S->getOperand())
1107       Visit(S->getOperand());
1108     terminateRegion(S);
1109   }
1110 
1111   void VisitCXXThrowExpr(const CXXThrowExpr *E) {
1112     extendRegion(E);
1113     if (E->getSubExpr())
1114       Visit(E->getSubExpr());
1115     terminateRegion(E);
1116   }
1117 
1118   void VisitGotoStmt(const GotoStmt *S) { terminateRegion(S); }
1119 
1120   void VisitLabelStmt(const LabelStmt *S) {
1121     Counter LabelCount = getRegionCounter(S);
1122     SourceLocation Start = getStart(S);
1123     completeTopLevelDeferredRegion(LabelCount, Start);
1124     completeDeferred(LabelCount, Start);
1125     // We can't extendRegion here or we risk overlapping with our new region.
1126     handleFileExit(Start);
1127     pushRegion(LabelCount, Start);
1128     Visit(S->getSubStmt());
1129   }
1130 
1131   void VisitBreakStmt(const BreakStmt *S) {
1132     assert(!BreakContinueStack.empty() && "break not in a loop or switch!");
1133     BreakContinueStack.back().BreakCount = addCounters(
1134         BreakContinueStack.back().BreakCount, getRegion().getCounter());
1135     // FIXME: a break in a switch should terminate regions for all preceding
1136     // case statements, not just the most recent one.
1137     terminateRegion(S);
1138   }
1139 
1140   void VisitContinueStmt(const ContinueStmt *S) {
1141     assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
1142     BreakContinueStack.back().ContinueCount = addCounters(
1143         BreakContinueStack.back().ContinueCount, getRegion().getCounter());
1144     terminateRegion(S);
1145   }
1146 
1147   void VisitCallExpr(const CallExpr *E) {
1148     VisitStmt(E);
1149 
1150     // Terminate the region when we hit a noreturn function.
1151     // (This is helpful dealing with switch statements.)
1152     QualType CalleeType = E->getCallee()->getType();
1153     if (getFunctionExtInfo(*CalleeType).getNoReturn())
1154       terminateRegion(E);
1155   }
1156 
1157   void VisitWhileStmt(const WhileStmt *S) {
1158     extendRegion(S);
1159 
1160     Counter ParentCount = getRegion().getCounter();
1161     Counter BodyCount = getRegionCounter(S);
1162 
1163     // Handle the body first so that we can get the backedge count.
1164     BreakContinueStack.push_back(BreakContinue());
1165     extendRegion(S->getBody());
1166     Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
1167     BreakContinue BC = BreakContinueStack.pop_back_val();
1168 
1169     // Go back to handle the condition.
1170     Counter CondCount =
1171         addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
1172     propagateCounts(CondCount, S->getCond());
1173     adjustForOutOfOrderTraversal(getEnd(S));
1174 
1175     // The body count applies to the area immediately after the increment.
1176     auto Gap = findGapAreaBetween(S->getRParenLoc(), getStart(S->getBody()));
1177     if (Gap)
1178       fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1179 
1180     Counter OutCount =
1181         addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount));
1182     if (OutCount != ParentCount)
1183       pushRegion(OutCount);
1184 
1185     // Create Branch Region around condition.
1186     createBranchRegion(S->getCond(), BodyCount,
1187                        subtractCounters(CondCount, BodyCount));
1188   }
1189 
1190   void VisitDoStmt(const DoStmt *S) {
1191     extendRegion(S);
1192 
1193     Counter ParentCount = getRegion().getCounter();
1194     Counter BodyCount = getRegionCounter(S);
1195 
1196     BreakContinueStack.push_back(BreakContinue());
1197     extendRegion(S->getBody());
1198     Counter BackedgeCount =
1199         propagateCounts(addCounters(ParentCount, BodyCount), S->getBody());
1200     BreakContinue BC = BreakContinueStack.pop_back_val();
1201 
1202     Counter CondCount = addCounters(BackedgeCount, BC.ContinueCount);
1203     propagateCounts(CondCount, S->getCond());
1204 
1205     Counter OutCount =
1206         addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount));
1207     if (OutCount != ParentCount)
1208       pushRegion(OutCount);
1209 
1210     // Create Branch Region around condition.
1211     createBranchRegion(S->getCond(), BodyCount,
1212                        subtractCounters(CondCount, BodyCount));
1213   }
1214 
1215   void VisitForStmt(const ForStmt *S) {
1216     extendRegion(S);
1217     if (S->getInit())
1218       Visit(S->getInit());
1219 
1220     Counter ParentCount = getRegion().getCounter();
1221     Counter BodyCount = getRegionCounter(S);
1222 
1223     // The loop increment may contain a break or continue.
1224     if (S->getInc())
1225       BreakContinueStack.emplace_back();
1226 
1227     // Handle the body first so that we can get the backedge count.
1228     BreakContinueStack.emplace_back();
1229     extendRegion(S->getBody());
1230     Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
1231     BreakContinue BodyBC = BreakContinueStack.pop_back_val();
1232 
1233     // The increment is essentially part of the body but it needs to include
1234     // the count for all the continue statements.
1235     BreakContinue IncrementBC;
1236     if (const Stmt *Inc = S->getInc()) {
1237       propagateCounts(addCounters(BackedgeCount, BodyBC.ContinueCount), Inc);
1238       IncrementBC = BreakContinueStack.pop_back_val();
1239     }
1240 
1241     // Go back to handle the condition.
1242     Counter CondCount = addCounters(
1243         addCounters(ParentCount, BackedgeCount, BodyBC.ContinueCount),
1244         IncrementBC.ContinueCount);
1245     if (const Expr *Cond = S->getCond()) {
1246       propagateCounts(CondCount, Cond);
1247       adjustForOutOfOrderTraversal(getEnd(S));
1248     }
1249 
1250     // The body count applies to the area immediately after the increment.
1251     auto Gap = findGapAreaBetween(S->getRParenLoc(), getStart(S->getBody()));
1252     if (Gap)
1253       fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1254 
1255     Counter OutCount = addCounters(BodyBC.BreakCount, IncrementBC.BreakCount,
1256                                    subtractCounters(CondCount, BodyCount));
1257     if (OutCount != ParentCount)
1258       pushRegion(OutCount);
1259 
1260     // Create Branch Region around condition.
1261     createBranchRegion(S->getCond(), BodyCount,
1262                        subtractCounters(CondCount, BodyCount));
1263   }
1264 
1265   void VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
1266     extendRegion(S);
1267     if (S->getInit())
1268       Visit(S->getInit());
1269     Visit(S->getLoopVarStmt());
1270     Visit(S->getRangeStmt());
1271 
1272     Counter ParentCount = getRegion().getCounter();
1273     Counter BodyCount = getRegionCounter(S);
1274 
1275     BreakContinueStack.push_back(BreakContinue());
1276     extendRegion(S->getBody());
1277     Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
1278     BreakContinue BC = BreakContinueStack.pop_back_val();
1279 
1280     // The body count applies to the area immediately after the range.
1281     auto Gap = findGapAreaBetween(S->getRParenLoc(), getStart(S->getBody()));
1282     if (Gap)
1283       fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1284 
1285     Counter LoopCount =
1286         addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
1287     Counter OutCount =
1288         addCounters(BC.BreakCount, subtractCounters(LoopCount, BodyCount));
1289     if (OutCount != ParentCount)
1290       pushRegion(OutCount);
1291 
1292     // Create Branch Region around condition.
1293     createBranchRegion(S->getCond(), BodyCount,
1294                        subtractCounters(LoopCount, BodyCount));
1295   }
1296 
1297   void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) {
1298     extendRegion(S);
1299     Visit(S->getElement());
1300 
1301     Counter ParentCount = getRegion().getCounter();
1302     Counter BodyCount = getRegionCounter(S);
1303 
1304     BreakContinueStack.push_back(BreakContinue());
1305     extendRegion(S->getBody());
1306     Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
1307     BreakContinue BC = BreakContinueStack.pop_back_val();
1308 
1309     // The body count applies to the area immediately after the collection.
1310     auto Gap = findGapAreaBetween(S->getRParenLoc(), getStart(S->getBody()));
1311     if (Gap)
1312       fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1313 
1314     Counter LoopCount =
1315         addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
1316     Counter OutCount =
1317         addCounters(BC.BreakCount, subtractCounters(LoopCount, BodyCount));
1318     if (OutCount != ParentCount)
1319       pushRegion(OutCount);
1320   }
1321 
1322   void VisitSwitchStmt(const SwitchStmt *S) {
1323     extendRegion(S);
1324     if (S->getInit())
1325       Visit(S->getInit());
1326     Visit(S->getCond());
1327 
1328     BreakContinueStack.push_back(BreakContinue());
1329 
1330     const Stmt *Body = S->getBody();
1331     extendRegion(Body);
1332     if (const auto *CS = dyn_cast<CompoundStmt>(Body)) {
1333       if (!CS->body_empty()) {
1334         // Make a region for the body of the switch.  If the body starts with
1335         // a case, that case will reuse this region; otherwise, this covers
1336         // the unreachable code at the beginning of the switch body.
1337         size_t Index = pushRegion(Counter::getZero(), getStart(CS));
1338         getRegion().setGap(true);
1339         for (const auto *Child : CS->children())
1340           Visit(Child);
1341 
1342         // Set the end for the body of the switch, if it isn't already set.
1343         for (size_t i = RegionStack.size(); i != Index; --i) {
1344           if (!RegionStack[i - 1].hasEndLoc())
1345             RegionStack[i - 1].setEndLoc(getEnd(CS->body_back()));
1346         }
1347 
1348         popRegions(Index);
1349       }
1350     } else
1351       propagateCounts(Counter::getZero(), Body);
1352     BreakContinue BC = BreakContinueStack.pop_back_val();
1353 
1354     if (!BreakContinueStack.empty())
1355       BreakContinueStack.back().ContinueCount = addCounters(
1356           BreakContinueStack.back().ContinueCount, BC.ContinueCount);
1357 
1358     Counter ParentCount = getRegion().getCounter();
1359     Counter ExitCount = getRegionCounter(S);
1360     SourceLocation ExitLoc = getEnd(S);
1361     pushRegion(ExitCount);
1362 
1363     // Ensure that handleFileExit recognizes when the end location is located
1364     // in a different file.
1365     MostRecentLocation = getStart(S);
1366     handleFileExit(ExitLoc);
1367 
1368     // Create a Branch Region around each Case. Subtract the case's
1369     // counter from the Parent counter to track the "False" branch count.
1370     Counter CaseCountSum;
1371     bool HasDefaultCase = false;
1372     const SwitchCase *Case = S->getSwitchCaseList();
1373     for (; Case; Case = Case->getNextSwitchCase()) {
1374       HasDefaultCase = HasDefaultCase || isa<DefaultStmt>(Case);
1375       CaseCountSum = addCounters(CaseCountSum, getRegionCounter(Case));
1376       createSwitchCaseRegion(
1377           Case, getRegionCounter(Case),
1378           subtractCounters(ParentCount, getRegionCounter(Case)));
1379     }
1380 
1381     // If no explicit default case exists, create a branch region to represent
1382     // the hidden branch, which will be added later by the CodeGen. This region
1383     // will be associated with the switch statement's condition.
1384     if (!HasDefaultCase) {
1385       Counter DefaultTrue = subtractCounters(ParentCount, CaseCountSum);
1386       Counter DefaultFalse = subtractCounters(ParentCount, DefaultTrue);
1387       createBranchRegion(S->getCond(), DefaultTrue, DefaultFalse);
1388     }
1389   }
1390 
1391   void VisitSwitchCase(const SwitchCase *S) {
1392     extendRegion(S);
1393 
1394     SourceMappingRegion &Parent = getRegion();
1395 
1396     Counter Count = addCounters(Parent.getCounter(), getRegionCounter(S));
1397     // Reuse the existing region if it starts at our label. This is typical of
1398     // the first case in a switch.
1399     if (Parent.hasStartLoc() && Parent.getBeginLoc() == getStart(S))
1400       Parent.setCounter(Count);
1401     else
1402       pushRegion(Count, getStart(S));
1403 
1404     if (const auto *CS = dyn_cast<CaseStmt>(S)) {
1405       Visit(CS->getLHS());
1406       if (const Expr *RHS = CS->getRHS())
1407         Visit(RHS);
1408     }
1409     Visit(S->getSubStmt());
1410   }
1411 
1412   void VisitIfStmt(const IfStmt *S) {
1413     extendRegion(S);
1414     if (S->getInit())
1415       Visit(S->getInit());
1416 
1417     // Extend into the condition before we propagate through it below - this is
1418     // needed to handle macros that generate the "if" but not the condition.
1419     extendRegion(S->getCond());
1420 
1421     Counter ParentCount = getRegion().getCounter();
1422     Counter ThenCount = getRegionCounter(S);
1423 
1424     // Emitting a counter for the condition makes it easier to interpret the
1425     // counter for the body when looking at the coverage.
1426     propagateCounts(ParentCount, S->getCond());
1427 
1428     // The 'then' count applies to the area immediately after the condition.
1429     auto Gap = findGapAreaBetween(S->getRParenLoc(), getStart(S->getThen()));
1430     if (Gap)
1431       fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), ThenCount);
1432 
1433     extendRegion(S->getThen());
1434     Counter OutCount = propagateCounts(ThenCount, S->getThen());
1435 
1436     Counter ElseCount = subtractCounters(ParentCount, ThenCount);
1437     if (const Stmt *Else = S->getElse()) {
1438       // The 'else' count applies to the area immediately after the 'then'.
1439       Gap = findGapAreaBetween(getEnd(S->getThen()), getStart(Else));
1440       if (Gap)
1441         fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), ElseCount);
1442       extendRegion(Else);
1443       OutCount = addCounters(OutCount, propagateCounts(ElseCount, Else));
1444     } else
1445       OutCount = addCounters(OutCount, ElseCount);
1446 
1447     if (OutCount != ParentCount)
1448       pushRegion(OutCount);
1449 
1450     // Create Branch Region around condition.
1451     createBranchRegion(S->getCond(), ThenCount,
1452                        subtractCounters(ParentCount, ThenCount));
1453   }
1454 
1455   void VisitCXXTryStmt(const CXXTryStmt *S) {
1456     extendRegion(S);
1457     // Handle macros that generate the "try" but not the rest.
1458     extendRegion(S->getTryBlock());
1459 
1460     Counter ParentCount = getRegion().getCounter();
1461     propagateCounts(ParentCount, S->getTryBlock());
1462 
1463     for (unsigned I = 0, E = S->getNumHandlers(); I < E; ++I)
1464       Visit(S->getHandler(I));
1465 
1466     Counter ExitCount = getRegionCounter(S);
1467     pushRegion(ExitCount);
1468   }
1469 
1470   void VisitCXXCatchStmt(const CXXCatchStmt *S) {
1471     propagateCounts(getRegionCounter(S), S->getHandlerBlock());
1472   }
1473 
1474   void VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
1475     extendRegion(E);
1476 
1477     Counter ParentCount = getRegion().getCounter();
1478     Counter TrueCount = getRegionCounter(E);
1479 
1480     propagateCounts(ParentCount, E->getCond());
1481 
1482     if (!isa<BinaryConditionalOperator>(E)) {
1483       // The 'then' count applies to the area immediately after the condition.
1484       auto Gap =
1485           findGapAreaBetween(E->getQuestionLoc(), getStart(E->getTrueExpr()));
1486       if (Gap)
1487         fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), TrueCount);
1488 
1489       extendRegion(E->getTrueExpr());
1490       propagateCounts(TrueCount, E->getTrueExpr());
1491     }
1492 
1493     extendRegion(E->getFalseExpr());
1494     propagateCounts(subtractCounters(ParentCount, TrueCount),
1495                     E->getFalseExpr());
1496 
1497     // Create Branch Region around condition.
1498     createBranchRegion(E->getCond(), TrueCount,
1499                        subtractCounters(ParentCount, TrueCount));
1500   }
1501 
1502   void VisitBinLAnd(const BinaryOperator *E) {
1503     extendRegion(E->getLHS());
1504     propagateCounts(getRegion().getCounter(), E->getLHS());
1505     handleFileExit(getEnd(E->getLHS()));
1506 
1507     // Counter tracks the right hand side of a logical and operator.
1508     extendRegion(E->getRHS());
1509     propagateCounts(getRegionCounter(E), E->getRHS());
1510 
1511     // Extract the RHS's Execution Counter.
1512     Counter RHSExecCnt = getRegionCounter(E);
1513 
1514     // Extract the RHS's "True" Instance Counter.
1515     Counter RHSTrueCnt = getRegionCounter(E->getRHS());
1516 
1517     // Extract the Parent Region Counter.
1518     Counter ParentCnt = getRegion().getCounter();
1519 
1520     // Create Branch Region around LHS condition.
1521     createBranchRegion(E->getLHS(), RHSExecCnt,
1522                        subtractCounters(ParentCnt, RHSExecCnt));
1523 
1524     // Create Branch Region around RHS condition.
1525     createBranchRegion(E->getRHS(), RHSTrueCnt,
1526                        subtractCounters(RHSExecCnt, RHSTrueCnt));
1527   }
1528 
1529   void VisitBinLOr(const BinaryOperator *E) {
1530     extendRegion(E->getLHS());
1531     propagateCounts(getRegion().getCounter(), E->getLHS());
1532     handleFileExit(getEnd(E->getLHS()));
1533 
1534     // Counter tracks the right hand side of a logical or operator.
1535     extendRegion(E->getRHS());
1536     propagateCounts(getRegionCounter(E), E->getRHS());
1537 
1538     // Extract the RHS's Execution Counter.
1539     Counter RHSExecCnt = getRegionCounter(E);
1540 
1541     // Extract the RHS's "False" Instance Counter.
1542     Counter RHSFalseCnt = getRegionCounter(E->getRHS());
1543 
1544     // Extract the Parent Region Counter.
1545     Counter ParentCnt = getRegion().getCounter();
1546 
1547     // Create Branch Region around LHS condition.
1548     createBranchRegion(E->getLHS(), subtractCounters(ParentCnt, RHSExecCnt),
1549                        RHSExecCnt);
1550 
1551     // Create Branch Region around RHS condition.
1552     createBranchRegion(E->getRHS(), subtractCounters(RHSExecCnt, RHSFalseCnt),
1553                        RHSFalseCnt);
1554   }
1555 
1556   void VisitLambdaExpr(const LambdaExpr *LE) {
1557     // Lambdas are treated as their own functions for now, so we shouldn't
1558     // propagate counts into them.
1559   }
1560 };
1561 
1562 } // end anonymous namespace
1563 
1564 static void dump(llvm::raw_ostream &OS, StringRef FunctionName,
1565                  ArrayRef<CounterExpression> Expressions,
1566                  ArrayRef<CounterMappingRegion> Regions) {
1567   OS << FunctionName << ":\n";
1568   CounterMappingContext Ctx(Expressions);
1569   for (const auto &R : Regions) {
1570     OS.indent(2);
1571     switch (R.Kind) {
1572     case CounterMappingRegion::CodeRegion:
1573       break;
1574     case CounterMappingRegion::ExpansionRegion:
1575       OS << "Expansion,";
1576       break;
1577     case CounterMappingRegion::SkippedRegion:
1578       OS << "Skipped,";
1579       break;
1580     case CounterMappingRegion::GapRegion:
1581       OS << "Gap,";
1582       break;
1583     case CounterMappingRegion::BranchRegion:
1584       OS << "Branch,";
1585       break;
1586     }
1587 
1588     OS << "File " << R.FileID << ", " << R.LineStart << ":" << R.ColumnStart
1589        << " -> " << R.LineEnd << ":" << R.ColumnEnd << " = ";
1590     Ctx.dump(R.Count, OS);
1591 
1592     if (R.Kind == CounterMappingRegion::BranchRegion) {
1593       OS << ", ";
1594       Ctx.dump(R.FalseCount, OS);
1595     }
1596 
1597     if (R.Kind == CounterMappingRegion::ExpansionRegion)
1598       OS << " (Expanded file = " << R.ExpandedFileID << ")";
1599     OS << "\n";
1600   }
1601 }
1602 
1603 CoverageMappingModuleGen::CoverageMappingModuleGen(
1604     CodeGenModule &CGM, CoverageSourceInfo &SourceInfo)
1605     : CGM(CGM), SourceInfo(SourceInfo) {
1606   ProfilePrefixMap = CGM.getCodeGenOpts().ProfilePrefixMap;
1607 }
1608 
1609 std::string CoverageMappingModuleGen::normalizeFilename(StringRef Filename) {
1610   llvm::SmallString<256> Path(Filename);
1611   llvm::sys::fs::make_absolute(Path);
1612   llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
1613   for (const auto &Entry : ProfilePrefixMap) {
1614     if (llvm::sys::path::replace_path_prefix(Path, Entry.first, Entry.second))
1615       break;
1616   }
1617   return Path.str().str();
1618 }
1619 
1620 static std::string getInstrProfSection(const CodeGenModule &CGM,
1621                                        llvm::InstrProfSectKind SK) {
1622   return llvm::getInstrProfSectionName(
1623       SK, CGM.getContext().getTargetInfo().getTriple().getObjectFormat());
1624 }
1625 
1626 void CoverageMappingModuleGen::emitFunctionMappingRecord(
1627     const FunctionInfo &Info, uint64_t FilenamesRef) {
1628   llvm::LLVMContext &Ctx = CGM.getLLVMContext();
1629 
1630   // Assign a name to the function record. This is used to merge duplicates.
1631   std::string FuncRecordName = "__covrec_" + llvm::utohexstr(Info.NameHash);
1632 
1633   // A dummy description for a function included-but-not-used in a TU can be
1634   // replaced by full description provided by a different TU. The two kinds of
1635   // descriptions play distinct roles: therefore, assign them different names
1636   // to prevent `linkonce_odr` merging.
1637   if (Info.IsUsed)
1638     FuncRecordName += "u";
1639 
1640   // Create the function record type.
1641   const uint64_t NameHash = Info.NameHash;
1642   const uint64_t FuncHash = Info.FuncHash;
1643   const std::string &CoverageMapping = Info.CoverageMapping;
1644 #define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) LLVMType,
1645   llvm::Type *FunctionRecordTypes[] = {
1646 #include "llvm/ProfileData/InstrProfData.inc"
1647   };
1648   auto *FunctionRecordTy =
1649       llvm::StructType::get(Ctx, makeArrayRef(FunctionRecordTypes),
1650                             /*isPacked=*/true);
1651 
1652   // Create the function record constant.
1653 #define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) Init,
1654   llvm::Constant *FunctionRecordVals[] = {
1655       #include "llvm/ProfileData/InstrProfData.inc"
1656   };
1657   auto *FuncRecordConstant = llvm::ConstantStruct::get(
1658       FunctionRecordTy, makeArrayRef(FunctionRecordVals));
1659 
1660   // Create the function record global.
1661   auto *FuncRecord = new llvm::GlobalVariable(
1662       CGM.getModule(), FunctionRecordTy, /*isConstant=*/true,
1663       llvm::GlobalValue::LinkOnceODRLinkage, FuncRecordConstant,
1664       FuncRecordName);
1665   FuncRecord->setVisibility(llvm::GlobalValue::HiddenVisibility);
1666   FuncRecord->setSection(getInstrProfSection(CGM, llvm::IPSK_covfun));
1667   FuncRecord->setAlignment(llvm::Align(8));
1668   if (CGM.supportsCOMDAT())
1669     FuncRecord->setComdat(CGM.getModule().getOrInsertComdat(FuncRecordName));
1670 
1671   // Make sure the data doesn't get deleted.
1672   CGM.addUsedGlobal(FuncRecord);
1673 }
1674 
1675 void CoverageMappingModuleGen::addFunctionMappingRecord(
1676     llvm::GlobalVariable *NamePtr, StringRef NameValue, uint64_t FuncHash,
1677     const std::string &CoverageMapping, bool IsUsed) {
1678   llvm::LLVMContext &Ctx = CGM.getLLVMContext();
1679   const uint64_t NameHash = llvm::IndexedInstrProf::ComputeHash(NameValue);
1680   FunctionRecords.push_back({NameHash, FuncHash, CoverageMapping, IsUsed});
1681 
1682   if (!IsUsed)
1683     FunctionNames.push_back(
1684         llvm::ConstantExpr::getBitCast(NamePtr, llvm::Type::getInt8PtrTy(Ctx)));
1685 
1686   if (CGM.getCodeGenOpts().DumpCoverageMapping) {
1687     // Dump the coverage mapping data for this function by decoding the
1688     // encoded data. This allows us to dump the mapping regions which were
1689     // also processed by the CoverageMappingWriter which performs
1690     // additional minimization operations such as reducing the number of
1691     // expressions.
1692     std::vector<StringRef> Filenames;
1693     std::vector<CounterExpression> Expressions;
1694     std::vector<CounterMappingRegion> Regions;
1695     llvm::SmallVector<std::string, 16> FilenameStrs;
1696     llvm::SmallVector<StringRef, 16> FilenameRefs;
1697     FilenameStrs.resize(FileEntries.size());
1698     FilenameRefs.resize(FileEntries.size());
1699     for (const auto &Entry : FileEntries) {
1700       auto I = Entry.second;
1701       FilenameStrs[I] = normalizeFilename(Entry.first->getName());
1702       FilenameRefs[I] = FilenameStrs[I];
1703     }
1704     RawCoverageMappingReader Reader(CoverageMapping, FilenameRefs, Filenames,
1705                                     Expressions, Regions);
1706     if (Reader.read())
1707       return;
1708     dump(llvm::outs(), NameValue, Expressions, Regions);
1709   }
1710 }
1711 
1712 void CoverageMappingModuleGen::emit() {
1713   if (FunctionRecords.empty())
1714     return;
1715   llvm::LLVMContext &Ctx = CGM.getLLVMContext();
1716   auto *Int32Ty = llvm::Type::getInt32Ty(Ctx);
1717 
1718   // Create the filenames and merge them with coverage mappings
1719   llvm::SmallVector<std::string, 16> FilenameStrs;
1720   llvm::SmallVector<StringRef, 16> FilenameRefs;
1721   FilenameStrs.resize(FileEntries.size());
1722   FilenameRefs.resize(FileEntries.size());
1723   for (const auto &Entry : FileEntries) {
1724     auto I = Entry.second;
1725     FilenameStrs[I] = normalizeFilename(Entry.first->getName());
1726     FilenameRefs[I] = FilenameStrs[I];
1727   }
1728 
1729   std::string Filenames;
1730   {
1731     llvm::raw_string_ostream OS(Filenames);
1732     CoverageFilenamesSectionWriter(FilenameRefs).write(OS);
1733   }
1734   auto *FilenamesVal =
1735       llvm::ConstantDataArray::getString(Ctx, Filenames, false);
1736   const int64_t FilenamesRef = llvm::IndexedInstrProf::ComputeHash(Filenames);
1737 
1738   // Emit the function records.
1739   for (const FunctionInfo &Info : FunctionRecords)
1740     emitFunctionMappingRecord(Info, FilenamesRef);
1741 
1742   const unsigned NRecords = 0;
1743   const size_t FilenamesSize = Filenames.size();
1744   const unsigned CoverageMappingSize = 0;
1745   llvm::Type *CovDataHeaderTypes[] = {
1746 #define COVMAP_HEADER(Type, LLVMType, Name, Init) LLVMType,
1747 #include "llvm/ProfileData/InstrProfData.inc"
1748   };
1749   auto CovDataHeaderTy =
1750       llvm::StructType::get(Ctx, makeArrayRef(CovDataHeaderTypes));
1751   llvm::Constant *CovDataHeaderVals[] = {
1752 #define COVMAP_HEADER(Type, LLVMType, Name, Init) Init,
1753 #include "llvm/ProfileData/InstrProfData.inc"
1754   };
1755   auto CovDataHeaderVal = llvm::ConstantStruct::get(
1756       CovDataHeaderTy, makeArrayRef(CovDataHeaderVals));
1757 
1758   // Create the coverage data record
1759   llvm::Type *CovDataTypes[] = {CovDataHeaderTy, FilenamesVal->getType()};
1760   auto CovDataTy = llvm::StructType::get(Ctx, makeArrayRef(CovDataTypes));
1761   llvm::Constant *TUDataVals[] = {CovDataHeaderVal, FilenamesVal};
1762   auto CovDataVal =
1763       llvm::ConstantStruct::get(CovDataTy, makeArrayRef(TUDataVals));
1764   auto CovData = new llvm::GlobalVariable(
1765       CGM.getModule(), CovDataTy, true, llvm::GlobalValue::PrivateLinkage,
1766       CovDataVal, llvm::getCoverageMappingVarName());
1767 
1768   CovData->setSection(getInstrProfSection(CGM, llvm::IPSK_covmap));
1769   CovData->setAlignment(llvm::Align(8));
1770 
1771   // Make sure the data doesn't get deleted.
1772   CGM.addUsedGlobal(CovData);
1773   // Create the deferred function records array
1774   if (!FunctionNames.empty()) {
1775     auto NamesArrTy = llvm::ArrayType::get(llvm::Type::getInt8PtrTy(Ctx),
1776                                            FunctionNames.size());
1777     auto NamesArrVal = llvm::ConstantArray::get(NamesArrTy, FunctionNames);
1778     // This variable will *NOT* be emitted to the object file. It is used
1779     // to pass the list of names referenced to codegen.
1780     new llvm::GlobalVariable(CGM.getModule(), NamesArrTy, true,
1781                              llvm::GlobalValue::InternalLinkage, NamesArrVal,
1782                              llvm::getCoverageUnusedNamesVarName());
1783   }
1784 }
1785 
1786 unsigned CoverageMappingModuleGen::getFileID(const FileEntry *File) {
1787   auto It = FileEntries.find(File);
1788   if (It != FileEntries.end())
1789     return It->second;
1790   unsigned FileID = FileEntries.size();
1791   FileEntries.insert(std::make_pair(File, FileID));
1792   return FileID;
1793 }
1794 
1795 void CoverageMappingGen::emitCounterMapping(const Decl *D,
1796                                             llvm::raw_ostream &OS) {
1797   assert(CounterMap);
1798   CounterCoverageMappingBuilder Walker(CVM, *CounterMap, SM, LangOpts);
1799   Walker.VisitDecl(D);
1800   Walker.write(OS);
1801 }
1802 
1803 void CoverageMappingGen::emitEmptyMapping(const Decl *D,
1804                                           llvm::raw_ostream &OS) {
1805   EmptyCoverageMappingBuilder Walker(CVM, SM, LangOpts);
1806   Walker.VisitDecl(D);
1807   Walker.write(OS);
1808 }
1809