LLVM  7.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 
210  // Don't load records for (filenames, function) pairs we've already seen.
211  auto FilenamesHash = hash_combine_range(Record.Filenames.begin(),
212  Record.Filenames.end());
213  if (!RecordProvenance[FilenamesHash].insert(hash_value(OrigFuncName)).second)
214  return Error::success();
215 
217 
218  std::vector<uint64_t> Counts;
219  if (Error E = ProfileReader.getFunctionCounts(Record.FunctionName,
220  Record.FunctionHash, Counts)) {
221  instrprof_error IPE = InstrProfError::take(std::move(E));
222  if (IPE == instrprof_error::hash_mismatch) {
223  FuncHashMismatches.emplace_back(Record.FunctionName, Record.FunctionHash);
224  return Error::success();
225  } else if (IPE != instrprof_error::unknown_function)
226  return make_error<InstrProfError>(IPE);
227  Counts.assign(Record.MappingRegions.size(), 0);
228  }
229  Ctx.setCounts(Counts);
230 
231  assert(!Record.MappingRegions.empty() && "Function has no regions");
232 
233  FunctionRecord Function(OrigFuncName, Record.Filenames);
234  for (const auto &Region : Record.MappingRegions) {
235  Expected<int64_t> ExecutionCount = Ctx.evaluate(Region.Count);
236  if (auto E = ExecutionCount.takeError()) {
237  consumeError(std::move(E));
238  return Error::success();
239  }
240  Function.pushRegion(Region, *ExecutionCount);
241  }
242  if (Function.CountedRegions.size() != Record.MappingRegions.size()) {
243  FuncCounterMismatches.emplace_back(Record.FunctionName,
244  Function.CountedRegions.size());
245  return Error::success();
246  }
247 
248  Functions.push_back(std::move(Function));
249  return Error::success();
250 }
251 
253  ArrayRef<std::unique_ptr<CoverageMappingReader>> CoverageReaders,
254  IndexedInstrProfReader &ProfileReader) {
255  auto Coverage = std::unique_ptr<CoverageMapping>(new CoverageMapping());
256 
257  for (const auto &CoverageReader : CoverageReaders) {
258  for (auto RecordOrErr : *CoverageReader) {
259  if (Error E = RecordOrErr.takeError())
260  return std::move(E);
261  const auto &Record = *RecordOrErr;
262  if (Error E = Coverage->loadFunctionRecord(Record, ProfileReader))
263  return std::move(E);
264  }
265  }
266 
267  return std::move(Coverage);
268 }
269 
272  StringRef ProfileFilename, ArrayRef<StringRef> Arches) {
273  auto ProfileReaderOrErr = IndexedInstrProfReader::create(ProfileFilename);
274  if (Error E = ProfileReaderOrErr.takeError())
275  return std::move(E);
276  auto ProfileReader = std::move(ProfileReaderOrErr.get());
277 
280  for (const auto &File : llvm::enumerate(ObjectFilenames)) {
281  auto CovMappingBufOrErr = MemoryBuffer::getFileOrSTDIN(File.value());
282  if (std::error_code EC = CovMappingBufOrErr.getError())
283  return errorCodeToError(EC);
284  StringRef Arch = Arches.empty() ? StringRef() : Arches[File.index()];
285  auto CoverageReaderOrErr =
286  BinaryCoverageReader::create(CovMappingBufOrErr.get(), Arch);
287  if (Error E = CoverageReaderOrErr.takeError())
288  return std::move(E);
289  Readers.push_back(std::move(CoverageReaderOrErr.get()));
290  Buffers.push_back(std::move(CovMappingBufOrErr.get()));
291  }
292  return load(Readers, *ProfileReader);
293 }
294 
295 namespace {
296 
297 /// Distributes functions into instantiation sets.
298 ///
299 /// An instantiation set is a collection of functions that have the same source
300 /// code, ie, template functions specializations.
301 class FunctionInstantiationSetCollector {
302  using MapT = std::map<LineColPair, std::vector<const FunctionRecord *>>;
303  MapT InstantiatedFunctions;
304 
305 public:
306  void insert(const FunctionRecord &Function, unsigned FileID) {
307  auto I = Function.CountedRegions.begin(), E = Function.CountedRegions.end();
308  while (I != E && I->FileID != FileID)
309  ++I;
310  assert(I != E && "function does not cover the given file");
311  auto &Functions = InstantiatedFunctions[I->startLoc()];
312  Functions.push_back(&Function);
313  }
314 
315  MapT::iterator begin() { return InstantiatedFunctions.begin(); }
316  MapT::iterator end() { return InstantiatedFunctions.end(); }
317 };
318 
319 class SegmentBuilder {
320  std::vector<CoverageSegment> &Segments;
322 
323  SegmentBuilder(std::vector<CoverageSegment> &Segments) : Segments(Segments) {}
324 
325  /// Emit a segment with the count from \p Region starting at \p StartLoc.
326  //
327  /// \p IsRegionEntry: The segment is at the start of a new non-gap region.
328  /// \p EmitSkippedRegion: The segment must be emitted as a skipped region.
329  void startSegment(const CountedRegion &Region, LineColPair StartLoc,
330  bool IsRegionEntry, bool EmitSkippedRegion = false) {
331  bool HasCount = !EmitSkippedRegion &&
333 
334  // If the new segment wouldn't affect coverage rendering, skip it.
335  if (!Segments.empty() && !IsRegionEntry && !EmitSkippedRegion) {
336  const auto &Last = Segments.back();
337  if (Last.HasCount == HasCount && Last.Count == Region.ExecutionCount &&
338  !Last.IsRegionEntry)
339  return;
340  }
341 
342  if (HasCount)
343  Segments.emplace_back(StartLoc.first, StartLoc.second,
344  Region.ExecutionCount, IsRegionEntry,
346  else
347  Segments.emplace_back(StartLoc.first, StartLoc.second, IsRegionEntry);
348 
349  LLVM_DEBUG({
350  const auto &Last = Segments.back();
351  dbgs() << "Segment at " << Last.Line << ":" << Last.Col
352  << " (count = " << Last.Count << ")"
353  << (Last.IsRegionEntry ? ", RegionEntry" : "")
354  << (!Last.HasCount ? ", Skipped" : "")
355  << (Last.IsGapRegion ? ", Gap" : "") << "\n";
356  });
357  }
358 
359  /// Emit segments for active regions which end before \p Loc.
360  ///
361  /// \p Loc: The start location of the next region. If None, all active
362  /// regions are completed.
363  /// \p FirstCompletedRegion: Index of the first completed region.
364  void completeRegionsUntil(Optional<LineColPair> Loc,
365  unsigned FirstCompletedRegion) {
366  // Sort the completed regions by end location. This makes it simple to
367  // emit closing segments in sorted order.
368  auto CompletedRegionsIt = ActiveRegions.begin() + FirstCompletedRegion;
369  std::stable_sort(CompletedRegionsIt, ActiveRegions.end(),
370  [](const CountedRegion *L, const CountedRegion *R) {
371  return L->endLoc() < R->endLoc();
372  });
373 
374  // Emit segments for all completed regions.
375  for (unsigned I = FirstCompletedRegion + 1, E = ActiveRegions.size(); I < E;
376  ++I) {
377  const auto *CompletedRegion = ActiveRegions[I];
378  assert((!Loc || CompletedRegion->endLoc() <= *Loc) &&
379  "Completed region ends after start of new region");
380 
381  const auto *PrevCompletedRegion = ActiveRegions[I - 1];
382  auto CompletedSegmentLoc = PrevCompletedRegion->endLoc();
383 
384  // Don't emit any more segments if they start where the new region begins.
385  if (Loc && CompletedSegmentLoc == *Loc)
386  break;
387 
388  // Don't emit a segment if the next completed region ends at the same
389  // location as this one.
390  if (CompletedSegmentLoc == CompletedRegion->endLoc())
391  continue;
392 
393  // Use the count from the last completed region which ends at this loc.
394  for (unsigned J = I + 1; J < E; ++J)
395  if (CompletedRegion->endLoc() == ActiveRegions[J]->endLoc())
396  CompletedRegion = ActiveRegions[J];
397 
398  startSegment(*CompletedRegion, CompletedSegmentLoc, false);
399  }
400 
401  auto Last = ActiveRegions.back();
402  if (FirstCompletedRegion && Last->endLoc() != *Loc) {
403  // If there's a gap after the end of the last completed region and the
404  // start of the new region, use the last active region to fill the gap.
405  startSegment(*ActiveRegions[FirstCompletedRegion - 1], Last->endLoc(),
406  false);
407  } else if (!FirstCompletedRegion && (!Loc || *Loc != Last->endLoc())) {
408  // Emit a skipped segment if there are no more active regions. This
409  // ensures that gaps between functions are marked correctly.
410  startSegment(*Last, Last->endLoc(), false, true);
411  }
412 
413  // Pop the completed regions.
414  ActiveRegions.erase(CompletedRegionsIt, ActiveRegions.end());
415  }
416 
417  void buildSegmentsImpl(ArrayRef<CountedRegion> Regions) {
418  for (const auto &CR : enumerate(Regions)) {
419  auto CurStartLoc = CR.value().startLoc();
420 
421  // Active regions which end before the current region need to be popped.
422  auto CompletedRegions =
423  std::stable_partition(ActiveRegions.begin(), ActiveRegions.end(),
424  [&](const CountedRegion *Region) {
425  return !(Region->endLoc() <= CurStartLoc);
426  });
427  if (CompletedRegions != ActiveRegions.end()) {
428  unsigned FirstCompletedRegion =
429  std::distance(ActiveRegions.begin(), CompletedRegions);
430  completeRegionsUntil(CurStartLoc, FirstCompletedRegion);
431  }
432 
433  bool GapRegion = CR.value().Kind == CounterMappingRegion::GapRegion;
434 
435  // Try to emit a segment for the current region.
436  if (CurStartLoc == CR.value().endLoc()) {
437  // Avoid making zero-length regions active. If it's the last region,
438  // emit a skipped segment. Otherwise use its predecessor's count.
439  const bool Skipped = (CR.index() + 1) == Regions.size();
440  startSegment(ActiveRegions.empty() ? CR.value() : *ActiveRegions.back(),
441  CurStartLoc, !GapRegion, Skipped);
442  continue;
443  }
444  if (CR.index() + 1 == Regions.size() ||
445  CurStartLoc != Regions[CR.index() + 1].startLoc()) {
446  // Emit a segment if the next region doesn't start at the same location
447  // as this one.
448  startSegment(CR.value(), CurStartLoc, !GapRegion);
449  }
450 
451  // This region is active (i.e not completed).
452  ActiveRegions.push_back(&CR.value());
453  }
454 
455  // Complete any remaining active regions.
456  if (!ActiveRegions.empty())
457  completeRegionsUntil(None, 0);
458  }
459 
460  /// Sort a nested sequence of regions from a single file.
461  static void sortNestedRegions(MutableArrayRef<CountedRegion> Regions) {
462  llvm::sort(Regions.begin(), Regions.end(), [](const CountedRegion &LHS,
463  const CountedRegion &RHS) {
464  if (LHS.startLoc() != RHS.startLoc())
465  return LHS.startLoc() < RHS.startLoc();
466  if (LHS.endLoc() != RHS.endLoc())
467  // When LHS completely contains RHS, we sort LHS first.
468  return RHS.endLoc() < LHS.endLoc();
469  // If LHS and RHS cover the same area, we need to sort them according
470  // to their kinds so that the most suitable region will become "active"
471  // in combineRegions(). Because we accumulate counter values only from
472  // regions of the same kind as the first region of the area, prefer
473  // CodeRegion to ExpansionRegion and ExpansionRegion to SkippedRegion.
474  static_assert(CounterMappingRegion::CodeRegion <
478  "Unexpected order of region kind values");
479  return LHS.Kind < RHS.Kind;
480  });
481  }
482 
483  /// Combine counts of regions which cover the same area.
485  combineRegions(MutableArrayRef<CountedRegion> Regions) {
486  if (Regions.empty())
487  return Regions;
488  auto Active = Regions.begin();
489  auto End = Regions.end();
490  for (auto I = Regions.begin() + 1; I != End; ++I) {
491  if (Active->startLoc() != I->startLoc() ||
492  Active->endLoc() != I->endLoc()) {
493  // Shift to the next region.
494  ++Active;
495  if (Active != I)
496  *Active = *I;
497  continue;
498  }
499  // Merge duplicate region.
500  // If CodeRegions and ExpansionRegions cover the same area, it's probably
501  // a macro which is fully expanded to another macro. In that case, we need
502  // to accumulate counts only from CodeRegions, or else the area will be
503  // counted twice.
504  // On the other hand, a macro may have a nested macro in its body. If the
505  // outer macro is used several times, the ExpansionRegion for the nested
506  // macro will also be added several times. These ExpansionRegions cover
507  // the same source locations and have to be combined to reach the correct
508  // value for that area.
509  // We add counts of the regions of the same kind as the active region
510  // to handle the both situations.
511  if (I->Kind == Active->Kind)
512  Active->ExecutionCount += I->ExecutionCount;
513  }
514  return Regions.drop_back(std::distance(++Active, End));
515  }
516 
517 public:
518  /// Build a sorted list of CoverageSegments from a list of Regions.
519  static std::vector<CoverageSegment>
520  buildSegments(MutableArrayRef<CountedRegion> Regions) {
521  std::vector<CoverageSegment> Segments;
522  SegmentBuilder Builder(Segments);
523 
524  sortNestedRegions(Regions);
525  ArrayRef<CountedRegion> CombinedRegions = combineRegions(Regions);
526 
527  LLVM_DEBUG({
528  dbgs() << "Combined regions:\n";
529  for (const auto &CR : CombinedRegions)
530  dbgs() << " " << CR.LineStart << ":" << CR.ColumnStart << " -> "
531  << CR.LineEnd << ":" << CR.ColumnEnd
532  << " (count=" << CR.ExecutionCount << ")\n";
533  });
534 
535  Builder.buildSegmentsImpl(CombinedRegions);
536 
537 #ifndef NDEBUG
538  for (unsigned I = 1, E = Segments.size(); I < E; ++I) {
539  const auto &L = Segments[I - 1];
540  const auto &R = Segments[I];
541  if (!(L.Line < R.Line) && !(L.Line == R.Line && L.Col < R.Col)) {
542  LLVM_DEBUG(dbgs() << " ! Segment " << L.Line << ":" << L.Col
543  << " followed by " << R.Line << ":" << R.Col << "\n");
544  assert(false && "Coverage segments not unique or sorted");
545  }
546  }
547 #endif
548 
549  return Segments;
550  }
551 };
552 
553 } // end anonymous namespace
554 
555 std::vector<StringRef> CoverageMapping::getUniqueSourceFiles() const {
556  std::vector<StringRef> Filenames;
557  for (const auto &Function : getCoveredFunctions())
558  Filenames.insert(Filenames.end(), Function.Filenames.begin(),
559  Function.Filenames.end());
560  llvm::sort(Filenames.begin(), Filenames.end());
561  auto Last = std::unique(Filenames.begin(), Filenames.end());
562  Filenames.erase(Last, Filenames.end());
563  return Filenames;
564 }
565 
567  const FunctionRecord &Function) {
568  SmallBitVector FilenameEquivalence(Function.Filenames.size(), false);
569  for (unsigned I = 0, E = Function.Filenames.size(); I < E; ++I)
570  if (SourceFile == Function.Filenames[I])
571  FilenameEquivalence[I] = true;
572  return FilenameEquivalence;
573 }
574 
575 /// Return the ID of the file where the definition of the function is located.
577  SmallBitVector IsNotExpandedFile(Function.Filenames.size(), true);
578  for (const auto &CR : Function.CountedRegions)
580  IsNotExpandedFile[CR.ExpandedFileID] = false;
581  int I = IsNotExpandedFile.find_first();
582  if (I == -1)
583  return None;
584  return I;
585 }
586 
587 /// Check if SourceFile is the file that contains the definition of
588 /// the Function. Return the ID of the file in that case or None otherwise.
590  const FunctionRecord &Function) {
592  if (I && SourceFile == Function.Filenames[*I])
593  return I;
594  return None;
595 }
596 
597 static bool isExpansion(const CountedRegion &R, unsigned FileID) {
598  return R.Kind == CounterMappingRegion::ExpansionRegion && R.FileID == FileID;
599 }
600 
602  CoverageData FileCoverage(Filename);
603  std::vector<CountedRegion> Regions;
604 
605  for (const auto &Function : Functions) {
606  auto MainFileID = findMainViewFileID(Filename, Function);
607  auto FileIDs = gatherFileIDs(Filename, Function);
608  for (const auto &CR : Function.CountedRegions)
609  if (FileIDs.test(CR.FileID)) {
610  Regions.push_back(CR);
611  if (MainFileID && isExpansion(CR, *MainFileID))
612  FileCoverage.Expansions.emplace_back(CR, Function);
613  }
614  }
615 
616  LLVM_DEBUG(dbgs() << "Emitting segments for file: " << Filename << "\n");
617  FileCoverage.Segments = SegmentBuilder::buildSegments(Regions);
618 
619  return FileCoverage;
620 }
621 
622 std::vector<InstantiationGroup>
624  FunctionInstantiationSetCollector InstantiationSetCollector;
625  for (const auto &Function : Functions) {
626  auto MainFileID = findMainViewFileID(Filename, Function);
627  if (!MainFileID)
628  continue;
629  InstantiationSetCollector.insert(Function, *MainFileID);
630  }
631 
632  std::vector<InstantiationGroup> Result;
633  for (auto &InstantiationSet : InstantiationSetCollector) {
634  InstantiationGroup IG{InstantiationSet.first.first,
635  InstantiationSet.first.second,
636  std::move(InstantiationSet.second)};
637  Result.emplace_back(std::move(IG));
638  }
639  return Result;
640 }
641 
644  auto MainFileID = findMainViewFileID(Function);
645  if (!MainFileID)
646  return CoverageData();
647 
648  CoverageData FunctionCoverage(Function.Filenames[*MainFileID]);
649  std::vector<CountedRegion> Regions;
650  for (const auto &CR : Function.CountedRegions)
651  if (CR.FileID == *MainFileID) {
652  Regions.push_back(CR);
653  if (isExpansion(CR, *MainFileID))
654  FunctionCoverage.Expansions.emplace_back(CR, Function);
655  }
656 
657  LLVM_DEBUG(dbgs() << "Emitting segments for function: " << Function.Name
658  << "\n");
659  FunctionCoverage.Segments = SegmentBuilder::buildSegments(Regions);
660 
661  return FunctionCoverage;
662 }
663 
665  const ExpansionRecord &Expansion) const {
666  CoverageData ExpansionCoverage(
667  Expansion.Function.Filenames[Expansion.FileID]);
668  std::vector<CountedRegion> Regions;
669  for (const auto &CR : Expansion.Function.CountedRegions)
670  if (CR.FileID == Expansion.FileID) {
671  Regions.push_back(CR);
672  if (isExpansion(CR, Expansion.FileID))
673  ExpansionCoverage.Expansions.emplace_back(CR, Expansion.Function);
674  }
675 
676  LLVM_DEBUG(dbgs() << "Emitting segments for expansion of file "
677  << Expansion.FileID << "\n");
678  ExpansionCoverage.Segments = SegmentBuilder::buildSegments(Regions);
679 
680  return ExpansionCoverage;
681 }
682 
683 LineCoverageStats::LineCoverageStats(
685  const CoverageSegment *WrappedSegment, unsigned Line)
686  : ExecutionCount(0), HasMultipleRegions(false), Mapped(false), Line(Line),
687  LineSegments(LineSegments), WrappedSegment(WrappedSegment) {
688  // Find the minimum number of regions which start in this line.
689  unsigned MinRegionCount = 0;
690  auto isStartOfRegion = [](const CoverageSegment *S) {
691  return !S->IsGapRegion && S->HasCount && S->IsRegionEntry;
692  };
693  for (unsigned I = 0; I < LineSegments.size() && MinRegionCount < 2; ++I)
694  if (isStartOfRegion(LineSegments[I]))
695  ++MinRegionCount;
696 
697  bool StartOfSkippedRegion = !LineSegments.empty() &&
698  !LineSegments.front()->HasCount &&
699  LineSegments.front()->IsRegionEntry;
700 
701  HasMultipleRegions = MinRegionCount > 1;
702  Mapped =
703  !StartOfSkippedRegion &&
704  ((WrappedSegment && WrappedSegment->HasCount) || (MinRegionCount > 0));
705 
706  if (!Mapped)
707  return;
708 
709  // Pick the max count from the non-gap, region entry segments and the
710  // wrapped count.
711  if (WrappedSegment)
712  ExecutionCount = WrappedSegment->Count;
713  if (!MinRegionCount)
714  return;
715  for (const auto *LS : LineSegments)
716  if (isStartOfRegion(LS))
717  ExecutionCount = std::max(ExecutionCount, LS->Count);
718 }
719 
721  if (Next == CD.end()) {
723  Ended = true;
724  return *this;
725  }
726  if (Segments.size())
727  WrappedSegment = Segments.back();
728  Segments.clear();
729  while (Next != CD.end() && Next->Line == Line)
730  Segments.push_back(&*Next++);
731  Stats = LineCoverageStats(Segments, WrappedSegment, Line);
732  ++Line;
733  return *this;
734 }
735 
737  switch (Err) {
739  return "Success";
741  return "End of File";
743  return "No coverage data found";
745  return "Unsupported coverage format version";
747  return "Truncated coverage data";
749  return "Malformed coverage data";
750  }
751  llvm_unreachable("A value of coveragemap_error has no message.");
752 }
753 
754 namespace {
755 
756 // FIXME: This class is only here to support the transition to llvm::Error. It
757 // will be removed once this transition is complete. Clients should prefer to
758 // deal with the Error value directly, rather than converting to error_code.
759 class CoverageMappingErrorCategoryType : public std::error_category {
760  const char *name() const noexcept override { return "llvm.coveragemap"; }
761  std::string message(int IE) const override {
762  return getCoverageMapErrString(static_cast<coveragemap_error>(IE));
763  }
764 };
765 
766 } // end anonymous namespace
767 
768 std::string CoverageMapError::message() const {
769  return getCoverageMapErrString(Err);
770 }
771 
773 
775  return *ErrorCategory;
776 }
777 
778 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:250
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:241
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.
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
Definition: SmallVector.h:137
iterator end()
Definition: Function.h:644
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
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE size_t size() const
size - Get the string size.
Definition: StringRef.h:138
static SmallBitVector gatherFileIDs(StringRef SourceFile, const FunctionRecord &Function)
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:537
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:241
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:642
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:250
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:78
An instantiation group contains a FunctionRecord list, such that each record corresponds to a distinc...
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
Definition: SmallVector.h:117
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 const unsigned End
static ManagedStatic< CoverageMappingErrorCategoryType > ErrorCategory
Associates a source range with an execution count.
iterator erase(const_iterator CI)
Definition: SmallVector.h:446
void consumeError(Error Err)
Consume a Error without doing anything.
Definition: Error.h:962
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:859
Code coverage information for a single function.
static ErrorSuccess success()
Create a success value.
Definition: Error.h:313
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:861
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:480
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:121
std::string message() const override
Return the error message as a string.
void emplace_back(ArgTypes &&... Args)
Definition: SmallVector.h:653
unsigned getExpressionID() const
CounterKind getKind() const
LLVM_NODISCARD bool empty() const
Definition: SmallVector.h:62
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:156
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:119
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:1224
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.