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/ADT/Optional.h"
19 #include "llvm/ProfileData/CoverageMapping.h"
20 #include "llvm/ProfileData/CoverageMappingReader.h"
21 #include "llvm/ProfileData/CoverageMappingWriter.h"
22 #include "llvm/ProfileData/InstrProfReader.h"
23 #include "llvm/Support/FileSystem.h"
24 
25 using namespace clang;
26 using namespace CodeGen;
27 using namespace llvm::coverage;
28 
29 void CoverageSourceInfo::SourceRangeSkipped(SourceRange Range) {
30   SkippedRanges.push_back(Range);
31 }
32 
33 namespace {
34 
35 /// \brief A region of source code that can be mapped to a counter.
36 class SourceMappingRegion {
37   Counter Count;
38 
39   /// \brief The region's starting location.
40   Optional<SourceLocation> LocStart;
41 
42   /// \brief The region's ending location.
43   Optional<SourceLocation> LocEnd;
44 
45 public:
46   SourceMappingRegion(Counter Count, Optional<SourceLocation> LocStart,
47                       Optional<SourceLocation> LocEnd)
48       : Count(Count), LocStart(LocStart), LocEnd(LocEnd) {}
49 
50   SourceMappingRegion(SourceMappingRegion &&Region)
51       : Count(std::move(Region.Count)), LocStart(std::move(Region.LocStart)),
52         LocEnd(std::move(Region.LocEnd)) {}
53 
54   SourceMappingRegion &operator=(SourceMappingRegion &&RHS) {
55     Count = std::move(RHS.Count);
56     LocStart = std::move(RHS.LocStart);
57     LocEnd = std::move(RHS.LocEnd);
58     return *this;
59   }
60 
61   const Counter &getCounter() const { return Count; }
62 
63   void setCounter(Counter C) { Count = C; }
64 
65   bool hasStartLoc() const { return LocStart.hasValue(); }
66 
67   void setStartLoc(SourceLocation Loc) { LocStart = Loc; }
68 
69   const SourceLocation &getStartLoc() const {
70     assert(LocStart && "Region has no start location");
71     return *LocStart;
72   }
73 
74   bool hasEndLoc() const { return LocEnd.hasValue(); }
75 
76   void setEndLoc(SourceLocation Loc) { LocEnd = Loc; }
77 
78   const SourceLocation &getEndLoc() const {
79     assert(LocEnd && "Region has no end location");
80     return *LocEnd;
81   }
82 };
83 
84 /// \brief Provides the common functionality for the different
85 /// coverage mapping region builders.
86 class CoverageMappingBuilder {
87 public:
88   CoverageMappingModuleGen &CVM;
89   SourceManager &SM;
90   const LangOptions &LangOpts;
91 
92 private:
93   /// \brief Map of clang's FileIDs to IDs used for coverage mapping.
94   llvm::SmallDenseMap<FileID, std::pair<unsigned, SourceLocation>, 8>
95       FileIDMapping;
96 
97 public:
98   /// \brief The coverage mapping regions for this function
99   llvm::SmallVector<CounterMappingRegion, 32> MappingRegions;
100   /// \brief The source mapping regions for this function.
101   std::vector<SourceMappingRegion> SourceRegions;
102 
103   CoverageMappingBuilder(CoverageMappingModuleGen &CVM, SourceManager &SM,
104                          const LangOptions &LangOpts)
105       : CVM(CVM), SM(SM), LangOpts(LangOpts) {}
106 
107   /// \brief Return the precise end location for the given token.
108   SourceLocation getPreciseTokenLocEnd(SourceLocation Loc) {
109     // We avoid getLocForEndOfToken here, because it doesn't do what we want for
110     // macro locations, which we just treat as expanded files.
111     unsigned TokLen =
112         Lexer::MeasureTokenLength(SM.getSpellingLoc(Loc), SM, LangOpts);
113     return Loc.getLocWithOffset(TokLen);
114   }
115 
116   /// \brief Return the start location of an included file or expanded macro.
117   SourceLocation getStartOfFileOrMacro(SourceLocation Loc) {
118     if (Loc.isMacroID())
119       return Loc.getLocWithOffset(-SM.getFileOffset(Loc));
120     return SM.getLocForStartOfFile(SM.getFileID(Loc));
121   }
122 
123   /// \brief Return the end location of an included file or expanded macro.
124   SourceLocation getEndOfFileOrMacro(SourceLocation Loc) {
125     if (Loc.isMacroID())
126       return Loc.getLocWithOffset(SM.getFileIDSize(SM.getFileID(Loc)) -
127                                   SM.getFileOffset(Loc));
128     return SM.getLocForEndOfFile(SM.getFileID(Loc));
129   }
130 
131   /// \brief Find out where the current file is included or macro is expanded.
132   SourceLocation getIncludeOrExpansionLoc(SourceLocation Loc) {
133     return Loc.isMacroID() ? SM.getImmediateExpansionRange(Loc).first
134                            : SM.getIncludeLoc(SM.getFileID(Loc));
135   }
136 
137   /// \brief Get the start of \c S ignoring macro arguments and system macros.
138   SourceLocation getStart(const Stmt *S) {
139     SourceLocation Loc = S->getLocStart();
140     while (SM.isMacroArgExpansion(Loc) || SM.isInSystemMacro(Loc))
141       Loc = SM.getImmediateExpansionRange(Loc).first;
142     return Loc;
143   }
144 
145   /// \brief Get the end of \c S ignoring macro arguments and system macros.
146   SourceLocation getEnd(const Stmt *S) {
147     SourceLocation Loc = S->getLocEnd();
148     while (SM.isMacroArgExpansion(Loc) || SM.isInSystemMacro(Loc))
149       Loc = SM.getImmediateExpansionRange(Loc).first;
150     return getPreciseTokenLocEnd(Loc);
151   }
152 
153   /// \brief Find the set of files we have regions for and assign IDs
154   ///
155   /// Fills \c Mapping with the virtual file mapping needed to write out
156   /// coverage and collects the necessary file information to emit source and
157   /// expansion regions.
158   void gatherFileIDs(SmallVectorImpl<unsigned> &Mapping) {
159     FileIDMapping.clear();
160 
161     SmallVector<FileID, 8> Visited;
162     SmallVector<std::pair<SourceLocation, unsigned>, 8> FileLocs;
163     for (const auto &Region : SourceRegions) {
164       SourceLocation Loc = Region.getStartLoc();
165       FileID File = SM.getFileID(Loc);
166       if (std::find(Visited.begin(), Visited.end(), File) != Visited.end())
167         continue;
168       Visited.push_back(File);
169 
170       unsigned Depth = 0;
171       for (SourceLocation Parent = getIncludeOrExpansionLoc(Loc);
172            !Parent.isInvalid(); Parent = getIncludeOrExpansionLoc(Parent))
173         ++Depth;
174       FileLocs.push_back(std::make_pair(Loc, Depth));
175     }
176     std::stable_sort(FileLocs.begin(), FileLocs.end(), llvm::less_second());
177 
178     for (const auto &FL : FileLocs) {
179       SourceLocation Loc = FL.first;
180       FileID SpellingFile = SM.getDecomposedSpellingLoc(Loc).first;
181       auto Entry = SM.getFileEntryForID(SpellingFile);
182       if (!Entry)
183         continue;
184 
185       FileIDMapping[SM.getFileID(Loc)] = std::make_pair(Mapping.size(), Loc);
186       Mapping.push_back(CVM.getFileID(Entry));
187     }
188   }
189 
190   /// \brief Get the coverage mapping file ID for \c Loc.
191   ///
192   /// If such file id doesn't exist, return None.
193   Optional<unsigned> getCoverageFileID(SourceLocation Loc) {
194     auto Mapping = FileIDMapping.find(SM.getFileID(Loc));
195     if (Mapping != FileIDMapping.end())
196       return Mapping->second.first;
197     return None;
198   }
199 
200   /// \brief Return true if the given clang's file id has a corresponding
201   /// coverage file id.
202   bool hasExistingCoverageFileID(FileID File) const {
203     return FileIDMapping.count(File);
204   }
205 
206   /// \brief Gather all the regions that were skipped by the preprocessor
207   /// using the constructs like #if.
208   void gatherSkippedRegions() {
209     /// An array of the minimum lineStarts and the maximum lineEnds
210     /// for mapping regions from the appropriate source files.
211     llvm::SmallVector<std::pair<unsigned, unsigned>, 8> FileLineRanges;
212     FileLineRanges.resize(
213         FileIDMapping.size(),
214         std::make_pair(std::numeric_limits<unsigned>::max(), 0));
215     for (const auto &R : MappingRegions) {
216       FileLineRanges[R.FileID].first =
217           std::min(FileLineRanges[R.FileID].first, R.LineStart);
218       FileLineRanges[R.FileID].second =
219           std::max(FileLineRanges[R.FileID].second, R.LineEnd);
220     }
221 
222     auto SkippedRanges = CVM.getSourceInfo().getSkippedRanges();
223     for (const auto &I : SkippedRanges) {
224       auto LocStart = I.getBegin();
225       auto LocEnd = I.getEnd();
226       assert(SM.isWrittenInSameFile(LocStart, LocEnd) &&
227              "region spans multiple files");
228 
229       auto CovFileID = getCoverageFileID(LocStart);
230       if (!CovFileID)
231         continue;
232       unsigned LineStart = SM.getSpellingLineNumber(LocStart);
233       unsigned ColumnStart = SM.getSpellingColumnNumber(LocStart);
234       unsigned LineEnd = SM.getSpellingLineNumber(LocEnd);
235       unsigned ColumnEnd = SM.getSpellingColumnNumber(LocEnd);
236       auto Region = CounterMappingRegion::makeSkipped(
237           *CovFileID, LineStart, ColumnStart, LineEnd, ColumnEnd);
238       // Make sure that we only collect the regions that are inside
239       // the souce code of this function.
240       if (Region.LineStart >= FileLineRanges[*CovFileID].first &&
241           Region.LineEnd <= FileLineRanges[*CovFileID].second)
242         MappingRegions.push_back(Region);
243     }
244   }
245 
246   /// \brief Generate the coverage counter mapping regions from collected
247   /// source regions.
248   void emitSourceRegions() {
249     for (const auto &Region : SourceRegions) {
250       assert(Region.hasEndLoc() && "incomplete region");
251 
252       SourceLocation LocStart = Region.getStartLoc();
253       assert(!SM.getFileID(LocStart).isInvalid() && "region in invalid file");
254 
255       auto CovFileID = getCoverageFileID(LocStart);
256       // Ignore regions that don't have a file, such as builtin macros.
257       if (!CovFileID)
258         continue;
259 
260       SourceLocation LocEnd = Region.getEndLoc();
261       assert(SM.isWrittenInSameFile(LocStart, LocEnd) &&
262              "region spans multiple files");
263 
264       // Find the spilling locations for the mapping region.
265       unsigned LineStart = SM.getSpellingLineNumber(LocStart);
266       unsigned ColumnStart = SM.getSpellingColumnNumber(LocStart);
267       unsigned LineEnd = SM.getSpellingLineNumber(LocEnd);
268       unsigned ColumnEnd = SM.getSpellingColumnNumber(LocEnd);
269 
270       assert(LineStart <= LineEnd && "region start and end out of order");
271       MappingRegions.push_back(CounterMappingRegion::makeRegion(
272           Region.getCounter(), *CovFileID, LineStart, ColumnStart, LineEnd,
273           ColumnEnd));
274     }
275   }
276 
277   /// \brief Generate expansion regions for each virtual file we've seen.
278   void emitExpansionRegions() {
279     for (const auto &FM : FileIDMapping) {
280       SourceLocation ExpandedLoc = FM.second.second;
281       SourceLocation ParentLoc = getIncludeOrExpansionLoc(ExpandedLoc);
282       if (ParentLoc.isInvalid())
283         continue;
284 
285       auto ParentFileID = getCoverageFileID(ParentLoc);
286       if (!ParentFileID)
287         continue;
288       auto ExpandedFileID = getCoverageFileID(ExpandedLoc);
289       assert(ExpandedFileID && "expansion in uncovered file");
290 
291       SourceLocation LocEnd = getPreciseTokenLocEnd(ParentLoc);
292       assert(SM.isWrittenInSameFile(ParentLoc, LocEnd) &&
293              "region spans multiple files");
294 
295       unsigned LineStart = SM.getSpellingLineNumber(ParentLoc);
296       unsigned ColumnStart = SM.getSpellingColumnNumber(ParentLoc);
297       unsigned LineEnd = SM.getSpellingLineNumber(LocEnd);
298       unsigned ColumnEnd = SM.getSpellingColumnNumber(LocEnd);
299 
300       MappingRegions.push_back(CounterMappingRegion::makeExpansion(
301           *ParentFileID, *ExpandedFileID, LineStart, ColumnStart, LineEnd,
302           ColumnEnd));
303     }
304   }
305 };
306 
307 /// \brief Creates unreachable coverage regions for the functions that
308 /// are not emitted.
309 struct EmptyCoverageMappingBuilder : public CoverageMappingBuilder {
310   EmptyCoverageMappingBuilder(CoverageMappingModuleGen &CVM, SourceManager &SM,
311                               const LangOptions &LangOpts)
312       : CoverageMappingBuilder(CVM, SM, LangOpts) {}
313 
314   void VisitDecl(const Decl *D) {
315     if (!D->hasBody())
316       return;
317     auto Body = D->getBody();
318     SourceRegions.emplace_back(Counter(), getStart(Body), getEnd(Body));
319   }
320 
321   /// \brief Write the mapping data to the output stream
322   void write(llvm::raw_ostream &OS) {
323     SmallVector<unsigned, 16> FileIDMapping;
324     gatherFileIDs(FileIDMapping);
325     emitSourceRegions();
326 
327     CoverageMappingWriter Writer(FileIDMapping, None, MappingRegions);
328     Writer.write(OS);
329   }
330 };
331 
332 /// \brief A StmtVisitor that creates coverage mapping regions which map
333 /// from the source code locations to the PGO counters.
334 struct CounterCoverageMappingBuilder
335     : public CoverageMappingBuilder,
336       public ConstStmtVisitor<CounterCoverageMappingBuilder> {
337   /// \brief The map of statements to count values.
338   llvm::DenseMap<const Stmt *, unsigned> &CounterMap;
339 
340   /// \brief A stack of currently live regions.
341   std::vector<SourceMappingRegion> RegionStack;
342 
343   CounterExpressionBuilder Builder;
344 
345   /// \brief A location in the most recently visited file or macro.
346   ///
347   /// This is used to adjust the active source regions appropriately when
348   /// expressions cross file or macro boundaries.
349   SourceLocation MostRecentLocation;
350 
351   /// \brief Return a counter for the subtraction of \c RHS from \c LHS
352   Counter subtractCounters(Counter LHS, Counter RHS) {
353     return Builder.subtract(LHS, RHS);
354   }
355 
356   /// \brief Return a counter for the sum of \c LHS and \c RHS.
357   Counter addCounters(Counter LHS, Counter RHS) {
358     return Builder.add(LHS, RHS);
359   }
360 
361   Counter addCounters(Counter C1, Counter C2, Counter C3) {
362     return addCounters(addCounters(C1, C2), C3);
363   }
364 
365   Counter addCounters(Counter C1, Counter C2, Counter C3, Counter C4) {
366     return addCounters(addCounters(C1, C2, C3), C4);
367   }
368 
369   /// \brief Return the region counter for the given statement.
370   ///
371   /// This should only be called on statements that have a dedicated counter.
372   Counter getRegionCounter(const Stmt *S) {
373     return Counter::getCounter(CounterMap[S]);
374   }
375 
376   /// \brief Push a region onto the stack.
377   ///
378   /// Returns the index on the stack where the region was pushed. This can be
379   /// used with popRegions to exit a "scope", ending the region that was pushed.
380   size_t pushRegion(Counter Count, Optional<SourceLocation> StartLoc = None,
381                     Optional<SourceLocation> EndLoc = None) {
382     if (StartLoc)
383       MostRecentLocation = *StartLoc;
384     RegionStack.emplace_back(Count, StartLoc, EndLoc);
385 
386     return RegionStack.size() - 1;
387   }
388 
389   /// \brief Pop regions from the stack into the function's list of regions.
390   ///
391   /// Adds all regions from \c ParentIndex to the top of the stack to the
392   /// function's \c SourceRegions.
393   void popRegions(size_t ParentIndex) {
394     assert(RegionStack.size() >= ParentIndex && "parent not in stack");
395     while (RegionStack.size() > ParentIndex) {
396       SourceMappingRegion &Region = RegionStack.back();
397       if (Region.hasStartLoc()) {
398         SourceLocation StartLoc = Region.getStartLoc();
399         SourceLocation EndLoc = Region.hasEndLoc()
400                                     ? Region.getEndLoc()
401                                     : RegionStack[ParentIndex].getEndLoc();
402         while (!SM.isWrittenInSameFile(StartLoc, EndLoc)) {
403           // The region ends in a nested file or macro expansion. Create a
404           // separate region for each expansion.
405           SourceLocation NestedLoc = getStartOfFileOrMacro(EndLoc);
406           assert(SM.isWrittenInSameFile(NestedLoc, EndLoc));
407 
408           SourceRegions.emplace_back(Region.getCounter(), NestedLoc, EndLoc);
409 
410           EndLoc = getPreciseTokenLocEnd(getIncludeOrExpansionLoc(EndLoc));
411           assert(!EndLoc.isInvalid() &&
412                  "File exit was not handled before popRegions");
413         }
414         Region.setEndLoc(EndLoc);
415 
416         MostRecentLocation = EndLoc;
417         // If this region happens to span an entire expansion, we need to make
418         // sure we don't overlap the parent region with it.
419         if (StartLoc == getStartOfFileOrMacro(StartLoc) &&
420             EndLoc == getEndOfFileOrMacro(EndLoc))
421           MostRecentLocation = getIncludeOrExpansionLoc(EndLoc);
422 
423         assert(SM.isWrittenInSameFile(Region.getStartLoc(), EndLoc));
424         SourceRegions.push_back(std::move(Region));
425       }
426       RegionStack.pop_back();
427     }
428   }
429 
430   /// \brief Return the currently active region.
431   SourceMappingRegion &getRegion() {
432     assert(!RegionStack.empty() && "statement has no region");
433     return RegionStack.back();
434   }
435 
436   /// \brief Propagate counts through the children of \c S.
437   Counter propagateCounts(Counter TopCount, const Stmt *S) {
438     size_t Index = pushRegion(TopCount, getStart(S), getEnd(S));
439     Visit(S);
440     Counter ExitCount = getRegion().getCounter();
441     popRegions(Index);
442     return ExitCount;
443   }
444 
445   /// \brief Adjust the most recently visited location to \c EndLoc.
446   ///
447   /// This should be used after visiting any statements in non-source order.
448   void adjustForOutOfOrderTraversal(SourceLocation EndLoc) {
449     MostRecentLocation = EndLoc;
450     // Avoid adding duplicate regions if we have a completed region on the top
451     // of the stack and are adjusting to the end of a virtual file.
452     if (getRegion().hasEndLoc() &&
453         MostRecentLocation == getEndOfFileOrMacro(MostRecentLocation))
454       MostRecentLocation = getIncludeOrExpansionLoc(MostRecentLocation);
455   }
456 
457   /// \brief Check whether \c Loc is included or expanded from \c Parent.
458   bool isNestedIn(SourceLocation Loc, FileID Parent) {
459     do {
460       Loc = getIncludeOrExpansionLoc(Loc);
461       if (Loc.isInvalid())
462         return false;
463     } while (!SM.isInFileID(Loc, Parent));
464     return true;
465   }
466 
467   /// \brief Adjust regions and state when \c NewLoc exits a file.
468   ///
469   /// If moving from our most recently tracked location to \c NewLoc exits any
470   /// files, this adjusts our current region stack and creates the file regions
471   /// for the exited file.
472   void handleFileExit(SourceLocation NewLoc) {
473     if (SM.isWrittenInSameFile(MostRecentLocation, NewLoc))
474       return;
475 
476     // If NewLoc is not in a file that contains MostRecentLocation, walk up to
477     // find the common ancestor.
478     SourceLocation LCA = NewLoc;
479     FileID ParentFile = SM.getFileID(LCA);
480     while (!isNestedIn(MostRecentLocation, ParentFile)) {
481       LCA = getIncludeOrExpansionLoc(LCA);
482       if (LCA.isInvalid() || SM.isWrittenInSameFile(LCA, MostRecentLocation)) {
483         // Since there isn't a common ancestor, no file was exited. We just need
484         // to adjust our location to the new file.
485         MostRecentLocation = NewLoc;
486         return;
487       }
488       ParentFile = SM.getFileID(LCA);
489     }
490 
491     llvm::SmallSet<SourceLocation, 8> StartLocs;
492     Optional<Counter> ParentCounter;
493     for (auto I = RegionStack.rbegin(), E = RegionStack.rend(); I != E; ++I) {
494       if (!I->hasStartLoc())
495         continue;
496       SourceLocation Loc = I->getStartLoc();
497       if (!isNestedIn(Loc, ParentFile)) {
498         ParentCounter = I->getCounter();
499         break;
500       }
501 
502       while (!SM.isInFileID(Loc, ParentFile)) {
503         // The most nested region for each start location is the one with the
504         // correct count. We avoid creating redundant regions by stopping once
505         // we've seen this region.
506         if (StartLocs.insert(Loc).second)
507           SourceRegions.emplace_back(I->getCounter(), Loc,
508                                      getEndOfFileOrMacro(Loc));
509         Loc = getIncludeOrExpansionLoc(Loc);
510       }
511       I->setStartLoc(getPreciseTokenLocEnd(Loc));
512     }
513 
514     if (ParentCounter) {
515       // If the file is contained completely by another region and doesn't
516       // immediately start its own region, the whole file gets a region
517       // corresponding to the parent.
518       SourceLocation Loc = MostRecentLocation;
519       while (isNestedIn(Loc, ParentFile)) {
520         SourceLocation FileStart = getStartOfFileOrMacro(Loc);
521         if (StartLocs.insert(FileStart).second)
522           SourceRegions.emplace_back(*ParentCounter, FileStart,
523                                      getEndOfFileOrMacro(Loc));
524         Loc = getIncludeOrExpansionLoc(Loc);
525       }
526     }
527 
528     MostRecentLocation = NewLoc;
529   }
530 
531   /// \brief Ensure that \c S is included in the current region.
532   void extendRegion(const Stmt *S) {
533     SourceMappingRegion &Region = getRegion();
534     SourceLocation StartLoc = getStart(S);
535 
536     handleFileExit(StartLoc);
537     if (!Region.hasStartLoc())
538       Region.setStartLoc(StartLoc);
539   }
540 
541   /// \brief Mark \c S as a terminator, starting a zero region.
542   void terminateRegion(const Stmt *S) {
543     extendRegion(S);
544     SourceMappingRegion &Region = getRegion();
545     if (!Region.hasEndLoc())
546       Region.setEndLoc(getEnd(S));
547     pushRegion(Counter::getZero());
548   }
549 
550   /// \brief Keep counts of breaks and continues inside loops.
551   struct BreakContinue {
552     Counter BreakCount;
553     Counter ContinueCount;
554   };
555   SmallVector<BreakContinue, 8> BreakContinueStack;
556 
557   CounterCoverageMappingBuilder(
558       CoverageMappingModuleGen &CVM,
559       llvm::DenseMap<const Stmt *, unsigned> &CounterMap, SourceManager &SM,
560       const LangOptions &LangOpts)
561       : CoverageMappingBuilder(CVM, SM, LangOpts), CounterMap(CounterMap) {}
562 
563   /// \brief Write the mapping data to the output stream
564   void write(llvm::raw_ostream &OS) {
565     llvm::SmallVector<unsigned, 8> VirtualFileMapping;
566     gatherFileIDs(VirtualFileMapping);
567     emitSourceRegions();
568     emitExpansionRegions();
569     gatherSkippedRegions();
570 
571     CoverageMappingWriter Writer(VirtualFileMapping, Builder.getExpressions(),
572                                  MappingRegions);
573     Writer.write(OS);
574   }
575 
576   void VisitStmt(const Stmt *S) {
577     if (!S->getLocStart().isInvalid())
578       extendRegion(S);
579     for (Stmt::const_child_range I = S->children(); I; ++I) {
580       if (*I)
581         this->Visit(*I);
582     }
583     handleFileExit(getEnd(S));
584   }
585 
586   void VisitDecl(const Decl *D) {
587     Stmt *Body = D->getBody();
588     propagateCounts(getRegionCounter(Body), Body);
589   }
590 
591   void VisitReturnStmt(const ReturnStmt *S) {
592     extendRegion(S);
593     if (S->getRetValue())
594       Visit(S->getRetValue());
595     terminateRegion(S);
596   }
597 
598   void VisitCXXThrowExpr(const CXXThrowExpr *E) {
599     extendRegion(E);
600     if (E->getSubExpr())
601       Visit(E->getSubExpr());
602     terminateRegion(E);
603   }
604 
605   void VisitGotoStmt(const GotoStmt *S) { terminateRegion(S); }
606 
607   void VisitLabelStmt(const LabelStmt *S) {
608     SourceLocation Start = getStart(S);
609     // We can't extendRegion here or we risk overlapping with our new region.
610     handleFileExit(Start);
611     pushRegion(getRegionCounter(S), Start);
612     Visit(S->getSubStmt());
613   }
614 
615   void VisitBreakStmt(const BreakStmt *S) {
616     assert(!BreakContinueStack.empty() && "break not in a loop or switch!");
617     BreakContinueStack.back().BreakCount = addCounters(
618         BreakContinueStack.back().BreakCount, getRegion().getCounter());
619     terminateRegion(S);
620   }
621 
622   void VisitContinueStmt(const ContinueStmt *S) {
623     assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
624     BreakContinueStack.back().ContinueCount = addCounters(
625         BreakContinueStack.back().ContinueCount, getRegion().getCounter());
626     terminateRegion(S);
627   }
628 
629   void VisitWhileStmt(const WhileStmt *S) {
630     extendRegion(S);
631 
632     Counter ParentCount = getRegion().getCounter();
633     Counter BodyCount = getRegionCounter(S);
634 
635     // Handle the body first so that we can get the backedge count.
636     BreakContinueStack.push_back(BreakContinue());
637     extendRegion(S->getBody());
638     Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
639     BreakContinue BC = BreakContinueStack.pop_back_val();
640 
641     // Go back to handle the condition.
642     Counter CondCount =
643         addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
644     propagateCounts(CondCount, S->getCond());
645     adjustForOutOfOrderTraversal(getEnd(S));
646 
647     Counter OutCount =
648         addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount));
649     if (OutCount != ParentCount)
650       pushRegion(OutCount);
651   }
652 
653   void VisitDoStmt(const DoStmt *S) {
654     extendRegion(S);
655 
656     Counter ParentCount = getRegion().getCounter();
657     Counter BodyCount = getRegionCounter(S);
658 
659     BreakContinueStack.push_back(BreakContinue());
660     extendRegion(S->getBody());
661     Counter BackedgeCount =
662         propagateCounts(addCounters(ParentCount, BodyCount), S->getBody());
663     BreakContinue BC = BreakContinueStack.pop_back_val();
664 
665     Counter CondCount = addCounters(BackedgeCount, BC.ContinueCount);
666     propagateCounts(CondCount, S->getCond());
667 
668     Counter OutCount =
669         addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount));
670     if (OutCount != ParentCount)
671       pushRegion(OutCount);
672   }
673 
674   void VisitForStmt(const ForStmt *S) {
675     extendRegion(S);
676     if (S->getInit())
677       Visit(S->getInit());
678 
679     Counter ParentCount = getRegion().getCounter();
680     Counter BodyCount = getRegionCounter(S);
681 
682     // Handle the body first so that we can get the backedge count.
683     BreakContinueStack.push_back(BreakContinue());
684     extendRegion(S->getBody());
685     Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
686     BreakContinue BC = BreakContinueStack.pop_back_val();
687 
688     // The increment is essentially part of the body but it needs to include
689     // the count for all the continue statements.
690     if (const Stmt *Inc = S->getInc())
691       propagateCounts(addCounters(BackedgeCount, BC.ContinueCount), Inc);
692 
693     // Go back to handle the condition.
694     Counter CondCount =
695         addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
696     if (const Expr *Cond = S->getCond()) {
697       propagateCounts(CondCount, Cond);
698       adjustForOutOfOrderTraversal(getEnd(S));
699     }
700 
701     Counter OutCount =
702         addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount));
703     if (OutCount != ParentCount)
704       pushRegion(OutCount);
705   }
706 
707   void VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
708     extendRegion(S);
709     Visit(S->getLoopVarStmt());
710     Visit(S->getRangeStmt());
711 
712     Counter ParentCount = getRegion().getCounter();
713     Counter BodyCount = getRegionCounter(S);
714 
715     BreakContinueStack.push_back(BreakContinue());
716     extendRegion(S->getBody());
717     Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
718     BreakContinue BC = BreakContinueStack.pop_back_val();
719 
720     Counter LoopCount =
721         addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
722     Counter OutCount =
723         addCounters(BC.BreakCount, subtractCounters(LoopCount, BodyCount));
724     if (OutCount != ParentCount)
725       pushRegion(OutCount);
726   }
727 
728   void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) {
729     extendRegion(S);
730     Visit(S->getElement());
731 
732     Counter ParentCount = getRegion().getCounter();
733     Counter BodyCount = getRegionCounter(S);
734 
735     BreakContinueStack.push_back(BreakContinue());
736     extendRegion(S->getBody());
737     Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
738     BreakContinue BC = BreakContinueStack.pop_back_val();
739 
740     Counter LoopCount =
741         addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
742     Counter OutCount =
743         addCounters(BC.BreakCount, subtractCounters(LoopCount, BodyCount));
744     if (OutCount != ParentCount)
745       pushRegion(OutCount);
746   }
747 
748   void VisitSwitchStmt(const SwitchStmt *S) {
749     extendRegion(S);
750     Visit(S->getCond());
751 
752     BreakContinueStack.push_back(BreakContinue());
753 
754     const Stmt *Body = S->getBody();
755     extendRegion(Body);
756     if (const auto *CS = dyn_cast<CompoundStmt>(Body)) {
757       if (!CS->body_empty()) {
758         // The body of the switch needs a zero region so that fallthrough counts
759         // behave correctly, but it would be misleading to include the braces of
760         // the compound statement in the zeroed area, so we need to handle this
761         // specially.
762         size_t Index =
763             pushRegion(Counter::getZero(), getStart(CS->body_front()),
764                        getEnd(CS->body_back()));
765         for (const auto *Child : CS->children())
766           Visit(Child);
767         popRegions(Index);
768       }
769     } else
770       propagateCounts(Counter::getZero(), Body);
771     BreakContinue BC = BreakContinueStack.pop_back_val();
772 
773     if (!BreakContinueStack.empty())
774       BreakContinueStack.back().ContinueCount = addCounters(
775           BreakContinueStack.back().ContinueCount, BC.ContinueCount);
776 
777     Counter ExitCount = getRegionCounter(S);
778     pushRegion(ExitCount);
779   }
780 
781   void VisitSwitchCase(const SwitchCase *S) {
782     extendRegion(S);
783 
784     SourceMappingRegion &Parent = getRegion();
785 
786     Counter Count = addCounters(Parent.getCounter(), getRegionCounter(S));
787     // Reuse the existing region if it starts at our label. This is typical of
788     // the first case in a switch.
789     if (Parent.hasStartLoc() && Parent.getStartLoc() == getStart(S))
790       Parent.setCounter(Count);
791     else
792       pushRegion(Count, getStart(S));
793 
794     if (const CaseStmt *CS = dyn_cast<CaseStmt>(S)) {
795       Visit(CS->getLHS());
796       if (const Expr *RHS = CS->getRHS())
797         Visit(RHS);
798     }
799     Visit(S->getSubStmt());
800   }
801 
802   void VisitIfStmt(const IfStmt *S) {
803     extendRegion(S);
804 
805     Counter ParentCount = getRegion().getCounter();
806     Counter ThenCount = getRegionCounter(S);
807 
808     // Emitting a counter for the condition makes it easier to interpret the
809     // counter for the body when looking at the coverage.
810     propagateCounts(ParentCount, S->getCond());
811 
812     extendRegion(S->getThen());
813     Counter OutCount = propagateCounts(ThenCount, S->getThen());
814 
815     Counter ElseCount = subtractCounters(ParentCount, ThenCount);
816     if (const Stmt *Else = S->getElse()) {
817       extendRegion(S->getElse());
818       OutCount = addCounters(OutCount, propagateCounts(ElseCount, Else));
819     } else
820       OutCount = addCounters(OutCount, ElseCount);
821 
822     if (OutCount != ParentCount)
823       pushRegion(OutCount);
824   }
825 
826   void VisitCXXTryStmt(const CXXTryStmt *S) {
827     extendRegion(S);
828     Visit(S->getTryBlock());
829     for (unsigned I = 0, E = S->getNumHandlers(); I < E; ++I)
830       Visit(S->getHandler(I));
831 
832     Counter ExitCount = getRegionCounter(S);
833     pushRegion(ExitCount);
834   }
835 
836   void VisitCXXCatchStmt(const CXXCatchStmt *S) {
837     extendRegion(S);
838     propagateCounts(getRegionCounter(S), S->getHandlerBlock());
839   }
840 
841   void VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
842     extendRegion(E);
843 
844     Counter ParentCount = getRegion().getCounter();
845     Counter TrueCount = getRegionCounter(E);
846 
847     Visit(E->getCond());
848 
849     if (!isa<BinaryConditionalOperator>(E)) {
850       extendRegion(E->getTrueExpr());
851       propagateCounts(TrueCount, E->getTrueExpr());
852     }
853     extendRegion(E->getFalseExpr());
854     propagateCounts(subtractCounters(ParentCount, TrueCount),
855                     E->getFalseExpr());
856   }
857 
858   void VisitBinLAnd(const BinaryOperator *E) {
859     extendRegion(E);
860     Visit(E->getLHS());
861 
862     extendRegion(E->getRHS());
863     propagateCounts(getRegionCounter(E), E->getRHS());
864   }
865 
866   void VisitBinLOr(const BinaryOperator *E) {
867     extendRegion(E);
868     Visit(E->getLHS());
869 
870     extendRegion(E->getRHS());
871     propagateCounts(getRegionCounter(E), E->getRHS());
872   }
873 
874   void VisitLambdaExpr(const LambdaExpr *LE) {
875     // Lambdas are treated as their own functions for now, so we shouldn't
876     // propagate counts into them.
877   }
878 };
879 }
880 
881 static bool isMachO(const CodeGenModule &CGM) {
882   return CGM.getTarget().getTriple().isOSBinFormatMachO();
883 }
884 
885 static StringRef getCoverageSection(const CodeGenModule &CGM) {
886   return isMachO(CGM) ? "__DATA,__llvm_covmap" : "__llvm_covmap";
887 }
888 
889 static void dump(llvm::raw_ostream &OS, StringRef FunctionName,
890                  ArrayRef<CounterExpression> Expressions,
891                  ArrayRef<CounterMappingRegion> Regions) {
892   OS << FunctionName << ":\n";
893   CounterMappingContext Ctx(Expressions);
894   for (const auto &R : Regions) {
895     OS.indent(2);
896     switch (R.Kind) {
897     case CounterMappingRegion::CodeRegion:
898       break;
899     case CounterMappingRegion::ExpansionRegion:
900       OS << "Expansion,";
901       break;
902     case CounterMappingRegion::SkippedRegion:
903       OS << "Skipped,";
904       break;
905     }
906 
907     OS << "File " << R.FileID << ", " << R.LineStart << ":" << R.ColumnStart
908        << " -> " << R.LineEnd << ":" << R.ColumnEnd << " = ";
909     Ctx.dump(R.Count, OS);
910     if (R.Kind == CounterMappingRegion::ExpansionRegion)
911       OS << " (Expanded file = " << R.ExpandedFileID << ")";
912     OS << "\n";
913   }
914 }
915 
916 void CoverageMappingModuleGen::addFunctionMappingRecord(
917     llvm::GlobalVariable *FunctionName, StringRef FunctionNameValue,
918     uint64_t FunctionHash, const std::string &CoverageMapping) {
919   llvm::LLVMContext &Ctx = CGM.getLLVMContext();
920   auto *Int32Ty = llvm::Type::getInt32Ty(Ctx);
921   auto *Int64Ty = llvm::Type::getInt64Ty(Ctx);
922   auto *Int8PtrTy = llvm::Type::getInt8PtrTy(Ctx);
923   if (!FunctionRecordTy) {
924     llvm::Type *FunctionRecordTypes[] = {Int8PtrTy, Int32Ty, Int32Ty, Int64Ty};
925     FunctionRecordTy =
926         llvm::StructType::get(Ctx, makeArrayRef(FunctionRecordTypes));
927   }
928 
929   llvm::Constant *FunctionRecordVals[] = {
930       llvm::ConstantExpr::getBitCast(FunctionName, Int8PtrTy),
931       llvm::ConstantInt::get(Int32Ty, FunctionNameValue.size()),
932       llvm::ConstantInt::get(Int32Ty, CoverageMapping.size()),
933       llvm::ConstantInt::get(Int64Ty, FunctionHash)};
934   FunctionRecords.push_back(llvm::ConstantStruct::get(
935       FunctionRecordTy, makeArrayRef(FunctionRecordVals)));
936   CoverageMappings += CoverageMapping;
937 
938   if (CGM.getCodeGenOpts().DumpCoverageMapping) {
939     // Dump the coverage mapping data for this function by decoding the
940     // encoded data. This allows us to dump the mapping regions which were
941     // also processed by the CoverageMappingWriter which performs
942     // additional minimization operations such as reducing the number of
943     // expressions.
944     std::vector<StringRef> Filenames;
945     std::vector<CounterExpression> Expressions;
946     std::vector<CounterMappingRegion> Regions;
947     llvm::SmallVector<StringRef, 16> FilenameRefs;
948     FilenameRefs.resize(FileEntries.size());
949     for (const auto &Entry : FileEntries)
950       FilenameRefs[Entry.second] = Entry.first->getName();
951     RawCoverageMappingReader Reader(CoverageMapping, FilenameRefs, Filenames,
952                                     Expressions, Regions);
953     if (Reader.read())
954       return;
955     dump(llvm::outs(), FunctionNameValue, Expressions, Regions);
956   }
957 }
958 
959 void CoverageMappingModuleGen::emit() {
960   if (FunctionRecords.empty())
961     return;
962   llvm::LLVMContext &Ctx = CGM.getLLVMContext();
963   auto *Int32Ty = llvm::Type::getInt32Ty(Ctx);
964 
965   // Create the filenames and merge them with coverage mappings
966   llvm::SmallVector<std::string, 16> FilenameStrs;
967   llvm::SmallVector<StringRef, 16> FilenameRefs;
968   FilenameStrs.resize(FileEntries.size());
969   FilenameRefs.resize(FileEntries.size());
970   for (const auto &Entry : FileEntries) {
971     llvm::SmallString<256> Path(Entry.first->getName());
972     llvm::sys::fs::make_absolute(Path);
973 
974     auto I = Entry.second;
975     FilenameStrs[I] = std::string(Path.begin(), Path.end());
976     FilenameRefs[I] = FilenameStrs[I];
977   }
978 
979   std::string FilenamesAndCoverageMappings;
980   llvm::raw_string_ostream OS(FilenamesAndCoverageMappings);
981   CoverageFilenamesSectionWriter(FilenameRefs).write(OS);
982   OS << CoverageMappings;
983   size_t CoverageMappingSize = CoverageMappings.size();
984   size_t FilenamesSize = OS.str().size() - CoverageMappingSize;
985   // Append extra zeroes if necessary to ensure that the size of the filenames
986   // and coverage mappings is a multiple of 8.
987   if (size_t Rem = OS.str().size() % 8) {
988     CoverageMappingSize += 8 - Rem;
989     for (size_t I = 0, S = 8 - Rem; I < S; ++I)
990       OS << '\0';
991   }
992   auto *FilenamesAndMappingsVal =
993       llvm::ConstantDataArray::getString(Ctx, OS.str(), false);
994 
995   // Create the deferred function records array
996   auto RecordsTy =
997       llvm::ArrayType::get(FunctionRecordTy, FunctionRecords.size());
998   auto RecordsVal = llvm::ConstantArray::get(RecordsTy, FunctionRecords);
999 
1000   // Create the coverage data record
1001   llvm::Type *CovDataTypes[] = {Int32Ty,   Int32Ty,
1002                                 Int32Ty,   Int32Ty,
1003                                 RecordsTy, FilenamesAndMappingsVal->getType()};
1004   auto CovDataTy = llvm::StructType::get(Ctx, makeArrayRef(CovDataTypes));
1005   llvm::Constant *TUDataVals[] = {
1006       llvm::ConstantInt::get(Int32Ty, FunctionRecords.size()),
1007       llvm::ConstantInt::get(Int32Ty, FilenamesSize),
1008       llvm::ConstantInt::get(Int32Ty, CoverageMappingSize),
1009       llvm::ConstantInt::get(Int32Ty,
1010                              /*Version=*/CoverageMappingVersion1),
1011       RecordsVal, FilenamesAndMappingsVal};
1012   auto CovDataVal =
1013       llvm::ConstantStruct::get(CovDataTy, makeArrayRef(TUDataVals));
1014   auto CovData = new llvm::GlobalVariable(CGM.getModule(), CovDataTy, true,
1015                                           llvm::GlobalValue::InternalLinkage,
1016                                           CovDataVal,
1017                                           "__llvm_coverage_mapping");
1018 
1019   CovData->setSection(getCoverageSection(CGM));
1020   CovData->setAlignment(8);
1021 
1022   // Make sure the data doesn't get deleted.
1023   CGM.addUsedGlobal(CovData);
1024 }
1025 
1026 unsigned CoverageMappingModuleGen::getFileID(const FileEntry *File) {
1027   auto It = FileEntries.find(File);
1028   if (It != FileEntries.end())
1029     return It->second;
1030   unsigned FileID = FileEntries.size();
1031   FileEntries.insert(std::make_pair(File, FileID));
1032   return FileID;
1033 }
1034 
1035 void CoverageMappingGen::emitCounterMapping(const Decl *D,
1036                                             llvm::raw_ostream &OS) {
1037   assert(CounterMap);
1038   CounterCoverageMappingBuilder Walker(CVM, *CounterMap, SM, LangOpts);
1039   Walker.VisitDecl(D);
1040   Walker.write(OS);
1041 }
1042 
1043 void CoverageMappingGen::emitEmptyMapping(const Decl *D,
1044                                           llvm::raw_ostream &OS) {
1045   EmptyCoverageMappingBuilder Walker(CVM, SM, LangOpts);
1046   Walker.VisitDecl(D);
1047   Walker.write(OS);
1048 }
1049