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