1ee02499aSAlex Lorenz //===--- CoverageMappingGen.cpp - Coverage mapping generation ---*- C++ -*-===// 2ee02499aSAlex Lorenz // 32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information. 52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6ee02499aSAlex Lorenz // 7ee02499aSAlex Lorenz //===----------------------------------------------------------------------===// 8ee02499aSAlex Lorenz // 9ee02499aSAlex Lorenz // Instrumentation-based code coverage mapping generator 10ee02499aSAlex Lorenz // 11ee02499aSAlex Lorenz //===----------------------------------------------------------------------===// 12ee02499aSAlex Lorenz 13ee02499aSAlex Lorenz #include "CoverageMappingGen.h" 14ee02499aSAlex Lorenz #include "CodeGenFunction.h" 15ee02499aSAlex Lorenz #include "clang/AST/StmtVisitor.h" 16dd1ea9deSVedant Kumar #include "clang/Basic/Diagnostic.h" 17e08464fbSReid Kleckner #include "clang/Basic/FileManager.h" 18dd1ea9deSVedant Kumar #include "clang/Frontend/FrontendDiagnostic.h" 19ee02499aSAlex Lorenz #include "clang/Lex/Lexer.h" 20e08464fbSReid Kleckner #include "llvm/ADT/Optional.h" 21bc6b80a0SVedant Kumar #include "llvm/ADT/SmallSet.h" 22ca3326c0SVedant Kumar #include "llvm/ADT/StringExtras.h" 23b014ee46SEaswaran Raman #include "llvm/ProfileData/Coverage/CoverageMapping.h" 24b014ee46SEaswaran Raman #include "llvm/ProfileData/Coverage/CoverageMappingReader.h" 25b014ee46SEaswaran Raman #include "llvm/ProfileData/Coverage/CoverageMappingWriter.h" 260d9593ddSChandler Carruth #include "llvm/ProfileData/InstrProfReader.h" 27ee02499aSAlex Lorenz #include "llvm/Support/FileSystem.h" 2814f8fb68SVedant Kumar #include "llvm/Support/Path.h" 29ee02499aSAlex Lorenz 30dd1ea9deSVedant Kumar // This selects the coverage mapping format defined when `InstrProfData.inc` 31dd1ea9deSVedant Kumar // is textually included. 32dd1ea9deSVedant Kumar #define COVMAP_V3 33dd1ea9deSVedant Kumar 349caa3fbeSZequan Wu static llvm::cl::opt<bool> EmptyLineCommentCoverage( 359caa3fbeSZequan Wu "emptyline-comment-coverage", 369caa3fbeSZequan Wu llvm::cl::desc("Emit emptylines and comment lines as skipped regions (only " 379caa3fbeSZequan Wu "disable it on test)"), 389caa3fbeSZequan Wu llvm::cl::init(true), llvm::cl::Hidden); 399caa3fbeSZequan Wu 40ee02499aSAlex Lorenz using namespace clang; 41ee02499aSAlex Lorenz using namespace CodeGen; 42ee02499aSAlex Lorenz using namespace llvm::coverage; 43ee02499aSAlex Lorenz 44b46176bbSZequan Wu CoverageSourceInfo * 45b46176bbSZequan Wu CoverageMappingModuleGen::setUpCoverageCallbacks(Preprocessor &PP) { 469caa3fbeSZequan Wu CoverageSourceInfo *CoverageInfo = 479caa3fbeSZequan Wu new CoverageSourceInfo(PP.getSourceManager()); 48b46176bbSZequan Wu PP.addPPCallbacks(std::unique_ptr<PPCallbacks>(CoverageInfo)); 499caa3fbeSZequan Wu if (EmptyLineCommentCoverage) { 50b46176bbSZequan Wu PP.addCommentHandler(CoverageInfo); 519caa3fbeSZequan Wu PP.setEmptylineHandler(CoverageInfo); 52b46176bbSZequan Wu PP.setPreprocessToken(true); 53b46176bbSZequan Wu PP.setTokenWatcher([CoverageInfo](clang::Token Tok) { 54b46176bbSZequan Wu // Update previous token location. 55b46176bbSZequan Wu CoverageInfo->PrevTokLoc = Tok.getLocation(); 5684fffa67SZequan Wu if (Tok.getKind() != clang::tok::eod) 57b46176bbSZequan Wu CoverageInfo->updateNextTokLoc(Tok.getLocation()); 58b46176bbSZequan Wu }); 599caa3fbeSZequan Wu } 60b46176bbSZequan Wu return CoverageInfo; 61b46176bbSZequan Wu } 62b46176bbSZequan Wu 639caa3fbeSZequan Wu void CoverageSourceInfo::AddSkippedRange(SourceRange Range) { 649caa3fbeSZequan Wu if (EmptyLineCommentCoverage && !SkippedRanges.empty() && 659caa3fbeSZequan Wu PrevTokLoc == SkippedRanges.back().PrevTokLoc && 669caa3fbeSZequan Wu SourceMgr.isWrittenInSameFile(SkippedRanges.back().Range.getEnd(), 679caa3fbeSZequan Wu Range.getBegin())) 689caa3fbeSZequan Wu SkippedRanges.back().Range.setEnd(Range.getEnd()); 699caa3fbeSZequan Wu else 709caa3fbeSZequan Wu SkippedRanges.push_back({Range, PrevTokLoc}); 719caa3fbeSZequan Wu } 729caa3fbeSZequan Wu 733919a501SVedant Kumar void CoverageSourceInfo::SourceRangeSkipped(SourceRange Range, SourceLocation) { 749caa3fbeSZequan Wu AddSkippedRange(Range); 759caa3fbeSZequan Wu } 769caa3fbeSZequan Wu 779caa3fbeSZequan Wu void CoverageSourceInfo::HandleEmptyline(SourceRange Range) { 789caa3fbeSZequan Wu AddSkippedRange(Range); 79b46176bbSZequan Wu } 80b46176bbSZequan Wu 81b46176bbSZequan Wu bool CoverageSourceInfo::HandleComment(Preprocessor &PP, SourceRange Range) { 829caa3fbeSZequan Wu AddSkippedRange(Range); 83b46176bbSZequan Wu return false; 84b46176bbSZequan Wu } 85b46176bbSZequan Wu 86b46176bbSZequan Wu void CoverageSourceInfo::updateNextTokLoc(SourceLocation Loc) { 879caa3fbeSZequan Wu if (!SkippedRanges.empty() && SkippedRanges.back().NextTokLoc.isInvalid()) 88b46176bbSZequan Wu SkippedRanges.back().NextTokLoc = Loc; 89ee02499aSAlex Lorenz } 90ee02499aSAlex Lorenz 91ee02499aSAlex Lorenz namespace { 92ee02499aSAlex Lorenz 939fc8faf9SAdrian Prantl /// A region of source code that can be mapped to a counter. 9409c7179bSJustin Bogner class SourceMappingRegion { 959f2967bcSAlan Phipps /// Primary Counter that is also used for Branch Regions for "True" branches. 96ee02499aSAlex Lorenz Counter Count; 97ee02499aSAlex Lorenz 989f2967bcSAlan Phipps /// Secondary Counter used for Branch Regions for "False" branches. 999f2967bcSAlan Phipps Optional<Counter> FalseCount; 1009f2967bcSAlan Phipps 1019fc8faf9SAdrian Prantl /// The region's starting location. 102bf42cfd7SJustin Bogner Optional<SourceLocation> LocStart; 103ee02499aSAlex Lorenz 1049fc8faf9SAdrian Prantl /// The region's ending location. 105bf42cfd7SJustin Bogner Optional<SourceLocation> LocEnd; 106ee02499aSAlex Lorenz 107747b0e29SVedant Kumar /// Whether this region should be emitted after its parent is emitted. 108747b0e29SVedant Kumar bool DeferRegion; 109747b0e29SVedant Kumar 110a1c4deb7SVedant Kumar /// Whether this region is a gap region. The count from a gap region is set 111a1c4deb7SVedant Kumar /// as the line execution count if there are no other regions on the line. 112a1c4deb7SVedant Kumar bool GapRegion; 113a1c4deb7SVedant Kumar 11409c7179bSJustin Bogner public: 115bf42cfd7SJustin Bogner SourceMappingRegion(Counter Count, Optional<SourceLocation> LocStart, 116a1c4deb7SVedant Kumar Optional<SourceLocation> LocEnd, bool DeferRegion = false, 117a1c4deb7SVedant Kumar bool GapRegion = false) 118747b0e29SVedant Kumar : Count(Count), LocStart(LocStart), LocEnd(LocEnd), 119a1c4deb7SVedant Kumar DeferRegion(DeferRegion), GapRegion(GapRegion) {} 120ee02499aSAlex Lorenz 1219f2967bcSAlan Phipps SourceMappingRegion(Counter Count, Optional<Counter> FalseCount, 1229f2967bcSAlan Phipps Optional<SourceLocation> LocStart, 1239f2967bcSAlan Phipps Optional<SourceLocation> LocEnd, bool DeferRegion = false, 1249f2967bcSAlan Phipps bool GapRegion = false) 1259f2967bcSAlan Phipps : Count(Count), FalseCount(FalseCount), LocStart(LocStart), 1269f2967bcSAlan Phipps LocEnd(LocEnd), DeferRegion(DeferRegion), GapRegion(GapRegion) {} 1279f2967bcSAlan Phipps 12809c7179bSJustin Bogner const Counter &getCounter() const { return Count; } 12909c7179bSJustin Bogner 1309f2967bcSAlan Phipps const Counter &getFalseCounter() const { 1319f2967bcSAlan Phipps assert(FalseCount && "Region has no alternate counter"); 1329f2967bcSAlan Phipps return *FalseCount; 1339f2967bcSAlan Phipps } 1349f2967bcSAlan Phipps 135bf42cfd7SJustin Bogner void setCounter(Counter C) { Count = C; } 13609c7179bSJustin Bogner 137bf42cfd7SJustin Bogner bool hasStartLoc() const { return LocStart.hasValue(); } 138bf42cfd7SJustin Bogner 139bf42cfd7SJustin Bogner void setStartLoc(SourceLocation Loc) { LocStart = Loc; } 140bf42cfd7SJustin Bogner 1413cffc4c7SStephen Kelly SourceLocation getBeginLoc() const { 142bf42cfd7SJustin Bogner assert(LocStart && "Region has no start location"); 143bf42cfd7SJustin Bogner return *LocStart; 14409c7179bSJustin Bogner } 14509c7179bSJustin Bogner 146bf42cfd7SJustin Bogner bool hasEndLoc() const { return LocEnd.hasValue(); } 147ee02499aSAlex Lorenz 148a14a1f92SVedant Kumar void setEndLoc(SourceLocation Loc) { 149a14a1f92SVedant Kumar assert(Loc.isValid() && "Setting an invalid end location"); 150a14a1f92SVedant Kumar LocEnd = Loc; 151a14a1f92SVedant Kumar } 152ee02499aSAlex Lorenz 153462c77b4SCraig Topper SourceLocation getEndLoc() const { 154bf42cfd7SJustin Bogner assert(LocEnd && "Region has no end location"); 155bf42cfd7SJustin Bogner return *LocEnd; 156ee02499aSAlex Lorenz } 157747b0e29SVedant Kumar 158747b0e29SVedant Kumar bool isDeferred() const { return DeferRegion; } 159747b0e29SVedant Kumar 160747b0e29SVedant Kumar void setDeferred(bool Deferred) { DeferRegion = Deferred; } 161a1c4deb7SVedant Kumar 162a1c4deb7SVedant Kumar bool isGap() const { return GapRegion; } 163a1c4deb7SVedant Kumar 164a1c4deb7SVedant Kumar void setGap(bool Gap) { GapRegion = Gap; } 1659f2967bcSAlan Phipps 1669f2967bcSAlan Phipps bool isBranch() const { return FalseCount.hasValue(); } 167ee02499aSAlex Lorenz }; 168ee02499aSAlex Lorenz 169d7369648SVedant Kumar /// Spelling locations for the start and end of a source region. 170d7369648SVedant Kumar struct SpellingRegion { 171d7369648SVedant Kumar /// The line where the region starts. 172d7369648SVedant Kumar unsigned LineStart; 173d7369648SVedant Kumar 174d7369648SVedant Kumar /// The column where the region starts. 175d7369648SVedant Kumar unsigned ColumnStart; 176d7369648SVedant Kumar 177d7369648SVedant Kumar /// The line where the region ends. 178d7369648SVedant Kumar unsigned LineEnd; 179d7369648SVedant Kumar 180d7369648SVedant Kumar /// The column where the region ends. 181d7369648SVedant Kumar unsigned ColumnEnd; 182d7369648SVedant Kumar 183d7369648SVedant Kumar SpellingRegion(SourceManager &SM, SourceLocation LocStart, 184d7369648SVedant Kumar SourceLocation LocEnd) { 185d7369648SVedant Kumar LineStart = SM.getSpellingLineNumber(LocStart); 186d7369648SVedant Kumar ColumnStart = SM.getSpellingColumnNumber(LocStart); 187d7369648SVedant Kumar LineEnd = SM.getSpellingLineNumber(LocEnd); 188d7369648SVedant Kumar ColumnEnd = SM.getSpellingColumnNumber(LocEnd); 189d7369648SVedant Kumar } 190d7369648SVedant Kumar 191fa8fa044SVedant Kumar SpellingRegion(SourceManager &SM, SourceMappingRegion &R) 192a6e4358fSStephen Kelly : SpellingRegion(SM, R.getBeginLoc(), R.getEndLoc()) {} 193fa8fa044SVedant Kumar 194d7369648SVedant Kumar /// Check if the start and end locations appear in source order, i.e 195d7369648SVedant Kumar /// top->bottom, left->right. 196d7369648SVedant Kumar bool isInSourceOrder() const { 197d7369648SVedant Kumar return (LineStart < LineEnd) || 198d7369648SVedant Kumar (LineStart == LineEnd && ColumnStart <= ColumnEnd); 199d7369648SVedant Kumar } 200d7369648SVedant Kumar }; 201d7369648SVedant Kumar 2029fc8faf9SAdrian Prantl /// Provides the common functionality for the different 203ee02499aSAlex Lorenz /// coverage mapping region builders. 204ee02499aSAlex Lorenz class CoverageMappingBuilder { 205ee02499aSAlex Lorenz public: 206ee02499aSAlex Lorenz CoverageMappingModuleGen &CVM; 207ee02499aSAlex Lorenz SourceManager &SM; 208ee02499aSAlex Lorenz const LangOptions &LangOpts; 209ee02499aSAlex Lorenz 210ee02499aSAlex Lorenz private: 2119fc8faf9SAdrian Prantl /// Map of clang's FileIDs to IDs used for coverage mapping. 212bf42cfd7SJustin Bogner llvm::SmallDenseMap<FileID, std::pair<unsigned, SourceLocation>, 8> 213bf42cfd7SJustin Bogner FileIDMapping; 214ee02499aSAlex Lorenz 215ee02499aSAlex Lorenz public: 2169fc8faf9SAdrian Prantl /// The coverage mapping regions for this function 217ee02499aSAlex Lorenz llvm::SmallVector<CounterMappingRegion, 32> MappingRegions; 2189fc8faf9SAdrian Prantl /// The source mapping regions for this function. 219f59329b0SJustin Bogner std::vector<SourceMappingRegion> SourceRegions; 220ee02499aSAlex Lorenz 2219fc8faf9SAdrian Prantl /// A set of regions which can be used as a filter. 222fc05ee34SIgor Kudrin /// 223fc05ee34SIgor Kudrin /// It is produced by emitExpansionRegions() and is used in 224fc05ee34SIgor Kudrin /// emitSourceRegions() to suppress producing code regions if 225fc05ee34SIgor Kudrin /// the same area is covered by expansion regions. 226fc05ee34SIgor Kudrin typedef llvm::SmallSet<std::pair<SourceLocation, SourceLocation>, 8> 227fc05ee34SIgor Kudrin SourceRegionFilter; 228fc05ee34SIgor Kudrin 229ee02499aSAlex Lorenz CoverageMappingBuilder(CoverageMappingModuleGen &CVM, SourceManager &SM, 230ee02499aSAlex Lorenz const LangOptions &LangOpts) 231bf42cfd7SJustin Bogner : CVM(CVM), SM(SM), LangOpts(LangOpts) {} 232ee02499aSAlex Lorenz 2339fc8faf9SAdrian Prantl /// Return the precise end location for the given token. 234ee02499aSAlex Lorenz SourceLocation getPreciseTokenLocEnd(SourceLocation Loc) { 235bf42cfd7SJustin Bogner // We avoid getLocForEndOfToken here, because it doesn't do what we want for 236bf42cfd7SJustin Bogner // macro locations, which we just treat as expanded files. 237bf42cfd7SJustin Bogner unsigned TokLen = 238bf42cfd7SJustin Bogner Lexer::MeasureTokenLength(SM.getSpellingLoc(Loc), SM, LangOpts); 239bf42cfd7SJustin Bogner return Loc.getLocWithOffset(TokLen); 240ee02499aSAlex Lorenz } 241ee02499aSAlex Lorenz 2429fc8faf9SAdrian Prantl /// Return the start location of an included file or expanded macro. 243bf42cfd7SJustin Bogner SourceLocation getStartOfFileOrMacro(SourceLocation Loc) { 244bf42cfd7SJustin Bogner if (Loc.isMacroID()) 245bf42cfd7SJustin Bogner return Loc.getLocWithOffset(-SM.getFileOffset(Loc)); 246bf42cfd7SJustin Bogner return SM.getLocForStartOfFile(SM.getFileID(Loc)); 247ee02499aSAlex Lorenz } 248ee02499aSAlex Lorenz 2499fc8faf9SAdrian Prantl /// Return the end location of an included file or expanded macro. 250bf42cfd7SJustin Bogner SourceLocation getEndOfFileOrMacro(SourceLocation Loc) { 251bf42cfd7SJustin Bogner if (Loc.isMacroID()) 252bf42cfd7SJustin Bogner return Loc.getLocWithOffset(SM.getFileIDSize(SM.getFileID(Loc)) - 253f14b2078SJustin Bogner SM.getFileOffset(Loc)); 254bf42cfd7SJustin Bogner return SM.getLocForEndOfFile(SM.getFileID(Loc)); 255bf42cfd7SJustin Bogner } 256ee02499aSAlex Lorenz 2579fc8faf9SAdrian Prantl /// Find out where the current file is included or macro is expanded. 258bf42cfd7SJustin Bogner SourceLocation getIncludeOrExpansionLoc(SourceLocation Loc) { 259b5f8171aSRichard Smith return Loc.isMacroID() ? SM.getImmediateExpansionRange(Loc).getBegin() 260bf42cfd7SJustin Bogner : SM.getIncludeLoc(SM.getFileID(Loc)); 261bf42cfd7SJustin Bogner } 262bf42cfd7SJustin Bogner 2639fc8faf9SAdrian Prantl /// Return true if \c Loc is a location in a built-in macro. 264682bfbf3SJustin Bogner bool isInBuiltin(SourceLocation Loc) { 26599d1b295SMehdi Amini return SM.getBufferName(SM.getSpellingLoc(Loc)) == "<built-in>"; 266682bfbf3SJustin Bogner } 267682bfbf3SJustin Bogner 2689fc8faf9SAdrian Prantl /// Check whether \c Loc is included or expanded from \c Parent. 269d9e1a61dSIgor Kudrin bool isNestedIn(SourceLocation Loc, FileID Parent) { 270d9e1a61dSIgor Kudrin do { 271d9e1a61dSIgor Kudrin Loc = getIncludeOrExpansionLoc(Loc); 272d9e1a61dSIgor Kudrin if (Loc.isInvalid()) 273d9e1a61dSIgor Kudrin return false; 274d9e1a61dSIgor Kudrin } while (!SM.isInFileID(Loc, Parent)); 275d9e1a61dSIgor Kudrin return true; 276d9e1a61dSIgor Kudrin } 277d9e1a61dSIgor Kudrin 2789fc8faf9SAdrian Prantl /// Get the start of \c S ignoring macro arguments and builtin macros. 279bf42cfd7SJustin Bogner SourceLocation getStart(const Stmt *S) { 280f2ceec48SStephen Kelly SourceLocation Loc = S->getBeginLoc(); 281682bfbf3SJustin Bogner while (SM.isMacroArgExpansion(Loc) || isInBuiltin(Loc)) 282b5f8171aSRichard Smith Loc = SM.getImmediateExpansionRange(Loc).getBegin(); 283bf42cfd7SJustin Bogner return Loc; 284bf42cfd7SJustin Bogner } 285bf42cfd7SJustin Bogner 2869fc8faf9SAdrian Prantl /// Get the end of \c S ignoring macro arguments and builtin macros. 287bf42cfd7SJustin Bogner SourceLocation getEnd(const Stmt *S) { 2881c301dcbSStephen Kelly SourceLocation Loc = S->getEndLoc(); 289682bfbf3SJustin Bogner while (SM.isMacroArgExpansion(Loc) || isInBuiltin(Loc)) 290b5f8171aSRichard Smith Loc = SM.getImmediateExpansionRange(Loc).getBegin(); 291f14b2078SJustin Bogner return getPreciseTokenLocEnd(Loc); 292bf42cfd7SJustin Bogner } 293bf42cfd7SJustin Bogner 2949fc8faf9SAdrian Prantl /// Find the set of files we have regions for and assign IDs 295bf42cfd7SJustin Bogner /// 296bf42cfd7SJustin Bogner /// Fills \c Mapping with the virtual file mapping needed to write out 297bf42cfd7SJustin Bogner /// coverage and collects the necessary file information to emit source and 298bf42cfd7SJustin Bogner /// expansion regions. 299bf42cfd7SJustin Bogner void gatherFileIDs(SmallVectorImpl<unsigned> &Mapping) { 300bf42cfd7SJustin Bogner FileIDMapping.clear(); 301bf42cfd7SJustin Bogner 302bc6b80a0SVedant Kumar llvm::SmallSet<FileID, 8> Visited; 303bf42cfd7SJustin Bogner SmallVector<std::pair<SourceLocation, unsigned>, 8> FileLocs; 304bf42cfd7SJustin Bogner for (const auto &Region : SourceRegions) { 305a6e4358fSStephen Kelly SourceLocation Loc = Region.getBeginLoc(); 306bf42cfd7SJustin Bogner FileID File = SM.getFileID(Loc); 307bc6b80a0SVedant Kumar if (!Visited.insert(File).second) 308bf42cfd7SJustin Bogner continue; 309bf42cfd7SJustin Bogner 31093205af0SVedant Kumar // Do not map FileID's associated with system headers. 31193205af0SVedant Kumar if (SM.isInSystemHeader(SM.getSpellingLoc(Loc))) 31293205af0SVedant Kumar continue; 31393205af0SVedant Kumar 314bf42cfd7SJustin Bogner unsigned Depth = 0; 315bf42cfd7SJustin Bogner for (SourceLocation Parent = getIncludeOrExpansionLoc(Loc); 316ed1fe5d0SYaron Keren Parent.isValid(); Parent = getIncludeOrExpansionLoc(Parent)) 317bf42cfd7SJustin Bogner ++Depth; 318bf42cfd7SJustin Bogner FileLocs.push_back(std::make_pair(Loc, Depth)); 319bf42cfd7SJustin Bogner } 320899d1392SFangrui Song llvm::stable_sort(FileLocs, llvm::less_second()); 321bf42cfd7SJustin Bogner 322bf42cfd7SJustin Bogner for (const auto &FL : FileLocs) { 323bf42cfd7SJustin Bogner SourceLocation Loc = FL.first; 324bf42cfd7SJustin Bogner FileID SpellingFile = SM.getDecomposedSpellingLoc(Loc).first; 325ee02499aSAlex Lorenz auto Entry = SM.getFileEntryForID(SpellingFile); 326ee02499aSAlex Lorenz if (!Entry) 327bf42cfd7SJustin Bogner continue; 328ee02499aSAlex Lorenz 329bf42cfd7SJustin Bogner FileIDMapping[SM.getFileID(Loc)] = std::make_pair(Mapping.size(), Loc); 330bf42cfd7SJustin Bogner Mapping.push_back(CVM.getFileID(Entry)); 331bf42cfd7SJustin Bogner } 332ee02499aSAlex Lorenz } 333ee02499aSAlex Lorenz 3349fc8faf9SAdrian Prantl /// Get the coverage mapping file ID for \c Loc. 335bf42cfd7SJustin Bogner /// 336bf42cfd7SJustin Bogner /// If such file id doesn't exist, return None. 337bf42cfd7SJustin Bogner Optional<unsigned> getCoverageFileID(SourceLocation Loc) { 338bf42cfd7SJustin Bogner auto Mapping = FileIDMapping.find(SM.getFileID(Loc)); 339bf42cfd7SJustin Bogner if (Mapping != FileIDMapping.end()) 340bf42cfd7SJustin Bogner return Mapping->second.first; 341903678caSJustin Bogner return None; 342ee02499aSAlex Lorenz } 343ee02499aSAlex Lorenz 344b46176bbSZequan Wu /// This shrinks the skipped range if it spans a line that contains a 345b46176bbSZequan Wu /// non-comment token. If shrinking the skipped range would make it empty, 346b46176bbSZequan Wu /// this returns None. 347b46176bbSZequan Wu Optional<SpellingRegion> adjustSkippedRange(SourceManager &SM, 34884fffa67SZequan Wu SourceLocation LocStart, 34984fffa67SZequan Wu SourceLocation LocEnd, 350b46176bbSZequan Wu SourceLocation PrevTokLoc, 351b46176bbSZequan Wu SourceLocation NextTokLoc) { 35284fffa67SZequan Wu SpellingRegion SR{SM, LocStart, LocEnd}; 3539caa3fbeSZequan Wu SR.ColumnStart = 1; 3549caa3fbeSZequan Wu if (PrevTokLoc.isValid() && SM.isWrittenInSameFile(LocStart, PrevTokLoc) && 3559caa3fbeSZequan Wu SR.LineStart == SM.getSpellingLineNumber(PrevTokLoc)) 3569caa3fbeSZequan Wu SR.LineStart++; 3579caa3fbeSZequan Wu if (NextTokLoc.isValid() && SM.isWrittenInSameFile(LocEnd, NextTokLoc) && 3589caa3fbeSZequan Wu SR.LineEnd == SM.getSpellingLineNumber(NextTokLoc)) { 3599caa3fbeSZequan Wu SR.LineEnd--; 3609caa3fbeSZequan Wu SR.ColumnEnd++; 3619caa3fbeSZequan Wu } 3629caa3fbeSZequan Wu if (SR.isInSourceOrder()) 363b46176bbSZequan Wu return SR; 364b46176bbSZequan Wu return None; 365b46176bbSZequan Wu } 366b46176bbSZequan Wu 3679fc8faf9SAdrian Prantl /// Gather all the regions that were skipped by the preprocessor 368b46176bbSZequan Wu /// using the constructs like #if or comments. 369ee02499aSAlex Lorenz void gatherSkippedRegions() { 370ee02499aSAlex Lorenz /// An array of the minimum lineStarts and the maximum lineEnds 371ee02499aSAlex Lorenz /// for mapping regions from the appropriate source files. 372ee02499aSAlex Lorenz llvm::SmallVector<std::pair<unsigned, unsigned>, 8> FileLineRanges; 373ee02499aSAlex Lorenz FileLineRanges.resize( 374ee02499aSAlex Lorenz FileIDMapping.size(), 375ee02499aSAlex Lorenz std::make_pair(std::numeric_limits<unsigned>::max(), 0)); 376ee02499aSAlex Lorenz for (const auto &R : MappingRegions) { 377ee02499aSAlex Lorenz FileLineRanges[R.FileID].first = 378ee02499aSAlex Lorenz std::min(FileLineRanges[R.FileID].first, R.LineStart); 379ee02499aSAlex Lorenz FileLineRanges[R.FileID].second = 380ee02499aSAlex Lorenz std::max(FileLineRanges[R.FileID].second, R.LineEnd); 381ee02499aSAlex Lorenz } 382ee02499aSAlex Lorenz 383ee02499aSAlex Lorenz auto SkippedRanges = CVM.getSourceInfo().getSkippedRanges(); 384b46176bbSZequan Wu for (auto &I : SkippedRanges) { 385b46176bbSZequan Wu SourceRange Range = I.Range; 386b46176bbSZequan Wu auto LocStart = Range.getBegin(); 387b46176bbSZequan Wu auto LocEnd = Range.getEnd(); 388bf42cfd7SJustin Bogner assert(SM.isWrittenInSameFile(LocStart, LocEnd) && 389bf42cfd7SJustin Bogner "region spans multiple files"); 390ee02499aSAlex Lorenz 391bf42cfd7SJustin Bogner auto CovFileID = getCoverageFileID(LocStart); 392903678caSJustin Bogner if (!CovFileID) 393ee02499aSAlex Lorenz continue; 39484fffa67SZequan Wu Optional<SpellingRegion> SR = 39584fffa67SZequan Wu adjustSkippedRange(SM, LocStart, LocEnd, I.PrevTokLoc, I.NextTokLoc); 39684fffa67SZequan Wu if (!SR.hasValue()) 397b46176bbSZequan Wu continue; 398fd34280bSJustin Bogner auto Region = CounterMappingRegion::makeSkipped( 39984fffa67SZequan Wu *CovFileID, SR->LineStart, SR->ColumnStart, SR->LineEnd, 40084fffa67SZequan Wu SR->ColumnEnd); 401ee02499aSAlex Lorenz // Make sure that we only collect the regions that are inside 4022a8c18d9SAlexander Kornienko // the source code of this function. 403903678caSJustin Bogner if (Region.LineStart >= FileLineRanges[*CovFileID].first && 404903678caSJustin Bogner Region.LineEnd <= FileLineRanges[*CovFileID].second) 405ee02499aSAlex Lorenz MappingRegions.push_back(Region); 406ee02499aSAlex Lorenz } 407ee02499aSAlex Lorenz } 408ee02499aSAlex Lorenz 4099fc8faf9SAdrian Prantl /// Generate the coverage counter mapping regions from collected 410ee02499aSAlex Lorenz /// source regions. 411fc05ee34SIgor Kudrin void emitSourceRegions(const SourceRegionFilter &Filter) { 412bf42cfd7SJustin Bogner for (const auto &Region : SourceRegions) { 413bf42cfd7SJustin Bogner assert(Region.hasEndLoc() && "incomplete region"); 414ee02499aSAlex Lorenz 415a6e4358fSStephen Kelly SourceLocation LocStart = Region.getBeginLoc(); 4168b563665SYaron Keren assert(SM.getFileID(LocStart).isValid() && "region in invalid file"); 417f59329b0SJustin Bogner 41893205af0SVedant Kumar // Ignore regions from system headers. 41993205af0SVedant Kumar if (SM.isInSystemHeader(SM.getSpellingLoc(LocStart))) 42093205af0SVedant Kumar continue; 42193205af0SVedant Kumar 422bf42cfd7SJustin Bogner auto CovFileID = getCoverageFileID(LocStart); 423bf42cfd7SJustin Bogner // Ignore regions that don't have a file, such as builtin macros. 424bf42cfd7SJustin Bogner if (!CovFileID) 425ee02499aSAlex Lorenz continue; 426ee02499aSAlex Lorenz 427f14b2078SJustin Bogner SourceLocation LocEnd = Region.getEndLoc(); 428bf42cfd7SJustin Bogner assert(SM.isWrittenInSameFile(LocStart, LocEnd) && 429bf42cfd7SJustin Bogner "region spans multiple files"); 430bf42cfd7SJustin Bogner 431fc05ee34SIgor Kudrin // Don't add code regions for the area covered by expansion regions. 432fc05ee34SIgor Kudrin // This not only suppresses redundant regions, but sometimes prevents 433fc05ee34SIgor Kudrin // creating regions with wrong counters if, for example, a statement's 434fc05ee34SIgor Kudrin // body ends at the end of a nested macro. 435fc05ee34SIgor Kudrin if (Filter.count(std::make_pair(LocStart, LocEnd))) 436fc05ee34SIgor Kudrin continue; 437fc05ee34SIgor Kudrin 438d7369648SVedant Kumar // Find the spelling locations for the mapping region. 439d7369648SVedant Kumar SpellingRegion SR{SM, LocStart, LocEnd}; 440d7369648SVedant Kumar assert(SR.isInSourceOrder() && "region start and end out of order"); 441a1c4deb7SVedant Kumar 442a1c4deb7SVedant Kumar if (Region.isGap()) { 443a1c4deb7SVedant Kumar MappingRegions.push_back(CounterMappingRegion::makeGapRegion( 444a1c4deb7SVedant Kumar Region.getCounter(), *CovFileID, SR.LineStart, SR.ColumnStart, 445a1c4deb7SVedant Kumar SR.LineEnd, SR.ColumnEnd)); 4469f2967bcSAlan Phipps } else if (Region.isBranch()) { 4479f2967bcSAlan Phipps MappingRegions.push_back(CounterMappingRegion::makeBranchRegion( 4489f2967bcSAlan Phipps Region.getCounter(), Region.getFalseCounter(), *CovFileID, 4499f2967bcSAlan Phipps SR.LineStart, SR.ColumnStart, SR.LineEnd, SR.ColumnEnd)); 450a1c4deb7SVedant Kumar } else { 451bf42cfd7SJustin Bogner MappingRegions.push_back(CounterMappingRegion::makeRegion( 452d7369648SVedant Kumar Region.getCounter(), *CovFileID, SR.LineStart, SR.ColumnStart, 453d7369648SVedant Kumar SR.LineEnd, SR.ColumnEnd)); 454bf42cfd7SJustin Bogner } 455bf42cfd7SJustin Bogner } 456a1c4deb7SVedant Kumar } 457bf42cfd7SJustin Bogner 4589fc8faf9SAdrian Prantl /// Generate expansion regions for each virtual file we've seen. 459fc05ee34SIgor Kudrin SourceRegionFilter emitExpansionRegions() { 460fc05ee34SIgor Kudrin SourceRegionFilter Filter; 461bf42cfd7SJustin Bogner for (const auto &FM : FileIDMapping) { 462bf42cfd7SJustin Bogner SourceLocation ExpandedLoc = FM.second.second; 463bf42cfd7SJustin Bogner SourceLocation ParentLoc = getIncludeOrExpansionLoc(ExpandedLoc); 464bf42cfd7SJustin Bogner if (ParentLoc.isInvalid()) 465ee02499aSAlex Lorenz continue; 466ee02499aSAlex Lorenz 467bf42cfd7SJustin Bogner auto ParentFileID = getCoverageFileID(ParentLoc); 468bf42cfd7SJustin Bogner if (!ParentFileID) 469bf42cfd7SJustin Bogner continue; 470bf42cfd7SJustin Bogner auto ExpandedFileID = getCoverageFileID(ExpandedLoc); 471bf42cfd7SJustin Bogner assert(ExpandedFileID && "expansion in uncovered file"); 472bf42cfd7SJustin Bogner 473bf42cfd7SJustin Bogner SourceLocation LocEnd = getPreciseTokenLocEnd(ParentLoc); 474bf42cfd7SJustin Bogner assert(SM.isWrittenInSameFile(ParentLoc, LocEnd) && 475bf42cfd7SJustin Bogner "region spans multiple files"); 476fc05ee34SIgor Kudrin Filter.insert(std::make_pair(ParentLoc, LocEnd)); 477bf42cfd7SJustin Bogner 478d7369648SVedant Kumar SpellingRegion SR{SM, ParentLoc, LocEnd}; 479d7369648SVedant Kumar assert(SR.isInSourceOrder() && "region start and end out of order"); 480bf42cfd7SJustin Bogner MappingRegions.push_back(CounterMappingRegion::makeExpansion( 481d7369648SVedant Kumar *ParentFileID, *ExpandedFileID, SR.LineStart, SR.ColumnStart, 482d7369648SVedant Kumar SR.LineEnd, SR.ColumnEnd)); 483ee02499aSAlex Lorenz } 484fc05ee34SIgor Kudrin return Filter; 485ee02499aSAlex Lorenz } 486ee02499aSAlex Lorenz }; 487ee02499aSAlex Lorenz 4889fc8faf9SAdrian Prantl /// Creates unreachable coverage regions for the functions that 489ee02499aSAlex Lorenz /// are not emitted. 490ee02499aSAlex Lorenz struct EmptyCoverageMappingBuilder : public CoverageMappingBuilder { 491ee02499aSAlex Lorenz EmptyCoverageMappingBuilder(CoverageMappingModuleGen &CVM, SourceManager &SM, 492ee02499aSAlex Lorenz const LangOptions &LangOpts) 493ee02499aSAlex Lorenz : CoverageMappingBuilder(CVM, SM, LangOpts) {} 494ee02499aSAlex Lorenz 495ee02499aSAlex Lorenz void VisitDecl(const Decl *D) { 496ee02499aSAlex Lorenz if (!D->hasBody()) 497ee02499aSAlex Lorenz return; 498ee02499aSAlex Lorenz auto Body = D->getBody(); 499d9e1a61dSIgor Kudrin SourceLocation Start = getStart(Body); 500d9e1a61dSIgor Kudrin SourceLocation End = getEnd(Body); 501d9e1a61dSIgor Kudrin if (!SM.isWrittenInSameFile(Start, End)) { 502d9e1a61dSIgor Kudrin // Walk up to find the common ancestor. 503d9e1a61dSIgor Kudrin // Correct the locations accordingly. 504d9e1a61dSIgor Kudrin FileID StartFileID = SM.getFileID(Start); 505d9e1a61dSIgor Kudrin FileID EndFileID = SM.getFileID(End); 506d9e1a61dSIgor Kudrin while (StartFileID != EndFileID && !isNestedIn(End, StartFileID)) { 507d9e1a61dSIgor Kudrin Start = getIncludeOrExpansionLoc(Start); 508d9e1a61dSIgor Kudrin assert(Start.isValid() && 509d9e1a61dSIgor Kudrin "Declaration start location not nested within a known region"); 510d9e1a61dSIgor Kudrin StartFileID = SM.getFileID(Start); 511d9e1a61dSIgor Kudrin } 512d9e1a61dSIgor Kudrin while (StartFileID != EndFileID) { 513d9e1a61dSIgor Kudrin End = getPreciseTokenLocEnd(getIncludeOrExpansionLoc(End)); 514d9e1a61dSIgor Kudrin assert(End.isValid() && 515d9e1a61dSIgor Kudrin "Declaration end location not nested within a known region"); 516d9e1a61dSIgor Kudrin EndFileID = SM.getFileID(End); 517d9e1a61dSIgor Kudrin } 518d9e1a61dSIgor Kudrin } 519d9e1a61dSIgor Kudrin SourceRegions.emplace_back(Counter(), Start, End); 520ee02499aSAlex Lorenz } 521ee02499aSAlex Lorenz 5229fc8faf9SAdrian Prantl /// Write the mapping data to the output stream 523ee02499aSAlex Lorenz void write(llvm::raw_ostream &OS) { 524ee02499aSAlex Lorenz SmallVector<unsigned, 16> FileIDMapping; 525bf42cfd7SJustin Bogner gatherFileIDs(FileIDMapping); 526fc05ee34SIgor Kudrin emitSourceRegions(SourceRegionFilter()); 527ee02499aSAlex Lorenz 528efd319a2SVedant Kumar if (MappingRegions.empty()) 529efd319a2SVedant Kumar return; 530efd319a2SVedant Kumar 5315fc8fc2dSCraig Topper CoverageMappingWriter Writer(FileIDMapping, None, MappingRegions); 532ee02499aSAlex Lorenz Writer.write(OS); 533ee02499aSAlex Lorenz } 534ee02499aSAlex Lorenz }; 535ee02499aSAlex Lorenz 5369fc8faf9SAdrian Prantl /// A StmtVisitor that creates coverage mapping regions which map 537ee02499aSAlex Lorenz /// from the source code locations to the PGO counters. 538ee02499aSAlex Lorenz struct CounterCoverageMappingBuilder 539ee02499aSAlex Lorenz : public CoverageMappingBuilder, 540ee02499aSAlex Lorenz public ConstStmtVisitor<CounterCoverageMappingBuilder> { 5419fc8faf9SAdrian Prantl /// The map of statements to count values. 542ee02499aSAlex Lorenz llvm::DenseMap<const Stmt *, unsigned> &CounterMap; 543ee02499aSAlex Lorenz 5449fc8faf9SAdrian Prantl /// A stack of currently live regions. 545bf42cfd7SJustin Bogner std::vector<SourceMappingRegion> RegionStack; 546ee02499aSAlex Lorenz 547747b0e29SVedant Kumar /// The currently deferred region: its end location and count can be set once 548747b0e29SVedant Kumar /// its parent has been popped from the region stack. 549747b0e29SVedant Kumar Optional<SourceMappingRegion> DeferredRegion; 550747b0e29SVedant Kumar 551ee02499aSAlex Lorenz CounterExpressionBuilder Builder; 552ee02499aSAlex Lorenz 5539fc8faf9SAdrian Prantl /// A location in the most recently visited file or macro. 554bf42cfd7SJustin Bogner /// 555bf42cfd7SJustin Bogner /// This is used to adjust the active source regions appropriately when 556bf42cfd7SJustin Bogner /// expressions cross file or macro boundaries. 557bf42cfd7SJustin Bogner SourceLocation MostRecentLocation; 558bf42cfd7SJustin Bogner 5598046d22aSVedant Kumar /// Location of the last terminated region. 5608046d22aSVedant Kumar Optional<std::pair<SourceLocation, size_t>> LastTerminatedRegion; 5618046d22aSVedant Kumar 5629fc8faf9SAdrian Prantl /// Return a counter for the subtraction of \c RHS from \c LHS 563ee02499aSAlex Lorenz Counter subtractCounters(Counter LHS, Counter RHS) { 564ee02499aSAlex Lorenz return Builder.subtract(LHS, RHS); 565ee02499aSAlex Lorenz } 566ee02499aSAlex Lorenz 5679fc8faf9SAdrian Prantl /// Return a counter for the sum of \c LHS and \c RHS. 568ee02499aSAlex Lorenz Counter addCounters(Counter LHS, Counter RHS) { 569ee02499aSAlex Lorenz return Builder.add(LHS, RHS); 570ee02499aSAlex Lorenz } 571ee02499aSAlex Lorenz 572bf42cfd7SJustin Bogner Counter addCounters(Counter C1, Counter C2, Counter C3) { 573bf42cfd7SJustin Bogner return addCounters(addCounters(C1, C2), C3); 574bf42cfd7SJustin Bogner } 575bf42cfd7SJustin Bogner 5769fc8faf9SAdrian Prantl /// Return the region counter for the given statement. 577bf42cfd7SJustin Bogner /// 578ee02499aSAlex Lorenz /// This should only be called on statements that have a dedicated counter. 579bf42cfd7SJustin Bogner Counter getRegionCounter(const Stmt *S) { 580bf42cfd7SJustin Bogner return Counter::getCounter(CounterMap[S]); 581ee02499aSAlex Lorenz } 582ee02499aSAlex Lorenz 5839fc8faf9SAdrian Prantl /// Push a region onto the stack. 584bf42cfd7SJustin Bogner /// 585bf42cfd7SJustin Bogner /// Returns the index on the stack where the region was pushed. This can be 586bf42cfd7SJustin Bogner /// used with popRegions to exit a "scope", ending the region that was pushed. 587bf42cfd7SJustin Bogner size_t pushRegion(Counter Count, Optional<SourceLocation> StartLoc = None, 5889f2967bcSAlan Phipps Optional<SourceLocation> EndLoc = None, 5899f2967bcSAlan Phipps Optional<Counter> FalseCount = None) { 5909f2967bcSAlan Phipps 5919f2967bcSAlan Phipps if (StartLoc && !FalseCount.hasValue()) { 592bf42cfd7SJustin Bogner MostRecentLocation = *StartLoc; 593747b0e29SVedant Kumar completeDeferred(Count, MostRecentLocation); 594747b0e29SVedant Kumar } 5959f2967bcSAlan Phipps 5969f2967bcSAlan Phipps RegionStack.emplace_back(Count, FalseCount, StartLoc, EndLoc, 5979f2967bcSAlan Phipps FalseCount.hasValue()); 598ee02499aSAlex Lorenz 599bf42cfd7SJustin Bogner return RegionStack.size() - 1; 600ee02499aSAlex Lorenz } 601ee02499aSAlex Lorenz 602747b0e29SVedant Kumar /// Complete any pending deferred region by setting its end location and 603747b0e29SVedant Kumar /// count, and then pushing it onto the region stack. 604747b0e29SVedant Kumar size_t completeDeferred(Counter Count, SourceLocation DeferredEndLoc) { 605747b0e29SVedant Kumar size_t Index = RegionStack.size(); 606747b0e29SVedant Kumar if (!DeferredRegion) 607747b0e29SVedant Kumar return Index; 608747b0e29SVedant Kumar 609747b0e29SVedant Kumar // Consume the pending region. 610747b0e29SVedant Kumar SourceMappingRegion DR = DeferredRegion.getValue(); 611747b0e29SVedant Kumar DeferredRegion = None; 612747b0e29SVedant Kumar 613747b0e29SVedant Kumar // If the region ends in an expansion, find the expansion site. 614a6e4358fSStephen Kelly FileID StartFile = SM.getFileID(DR.getBeginLoc()); 615f9a0d44eSVedant Kumar if (SM.getFileID(DeferredEndLoc) != StartFile) { 616747b0e29SVedant Kumar if (isNestedIn(DeferredEndLoc, StartFile)) { 617747b0e29SVedant Kumar do { 618747b0e29SVedant Kumar DeferredEndLoc = getIncludeOrExpansionLoc(DeferredEndLoc); 619747b0e29SVedant Kumar } while (StartFile != SM.getFileID(DeferredEndLoc)); 620f9a0d44eSVedant Kumar } else { 621f9a0d44eSVedant Kumar return Index; 622747b0e29SVedant Kumar } 623747b0e29SVedant Kumar } 624747b0e29SVedant Kumar 625747b0e29SVedant Kumar // The parent of this deferred region ends where the containing decl ends, 626747b0e29SVedant Kumar // so the region isn't useful. 627a6e4358fSStephen Kelly if (DR.getBeginLoc() == DeferredEndLoc) 628747b0e29SVedant Kumar return Index; 629747b0e29SVedant Kumar 630747b0e29SVedant Kumar // If we're visiting statements in non-source order (e.g switch cases or 631747b0e29SVedant Kumar // a loop condition) we can't construct a sensible deferred region. 632a6e4358fSStephen Kelly if (!SpellingRegion(SM, DR.getBeginLoc(), DeferredEndLoc).isInSourceOrder()) 633747b0e29SVedant Kumar return Index; 634747b0e29SVedant Kumar 635a1c4deb7SVedant Kumar DR.setGap(true); 636747b0e29SVedant Kumar DR.setCounter(Count); 637747b0e29SVedant Kumar DR.setEndLoc(DeferredEndLoc); 638747b0e29SVedant Kumar handleFileExit(DeferredEndLoc); 639747b0e29SVedant Kumar RegionStack.push_back(DR); 640747b0e29SVedant Kumar return Index; 641747b0e29SVedant Kumar } 642747b0e29SVedant Kumar 6438046d22aSVedant Kumar /// Complete a deferred region created after a terminated region at the 6448046d22aSVedant Kumar /// top-level. 6458046d22aSVedant Kumar void completeTopLevelDeferredRegion(Counter Count, 6468046d22aSVedant Kumar SourceLocation DeferredEndLoc) { 6478046d22aSVedant Kumar if (DeferredRegion || !LastTerminatedRegion) 6488046d22aSVedant Kumar return; 6498046d22aSVedant Kumar 6508046d22aSVedant Kumar if (LastTerminatedRegion->second != RegionStack.size()) 6518046d22aSVedant Kumar return; 6528046d22aSVedant Kumar 6538046d22aSVedant Kumar SourceLocation Start = LastTerminatedRegion->first; 6548046d22aSVedant Kumar if (SM.getFileID(Start) != SM.getMainFileID()) 6558046d22aSVedant Kumar return; 6568046d22aSVedant Kumar 6578046d22aSVedant Kumar SourceMappingRegion DR = RegionStack.back(); 6588046d22aSVedant Kumar DR.setStartLoc(Start); 6598046d22aSVedant Kumar DR.setDeferred(false); 6608046d22aSVedant Kumar DeferredRegion = DR; 6618046d22aSVedant Kumar completeDeferred(Count, DeferredEndLoc); 6628046d22aSVedant Kumar } 6638046d22aSVedant Kumar 6640c3e3115SVedant Kumar size_t locationDepth(SourceLocation Loc) { 6650c3e3115SVedant Kumar size_t Depth = 0; 6660c3e3115SVedant Kumar while (Loc.isValid()) { 6670c3e3115SVedant Kumar Loc = getIncludeOrExpansionLoc(Loc); 6680c3e3115SVedant Kumar Depth++; 6690c3e3115SVedant Kumar } 6700c3e3115SVedant Kumar return Depth; 6710c3e3115SVedant Kumar } 6720c3e3115SVedant Kumar 6739fc8faf9SAdrian Prantl /// Pop regions from the stack into the function's list of regions. 674bf42cfd7SJustin Bogner /// 675bf42cfd7SJustin Bogner /// Adds all regions from \c ParentIndex to the top of the stack to the 676bf42cfd7SJustin Bogner /// function's \c SourceRegions. 677bf42cfd7SJustin Bogner void popRegions(size_t ParentIndex) { 678bf42cfd7SJustin Bogner assert(RegionStack.size() >= ParentIndex && "parent not in stack"); 679747b0e29SVedant Kumar bool ParentOfDeferredRegion = false; 680bf42cfd7SJustin Bogner while (RegionStack.size() > ParentIndex) { 681bf42cfd7SJustin Bogner SourceMappingRegion &Region = RegionStack.back(); 682bf42cfd7SJustin Bogner if (Region.hasStartLoc()) { 683a6e4358fSStephen Kelly SourceLocation StartLoc = Region.getBeginLoc(); 684bf42cfd7SJustin Bogner SourceLocation EndLoc = Region.hasEndLoc() 685bf42cfd7SJustin Bogner ? Region.getEndLoc() 686bf42cfd7SJustin Bogner : RegionStack[ParentIndex].getEndLoc(); 6879f2967bcSAlan Phipps bool isBranch = Region.isBranch(); 6880c3e3115SVedant Kumar size_t StartDepth = locationDepth(StartLoc); 6890c3e3115SVedant Kumar size_t EndDepth = locationDepth(EndLoc); 690bf42cfd7SJustin Bogner while (!SM.isWrittenInSameFile(StartLoc, EndLoc)) { 6910c3e3115SVedant Kumar bool UnnestStart = StartDepth >= EndDepth; 6920c3e3115SVedant Kumar bool UnnestEnd = EndDepth >= StartDepth; 6930c3e3115SVedant Kumar if (UnnestEnd) { 6949f2967bcSAlan Phipps // The region ends in a nested file or macro expansion. If the 6959f2967bcSAlan Phipps // region is not a branch region, create a separate region for each 6969f2967bcSAlan Phipps // expansion, and for all regions, update the EndLoc. Branch 6979f2967bcSAlan Phipps // regions should not be split in order to keep a straightforward 6989f2967bcSAlan Phipps // correspondance between the region and its associated branch 6999f2967bcSAlan Phipps // condition, even if the condition spans multiple depths. 700bf42cfd7SJustin Bogner SourceLocation NestedLoc = getStartOfFileOrMacro(EndLoc); 701bf42cfd7SJustin Bogner assert(SM.isWrittenInSameFile(NestedLoc, EndLoc)); 702bf42cfd7SJustin Bogner 7039f2967bcSAlan Phipps if (!isBranch && !isRegionAlreadyAdded(NestedLoc, EndLoc)) 7049f2967bcSAlan Phipps SourceRegions.emplace_back(Region.getCounter(), NestedLoc, 7059f2967bcSAlan Phipps EndLoc); 706bf42cfd7SJustin Bogner 707f14b2078SJustin Bogner EndLoc = getPreciseTokenLocEnd(getIncludeOrExpansionLoc(EndLoc)); 708dceaaadfSJustin Bogner if (EndLoc.isInvalid()) 7099f2967bcSAlan Phipps llvm::report_fatal_error( 7109f2967bcSAlan Phipps "File exit not handled before popRegions"); 7110c3e3115SVedant Kumar EndDepth--; 712bf42cfd7SJustin Bogner } 7130c3e3115SVedant Kumar if (UnnestStart) { 7149f2967bcSAlan Phipps // The region ends in a nested file or macro expansion. If the 7159f2967bcSAlan Phipps // region is not a branch region, create a separate region for each 7169f2967bcSAlan Phipps // expansion, and for all regions, update the StartLoc. Branch 7179f2967bcSAlan Phipps // regions should not be split in order to keep a straightforward 7189f2967bcSAlan Phipps // correspondance between the region and its associated branch 7199f2967bcSAlan Phipps // condition, even if the condition spans multiple depths. 7200c3e3115SVedant Kumar SourceLocation NestedLoc = getEndOfFileOrMacro(StartLoc); 7210c3e3115SVedant Kumar assert(SM.isWrittenInSameFile(StartLoc, NestedLoc)); 7220c3e3115SVedant Kumar 7239f2967bcSAlan Phipps if (!isBranch && !isRegionAlreadyAdded(StartLoc, NestedLoc)) 7249f2967bcSAlan Phipps SourceRegions.emplace_back(Region.getCounter(), StartLoc, 7259f2967bcSAlan Phipps NestedLoc); 7260c3e3115SVedant Kumar 7270c3e3115SVedant Kumar StartLoc = getIncludeOrExpansionLoc(StartLoc); 7280c3e3115SVedant Kumar if (StartLoc.isInvalid()) 7299f2967bcSAlan Phipps llvm::report_fatal_error( 7309f2967bcSAlan Phipps "File exit not handled before popRegions"); 7310c3e3115SVedant Kumar StartDepth--; 7320c3e3115SVedant Kumar } 7330c3e3115SVedant Kumar } 7340c3e3115SVedant Kumar Region.setStartLoc(StartLoc); 735bf42cfd7SJustin Bogner Region.setEndLoc(EndLoc); 736bf42cfd7SJustin Bogner 7379f2967bcSAlan Phipps if (!isBranch) { 738bf42cfd7SJustin Bogner MostRecentLocation = EndLoc; 7399f2967bcSAlan Phipps // If this region happens to span an entire expansion, we need to 7409f2967bcSAlan Phipps // make sure we don't overlap the parent region with it. 741bf42cfd7SJustin Bogner if (StartLoc == getStartOfFileOrMacro(StartLoc) && 742bf42cfd7SJustin Bogner EndLoc == getEndOfFileOrMacro(EndLoc)) 743bf42cfd7SJustin Bogner MostRecentLocation = getIncludeOrExpansionLoc(EndLoc); 7449f2967bcSAlan Phipps } 745bf42cfd7SJustin Bogner 746a6e4358fSStephen Kelly assert(SM.isWrittenInSameFile(Region.getBeginLoc(), EndLoc)); 747fa8fa044SVedant Kumar assert(SpellingRegion(SM, Region).isInSourceOrder()); 748f36a5c4aSCraig Topper SourceRegions.push_back(Region); 749747b0e29SVedant Kumar 750747b0e29SVedant Kumar if (ParentOfDeferredRegion) { 751747b0e29SVedant Kumar ParentOfDeferredRegion = false; 752747b0e29SVedant Kumar 753747b0e29SVedant Kumar // If there's an existing deferred region, keep the old one, because 754747b0e29SVedant Kumar // it means there are two consecutive returns (or a similar pattern). 755747b0e29SVedant Kumar if (!DeferredRegion.hasValue() && 756747b0e29SVedant Kumar // File IDs aren't gathered within macro expansions, so it isn't 757747b0e29SVedant Kumar // useful to try and create a deferred region inside of one. 758f9a0d44eSVedant Kumar !EndLoc.isMacroID()) 759747b0e29SVedant Kumar DeferredRegion = 760747b0e29SVedant Kumar SourceMappingRegion(Counter::getZero(), EndLoc, None); 761747b0e29SVedant Kumar } 762747b0e29SVedant Kumar } else if (Region.isDeferred()) { 763747b0e29SVedant Kumar assert(!ParentOfDeferredRegion && "Consecutive deferred regions"); 764747b0e29SVedant Kumar ParentOfDeferredRegion = true; 765bf42cfd7SJustin Bogner } 766bf42cfd7SJustin Bogner RegionStack.pop_back(); 7678046d22aSVedant Kumar 7688046d22aSVedant Kumar // If the zero region pushed after the last terminated region no longer 7698046d22aSVedant Kumar // exists, clear its cached information. 7708046d22aSVedant Kumar if (LastTerminatedRegion && 7718046d22aSVedant Kumar RegionStack.size() < LastTerminatedRegion->second) 7728046d22aSVedant Kumar LastTerminatedRegion = None; 773bf42cfd7SJustin Bogner } 774747b0e29SVedant Kumar assert(!ParentOfDeferredRegion && "Deferred region with no parent"); 775ee02499aSAlex Lorenz } 776ee02499aSAlex Lorenz 7779fc8faf9SAdrian Prantl /// Return the currently active region. 778bf42cfd7SJustin Bogner SourceMappingRegion &getRegion() { 779bf42cfd7SJustin Bogner assert(!RegionStack.empty() && "statement has no region"); 780bf42cfd7SJustin Bogner return RegionStack.back(); 781ee02499aSAlex Lorenz } 782ee02499aSAlex Lorenz 7837225a261SVedant Kumar /// Propagate counts through the children of \p S if \p VisitChildren is true. 7847225a261SVedant Kumar /// Otherwise, only emit a count for \p S itself. 7857225a261SVedant Kumar Counter propagateCounts(Counter TopCount, const Stmt *S, 7867225a261SVedant Kumar bool VisitChildren = true) { 7877838696eSVedant Kumar SourceLocation StartLoc = getStart(S); 7887838696eSVedant Kumar SourceLocation EndLoc = getEnd(S); 7897838696eSVedant Kumar size_t Index = pushRegion(TopCount, StartLoc, EndLoc); 7907225a261SVedant Kumar if (VisitChildren) 791bf42cfd7SJustin Bogner Visit(S); 792bf42cfd7SJustin Bogner Counter ExitCount = getRegion().getCounter(); 793bf42cfd7SJustin Bogner popRegions(Index); 79439f01975SVedant Kumar 79539f01975SVedant Kumar // The statement may be spanned by an expansion. Make sure we handle a file 79639f01975SVedant Kumar // exit out of this expansion before moving to the next statement. 797f2ceec48SStephen Kelly if (SM.isBeforeInTranslationUnit(StartLoc, S->getBeginLoc())) 7987838696eSVedant Kumar MostRecentLocation = EndLoc; 79939f01975SVedant Kumar 800bf42cfd7SJustin Bogner return ExitCount; 801ee02499aSAlex Lorenz } 802ee02499aSAlex Lorenz 8039f2967bcSAlan Phipps /// Determine whether the given condition can be constant folded. 8049f2967bcSAlan Phipps bool ConditionFoldsToBool(const Expr *Cond) { 8059f2967bcSAlan Phipps Expr::EvalResult Result; 8069f2967bcSAlan Phipps return (Cond->EvaluateAsInt(Result, CVM.getCodeGenModule().getContext())); 8079f2967bcSAlan Phipps } 8089f2967bcSAlan Phipps 8099f2967bcSAlan Phipps /// Create a Branch Region around an instrumentable condition for coverage 8109f2967bcSAlan Phipps /// and add it to the function's SourceRegions. A branch region tracks a 8119f2967bcSAlan Phipps /// "True" counter and a "False" counter for boolean expressions that 8129f2967bcSAlan Phipps /// result in the generation of a branch. 8139f2967bcSAlan Phipps void createBranchRegion(const Expr *C, Counter TrueCnt, Counter FalseCnt) { 8149f2967bcSAlan Phipps // Check for NULL conditions. 8159f2967bcSAlan Phipps if (!C) 8169f2967bcSAlan Phipps return; 8179f2967bcSAlan Phipps 8189f2967bcSAlan Phipps // Ensure we are an instrumentable condition (i.e. no "&&" or "||"). Push 8199f2967bcSAlan Phipps // region onto RegionStack but immediately pop it (which adds it to the 8209f2967bcSAlan Phipps // function's SourceRegions) because it doesn't apply to any other source 8219f2967bcSAlan Phipps // code other than the Condition. 8229f2967bcSAlan Phipps if (CodeGenFunction::isInstrumentedCondition(C)) { 8239f2967bcSAlan Phipps // If a condition can fold to true or false, the corresponding branch 8249f2967bcSAlan Phipps // will be removed. Create a region with both counters hard-coded to 8259f2967bcSAlan Phipps // zero. This allows us to visualize them in a special way. 8269f2967bcSAlan Phipps // Alternatively, we can prevent any optimization done via 8279f2967bcSAlan Phipps // constant-folding by ensuring that ConstantFoldsToSimpleInteger() in 8289f2967bcSAlan Phipps // CodeGenFunction.c always returns false, but that is very heavy-handed. 8299f2967bcSAlan Phipps if (ConditionFoldsToBool(C)) 8309f2967bcSAlan Phipps popRegions(pushRegion(Counter::getZero(), getStart(C), getEnd(C), 8319f2967bcSAlan Phipps Counter::getZero())); 8329f2967bcSAlan Phipps else 8339f2967bcSAlan Phipps // Otherwise, create a region with the True counter and False counter. 8349f2967bcSAlan Phipps popRegions(pushRegion(TrueCnt, getStart(C), getEnd(C), FalseCnt)); 8359f2967bcSAlan Phipps } 8369f2967bcSAlan Phipps } 8379f2967bcSAlan Phipps 8389f2967bcSAlan Phipps /// Create a Branch Region around a SwitchCase for code coverage 8399f2967bcSAlan Phipps /// and add it to the function's SourceRegions. 8409f2967bcSAlan Phipps void createSwitchCaseRegion(const SwitchCase *SC, Counter TrueCnt, 8419f2967bcSAlan Phipps Counter FalseCnt) { 8429f2967bcSAlan Phipps // Push region onto RegionStack but immediately pop it (which adds it to 8439f2967bcSAlan Phipps // the function's SourceRegions) because it doesn't apply to any other 8449f2967bcSAlan Phipps // source other than the SwitchCase. 8459f2967bcSAlan Phipps popRegions(pushRegion(TrueCnt, getStart(SC), SC->getColonLoc(), FalseCnt)); 8469f2967bcSAlan Phipps } 8479f2967bcSAlan Phipps 8489fc8faf9SAdrian Prantl /// Check whether a region with bounds \c StartLoc and \c EndLoc 8490a7c9d11SIgor Kudrin /// is already added to \c SourceRegions. 8509f2967bcSAlan Phipps bool isRegionAlreadyAdded(SourceLocation StartLoc, SourceLocation EndLoc, 8519f2967bcSAlan Phipps bool isBranch = false) { 8520a7c9d11SIgor Kudrin return SourceRegions.rend() != 8530a7c9d11SIgor Kudrin std::find_if(SourceRegions.rbegin(), SourceRegions.rend(), 8540a7c9d11SIgor Kudrin [&](const SourceMappingRegion &Region) { 855a6e4358fSStephen Kelly return Region.getBeginLoc() == StartLoc && 8569f2967bcSAlan Phipps Region.getEndLoc() == EndLoc && 8579f2967bcSAlan Phipps Region.isBranch() == isBranch; 8580a7c9d11SIgor Kudrin }); 8590a7c9d11SIgor Kudrin } 8600a7c9d11SIgor Kudrin 8619fc8faf9SAdrian Prantl /// Adjust the most recently visited location to \c EndLoc. 862bf42cfd7SJustin Bogner /// 863bf42cfd7SJustin Bogner /// This should be used after visiting any statements in non-source order. 864bf42cfd7SJustin Bogner void adjustForOutOfOrderTraversal(SourceLocation EndLoc) { 865bf42cfd7SJustin Bogner MostRecentLocation = EndLoc; 8660a7c9d11SIgor Kudrin // The code region for a whole macro is created in handleFileExit() when 8670a7c9d11SIgor Kudrin // it detects exiting of the virtual file of that macro. If we visited 8680a7c9d11SIgor Kudrin // statements in non-source order, we might already have such a region 8690a7c9d11SIgor Kudrin // added, for example, if a body of a loop is divided among multiple 8700a7c9d11SIgor Kudrin // macros. Avoid adding duplicate regions in such case. 87196ae73f7SJustin Bogner if (getRegion().hasEndLoc() && 8720a7c9d11SIgor Kudrin MostRecentLocation == getEndOfFileOrMacro(MostRecentLocation) && 8730a7c9d11SIgor Kudrin isRegionAlreadyAdded(getStartOfFileOrMacro(MostRecentLocation), 8749f2967bcSAlan Phipps MostRecentLocation, getRegion().isBranch())) 875bf42cfd7SJustin Bogner MostRecentLocation = getIncludeOrExpansionLoc(MostRecentLocation); 876ee02499aSAlex Lorenz } 877ee02499aSAlex Lorenz 8789fc8faf9SAdrian Prantl /// Adjust regions and state when \c NewLoc exits a file. 879bf42cfd7SJustin Bogner /// 880bf42cfd7SJustin Bogner /// If moving from our most recently tracked location to \c NewLoc exits any 881bf42cfd7SJustin Bogner /// files, this adjusts our current region stack and creates the file regions 882bf42cfd7SJustin Bogner /// for the exited file. 883bf42cfd7SJustin Bogner void handleFileExit(SourceLocation NewLoc) { 884e44dd6dbSJustin Bogner if (NewLoc.isInvalid() || 885e44dd6dbSJustin Bogner SM.isWrittenInSameFile(MostRecentLocation, NewLoc)) 886bf42cfd7SJustin Bogner return; 887bf42cfd7SJustin Bogner 888bf42cfd7SJustin Bogner // If NewLoc is not in a file that contains MostRecentLocation, walk up to 889bf42cfd7SJustin Bogner // find the common ancestor. 890bf42cfd7SJustin Bogner SourceLocation LCA = NewLoc; 891bf42cfd7SJustin Bogner FileID ParentFile = SM.getFileID(LCA); 892bf42cfd7SJustin Bogner while (!isNestedIn(MostRecentLocation, ParentFile)) { 893bf42cfd7SJustin Bogner LCA = getIncludeOrExpansionLoc(LCA); 894bf42cfd7SJustin Bogner if (LCA.isInvalid() || SM.isWrittenInSameFile(LCA, MostRecentLocation)) { 895bf42cfd7SJustin Bogner // Since there isn't a common ancestor, no file was exited. We just need 896bf42cfd7SJustin Bogner // to adjust our location to the new file. 897bf42cfd7SJustin Bogner MostRecentLocation = NewLoc; 898bf42cfd7SJustin Bogner return; 899bf42cfd7SJustin Bogner } 900bf42cfd7SJustin Bogner ParentFile = SM.getFileID(LCA); 901ee02499aSAlex Lorenz } 902ee02499aSAlex Lorenz 903bf42cfd7SJustin Bogner llvm::SmallSet<SourceLocation, 8> StartLocs; 904bf42cfd7SJustin Bogner Optional<Counter> ParentCounter; 90557d3f145SPete Cooper for (SourceMappingRegion &I : llvm::reverse(RegionStack)) { 90657d3f145SPete Cooper if (!I.hasStartLoc()) 907bf42cfd7SJustin Bogner continue; 908a6e4358fSStephen Kelly SourceLocation Loc = I.getBeginLoc(); 909bf42cfd7SJustin Bogner if (!isNestedIn(Loc, ParentFile)) { 91057d3f145SPete Cooper ParentCounter = I.getCounter(); 911bf42cfd7SJustin Bogner break; 912ee02499aSAlex Lorenz } 913bf42cfd7SJustin Bogner 914bf42cfd7SJustin Bogner while (!SM.isInFileID(Loc, ParentFile)) { 915bf42cfd7SJustin Bogner // The most nested region for each start location is the one with the 916bf42cfd7SJustin Bogner // correct count. We avoid creating redundant regions by stopping once 917bf42cfd7SJustin Bogner // we've seen this region. 9189f2967bcSAlan Phipps if (StartLocs.insert(Loc).second) { 9199f2967bcSAlan Phipps if (I.isBranch()) 9209f2967bcSAlan Phipps SourceRegions.emplace_back(I.getCounter(), I.getFalseCounter(), Loc, 9219f2967bcSAlan Phipps getEndOfFileOrMacro(Loc), I.isBranch()); 9229f2967bcSAlan Phipps else 92357d3f145SPete Cooper SourceRegions.emplace_back(I.getCounter(), Loc, 924bf42cfd7SJustin Bogner getEndOfFileOrMacro(Loc)); 9259f2967bcSAlan Phipps } 926bf42cfd7SJustin Bogner Loc = getIncludeOrExpansionLoc(Loc); 927ee02499aSAlex Lorenz } 92857d3f145SPete Cooper I.setStartLoc(getPreciseTokenLocEnd(Loc)); 929bf42cfd7SJustin Bogner } 930bf42cfd7SJustin Bogner 931bf42cfd7SJustin Bogner if (ParentCounter) { 932bf42cfd7SJustin Bogner // If the file is contained completely by another region and doesn't 933bf42cfd7SJustin Bogner // immediately start its own region, the whole file gets a region 934bf42cfd7SJustin Bogner // corresponding to the parent. 935bf42cfd7SJustin Bogner SourceLocation Loc = MostRecentLocation; 936bf42cfd7SJustin Bogner while (isNestedIn(Loc, ParentFile)) { 937bf42cfd7SJustin Bogner SourceLocation FileStart = getStartOfFileOrMacro(Loc); 938fa8fa044SVedant Kumar if (StartLocs.insert(FileStart).second) { 939bf42cfd7SJustin Bogner SourceRegions.emplace_back(*ParentCounter, FileStart, 940bf42cfd7SJustin Bogner getEndOfFileOrMacro(Loc)); 941fa8fa044SVedant Kumar assert(SpellingRegion(SM, SourceRegions.back()).isInSourceOrder()); 942fa8fa044SVedant Kumar } 943bf42cfd7SJustin Bogner Loc = getIncludeOrExpansionLoc(Loc); 944bf42cfd7SJustin Bogner } 945bf42cfd7SJustin Bogner } 946bf42cfd7SJustin Bogner 947bf42cfd7SJustin Bogner MostRecentLocation = NewLoc; 948bf42cfd7SJustin Bogner } 949bf42cfd7SJustin Bogner 9509fc8faf9SAdrian Prantl /// Ensure that \c S is included in the current region. 951bf42cfd7SJustin Bogner void extendRegion(const Stmt *S) { 952bf42cfd7SJustin Bogner SourceMappingRegion &Region = getRegion(); 953bf42cfd7SJustin Bogner SourceLocation StartLoc = getStart(S); 954bf42cfd7SJustin Bogner 955bf42cfd7SJustin Bogner handleFileExit(StartLoc); 956bf42cfd7SJustin Bogner if (!Region.hasStartLoc()) 957bf42cfd7SJustin Bogner Region.setStartLoc(StartLoc); 958747b0e29SVedant Kumar 959747b0e29SVedant Kumar completeDeferred(Region.getCounter(), StartLoc); 960bf42cfd7SJustin Bogner } 961bf42cfd7SJustin Bogner 9629fc8faf9SAdrian Prantl /// Mark \c S as a terminator, starting a zero region. 963bf42cfd7SJustin Bogner void terminateRegion(const Stmt *S) { 964bf42cfd7SJustin Bogner extendRegion(S); 965bf42cfd7SJustin Bogner SourceMappingRegion &Region = getRegion(); 9668046d22aSVedant Kumar SourceLocation EndLoc = getEnd(S); 967bf42cfd7SJustin Bogner if (!Region.hasEndLoc()) 9688046d22aSVedant Kumar Region.setEndLoc(EndLoc); 969bf42cfd7SJustin Bogner pushRegion(Counter::getZero()); 9708046d22aSVedant Kumar auto &ZeroRegion = getRegion(); 9718046d22aSVedant Kumar ZeroRegion.setDeferred(true); 9728046d22aSVedant Kumar LastTerminatedRegion = {EndLoc, RegionStack.size()}; 973bf42cfd7SJustin Bogner } 974ee02499aSAlex Lorenz 975fa8fa044SVedant Kumar /// Find a valid gap range between \p AfterLoc and \p BeforeLoc. 976fa8fa044SVedant Kumar Optional<SourceRange> findGapAreaBetween(SourceLocation AfterLoc, 977fa8fa044SVedant Kumar SourceLocation BeforeLoc) { 9789500a720SZequan Wu // If the start and end locations of the gap are both within the same macro 9799500a720SZequan Wu // file, the range may not be in source order. 9809500a720SZequan Wu if (AfterLoc.isMacroID() || BeforeLoc.isMacroID()) 9819500a720SZequan Wu return None; 982fa8fa044SVedant Kumar if (!SM.isWrittenInSameFile(AfterLoc, BeforeLoc)) 983fa8fa044SVedant Kumar return None; 984fa8fa044SVedant Kumar return {{AfterLoc, BeforeLoc}}; 985fa8fa044SVedant Kumar } 986fa8fa044SVedant Kumar 9879500a720SZequan Wu /// Find the source range after \p AfterStmt and before \p BeforeStmt. 9889500a720SZequan Wu Optional<SourceRange> findGapAreaBetween(const Stmt *AfterStmt, 9899500a720SZequan Wu const Stmt *BeforeStmt) { 9909500a720SZequan Wu return findGapAreaBetween(getPreciseTokenLocEnd(getEnd(AfterStmt)), 9919500a720SZequan Wu getStart(BeforeStmt)); 9929500a720SZequan Wu } 9939500a720SZequan Wu 9942e8c8759SVedant Kumar /// Emit a gap region between \p StartLoc and \p EndLoc with the given count. 9952e8c8759SVedant Kumar void fillGapAreaWithCount(SourceLocation StartLoc, SourceLocation EndLoc, 9962e8c8759SVedant Kumar Counter Count) { 997fa8fa044SVedant Kumar if (StartLoc == EndLoc) 9982e8c8759SVedant Kumar return; 999fa8fa044SVedant Kumar assert(SpellingRegion(SM, StartLoc, EndLoc).isInSourceOrder()); 10002e8c8759SVedant Kumar handleFileExit(StartLoc); 10012e8c8759SVedant Kumar size_t Index = pushRegion(Count, StartLoc, EndLoc); 10022e8c8759SVedant Kumar getRegion().setGap(true); 10032e8c8759SVedant Kumar handleFileExit(EndLoc); 10042e8c8759SVedant Kumar popRegions(Index); 10052e8c8759SVedant Kumar } 10062e8c8759SVedant Kumar 10079fc8faf9SAdrian Prantl /// Keep counts of breaks and continues inside loops. 1008ee02499aSAlex Lorenz struct BreakContinue { 1009ee02499aSAlex Lorenz Counter BreakCount; 1010ee02499aSAlex Lorenz Counter ContinueCount; 1011ee02499aSAlex Lorenz }; 1012ee02499aSAlex Lorenz SmallVector<BreakContinue, 8> BreakContinueStack; 1013ee02499aSAlex Lorenz 1014ee02499aSAlex Lorenz CounterCoverageMappingBuilder( 1015ee02499aSAlex Lorenz CoverageMappingModuleGen &CVM, 1016e5ee6c58SJustin Bogner llvm::DenseMap<const Stmt *, unsigned> &CounterMap, SourceManager &SM, 1017ee02499aSAlex Lorenz const LangOptions &LangOpts) 1018747b0e29SVedant Kumar : CoverageMappingBuilder(CVM, SM, LangOpts), CounterMap(CounterMap), 1019747b0e29SVedant Kumar DeferredRegion(None) {} 1020ee02499aSAlex Lorenz 10219fc8faf9SAdrian Prantl /// Write the mapping data to the output stream 1022ee02499aSAlex Lorenz void write(llvm::raw_ostream &OS) { 1023ee02499aSAlex Lorenz llvm::SmallVector<unsigned, 8> VirtualFileMapping; 1024bf42cfd7SJustin Bogner gatherFileIDs(VirtualFileMapping); 1025fc05ee34SIgor Kudrin SourceRegionFilter Filter = emitExpansionRegions(); 1026747b0e29SVedant Kumar assert(!DeferredRegion && "Deferred region never completed"); 1027fc05ee34SIgor Kudrin emitSourceRegions(Filter); 1028ee02499aSAlex Lorenz gatherSkippedRegions(); 1029ee02499aSAlex Lorenz 1030efd319a2SVedant Kumar if (MappingRegions.empty()) 1031efd319a2SVedant Kumar return; 1032efd319a2SVedant Kumar 10334da909b2SJustin Bogner CoverageMappingWriter Writer(VirtualFileMapping, Builder.getExpressions(), 10344da909b2SJustin Bogner MappingRegions); 1035ee02499aSAlex Lorenz Writer.write(OS); 1036ee02499aSAlex Lorenz } 1037ee02499aSAlex Lorenz 1038ee02499aSAlex Lorenz void VisitStmt(const Stmt *S) { 1039f2ceec48SStephen Kelly if (S->getBeginLoc().isValid()) 1040bf42cfd7SJustin Bogner extendRegion(S); 1041642f173aSBenjamin Kramer for (const Stmt *Child : S->children()) 1042642f173aSBenjamin Kramer if (Child) 1043642f173aSBenjamin Kramer this->Visit(Child); 1044bf42cfd7SJustin Bogner handleFileExit(getEnd(S)); 1045ee02499aSAlex Lorenz } 1046ee02499aSAlex Lorenz 1047ee02499aSAlex Lorenz void VisitDecl(const Decl *D) { 1048747b0e29SVedant Kumar assert(!DeferredRegion && "Deferred region never completed"); 1049747b0e29SVedant Kumar 1050bf42cfd7SJustin Bogner Stmt *Body = D->getBody(); 1051efd319a2SVedant Kumar 1052efd319a2SVedant Kumar // Do not propagate region counts into system headers. 1053efd319a2SVedant Kumar if (Body && SM.isInSystemHeader(SM.getSpellingLoc(getStart(Body)))) 1054efd319a2SVedant Kumar return; 1055efd319a2SVedant Kumar 10567225a261SVedant Kumar // Do not visit the artificial children nodes of defaulted methods. The 10577225a261SVedant Kumar // lexer may not be able to report back precise token end locations for 10587225a261SVedant Kumar // these children nodes (llvm.org/PR39822), and moreover users will not be 10597225a261SVedant Kumar // able to see coverage for them. 10607225a261SVedant Kumar bool Defaulted = false; 10617225a261SVedant Kumar if (auto *Method = dyn_cast<CXXMethodDecl>(D)) 10627225a261SVedant Kumar Defaulted = Method->isDefaulted(); 10637225a261SVedant Kumar 10647225a261SVedant Kumar propagateCounts(getRegionCounter(Body), Body, 10657225a261SVedant Kumar /*VisitChildren=*/!Defaulted); 1066747b0e29SVedant Kumar assert(RegionStack.empty() && "Regions entered but never exited"); 1067747b0e29SVedant Kumar 106861763b65SVedant Kumar // Discard the last uncompleted deferred region in a decl, if one exists. 106961763b65SVedant Kumar // This prevents lines at the end of a function containing only whitespace 107061763b65SVedant Kumar // or closing braces from being marked as uncovered. 1071ef8e05ffSVedant Kumar DeferredRegion = None; 1072341bf429SVedant Kumar } 1073ee02499aSAlex Lorenz 1074ee02499aSAlex Lorenz void VisitReturnStmt(const ReturnStmt *S) { 1075bf42cfd7SJustin Bogner extendRegion(S); 1076ee02499aSAlex Lorenz if (S->getRetValue()) 1077ee02499aSAlex Lorenz Visit(S->getRetValue()); 1078bf42cfd7SJustin Bogner terminateRegion(S); 1079ee02499aSAlex Lorenz } 1080ee02499aSAlex Lorenz 1081565e37c7SXun Li void VisitCoroutineBodyStmt(const CoroutineBodyStmt *S) { 1082565e37c7SXun Li extendRegion(S); 1083565e37c7SXun Li Visit(S->getBody()); 1084565e37c7SXun Li } 1085565e37c7SXun Li 1086565e37c7SXun Li void VisitCoreturnStmt(const CoreturnStmt *S) { 1087565e37c7SXun Li extendRegion(S); 1088565e37c7SXun Li if (S->getOperand()) 1089565e37c7SXun Li Visit(S->getOperand()); 1090565e37c7SXun Li terminateRegion(S); 1091565e37c7SXun Li } 1092565e37c7SXun Li 1093f959febfSJustin Bogner void VisitCXXThrowExpr(const CXXThrowExpr *E) { 1094f959febfSJustin Bogner extendRegion(E); 1095f959febfSJustin Bogner if (E->getSubExpr()) 1096f959febfSJustin Bogner Visit(E->getSubExpr()); 1097f959febfSJustin Bogner terminateRegion(E); 1098f959febfSJustin Bogner } 1099f959febfSJustin Bogner 1100bf42cfd7SJustin Bogner void VisitGotoStmt(const GotoStmt *S) { terminateRegion(S); } 1101ee02499aSAlex Lorenz 1102ee02499aSAlex Lorenz void VisitLabelStmt(const LabelStmt *S) { 11038046d22aSVedant Kumar Counter LabelCount = getRegionCounter(S); 1104bf42cfd7SJustin Bogner SourceLocation Start = getStart(S); 11058046d22aSVedant Kumar completeTopLevelDeferredRegion(LabelCount, Start); 1106d781d97eSVedant Kumar completeDeferred(LabelCount, Start); 1107bf42cfd7SJustin Bogner // We can't extendRegion here or we risk overlapping with our new region. 1108bf42cfd7SJustin Bogner handleFileExit(Start); 11098046d22aSVedant Kumar pushRegion(LabelCount, Start); 1110ee02499aSAlex Lorenz Visit(S->getSubStmt()); 1111ee02499aSAlex Lorenz } 1112ee02499aSAlex Lorenz 1113ee02499aSAlex Lorenz void VisitBreakStmt(const BreakStmt *S) { 1114ee02499aSAlex Lorenz assert(!BreakContinueStack.empty() && "break not in a loop or switch!"); 1115ee02499aSAlex Lorenz BreakContinueStack.back().BreakCount = addCounters( 1116bf42cfd7SJustin Bogner BreakContinueStack.back().BreakCount, getRegion().getCounter()); 11177f53fbfcSEli Friedman // FIXME: a break in a switch should terminate regions for all preceding 11187f53fbfcSEli Friedman // case statements, not just the most recent one. 1119bf42cfd7SJustin Bogner terminateRegion(S); 1120ee02499aSAlex Lorenz } 1121ee02499aSAlex Lorenz 1122ee02499aSAlex Lorenz void VisitContinueStmt(const ContinueStmt *S) { 1123ee02499aSAlex Lorenz assert(!BreakContinueStack.empty() && "continue stmt not in a loop!"); 1124ee02499aSAlex Lorenz BreakContinueStack.back().ContinueCount = addCounters( 1125bf42cfd7SJustin Bogner BreakContinueStack.back().ContinueCount, getRegion().getCounter()); 1126bf42cfd7SJustin Bogner terminateRegion(S); 1127ee02499aSAlex Lorenz } 1128ee02499aSAlex Lorenz 1129181dfe4cSEli Friedman void VisitCallExpr(const CallExpr *E) { 1130181dfe4cSEli Friedman VisitStmt(E); 1131181dfe4cSEli Friedman 1132181dfe4cSEli Friedman // Terminate the region when we hit a noreturn function. 1133181dfe4cSEli Friedman // (This is helpful dealing with switch statements.) 1134181dfe4cSEli Friedman QualType CalleeType = E->getCallee()->getType(); 1135181dfe4cSEli Friedman if (getFunctionExtInfo(*CalleeType).getNoReturn()) 1136181dfe4cSEli Friedman terminateRegion(E); 1137181dfe4cSEli Friedman } 1138181dfe4cSEli Friedman 1139ee02499aSAlex Lorenz void VisitWhileStmt(const WhileStmt *S) { 1140bf42cfd7SJustin Bogner extendRegion(S); 1141ee02499aSAlex Lorenz 1142bf42cfd7SJustin Bogner Counter ParentCount = getRegion().getCounter(); 1143bf42cfd7SJustin Bogner Counter BodyCount = getRegionCounter(S); 1144bf42cfd7SJustin Bogner 1145bf42cfd7SJustin Bogner // Handle the body first so that we can get the backedge count. 1146bf42cfd7SJustin Bogner BreakContinueStack.push_back(BreakContinue()); 1147bf42cfd7SJustin Bogner extendRegion(S->getBody()); 1148bf42cfd7SJustin Bogner Counter BackedgeCount = propagateCounts(BodyCount, S->getBody()); 1149ee02499aSAlex Lorenz BreakContinue BC = BreakContinueStack.pop_back_val(); 1150bf42cfd7SJustin Bogner 1151bf42cfd7SJustin Bogner // Go back to handle the condition. 1152bf42cfd7SJustin Bogner Counter CondCount = 1153bf42cfd7SJustin Bogner addCounters(ParentCount, BackedgeCount, BC.ContinueCount); 1154bf42cfd7SJustin Bogner propagateCounts(CondCount, S->getCond()); 1155bf42cfd7SJustin Bogner adjustForOutOfOrderTraversal(getEnd(S)); 1156bf42cfd7SJustin Bogner 1157fa8fa044SVedant Kumar // The body count applies to the area immediately after the increment. 11589500a720SZequan Wu auto Gap = findGapAreaBetween(S->getCond(), S->getBody()); 1159fa8fa044SVedant Kumar if (Gap) 1160fa8fa044SVedant Kumar fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount); 1161fa8fa044SVedant Kumar 1162bf42cfd7SJustin Bogner Counter OutCount = 1163bf42cfd7SJustin Bogner addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount)); 1164bf42cfd7SJustin Bogner if (OutCount != ParentCount) 1165bf42cfd7SJustin Bogner pushRegion(OutCount); 11669f2967bcSAlan Phipps 11679f2967bcSAlan Phipps // Create Branch Region around condition. 11689f2967bcSAlan Phipps createBranchRegion(S->getCond(), BodyCount, 11699f2967bcSAlan Phipps subtractCounters(CondCount, BodyCount)); 1170ee02499aSAlex Lorenz } 1171ee02499aSAlex Lorenz 1172ee02499aSAlex Lorenz void VisitDoStmt(const DoStmt *S) { 1173bf42cfd7SJustin Bogner extendRegion(S); 1174ee02499aSAlex Lorenz 1175bf42cfd7SJustin Bogner Counter ParentCount = getRegion().getCounter(); 1176bf42cfd7SJustin Bogner Counter BodyCount = getRegionCounter(S); 1177bf42cfd7SJustin Bogner 1178bf42cfd7SJustin Bogner BreakContinueStack.push_back(BreakContinue()); 1179bf42cfd7SJustin Bogner extendRegion(S->getBody()); 1180bf42cfd7SJustin Bogner Counter BackedgeCount = 1181bf42cfd7SJustin Bogner propagateCounts(addCounters(ParentCount, BodyCount), S->getBody()); 1182ee02499aSAlex Lorenz BreakContinue BC = BreakContinueStack.pop_back_val(); 1183bf42cfd7SJustin Bogner 1184bf42cfd7SJustin Bogner Counter CondCount = addCounters(BackedgeCount, BC.ContinueCount); 1185bf42cfd7SJustin Bogner propagateCounts(CondCount, S->getCond()); 1186bf42cfd7SJustin Bogner 1187bf42cfd7SJustin Bogner Counter OutCount = 1188bf42cfd7SJustin Bogner addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount)); 1189bf42cfd7SJustin Bogner if (OutCount != ParentCount) 1190bf42cfd7SJustin Bogner pushRegion(OutCount); 11919f2967bcSAlan Phipps 11929f2967bcSAlan Phipps // Create Branch Region around condition. 11939f2967bcSAlan Phipps createBranchRegion(S->getCond(), BodyCount, 11949f2967bcSAlan Phipps subtractCounters(CondCount, BodyCount)); 1195ee02499aSAlex Lorenz } 1196ee02499aSAlex Lorenz 1197ee02499aSAlex Lorenz void VisitForStmt(const ForStmt *S) { 1198bf42cfd7SJustin Bogner extendRegion(S); 1199ee02499aSAlex Lorenz if (S->getInit()) 1200ee02499aSAlex Lorenz Visit(S->getInit()); 1201ee02499aSAlex Lorenz 1202bf42cfd7SJustin Bogner Counter ParentCount = getRegion().getCounter(); 1203bf42cfd7SJustin Bogner Counter BodyCount = getRegionCounter(S); 1204bf42cfd7SJustin Bogner 12053e2ae49aSVedant Kumar // The loop increment may contain a break or continue. 12063e2ae49aSVedant Kumar if (S->getInc()) 12073e2ae49aSVedant Kumar BreakContinueStack.emplace_back(); 12083e2ae49aSVedant Kumar 1209bf42cfd7SJustin Bogner // Handle the body first so that we can get the backedge count. 12103e2ae49aSVedant Kumar BreakContinueStack.emplace_back(); 1211bf42cfd7SJustin Bogner extendRegion(S->getBody()); 1212bf42cfd7SJustin Bogner Counter BackedgeCount = propagateCounts(BodyCount, S->getBody()); 12133e2ae49aSVedant Kumar BreakContinue BodyBC = BreakContinueStack.pop_back_val(); 1214ee02499aSAlex Lorenz 1215ee02499aSAlex Lorenz // The increment is essentially part of the body but it needs to include 1216ee02499aSAlex Lorenz // the count for all the continue statements. 12173e2ae49aSVedant Kumar BreakContinue IncrementBC; 12183e2ae49aSVedant Kumar if (const Stmt *Inc = S->getInc()) { 12193e2ae49aSVedant Kumar propagateCounts(addCounters(BackedgeCount, BodyBC.ContinueCount), Inc); 12203e2ae49aSVedant Kumar IncrementBC = BreakContinueStack.pop_back_val(); 12213e2ae49aSVedant Kumar } 1222bf42cfd7SJustin Bogner 1223bf42cfd7SJustin Bogner // Go back to handle the condition. 12243e2ae49aSVedant Kumar Counter CondCount = addCounters( 12253e2ae49aSVedant Kumar addCounters(ParentCount, BackedgeCount, BodyBC.ContinueCount), 12263e2ae49aSVedant Kumar IncrementBC.ContinueCount); 1227bf42cfd7SJustin Bogner if (const Expr *Cond = S->getCond()) { 1228bf42cfd7SJustin Bogner propagateCounts(CondCount, Cond); 1229bf42cfd7SJustin Bogner adjustForOutOfOrderTraversal(getEnd(S)); 1230ee02499aSAlex Lorenz } 1231ee02499aSAlex Lorenz 1232fa8fa044SVedant Kumar // The body count applies to the area immediately after the increment. 1233fa8fa044SVedant Kumar auto Gap = findGapAreaBetween(getPreciseTokenLocEnd(S->getRParenLoc()), 1234fa8fa044SVedant Kumar getStart(S->getBody())); 1235fa8fa044SVedant Kumar if (Gap) 1236fa8fa044SVedant Kumar fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount); 1237fa8fa044SVedant Kumar 12383e2ae49aSVedant Kumar Counter OutCount = addCounters(BodyBC.BreakCount, IncrementBC.BreakCount, 12393e2ae49aSVedant Kumar subtractCounters(CondCount, BodyCount)); 1240bf42cfd7SJustin Bogner if (OutCount != ParentCount) 1241bf42cfd7SJustin Bogner pushRegion(OutCount); 12429f2967bcSAlan Phipps 12439f2967bcSAlan Phipps // Create Branch Region around condition. 12449f2967bcSAlan Phipps createBranchRegion(S->getCond(), BodyCount, 12459f2967bcSAlan Phipps subtractCounters(CondCount, BodyCount)); 1246ee02499aSAlex Lorenz } 1247ee02499aSAlex Lorenz 1248ee02499aSAlex Lorenz void VisitCXXForRangeStmt(const CXXForRangeStmt *S) { 1249bf42cfd7SJustin Bogner extendRegion(S); 12508baa5001SRichard Smith if (S->getInit()) 12518baa5001SRichard Smith Visit(S->getInit()); 1252bf42cfd7SJustin Bogner Visit(S->getLoopVarStmt()); 1253ee02499aSAlex Lorenz Visit(S->getRangeStmt()); 1254bf42cfd7SJustin Bogner 1255bf42cfd7SJustin Bogner Counter ParentCount = getRegion().getCounter(); 1256bf42cfd7SJustin Bogner Counter BodyCount = getRegionCounter(S); 1257bf42cfd7SJustin Bogner 1258ee02499aSAlex Lorenz BreakContinueStack.push_back(BreakContinue()); 1259bf42cfd7SJustin Bogner extendRegion(S->getBody()); 1260bf42cfd7SJustin Bogner Counter BackedgeCount = propagateCounts(BodyCount, S->getBody()); 1261ee02499aSAlex Lorenz BreakContinue BC = BreakContinueStack.pop_back_val(); 1262bf42cfd7SJustin Bogner 1263fa8fa044SVedant Kumar // The body count applies to the area immediately after the range. 1264fa8fa044SVedant Kumar auto Gap = findGapAreaBetween(getPreciseTokenLocEnd(S->getRParenLoc()), 1265fa8fa044SVedant Kumar getStart(S->getBody())); 1266fa8fa044SVedant Kumar if (Gap) 1267fa8fa044SVedant Kumar fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount); 1268fa8fa044SVedant Kumar 12691587432dSJustin Bogner Counter LoopCount = 12701587432dSJustin Bogner addCounters(ParentCount, BackedgeCount, BC.ContinueCount); 12711587432dSJustin Bogner Counter OutCount = 12721587432dSJustin Bogner addCounters(BC.BreakCount, subtractCounters(LoopCount, BodyCount)); 1273bf42cfd7SJustin Bogner if (OutCount != ParentCount) 1274bf42cfd7SJustin Bogner pushRegion(OutCount); 12759f2967bcSAlan Phipps 12769f2967bcSAlan Phipps // Create Branch Region around condition. 12779f2967bcSAlan Phipps createBranchRegion(S->getCond(), BodyCount, 12789f2967bcSAlan Phipps subtractCounters(LoopCount, BodyCount)); 1279ee02499aSAlex Lorenz } 1280ee02499aSAlex Lorenz 1281ee02499aSAlex Lorenz void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) { 1282bf42cfd7SJustin Bogner extendRegion(S); 1283ee02499aSAlex Lorenz Visit(S->getElement()); 1284bf42cfd7SJustin Bogner 1285bf42cfd7SJustin Bogner Counter ParentCount = getRegion().getCounter(); 1286bf42cfd7SJustin Bogner Counter BodyCount = getRegionCounter(S); 1287bf42cfd7SJustin Bogner 1288ee02499aSAlex Lorenz BreakContinueStack.push_back(BreakContinue()); 1289bf42cfd7SJustin Bogner extendRegion(S->getBody()); 1290bf42cfd7SJustin Bogner Counter BackedgeCount = propagateCounts(BodyCount, S->getBody()); 1291ee02499aSAlex Lorenz BreakContinue BC = BreakContinueStack.pop_back_val(); 1292bf42cfd7SJustin Bogner 1293fa8fa044SVedant Kumar // The body count applies to the area immediately after the collection. 1294fa8fa044SVedant Kumar auto Gap = findGapAreaBetween(getPreciseTokenLocEnd(S->getRParenLoc()), 1295fa8fa044SVedant Kumar getStart(S->getBody())); 1296fa8fa044SVedant Kumar if (Gap) 1297fa8fa044SVedant Kumar fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount); 1298fa8fa044SVedant Kumar 12991587432dSJustin Bogner Counter LoopCount = 13001587432dSJustin Bogner addCounters(ParentCount, BackedgeCount, BC.ContinueCount); 13011587432dSJustin Bogner Counter OutCount = 13021587432dSJustin Bogner addCounters(BC.BreakCount, subtractCounters(LoopCount, BodyCount)); 1303bf42cfd7SJustin Bogner if (OutCount != ParentCount) 1304bf42cfd7SJustin Bogner pushRegion(OutCount); 1305ee02499aSAlex Lorenz } 1306ee02499aSAlex Lorenz 1307ee02499aSAlex Lorenz void VisitSwitchStmt(const SwitchStmt *S) { 1308bf42cfd7SJustin Bogner extendRegion(S); 1309f2a6ec55SVedant Kumar if (S->getInit()) 1310f2a6ec55SVedant Kumar Visit(S->getInit()); 1311ee02499aSAlex Lorenz Visit(S->getCond()); 1312bf42cfd7SJustin Bogner 1313ee02499aSAlex Lorenz BreakContinueStack.push_back(BreakContinue()); 1314bf42cfd7SJustin Bogner 1315bf42cfd7SJustin Bogner const Stmt *Body = S->getBody(); 1316bf42cfd7SJustin Bogner extendRegion(Body); 1317bf42cfd7SJustin Bogner if (const auto *CS = dyn_cast<CompoundStmt>(Body)) { 1318bf42cfd7SJustin Bogner if (!CS->body_empty()) { 13197f53fbfcSEli Friedman // Make a region for the body of the switch. If the body starts with 13207f53fbfcSEli Friedman // a case, that case will reuse this region; otherwise, this covers 13217f53fbfcSEli Friedman // the unreachable code at the beginning of the switch body. 1322859bf4d2SVedant Kumar size_t Index = pushRegion(Counter::getZero(), getStart(CS)); 1323859bf4d2SVedant Kumar getRegion().setGap(true); 1324b5841332SRichard Trieu for (const auto *Child : CS->children()) 1325bf42cfd7SJustin Bogner Visit(Child); 13267f53fbfcSEli Friedman 13277f53fbfcSEli Friedman // Set the end for the body of the switch, if it isn't already set. 13287f53fbfcSEli Friedman for (size_t i = RegionStack.size(); i != Index; --i) { 13297f53fbfcSEli Friedman if (!RegionStack[i - 1].hasEndLoc()) 13307f53fbfcSEli Friedman RegionStack[i - 1].setEndLoc(getEnd(CS->body_back())); 13317f53fbfcSEli Friedman } 13327f53fbfcSEli Friedman 1333bf42cfd7SJustin Bogner popRegions(Index); 1334ee02499aSAlex Lorenz } 133587ea3b05SVedant Kumar } else 1336bf42cfd7SJustin Bogner propagateCounts(Counter::getZero(), Body); 1337ee02499aSAlex Lorenz BreakContinue BC = BreakContinueStack.pop_back_val(); 1338bf42cfd7SJustin Bogner 1339ee02499aSAlex Lorenz if (!BreakContinueStack.empty()) 1340ee02499aSAlex Lorenz BreakContinueStack.back().ContinueCount = addCounters( 1341ee02499aSAlex Lorenz BreakContinueStack.back().ContinueCount, BC.ContinueCount); 1342bf42cfd7SJustin Bogner 13439f2967bcSAlan Phipps Counter ParentCount = getRegion().getCounter(); 1344bf42cfd7SJustin Bogner Counter ExitCount = getRegionCounter(S); 13453836482aSVedant Kumar SourceLocation ExitLoc = getEnd(S); 134608780529SAlex Lorenz pushRegion(ExitCount); 134708780529SAlex Lorenz 134808780529SAlex Lorenz // Ensure that handleFileExit recognizes when the end location is located 134908780529SAlex Lorenz // in a different file. 135008780529SAlex Lorenz MostRecentLocation = getStart(S); 13513836482aSVedant Kumar handleFileExit(ExitLoc); 13529f2967bcSAlan Phipps 13539f2967bcSAlan Phipps // Create a Branch Region around each Case. Subtract the case's 13549f2967bcSAlan Phipps // counter from the Parent counter to track the "False" branch count. 13559f2967bcSAlan Phipps Counter CaseCountSum; 13569f2967bcSAlan Phipps bool HasDefaultCase = false; 13579f2967bcSAlan Phipps const SwitchCase *Case = S->getSwitchCaseList(); 13589f2967bcSAlan Phipps for (; Case; Case = Case->getNextSwitchCase()) { 13599f2967bcSAlan Phipps HasDefaultCase = HasDefaultCase || isa<DefaultStmt>(Case); 13609f2967bcSAlan Phipps CaseCountSum = addCounters(CaseCountSum, getRegionCounter(Case)); 13619f2967bcSAlan Phipps createSwitchCaseRegion( 13629f2967bcSAlan Phipps Case, getRegionCounter(Case), 13639f2967bcSAlan Phipps subtractCounters(ParentCount, getRegionCounter(Case))); 13649f2967bcSAlan Phipps } 13659f2967bcSAlan Phipps 13669f2967bcSAlan Phipps // If no explicit default case exists, create a branch region to represent 13679f2967bcSAlan Phipps // the hidden branch, which will be added later by the CodeGen. This region 13689f2967bcSAlan Phipps // will be associated with the switch statement's condition. 13699f2967bcSAlan Phipps if (!HasDefaultCase) { 13709f2967bcSAlan Phipps Counter DefaultTrue = subtractCounters(ParentCount, CaseCountSum); 13719f2967bcSAlan Phipps Counter DefaultFalse = subtractCounters(ParentCount, DefaultTrue); 13729f2967bcSAlan Phipps createBranchRegion(S->getCond(), DefaultTrue, DefaultFalse); 13739f2967bcSAlan Phipps } 1374ee02499aSAlex Lorenz } 1375ee02499aSAlex Lorenz 1376bf42cfd7SJustin Bogner void VisitSwitchCase(const SwitchCase *S) { 1377bf42cfd7SJustin Bogner extendRegion(S); 1378ee02499aSAlex Lorenz 1379bf42cfd7SJustin Bogner SourceMappingRegion &Parent = getRegion(); 1380bf42cfd7SJustin Bogner 1381bf42cfd7SJustin Bogner Counter Count = addCounters(Parent.getCounter(), getRegionCounter(S)); 1382bf42cfd7SJustin Bogner // Reuse the existing region if it starts at our label. This is typical of 1383bf42cfd7SJustin Bogner // the first case in a switch. 1384a6e4358fSStephen Kelly if (Parent.hasStartLoc() && Parent.getBeginLoc() == getStart(S)) 1385bf42cfd7SJustin Bogner Parent.setCounter(Count); 1386bf42cfd7SJustin Bogner else 1387bf42cfd7SJustin Bogner pushRegion(Count, getStart(S)); 1388bf42cfd7SJustin Bogner 1389376c06c2SSanjay Patel if (const auto *CS = dyn_cast<CaseStmt>(S)) { 1390bf42cfd7SJustin Bogner Visit(CS->getLHS()); 1391bf42cfd7SJustin Bogner if (const Expr *RHS = CS->getRHS()) 1392bf42cfd7SJustin Bogner Visit(RHS); 1393bf42cfd7SJustin Bogner } 1394ee02499aSAlex Lorenz Visit(S->getSubStmt()); 1395ee02499aSAlex Lorenz } 1396ee02499aSAlex Lorenz 1397ee02499aSAlex Lorenz void VisitIfStmt(const IfStmt *S) { 1398bf42cfd7SJustin Bogner extendRegion(S); 13999d2a16b9SVedant Kumar if (S->getInit()) 14009d2a16b9SVedant Kumar Visit(S->getInit()); 14019d2a16b9SVedant Kumar 1402055ebc34SJustin Bogner // Extend into the condition before we propagate through it below - this is 1403055ebc34SJustin Bogner // needed to handle macros that generate the "if" but not the condition. 1404055ebc34SJustin Bogner extendRegion(S->getCond()); 1405ee02499aSAlex Lorenz 1406bf42cfd7SJustin Bogner Counter ParentCount = getRegion().getCounter(); 1407bf42cfd7SJustin Bogner Counter ThenCount = getRegionCounter(S); 1408ee02499aSAlex Lorenz 140991f2e3c9SJustin Bogner // Emitting a counter for the condition makes it easier to interpret the 141091f2e3c9SJustin Bogner // counter for the body when looking at the coverage. 141191f2e3c9SJustin Bogner propagateCounts(ParentCount, S->getCond()); 141291f2e3c9SJustin Bogner 14132e8c8759SVedant Kumar // The 'then' count applies to the area immediately after the condition. 14149500a720SZequan Wu auto Gap = findGapAreaBetween(S->getCond(), S->getThen()); 1415fa8fa044SVedant Kumar if (Gap) 1416fa8fa044SVedant Kumar fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), ThenCount); 14172e8c8759SVedant Kumar 1418bf42cfd7SJustin Bogner extendRegion(S->getThen()); 1419bf42cfd7SJustin Bogner Counter OutCount = propagateCounts(ThenCount, S->getThen()); 1420bf42cfd7SJustin Bogner 1421bf42cfd7SJustin Bogner Counter ElseCount = subtractCounters(ParentCount, ThenCount); 1422bf42cfd7SJustin Bogner if (const Stmt *Else = S->getElse()) { 14232e8c8759SVedant Kumar // The 'else' count applies to the area immediately after the 'then'. 14249500a720SZequan Wu Gap = findGapAreaBetween(S->getThen(), Else); 1425fa8fa044SVedant Kumar if (Gap) 1426fa8fa044SVedant Kumar fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), ElseCount); 14272e8c8759SVedant Kumar extendRegion(Else); 1428bf42cfd7SJustin Bogner OutCount = addCounters(OutCount, propagateCounts(ElseCount, Else)); 1429bf42cfd7SJustin Bogner } else 1430bf42cfd7SJustin Bogner OutCount = addCounters(OutCount, ElseCount); 1431bf42cfd7SJustin Bogner 1432bf42cfd7SJustin Bogner if (OutCount != ParentCount) 1433bf42cfd7SJustin Bogner pushRegion(OutCount); 14349f2967bcSAlan Phipps 14359f2967bcSAlan Phipps // Create Branch Region around condition. 14369f2967bcSAlan Phipps createBranchRegion(S->getCond(), ThenCount, 14379f2967bcSAlan Phipps subtractCounters(ParentCount, ThenCount)); 1438ee02499aSAlex Lorenz } 1439ee02499aSAlex Lorenz 1440ee02499aSAlex Lorenz void VisitCXXTryStmt(const CXXTryStmt *S) { 1441bf42cfd7SJustin Bogner extendRegion(S); 1442049908b2SVedant Kumar // Handle macros that generate the "try" but not the rest. 1443049908b2SVedant Kumar extendRegion(S->getTryBlock()); 1444049908b2SVedant Kumar 1445049908b2SVedant Kumar Counter ParentCount = getRegion().getCounter(); 1446049908b2SVedant Kumar propagateCounts(ParentCount, S->getTryBlock()); 1447049908b2SVedant Kumar 1448ee02499aSAlex Lorenz for (unsigned I = 0, E = S->getNumHandlers(); I < E; ++I) 1449ee02499aSAlex Lorenz Visit(S->getHandler(I)); 1450bf42cfd7SJustin Bogner 1451bf42cfd7SJustin Bogner Counter ExitCount = getRegionCounter(S); 1452bf42cfd7SJustin Bogner pushRegion(ExitCount); 1453ee02499aSAlex Lorenz } 1454ee02499aSAlex Lorenz 1455ee02499aSAlex Lorenz void VisitCXXCatchStmt(const CXXCatchStmt *S) { 1456bf42cfd7SJustin Bogner propagateCounts(getRegionCounter(S), S->getHandlerBlock()); 1457ee02499aSAlex Lorenz } 1458ee02499aSAlex Lorenz 1459ee02499aSAlex Lorenz void VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) { 1460bf42cfd7SJustin Bogner extendRegion(E); 1461ee02499aSAlex Lorenz 1462bf42cfd7SJustin Bogner Counter ParentCount = getRegion().getCounter(); 1463bf42cfd7SJustin Bogner Counter TrueCount = getRegionCounter(E); 1464ee02499aSAlex Lorenz 1465*4dc08cc3SZequan Wu propagateCounts(ParentCount, E->getCond()); 1466e3654ce7SJustin Bogner 1467e3654ce7SJustin Bogner if (!isa<BinaryConditionalOperator>(E)) { 14682e8c8759SVedant Kumar // The 'then' count applies to the area immediately after the condition. 1469fa8fa044SVedant Kumar auto Gap = 1470fa8fa044SVedant Kumar findGapAreaBetween(E->getQuestionLoc(), getStart(E->getTrueExpr())); 1471fa8fa044SVedant Kumar if (Gap) 1472fa8fa044SVedant Kumar fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), TrueCount); 14732e8c8759SVedant Kumar 1474e3654ce7SJustin Bogner extendRegion(E->getTrueExpr()); 1475bf42cfd7SJustin Bogner propagateCounts(TrueCount, E->getTrueExpr()); 1476e3654ce7SJustin Bogner } 14772e8c8759SVedant Kumar 1478e3654ce7SJustin Bogner extendRegion(E->getFalseExpr()); 1479bf42cfd7SJustin Bogner propagateCounts(subtractCounters(ParentCount, TrueCount), 1480bf42cfd7SJustin Bogner E->getFalseExpr()); 14819f2967bcSAlan Phipps 14829f2967bcSAlan Phipps // Create Branch Region around condition. 14839f2967bcSAlan Phipps createBranchRegion(E->getCond(), TrueCount, 14849f2967bcSAlan Phipps subtractCounters(ParentCount, TrueCount)); 1485ee02499aSAlex Lorenz } 1486ee02499aSAlex Lorenz 1487ee02499aSAlex Lorenz void VisitBinLAnd(const BinaryOperator *E) { 1488e5f06a81SVedant Kumar extendRegion(E->getLHS()); 1489e5f06a81SVedant Kumar propagateCounts(getRegion().getCounter(), E->getLHS()); 1490e5f06a81SVedant Kumar handleFileExit(getEnd(E->getLHS())); 1491bf42cfd7SJustin Bogner 14929f2967bcSAlan Phipps // Counter tracks the right hand side of a logical and operator. 1493bf42cfd7SJustin Bogner extendRegion(E->getRHS()); 1494bf42cfd7SJustin Bogner propagateCounts(getRegionCounter(E), E->getRHS()); 14959f2967bcSAlan Phipps 14969f2967bcSAlan Phipps // Extract the RHS's Execution Counter. 14979f2967bcSAlan Phipps Counter RHSExecCnt = getRegionCounter(E); 14989f2967bcSAlan Phipps 14999f2967bcSAlan Phipps // Extract the RHS's "True" Instance Counter. 15009f2967bcSAlan Phipps Counter RHSTrueCnt = getRegionCounter(E->getRHS()); 15019f2967bcSAlan Phipps 15029f2967bcSAlan Phipps // Extract the Parent Region Counter. 15039f2967bcSAlan Phipps Counter ParentCnt = getRegion().getCounter(); 15049f2967bcSAlan Phipps 15059f2967bcSAlan Phipps // Create Branch Region around LHS condition. 15069f2967bcSAlan Phipps createBranchRegion(E->getLHS(), RHSExecCnt, 15079f2967bcSAlan Phipps subtractCounters(ParentCnt, RHSExecCnt)); 15089f2967bcSAlan Phipps 15099f2967bcSAlan Phipps // Create Branch Region around RHS condition. 15109f2967bcSAlan Phipps createBranchRegion(E->getRHS(), RHSTrueCnt, 15119f2967bcSAlan Phipps subtractCounters(RHSExecCnt, RHSTrueCnt)); 1512ee02499aSAlex Lorenz } 1513ee02499aSAlex Lorenz 1514ee02499aSAlex Lorenz void VisitBinLOr(const BinaryOperator *E) { 1515e5f06a81SVedant Kumar extendRegion(E->getLHS()); 1516e5f06a81SVedant Kumar propagateCounts(getRegion().getCounter(), E->getLHS()); 1517e5f06a81SVedant Kumar handleFileExit(getEnd(E->getLHS())); 1518ee02499aSAlex Lorenz 15199f2967bcSAlan Phipps // Counter tracks the right hand side of a logical or operator. 1520bf42cfd7SJustin Bogner extendRegion(E->getRHS()); 1521bf42cfd7SJustin Bogner propagateCounts(getRegionCounter(E), E->getRHS()); 15229f2967bcSAlan Phipps 15239f2967bcSAlan Phipps // Extract the RHS's Execution Counter. 15249f2967bcSAlan Phipps Counter RHSExecCnt = getRegionCounter(E); 15259f2967bcSAlan Phipps 15269f2967bcSAlan Phipps // Extract the RHS's "False" Instance Counter. 15279f2967bcSAlan Phipps Counter RHSFalseCnt = getRegionCounter(E->getRHS()); 15289f2967bcSAlan Phipps 15299f2967bcSAlan Phipps // Extract the Parent Region Counter. 15309f2967bcSAlan Phipps Counter ParentCnt = getRegion().getCounter(); 15319f2967bcSAlan Phipps 15329f2967bcSAlan Phipps // Create Branch Region around LHS condition. 15339f2967bcSAlan Phipps createBranchRegion(E->getLHS(), subtractCounters(ParentCnt, RHSExecCnt), 15349f2967bcSAlan Phipps RHSExecCnt); 15359f2967bcSAlan Phipps 15369f2967bcSAlan Phipps // Create Branch Region around RHS condition. 15379f2967bcSAlan Phipps createBranchRegion(E->getRHS(), subtractCounters(RHSExecCnt, RHSFalseCnt), 15389f2967bcSAlan Phipps RHSFalseCnt); 153901a0d062SAlex Lorenz } 1540c109102eSJustin Bogner 1541c109102eSJustin Bogner void VisitLambdaExpr(const LambdaExpr *LE) { 1542c109102eSJustin Bogner // Lambdas are treated as their own functions for now, so we shouldn't 1543c109102eSJustin Bogner // propagate counts into them. 1544c109102eSJustin Bogner } 1545ee02499aSAlex Lorenz }; 1546ee02499aSAlex Lorenz 154714f8fb68SVedant Kumar } // end anonymous namespace 154814f8fb68SVedant Kumar 1549a432d176SJustin Bogner static void dump(llvm::raw_ostream &OS, StringRef FunctionName, 1550a432d176SJustin Bogner ArrayRef<CounterExpression> Expressions, 1551a432d176SJustin Bogner ArrayRef<CounterMappingRegion> Regions) { 1552a432d176SJustin Bogner OS << FunctionName << ":\n"; 1553a432d176SJustin Bogner CounterMappingContext Ctx(Expressions); 1554a432d176SJustin Bogner for (const auto &R : Regions) { 1555f2cf38e0SAlex Lorenz OS.indent(2); 1556f2cf38e0SAlex Lorenz switch (R.Kind) { 1557f2cf38e0SAlex Lorenz case CounterMappingRegion::CodeRegion: 1558f2cf38e0SAlex Lorenz break; 1559f2cf38e0SAlex Lorenz case CounterMappingRegion::ExpansionRegion: 1560f2cf38e0SAlex Lorenz OS << "Expansion,"; 1561f2cf38e0SAlex Lorenz break; 1562f2cf38e0SAlex Lorenz case CounterMappingRegion::SkippedRegion: 1563f2cf38e0SAlex Lorenz OS << "Skipped,"; 1564f2cf38e0SAlex Lorenz break; 1565a1c4deb7SVedant Kumar case CounterMappingRegion::GapRegion: 1566a1c4deb7SVedant Kumar OS << "Gap,"; 1567a1c4deb7SVedant Kumar break; 15689f2967bcSAlan Phipps case CounterMappingRegion::BranchRegion: 15699f2967bcSAlan Phipps OS << "Branch,"; 15709f2967bcSAlan Phipps break; 1571f2cf38e0SAlex Lorenz } 1572f2cf38e0SAlex Lorenz 15734da909b2SJustin Bogner OS << "File " << R.FileID << ", " << R.LineStart << ":" << R.ColumnStart 15744da909b2SJustin Bogner << " -> " << R.LineEnd << ":" << R.ColumnEnd << " = "; 1575f69dc349SJustin Bogner Ctx.dump(R.Count, OS); 15769f2967bcSAlan Phipps 15779f2967bcSAlan Phipps if (R.Kind == CounterMappingRegion::BranchRegion) { 15789f2967bcSAlan Phipps OS << ", "; 15799f2967bcSAlan Phipps Ctx.dump(R.FalseCount, OS); 15809f2967bcSAlan Phipps } 15819f2967bcSAlan Phipps 1582f2cf38e0SAlex Lorenz if (R.Kind == CounterMappingRegion::ExpansionRegion) 15834da909b2SJustin Bogner OS << " (Expanded file = " << R.ExpandedFileID << ")"; 15844da909b2SJustin Bogner OS << "\n"; 1585f2cf38e0SAlex Lorenz } 1586f2cf38e0SAlex Lorenz } 1587f2cf38e0SAlex Lorenz 1588c3324450SKeith Smiley CoverageMappingModuleGen::CoverageMappingModuleGen( 1589c3324450SKeith Smiley CodeGenModule &CGM, CoverageSourceInfo &SourceInfo) 1590c3324450SKeith Smiley : CGM(CGM), SourceInfo(SourceInfo) { 1591c3324450SKeith Smiley ProfilePrefixMap = CGM.getCodeGenOpts().ProfilePrefixMap; 1592c3324450SKeith Smiley } 1593c3324450SKeith Smiley 1594c3324450SKeith Smiley std::string CoverageMappingModuleGen::normalizeFilename(StringRef Filename) { 1595c3324450SKeith Smiley llvm::SmallString<256> Path(Filename); 1596c3324450SKeith Smiley llvm::sys::fs::make_absolute(Path); 1597c3324450SKeith Smiley llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true); 1598c3324450SKeith Smiley for (const auto &Entry : ProfilePrefixMap) { 1599c3324450SKeith Smiley if (llvm::sys::path::replace_path_prefix(Path, Entry.first, Entry.second)) 1600c3324450SKeith Smiley break; 1601c3324450SKeith Smiley } 1602c3324450SKeith Smiley return Path.str().str(); 1603c3324450SKeith Smiley } 1604c3324450SKeith Smiley 1605dd1ea9deSVedant Kumar static std::string getInstrProfSection(const CodeGenModule &CGM, 1606dd1ea9deSVedant Kumar llvm::InstrProfSectKind SK) { 1607dd1ea9deSVedant Kumar return llvm::getInstrProfSectionName( 1608dd1ea9deSVedant Kumar SK, CGM.getContext().getTargetInfo().getTriple().getObjectFormat()); 1609dd1ea9deSVedant Kumar } 1610dd1ea9deSVedant Kumar 1611dd1ea9deSVedant Kumar void CoverageMappingModuleGen::emitFunctionMappingRecord( 1612dd1ea9deSVedant Kumar const FunctionInfo &Info, uint64_t FilenamesRef) { 161399317124SVedant Kumar llvm::LLVMContext &Ctx = CGM.getLLVMContext(); 1614dd1ea9deSVedant Kumar 1615dd1ea9deSVedant Kumar // Assign a name to the function record. This is used to merge duplicates. 1616dd1ea9deSVedant Kumar std::string FuncRecordName = "__covrec_" + llvm::utohexstr(Info.NameHash); 1617dd1ea9deSVedant Kumar 1618dd1ea9deSVedant Kumar // A dummy description for a function included-but-not-used in a TU can be 1619dd1ea9deSVedant Kumar // replaced by full description provided by a different TU. The two kinds of 1620dd1ea9deSVedant Kumar // descriptions play distinct roles: therefore, assign them different names 1621dd1ea9deSVedant Kumar // to prevent `linkonce_odr` merging. 1622dd1ea9deSVedant Kumar if (Info.IsUsed) 1623dd1ea9deSVedant Kumar FuncRecordName += "u"; 1624dd1ea9deSVedant Kumar 1625dd1ea9deSVedant Kumar // Create the function record type. 1626dd1ea9deSVedant Kumar const uint64_t NameHash = Info.NameHash; 1627dd1ea9deSVedant Kumar const uint64_t FuncHash = Info.FuncHash; 1628dd1ea9deSVedant Kumar const std::string &CoverageMapping = Info.CoverageMapping; 162933888717SVedant Kumar #define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) LLVMType, 163033888717SVedant Kumar llvm::Type *FunctionRecordTypes[] = { 163133888717SVedant Kumar #include "llvm/ProfileData/InstrProfData.inc" 163233888717SVedant Kumar }; 1633dd1ea9deSVedant Kumar auto *FunctionRecordTy = 163433888717SVedant Kumar llvm::StructType::get(Ctx, makeArrayRef(FunctionRecordTypes), 163533888717SVedant Kumar /*isPacked=*/true); 163699317124SVedant Kumar 1637dd1ea9deSVedant Kumar // Create the function record constant. 163833888717SVedant Kumar #define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) Init, 163933888717SVedant Kumar llvm::Constant *FunctionRecordVals[] = { 164033888717SVedant Kumar #include "llvm/ProfileData/InstrProfData.inc" 164133888717SVedant Kumar }; 1642dd1ea9deSVedant Kumar auto *FuncRecordConstant = llvm::ConstantStruct::get( 1643dd1ea9deSVedant Kumar FunctionRecordTy, makeArrayRef(FunctionRecordVals)); 1644dd1ea9deSVedant Kumar 1645dd1ea9deSVedant Kumar // Create the function record global. 1646dd1ea9deSVedant Kumar auto *FuncRecord = new llvm::GlobalVariable( 1647dd1ea9deSVedant Kumar CGM.getModule(), FunctionRecordTy, /*isConstant=*/true, 1648dd1ea9deSVedant Kumar llvm::GlobalValue::LinkOnceODRLinkage, FuncRecordConstant, 1649dd1ea9deSVedant Kumar FuncRecordName); 1650dd1ea9deSVedant Kumar FuncRecord->setVisibility(llvm::GlobalValue::HiddenVisibility); 1651dd1ea9deSVedant Kumar FuncRecord->setSection(getInstrProfSection(CGM, llvm::IPSK_covfun)); 1652dd1ea9deSVedant Kumar FuncRecord->setAlignment(llvm::Align(8)); 1653dd1ea9deSVedant Kumar if (CGM.supportsCOMDAT()) 1654dd1ea9deSVedant Kumar FuncRecord->setComdat(CGM.getModule().getOrInsertComdat(FuncRecordName)); 1655dd1ea9deSVedant Kumar 1656dd1ea9deSVedant Kumar // Make sure the data doesn't get deleted. 1657dd1ea9deSVedant Kumar CGM.addUsedGlobal(FuncRecord); 1658dd1ea9deSVedant Kumar } 1659dd1ea9deSVedant Kumar 1660dd1ea9deSVedant Kumar void CoverageMappingModuleGen::addFunctionMappingRecord( 1661dd1ea9deSVedant Kumar llvm::GlobalVariable *NamePtr, StringRef NameValue, uint64_t FuncHash, 1662dd1ea9deSVedant Kumar const std::string &CoverageMapping, bool IsUsed) { 1663dd1ea9deSVedant Kumar llvm::LLVMContext &Ctx = CGM.getLLVMContext(); 1664dd1ea9deSVedant Kumar const uint64_t NameHash = llvm::IndexedInstrProf::ComputeHash(NameValue); 1665dd1ea9deSVedant Kumar FunctionRecords.push_back({NameHash, FuncHash, CoverageMapping, IsUsed}); 1666dd1ea9deSVedant Kumar 1667848da137SXinliang David Li if (!IsUsed) 16682129ae53SXinliang David Li FunctionNames.push_back( 16692129ae53SXinliang David Li llvm::ConstantExpr::getBitCast(NamePtr, llvm::Type::getInt8PtrTy(Ctx))); 1670f2cf38e0SAlex Lorenz 1671f2cf38e0SAlex Lorenz if (CGM.getCodeGenOpts().DumpCoverageMapping) { 1672f2cf38e0SAlex Lorenz // Dump the coverage mapping data for this function by decoding the 1673f2cf38e0SAlex Lorenz // encoded data. This allows us to dump the mapping regions which were 1674f2cf38e0SAlex Lorenz // also processed by the CoverageMappingWriter which performs 1675f2cf38e0SAlex Lorenz // additional minimization operations such as reducing the number of 1676f2cf38e0SAlex Lorenz // expressions. 1677f2cf38e0SAlex Lorenz std::vector<StringRef> Filenames; 1678f2cf38e0SAlex Lorenz std::vector<CounterExpression> Expressions; 1679f2cf38e0SAlex Lorenz std::vector<CounterMappingRegion> Regions; 1680b31ee819SJordan Rose llvm::SmallVector<std::string, 16> FilenameStrs; 1681f2cf38e0SAlex Lorenz llvm::SmallVector<StringRef, 16> FilenameRefs; 1682b31ee819SJordan Rose FilenameStrs.resize(FileEntries.size()); 1683f2cf38e0SAlex Lorenz FilenameRefs.resize(FileEntries.size()); 1684b31ee819SJordan Rose for (const auto &Entry : FileEntries) { 1685b31ee819SJordan Rose auto I = Entry.second; 1686b31ee819SJordan Rose FilenameStrs[I] = normalizeFilename(Entry.first->getName()); 1687b31ee819SJordan Rose FilenameRefs[I] = FilenameStrs[I]; 1688b31ee819SJordan Rose } 1689a432d176SJustin Bogner RawCoverageMappingReader Reader(CoverageMapping, FilenameRefs, Filenames, 1690a432d176SJustin Bogner Expressions, Regions); 1691a432d176SJustin Bogner if (Reader.read()) 1692f2cf38e0SAlex Lorenz return; 1693a026a437SXinliang David Li dump(llvm::outs(), NameValue, Expressions, Regions); 1694f2cf38e0SAlex Lorenz } 1695ee02499aSAlex Lorenz } 1696ee02499aSAlex Lorenz 1697ee02499aSAlex Lorenz void CoverageMappingModuleGen::emit() { 1698ee02499aSAlex Lorenz if (FunctionRecords.empty()) 1699ee02499aSAlex Lorenz return; 1700ee02499aSAlex Lorenz llvm::LLVMContext &Ctx = CGM.getLLVMContext(); 1701ee02499aSAlex Lorenz auto *Int32Ty = llvm::Type::getInt32Ty(Ctx); 1702ee02499aSAlex Lorenz 1703ee02499aSAlex Lorenz // Create the filenames and merge them with coverage mappings 1704ee02499aSAlex Lorenz llvm::SmallVector<std::string, 16> FilenameStrs; 17059e324dd1SVedant Kumar llvm::SmallVector<StringRef, 16> FilenameRefs; 1706ee02499aSAlex Lorenz FilenameStrs.resize(FileEntries.size()); 17079e324dd1SVedant Kumar FilenameRefs.resize(FileEntries.size()); 1708ee02499aSAlex Lorenz for (const auto &Entry : FileEntries) { 1709ee02499aSAlex Lorenz auto I = Entry.second; 171014f8fb68SVedant Kumar FilenameStrs[I] = normalizeFilename(Entry.first->getName()); 17119e324dd1SVedant Kumar FilenameRefs[I] = FilenameStrs[I]; 1712ee02499aSAlex Lorenz } 1713ee02499aSAlex Lorenz 1714dd1ea9deSVedant Kumar std::string Filenames; 1715dd1ea9deSVedant Kumar { 1716dd1ea9deSVedant Kumar llvm::raw_string_ostream OS(Filenames); 17179e324dd1SVedant Kumar CoverageFilenamesSectionWriter(FilenameRefs).write(OS); 17184cd07dbeSSerge Guelton } 1719dd1ea9deSVedant Kumar auto *FilenamesVal = 1720dd1ea9deSVedant Kumar llvm::ConstantDataArray::getString(Ctx, Filenames, false); 1721dd1ea9deSVedant Kumar const int64_t FilenamesRef = llvm::IndexedInstrProf::ComputeHash(Filenames); 17224cd07dbeSSerge Guelton 1723dd1ea9deSVedant Kumar // Emit the function records. 1724dd1ea9deSVedant Kumar for (const FunctionInfo &Info : FunctionRecords) 1725dd1ea9deSVedant Kumar emitFunctionMappingRecord(Info, FilenamesRef); 1726ee02499aSAlex Lorenz 1727dd1ea9deSVedant Kumar const unsigned NRecords = 0; 1728dd1ea9deSVedant Kumar const size_t FilenamesSize = Filenames.size(); 1729dd1ea9deSVedant Kumar const unsigned CoverageMappingSize = 0; 173020b188c0SXinliang David Li llvm::Type *CovDataHeaderTypes[] = { 173120b188c0SXinliang David Li #define COVMAP_HEADER(Type, LLVMType, Name, Init) LLVMType, 173220b188c0SXinliang David Li #include "llvm/ProfileData/InstrProfData.inc" 173320b188c0SXinliang David Li }; 173420b188c0SXinliang David Li auto CovDataHeaderTy = 173520b188c0SXinliang David Li llvm::StructType::get(Ctx, makeArrayRef(CovDataHeaderTypes)); 173620b188c0SXinliang David Li llvm::Constant *CovDataHeaderVals[] = { 173720b188c0SXinliang David Li #define COVMAP_HEADER(Type, LLVMType, Name, Init) Init, 173820b188c0SXinliang David Li #include "llvm/ProfileData/InstrProfData.inc" 173920b188c0SXinliang David Li }; 174020b188c0SXinliang David Li auto CovDataHeaderVal = llvm::ConstantStruct::get( 174120b188c0SXinliang David Li CovDataHeaderTy, makeArrayRef(CovDataHeaderVals)); 174220b188c0SXinliang David Li 1743ee02499aSAlex Lorenz // Create the coverage data record 1744dd1ea9deSVedant Kumar llvm::Type *CovDataTypes[] = {CovDataHeaderTy, FilenamesVal->getType()}; 1745ee02499aSAlex Lorenz auto CovDataTy = llvm::StructType::get(Ctx, makeArrayRef(CovDataTypes)); 1746dd1ea9deSVedant Kumar llvm::Constant *TUDataVals[] = {CovDataHeaderVal, FilenamesVal}; 1747ee02499aSAlex Lorenz auto CovDataVal = 1748ee02499aSAlex Lorenz llvm::ConstantStruct::get(CovDataTy, makeArrayRef(TUDataVals)); 174920b188c0SXinliang David Li auto CovData = new llvm::GlobalVariable( 1750dd1ea9deSVedant Kumar CGM.getModule(), CovDataTy, true, llvm::GlobalValue::PrivateLinkage, 175120b188c0SXinliang David Li CovDataVal, llvm::getCoverageMappingVarName()); 1752ee02499aSAlex Lorenz 1753dd1ea9deSVedant Kumar CovData->setSection(getInstrProfSection(CGM, llvm::IPSK_covmap)); 1754c79099e0SGuillaume Chatelet CovData->setAlignment(llvm::Align(8)); 1755ee02499aSAlex Lorenz 1756ee02499aSAlex Lorenz // Make sure the data doesn't get deleted. 1757ee02499aSAlex Lorenz CGM.addUsedGlobal(CovData); 17582129ae53SXinliang David Li // Create the deferred function records array 17592129ae53SXinliang David Li if (!FunctionNames.empty()) { 17602129ae53SXinliang David Li auto NamesArrTy = llvm::ArrayType::get(llvm::Type::getInt8PtrTy(Ctx), 17612129ae53SXinliang David Li FunctionNames.size()); 17622129ae53SXinliang David Li auto NamesArrVal = llvm::ConstantArray::get(NamesArrTy, FunctionNames); 17632129ae53SXinliang David Li // This variable will *NOT* be emitted to the object file. It is used 17642129ae53SXinliang David Li // to pass the list of names referenced to codegen. 17652129ae53SXinliang David Li new llvm::GlobalVariable(CGM.getModule(), NamesArrTy, true, 17662129ae53SXinliang David Li llvm::GlobalValue::InternalLinkage, NamesArrVal, 17677077f0afSXinliang David Li llvm::getCoverageUnusedNamesVarName()); 17682129ae53SXinliang David Li } 1769ee02499aSAlex Lorenz } 1770ee02499aSAlex Lorenz 1771ee02499aSAlex Lorenz unsigned CoverageMappingModuleGen::getFileID(const FileEntry *File) { 1772ee02499aSAlex Lorenz auto It = FileEntries.find(File); 1773ee02499aSAlex Lorenz if (It != FileEntries.end()) 1774ee02499aSAlex Lorenz return It->second; 1775ee02499aSAlex Lorenz unsigned FileID = FileEntries.size(); 1776ee02499aSAlex Lorenz FileEntries.insert(std::make_pair(File, FileID)); 1777ee02499aSAlex Lorenz return FileID; 1778ee02499aSAlex Lorenz } 1779ee02499aSAlex Lorenz 1780ee02499aSAlex Lorenz void CoverageMappingGen::emitCounterMapping(const Decl *D, 1781ee02499aSAlex Lorenz llvm::raw_ostream &OS) { 1782ee02499aSAlex Lorenz assert(CounterMap); 1783e5ee6c58SJustin Bogner CounterCoverageMappingBuilder Walker(CVM, *CounterMap, SM, LangOpts); 1784ee02499aSAlex Lorenz Walker.VisitDecl(D); 1785ee02499aSAlex Lorenz Walker.write(OS); 1786ee02499aSAlex Lorenz } 1787ee02499aSAlex Lorenz 1788ee02499aSAlex Lorenz void CoverageMappingGen::emitEmptyMapping(const Decl *D, 1789ee02499aSAlex Lorenz llvm::raw_ostream &OS) { 1790ee02499aSAlex Lorenz EmptyCoverageMappingBuilder Walker(CVM, SM, LangOpts); 1791ee02499aSAlex Lorenz Walker.VisitDecl(D); 1792ee02499aSAlex Lorenz Walker.write(OS); 1793ee02499aSAlex Lorenz } 1794