1 //===--- CoverageMappingGen.cpp - Coverage mapping generation ---*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Instrumentation-based code coverage mapping generator
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "CoverageMappingGen.h"
15 #include "CodeGenFunction.h"
16 #include "clang/AST/StmtVisitor.h"
17 #include "clang/Lex/Lexer.h"
18 #include "llvm/ProfileData/InstrProfReader.h"
19 #include "llvm/ProfileData/CoverageMapping.h"
20 #include "llvm/ProfileData/CoverageMappingWriter.h"
21 #include "llvm/ProfileData/CoverageMappingReader.h"
22 #include "llvm/Support/FileSystem.h"
23 
24 using namespace clang;
25 using namespace CodeGen;
26 using namespace llvm::coverage;
27 
28 void CoverageSourceInfo::SourceRangeSkipped(SourceRange Range) {
29   SkippedRanges.push_back(Range);
30 }
31 
32 namespace {
33 
34 /// \brief A region of source code that can be mapped to a counter.
35 class SourceMappingRegion {
36 public:
37   enum RegionFlags {
38     /// \brief This region won't be emitted if it wasn't extended.
39     /// This is useful so that we won't emit source ranges for single tokens
40     /// that we don't really care that much about, like:
41     ///   the '(' token in #define MACRO (
42     IgnoreIfNotExtended = 0x0001,
43   };
44 
45 private:
46   FileID File, MacroArgumentFile;
47 
48   Counter Count;
49 
50   /// \brief A statement that initiated the count of Zero.
51   ///
52   /// This initiator statement is useful to prevent merging of unreachable
53   /// regions with different statements that caused the counter to become
54   /// unreachable.
55   const Stmt *UnreachableInitiator;
56 
57   /// \brief A statement that separates certain mapping regions into groups.
58   ///
59   /// The group statement is sometimes useful when we are emitting the source
60   /// regions not in their correct lexical order, e.g. the regions for the
61   /// incrementation expression in the 'for' construct. By marking the regions
62   /// in the incrementation expression with the group statement, we avoid the
63   /// merging of the regions from the incrementation expression and the loop's
64   /// body.
65   const Stmt *Group;
66 
67   /// \brief The region's starting location.
68   SourceLocation LocStart;
69 
70   /// \brief The region's ending location.
71   SourceLocation LocEnd, AlternativeLocEnd;
72   unsigned Flags;
73 
74 public:
75   SourceMappingRegion(FileID File, FileID MacroArgumentFile, Counter Count,
76                       const Stmt *UnreachableInitiator, const Stmt *Group,
77                       SourceLocation LocStart, SourceLocation LocEnd,
78                       unsigned Flags = 0)
79       : File(File), MacroArgumentFile(MacroArgumentFile), Count(Count),
80         UnreachableInitiator(UnreachableInitiator), Group(Group),
81         LocStart(LocStart), LocEnd(LocEnd), AlternativeLocEnd(LocStart),
82         Flags(Flags) {}
83 
84   const FileID &getFile() const { return File; }
85 
86   const Counter &getCounter() const { return Count; }
87 
88   const SourceLocation &getStartLoc() const { return LocStart; }
89 
90   const SourceLocation &getEndLoc(const SourceManager &SM) const {
91     if (SM.getFileID(LocEnd) != File)
92       return AlternativeLocEnd;
93     return LocEnd;
94   }
95 
96   bool hasFlag(RegionFlags Flag) const { return (Flags & Flag) != 0; }
97 
98   void setFlag(RegionFlags Flag) { Flags |= Flag; }
99 
100   void clearFlag(RegionFlags Flag) { Flags &= ~Flag; }
101 
102   /// \brief Return true if two regions can be merged together.
103   bool isMergeable(SourceMappingRegion &R) {
104     // FIXME: We allow merging regions with a gap in between them. Should we?
105     return File == R.File && MacroArgumentFile == R.MacroArgumentFile &&
106            Count == R.Count && UnreachableInitiator == R.UnreachableInitiator &&
107            Group == R.Group;
108   }
109 
110   /// \brief A comparison that sorts such that mergeable regions are adjacent.
111   friend bool operator<(const SourceMappingRegion &LHS,
112                         const SourceMappingRegion &RHS) {
113     return std::tie(LHS.File, LHS.MacroArgumentFile, LHS.Count,
114                     LHS.UnreachableInitiator, LHS.Group) <
115            std::tie(RHS.File, RHS.MacroArgumentFile, RHS.Count,
116                     RHS.UnreachableInitiator, RHS.Group);
117   }
118 };
119 
120 /// \brief The state of the coverage mapping builder.
121 struct SourceMappingState {
122   Counter CurrentRegionCount;
123   const Stmt *CurrentSourceGroup;
124   const Stmt *CurrentUnreachableRegionInitiator;
125 
126   SourceMappingState(Counter CurrentRegionCount, const Stmt *CurrentSourceGroup,
127                      const Stmt *CurrentUnreachableRegionInitiator)
128       : CurrentRegionCount(CurrentRegionCount),
129         CurrentSourceGroup(CurrentSourceGroup),
130         CurrentUnreachableRegionInitiator(CurrentUnreachableRegionInitiator) {}
131 };
132 
133 /// \brief Provides the common functionality for the different
134 /// coverage mapping region builders.
135 class CoverageMappingBuilder {
136 public:
137   CoverageMappingModuleGen &CVM;
138   SourceManager &SM;
139   const LangOptions &LangOpts;
140 
141 private:
142   struct FileInfo {
143     /// \brief The file id that will be used by the coverage mapping system.
144     unsigned CovMappingFileID;
145     const FileEntry *Entry;
146 
147     FileInfo(unsigned CovMappingFileID, const FileEntry *Entry)
148         : CovMappingFileID(CovMappingFileID), Entry(Entry) {}
149   };
150 
151   /// \brief This mapping maps clang's FileIDs to file ids used
152   /// by the coverage mapping system and clang's file entries.
153   llvm::SmallDenseMap<FileID, FileInfo, 8> FileIDMapping;
154 
155 public:
156   /// \brief The statement that corresponds to the current source group.
157   const Stmt *CurrentSourceGroup;
158 
159   /// \brief The statement the initiated the current unreachable region.
160   const Stmt *CurrentUnreachableRegionInitiator;
161 
162   /// \brief The coverage mapping regions for this function
163   llvm::SmallVector<CounterMappingRegion, 32> MappingRegions;
164   /// \brief The source mapping regions for this function.
165   std::vector<SourceMappingRegion> SourceRegions;
166 
167   CoverageMappingBuilder(CoverageMappingModuleGen &CVM, SourceManager &SM,
168                          const LangOptions &LangOpts)
169       : CVM(CVM), SM(SM), LangOpts(LangOpts),
170         CurrentSourceGroup(nullptr),
171         CurrentUnreachableRegionInitiator(nullptr) {}
172 
173   /// \brief Return the precise end location for the given token.
174   SourceLocation getPreciseTokenLocEnd(SourceLocation Loc) {
175     return Lexer::getLocForEndOfToken(SM.getSpellingLoc(Loc), 0, SM, LangOpts);
176   }
177 
178   /// \brief Create the mapping that maps from the function's file ids to
179   /// the indices for the translation unit's filenames.
180   void createFileIDMapping(SmallVectorImpl<unsigned> &Mapping) {
181     Mapping.resize(FileIDMapping.size(), 0);
182     for (const auto &I : FileIDMapping)
183       Mapping[I.second.CovMappingFileID] = CVM.getFileID(I.second.Entry);
184   }
185 
186   /// \brief Get the coverage mapping file id that corresponds to the given
187   /// clang file id. If such file id doesn't exist, it gets added to the
188   /// mapping that maps from clang's file ids to coverage mapping file ids.
189   /// Return true if there was an error getting the coverage mapping file id.
190   /// An example of an when this function fails is when the region tries
191   /// to get a coverage file id for a location in a built-in macro.
192   bool getCoverageFileID(SourceLocation LocStart, FileID File,
193                          FileID SpellingFile, unsigned &Result) {
194     auto Mapping = FileIDMapping.find(File);
195     if (Mapping != FileIDMapping.end()) {
196       Result = Mapping->second.CovMappingFileID;
197       return false;
198     }
199 
200     auto Entry = SM.getFileEntryForID(SpellingFile);
201     if (!Entry)
202       return true;
203 
204     Result = FileIDMapping.size();
205     FileIDMapping.insert(std::make_pair(File, FileInfo(Result, Entry)));
206     createFileExpansionRegion(LocStart, File);
207     return false;
208   }
209 
210   /// \brief Get the coverage mapping file id that corresponds to the given
211   /// clang file id.
212   /// Return true if there was an error getting the coverage mapping file id.
213   bool getExistingCoverageFileID(FileID File, unsigned &Result) {
214     // Make sure that the file is valid.
215     if (File.isInvalid())
216       return true;
217     auto Mapping = FileIDMapping.find(File);
218     if (Mapping != FileIDMapping.end()) {
219       Result = Mapping->second.CovMappingFileID;
220       return false;
221     }
222     return true;
223   }
224 
225   /// \brief Return true if the given clang's file id has a corresponding
226   /// coverage file id.
227   bool hasExistingCoverageFileID(FileID File) const {
228     return FileIDMapping.count(File);
229   }
230 
231   /// \brief Gather all the regions that were skipped by the preprocessor
232   /// using the constructs like #if.
233   void gatherSkippedRegions() {
234     /// An array of the minimum lineStarts and the maximum lineEnds
235     /// for mapping regions from the appropriate source files.
236     llvm::SmallVector<std::pair<unsigned, unsigned>, 8> FileLineRanges;
237     FileLineRanges.resize(
238         FileIDMapping.size(),
239         std::make_pair(std::numeric_limits<unsigned>::max(), 0));
240     for (const auto &R : MappingRegions) {
241       FileLineRanges[R.FileID].first =
242           std::min(FileLineRanges[R.FileID].first, R.LineStart);
243       FileLineRanges[R.FileID].second =
244           std::max(FileLineRanges[R.FileID].second, R.LineEnd);
245     }
246 
247     auto SkippedRanges = CVM.getSourceInfo().getSkippedRanges();
248     for (const auto &I : SkippedRanges) {
249       auto LocStart = I.getBegin();
250       auto LocEnd = I.getEnd();
251       auto FileStart = SM.getFileID(LocStart);
252       if (!hasExistingCoverageFileID(FileStart))
253         continue;
254       auto ActualFileStart = SM.getDecomposedSpellingLoc(LocStart).first;
255       if (ActualFileStart != SM.getDecomposedSpellingLoc(LocEnd).first)
256         // Ignore regions that span across multiple files.
257         continue;
258 
259       unsigned CovFileID;
260       if (getCoverageFileID(LocStart, FileStart, ActualFileStart, CovFileID))
261         continue;
262       unsigned LineStart = SM.getSpellingLineNumber(LocStart);
263       unsigned ColumnStart = SM.getSpellingColumnNumber(LocStart);
264       unsigned LineEnd = SM.getSpellingLineNumber(LocEnd);
265       unsigned ColumnEnd = SM.getSpellingColumnNumber(LocEnd);
266       CounterMappingRegion Region(Counter(), CovFileID, LineStart, ColumnStart,
267                                   LineEnd, ColumnEnd, false,
268                                   CounterMappingRegion::SkippedRegion);
269       // Make sure that we only collect the regions that are inside
270       // the souce code of this function.
271       if (Region.LineStart >= FileLineRanges[CovFileID].first &&
272           Region.LineEnd <= FileLineRanges[CovFileID].second)
273         MappingRegions.push_back(Region);
274     }
275   }
276 
277   /// \brief Create a mapping region that correponds to an expansion of
278   /// a macro or an embedded include.
279   void createFileExpansionRegion(SourceLocation Loc, FileID ExpandedFile) {
280     SourceLocation LocStart;
281     if (Loc.isMacroID())
282       LocStart = SM.getImmediateExpansionRange(Loc).first;
283     else {
284       LocStart = SM.getIncludeLoc(ExpandedFile);
285       if (LocStart.isInvalid())
286         return; // This file has no expansion region.
287     }
288 
289     auto File = SM.getFileID(LocStart);
290     auto SpellingFile = SM.getDecomposedSpellingLoc(LocStart).first;
291     unsigned CovFileID, ExpandedFileID;
292     if (getExistingCoverageFileID(ExpandedFile, ExpandedFileID))
293       return;
294     if (getCoverageFileID(LocStart, File, SpellingFile, CovFileID))
295       return;
296     unsigned LineStart = SM.getSpellingLineNumber(LocStart);
297     unsigned ColumnStart = SM.getSpellingColumnNumber(LocStart);
298     unsigned LineEnd = LineStart;
299     // Compute the end column manually as Lexer::getLocForEndOfToken doesn't
300     // give the correct result in all cases.
301     unsigned ColumnEnd =
302         ColumnStart +
303         Lexer::MeasureTokenLength(SM.getSpellingLoc(LocStart), SM, LangOpts);
304 
305     MappingRegions.push_back(CounterMappingRegion(
306         Counter(), CovFileID, LineStart, ColumnStart, LineEnd, ColumnEnd,
307         false, CounterMappingRegion::ExpansionRegion));
308     MappingRegions.back().ExpandedFileID = ExpandedFileID;
309   }
310 
311   /// \brief Enter a source region group that is identified by the given
312   /// statement.
313   /// It's not possible to enter a group when there is already
314   /// another group present.
315   void beginSourceRegionGroup(const Stmt *Group) {
316     assert(!CurrentSourceGroup);
317     CurrentSourceGroup = Group;
318   }
319 
320   /// \brief Exit the current source region group.
321   void endSourceRegionGroup() { CurrentSourceGroup = nullptr; }
322 
323   /// \brief Associate a counter with a given source code range.
324   void mapSourceCodeRange(SourceLocation LocStart, SourceLocation LocEnd,
325                           Counter Count, const Stmt *UnreachableInitiator,
326                           const Stmt *SourceGroup, unsigned Flags = 0,
327                           FileID MacroArgumentFile = FileID()) {
328     if (SM.isMacroArgExpansion(LocStart)) {
329       // Map the code range with the macro argument's value.
330       mapSourceCodeRange(SM.getImmediateSpellingLoc(LocStart),
331                          SM.getImmediateSpellingLoc(LocEnd), Count,
332                          UnreachableInitiator, SourceGroup, Flags,
333                          SM.getFileID(LocStart));
334       // Map the code range where the macro argument is referenced.
335       SourceLocation RefLocStart(SM.getImmediateExpansionRange(LocStart).first);
336       SourceLocation RefLocEnd(RefLocStart);
337       if (SM.isMacroArgExpansion(RefLocStart))
338         mapSourceCodeRange(RefLocStart, RefLocEnd, Count, UnreachableInitiator,
339                            SourceGroup, 0, SM.getFileID(RefLocStart));
340       else
341         mapSourceCodeRange(RefLocStart, RefLocEnd, Count, UnreachableInitiator,
342                            SourceGroup);
343       return;
344     }
345     auto File = SM.getFileID(LocStart);
346     // Make sure that the file id is valid.
347     if (File.isInvalid())
348       return;
349     SourceRegions.emplace_back(File, MacroArgumentFile, Count,
350                                UnreachableInitiator, SourceGroup, LocStart,
351                                LocEnd, Flags);
352   }
353 
354   void mapSourceCodeRange(SourceLocation LocStart, SourceLocation LocEnd,
355                           Counter Count, unsigned Flags = 0) {
356     mapSourceCodeRange(LocStart, LocEnd, Count,
357                        CurrentUnreachableRegionInitiator, CurrentSourceGroup,
358                        Flags);
359   }
360 
361   void mapSourceCodeRange(const SourceMappingState &State,
362                           SourceLocation LocStart, SourceLocation LocEnd,
363                           unsigned Flags = 0) {
364     mapSourceCodeRange(LocStart, LocEnd, State.CurrentRegionCount,
365                        State.CurrentUnreachableRegionInitiator,
366                        State.CurrentSourceGroup, Flags);
367   }
368 
369   /// \brief Generate the coverage counter mapping regions from collected
370   /// source regions.
371   void emitSourceRegions() {
372     std::sort(SourceRegions.begin(), SourceRegions.end());
373 
374     for (auto I = SourceRegions.begin(), E = SourceRegions.end(); I != E; ++I) {
375       // Keep the original start location of this region.
376       SourceLocation LocStart = I->getStartLoc();
377       SourceLocation LocEnd = I->getEndLoc(SM);
378 
379       bool Ignore = I->hasFlag(SourceMappingRegion::IgnoreIfNotExtended);
380       // We need to handle mergeable regions together.
381       for (auto Next = I + 1; Next != E && Next->isMergeable(*I); ++Next) {
382         ++I;
383         LocStart = std::min(LocStart, I->getStartLoc());
384         LocEnd = std::max(LocEnd, I->getEndLoc(SM));
385         // FIXME: Should we && together the Ignore flag of multiple regions?
386         Ignore = false;
387       }
388       if (Ignore)
389         continue;
390 
391       // Find the spilling locations for the mapping region.
392       LocEnd = getPreciseTokenLocEnd(LocEnd);
393       unsigned LineStart = SM.getSpellingLineNumber(LocStart);
394       unsigned ColumnStart = SM.getSpellingColumnNumber(LocStart);
395       unsigned LineEnd = SM.getSpellingLineNumber(LocEnd);
396       unsigned ColumnEnd = SM.getSpellingColumnNumber(LocEnd);
397 
398       auto SpellingFile = SM.getDecomposedSpellingLoc(LocStart).first;
399       unsigned CovFileID;
400       if (getCoverageFileID(LocStart, I->getFile(), SpellingFile, CovFileID))
401         continue;
402 
403       assert(LineStart <= LineEnd);
404       MappingRegions.push_back(CounterMappingRegion(
405           I->getCounter(), CovFileID, LineStart, ColumnStart, LineEnd,
406           ColumnEnd, false, CounterMappingRegion::CodeRegion));
407     }
408   }
409 };
410 
411 /// \brief Creates unreachable coverage regions for the functions that
412 /// are not emitted.
413 struct EmptyCoverageMappingBuilder : public CoverageMappingBuilder {
414   EmptyCoverageMappingBuilder(CoverageMappingModuleGen &CVM, SourceManager &SM,
415                               const LangOptions &LangOpts)
416       : CoverageMappingBuilder(CVM, SM, LangOpts) {}
417 
418   void VisitDecl(const Decl *D) {
419     if (!D->hasBody())
420       return;
421     auto Body = D->getBody();
422     mapSourceCodeRange(Body->getLocStart(), Body->getLocEnd(), Counter());
423   }
424 
425   /// \brief Write the mapping data to the output stream
426   void write(llvm::raw_ostream &OS) {
427     emitSourceRegions();
428     SmallVector<unsigned, 16> FileIDMapping;
429     createFileIDMapping(FileIDMapping);
430 
431     CoverageMappingWriter Writer(FileIDMapping, None, MappingRegions);
432     Writer.write(OS);
433   }
434 };
435 
436 /// \brief A StmtVisitor that creates coverage mapping regions which map
437 /// from the source code locations to the PGO counters.
438 struct CounterCoverageMappingBuilder
439     : public CoverageMappingBuilder,
440       public ConstStmtVisitor<CounterCoverageMappingBuilder> {
441   /// \brief The map of statements to count values.
442   llvm::DenseMap<const Stmt *, unsigned> &CounterMap;
443 
444   Counter CurrentRegionCount;
445 
446   CounterExpressionBuilder Builder;
447 
448   /// \brief Return a counter that represents the
449   /// expression that subracts rhs from lhs.
450   Counter subtractCounters(Counter LHS, Counter RHS) {
451     return Builder.subtract(LHS, RHS);
452   }
453 
454   /// \brief Return a counter that represents the
455   /// the exression that adds lhs and rhs.
456   Counter addCounters(Counter LHS, Counter RHS) {
457     return Builder.add(LHS, RHS);
458   }
459 
460   /// \brief Return the region counter for the given statement.
461   /// This should only be called on statements that have a dedicated counter.
462   unsigned getRegionCounter(const Stmt *S) { return CounterMap[S]; }
463 
464   /// \brief Return the region count for the counter at the given index.
465   Counter getRegionCount(unsigned CounterId) {
466     return Counter::getCounter(CounterId);
467   }
468 
469   /// \brief Return the counter value of the current region.
470   Counter getCurrentRegionCount() { return CurrentRegionCount; }
471 
472   /// \brief Set the counter value for the current region.
473   /// This is used to keep track of changes to the most recent counter
474   /// from control flow and non-local exits.
475   void setCurrentRegionCount(Counter Count) {
476     CurrentRegionCount = Count;
477     CurrentUnreachableRegionInitiator = nullptr;
478   }
479 
480   /// \brief Indicate that the current region is never reached,
481   /// and thus should have a counter value of zero.
482   /// This is important so that subsequent regions can correctly track
483   /// their parent counts.
484   void setCurrentRegionUnreachable(const Stmt *Initiator) {
485     CurrentRegionCount = Counter::getZero();
486     CurrentUnreachableRegionInitiator = Initiator;
487   }
488 
489   /// \brief A counter for a particular region.
490   /// This is the primary interface through
491   /// which the coverage mapping builder manages counters and their values.
492   class RegionMapper {
493     CounterCoverageMappingBuilder &Mapping;
494     Counter Count;
495     Counter ParentCount;
496     Counter RegionCount;
497     Counter Adjust;
498 
499   public:
500     RegionMapper(CounterCoverageMappingBuilder *Mapper, const Stmt *S)
501         : Mapping(*Mapper),
502           Count(Mapper->getRegionCount(Mapper->getRegionCounter(S))),
503           ParentCount(Mapper->getCurrentRegionCount()) {}
504 
505     /// Get the value of the counter. In most cases this is the number of times
506     /// the region of the counter was entered, but for switch labels it's the
507     /// number of direct jumps to that label.
508     Counter getCount() const { return Count; }
509 
510     /// Get the value of the counter with adjustments applied. Adjustments occur
511     /// when control enters or leaves the region abnormally; i.e., if there is a
512     /// jump to a label within the region, or if the function can return from
513     /// within the region. The adjusted count, then, is the value of the counter
514     /// at the end of the region.
515     Counter getAdjustedCount() const {
516       return Mapping.addCounters(Count, Adjust);
517     }
518 
519     /// Get the value of the counter in this region's parent, i.e., the region
520     /// that was active when this region began. This is useful for deriving
521     /// counts in implicitly counted regions, like the false case of a condition
522     /// or the normal exits of a loop.
523     Counter getParentCount() const { return ParentCount; }
524 
525     /// Activate the counter by emitting an increment and starting to track
526     /// adjustments. If AddIncomingFallThrough is true, the current region count
527     /// will be added to the counter for the purposes of tracking the region.
528     void beginRegion(bool AddIncomingFallThrough = false) {
529       RegionCount = Count;
530       if (AddIncomingFallThrough)
531         RegionCount =
532             Mapping.addCounters(RegionCount, Mapping.getCurrentRegionCount());
533       Mapping.setCurrentRegionCount(RegionCount);
534     }
535 
536     /// For counters on boolean branches, begins tracking adjustments for the
537     /// uncounted path.
538     void beginElseRegion() {
539       RegionCount = Mapping.subtractCounters(ParentCount, Count);
540       Mapping.setCurrentRegionCount(RegionCount);
541     }
542 
543     /// Reset the current region count.
544     void setCurrentRegionCount(Counter CurrentCount) {
545       RegionCount = CurrentCount;
546       Mapping.setCurrentRegionCount(RegionCount);
547     }
548 
549     /// Adjust for non-local control flow after emitting a subexpression or
550     /// substatement. This must be called to account for constructs such as
551     /// gotos,
552     /// labels, and returns, so that we can ensure that our region's count is
553     /// correct in the code that follows.
554     void adjustForControlFlow() {
555       Adjust = Mapping.addCounters(
556           Adjust, Mapping.subtractCounters(Mapping.getCurrentRegionCount(),
557                                            RegionCount));
558       // Reset the region count in case this is called again later.
559       RegionCount = Mapping.getCurrentRegionCount();
560     }
561 
562     /// Commit all adjustments to the current region. If the region is a loop,
563     /// the LoopAdjust value should be the count of all the breaks and continues
564     /// from the loop, to compensate for those counts being deducted from the
565     /// adjustments for the body of the loop.
566     void applyAdjustmentsToRegion() {
567       Mapping.setCurrentRegionCount(Mapping.addCounters(ParentCount, Adjust));
568     }
569     void applyAdjustmentsToRegion(Counter LoopAdjust) {
570       Mapping.setCurrentRegionCount(Mapping.addCounters(
571           Mapping.addCounters(ParentCount, Adjust), LoopAdjust));
572     }
573   };
574 
575   /// \brief Keep counts of breaks and continues inside loops.
576   struct BreakContinue {
577     Counter BreakCount;
578     Counter ContinueCount;
579   };
580   SmallVector<BreakContinue, 8> BreakContinueStack;
581 
582   CounterCoverageMappingBuilder(
583       CoverageMappingModuleGen &CVM,
584       llvm::DenseMap<const Stmt *, unsigned> &CounterMap,
585       unsigned NumRegionCounters, SourceManager &SM,
586       const LangOptions &LangOpts)
587       : CoverageMappingBuilder(CVM, SM, LangOpts), CounterMap(CounterMap),
588         Builder(NumRegionCounters) {}
589 
590   /// \brief Write the mapping data to the output stream
591   void write(llvm::raw_ostream &OS) {
592     emitSourceRegions();
593     llvm::SmallVector<unsigned, 8> VirtualFileMapping;
594     createFileIDMapping(VirtualFileMapping);
595     gatherSkippedRegions();
596 
597     CoverageMappingWriter Writer(
598         VirtualFileMapping, Builder.getExpressions(), MappingRegions);
599     Writer.write(OS);
600   }
601 
602   /// \brief Return the current source mapping state.
603   SourceMappingState getCurrentState() const {
604     return SourceMappingState(CurrentRegionCount, CurrentSourceGroup,
605                               CurrentUnreachableRegionInitiator);
606   }
607 
608   /// \brief Associate the source code range with the current region count.
609   void mapSourceCodeRange(SourceLocation LocStart, SourceLocation LocEnd,
610                           unsigned Flags = 0) {
611     CoverageMappingBuilder::mapSourceCodeRange(LocStart, LocEnd,
612                                                CurrentRegionCount, Flags);
613   }
614 
615   void mapSourceCodeRange(SourceLocation LocStart) {
616     CoverageMappingBuilder::mapSourceCodeRange(LocStart, LocStart,
617                                                CurrentRegionCount);
618   }
619 
620   /// \brief Associate the source range of a token with the current region
621   /// count.
622   /// Ignore the source range for this token if it produces a distinct
623   /// mapping region with no other source ranges.
624   void mapToken(SourceLocation LocStart) {
625     CoverageMappingBuilder::mapSourceCodeRange(
626         LocStart, LocStart, CurrentRegionCount,
627         SourceMappingRegion::IgnoreIfNotExtended);
628   }
629 
630   void mapToken(const SourceMappingState &State, SourceLocation LocStart) {
631     CoverageMappingBuilder::mapSourceCodeRange(
632         State, LocStart, LocStart, SourceMappingRegion::IgnoreIfNotExtended);
633   }
634 
635   void VisitStmt(const Stmt *S) {
636     mapSourceCodeRange(S->getLocStart());
637     for (Stmt::const_child_range I = S->children(); I; ++I) {
638       if (*I)
639         this->Visit(*I);
640     }
641   }
642 
643   /// \brief If the given statement is a compound statement,
644   /// map '}' with the same count as '{'.
645   void VisitSubStmtRBraceState(const Stmt *S) {
646     if (!isa<CompoundStmt>(S))
647       return Visit(S);
648     const auto *CS = cast<CompoundStmt>(S);
649     auto State = getCurrentState();
650     mapSourceCodeRange(CS->getLBracLoc());
651     for (Stmt::const_child_range I = S->children(); I; ++I) {
652       if (*I)
653         this->Visit(*I);
654     }
655     CoverageMappingBuilder::mapSourceCodeRange(State, CS->getRBracLoc(),
656                                                CS->getRBracLoc());
657   }
658 
659   void VisitDecl(const Decl *D) {
660     if (!D->hasBody())
661       return;
662     // Counter tracks entry to the function body.
663     auto Body = D->getBody();
664     RegionMapper Cnt(this, Body);
665     Cnt.beginRegion();
666     VisitSubStmtRBraceState(Body);
667   }
668 
669   void VisitDeclStmt(const DeclStmt *S) {
670     mapSourceCodeRange(S->getLocStart());
671     for (Stmt::const_child_range I = static_cast<const Stmt *>(S)->children();
672          I; ++I) {
673       if (*I)
674         this->Visit(*I);
675     }
676   }
677 
678   void VisitCompoundStmt(const CompoundStmt *S) {
679     mapSourceCodeRange(S->getLBracLoc());
680     for (Stmt::const_child_range I = S->children(); I; ++I) {
681       if (*I)
682         this->Visit(*I);
683     }
684     mapSourceCodeRange(S->getRBracLoc(), S->getRBracLoc());
685   }
686 
687   void VisitReturnStmt(const ReturnStmt *S) {
688     mapSourceCodeRange(S->getLocStart());
689     if (S->getRetValue())
690       Visit(S->getRetValue());
691     setCurrentRegionUnreachable(S);
692   }
693 
694   void VisitGotoStmt(const GotoStmt *S) {
695     mapSourceCodeRange(S->getLocStart());
696     mapToken(S->getLabelLoc());
697     setCurrentRegionUnreachable(S);
698   }
699 
700   void VisitLabelStmt(const LabelStmt *S) {
701     // Counter tracks the block following the label.
702     RegionMapper Cnt(this, S);
703     Cnt.beginRegion();
704     mapSourceCodeRange(S->getLocStart());
705     // Can't map the ':' token as its location isn't known.
706     Visit(S->getSubStmt());
707   }
708 
709   void VisitBreakStmt(const BreakStmt *S) {
710     mapSourceCodeRange(S->getLocStart());
711     assert(!BreakContinueStack.empty() && "break not in a loop or switch!");
712     BreakContinueStack.back().BreakCount = addCounters(
713         BreakContinueStack.back().BreakCount, getCurrentRegionCount());
714     setCurrentRegionUnreachable(S);
715   }
716 
717   void VisitContinueStmt(const ContinueStmt *S) {
718     mapSourceCodeRange(S->getLocStart());
719     assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
720     BreakContinueStack.back().ContinueCount = addCounters(
721         BreakContinueStack.back().ContinueCount, getCurrentRegionCount());
722     setCurrentRegionUnreachable(S);
723   }
724 
725   void VisitWhileStmt(const WhileStmt *S) {
726     mapSourceCodeRange(S->getLocStart());
727     // Counter tracks the body of the loop.
728     RegionMapper Cnt(this, S);
729     BreakContinueStack.push_back(BreakContinue());
730     // Visit the body region first so the break/continue adjustments can be
731     // included when visiting the condition.
732     Cnt.beginRegion();
733     VisitSubStmtRBraceState(S->getBody());
734     Cnt.adjustForControlFlow();
735 
736     // ...then go back and propagate counts through the condition. The count
737     // at the start of the condition is the sum of the incoming edges,
738     // the backedge from the end of the loop body, and the edges from
739     // continue statements.
740     BreakContinue BC = BreakContinueStack.pop_back_val();
741     Cnt.setCurrentRegionCount(
742         addCounters(Cnt.getParentCount(),
743                     addCounters(Cnt.getAdjustedCount(), BC.ContinueCount)));
744     beginSourceRegionGroup(S->getCond());
745     Visit(S->getCond());
746     endSourceRegionGroup();
747     Cnt.adjustForControlFlow();
748     Cnt.applyAdjustmentsToRegion(addCounters(BC.BreakCount, BC.ContinueCount));
749   }
750 
751   void VisitDoStmt(const DoStmt *S) {
752     mapSourceCodeRange(S->getLocStart());
753     // Counter tracks the body of the loop.
754     RegionMapper Cnt(this, S);
755     BreakContinueStack.push_back(BreakContinue());
756     Cnt.beginRegion(/*AddIncomingFallThrough=*/true);
757     VisitSubStmtRBraceState(S->getBody());
758     Cnt.adjustForControlFlow();
759 
760     BreakContinue BC = BreakContinueStack.pop_back_val();
761     // The count at the start of the condition is equal to the count at the
762     // end of the body. The adjusted count does not include either the
763     // fall-through count coming into the loop or the continue count, so add
764     // both of those separately. This is coincidentally the same equation as
765     // with while loops but for different reasons.
766     Cnt.setCurrentRegionCount(
767         addCounters(Cnt.getParentCount(),
768                     addCounters(Cnt.getAdjustedCount(), BC.ContinueCount)));
769     Visit(S->getCond());
770     Cnt.adjustForControlFlow();
771     Cnt.applyAdjustmentsToRegion(addCounters(BC.BreakCount, BC.ContinueCount));
772   }
773 
774   void VisitForStmt(const ForStmt *S) {
775     mapSourceCodeRange(S->getLocStart());
776     if (S->getInit())
777       Visit(S->getInit());
778 
779     // Counter tracks the body of the loop.
780     RegionMapper Cnt(this, S);
781     BreakContinueStack.push_back(BreakContinue());
782     // Visit the body region first. (This is basically the same as a while
783     // loop; see further comments in VisitWhileStmt.)
784     Cnt.beginRegion();
785     VisitSubStmtRBraceState(S->getBody());
786     Cnt.adjustForControlFlow();
787 
788     // The increment is essentially part of the body but it needs to include
789     // the count for all the continue statements.
790     if (S->getInc()) {
791       Cnt.setCurrentRegionCount(addCounters(
792           getCurrentRegionCount(), BreakContinueStack.back().ContinueCount));
793       beginSourceRegionGroup(S->getInc());
794       Visit(S->getInc());
795       endSourceRegionGroup();
796       Cnt.adjustForControlFlow();
797     }
798 
799     BreakContinue BC = BreakContinueStack.pop_back_val();
800 
801     // ...then go back and propagate counts through the condition.
802     if (S->getCond()) {
803       Cnt.setCurrentRegionCount(
804           addCounters(addCounters(Cnt.getParentCount(), Cnt.getAdjustedCount()),
805                       BC.ContinueCount));
806       beginSourceRegionGroup(S->getCond());
807       Visit(S->getCond());
808       endSourceRegionGroup();
809       Cnt.adjustForControlFlow();
810     }
811     Cnt.applyAdjustmentsToRegion(addCounters(BC.BreakCount, BC.ContinueCount));
812   }
813 
814   void VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
815     mapSourceCodeRange(S->getLocStart());
816     Visit(S->getRangeStmt());
817     Visit(S->getBeginEndStmt());
818     // Counter tracks the body of the loop.
819     RegionMapper Cnt(this, S);
820     BreakContinueStack.push_back(BreakContinue());
821     // Visit the body region first. (This is basically the same as a while
822     // loop; see further comments in VisitWhileStmt.)
823     Cnt.beginRegion();
824     VisitSubStmtRBraceState(S->getBody());
825     Cnt.adjustForControlFlow();
826     BreakContinue BC = BreakContinueStack.pop_back_val();
827     Cnt.applyAdjustmentsToRegion(addCounters(BC.BreakCount, BC.ContinueCount));
828   }
829 
830   void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) {
831     mapSourceCodeRange(S->getLocStart());
832     Visit(S->getElement());
833     // Counter tracks the body of the loop.
834     RegionMapper Cnt(this, S);
835     BreakContinueStack.push_back(BreakContinue());
836     Cnt.beginRegion();
837     VisitSubStmtRBraceState(S->getBody());
838     BreakContinue BC = BreakContinueStack.pop_back_val();
839     Cnt.adjustForControlFlow();
840     Cnt.applyAdjustmentsToRegion(addCounters(BC.BreakCount, BC.ContinueCount));
841   }
842 
843   void VisitSwitchStmt(const SwitchStmt *S) {
844     mapSourceCodeRange(S->getLocStart());
845     Visit(S->getCond());
846     BreakContinueStack.push_back(BreakContinue());
847     // Map the '}' for the body to have the same count as the regions after
848     // the switch.
849     SourceLocation RBracLoc;
850     if (const auto *CS = dyn_cast<CompoundStmt>(S->getBody())) {
851       mapSourceCodeRange(CS->getLBracLoc());
852       setCurrentRegionUnreachable(S);
853       for (Stmt::const_child_range I = CS->children(); I; ++I) {
854         if (*I)
855           this->Visit(*I);
856       }
857       RBracLoc = CS->getRBracLoc();
858     } else {
859       setCurrentRegionUnreachable(S);
860       Visit(S->getBody());
861     }
862     // If the switch is inside a loop, add the continue counts.
863     BreakContinue BC = BreakContinueStack.pop_back_val();
864     if (!BreakContinueStack.empty())
865       BreakContinueStack.back().ContinueCount = addCounters(
866           BreakContinueStack.back().ContinueCount, BC.ContinueCount);
867     // Counter tracks the exit block of the switch.
868     RegionMapper ExitCnt(this, S);
869     ExitCnt.beginRegion();
870     if (RBracLoc.isValid())
871       mapSourceCodeRange(RBracLoc);
872   }
873 
874   void VisitCaseStmt(const CaseStmt *S) {
875     // Counter for this particular case. This counts only jumps from the
876     // switch header and does not include fallthrough from the case before
877     // this one.
878     RegionMapper Cnt(this, S);
879     Cnt.beginRegion(/*AddIncomingFallThrough=*/true);
880     mapSourceCodeRange(S->getLocStart());
881     mapToken(S->getColonLoc());
882     Visit(S->getSubStmt());
883   }
884 
885   void VisitDefaultStmt(const DefaultStmt *S) {
886     // Counter for this default case. This does not include fallthrough from
887     // the previous case.
888     RegionMapper Cnt(this, S);
889     Cnt.beginRegion(/*AddIncomingFallThrough=*/true);
890     mapSourceCodeRange(S->getLocStart());
891     mapToken(S->getColonLoc());
892     Visit(S->getSubStmt());
893   }
894 
895   void VisitIfStmt(const IfStmt *S) {
896     mapSourceCodeRange(S->getLocStart());
897     Visit(S->getCond());
898     mapToken(S->getElseLoc());
899 
900     // Counter tracks the "then" part of an if statement. The count for
901     // the "else" part, if it exists, will be calculated from this counter.
902     RegionMapper Cnt(this, S);
903     Cnt.beginRegion();
904     VisitSubStmtRBraceState(S->getThen());
905     Cnt.adjustForControlFlow();
906 
907     if (S->getElse()) {
908       Cnt.beginElseRegion();
909       VisitSubStmtRBraceState(S->getElse());
910       Cnt.adjustForControlFlow();
911     }
912     Cnt.applyAdjustmentsToRegion();
913   }
914 
915   void VisitCXXTryStmt(const CXXTryStmt *S) {
916     mapSourceCodeRange(S->getLocStart());
917     Visit(S->getTryBlock());
918     for (unsigned I = 0, E = S->getNumHandlers(); I < E; ++I)
919       Visit(S->getHandler(I));
920     // Counter tracks the continuation block of the try statement.
921     RegionMapper Cnt(this, S);
922     Cnt.beginRegion();
923   }
924 
925   void VisitCXXCatchStmt(const CXXCatchStmt *S) {
926     mapSourceCodeRange(S->getLocStart());
927     // Counter tracks the catch statement's handler block.
928     RegionMapper Cnt(this, S);
929     Cnt.beginRegion();
930     VisitSubStmtRBraceState(S->getHandlerBlock());
931   }
932 
933   void VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
934     Visit(E->getCond());
935     mapToken(E->getQuestionLoc());
936     auto State = getCurrentState();
937 
938     // Counter tracks the "true" part of a conditional operator. The
939     // count in the "false" part will be calculated from this counter.
940     RegionMapper Cnt(this, E);
941     Cnt.beginRegion();
942     Visit(E->getTrueExpr());
943     Cnt.adjustForControlFlow();
944 
945     mapToken(State, E->getColonLoc());
946 
947     Cnt.beginElseRegion();
948     Visit(E->getFalseExpr());
949     Cnt.adjustForControlFlow();
950 
951     Cnt.applyAdjustmentsToRegion();
952   }
953 
954   void VisitBinLAnd(const BinaryOperator *E) {
955     Visit(E->getLHS());
956     mapToken(E->getOperatorLoc());
957     // Counter tracks the right hand side of a logical and operator.
958     RegionMapper Cnt(this, E);
959     Cnt.beginRegion();
960     Visit(E->getRHS());
961     Cnt.adjustForControlFlow();
962     Cnt.applyAdjustmentsToRegion();
963   }
964 
965   void VisitBinLOr(const BinaryOperator *E) {
966     Visit(E->getLHS());
967     mapToken(E->getOperatorLoc());
968     // Counter tracks the right hand side of a logical or operator.
969     RegionMapper Cnt(this, E);
970     Cnt.beginRegion();
971     Visit(E->getRHS());
972     Cnt.adjustForControlFlow();
973     Cnt.applyAdjustmentsToRegion();
974   }
975 
976   void VisitParenExpr(const ParenExpr *E) {
977     mapToken(E->getLParen());
978     Visit(E->getSubExpr());
979     mapToken(E->getRParen());
980   }
981 
982   void VisitBinaryOperator(const BinaryOperator *E) {
983     Visit(E->getLHS());
984     mapToken(E->getOperatorLoc());
985     Visit(E->getRHS());
986   }
987 
988   void VisitUnaryOperator(const UnaryOperator *E) {
989     bool Postfix = E->isPostfix();
990     if (!Postfix)
991       mapToken(E->getOperatorLoc());
992     Visit(E->getSubExpr());
993     if (Postfix)
994       mapToken(E->getOperatorLoc());
995   }
996 
997   void VisitMemberExpr(const MemberExpr *E) {
998     Visit(E->getBase());
999     mapToken(E->getMemberLoc());
1000   }
1001 
1002   void VisitCallExpr(const CallExpr *E) {
1003     Visit(E->getCallee());
1004     for (const auto &Arg : E->arguments())
1005       Visit(Arg);
1006     mapToken(E->getRParenLoc());
1007   }
1008 
1009   void VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
1010     Visit(E->getLHS());
1011     Visit(E->getRHS());
1012     mapToken(E->getRBracketLoc());
1013   }
1014 
1015   void VisitCStyleCastExpr(const CStyleCastExpr *E) {
1016     mapToken(E->getLParenLoc());
1017     mapToken(E->getRParenLoc());
1018     Visit(E->getSubExpr());
1019   }
1020 
1021   // Map literals as tokens so that the macros like #define PI 3.14
1022   // won't generate coverage mapping regions.
1023 
1024   void VisitIntegerLiteral(const IntegerLiteral *E) {
1025     mapToken(E->getLocStart());
1026   }
1027 
1028   void VisitFloatingLiteral(const FloatingLiteral *E) {
1029     mapToken(E->getLocStart());
1030   }
1031 
1032   void VisitCharacterLiteral(const CharacterLiteral *E) {
1033     mapToken(E->getLocStart());
1034   }
1035 
1036   void VisitStringLiteral(const StringLiteral *E) {
1037     mapToken(E->getLocStart());
1038   }
1039 
1040   void VisitImaginaryLiteral(const ImaginaryLiteral *E) {
1041     mapToken(E->getLocStart());
1042   }
1043 
1044   void VisitObjCMessageExpr(const ObjCMessageExpr *E) {
1045     mapToken(E->getLeftLoc());
1046     for (Stmt::const_child_range I = static_cast<const Stmt*>(E)->children(); I;
1047          ++I) {
1048       if (*I)
1049         this->Visit(*I);
1050     }
1051     mapToken(E->getRightLoc());
1052   }
1053 };
1054 }
1055 
1056 static bool isMachO(const CodeGenModule &CGM) {
1057   return CGM.getTarget().getTriple().isOSBinFormatMachO();
1058 }
1059 
1060 static StringRef getCoverageSection(const CodeGenModule &CGM) {
1061   return isMachO(CGM) ? "__DATA,__llvm_covmap" : "__llvm_covmap";
1062 }
1063 
1064 static void dump(llvm::raw_ostream &OS, const CoverageMappingRecord &Function) {
1065   OS << Function.FunctionName << ":\n";
1066   CounterMappingContext Ctx(Function.Expressions);
1067   for (const auto &R : Function.MappingRegions) {
1068     OS.indent(2);
1069     switch (R.Kind) {
1070     case CounterMappingRegion::CodeRegion:
1071       break;
1072     case CounterMappingRegion::ExpansionRegion:
1073       OS << "Expansion,";
1074       break;
1075     case CounterMappingRegion::SkippedRegion:
1076       OS << "Skipped,";
1077       break;
1078     }
1079 
1080     OS << "File " << R.FileID << ", " << R.LineStart << ":"
1081            << R.ColumnStart << " -> " << R.LineEnd << ":" << R.ColumnEnd
1082            << " = ";
1083     Ctx.dump(R.Count);
1084     OS << " (HasCodeBefore = " << R.HasCodeBefore;
1085     if (R.Kind == CounterMappingRegion::ExpansionRegion)
1086       OS << ", Expanded file = " << R.ExpandedFileID;
1087 
1088     OS << ")\n";
1089   }
1090 }
1091 
1092 void CoverageMappingModuleGen::addFunctionMappingRecord(
1093     llvm::GlobalVariable *FunctionName, StringRef FunctionNameValue,
1094     uint64_t FunctionHash, const std::string &CoverageMapping) {
1095   llvm::LLVMContext &Ctx = CGM.getLLVMContext();
1096   auto *Int32Ty = llvm::Type::getInt32Ty(Ctx);
1097   auto *Int64Ty = llvm::Type::getInt64Ty(Ctx);
1098   auto *Int8PtrTy = llvm::Type::getInt8PtrTy(Ctx);
1099   if (!FunctionRecordTy) {
1100     llvm::Type *FunctionRecordTypes[] = {Int8PtrTy, Int32Ty, Int32Ty, Int64Ty};
1101     FunctionRecordTy =
1102         llvm::StructType::get(Ctx, makeArrayRef(FunctionRecordTypes));
1103   }
1104 
1105   llvm::Constant *FunctionRecordVals[] = {
1106       llvm::ConstantExpr::getBitCast(FunctionName, Int8PtrTy),
1107       llvm::ConstantInt::get(Int32Ty, FunctionNameValue.size()),
1108       llvm::ConstantInt::get(Int32Ty, CoverageMapping.size()),
1109       llvm::ConstantInt::get(Int64Ty, FunctionHash)};
1110   FunctionRecords.push_back(llvm::ConstantStruct::get(
1111       FunctionRecordTy, makeArrayRef(FunctionRecordVals)));
1112   CoverageMappings += CoverageMapping;
1113 
1114   if (CGM.getCodeGenOpts().DumpCoverageMapping) {
1115     // Dump the coverage mapping data for this function by decoding the
1116     // encoded data. This allows us to dump the mapping regions which were
1117     // also processed by the CoverageMappingWriter which performs
1118     // additional minimization operations such as reducing the number of
1119     // expressions.
1120     std::vector<StringRef> Filenames;
1121     std::vector<CounterExpression> Expressions;
1122     std::vector<CounterMappingRegion> Regions;
1123     llvm::SmallVector<StringRef, 16> FilenameRefs;
1124     FilenameRefs.resize(FileEntries.size());
1125     for (const auto &Entry : FileEntries)
1126       FilenameRefs[Entry.second] = Entry.first->getName();
1127     RawCoverageMappingReader Reader(FunctionNameValue, CoverageMapping,
1128                                     FilenameRefs,
1129                                     Filenames, Expressions, Regions);
1130     CoverageMappingRecord FunctionRecord;
1131     if (Reader.read(FunctionRecord))
1132       return;
1133     dump(llvm::outs(), FunctionRecord);
1134   }
1135 }
1136 
1137 void CoverageMappingModuleGen::emit() {
1138   if (FunctionRecords.empty())
1139     return;
1140   llvm::LLVMContext &Ctx = CGM.getLLVMContext();
1141   auto *Int32Ty = llvm::Type::getInt32Ty(Ctx);
1142 
1143   // Create the filenames and merge them with coverage mappings
1144   llvm::SmallVector<std::string, 16> FilenameStrs;
1145   llvm::SmallVector<StringRef, 16> FilenameRefs;
1146   FilenameStrs.resize(FileEntries.size());
1147   FilenameRefs.resize(FileEntries.size());
1148   for (const auto &Entry : FileEntries) {
1149     llvm::SmallString<256> Path(Entry.first->getName());
1150     llvm::sys::fs::make_absolute(Path);
1151 
1152     auto I = Entry.second;
1153     FilenameStrs[I] = std::move(std::string(Path.begin(), Path.end()));
1154     FilenameRefs[I] = FilenameStrs[I];
1155   }
1156 
1157   std::string FilenamesAndCoverageMappings;
1158   llvm::raw_string_ostream OS(FilenamesAndCoverageMappings);
1159   CoverageFilenamesSectionWriter(FilenameRefs).write(OS);
1160   OS << CoverageMappings;
1161   size_t CoverageMappingSize = CoverageMappings.size();
1162   size_t FilenamesSize = OS.str().size() - CoverageMappingSize;
1163   // Append extra zeroes if necessary to ensure that the size of the filenames
1164   // and coverage mappings is a multiple of 8.
1165   if (size_t Rem = OS.str().size() % 8) {
1166     CoverageMappingSize += 8 - Rem;
1167     for (size_t I = 0, S = 8 - Rem; I < S; ++I)
1168       OS << '\0';
1169   }
1170   auto *FilenamesAndMappingsVal =
1171       llvm::ConstantDataArray::getString(Ctx, OS.str(), false);
1172 
1173   // Create the deferred function records array
1174   auto RecordsTy =
1175       llvm::ArrayType::get(FunctionRecordTy, FunctionRecords.size());
1176   auto RecordsVal = llvm::ConstantArray::get(RecordsTy, FunctionRecords);
1177 
1178   // Create the coverage data record
1179   llvm::Type *CovDataTypes[] = {Int32Ty,   Int32Ty,
1180                                 Int32Ty,   Int32Ty,
1181                                 RecordsTy, FilenamesAndMappingsVal->getType()};
1182   auto CovDataTy = llvm::StructType::get(Ctx, makeArrayRef(CovDataTypes));
1183   llvm::Constant *TUDataVals[] = {
1184       llvm::ConstantInt::get(Int32Ty, FunctionRecords.size()),
1185       llvm::ConstantInt::get(Int32Ty, FilenamesSize),
1186       llvm::ConstantInt::get(Int32Ty, CoverageMappingSize),
1187       llvm::ConstantInt::get(Int32Ty,
1188                              /*Version=*/CoverageMappingVersion1),
1189       RecordsVal, FilenamesAndMappingsVal};
1190   auto CovDataVal =
1191       llvm::ConstantStruct::get(CovDataTy, makeArrayRef(TUDataVals));
1192   auto CovData = new llvm::GlobalVariable(CGM.getModule(), CovDataTy, true,
1193                                           llvm::GlobalValue::InternalLinkage,
1194                                           CovDataVal,
1195                                           "__llvm_coverage_mapping");
1196 
1197   CovData->setSection(getCoverageSection(CGM));
1198   CovData->setAlignment(8);
1199 
1200   // Make sure the data doesn't get deleted.
1201   CGM.addUsedGlobal(CovData);
1202 }
1203 
1204 unsigned CoverageMappingModuleGen::getFileID(const FileEntry *File) {
1205   auto It = FileEntries.find(File);
1206   if (It != FileEntries.end())
1207     return It->second;
1208   unsigned FileID = FileEntries.size();
1209   FileEntries.insert(std::make_pair(File, FileID));
1210   return FileID;
1211 }
1212 
1213 void CoverageMappingGen::emitCounterMapping(const Decl *D,
1214                                             llvm::raw_ostream &OS) {
1215   assert(CounterMap);
1216   CounterCoverageMappingBuilder Walker(CVM, *CounterMap, NumRegionCounters, SM,
1217                                        LangOpts);
1218   Walker.VisitDecl(D);
1219   Walker.write(OS);
1220 }
1221 
1222 void CoverageMappingGen::emitEmptyMapping(const Decl *D,
1223                                           llvm::raw_ostream &OS) {
1224   EmptyCoverageMappingBuilder Walker(CVM, SM, LangOpts);
1225   Walker.VisitDecl(D);
1226   Walker.write(OS);
1227 }
1228