xref: /llvm-project/llvm/unittests/ProfileData/CoverageMappingTest.cpp (revision f5f153dd6f1944c4bcca4a1485df3098eef13096)
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, dont_emit_redundant_segments) {
470   ProfileWriter.addRecord({"func1", 0x1234, {1, 1}}, Err);
471   startFunction("func1", 0x1234);
472 
473   addCMR(Counter::getCounter(0), "file1", 1, 1, 4, 4);
474   addCMR(Counter::getCounter(1), "file1", 2, 2, 5, 5);
475   addCMR(Counter::getCounter(0), "file1", 3, 3, 6, 6);
476 
477   EXPECT_THAT_ERROR(loadCoverageMapping(), Succeeded());
478   const auto FunctionRecords = LoadedCoverage->getCoveredFunctions();
479   const auto &FunctionRecord = *FunctionRecords.begin();
480   CoverageData Data = LoadedCoverage->getCoverageForFunction(FunctionRecord);
481   std::vector<CoverageSegment> Segments(Data.begin(), Data.end());
482 
483   ASSERT_EQ(5U, Segments.size());
484   EXPECT_EQ(CoverageSegment(1, 1, 1, true), Segments[0]);
485   EXPECT_EQ(CoverageSegment(2, 2, 1, true), Segments[1]);
486   EXPECT_EQ(CoverageSegment(3, 3, 1, true), Segments[2]);
487   EXPECT_EQ(CoverageSegment(4, 4, 1, false), Segments[3]);
488   // A closing segment starting at 5:5 would be redundant: it would have the
489   // same count as the segment starting at 4:4, and has all the same metadata.
490   EXPECT_EQ(CoverageSegment(6, 6, false), Segments[4]);
491 }
492 
493 TEST_P(CoverageMappingTest, dont_emit_closing_segment_at_new_region_start) {
494   ProfileWriter.addRecord({"func1", 0x1234, {1}}, Err);
495   startFunction("func1", 0x1234);
496 
497   addCMR(Counter::getCounter(0), "file1", 1, 1, 6, 5);
498   addCMR(Counter::getCounter(0), "file1", 2, 2, 6, 5);
499   addCMR(Counter::getCounter(0), "file1", 3, 3, 6, 5);
500   addCMR(Counter::getCounter(0), "file1", 6, 5, 7, 7);
501 
502   EXPECT_THAT_ERROR(loadCoverageMapping(), Succeeded());
503   const auto FunctionRecords = LoadedCoverage->getCoveredFunctions();
504   const auto &FunctionRecord = *FunctionRecords.begin();
505   CoverageData Data = LoadedCoverage->getCoverageForFunction(FunctionRecord);
506   std::vector<CoverageSegment> Segments(Data.begin(), Data.end());
507 
508   ASSERT_EQ(5U, Segments.size());
509   EXPECT_EQ(CoverageSegment(1, 1, 1, true), Segments[0]);
510   EXPECT_EQ(CoverageSegment(2, 2, 1, true), Segments[1]);
511   EXPECT_EQ(CoverageSegment(3, 3, 1, true), Segments[2]);
512   EXPECT_EQ(CoverageSegment(6, 5, 1, true), Segments[3]);
513   // The old segment builder would get this wrong by emitting multiple segments
514   // which start at 6:5 (a few of which were skipped segments). We should just
515   // get a segment for the region entry.
516   EXPECT_EQ(CoverageSegment(7, 7, false), Segments[4]);
517 }
518 
519 TEST_P(CoverageMappingTest, handle_consecutive_regions_with_zero_length) {
520   ProfileWriter.addRecord({"func1", 0x1234, {1, 2}}, Err);
521   startFunction("func1", 0x1234);
522 
523   addCMR(Counter::getCounter(0), "file1", 1, 1, 1, 1);
524   addCMR(Counter::getCounter(1), "file1", 1, 1, 1, 1);
525   addCMR(Counter::getCounter(0), "file1", 1, 1, 1, 1);
526   addCMR(Counter::getCounter(1), "file1", 1, 1, 1, 1);
527   addCMR(Counter::getCounter(0), "file1", 1, 1, 1, 1);
528 
529   EXPECT_THAT_ERROR(loadCoverageMapping(), Succeeded());
530   const auto FunctionRecords = LoadedCoverage->getCoveredFunctions();
531   const auto &FunctionRecord = *FunctionRecords.begin();
532   CoverageData Data = LoadedCoverage->getCoverageForFunction(FunctionRecord);
533   std::vector<CoverageSegment> Segments(Data.begin(), Data.end());
534 
535   ASSERT_EQ(1U, Segments.size());
536   EXPECT_EQ(CoverageSegment(1, 1, true), Segments[0]);
537   // We need to get a skipped segment starting at 1:1. In this case there is
538   // also a region entry at 1:1.
539 }
540 
541 TEST_P(CoverageMappingTest, handle_sandwiched_zero_length_region) {
542   ProfileWriter.addRecord({"func1", 0x1234, {2, 1}}, Err);
543   startFunction("func1", 0x1234);
544 
545   addCMR(Counter::getCounter(0), "file1", 1, 5, 4, 4);
546   addCMR(Counter::getCounter(1), "file1", 1, 9, 1, 50);
547   addCMR(Counter::getCounter(1), "file1", 2, 7, 2, 34);
548   addCMR(Counter::getCounter(1), "file1", 3, 5, 3, 21);
549   addCMR(Counter::getCounter(1), "file1", 3, 21, 3, 21);
550   addCMR(Counter::getCounter(1), "file1", 4, 12, 4, 17);
551 
552   EXPECT_THAT_ERROR(loadCoverageMapping(), Succeeded());
553   const auto FunctionRecords = LoadedCoverage->getCoveredFunctions();
554   const auto &FunctionRecord = *FunctionRecords.begin();
555   CoverageData Data = LoadedCoverage->getCoverageForFunction(FunctionRecord);
556   std::vector<CoverageSegment> Segments(Data.begin(), Data.end());
557 
558   ASSERT_EQ(10U, Segments.size());
559   EXPECT_EQ(CoverageSegment(1, 5, 2, true), Segments[0]);
560   EXPECT_EQ(CoverageSegment(1, 9, 1, true), Segments[1]);
561   EXPECT_EQ(CoverageSegment(1, 50, 2, false), Segments[2]);
562   EXPECT_EQ(CoverageSegment(2, 7, 1, true), Segments[3]);
563   EXPECT_EQ(CoverageSegment(2, 34, 2, false), Segments[4]);
564   EXPECT_EQ(CoverageSegment(3, 5, 1, true), Segments[5]);
565   EXPECT_EQ(CoverageSegment(3, 21, 2, true), Segments[6]);
566   // Handle the zero-length region by creating a segment with its predecessor's
567   // count (i.e the count from 1:5 -> 4:4).
568   EXPECT_EQ(CoverageSegment(4, 4, false), Segments[7]);
569   // The area between 4:4 and 4:12 is skipped.
570   EXPECT_EQ(CoverageSegment(4, 12, 1, true), Segments[8]);
571   EXPECT_EQ(CoverageSegment(4, 17, false), Segments[9]);
572 }
573 
574 TEST_P(CoverageMappingTest, handle_last_completed_region) {
575   ProfileWriter.addRecord({"func1", 0x1234, {1, 2, 3, 4}}, Err);
576   startFunction("func1", 0x1234);
577 
578   addCMR(Counter::getCounter(0), "file1", 1, 1, 8, 8);
579   addCMR(Counter::getCounter(1), "file1", 2, 2, 5, 5);
580   addCMR(Counter::getCounter(2), "file1", 3, 3, 4, 4);
581   addCMR(Counter::getCounter(3), "file1", 6, 6, 7, 7);
582 
583   EXPECT_THAT_ERROR(loadCoverageMapping(), Succeeded());
584   const auto FunctionRecords = LoadedCoverage->getCoveredFunctions();
585   const auto &FunctionRecord = *FunctionRecords.begin();
586   CoverageData Data = LoadedCoverage->getCoverageForFunction(FunctionRecord);
587   std::vector<CoverageSegment> Segments(Data.begin(), Data.end());
588 
589   ASSERT_EQ(8U, Segments.size());
590   EXPECT_EQ(CoverageSegment(1, 1, 1, true), Segments[0]);
591   EXPECT_EQ(CoverageSegment(2, 2, 2, true), Segments[1]);
592   EXPECT_EQ(CoverageSegment(3, 3, 3, true), Segments[2]);
593   EXPECT_EQ(CoverageSegment(4, 4, 2, false), Segments[3]);
594   EXPECT_EQ(CoverageSegment(5, 5, 1, false), Segments[4]);
595   EXPECT_EQ(CoverageSegment(6, 6, 4, true), Segments[5]);
596   EXPECT_EQ(CoverageSegment(7, 7, 1, false), Segments[6]);
597   EXPECT_EQ(CoverageSegment(8, 8, false), Segments[7]);
598 }
599 
600 TEST_P(CoverageMappingTest, expansion_gets_first_counter) {
601   startFunction("func", 0x1234);
602   addCMR(Counter::getCounter(1), "foo", 10, 1, 10, 2);
603   // This starts earlier in "foo", so the expansion should get its counter.
604   addCMR(Counter::getCounter(2), "foo", 1, 1, 20, 1);
605   addExpansionCMR("bar", "foo", 3, 3, 3, 3);
606 
607   writeAndReadCoverageRegions();
608   ASSERT_EQ(1u, OutputFunctions.size());
609   OutputFunctionCoverageData &Output = OutputFunctions.back();
610 
611   ASSERT_EQ(CounterMappingRegion::ExpansionRegion, Output.Regions[2].Kind);
612   ASSERT_EQ(Counter::getCounter(2), Output.Regions[2].Count);
613   ASSERT_EQ(3U, Output.Regions[2].LineStart);
614 }
615 
616 TEST_P(CoverageMappingTest, basic_coverage_iteration) {
617   ProfileWriter.addRecord({"func", 0x1234, {30, 20, 10, 0}}, Err);
618 
619   startFunction("func", 0x1234);
620   addCMR(Counter::getCounter(0), "file1", 1, 1, 9, 9);
621   addCMR(Counter::getCounter(1), "file1", 1, 1, 4, 7);
622   addCMR(Counter::getCounter(2), "file1", 5, 8, 9, 1);
623   addCMR(Counter::getCounter(3), "file1", 10, 10, 11, 11);
624   EXPECT_THAT_ERROR(loadCoverageMapping(), Succeeded());
625 
626   CoverageData Data = LoadedCoverage->getCoverageForFile("file1");
627   std::vector<CoverageSegment> Segments(Data.begin(), Data.end());
628   ASSERT_EQ(7U, Segments.size());
629   ASSERT_EQ(CoverageSegment(1, 1, 20, true),  Segments[0]);
630   ASSERT_EQ(CoverageSegment(4, 7, 30, false), Segments[1]);
631   ASSERT_EQ(CoverageSegment(5, 8, 10, true),  Segments[2]);
632   ASSERT_EQ(CoverageSegment(9, 1, 30, false), Segments[3]);
633   ASSERT_EQ(CoverageSegment(9, 9, false),     Segments[4]);
634   ASSERT_EQ(CoverageSegment(10, 10, 0, true), Segments[5]);
635   ASSERT_EQ(CoverageSegment(11, 11, false),   Segments[6]);
636 }
637 
638 TEST_P(CoverageMappingTest, test_line_coverage_iterator) {
639   ProfileWriter.addRecord({"func", 0x1234, {30, 20, 10, 0}}, Err);
640 
641   startFunction("func", 0x1234);
642   addCMR(Counter::getCounter(0), "file1", 1, 1, 9, 9);
643   addCMR(Counter::getCounter(1), "file1", 1, 1, 4, 7);
644   addCMR(Counter::getCounter(2), "file1", 5, 8, 9, 1);
645   addCMR(Counter::getCounter(3), "file1", 10, 10, 11, 11);
646   EXPECT_THAT_ERROR(loadCoverageMapping(), Succeeded());
647 
648   CoverageData Data = LoadedCoverage->getCoverageForFile("file1");
649 
650   unsigned Line = 0;
651   unsigned LineCounts[] = {20, 20, 20, 20, 10, 10, 10, 10, 10, 0, 0};
652   for (const auto &LCS : getLineCoverageStats(Data)) {
653     ASSERT_EQ(Line + 1, LCS.getLine());
654     ASSERT_EQ(LineCounts[Line], LCS.getExecutionCount());
655     ++Line;
656   }
657   ASSERT_EQ(11U, Line);
658 }
659 
660 TEST_P(CoverageMappingTest, uncovered_function) {
661   startFunction("func", 0x1234);
662   addCMR(Counter::getZero(), "file1", 1, 2, 3, 4);
663   EXPECT_THAT_ERROR(loadCoverageMapping(), Succeeded());
664 
665   CoverageData Data = LoadedCoverage->getCoverageForFile("file1");
666   std::vector<CoverageSegment> Segments(Data.begin(), Data.end());
667   ASSERT_EQ(2U, Segments.size());
668   ASSERT_EQ(CoverageSegment(1, 2, 0, true), Segments[0]);
669   ASSERT_EQ(CoverageSegment(3, 4, false),   Segments[1]);
670 }
671 
672 TEST_P(CoverageMappingTest, uncovered_function_with_mapping) {
673   startFunction("func", 0x1234);
674   addCMR(Counter::getCounter(0), "file1", 1, 1, 9, 9);
675   addCMR(Counter::getCounter(1), "file1", 1, 1, 4, 7);
676   EXPECT_THAT_ERROR(loadCoverageMapping(), Succeeded());
677 
678   CoverageData Data = LoadedCoverage->getCoverageForFile("file1");
679   std::vector<CoverageSegment> Segments(Data.begin(), Data.end());
680   ASSERT_EQ(3U, Segments.size());
681   ASSERT_EQ(CoverageSegment(1, 1, 0, true),  Segments[0]);
682   ASSERT_EQ(CoverageSegment(4, 7, 0, false), Segments[1]);
683   ASSERT_EQ(CoverageSegment(9, 9, false),    Segments[2]);
684 }
685 
686 TEST_P(CoverageMappingTest, combine_regions) {
687   ProfileWriter.addRecord({"func", 0x1234, {10, 20, 30}}, Err);
688 
689   startFunction("func", 0x1234);
690   addCMR(Counter::getCounter(0), "file1", 1, 1, 9, 9);
691   addCMR(Counter::getCounter(1), "file1", 3, 3, 4, 4);
692   addCMR(Counter::getCounter(2), "file1", 3, 3, 4, 4);
693   EXPECT_THAT_ERROR(loadCoverageMapping(), Succeeded());
694 
695   CoverageData Data = LoadedCoverage->getCoverageForFile("file1");
696   std::vector<CoverageSegment> Segments(Data.begin(), Data.end());
697   ASSERT_EQ(4U, Segments.size());
698   ASSERT_EQ(CoverageSegment(1, 1, 10, true), Segments[0]);
699   ASSERT_EQ(CoverageSegment(3, 3, 50, true), Segments[1]);
700   ASSERT_EQ(CoverageSegment(4, 4, 10, false), Segments[2]);
701   ASSERT_EQ(CoverageSegment(9, 9, false), Segments[3]);
702 }
703 
704 TEST_P(CoverageMappingTest, restore_combined_counter_after_nested_region) {
705   ProfileWriter.addRecord({"func", 0x1234, {10, 20, 40}}, Err);
706 
707   startFunction("func", 0x1234);
708   addCMR(Counter::getCounter(0), "file1", 1, 1, 9, 9);
709   addCMR(Counter::getCounter(1), "file1", 1, 1, 9, 9);
710   addCMR(Counter::getCounter(2), "file1", 3, 3, 5, 5);
711   EXPECT_THAT_ERROR(loadCoverageMapping(), Succeeded());
712 
713   CoverageData Data = LoadedCoverage->getCoverageForFile("file1");
714   std::vector<CoverageSegment> Segments(Data.begin(), Data.end());
715   ASSERT_EQ(4U, Segments.size());
716   EXPECT_EQ(CoverageSegment(1, 1, 30, true), Segments[0]);
717   EXPECT_EQ(CoverageSegment(3, 3, 40, true), Segments[1]);
718   EXPECT_EQ(CoverageSegment(5, 5, 30, false), Segments[2]);
719   EXPECT_EQ(CoverageSegment(9, 9, false), Segments[3]);
720 }
721 
722 // If CodeRegions and ExpansionRegions cover the same area,
723 // only counts of CodeRegions should be used.
724 TEST_P(CoverageMappingTest, dont_combine_expansions) {
725   ProfileWriter.addRecord({"func", 0x1234, {10, 20}}, Err);
726   ProfileWriter.addRecord({"func", 0x1234, {0, 0}}, Err);
727 
728   startFunction("func", 0x1234);
729   addCMR(Counter::getCounter(0), "file1", 1, 1, 9, 9);
730   addCMR(Counter::getCounter(1), "file1", 3, 3, 4, 4);
731   addCMR(Counter::getCounter(1), "include1", 6, 6, 7, 7);
732   addExpansionCMR("file1", "include1", 3, 3, 4, 4);
733   EXPECT_THAT_ERROR(loadCoverageMapping(), Succeeded());
734 
735   CoverageData Data = LoadedCoverage->getCoverageForFile("file1");
736   std::vector<CoverageSegment> Segments(Data.begin(), Data.end());
737   ASSERT_EQ(4U, Segments.size());
738   ASSERT_EQ(CoverageSegment(1, 1, 10, true), Segments[0]);
739   ASSERT_EQ(CoverageSegment(3, 3, 20, true), Segments[1]);
740   ASSERT_EQ(CoverageSegment(4, 4, 10, false), Segments[2]);
741   ASSERT_EQ(CoverageSegment(9, 9, false), Segments[3]);
742 }
743 
744 // If an area is covered only by ExpansionRegions, they should be combinated.
745 TEST_P(CoverageMappingTest, combine_expansions) {
746   ProfileWriter.addRecord({"func", 0x1234, {2, 3, 7}}, Err);
747 
748   startFunction("func", 0x1234);
749   addCMR(Counter::getCounter(1), "include1", 1, 1, 1, 10);
750   addCMR(Counter::getCounter(2), "include2", 1, 1, 1, 10);
751   addCMR(Counter::getCounter(0), "file", 1, 1, 5, 5);
752   addExpansionCMR("file", "include1", 3, 1, 3, 5);
753   addExpansionCMR("file", "include2", 3, 1, 3, 5);
754 
755   EXPECT_THAT_ERROR(loadCoverageMapping(), Succeeded());
756 
757   CoverageData Data = LoadedCoverage->getCoverageForFile("file");
758   std::vector<CoverageSegment> Segments(Data.begin(), Data.end());
759   ASSERT_EQ(4U, Segments.size());
760   EXPECT_EQ(CoverageSegment(1, 1, 2, true), Segments[0]);
761   EXPECT_EQ(CoverageSegment(3, 1, 10, true), Segments[1]);
762   EXPECT_EQ(CoverageSegment(3, 5, 2, false), Segments[2]);
763   EXPECT_EQ(CoverageSegment(5, 5, false), Segments[3]);
764 }
765 
766 TEST_P(CoverageMappingTest, strip_filename_prefix) {
767   ProfileWriter.addRecord({"file1:func", 0x1234, {0}}, Err);
768 
769   startFunction("file1:func", 0x1234);
770   addCMR(Counter::getCounter(0), "file1", 1, 1, 9, 9);
771   EXPECT_THAT_ERROR(loadCoverageMapping(), Succeeded());
772 
773   std::vector<std::string> Names;
774   for (const auto &Func : LoadedCoverage->getCoveredFunctions())
775     Names.push_back(Func.Name);
776   ASSERT_EQ(1U, Names.size());
777   ASSERT_EQ("func", Names[0]);
778 }
779 
780 TEST_P(CoverageMappingTest, strip_unknown_filename_prefix) {
781   ProfileWriter.addRecord({"<unknown>:func", 0x1234, {0}}, Err);
782 
783   startFunction("<unknown>:func", 0x1234);
784   addCMR(Counter::getCounter(0), "", 1, 1, 9, 9);
785   EXPECT_THAT_ERROR(loadCoverageMapping(/*EmitFilenames=*/false), Succeeded());
786 
787   std::vector<std::string> Names;
788   for (const auto &Func : LoadedCoverage->getCoveredFunctions())
789     Names.push_back(Func.Name);
790   ASSERT_EQ(1U, Names.size());
791   ASSERT_EQ("func", Names[0]);
792 }
793 
794 TEST_P(CoverageMappingTest, dont_detect_false_instantiations) {
795   ProfileWriter.addRecord({"foo", 0x1234, {10}}, Err);
796   ProfileWriter.addRecord({"bar", 0x2345, {20}}, Err);
797 
798   startFunction("foo", 0x1234);
799   addCMR(Counter::getCounter(0), "expanded", 1, 1, 1, 10);
800   addExpansionCMR("main", "expanded", 4, 1, 4, 5);
801 
802   startFunction("bar", 0x2345);
803   addCMR(Counter::getCounter(0), "expanded", 1, 1, 1, 10);
804   addExpansionCMR("main", "expanded", 9, 1, 9, 5);
805 
806   EXPECT_THAT_ERROR(loadCoverageMapping(), Succeeded());
807 
808   std::vector<InstantiationGroup> InstantiationGroups =
809       LoadedCoverage->getInstantiationGroups("expanded");
810   for (const auto &Group : InstantiationGroups)
811     ASSERT_EQ(Group.size(), 1U);
812 }
813 
814 TEST_P(CoverageMappingTest, load_coverage_for_expanded_file) {
815   ProfileWriter.addRecord({"func", 0x1234, {10}}, Err);
816 
817   startFunction("func", 0x1234);
818   addCMR(Counter::getCounter(0), "expanded", 1, 1, 1, 10);
819   addExpansionCMR("main", "expanded", 4, 1, 4, 5);
820 
821   EXPECT_THAT_ERROR(loadCoverageMapping(), Succeeded());
822 
823   CoverageData Data = LoadedCoverage->getCoverageForFile("expanded");
824   std::vector<CoverageSegment> Segments(Data.begin(), Data.end());
825   ASSERT_EQ(2U, Segments.size());
826   EXPECT_EQ(CoverageSegment(1, 1, 10, true), Segments[0]);
827   EXPECT_EQ(CoverageSegment(1, 10, false), Segments[1]);
828 }
829 
830 TEST_P(CoverageMappingTest, skip_duplicate_function_record) {
831   ProfileWriter.addRecord({"func", 0x1234, {1}}, Err);
832 
833   startFunction("func", 0x1234);
834   addCMR(Counter::getCounter(0), "file1", 1, 1, 9, 9);
835 
836   startFunction("func", 0x1234);
837   addCMR(Counter::getCounter(0), "file1", 1, 1, 9, 9);
838 
839   EXPECT_THAT_ERROR(loadCoverageMapping(), Succeeded());
840 
841   auto Funcs = LoadedCoverage->getCoveredFunctions();
842   unsigned NumFuncs = std::distance(Funcs.begin(), Funcs.end());
843   ASSERT_EQ(1U, NumFuncs);
844 }
845 
846 // FIXME: Use ::testing::Combine() when llvm updates its copy of googletest.
847 INSTANTIATE_TEST_CASE_P(ParameterizedCovMapTest, CoverageMappingTest,
848                         ::testing::Values(std::pair<bool, bool>({false, false}),
849                                           std::pair<bool, bool>({false, true}),
850                                           std::pair<bool, bool>({true, false}),
851                                           std::pair<bool, bool>({true, true})),);
852 
853 } // end anonymous namespace
854