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