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