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