xref: /llvm-project/llvm/unittests/ProfileData/CoverageMappingTest.cpp (revision 80fbb85555b51fbb8c500ec13756490400191865)
1 //===- unittest/ProfileData/CoverageMappingTest.cpp -------------------------=//
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 #include "llvm/ProfileData/Coverage/CoverageMapping.h"
11 #include "llvm/ProfileData/Coverage/CoverageMappingReader.h"
12 #include "llvm/ProfileData/Coverage/CoverageMappingWriter.h"
13 #include "llvm/ProfileData/InstrProfReader.h"
14 #include "llvm/ProfileData/InstrProfWriter.h"
15 #include "llvm/Support/raw_ostream.h"
16 #include "llvm/Testing/Support/Error.h"
17 #include "llvm/Testing/Support/SupportHelpers.h"
18 #include "gtest/gtest.h"
19 
20 #include <ostream>
21 #include <utility>
22 
23 using namespace llvm;
24 using namespace coverage;
25 
26 LLVM_NODISCARD static ::testing::AssertionResult
27 ErrorEquals(coveragemap_error Expected, Error E) {
28   coveragemap_error Found;
29   std::string FoundMsg;
30   handleAllErrors(std::move(E), [&](const CoverageMapError &CME) {
31     Found = CME.get();
32     FoundMsg = CME.message();
33   });
34   if (Expected == Found)
35     return ::testing::AssertionSuccess();
36   return ::testing::AssertionFailure() << "error: " << FoundMsg << "\n";
37 }
38 
39 namespace llvm {
40 namespace coverage {
41 void PrintTo(const Counter &C, ::std::ostream *os) {
42   if (C.isZero())
43     *os << "Zero";
44   else if (C.isExpression())
45     *os << "Expression " << C.getExpressionID();
46   else
47     *os << "Counter " << C.getCounterID();
48 }
49 
50 void PrintTo(const CoverageSegment &S, ::std::ostream *os) {
51   *os << "CoverageSegment(" << S.Line << ", " << S.Col << ", ";
52   if (S.HasCount)
53     *os << S.Count << ", ";
54   *os << (S.IsRegionEntry ? "true" : "false") << ")";
55 }
56 }
57 }
58 
59 namespace {
60 
61 struct OutputFunctionCoverageData {
62   StringRef Name;
63   uint64_t Hash;
64   std::vector<StringRef> Filenames;
65   std::vector<CounterMappingRegion> Regions;
66 
67   OutputFunctionCoverageData() : Hash(0) {}
68 
69   OutputFunctionCoverageData(OutputFunctionCoverageData &&OFCD)
70       : Name(OFCD.Name), Hash(OFCD.Hash), Filenames(std::move(OFCD.Filenames)),
71         Regions(std::move(OFCD.Regions)) {}
72 
73   OutputFunctionCoverageData(const OutputFunctionCoverageData &) = delete;
74   OutputFunctionCoverageData &
75   operator=(const OutputFunctionCoverageData &) = delete;
76   OutputFunctionCoverageData &operator=(OutputFunctionCoverageData &&) = delete;
77 
78   void fillCoverageMappingRecord(CoverageMappingRecord &Record) const {
79     Record.FunctionName = Name;
80     Record.FunctionHash = Hash;
81     Record.Filenames = Filenames;
82     Record.Expressions = {};
83     Record.MappingRegions = Regions;
84   }
85 };
86 
87 struct CoverageMappingReaderMock : CoverageMappingReader {
88   ArrayRef<OutputFunctionCoverageData> Functions;
89 
90   CoverageMappingReaderMock(ArrayRef<OutputFunctionCoverageData> Functions)
91       : Functions(Functions) {}
92 
93   Error readNextRecord(CoverageMappingRecord &Record) override {
94     if (Functions.empty())
95       return make_error<CoverageMapError>(coveragemap_error::eof);
96 
97     Functions.front().fillCoverageMappingRecord(Record);
98     Functions = Functions.slice(1);
99 
100     return Error::success();
101   }
102 };
103 
104 struct InputFunctionCoverageData {
105   // Maps the global file index from CoverageMappingTest.Files
106   // to the index of that file within this function. We can't just use
107   // global file indexes here because local indexes have to be dense.
108   // This map is used during serialization to create the virtual file mapping
109   // (from local fileId to global Index) in the head of the per-function
110   // coverage mapping data.
111   SmallDenseMap<unsigned, unsigned> ReverseVirtualFileMapping;
112   std::string Name;
113   uint64_t Hash;
114   std::vector<CounterMappingRegion> Regions;
115 
116   InputFunctionCoverageData(std::string Name, uint64_t Hash)
117       : Name(std::move(Name)), Hash(Hash) {}
118 
119   InputFunctionCoverageData(InputFunctionCoverageData &&IFCD)
120       : ReverseVirtualFileMapping(std::move(IFCD.ReverseVirtualFileMapping)),
121         Name(std::move(IFCD.Name)), Hash(IFCD.Hash),
122         Regions(std::move(IFCD.Regions)) {}
123 
124   InputFunctionCoverageData(const InputFunctionCoverageData &) = delete;
125   InputFunctionCoverageData &
126   operator=(const InputFunctionCoverageData &) = delete;
127   InputFunctionCoverageData &operator=(InputFunctionCoverageData &&) = delete;
128 };
129 
130 struct CoverageMappingTest : ::testing::TestWithParam<std::pair<bool, bool>> {
131   bool UseMultipleReaders;
132   StringMap<unsigned> Files;
133   std::vector<InputFunctionCoverageData> InputFunctions;
134   std::vector<OutputFunctionCoverageData> OutputFunctions;
135 
136   InstrProfWriter ProfileWriter;
137   std::unique_ptr<IndexedInstrProfReader> ProfileReader;
138 
139   std::unique_ptr<CoverageMapping> LoadedCoverage;
140 
141   void SetUp() override {
142     ProfileWriter.setOutputSparse(GetParam().first);
143     UseMultipleReaders = GetParam().second;
144   }
145 
146   unsigned getGlobalFileIndex(StringRef Name) {
147     auto R = Files.find(Name);
148     if (R != Files.end())
149       return R->second;
150     unsigned Index = Files.size();
151     Files.try_emplace(Name, Index);
152     return Index;
153   }
154 
155   // Return the file index of file 'Name' for the current function.
156   // Add the file into the global map if necessary.
157   // See also InputFunctionCoverageData::ReverseVirtualFileMapping
158   // for additional comments.
159   unsigned getFileIndexForFunction(StringRef Name) {
160     unsigned GlobalIndex = getGlobalFileIndex(Name);
161     auto &CurrentFunctionFileMapping =
162         InputFunctions.back().ReverseVirtualFileMapping;
163     auto R = CurrentFunctionFileMapping.find(GlobalIndex);
164     if (R != CurrentFunctionFileMapping.end())
165       return R->second;
166     unsigned IndexInFunction = CurrentFunctionFileMapping.size();
167     CurrentFunctionFileMapping.insert(
168         std::make_pair(GlobalIndex, IndexInFunction));
169     return IndexInFunction;
170   }
171 
172   void startFunction(StringRef FuncName, uint64_t Hash) {
173     InputFunctions.emplace_back(FuncName.str(), Hash);
174   }
175 
176   void addCMR(Counter C, StringRef File, unsigned LS, unsigned CS, unsigned LE,
177               unsigned CE, bool Skipped = false) {
178     auto &Regions = InputFunctions.back().Regions;
179     unsigned FileID = getFileIndexForFunction(File);
180     Regions.push_back(
181         Skipped ? CounterMappingRegion::makeSkipped(FileID, LS, CS, LE, CE)
182                 : CounterMappingRegion::makeRegion(C, FileID, LS, CS, LE, CE));
183   }
184 
185   void addExpansionCMR(StringRef File, StringRef ExpandedFile, unsigned LS,
186                        unsigned CS, unsigned LE, unsigned CE) {
187     InputFunctions.back().Regions.push_back(CounterMappingRegion::makeExpansion(
188         getFileIndexForFunction(File), getFileIndexForFunction(ExpandedFile),
189         LS, CS, LE, CE));
190   }
191 
192   std::string writeCoverageRegions(InputFunctionCoverageData &Data) {
193     SmallVector<unsigned, 8> FileIDs(Data.ReverseVirtualFileMapping.size());
194     for (const auto &E : Data.ReverseVirtualFileMapping)
195       FileIDs[E.second] = E.first;
196     std::string Coverage;
197     llvm::raw_string_ostream OS(Coverage);
198     CoverageMappingWriter(FileIDs, None, Data.Regions).write(OS);
199     return OS.str();
200   }
201 
202   void readCoverageRegions(const std::string &Coverage,
203                            OutputFunctionCoverageData &Data) {
204     SmallVector<StringRef, 8> Filenames(Files.size());
205     for (const auto &E : Files)
206       Filenames[E.getValue()] = E.getKey();
207     std::vector<CounterExpression> Expressions;
208     RawCoverageMappingReader Reader(Coverage, Filenames, Data.Filenames,
209                                     Expressions, Data.Regions);
210     EXPECT_THAT_ERROR(Reader.read(), Succeeded());
211   }
212 
213   void writeAndReadCoverageRegions(bool EmitFilenames = true) {
214     OutputFunctions.resize(InputFunctions.size());
215     for (unsigned I = 0; I < InputFunctions.size(); ++I) {
216       std::string Regions = writeCoverageRegions(InputFunctions[I]);
217       readCoverageRegions(Regions, OutputFunctions[I]);
218       OutputFunctions[I].Name = InputFunctions[I].Name;
219       OutputFunctions[I].Hash = InputFunctions[I].Hash;
220       if (!EmitFilenames)
221         OutputFunctions[I].Filenames.clear();
222     }
223   }
224 
225   void readProfCounts() {
226     auto Profile = ProfileWriter.writeBuffer();
227     auto ReaderOrErr = IndexedInstrProfReader::create(std::move(Profile));
228     EXPECT_THAT_ERROR(ReaderOrErr.takeError(), Succeeded());
229     ProfileReader = std::move(ReaderOrErr.get());
230   }
231 
232   Expected<std::unique_ptr<CoverageMapping>> readOutputFunctions() {
233     std::vector<std::unique_ptr<CoverageMappingReader>> CoverageReaders;
234     if (UseMultipleReaders) {
235       for (const auto &OF : OutputFunctions) {
236         ArrayRef<OutputFunctionCoverageData> Funcs(OF);
237         CoverageReaders.push_back(
238             make_unique<CoverageMappingReaderMock>(Funcs));
239       }
240     } else {
241       ArrayRef<OutputFunctionCoverageData> Funcs(OutputFunctions);
242       CoverageReaders.push_back(
243           make_unique<CoverageMappingReaderMock>(Funcs));
244     }
245     return CoverageMapping::load(CoverageReaders, *ProfileReader);
246   }
247 
248   Error loadCoverageMapping(bool EmitFilenames = true) {
249     readProfCounts();
250     writeAndReadCoverageRegions(EmitFilenames);
251     auto CoverageOrErr = readOutputFunctions();
252     if (!CoverageOrErr)
253       return CoverageOrErr.takeError();
254     LoadedCoverage = std::move(CoverageOrErr.get());
255     return Error::success();
256   }
257 };
258 
259 TEST_P(CoverageMappingTest, basic_write_read) {
260   startFunction("func", 0x1234);
261   addCMR(Counter::getCounter(0), "foo", 1, 1, 1, 1);
262   addCMR(Counter::getCounter(1), "foo", 2, 1, 2, 2);
263   addCMR(Counter::getZero(),     "foo", 3, 1, 3, 4);
264   addCMR(Counter::getCounter(2), "foo", 4, 1, 4, 8);
265   addCMR(Counter::getCounter(3), "bar", 1, 2, 3, 4);
266 
267   writeAndReadCoverageRegions();
268   ASSERT_EQ(1u, InputFunctions.size());
269   ASSERT_EQ(1u, OutputFunctions.size());
270   InputFunctionCoverageData &Input = InputFunctions.back();
271   OutputFunctionCoverageData &Output = OutputFunctions.back();
272 
273   size_t N = makeArrayRef(Input.Regions).size();
274   ASSERT_EQ(N, Output.Regions.size());
275   for (size_t I = 0; I < N; ++I) {
276     ASSERT_EQ(Input.Regions[I].Count, Output.Regions[I].Count);
277     ASSERT_EQ(Input.Regions[I].FileID, Output.Regions[I].FileID);
278     ASSERT_EQ(Input.Regions[I].startLoc(), Output.Regions[I].startLoc());
279     ASSERT_EQ(Input.Regions[I].endLoc(), Output.Regions[I].endLoc());
280     ASSERT_EQ(Input.Regions[I].Kind, Output.Regions[I].Kind);
281   }
282 }
283 
284 TEST_P(CoverageMappingTest, correct_deserialize_for_more_than_two_files) {
285   const char *FileNames[] = {"bar", "baz", "foo"};
286   static const unsigned N = array_lengthof(FileNames);
287 
288   startFunction("func", 0x1234);
289   for (unsigned I = 0; I < N; ++I)
290     // Use LineStart to hold the index of the file name
291     // in order to preserve that information during possible sorting of CMRs.
292     addCMR(Counter::getCounter(0), FileNames[I], I, 1, I, 1);
293 
294   writeAndReadCoverageRegions();
295   ASSERT_EQ(1u, OutputFunctions.size());
296   OutputFunctionCoverageData &Output = OutputFunctions.back();
297 
298   ASSERT_EQ(N, Output.Regions.size());
299   ASSERT_EQ(N, Output.Filenames.size());
300 
301   for (unsigned I = 0; I < N; ++I) {
302     ASSERT_GT(N, Output.Regions[I].FileID);
303     ASSERT_GT(N, Output.Regions[I].LineStart);
304     EXPECT_EQ(FileNames[Output.Regions[I].LineStart],
305               Output.Filenames[Output.Regions[I].FileID]);
306   }
307 }
308 
309 static const auto Err = [](Error E) { FAIL(); };
310 
311 TEST_P(CoverageMappingTest, load_coverage_for_more_than_two_files) {
312   ProfileWriter.addRecord({"func", 0x1234, {0}}, Err);
313 
314   const char *FileNames[] = {"bar", "baz", "foo"};
315   static const unsigned N = array_lengthof(FileNames);
316 
317   startFunction("func", 0x1234);
318   for (unsigned I = 0; I < N; ++I)
319     // Use LineStart to hold the index of the file name
320     // in order to preserve that information during possible sorting of CMRs.
321     addCMR(Counter::getCounter(0), FileNames[I], I, 1, I, 1);
322 
323   EXPECT_THAT_ERROR(loadCoverageMapping(), Succeeded());
324 
325   for (unsigned I = 0; I < N; ++I) {
326     CoverageData Data = LoadedCoverage->getCoverageForFile(FileNames[I]);
327     ASSERT_TRUE(!Data.empty());
328     EXPECT_EQ(I, Data.begin()->Line);
329   }
330 }
331 
332 TEST_P(CoverageMappingTest, load_coverage_with_bogus_function_name) {
333   ProfileWriter.addRecord({"", 0x1234, {10}}, Err);
334   startFunction("", 0x1234);
335   addCMR(Counter::getCounter(0), "foo", 1, 1, 5, 5);
336   EXPECT_TRUE(ErrorEquals(coveragemap_error::malformed, loadCoverageMapping()));
337 }
338 
339 TEST_P(CoverageMappingTest, load_coverage_for_several_functions) {
340   ProfileWriter.addRecord({"func1", 0x1234, {10}}, Err);
341   ProfileWriter.addRecord({"func2", 0x2345, {20}}, Err);
342 
343   startFunction("func1", 0x1234);
344   addCMR(Counter::getCounter(0), "foo", 1, 1, 5, 5);
345 
346   startFunction("func2", 0x2345);
347   addCMR(Counter::getCounter(0), "bar", 2, 2, 6, 6);
348 
349   EXPECT_THAT_ERROR(loadCoverageMapping(), Succeeded());
350 
351   const auto FunctionRecords = LoadedCoverage->getCoveredFunctions();
352   EXPECT_EQ(2, std::distance(FunctionRecords.begin(), FunctionRecords.end()));
353   for (const auto &FunctionRecord : FunctionRecords) {
354     CoverageData Data = LoadedCoverage->getCoverageForFunction(FunctionRecord);
355     std::vector<CoverageSegment> Segments(Data.begin(), Data.end());
356     ASSERT_EQ(2U, Segments.size());
357     if (FunctionRecord.Name == "func1") {
358       EXPECT_EQ(CoverageSegment(1, 1, 10, true), Segments[0]);
359       EXPECT_EQ(CoverageSegment(5, 5, false), Segments[1]);
360     } else {
361       ASSERT_EQ("func2", FunctionRecord.Name);
362       EXPECT_EQ(CoverageSegment(2, 2, 20, true), Segments[0]);
363       EXPECT_EQ(CoverageSegment(6, 6, false), Segments[1]);
364     }
365   }
366 }
367 
368 TEST_P(CoverageMappingTest, create_combined_regions) {
369   ProfileWriter.addRecord({"func1", 0x1234, {1, 2, 3}}, Err);
370   startFunction("func1", 0x1234);
371 
372   // Given regions which start at the same location, emit a segment for the
373   // last region.
374   addCMR(Counter::getCounter(0), "file1", 1, 1, 2, 2);
375   addCMR(Counter::getCounter(1), "file1", 1, 1, 2, 2);
376   addCMR(Counter::getCounter(2), "file1", 1, 1, 2, 2);
377 
378   EXPECT_THAT_ERROR(loadCoverageMapping(), Succeeded());
379   const auto FunctionRecords = LoadedCoverage->getCoveredFunctions();
380   const auto &FunctionRecord = *FunctionRecords.begin();
381   CoverageData Data = LoadedCoverage->getCoverageForFunction(FunctionRecord);
382   std::vector<CoverageSegment> Segments(Data.begin(), Data.end());
383 
384   ASSERT_EQ(2U, Segments.size());
385   EXPECT_EQ(CoverageSegment(1, 1, 6, true), Segments[0]);
386   EXPECT_EQ(CoverageSegment(2, 2, false), Segments[1]);
387 }
388 
389 TEST_P(CoverageMappingTest, skipped_segments_have_no_count) {
390   ProfileWriter.addRecord({"func1", 0x1234, {1}}, Err);
391   startFunction("func1", 0x1234);
392 
393   addCMR(Counter::getCounter(0), "file1", 1, 1, 5, 5);
394   addCMR(Counter::getCounter(0), "file1", 5, 1, 5, 5, /*Skipped=*/true);
395 
396   EXPECT_THAT_ERROR(loadCoverageMapping(), Succeeded());
397   const auto FunctionRecords = LoadedCoverage->getCoveredFunctions();
398   const auto &FunctionRecord = *FunctionRecords.begin();
399   CoverageData Data = LoadedCoverage->getCoverageForFunction(FunctionRecord);
400   std::vector<CoverageSegment> Segments(Data.begin(), Data.end());
401 
402   ASSERT_EQ(3U, Segments.size());
403   EXPECT_EQ(CoverageSegment(1, 1, 1, true), Segments[0]);
404   EXPECT_EQ(CoverageSegment(5, 1, true), Segments[1]);
405   EXPECT_EQ(CoverageSegment(5, 5, false), Segments[2]);
406 }
407 
408 TEST_P(CoverageMappingTest, multiple_regions_end_after_parent_ends) {
409   ProfileWriter.addRecord({"func1", 0x1234, {1, 0}}, Err);
410   startFunction("func1", 0x1234);
411 
412   // 1| F{ a{
413   // 2|
414   // 3|    a} b{ c{
415   // 4|
416   // 5|    b}
417   // 6|
418   // 7| c} d{   e{
419   // 8|
420   // 9| d}      e} F}
421   addCMR(Counter::getCounter(0), "file1", 1, 1, 9, 9); // < F
422   addCMR(Counter::getCounter(0), "file1", 1, 1, 3, 5); // < a
423   addCMR(Counter::getCounter(0), "file1", 3, 5, 5, 4); // < b
424   addCMR(Counter::getCounter(1), "file1", 3, 5, 7, 3); // < c
425   addCMR(Counter::getCounter(1), "file1", 7, 3, 9, 2); // < d
426   addCMR(Counter::getCounter(1), "file1", 7, 7, 9, 7); // < e
427 
428   EXPECT_THAT_ERROR(loadCoverageMapping(), Succeeded());
429   const auto FunctionRecords = LoadedCoverage->getCoveredFunctions();
430   const auto &FunctionRecord = *FunctionRecords.begin();
431   CoverageData Data = LoadedCoverage->getCoverageForFunction(FunctionRecord);
432   std::vector<CoverageSegment> Segments(Data.begin(), Data.end());
433 
434   // Old output (not sorted or unique):
435   //   Segment at 1:1 with count 1
436   //   Segment at 1:1 with count 1
437   //   Segment at 3:5 with count 1
438   //   Segment at 3:5 with count 0
439   //   Segment at 3:5 with count 1
440   //   Segment at 5:4 with count 0
441   //   Segment at 7:3 with count 1
442   //   Segment at 7:3 with count 0
443   //   Segment at 7:7 with count 0
444   //   Segment at 9:7 with count 0
445   //   Segment at 9:2 with count 1
446   //   Top level segment at 9:9
447 
448   // New output (sorted and unique):
449   //   Segment at 1:1 (count = 1), RegionEntry
450   //   Segment at 3:5 (count = 1), RegionEntry
451   //   Segment at 5:4 (count = 0)
452   //   Segment at 7:3 (count = 0), RegionEntry
453   //   Segment at 7:7 (count = 0), RegionEntry
454   //   Segment at 9:2 (count = 0)
455   //   Segment at 9:7 (count = 1)
456   //   Segment at 9:9 (count = 0), Skipped
457 
458   ASSERT_EQ(8U, Segments.size());
459   EXPECT_EQ(CoverageSegment(1, 1, 1, true), Segments[0]);
460   EXPECT_EQ(CoverageSegment(3, 5, 1, true), Segments[1]);
461   EXPECT_EQ(CoverageSegment(5, 4, 0, false), Segments[2]);
462   EXPECT_EQ(CoverageSegment(7, 3, 0, true), Segments[3]);
463   EXPECT_EQ(CoverageSegment(7, 7, 0, true), Segments[4]);
464   EXPECT_EQ(CoverageSegment(9, 2, 0, false), Segments[5]);
465   EXPECT_EQ(CoverageSegment(9, 7, 1, false), Segments[6]);
466   EXPECT_EQ(CoverageSegment(9, 9, false), Segments[7]);
467 }
468 
469 TEST_P(CoverageMappingTest, multiple_completed_segments_at_same_loc) {
470   ProfileWriter.addRecord({"func1", 0x1234, {0, 1, 2}}, Err);
471   startFunction("func1", 0x1234);
472 
473   // PR35437
474   addCMR(Counter::getCounter(1), "file1", 2, 1, 18, 2);
475   addCMR(Counter::getCounter(0), "file1", 8, 12, 14, 6);
476   addCMR(Counter::getCounter(1), "file1", 9, 1, 14, 6);
477   addCMR(Counter::getCounter(2), "file1", 11, 13, 11, 14);
478 
479   EXPECT_THAT_ERROR(loadCoverageMapping(), Succeeded());
480   const auto FunctionRecords = LoadedCoverage->getCoveredFunctions();
481   const auto &FunctionRecord = *FunctionRecords.begin();
482   CoverageData Data = LoadedCoverage->getCoverageForFunction(FunctionRecord);
483   std::vector<CoverageSegment> Segments(Data.begin(), Data.end());
484 
485   ASSERT_EQ(6U, Segments.size());
486   EXPECT_EQ(CoverageSegment(2, 1, 1, true), Segments[0]);
487   EXPECT_EQ(CoverageSegment(8, 12, 0, true), Segments[1]);
488   EXPECT_EQ(CoverageSegment(9, 1, 1, true), Segments[2]);
489   EXPECT_EQ(CoverageSegment(11, 13, 2, true), Segments[3]);
490   // Use count=1 (from 9:1 -> 14:6), not count=0 (from 8:12 -> 14:6).
491   EXPECT_EQ(CoverageSegment(11, 14, 1, false), Segments[4]);
492   EXPECT_EQ(CoverageSegment(18, 2, false), Segments[5]);
493 }
494 
495 TEST_P(CoverageMappingTest, dont_emit_redundant_segments) {
496   ProfileWriter.addRecord({"func1", 0x1234, {1, 1}}, Err);
497   startFunction("func1", 0x1234);
498 
499   addCMR(Counter::getCounter(0), "file1", 1, 1, 4, 4);
500   addCMR(Counter::getCounter(1), "file1", 2, 2, 5, 5);
501   addCMR(Counter::getCounter(0), "file1", 3, 3, 6, 6);
502 
503   EXPECT_THAT_ERROR(loadCoverageMapping(), Succeeded());
504   const auto FunctionRecords = LoadedCoverage->getCoveredFunctions();
505   const auto &FunctionRecord = *FunctionRecords.begin();
506   CoverageData Data = LoadedCoverage->getCoverageForFunction(FunctionRecord);
507   std::vector<CoverageSegment> Segments(Data.begin(), Data.end());
508 
509   ASSERT_EQ(5U, Segments.size());
510   EXPECT_EQ(CoverageSegment(1, 1, 1, true), Segments[0]);
511   EXPECT_EQ(CoverageSegment(2, 2, 1, true), Segments[1]);
512   EXPECT_EQ(CoverageSegment(3, 3, 1, true), Segments[2]);
513   EXPECT_EQ(CoverageSegment(4, 4, 1, false), Segments[3]);
514   // A closing segment starting at 5:5 would be redundant: it would have the
515   // same count as the segment starting at 4:4, and has all the same metadata.
516   EXPECT_EQ(CoverageSegment(6, 6, false), Segments[4]);
517 }
518 
519 TEST_P(CoverageMappingTest, dont_emit_closing_segment_at_new_region_start) {
520   ProfileWriter.addRecord({"func1", 0x1234, {1}}, Err);
521   startFunction("func1", 0x1234);
522 
523   addCMR(Counter::getCounter(0), "file1", 1, 1, 6, 5);
524   addCMR(Counter::getCounter(0), "file1", 2, 2, 6, 5);
525   addCMR(Counter::getCounter(0), "file1", 3, 3, 6, 5);
526   addCMR(Counter::getCounter(0), "file1", 6, 5, 7, 7);
527 
528   EXPECT_THAT_ERROR(loadCoverageMapping(), Succeeded());
529   const auto FunctionRecords = LoadedCoverage->getCoveredFunctions();
530   const auto &FunctionRecord = *FunctionRecords.begin();
531   CoverageData Data = LoadedCoverage->getCoverageForFunction(FunctionRecord);
532   std::vector<CoverageSegment> Segments(Data.begin(), Data.end());
533 
534   ASSERT_EQ(5U, Segments.size());
535   EXPECT_EQ(CoverageSegment(1, 1, 1, true), Segments[0]);
536   EXPECT_EQ(CoverageSegment(2, 2, 1, true), Segments[1]);
537   EXPECT_EQ(CoverageSegment(3, 3, 1, true), Segments[2]);
538   EXPECT_EQ(CoverageSegment(6, 5, 1, true), Segments[3]);
539   // The old segment builder would get this wrong by emitting multiple segments
540   // which start at 6:5 (a few of which were skipped segments). We should just
541   // get a segment for the region entry.
542   EXPECT_EQ(CoverageSegment(7, 7, false), Segments[4]);
543 }
544 
545 TEST_P(CoverageMappingTest, handle_consecutive_regions_with_zero_length) {
546   ProfileWriter.addRecord({"func1", 0x1234, {1, 2}}, Err);
547   startFunction("func1", 0x1234);
548 
549   addCMR(Counter::getCounter(0), "file1", 1, 1, 1, 1);
550   addCMR(Counter::getCounter(1), "file1", 1, 1, 1, 1);
551   addCMR(Counter::getCounter(0), "file1", 1, 1, 1, 1);
552   addCMR(Counter::getCounter(1), "file1", 1, 1, 1, 1);
553   addCMR(Counter::getCounter(0), "file1", 1, 1, 1, 1);
554 
555   EXPECT_THAT_ERROR(loadCoverageMapping(), Succeeded());
556   const auto FunctionRecords = LoadedCoverage->getCoveredFunctions();
557   const auto &FunctionRecord = *FunctionRecords.begin();
558   CoverageData Data = LoadedCoverage->getCoverageForFunction(FunctionRecord);
559   std::vector<CoverageSegment> Segments(Data.begin(), Data.end());
560 
561   ASSERT_EQ(1U, Segments.size());
562   EXPECT_EQ(CoverageSegment(1, 1, true), Segments[0]);
563   // We need to get a skipped segment starting at 1:1. In this case there is
564   // also a region entry at 1:1.
565 }
566 
567 TEST_P(CoverageMappingTest, handle_sandwiched_zero_length_region) {
568   ProfileWriter.addRecord({"func1", 0x1234, {2, 1}}, Err);
569   startFunction("func1", 0x1234);
570 
571   addCMR(Counter::getCounter(0), "file1", 1, 5, 4, 4);
572   addCMR(Counter::getCounter(1), "file1", 1, 9, 1, 50);
573   addCMR(Counter::getCounter(1), "file1", 2, 7, 2, 34);
574   addCMR(Counter::getCounter(1), "file1", 3, 5, 3, 21);
575   addCMR(Counter::getCounter(1), "file1", 3, 21, 3, 21);
576   addCMR(Counter::getCounter(1), "file1", 4, 12, 4, 17);
577 
578   EXPECT_THAT_ERROR(loadCoverageMapping(), Succeeded());
579   const auto FunctionRecords = LoadedCoverage->getCoveredFunctions();
580   const auto &FunctionRecord = *FunctionRecords.begin();
581   CoverageData Data = LoadedCoverage->getCoverageForFunction(FunctionRecord);
582   std::vector<CoverageSegment> Segments(Data.begin(), Data.end());
583 
584   ASSERT_EQ(10U, Segments.size());
585   EXPECT_EQ(CoverageSegment(1, 5, 2, true), Segments[0]);
586   EXPECT_EQ(CoverageSegment(1, 9, 1, true), Segments[1]);
587   EXPECT_EQ(CoverageSegment(1, 50, 2, false), Segments[2]);
588   EXPECT_EQ(CoverageSegment(2, 7, 1, true), Segments[3]);
589   EXPECT_EQ(CoverageSegment(2, 34, 2, false), Segments[4]);
590   EXPECT_EQ(CoverageSegment(3, 5, 1, true), Segments[5]);
591   EXPECT_EQ(CoverageSegment(3, 21, 2, true), Segments[6]);
592   // Handle the zero-length region by creating a segment with its predecessor's
593   // count (i.e the count from 1:5 -> 4:4).
594   EXPECT_EQ(CoverageSegment(4, 4, false), Segments[7]);
595   // The area between 4:4 and 4:12 is skipped.
596   EXPECT_EQ(CoverageSegment(4, 12, 1, true), Segments[8]);
597   EXPECT_EQ(CoverageSegment(4, 17, false), Segments[9]);
598 }
599 
600 TEST_P(CoverageMappingTest, handle_last_completed_region) {
601   ProfileWriter.addRecord({"func1", 0x1234, {1, 2, 3, 4}}, Err);
602   startFunction("func1", 0x1234);
603 
604   addCMR(Counter::getCounter(0), "file1", 1, 1, 8, 8);
605   addCMR(Counter::getCounter(1), "file1", 2, 2, 5, 5);
606   addCMR(Counter::getCounter(2), "file1", 3, 3, 4, 4);
607   addCMR(Counter::getCounter(3), "file1", 6, 6, 7, 7);
608 
609   EXPECT_THAT_ERROR(loadCoverageMapping(), Succeeded());
610   const auto FunctionRecords = LoadedCoverage->getCoveredFunctions();
611   const auto &FunctionRecord = *FunctionRecords.begin();
612   CoverageData Data = LoadedCoverage->getCoverageForFunction(FunctionRecord);
613   std::vector<CoverageSegment> Segments(Data.begin(), Data.end());
614 
615   ASSERT_EQ(8U, Segments.size());
616   EXPECT_EQ(CoverageSegment(1, 1, 1, true), Segments[0]);
617   EXPECT_EQ(CoverageSegment(2, 2, 2, true), Segments[1]);
618   EXPECT_EQ(CoverageSegment(3, 3, 3, true), Segments[2]);
619   EXPECT_EQ(CoverageSegment(4, 4, 2, false), Segments[3]);
620   EXPECT_EQ(CoverageSegment(5, 5, 1, false), Segments[4]);
621   EXPECT_EQ(CoverageSegment(6, 6, 4, true), Segments[5]);
622   EXPECT_EQ(CoverageSegment(7, 7, 1, false), Segments[6]);
623   EXPECT_EQ(CoverageSegment(8, 8, false), Segments[7]);
624 }
625 
626 TEST_P(CoverageMappingTest, expansion_gets_first_counter) {
627   startFunction("func", 0x1234);
628   addCMR(Counter::getCounter(1), "foo", 10, 1, 10, 2);
629   // This starts earlier in "foo", so the expansion should get its counter.
630   addCMR(Counter::getCounter(2), "foo", 1, 1, 20, 1);
631   addExpansionCMR("bar", "foo", 3, 3, 3, 3);
632 
633   writeAndReadCoverageRegions();
634   ASSERT_EQ(1u, OutputFunctions.size());
635   OutputFunctionCoverageData &Output = OutputFunctions.back();
636 
637   ASSERT_EQ(CounterMappingRegion::ExpansionRegion, Output.Regions[2].Kind);
638   ASSERT_EQ(Counter::getCounter(2), Output.Regions[2].Count);
639   ASSERT_EQ(3U, Output.Regions[2].LineStart);
640 }
641 
642 TEST_P(CoverageMappingTest, basic_coverage_iteration) {
643   ProfileWriter.addRecord({"func", 0x1234, {30, 20, 10, 0}}, Err);
644 
645   startFunction("func", 0x1234);
646   addCMR(Counter::getCounter(0), "file1", 1, 1, 9, 9);
647   addCMR(Counter::getCounter(1), "file1", 1, 1, 4, 7);
648   addCMR(Counter::getCounter(2), "file1", 5, 8, 9, 1);
649   addCMR(Counter::getCounter(3), "file1", 10, 10, 11, 11);
650   EXPECT_THAT_ERROR(loadCoverageMapping(), Succeeded());
651 
652   CoverageData Data = LoadedCoverage->getCoverageForFile("file1");
653   std::vector<CoverageSegment> Segments(Data.begin(), Data.end());
654   ASSERT_EQ(7U, Segments.size());
655   ASSERT_EQ(CoverageSegment(1, 1, 20, true),  Segments[0]);
656   ASSERT_EQ(CoverageSegment(4, 7, 30, false), Segments[1]);
657   ASSERT_EQ(CoverageSegment(5, 8, 10, true),  Segments[2]);
658   ASSERT_EQ(CoverageSegment(9, 1, 30, false), Segments[3]);
659   ASSERT_EQ(CoverageSegment(9, 9, false),     Segments[4]);
660   ASSERT_EQ(CoverageSegment(10, 10, 0, true), Segments[5]);
661   ASSERT_EQ(CoverageSegment(11, 11, false),   Segments[6]);
662 }
663 
664 TEST_P(CoverageMappingTest, test_line_coverage_iterator) {
665   ProfileWriter.addRecord({"func", 0x1234, {30, 20, 10, 0}}, Err);
666 
667   startFunction("func", 0x1234);
668   addCMR(Counter::getCounter(0), "file1", 1, 1, 9, 9);
669   addCMR(Counter::getCounter(1), "file1", 1, 1, 4, 7);
670   addCMR(Counter::getCounter(2), "file1", 5, 8, 9, 1);
671   addCMR(Counter::getCounter(3), "file1", 10, 10, 11, 11);
672   EXPECT_THAT_ERROR(loadCoverageMapping(), Succeeded());
673 
674   CoverageData Data = LoadedCoverage->getCoverageForFile("file1");
675 
676   unsigned Line = 0;
677   unsigned LineCounts[] = {20, 20, 20, 20, 30, 10, 10, 10, 10, 0, 0};
678   for (const auto &LCS : getLineCoverageStats(Data)) {
679     ASSERT_EQ(Line + 1, LCS.getLine());
680     errs() << "Line: " << Line + 1 << ", count = " << LCS.getExecutionCount() << "\n";
681     ASSERT_EQ(LineCounts[Line], LCS.getExecutionCount());
682     ++Line;
683   }
684   ASSERT_EQ(11U, Line);
685 }
686 
687 TEST_P(CoverageMappingTest, uncovered_function) {
688   startFunction("func", 0x1234);
689   addCMR(Counter::getZero(), "file1", 1, 2, 3, 4);
690   EXPECT_THAT_ERROR(loadCoverageMapping(), Succeeded());
691 
692   CoverageData Data = LoadedCoverage->getCoverageForFile("file1");
693   std::vector<CoverageSegment> Segments(Data.begin(), Data.end());
694   ASSERT_EQ(2U, Segments.size());
695   ASSERT_EQ(CoverageSegment(1, 2, 0, true), Segments[0]);
696   ASSERT_EQ(CoverageSegment(3, 4, false),   Segments[1]);
697 }
698 
699 TEST_P(CoverageMappingTest, uncovered_function_with_mapping) {
700   startFunction("func", 0x1234);
701   addCMR(Counter::getCounter(0), "file1", 1, 1, 9, 9);
702   addCMR(Counter::getCounter(1), "file1", 1, 1, 4, 7);
703   EXPECT_THAT_ERROR(loadCoverageMapping(), Succeeded());
704 
705   CoverageData Data = LoadedCoverage->getCoverageForFile("file1");
706   std::vector<CoverageSegment> Segments(Data.begin(), Data.end());
707   ASSERT_EQ(3U, Segments.size());
708   ASSERT_EQ(CoverageSegment(1, 1, 0, true),  Segments[0]);
709   ASSERT_EQ(CoverageSegment(4, 7, 0, false), Segments[1]);
710   ASSERT_EQ(CoverageSegment(9, 9, false),    Segments[2]);
711 }
712 
713 TEST_P(CoverageMappingTest, combine_regions) {
714   ProfileWriter.addRecord({"func", 0x1234, {10, 20, 30}}, Err);
715 
716   startFunction("func", 0x1234);
717   addCMR(Counter::getCounter(0), "file1", 1, 1, 9, 9);
718   addCMR(Counter::getCounter(1), "file1", 3, 3, 4, 4);
719   addCMR(Counter::getCounter(2), "file1", 3, 3, 4, 4);
720   EXPECT_THAT_ERROR(loadCoverageMapping(), Succeeded());
721 
722   CoverageData Data = LoadedCoverage->getCoverageForFile("file1");
723   std::vector<CoverageSegment> Segments(Data.begin(), Data.end());
724   ASSERT_EQ(4U, Segments.size());
725   ASSERT_EQ(CoverageSegment(1, 1, 10, true), Segments[0]);
726   ASSERT_EQ(CoverageSegment(3, 3, 50, true), Segments[1]);
727   ASSERT_EQ(CoverageSegment(4, 4, 10, false), Segments[2]);
728   ASSERT_EQ(CoverageSegment(9, 9, false), Segments[3]);
729 }
730 
731 TEST_P(CoverageMappingTest, restore_combined_counter_after_nested_region) {
732   ProfileWriter.addRecord({"func", 0x1234, {10, 20, 40}}, Err);
733 
734   startFunction("func", 0x1234);
735   addCMR(Counter::getCounter(0), "file1", 1, 1, 9, 9);
736   addCMR(Counter::getCounter(1), "file1", 1, 1, 9, 9);
737   addCMR(Counter::getCounter(2), "file1", 3, 3, 5, 5);
738   EXPECT_THAT_ERROR(loadCoverageMapping(), Succeeded());
739 
740   CoverageData Data = LoadedCoverage->getCoverageForFile("file1");
741   std::vector<CoverageSegment> Segments(Data.begin(), Data.end());
742   ASSERT_EQ(4U, Segments.size());
743   EXPECT_EQ(CoverageSegment(1, 1, 30, true), Segments[0]);
744   EXPECT_EQ(CoverageSegment(3, 3, 40, true), Segments[1]);
745   EXPECT_EQ(CoverageSegment(5, 5, 30, false), Segments[2]);
746   EXPECT_EQ(CoverageSegment(9, 9, false), Segments[3]);
747 }
748 
749 // If CodeRegions and ExpansionRegions cover the same area,
750 // only counts of CodeRegions should be used.
751 TEST_P(CoverageMappingTest, dont_combine_expansions) {
752   ProfileWriter.addRecord({"func", 0x1234, {10, 20}}, Err);
753   ProfileWriter.addRecord({"func", 0x1234, {0, 0}}, Err);
754 
755   startFunction("func", 0x1234);
756   addCMR(Counter::getCounter(0), "file1", 1, 1, 9, 9);
757   addCMR(Counter::getCounter(1), "file1", 3, 3, 4, 4);
758   addCMR(Counter::getCounter(1), "include1", 6, 6, 7, 7);
759   addExpansionCMR("file1", "include1", 3, 3, 4, 4);
760   EXPECT_THAT_ERROR(loadCoverageMapping(), Succeeded());
761 
762   CoverageData Data = LoadedCoverage->getCoverageForFile("file1");
763   std::vector<CoverageSegment> Segments(Data.begin(), Data.end());
764   ASSERT_EQ(4U, Segments.size());
765   ASSERT_EQ(CoverageSegment(1, 1, 10, true), Segments[0]);
766   ASSERT_EQ(CoverageSegment(3, 3, 20, true), Segments[1]);
767   ASSERT_EQ(CoverageSegment(4, 4, 10, false), Segments[2]);
768   ASSERT_EQ(CoverageSegment(9, 9, false), Segments[3]);
769 }
770 
771 // If an area is covered only by ExpansionRegions, they should be combinated.
772 TEST_P(CoverageMappingTest, combine_expansions) {
773   ProfileWriter.addRecord({"func", 0x1234, {2, 3, 7}}, Err);
774 
775   startFunction("func", 0x1234);
776   addCMR(Counter::getCounter(1), "include1", 1, 1, 1, 10);
777   addCMR(Counter::getCounter(2), "include2", 1, 1, 1, 10);
778   addCMR(Counter::getCounter(0), "file", 1, 1, 5, 5);
779   addExpansionCMR("file", "include1", 3, 1, 3, 5);
780   addExpansionCMR("file", "include2", 3, 1, 3, 5);
781 
782   EXPECT_THAT_ERROR(loadCoverageMapping(), Succeeded());
783 
784   CoverageData Data = LoadedCoverage->getCoverageForFile("file");
785   std::vector<CoverageSegment> Segments(Data.begin(), Data.end());
786   ASSERT_EQ(4U, Segments.size());
787   EXPECT_EQ(CoverageSegment(1, 1, 2, true), Segments[0]);
788   EXPECT_EQ(CoverageSegment(3, 1, 10, true), Segments[1]);
789   EXPECT_EQ(CoverageSegment(3, 5, 2, false), Segments[2]);
790   EXPECT_EQ(CoverageSegment(5, 5, false), Segments[3]);
791 }
792 
793 TEST_P(CoverageMappingTest, strip_filename_prefix) {
794   ProfileWriter.addRecord({"file1:func", 0x1234, {0}}, Err);
795 
796   startFunction("file1:func", 0x1234);
797   addCMR(Counter::getCounter(0), "file1", 1, 1, 9, 9);
798   EXPECT_THAT_ERROR(loadCoverageMapping(), Succeeded());
799 
800   std::vector<std::string> Names;
801   for (const auto &Func : LoadedCoverage->getCoveredFunctions())
802     Names.push_back(Func.Name);
803   ASSERT_EQ(1U, Names.size());
804   ASSERT_EQ("func", Names[0]);
805 }
806 
807 TEST_P(CoverageMappingTest, strip_unknown_filename_prefix) {
808   ProfileWriter.addRecord({"<unknown>:func", 0x1234, {0}}, Err);
809 
810   startFunction("<unknown>:func", 0x1234);
811   addCMR(Counter::getCounter(0), "", 1, 1, 9, 9);
812   EXPECT_THAT_ERROR(loadCoverageMapping(/*EmitFilenames=*/false), Succeeded());
813 
814   std::vector<std::string> Names;
815   for (const auto &Func : LoadedCoverage->getCoveredFunctions())
816     Names.push_back(Func.Name);
817   ASSERT_EQ(1U, Names.size());
818   ASSERT_EQ("func", Names[0]);
819 }
820 
821 TEST_P(CoverageMappingTest, dont_detect_false_instantiations) {
822   ProfileWriter.addRecord({"foo", 0x1234, {10}}, Err);
823   ProfileWriter.addRecord({"bar", 0x2345, {20}}, Err);
824 
825   startFunction("foo", 0x1234);
826   addCMR(Counter::getCounter(0), "expanded", 1, 1, 1, 10);
827   addExpansionCMR("main", "expanded", 4, 1, 4, 5);
828 
829   startFunction("bar", 0x2345);
830   addCMR(Counter::getCounter(0), "expanded", 1, 1, 1, 10);
831   addExpansionCMR("main", "expanded", 9, 1, 9, 5);
832 
833   EXPECT_THAT_ERROR(loadCoverageMapping(), Succeeded());
834 
835   std::vector<InstantiationGroup> InstantiationGroups =
836       LoadedCoverage->getInstantiationGroups("expanded");
837   for (const auto &Group : InstantiationGroups)
838     ASSERT_EQ(Group.size(), 1U);
839 }
840 
841 TEST_P(CoverageMappingTest, load_coverage_for_expanded_file) {
842   ProfileWriter.addRecord({"func", 0x1234, {10}}, Err);
843 
844   startFunction("func", 0x1234);
845   addCMR(Counter::getCounter(0), "expanded", 1, 1, 1, 10);
846   addExpansionCMR("main", "expanded", 4, 1, 4, 5);
847 
848   EXPECT_THAT_ERROR(loadCoverageMapping(), Succeeded());
849 
850   CoverageData Data = LoadedCoverage->getCoverageForFile("expanded");
851   std::vector<CoverageSegment> Segments(Data.begin(), Data.end());
852   ASSERT_EQ(2U, Segments.size());
853   EXPECT_EQ(CoverageSegment(1, 1, 10, true), Segments[0]);
854   EXPECT_EQ(CoverageSegment(1, 10, false), Segments[1]);
855 }
856 
857 TEST_P(CoverageMappingTest, skip_duplicate_function_record) {
858   ProfileWriter.addRecord({"func", 0x1234, {1}}, Err);
859 
860   startFunction("func", 0x1234);
861   addCMR(Counter::getCounter(0), "file1", 1, 1, 9, 9);
862 
863   startFunction("func", 0x1234);
864   addCMR(Counter::getCounter(0), "file1", 1, 1, 9, 9);
865 
866   EXPECT_THAT_ERROR(loadCoverageMapping(), Succeeded());
867 
868   auto Funcs = LoadedCoverage->getCoveredFunctions();
869   unsigned NumFuncs = std::distance(Funcs.begin(), Funcs.end());
870   ASSERT_EQ(1U, NumFuncs);
871 }
872 
873 // FIXME: Use ::testing::Combine() when llvm updates its copy of googletest.
874 INSTANTIATE_TEST_CASE_P(ParameterizedCovMapTest, CoverageMappingTest,
875                         ::testing::Values(std::pair<bool, bool>({false, false}),
876                                           std::pair<bool, bool>({false, true}),
877                                           std::pair<bool, bool>({true, false}),
878                                           std::pair<bool, bool>({true, true})),);
879 
880 } // end anonymous namespace
881