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