1ee02499aSAlex Lorenz //===--- CoverageMappingGen.cpp - Coverage mapping generation ---*- C++ -*-===// 2ee02499aSAlex Lorenz // 3ee02499aSAlex Lorenz // The LLVM Compiler Infrastructure 4ee02499aSAlex Lorenz // 5ee02499aSAlex Lorenz // This file is distributed under the University of Illinois Open Source 6ee02499aSAlex Lorenz // License. See LICENSE.TXT for details. 7ee02499aSAlex Lorenz // 8ee02499aSAlex Lorenz //===----------------------------------------------------------------------===// 9ee02499aSAlex Lorenz // 10ee02499aSAlex Lorenz // Instrumentation-based code coverage mapping generator 11ee02499aSAlex Lorenz // 12ee02499aSAlex Lorenz //===----------------------------------------------------------------------===// 13ee02499aSAlex Lorenz 14ee02499aSAlex Lorenz #include "CoverageMappingGen.h" 15ee02499aSAlex Lorenz #include "CodeGenFunction.h" 16ee02499aSAlex Lorenz #include "clang/AST/StmtVisitor.h" 17ee02499aSAlex Lorenz #include "clang/Lex/Lexer.h" 18bc6b80a0SVedant Kumar #include "llvm/ADT/SmallSet.h" 19ca3326c0SVedant Kumar #include "llvm/ADT/StringExtras.h" 20bf42cfd7SJustin Bogner #include "llvm/ADT/Optional.h" 21b014ee46SEaswaran Raman #include "llvm/ProfileData/Coverage/CoverageMapping.h" 22b014ee46SEaswaran Raman #include "llvm/ProfileData/Coverage/CoverageMappingReader.h" 23b014ee46SEaswaran Raman #include "llvm/ProfileData/Coverage/CoverageMappingWriter.h" 240d9593ddSChandler Carruth #include "llvm/ProfileData/InstrProfReader.h" 25ee02499aSAlex Lorenz #include "llvm/Support/FileSystem.h" 26ee02499aSAlex Lorenz 27ee02499aSAlex Lorenz using namespace clang; 28ee02499aSAlex Lorenz using namespace CodeGen; 29ee02499aSAlex Lorenz using namespace llvm::coverage; 30ee02499aSAlex Lorenz 31ee02499aSAlex Lorenz void CoverageSourceInfo::SourceRangeSkipped(SourceRange Range) { 32ee02499aSAlex Lorenz SkippedRanges.push_back(Range); 33ee02499aSAlex Lorenz } 34ee02499aSAlex Lorenz 35ee02499aSAlex Lorenz namespace { 36ee02499aSAlex Lorenz 37ee02499aSAlex Lorenz /// \brief A region of source code that can be mapped to a counter. 3809c7179bSJustin Bogner class SourceMappingRegion { 39ee02499aSAlex Lorenz Counter Count; 40ee02499aSAlex Lorenz 41ee02499aSAlex Lorenz /// \brief The region's starting location. 42bf42cfd7SJustin Bogner Optional<SourceLocation> LocStart; 43ee02499aSAlex Lorenz 44ee02499aSAlex Lorenz /// \brief The region's ending location. 45bf42cfd7SJustin Bogner Optional<SourceLocation> LocEnd; 46ee02499aSAlex Lorenz 4709c7179bSJustin Bogner public: 48bf42cfd7SJustin Bogner SourceMappingRegion(Counter Count, Optional<SourceLocation> LocStart, 49bf42cfd7SJustin Bogner Optional<SourceLocation> LocEnd) 50bf42cfd7SJustin Bogner : Count(Count), LocStart(LocStart), LocEnd(LocEnd) {} 51ee02499aSAlex Lorenz 5209c7179bSJustin Bogner const Counter &getCounter() const { return Count; } 5309c7179bSJustin Bogner 54bf42cfd7SJustin Bogner void setCounter(Counter C) { Count = C; } 5509c7179bSJustin Bogner 56bf42cfd7SJustin Bogner bool hasStartLoc() const { return LocStart.hasValue(); } 57bf42cfd7SJustin Bogner 58bf42cfd7SJustin Bogner void setStartLoc(SourceLocation Loc) { LocStart = Loc; } 59bf42cfd7SJustin Bogner 60462c77b4SCraig Topper SourceLocation getStartLoc() const { 61bf42cfd7SJustin Bogner assert(LocStart && "Region has no start location"); 62bf42cfd7SJustin Bogner return *LocStart; 6309c7179bSJustin Bogner } 6409c7179bSJustin Bogner 65bf42cfd7SJustin Bogner bool hasEndLoc() const { return LocEnd.hasValue(); } 66ee02499aSAlex Lorenz 67bf42cfd7SJustin Bogner void setEndLoc(SourceLocation Loc) { LocEnd = Loc; } 68ee02499aSAlex Lorenz 69462c77b4SCraig Topper SourceLocation getEndLoc() const { 70bf42cfd7SJustin Bogner assert(LocEnd && "Region has no end location"); 71bf42cfd7SJustin Bogner return *LocEnd; 72ee02499aSAlex Lorenz } 73ee02499aSAlex Lorenz }; 74ee02499aSAlex Lorenz 75ee02499aSAlex Lorenz /// \brief Provides the common functionality for the different 76ee02499aSAlex Lorenz /// coverage mapping region builders. 77ee02499aSAlex Lorenz class CoverageMappingBuilder { 78ee02499aSAlex Lorenz public: 79ee02499aSAlex Lorenz CoverageMappingModuleGen &CVM; 80ee02499aSAlex Lorenz SourceManager &SM; 81ee02499aSAlex Lorenz const LangOptions &LangOpts; 82ee02499aSAlex Lorenz 83ee02499aSAlex Lorenz private: 84bf42cfd7SJustin Bogner /// \brief Map of clang's FileIDs to IDs used for coverage mapping. 85bf42cfd7SJustin Bogner llvm::SmallDenseMap<FileID, std::pair<unsigned, SourceLocation>, 8> 86bf42cfd7SJustin Bogner FileIDMapping; 87ee02499aSAlex Lorenz 88ee02499aSAlex Lorenz public: 89ee02499aSAlex Lorenz /// \brief The coverage mapping regions for this function 90ee02499aSAlex Lorenz llvm::SmallVector<CounterMappingRegion, 32> MappingRegions; 91ee02499aSAlex Lorenz /// \brief The source mapping regions for this function. 92f59329b0SJustin Bogner std::vector<SourceMappingRegion> SourceRegions; 93ee02499aSAlex Lorenz 94ee02499aSAlex Lorenz CoverageMappingBuilder(CoverageMappingModuleGen &CVM, SourceManager &SM, 95ee02499aSAlex Lorenz const LangOptions &LangOpts) 96bf42cfd7SJustin Bogner : CVM(CVM), SM(SM), LangOpts(LangOpts) {} 97ee02499aSAlex Lorenz 98ee02499aSAlex Lorenz /// \brief Return the precise end location for the given token. 99ee02499aSAlex Lorenz SourceLocation getPreciseTokenLocEnd(SourceLocation Loc) { 100bf42cfd7SJustin Bogner // We avoid getLocForEndOfToken here, because it doesn't do what we want for 101bf42cfd7SJustin Bogner // macro locations, which we just treat as expanded files. 102bf42cfd7SJustin Bogner unsigned TokLen = 103bf42cfd7SJustin Bogner Lexer::MeasureTokenLength(SM.getSpellingLoc(Loc), SM, LangOpts); 104bf42cfd7SJustin Bogner return Loc.getLocWithOffset(TokLen); 105ee02499aSAlex Lorenz } 106ee02499aSAlex Lorenz 107bf42cfd7SJustin Bogner /// \brief Return the start location of an included file or expanded macro. 108bf42cfd7SJustin Bogner SourceLocation getStartOfFileOrMacro(SourceLocation Loc) { 109bf42cfd7SJustin Bogner if (Loc.isMacroID()) 110bf42cfd7SJustin Bogner return Loc.getLocWithOffset(-SM.getFileOffset(Loc)); 111bf42cfd7SJustin Bogner return SM.getLocForStartOfFile(SM.getFileID(Loc)); 112ee02499aSAlex Lorenz } 113ee02499aSAlex Lorenz 114bf42cfd7SJustin Bogner /// \brief Return the end location of an included file or expanded macro. 115bf42cfd7SJustin Bogner SourceLocation getEndOfFileOrMacro(SourceLocation Loc) { 116bf42cfd7SJustin Bogner if (Loc.isMacroID()) 117bf42cfd7SJustin Bogner return Loc.getLocWithOffset(SM.getFileIDSize(SM.getFileID(Loc)) - 118f14b2078SJustin Bogner SM.getFileOffset(Loc)); 119bf42cfd7SJustin Bogner return SM.getLocForEndOfFile(SM.getFileID(Loc)); 120bf42cfd7SJustin Bogner } 121ee02499aSAlex Lorenz 122bf42cfd7SJustin Bogner /// \brief Find out where the current file is included or macro is expanded. 123bf42cfd7SJustin Bogner SourceLocation getIncludeOrExpansionLoc(SourceLocation Loc) { 124bf42cfd7SJustin Bogner return Loc.isMacroID() ? SM.getImmediateExpansionRange(Loc).first 125bf42cfd7SJustin Bogner : SM.getIncludeLoc(SM.getFileID(Loc)); 126bf42cfd7SJustin Bogner } 127bf42cfd7SJustin Bogner 128682bfbf3SJustin Bogner /// \brief Return true if \c Loc is a location in a built-in macro. 129682bfbf3SJustin Bogner bool isInBuiltin(SourceLocation Loc) { 130682bfbf3SJustin Bogner return strcmp(SM.getBufferName(SM.getSpellingLoc(Loc)), "<built-in>") == 0; 131682bfbf3SJustin Bogner } 132682bfbf3SJustin Bogner 133682bfbf3SJustin Bogner /// \brief Get the start of \c S ignoring macro arguments and builtin macros. 134bf42cfd7SJustin Bogner SourceLocation getStart(const Stmt *S) { 135bf42cfd7SJustin Bogner SourceLocation Loc = S->getLocStart(); 136682bfbf3SJustin Bogner while (SM.isMacroArgExpansion(Loc) || isInBuiltin(Loc)) 137bf42cfd7SJustin Bogner Loc = SM.getImmediateExpansionRange(Loc).first; 138bf42cfd7SJustin Bogner return Loc; 139bf42cfd7SJustin Bogner } 140bf42cfd7SJustin Bogner 141682bfbf3SJustin Bogner /// \brief Get the end of \c S ignoring macro arguments and builtin macros. 142bf42cfd7SJustin Bogner SourceLocation getEnd(const Stmt *S) { 143bf42cfd7SJustin Bogner SourceLocation Loc = S->getLocEnd(); 144682bfbf3SJustin Bogner while (SM.isMacroArgExpansion(Loc) || isInBuiltin(Loc)) 145bf42cfd7SJustin Bogner Loc = SM.getImmediateExpansionRange(Loc).first; 146f14b2078SJustin Bogner return getPreciseTokenLocEnd(Loc); 147bf42cfd7SJustin Bogner } 148bf42cfd7SJustin Bogner 149bf42cfd7SJustin Bogner /// \brief Find the set of files we have regions for and assign IDs 150bf42cfd7SJustin Bogner /// 151bf42cfd7SJustin Bogner /// Fills \c Mapping with the virtual file mapping needed to write out 152bf42cfd7SJustin Bogner /// coverage and collects the necessary file information to emit source and 153bf42cfd7SJustin Bogner /// expansion regions. 154bf42cfd7SJustin Bogner void gatherFileIDs(SmallVectorImpl<unsigned> &Mapping) { 155bf42cfd7SJustin Bogner FileIDMapping.clear(); 156bf42cfd7SJustin Bogner 157bc6b80a0SVedant Kumar llvm::SmallSet<FileID, 8> Visited; 158bf42cfd7SJustin Bogner SmallVector<std::pair<SourceLocation, unsigned>, 8> FileLocs; 159bf42cfd7SJustin Bogner for (const auto &Region : SourceRegions) { 160bf42cfd7SJustin Bogner SourceLocation Loc = Region.getStartLoc(); 161bf42cfd7SJustin Bogner FileID File = SM.getFileID(Loc); 162bc6b80a0SVedant Kumar if (!Visited.insert(File).second) 163bf42cfd7SJustin Bogner continue; 164bf42cfd7SJustin Bogner 165bf42cfd7SJustin Bogner unsigned Depth = 0; 166bf42cfd7SJustin Bogner for (SourceLocation Parent = getIncludeOrExpansionLoc(Loc); 167ed1fe5d0SYaron Keren Parent.isValid(); Parent = getIncludeOrExpansionLoc(Parent)) 168bf42cfd7SJustin Bogner ++Depth; 169bf42cfd7SJustin Bogner FileLocs.push_back(std::make_pair(Loc, Depth)); 170bf42cfd7SJustin Bogner } 171bf42cfd7SJustin Bogner std::stable_sort(FileLocs.begin(), FileLocs.end(), llvm::less_second()); 172bf42cfd7SJustin Bogner 173bf42cfd7SJustin Bogner for (const auto &FL : FileLocs) { 174bf42cfd7SJustin Bogner SourceLocation Loc = FL.first; 175bf42cfd7SJustin Bogner FileID SpellingFile = SM.getDecomposedSpellingLoc(Loc).first; 176ee02499aSAlex Lorenz auto Entry = SM.getFileEntryForID(SpellingFile); 177ee02499aSAlex Lorenz if (!Entry) 178bf42cfd7SJustin Bogner continue; 179ee02499aSAlex Lorenz 180bf42cfd7SJustin Bogner FileIDMapping[SM.getFileID(Loc)] = std::make_pair(Mapping.size(), Loc); 181bf42cfd7SJustin Bogner Mapping.push_back(CVM.getFileID(Entry)); 182bf42cfd7SJustin Bogner } 183ee02499aSAlex Lorenz } 184ee02499aSAlex Lorenz 185bf42cfd7SJustin Bogner /// \brief Get the coverage mapping file ID for \c Loc. 186bf42cfd7SJustin Bogner /// 187bf42cfd7SJustin Bogner /// If such file id doesn't exist, return None. 188bf42cfd7SJustin Bogner Optional<unsigned> getCoverageFileID(SourceLocation Loc) { 189bf42cfd7SJustin Bogner auto Mapping = FileIDMapping.find(SM.getFileID(Loc)); 190bf42cfd7SJustin Bogner if (Mapping != FileIDMapping.end()) 191bf42cfd7SJustin Bogner return Mapping->second.first; 192903678caSJustin Bogner return None; 193ee02499aSAlex Lorenz } 194ee02499aSAlex Lorenz 195ee02499aSAlex Lorenz /// \brief Return true if the given clang's file id has a corresponding 196ee02499aSAlex Lorenz /// coverage file id. 197ee02499aSAlex Lorenz bool hasExistingCoverageFileID(FileID File) const { 198ee02499aSAlex Lorenz return FileIDMapping.count(File); 199ee02499aSAlex Lorenz } 200ee02499aSAlex Lorenz 201ee02499aSAlex Lorenz /// \brief Gather all the regions that were skipped by the preprocessor 202ee02499aSAlex Lorenz /// using the constructs like #if. 203ee02499aSAlex Lorenz void gatherSkippedRegions() { 204ee02499aSAlex Lorenz /// An array of the minimum lineStarts and the maximum lineEnds 205ee02499aSAlex Lorenz /// for mapping regions from the appropriate source files. 206ee02499aSAlex Lorenz llvm::SmallVector<std::pair<unsigned, unsigned>, 8> FileLineRanges; 207ee02499aSAlex Lorenz FileLineRanges.resize( 208ee02499aSAlex Lorenz FileIDMapping.size(), 209ee02499aSAlex Lorenz std::make_pair(std::numeric_limits<unsigned>::max(), 0)); 210ee02499aSAlex Lorenz for (const auto &R : MappingRegions) { 211ee02499aSAlex Lorenz FileLineRanges[R.FileID].first = 212ee02499aSAlex Lorenz std::min(FileLineRanges[R.FileID].first, R.LineStart); 213ee02499aSAlex Lorenz FileLineRanges[R.FileID].second = 214ee02499aSAlex Lorenz std::max(FileLineRanges[R.FileID].second, R.LineEnd); 215ee02499aSAlex Lorenz } 216ee02499aSAlex Lorenz 217ee02499aSAlex Lorenz auto SkippedRanges = CVM.getSourceInfo().getSkippedRanges(); 218ee02499aSAlex Lorenz for (const auto &I : SkippedRanges) { 219ee02499aSAlex Lorenz auto LocStart = I.getBegin(); 220ee02499aSAlex Lorenz auto LocEnd = I.getEnd(); 221bf42cfd7SJustin Bogner assert(SM.isWrittenInSameFile(LocStart, LocEnd) && 222bf42cfd7SJustin Bogner "region spans multiple files"); 223ee02499aSAlex Lorenz 224bf42cfd7SJustin Bogner auto CovFileID = getCoverageFileID(LocStart); 225903678caSJustin Bogner if (!CovFileID) 226ee02499aSAlex Lorenz continue; 227ee02499aSAlex Lorenz unsigned LineStart = SM.getSpellingLineNumber(LocStart); 228ee02499aSAlex Lorenz unsigned ColumnStart = SM.getSpellingColumnNumber(LocStart); 229ee02499aSAlex Lorenz unsigned LineEnd = SM.getSpellingLineNumber(LocEnd); 230ee02499aSAlex Lorenz unsigned ColumnEnd = SM.getSpellingColumnNumber(LocEnd); 231fd34280bSJustin Bogner auto Region = CounterMappingRegion::makeSkipped( 232fd34280bSJustin Bogner *CovFileID, LineStart, ColumnStart, LineEnd, ColumnEnd); 233ee02499aSAlex Lorenz // Make sure that we only collect the regions that are inside 234ee02499aSAlex Lorenz // the souce code of this function. 235903678caSJustin Bogner if (Region.LineStart >= FileLineRanges[*CovFileID].first && 236903678caSJustin Bogner Region.LineEnd <= FileLineRanges[*CovFileID].second) 237ee02499aSAlex Lorenz MappingRegions.push_back(Region); 238ee02499aSAlex Lorenz } 239ee02499aSAlex Lorenz } 240ee02499aSAlex Lorenz 241ee02499aSAlex Lorenz /// \brief Generate the coverage counter mapping regions from collected 242ee02499aSAlex Lorenz /// source regions. 243ee02499aSAlex Lorenz void emitSourceRegions() { 244bf42cfd7SJustin Bogner for (const auto &Region : SourceRegions) { 245bf42cfd7SJustin Bogner assert(Region.hasEndLoc() && "incomplete region"); 246ee02499aSAlex Lorenz 247bf42cfd7SJustin Bogner SourceLocation LocStart = Region.getStartLoc(); 2488b563665SYaron Keren assert(SM.getFileID(LocStart).isValid() && "region in invalid file"); 249f59329b0SJustin Bogner 250bf42cfd7SJustin Bogner auto CovFileID = getCoverageFileID(LocStart); 251bf42cfd7SJustin Bogner // Ignore regions that don't have a file, such as builtin macros. 252bf42cfd7SJustin Bogner if (!CovFileID) 253ee02499aSAlex Lorenz continue; 254ee02499aSAlex Lorenz 255f14b2078SJustin Bogner SourceLocation LocEnd = Region.getEndLoc(); 256bf42cfd7SJustin Bogner assert(SM.isWrittenInSameFile(LocStart, LocEnd) && 257bf42cfd7SJustin Bogner "region spans multiple files"); 258bf42cfd7SJustin Bogner 259f59329b0SJustin Bogner // Find the spilling locations for the mapping region. 260ee02499aSAlex Lorenz unsigned LineStart = SM.getSpellingLineNumber(LocStart); 261ee02499aSAlex Lorenz unsigned ColumnStart = SM.getSpellingColumnNumber(LocStart); 262ee02499aSAlex Lorenz unsigned LineEnd = SM.getSpellingLineNumber(LocEnd); 263ee02499aSAlex Lorenz unsigned ColumnEnd = SM.getSpellingColumnNumber(LocEnd); 264ee02499aSAlex Lorenz 265bf42cfd7SJustin Bogner assert(LineStart <= LineEnd && "region start and end out of order"); 266bf42cfd7SJustin Bogner MappingRegions.push_back(CounterMappingRegion::makeRegion( 267bf42cfd7SJustin Bogner Region.getCounter(), *CovFileID, LineStart, ColumnStart, LineEnd, 268bf42cfd7SJustin Bogner ColumnEnd)); 269bf42cfd7SJustin Bogner } 270bf42cfd7SJustin Bogner } 271bf42cfd7SJustin Bogner 272bf42cfd7SJustin Bogner /// \brief Generate expansion regions for each virtual file we've seen. 273bf42cfd7SJustin Bogner void emitExpansionRegions() { 274bf42cfd7SJustin Bogner for (const auto &FM : FileIDMapping) { 275bf42cfd7SJustin Bogner SourceLocation ExpandedLoc = FM.second.second; 276bf42cfd7SJustin Bogner SourceLocation ParentLoc = getIncludeOrExpansionLoc(ExpandedLoc); 277bf42cfd7SJustin Bogner if (ParentLoc.isInvalid()) 278ee02499aSAlex Lorenz continue; 279ee02499aSAlex Lorenz 280bf42cfd7SJustin Bogner auto ParentFileID = getCoverageFileID(ParentLoc); 281bf42cfd7SJustin Bogner if (!ParentFileID) 282bf42cfd7SJustin Bogner continue; 283bf42cfd7SJustin Bogner auto ExpandedFileID = getCoverageFileID(ExpandedLoc); 284bf42cfd7SJustin Bogner assert(ExpandedFileID && "expansion in uncovered file"); 285bf42cfd7SJustin Bogner 286bf42cfd7SJustin Bogner SourceLocation LocEnd = getPreciseTokenLocEnd(ParentLoc); 287bf42cfd7SJustin Bogner assert(SM.isWrittenInSameFile(ParentLoc, LocEnd) && 288bf42cfd7SJustin Bogner "region spans multiple files"); 289bf42cfd7SJustin Bogner 290bf42cfd7SJustin Bogner unsigned LineStart = SM.getSpellingLineNumber(ParentLoc); 291bf42cfd7SJustin Bogner unsigned ColumnStart = SM.getSpellingColumnNumber(ParentLoc); 292bf42cfd7SJustin Bogner unsigned LineEnd = SM.getSpellingLineNumber(LocEnd); 293bf42cfd7SJustin Bogner unsigned ColumnEnd = SM.getSpellingColumnNumber(LocEnd); 294bf42cfd7SJustin Bogner 295bf42cfd7SJustin Bogner MappingRegions.push_back(CounterMappingRegion::makeExpansion( 296bf42cfd7SJustin Bogner *ParentFileID, *ExpandedFileID, LineStart, ColumnStart, LineEnd, 297fd34280bSJustin Bogner ColumnEnd)); 298ee02499aSAlex Lorenz } 299ee02499aSAlex Lorenz } 300ee02499aSAlex Lorenz }; 301ee02499aSAlex Lorenz 302ee02499aSAlex Lorenz /// \brief Creates unreachable coverage regions for the functions that 303ee02499aSAlex Lorenz /// are not emitted. 304ee02499aSAlex Lorenz struct EmptyCoverageMappingBuilder : public CoverageMappingBuilder { 305ee02499aSAlex Lorenz EmptyCoverageMappingBuilder(CoverageMappingModuleGen &CVM, SourceManager &SM, 306ee02499aSAlex Lorenz const LangOptions &LangOpts) 307ee02499aSAlex Lorenz : CoverageMappingBuilder(CVM, SM, LangOpts) {} 308ee02499aSAlex Lorenz 309ee02499aSAlex Lorenz void VisitDecl(const Decl *D) { 310ee02499aSAlex Lorenz if (!D->hasBody()) 311ee02499aSAlex Lorenz return; 312ee02499aSAlex Lorenz auto Body = D->getBody(); 313bf42cfd7SJustin Bogner SourceRegions.emplace_back(Counter(), getStart(Body), getEnd(Body)); 314ee02499aSAlex Lorenz } 315ee02499aSAlex Lorenz 316ee02499aSAlex Lorenz /// \brief Write the mapping data to the output stream 317ee02499aSAlex Lorenz void write(llvm::raw_ostream &OS) { 318ee02499aSAlex Lorenz SmallVector<unsigned, 16> FileIDMapping; 319bf42cfd7SJustin Bogner gatherFileIDs(FileIDMapping); 320bf42cfd7SJustin Bogner emitSourceRegions(); 321ee02499aSAlex Lorenz 3225fc8fc2dSCraig Topper CoverageMappingWriter Writer(FileIDMapping, None, MappingRegions); 323ee02499aSAlex Lorenz Writer.write(OS); 324ee02499aSAlex Lorenz } 325ee02499aSAlex Lorenz }; 326ee02499aSAlex Lorenz 327ee02499aSAlex Lorenz /// \brief A StmtVisitor that creates coverage mapping regions which map 328ee02499aSAlex Lorenz /// from the source code locations to the PGO counters. 329ee02499aSAlex Lorenz struct CounterCoverageMappingBuilder 330ee02499aSAlex Lorenz : public CoverageMappingBuilder, 331ee02499aSAlex Lorenz public ConstStmtVisitor<CounterCoverageMappingBuilder> { 332ee02499aSAlex Lorenz /// \brief The map of statements to count values. 333ee02499aSAlex Lorenz llvm::DenseMap<const Stmt *, unsigned> &CounterMap; 334ee02499aSAlex Lorenz 335bf42cfd7SJustin Bogner /// \brief A stack of currently live regions. 336bf42cfd7SJustin Bogner std::vector<SourceMappingRegion> RegionStack; 337ee02499aSAlex Lorenz 338ee02499aSAlex Lorenz CounterExpressionBuilder Builder; 339ee02499aSAlex Lorenz 340bf42cfd7SJustin Bogner /// \brief A location in the most recently visited file or macro. 341bf42cfd7SJustin Bogner /// 342bf42cfd7SJustin Bogner /// This is used to adjust the active source regions appropriately when 343bf42cfd7SJustin Bogner /// expressions cross file or macro boundaries. 344bf42cfd7SJustin Bogner SourceLocation MostRecentLocation; 345bf42cfd7SJustin Bogner 346bf42cfd7SJustin Bogner /// \brief Return a counter for the subtraction of \c RHS from \c LHS 347ee02499aSAlex Lorenz Counter subtractCounters(Counter LHS, Counter RHS) { 348ee02499aSAlex Lorenz return Builder.subtract(LHS, RHS); 349ee02499aSAlex Lorenz } 350ee02499aSAlex Lorenz 351bf42cfd7SJustin Bogner /// \brief Return a counter for the sum of \c LHS and \c RHS. 352ee02499aSAlex Lorenz Counter addCounters(Counter LHS, Counter RHS) { 353ee02499aSAlex Lorenz return Builder.add(LHS, RHS); 354ee02499aSAlex Lorenz } 355ee02499aSAlex Lorenz 356bf42cfd7SJustin Bogner Counter addCounters(Counter C1, Counter C2, Counter C3) { 357bf42cfd7SJustin Bogner return addCounters(addCounters(C1, C2), C3); 358bf42cfd7SJustin Bogner } 359bf42cfd7SJustin Bogner 360bf42cfd7SJustin Bogner Counter addCounters(Counter C1, Counter C2, Counter C3, Counter C4) { 361bf42cfd7SJustin Bogner return addCounters(addCounters(C1, C2, C3), C4); 362bf42cfd7SJustin Bogner } 363bf42cfd7SJustin Bogner 364ee02499aSAlex Lorenz /// \brief Return the region counter for the given statement. 365bf42cfd7SJustin Bogner /// 366ee02499aSAlex Lorenz /// This should only be called on statements that have a dedicated counter. 367bf42cfd7SJustin Bogner Counter getRegionCounter(const Stmt *S) { 368bf42cfd7SJustin Bogner return Counter::getCounter(CounterMap[S]); 369ee02499aSAlex Lorenz } 370ee02499aSAlex Lorenz 371bf42cfd7SJustin Bogner /// \brief Push a region onto the stack. 372bf42cfd7SJustin Bogner /// 373bf42cfd7SJustin Bogner /// Returns the index on the stack where the region was pushed. This can be 374bf42cfd7SJustin Bogner /// used with popRegions to exit a "scope", ending the region that was pushed. 375bf42cfd7SJustin Bogner size_t pushRegion(Counter Count, Optional<SourceLocation> StartLoc = None, 376bf42cfd7SJustin Bogner Optional<SourceLocation> EndLoc = None) { 377bf42cfd7SJustin Bogner if (StartLoc) 378bf42cfd7SJustin Bogner MostRecentLocation = *StartLoc; 379bf42cfd7SJustin Bogner RegionStack.emplace_back(Count, StartLoc, EndLoc); 380ee02499aSAlex Lorenz 381bf42cfd7SJustin Bogner return RegionStack.size() - 1; 382ee02499aSAlex Lorenz } 383ee02499aSAlex Lorenz 384bf42cfd7SJustin Bogner /// \brief Pop regions from the stack into the function's list of regions. 385bf42cfd7SJustin Bogner /// 386bf42cfd7SJustin Bogner /// Adds all regions from \c ParentIndex to the top of the stack to the 387bf42cfd7SJustin Bogner /// function's \c SourceRegions. 388bf42cfd7SJustin Bogner void popRegions(size_t ParentIndex) { 389bf42cfd7SJustin Bogner assert(RegionStack.size() >= ParentIndex && "parent not in stack"); 390bf42cfd7SJustin Bogner while (RegionStack.size() > ParentIndex) { 391bf42cfd7SJustin Bogner SourceMappingRegion &Region = RegionStack.back(); 392bf42cfd7SJustin Bogner if (Region.hasStartLoc()) { 393bf42cfd7SJustin Bogner SourceLocation StartLoc = Region.getStartLoc(); 394bf42cfd7SJustin Bogner SourceLocation EndLoc = Region.hasEndLoc() 395bf42cfd7SJustin Bogner ? Region.getEndLoc() 396bf42cfd7SJustin Bogner : RegionStack[ParentIndex].getEndLoc(); 397bf42cfd7SJustin Bogner while (!SM.isWrittenInSameFile(StartLoc, EndLoc)) { 398bf42cfd7SJustin Bogner // The region ends in a nested file or macro expansion. Create a 399bf42cfd7SJustin Bogner // separate region for each expansion. 400bf42cfd7SJustin Bogner SourceLocation NestedLoc = getStartOfFileOrMacro(EndLoc); 401bf42cfd7SJustin Bogner assert(SM.isWrittenInSameFile(NestedLoc, EndLoc)); 402bf42cfd7SJustin Bogner 403bf42cfd7SJustin Bogner SourceRegions.emplace_back(Region.getCounter(), NestedLoc, EndLoc); 404bf42cfd7SJustin Bogner 405f14b2078SJustin Bogner EndLoc = getPreciseTokenLocEnd(getIncludeOrExpansionLoc(EndLoc)); 406dceaaadfSJustin Bogner if (EndLoc.isInvalid()) 407dceaaadfSJustin Bogner llvm::report_fatal_error("File exit not handled before popRegions"); 408bf42cfd7SJustin Bogner } 409bf42cfd7SJustin Bogner Region.setEndLoc(EndLoc); 410bf42cfd7SJustin Bogner 411bf42cfd7SJustin Bogner MostRecentLocation = EndLoc; 412bf42cfd7SJustin Bogner // If this region happens to span an entire expansion, we need to make 413bf42cfd7SJustin Bogner // sure we don't overlap the parent region with it. 414bf42cfd7SJustin Bogner if (StartLoc == getStartOfFileOrMacro(StartLoc) && 415bf42cfd7SJustin Bogner EndLoc == getEndOfFileOrMacro(EndLoc)) 416bf42cfd7SJustin Bogner MostRecentLocation = getIncludeOrExpansionLoc(EndLoc); 417bf42cfd7SJustin Bogner 418bf42cfd7SJustin Bogner assert(SM.isWrittenInSameFile(Region.getStartLoc(), EndLoc)); 419f36a5c4aSCraig Topper SourceRegions.push_back(Region); 420bf42cfd7SJustin Bogner } 421bf42cfd7SJustin Bogner RegionStack.pop_back(); 422bf42cfd7SJustin Bogner } 423ee02499aSAlex Lorenz } 424ee02499aSAlex Lorenz 425bf42cfd7SJustin Bogner /// \brief Return the currently active region. 426bf42cfd7SJustin Bogner SourceMappingRegion &getRegion() { 427bf42cfd7SJustin Bogner assert(!RegionStack.empty() && "statement has no region"); 428bf42cfd7SJustin Bogner return RegionStack.back(); 429ee02499aSAlex Lorenz } 430ee02499aSAlex Lorenz 431bf42cfd7SJustin Bogner /// \brief Propagate counts through the children of \c S. 432bf42cfd7SJustin Bogner Counter propagateCounts(Counter TopCount, const Stmt *S) { 433bf42cfd7SJustin Bogner size_t Index = pushRegion(TopCount, getStart(S), getEnd(S)); 434bf42cfd7SJustin Bogner Visit(S); 435bf42cfd7SJustin Bogner Counter ExitCount = getRegion().getCounter(); 436bf42cfd7SJustin Bogner popRegions(Index); 43739f01975SVedant Kumar 43839f01975SVedant Kumar // The statement may be spanned by an expansion. Make sure we handle a file 43939f01975SVedant Kumar // exit out of this expansion before moving to the next statement. 44039f01975SVedant Kumar if (SM.isBeforeInTranslationUnit(getStart(S), S->getLocStart())) 44139f01975SVedant Kumar MostRecentLocation = getEnd(S); 44239f01975SVedant Kumar 443bf42cfd7SJustin Bogner return ExitCount; 444ee02499aSAlex Lorenz } 445ee02499aSAlex Lorenz 4460a7c9d11SIgor Kudrin /// \brief Check whether a region with bounds \c StartLoc and \c EndLoc 4470a7c9d11SIgor Kudrin /// is already added to \c SourceRegions. 4480a7c9d11SIgor Kudrin bool isRegionAlreadyAdded(SourceLocation StartLoc, SourceLocation EndLoc) { 4490a7c9d11SIgor Kudrin return SourceRegions.rend() != 4500a7c9d11SIgor Kudrin std::find_if(SourceRegions.rbegin(), SourceRegions.rend(), 4510a7c9d11SIgor Kudrin [&](const SourceMappingRegion &Region) { 4520a7c9d11SIgor Kudrin return Region.getStartLoc() == StartLoc && 4530a7c9d11SIgor Kudrin Region.getEndLoc() == EndLoc; 4540a7c9d11SIgor Kudrin }); 4550a7c9d11SIgor Kudrin } 4560a7c9d11SIgor Kudrin 457bf42cfd7SJustin Bogner /// \brief Adjust the most recently visited location to \c EndLoc. 458bf42cfd7SJustin Bogner /// 459bf42cfd7SJustin Bogner /// This should be used after visiting any statements in non-source order. 460bf42cfd7SJustin Bogner void adjustForOutOfOrderTraversal(SourceLocation EndLoc) { 461bf42cfd7SJustin Bogner MostRecentLocation = EndLoc; 4620a7c9d11SIgor Kudrin // The code region for a whole macro is created in handleFileExit() when 4630a7c9d11SIgor Kudrin // it detects exiting of the virtual file of that macro. If we visited 4640a7c9d11SIgor Kudrin // statements in non-source order, we might already have such a region 4650a7c9d11SIgor Kudrin // added, for example, if a body of a loop is divided among multiple 4660a7c9d11SIgor Kudrin // macros. Avoid adding duplicate regions in such case. 46796ae73f7SJustin Bogner if (getRegion().hasEndLoc() && 4680a7c9d11SIgor Kudrin MostRecentLocation == getEndOfFileOrMacro(MostRecentLocation) && 4690a7c9d11SIgor Kudrin isRegionAlreadyAdded(getStartOfFileOrMacro(MostRecentLocation), 4700a7c9d11SIgor Kudrin MostRecentLocation)) 471bf42cfd7SJustin Bogner MostRecentLocation = getIncludeOrExpansionLoc(MostRecentLocation); 472ee02499aSAlex Lorenz } 473ee02499aSAlex Lorenz 474bf42cfd7SJustin Bogner /// \brief Check whether \c Loc is included or expanded from \c Parent. 475bf42cfd7SJustin Bogner bool isNestedIn(SourceLocation Loc, FileID Parent) { 476bf42cfd7SJustin Bogner do { 477bf42cfd7SJustin Bogner Loc = getIncludeOrExpansionLoc(Loc); 478bf42cfd7SJustin Bogner if (Loc.isInvalid()) 479bf42cfd7SJustin Bogner return false; 480bf42cfd7SJustin Bogner } while (!SM.isInFileID(Loc, Parent)); 481bf42cfd7SJustin Bogner return true; 482ee02499aSAlex Lorenz } 483ee02499aSAlex Lorenz 484bf42cfd7SJustin Bogner /// \brief Adjust regions and state when \c NewLoc exits a file. 485bf42cfd7SJustin Bogner /// 486bf42cfd7SJustin Bogner /// If moving from our most recently tracked location to \c NewLoc exits any 487bf42cfd7SJustin Bogner /// files, this adjusts our current region stack and creates the file regions 488bf42cfd7SJustin Bogner /// for the exited file. 489bf42cfd7SJustin Bogner void handleFileExit(SourceLocation NewLoc) { 490e44dd6dbSJustin Bogner if (NewLoc.isInvalid() || 491e44dd6dbSJustin Bogner SM.isWrittenInSameFile(MostRecentLocation, NewLoc)) 492bf42cfd7SJustin Bogner return; 493bf42cfd7SJustin Bogner 494bf42cfd7SJustin Bogner // If NewLoc is not in a file that contains MostRecentLocation, walk up to 495bf42cfd7SJustin Bogner // find the common ancestor. 496bf42cfd7SJustin Bogner SourceLocation LCA = NewLoc; 497bf42cfd7SJustin Bogner FileID ParentFile = SM.getFileID(LCA); 498bf42cfd7SJustin Bogner while (!isNestedIn(MostRecentLocation, ParentFile)) { 499bf42cfd7SJustin Bogner LCA = getIncludeOrExpansionLoc(LCA); 500bf42cfd7SJustin Bogner if (LCA.isInvalid() || SM.isWrittenInSameFile(LCA, MostRecentLocation)) { 501bf42cfd7SJustin Bogner // Since there isn't a common ancestor, no file was exited. We just need 502bf42cfd7SJustin Bogner // to adjust our location to the new file. 503bf42cfd7SJustin Bogner MostRecentLocation = NewLoc; 504bf42cfd7SJustin Bogner return; 505bf42cfd7SJustin Bogner } 506bf42cfd7SJustin Bogner ParentFile = SM.getFileID(LCA); 507ee02499aSAlex Lorenz } 508ee02499aSAlex Lorenz 509bf42cfd7SJustin Bogner llvm::SmallSet<SourceLocation, 8> StartLocs; 510bf42cfd7SJustin Bogner Optional<Counter> ParentCounter; 51157d3f145SPete Cooper for (SourceMappingRegion &I : llvm::reverse(RegionStack)) { 51257d3f145SPete Cooper if (!I.hasStartLoc()) 513bf42cfd7SJustin Bogner continue; 51457d3f145SPete Cooper SourceLocation Loc = I.getStartLoc(); 515bf42cfd7SJustin Bogner if (!isNestedIn(Loc, ParentFile)) { 51657d3f145SPete Cooper ParentCounter = I.getCounter(); 517bf42cfd7SJustin Bogner break; 518ee02499aSAlex Lorenz } 519bf42cfd7SJustin Bogner 520bf42cfd7SJustin Bogner while (!SM.isInFileID(Loc, ParentFile)) { 521bf42cfd7SJustin Bogner // The most nested region for each start location is the one with the 522bf42cfd7SJustin Bogner // correct count. We avoid creating redundant regions by stopping once 523bf42cfd7SJustin Bogner // we've seen this region. 524bf42cfd7SJustin Bogner if (StartLocs.insert(Loc).second) 52557d3f145SPete Cooper SourceRegions.emplace_back(I.getCounter(), Loc, 526bf42cfd7SJustin Bogner getEndOfFileOrMacro(Loc)); 527bf42cfd7SJustin Bogner Loc = getIncludeOrExpansionLoc(Loc); 528ee02499aSAlex Lorenz } 52957d3f145SPete Cooper I.setStartLoc(getPreciseTokenLocEnd(Loc)); 530bf42cfd7SJustin Bogner } 531bf42cfd7SJustin Bogner 532bf42cfd7SJustin Bogner if (ParentCounter) { 533bf42cfd7SJustin Bogner // If the file is contained completely by another region and doesn't 534bf42cfd7SJustin Bogner // immediately start its own region, the whole file gets a region 535bf42cfd7SJustin Bogner // corresponding to the parent. 536bf42cfd7SJustin Bogner SourceLocation Loc = MostRecentLocation; 537bf42cfd7SJustin Bogner while (isNestedIn(Loc, ParentFile)) { 538bf42cfd7SJustin Bogner SourceLocation FileStart = getStartOfFileOrMacro(Loc); 539bf42cfd7SJustin Bogner if (StartLocs.insert(FileStart).second) 540bf42cfd7SJustin Bogner SourceRegions.emplace_back(*ParentCounter, FileStart, 541bf42cfd7SJustin Bogner getEndOfFileOrMacro(Loc)); 542bf42cfd7SJustin Bogner Loc = getIncludeOrExpansionLoc(Loc); 543bf42cfd7SJustin Bogner } 544bf42cfd7SJustin Bogner } 545bf42cfd7SJustin Bogner 546bf42cfd7SJustin Bogner MostRecentLocation = NewLoc; 547bf42cfd7SJustin Bogner } 548bf42cfd7SJustin Bogner 549bf42cfd7SJustin Bogner /// \brief Ensure that \c S is included in the current region. 550bf42cfd7SJustin Bogner void extendRegion(const Stmt *S) { 551bf42cfd7SJustin Bogner SourceMappingRegion &Region = getRegion(); 552bf42cfd7SJustin Bogner SourceLocation StartLoc = getStart(S); 553bf42cfd7SJustin Bogner 554bf42cfd7SJustin Bogner handleFileExit(StartLoc); 555bf42cfd7SJustin Bogner if (!Region.hasStartLoc()) 556bf42cfd7SJustin Bogner Region.setStartLoc(StartLoc); 557bf42cfd7SJustin Bogner } 558bf42cfd7SJustin Bogner 559bf42cfd7SJustin Bogner /// \brief Mark \c S as a terminator, starting a zero region. 560bf42cfd7SJustin Bogner void terminateRegion(const Stmt *S) { 561bf42cfd7SJustin Bogner extendRegion(S); 562bf42cfd7SJustin Bogner SourceMappingRegion &Region = getRegion(); 563bf42cfd7SJustin Bogner if (!Region.hasEndLoc()) 564bf42cfd7SJustin Bogner Region.setEndLoc(getEnd(S)); 565bf42cfd7SJustin Bogner pushRegion(Counter::getZero()); 566bf42cfd7SJustin Bogner } 567ee02499aSAlex Lorenz 568ee02499aSAlex Lorenz /// \brief Keep counts of breaks and continues inside loops. 569ee02499aSAlex Lorenz struct BreakContinue { 570ee02499aSAlex Lorenz Counter BreakCount; 571ee02499aSAlex Lorenz Counter ContinueCount; 572ee02499aSAlex Lorenz }; 573ee02499aSAlex Lorenz SmallVector<BreakContinue, 8> BreakContinueStack; 574ee02499aSAlex Lorenz 575ee02499aSAlex Lorenz CounterCoverageMappingBuilder( 576ee02499aSAlex Lorenz CoverageMappingModuleGen &CVM, 577e5ee6c58SJustin Bogner llvm::DenseMap<const Stmt *, unsigned> &CounterMap, SourceManager &SM, 578ee02499aSAlex Lorenz const LangOptions &LangOpts) 579e5ee6c58SJustin Bogner : CoverageMappingBuilder(CVM, SM, LangOpts), CounterMap(CounterMap) {} 580ee02499aSAlex Lorenz 581ee02499aSAlex Lorenz /// \brief Write the mapping data to the output stream 582ee02499aSAlex Lorenz void write(llvm::raw_ostream &OS) { 583ee02499aSAlex Lorenz llvm::SmallVector<unsigned, 8> VirtualFileMapping; 584bf42cfd7SJustin Bogner gatherFileIDs(VirtualFileMapping); 585bf42cfd7SJustin Bogner emitSourceRegions(); 586bf42cfd7SJustin Bogner emitExpansionRegions(); 587ee02499aSAlex Lorenz gatherSkippedRegions(); 588ee02499aSAlex Lorenz 5894da909b2SJustin Bogner CoverageMappingWriter Writer(VirtualFileMapping, Builder.getExpressions(), 5904da909b2SJustin Bogner MappingRegions); 591ee02499aSAlex Lorenz Writer.write(OS); 592ee02499aSAlex Lorenz } 593ee02499aSAlex Lorenz 594ee02499aSAlex Lorenz void VisitStmt(const Stmt *S) { 595ed1fe5d0SYaron Keren if (S->getLocStart().isValid()) 596bf42cfd7SJustin Bogner extendRegion(S); 597642f173aSBenjamin Kramer for (const Stmt *Child : S->children()) 598642f173aSBenjamin Kramer if (Child) 599642f173aSBenjamin Kramer this->Visit(Child); 600bf42cfd7SJustin Bogner handleFileExit(getEnd(S)); 601ee02499aSAlex Lorenz } 602ee02499aSAlex Lorenz 603ee02499aSAlex Lorenz void VisitDecl(const Decl *D) { 604bf42cfd7SJustin Bogner Stmt *Body = D->getBody(); 605bf42cfd7SJustin Bogner propagateCounts(getRegionCounter(Body), Body); 606ee02499aSAlex Lorenz } 607ee02499aSAlex Lorenz 608ee02499aSAlex Lorenz void VisitReturnStmt(const ReturnStmt *S) { 609bf42cfd7SJustin Bogner extendRegion(S); 610ee02499aSAlex Lorenz if (S->getRetValue()) 611ee02499aSAlex Lorenz Visit(S->getRetValue()); 612bf42cfd7SJustin Bogner terminateRegion(S); 613ee02499aSAlex Lorenz } 614ee02499aSAlex Lorenz 615f959febfSJustin Bogner void VisitCXXThrowExpr(const CXXThrowExpr *E) { 616f959febfSJustin Bogner extendRegion(E); 617f959febfSJustin Bogner if (E->getSubExpr()) 618f959febfSJustin Bogner Visit(E->getSubExpr()); 619f959febfSJustin Bogner terminateRegion(E); 620f959febfSJustin Bogner } 621f959febfSJustin Bogner 622bf42cfd7SJustin Bogner void VisitGotoStmt(const GotoStmt *S) { terminateRegion(S); } 623ee02499aSAlex Lorenz 624ee02499aSAlex Lorenz void VisitLabelStmt(const LabelStmt *S) { 625bf42cfd7SJustin Bogner SourceLocation Start = getStart(S); 626bf42cfd7SJustin Bogner // We can't extendRegion here or we risk overlapping with our new region. 627bf42cfd7SJustin Bogner handleFileExit(Start); 628bf42cfd7SJustin Bogner pushRegion(getRegionCounter(S), Start); 629ee02499aSAlex Lorenz Visit(S->getSubStmt()); 630ee02499aSAlex Lorenz } 631ee02499aSAlex Lorenz 632ee02499aSAlex Lorenz void VisitBreakStmt(const BreakStmt *S) { 633ee02499aSAlex Lorenz assert(!BreakContinueStack.empty() && "break not in a loop or switch!"); 634ee02499aSAlex Lorenz BreakContinueStack.back().BreakCount = addCounters( 635bf42cfd7SJustin Bogner BreakContinueStack.back().BreakCount, getRegion().getCounter()); 636bf42cfd7SJustin Bogner terminateRegion(S); 637ee02499aSAlex Lorenz } 638ee02499aSAlex Lorenz 639ee02499aSAlex Lorenz void VisitContinueStmt(const ContinueStmt *S) { 640ee02499aSAlex Lorenz assert(!BreakContinueStack.empty() && "continue stmt not in a loop!"); 641ee02499aSAlex Lorenz BreakContinueStack.back().ContinueCount = addCounters( 642bf42cfd7SJustin Bogner BreakContinueStack.back().ContinueCount, getRegion().getCounter()); 643bf42cfd7SJustin Bogner terminateRegion(S); 644ee02499aSAlex Lorenz } 645ee02499aSAlex Lorenz 646ee02499aSAlex Lorenz void VisitWhileStmt(const WhileStmt *S) { 647bf42cfd7SJustin Bogner extendRegion(S); 648ee02499aSAlex Lorenz 649bf42cfd7SJustin Bogner Counter ParentCount = getRegion().getCounter(); 650bf42cfd7SJustin Bogner Counter BodyCount = getRegionCounter(S); 651bf42cfd7SJustin Bogner 652bf42cfd7SJustin Bogner // Handle the body first so that we can get the backedge count. 653bf42cfd7SJustin Bogner BreakContinueStack.push_back(BreakContinue()); 654bf42cfd7SJustin Bogner extendRegion(S->getBody()); 655bf42cfd7SJustin Bogner Counter BackedgeCount = propagateCounts(BodyCount, S->getBody()); 656ee02499aSAlex Lorenz BreakContinue BC = BreakContinueStack.pop_back_val(); 657bf42cfd7SJustin Bogner 658bf42cfd7SJustin Bogner // Go back to handle the condition. 659bf42cfd7SJustin Bogner Counter CondCount = 660bf42cfd7SJustin Bogner addCounters(ParentCount, BackedgeCount, BC.ContinueCount); 661bf42cfd7SJustin Bogner propagateCounts(CondCount, S->getCond()); 662bf42cfd7SJustin Bogner adjustForOutOfOrderTraversal(getEnd(S)); 663bf42cfd7SJustin Bogner 664bf42cfd7SJustin Bogner Counter OutCount = 665bf42cfd7SJustin Bogner addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount)); 666bf42cfd7SJustin Bogner if (OutCount != ParentCount) 667bf42cfd7SJustin Bogner pushRegion(OutCount); 668ee02499aSAlex Lorenz } 669ee02499aSAlex Lorenz 670ee02499aSAlex Lorenz void VisitDoStmt(const DoStmt *S) { 671bf42cfd7SJustin Bogner extendRegion(S); 672ee02499aSAlex Lorenz 673bf42cfd7SJustin Bogner Counter ParentCount = getRegion().getCounter(); 674bf42cfd7SJustin Bogner Counter BodyCount = getRegionCounter(S); 675bf42cfd7SJustin Bogner 676bf42cfd7SJustin Bogner BreakContinueStack.push_back(BreakContinue()); 677bf42cfd7SJustin Bogner extendRegion(S->getBody()); 678bf42cfd7SJustin Bogner Counter BackedgeCount = 679bf42cfd7SJustin Bogner propagateCounts(addCounters(ParentCount, BodyCount), S->getBody()); 680ee02499aSAlex Lorenz BreakContinue BC = BreakContinueStack.pop_back_val(); 681bf42cfd7SJustin Bogner 682bf42cfd7SJustin Bogner Counter CondCount = addCounters(BackedgeCount, BC.ContinueCount); 683bf42cfd7SJustin Bogner propagateCounts(CondCount, S->getCond()); 684bf42cfd7SJustin Bogner 685bf42cfd7SJustin Bogner Counter OutCount = 686bf42cfd7SJustin Bogner addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount)); 687bf42cfd7SJustin Bogner if (OutCount != ParentCount) 688bf42cfd7SJustin Bogner pushRegion(OutCount); 689ee02499aSAlex Lorenz } 690ee02499aSAlex Lorenz 691ee02499aSAlex Lorenz void VisitForStmt(const ForStmt *S) { 692bf42cfd7SJustin Bogner extendRegion(S); 693ee02499aSAlex Lorenz if (S->getInit()) 694ee02499aSAlex Lorenz Visit(S->getInit()); 695ee02499aSAlex Lorenz 696bf42cfd7SJustin Bogner Counter ParentCount = getRegion().getCounter(); 697bf42cfd7SJustin Bogner Counter BodyCount = getRegionCounter(S); 698bf42cfd7SJustin Bogner 699bf42cfd7SJustin Bogner // Handle the body first so that we can get the backedge count. 700ee02499aSAlex Lorenz BreakContinueStack.push_back(BreakContinue()); 701bf42cfd7SJustin Bogner extendRegion(S->getBody()); 702bf42cfd7SJustin Bogner Counter BackedgeCount = propagateCounts(BodyCount, S->getBody()); 703bf42cfd7SJustin Bogner BreakContinue BC = BreakContinueStack.pop_back_val(); 704ee02499aSAlex Lorenz 705ee02499aSAlex Lorenz // The increment is essentially part of the body but it needs to include 706ee02499aSAlex Lorenz // the count for all the continue statements. 707bf42cfd7SJustin Bogner if (const Stmt *Inc = S->getInc()) 708bf42cfd7SJustin Bogner propagateCounts(addCounters(BackedgeCount, BC.ContinueCount), Inc); 709bf42cfd7SJustin Bogner 710bf42cfd7SJustin Bogner // Go back to handle the condition. 711bf42cfd7SJustin Bogner Counter CondCount = 712bf42cfd7SJustin Bogner addCounters(ParentCount, BackedgeCount, BC.ContinueCount); 713bf42cfd7SJustin Bogner if (const Expr *Cond = S->getCond()) { 714bf42cfd7SJustin Bogner propagateCounts(CondCount, Cond); 715bf42cfd7SJustin Bogner adjustForOutOfOrderTraversal(getEnd(S)); 716ee02499aSAlex Lorenz } 717ee02499aSAlex Lorenz 718bf42cfd7SJustin Bogner Counter OutCount = 719bf42cfd7SJustin Bogner addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount)); 720bf42cfd7SJustin Bogner if (OutCount != ParentCount) 721bf42cfd7SJustin Bogner pushRegion(OutCount); 722ee02499aSAlex Lorenz } 723ee02499aSAlex Lorenz 724ee02499aSAlex Lorenz void VisitCXXForRangeStmt(const CXXForRangeStmt *S) { 725bf42cfd7SJustin Bogner extendRegion(S); 726bf42cfd7SJustin Bogner Visit(S->getLoopVarStmt()); 727ee02499aSAlex Lorenz Visit(S->getRangeStmt()); 728bf42cfd7SJustin Bogner 729bf42cfd7SJustin Bogner Counter ParentCount = getRegion().getCounter(); 730bf42cfd7SJustin Bogner Counter BodyCount = getRegionCounter(S); 731bf42cfd7SJustin Bogner 732ee02499aSAlex Lorenz BreakContinueStack.push_back(BreakContinue()); 733bf42cfd7SJustin Bogner extendRegion(S->getBody()); 734bf42cfd7SJustin Bogner Counter BackedgeCount = propagateCounts(BodyCount, S->getBody()); 735ee02499aSAlex Lorenz BreakContinue BC = BreakContinueStack.pop_back_val(); 736bf42cfd7SJustin Bogner 7371587432dSJustin Bogner Counter LoopCount = 7381587432dSJustin Bogner addCounters(ParentCount, BackedgeCount, BC.ContinueCount); 7391587432dSJustin Bogner Counter OutCount = 7401587432dSJustin Bogner addCounters(BC.BreakCount, subtractCounters(LoopCount, BodyCount)); 741bf42cfd7SJustin Bogner if (OutCount != ParentCount) 742bf42cfd7SJustin Bogner pushRegion(OutCount); 743ee02499aSAlex Lorenz } 744ee02499aSAlex Lorenz 745ee02499aSAlex Lorenz void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) { 746bf42cfd7SJustin Bogner extendRegion(S); 747ee02499aSAlex Lorenz Visit(S->getElement()); 748bf42cfd7SJustin Bogner 749bf42cfd7SJustin Bogner Counter ParentCount = getRegion().getCounter(); 750bf42cfd7SJustin Bogner Counter BodyCount = getRegionCounter(S); 751bf42cfd7SJustin Bogner 752ee02499aSAlex Lorenz BreakContinueStack.push_back(BreakContinue()); 753bf42cfd7SJustin Bogner extendRegion(S->getBody()); 754bf42cfd7SJustin Bogner Counter BackedgeCount = propagateCounts(BodyCount, S->getBody()); 755ee02499aSAlex Lorenz BreakContinue BC = BreakContinueStack.pop_back_val(); 756bf42cfd7SJustin Bogner 7571587432dSJustin Bogner Counter LoopCount = 7581587432dSJustin Bogner addCounters(ParentCount, BackedgeCount, BC.ContinueCount); 7591587432dSJustin Bogner Counter OutCount = 7601587432dSJustin Bogner addCounters(BC.BreakCount, subtractCounters(LoopCount, BodyCount)); 761bf42cfd7SJustin Bogner if (OutCount != ParentCount) 762bf42cfd7SJustin Bogner pushRegion(OutCount); 763ee02499aSAlex Lorenz } 764ee02499aSAlex Lorenz 765ee02499aSAlex Lorenz void VisitSwitchStmt(const SwitchStmt *S) { 766bf42cfd7SJustin Bogner extendRegion(S); 767ee02499aSAlex Lorenz Visit(S->getCond()); 768bf42cfd7SJustin Bogner 769ee02499aSAlex Lorenz BreakContinueStack.push_back(BreakContinue()); 770bf42cfd7SJustin Bogner 771bf42cfd7SJustin Bogner const Stmt *Body = S->getBody(); 772bf42cfd7SJustin Bogner extendRegion(Body); 773bf42cfd7SJustin Bogner if (const auto *CS = dyn_cast<CompoundStmt>(Body)) { 774bf42cfd7SJustin Bogner if (!CS->body_empty()) { 775bf42cfd7SJustin Bogner // The body of the switch needs a zero region so that fallthrough counts 776bf42cfd7SJustin Bogner // behave correctly, but it would be misleading to include the braces of 777bf42cfd7SJustin Bogner // the compound statement in the zeroed area, so we need to handle this 778bf42cfd7SJustin Bogner // specially. 779bf42cfd7SJustin Bogner size_t Index = 780bf42cfd7SJustin Bogner pushRegion(Counter::getZero(), getStart(CS->body_front()), 781bf42cfd7SJustin Bogner getEnd(CS->body_back())); 782b5841332SRichard Trieu for (const auto *Child : CS->children()) 783bf42cfd7SJustin Bogner Visit(Child); 784bf42cfd7SJustin Bogner popRegions(Index); 785ee02499aSAlex Lorenz } 786*87ea3b05SVedant Kumar } else 787bf42cfd7SJustin Bogner propagateCounts(Counter::getZero(), Body); 788ee02499aSAlex Lorenz BreakContinue BC = BreakContinueStack.pop_back_val(); 789bf42cfd7SJustin Bogner 790ee02499aSAlex Lorenz if (!BreakContinueStack.empty()) 791ee02499aSAlex Lorenz BreakContinueStack.back().ContinueCount = addCounters( 792ee02499aSAlex Lorenz BreakContinueStack.back().ContinueCount, BC.ContinueCount); 793bf42cfd7SJustin Bogner 794bf42cfd7SJustin Bogner Counter ExitCount = getRegionCounter(S); 7953836482aSVedant Kumar SourceLocation ExitLoc = getEnd(S); 7963836482aSVedant Kumar pushRegion(ExitCount, getStart(S), ExitLoc); 7973836482aSVedant Kumar handleFileExit(ExitLoc); 798ee02499aSAlex Lorenz } 799ee02499aSAlex Lorenz 800bf42cfd7SJustin Bogner void VisitSwitchCase(const SwitchCase *S) { 801bf42cfd7SJustin Bogner extendRegion(S); 802ee02499aSAlex Lorenz 803bf42cfd7SJustin Bogner SourceMappingRegion &Parent = getRegion(); 804bf42cfd7SJustin Bogner 805bf42cfd7SJustin Bogner Counter Count = addCounters(Parent.getCounter(), getRegionCounter(S)); 806bf42cfd7SJustin Bogner // Reuse the existing region if it starts at our label. This is typical of 807bf42cfd7SJustin Bogner // the first case in a switch. 808bf42cfd7SJustin Bogner if (Parent.hasStartLoc() && Parent.getStartLoc() == getStart(S)) 809bf42cfd7SJustin Bogner Parent.setCounter(Count); 810bf42cfd7SJustin Bogner else 811bf42cfd7SJustin Bogner pushRegion(Count, getStart(S)); 812bf42cfd7SJustin Bogner 813376c06c2SSanjay Patel if (const auto *CS = dyn_cast<CaseStmt>(S)) { 814bf42cfd7SJustin Bogner Visit(CS->getLHS()); 815bf42cfd7SJustin Bogner if (const Expr *RHS = CS->getRHS()) 816bf42cfd7SJustin Bogner Visit(RHS); 817bf42cfd7SJustin Bogner } 818ee02499aSAlex Lorenz Visit(S->getSubStmt()); 819ee02499aSAlex Lorenz } 820ee02499aSAlex Lorenz 821ee02499aSAlex Lorenz void VisitIfStmt(const IfStmt *S) { 822bf42cfd7SJustin Bogner extendRegion(S); 823055ebc34SJustin Bogner // Extend into the condition before we propagate through it below - this is 824055ebc34SJustin Bogner // needed to handle macros that generate the "if" but not the condition. 825055ebc34SJustin Bogner extendRegion(S->getCond()); 826ee02499aSAlex Lorenz 827bf42cfd7SJustin Bogner Counter ParentCount = getRegion().getCounter(); 828bf42cfd7SJustin Bogner Counter ThenCount = getRegionCounter(S); 829ee02499aSAlex Lorenz 83091f2e3c9SJustin Bogner // Emitting a counter for the condition makes it easier to interpret the 83191f2e3c9SJustin Bogner // counter for the body when looking at the coverage. 83291f2e3c9SJustin Bogner propagateCounts(ParentCount, S->getCond()); 83391f2e3c9SJustin Bogner 834bf42cfd7SJustin Bogner extendRegion(S->getThen()); 835bf42cfd7SJustin Bogner Counter OutCount = propagateCounts(ThenCount, S->getThen()); 836bf42cfd7SJustin Bogner 837bf42cfd7SJustin Bogner Counter ElseCount = subtractCounters(ParentCount, ThenCount); 838bf42cfd7SJustin Bogner if (const Stmt *Else = S->getElse()) { 839bf42cfd7SJustin Bogner extendRegion(S->getElse()); 840bf42cfd7SJustin Bogner OutCount = addCounters(OutCount, propagateCounts(ElseCount, Else)); 841bf42cfd7SJustin Bogner } else 842bf42cfd7SJustin Bogner OutCount = addCounters(OutCount, ElseCount); 843bf42cfd7SJustin Bogner 844bf42cfd7SJustin Bogner if (OutCount != ParentCount) 845bf42cfd7SJustin Bogner pushRegion(OutCount); 846ee02499aSAlex Lorenz } 847ee02499aSAlex Lorenz 848ee02499aSAlex Lorenz void VisitCXXTryStmt(const CXXTryStmt *S) { 849bf42cfd7SJustin Bogner extendRegion(S); 850ee02499aSAlex Lorenz Visit(S->getTryBlock()); 851ee02499aSAlex Lorenz for (unsigned I = 0, E = S->getNumHandlers(); I < E; ++I) 852ee02499aSAlex Lorenz Visit(S->getHandler(I)); 853bf42cfd7SJustin Bogner 854bf42cfd7SJustin Bogner Counter ExitCount = getRegionCounter(S); 855bf42cfd7SJustin Bogner pushRegion(ExitCount); 856ee02499aSAlex Lorenz } 857ee02499aSAlex Lorenz 858ee02499aSAlex Lorenz void VisitCXXCatchStmt(const CXXCatchStmt *S) { 859bf42cfd7SJustin Bogner propagateCounts(getRegionCounter(S), S->getHandlerBlock()); 860ee02499aSAlex Lorenz } 861ee02499aSAlex Lorenz 862ee02499aSAlex Lorenz void VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) { 863bf42cfd7SJustin Bogner extendRegion(E); 864ee02499aSAlex Lorenz 865bf42cfd7SJustin Bogner Counter ParentCount = getRegion().getCounter(); 866bf42cfd7SJustin Bogner Counter TrueCount = getRegionCounter(E); 867ee02499aSAlex Lorenz 868e3654ce7SJustin Bogner Visit(E->getCond()); 869e3654ce7SJustin Bogner 870e3654ce7SJustin Bogner if (!isa<BinaryConditionalOperator>(E)) { 871e3654ce7SJustin Bogner extendRegion(E->getTrueExpr()); 872bf42cfd7SJustin Bogner propagateCounts(TrueCount, E->getTrueExpr()); 873e3654ce7SJustin Bogner } 874e3654ce7SJustin Bogner extendRegion(E->getFalseExpr()); 875bf42cfd7SJustin Bogner propagateCounts(subtractCounters(ParentCount, TrueCount), 876bf42cfd7SJustin Bogner E->getFalseExpr()); 877ee02499aSAlex Lorenz } 878ee02499aSAlex Lorenz 879ee02499aSAlex Lorenz void VisitBinLAnd(const BinaryOperator *E) { 880bf42cfd7SJustin Bogner extendRegion(E); 881ee02499aSAlex Lorenz Visit(E->getLHS()); 882bf42cfd7SJustin Bogner 883bf42cfd7SJustin Bogner extendRegion(E->getRHS()); 884bf42cfd7SJustin Bogner propagateCounts(getRegionCounter(E), E->getRHS()); 885ee02499aSAlex Lorenz } 886ee02499aSAlex Lorenz 887ee02499aSAlex Lorenz void VisitBinLOr(const BinaryOperator *E) { 888bf42cfd7SJustin Bogner extendRegion(E); 889ee02499aSAlex Lorenz Visit(E->getLHS()); 890ee02499aSAlex Lorenz 891bf42cfd7SJustin Bogner extendRegion(E->getRHS()); 892bf42cfd7SJustin Bogner propagateCounts(getRegionCounter(E), E->getRHS()); 89301a0d062SAlex Lorenz } 894c109102eSJustin Bogner 895c109102eSJustin Bogner void VisitLambdaExpr(const LambdaExpr *LE) { 896c109102eSJustin Bogner // Lambdas are treated as their own functions for now, so we shouldn't 897c109102eSJustin Bogner // propagate counts into them. 898c109102eSJustin Bogner } 899ee02499aSAlex Lorenz }; 900ab9db510SAlexander Kornienko } 901ee02499aSAlex Lorenz 902ee02499aSAlex Lorenz static bool isMachO(const CodeGenModule &CGM) { 903ee02499aSAlex Lorenz return CGM.getTarget().getTriple().isOSBinFormatMachO(); 904ee02499aSAlex Lorenz } 905ee02499aSAlex Lorenz 906ee02499aSAlex Lorenz static StringRef getCoverageSection(const CodeGenModule &CGM) { 90703711cbdSXinliang David Li return llvm::getInstrProfCoverageSectionName(isMachO(CGM)); 908ee02499aSAlex Lorenz } 909ee02499aSAlex Lorenz 910a432d176SJustin Bogner static void dump(llvm::raw_ostream &OS, StringRef FunctionName, 911a432d176SJustin Bogner ArrayRef<CounterExpression> Expressions, 912a432d176SJustin Bogner ArrayRef<CounterMappingRegion> Regions) { 913a432d176SJustin Bogner OS << FunctionName << ":\n"; 914a432d176SJustin Bogner CounterMappingContext Ctx(Expressions); 915a432d176SJustin Bogner for (const auto &R : Regions) { 916f2cf38e0SAlex Lorenz OS.indent(2); 917f2cf38e0SAlex Lorenz switch (R.Kind) { 918f2cf38e0SAlex Lorenz case CounterMappingRegion::CodeRegion: 919f2cf38e0SAlex Lorenz break; 920f2cf38e0SAlex Lorenz case CounterMappingRegion::ExpansionRegion: 921f2cf38e0SAlex Lorenz OS << "Expansion,"; 922f2cf38e0SAlex Lorenz break; 923f2cf38e0SAlex Lorenz case CounterMappingRegion::SkippedRegion: 924f2cf38e0SAlex Lorenz OS << "Skipped,"; 925f2cf38e0SAlex Lorenz break; 926f2cf38e0SAlex Lorenz } 927f2cf38e0SAlex Lorenz 9284da909b2SJustin Bogner OS << "File " << R.FileID << ", " << R.LineStart << ":" << R.ColumnStart 9294da909b2SJustin Bogner << " -> " << R.LineEnd << ":" << R.ColumnEnd << " = "; 930f69dc349SJustin Bogner Ctx.dump(R.Count, OS); 931f2cf38e0SAlex Lorenz if (R.Kind == CounterMappingRegion::ExpansionRegion) 9324da909b2SJustin Bogner OS << " (Expanded file = " << R.ExpandedFileID << ")"; 9334da909b2SJustin Bogner OS << "\n"; 934f2cf38e0SAlex Lorenz } 935f2cf38e0SAlex Lorenz } 936f2cf38e0SAlex Lorenz 937ee02499aSAlex Lorenz void CoverageMappingModuleGen::addFunctionMappingRecord( 9382129ae53SXinliang David Li llvm::GlobalVariable *NamePtr, StringRef NameValue, uint64_t FuncHash, 939848da137SXinliang David Li const std::string &CoverageMapping, bool IsUsed) { 940ee02499aSAlex Lorenz llvm::LLVMContext &Ctx = CGM.getLLVMContext(); 941ee02499aSAlex Lorenz if (!FunctionRecordTy) { 942a026a437SXinliang David Li #define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) LLVMType, 943a026a437SXinliang David Li llvm::Type *FunctionRecordTypes[] = { 944a026a437SXinliang David Li #include "llvm/ProfileData/InstrProfData.inc" 945a026a437SXinliang David Li }; 946ee02499aSAlex Lorenz FunctionRecordTy = 9474dc5adc7SJustin Bogner llvm::StructType::get(Ctx, makeArrayRef(FunctionRecordTypes), 9484dc5adc7SJustin Bogner /*isPacked=*/true); 949ee02499aSAlex Lorenz } 950ee02499aSAlex Lorenz 951a026a437SXinliang David Li #define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) Init, 952ee02499aSAlex Lorenz llvm::Constant *FunctionRecordVals[] = { 953a026a437SXinliang David Li #include "llvm/ProfileData/InstrProfData.inc" 954a026a437SXinliang David Li }; 955ee02499aSAlex Lorenz FunctionRecords.push_back(llvm::ConstantStruct::get( 956ee02499aSAlex Lorenz FunctionRecordTy, makeArrayRef(FunctionRecordVals))); 957848da137SXinliang David Li if (!IsUsed) 9582129ae53SXinliang David Li FunctionNames.push_back( 9592129ae53SXinliang David Li llvm::ConstantExpr::getBitCast(NamePtr, llvm::Type::getInt8PtrTy(Ctx))); 960ca3326c0SVedant Kumar CoverageMappings.push_back(CoverageMapping); 961f2cf38e0SAlex Lorenz 962f2cf38e0SAlex Lorenz if (CGM.getCodeGenOpts().DumpCoverageMapping) { 963f2cf38e0SAlex Lorenz // Dump the coverage mapping data for this function by decoding the 964f2cf38e0SAlex Lorenz // encoded data. This allows us to dump the mapping regions which were 965f2cf38e0SAlex Lorenz // also processed by the CoverageMappingWriter which performs 966f2cf38e0SAlex Lorenz // additional minimization operations such as reducing the number of 967f2cf38e0SAlex Lorenz // expressions. 968f2cf38e0SAlex Lorenz std::vector<StringRef> Filenames; 969f2cf38e0SAlex Lorenz std::vector<CounterExpression> Expressions; 970f2cf38e0SAlex Lorenz std::vector<CounterMappingRegion> Regions; 971f2cf38e0SAlex Lorenz llvm::SmallVector<StringRef, 16> FilenameRefs; 972f2cf38e0SAlex Lorenz FilenameRefs.resize(FileEntries.size()); 973f2cf38e0SAlex Lorenz for (const auto &Entry : FileEntries) 974f2cf38e0SAlex Lorenz FilenameRefs[Entry.second] = Entry.first->getName(); 975a432d176SJustin Bogner RawCoverageMappingReader Reader(CoverageMapping, FilenameRefs, Filenames, 976a432d176SJustin Bogner Expressions, Regions); 977a432d176SJustin Bogner if (Reader.read()) 978f2cf38e0SAlex Lorenz return; 979a026a437SXinliang David Li dump(llvm::outs(), NameValue, Expressions, Regions); 980f2cf38e0SAlex Lorenz } 981ee02499aSAlex Lorenz } 982ee02499aSAlex Lorenz 983ee02499aSAlex Lorenz void CoverageMappingModuleGen::emit() { 984ee02499aSAlex Lorenz if (FunctionRecords.empty()) 985ee02499aSAlex Lorenz return; 986ee02499aSAlex Lorenz llvm::LLVMContext &Ctx = CGM.getLLVMContext(); 987ee02499aSAlex Lorenz auto *Int32Ty = llvm::Type::getInt32Ty(Ctx); 988ee02499aSAlex Lorenz 989ee02499aSAlex Lorenz // Create the filenames and merge them with coverage mappings 990ee02499aSAlex Lorenz llvm::SmallVector<std::string, 16> FilenameStrs; 991ee02499aSAlex Lorenz llvm::SmallVector<StringRef, 16> FilenameRefs; 992ee02499aSAlex Lorenz FilenameStrs.resize(FileEntries.size()); 993ee02499aSAlex Lorenz FilenameRefs.resize(FileEntries.size()); 994ee02499aSAlex Lorenz for (const auto &Entry : FileEntries) { 995ee02499aSAlex Lorenz llvm::SmallString<256> Path(Entry.first->getName()); 996ee02499aSAlex Lorenz llvm::sys::fs::make_absolute(Path); 997ee02499aSAlex Lorenz 998ee02499aSAlex Lorenz auto I = Entry.second; 999d1ffdda4SRichard Trieu FilenameStrs[I] = std::string(Path.begin(), Path.end()); 1000ee02499aSAlex Lorenz FilenameRefs[I] = FilenameStrs[I]; 1001ee02499aSAlex Lorenz } 1002ee02499aSAlex Lorenz 1003ee02499aSAlex Lorenz std::string FilenamesAndCoverageMappings; 1004ee02499aSAlex Lorenz llvm::raw_string_ostream OS(FilenamesAndCoverageMappings); 1005ee02499aSAlex Lorenz CoverageFilenamesSectionWriter(FilenameRefs).write(OS); 1006ca3326c0SVedant Kumar std::string RawCoverageMappings = 1007ca3326c0SVedant Kumar llvm::join(CoverageMappings.begin(), CoverageMappings.end(), ""); 1008ca3326c0SVedant Kumar OS << RawCoverageMappings; 1009ca3326c0SVedant Kumar size_t CoverageMappingSize = RawCoverageMappings.size(); 1010ee02499aSAlex Lorenz size_t FilenamesSize = OS.str().size() - CoverageMappingSize; 1011ee02499aSAlex Lorenz // Append extra zeroes if necessary to ensure that the size of the filenames 1012ee02499aSAlex Lorenz // and coverage mappings is a multiple of 8. 1013ee02499aSAlex Lorenz if (size_t Rem = OS.str().size() % 8) { 1014ee02499aSAlex Lorenz CoverageMappingSize += 8 - Rem; 1015ee02499aSAlex Lorenz for (size_t I = 0, S = 8 - Rem; I < S; ++I) 1016ee02499aSAlex Lorenz OS << '\0'; 1017ee02499aSAlex Lorenz } 1018ee02499aSAlex Lorenz auto *FilenamesAndMappingsVal = 1019ee02499aSAlex Lorenz llvm::ConstantDataArray::getString(Ctx, OS.str(), false); 1020ee02499aSAlex Lorenz 1021ee02499aSAlex Lorenz // Create the deferred function records array 1022ee02499aSAlex Lorenz auto RecordsTy = 1023ee02499aSAlex Lorenz llvm::ArrayType::get(FunctionRecordTy, FunctionRecords.size()); 1024ee02499aSAlex Lorenz auto RecordsVal = llvm::ConstantArray::get(RecordsTy, FunctionRecords); 1025ee02499aSAlex Lorenz 102620b188c0SXinliang David Li llvm::Type *CovDataHeaderTypes[] = { 102720b188c0SXinliang David Li #define COVMAP_HEADER(Type, LLVMType, Name, Init) LLVMType, 102820b188c0SXinliang David Li #include "llvm/ProfileData/InstrProfData.inc" 102920b188c0SXinliang David Li }; 103020b188c0SXinliang David Li auto CovDataHeaderTy = 103120b188c0SXinliang David Li llvm::StructType::get(Ctx, makeArrayRef(CovDataHeaderTypes)); 103220b188c0SXinliang David Li llvm::Constant *CovDataHeaderVals[] = { 103320b188c0SXinliang David Li #define COVMAP_HEADER(Type, LLVMType, Name, Init) Init, 103420b188c0SXinliang David Li #include "llvm/ProfileData/InstrProfData.inc" 103520b188c0SXinliang David Li }; 103620b188c0SXinliang David Li auto CovDataHeaderVal = llvm::ConstantStruct::get( 103720b188c0SXinliang David Li CovDataHeaderTy, makeArrayRef(CovDataHeaderVals)); 103820b188c0SXinliang David Li 1039ee02499aSAlex Lorenz // Create the coverage data record 104020b188c0SXinliang David Li llvm::Type *CovDataTypes[] = {CovDataHeaderTy, RecordsTy, 104120b188c0SXinliang David Li FilenamesAndMappingsVal->getType()}; 1042ee02499aSAlex Lorenz auto CovDataTy = llvm::StructType::get(Ctx, makeArrayRef(CovDataTypes)); 104320b188c0SXinliang David Li llvm::Constant *TUDataVals[] = {CovDataHeaderVal, RecordsVal, 104420b188c0SXinliang David Li FilenamesAndMappingsVal}; 1045ee02499aSAlex Lorenz auto CovDataVal = 1046ee02499aSAlex Lorenz llvm::ConstantStruct::get(CovDataTy, makeArrayRef(TUDataVals)); 104720b188c0SXinliang David Li auto CovData = new llvm::GlobalVariable( 104820b188c0SXinliang David Li CGM.getModule(), CovDataTy, true, llvm::GlobalValue::InternalLinkage, 104920b188c0SXinliang David Li CovDataVal, llvm::getCoverageMappingVarName()); 1050ee02499aSAlex Lorenz 1051ee02499aSAlex Lorenz CovData->setSection(getCoverageSection(CGM)); 1052ee02499aSAlex Lorenz CovData->setAlignment(8); 1053ee02499aSAlex Lorenz 1054ee02499aSAlex Lorenz // Make sure the data doesn't get deleted. 1055ee02499aSAlex Lorenz CGM.addUsedGlobal(CovData); 10562129ae53SXinliang David Li // Create the deferred function records array 10572129ae53SXinliang David Li if (!FunctionNames.empty()) { 10582129ae53SXinliang David Li auto NamesArrTy = llvm::ArrayType::get(llvm::Type::getInt8PtrTy(Ctx), 10592129ae53SXinliang David Li FunctionNames.size()); 10602129ae53SXinliang David Li auto NamesArrVal = llvm::ConstantArray::get(NamesArrTy, FunctionNames); 10612129ae53SXinliang David Li // This variable will *NOT* be emitted to the object file. It is used 10622129ae53SXinliang David Li // to pass the list of names referenced to codegen. 10632129ae53SXinliang David Li new llvm::GlobalVariable(CGM.getModule(), NamesArrTy, true, 10642129ae53SXinliang David Li llvm::GlobalValue::InternalLinkage, NamesArrVal, 10657077f0afSXinliang David Li llvm::getCoverageUnusedNamesVarName()); 10662129ae53SXinliang David Li } 1067ee02499aSAlex Lorenz } 1068ee02499aSAlex Lorenz 1069ee02499aSAlex Lorenz unsigned CoverageMappingModuleGen::getFileID(const FileEntry *File) { 1070ee02499aSAlex Lorenz auto It = FileEntries.find(File); 1071ee02499aSAlex Lorenz if (It != FileEntries.end()) 1072ee02499aSAlex Lorenz return It->second; 1073ee02499aSAlex Lorenz unsigned FileID = FileEntries.size(); 1074ee02499aSAlex Lorenz FileEntries.insert(std::make_pair(File, FileID)); 1075ee02499aSAlex Lorenz return FileID; 1076ee02499aSAlex Lorenz } 1077ee02499aSAlex Lorenz 1078ee02499aSAlex Lorenz void CoverageMappingGen::emitCounterMapping(const Decl *D, 1079ee02499aSAlex Lorenz llvm::raw_ostream &OS) { 1080ee02499aSAlex Lorenz assert(CounterMap); 1081e5ee6c58SJustin Bogner CounterCoverageMappingBuilder Walker(CVM, *CounterMap, SM, LangOpts); 1082ee02499aSAlex Lorenz Walker.VisitDecl(D); 1083ee02499aSAlex Lorenz Walker.write(OS); 1084ee02499aSAlex Lorenz } 1085ee02499aSAlex Lorenz 1086ee02499aSAlex Lorenz void CoverageMappingGen::emitEmptyMapping(const Decl *D, 1087ee02499aSAlex Lorenz llvm::raw_ostream &OS) { 1088ee02499aSAlex Lorenz EmptyCoverageMappingBuilder Walker(CVM, SM, LangOpts); 1089ee02499aSAlex Lorenz Walker.VisitDecl(D); 1090ee02499aSAlex Lorenz Walker.write(OS); 1091ee02499aSAlex Lorenz } 1092