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 VisitCallExpr(const CallExpr *E) { 720 VisitStmt(E); 721 722 // Terminate the region when we hit a noreturn function. 723 // (This is helpful dealing with switch statements.) 724 QualType CalleeType = E->getCallee()->getType(); 725 if (getFunctionExtInfo(*CalleeType).getNoReturn()) 726 terminateRegion(E); 727 } 728 729 void VisitWhileStmt(const WhileStmt *S) { 730 extendRegion(S); 731 732 Counter ParentCount = getRegion().getCounter(); 733 Counter BodyCount = getRegionCounter(S); 734 735 // Handle the body first so that we can get the backedge count. 736 BreakContinueStack.push_back(BreakContinue()); 737 extendRegion(S->getBody()); 738 Counter BackedgeCount = propagateCounts(BodyCount, S->getBody()); 739 BreakContinue BC = BreakContinueStack.pop_back_val(); 740 741 // Go back to handle the condition. 742 Counter CondCount = 743 addCounters(ParentCount, BackedgeCount, BC.ContinueCount); 744 propagateCounts(CondCount, S->getCond()); 745 adjustForOutOfOrderTraversal(getEnd(S)); 746 747 Counter OutCount = 748 addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount)); 749 if (OutCount != ParentCount) 750 pushRegion(OutCount); 751 } 752 753 void VisitDoStmt(const DoStmt *S) { 754 extendRegion(S); 755 756 Counter ParentCount = getRegion().getCounter(); 757 Counter BodyCount = getRegionCounter(S); 758 759 BreakContinueStack.push_back(BreakContinue()); 760 extendRegion(S->getBody()); 761 Counter BackedgeCount = 762 propagateCounts(addCounters(ParentCount, BodyCount), S->getBody()); 763 BreakContinue BC = BreakContinueStack.pop_back_val(); 764 765 Counter CondCount = addCounters(BackedgeCount, BC.ContinueCount); 766 propagateCounts(CondCount, S->getCond()); 767 768 Counter OutCount = 769 addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount)); 770 if (OutCount != ParentCount) 771 pushRegion(OutCount); 772 } 773 774 void VisitForStmt(const ForStmt *S) { 775 extendRegion(S); 776 if (S->getInit()) 777 Visit(S->getInit()); 778 779 Counter ParentCount = getRegion().getCounter(); 780 Counter BodyCount = getRegionCounter(S); 781 782 // Handle the body first so that we can get the backedge count. 783 BreakContinueStack.push_back(BreakContinue()); 784 extendRegion(S->getBody()); 785 Counter BackedgeCount = propagateCounts(BodyCount, S->getBody()); 786 BreakContinue BC = BreakContinueStack.pop_back_val(); 787 788 // The increment is essentially part of the body but it needs to include 789 // the count for all the continue statements. 790 if (const Stmt *Inc = S->getInc()) 791 propagateCounts(addCounters(BackedgeCount, BC.ContinueCount), Inc); 792 793 // Go back to handle the condition. 794 Counter CondCount = 795 addCounters(ParentCount, BackedgeCount, BC.ContinueCount); 796 if (const Expr *Cond = S->getCond()) { 797 propagateCounts(CondCount, Cond); 798 adjustForOutOfOrderTraversal(getEnd(S)); 799 } 800 801 Counter OutCount = 802 addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount)); 803 if (OutCount != ParentCount) 804 pushRegion(OutCount); 805 } 806 807 void VisitCXXForRangeStmt(const CXXForRangeStmt *S) { 808 extendRegion(S); 809 Visit(S->getLoopVarStmt()); 810 Visit(S->getRangeStmt()); 811 812 Counter ParentCount = getRegion().getCounter(); 813 Counter BodyCount = getRegionCounter(S); 814 815 BreakContinueStack.push_back(BreakContinue()); 816 extendRegion(S->getBody()); 817 Counter BackedgeCount = propagateCounts(BodyCount, S->getBody()); 818 BreakContinue BC = BreakContinueStack.pop_back_val(); 819 820 Counter LoopCount = 821 addCounters(ParentCount, BackedgeCount, BC.ContinueCount); 822 Counter OutCount = 823 addCounters(BC.BreakCount, subtractCounters(LoopCount, BodyCount)); 824 if (OutCount != ParentCount) 825 pushRegion(OutCount); 826 } 827 828 void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) { 829 extendRegion(S); 830 Visit(S->getElement()); 831 832 Counter ParentCount = getRegion().getCounter(); 833 Counter BodyCount = getRegionCounter(S); 834 835 BreakContinueStack.push_back(BreakContinue()); 836 extendRegion(S->getBody()); 837 Counter BackedgeCount = propagateCounts(BodyCount, S->getBody()); 838 BreakContinue BC = BreakContinueStack.pop_back_val(); 839 840 Counter LoopCount = 841 addCounters(ParentCount, BackedgeCount, BC.ContinueCount); 842 Counter OutCount = 843 addCounters(BC.BreakCount, subtractCounters(LoopCount, BodyCount)); 844 if (OutCount != ParentCount) 845 pushRegion(OutCount); 846 } 847 848 void VisitSwitchStmt(const SwitchStmt *S) { 849 extendRegion(S); 850 if (S->getInit()) 851 Visit(S->getInit()); 852 Visit(S->getCond()); 853 854 BreakContinueStack.push_back(BreakContinue()); 855 856 const Stmt *Body = S->getBody(); 857 extendRegion(Body); 858 if (const auto *CS = dyn_cast<CompoundStmt>(Body)) { 859 if (!CS->body_empty()) { 860 // Make a region for the body of the switch. If the body starts with 861 // a case, that case will reuse this region; otherwise, this covers 862 // the unreachable code at the beginning of the switch body. 863 size_t Index = 864 pushRegion(Counter::getZero(), getStart(CS->body_front())); 865 for (const auto *Child : CS->children()) 866 Visit(Child); 867 868 // Set the end for the body of the switch, if it isn't already set. 869 for (size_t i = RegionStack.size(); i != Index; --i) { 870 if (!RegionStack[i - 1].hasEndLoc()) 871 RegionStack[i - 1].setEndLoc(getEnd(CS->body_back())); 872 } 873 874 popRegions(Index); 875 } 876 } else 877 propagateCounts(Counter::getZero(), Body); 878 BreakContinue BC = BreakContinueStack.pop_back_val(); 879 880 if (!BreakContinueStack.empty()) 881 BreakContinueStack.back().ContinueCount = addCounters( 882 BreakContinueStack.back().ContinueCount, BC.ContinueCount); 883 884 Counter ExitCount = getRegionCounter(S); 885 SourceLocation ExitLoc = getEnd(S); 886 pushRegion(ExitCount); 887 888 // Ensure that handleFileExit recognizes when the end location is located 889 // in a different file. 890 MostRecentLocation = getStart(S); 891 handleFileExit(ExitLoc); 892 } 893 894 void VisitSwitchCase(const SwitchCase *S) { 895 extendRegion(S); 896 897 SourceMappingRegion &Parent = getRegion(); 898 899 Counter Count = addCounters(Parent.getCounter(), getRegionCounter(S)); 900 // Reuse the existing region if it starts at our label. This is typical of 901 // the first case in a switch. 902 if (Parent.hasStartLoc() && Parent.getStartLoc() == getStart(S)) 903 Parent.setCounter(Count); 904 else 905 pushRegion(Count, getStart(S)); 906 907 if (const auto *CS = dyn_cast<CaseStmt>(S)) { 908 Visit(CS->getLHS()); 909 if (const Expr *RHS = CS->getRHS()) 910 Visit(RHS); 911 } 912 Visit(S->getSubStmt()); 913 } 914 915 void VisitIfStmt(const IfStmt *S) { 916 extendRegion(S); 917 if (S->getInit()) 918 Visit(S->getInit()); 919 920 // Extend into the condition before we propagate through it below - this is 921 // needed to handle macros that generate the "if" but not the condition. 922 extendRegion(S->getCond()); 923 924 Counter ParentCount = getRegion().getCounter(); 925 Counter ThenCount = getRegionCounter(S); 926 927 // Emitting a counter for the condition makes it easier to interpret the 928 // counter for the body when looking at the coverage. 929 propagateCounts(ParentCount, S->getCond()); 930 931 extendRegion(S->getThen()); 932 Counter OutCount = propagateCounts(ThenCount, S->getThen()); 933 934 Counter ElseCount = subtractCounters(ParentCount, ThenCount); 935 if (const Stmt *Else = S->getElse()) { 936 extendRegion(S->getElse()); 937 OutCount = addCounters(OutCount, propagateCounts(ElseCount, Else)); 938 } else 939 OutCount = addCounters(OutCount, ElseCount); 940 941 if (OutCount != ParentCount) 942 pushRegion(OutCount); 943 } 944 945 void VisitCXXTryStmt(const CXXTryStmt *S) { 946 extendRegion(S); 947 // Handle macros that generate the "try" but not the rest. 948 extendRegion(S->getTryBlock()); 949 950 Counter ParentCount = getRegion().getCounter(); 951 propagateCounts(ParentCount, S->getTryBlock()); 952 953 for (unsigned I = 0, E = S->getNumHandlers(); I < E; ++I) 954 Visit(S->getHandler(I)); 955 956 Counter ExitCount = getRegionCounter(S); 957 pushRegion(ExitCount); 958 } 959 960 void VisitCXXCatchStmt(const CXXCatchStmt *S) { 961 propagateCounts(getRegionCounter(S), S->getHandlerBlock()); 962 } 963 964 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) { 965 extendRegion(E); 966 967 Counter ParentCount = getRegion().getCounter(); 968 Counter TrueCount = getRegionCounter(E); 969 970 Visit(E->getCond()); 971 972 if (!isa<BinaryConditionalOperator>(E)) { 973 extendRegion(E->getTrueExpr()); 974 propagateCounts(TrueCount, E->getTrueExpr()); 975 } 976 extendRegion(E->getFalseExpr()); 977 propagateCounts(subtractCounters(ParentCount, TrueCount), 978 E->getFalseExpr()); 979 } 980 981 void VisitBinLAnd(const BinaryOperator *E) { 982 extendRegion(E); 983 Visit(E->getLHS()); 984 985 extendRegion(E->getRHS()); 986 propagateCounts(getRegionCounter(E), E->getRHS()); 987 } 988 989 void VisitBinLOr(const BinaryOperator *E) { 990 extendRegion(E); 991 Visit(E->getLHS()); 992 993 extendRegion(E->getRHS()); 994 propagateCounts(getRegionCounter(E), E->getRHS()); 995 } 996 997 void VisitLambdaExpr(const LambdaExpr *LE) { 998 // Lambdas are treated as their own functions for now, so we shouldn't 999 // propagate counts into them. 1000 } 1001 }; 1002 1003 std::string getCoverageSection(const CodeGenModule &CGM) { 1004 return llvm::getInstrProfSectionName( 1005 llvm::IPSK_covmap, 1006 CGM.getContext().getTargetInfo().getTriple().getObjectFormat()); 1007 } 1008 1009 std::string normalizeFilename(StringRef Filename) { 1010 llvm::SmallString<256> Path(Filename); 1011 llvm::sys::fs::make_absolute(Path); 1012 llvm::sys::path::remove_dots(Path, /*remove_dot_dots=*/true); 1013 return Path.str().str(); 1014 } 1015 1016 } // end anonymous namespace 1017 1018 static void dump(llvm::raw_ostream &OS, StringRef FunctionName, 1019 ArrayRef<CounterExpression> Expressions, 1020 ArrayRef<CounterMappingRegion> Regions) { 1021 OS << FunctionName << ":\n"; 1022 CounterMappingContext Ctx(Expressions); 1023 for (const auto &R : Regions) { 1024 OS.indent(2); 1025 switch (R.Kind) { 1026 case CounterMappingRegion::CodeRegion: 1027 break; 1028 case CounterMappingRegion::ExpansionRegion: 1029 OS << "Expansion,"; 1030 break; 1031 case CounterMappingRegion::SkippedRegion: 1032 OS << "Skipped,"; 1033 break; 1034 } 1035 1036 OS << "File " << R.FileID << ", " << R.LineStart << ":" << R.ColumnStart 1037 << " -> " << R.LineEnd << ":" << R.ColumnEnd << " = "; 1038 Ctx.dump(R.Count, OS); 1039 if (R.Kind == CounterMappingRegion::ExpansionRegion) 1040 OS << " (Expanded file = " << R.ExpandedFileID << ")"; 1041 OS << "\n"; 1042 } 1043 } 1044 1045 void CoverageMappingModuleGen::addFunctionMappingRecord( 1046 llvm::GlobalVariable *NamePtr, StringRef NameValue, uint64_t FuncHash, 1047 const std::string &CoverageMapping, bool IsUsed) { 1048 llvm::LLVMContext &Ctx = CGM.getLLVMContext(); 1049 if (!FunctionRecordTy) { 1050 #define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) LLVMType, 1051 llvm::Type *FunctionRecordTypes[] = { 1052 #include "llvm/ProfileData/InstrProfData.inc" 1053 }; 1054 FunctionRecordTy = 1055 llvm::StructType::get(Ctx, makeArrayRef(FunctionRecordTypes), 1056 /*isPacked=*/true); 1057 } 1058 1059 #define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) Init, 1060 llvm::Constant *FunctionRecordVals[] = { 1061 #include "llvm/ProfileData/InstrProfData.inc" 1062 }; 1063 FunctionRecords.push_back(llvm::ConstantStruct::get( 1064 FunctionRecordTy, makeArrayRef(FunctionRecordVals))); 1065 if (!IsUsed) 1066 FunctionNames.push_back( 1067 llvm::ConstantExpr::getBitCast(NamePtr, llvm::Type::getInt8PtrTy(Ctx))); 1068 CoverageMappings.push_back(CoverageMapping); 1069 1070 if (CGM.getCodeGenOpts().DumpCoverageMapping) { 1071 // Dump the coverage mapping data for this function by decoding the 1072 // encoded data. This allows us to dump the mapping regions which were 1073 // also processed by the CoverageMappingWriter which performs 1074 // additional minimization operations such as reducing the number of 1075 // expressions. 1076 std::vector<StringRef> Filenames; 1077 std::vector<CounterExpression> Expressions; 1078 std::vector<CounterMappingRegion> Regions; 1079 llvm::SmallVector<std::string, 16> FilenameStrs; 1080 llvm::SmallVector<StringRef, 16> FilenameRefs; 1081 FilenameStrs.resize(FileEntries.size()); 1082 FilenameRefs.resize(FileEntries.size()); 1083 for (const auto &Entry : FileEntries) { 1084 auto I = Entry.second; 1085 FilenameStrs[I] = normalizeFilename(Entry.first->getName()); 1086 FilenameRefs[I] = FilenameStrs[I]; 1087 } 1088 RawCoverageMappingReader Reader(CoverageMapping, FilenameRefs, Filenames, 1089 Expressions, Regions); 1090 if (Reader.read()) 1091 return; 1092 dump(llvm::outs(), NameValue, Expressions, Regions); 1093 } 1094 } 1095 1096 void CoverageMappingModuleGen::emit() { 1097 if (FunctionRecords.empty()) 1098 return; 1099 llvm::LLVMContext &Ctx = CGM.getLLVMContext(); 1100 auto *Int32Ty = llvm::Type::getInt32Ty(Ctx); 1101 1102 // Create the filenames and merge them with coverage mappings 1103 llvm::SmallVector<std::string, 16> FilenameStrs; 1104 llvm::SmallVector<StringRef, 16> FilenameRefs; 1105 FilenameStrs.resize(FileEntries.size()); 1106 FilenameRefs.resize(FileEntries.size()); 1107 for (const auto &Entry : FileEntries) { 1108 auto I = Entry.second; 1109 FilenameStrs[I] = normalizeFilename(Entry.first->getName()); 1110 FilenameRefs[I] = FilenameStrs[I]; 1111 } 1112 1113 std::string FilenamesAndCoverageMappings; 1114 llvm::raw_string_ostream OS(FilenamesAndCoverageMappings); 1115 CoverageFilenamesSectionWriter(FilenameRefs).write(OS); 1116 std::string RawCoverageMappings = 1117 llvm::join(CoverageMappings.begin(), CoverageMappings.end(), ""); 1118 OS << RawCoverageMappings; 1119 size_t CoverageMappingSize = RawCoverageMappings.size(); 1120 size_t FilenamesSize = OS.str().size() - CoverageMappingSize; 1121 // Append extra zeroes if necessary to ensure that the size of the filenames 1122 // and coverage mappings is a multiple of 8. 1123 if (size_t Rem = OS.str().size() % 8) { 1124 CoverageMappingSize += 8 - Rem; 1125 for (size_t I = 0, S = 8 - Rem; I < S; ++I) 1126 OS << '\0'; 1127 } 1128 auto *FilenamesAndMappingsVal = 1129 llvm::ConstantDataArray::getString(Ctx, OS.str(), false); 1130 1131 // Create the deferred function records array 1132 auto RecordsTy = 1133 llvm::ArrayType::get(FunctionRecordTy, FunctionRecords.size()); 1134 auto RecordsVal = llvm::ConstantArray::get(RecordsTy, FunctionRecords); 1135 1136 llvm::Type *CovDataHeaderTypes[] = { 1137 #define COVMAP_HEADER(Type, LLVMType, Name, Init) LLVMType, 1138 #include "llvm/ProfileData/InstrProfData.inc" 1139 }; 1140 auto CovDataHeaderTy = 1141 llvm::StructType::get(Ctx, makeArrayRef(CovDataHeaderTypes)); 1142 llvm::Constant *CovDataHeaderVals[] = { 1143 #define COVMAP_HEADER(Type, LLVMType, Name, Init) Init, 1144 #include "llvm/ProfileData/InstrProfData.inc" 1145 }; 1146 auto CovDataHeaderVal = llvm::ConstantStruct::get( 1147 CovDataHeaderTy, makeArrayRef(CovDataHeaderVals)); 1148 1149 // Create the coverage data record 1150 llvm::Type *CovDataTypes[] = {CovDataHeaderTy, RecordsTy, 1151 FilenamesAndMappingsVal->getType()}; 1152 auto CovDataTy = llvm::StructType::get(Ctx, makeArrayRef(CovDataTypes)); 1153 llvm::Constant *TUDataVals[] = {CovDataHeaderVal, RecordsVal, 1154 FilenamesAndMappingsVal}; 1155 auto CovDataVal = 1156 llvm::ConstantStruct::get(CovDataTy, makeArrayRef(TUDataVals)); 1157 auto CovData = new llvm::GlobalVariable( 1158 CGM.getModule(), CovDataTy, true, llvm::GlobalValue::InternalLinkage, 1159 CovDataVal, llvm::getCoverageMappingVarName()); 1160 1161 CovData->setSection(getCoverageSection(CGM)); 1162 CovData->setAlignment(8); 1163 1164 // Make sure the data doesn't get deleted. 1165 CGM.addUsedGlobal(CovData); 1166 // Create the deferred function records array 1167 if (!FunctionNames.empty()) { 1168 auto NamesArrTy = llvm::ArrayType::get(llvm::Type::getInt8PtrTy(Ctx), 1169 FunctionNames.size()); 1170 auto NamesArrVal = llvm::ConstantArray::get(NamesArrTy, FunctionNames); 1171 // This variable will *NOT* be emitted to the object file. It is used 1172 // to pass the list of names referenced to codegen. 1173 new llvm::GlobalVariable(CGM.getModule(), NamesArrTy, true, 1174 llvm::GlobalValue::InternalLinkage, NamesArrVal, 1175 llvm::getCoverageUnusedNamesVarName()); 1176 } 1177 } 1178 1179 unsigned CoverageMappingModuleGen::getFileID(const FileEntry *File) { 1180 auto It = FileEntries.find(File); 1181 if (It != FileEntries.end()) 1182 return It->second; 1183 unsigned FileID = FileEntries.size(); 1184 FileEntries.insert(std::make_pair(File, FileID)); 1185 return FileID; 1186 } 1187 1188 void CoverageMappingGen::emitCounterMapping(const Decl *D, 1189 llvm::raw_ostream &OS) { 1190 assert(CounterMap); 1191 CounterCoverageMappingBuilder Walker(CVM, *CounterMap, SM, LangOpts); 1192 Walker.VisitDecl(D); 1193 Walker.write(OS); 1194 } 1195 1196 void CoverageMappingGen::emitEmptyMapping(const Decl *D, 1197 llvm::raw_ostream &OS) { 1198 EmptyCoverageMappingBuilder Walker(CVM, SM, LangOpts); 1199 Walker.VisitDecl(D); 1200 Walker.write(OS); 1201 } 1202