CoverageMapping.cpp 36 KB

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