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" 2614f8fb68SVedant Kumar #include "llvm/Support/Path.h" 27ee02499aSAlex Lorenz 28ee02499aSAlex Lorenz using namespace clang; 29ee02499aSAlex Lorenz using namespace CodeGen; 30ee02499aSAlex Lorenz using namespace llvm::coverage; 31ee02499aSAlex Lorenz 32ee02499aSAlex Lorenz void CoverageSourceInfo::SourceRangeSkipped(SourceRange Range) { 33ee02499aSAlex Lorenz SkippedRanges.push_back(Range); 34ee02499aSAlex Lorenz } 35ee02499aSAlex Lorenz 36ee02499aSAlex Lorenz namespace { 37ee02499aSAlex Lorenz 38ee02499aSAlex Lorenz /// \brief A region of source code that can be mapped to a counter. 3909c7179bSJustin Bogner class SourceMappingRegion { 40ee02499aSAlex Lorenz Counter Count; 41ee02499aSAlex Lorenz 42ee02499aSAlex Lorenz /// \brief The region's starting location. 43bf42cfd7SJustin Bogner Optional<SourceLocation> LocStart; 44ee02499aSAlex Lorenz 45ee02499aSAlex Lorenz /// \brief The region's ending location. 46bf42cfd7SJustin Bogner Optional<SourceLocation> LocEnd; 47ee02499aSAlex Lorenz 4809c7179bSJustin Bogner public: 49bf42cfd7SJustin Bogner SourceMappingRegion(Counter Count, Optional<SourceLocation> LocStart, 50bf42cfd7SJustin Bogner Optional<SourceLocation> LocEnd) 51bf42cfd7SJustin Bogner : Count(Count), LocStart(LocStart), LocEnd(LocEnd) {} 52ee02499aSAlex Lorenz 5309c7179bSJustin Bogner const Counter &getCounter() const { return Count; } 5409c7179bSJustin Bogner 55bf42cfd7SJustin Bogner void setCounter(Counter C) { Count = C; } 5609c7179bSJustin Bogner 57bf42cfd7SJustin Bogner bool hasStartLoc() const { return LocStart.hasValue(); } 58bf42cfd7SJustin Bogner 59bf42cfd7SJustin Bogner void setStartLoc(SourceLocation Loc) { LocStart = Loc; } 60bf42cfd7SJustin Bogner 61462c77b4SCraig Topper SourceLocation getStartLoc() const { 62bf42cfd7SJustin Bogner assert(LocStart && "Region has no start location"); 63bf42cfd7SJustin Bogner return *LocStart; 6409c7179bSJustin Bogner } 6509c7179bSJustin Bogner 66bf42cfd7SJustin Bogner bool hasEndLoc() const { return LocEnd.hasValue(); } 67ee02499aSAlex Lorenz 68bf42cfd7SJustin Bogner void setEndLoc(SourceLocation Loc) { LocEnd = Loc; } 69ee02499aSAlex Lorenz 70462c77b4SCraig Topper SourceLocation getEndLoc() const { 71bf42cfd7SJustin Bogner assert(LocEnd && "Region has no end location"); 72bf42cfd7SJustin Bogner return *LocEnd; 73ee02499aSAlex Lorenz } 74ee02499aSAlex Lorenz }; 75ee02499aSAlex Lorenz 76ee02499aSAlex Lorenz /// \brief Provides the common functionality for the different 77ee02499aSAlex Lorenz /// coverage mapping region builders. 78ee02499aSAlex Lorenz class CoverageMappingBuilder { 79ee02499aSAlex Lorenz public: 80ee02499aSAlex Lorenz CoverageMappingModuleGen &CVM; 81ee02499aSAlex Lorenz SourceManager &SM; 82ee02499aSAlex Lorenz const LangOptions &LangOpts; 83ee02499aSAlex Lorenz 84ee02499aSAlex Lorenz private: 85bf42cfd7SJustin Bogner /// \brief Map of clang's FileIDs to IDs used for coverage mapping. 86bf42cfd7SJustin Bogner llvm::SmallDenseMap<FileID, std::pair<unsigned, SourceLocation>, 8> 87bf42cfd7SJustin Bogner FileIDMapping; 88ee02499aSAlex Lorenz 89ee02499aSAlex Lorenz public: 90ee02499aSAlex Lorenz /// \brief The coverage mapping regions for this function 91ee02499aSAlex Lorenz llvm::SmallVector<CounterMappingRegion, 32> MappingRegions; 92ee02499aSAlex Lorenz /// \brief The source mapping regions for this function. 93f59329b0SJustin Bogner std::vector<SourceMappingRegion> SourceRegions; 94ee02499aSAlex Lorenz 95ee02499aSAlex Lorenz CoverageMappingBuilder(CoverageMappingModuleGen &CVM, SourceManager &SM, 96ee02499aSAlex Lorenz const LangOptions &LangOpts) 97bf42cfd7SJustin Bogner : CVM(CVM), SM(SM), LangOpts(LangOpts) {} 98ee02499aSAlex Lorenz 99ee02499aSAlex Lorenz /// \brief Return the precise end location for the given token. 100ee02499aSAlex Lorenz SourceLocation getPreciseTokenLocEnd(SourceLocation Loc) { 101bf42cfd7SJustin Bogner // We avoid getLocForEndOfToken here, because it doesn't do what we want for 102bf42cfd7SJustin Bogner // macro locations, which we just treat as expanded files. 103bf42cfd7SJustin Bogner unsigned TokLen = 104bf42cfd7SJustin Bogner Lexer::MeasureTokenLength(SM.getSpellingLoc(Loc), SM, LangOpts); 105bf42cfd7SJustin Bogner return Loc.getLocWithOffset(TokLen); 106ee02499aSAlex Lorenz } 107ee02499aSAlex Lorenz 108bf42cfd7SJustin Bogner /// \brief Return the start location of an included file or expanded macro. 109bf42cfd7SJustin Bogner SourceLocation getStartOfFileOrMacro(SourceLocation Loc) { 110bf42cfd7SJustin Bogner if (Loc.isMacroID()) 111bf42cfd7SJustin Bogner return Loc.getLocWithOffset(-SM.getFileOffset(Loc)); 112bf42cfd7SJustin Bogner return SM.getLocForStartOfFile(SM.getFileID(Loc)); 113ee02499aSAlex Lorenz } 114ee02499aSAlex Lorenz 115bf42cfd7SJustin Bogner /// \brief Return the end location of an included file or expanded macro. 116bf42cfd7SJustin Bogner SourceLocation getEndOfFileOrMacro(SourceLocation Loc) { 117bf42cfd7SJustin Bogner if (Loc.isMacroID()) 118bf42cfd7SJustin Bogner return Loc.getLocWithOffset(SM.getFileIDSize(SM.getFileID(Loc)) - 119f14b2078SJustin Bogner SM.getFileOffset(Loc)); 120bf42cfd7SJustin Bogner return SM.getLocForEndOfFile(SM.getFileID(Loc)); 121bf42cfd7SJustin Bogner } 122ee02499aSAlex Lorenz 123bf42cfd7SJustin Bogner /// \brief Find out where the current file is included or macro is expanded. 124bf42cfd7SJustin Bogner SourceLocation getIncludeOrExpansionLoc(SourceLocation Loc) { 125bf42cfd7SJustin Bogner return Loc.isMacroID() ? SM.getImmediateExpansionRange(Loc).first 126bf42cfd7SJustin Bogner : SM.getIncludeLoc(SM.getFileID(Loc)); 127bf42cfd7SJustin Bogner } 128bf42cfd7SJustin Bogner 129682bfbf3SJustin Bogner /// \brief Return true if \c Loc is a location in a built-in macro. 130682bfbf3SJustin Bogner bool isInBuiltin(SourceLocation Loc) { 131682bfbf3SJustin Bogner return strcmp(SM.getBufferName(SM.getSpellingLoc(Loc)), "<built-in>") == 0; 132682bfbf3SJustin Bogner } 133682bfbf3SJustin Bogner 134d9e1a61dSIgor Kudrin /// \brief Check whether \c Loc is included or expanded from \c Parent. 135d9e1a61dSIgor Kudrin bool isNestedIn(SourceLocation Loc, FileID Parent) { 136d9e1a61dSIgor Kudrin do { 137d9e1a61dSIgor Kudrin Loc = getIncludeOrExpansionLoc(Loc); 138d9e1a61dSIgor Kudrin if (Loc.isInvalid()) 139d9e1a61dSIgor Kudrin return false; 140d9e1a61dSIgor Kudrin } while (!SM.isInFileID(Loc, Parent)); 141d9e1a61dSIgor Kudrin return true; 142d9e1a61dSIgor Kudrin } 143d9e1a61dSIgor Kudrin 144682bfbf3SJustin Bogner /// \brief Get the start of \c S ignoring macro arguments and builtin macros. 145bf42cfd7SJustin Bogner SourceLocation getStart(const Stmt *S) { 146bf42cfd7SJustin Bogner SourceLocation Loc = S->getLocStart(); 147682bfbf3SJustin Bogner while (SM.isMacroArgExpansion(Loc) || isInBuiltin(Loc)) 148bf42cfd7SJustin Bogner Loc = SM.getImmediateExpansionRange(Loc).first; 149bf42cfd7SJustin Bogner return Loc; 150bf42cfd7SJustin Bogner } 151bf42cfd7SJustin Bogner 152682bfbf3SJustin Bogner /// \brief Get the end of \c S ignoring macro arguments and builtin macros. 153bf42cfd7SJustin Bogner SourceLocation getEnd(const Stmt *S) { 154bf42cfd7SJustin Bogner SourceLocation Loc = S->getLocEnd(); 155682bfbf3SJustin Bogner while (SM.isMacroArgExpansion(Loc) || isInBuiltin(Loc)) 156bf42cfd7SJustin Bogner Loc = SM.getImmediateExpansionRange(Loc).first; 157f14b2078SJustin Bogner return getPreciseTokenLocEnd(Loc); 158bf42cfd7SJustin Bogner } 159bf42cfd7SJustin Bogner 160bf42cfd7SJustin Bogner /// \brief Find the set of files we have regions for and assign IDs 161bf42cfd7SJustin Bogner /// 162bf42cfd7SJustin Bogner /// Fills \c Mapping with the virtual file mapping needed to write out 163bf42cfd7SJustin Bogner /// coverage and collects the necessary file information to emit source and 164bf42cfd7SJustin Bogner /// expansion regions. 165bf42cfd7SJustin Bogner void gatherFileIDs(SmallVectorImpl<unsigned> &Mapping) { 166bf42cfd7SJustin Bogner FileIDMapping.clear(); 167bf42cfd7SJustin Bogner 168bc6b80a0SVedant Kumar llvm::SmallSet<FileID, 8> Visited; 169bf42cfd7SJustin Bogner SmallVector<std::pair<SourceLocation, unsigned>, 8> FileLocs; 170bf42cfd7SJustin Bogner for (const auto &Region : SourceRegions) { 171bf42cfd7SJustin Bogner SourceLocation Loc = Region.getStartLoc(); 172bf42cfd7SJustin Bogner FileID File = SM.getFileID(Loc); 173bc6b80a0SVedant Kumar if (!Visited.insert(File).second) 174bf42cfd7SJustin Bogner continue; 175bf42cfd7SJustin Bogner 17693205af0SVedant Kumar // Do not map FileID's associated with system headers. 17793205af0SVedant Kumar if (SM.isInSystemHeader(SM.getSpellingLoc(Loc))) 17893205af0SVedant Kumar continue; 17993205af0SVedant Kumar 180bf42cfd7SJustin Bogner unsigned Depth = 0; 181bf42cfd7SJustin Bogner for (SourceLocation Parent = getIncludeOrExpansionLoc(Loc); 182ed1fe5d0SYaron Keren Parent.isValid(); Parent = getIncludeOrExpansionLoc(Parent)) 183bf42cfd7SJustin Bogner ++Depth; 184bf42cfd7SJustin Bogner FileLocs.push_back(std::make_pair(Loc, Depth)); 185bf42cfd7SJustin Bogner } 186bf42cfd7SJustin Bogner std::stable_sort(FileLocs.begin(), FileLocs.end(), llvm::less_second()); 187bf42cfd7SJustin Bogner 188bf42cfd7SJustin Bogner for (const auto &FL : FileLocs) { 189bf42cfd7SJustin Bogner SourceLocation Loc = FL.first; 190bf42cfd7SJustin Bogner FileID SpellingFile = SM.getDecomposedSpellingLoc(Loc).first; 191ee02499aSAlex Lorenz auto Entry = SM.getFileEntryForID(SpellingFile); 192ee02499aSAlex Lorenz if (!Entry) 193bf42cfd7SJustin Bogner continue; 194ee02499aSAlex Lorenz 195bf42cfd7SJustin Bogner FileIDMapping[SM.getFileID(Loc)] = std::make_pair(Mapping.size(), Loc); 196bf42cfd7SJustin Bogner Mapping.push_back(CVM.getFileID(Entry)); 197bf42cfd7SJustin Bogner } 198ee02499aSAlex Lorenz } 199ee02499aSAlex Lorenz 200bf42cfd7SJustin Bogner /// \brief Get the coverage mapping file ID for \c Loc. 201bf42cfd7SJustin Bogner /// 202bf42cfd7SJustin Bogner /// If such file id doesn't exist, return None. 203bf42cfd7SJustin Bogner Optional<unsigned> getCoverageFileID(SourceLocation Loc) { 204bf42cfd7SJustin Bogner auto Mapping = FileIDMapping.find(SM.getFileID(Loc)); 205bf42cfd7SJustin Bogner if (Mapping != FileIDMapping.end()) 206bf42cfd7SJustin Bogner return Mapping->second.first; 207903678caSJustin Bogner return None; 208ee02499aSAlex Lorenz } 209ee02499aSAlex Lorenz 210ee02499aSAlex Lorenz /// \brief Gather all the regions that were skipped by the preprocessor 211ee02499aSAlex Lorenz /// using the constructs like #if. 212ee02499aSAlex Lorenz void gatherSkippedRegions() { 213ee02499aSAlex Lorenz /// An array of the minimum lineStarts and the maximum lineEnds 214ee02499aSAlex Lorenz /// for mapping regions from the appropriate source files. 215ee02499aSAlex Lorenz llvm::SmallVector<std::pair<unsigned, unsigned>, 8> FileLineRanges; 216ee02499aSAlex Lorenz FileLineRanges.resize( 217ee02499aSAlex Lorenz FileIDMapping.size(), 218ee02499aSAlex Lorenz std::make_pair(std::numeric_limits<unsigned>::max(), 0)); 219ee02499aSAlex Lorenz for (const auto &R : MappingRegions) { 220ee02499aSAlex Lorenz FileLineRanges[R.FileID].first = 221ee02499aSAlex Lorenz std::min(FileLineRanges[R.FileID].first, R.LineStart); 222ee02499aSAlex Lorenz FileLineRanges[R.FileID].second = 223ee02499aSAlex Lorenz std::max(FileLineRanges[R.FileID].second, R.LineEnd); 224ee02499aSAlex Lorenz } 225ee02499aSAlex Lorenz 226ee02499aSAlex Lorenz auto SkippedRanges = CVM.getSourceInfo().getSkippedRanges(); 227ee02499aSAlex Lorenz for (const auto &I : SkippedRanges) { 228ee02499aSAlex Lorenz auto LocStart = I.getBegin(); 229ee02499aSAlex Lorenz auto LocEnd = I.getEnd(); 230bf42cfd7SJustin Bogner assert(SM.isWrittenInSameFile(LocStart, LocEnd) && 231bf42cfd7SJustin Bogner "region spans multiple files"); 232ee02499aSAlex Lorenz 233bf42cfd7SJustin Bogner auto CovFileID = getCoverageFileID(LocStart); 234903678caSJustin Bogner if (!CovFileID) 235ee02499aSAlex Lorenz continue; 236ee02499aSAlex Lorenz unsigned LineStart = SM.getSpellingLineNumber(LocStart); 237ee02499aSAlex Lorenz unsigned ColumnStart = SM.getSpellingColumnNumber(LocStart); 238ee02499aSAlex Lorenz unsigned LineEnd = SM.getSpellingLineNumber(LocEnd); 239ee02499aSAlex Lorenz unsigned ColumnEnd = SM.getSpellingColumnNumber(LocEnd); 240fd34280bSJustin Bogner auto Region = CounterMappingRegion::makeSkipped( 241fd34280bSJustin Bogner *CovFileID, LineStart, ColumnStart, LineEnd, ColumnEnd); 242ee02499aSAlex Lorenz // Make sure that we only collect the regions that are inside 243ee02499aSAlex Lorenz // the souce code of this function. 244903678caSJustin Bogner if (Region.LineStart >= FileLineRanges[*CovFileID].first && 245903678caSJustin Bogner Region.LineEnd <= FileLineRanges[*CovFileID].second) 246ee02499aSAlex Lorenz MappingRegions.push_back(Region); 247ee02499aSAlex Lorenz } 248ee02499aSAlex Lorenz } 249ee02499aSAlex Lorenz 250ee02499aSAlex Lorenz /// \brief Generate the coverage counter mapping regions from collected 251ee02499aSAlex Lorenz /// source regions. 252ee02499aSAlex Lorenz void emitSourceRegions() { 253bf42cfd7SJustin Bogner for (const auto &Region : SourceRegions) { 254bf42cfd7SJustin Bogner assert(Region.hasEndLoc() && "incomplete region"); 255ee02499aSAlex Lorenz 256bf42cfd7SJustin Bogner SourceLocation LocStart = Region.getStartLoc(); 2578b563665SYaron Keren assert(SM.getFileID(LocStart).isValid() && "region in invalid file"); 258f59329b0SJustin Bogner 25993205af0SVedant Kumar // Ignore regions from system headers. 26093205af0SVedant Kumar if (SM.isInSystemHeader(SM.getSpellingLoc(LocStart))) 26193205af0SVedant Kumar continue; 26293205af0SVedant Kumar 263bf42cfd7SJustin Bogner auto CovFileID = getCoverageFileID(LocStart); 264bf42cfd7SJustin Bogner // Ignore regions that don't have a file, such as builtin macros. 265bf42cfd7SJustin Bogner if (!CovFileID) 266ee02499aSAlex Lorenz continue; 267ee02499aSAlex Lorenz 268f14b2078SJustin Bogner SourceLocation LocEnd = Region.getEndLoc(); 269bf42cfd7SJustin Bogner assert(SM.isWrittenInSameFile(LocStart, LocEnd) && 270bf42cfd7SJustin Bogner "region spans multiple files"); 271bf42cfd7SJustin Bogner 272f59329b0SJustin Bogner // Find the spilling locations for the mapping region. 273ee02499aSAlex Lorenz unsigned LineStart = SM.getSpellingLineNumber(LocStart); 274ee02499aSAlex Lorenz unsigned ColumnStart = SM.getSpellingColumnNumber(LocStart); 275ee02499aSAlex Lorenz unsigned LineEnd = SM.getSpellingLineNumber(LocEnd); 276ee02499aSAlex Lorenz unsigned ColumnEnd = SM.getSpellingColumnNumber(LocEnd); 277ee02499aSAlex Lorenz 278bf42cfd7SJustin Bogner assert(LineStart <= LineEnd && "region start and end out of order"); 279bf42cfd7SJustin Bogner MappingRegions.push_back(CounterMappingRegion::makeRegion( 280bf42cfd7SJustin Bogner Region.getCounter(), *CovFileID, LineStart, ColumnStart, LineEnd, 281bf42cfd7SJustin Bogner ColumnEnd)); 282bf42cfd7SJustin Bogner } 283bf42cfd7SJustin Bogner } 284bf42cfd7SJustin Bogner 285bf42cfd7SJustin Bogner /// \brief Generate expansion regions for each virtual file we've seen. 286bf42cfd7SJustin Bogner void emitExpansionRegions() { 287bf42cfd7SJustin Bogner for (const auto &FM : FileIDMapping) { 288bf42cfd7SJustin Bogner SourceLocation ExpandedLoc = FM.second.second; 289bf42cfd7SJustin Bogner SourceLocation ParentLoc = getIncludeOrExpansionLoc(ExpandedLoc); 290bf42cfd7SJustin Bogner if (ParentLoc.isInvalid()) 291ee02499aSAlex Lorenz continue; 292ee02499aSAlex Lorenz 293bf42cfd7SJustin Bogner auto ParentFileID = getCoverageFileID(ParentLoc); 294bf42cfd7SJustin Bogner if (!ParentFileID) 295bf42cfd7SJustin Bogner continue; 296bf42cfd7SJustin Bogner auto ExpandedFileID = getCoverageFileID(ExpandedLoc); 297bf42cfd7SJustin Bogner assert(ExpandedFileID && "expansion in uncovered file"); 298bf42cfd7SJustin Bogner 299bf42cfd7SJustin Bogner SourceLocation LocEnd = getPreciseTokenLocEnd(ParentLoc); 300bf42cfd7SJustin Bogner assert(SM.isWrittenInSameFile(ParentLoc, LocEnd) && 301bf42cfd7SJustin Bogner "region spans multiple files"); 302bf42cfd7SJustin Bogner 303bf42cfd7SJustin Bogner unsigned LineStart = SM.getSpellingLineNumber(ParentLoc); 304bf42cfd7SJustin Bogner unsigned ColumnStart = SM.getSpellingColumnNumber(ParentLoc); 305bf42cfd7SJustin Bogner unsigned LineEnd = SM.getSpellingLineNumber(LocEnd); 306bf42cfd7SJustin Bogner unsigned ColumnEnd = SM.getSpellingColumnNumber(LocEnd); 307bf42cfd7SJustin Bogner 308bf42cfd7SJustin Bogner MappingRegions.push_back(CounterMappingRegion::makeExpansion( 309bf42cfd7SJustin Bogner *ParentFileID, *ExpandedFileID, LineStart, ColumnStart, LineEnd, 310fd34280bSJustin Bogner ColumnEnd)); 311ee02499aSAlex Lorenz } 312ee02499aSAlex Lorenz } 313ee02499aSAlex Lorenz }; 314ee02499aSAlex Lorenz 315ee02499aSAlex Lorenz /// \brief Creates unreachable coverage regions for the functions that 316ee02499aSAlex Lorenz /// are not emitted. 317ee02499aSAlex Lorenz struct EmptyCoverageMappingBuilder : public CoverageMappingBuilder { 318ee02499aSAlex Lorenz EmptyCoverageMappingBuilder(CoverageMappingModuleGen &CVM, SourceManager &SM, 319ee02499aSAlex Lorenz const LangOptions &LangOpts) 320ee02499aSAlex Lorenz : CoverageMappingBuilder(CVM, SM, LangOpts) {} 321ee02499aSAlex Lorenz 322ee02499aSAlex Lorenz void VisitDecl(const Decl *D) { 323ee02499aSAlex Lorenz if (!D->hasBody()) 324ee02499aSAlex Lorenz return; 325ee02499aSAlex Lorenz auto Body = D->getBody(); 326d9e1a61dSIgor Kudrin SourceLocation Start = getStart(Body); 327d9e1a61dSIgor Kudrin SourceLocation End = getEnd(Body); 328d9e1a61dSIgor Kudrin if (!SM.isWrittenInSameFile(Start, End)) { 329d9e1a61dSIgor Kudrin // Walk up to find the common ancestor. 330d9e1a61dSIgor Kudrin // Correct the locations accordingly. 331d9e1a61dSIgor Kudrin FileID StartFileID = SM.getFileID(Start); 332d9e1a61dSIgor Kudrin FileID EndFileID = SM.getFileID(End); 333d9e1a61dSIgor Kudrin while (StartFileID != EndFileID && !isNestedIn(End, StartFileID)) { 334d9e1a61dSIgor Kudrin Start = getIncludeOrExpansionLoc(Start); 335d9e1a61dSIgor Kudrin assert(Start.isValid() && 336d9e1a61dSIgor Kudrin "Declaration start location not nested within a known region"); 337d9e1a61dSIgor Kudrin StartFileID = SM.getFileID(Start); 338d9e1a61dSIgor Kudrin } 339d9e1a61dSIgor Kudrin while (StartFileID != EndFileID) { 340d9e1a61dSIgor Kudrin End = getPreciseTokenLocEnd(getIncludeOrExpansionLoc(End)); 341d9e1a61dSIgor Kudrin assert(End.isValid() && 342d9e1a61dSIgor Kudrin "Declaration end location not nested within a known region"); 343d9e1a61dSIgor Kudrin EndFileID = SM.getFileID(End); 344d9e1a61dSIgor Kudrin } 345d9e1a61dSIgor Kudrin } 346d9e1a61dSIgor Kudrin SourceRegions.emplace_back(Counter(), Start, End); 347ee02499aSAlex Lorenz } 348ee02499aSAlex Lorenz 349ee02499aSAlex Lorenz /// \brief Write the mapping data to the output stream 350ee02499aSAlex Lorenz void write(llvm::raw_ostream &OS) { 351ee02499aSAlex Lorenz SmallVector<unsigned, 16> FileIDMapping; 352bf42cfd7SJustin Bogner gatherFileIDs(FileIDMapping); 353bf42cfd7SJustin Bogner emitSourceRegions(); 354ee02499aSAlex Lorenz 355efd319a2SVedant Kumar if (MappingRegions.empty()) 356efd319a2SVedant Kumar return; 357efd319a2SVedant Kumar 3585fc8fc2dSCraig Topper CoverageMappingWriter Writer(FileIDMapping, None, MappingRegions); 359ee02499aSAlex Lorenz Writer.write(OS); 360ee02499aSAlex Lorenz } 361ee02499aSAlex Lorenz }; 362ee02499aSAlex Lorenz 363ee02499aSAlex Lorenz /// \brief A StmtVisitor that creates coverage mapping regions which map 364ee02499aSAlex Lorenz /// from the source code locations to the PGO counters. 365ee02499aSAlex Lorenz struct CounterCoverageMappingBuilder 366ee02499aSAlex Lorenz : public CoverageMappingBuilder, 367ee02499aSAlex Lorenz public ConstStmtVisitor<CounterCoverageMappingBuilder> { 368ee02499aSAlex Lorenz /// \brief The map of statements to count values. 369ee02499aSAlex Lorenz llvm::DenseMap<const Stmt *, unsigned> &CounterMap; 370ee02499aSAlex Lorenz 371bf42cfd7SJustin Bogner /// \brief A stack of currently live regions. 372bf42cfd7SJustin Bogner std::vector<SourceMappingRegion> RegionStack; 373ee02499aSAlex Lorenz 374ee02499aSAlex Lorenz CounterExpressionBuilder Builder; 375ee02499aSAlex Lorenz 376bf42cfd7SJustin Bogner /// \brief A location in the most recently visited file or macro. 377bf42cfd7SJustin Bogner /// 378bf42cfd7SJustin Bogner /// This is used to adjust the active source regions appropriately when 379bf42cfd7SJustin Bogner /// expressions cross file or macro boundaries. 380bf42cfd7SJustin Bogner SourceLocation MostRecentLocation; 381bf42cfd7SJustin Bogner 382bf42cfd7SJustin Bogner /// \brief Return a counter for the subtraction of \c RHS from \c LHS 383ee02499aSAlex Lorenz Counter subtractCounters(Counter LHS, Counter RHS) { 384ee02499aSAlex Lorenz return Builder.subtract(LHS, RHS); 385ee02499aSAlex Lorenz } 386ee02499aSAlex Lorenz 387bf42cfd7SJustin Bogner /// \brief Return a counter for the sum of \c LHS and \c RHS. 388ee02499aSAlex Lorenz Counter addCounters(Counter LHS, Counter RHS) { 389ee02499aSAlex Lorenz return Builder.add(LHS, RHS); 390ee02499aSAlex Lorenz } 391ee02499aSAlex Lorenz 392bf42cfd7SJustin Bogner Counter addCounters(Counter C1, Counter C2, Counter C3) { 393bf42cfd7SJustin Bogner return addCounters(addCounters(C1, C2), C3); 394bf42cfd7SJustin Bogner } 395bf42cfd7SJustin Bogner 396ee02499aSAlex Lorenz /// \brief Return the region counter for the given statement. 397bf42cfd7SJustin Bogner /// 398ee02499aSAlex Lorenz /// This should only be called on statements that have a dedicated counter. 399bf42cfd7SJustin Bogner Counter getRegionCounter(const Stmt *S) { 400bf42cfd7SJustin Bogner return Counter::getCounter(CounterMap[S]); 401ee02499aSAlex Lorenz } 402ee02499aSAlex Lorenz 403bf42cfd7SJustin Bogner /// \brief Push a region onto the stack. 404bf42cfd7SJustin Bogner /// 405bf42cfd7SJustin Bogner /// Returns the index on the stack where the region was pushed. This can be 406bf42cfd7SJustin Bogner /// used with popRegions to exit a "scope", ending the region that was pushed. 407bf42cfd7SJustin Bogner size_t pushRegion(Counter Count, Optional<SourceLocation> StartLoc = None, 408bf42cfd7SJustin Bogner Optional<SourceLocation> EndLoc = None) { 409bf42cfd7SJustin Bogner if (StartLoc) 410bf42cfd7SJustin Bogner MostRecentLocation = *StartLoc; 411bf42cfd7SJustin Bogner RegionStack.emplace_back(Count, StartLoc, EndLoc); 412ee02499aSAlex Lorenz 413bf42cfd7SJustin Bogner return RegionStack.size() - 1; 414ee02499aSAlex Lorenz } 415ee02499aSAlex Lorenz 416bf42cfd7SJustin Bogner /// \brief Pop regions from the stack into the function's list of regions. 417bf42cfd7SJustin Bogner /// 418bf42cfd7SJustin Bogner /// Adds all regions from \c ParentIndex to the top of the stack to the 419bf42cfd7SJustin Bogner /// function's \c SourceRegions. 420bf42cfd7SJustin Bogner void popRegions(size_t ParentIndex) { 421bf42cfd7SJustin Bogner assert(RegionStack.size() >= ParentIndex && "parent not in stack"); 422bf42cfd7SJustin Bogner while (RegionStack.size() > ParentIndex) { 423bf42cfd7SJustin Bogner SourceMappingRegion &Region = RegionStack.back(); 424bf42cfd7SJustin Bogner if (Region.hasStartLoc()) { 425bf42cfd7SJustin Bogner SourceLocation StartLoc = Region.getStartLoc(); 426bf42cfd7SJustin Bogner SourceLocation EndLoc = Region.hasEndLoc() 427bf42cfd7SJustin Bogner ? Region.getEndLoc() 428bf42cfd7SJustin Bogner : RegionStack[ParentIndex].getEndLoc(); 429bf42cfd7SJustin Bogner while (!SM.isWrittenInSameFile(StartLoc, EndLoc)) { 430bf42cfd7SJustin Bogner // The region ends in a nested file or macro expansion. Create a 431bf42cfd7SJustin Bogner // separate region for each expansion. 432bf42cfd7SJustin Bogner SourceLocation NestedLoc = getStartOfFileOrMacro(EndLoc); 433bf42cfd7SJustin Bogner assert(SM.isWrittenInSameFile(NestedLoc, EndLoc)); 434bf42cfd7SJustin Bogner 435*8545dae2SIgor Kudrin if (!isRegionAlreadyAdded(NestedLoc, EndLoc)) 436bf42cfd7SJustin Bogner SourceRegions.emplace_back(Region.getCounter(), NestedLoc, EndLoc); 437bf42cfd7SJustin Bogner 438f14b2078SJustin Bogner EndLoc = getPreciseTokenLocEnd(getIncludeOrExpansionLoc(EndLoc)); 439dceaaadfSJustin Bogner if (EndLoc.isInvalid()) 440dceaaadfSJustin Bogner llvm::report_fatal_error("File exit not handled before popRegions"); 441bf42cfd7SJustin Bogner } 442bf42cfd7SJustin Bogner Region.setEndLoc(EndLoc); 443bf42cfd7SJustin Bogner 444bf42cfd7SJustin Bogner MostRecentLocation = EndLoc; 445bf42cfd7SJustin Bogner // If this region happens to span an entire expansion, we need to make 446bf42cfd7SJustin Bogner // sure we don't overlap the parent region with it. 447bf42cfd7SJustin Bogner if (StartLoc == getStartOfFileOrMacro(StartLoc) && 448bf42cfd7SJustin Bogner EndLoc == getEndOfFileOrMacro(EndLoc)) 449bf42cfd7SJustin Bogner MostRecentLocation = getIncludeOrExpansionLoc(EndLoc); 450bf42cfd7SJustin Bogner 451bf42cfd7SJustin Bogner assert(SM.isWrittenInSameFile(Region.getStartLoc(), EndLoc)); 452f36a5c4aSCraig Topper SourceRegions.push_back(Region); 453bf42cfd7SJustin Bogner } 454bf42cfd7SJustin Bogner RegionStack.pop_back(); 455bf42cfd7SJustin Bogner } 456ee02499aSAlex Lorenz } 457ee02499aSAlex Lorenz 458bf42cfd7SJustin Bogner /// \brief Return the currently active region. 459bf42cfd7SJustin Bogner SourceMappingRegion &getRegion() { 460bf42cfd7SJustin Bogner assert(!RegionStack.empty() && "statement has no region"); 461bf42cfd7SJustin Bogner return RegionStack.back(); 462ee02499aSAlex Lorenz } 463ee02499aSAlex Lorenz 464bf42cfd7SJustin Bogner /// \brief Propagate counts through the children of \c S. 465bf42cfd7SJustin Bogner Counter propagateCounts(Counter TopCount, const Stmt *S) { 466bf42cfd7SJustin Bogner size_t Index = pushRegion(TopCount, getStart(S), getEnd(S)); 467bf42cfd7SJustin Bogner Visit(S); 468bf42cfd7SJustin Bogner Counter ExitCount = getRegion().getCounter(); 469bf42cfd7SJustin Bogner popRegions(Index); 47039f01975SVedant Kumar 47139f01975SVedant Kumar // The statement may be spanned by an expansion. Make sure we handle a file 47239f01975SVedant Kumar // exit out of this expansion before moving to the next statement. 47339f01975SVedant Kumar if (SM.isBeforeInTranslationUnit(getStart(S), S->getLocStart())) 47439f01975SVedant Kumar MostRecentLocation = getEnd(S); 47539f01975SVedant Kumar 476bf42cfd7SJustin Bogner return ExitCount; 477ee02499aSAlex Lorenz } 478ee02499aSAlex Lorenz 4790a7c9d11SIgor Kudrin /// \brief Check whether a region with bounds \c StartLoc and \c EndLoc 4800a7c9d11SIgor Kudrin /// is already added to \c SourceRegions. 4810a7c9d11SIgor Kudrin bool isRegionAlreadyAdded(SourceLocation StartLoc, SourceLocation EndLoc) { 4820a7c9d11SIgor Kudrin return SourceRegions.rend() != 4830a7c9d11SIgor Kudrin std::find_if(SourceRegions.rbegin(), SourceRegions.rend(), 4840a7c9d11SIgor Kudrin [&](const SourceMappingRegion &Region) { 4850a7c9d11SIgor Kudrin return Region.getStartLoc() == StartLoc && 4860a7c9d11SIgor Kudrin Region.getEndLoc() == EndLoc; 4870a7c9d11SIgor Kudrin }); 4880a7c9d11SIgor Kudrin } 4890a7c9d11SIgor Kudrin 490bf42cfd7SJustin Bogner /// \brief Adjust the most recently visited location to \c EndLoc. 491bf42cfd7SJustin Bogner /// 492bf42cfd7SJustin Bogner /// This should be used after visiting any statements in non-source order. 493bf42cfd7SJustin Bogner void adjustForOutOfOrderTraversal(SourceLocation EndLoc) { 494bf42cfd7SJustin Bogner MostRecentLocation = EndLoc; 4950a7c9d11SIgor Kudrin // The code region for a whole macro is created in handleFileExit() when 4960a7c9d11SIgor Kudrin // it detects exiting of the virtual file of that macro. If we visited 4970a7c9d11SIgor Kudrin // statements in non-source order, we might already have such a region 4980a7c9d11SIgor Kudrin // added, for example, if a body of a loop is divided among multiple 4990a7c9d11SIgor Kudrin // macros. Avoid adding duplicate regions in such case. 50096ae73f7SJustin Bogner if (getRegion().hasEndLoc() && 5010a7c9d11SIgor Kudrin MostRecentLocation == getEndOfFileOrMacro(MostRecentLocation) && 5020a7c9d11SIgor Kudrin isRegionAlreadyAdded(getStartOfFileOrMacro(MostRecentLocation), 5030a7c9d11SIgor Kudrin MostRecentLocation)) 504bf42cfd7SJustin Bogner MostRecentLocation = getIncludeOrExpansionLoc(MostRecentLocation); 505ee02499aSAlex Lorenz } 506ee02499aSAlex Lorenz 507bf42cfd7SJustin Bogner /// \brief Adjust regions and state when \c NewLoc exits a file. 508bf42cfd7SJustin Bogner /// 509bf42cfd7SJustin Bogner /// If moving from our most recently tracked location to \c NewLoc exits any 510bf42cfd7SJustin Bogner /// files, this adjusts our current region stack and creates the file regions 511bf42cfd7SJustin Bogner /// for the exited file. 512bf42cfd7SJustin Bogner void handleFileExit(SourceLocation NewLoc) { 513e44dd6dbSJustin Bogner if (NewLoc.isInvalid() || 514e44dd6dbSJustin Bogner SM.isWrittenInSameFile(MostRecentLocation, NewLoc)) 515bf42cfd7SJustin Bogner return; 516bf42cfd7SJustin Bogner 517bf42cfd7SJustin Bogner // If NewLoc is not in a file that contains MostRecentLocation, walk up to 518bf42cfd7SJustin Bogner // find the common ancestor. 519bf42cfd7SJustin Bogner SourceLocation LCA = NewLoc; 520bf42cfd7SJustin Bogner FileID ParentFile = SM.getFileID(LCA); 521bf42cfd7SJustin Bogner while (!isNestedIn(MostRecentLocation, ParentFile)) { 522bf42cfd7SJustin Bogner LCA = getIncludeOrExpansionLoc(LCA); 523bf42cfd7SJustin Bogner if (LCA.isInvalid() || SM.isWrittenInSameFile(LCA, MostRecentLocation)) { 524bf42cfd7SJustin Bogner // Since there isn't a common ancestor, no file was exited. We just need 525bf42cfd7SJustin Bogner // to adjust our location to the new file. 526bf42cfd7SJustin Bogner MostRecentLocation = NewLoc; 527bf42cfd7SJustin Bogner return; 528bf42cfd7SJustin Bogner } 529bf42cfd7SJustin Bogner ParentFile = SM.getFileID(LCA); 530ee02499aSAlex Lorenz } 531ee02499aSAlex Lorenz 532bf42cfd7SJustin Bogner llvm::SmallSet<SourceLocation, 8> StartLocs; 533bf42cfd7SJustin Bogner Optional<Counter> ParentCounter; 53457d3f145SPete Cooper for (SourceMappingRegion &I : llvm::reverse(RegionStack)) { 53557d3f145SPete Cooper if (!I.hasStartLoc()) 536bf42cfd7SJustin Bogner continue; 53757d3f145SPete Cooper SourceLocation Loc = I.getStartLoc(); 538bf42cfd7SJustin Bogner if (!isNestedIn(Loc, ParentFile)) { 53957d3f145SPete Cooper ParentCounter = I.getCounter(); 540bf42cfd7SJustin Bogner break; 541ee02499aSAlex Lorenz } 542bf42cfd7SJustin Bogner 543bf42cfd7SJustin Bogner while (!SM.isInFileID(Loc, ParentFile)) { 544bf42cfd7SJustin Bogner // The most nested region for each start location is the one with the 545bf42cfd7SJustin Bogner // correct count. We avoid creating redundant regions by stopping once 546bf42cfd7SJustin Bogner // we've seen this region. 547bf42cfd7SJustin Bogner if (StartLocs.insert(Loc).second) 54857d3f145SPete Cooper SourceRegions.emplace_back(I.getCounter(), Loc, 549bf42cfd7SJustin Bogner getEndOfFileOrMacro(Loc)); 550bf42cfd7SJustin Bogner Loc = getIncludeOrExpansionLoc(Loc); 551ee02499aSAlex Lorenz } 55257d3f145SPete Cooper I.setStartLoc(getPreciseTokenLocEnd(Loc)); 553bf42cfd7SJustin Bogner } 554bf42cfd7SJustin Bogner 555bf42cfd7SJustin Bogner if (ParentCounter) { 556bf42cfd7SJustin Bogner // If the file is contained completely by another region and doesn't 557bf42cfd7SJustin Bogner // immediately start its own region, the whole file gets a region 558bf42cfd7SJustin Bogner // corresponding to the parent. 559bf42cfd7SJustin Bogner SourceLocation Loc = MostRecentLocation; 560bf42cfd7SJustin Bogner while (isNestedIn(Loc, ParentFile)) { 561bf42cfd7SJustin Bogner SourceLocation FileStart = getStartOfFileOrMacro(Loc); 562bf42cfd7SJustin Bogner if (StartLocs.insert(FileStart).second) 563bf42cfd7SJustin Bogner SourceRegions.emplace_back(*ParentCounter, FileStart, 564bf42cfd7SJustin Bogner getEndOfFileOrMacro(Loc)); 565bf42cfd7SJustin Bogner Loc = getIncludeOrExpansionLoc(Loc); 566bf42cfd7SJustin Bogner } 567bf42cfd7SJustin Bogner } 568bf42cfd7SJustin Bogner 569bf42cfd7SJustin Bogner MostRecentLocation = NewLoc; 570bf42cfd7SJustin Bogner } 571bf42cfd7SJustin Bogner 572bf42cfd7SJustin Bogner /// \brief Ensure that \c S is included in the current region. 573bf42cfd7SJustin Bogner void extendRegion(const Stmt *S) { 574bf42cfd7SJustin Bogner SourceMappingRegion &Region = getRegion(); 575bf42cfd7SJustin Bogner SourceLocation StartLoc = getStart(S); 576bf42cfd7SJustin Bogner 577bf42cfd7SJustin Bogner handleFileExit(StartLoc); 578bf42cfd7SJustin Bogner if (!Region.hasStartLoc()) 579bf42cfd7SJustin Bogner Region.setStartLoc(StartLoc); 580bf42cfd7SJustin Bogner } 581bf42cfd7SJustin Bogner 582bf42cfd7SJustin Bogner /// \brief Mark \c S as a terminator, starting a zero region. 583bf42cfd7SJustin Bogner void terminateRegion(const Stmt *S) { 584bf42cfd7SJustin Bogner extendRegion(S); 585bf42cfd7SJustin Bogner SourceMappingRegion &Region = getRegion(); 586bf42cfd7SJustin Bogner if (!Region.hasEndLoc()) 587bf42cfd7SJustin Bogner Region.setEndLoc(getEnd(S)); 588bf42cfd7SJustin Bogner pushRegion(Counter::getZero()); 589bf42cfd7SJustin Bogner } 590ee02499aSAlex Lorenz 591ee02499aSAlex Lorenz /// \brief Keep counts of breaks and continues inside loops. 592ee02499aSAlex Lorenz struct BreakContinue { 593ee02499aSAlex Lorenz Counter BreakCount; 594ee02499aSAlex Lorenz Counter ContinueCount; 595ee02499aSAlex Lorenz }; 596ee02499aSAlex Lorenz SmallVector<BreakContinue, 8> BreakContinueStack; 597ee02499aSAlex Lorenz 598ee02499aSAlex Lorenz CounterCoverageMappingBuilder( 599ee02499aSAlex Lorenz CoverageMappingModuleGen &CVM, 600e5ee6c58SJustin Bogner llvm::DenseMap<const Stmt *, unsigned> &CounterMap, SourceManager &SM, 601ee02499aSAlex Lorenz const LangOptions &LangOpts) 602e5ee6c58SJustin Bogner : CoverageMappingBuilder(CVM, SM, LangOpts), CounterMap(CounterMap) {} 603ee02499aSAlex Lorenz 604ee02499aSAlex Lorenz /// \brief Write the mapping data to the output stream 605ee02499aSAlex Lorenz void write(llvm::raw_ostream &OS) { 606ee02499aSAlex Lorenz llvm::SmallVector<unsigned, 8> VirtualFileMapping; 607bf42cfd7SJustin Bogner gatherFileIDs(VirtualFileMapping); 608bf42cfd7SJustin Bogner emitSourceRegions(); 609bf42cfd7SJustin Bogner emitExpansionRegions(); 610ee02499aSAlex Lorenz gatherSkippedRegions(); 611ee02499aSAlex Lorenz 612efd319a2SVedant Kumar if (MappingRegions.empty()) 613efd319a2SVedant Kumar return; 614efd319a2SVedant Kumar 6154da909b2SJustin Bogner CoverageMappingWriter Writer(VirtualFileMapping, Builder.getExpressions(), 6164da909b2SJustin Bogner MappingRegions); 617ee02499aSAlex Lorenz Writer.write(OS); 618ee02499aSAlex Lorenz } 619ee02499aSAlex Lorenz 620ee02499aSAlex Lorenz void VisitStmt(const Stmt *S) { 621ed1fe5d0SYaron Keren if (S->getLocStart().isValid()) 622bf42cfd7SJustin Bogner extendRegion(S); 623642f173aSBenjamin Kramer for (const Stmt *Child : S->children()) 624642f173aSBenjamin Kramer if (Child) 625642f173aSBenjamin Kramer this->Visit(Child); 626bf42cfd7SJustin Bogner handleFileExit(getEnd(S)); 627ee02499aSAlex Lorenz } 628ee02499aSAlex Lorenz 629ee02499aSAlex Lorenz void VisitDecl(const Decl *D) { 630bf42cfd7SJustin Bogner Stmt *Body = D->getBody(); 631efd319a2SVedant Kumar 632efd319a2SVedant Kumar // Do not propagate region counts into system headers. 633efd319a2SVedant Kumar if (Body && SM.isInSystemHeader(SM.getSpellingLoc(getStart(Body)))) 634efd319a2SVedant Kumar return; 635efd319a2SVedant Kumar 636bf42cfd7SJustin Bogner propagateCounts(getRegionCounter(Body), Body); 637ee02499aSAlex Lorenz } 638ee02499aSAlex Lorenz 639ee02499aSAlex Lorenz void VisitReturnStmt(const ReturnStmt *S) { 640bf42cfd7SJustin Bogner extendRegion(S); 641ee02499aSAlex Lorenz if (S->getRetValue()) 642ee02499aSAlex Lorenz Visit(S->getRetValue()); 643bf42cfd7SJustin Bogner terminateRegion(S); 644ee02499aSAlex Lorenz } 645ee02499aSAlex Lorenz 646f959febfSJustin Bogner void VisitCXXThrowExpr(const CXXThrowExpr *E) { 647f959febfSJustin Bogner extendRegion(E); 648f959febfSJustin Bogner if (E->getSubExpr()) 649f959febfSJustin Bogner Visit(E->getSubExpr()); 650f959febfSJustin Bogner terminateRegion(E); 651f959febfSJustin Bogner } 652f959febfSJustin Bogner 653bf42cfd7SJustin Bogner void VisitGotoStmt(const GotoStmt *S) { terminateRegion(S); } 654ee02499aSAlex Lorenz 655ee02499aSAlex Lorenz void VisitLabelStmt(const LabelStmt *S) { 656bf42cfd7SJustin Bogner SourceLocation Start = getStart(S); 657bf42cfd7SJustin Bogner // We can't extendRegion here or we risk overlapping with our new region. 658bf42cfd7SJustin Bogner handleFileExit(Start); 659bf42cfd7SJustin Bogner pushRegion(getRegionCounter(S), Start); 660ee02499aSAlex Lorenz Visit(S->getSubStmt()); 661ee02499aSAlex Lorenz } 662ee02499aSAlex Lorenz 663ee02499aSAlex Lorenz void VisitBreakStmt(const BreakStmt *S) { 664ee02499aSAlex Lorenz assert(!BreakContinueStack.empty() && "break not in a loop or switch!"); 665ee02499aSAlex Lorenz BreakContinueStack.back().BreakCount = addCounters( 666bf42cfd7SJustin Bogner BreakContinueStack.back().BreakCount, getRegion().getCounter()); 667bf42cfd7SJustin Bogner terminateRegion(S); 668ee02499aSAlex Lorenz } 669ee02499aSAlex Lorenz 670ee02499aSAlex Lorenz void VisitContinueStmt(const ContinueStmt *S) { 671ee02499aSAlex Lorenz assert(!BreakContinueStack.empty() && "continue stmt not in a loop!"); 672ee02499aSAlex Lorenz BreakContinueStack.back().ContinueCount = addCounters( 673bf42cfd7SJustin Bogner BreakContinueStack.back().ContinueCount, getRegion().getCounter()); 674bf42cfd7SJustin Bogner terminateRegion(S); 675ee02499aSAlex Lorenz } 676ee02499aSAlex Lorenz 677ee02499aSAlex Lorenz void VisitWhileStmt(const WhileStmt *S) { 678bf42cfd7SJustin Bogner extendRegion(S); 679ee02499aSAlex Lorenz 680bf42cfd7SJustin Bogner Counter ParentCount = getRegion().getCounter(); 681bf42cfd7SJustin Bogner Counter BodyCount = getRegionCounter(S); 682bf42cfd7SJustin Bogner 683bf42cfd7SJustin Bogner // Handle the body first so that we can get the backedge count. 684bf42cfd7SJustin Bogner BreakContinueStack.push_back(BreakContinue()); 685bf42cfd7SJustin Bogner extendRegion(S->getBody()); 686bf42cfd7SJustin Bogner Counter BackedgeCount = propagateCounts(BodyCount, S->getBody()); 687ee02499aSAlex Lorenz BreakContinue BC = BreakContinueStack.pop_back_val(); 688bf42cfd7SJustin Bogner 689bf42cfd7SJustin Bogner // Go back to handle the condition. 690bf42cfd7SJustin Bogner Counter CondCount = 691bf42cfd7SJustin Bogner addCounters(ParentCount, BackedgeCount, BC.ContinueCount); 692bf42cfd7SJustin Bogner propagateCounts(CondCount, S->getCond()); 693bf42cfd7SJustin Bogner adjustForOutOfOrderTraversal(getEnd(S)); 694bf42cfd7SJustin Bogner 695bf42cfd7SJustin Bogner Counter OutCount = 696bf42cfd7SJustin Bogner addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount)); 697bf42cfd7SJustin Bogner if (OutCount != ParentCount) 698bf42cfd7SJustin Bogner pushRegion(OutCount); 699ee02499aSAlex Lorenz } 700ee02499aSAlex Lorenz 701ee02499aSAlex Lorenz void VisitDoStmt(const DoStmt *S) { 702bf42cfd7SJustin Bogner extendRegion(S); 703ee02499aSAlex Lorenz 704bf42cfd7SJustin Bogner Counter ParentCount = getRegion().getCounter(); 705bf42cfd7SJustin Bogner Counter BodyCount = getRegionCounter(S); 706bf42cfd7SJustin Bogner 707bf42cfd7SJustin Bogner BreakContinueStack.push_back(BreakContinue()); 708bf42cfd7SJustin Bogner extendRegion(S->getBody()); 709bf42cfd7SJustin Bogner Counter BackedgeCount = 710bf42cfd7SJustin Bogner propagateCounts(addCounters(ParentCount, BodyCount), S->getBody()); 711ee02499aSAlex Lorenz BreakContinue BC = BreakContinueStack.pop_back_val(); 712bf42cfd7SJustin Bogner 713bf42cfd7SJustin Bogner Counter CondCount = addCounters(BackedgeCount, BC.ContinueCount); 714bf42cfd7SJustin Bogner propagateCounts(CondCount, S->getCond()); 715bf42cfd7SJustin Bogner 716bf42cfd7SJustin Bogner Counter OutCount = 717bf42cfd7SJustin Bogner addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount)); 718bf42cfd7SJustin Bogner if (OutCount != ParentCount) 719bf42cfd7SJustin Bogner pushRegion(OutCount); 720ee02499aSAlex Lorenz } 721ee02499aSAlex Lorenz 722ee02499aSAlex Lorenz void VisitForStmt(const ForStmt *S) { 723bf42cfd7SJustin Bogner extendRegion(S); 724ee02499aSAlex Lorenz if (S->getInit()) 725ee02499aSAlex Lorenz Visit(S->getInit()); 726ee02499aSAlex Lorenz 727bf42cfd7SJustin Bogner Counter ParentCount = getRegion().getCounter(); 728bf42cfd7SJustin Bogner Counter BodyCount = getRegionCounter(S); 729bf42cfd7SJustin Bogner 730bf42cfd7SJustin Bogner // Handle the body first so that we can get the backedge count. 731ee02499aSAlex Lorenz BreakContinueStack.push_back(BreakContinue()); 732bf42cfd7SJustin Bogner extendRegion(S->getBody()); 733bf42cfd7SJustin Bogner Counter BackedgeCount = propagateCounts(BodyCount, S->getBody()); 734bf42cfd7SJustin Bogner BreakContinue BC = BreakContinueStack.pop_back_val(); 735ee02499aSAlex Lorenz 736ee02499aSAlex Lorenz // The increment is essentially part of the body but it needs to include 737ee02499aSAlex Lorenz // the count for all the continue statements. 738bf42cfd7SJustin Bogner if (const Stmt *Inc = S->getInc()) 739bf42cfd7SJustin Bogner propagateCounts(addCounters(BackedgeCount, BC.ContinueCount), Inc); 740bf42cfd7SJustin Bogner 741bf42cfd7SJustin Bogner // Go back to handle the condition. 742bf42cfd7SJustin Bogner Counter CondCount = 743bf42cfd7SJustin Bogner addCounters(ParentCount, BackedgeCount, BC.ContinueCount); 744bf42cfd7SJustin Bogner if (const Expr *Cond = S->getCond()) { 745bf42cfd7SJustin Bogner propagateCounts(CondCount, Cond); 746bf42cfd7SJustin Bogner adjustForOutOfOrderTraversal(getEnd(S)); 747ee02499aSAlex Lorenz } 748ee02499aSAlex Lorenz 749bf42cfd7SJustin Bogner Counter OutCount = 750bf42cfd7SJustin Bogner addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount)); 751bf42cfd7SJustin Bogner if (OutCount != ParentCount) 752bf42cfd7SJustin Bogner pushRegion(OutCount); 753ee02499aSAlex Lorenz } 754ee02499aSAlex Lorenz 755ee02499aSAlex Lorenz void VisitCXXForRangeStmt(const CXXForRangeStmt *S) { 756bf42cfd7SJustin Bogner extendRegion(S); 757bf42cfd7SJustin Bogner Visit(S->getLoopVarStmt()); 758ee02499aSAlex Lorenz Visit(S->getRangeStmt()); 759bf42cfd7SJustin Bogner 760bf42cfd7SJustin Bogner Counter ParentCount = getRegion().getCounter(); 761bf42cfd7SJustin Bogner Counter BodyCount = getRegionCounter(S); 762bf42cfd7SJustin Bogner 763ee02499aSAlex Lorenz BreakContinueStack.push_back(BreakContinue()); 764bf42cfd7SJustin Bogner extendRegion(S->getBody()); 765bf42cfd7SJustin Bogner Counter BackedgeCount = propagateCounts(BodyCount, S->getBody()); 766ee02499aSAlex Lorenz BreakContinue BC = BreakContinueStack.pop_back_val(); 767bf42cfd7SJustin Bogner 7681587432dSJustin Bogner Counter LoopCount = 7691587432dSJustin Bogner addCounters(ParentCount, BackedgeCount, BC.ContinueCount); 7701587432dSJustin Bogner Counter OutCount = 7711587432dSJustin Bogner addCounters(BC.BreakCount, subtractCounters(LoopCount, BodyCount)); 772bf42cfd7SJustin Bogner if (OutCount != ParentCount) 773bf42cfd7SJustin Bogner pushRegion(OutCount); 774ee02499aSAlex Lorenz } 775ee02499aSAlex Lorenz 776ee02499aSAlex Lorenz void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) { 777bf42cfd7SJustin Bogner extendRegion(S); 778ee02499aSAlex Lorenz Visit(S->getElement()); 779bf42cfd7SJustin Bogner 780bf42cfd7SJustin Bogner Counter ParentCount = getRegion().getCounter(); 781bf42cfd7SJustin Bogner Counter BodyCount = getRegionCounter(S); 782bf42cfd7SJustin Bogner 783ee02499aSAlex Lorenz BreakContinueStack.push_back(BreakContinue()); 784bf42cfd7SJustin Bogner extendRegion(S->getBody()); 785bf42cfd7SJustin Bogner Counter BackedgeCount = propagateCounts(BodyCount, S->getBody()); 786ee02499aSAlex Lorenz BreakContinue BC = BreakContinueStack.pop_back_val(); 787bf42cfd7SJustin Bogner 7881587432dSJustin Bogner Counter LoopCount = 7891587432dSJustin Bogner addCounters(ParentCount, BackedgeCount, BC.ContinueCount); 7901587432dSJustin Bogner Counter OutCount = 7911587432dSJustin Bogner addCounters(BC.BreakCount, subtractCounters(LoopCount, BodyCount)); 792bf42cfd7SJustin Bogner if (OutCount != ParentCount) 793bf42cfd7SJustin Bogner pushRegion(OutCount); 794ee02499aSAlex Lorenz } 795ee02499aSAlex Lorenz 796ee02499aSAlex Lorenz void VisitSwitchStmt(const SwitchStmt *S) { 797bf42cfd7SJustin Bogner extendRegion(S); 798ee02499aSAlex Lorenz Visit(S->getCond()); 799bf42cfd7SJustin Bogner 800ee02499aSAlex Lorenz BreakContinueStack.push_back(BreakContinue()); 801bf42cfd7SJustin Bogner 802bf42cfd7SJustin Bogner const Stmt *Body = S->getBody(); 803bf42cfd7SJustin Bogner extendRegion(Body); 804bf42cfd7SJustin Bogner if (const auto *CS = dyn_cast<CompoundStmt>(Body)) { 805bf42cfd7SJustin Bogner if (!CS->body_empty()) { 806bf42cfd7SJustin Bogner // The body of the switch needs a zero region so that fallthrough counts 807bf42cfd7SJustin Bogner // behave correctly, but it would be misleading to include the braces of 808bf42cfd7SJustin Bogner // the compound statement in the zeroed area, so we need to handle this 809bf42cfd7SJustin Bogner // specially. 810bf42cfd7SJustin Bogner size_t Index = 811bf42cfd7SJustin Bogner pushRegion(Counter::getZero(), getStart(CS->body_front()), 812bf42cfd7SJustin Bogner getEnd(CS->body_back())); 813b5841332SRichard Trieu for (const auto *Child : CS->children()) 814bf42cfd7SJustin Bogner Visit(Child); 815bf42cfd7SJustin Bogner popRegions(Index); 816ee02499aSAlex Lorenz } 81787ea3b05SVedant Kumar } else 818bf42cfd7SJustin Bogner propagateCounts(Counter::getZero(), Body); 819ee02499aSAlex Lorenz BreakContinue BC = BreakContinueStack.pop_back_val(); 820bf42cfd7SJustin Bogner 821ee02499aSAlex Lorenz if (!BreakContinueStack.empty()) 822ee02499aSAlex Lorenz BreakContinueStack.back().ContinueCount = addCounters( 823ee02499aSAlex Lorenz BreakContinueStack.back().ContinueCount, BC.ContinueCount); 824bf42cfd7SJustin Bogner 825bf42cfd7SJustin Bogner Counter ExitCount = getRegionCounter(S); 8263836482aSVedant Kumar SourceLocation ExitLoc = getEnd(S); 8273836482aSVedant Kumar pushRegion(ExitCount, getStart(S), ExitLoc); 8283836482aSVedant Kumar handleFileExit(ExitLoc); 829ee02499aSAlex Lorenz } 830ee02499aSAlex Lorenz 831bf42cfd7SJustin Bogner void VisitSwitchCase(const SwitchCase *S) { 832bf42cfd7SJustin Bogner extendRegion(S); 833ee02499aSAlex Lorenz 834bf42cfd7SJustin Bogner SourceMappingRegion &Parent = getRegion(); 835bf42cfd7SJustin Bogner 836bf42cfd7SJustin Bogner Counter Count = addCounters(Parent.getCounter(), getRegionCounter(S)); 837bf42cfd7SJustin Bogner // Reuse the existing region if it starts at our label. This is typical of 838bf42cfd7SJustin Bogner // the first case in a switch. 839bf42cfd7SJustin Bogner if (Parent.hasStartLoc() && Parent.getStartLoc() == getStart(S)) 840bf42cfd7SJustin Bogner Parent.setCounter(Count); 841bf42cfd7SJustin Bogner else 842bf42cfd7SJustin Bogner pushRegion(Count, getStart(S)); 843bf42cfd7SJustin Bogner 844376c06c2SSanjay Patel if (const auto *CS = dyn_cast<CaseStmt>(S)) { 845bf42cfd7SJustin Bogner Visit(CS->getLHS()); 846bf42cfd7SJustin Bogner if (const Expr *RHS = CS->getRHS()) 847bf42cfd7SJustin Bogner Visit(RHS); 848bf42cfd7SJustin Bogner } 849ee02499aSAlex Lorenz Visit(S->getSubStmt()); 850ee02499aSAlex Lorenz } 851ee02499aSAlex Lorenz 852ee02499aSAlex Lorenz void VisitIfStmt(const IfStmt *S) { 853bf42cfd7SJustin Bogner extendRegion(S); 854055ebc34SJustin Bogner // Extend into the condition before we propagate through it below - this is 855055ebc34SJustin Bogner // needed to handle macros that generate the "if" but not the condition. 856055ebc34SJustin Bogner extendRegion(S->getCond()); 857ee02499aSAlex Lorenz 858bf42cfd7SJustin Bogner Counter ParentCount = getRegion().getCounter(); 859bf42cfd7SJustin Bogner Counter ThenCount = getRegionCounter(S); 860ee02499aSAlex Lorenz 86191f2e3c9SJustin Bogner // Emitting a counter for the condition makes it easier to interpret the 86291f2e3c9SJustin Bogner // counter for the body when looking at the coverage. 86391f2e3c9SJustin Bogner propagateCounts(ParentCount, S->getCond()); 86491f2e3c9SJustin Bogner 865bf42cfd7SJustin Bogner extendRegion(S->getThen()); 866bf42cfd7SJustin Bogner Counter OutCount = propagateCounts(ThenCount, S->getThen()); 867bf42cfd7SJustin Bogner 868bf42cfd7SJustin Bogner Counter ElseCount = subtractCounters(ParentCount, ThenCount); 869bf42cfd7SJustin Bogner if (const Stmt *Else = S->getElse()) { 870bf42cfd7SJustin Bogner extendRegion(S->getElse()); 871bf42cfd7SJustin Bogner OutCount = addCounters(OutCount, propagateCounts(ElseCount, Else)); 872bf42cfd7SJustin Bogner } else 873bf42cfd7SJustin Bogner OutCount = addCounters(OutCount, ElseCount); 874bf42cfd7SJustin Bogner 875bf42cfd7SJustin Bogner if (OutCount != ParentCount) 876bf42cfd7SJustin Bogner pushRegion(OutCount); 877ee02499aSAlex Lorenz } 878ee02499aSAlex Lorenz 879ee02499aSAlex Lorenz void VisitCXXTryStmt(const CXXTryStmt *S) { 880bf42cfd7SJustin Bogner extendRegion(S); 881049908b2SVedant Kumar // Handle macros that generate the "try" but not the rest. 882049908b2SVedant Kumar extendRegion(S->getTryBlock()); 883049908b2SVedant Kumar 884049908b2SVedant Kumar Counter ParentCount = getRegion().getCounter(); 885049908b2SVedant Kumar propagateCounts(ParentCount, S->getTryBlock()); 886049908b2SVedant Kumar 887ee02499aSAlex Lorenz for (unsigned I = 0, E = S->getNumHandlers(); I < E; ++I) 888ee02499aSAlex Lorenz Visit(S->getHandler(I)); 889bf42cfd7SJustin Bogner 890bf42cfd7SJustin Bogner Counter ExitCount = getRegionCounter(S); 891bf42cfd7SJustin Bogner pushRegion(ExitCount); 892ee02499aSAlex Lorenz } 893ee02499aSAlex Lorenz 894ee02499aSAlex Lorenz void VisitCXXCatchStmt(const CXXCatchStmt *S) { 895bf42cfd7SJustin Bogner propagateCounts(getRegionCounter(S), S->getHandlerBlock()); 896ee02499aSAlex Lorenz } 897ee02499aSAlex Lorenz 898ee02499aSAlex Lorenz void VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) { 899bf42cfd7SJustin Bogner extendRegion(E); 900ee02499aSAlex Lorenz 901bf42cfd7SJustin Bogner Counter ParentCount = getRegion().getCounter(); 902bf42cfd7SJustin Bogner Counter TrueCount = getRegionCounter(E); 903ee02499aSAlex Lorenz 904e3654ce7SJustin Bogner Visit(E->getCond()); 905e3654ce7SJustin Bogner 906e3654ce7SJustin Bogner if (!isa<BinaryConditionalOperator>(E)) { 907e3654ce7SJustin Bogner extendRegion(E->getTrueExpr()); 908bf42cfd7SJustin Bogner propagateCounts(TrueCount, E->getTrueExpr()); 909e3654ce7SJustin Bogner } 910e3654ce7SJustin Bogner extendRegion(E->getFalseExpr()); 911bf42cfd7SJustin Bogner propagateCounts(subtractCounters(ParentCount, TrueCount), 912bf42cfd7SJustin Bogner E->getFalseExpr()); 913ee02499aSAlex Lorenz } 914ee02499aSAlex Lorenz 915ee02499aSAlex Lorenz void VisitBinLAnd(const BinaryOperator *E) { 916bf42cfd7SJustin Bogner extendRegion(E); 917ee02499aSAlex Lorenz Visit(E->getLHS()); 918bf42cfd7SJustin Bogner 919bf42cfd7SJustin Bogner extendRegion(E->getRHS()); 920bf42cfd7SJustin Bogner propagateCounts(getRegionCounter(E), E->getRHS()); 921ee02499aSAlex Lorenz } 922ee02499aSAlex Lorenz 923ee02499aSAlex Lorenz void VisitBinLOr(const BinaryOperator *E) { 924bf42cfd7SJustin Bogner extendRegion(E); 925ee02499aSAlex Lorenz Visit(E->getLHS()); 926ee02499aSAlex Lorenz 927bf42cfd7SJustin Bogner extendRegion(E->getRHS()); 928bf42cfd7SJustin Bogner propagateCounts(getRegionCounter(E), E->getRHS()); 92901a0d062SAlex Lorenz } 930c109102eSJustin Bogner 931c109102eSJustin Bogner void VisitLambdaExpr(const LambdaExpr *LE) { 932c109102eSJustin Bogner // Lambdas are treated as their own functions for now, so we shouldn't 933c109102eSJustin Bogner // propagate counts into them. 934c109102eSJustin Bogner } 935ee02499aSAlex Lorenz }; 936ee02499aSAlex Lorenz 93714f8fb68SVedant Kumar bool isMachO(const CodeGenModule &CGM) { 938ee02499aSAlex Lorenz return CGM.getTarget().getTriple().isOSBinFormatMachO(); 939ee02499aSAlex Lorenz } 940ee02499aSAlex Lorenz 94114f8fb68SVedant Kumar StringRef getCoverageSection(const CodeGenModule &CGM) { 94203711cbdSXinliang David Li return llvm::getInstrProfCoverageSectionName(isMachO(CGM)); 943ee02499aSAlex Lorenz } 944ee02499aSAlex Lorenz 94514f8fb68SVedant Kumar std::string normalizeFilename(StringRef Filename) { 94614f8fb68SVedant Kumar llvm::SmallString<256> Path(Filename); 94714f8fb68SVedant Kumar llvm::sys::fs::make_absolute(Path); 948d04929d8SVedant Kumar llvm::sys::path::remove_dots(Path, /*remove_dot_dots=*/true); 94914f8fb68SVedant Kumar return Path.str().str(); 95014f8fb68SVedant Kumar } 95114f8fb68SVedant Kumar 95214f8fb68SVedant Kumar } // end anonymous namespace 95314f8fb68SVedant Kumar 954a432d176SJustin Bogner static void dump(llvm::raw_ostream &OS, StringRef FunctionName, 955a432d176SJustin Bogner ArrayRef<CounterExpression> Expressions, 956a432d176SJustin Bogner ArrayRef<CounterMappingRegion> Regions) { 957a432d176SJustin Bogner OS << FunctionName << ":\n"; 958a432d176SJustin Bogner CounterMappingContext Ctx(Expressions); 959a432d176SJustin Bogner for (const auto &R : Regions) { 960f2cf38e0SAlex Lorenz OS.indent(2); 961f2cf38e0SAlex Lorenz switch (R.Kind) { 962f2cf38e0SAlex Lorenz case CounterMappingRegion::CodeRegion: 963f2cf38e0SAlex Lorenz break; 964f2cf38e0SAlex Lorenz case CounterMappingRegion::ExpansionRegion: 965f2cf38e0SAlex Lorenz OS << "Expansion,"; 966f2cf38e0SAlex Lorenz break; 967f2cf38e0SAlex Lorenz case CounterMappingRegion::SkippedRegion: 968f2cf38e0SAlex Lorenz OS << "Skipped,"; 969f2cf38e0SAlex Lorenz break; 970f2cf38e0SAlex Lorenz } 971f2cf38e0SAlex Lorenz 9724da909b2SJustin Bogner OS << "File " << R.FileID << ", " << R.LineStart << ":" << R.ColumnStart 9734da909b2SJustin Bogner << " -> " << R.LineEnd << ":" << R.ColumnEnd << " = "; 974f69dc349SJustin Bogner Ctx.dump(R.Count, OS); 975f2cf38e0SAlex Lorenz if (R.Kind == CounterMappingRegion::ExpansionRegion) 9764da909b2SJustin Bogner OS << " (Expanded file = " << R.ExpandedFileID << ")"; 9774da909b2SJustin Bogner OS << "\n"; 978f2cf38e0SAlex Lorenz } 979f2cf38e0SAlex Lorenz } 980f2cf38e0SAlex Lorenz 981ee02499aSAlex Lorenz void CoverageMappingModuleGen::addFunctionMappingRecord( 9822129ae53SXinliang David Li llvm::GlobalVariable *NamePtr, StringRef NameValue, uint64_t FuncHash, 983848da137SXinliang David Li const std::string &CoverageMapping, bool IsUsed) { 984ee02499aSAlex Lorenz llvm::LLVMContext &Ctx = CGM.getLLVMContext(); 985ee02499aSAlex Lorenz if (!FunctionRecordTy) { 986a026a437SXinliang David Li #define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) LLVMType, 987a026a437SXinliang David Li llvm::Type *FunctionRecordTypes[] = { 988a026a437SXinliang David Li #include "llvm/ProfileData/InstrProfData.inc" 989a026a437SXinliang David Li }; 990ee02499aSAlex Lorenz FunctionRecordTy = 9914dc5adc7SJustin Bogner llvm::StructType::get(Ctx, makeArrayRef(FunctionRecordTypes), 9924dc5adc7SJustin Bogner /*isPacked=*/true); 993ee02499aSAlex Lorenz } 994ee02499aSAlex Lorenz 995a026a437SXinliang David Li #define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) Init, 996ee02499aSAlex Lorenz llvm::Constant *FunctionRecordVals[] = { 997a026a437SXinliang David Li #include "llvm/ProfileData/InstrProfData.inc" 998a026a437SXinliang David Li }; 999ee02499aSAlex Lorenz FunctionRecords.push_back(llvm::ConstantStruct::get( 1000ee02499aSAlex Lorenz FunctionRecordTy, makeArrayRef(FunctionRecordVals))); 1001848da137SXinliang David Li if (!IsUsed) 10022129ae53SXinliang David Li FunctionNames.push_back( 10032129ae53SXinliang David Li llvm::ConstantExpr::getBitCast(NamePtr, llvm::Type::getInt8PtrTy(Ctx))); 1004ca3326c0SVedant Kumar CoverageMappings.push_back(CoverageMapping); 1005f2cf38e0SAlex Lorenz 1006f2cf38e0SAlex Lorenz if (CGM.getCodeGenOpts().DumpCoverageMapping) { 1007f2cf38e0SAlex Lorenz // Dump the coverage mapping data for this function by decoding the 1008f2cf38e0SAlex Lorenz // encoded data. This allows us to dump the mapping regions which were 1009f2cf38e0SAlex Lorenz // also processed by the CoverageMappingWriter which performs 1010f2cf38e0SAlex Lorenz // additional minimization operations such as reducing the number of 1011f2cf38e0SAlex Lorenz // expressions. 1012f2cf38e0SAlex Lorenz std::vector<StringRef> Filenames; 1013f2cf38e0SAlex Lorenz std::vector<CounterExpression> Expressions; 1014f2cf38e0SAlex Lorenz std::vector<CounterMappingRegion> Regions; 1015f2cf38e0SAlex Lorenz llvm::SmallVector<StringRef, 16> FilenameRefs; 1016f2cf38e0SAlex Lorenz FilenameRefs.resize(FileEntries.size()); 1017f2cf38e0SAlex Lorenz for (const auto &Entry : FileEntries) 101814f8fb68SVedant Kumar FilenameRefs[Entry.second] = normalizeFilename(Entry.first->getName()); 1019a432d176SJustin Bogner RawCoverageMappingReader Reader(CoverageMapping, FilenameRefs, Filenames, 1020a432d176SJustin Bogner Expressions, Regions); 1021a432d176SJustin Bogner if (Reader.read()) 1022f2cf38e0SAlex Lorenz return; 1023a026a437SXinliang David Li dump(llvm::outs(), NameValue, Expressions, Regions); 1024f2cf38e0SAlex Lorenz } 1025ee02499aSAlex Lorenz } 1026ee02499aSAlex Lorenz 1027ee02499aSAlex Lorenz void CoverageMappingModuleGen::emit() { 1028ee02499aSAlex Lorenz if (FunctionRecords.empty()) 1029ee02499aSAlex Lorenz return; 1030ee02499aSAlex Lorenz llvm::LLVMContext &Ctx = CGM.getLLVMContext(); 1031ee02499aSAlex Lorenz auto *Int32Ty = llvm::Type::getInt32Ty(Ctx); 1032ee02499aSAlex Lorenz 1033ee02499aSAlex Lorenz // Create the filenames and merge them with coverage mappings 1034ee02499aSAlex Lorenz llvm::SmallVector<std::string, 16> FilenameStrs; 10359e324dd1SVedant Kumar llvm::SmallVector<StringRef, 16> FilenameRefs; 1036ee02499aSAlex Lorenz FilenameStrs.resize(FileEntries.size()); 10379e324dd1SVedant Kumar FilenameRefs.resize(FileEntries.size()); 1038ee02499aSAlex Lorenz for (const auto &Entry : FileEntries) { 1039ee02499aSAlex Lorenz auto I = Entry.second; 104014f8fb68SVedant Kumar FilenameStrs[I] = normalizeFilename(Entry.first->getName()); 10419e324dd1SVedant Kumar FilenameRefs[I] = FilenameStrs[I]; 1042ee02499aSAlex Lorenz } 1043ee02499aSAlex Lorenz 10449e324dd1SVedant Kumar std::string FilenamesAndCoverageMappings; 10459e324dd1SVedant Kumar llvm::raw_string_ostream OS(FilenamesAndCoverageMappings); 10469e324dd1SVedant Kumar CoverageFilenamesSectionWriter(FilenameRefs).write(OS); 10479e324dd1SVedant Kumar std::string RawCoverageMappings = 10489e324dd1SVedant Kumar llvm::join(CoverageMappings.begin(), CoverageMappings.end(), ""); 10499e324dd1SVedant Kumar OS << RawCoverageMappings; 10509e324dd1SVedant Kumar size_t CoverageMappingSize = RawCoverageMappings.size(); 10519e324dd1SVedant Kumar size_t FilenamesSize = OS.str().size() - CoverageMappingSize; 10529e324dd1SVedant Kumar // Append extra zeroes if necessary to ensure that the size of the filenames 10539e324dd1SVedant Kumar // and coverage mappings is a multiple of 8. 10549e324dd1SVedant Kumar if (size_t Rem = OS.str().size() % 8) { 10559e324dd1SVedant Kumar CoverageMappingSize += 8 - Rem; 10569e324dd1SVedant Kumar for (size_t I = 0, S = 8 - Rem; I < S; ++I) 10579e324dd1SVedant Kumar OS << '\0'; 1058ee02499aSAlex Lorenz } 1059ee02499aSAlex Lorenz auto *FilenamesAndMappingsVal = 10609e324dd1SVedant Kumar llvm::ConstantDataArray::getString(Ctx, OS.str(), false); 1061ee02499aSAlex Lorenz 1062ee02499aSAlex Lorenz // Create the deferred function records array 1063ee02499aSAlex Lorenz auto RecordsTy = 1064ee02499aSAlex Lorenz llvm::ArrayType::get(FunctionRecordTy, FunctionRecords.size()); 1065ee02499aSAlex Lorenz auto RecordsVal = llvm::ConstantArray::get(RecordsTy, FunctionRecords); 1066ee02499aSAlex Lorenz 106720b188c0SXinliang David Li llvm::Type *CovDataHeaderTypes[] = { 106820b188c0SXinliang David Li #define COVMAP_HEADER(Type, LLVMType, Name, Init) LLVMType, 106920b188c0SXinliang David Li #include "llvm/ProfileData/InstrProfData.inc" 107020b188c0SXinliang David Li }; 107120b188c0SXinliang David Li auto CovDataHeaderTy = 107220b188c0SXinliang David Li llvm::StructType::get(Ctx, makeArrayRef(CovDataHeaderTypes)); 107320b188c0SXinliang David Li llvm::Constant *CovDataHeaderVals[] = { 107420b188c0SXinliang David Li #define COVMAP_HEADER(Type, LLVMType, Name, Init) Init, 107520b188c0SXinliang David Li #include "llvm/ProfileData/InstrProfData.inc" 107620b188c0SXinliang David Li }; 107720b188c0SXinliang David Li auto CovDataHeaderVal = llvm::ConstantStruct::get( 107820b188c0SXinliang David Li CovDataHeaderTy, makeArrayRef(CovDataHeaderVals)); 107920b188c0SXinliang David Li 1080ee02499aSAlex Lorenz // Create the coverage data record 108120b188c0SXinliang David Li llvm::Type *CovDataTypes[] = {CovDataHeaderTy, RecordsTy, 108220b188c0SXinliang David Li FilenamesAndMappingsVal->getType()}; 1083ee02499aSAlex Lorenz auto CovDataTy = llvm::StructType::get(Ctx, makeArrayRef(CovDataTypes)); 108420b188c0SXinliang David Li llvm::Constant *TUDataVals[] = {CovDataHeaderVal, RecordsVal, 108520b188c0SXinliang David Li FilenamesAndMappingsVal}; 1086ee02499aSAlex Lorenz auto CovDataVal = 1087ee02499aSAlex Lorenz llvm::ConstantStruct::get(CovDataTy, makeArrayRef(TUDataVals)); 108820b188c0SXinliang David Li auto CovData = new llvm::GlobalVariable( 108920b188c0SXinliang David Li CGM.getModule(), CovDataTy, true, llvm::GlobalValue::InternalLinkage, 109020b188c0SXinliang David Li CovDataVal, llvm::getCoverageMappingVarName()); 1091ee02499aSAlex Lorenz 1092ee02499aSAlex Lorenz CovData->setSection(getCoverageSection(CGM)); 1093ee02499aSAlex Lorenz CovData->setAlignment(8); 1094ee02499aSAlex Lorenz 1095ee02499aSAlex Lorenz // Make sure the data doesn't get deleted. 1096ee02499aSAlex Lorenz CGM.addUsedGlobal(CovData); 10972129ae53SXinliang David Li // Create the deferred function records array 10982129ae53SXinliang David Li if (!FunctionNames.empty()) { 10992129ae53SXinliang David Li auto NamesArrTy = llvm::ArrayType::get(llvm::Type::getInt8PtrTy(Ctx), 11002129ae53SXinliang David Li FunctionNames.size()); 11012129ae53SXinliang David Li auto NamesArrVal = llvm::ConstantArray::get(NamesArrTy, FunctionNames); 11022129ae53SXinliang David Li // This variable will *NOT* be emitted to the object file. It is used 11032129ae53SXinliang David Li // to pass the list of names referenced to codegen. 11042129ae53SXinliang David Li new llvm::GlobalVariable(CGM.getModule(), NamesArrTy, true, 11052129ae53SXinliang David Li llvm::GlobalValue::InternalLinkage, NamesArrVal, 11067077f0afSXinliang David Li llvm::getCoverageUnusedNamesVarName()); 11072129ae53SXinliang David Li } 1108ee02499aSAlex Lorenz } 1109ee02499aSAlex Lorenz 1110ee02499aSAlex Lorenz unsigned CoverageMappingModuleGen::getFileID(const FileEntry *File) { 1111ee02499aSAlex Lorenz auto It = FileEntries.find(File); 1112ee02499aSAlex Lorenz if (It != FileEntries.end()) 1113ee02499aSAlex Lorenz return It->second; 1114ee02499aSAlex Lorenz unsigned FileID = FileEntries.size(); 1115ee02499aSAlex Lorenz FileEntries.insert(std::make_pair(File, FileID)); 1116ee02499aSAlex Lorenz return FileID; 1117ee02499aSAlex Lorenz } 1118ee02499aSAlex Lorenz 1119ee02499aSAlex Lorenz void CoverageMappingGen::emitCounterMapping(const Decl *D, 1120ee02499aSAlex Lorenz llvm::raw_ostream &OS) { 1121ee02499aSAlex Lorenz assert(CounterMap); 1122e5ee6c58SJustin Bogner CounterCoverageMappingBuilder Walker(CVM, *CounterMap, SM, LangOpts); 1123ee02499aSAlex Lorenz Walker.VisitDecl(D); 1124ee02499aSAlex Lorenz Walker.write(OS); 1125ee02499aSAlex Lorenz } 1126ee02499aSAlex Lorenz 1127ee02499aSAlex Lorenz void CoverageMappingGen::emitEmptyMapping(const Decl *D, 1128ee02499aSAlex Lorenz llvm::raw_ostream &OS) { 1129ee02499aSAlex Lorenz EmptyCoverageMappingBuilder Walker(CVM, SM, LangOpts); 1130ee02499aSAlex Lorenz Walker.VisitDecl(D); 1131ee02499aSAlex Lorenz Walker.write(OS); 1132ee02499aSAlex Lorenz } 1133