InstrProf: Rename ObjectFileCoverageMappingReader to BinaryCoverageReader
[oota-llvm.git] / lib / ProfileData / CoverageMapping.cpp
1 //=-- CoverageMapping.cpp - Code coverage mapping support ---------*- C++ -*-=//
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
15 #include "llvm/ProfileData/CoverageMapping.h"
16 #include "llvm/ADT/DenseMap.h"
17 #include "llvm/ADT/Optional.h"
18 #include "llvm/ADT/SmallBitVector.h"
19 #include "llvm/ProfileData/CoverageMappingReader.h"
20 #include "llvm/ProfileData/InstrProfReader.h"
21 #include "llvm/Support/Debug.h"
22 #include "llvm/Support/ErrorHandling.h"
23
24 using namespace llvm;
25 using namespace coverage;
26
27 #define DEBUG_TYPE "coverage-mapping"
28
29 Counter CounterExpressionBuilder::get(const CounterExpression &E) {
30   auto It = ExpressionIndices.find(E);
31   if (It != ExpressionIndices.end())
32     return Counter::getExpression(It->second);
33   unsigned I = Expressions.size();
34   Expressions.push_back(E);
35   ExpressionIndices[E] = I;
36   return Counter::getExpression(I);
37 }
38
39 void CounterExpressionBuilder::extractTerms(
40     Counter C, int Sign, SmallVectorImpl<std::pair<unsigned, int>> &Terms) {
41   switch (C.getKind()) {
42   case Counter::Zero:
43     break;
44   case Counter::CounterValueReference:
45     Terms.push_back(std::make_pair(C.getCounterID(), Sign));
46     break;
47   case Counter::Expression:
48     const auto &E = Expressions[C.getExpressionID()];
49     extractTerms(E.LHS, Sign, Terms);
50     extractTerms(E.RHS, E.Kind == CounterExpression::Subtract ? -Sign : Sign,
51                  Terms);
52     break;
53   }
54 }
55
56 Counter CounterExpressionBuilder::simplify(Counter ExpressionTree) {
57   // Gather constant terms.
58   llvm::SmallVector<std::pair<unsigned, int>, 32> Terms;
59   extractTerms(ExpressionTree, +1, Terms);
60
61   // If there are no terms, this is just a zero. The algorithm below assumes at
62   // least one term.
63   if (Terms.size() == 0)
64     return Counter::getZero();
65
66   // Group the terms by counter ID.
67   std::sort(Terms.begin(), Terms.end(),
68             [](const std::pair<unsigned, int> &LHS,
69                const std::pair<unsigned, int> &RHS) {
70     return LHS.first < RHS.first;
71   });
72
73   // Combine terms by counter ID to eliminate counters that sum to zero.
74   auto Prev = Terms.begin();
75   for (auto I = Prev + 1, E = Terms.end(); I != E; ++I) {
76     if (I->first == Prev->first) {
77       Prev->second += I->second;
78       continue;
79     }
80     ++Prev;
81     *Prev = *I;
82   }
83   Terms.erase(++Prev, Terms.end());
84
85   Counter C;
86   // Create additions. We do this before subtractions to avoid constructs like
87   // ((0 - X) + Y), as opposed to (Y - X).
88   for (auto Term : Terms) {
89     if (Term.second <= 0)
90       continue;
91     for (int I = 0; I < Term.second; ++I)
92       if (C.isZero())
93         C = Counter::getCounter(Term.first);
94       else
95         C = get(CounterExpression(CounterExpression::Add, C,
96                                   Counter::getCounter(Term.first)));
97   }
98
99   // Create subtractions.
100   for (auto Term : Terms) {
101     if (Term.second >= 0)
102       continue;
103     for (int I = 0; I < -Term.second; ++I)
104       C = get(CounterExpression(CounterExpression::Subtract, C,
105                                 Counter::getCounter(Term.first)));
106   }
107   return C;
108 }
109
110 Counter CounterExpressionBuilder::add(Counter LHS, Counter RHS) {
111   return simplify(get(CounterExpression(CounterExpression::Add, LHS, RHS)));
112 }
113
114 Counter CounterExpressionBuilder::subtract(Counter LHS, Counter RHS) {
115   return simplify(
116       get(CounterExpression(CounterExpression::Subtract, LHS, RHS)));
117 }
118
119 void CounterMappingContext::dump(const Counter &C,
120                                  llvm::raw_ostream &OS) const {
121   switch (C.getKind()) {
122   case Counter::Zero:
123     OS << '0';
124     return;
125   case Counter::CounterValueReference:
126     OS << '#' << C.getCounterID();
127     break;
128   case Counter::Expression: {
129     if (C.getExpressionID() >= Expressions.size())
130       return;
131     const auto &E = Expressions[C.getExpressionID()];
132     OS << '(';
133     dump(E.LHS, OS);
134     OS << (E.Kind == CounterExpression::Subtract ? " - " : " + ");
135     dump(E.RHS, OS);
136     OS << ')';
137     break;
138   }
139   }
140   if (CounterValues.empty())
141     return;
142   ErrorOr<int64_t> Value = evaluate(C);
143   if (!Value)
144     return;
145   OS << '[' << *Value << ']';
146 }
147
148 ErrorOr<int64_t> CounterMappingContext::evaluate(const Counter &C) const {
149   switch (C.getKind()) {
150   case Counter::Zero:
151     return 0;
152   case Counter::CounterValueReference:
153     if (C.getCounterID() >= CounterValues.size())
154       return std::make_error_code(std::errc::argument_out_of_domain);
155     return CounterValues[C.getCounterID()];
156   case Counter::Expression: {
157     if (C.getExpressionID() >= Expressions.size())
158       return std::make_error_code(std::errc::argument_out_of_domain);
159     const auto &E = Expressions[C.getExpressionID()];
160     ErrorOr<int64_t> LHS = evaluate(E.LHS);
161     if (!LHS)
162       return LHS;
163     ErrorOr<int64_t> RHS = evaluate(E.RHS);
164     if (!RHS)
165       return RHS;
166     return E.Kind == CounterExpression::Subtract ? *LHS - *RHS : *LHS + *RHS;
167   }
168   }
169   llvm_unreachable("Unhandled CounterKind");
170 }
171
172 void FunctionRecordIterator::skipOtherFiles() {
173   while (Current != Records.end() && !Filename.empty() &&
174          Filename != Current->Filenames[0])
175     ++Current;
176   if (Current == Records.end())
177     *this = FunctionRecordIterator();
178 }
179
180 ErrorOr<std::unique_ptr<CoverageMapping>>
181 CoverageMapping::load(CoverageMappingReader &CoverageReader,
182                       IndexedInstrProfReader &ProfileReader) {
183   auto Coverage = std::unique_ptr<CoverageMapping>(new CoverageMapping());
184
185   std::vector<uint64_t> Counts;
186   for (const auto &Record : CoverageReader) {
187     CounterMappingContext Ctx(Record.Expressions);
188
189     Counts.clear();
190     if (std::error_code EC = ProfileReader.getFunctionCounts(
191             Record.FunctionName, Record.FunctionHash, Counts)) {
192       if (EC == instrprof_error::hash_mismatch) {
193         Coverage->MismatchedFunctionCount++;
194         continue;
195       } else if (EC != instrprof_error::unknown_function)
196         return EC;
197     } else
198       Ctx.setCounts(Counts);
199
200     assert(!Record.MappingRegions.empty() && "Function has no regions");
201     FunctionRecord Function(Record.FunctionName, Record.Filenames);
202     for (const auto &Region : Record.MappingRegions) {
203       ErrorOr<int64_t> ExecutionCount = Ctx.evaluate(Region.Count);
204       if (!ExecutionCount)
205         break;
206       Function.pushRegion(Region, *ExecutionCount);
207     }
208     if (Function.CountedRegions.size() != Record.MappingRegions.size()) {
209       Coverage->MismatchedFunctionCount++;
210       continue;
211     }
212
213     Coverage->Functions.push_back(std::move(Function));
214   }
215
216   return std::move(Coverage);
217 }
218
219 ErrorOr<std::unique_ptr<CoverageMapping>>
220 CoverageMapping::load(StringRef ObjectFilename, StringRef ProfileFilename) {
221   auto CounterMappingBuff = MemoryBuffer::getFileOrSTDIN(ObjectFilename);
222   if (auto EC = CounterMappingBuff.getError())
223     return EC;
224   BinaryCoverageReader CoverageReader(CounterMappingBuff.get());
225   if (auto EC = CoverageReader.readHeader())
226     return EC;
227   auto ProfileReaderOrErr = IndexedInstrProfReader::create(ProfileFilename);
228   if (auto EC = ProfileReaderOrErr.getError())
229     return EC;
230   auto ProfileReader = std::move(ProfileReaderOrErr.get());
231   return load(CoverageReader, *ProfileReader);
232 }
233
234 namespace {
235 /// \brief Distributes functions into instantiation sets.
236 ///
237 /// An instantiation set is a collection of functions that have the same source
238 /// code, ie, template functions specializations.
239 class FunctionInstantiationSetCollector {
240   typedef DenseMap<std::pair<unsigned, unsigned>,
241                    std::vector<const FunctionRecord *>> MapT;
242   MapT InstantiatedFunctions;
243
244 public:
245   void insert(const FunctionRecord &Function, unsigned FileID) {
246     auto I = Function.CountedRegions.begin(), E = Function.CountedRegions.end();
247     while (I != E && I->FileID != FileID)
248       ++I;
249     assert(I != E && "function does not cover the given file");
250     auto &Functions = InstantiatedFunctions[I->startLoc()];
251     Functions.push_back(&Function);
252   }
253
254   MapT::iterator begin() { return InstantiatedFunctions.begin(); }
255
256   MapT::iterator end() { return InstantiatedFunctions.end(); }
257 };
258
259 class SegmentBuilder {
260   std::vector<CoverageSegment> Segments;
261   SmallVector<const CountedRegion *, 8> ActiveRegions;
262
263   /// Start a segment with no count specified.
264   void startSegment(unsigned Line, unsigned Col) {
265     DEBUG(dbgs() << "Top level segment at " << Line << ":" << Col << "\n");
266     Segments.emplace_back(Line, Col, /*IsRegionEntry=*/false);
267   }
268
269   /// Start a segment with the given Region's count.
270   void startSegment(unsigned Line, unsigned Col, bool IsRegionEntry,
271                     const CountedRegion &Region) {
272     if (Segments.empty())
273       Segments.emplace_back(Line, Col, IsRegionEntry);
274     CoverageSegment S = Segments.back();
275     // Avoid creating empty regions.
276     if (S.Line != Line || S.Col != Col) {
277       Segments.emplace_back(Line, Col, IsRegionEntry);
278       S = Segments.back();
279     }
280     DEBUG(dbgs() << "Segment at " << Line << ":" << Col);
281     // Set this region's count.
282     if (Region.Kind != coverage::CounterMappingRegion::SkippedRegion) {
283       DEBUG(dbgs() << " with count " << Region.ExecutionCount);
284       Segments.back().setCount(Region.ExecutionCount);
285     }
286     DEBUG(dbgs() << "\n");
287   }
288
289   /// Start a segment for the given region.
290   void startSegment(const CountedRegion &Region) {
291     startSegment(Region.LineStart, Region.ColumnStart, true, Region);
292   }
293
294   /// Pop the top region off of the active stack, starting a new segment with
295   /// the containing Region's count.
296   void popRegion() {
297     const CountedRegion *Active = ActiveRegions.back();
298     unsigned Line = Active->LineEnd, Col = Active->ColumnEnd;
299     ActiveRegions.pop_back();
300     if (ActiveRegions.empty())
301       startSegment(Line, Col);
302     else
303       startSegment(Line, Col, false, *ActiveRegions.back());
304   }
305
306 public:
307   /// Build a list of CoverageSegments from a sorted list of Regions.
308   std::vector<CoverageSegment> buildSegments(ArrayRef<CountedRegion> Regions) {
309     const CountedRegion *PrevRegion = nullptr;
310     for (const auto &Region : Regions) {
311       // Pop any regions that end before this one starts.
312       while (!ActiveRegions.empty() &&
313              ActiveRegions.back()->endLoc() <= Region.startLoc())
314         popRegion();
315       if (PrevRegion && PrevRegion->startLoc() == Region.startLoc() &&
316           PrevRegion->endLoc() == Region.endLoc()) {
317         if (Region.Kind == coverage::CounterMappingRegion::CodeRegion)
318           Segments.back().addCount(Region.ExecutionCount);
319       } else {
320         // Add this region to the stack.
321         ActiveRegions.push_back(&Region);
322         startSegment(Region);
323       }
324       PrevRegion = &Region;
325     }
326     // Pop any regions that are left in the stack.
327     while (!ActiveRegions.empty())
328       popRegion();
329     return Segments;
330   }
331 };
332 }
333
334 std::vector<StringRef> CoverageMapping::getUniqueSourceFiles() const {
335   std::vector<StringRef> Filenames;
336   for (const auto &Function : getCoveredFunctions())
337     Filenames.insert(Filenames.end(), Function.Filenames.begin(),
338                      Function.Filenames.end());
339   std::sort(Filenames.begin(), Filenames.end());
340   auto Last = std::unique(Filenames.begin(), Filenames.end());
341   Filenames.erase(Last, Filenames.end());
342   return Filenames;
343 }
344
345 static SmallBitVector gatherFileIDs(StringRef SourceFile,
346                                     const FunctionRecord &Function) {
347   SmallBitVector FilenameEquivalence(Function.Filenames.size(), false);
348   for (unsigned I = 0, E = Function.Filenames.size(); I < E; ++I)
349     if (SourceFile == Function.Filenames[I])
350       FilenameEquivalence[I] = true;
351   return FilenameEquivalence;
352 }
353
354 static Optional<unsigned> findMainViewFileID(StringRef SourceFile,
355                                              const FunctionRecord &Function) {
356   SmallBitVector IsNotExpandedFile(Function.Filenames.size(), true);
357   SmallBitVector FilenameEquivalence = gatherFileIDs(SourceFile, Function);
358   for (const auto &CR : Function.CountedRegions)
359     if (CR.Kind == CounterMappingRegion::ExpansionRegion &&
360         FilenameEquivalence[CR.FileID])
361       IsNotExpandedFile[CR.ExpandedFileID] = false;
362   IsNotExpandedFile &= FilenameEquivalence;
363   int I = IsNotExpandedFile.find_first();
364   if (I == -1)
365     return None;
366   return I;
367 }
368
369 static Optional<unsigned> findMainViewFileID(const FunctionRecord &Function) {
370   SmallBitVector IsNotExpandedFile(Function.Filenames.size(), true);
371   for (const auto &CR : Function.CountedRegions)
372     if (CR.Kind == CounterMappingRegion::ExpansionRegion)
373       IsNotExpandedFile[CR.ExpandedFileID] = false;
374   int I = IsNotExpandedFile.find_first();
375   if (I == -1)
376     return None;
377   return I;
378 }
379
380 /// Sort a nested sequence of regions from a single file.
381 template <class It> static void sortNestedRegions(It First, It Last) {
382   std::sort(First, Last,
383             [](const CountedRegion &LHS, const CountedRegion &RHS) {
384     if (LHS.startLoc() == RHS.startLoc())
385       // When LHS completely contains RHS, we sort LHS first.
386       return RHS.endLoc() < LHS.endLoc();
387     return LHS.startLoc() < RHS.startLoc();
388   });
389 }
390
391 static bool isExpansion(const CountedRegion &R, unsigned FileID) {
392   return R.Kind == CounterMappingRegion::ExpansionRegion && R.FileID == FileID;
393 }
394
395 CoverageData CoverageMapping::getCoverageForFile(StringRef Filename) {
396   CoverageData FileCoverage(Filename);
397   std::vector<coverage::CountedRegion> Regions;
398
399   for (const auto &Function : Functions) {
400     auto MainFileID = findMainViewFileID(Filename, Function);
401     if (!MainFileID)
402       continue;
403     auto FileIDs = gatherFileIDs(Filename, Function);
404     for (const auto &CR : Function.CountedRegions)
405       if (FileIDs.test(CR.FileID)) {
406         Regions.push_back(CR);
407         if (isExpansion(CR, *MainFileID))
408           FileCoverage.Expansions.emplace_back(CR, Function);
409       }
410   }
411
412   sortNestedRegions(Regions.begin(), Regions.end());
413   DEBUG(dbgs() << "Emitting segments for file: " << Filename << "\n");
414   FileCoverage.Segments = SegmentBuilder().buildSegments(Regions);
415
416   return FileCoverage;
417 }
418
419 std::vector<const FunctionRecord *>
420 CoverageMapping::getInstantiations(StringRef Filename) {
421   FunctionInstantiationSetCollector InstantiationSetCollector;
422   for (const auto &Function : Functions) {
423     auto MainFileID = findMainViewFileID(Filename, Function);
424     if (!MainFileID)
425       continue;
426     InstantiationSetCollector.insert(Function, *MainFileID);
427   }
428
429   std::vector<const FunctionRecord *> Result;
430   for (const auto &InstantiationSet : InstantiationSetCollector) {
431     if (InstantiationSet.second.size() < 2)
432       continue;
433     Result.insert(Result.end(), InstantiationSet.second.begin(),
434                   InstantiationSet.second.end());
435   }
436   return Result;
437 }
438
439 CoverageData
440 CoverageMapping::getCoverageForFunction(const FunctionRecord &Function) {
441   auto MainFileID = findMainViewFileID(Function);
442   if (!MainFileID)
443     return CoverageData();
444
445   CoverageData FunctionCoverage(Function.Filenames[*MainFileID]);
446   std::vector<coverage::CountedRegion> Regions;
447   for (const auto &CR : Function.CountedRegions)
448     if (CR.FileID == *MainFileID) {
449       Regions.push_back(CR);
450       if (isExpansion(CR, *MainFileID))
451         FunctionCoverage.Expansions.emplace_back(CR, Function);
452     }
453
454   sortNestedRegions(Regions.begin(), Regions.end());
455   DEBUG(dbgs() << "Emitting segments for function: " << Function.Name << "\n");
456   FunctionCoverage.Segments = SegmentBuilder().buildSegments(Regions);
457
458   return FunctionCoverage;
459 }
460
461 CoverageData
462 CoverageMapping::getCoverageForExpansion(const ExpansionRecord &Expansion) {
463   CoverageData ExpansionCoverage(
464       Expansion.Function.Filenames[Expansion.FileID]);
465   std::vector<coverage::CountedRegion> Regions;
466   for (const auto &CR : Expansion.Function.CountedRegions)
467     if (CR.FileID == Expansion.FileID) {
468       Regions.push_back(CR);
469       if (isExpansion(CR, Expansion.FileID))
470         ExpansionCoverage.Expansions.emplace_back(CR, Expansion.Function);
471     }
472
473   sortNestedRegions(Regions.begin(), Regions.end());
474   DEBUG(dbgs() << "Emitting segments for expansion of file " << Expansion.FileID
475                << "\n");
476   ExpansionCoverage.Segments = SegmentBuilder().buildSegments(Regions);
477
478   return ExpansionCoverage;
479 }