LLVM  16.0.0git
CoverageMapping.cpp
Go to the documentation of this file.
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 
15 #include "llvm/ADT/ArrayRef.h"
16 #include "llvm/ADT/DenseMap.h"
17 #include "llvm/ADT/None.h"
18 #include "llvm/ADT/Optional.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/ADT/StringRef.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/Support/Errc.h"
26 #include "llvm/Support/Error.h"
30 #include <algorithm>
31 #include <cassert>
32 #include <cstdint>
33 #include <iterator>
34 #include <map>
35 #include <memory>
36 #include <optional>
37 #include <string>
38 #include <system_error>
39 #include <utility>
40 #include <vector>
41 
42 using namespace llvm;
43 using namespace coverage;
44 
45 #define DEBUG_TYPE "coverage-mapping"
46 
47 Counter CounterExpressionBuilder::get(const CounterExpression &E) {
48  auto It = ExpressionIndices.find(E);
49  if (It != ExpressionIndices.end())
50  return Counter::getExpression(It->second);
51  unsigned I = Expressions.size();
52  Expressions.push_back(E);
53  ExpressionIndices[E] = I;
54  return Counter::getExpression(I);
55 }
56 
57 void CounterExpressionBuilder::extractTerms(Counter C, int Factor,
58  SmallVectorImpl<Term> &Terms) {
59  switch (C.getKind()) {
60  case Counter::Zero:
61  break;
63  Terms.emplace_back(C.getCounterID(), Factor);
64  break;
66  const auto &E = Expressions[C.getExpressionID()];
67  extractTerms(E.LHS, Factor, Terms);
68  extractTerms(
69  E.RHS, E.Kind == CounterExpression::Subtract ? -Factor : Factor, Terms);
70  break;
71  }
72 }
73 
74 Counter CounterExpressionBuilder::simplify(Counter ExpressionTree) {
75  // Gather constant terms.
77  extractTerms(ExpressionTree, +1, Terms);
78 
79  // If there are no terms, this is just a zero. The algorithm below assumes at
80  // least one term.
81  if (Terms.size() == 0)
82  return Counter::getZero();
83 
84  // Group the terms by counter ID.
85  llvm::sort(Terms, [](const Term &LHS, const Term &RHS) {
86  return LHS.CounterID < RHS.CounterID;
87  });
88 
89  // Combine terms by counter ID to eliminate counters that sum to zero.
90  auto Prev = Terms.begin();
91  for (auto I = Prev + 1, E = Terms.end(); I != E; ++I) {
92  if (I->CounterID == Prev->CounterID) {
93  Prev->Factor += I->Factor;
94  continue;
95  }
96  ++Prev;
97  *Prev = *I;
98  }
99  Terms.erase(++Prev, Terms.end());
100 
101  Counter C;
102  // Create additions. We do this before subtractions to avoid constructs like
103  // ((0 - X) + Y), as opposed to (Y - X).
104  for (auto T : Terms) {
105  if (T.Factor <= 0)
106  continue;
107  for (int I = 0; I < T.Factor; ++I)
108  if (C.isZero())
109  C = Counter::getCounter(T.CounterID);
110  else
112  Counter::getCounter(T.CounterID)));
113  }
114 
115  // Create subtractions.
116  for (auto T : Terms) {
117  if (T.Factor >= 0)
118  continue;
119  for (int I = 0; I < -T.Factor; ++I)
121  Counter::getCounter(T.CounterID)));
122  }
123  return C;
124 }
125 
127  auto Cnt = get(CounterExpression(CounterExpression::Add, LHS, RHS));
128  return Simplify ? simplify(Cnt) : Cnt;
129 }
130 
132  bool Simplify) {
134  return Simplify ? simplify(Cnt) : Cnt;
135 }
136 
138  switch (C.getKind()) {
139  case Counter::Zero:
140  OS << '0';
141  return;
143  OS << '#' << C.getCounterID();
144  break;
145  case Counter::Expression: {
146  if (C.getExpressionID() >= Expressions.size())
147  return;
148  const auto &E = Expressions[C.getExpressionID()];
149  OS << '(';
150  dump(E.LHS, OS);
151  OS << (E.Kind == CounterExpression::Subtract ? " - " : " + ");
152  dump(E.RHS, OS);
153  OS << ')';
154  break;
155  }
156  }
157  if (CounterValues.empty())
158  return;
160  if (auto E = Value.takeError()) {
162  return;
163  }
164  OS << '[' << *Value << ']';
165 }
166 
168  switch (C.getKind()) {
169  case Counter::Zero:
170  return 0;
172  if (C.getCounterID() >= CounterValues.size())
174  return CounterValues[C.getCounterID()];
175  case Counter::Expression: {
176  if (C.getExpressionID() >= Expressions.size())
178  const auto &E = Expressions[C.getExpressionID()];
180  if (!LHS)
181  return LHS;
183  if (!RHS)
184  return RHS;
185  return E.Kind == CounterExpression::Subtract ? *LHS - *RHS : *LHS + *RHS;
186  }
187  }
188  llvm_unreachable("Unhandled CounterKind");
189 }
190 
192  switch (C.getKind()) {
193  case Counter::Zero:
194  return 0;
196  return C.getCounterID();
197  case Counter::Expression: {
198  if (C.getExpressionID() >= Expressions.size())
199  return 0;
200  const auto &E = Expressions[C.getExpressionID()];
201  return std::max(getMaxCounterID(E.LHS), getMaxCounterID(E.RHS));
202  }
203  }
204  llvm_unreachable("Unhandled CounterKind");
205 }
206 
207 void FunctionRecordIterator::skipOtherFiles() {
208  while (Current != Records.end() && !Filename.empty() &&
209  Filename != Current->Filenames[0])
210  ++Current;
211  if (Current == Records.end())
212  *this = FunctionRecordIterator();
213 }
214 
215 ArrayRef<unsigned> CoverageMapping::getImpreciseRecordIndicesForFilename(
216  StringRef Filename) const {
217  size_t FilenameHash = hash_value(Filename);
218  auto RecordIt = FilenameHash2RecordIndices.find(FilenameHash);
219  if (RecordIt == FilenameHash2RecordIndices.end())
220  return {};
221  return RecordIt->second;
222 }
223 
224 static unsigned getMaxCounterID(const CounterMappingContext &Ctx,
225  const CoverageMappingRecord &Record) {
226  unsigned MaxCounterID = 0;
227  for (const auto &Region : Record.MappingRegions) {
228  MaxCounterID = std::max(MaxCounterID, Ctx.getMaxCounterID(Region.Count));
229  }
230  return MaxCounterID;
231 }
232 
233 Error CoverageMapping::loadFunctionRecord(
235  IndexedInstrProfReader &ProfileReader) {
236  StringRef OrigFuncName = Record.FunctionName;
237  if (OrigFuncName.empty())
238  return make_error<CoverageMapError>(coveragemap_error::malformed);
239 
240  if (Record.Filenames.empty())
241  OrigFuncName = getFuncNameWithoutPrefix(OrigFuncName);
242  else
243  OrigFuncName = getFuncNameWithoutPrefix(OrigFuncName, Record.Filenames[0]);
244 
245  CounterMappingContext Ctx(Record.Expressions);
246 
247  std::vector<uint64_t> Counts;
248  if (Error E = ProfileReader.getFunctionCounts(Record.FunctionName,
249  Record.FunctionHash, Counts)) {
251  if (IPE == instrprof_error::hash_mismatch) {
252  FuncHashMismatches.emplace_back(std::string(Record.FunctionName),
253  Record.FunctionHash);
254  return Error::success();
255  } else if (IPE != instrprof_error::unknown_function)
256  return make_error<InstrProfError>(IPE);
257  Counts.assign(getMaxCounterID(Ctx, Record) + 1, 0);
258  }
259  Ctx.setCounts(Counts);
260 
261  assert(!Record.MappingRegions.empty() && "Function has no regions");
262 
263  // This coverage record is a zero region for a function that's unused in
264  // some TU, but used in a different TU. Ignore it. The coverage maps from the
265  // the other TU will either be loaded (providing full region counts) or they
266  // won't (in which case we don't unintuitively report functions as uncovered
267  // when they have non-zero counts in the profile).
268  if (Record.MappingRegions.size() == 1 &&
269  Record.MappingRegions[0].Count.isZero() && Counts[0] > 0)
270  return Error::success();
271 
272  FunctionRecord Function(OrigFuncName, Record.Filenames);
273  for (const auto &Region : Record.MappingRegions) {
274  Expected<int64_t> ExecutionCount = Ctx.evaluate(Region.Count);
275  if (auto E = ExecutionCount.takeError()) {
277  return Error::success();
278  }
279  Expected<int64_t> AltExecutionCount = Ctx.evaluate(Region.FalseCount);
280  if (auto E = AltExecutionCount.takeError()) {
282  return Error::success();
283  }
284  Function.pushRegion(Region, *ExecutionCount, *AltExecutionCount);
285  }
286 
287  // Don't create records for (filenames, function) pairs we've already seen.
288  auto FilenamesHash = hash_combine_range(Record.Filenames.begin(),
289  Record.Filenames.end());
290  if (!RecordProvenance[FilenamesHash].insert(hash_value(OrigFuncName)).second)
291  return Error::success();
292 
293  Functions.push_back(std::move(Function));
294 
295  // Performance optimization: keep track of the indices of the function records
296  // which correspond to each filename. This can be used to substantially speed
297  // up queries for coverage info in a file.
298  unsigned RecordIndex = Functions.size() - 1;
299  for (StringRef Filename : Record.Filenames) {
300  auto &RecordIndices = FilenameHash2RecordIndices[hash_value(Filename)];
301  // Note that there may be duplicates in the filename set for a function
302  // record, because of e.g. macro expansions in the function in which both
303  // the macro and the function are defined in the same file.
304  if (RecordIndices.empty() || RecordIndices.back() != RecordIndex)
305  RecordIndices.push_back(RecordIndex);
306  }
307 
308  return Error::success();
309 }
310 
311 // This function is for memory optimization by shortening the lifetimes
312 // of CoverageMappingReader instances.
313 Error CoverageMapping::loadFromReaders(
314  ArrayRef<std::unique_ptr<CoverageMappingReader>> CoverageReaders,
315  IndexedInstrProfReader &ProfileReader, CoverageMapping &Coverage) {
316  for (const auto &CoverageReader : CoverageReaders) {
317  for (auto RecordOrErr : *CoverageReader) {
318  if (Error E = RecordOrErr.takeError())
319  return E;
320  const auto &Record = *RecordOrErr;
321  if (Error E = Coverage.loadFunctionRecord(Record, ProfileReader))
322  return E;
323  }
324  }
325  return Error::success();
326 }
327 
329  ArrayRef<std::unique_ptr<CoverageMappingReader>> CoverageReaders,
330  IndexedInstrProfReader &ProfileReader) {
331  auto Coverage = std::unique_ptr<CoverageMapping>(new CoverageMapping());
332  if (Error E = loadFromReaders(CoverageReaders, ProfileReader, *Coverage))
333  return std::move(E);
334  return std::move(Coverage);
335 }
336 
337 // If E is a no_data_found error, returns success. Otherwise returns E.
339  return handleErrors(
340  std::move(E), [](const CoverageMapError &CME) {
342  return static_cast<Error>(Error::success());
343  return make_error<CoverageMapError>(CME.get());
344  });
345 }
346 
349  StringRef ProfileFilename, ArrayRef<StringRef> Arches,
350  StringRef CompilationDir) {
351  auto ProfileReaderOrErr = IndexedInstrProfReader::create(ProfileFilename);
352  if (Error E = ProfileReaderOrErr.takeError())
353  return createFileError(ProfileFilename, std::move(E));
354  auto ProfileReader = std::move(ProfileReaderOrErr.get());
355  auto Coverage = std::unique_ptr<CoverageMapping>(new CoverageMapping());
356  bool DataFound = false;
357 
358  for (const auto &File : llvm::enumerate(ObjectFilenames)) {
359  auto CovMappingBufOrErr = MemoryBuffer::getFileOrSTDIN(
360  File.value(), /*IsText=*/false, /*RequiresNullTerminator=*/false);
361  if (std::error_code EC = CovMappingBufOrErr.getError())
362  return createFileError(File.value(), errorCodeToError(EC));
363  StringRef Arch = Arches.empty() ? StringRef() : Arches[File.index()];
364  MemoryBufferRef CovMappingBufRef =
365  CovMappingBufOrErr.get()->getMemBufferRef();
367  auto CoverageReadersOrErr = BinaryCoverageReader::create(
368  CovMappingBufRef, Arch, Buffers, CompilationDir);
369  if (Error E = CoverageReadersOrErr.takeError()) {
371  if (E)
372  return createFileError(File.value(), std::move(E));
373  // E == success (originally a no_data_found error).
374  continue;
375  }
376 
378  for (auto &Reader : CoverageReadersOrErr.get())
379  Readers.push_back(std::move(Reader));
380  DataFound |= !Readers.empty();
381  if (Error E = loadFromReaders(Readers, *ProfileReader, *Coverage))
382  return createFileError(File.value(), std::move(E));
383  }
384  // If no readers were created, either no objects were provided or none of them
385  // had coverage data. Return an error in the latter case.
386  if (!DataFound && !ObjectFilenames.empty())
387  return createFileError(
388  join(ObjectFilenames.begin(), ObjectFilenames.end(), ", "),
389  make_error<CoverageMapError>(coveragemap_error::no_data_found));
390  return std::move(Coverage);
391 }
392 
393 namespace {
394 
395 /// Distributes functions into instantiation sets.
396 ///
397 /// An instantiation set is a collection of functions that have the same source
398 /// code, ie, template functions specializations.
399 class FunctionInstantiationSetCollector {
400  using MapT = std::map<LineColPair, std::vector<const FunctionRecord *>>;
401  MapT InstantiatedFunctions;
402 
403 public:
404  void insert(const FunctionRecord &Function, unsigned FileID) {
405  auto I = Function.CountedRegions.begin(), E = Function.CountedRegions.end();
406  while (I != E && I->FileID != FileID)
407  ++I;
408  assert(I != E && "function does not cover the given file");
409  auto &Functions = InstantiatedFunctions[I->startLoc()];
410  Functions.push_back(&Function);
411  }
412 
413  MapT::iterator begin() { return InstantiatedFunctions.begin(); }
414  MapT::iterator end() { return InstantiatedFunctions.end(); }
415 };
416 
417 class SegmentBuilder {
418  std::vector<CoverageSegment> &Segments;
420 
421  SegmentBuilder(std::vector<CoverageSegment> &Segments) : Segments(Segments) {}
422 
423  /// Emit a segment with the count from \p Region starting at \p StartLoc.
424  //
425  /// \p IsRegionEntry: The segment is at the start of a new non-gap region.
426  /// \p EmitSkippedRegion: The segment must be emitted as a skipped region.
427  void startSegment(const CountedRegion &Region, LineColPair StartLoc,
428  bool IsRegionEntry, bool EmitSkippedRegion = false) {
429  bool HasCount = !EmitSkippedRegion &&
431 
432  // If the new segment wouldn't affect coverage rendering, skip it.
433  if (!Segments.empty() && !IsRegionEntry && !EmitSkippedRegion) {
434  const auto &Last = Segments.back();
435  if (Last.HasCount == HasCount && Last.Count == Region.ExecutionCount &&
436  !Last.IsRegionEntry)
437  return;
438  }
439 
440  if (HasCount)
441  Segments.emplace_back(StartLoc.first, StartLoc.second,
442  Region.ExecutionCount, IsRegionEntry,
444  else
445  Segments.emplace_back(StartLoc.first, StartLoc.second, IsRegionEntry);
446 
447  LLVM_DEBUG({
448  const auto &Last = Segments.back();
449  dbgs() << "Segment at " << Last.Line << ":" << Last.Col
450  << " (count = " << Last.Count << ")"
451  << (Last.IsRegionEntry ? ", RegionEntry" : "")
452  << (!Last.HasCount ? ", Skipped" : "")
453  << (Last.IsGapRegion ? ", Gap" : "") << "\n";
454  });
455  }
456 
457  /// Emit segments for active regions which end before \p Loc.
458  ///
459  /// \p Loc: The start location of the next region. If None, all active
460  /// regions are completed.
461  /// \p FirstCompletedRegion: Index of the first completed region.
462  void completeRegionsUntil(std::optional<LineColPair> Loc,
463  unsigned FirstCompletedRegion) {
464  // Sort the completed regions by end location. This makes it simple to
465  // emit closing segments in sorted order.
466  auto CompletedRegionsIt = ActiveRegions.begin() + FirstCompletedRegion;
467  std::stable_sort(CompletedRegionsIt, ActiveRegions.end(),
468  [](const CountedRegion *L, const CountedRegion *R) {
469  return L->endLoc() < R->endLoc();
470  });
471 
472  // Emit segments for all completed regions.
473  for (unsigned I = FirstCompletedRegion + 1, E = ActiveRegions.size(); I < E;
474  ++I) {
475  const auto *CompletedRegion = ActiveRegions[I];
476  assert((!Loc || CompletedRegion->endLoc() <= *Loc) &&
477  "Completed region ends after start of new region");
478 
479  const auto *PrevCompletedRegion = ActiveRegions[I - 1];
480  auto CompletedSegmentLoc = PrevCompletedRegion->endLoc();
481 
482  // Don't emit any more segments if they start where the new region begins.
483  if (Loc && CompletedSegmentLoc == *Loc)
484  break;
485 
486  // Don't emit a segment if the next completed region ends at the same
487  // location as this one.
488  if (CompletedSegmentLoc == CompletedRegion->endLoc())
489  continue;
490 
491  // Use the count from the last completed region which ends at this loc.
492  for (unsigned J = I + 1; J < E; ++J)
493  if (CompletedRegion->endLoc() == ActiveRegions[J]->endLoc())
494  CompletedRegion = ActiveRegions[J];
495 
496  startSegment(*CompletedRegion, CompletedSegmentLoc, false);
497  }
498 
499  auto Last = ActiveRegions.back();
500  if (FirstCompletedRegion && Last->endLoc() != *Loc) {
501  // If there's a gap after the end of the last completed region and the
502  // start of the new region, use the last active region to fill the gap.
503  startSegment(*ActiveRegions[FirstCompletedRegion - 1], Last->endLoc(),
504  false);
505  } else if (!FirstCompletedRegion && (!Loc || *Loc != Last->endLoc())) {
506  // Emit a skipped segment if there are no more active regions. This
507  // ensures that gaps between functions are marked correctly.
508  startSegment(*Last, Last->endLoc(), false, true);
509  }
510 
511  // Pop the completed regions.
512  ActiveRegions.erase(CompletedRegionsIt, ActiveRegions.end());
513  }
514 
515  void buildSegmentsImpl(ArrayRef<CountedRegion> Regions) {
516  for (const auto &CR : enumerate(Regions)) {
517  auto CurStartLoc = CR.value().startLoc();
518 
519  // Active regions which end before the current region need to be popped.
520  auto CompletedRegions =
521  std::stable_partition(ActiveRegions.begin(), ActiveRegions.end(),
522  [&](const CountedRegion *Region) {
523  return !(Region->endLoc() <= CurStartLoc);
524  });
525  if (CompletedRegions != ActiveRegions.end()) {
526  unsigned FirstCompletedRegion =
527  std::distance(ActiveRegions.begin(), CompletedRegions);
528  completeRegionsUntil(CurStartLoc, FirstCompletedRegion);
529  }
530 
531  bool GapRegion = CR.value().Kind == CounterMappingRegion::GapRegion;
532 
533  // Try to emit a segment for the current region.
534  if (CurStartLoc == CR.value().endLoc()) {
535  // Avoid making zero-length regions active. If it's the last region,
536  // emit a skipped segment. Otherwise use its predecessor's count.
537  const bool Skipped =
538  (CR.index() + 1) == Regions.size() ||
539  CR.value().Kind == CounterMappingRegion::SkippedRegion;
540  startSegment(ActiveRegions.empty() ? CR.value() : *ActiveRegions.back(),
541  CurStartLoc, !GapRegion, Skipped);
542  // If it is skipped segment, create a segment with last pushed
543  // regions's count at CurStartLoc.
544  if (Skipped && !ActiveRegions.empty())
545  startSegment(*ActiveRegions.back(), CurStartLoc, false);
546  continue;
547  }
548  if (CR.index() + 1 == Regions.size() ||
549  CurStartLoc != Regions[CR.index() + 1].startLoc()) {
550  // Emit a segment if the next region doesn't start at the same location
551  // as this one.
552  startSegment(CR.value(), CurStartLoc, !GapRegion);
553  }
554 
555  // This region is active (i.e not completed).
556  ActiveRegions.push_back(&CR.value());
557  }
558 
559  // Complete any remaining active regions.
560  if (!ActiveRegions.empty())
561  completeRegionsUntil(std::nullopt, 0);
562  }
563 
564  /// Sort a nested sequence of regions from a single file.
565  static void sortNestedRegions(MutableArrayRef<CountedRegion> Regions) {
566  llvm::sort(Regions, [](const CountedRegion &LHS, const CountedRegion &RHS) {
567  if (LHS.startLoc() != RHS.startLoc())
568  return LHS.startLoc() < RHS.startLoc();
569  if (LHS.endLoc() != RHS.endLoc())
570  // When LHS completely contains RHS, we sort LHS first.
571  return RHS.endLoc() < LHS.endLoc();
572  // If LHS and RHS cover the same area, we need to sort them according
573  // to their kinds so that the most suitable region will become "active"
574  // in combineRegions(). Because we accumulate counter values only from
575  // regions of the same kind as the first region of the area, prefer
576  // CodeRegion to ExpansionRegion and ExpansionRegion to SkippedRegion.
577  static_assert(CounterMappingRegion::CodeRegion <
581  "Unexpected order of region kind values");
582  return LHS.Kind < RHS.Kind;
583  });
584  }
585 
586  /// Combine counts of regions which cover the same area.
588  combineRegions(MutableArrayRef<CountedRegion> Regions) {
589  if (Regions.empty())
590  return Regions;
591  auto Active = Regions.begin();
592  auto End = Regions.end();
593  for (auto I = Regions.begin() + 1; I != End; ++I) {
594  if (Active->startLoc() != I->startLoc() ||
595  Active->endLoc() != I->endLoc()) {
596  // Shift to the next region.
597  ++Active;
598  if (Active != I)
599  *Active = *I;
600  continue;
601  }
602  // Merge duplicate region.
603  // If CodeRegions and ExpansionRegions cover the same area, it's probably
604  // a macro which is fully expanded to another macro. In that case, we need
605  // to accumulate counts only from CodeRegions, or else the area will be
606  // counted twice.
607  // On the other hand, a macro may have a nested macro in its body. If the
608  // outer macro is used several times, the ExpansionRegion for the nested
609  // macro will also be added several times. These ExpansionRegions cover
610  // the same source locations and have to be combined to reach the correct
611  // value for that area.
612  // We add counts of the regions of the same kind as the active region
613  // to handle the both situations.
614  if (I->Kind == Active->Kind)
615  Active->ExecutionCount += I->ExecutionCount;
616  }
617  return Regions.drop_back(std::distance(++Active, End));
618  }
619 
620 public:
621  /// Build a sorted list of CoverageSegments from a list of Regions.
622  static std::vector<CoverageSegment>
623  buildSegments(MutableArrayRef<CountedRegion> Regions) {
624  std::vector<CoverageSegment> Segments;
625  SegmentBuilder Builder(Segments);
626 
627  sortNestedRegions(Regions);
628  ArrayRef<CountedRegion> CombinedRegions = combineRegions(Regions);
629 
630  LLVM_DEBUG({
631  dbgs() << "Combined regions:\n";
632  for (const auto &CR : CombinedRegions)
633  dbgs() << " " << CR.LineStart << ":" << CR.ColumnStart << " -> "
634  << CR.LineEnd << ":" << CR.ColumnEnd
635  << " (count=" << CR.ExecutionCount << ")\n";
636  });
637 
638  Builder.buildSegmentsImpl(CombinedRegions);
639 
640 #ifndef NDEBUG
641  for (unsigned I = 1, E = Segments.size(); I < E; ++I) {
642  const auto &L = Segments[I - 1];
643  const auto &R = Segments[I];
644  if (!(L.Line < R.Line) && !(L.Line == R.Line && L.Col < R.Col)) {
645  if (L.Line == R.Line && L.Col == R.Col && !L.HasCount)
646  continue;
647  LLVM_DEBUG(dbgs() << " ! Segment " << L.Line << ":" << L.Col
648  << " followed by " << R.Line << ":" << R.Col << "\n");
649  assert(false && "Coverage segments not unique or sorted");
650  }
651  }
652 #endif
653 
654  return Segments;
655  }
656 };
657 
658 } // end anonymous namespace
659 
660 std::vector<StringRef> CoverageMapping::getUniqueSourceFiles() const {
661  std::vector<StringRef> Filenames;
662  for (const auto &Function : getCoveredFunctions())
663  llvm::append_range(Filenames, Function.Filenames);
664  llvm::sort(Filenames);
665  auto Last = std::unique(Filenames.begin(), Filenames.end());
666  Filenames.erase(Last, Filenames.end());
667  return Filenames;
668 }
669 
671  const FunctionRecord &Function) {
672  SmallBitVector FilenameEquivalence(Function.Filenames.size(), false);
673  for (unsigned I = 0, E = Function.Filenames.size(); I < E; ++I)
674  if (SourceFile == Function.Filenames[I])
675  FilenameEquivalence[I] = true;
676  return FilenameEquivalence;
677 }
678 
679 /// Return the ID of the file where the definition of the function is located.
681  SmallBitVector IsNotExpandedFile(Function.Filenames.size(), true);
682  for (const auto &CR : Function.CountedRegions)
684  IsNotExpandedFile[CR.ExpandedFileID] = false;
685  int I = IsNotExpandedFile.find_first();
686  if (I == -1)
687  return std::nullopt;
688  return I;
689 }
690 
691 /// Check if SourceFile is the file that contains the definition of
692 /// the Function. Return the ID of the file in that case or std::nullopt
693 /// otherwise.
695  const FunctionRecord &Function) {
697  if (I && SourceFile == Function.Filenames[*I])
698  return I;
699  return std::nullopt;
700 }
701 
702 static bool isExpansion(const CountedRegion &R, unsigned FileID) {
703  return R.Kind == CounterMappingRegion::ExpansionRegion && R.FileID == FileID;
704 }
705 
707  CoverageData FileCoverage(Filename);
708  std::vector<CountedRegion> Regions;
709 
710  // Look up the function records in the given file. Due to hash collisions on
711  // the filename, we may get back some records that are not in the file.
712  ArrayRef<unsigned> RecordIndices =
713  getImpreciseRecordIndicesForFilename(Filename);
714  for (unsigned RecordIndex : RecordIndices) {
715  const FunctionRecord &Function = Functions[RecordIndex];
716  auto MainFileID = findMainViewFileID(Filename, Function);
717  auto FileIDs = gatherFileIDs(Filename, Function);
718  for (const auto &CR : Function.CountedRegions)
719  if (FileIDs.test(CR.FileID)) {
720  Regions.push_back(CR);
721  if (MainFileID && isExpansion(CR, *MainFileID))
722  FileCoverage.Expansions.emplace_back(CR, Function);
723  }
724  // Capture branch regions specific to the function (excluding expansions).
725  for (const auto &CR : Function.CountedBranchRegions)
726  if (FileIDs.test(CR.FileID) && (CR.FileID == CR.ExpandedFileID))
727  FileCoverage.BranchRegions.push_back(CR);
728  }
729 
730  LLVM_DEBUG(dbgs() << "Emitting segments for file: " << Filename << "\n");
731  FileCoverage.Segments = SegmentBuilder::buildSegments(Regions);
732 
733  return FileCoverage;
734 }
735 
736 std::vector<InstantiationGroup>
738  FunctionInstantiationSetCollector InstantiationSetCollector;
739  // Look up the function records in the given file. Due to hash collisions on
740  // the filename, we may get back some records that are not in the file.
741  ArrayRef<unsigned> RecordIndices =
742  getImpreciseRecordIndicesForFilename(Filename);
743  for (unsigned RecordIndex : RecordIndices) {
744  const FunctionRecord &Function = Functions[RecordIndex];
745  auto MainFileID = findMainViewFileID(Filename, Function);
746  if (!MainFileID)
747  continue;
748  InstantiationSetCollector.insert(Function, *MainFileID);
749  }
750 
751  std::vector<InstantiationGroup> Result;
752  for (auto &InstantiationSet : InstantiationSetCollector) {
753  InstantiationGroup IG{InstantiationSet.first.first,
754  InstantiationSet.first.second,
755  std::move(InstantiationSet.second)};
756  Result.emplace_back(std::move(IG));
757  }
758  return Result;
759 }
760 
763  auto MainFileID = findMainViewFileID(Function);
764  if (!MainFileID)
765  return CoverageData();
766 
767  CoverageData FunctionCoverage(Function.Filenames[*MainFileID]);
768  std::vector<CountedRegion> Regions;
769  for (const auto &CR : Function.CountedRegions)
770  if (CR.FileID == *MainFileID) {
771  Regions.push_back(CR);
772  if (isExpansion(CR, *MainFileID))
773  FunctionCoverage.Expansions.emplace_back(CR, Function);
774  }
775  // Capture branch regions specific to the function (excluding expansions).
776  for (const auto &CR : Function.CountedBranchRegions)
777  if (CR.FileID == *MainFileID)
778  FunctionCoverage.BranchRegions.push_back(CR);
779 
780  LLVM_DEBUG(dbgs() << "Emitting segments for function: " << Function.Name
781  << "\n");
782  FunctionCoverage.Segments = SegmentBuilder::buildSegments(Regions);
783 
784  return FunctionCoverage;
785 }
786 
788  const ExpansionRecord &Expansion) const {
789  CoverageData ExpansionCoverage(
790  Expansion.Function.Filenames[Expansion.FileID]);
791  std::vector<CountedRegion> Regions;
792  for (const auto &CR : Expansion.Function.CountedRegions)
793  if (CR.FileID == Expansion.FileID) {
794  Regions.push_back(CR);
795  if (isExpansion(CR, Expansion.FileID))
796  ExpansionCoverage.Expansions.emplace_back(CR, Expansion.Function);
797  }
798  for (const auto &CR : Expansion.Function.CountedBranchRegions)
799  // Capture branch regions that only pertain to the corresponding expansion.
800  if (CR.FileID == Expansion.FileID)
801  ExpansionCoverage.BranchRegions.push_back(CR);
802 
803  LLVM_DEBUG(dbgs() << "Emitting segments for expansion of file "
804  << Expansion.FileID << "\n");
805  ExpansionCoverage.Segments = SegmentBuilder::buildSegments(Regions);
806 
807  return ExpansionCoverage;
808 }
809 
810 LineCoverageStats::LineCoverageStats(
812  const CoverageSegment *WrappedSegment, unsigned Line)
813  : ExecutionCount(0), HasMultipleRegions(false), Mapped(false), Line(Line),
814  LineSegments(LineSegments), WrappedSegment(WrappedSegment) {
815  // Find the minimum number of regions which start in this line.
816  unsigned MinRegionCount = 0;
817  auto isStartOfRegion = [](const CoverageSegment *S) {
818  return !S->IsGapRegion && S->HasCount && S->IsRegionEntry;
819  };
820  for (unsigned I = 0; I < LineSegments.size() && MinRegionCount < 2; ++I)
821  if (isStartOfRegion(LineSegments[I]))
822  ++MinRegionCount;
823 
824  bool StartOfSkippedRegion = !LineSegments.empty() &&
825  !LineSegments.front()->HasCount &&
826  LineSegments.front()->IsRegionEntry;
827 
828  HasMultipleRegions = MinRegionCount > 1;
829  Mapped =
830  !StartOfSkippedRegion &&
831  ((WrappedSegment && WrappedSegment->HasCount) || (MinRegionCount > 0));
832 
833  if (!Mapped)
834  return;
835 
836  // Pick the max count from the non-gap, region entry segments and the
837  // wrapped count.
838  if (WrappedSegment)
839  ExecutionCount = WrappedSegment->Count;
840  if (!MinRegionCount)
841  return;
842  for (const auto *LS : LineSegments)
843  if (isStartOfRegion(LS))
844  ExecutionCount = std::max(ExecutionCount, LS->Count);
845 }
846 
848  if (Next == CD.end()) {
849  Stats = LineCoverageStats();
850  Ended = true;
851  return *this;
852  }
853  if (Segments.size())
854  WrappedSegment = Segments.back();
855  Segments.clear();
856  while (Next != CD.end() && Next->Line == Line)
857  Segments.push_back(&*Next++);
858  Stats = LineCoverageStats(Segments, WrappedSegment, Line);
859  ++Line;
860  return *this;
861 }
862 
864  switch (Err) {
866  return "Success";
868  return "End of File";
870  return "No coverage data found";
872  return "Unsupported coverage format version";
874  return "Truncated coverage data";
876  return "Malformed coverage data";
878  return "Failed to decompress coverage data (zlib)";
880  return "`-arch` specifier is invalid or missing for universal binary";
881  }
882  llvm_unreachable("A value of coveragemap_error has no message.");
883 }
884 
885 namespace {
886 
887 // FIXME: This class is only here to support the transition to llvm::Error. It
888 // will be removed once this transition is complete. Clients should prefer to
889 // deal with the Error value directly, rather than converting to error_code.
890 class CoverageMappingErrorCategoryType : public std::error_category {
891  const char *name() const noexcept override { return "llvm.coveragemap"; }
892  std::string message(int IE) const override {
893  return getCoverageMapErrString(static_cast<coveragemap_error>(IE));
894  }
895 };
896 
897 } // end anonymous namespace
898 
899 std::string CoverageMapError::message() const {
900  return getCoverageMapErrString(Err);
901 }
902 
903 const std::error_category &llvm::coverage::coveragemap_category() {
904  static CoverageMappingErrorCategoryType ErrorCategory;
905  return ErrorCategory;
906 }
907 
908 char CoverageMapError::ID = 0;
llvm::MemoryBuffer::getFileOrSTDIN
static ErrorOr< std::unique_ptr< MemoryBuffer > > getFileOrSTDIN(const Twine &Filename, bool IsText=false, bool RequiresNullTerminator=true, Optional< Align > Alignment=std::nullopt)
Open the specified file as a MemoryBuffer, or open stdin if the Filename is "-".
Definition: MemoryBuffer.cpp:151
llvm::coverage::Counter::getExpression
static Counter getExpression(unsigned ExpressionId)
Return the counter that corresponds to a specific addition counter expression.
Definition: CoverageMapping.h:142
llvm::coverage::coveragemap_error::success
@ success
llvm::coverage::CounterExpressionBuilder::add
Counter add(Counter LHS, Counter RHS, bool Simplify=true)
Return a counter that represents the expression that adds LHS and RHS.
Definition: CoverageMapping.cpp:126
MemoryBuffer.h
llvm::coverage::CounterExpression
A Counter expression is a value that represents an arithmetic operation with two counters.
Definition: CoverageMapping.h:149
llvm::coverage::CoverageMapping::getCoverageForExpansion
CoverageData getCoverageForExpansion(const ExpansionRecord &Expansion) const
Get the coverage for an expansion within a coverage set.
Definition: CoverageMapping.cpp:787
llvm::coverage::CoverageMapping::getInstantiationGroups
std::vector< InstantiationGroup > getInstantiationGroups(StringRef Filename) const
Get the list of function instantiation groups in a particular file.
Definition: CoverageMapping.cpp:737
llvm::coverage::CoverageData::end
std::vector< CoverageSegment >::const_iterator end() const
Definition: CoverageMapping.h:553
llvm::coverage::FunctionRecord::Filenames
std::vector< std::string > Filenames
Mapping from FileID (i.e.
Definition: CoverageMapping.h:351
llvm
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
llvm::SmallVectorImpl::erase
iterator erase(const_iterator CI)
Definition: SmallVector.h:741
llvm::sys::path::const_iterator::end
friend const_iterator end(StringRef path)
Get end iterator over path.
Definition: Path.cpp:235
llvm::handleErrors
Error handleErrors(Error E, HandlerTs &&... Hs)
Pass the ErrorInfo(s) contained in E to their respective handlers.
Definition: Error.h:942
Optional.h
llvm::coverage::CoverageMapError
Definition: CoverageMapping.h:68
llvm::coverage::CoverageMapError::get
coveragemap_error get() const
Definition: CoverageMapping.h:82
llvm::Function::end
iterator end()
Definition: Function.h:709
llvm::coverage::coveragemap_error::no_data_found
@ no_data_found
llvm::coverage::FunctionRecordIterator::FunctionRecordIterator
FunctionRecordIterator()
Definition: CoverageMapping.h:399
T
llvm::Function
Definition: Function.h:60
llvm::coverage::CounterExpression::Subtract
@ Subtract
Definition: CoverageMapping.h:150
llvm::PseudoProbeReservedId::Last
@ Last
StringRef.h
name
static const char * name
Definition: SMEABIPass.cpp:49
handleMaybeNoDataFoundError
static Error handleMaybeNoDataFoundError(Error E)
Definition: CoverageMapping.cpp:338
llvm::SmallVector
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1199
llvm::coverage::LineCoverageIterator
An iterator over the LineCoverageStats objects for lines described by a CoverageData instance.
Definition: CoverageMapping.h:696
llvm::enumerate
detail::enumerator< R > enumerate(R &&TheRange)
Given an input range, returns a new range whose values are are pair (A,B) such that A is the 0-based ...
Definition: STLExtras.h:2263
llvm::coverage::Counter::Expression
@ Expression
Definition: CoverageMapping.h:95
ErrorHandling.h
llvm::Error::success
static ErrorSuccess success()
Create a success value.
Definition: Error.h:329
Error.h
llvm::coverage::Counter::getCounter
static Counter getCounter(unsigned CounterId)
Return the counter that corresponds to a specific profile counter.
Definition: CoverageMapping.h:136
llvm::coverage::Counter::CounterValueReference
@ CounterValueReference
Definition: CoverageMapping.h:95
Errc.h
llvm::SmallBitVector::find_first
int find_first() const
Returns the index of the first set bit, -1 if none of the bits are set.
Definition: SmallBitVector.h:230
DenseMap.h
llvm::sys::path::end
const_iterator end(StringRef path)
Get end iterator over path.
Definition: Path.cpp:235
llvm::sys::path::begin
const_iterator begin(StringRef path, Style style=Style::native)
Get begin iterator over path.
Definition: Path.cpp:226
llvm::coverage::coveragemap_error
coveragemap_error
Definition: CoverageMapping.h:51
llvm::coverage::CoverageSegment::IsRegionEntry
bool IsRegionEntry
Whether this enters a new region or returns to a previous count.
Definition: CoverageMapping.h:447
llvm::Optional< unsigned >
llvm::coverage::CounterMappingRegion::ExpansionRegion
@ ExpansionRegion
An ExpansionRegion represents a file expansion region that associates a source range with the expansi...
Definition: CoverageMapping.h:216
llvm::max
Expected< ExpressionValue > max(const ExpressionValue &Lhs, const ExpressionValue &Rhs)
Definition: FileCheck.cpp:337
llvm::coverage::CounterExpression::Add
@ Add
Definition: CoverageMapping.h:150
llvm::Expected
Tagged union holding either a T or a Error.
Definition: APFloat.h:41
isExpansion
static bool isExpansion(const CountedRegion &R, unsigned FileID)
Definition: CoverageMapping.cpp:702
RHS
Value * RHS
Definition: X86PartialReduction.cpp:76
llvm::coverage::coveragemap_error::unsupported_version
@ unsupported_version
llvm::coverage::CoverageMapError::message
std::string message() const override
Return the error message as a string.
Definition: CoverageMapping.cpp:899
llvm::consumeError
void consumeError(Error Err)
Consume a Error without doing anything.
Definition: Error.h:1042
llvm::MemoryBufferRef
Definition: MemoryBufferRef.h:22
llvm::ArrayRef::empty
bool empty() const
empty - Check if the array is empty.
Definition: ArrayRef.h:159
LLVM_DEBUG
#define LLVM_DEBUG(X)
Definition: Debug.h:101
llvm::coverage::coveragemap_error::decompression_failed
@ decompression_failed
llvm::coverage::ExpansionRecord::Function
const FunctionRecord & Function
Coverage for the expansion.
Definition: CoverageMapping.h:426
llvm::RISCVFenceField::R
@ R
Definition: RISCVBaseInfo.h:265
findMainViewFileID
static Optional< unsigned > findMainViewFileID(const FunctionRecord &Function)
Return the ID of the file where the definition of the function is located.
Definition: CoverageMapping.cpp:680
llvm::logicalview::LVAttributeKind::Coverage
@ Coverage
llvm::dbgs
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
llvm::SmallBitVector
This is a 'bitvector' (really, a variable-sized bit array), optimized for the case when the array is ...
Definition: SmallBitVector.h:35
LHS
Value * LHS
Definition: X86PartialReduction.cpp:75
llvm::coverage::coveragemap_error::eof
@ eof
llvm::coverage::LineCoverageIterator::operator++
LineCoverageIterator & operator++()
Definition: CoverageMapping.cpp:847
llvm::errc::argument_out_of_domain
@ argument_out_of_domain
llvm::MutableArrayRef::end
iterator end() const
Definition: ArrayRef.h:356
llvm::coverage::LineColPair
std::pair< unsigned, unsigned > LineColPair
Definition: CoverageMapping.h:205
llvm::MutableArrayRef
MutableArrayRef - Represent a mutable reference to an array (0 or more elements consecutively in memo...
Definition: ArrayRef.h:28
llvm::createFileError
Error createFileError(const Twine &F, Error E)
Concatenate a source file path and/or name with an Error.
Definition: Error.h:1319
llvm::coverage::coveragemap_error::malformed
@ malformed
E
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
C
(vector float) vec_cmpeq(*A, *B) C
Definition: README_ALTIVEC.txt:86
llvm::errorCodeToError
Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
Definition: Error.cpp:92
llvm::coverage::CoverageMapping::getCoverageForFunction
CoverageData getCoverageForFunction(const FunctionRecord &Function) const
Get the coverage for a particular function.
Definition: CoverageMapping.cpp:762
llvm::coverage::FunctionRecord::CountedBranchRegions
std::vector< CountedRegion > CountedBranchRegions
Branch Regions in the function along with their counts.
Definition: CoverageMapping.h:355
false
Definition: StackSlotColoring.cpp:141
llvm::coverage::CoverageMapping::getUniqueSourceFiles
std::vector< StringRef > getUniqueSourceFiles() const
Returns a lexicographically sorted, unique list of files that are covered.
Definition: CoverageMapping.cpp:660
llvm::raw_ostream
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:53
llvm::coverage::coveragemap_error::invalid_or_missing_arch_specifier
@ invalid_or_missing_arch_specifier
llvm::IndexedInstrProfReader::getFunctionCounts
Error getFunctionCounts(StringRef FuncName, uint64_t FuncHash, std::vector< uint64_t > &Counts)
Fill Counts with the profile data for the given function name.
Definition: InstrProfReader.cpp:1113
llvm::coverage::CounterMappingContext::dump
void dump(const Counter &C, raw_ostream &OS) const
Definition: CoverageMapping.cpp:137
llvm::coverage::CounterMappingContext::evaluate
Expected< int64_t > evaluate(const Counter &C) const
Return the number of times that a region of code associated with this counter was executed.
Definition: CoverageMapping.cpp:167
llvm::InstrProfError::take
static instrprof_error take(Error E)
Consume an Error and return the raw enum value contained within it.
Definition: InstrProf.h:358
llvm::coverage::CoverageSegment::HasCount
bool HasCount
When false, the segment was uninstrumented or skipped.
Definition: CoverageMapping.h:445
llvm::coverage::BinaryCoverageReader::create
static Expected< std::vector< std::unique_ptr< BinaryCoverageReader > > > create(MemoryBufferRef ObjectBuffer, StringRef Arch, SmallVectorImpl< std::unique_ptr< MemoryBuffer >> &ObjectFileBuffers, StringRef CompilationDir="")
Definition: CoverageMappingReader.cpp:1074
llvm::coverage::coveragemap_error::truncated
@ truncated
llvm::ARM_PROC::IE
@ IE
Definition: ARMBaseInfo.h:27
llvm::coverage::FunctionRecord
Code coverage information for a single function.
Definition: CoverageMapping.h:342
llvm::sort
void sort(IteratorTy Start, IteratorTy End)
Definition: STLExtras.h:1682
llvm::StringRef::empty
constexpr bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:134
CoverageMappingReader.h
InstrProfReader.h
const
aarch64 promote const
Definition: AArch64PromoteConstant.cpp:232
llvm::IndexedInstrProfReader
Reader for the indexed binary instrprof format.
Definition: InstrProfReader.h:579
move
compiles ldr LCPI1_0 ldr ldr mov lsr tst moveq r1 ldr LCPI1_1 and r0 bx lr It would be better to do something like to fold the shift into the conditional move
Definition: README.txt:546
llvm::coverage::Counter
A Counter is an abstract value that describes how to compute the execution count for a region of code...
Definition: CoverageMapping.h:92
I
#define I(x, y, z)
Definition: MD5.cpp:58
llvm::instrprof_error
instrprof_error
Definition: InstrProf.h:308
ArrayRef.h
llvm::coverage::coveragemap_category
const std::error_category & coveragemap_category()
Definition: CoverageMapping.cpp:903
llvm::MutableArrayRef::drop_back
MutableArrayRef< T > drop_back(size_t N=1) const
Definition: ArrayRef.h:391
message
message(STATUS "Targeting ${t}") add_subdirectory($
Definition: CMakeLists.txt:34
llvm::sys::path::const_iterator::begin
friend const_iterator begin(StringRef path, Style style)
Get begin iterator over path.
Definition: Path.cpp:226
assert
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
llvm::instrprof_error::unknown_function
@ unknown_function
llvm::pdb::PDB_TableType::Segments
@ Segments
llvm::MutableArrayRef::begin
iterator begin() const
Definition: ArrayRef.h:355
llvm::Record
Definition: Record.h:1574
llvm::IndexedInstrProfReader::create
static Expected< std::unique_ptr< IndexedInstrProfReader > > create(const Twine &Path, const Twine &RemappingPath="")
Factory method to create an indexed reader.
Definition: InstrProfReader.cpp:119
llvm::coverage::CounterMappingRegion::GapRegion
@ GapRegion
A GapRegion is like a CodeRegion, but its count is only set as the line execution count when its the ...
Definition: CoverageMapping.h:224
Builder
assume Assume Builder
Definition: AssumeBundleBuilder.cpp:651
llvm::ArrayRef< unsigned >
None.h
llvm::StringRef
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
Simplify
assume Assume Simplify
Definition: AssumeBundleBuilder.cpp:604
llvm_unreachable
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Definition: ErrorHandling.h:143
if
if(llvm_vc STREQUAL "") set(fake_version_inc "$
Definition: CMakeLists.txt:14
llvm::coverage::CoverageMapping
The mapping of profile information to coverage data.
Definition: CoverageMapping.h:570
llvm::coverage::CoverageMapping::getCoverageForFile
CoverageData getCoverageForFile(StringRef Filename) const
Get the coverage for a particular file.
Definition: CoverageMapping.cpp:706
gatherFileIDs
static SmallBitVector gatherFileIDs(StringRef SourceFile, const FunctionRecord &Function)
Definition: CoverageMapping.cpp:670
llvm::append_range
void append_range(Container &C, Range &&R)
Wrapper function to append a range to a container.
Definition: STLExtras.h:2013
S
add sub stmia L5 ldr r0 bl L_printf $stub Instead of a and a wouldn t it be better to do three moves *Return an aggregate type is even return S
Definition: README.txt:210
llvm::instrprof_error::hash_mismatch
@ hash_mismatch
llvm::ArrayRef::front
const T & front() const
front - Get the first element.
Definition: ArrayRef.h:167
llvm::Function::begin
iterator begin()
Definition: Function.h:707
CoverageMapping.h
llvm::coverage::CoverageSegment::Count
uint64_t Count
The execution count, or zero if no count was recorded.
Definition: CoverageMapping.h:443
llvm::coverage::CoverageData
Coverage information to be processed or displayed.
Definition: CoverageMapping.h:531
llvm::coverage::LineCoverageStats
Coverage statistics for a single line.
Definition: CoverageMapping.h:664
llvm::stable_sort
void stable_sort(R &&Range)
Definition: STLExtras.h:1947
llvm::coverage::CoverageMapError::ID
static char ID
Definition: CoverageMapping.h:84
getMaxCounterID
static unsigned getMaxCounterID(const CounterMappingContext &Ctx, const CoverageMappingRecord &Record)
Definition: CoverageMapping.cpp:224
llvm::coverage::ExpansionRecord::FileID
unsigned FileID
The abstract file this expansion covers.
Definition: CoverageMapping.h:422
llvm::ArrayRef::begin
iterator begin() const
Definition: ArrayRef.h:152
llvm::Error
Lightweight error class with error context and mandatory checking.
Definition: Error.h:155
llvm::AArch64CC::LS
@ LS
Definition: AArch64BaseInfo.h:264
llvm::unique
auto unique(Range &&R, Predicate P)
Definition: STLExtras.h:1965
llvm::coverage::CoverageMapping::load
static Expected< std::unique_ptr< CoverageMapping > > load(ArrayRef< std::unique_ptr< CoverageMappingReader >> CoverageReaders, IndexedInstrProfReader &ProfileReader)
Load the coverage mapping using the given readers.
Definition: CoverageMapping.cpp:328
llvm::coverage::CounterMappingContext
A Counter mapping context is used to connect the counters, expressions and the obtained counter value...
Definition: CoverageMapping.h:320
llvm::hash_value
hash_code hash_value(const FixedPointSemantics &Val)
Definition: APFixedPoint.h:128
llvm::Expected::takeError
Error takeError()
Take ownership of the stored error.
Definition: Error.h:596
llvm::coverage::Counter::Zero
@ Zero
Definition: CoverageMapping.h:95
SmallVector.h
SmallBitVector.h
llvm::hash_combine_range
hash_code hash_combine_range(InputIteratorT first, InputIteratorT last)
Compute a hash_code for a sequence of values.
Definition: Hashing.h:486
llvm::ArrayRef::size
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:164
llvm::coverage::CounterExpressionBuilder::subtract
Counter subtract(Counter LHS, Counter RHS, bool Simplify=true)
Return a counter that represents the expression that subtracts RHS from LHS.
Definition: CoverageMapping.cpp:131
llvm::SmallVectorImpl
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: APFloat.h:42
llvm::coverage::Counter::getZero
static Counter getZero()
Return the counter that represents the number zero.
Definition: CoverageMapping.h:133
llvm::getFuncNameWithoutPrefix
StringRef getFuncNameWithoutPrefix(StringRef PGOFuncName, StringRef FileName="<unknown>")
Given a PGO function name, remove the filename prefix and return the original (static) function name.
Definition: InstrProf.cpp:323
llvm::coverage::CounterMappingRegion::CodeRegion
@ CodeRegion
A CodeRegion associates some code with a counter.
Definition: CoverageMapping.h:211
llvm::coverage::CounterMappingContext::getMaxCounterID
unsigned getMaxCounterID(const Counter &C) const
Definition: CoverageMapping.cpp:191
llvm::coverage::CoverageMapping::getCoveredFunctions
iterator_range< FunctionRecordIterator > getCoveredFunctions() const
Gets all of the functions covered by this profile.
Definition: CoverageMapping.h:643
llvm::coverage::ExpansionRecord
Coverage information for a macro expansion or #included file.
Definition: CoverageMapping.h:420
llvm::Region
Definition: RegionInfo.h:889
llvm::M68kBeads::Term
@ Term
Definition: M68kBaseInfo.h:71
raw_ostream.h
llvm::coverage::CoverageSegment
The execution count information starting at a point in a file.
Definition: CoverageMapping.h:437
llvm::coverage::InstantiationGroup
An instantiation group contains a FunctionRecord list, such that each record corresponds to a distinc...
Definition: CoverageMapping.h:474
getCoverageMapErrString
static std::string getCoverageMapErrString(coveragemap_error Err)
Definition: CoverageMapping.cpp:863
llvm::coverage::CountedRegion
Associates a source range with an execution count.
Definition: CoverageMapping.h:303
llvm::coverage::CoverageMappingRecord
Coverage mapping information for a single function.
Definition: CoverageMappingReader.h:35
llvm::Value
LLVM Value Representation.
Definition: Value.h:74
Debug.h
llvm::coverage::CounterMappingRegion::SkippedRegion
@ SkippedRegion
A SkippedRegion represents a source range with code that was skipped by a preprocessor or similar mea...
Definition: CoverageMapping.h:220
llvm::ArrayRef::end
iterator end() const
Definition: ArrayRef.h:153
llvm::SmallVectorImpl::emplace_back
reference emplace_back(ArgTypes &&... Args)
Definition: SmallVector.h:941
llvm::Function::size
size_t size() const
Definition: Function.h:712
llvm::coverage::FunctionRecord::CountedRegions
std::vector< CountedRegion > CountedRegions
Regions in the function along with their counts.
Definition: CoverageMapping.h:353