LLVM  8.0.0svn
CoverageMapping.cpp
Go to the documentation of this file.
1 //===- CoverageMapping.cpp - Code coverage mapping support ----------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains support for clang's and llvm's instrumentation based
11 // code coverage.
12 //
13 //===----------------------------------------------------------------------===//
14 
16 #include "llvm/ADT/ArrayRef.h"
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/None.h"
19 #include "llvm/ADT/Optional.h"
21 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/ADT/StringRef.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/Errc.h"
27 #include "llvm/Support/Error.h"
32 #include <algorithm>
33 #include <cassert>
34 #include <cstdint>
35 #include <iterator>
36 #include <map>
37 #include <memory>
38 #include <string>
39 #include <system_error>
40 #include <utility>
41 #include <vector>
42 
43 using namespace llvm;
44 using namespace coverage;
45 
46 #define DEBUG_TYPE "coverage-mapping"
47 
48 Counter CounterExpressionBuilder::get(const CounterExpression &E) {
49  auto It = ExpressionIndices.find(E);
50  if (It != ExpressionIndices.end())
51  return Counter::getExpression(It->second);
52  unsigned I = Expressions.size();
53  Expressions.push_back(E);
54  ExpressionIndices[E] = I;
55  return Counter::getExpression(I);
56 }
57 
58 void CounterExpressionBuilder::extractTerms(Counter C, int Factor,
59  SmallVectorImpl<Term> &Terms) {
60  switch (C.getKind()) {
61  case Counter::Zero:
62  break;
64  Terms.emplace_back(C.getCounterID(), Factor);
65  break;
67  const auto &E = Expressions[C.getExpressionID()];
68  extractTerms(E.LHS, Factor, Terms);
69  extractTerms(
70  E.RHS, E.Kind == CounterExpression::Subtract ? -Factor : Factor, Terms);
71  break;
72  }
73 }
74 
75 Counter CounterExpressionBuilder::simplify(Counter ExpressionTree) {
76  // Gather constant terms.
78  extractTerms(ExpressionTree, +1, Terms);
79 
80  // If there are no terms, this is just a zero. The algorithm below assumes at
81  // least one term.
82  if (Terms.size() == 0)
83  return Counter::getZero();
84 
85  // Group the terms by counter ID.
86  llvm::sort(Terms.begin(), Terms.end(), [](const Term &LHS, const Term &RHS) {
87  return LHS.CounterID < RHS.CounterID;
88  });
89 
90  // Combine terms by counter ID to eliminate counters that sum to zero.
91  auto Prev = Terms.begin();
92  for (auto I = Prev + 1, E = Terms.end(); I != E; ++I) {
93  if (I->CounterID == Prev->CounterID) {
94  Prev->Factor += I->Factor;
95  continue;
96  }
97  ++Prev;
98  *Prev = *I;
99  }
100  Terms.erase(++Prev, Terms.end());
101 
102  Counter C;
103  // Create additions. We do this before subtractions to avoid constructs like
104  // ((0 - X) + Y), as opposed to (Y - X).
105  for (auto T : Terms) {
106  if (T.Factor <= 0)
107  continue;
108  for (int I = 0; I < T.Factor; ++I)
109  if (C.isZero())
110  C = Counter::getCounter(T.CounterID);
111  else
113  Counter::getCounter(T.CounterID)));
114  }
115 
116  // Create subtractions.
117  for (auto T : Terms) {
118  if (T.Factor >= 0)
119  continue;
120  for (int I = 0; I < -T.Factor; ++I)
122  Counter::getCounter(T.CounterID)));
123  }
124  return C;
125 }
126 
128  return simplify(get(CounterExpression(CounterExpression::Add, LHS, RHS)));
129 }
130 
132  return simplify(
134 }
135 
137  switch (C.getKind()) {
138  case Counter::Zero:
139  OS << '0';
140  return;
142  OS << '#' << C.getCounterID();
143  break;
144  case Counter::Expression: {
145  if (C.getExpressionID() >= Expressions.size())
146  return;
147  const auto &E = Expressions[C.getExpressionID()];
148  OS << '(';
149  dump(E.LHS, OS);
150  OS << (E.Kind == CounterExpression::Subtract ? " - " : " + ");
151  dump(E.RHS, OS);
152  OS << ')';
153  break;
154  }
155  }
156  if (CounterValues.empty())
157  return;
158  Expected<int64_t> Value = evaluate(C);
159  if (auto E = Value.takeError()) {
160  consumeError(std::move(E));
161  return;
162  }
163  OS << '[' << *Value << ']';
164 }
165 
167  switch (C.getKind()) {
168  case Counter::Zero:
169  return 0;
171  if (C.getCounterID() >= CounterValues.size())
173  return CounterValues[C.getCounterID()];
174  case Counter::Expression: {
175  if (C.getExpressionID() >= Expressions.size())
177  const auto &E = Expressions[C.getExpressionID()];
178  Expected<int64_t> LHS = evaluate(E.LHS);
179  if (!LHS)
180  return LHS;
181  Expected<int64_t> RHS = evaluate(E.RHS);
182  if (!RHS)
183  return RHS;
184  return E.Kind == CounterExpression::Subtract ? *LHS - *RHS : *LHS + *RHS;
185  }
186  }
187  llvm_unreachable("Unhandled CounterKind");
188 }
189 
190 void FunctionRecordIterator::skipOtherFiles() {
191  while (Current != Records.end() && !Filename.empty() &&
192  Filename != Current->Filenames[0])
193  ++Current;
194  if (Current == Records.end())
195  *this = FunctionRecordIterator();
196 }
197 
198 Error CoverageMapping::loadFunctionRecord(
200  IndexedInstrProfReader &ProfileReader) {
201  StringRef OrigFuncName = Record.FunctionName;
202  if (OrigFuncName.empty())
203  return make_error<CoverageMapError>(coveragemap_error::malformed);
204 
205  if (Record.Filenames.empty())
206  OrigFuncName = getFuncNameWithoutPrefix(OrigFuncName);
207  else
208  OrigFuncName = getFuncNameWithoutPrefix(OrigFuncName, Record.Filenames[0]);
209 
211 
212  std::vector<uint64_t> Counts;
213  if (Error E = ProfileReader.getFunctionCounts(Record.FunctionName,
214  Record.FunctionHash, Counts)) {
215  instrprof_error IPE = InstrProfError::take(std::move(E));
216  if (IPE == instrprof_error::hash_mismatch) {
217  FuncHashMismatches.emplace_back(Record.FunctionName, Record.FunctionHash);
218  return Error::success();
219  } else if (IPE != instrprof_error::unknown_function)
220  return make_error<InstrProfError>(IPE);
221  Counts.assign(Record.MappingRegions.size(), 0);
222  }
223  Ctx.setCounts(Counts);
224 
225  assert(!Record.MappingRegions.empty() && "Function has no regions");
226 
227  // This coverage record is a zero region for a function that's unused in
228  // some TU, but used in a different TU. Ignore it. The coverage maps from the
229  // the other TU will either be loaded (providing full region counts) or they
230  // won't (in which case we don't unintuitively report functions as uncovered
231  // when they have non-zero counts in the profile).
232  if (Record.MappingRegions.size() == 1 &&
233  Record.MappingRegions[0].Count.isZero() && Counts[0] > 0)
234  return Error::success();
235 
236  FunctionRecord Function(OrigFuncName, Record.Filenames);
237  for (const auto &Region : Record.MappingRegions) {
238  Expected<int64_t> ExecutionCount = Ctx.evaluate(Region.Count);
239  if (auto E = ExecutionCount.takeError()) {
240  consumeError(std::move(E));
241  return Error::success();
242  }
243  Function.pushRegion(Region, *ExecutionCount);
244  }
245 
246  // Don't create records for (filenames, function) pairs we've already seen.
247  auto FilenamesHash = hash_combine_range(Record.Filenames.begin(),
248  Record.Filenames.end());
249  if (!RecordProvenance[FilenamesHash].insert(hash_value(OrigFuncName)).second)
250  return Error::success();
251 
252  Functions.push_back(std::move(Function));
253  return Error::success();
254 }
255 
257  ArrayRef<std::unique_ptr<CoverageMappingReader>> CoverageReaders,
258  IndexedInstrProfReader &ProfileReader) {
259  auto Coverage = std::unique_ptr<CoverageMapping>(new CoverageMapping());
260 
261  for (const auto &CoverageReader : CoverageReaders) {
262  for (auto RecordOrErr : *CoverageReader) {
263  if (Error E = RecordOrErr.takeError())
264  return std::move(E);
265  const auto &Record = *RecordOrErr;
266  if (Error E = Coverage->loadFunctionRecord(Record, ProfileReader))
267  return std::move(E);
268  }
269  }
270 
271  return std::move(Coverage);
272 }
273 
276  StringRef ProfileFilename, ArrayRef<StringRef> Arches) {
277  auto ProfileReaderOrErr = IndexedInstrProfReader::create(ProfileFilename);
278  if (Error E = ProfileReaderOrErr.takeError())
279  return std::move(E);
280  auto ProfileReader = std::move(ProfileReaderOrErr.get());
281 
284  for (const auto &File : llvm::enumerate(ObjectFilenames)) {
285  auto CovMappingBufOrErr = MemoryBuffer::getFileOrSTDIN(File.value());
286  if (std::error_code EC = CovMappingBufOrErr.getError())
287  return errorCodeToError(EC);
288  StringRef Arch = Arches.empty() ? StringRef() : Arches[File.index()];
289  auto CoverageReaderOrErr =
290  BinaryCoverageReader::create(CovMappingBufOrErr.get(), Arch);
291  if (Error E = CoverageReaderOrErr.takeError())
292  return std::move(E);
293  Readers.push_back(std::move(CoverageReaderOrErr.get()));
294  Buffers.push_back(std::move(CovMappingBufOrErr.get()));
295  }
296  return load(Readers, *ProfileReader);
297 }
298 
299 namespace {
300 
301 /// Distributes functions into instantiation sets.
302 ///
303 /// An instantiation set is a collection of functions that have the same source
304 /// code, ie, template functions specializations.
305 class FunctionInstantiationSetCollector {
306  using MapT = std::map<LineColPair, std::vector<const FunctionRecord *>>;
307  MapT InstantiatedFunctions;
308 
309 public:
310  void insert(const FunctionRecord &Function, unsigned FileID) {
311  auto I = Function.CountedRegions.begin(), E = Function.CountedRegions.end();
312  while (I != E && I->FileID != FileID)
313  ++I;
314  assert(I != E && "function does not cover the given file");
315  auto &Functions = InstantiatedFunctions[I->startLoc()];
316  Functions.push_back(&Function);
317  }
318 
319  MapT::iterator begin() { return InstantiatedFunctions.begin(); }
320  MapT::iterator end() { return InstantiatedFunctions.end(); }
321 };
322 
323 class SegmentBuilder {
324  std::vector<CoverageSegment> &Segments;
326 
327  SegmentBuilder(std::vector<CoverageSegment> &Segments) : Segments(Segments) {}
328 
329  /// Emit a segment with the count from \p Region starting at \p StartLoc.
330  //
331  /// \p IsRegionEntry: The segment is at the start of a new non-gap region.
332  /// \p EmitSkippedRegion: The segment must be emitted as a skipped region.
333  void startSegment(const CountedRegion &Region, LineColPair StartLoc,
334  bool IsRegionEntry, bool EmitSkippedRegion = false) {
335  bool HasCount = !EmitSkippedRegion &&
337 
338  // If the new segment wouldn't affect coverage rendering, skip it.
339  if (!Segments.empty() && !IsRegionEntry && !EmitSkippedRegion) {
340  const auto &Last = Segments.back();
341  if (Last.HasCount == HasCount && Last.Count == Region.ExecutionCount &&
342  !Last.IsRegionEntry)
343  return;
344  }
345 
346  if (HasCount)
347  Segments.emplace_back(StartLoc.first, StartLoc.second,
348  Region.ExecutionCount, IsRegionEntry,
350  else
351  Segments.emplace_back(StartLoc.first, StartLoc.second, IsRegionEntry);
352 
353  LLVM_DEBUG({
354  const auto &Last = Segments.back();
355  dbgs() << "Segment at " << Last.Line << ":" << Last.Col
356  << " (count = " << Last.Count << ")"
357  << (Last.IsRegionEntry ? ", RegionEntry" : "")
358  << (!Last.HasCount ? ", Skipped" : "")
359  << (Last.IsGapRegion ? ", Gap" : "") << "\n";
360  });
361  }
362 
363  /// Emit segments for active regions which end before \p Loc.
364  ///
365  /// \p Loc: The start location of the next region. If None, all active
366  /// regions are completed.
367  /// \p FirstCompletedRegion: Index of the first completed region.
368  void completeRegionsUntil(Optional<LineColPair> Loc,
369  unsigned FirstCompletedRegion) {
370  // Sort the completed regions by end location. This makes it simple to
371  // emit closing segments in sorted order.
372  auto CompletedRegionsIt = ActiveRegions.begin() + FirstCompletedRegion;
373  std::stable_sort(CompletedRegionsIt, ActiveRegions.end(),
374  [](const CountedRegion *L, const CountedRegion *R) {
375  return L->endLoc() < R->endLoc();
376  });
377 
378  // Emit segments for all completed regions.
379  for (unsigned I = FirstCompletedRegion + 1, E = ActiveRegions.size(); I < E;
380  ++I) {
381  const auto *CompletedRegion = ActiveRegions[I];
382  assert((!Loc || CompletedRegion->endLoc() <= *Loc) &&
383  "Completed region ends after start of new region");
384 
385  const auto *PrevCompletedRegion = ActiveRegions[I - 1];
386  auto CompletedSegmentLoc = PrevCompletedRegion->endLoc();
387 
388  // Don't emit any more segments if they start where the new region begins.
389  if (Loc && CompletedSegmentLoc == *Loc)
390  break;
391 
392  // Don't emit a segment if the next completed region ends at the same
393  // location as this one.
394  if (CompletedSegmentLoc == CompletedRegion->endLoc())
395  continue;
396 
397  // Use the count from the last completed region which ends at this loc.
398  for (unsigned J = I + 1; J < E; ++J)
399  if (CompletedRegion->endLoc() == ActiveRegions[J]->endLoc())
400  CompletedRegion = ActiveRegions[J];
401 
402  startSegment(*CompletedRegion, CompletedSegmentLoc, false);
403  }
404 
405  auto Last = ActiveRegions.back();
406  if (FirstCompletedRegion && Last->endLoc() != *Loc) {
407  // If there's a gap after the end of the last completed region and the
408  // start of the new region, use the last active region to fill the gap.
409  startSegment(*ActiveRegions[FirstCompletedRegion - 1], Last->endLoc(),
410  false);
411  } else if (!FirstCompletedRegion && (!Loc || *Loc != Last->endLoc())) {
412  // Emit a skipped segment if there are no more active regions. This
413  // ensures that gaps between functions are marked correctly.
414  startSegment(*Last, Last->endLoc(), false, true);
415  }
416 
417  // Pop the completed regions.
418  ActiveRegions.erase(CompletedRegionsIt, ActiveRegions.end());
419  }
420 
421  void buildSegmentsImpl(ArrayRef<CountedRegion> Regions) {
422  for (const auto &CR : enumerate(Regions)) {
423  auto CurStartLoc = CR.value().startLoc();
424 
425  // Active regions which end before the current region need to be popped.
426  auto CompletedRegions =
427  std::stable_partition(ActiveRegions.begin(), ActiveRegions.end(),
428  [&](const CountedRegion *Region) {
429  return !(Region->endLoc() <= CurStartLoc);
430  });
431  if (CompletedRegions != ActiveRegions.end()) {
432  unsigned FirstCompletedRegion =
433  std::distance(ActiveRegions.begin(), CompletedRegions);
434  completeRegionsUntil(CurStartLoc, FirstCompletedRegion);
435  }
436 
437  bool GapRegion = CR.value().Kind == CounterMappingRegion::GapRegion;
438 
439  // Try to emit a segment for the current region.
440  if (CurStartLoc == CR.value().endLoc()) {
441  // Avoid making zero-length regions active. If it's the last region,
442  // emit a skipped segment. Otherwise use its predecessor's count.
443  const bool Skipped = (CR.index() + 1) == Regions.size();
444  startSegment(ActiveRegions.empty() ? CR.value() : *ActiveRegions.back(),
445  CurStartLoc, !GapRegion, Skipped);
446  continue;
447  }
448  if (CR.index() + 1 == Regions.size() ||
449  CurStartLoc != Regions[CR.index() + 1].startLoc()) {
450  // Emit a segment if the next region doesn't start at the same location
451  // as this one.
452  startSegment(CR.value(), CurStartLoc, !GapRegion);
453  }
454 
455  // This region is active (i.e not completed).
456  ActiveRegions.push_back(&CR.value());
457  }
458 
459  // Complete any remaining active regions.
460  if (!ActiveRegions.empty())
461  completeRegionsUntil(None, 0);
462  }
463 
464  /// Sort a nested sequence of regions from a single file.
465  static void sortNestedRegions(MutableArrayRef<CountedRegion> Regions) {
466  llvm::sort(Regions.begin(), Regions.end(), [](const CountedRegion &LHS,
467  const CountedRegion &RHS) {
468  if (LHS.startLoc() != RHS.startLoc())
469  return LHS.startLoc() < RHS.startLoc();
470  if (LHS.endLoc() != RHS.endLoc())
471  // When LHS completely contains RHS, we sort LHS first.
472  return RHS.endLoc() < LHS.endLoc();
473  // If LHS and RHS cover the same area, we need to sort them according
474  // to their kinds so that the most suitable region will become "active"
475  // in combineRegions(). Because we accumulate counter values only from
476  // regions of the same kind as the first region of the area, prefer
477  // CodeRegion to ExpansionRegion and ExpansionRegion to SkippedRegion.
478  static_assert(CounterMappingRegion::CodeRegion <
482  "Unexpected order of region kind values");
483  return LHS.Kind < RHS.Kind;
484  });
485  }
486 
487  /// Combine counts of regions which cover the same area.
489  combineRegions(MutableArrayRef<CountedRegion> Regions) {
490  if (Regions.empty())
491  return Regions;
492  auto Active = Regions.begin();
493  auto End = Regions.end();
494  for (auto I = Regions.begin() + 1; I != End; ++I) {
495  if (Active->startLoc() != I->startLoc() ||
496  Active->endLoc() != I->endLoc()) {
497  // Shift to the next region.
498  ++Active;
499  if (Active != I)
500  *Active = *I;
501  continue;
502  }
503  // Merge duplicate region.
504  // If CodeRegions and ExpansionRegions cover the same area, it's probably
505  // a macro which is fully expanded to another macro. In that case, we need
506  // to accumulate counts only from CodeRegions, or else the area will be
507  // counted twice.
508  // On the other hand, a macro may have a nested macro in its body. If the
509  // outer macro is used several times, the ExpansionRegion for the nested
510  // macro will also be added several times. These ExpansionRegions cover
511  // the same source locations and have to be combined to reach the correct
512  // value for that area.
513  // We add counts of the regions of the same kind as the active region
514  // to handle the both situations.
515  if (I->Kind == Active->Kind)
516  Active->ExecutionCount += I->ExecutionCount;
517  }
518  return Regions.drop_back(std::distance(++Active, End));
519  }
520 
521 public:
522  /// Build a sorted list of CoverageSegments from a list of Regions.
523  static std::vector<CoverageSegment>
524  buildSegments(MutableArrayRef<CountedRegion> Regions) {
525  std::vector<CoverageSegment> Segments;
526  SegmentBuilder Builder(Segments);
527 
528  sortNestedRegions(Regions);
529  ArrayRef<CountedRegion> CombinedRegions = combineRegions(Regions);
530 
531  LLVM_DEBUG({
532  dbgs() << "Combined regions:\n";
533  for (const auto &CR : CombinedRegions)
534  dbgs() << " " << CR.LineStart << ":" << CR.ColumnStart << " -> "
535  << CR.LineEnd << ":" << CR.ColumnEnd
536  << " (count=" << CR.ExecutionCount << ")\n";
537  });
538 
539  Builder.buildSegmentsImpl(CombinedRegions);
540 
541 #ifndef NDEBUG
542  for (unsigned I = 1, E = Segments.size(); I < E; ++I) {
543  const auto &L = Segments[I - 1];
544  const auto &R = Segments[I];
545  if (!(L.Line < R.Line) && !(L.Line == R.Line && L.Col < R.Col)) {
546  LLVM_DEBUG(dbgs() << " ! Segment " << L.Line << ":" << L.Col
547  << " followed by " << R.Line << ":" << R.Col << "\n");
548  assert(false && "Coverage segments not unique or sorted");
549  }
550  }
551 #endif
552 
553  return Segments;
554  }
555 };
556 
557 } // end anonymous namespace
558 
559 std::vector<StringRef> CoverageMapping::getUniqueSourceFiles() const {
560  std::vector<StringRef> Filenames;
561  for (const auto &Function : getCoveredFunctions())
562  Filenames.insert(Filenames.end(), Function.Filenames.begin(),
563  Function.Filenames.end());
564  llvm::sort(Filenames.begin(), Filenames.end());
565  auto Last = std::unique(Filenames.begin(), Filenames.end());
566  Filenames.erase(Last, Filenames.end());
567  return Filenames;
568 }
569 
571  const FunctionRecord &Function) {
572  SmallBitVector FilenameEquivalence(Function.Filenames.size(), false);
573  for (unsigned I = 0, E = Function.Filenames.size(); I < E; ++I)
574  if (SourceFile == Function.Filenames[I])
575  FilenameEquivalence[I] = true;
576  return FilenameEquivalence;
577 }
578 
579 /// Return the ID of the file where the definition of the function is located.
581  SmallBitVector IsNotExpandedFile(Function.Filenames.size(), true);
582  for (const auto &CR : Function.CountedRegions)
584  IsNotExpandedFile[CR.ExpandedFileID] = false;
585  int I = IsNotExpandedFile.find_first();
586  if (I == -1)
587  return None;
588  return I;
589 }
590 
591 /// Check if SourceFile is the file that contains the definition of
592 /// the Function. Return the ID of the file in that case or None otherwise.
594  const FunctionRecord &Function) {
596  if (I && SourceFile == Function.Filenames[*I])
597  return I;
598  return None;
599 }
600 
601 static bool isExpansion(const CountedRegion &R, unsigned FileID) {
602  return R.Kind == CounterMappingRegion::ExpansionRegion && R.FileID == FileID;
603 }
604 
606  CoverageData FileCoverage(Filename);
607  std::vector<CountedRegion> Regions;
608 
609  for (const auto &Function : Functions) {
610  auto MainFileID = findMainViewFileID(Filename, Function);
611  auto FileIDs = gatherFileIDs(Filename, Function);
612  for (const auto &CR : Function.CountedRegions)
613  if (FileIDs.test(CR.FileID)) {
614  Regions.push_back(CR);
615  if (MainFileID && isExpansion(CR, *MainFileID))
616  FileCoverage.Expansions.emplace_back(CR, Function);
617  }
618  }
619 
620  LLVM_DEBUG(dbgs() << "Emitting segments for file: " << Filename << "\n");
621  FileCoverage.Segments = SegmentBuilder::buildSegments(Regions);
622 
623  return FileCoverage;
624 }
625 
626 std::vector<InstantiationGroup>
628  FunctionInstantiationSetCollector InstantiationSetCollector;
629  for (const auto &Function : Functions) {
630  auto MainFileID = findMainViewFileID(Filename, Function);
631  if (!MainFileID)
632  continue;
633  InstantiationSetCollector.insert(Function, *MainFileID);
634  }
635 
636  std::vector<InstantiationGroup> Result;
637  for (auto &InstantiationSet : InstantiationSetCollector) {
638  InstantiationGroup IG{InstantiationSet.first.first,
639  InstantiationSet.first.second,
640  std::move(InstantiationSet.second)};
641  Result.emplace_back(std::move(IG));
642  }
643  return Result;
644 }
645 
648  auto MainFileID = findMainViewFileID(Function);
649  if (!MainFileID)
650  return CoverageData();
651 
652  CoverageData FunctionCoverage(Function.Filenames[*MainFileID]);
653  std::vector<CountedRegion> Regions;
654  for (const auto &CR : Function.CountedRegions)
655  if (CR.FileID == *MainFileID) {
656  Regions.push_back(CR);
657  if (isExpansion(CR, *MainFileID))
658  FunctionCoverage.Expansions.emplace_back(CR, Function);
659  }
660 
661  LLVM_DEBUG(dbgs() << "Emitting segments for function: " << Function.Name
662  << "\n");
663  FunctionCoverage.Segments = SegmentBuilder::buildSegments(Regions);
664 
665  return FunctionCoverage;
666 }
667 
669  const ExpansionRecord &Expansion) const {
670  CoverageData ExpansionCoverage(
671  Expansion.Function.Filenames[Expansion.FileID]);
672  std::vector<CountedRegion> Regions;
673  for (const auto &CR : Expansion.Function.CountedRegions)
674  if (CR.FileID == Expansion.FileID) {
675  Regions.push_back(CR);
676  if (isExpansion(CR, Expansion.FileID))
677  ExpansionCoverage.Expansions.emplace_back(CR, Expansion.Function);
678  }
679 
680  LLVM_DEBUG(dbgs() << "Emitting segments for expansion of file "
681  << Expansion.FileID << "\n");
682  ExpansionCoverage.Segments = SegmentBuilder::buildSegments(Regions);
683 
684  return ExpansionCoverage;
685 }
686 
687 LineCoverageStats::LineCoverageStats(
689  const CoverageSegment *WrappedSegment, unsigned Line)
690  : ExecutionCount(0), HasMultipleRegions(false), Mapped(false), Line(Line),
691  LineSegments(LineSegments), WrappedSegment(WrappedSegment) {
692  // Find the minimum number of regions which start in this line.
693  unsigned MinRegionCount = 0;
694  auto isStartOfRegion = [](const CoverageSegment *S) {
695  return !S->IsGapRegion && S->HasCount && S->IsRegionEntry;
696  };
697  for (unsigned I = 0; I < LineSegments.size() && MinRegionCount < 2; ++I)
698  if (isStartOfRegion(LineSegments[I]))
699  ++MinRegionCount;
700 
701  bool StartOfSkippedRegion = !LineSegments.empty() &&
702  !LineSegments.front()->HasCount &&
703  LineSegments.front()->IsRegionEntry;
704 
705  HasMultipleRegions = MinRegionCount > 1;
706  Mapped =
707  !StartOfSkippedRegion &&
708  ((WrappedSegment && WrappedSegment->HasCount) || (MinRegionCount > 0));
709 
710  if (!Mapped)
711  return;
712 
713  // Pick the max count from the non-gap, region entry segments and the
714  // wrapped count.
715  if (WrappedSegment)
716  ExecutionCount = WrappedSegment->Count;
717  if (!MinRegionCount)
718  return;
719  for (const auto *LS : LineSegments)
720  if (isStartOfRegion(LS))
721  ExecutionCount = std::max(ExecutionCount, LS->Count);
722 }
723 
725  if (Next == CD.end()) {
727  Ended = true;
728  return *this;
729  }
730  if (Segments.size())
731  WrappedSegment = Segments.back();
732  Segments.clear();
733  while (Next != CD.end() && Next->Line == Line)
734  Segments.push_back(&*Next++);
735  Stats = LineCoverageStats(Segments, WrappedSegment, Line);
736  ++Line;
737  return *this;
738 }
739 
741  switch (Err) {
743  return "Success";
745  return "End of File";
747  return "No coverage data found";
749  return "Unsupported coverage format version";
751  return "Truncated coverage data";
753  return "Malformed coverage data";
754  }
755  llvm_unreachable("A value of coveragemap_error has no message.");
756 }
757 
758 namespace {
759 
760 // FIXME: This class is only here to support the transition to llvm::Error. It
761 // will be removed once this transition is complete. Clients should prefer to
762 // deal with the Error value directly, rather than converting to error_code.
763 class CoverageMappingErrorCategoryType : public std::error_category {
764  const char *name() const noexcept override { return "llvm.coveragemap"; }
765  std::string message(int IE) const override {
766  return getCoverageMapErrString(static_cast<coveragemap_error>(IE));
767  }
768 };
769 
770 } // end anonymous namespace
771 
772 std::string CoverageMapError::message() const {
773  return getCoverageMapErrString(Err);
774 }
775 
777 
779  return *ErrorCategory;
780 }
781 
782 char CoverageMapError::ID = 0;
const T & front() const
front - Get the first element.
Definition: ArrayRef.h:152
const NoneType None
Definition: None.h:24
uint64_t CallInst * C
const_iterator end(StringRef path)
Get end iterator over path.
Definition: Path.cpp:259
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
const_iterator begin(StringRef path, Style style=Style::native)
Get begin iterator over path.
Definition: Path.cpp:250
This is a &#39;bitvector&#39; (really, a variable-sized bit array), optimized for the case when the array is ...
Compute iterated dominance frontiers using a linear time algorithm.
Definition: AllocatorList.h:24
static Counter getZero()
Return the counter that represents the number zero.
iterator end()
Definition: Function.h:658
void setCounts(ArrayRef< uint64_t > Counts)
static instrprof_error take(Error E)
Consume an Error and return the raw enum value contained within it.
Definition: InstrProf.h:324
static SmallBitVector gatherFileIDs(StringRef SourceFile, const FunctionRecord &Function)
void pushRegion(CounterMappingRegion Region, uint64_t Count)
A Counter expression is a value that represents an arithmetic operation with two counters.
Error takeError()
Take ownership of the stored error.
Definition: Error.h:553
ArrayRef< CounterMappingRegion > MappingRegions
CoverageData getCoverageForFile(StringRef Filename) const
Get the coverage for a particular file.
Iterator over Functions, optionally filtered to a single file.
A GapRegion is like a CodeRegion, but its count is only set as the line execution count when its the ...
ArrayRef< CounterExpression > Expressions
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: APFloat.h:42
An iterator over the LineCoverageStats objects for lines described by a CoverageData instance...
friend const_iterator begin(StringRef path, Style style)
Get begin iterator over path.
Definition: Path.cpp:250
Tagged union holding either a T or a Error.
Definition: CachePruning.h:23
block placement Basic Block Placement Stats
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:275
std::pair< unsigned, unsigned > LineColPair
void dump(const Counter &C, raw_ostream &OS) const
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:133
Coverage information to be processed or displayed.
static Expected< std::unique_ptr< CoverageMapping > > load(ArrayRef< std::unique_ptr< CoverageMappingReader >> CoverageReaders, IndexedInstrProfReader &ProfileReader)
Load the coverage mapping using the given readers.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Definition: APInt.h:33
hash_code hash_value(const APFloat &Arg)
See friend declarations above.
Definition: APFloat.cpp:4431
Counter add(Counter LHS, Counter RHS)
Return a counter that represents the expression that adds LHS and RHS.
iterator begin()
Definition: Function.h:656
const std::error_category & coveragemap_category()
The execution count information starting at a point in a file.
friend const_iterator end(StringRef path)
Get end iterator over path.
Definition: Path.cpp:259
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
MutableArrayRef - Represent a mutable reference to an array (0 or more elements consecutively in memo...
Definition: ArrayRef.h:291
Coverage mapping information for a single function.
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:149
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
Definition: Error.cpp:87
An instantiation group contains a FunctionRecord list, such that each record corresponds to a distinc...
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
Definition: SmallVector.h:129
A CodeRegion associates some code with a counter.
A Counter mapping context is used to connect the counters, expressions and the obtained counter value...
bool IsRegionEntry
Whether this enters a new region or returns to a previous count.
static ManagedStatic< _object_error_category > error_category
Definition: Error.cpp:74
static ManagedStatic< CoverageMappingErrorCategoryType > ErrorCategory
Associates a source range with an execution count.
iterator erase(const_iterator CI)
Definition: SmallVector.h:445
void consumeError(Error Err)
Consume a Error without doing anything.
Definition: Error.h:978
size_t size() const
Definition: SmallVector.h:53
MutableArrayRef< T > drop_back(size_t N=1) const
Definition: ArrayRef.h:367
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Counter subtract(Counter LHS, Counter RHS)
Return a counter that represents the expression that subtracts RHS from LHS.
CoverageData getCoverageForFunction(const FunctionRecord &Function) const
Get the coverage for a particular function.
void sort(IteratorTy Start, IteratorTy End)
Definition: STLExtras.h:972
Code coverage information for a single function.
static ErrorSuccess success()
Create a success value.
Definition: Error.h:327
static std::string getCoverageMapErrString(coveragemap_error Err)
Coverage statistics for a single line.
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:847
static bool isExpansion(const CountedRegion &R, unsigned FileID)
uint64_t Count
The execution count, or zero if no count was recorded.
bool HasCount
When false, the segment was uninstrumented or skipped.
static Expected< std::unique_ptr< BinaryCoverageReader > > create(std::unique_ptr< MemoryBuffer > &ObjectBuffer, StringRef Arch)
An ExpansionRegion represents a file expansion region that associates a source range with the expansi...
A SkippedRegion represents a source range with code that was skipped by a preprocessor or similar mea...
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:133
hash_code hash_combine_range(InputIteratorT first, InputIteratorT last)
Compute a hash_code for a sequence of values.
Definition: Hashing.h:479
iterator begin() const
Definition: ArrayRef.h:331
The mapping of profile information to coverage data.
static ErrorOr< std::unique_ptr< MemoryBuffer > > getFileOrSTDIN(const Twine &Filename, int64_t FileSize=-1, bool RequiresNullTerminator=true)
Open the specified file as a MemoryBuffer, or open stdin if the Filename is "-".
std::vector< InstantiationGroup > getInstantiationGroups(StringRef Filename) const
Get the list of function instantiation groups in a particular file.
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
Definition: SmallVector.h:133
std::string message() const override
Return the error message as a string.
void emplace_back(ArgTypes &&... Args)
Definition: SmallVector.h:652
unsigned getExpressionID() const
CounterKind getKind() const
LLVM_NODISCARD bool empty() const
Definition: SmallVector.h:56
instrprof_error
Definition: InstrProf.h:280
#define I(x, y, z)
Definition: MD5.cpp:58
static Optional< unsigned > findMainViewFileID(const FunctionRecord &Function)
Return the ID of the file where the definition of the function is located.
Expected< int64_t > evaluate(const Counter &C) const
Return the number of times that a region of code associated with this counter was executed...
std::vector< CountedRegion > CountedRegions
Regions in the function along with their counts.
std::string Name
Raw function name.
unsigned FileID
The abstract file this expansion covers.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
bool IsGapRegion
Whether this enters a gap region.
unsigned getCounterID() const
LLVM Value Representation.
Definition: Value.h:73
static const char * name
std::vector< std::string > Filenames
Associated files.
static Expected< std::unique_ptr< IndexedInstrProfReader > > create(const Twine &Path)
Factory method to create an indexed reader.
Lightweight error class with error context and mandatory checking.
Definition: Error.h:158
iterator end() const
Definition: ArrayRef.h:332
This class implements an extremely fast bulk output stream that can only output to a stream...
Definition: raw_ostream.h:46
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:49
Reader for the indexed binary instrprof format.
ManagedStatic - This transparently changes the behavior of global statics to be lazily constructed on...
Definition: ManagedStatic.h:61
static Counter getExpression(unsigned ExpressionId)
Return the counter that corresponds to a specific addition counter expression.
CoverageData getCoverageForExpansion(const ExpansionRecord &Expansion) const
Get the coverage for an expansion within a coverage set.
#define LLVM_DEBUG(X)
Definition: Debug.h:123
A Counter is an abstract value that describes how to compute the execution count for a region of code...
static Counter getCounter(unsigned CounterId)
Return the counter that corresponds to a specific profile counter.
const FunctionRecord & Function
Coverage for the expansion.
bool empty() const
empty - Check if the array is empty.
Definition: ArrayRef.h:144
std::vector< StringRef > getUniqueSourceFiles() const
Returns a lexicographically sorted, unique list of files that are covered.
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:1367
Error getFunctionCounts(StringRef FuncName, uint64_t FuncHash, std::vector< uint64_t > &Counts)
Fill Counts with the profile data for the given function name.
Coverage information for a macro expansion or #included file.