1 //===- CoverageMapping.cpp - Code coverage mapping support ----------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file contains support for clang's and llvm's instrumentation based 10 // code coverage. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm/ProfileData/Coverage/CoverageMapping.h" 15 #include "llvm/ADT/ArrayRef.h" 16 #include "llvm/ADT/DenseMap.h" 17 #include "llvm/ADT/SmallBitVector.h" 18 #include "llvm/ADT/SmallString.h" 19 #include "llvm/ADT/SmallVector.h" 20 #include "llvm/ADT/StringExtras.h" 21 #include "llvm/ADT/StringRef.h" 22 #include "llvm/Object/BuildID.h" 23 #include "llvm/ProfileData/Coverage/CoverageMappingReader.h" 24 #include "llvm/ProfileData/InstrProfReader.h" 25 #include "llvm/Support/Debug.h" 26 #include "llvm/Support/Errc.h" 27 #include "llvm/Support/Error.h" 28 #include "llvm/Support/ErrorHandling.h" 29 #include "llvm/Support/MemoryBuffer.h" 30 #include "llvm/Support/VirtualFileSystem.h" 31 #include "llvm/Support/raw_ostream.h" 32 #include <algorithm> 33 #include <cassert> 34 #include <cstdint> 35 #include <iterator> 36 #include <map> 37 #include <memory> 38 #include <optional> 39 #include <string> 40 #include <system_error> 41 #include <utility> 42 #include <vector> 43 44 using namespace llvm; 45 using namespace coverage; 46 47 #define DEBUG_TYPE "coverage-mapping" 48 49 Counter CounterExpressionBuilder::get(const CounterExpression &E) { 50 auto It = ExpressionIndices.find(E); 51 if (It != ExpressionIndices.end()) 52 return Counter::getExpression(It->second); 53 unsigned I = Expressions.size(); 54 Expressions.push_back(E); 55 ExpressionIndices[E] = I; 56 return Counter::getExpression(I); 57 } 58 59 void CounterExpressionBuilder::extractTerms(Counter C, int Factor, 60 SmallVectorImpl<Term> &Terms) { 61 switch (C.getKind()) { 62 case Counter::Zero: 63 break; 64 case Counter::CounterValueReference: 65 Terms.emplace_back(C.getCounterID(), Factor); 66 break; 67 case Counter::Expression: 68 const auto &E = Expressions[C.getExpressionID()]; 69 extractTerms(E.LHS, Factor, Terms); 70 extractTerms( 71 E.RHS, E.Kind == CounterExpression::Subtract ? -Factor : Factor, Terms); 72 break; 73 } 74 } 75 76 Counter CounterExpressionBuilder::simplify(Counter ExpressionTree) { 77 // Gather constant terms. 78 SmallVector<Term, 32> Terms; 79 extractTerms(ExpressionTree, +1, Terms); 80 81 // If there are no terms, this is just a zero. The algorithm below assumes at 82 // least one term. 83 if (Terms.size() == 0) 84 return Counter::getZero(); 85 86 // Group the terms by counter ID. 87 llvm::sort(Terms, [](const Term &LHS, const Term &RHS) { 88 return LHS.CounterID < RHS.CounterID; 89 }); 90 91 // Combine terms by counter ID to eliminate counters that sum to zero. 92 auto Prev = Terms.begin(); 93 for (auto I = Prev + 1, E = Terms.end(); I != E; ++I) { 94 if (I->CounterID == Prev->CounterID) { 95 Prev->Factor += I->Factor; 96 continue; 97 } 98 ++Prev; 99 *Prev = *I; 100 } 101 Terms.erase(++Prev, Terms.end()); 102 103 Counter C; 104 // Create additions. We do this before subtractions to avoid constructs like 105 // ((0 - X) + Y), as opposed to (Y - X). 106 for (auto T : Terms) { 107 if (T.Factor <= 0) 108 continue; 109 for (int I = 0; I < T.Factor; ++I) 110 if (C.isZero()) 111 C = Counter::getCounter(T.CounterID); 112 else 113 C = get(CounterExpression(CounterExpression::Add, C, 114 Counter::getCounter(T.CounterID))); 115 } 116 117 // Create subtractions. 118 for (auto T : Terms) { 119 if (T.Factor >= 0) 120 continue; 121 for (int I = 0; I < -T.Factor; ++I) 122 C = get(CounterExpression(CounterExpression::Subtract, C, 123 Counter::getCounter(T.CounterID))); 124 } 125 return C; 126 } 127 128 Counter CounterExpressionBuilder::add(Counter LHS, Counter RHS, bool Simplify) { 129 auto Cnt = get(CounterExpression(CounterExpression::Add, LHS, RHS)); 130 return Simplify ? simplify(Cnt) : Cnt; 131 } 132 133 Counter CounterExpressionBuilder::subtract(Counter LHS, Counter RHS, 134 bool Simplify) { 135 auto Cnt = get(CounterExpression(CounterExpression::Subtract, LHS, RHS)); 136 return Simplify ? simplify(Cnt) : Cnt; 137 } 138 139 void CounterMappingContext::dump(const Counter &C, raw_ostream &OS) const { 140 switch (C.getKind()) { 141 case Counter::Zero: 142 OS << '0'; 143 return; 144 case Counter::CounterValueReference: 145 OS << '#' << C.getCounterID(); 146 break; 147 case Counter::Expression: { 148 if (C.getExpressionID() >= Expressions.size()) 149 return; 150 const auto &E = Expressions[C.getExpressionID()]; 151 OS << '('; 152 dump(E.LHS, OS); 153 OS << (E.Kind == CounterExpression::Subtract ? " - " : " + "); 154 dump(E.RHS, OS); 155 OS << ')'; 156 break; 157 } 158 } 159 if (CounterValues.empty()) 160 return; 161 Expected<int64_t> Value = evaluate(C); 162 if (auto E = Value.takeError()) { 163 consumeError(std::move(E)); 164 return; 165 } 166 OS << '[' << *Value << ']'; 167 } 168 169 Expected<int64_t> CounterMappingContext::evaluate(const Counter &C) const { 170 struct StackElem { 171 Counter ICounter; 172 int64_t LHS = 0; 173 enum { 174 KNeverVisited = 0, 175 KVisitedOnce = 1, 176 KVisitedTwice = 2, 177 } VisitCount = KNeverVisited; 178 }; 179 180 std::stack<StackElem> CounterStack; 181 CounterStack.push({C}); 182 183 int64_t LastPoppedValue; 184 185 while (!CounterStack.empty()) { 186 StackElem &Current = CounterStack.top(); 187 188 switch (Current.ICounter.getKind()) { 189 case Counter::Zero: 190 LastPoppedValue = 0; 191 CounterStack.pop(); 192 break; 193 case Counter::CounterValueReference: 194 if (Current.ICounter.getCounterID() >= CounterValues.size()) 195 return errorCodeToError(errc::argument_out_of_domain); 196 LastPoppedValue = CounterValues[Current.ICounter.getCounterID()]; 197 CounterStack.pop(); 198 break; 199 case Counter::Expression: { 200 if (Current.ICounter.getExpressionID() >= Expressions.size()) 201 return errorCodeToError(errc::argument_out_of_domain); 202 const auto &E = Expressions[Current.ICounter.getExpressionID()]; 203 if (Current.VisitCount == StackElem::KNeverVisited) { 204 CounterStack.push(StackElem{E.LHS}); 205 Current.VisitCount = StackElem::KVisitedOnce; 206 } else if (Current.VisitCount == StackElem::KVisitedOnce) { 207 Current.LHS = LastPoppedValue; 208 CounterStack.push(StackElem{E.RHS}); 209 Current.VisitCount = StackElem::KVisitedTwice; 210 } else { 211 int64_t LHS = Current.LHS; 212 int64_t RHS = LastPoppedValue; 213 LastPoppedValue = 214 E.Kind == CounterExpression::Subtract ? LHS - RHS : LHS + RHS; 215 CounterStack.pop(); 216 } 217 break; 218 } 219 default: 220 llvm_unreachable("Unhandled CounterKind"); 221 } 222 } 223 224 return LastPoppedValue; 225 } 226 227 unsigned CounterMappingContext::getMaxCounterID(const Counter &C) const { 228 switch (C.getKind()) { 229 case Counter::Zero: 230 return 0; 231 case Counter::CounterValueReference: 232 return C.getCounterID(); 233 case Counter::Expression: { 234 if (C.getExpressionID() >= Expressions.size()) 235 return 0; 236 const auto &E = Expressions[C.getExpressionID()]; 237 return std::max(getMaxCounterID(E.LHS), getMaxCounterID(E.RHS)); 238 } 239 } 240 llvm_unreachable("Unhandled CounterKind"); 241 } 242 243 void FunctionRecordIterator::skipOtherFiles() { 244 while (Current != Records.end() && !Filename.empty() && 245 Filename != Current->Filenames[0]) 246 ++Current; 247 if (Current == Records.end()) 248 *this = FunctionRecordIterator(); 249 } 250 251 ArrayRef<unsigned> CoverageMapping::getImpreciseRecordIndicesForFilename( 252 StringRef Filename) const { 253 size_t FilenameHash = hash_value(Filename); 254 auto RecordIt = FilenameHash2RecordIndices.find(FilenameHash); 255 if (RecordIt == FilenameHash2RecordIndices.end()) 256 return {}; 257 return RecordIt->second; 258 } 259 260 static unsigned getMaxCounterID(const CounterMappingContext &Ctx, 261 const CoverageMappingRecord &Record) { 262 unsigned MaxCounterID = 0; 263 for (const auto &Region : Record.MappingRegions) { 264 MaxCounterID = std::max(MaxCounterID, Ctx.getMaxCounterID(Region.Count)); 265 } 266 return MaxCounterID; 267 } 268 269 Error CoverageMapping::loadFunctionRecord( 270 const CoverageMappingRecord &Record, 271 IndexedInstrProfReader &ProfileReader) { 272 StringRef OrigFuncName = Record.FunctionName; 273 if (OrigFuncName.empty()) 274 return make_error<CoverageMapError>(coveragemap_error::malformed, 275 "record function name is empty"); 276 277 if (Record.Filenames.empty()) 278 OrigFuncName = getFuncNameWithoutPrefix(OrigFuncName); 279 else 280 OrigFuncName = getFuncNameWithoutPrefix(OrigFuncName, Record.Filenames[0]); 281 282 CounterMappingContext Ctx(Record.Expressions); 283 284 std::vector<uint64_t> Counts; 285 if (Error E = ProfileReader.getFunctionCounts(Record.FunctionName, 286 Record.FunctionHash, Counts)) { 287 instrprof_error IPE = std::get<0>(InstrProfError::take(std::move(E))); 288 if (IPE == instrprof_error::hash_mismatch) { 289 FuncHashMismatches.emplace_back(std::string(Record.FunctionName), 290 Record.FunctionHash); 291 return Error::success(); 292 } else if (IPE != instrprof_error::unknown_function) 293 return make_error<InstrProfError>(IPE); 294 Counts.assign(getMaxCounterID(Ctx, Record) + 1, 0); 295 } 296 Ctx.setCounts(Counts); 297 298 assert(!Record.MappingRegions.empty() && "Function has no regions"); 299 300 // This coverage record is a zero region for a function that's unused in 301 // some TU, but used in a different TU. Ignore it. The coverage maps from the 302 // the other TU will either be loaded (providing full region counts) or they 303 // won't (in which case we don't unintuitively report functions as uncovered 304 // when they have non-zero counts in the profile). 305 if (Record.MappingRegions.size() == 1 && 306 Record.MappingRegions[0].Count.isZero() && Counts[0] > 0) 307 return Error::success(); 308 309 FunctionRecord Function(OrigFuncName, Record.Filenames); 310 for (const auto &Region : Record.MappingRegions) { 311 Expected<int64_t> ExecutionCount = Ctx.evaluate(Region.Count); 312 if (auto E = ExecutionCount.takeError()) { 313 consumeError(std::move(E)); 314 return Error::success(); 315 } 316 Expected<int64_t> AltExecutionCount = Ctx.evaluate(Region.FalseCount); 317 if (auto E = AltExecutionCount.takeError()) { 318 consumeError(std::move(E)); 319 return Error::success(); 320 } 321 Function.pushRegion(Region, *ExecutionCount, *AltExecutionCount); 322 } 323 324 // Don't create records for (filenames, function) pairs we've already seen. 325 auto FilenamesHash = hash_combine_range(Record.Filenames.begin(), 326 Record.Filenames.end()); 327 if (!RecordProvenance[FilenamesHash].insert(hash_value(OrigFuncName)).second) 328 return Error::success(); 329 330 Functions.push_back(std::move(Function)); 331 332 // Performance optimization: keep track of the indices of the function records 333 // which correspond to each filename. This can be used to substantially speed 334 // up queries for coverage info in a file. 335 unsigned RecordIndex = Functions.size() - 1; 336 for (StringRef Filename : Record.Filenames) { 337 auto &RecordIndices = FilenameHash2RecordIndices[hash_value(Filename)]; 338 // Note that there may be duplicates in the filename set for a function 339 // record, because of e.g. macro expansions in the function in which both 340 // the macro and the function are defined in the same file. 341 if (RecordIndices.empty() || RecordIndices.back() != RecordIndex) 342 RecordIndices.push_back(RecordIndex); 343 } 344 345 return Error::success(); 346 } 347 348 // This function is for memory optimization by shortening the lifetimes 349 // of CoverageMappingReader instances. 350 Error CoverageMapping::loadFromReaders( 351 ArrayRef<std::unique_ptr<CoverageMappingReader>> CoverageReaders, 352 IndexedInstrProfReader &ProfileReader, CoverageMapping &Coverage) { 353 for (const auto &CoverageReader : CoverageReaders) { 354 for (auto RecordOrErr : *CoverageReader) { 355 if (Error E = RecordOrErr.takeError()) 356 return E; 357 const auto &Record = *RecordOrErr; 358 if (Error E = Coverage.loadFunctionRecord(Record, ProfileReader)) 359 return E; 360 } 361 } 362 return Error::success(); 363 } 364 365 Expected<std::unique_ptr<CoverageMapping>> CoverageMapping::load( 366 ArrayRef<std::unique_ptr<CoverageMappingReader>> CoverageReaders, 367 IndexedInstrProfReader &ProfileReader) { 368 auto Coverage = std::unique_ptr<CoverageMapping>(new CoverageMapping()); 369 if (Error E = loadFromReaders(CoverageReaders, ProfileReader, *Coverage)) 370 return std::move(E); 371 return std::move(Coverage); 372 } 373 374 // If E is a no_data_found error, returns success. Otherwise returns E. 375 static Error handleMaybeNoDataFoundError(Error E) { 376 return handleErrors( 377 std::move(E), [](const CoverageMapError &CME) { 378 if (CME.get() == coveragemap_error::no_data_found) 379 return static_cast<Error>(Error::success()); 380 return make_error<CoverageMapError>(CME.get(), CME.getMessage()); 381 }); 382 } 383 384 Error CoverageMapping::loadFromFile( 385 StringRef Filename, StringRef Arch, StringRef CompilationDir, 386 IndexedInstrProfReader &ProfileReader, CoverageMapping &Coverage, 387 bool &DataFound, SmallVectorImpl<object::BuildID> *FoundBinaryIDs) { 388 auto CovMappingBufOrErr = MemoryBuffer::getFileOrSTDIN( 389 Filename, /*IsText=*/false, /*RequiresNullTerminator=*/false); 390 if (std::error_code EC = CovMappingBufOrErr.getError()) 391 return createFileError(Filename, errorCodeToError(EC)); 392 MemoryBufferRef CovMappingBufRef = 393 CovMappingBufOrErr.get()->getMemBufferRef(); 394 SmallVector<std::unique_ptr<MemoryBuffer>, 4> Buffers; 395 InstrProfSymtab &ProfSymTab = ProfileReader.getSymtab(); 396 397 SmallVector<object::BuildIDRef> BinaryIDs; 398 auto CoverageReadersOrErr = BinaryCoverageReader::create( 399 CovMappingBufRef, Arch, Buffers, ProfSymTab, 400 CompilationDir, FoundBinaryIDs ? &BinaryIDs : nullptr); 401 if (Error E = CoverageReadersOrErr.takeError()) { 402 E = handleMaybeNoDataFoundError(std::move(E)); 403 if (E) 404 return createFileError(Filename, std::move(E)); 405 return E; 406 } 407 408 SmallVector<std::unique_ptr<CoverageMappingReader>, 4> Readers; 409 for (auto &Reader : CoverageReadersOrErr.get()) 410 Readers.push_back(std::move(Reader)); 411 if (FoundBinaryIDs && !Readers.empty()) { 412 llvm::append_range(*FoundBinaryIDs, 413 llvm::map_range(BinaryIDs, [](object::BuildIDRef BID) { 414 return object::BuildID(BID); 415 })); 416 } 417 DataFound |= !Readers.empty(); 418 if (Error E = loadFromReaders(Readers, ProfileReader, Coverage)) 419 return createFileError(Filename, std::move(E)); 420 return Error::success(); 421 } 422 423 Expected<std::unique_ptr<CoverageMapping>> CoverageMapping::load( 424 ArrayRef<StringRef> ObjectFilenames, StringRef ProfileFilename, 425 vfs::FileSystem &FS, ArrayRef<StringRef> Arches, StringRef CompilationDir, 426 const object::BuildIDFetcher *BIDFetcher, bool CheckBinaryIDs) { 427 auto ProfileReaderOrErr = IndexedInstrProfReader::create(ProfileFilename, FS); 428 if (Error E = ProfileReaderOrErr.takeError()) 429 return createFileError(ProfileFilename, std::move(E)); 430 auto ProfileReader = std::move(ProfileReaderOrErr.get()); 431 auto Coverage = std::unique_ptr<CoverageMapping>(new CoverageMapping()); 432 bool DataFound = false; 433 434 auto GetArch = [&](size_t Idx) { 435 if (Arches.empty()) 436 return StringRef(); 437 if (Arches.size() == 1) 438 return Arches.front(); 439 return Arches[Idx]; 440 }; 441 442 SmallVector<object::BuildID> FoundBinaryIDs; 443 for (const auto &File : llvm::enumerate(ObjectFilenames)) { 444 if (Error E = 445 loadFromFile(File.value(), GetArch(File.index()), CompilationDir, 446 *ProfileReader, *Coverage, DataFound, &FoundBinaryIDs)) 447 return std::move(E); 448 } 449 450 if (BIDFetcher) { 451 std::vector<object::BuildID> ProfileBinaryIDs; 452 if (Error E = ProfileReader->readBinaryIds(ProfileBinaryIDs)) 453 return createFileError(ProfileFilename, std::move(E)); 454 455 SmallVector<object::BuildIDRef> BinaryIDsToFetch; 456 if (!ProfileBinaryIDs.empty()) { 457 const auto &Compare = [](object::BuildIDRef A, object::BuildIDRef B) { 458 return std::lexicographical_compare(A.begin(), A.end(), B.begin(), 459 B.end()); 460 }; 461 llvm::sort(FoundBinaryIDs, Compare); 462 std::set_difference( 463 ProfileBinaryIDs.begin(), ProfileBinaryIDs.end(), 464 FoundBinaryIDs.begin(), FoundBinaryIDs.end(), 465 std::inserter(BinaryIDsToFetch, BinaryIDsToFetch.end()), Compare); 466 } 467 468 for (object::BuildIDRef BinaryID : BinaryIDsToFetch) { 469 std::optional<std::string> PathOpt = BIDFetcher->fetch(BinaryID); 470 if (PathOpt) { 471 std::string Path = std::move(*PathOpt); 472 StringRef Arch = Arches.size() == 1 ? Arches.front() : StringRef(); 473 if (Error E = loadFromFile(Path, Arch, CompilationDir, *ProfileReader, 474 *Coverage, DataFound)) 475 return std::move(E); 476 } else if (CheckBinaryIDs) { 477 return createFileError( 478 ProfileFilename, 479 createStringError(errc::no_such_file_or_directory, 480 "Missing binary ID: " + 481 llvm::toHex(BinaryID, /*LowerCase=*/true))); 482 } 483 } 484 } 485 486 if (!DataFound) 487 return createFileError( 488 join(ObjectFilenames.begin(), ObjectFilenames.end(), ", "), 489 make_error<CoverageMapError>(coveragemap_error::no_data_found)); 490 return std::move(Coverage); 491 } 492 493 namespace { 494 495 /// Distributes functions into instantiation sets. 496 /// 497 /// An instantiation set is a collection of functions that have the same source 498 /// code, ie, template functions specializations. 499 class FunctionInstantiationSetCollector { 500 using MapT = std::map<LineColPair, std::vector<const FunctionRecord *>>; 501 MapT InstantiatedFunctions; 502 503 public: 504 void insert(const FunctionRecord &Function, unsigned FileID) { 505 auto I = Function.CountedRegions.begin(), E = Function.CountedRegions.end(); 506 while (I != E && I->FileID != FileID) 507 ++I; 508 assert(I != E && "function does not cover the given file"); 509 auto &Functions = InstantiatedFunctions[I->startLoc()]; 510 Functions.push_back(&Function); 511 } 512 513 MapT::iterator begin() { return InstantiatedFunctions.begin(); } 514 MapT::iterator end() { return InstantiatedFunctions.end(); } 515 }; 516 517 class SegmentBuilder { 518 std::vector<CoverageSegment> &Segments; 519 SmallVector<const CountedRegion *, 8> ActiveRegions; 520 521 SegmentBuilder(std::vector<CoverageSegment> &Segments) : Segments(Segments) {} 522 523 /// Emit a segment with the count from \p Region starting at \p StartLoc. 524 // 525 /// \p IsRegionEntry: The segment is at the start of a new non-gap region. 526 /// \p EmitSkippedRegion: The segment must be emitted as a skipped region. 527 void startSegment(const CountedRegion &Region, LineColPair StartLoc, 528 bool IsRegionEntry, bool EmitSkippedRegion = false) { 529 bool HasCount = !EmitSkippedRegion && 530 (Region.Kind != CounterMappingRegion::SkippedRegion); 531 532 // If the new segment wouldn't affect coverage rendering, skip it. 533 if (!Segments.empty() && !IsRegionEntry && !EmitSkippedRegion) { 534 const auto &Last = Segments.back(); 535 if (Last.HasCount == HasCount && Last.Count == Region.ExecutionCount && 536 !Last.IsRegionEntry) 537 return; 538 } 539 540 if (HasCount) 541 Segments.emplace_back(StartLoc.first, StartLoc.second, 542 Region.ExecutionCount, IsRegionEntry, 543 Region.Kind == CounterMappingRegion::GapRegion); 544 else 545 Segments.emplace_back(StartLoc.first, StartLoc.second, IsRegionEntry); 546 547 LLVM_DEBUG({ 548 const auto &Last = Segments.back(); 549 dbgs() << "Segment at " << Last.Line << ":" << Last.Col 550 << " (count = " << Last.Count << ")" 551 << (Last.IsRegionEntry ? ", RegionEntry" : "") 552 << (!Last.HasCount ? ", Skipped" : "") 553 << (Last.IsGapRegion ? ", Gap" : "") << "\n"; 554 }); 555 } 556 557 /// Emit segments for active regions which end before \p Loc. 558 /// 559 /// \p Loc: The start location of the next region. If std::nullopt, all active 560 /// regions are completed. 561 /// \p FirstCompletedRegion: Index of the first completed region. 562 void completeRegionsUntil(std::optional<LineColPair> Loc, 563 unsigned FirstCompletedRegion) { 564 // Sort the completed regions by end location. This makes it simple to 565 // emit closing segments in sorted order. 566 auto CompletedRegionsIt = ActiveRegions.begin() + FirstCompletedRegion; 567 std::stable_sort(CompletedRegionsIt, ActiveRegions.end(), 568 [](const CountedRegion *L, const CountedRegion *R) { 569 return L->endLoc() < R->endLoc(); 570 }); 571 572 // Emit segments for all completed regions. 573 for (unsigned I = FirstCompletedRegion + 1, E = ActiveRegions.size(); I < E; 574 ++I) { 575 const auto *CompletedRegion = ActiveRegions[I]; 576 assert((!Loc || CompletedRegion->endLoc() <= *Loc) && 577 "Completed region ends after start of new region"); 578 579 const auto *PrevCompletedRegion = ActiveRegions[I - 1]; 580 auto CompletedSegmentLoc = PrevCompletedRegion->endLoc(); 581 582 // Don't emit any more segments if they start where the new region begins. 583 if (Loc && CompletedSegmentLoc == *Loc) 584 break; 585 586 // Don't emit a segment if the next completed region ends at the same 587 // location as this one. 588 if (CompletedSegmentLoc == CompletedRegion->endLoc()) 589 continue; 590 591 // Use the count from the last completed region which ends at this loc. 592 for (unsigned J = I + 1; J < E; ++J) 593 if (CompletedRegion->endLoc() == ActiveRegions[J]->endLoc()) 594 CompletedRegion = ActiveRegions[J]; 595 596 startSegment(*CompletedRegion, CompletedSegmentLoc, false); 597 } 598 599 auto Last = ActiveRegions.back(); 600 if (FirstCompletedRegion && Last->endLoc() != *Loc) { 601 // If there's a gap after the end of the last completed region and the 602 // start of the new region, use the last active region to fill the gap. 603 startSegment(*ActiveRegions[FirstCompletedRegion - 1], Last->endLoc(), 604 false); 605 } else if (!FirstCompletedRegion && (!Loc || *Loc != Last->endLoc())) { 606 // Emit a skipped segment if there are no more active regions. This 607 // ensures that gaps between functions are marked correctly. 608 startSegment(*Last, Last->endLoc(), false, true); 609 } 610 611 // Pop the completed regions. 612 ActiveRegions.erase(CompletedRegionsIt, ActiveRegions.end()); 613 } 614 615 void buildSegmentsImpl(ArrayRef<CountedRegion> Regions) { 616 for (const auto &CR : enumerate(Regions)) { 617 auto CurStartLoc = CR.value().startLoc(); 618 619 // Active regions which end before the current region need to be popped. 620 auto CompletedRegions = 621 std::stable_partition(ActiveRegions.begin(), ActiveRegions.end(), 622 [&](const CountedRegion *Region) { 623 return !(Region->endLoc() <= CurStartLoc); 624 }); 625 if (CompletedRegions != ActiveRegions.end()) { 626 unsigned FirstCompletedRegion = 627 std::distance(ActiveRegions.begin(), CompletedRegions); 628 completeRegionsUntil(CurStartLoc, FirstCompletedRegion); 629 } 630 631 bool GapRegion = CR.value().Kind == CounterMappingRegion::GapRegion; 632 633 // Try to emit a segment for the current region. 634 if (CurStartLoc == CR.value().endLoc()) { 635 // Avoid making zero-length regions active. If it's the last region, 636 // emit a skipped segment. Otherwise use its predecessor's count. 637 const bool Skipped = 638 (CR.index() + 1) == Regions.size() || 639 CR.value().Kind == CounterMappingRegion::SkippedRegion; 640 startSegment(ActiveRegions.empty() ? CR.value() : *ActiveRegions.back(), 641 CurStartLoc, !GapRegion, Skipped); 642 // If it is skipped segment, create a segment with last pushed 643 // regions's count at CurStartLoc. 644 if (Skipped && !ActiveRegions.empty()) 645 startSegment(*ActiveRegions.back(), CurStartLoc, false); 646 continue; 647 } 648 if (CR.index() + 1 == Regions.size() || 649 CurStartLoc != Regions[CR.index() + 1].startLoc()) { 650 // Emit a segment if the next region doesn't start at the same location 651 // as this one. 652 startSegment(CR.value(), CurStartLoc, !GapRegion); 653 } 654 655 // This region is active (i.e not completed). 656 ActiveRegions.push_back(&CR.value()); 657 } 658 659 // Complete any remaining active regions. 660 if (!ActiveRegions.empty()) 661 completeRegionsUntil(std::nullopt, 0); 662 } 663 664 /// Sort a nested sequence of regions from a single file. 665 static void sortNestedRegions(MutableArrayRef<CountedRegion> Regions) { 666 llvm::sort(Regions, [](const CountedRegion &LHS, const CountedRegion &RHS) { 667 if (LHS.startLoc() != RHS.startLoc()) 668 return LHS.startLoc() < RHS.startLoc(); 669 if (LHS.endLoc() != RHS.endLoc()) 670 // When LHS completely contains RHS, we sort LHS first. 671 return RHS.endLoc() < LHS.endLoc(); 672 // If LHS and RHS cover the same area, we need to sort them according 673 // to their kinds so that the most suitable region will become "active" 674 // in combineRegions(). Because we accumulate counter values only from 675 // regions of the same kind as the first region of the area, prefer 676 // CodeRegion to ExpansionRegion and ExpansionRegion to SkippedRegion. 677 static_assert(CounterMappingRegion::CodeRegion < 678 CounterMappingRegion::ExpansionRegion && 679 CounterMappingRegion::ExpansionRegion < 680 CounterMappingRegion::SkippedRegion, 681 "Unexpected order of region kind values"); 682 return LHS.Kind < RHS.Kind; 683 }); 684 } 685 686 /// Combine counts of regions which cover the same area. 687 static ArrayRef<CountedRegion> 688 combineRegions(MutableArrayRef<CountedRegion> Regions) { 689 if (Regions.empty()) 690 return Regions; 691 auto Active = Regions.begin(); 692 auto End = Regions.end(); 693 for (auto I = Regions.begin() + 1; I != End; ++I) { 694 if (Active->startLoc() != I->startLoc() || 695 Active->endLoc() != I->endLoc()) { 696 // Shift to the next region. 697 ++Active; 698 if (Active != I) 699 *Active = *I; 700 continue; 701 } 702 // Merge duplicate region. 703 // If CodeRegions and ExpansionRegions cover the same area, it's probably 704 // a macro which is fully expanded to another macro. In that case, we need 705 // to accumulate counts only from CodeRegions, or else the area will be 706 // counted twice. 707 // On the other hand, a macro may have a nested macro in its body. If the 708 // outer macro is used several times, the ExpansionRegion for the nested 709 // macro will also be added several times. These ExpansionRegions cover 710 // the same source locations and have to be combined to reach the correct 711 // value for that area. 712 // We add counts of the regions of the same kind as the active region 713 // to handle the both situations. 714 if (I->Kind == Active->Kind) 715 Active->ExecutionCount += I->ExecutionCount; 716 } 717 return Regions.drop_back(std::distance(++Active, End)); 718 } 719 720 public: 721 /// Build a sorted list of CoverageSegments from a list of Regions. 722 static std::vector<CoverageSegment> 723 buildSegments(MutableArrayRef<CountedRegion> Regions) { 724 std::vector<CoverageSegment> Segments; 725 SegmentBuilder Builder(Segments); 726 727 sortNestedRegions(Regions); 728 ArrayRef<CountedRegion> CombinedRegions = combineRegions(Regions); 729 730 LLVM_DEBUG({ 731 dbgs() << "Combined regions:\n"; 732 for (const auto &CR : CombinedRegions) 733 dbgs() << " " << CR.LineStart << ":" << CR.ColumnStart << " -> " 734 << CR.LineEnd << ":" << CR.ColumnEnd 735 << " (count=" << CR.ExecutionCount << ")\n"; 736 }); 737 738 Builder.buildSegmentsImpl(CombinedRegions); 739 740 #ifndef NDEBUG 741 for (unsigned I = 1, E = Segments.size(); I < E; ++I) { 742 const auto &L = Segments[I - 1]; 743 const auto &R = Segments[I]; 744 if (!(L.Line < R.Line) && !(L.Line == R.Line && L.Col < R.Col)) { 745 if (L.Line == R.Line && L.Col == R.Col && !L.HasCount) 746 continue; 747 LLVM_DEBUG(dbgs() << " ! Segment " << L.Line << ":" << L.Col 748 << " followed by " << R.Line << ":" << R.Col << "\n"); 749 assert(false && "Coverage segments not unique or sorted"); 750 } 751 } 752 #endif 753 754 return Segments; 755 } 756 }; 757 758 } // end anonymous namespace 759 760 std::vector<StringRef> CoverageMapping::getUniqueSourceFiles() const { 761 std::vector<StringRef> Filenames; 762 for (const auto &Function : getCoveredFunctions()) 763 llvm::append_range(Filenames, Function.Filenames); 764 llvm::sort(Filenames); 765 auto Last = std::unique(Filenames.begin(), Filenames.end()); 766 Filenames.erase(Last, Filenames.end()); 767 return Filenames; 768 } 769 770 static SmallBitVector gatherFileIDs(StringRef SourceFile, 771 const FunctionRecord &Function) { 772 SmallBitVector FilenameEquivalence(Function.Filenames.size(), false); 773 for (unsigned I = 0, E = Function.Filenames.size(); I < E; ++I) 774 if (SourceFile == Function.Filenames[I]) 775 FilenameEquivalence[I] = true; 776 return FilenameEquivalence; 777 } 778 779 /// Return the ID of the file where the definition of the function is located. 780 static std::optional<unsigned> 781 findMainViewFileID(const FunctionRecord &Function) { 782 SmallBitVector IsNotExpandedFile(Function.Filenames.size(), true); 783 for (const auto &CR : Function.CountedRegions) 784 if (CR.Kind == CounterMappingRegion::ExpansionRegion) 785 IsNotExpandedFile[CR.ExpandedFileID] = false; 786 int I = IsNotExpandedFile.find_first(); 787 if (I == -1) 788 return std::nullopt; 789 return I; 790 } 791 792 /// Check if SourceFile is the file that contains the definition of 793 /// the Function. Return the ID of the file in that case or std::nullopt 794 /// otherwise. 795 static std::optional<unsigned> 796 findMainViewFileID(StringRef SourceFile, const FunctionRecord &Function) { 797 std::optional<unsigned> I = findMainViewFileID(Function); 798 if (I && SourceFile == Function.Filenames[*I]) 799 return I; 800 return std::nullopt; 801 } 802 803 static bool isExpansion(const CountedRegion &R, unsigned FileID) { 804 return R.Kind == CounterMappingRegion::ExpansionRegion && R.FileID == FileID; 805 } 806 807 CoverageData CoverageMapping::getCoverageForFile(StringRef Filename) const { 808 CoverageData FileCoverage(Filename); 809 std::vector<CountedRegion> Regions; 810 811 // Look up the function records in the given file. Due to hash collisions on 812 // the filename, we may get back some records that are not in the file. 813 ArrayRef<unsigned> RecordIndices = 814 getImpreciseRecordIndicesForFilename(Filename); 815 for (unsigned RecordIndex : RecordIndices) { 816 const FunctionRecord &Function = Functions[RecordIndex]; 817 auto MainFileID = findMainViewFileID(Filename, Function); 818 auto FileIDs = gatherFileIDs(Filename, Function); 819 for (const auto &CR : Function.CountedRegions) 820 if (FileIDs.test(CR.FileID)) { 821 Regions.push_back(CR); 822 if (MainFileID && isExpansion(CR, *MainFileID)) 823 FileCoverage.Expansions.emplace_back(CR, Function); 824 } 825 // Capture branch regions specific to the function (excluding expansions). 826 for (const auto &CR : Function.CountedBranchRegions) 827 if (FileIDs.test(CR.FileID) && (CR.FileID == CR.ExpandedFileID)) 828 FileCoverage.BranchRegions.push_back(CR); 829 } 830 831 LLVM_DEBUG(dbgs() << "Emitting segments for file: " << Filename << "\n"); 832 FileCoverage.Segments = SegmentBuilder::buildSegments(Regions); 833 834 return FileCoverage; 835 } 836 837 std::vector<InstantiationGroup> 838 CoverageMapping::getInstantiationGroups(StringRef Filename) const { 839 FunctionInstantiationSetCollector InstantiationSetCollector; 840 // Look up the function records in the given file. Due to hash collisions on 841 // the filename, we may get back some records that are not in the file. 842 ArrayRef<unsigned> RecordIndices = 843 getImpreciseRecordIndicesForFilename(Filename); 844 for (unsigned RecordIndex : RecordIndices) { 845 const FunctionRecord &Function = Functions[RecordIndex]; 846 auto MainFileID = findMainViewFileID(Filename, Function); 847 if (!MainFileID) 848 continue; 849 InstantiationSetCollector.insert(Function, *MainFileID); 850 } 851 852 std::vector<InstantiationGroup> Result; 853 for (auto &InstantiationSet : InstantiationSetCollector) { 854 InstantiationGroup IG{InstantiationSet.first.first, 855 InstantiationSet.first.second, 856 std::move(InstantiationSet.second)}; 857 Result.emplace_back(std::move(IG)); 858 } 859 return Result; 860 } 861 862 CoverageData 863 CoverageMapping::getCoverageForFunction(const FunctionRecord &Function) const { 864 auto MainFileID = findMainViewFileID(Function); 865 if (!MainFileID) 866 return CoverageData(); 867 868 CoverageData FunctionCoverage(Function.Filenames[*MainFileID]); 869 std::vector<CountedRegion> Regions; 870 for (const auto &CR : Function.CountedRegions) 871 if (CR.FileID == *MainFileID) { 872 Regions.push_back(CR); 873 if (isExpansion(CR, *MainFileID)) 874 FunctionCoverage.Expansions.emplace_back(CR, Function); 875 } 876 // Capture branch regions specific to the function (excluding expansions). 877 for (const auto &CR : Function.CountedBranchRegions) 878 if (CR.FileID == *MainFileID) 879 FunctionCoverage.BranchRegions.push_back(CR); 880 881 LLVM_DEBUG(dbgs() << "Emitting segments for function: " << Function.Name 882 << "\n"); 883 FunctionCoverage.Segments = SegmentBuilder::buildSegments(Regions); 884 885 return FunctionCoverage; 886 } 887 888 CoverageData CoverageMapping::getCoverageForExpansion( 889 const ExpansionRecord &Expansion) const { 890 CoverageData ExpansionCoverage( 891 Expansion.Function.Filenames[Expansion.FileID]); 892 std::vector<CountedRegion> Regions; 893 for (const auto &CR : Expansion.Function.CountedRegions) 894 if (CR.FileID == Expansion.FileID) { 895 Regions.push_back(CR); 896 if (isExpansion(CR, Expansion.FileID)) 897 ExpansionCoverage.Expansions.emplace_back(CR, Expansion.Function); 898 } 899 for (const auto &CR : Expansion.Function.CountedBranchRegions) 900 // Capture branch regions that only pertain to the corresponding expansion. 901 if (CR.FileID == Expansion.FileID) 902 ExpansionCoverage.BranchRegions.push_back(CR); 903 904 LLVM_DEBUG(dbgs() << "Emitting segments for expansion of file " 905 << Expansion.FileID << "\n"); 906 ExpansionCoverage.Segments = SegmentBuilder::buildSegments(Regions); 907 908 return ExpansionCoverage; 909 } 910 911 LineCoverageStats::LineCoverageStats( 912 ArrayRef<const CoverageSegment *> LineSegments, 913 const CoverageSegment *WrappedSegment, unsigned Line) 914 : ExecutionCount(0), HasMultipleRegions(false), Mapped(false), Line(Line), 915 LineSegments(LineSegments), WrappedSegment(WrappedSegment) { 916 // Find the minimum number of regions which start in this line. 917 unsigned MinRegionCount = 0; 918 auto isStartOfRegion = [](const CoverageSegment *S) { 919 return !S->IsGapRegion && S->HasCount && S->IsRegionEntry; 920 }; 921 for (unsigned I = 0; I < LineSegments.size() && MinRegionCount < 2; ++I) 922 if (isStartOfRegion(LineSegments[I])) 923 ++MinRegionCount; 924 925 bool StartOfSkippedRegion = !LineSegments.empty() && 926 !LineSegments.front()->HasCount && 927 LineSegments.front()->IsRegionEntry; 928 929 HasMultipleRegions = MinRegionCount > 1; 930 Mapped = 931 !StartOfSkippedRegion && 932 ((WrappedSegment && WrappedSegment->HasCount) || (MinRegionCount > 0)); 933 934 if (!Mapped) 935 return; 936 937 // Pick the max count from the non-gap, region entry segments and the 938 // wrapped count. 939 if (WrappedSegment) 940 ExecutionCount = WrappedSegment->Count; 941 if (!MinRegionCount) 942 return; 943 for (const auto *LS : LineSegments) 944 if (isStartOfRegion(LS)) 945 ExecutionCount = std::max(ExecutionCount, LS->Count); 946 } 947 948 LineCoverageIterator &LineCoverageIterator::operator++() { 949 if (Next == CD.end()) { 950 Stats = LineCoverageStats(); 951 Ended = true; 952 return *this; 953 } 954 if (Segments.size()) 955 WrappedSegment = Segments.back(); 956 Segments.clear(); 957 while (Next != CD.end() && Next->Line == Line) 958 Segments.push_back(&*Next++); 959 Stats = LineCoverageStats(Segments, WrappedSegment, Line); 960 ++Line; 961 return *this; 962 } 963 964 static std::string getCoverageMapErrString(coveragemap_error Err, 965 const std::string &ErrMsg = "") { 966 std::string Msg; 967 raw_string_ostream OS(Msg); 968 969 switch ((uint32_t)Err) { 970 case (uint32_t)coveragemap_error::success: 971 OS << "success"; 972 break; 973 case (uint32_t)coveragemap_error::eof: 974 OS << "end of File"; 975 break; 976 case (uint32_t)coveragemap_error::no_data_found: 977 OS << "no coverage data found"; 978 break; 979 case (uint32_t)coveragemap_error::unsupported_version: 980 OS << "unsupported coverage format version"; 981 break; 982 case (uint32_t)coveragemap_error::truncated: 983 OS << "truncated coverage data"; 984 break; 985 case (uint32_t)coveragemap_error::malformed: 986 OS << "malformed coverage data"; 987 break; 988 case (uint32_t)coveragemap_error::decompression_failed: 989 OS << "failed to decompress coverage data (zlib)"; 990 break; 991 case (uint32_t)coveragemap_error::invalid_or_missing_arch_specifier: 992 OS << "`-arch` specifier is invalid or missing for universal binary"; 993 break; 994 default: 995 llvm_unreachable("invalid coverage mapping error."); 996 } 997 998 // If optional error message is not empty, append it to the message. 999 if (!ErrMsg.empty()) 1000 OS << ": " << ErrMsg; 1001 1002 return Msg; 1003 } 1004 1005 namespace { 1006 1007 // FIXME: This class is only here to support the transition to llvm::Error. It 1008 // will be removed once this transition is complete. Clients should prefer to 1009 // deal with the Error value directly, rather than converting to error_code. 1010 class CoverageMappingErrorCategoryType : public std::error_category { 1011 const char *name() const noexcept override { return "llvm.coveragemap"; } 1012 std::string message(int IE) const override { 1013 return getCoverageMapErrString(static_cast<coveragemap_error>(IE)); 1014 } 1015 }; 1016 1017 } // end anonymous namespace 1018 1019 std::string CoverageMapError::message() const { 1020 return getCoverageMapErrString(Err, Msg); 1021 } 1022 1023 const std::error_category &llvm::coverage::coveragemap_category() { 1024 static CoverageMappingErrorCategoryType ErrorCategory; 1025 return ErrorCategory; 1026 } 1027 1028 char CoverageMapError::ID = 0; 1029