1 //=-- CoverageMapping.cpp - Code coverage mapping support ---------*- C++ -*-=// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file contains support for clang's and llvm's instrumentation based 11 // code coverage. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "llvm/ProfileData/Coverage/CoverageMapping.h" 16 #include "llvm/ADT/DenseMap.h" 17 #include "llvm/ADT/Optional.h" 18 #include "llvm/ADT/SmallBitVector.h" 19 #include "llvm/ProfileData/Coverage/CoverageMappingReader.h" 20 #include "llvm/ProfileData/InstrProfReader.h" 21 #include "llvm/Support/Debug.h" 22 #include "llvm/Support/Errc.h" 23 #include "llvm/Support/ErrorHandling.h" 24 #include "llvm/Support/ManagedStatic.h" 25 #include "llvm/Support/Path.h" 26 #include "llvm/Support/raw_ostream.h" 27 28 using namespace llvm; 29 using namespace coverage; 30 31 #define DEBUG_TYPE "coverage-mapping" 32 33 Counter CounterExpressionBuilder::get(const CounterExpression &E) { 34 auto It = ExpressionIndices.find(E); 35 if (It != ExpressionIndices.end()) 36 return Counter::getExpression(It->second); 37 unsigned I = Expressions.size(); 38 Expressions.push_back(E); 39 ExpressionIndices[E] = I; 40 return Counter::getExpression(I); 41 } 42 43 void CounterExpressionBuilder::extractTerms( 44 Counter C, int Sign, SmallVectorImpl<std::pair<unsigned, int>> &Terms) { 45 switch (C.getKind()) { 46 case Counter::Zero: 47 break; 48 case Counter::CounterValueReference: 49 Terms.push_back(std::make_pair(C.getCounterID(), Sign)); 50 break; 51 case Counter::Expression: 52 const auto &E = Expressions[C.getExpressionID()]; 53 extractTerms(E.LHS, Sign, Terms); 54 extractTerms(E.RHS, E.Kind == CounterExpression::Subtract ? -Sign : Sign, 55 Terms); 56 break; 57 } 58 } 59 60 Counter CounterExpressionBuilder::simplify(Counter ExpressionTree) { 61 // Gather constant terms. 62 llvm::SmallVector<std::pair<unsigned, int>, 32> Terms; 63 extractTerms(ExpressionTree, +1, Terms); 64 65 // If there are no terms, this is just a zero. The algorithm below assumes at 66 // least one term. 67 if (Terms.size() == 0) 68 return Counter::getZero(); 69 70 // Group the terms by counter ID. 71 std::sort(Terms.begin(), Terms.end(), 72 [](const std::pair<unsigned, int> &LHS, 73 const std::pair<unsigned, int> &RHS) { 74 return LHS.first < RHS.first; 75 }); 76 77 // Combine terms by counter ID to eliminate counters that sum to zero. 78 auto Prev = Terms.begin(); 79 for (auto I = Prev + 1, E = Terms.end(); I != E; ++I) { 80 if (I->first == Prev->first) { 81 Prev->second += I->second; 82 continue; 83 } 84 ++Prev; 85 *Prev = *I; 86 } 87 Terms.erase(++Prev, Terms.end()); 88 89 Counter C; 90 // Create additions. We do this before subtractions to avoid constructs like 91 // ((0 - X) + Y), as opposed to (Y - X). 92 for (auto Term : Terms) { 93 if (Term.second <= 0) 94 continue; 95 for (int I = 0; I < Term.second; ++I) 96 if (C.isZero()) 97 C = Counter::getCounter(Term.first); 98 else 99 C = get(CounterExpression(CounterExpression::Add, C, 100 Counter::getCounter(Term.first))); 101 } 102 103 // Create subtractions. 104 for (auto Term : Terms) { 105 if (Term.second >= 0) 106 continue; 107 for (int I = 0; I < -Term.second; ++I) 108 C = get(CounterExpression(CounterExpression::Subtract, C, 109 Counter::getCounter(Term.first))); 110 } 111 return C; 112 } 113 114 Counter CounterExpressionBuilder::add(Counter LHS, Counter RHS) { 115 return simplify(get(CounterExpression(CounterExpression::Add, LHS, RHS))); 116 } 117 118 Counter CounterExpressionBuilder::subtract(Counter LHS, Counter RHS) { 119 return simplify( 120 get(CounterExpression(CounterExpression::Subtract, LHS, RHS))); 121 } 122 123 void CounterMappingContext::dump(const Counter &C, 124 llvm::raw_ostream &OS) const { 125 switch (C.getKind()) { 126 case Counter::Zero: 127 OS << '0'; 128 return; 129 case Counter::CounterValueReference: 130 OS << '#' << C.getCounterID(); 131 break; 132 case Counter::Expression: { 133 if (C.getExpressionID() >= Expressions.size()) 134 return; 135 const auto &E = Expressions[C.getExpressionID()]; 136 OS << '('; 137 dump(E.LHS, OS); 138 OS << (E.Kind == CounterExpression::Subtract ? " - " : " + "); 139 dump(E.RHS, OS); 140 OS << ')'; 141 break; 142 } 143 } 144 if (CounterValues.empty()) 145 return; 146 Expected<int64_t> Value = evaluate(C); 147 if (auto E = Value.takeError()) { 148 llvm::consumeError(std::move(E)); 149 return; 150 } 151 OS << '[' << *Value << ']'; 152 } 153 154 Expected<int64_t> CounterMappingContext::evaluate(const Counter &C) const { 155 switch (C.getKind()) { 156 case Counter::Zero: 157 return 0; 158 case Counter::CounterValueReference: 159 if (C.getCounterID() >= CounterValues.size()) 160 return errorCodeToError(errc::argument_out_of_domain); 161 return CounterValues[C.getCounterID()]; 162 case Counter::Expression: { 163 if (C.getExpressionID() >= Expressions.size()) 164 return errorCodeToError(errc::argument_out_of_domain); 165 const auto &E = Expressions[C.getExpressionID()]; 166 Expected<int64_t> LHS = evaluate(E.LHS); 167 if (!LHS) 168 return LHS; 169 Expected<int64_t> RHS = evaluate(E.RHS); 170 if (!RHS) 171 return RHS; 172 return E.Kind == CounterExpression::Subtract ? *LHS - *RHS : *LHS + *RHS; 173 } 174 } 175 llvm_unreachable("Unhandled CounterKind"); 176 } 177 178 void FunctionRecordIterator::skipOtherFiles() { 179 while (Current != Records.end() && !Filename.empty() && 180 Filename != Current->Filenames[0]) 181 ++Current; 182 if (Current == Records.end()) 183 *this = FunctionRecordIterator(); 184 } 185 186 Error CoverageMapping::loadFunctionRecord( 187 const CoverageMappingRecord &Record, 188 IndexedInstrProfReader &ProfileReader) { 189 StringRef OrigFuncName = Record.FunctionName; 190 if (Record.Filenames.empty()) 191 OrigFuncName = getFuncNameWithoutPrefix(OrigFuncName); 192 else 193 OrigFuncName = getFuncNameWithoutPrefix(OrigFuncName, Record.Filenames[0]); 194 195 // Don't load records for functions we've already seen. 196 if (!FunctionNames.insert(OrigFuncName).second) 197 return Error::success(); 198 199 CounterMappingContext Ctx(Record.Expressions); 200 201 std::vector<uint64_t> Counts; 202 if (Error E = ProfileReader.getFunctionCounts(Record.FunctionName, 203 Record.FunctionHash, Counts)) { 204 instrprof_error IPE = InstrProfError::take(std::move(E)); 205 if (IPE == instrprof_error::hash_mismatch) { 206 MismatchedFunctionCount++; 207 return Error::success(); 208 } else if (IPE != instrprof_error::unknown_function) 209 return make_error<InstrProfError>(IPE); 210 Counts.assign(Record.MappingRegions.size(), 0); 211 } 212 Ctx.setCounts(Counts); 213 214 assert(!Record.MappingRegions.empty() && "Function has no regions"); 215 216 FunctionRecord Function(OrigFuncName, Record.Filenames); 217 for (const auto &Region : Record.MappingRegions) { 218 Expected<int64_t> ExecutionCount = Ctx.evaluate(Region.Count); 219 if (auto E = ExecutionCount.takeError()) { 220 llvm::consumeError(std::move(E)); 221 return Error::success(); 222 } 223 Function.pushRegion(Region, *ExecutionCount); 224 } 225 if (Function.CountedRegions.size() != Record.MappingRegions.size()) { 226 MismatchedFunctionCount++; 227 return Error::success(); 228 } 229 230 Functions.push_back(std::move(Function)); 231 return Error::success(); 232 } 233 234 Expected<std::unique_ptr<CoverageMapping>> 235 CoverageMapping::load(CoverageMappingReader &CoverageReader, 236 IndexedInstrProfReader &ProfileReader) { 237 auto Coverage = std::unique_ptr<CoverageMapping>(new CoverageMapping()); 238 239 for (const auto &Record : CoverageReader) 240 if (Error E = Coverage->loadFunctionRecord(Record, ProfileReader)) 241 return std::move(E); 242 243 return std::move(Coverage); 244 } 245 246 Expected<std::unique_ptr<CoverageMapping>> CoverageMapping::load( 247 ArrayRef<std::unique_ptr<CoverageMappingReader>> CoverageReaders, 248 IndexedInstrProfReader &ProfileReader) { 249 auto Coverage = std::unique_ptr<CoverageMapping>(new CoverageMapping()); 250 251 for (const auto &CoverageReader : CoverageReaders) 252 for (const auto &Record : *CoverageReader) 253 if (Error E = Coverage->loadFunctionRecord(Record, ProfileReader)) 254 return std::move(E); 255 256 return std::move(Coverage); 257 } 258 259 Expected<std::unique_ptr<CoverageMapping>> 260 CoverageMapping::load(ArrayRef<StringRef> ObjectFilenames, 261 StringRef ProfileFilename, StringRef Arch) { 262 auto ProfileReaderOrErr = IndexedInstrProfReader::create(ProfileFilename); 263 if (Error E = ProfileReaderOrErr.takeError()) 264 return std::move(E); 265 auto ProfileReader = std::move(ProfileReaderOrErr.get()); 266 267 SmallVector<std::unique_ptr<CoverageMappingReader>, 4> Readers; 268 SmallVector<std::unique_ptr<MemoryBuffer>, 4> Buffers; 269 for (StringRef ObjectFilename : ObjectFilenames) { 270 auto CovMappingBufOrErr = MemoryBuffer::getFileOrSTDIN(ObjectFilename); 271 if (std::error_code EC = CovMappingBufOrErr.getError()) 272 return errorCodeToError(EC); 273 auto CoverageReaderOrErr = 274 BinaryCoverageReader::create(CovMappingBufOrErr.get(), Arch); 275 if (Error E = CoverageReaderOrErr.takeError()) 276 return std::move(E); 277 Readers.push_back(std::move(CoverageReaderOrErr.get())); 278 Buffers.push_back(std::move(CovMappingBufOrErr.get())); 279 } 280 return load(Readers, *ProfileReader); 281 } 282 283 namespace { 284 /// \brief Distributes functions into instantiation sets. 285 /// 286 /// An instantiation set is a collection of functions that have the same source 287 /// code, ie, template functions specializations. 288 class FunctionInstantiationSetCollector { 289 typedef DenseMap<std::pair<unsigned, unsigned>, 290 std::vector<const FunctionRecord *>> MapT; 291 MapT InstantiatedFunctions; 292 293 public: 294 void insert(const FunctionRecord &Function, unsigned FileID) { 295 auto I = Function.CountedRegions.begin(), E = Function.CountedRegions.end(); 296 while (I != E && I->FileID != FileID) 297 ++I; 298 assert(I != E && "function does not cover the given file"); 299 auto &Functions = InstantiatedFunctions[I->startLoc()]; 300 Functions.push_back(&Function); 301 } 302 303 MapT::iterator begin() { return InstantiatedFunctions.begin(); } 304 305 MapT::iterator end() { return InstantiatedFunctions.end(); } 306 }; 307 308 class SegmentBuilder { 309 std::vector<CoverageSegment> &Segments; 310 SmallVector<const CountedRegion *, 8> ActiveRegions; 311 312 SegmentBuilder(std::vector<CoverageSegment> &Segments) : Segments(Segments) {} 313 314 /// Start a segment with no count specified. 315 void startSegment(unsigned Line, unsigned Col) { 316 DEBUG(dbgs() << "Top level segment at " << Line << ":" << Col << "\n"); 317 Segments.emplace_back(Line, Col, /*IsRegionEntry=*/false); 318 } 319 320 /// Start a segment with the given Region's count. 321 void startSegment(unsigned Line, unsigned Col, bool IsRegionEntry, 322 const CountedRegion &Region) { 323 // Avoid creating empty regions. 324 if (!Segments.empty() && Segments.back().Line == Line && 325 Segments.back().Col == Col) 326 Segments.pop_back(); 327 DEBUG(dbgs() << "Segment at " << Line << ":" << Col); 328 // Set this region's count. 329 if (Region.Kind != coverage::CounterMappingRegion::SkippedRegion) { 330 DEBUG(dbgs() << " with count " << Region.ExecutionCount); 331 Segments.emplace_back(Line, Col, Region.ExecutionCount, IsRegionEntry); 332 } else 333 Segments.emplace_back(Line, Col, IsRegionEntry); 334 DEBUG(dbgs() << "\n"); 335 } 336 337 /// Start a segment for the given region. 338 void startSegment(const CountedRegion &Region) { 339 startSegment(Region.LineStart, Region.ColumnStart, true, Region); 340 } 341 342 /// Pop the top region off of the active stack, starting a new segment with 343 /// the containing Region's count. 344 void popRegion() { 345 const CountedRegion *Active = ActiveRegions.back(); 346 unsigned Line = Active->LineEnd, Col = Active->ColumnEnd; 347 ActiveRegions.pop_back(); 348 if (ActiveRegions.empty()) 349 startSegment(Line, Col); 350 else 351 startSegment(Line, Col, false, *ActiveRegions.back()); 352 } 353 354 void buildSegmentsImpl(ArrayRef<CountedRegion> Regions) { 355 for (const auto &Region : Regions) { 356 // Pop any regions that end before this one starts. 357 while (!ActiveRegions.empty() && 358 ActiveRegions.back()->endLoc() <= Region.startLoc()) 359 popRegion(); 360 // Add this region to the stack. 361 ActiveRegions.push_back(&Region); 362 startSegment(Region); 363 } 364 // Pop any regions that are left in the stack. 365 while (!ActiveRegions.empty()) 366 popRegion(); 367 } 368 369 /// Sort a nested sequence of regions from a single file. 370 static void sortNestedRegions(MutableArrayRef<CountedRegion> Regions) { 371 std::sort(Regions.begin(), Regions.end(), [](const CountedRegion &LHS, 372 const CountedRegion &RHS) { 373 if (LHS.startLoc() != RHS.startLoc()) 374 return LHS.startLoc() < RHS.startLoc(); 375 if (LHS.endLoc() != RHS.endLoc()) 376 // When LHS completely contains RHS, we sort LHS first. 377 return RHS.endLoc() < LHS.endLoc(); 378 // If LHS and RHS cover the same area, we need to sort them according 379 // to their kinds so that the most suitable region will become "active" 380 // in combineRegions(). Because we accumulate counter values only from 381 // regions of the same kind as the first region of the area, prefer 382 // CodeRegion to ExpansionRegion and ExpansionRegion to SkippedRegion. 383 static_assert(coverage::CounterMappingRegion::CodeRegion < 384 coverage::CounterMappingRegion::ExpansionRegion && 385 coverage::CounterMappingRegion::ExpansionRegion < 386 coverage::CounterMappingRegion::SkippedRegion, 387 "Unexpected order of region kind values"); 388 return LHS.Kind < RHS.Kind; 389 }); 390 } 391 392 /// Combine counts of regions which cover the same area. 393 static ArrayRef<CountedRegion> 394 combineRegions(MutableArrayRef<CountedRegion> Regions) { 395 if (Regions.empty()) 396 return Regions; 397 auto Active = Regions.begin(); 398 auto End = Regions.end(); 399 for (auto I = Regions.begin() + 1; I != End; ++I) { 400 if (Active->startLoc() != I->startLoc() || 401 Active->endLoc() != I->endLoc()) { 402 // Shift to the next region. 403 ++Active; 404 if (Active != I) 405 *Active = *I; 406 continue; 407 } 408 // Merge duplicate region. 409 // If CodeRegions and ExpansionRegions cover the same area, it's probably 410 // a macro which is fully expanded to another macro. In that case, we need 411 // to accumulate counts only from CodeRegions, or else the area will be 412 // counted twice. 413 // On the other hand, a macro may have a nested macro in its body. If the 414 // outer macro is used several times, the ExpansionRegion for the nested 415 // macro will also be added several times. These ExpansionRegions cover 416 // the same source locations and have to be combined to reach the correct 417 // value for that area. 418 // We add counts of the regions of the same kind as the active region 419 // to handle the both situations. 420 if (I->Kind == Active->Kind) 421 Active->ExecutionCount += I->ExecutionCount; 422 } 423 return Regions.drop_back(std::distance(++Active, End)); 424 } 425 426 public: 427 /// Build a list of CoverageSegments from a list of Regions. 428 static std::vector<CoverageSegment> 429 buildSegments(MutableArrayRef<CountedRegion> Regions) { 430 std::vector<CoverageSegment> Segments; 431 SegmentBuilder Builder(Segments); 432 433 sortNestedRegions(Regions); 434 ArrayRef<CountedRegion> CombinedRegions = combineRegions(Regions); 435 436 Builder.buildSegmentsImpl(CombinedRegions); 437 return Segments; 438 } 439 }; 440 } 441 442 std::vector<StringRef> CoverageMapping::getUniqueSourceFiles() const { 443 std::vector<StringRef> Filenames; 444 for (const auto &Function : getCoveredFunctions()) 445 Filenames.insert(Filenames.end(), Function.Filenames.begin(), 446 Function.Filenames.end()); 447 std::sort(Filenames.begin(), Filenames.end()); 448 auto Last = std::unique(Filenames.begin(), Filenames.end()); 449 Filenames.erase(Last, Filenames.end()); 450 return Filenames; 451 } 452 453 static SmallBitVector gatherFileIDs(StringRef SourceFile, 454 const FunctionRecord &Function) { 455 SmallBitVector FilenameEquivalence(Function.Filenames.size(), false); 456 for (unsigned I = 0, E = Function.Filenames.size(); I < E; ++I) 457 if (SourceFile == Function.Filenames[I]) 458 FilenameEquivalence[I] = true; 459 return FilenameEquivalence; 460 } 461 462 /// Return the ID of the file where the definition of the function is located. 463 static Optional<unsigned> findMainViewFileID(const FunctionRecord &Function) { 464 SmallBitVector IsNotExpandedFile(Function.Filenames.size(), true); 465 for (const auto &CR : Function.CountedRegions) 466 if (CR.Kind == CounterMappingRegion::ExpansionRegion) 467 IsNotExpandedFile[CR.ExpandedFileID] = false; 468 int I = IsNotExpandedFile.find_first(); 469 if (I == -1) 470 return None; 471 return I; 472 } 473 474 /// Check if SourceFile is the file that contains the definition of 475 /// the Function. Return the ID of the file in that case or None otherwise. 476 static Optional<unsigned> findMainViewFileID(StringRef SourceFile, 477 const FunctionRecord &Function) { 478 Optional<unsigned> I = findMainViewFileID(Function); 479 if (I && SourceFile == Function.Filenames[*I]) 480 return I; 481 return None; 482 } 483 484 static bool isExpansion(const CountedRegion &R, unsigned FileID) { 485 return R.Kind == CounterMappingRegion::ExpansionRegion && R.FileID == FileID; 486 } 487 488 CoverageData CoverageMapping::getCoverageForFile(StringRef Filename) const { 489 CoverageData FileCoverage(Filename); 490 std::vector<coverage::CountedRegion> Regions; 491 492 for (const auto &Function : Functions) { 493 auto MainFileID = findMainViewFileID(Filename, Function); 494 auto FileIDs = gatherFileIDs(Filename, Function); 495 for (const auto &CR : Function.CountedRegions) 496 if (FileIDs.test(CR.FileID)) { 497 Regions.push_back(CR); 498 if (MainFileID && isExpansion(CR, *MainFileID)) 499 FileCoverage.Expansions.emplace_back(CR, Function); 500 } 501 } 502 503 DEBUG(dbgs() << "Emitting segments for file: " << Filename << "\n"); 504 FileCoverage.Segments = SegmentBuilder::buildSegments(Regions); 505 506 return FileCoverage; 507 } 508 509 std::vector<const FunctionRecord *> 510 CoverageMapping::getInstantiations(StringRef Filename) const { 511 FunctionInstantiationSetCollector InstantiationSetCollector; 512 for (const auto &Function : Functions) { 513 auto MainFileID = findMainViewFileID(Filename, Function); 514 if (!MainFileID) 515 continue; 516 InstantiationSetCollector.insert(Function, *MainFileID); 517 } 518 519 std::vector<const FunctionRecord *> Result; 520 for (const auto &InstantiationSet : InstantiationSetCollector) { 521 if (InstantiationSet.second.size() < 2) 522 continue; 523 Result.insert(Result.end(), InstantiationSet.second.begin(), 524 InstantiationSet.second.end()); 525 } 526 return Result; 527 } 528 529 CoverageData 530 CoverageMapping::getCoverageForFunction(const FunctionRecord &Function) const { 531 auto MainFileID = findMainViewFileID(Function); 532 if (!MainFileID) 533 return CoverageData(); 534 535 CoverageData FunctionCoverage(Function.Filenames[*MainFileID]); 536 std::vector<coverage::CountedRegion> Regions; 537 for (const auto &CR : Function.CountedRegions) 538 if (CR.FileID == *MainFileID) { 539 Regions.push_back(CR); 540 if (isExpansion(CR, *MainFileID)) 541 FunctionCoverage.Expansions.emplace_back(CR, Function); 542 } 543 544 DEBUG(dbgs() << "Emitting segments for function: " << Function.Name << "\n"); 545 FunctionCoverage.Segments = SegmentBuilder::buildSegments(Regions); 546 547 return FunctionCoverage; 548 } 549 550 CoverageData CoverageMapping::getCoverageForExpansion( 551 const ExpansionRecord &Expansion) const { 552 CoverageData ExpansionCoverage( 553 Expansion.Function.Filenames[Expansion.FileID]); 554 std::vector<coverage::CountedRegion> Regions; 555 for (const auto &CR : Expansion.Function.CountedRegions) 556 if (CR.FileID == Expansion.FileID) { 557 Regions.push_back(CR); 558 if (isExpansion(CR, Expansion.FileID)) 559 ExpansionCoverage.Expansions.emplace_back(CR, Expansion.Function); 560 } 561 562 DEBUG(dbgs() << "Emitting segments for expansion of file " << Expansion.FileID 563 << "\n"); 564 ExpansionCoverage.Segments = SegmentBuilder::buildSegments(Regions); 565 566 return ExpansionCoverage; 567 } 568 569 namespace { 570 std::string getCoverageMapErrString(coveragemap_error Err) { 571 switch (Err) { 572 case coveragemap_error::success: 573 return "Success"; 574 case coveragemap_error::eof: 575 return "End of File"; 576 case coveragemap_error::no_data_found: 577 return "No coverage data found"; 578 case coveragemap_error::unsupported_version: 579 return "Unsupported coverage format version"; 580 case coveragemap_error::truncated: 581 return "Truncated coverage data"; 582 case coveragemap_error::malformed: 583 return "Malformed coverage data"; 584 } 585 llvm_unreachable("A value of coveragemap_error has no message."); 586 } 587 588 // FIXME: This class is only here to support the transition to llvm::Error. It 589 // will be removed once this transition is complete. Clients should prefer to 590 // deal with the Error value directly, rather than converting to error_code. 591 class CoverageMappingErrorCategoryType : public std::error_category { 592 const char *name() const noexcept override { return "llvm.coveragemap"; } 593 std::string message(int IE) const override { 594 return getCoverageMapErrString(static_cast<coveragemap_error>(IE)); 595 } 596 }; 597 } // end anonymous namespace 598 599 std::string CoverageMapError::message() const { 600 return getCoverageMapErrString(Err); 601 } 602 603 static ManagedStatic<CoverageMappingErrorCategoryType> ErrorCategory; 604 605 const std::error_category &llvm::coverage::coveragemap_category() { 606 return *ErrorCategory; 607 } 608 609 char CoverageMapError::ID = 0; 610