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