CoverageMapping.cpp 34 KB

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