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