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