172208a82SEugene Zelenko //===- CoverageMappingReader.cpp - Code coverage mapping reader -----------===//
2dc707122SEaswaran Raman //
3dc707122SEaswaran Raman //                     The LLVM Compiler Infrastructure
4dc707122SEaswaran Raman //
5dc707122SEaswaran Raman // This file is distributed under the University of Illinois Open Source
6dc707122SEaswaran Raman // License. See LICENSE.TXT for details.
7dc707122SEaswaran Raman //
8dc707122SEaswaran Raman //===----------------------------------------------------------------------===//
9dc707122SEaswaran Raman //
10dc707122SEaswaran Raman // This file contains support for reading coverage mapping data for
11dc707122SEaswaran Raman // instrumentation based coverage.
12dc707122SEaswaran Raman //
13dc707122SEaswaran Raman //===----------------------------------------------------------------------===//
14dc707122SEaswaran Raman 
154a5ddf80SXinliang David Li #include "llvm/ProfileData/Coverage/CoverageMappingReader.h"
16e78d131aSEugene Zelenko #include "llvm/ADT/ArrayRef.h"
17ac40e819SIgor Kudrin #include "llvm/ADT/DenseMap.h"
18e78d131aSEugene Zelenko #include "llvm/ADT/STLExtras.h"
194a5ddf80SXinliang David Li #include "llvm/ADT/SmallVector.h"
20e78d131aSEugene Zelenko #include "llvm/ADT/StringRef.h"
21e78d131aSEugene Zelenko #include "llvm/ADT/Triple.h"
22e78d131aSEugene Zelenko #include "llvm/Object/Binary.h"
234a5ddf80SXinliang David Li #include "llvm/Object/COFF.h"
24e78d131aSEugene Zelenko #include "llvm/Object/Error.h"
25dc707122SEaswaran Raman #include "llvm/Object/MachOUniversal.h"
26dc707122SEaswaran Raman #include "llvm/Object/ObjectFile.h"
27e78d131aSEugene Zelenko #include "llvm/ProfileData/InstrProf.h"
28e78d131aSEugene Zelenko #include "llvm/Support/Casting.h"
29dc707122SEaswaran Raman #include "llvm/Support/Debug.h"
304a5ddf80SXinliang David Li #include "llvm/Support/Endian.h"
31e78d131aSEugene Zelenko #include "llvm/Support/Error.h"
32e78d131aSEugene Zelenko #include "llvm/Support/ErrorHandling.h"
33dc707122SEaswaran Raman #include "llvm/Support/LEB128.h"
34dc707122SEaswaran Raman #include "llvm/Support/MathExtras.h"
35dc707122SEaswaran Raman #include "llvm/Support/raw_ostream.h"
36e78d131aSEugene Zelenko #include <algorithm>
37e78d131aSEugene Zelenko #include <cassert>
38e78d131aSEugene Zelenko #include <cstddef>
39e78d131aSEugene Zelenko #include <cstdint>
40e78d131aSEugene Zelenko #include <limits>
41e78d131aSEugene Zelenko #include <memory>
42e78d131aSEugene Zelenko #include <utility>
43e78d131aSEugene Zelenko #include <vector>
44dc707122SEaswaran Raman 
45dc707122SEaswaran Raman using namespace llvm;
46dc707122SEaswaran Raman using namespace coverage;
47dc707122SEaswaran Raman using namespace object;
48dc707122SEaswaran Raman 
49dc707122SEaswaran Raman #define DEBUG_TYPE "coverage-mapping"
50dc707122SEaswaran Raman 
51dc707122SEaswaran Raman void CoverageMappingIterator::increment() {
52*bae83970SVedant Kumar   if (ReadErr != coveragemap_error::success)
53*bae83970SVedant Kumar     return;
54*bae83970SVedant Kumar 
55dc707122SEaswaran Raman   // Check if all the records were read or if an error occurred while reading
56dc707122SEaswaran Raman   // the next record.
57*bae83970SVedant Kumar   if (auto E = Reader->readNextRecord(Record))
589152fd17SVedant Kumar     handleAllErrors(std::move(E), [&](const CoverageMapError &CME) {
599152fd17SVedant Kumar       if (CME.get() == coveragemap_error::eof)
60dc707122SEaswaran Raman         *this = CoverageMappingIterator();
619152fd17SVedant Kumar       else
62*bae83970SVedant Kumar         ReadErr = CME.get();
639152fd17SVedant Kumar     });
649152fd17SVedant Kumar }
65dc707122SEaswaran Raman 
669152fd17SVedant Kumar Error RawCoverageReader::readULEB128(uint64_t &Result) {
6772208a82SEugene Zelenko   if (Data.empty())
689152fd17SVedant Kumar     return make_error<CoverageMapError>(coveragemap_error::truncated);
69dc707122SEaswaran Raman   unsigned N = 0;
70dc707122SEaswaran Raman   Result = decodeULEB128(reinterpret_cast<const uint8_t *>(Data.data()), &N);
71dc707122SEaswaran Raman   if (N > Data.size())
729152fd17SVedant Kumar     return make_error<CoverageMapError>(coveragemap_error::malformed);
73dc707122SEaswaran Raman   Data = Data.substr(N);
749152fd17SVedant Kumar   return Error::success();
75dc707122SEaswaran Raman }
76dc707122SEaswaran Raman 
779152fd17SVedant Kumar Error RawCoverageReader::readIntMax(uint64_t &Result, uint64_t MaxPlus1) {
78dc707122SEaswaran Raman   if (auto Err = readULEB128(Result))
79dc707122SEaswaran Raman     return Err;
80dc707122SEaswaran Raman   if (Result >= MaxPlus1)
819152fd17SVedant Kumar     return make_error<CoverageMapError>(coveragemap_error::malformed);
829152fd17SVedant Kumar   return Error::success();
83dc707122SEaswaran Raman }
84dc707122SEaswaran Raman 
859152fd17SVedant Kumar Error RawCoverageReader::readSize(uint64_t &Result) {
86dc707122SEaswaran Raman   if (auto Err = readULEB128(Result))
87dc707122SEaswaran Raman     return Err;
88dc707122SEaswaran Raman   // Sanity check the number.
89dc707122SEaswaran Raman   if (Result > Data.size())
909152fd17SVedant Kumar     return make_error<CoverageMapError>(coveragemap_error::malformed);
919152fd17SVedant Kumar   return Error::success();
92dc707122SEaswaran Raman }
93dc707122SEaswaran Raman 
949152fd17SVedant Kumar Error RawCoverageReader::readString(StringRef &Result) {
95dc707122SEaswaran Raman   uint64_t Length;
96dc707122SEaswaran Raman   if (auto Err = readSize(Length))
97dc707122SEaswaran Raman     return Err;
98dc707122SEaswaran Raman   Result = Data.substr(0, Length);
99dc707122SEaswaran Raman   Data = Data.substr(Length);
1009152fd17SVedant Kumar   return Error::success();
101dc707122SEaswaran Raman }
102dc707122SEaswaran Raman 
1039152fd17SVedant Kumar Error RawCoverageFilenamesReader::read() {
104dc707122SEaswaran Raman   uint64_t NumFilenames;
105dc707122SEaswaran Raman   if (auto Err = readSize(NumFilenames))
106dc707122SEaswaran Raman     return Err;
107dc707122SEaswaran Raman   for (size_t I = 0; I < NumFilenames; ++I) {
108dc707122SEaswaran Raman     StringRef Filename;
109dc707122SEaswaran Raman     if (auto Err = readString(Filename))
110dc707122SEaswaran Raman       return Err;
111dc707122SEaswaran Raman     Filenames.push_back(Filename);
112dc707122SEaswaran Raman   }
1139152fd17SVedant Kumar   return Error::success();
114dc707122SEaswaran Raman }
115dc707122SEaswaran Raman 
1169152fd17SVedant Kumar Error RawCoverageMappingReader::decodeCounter(unsigned Value, Counter &C) {
117dc707122SEaswaran Raman   auto Tag = Value & Counter::EncodingTagMask;
118dc707122SEaswaran Raman   switch (Tag) {
119dc707122SEaswaran Raman   case Counter::Zero:
120dc707122SEaswaran Raman     C = Counter::getZero();
1219152fd17SVedant Kumar     return Error::success();
122dc707122SEaswaran Raman   case Counter::CounterValueReference:
123dc707122SEaswaran Raman     C = Counter::getCounter(Value >> Counter::EncodingTagBits);
1249152fd17SVedant Kumar     return Error::success();
125dc707122SEaswaran Raman   default:
126dc707122SEaswaran Raman     break;
127dc707122SEaswaran Raman   }
128dc707122SEaswaran Raman   Tag -= Counter::Expression;
129dc707122SEaswaran Raman   switch (Tag) {
130dc707122SEaswaran Raman   case CounterExpression::Subtract:
131dc707122SEaswaran Raman   case CounterExpression::Add: {
132dc707122SEaswaran Raman     auto ID = Value >> Counter::EncodingTagBits;
133dc707122SEaswaran Raman     if (ID >= Expressions.size())
1349152fd17SVedant Kumar       return make_error<CoverageMapError>(coveragemap_error::malformed);
135dc707122SEaswaran Raman     Expressions[ID].Kind = CounterExpression::ExprKind(Tag);
136dc707122SEaswaran Raman     C = Counter::getExpression(ID);
137dc707122SEaswaran Raman     break;
138dc707122SEaswaran Raman   }
139dc707122SEaswaran Raman   default:
1409152fd17SVedant Kumar     return make_error<CoverageMapError>(coveragemap_error::malformed);
141dc707122SEaswaran Raman   }
1429152fd17SVedant Kumar   return Error::success();
143dc707122SEaswaran Raman }
144dc707122SEaswaran Raman 
1459152fd17SVedant Kumar Error RawCoverageMappingReader::readCounter(Counter &C) {
146dc707122SEaswaran Raman   uint64_t EncodedCounter;
147dc707122SEaswaran Raman   if (auto Err =
148dc707122SEaswaran Raman           readIntMax(EncodedCounter, std::numeric_limits<unsigned>::max()))
149dc707122SEaswaran Raman     return Err;
150dc707122SEaswaran Raman   if (auto Err = decodeCounter(EncodedCounter, C))
151dc707122SEaswaran Raman     return Err;
1529152fd17SVedant Kumar   return Error::success();
153dc707122SEaswaran Raman }
154dc707122SEaswaran Raman 
155dc707122SEaswaran Raman static const unsigned EncodingExpansionRegionBit = 1
156dc707122SEaswaran Raman                                                    << Counter::EncodingTagBits;
157dc707122SEaswaran Raman 
158dc707122SEaswaran Raman /// \brief Read the sub-array of regions for the given inferred file id.
159dc707122SEaswaran Raman /// \param NumFileIDs the number of file ids that are defined for this
160dc707122SEaswaran Raman /// function.
1619152fd17SVedant Kumar Error RawCoverageMappingReader::readMappingRegionsSubArray(
162dc707122SEaswaran Raman     std::vector<CounterMappingRegion> &MappingRegions, unsigned InferredFileID,
163dc707122SEaswaran Raman     size_t NumFileIDs) {
164dc707122SEaswaran Raman   uint64_t NumRegions;
165dc707122SEaswaran Raman   if (auto Err = readSize(NumRegions))
166dc707122SEaswaran Raman     return Err;
167dc707122SEaswaran Raman   unsigned LineStart = 0;
168dc707122SEaswaran Raman   for (size_t I = 0; I < NumRegions; ++I) {
169dc707122SEaswaran Raman     Counter C;
170dc707122SEaswaran Raman     CounterMappingRegion::RegionKind Kind = CounterMappingRegion::CodeRegion;
171dc707122SEaswaran Raman 
172dc707122SEaswaran Raman     // Read the combined counter + region kind.
173dc707122SEaswaran Raman     uint64_t EncodedCounterAndRegion;
174dc707122SEaswaran Raman     if (auto Err = readIntMax(EncodedCounterAndRegion,
175dc707122SEaswaran Raman                               std::numeric_limits<unsigned>::max()))
176dc707122SEaswaran Raman       return Err;
177dc707122SEaswaran Raman     unsigned Tag = EncodedCounterAndRegion & Counter::EncodingTagMask;
178dc707122SEaswaran Raman     uint64_t ExpandedFileID = 0;
179dc707122SEaswaran Raman     if (Tag != Counter::Zero) {
180dc707122SEaswaran Raman       if (auto Err = decodeCounter(EncodedCounterAndRegion, C))
181dc707122SEaswaran Raman         return Err;
182dc707122SEaswaran Raman     } else {
183dc707122SEaswaran Raman       // Is it an expansion region?
184dc707122SEaswaran Raman       if (EncodedCounterAndRegion & EncodingExpansionRegionBit) {
185dc707122SEaswaran Raman         Kind = CounterMappingRegion::ExpansionRegion;
186dc707122SEaswaran Raman         ExpandedFileID = EncodedCounterAndRegion >>
187dc707122SEaswaran Raman                          Counter::EncodingCounterTagAndExpansionRegionTagBits;
188dc707122SEaswaran Raman         if (ExpandedFileID >= NumFileIDs)
1899152fd17SVedant Kumar           return make_error<CoverageMapError>(coveragemap_error::malformed);
190dc707122SEaswaran Raman       } else {
191dc707122SEaswaran Raman         switch (EncodedCounterAndRegion >>
192dc707122SEaswaran Raman                 Counter::EncodingCounterTagAndExpansionRegionTagBits) {
193dc707122SEaswaran Raman         case CounterMappingRegion::CodeRegion:
194dc707122SEaswaran Raman           // Don't do anything when we have a code region with a zero counter.
195dc707122SEaswaran Raman           break;
196dc707122SEaswaran Raman         case CounterMappingRegion::SkippedRegion:
197dc707122SEaswaran Raman           Kind = CounterMappingRegion::SkippedRegion;
198dc707122SEaswaran Raman           break;
199dc707122SEaswaran Raman         default:
2009152fd17SVedant Kumar           return make_error<CoverageMapError>(coveragemap_error::malformed);
201dc707122SEaswaran Raman         }
202dc707122SEaswaran Raman       }
203dc707122SEaswaran Raman     }
204dc707122SEaswaran Raman 
205dc707122SEaswaran Raman     // Read the source range.
206dc707122SEaswaran Raman     uint64_t LineStartDelta, ColumnStart, NumLines, ColumnEnd;
207dc707122SEaswaran Raman     if (auto Err =
208dc707122SEaswaran Raman             readIntMax(LineStartDelta, std::numeric_limits<unsigned>::max()))
209dc707122SEaswaran Raman       return Err;
210dc707122SEaswaran Raman     if (auto Err = readULEB128(ColumnStart))
211dc707122SEaswaran Raman       return Err;
212dc707122SEaswaran Raman     if (ColumnStart > std::numeric_limits<unsigned>::max())
2139152fd17SVedant Kumar       return make_error<CoverageMapError>(coveragemap_error::malformed);
214dc707122SEaswaran Raman     if (auto Err = readIntMax(NumLines, std::numeric_limits<unsigned>::max()))
215dc707122SEaswaran Raman       return Err;
216dc707122SEaswaran Raman     if (auto Err = readIntMax(ColumnEnd, std::numeric_limits<unsigned>::max()))
217dc707122SEaswaran Raman       return Err;
218dc707122SEaswaran Raman     LineStart += LineStartDelta;
219dc707122SEaswaran Raman     // Adjust the column locations for the empty regions that are supposed to
220dc707122SEaswaran Raman     // cover whole lines. Those regions should be encoded with the
221dc707122SEaswaran Raman     // column range (1 -> std::numeric_limits<unsigned>::max()), but because
222dc707122SEaswaran Raman     // the encoded std::numeric_limits<unsigned>::max() is several bytes long,
223dc707122SEaswaran Raman     // we set the column range to (0 -> 0) to ensure that the column start and
224dc707122SEaswaran Raman     // column end take up one byte each.
225dc707122SEaswaran Raman     // The std::numeric_limits<unsigned>::max() is used to represent a column
226dc707122SEaswaran Raman     // position at the end of the line without knowing the length of that line.
227dc707122SEaswaran Raman     if (ColumnStart == 0 && ColumnEnd == 0) {
228dc707122SEaswaran Raman       ColumnStart = 1;
229dc707122SEaswaran Raman       ColumnEnd = std::numeric_limits<unsigned>::max();
230dc707122SEaswaran Raman     }
231dc707122SEaswaran Raman 
232dc707122SEaswaran Raman     DEBUG({
233dc707122SEaswaran Raman       dbgs() << "Counter in file " << InferredFileID << " " << LineStart << ":"
234dc707122SEaswaran Raman              << ColumnStart << " -> " << (LineStart + NumLines) << ":"
235dc707122SEaswaran Raman              << ColumnEnd << ", ";
236dc707122SEaswaran Raman       if (Kind == CounterMappingRegion::ExpansionRegion)
237dc707122SEaswaran Raman         dbgs() << "Expands to file " << ExpandedFileID;
238dc707122SEaswaran Raman       else
239dc707122SEaswaran Raman         CounterMappingContext(Expressions).dump(C, dbgs());
240dc707122SEaswaran Raman       dbgs() << "\n";
241dc707122SEaswaran Raman     });
242dc707122SEaswaran Raman 
243*bae83970SVedant Kumar     auto CMR = CounterMappingRegion(C, InferredFileID, ExpandedFileID,
244*bae83970SVedant Kumar                                     LineStart, ColumnStart,
245*bae83970SVedant Kumar                                     LineStart + NumLines, ColumnEnd, Kind);
246*bae83970SVedant Kumar     if (CMR.startLoc() > CMR.endLoc())
247*bae83970SVedant Kumar       return make_error<CoverageMapError>(coveragemap_error::malformed);
248*bae83970SVedant Kumar     MappingRegions.push_back(CMR);
249dc707122SEaswaran Raman   }
2509152fd17SVedant Kumar   return Error::success();
251dc707122SEaswaran Raman }
252dc707122SEaswaran Raman 
2539152fd17SVedant Kumar Error RawCoverageMappingReader::read() {
254dc707122SEaswaran Raman   // Read the virtual file mapping.
255e78d131aSEugene Zelenko   SmallVector<unsigned, 8> VirtualFileMapping;
256dc707122SEaswaran Raman   uint64_t NumFileMappings;
257dc707122SEaswaran Raman   if (auto Err = readSize(NumFileMappings))
258dc707122SEaswaran Raman     return Err;
259dc707122SEaswaran Raman   for (size_t I = 0; I < NumFileMappings; ++I) {
260dc707122SEaswaran Raman     uint64_t FilenameIndex;
261dc707122SEaswaran Raman     if (auto Err = readIntMax(FilenameIndex, TranslationUnitFilenames.size()))
262dc707122SEaswaran Raman       return Err;
263dc707122SEaswaran Raman     VirtualFileMapping.push_back(FilenameIndex);
264dc707122SEaswaran Raman   }
265dc707122SEaswaran Raman 
266dc707122SEaswaran Raman   // Construct the files using unique filenames and virtual file mapping.
267dc707122SEaswaran Raman   for (auto I : VirtualFileMapping) {
268dc707122SEaswaran Raman     Filenames.push_back(TranslationUnitFilenames[I]);
269dc707122SEaswaran Raman   }
270dc707122SEaswaran Raman 
271dc707122SEaswaran Raman   // Read the expressions.
272dc707122SEaswaran Raman   uint64_t NumExpressions;
273dc707122SEaswaran Raman   if (auto Err = readSize(NumExpressions))
274dc707122SEaswaran Raman     return Err;
275dc707122SEaswaran Raman   // Create an array of dummy expressions that get the proper counters
276dc707122SEaswaran Raman   // when the expressions are read, and the proper kinds when the counters
277dc707122SEaswaran Raman   // are decoded.
278dc707122SEaswaran Raman   Expressions.resize(
279dc707122SEaswaran Raman       NumExpressions,
280dc707122SEaswaran Raman       CounterExpression(CounterExpression::Subtract, Counter(), Counter()));
281dc707122SEaswaran Raman   for (size_t I = 0; I < NumExpressions; ++I) {
282dc707122SEaswaran Raman     if (auto Err = readCounter(Expressions[I].LHS))
283dc707122SEaswaran Raman       return Err;
284dc707122SEaswaran Raman     if (auto Err = readCounter(Expressions[I].RHS))
285dc707122SEaswaran Raman       return Err;
286dc707122SEaswaran Raman   }
287dc707122SEaswaran Raman 
288dc707122SEaswaran Raman   // Read the mapping regions sub-arrays.
289dc707122SEaswaran Raman   for (unsigned InferredFileID = 0, S = VirtualFileMapping.size();
290dc707122SEaswaran Raman        InferredFileID < S; ++InferredFileID) {
291dc707122SEaswaran Raman     if (auto Err = readMappingRegionsSubArray(MappingRegions, InferredFileID,
292dc707122SEaswaran Raman                                               VirtualFileMapping.size()))
293dc707122SEaswaran Raman       return Err;
294dc707122SEaswaran Raman   }
295dc707122SEaswaran Raman 
296dc707122SEaswaran Raman   // Set the counters for the expansion regions.
297dc707122SEaswaran Raman   // i.e. Counter of expansion region = counter of the first region
298dc707122SEaswaran Raman   // from the expanded file.
299dc707122SEaswaran Raman   // Perform multiple passes to correctly propagate the counters through
300dc707122SEaswaran Raman   // all the nested expansion regions.
301dc707122SEaswaran Raman   SmallVector<CounterMappingRegion *, 8> FileIDExpansionRegionMapping;
302dc707122SEaswaran Raman   FileIDExpansionRegionMapping.resize(VirtualFileMapping.size(), nullptr);
303dc707122SEaswaran Raman   for (unsigned Pass = 1, S = VirtualFileMapping.size(); Pass < S; ++Pass) {
304dc707122SEaswaran Raman     for (auto &R : MappingRegions) {
305dc707122SEaswaran Raman       if (R.Kind != CounterMappingRegion::ExpansionRegion)
306dc707122SEaswaran Raman         continue;
307dc707122SEaswaran Raman       assert(!FileIDExpansionRegionMapping[R.ExpandedFileID]);
308dc707122SEaswaran Raman       FileIDExpansionRegionMapping[R.ExpandedFileID] = &R;
309dc707122SEaswaran Raman     }
310dc707122SEaswaran Raman     for (auto &R : MappingRegions) {
311dc707122SEaswaran Raman       if (FileIDExpansionRegionMapping[R.FileID]) {
312dc707122SEaswaran Raman         FileIDExpansionRegionMapping[R.FileID]->Count = R.Count;
313dc707122SEaswaran Raman         FileIDExpansionRegionMapping[R.FileID] = nullptr;
314dc707122SEaswaran Raman       }
315dc707122SEaswaran Raman     }
316dc707122SEaswaran Raman   }
317dc707122SEaswaran Raman 
3189152fd17SVedant Kumar   return Error::success();
319dc707122SEaswaran Raman }
320dc707122SEaswaran Raman 
321ac40e819SIgor Kudrin Expected<bool> RawCoverageMappingDummyChecker::isDummy() {
322ac40e819SIgor Kudrin   // A dummy coverage mapping data consists of just one region with zero count.
323ac40e819SIgor Kudrin   uint64_t NumFileMappings;
324ac40e819SIgor Kudrin   if (Error Err = readSize(NumFileMappings))
325ac40e819SIgor Kudrin     return std::move(Err);
326ac40e819SIgor Kudrin   if (NumFileMappings != 1)
327ac40e819SIgor Kudrin     return false;
328ac40e819SIgor Kudrin   // We don't expect any specific value for the filename index, just skip it.
329ac40e819SIgor Kudrin   uint64_t FilenameIndex;
330ac40e819SIgor Kudrin   if (Error Err =
331ac40e819SIgor Kudrin           readIntMax(FilenameIndex, std::numeric_limits<unsigned>::max()))
332ac40e819SIgor Kudrin     return std::move(Err);
333ac40e819SIgor Kudrin   uint64_t NumExpressions;
334ac40e819SIgor Kudrin   if (Error Err = readSize(NumExpressions))
335ac40e819SIgor Kudrin     return std::move(Err);
336ac40e819SIgor Kudrin   if (NumExpressions != 0)
337ac40e819SIgor Kudrin     return false;
338ac40e819SIgor Kudrin   uint64_t NumRegions;
339ac40e819SIgor Kudrin   if (Error Err = readSize(NumRegions))
340ac40e819SIgor Kudrin     return std::move(Err);
341ac40e819SIgor Kudrin   if (NumRegions != 1)
342ac40e819SIgor Kudrin     return false;
343ac40e819SIgor Kudrin   uint64_t EncodedCounterAndRegion;
344ac40e819SIgor Kudrin   if (Error Err = readIntMax(EncodedCounterAndRegion,
345ac40e819SIgor Kudrin                              std::numeric_limits<unsigned>::max()))
346ac40e819SIgor Kudrin     return std::move(Err);
347ac40e819SIgor Kudrin   unsigned Tag = EncodedCounterAndRegion & Counter::EncodingTagMask;
348ac40e819SIgor Kudrin   return Tag == Counter::Zero;
349ac40e819SIgor Kudrin }
350ac40e819SIgor Kudrin 
3519152fd17SVedant Kumar Error InstrProfSymtab::create(SectionRef &Section) {
3529152fd17SVedant Kumar   if (auto EC = Section.getContents(Data))
3539152fd17SVedant Kumar     return errorCodeToError(EC);
354dc707122SEaswaran Raman   Address = Section.getAddress();
3559152fd17SVedant Kumar   return Error::success();
356dc707122SEaswaran Raman }
357dc707122SEaswaran Raman 
358dc707122SEaswaran Raman StringRef InstrProfSymtab::getFuncName(uint64_t Pointer, size_t Size) {
359dc707122SEaswaran Raman   if (Pointer < Address)
360dc707122SEaswaran Raman     return StringRef();
361dc707122SEaswaran Raman   auto Offset = Pointer - Address;
362dc707122SEaswaran Raman   if (Offset + Size > Data.size())
363dc707122SEaswaran Raman     return StringRef();
364dc707122SEaswaran Raman   return Data.substr(Pointer - Address, Size);
365dc707122SEaswaran Raman }
366dc707122SEaswaran Raman 
367ac40e819SIgor Kudrin // Check if the mapping data is a dummy, i.e. is emitted for an unused function.
368ac40e819SIgor Kudrin static Expected<bool> isCoverageMappingDummy(uint64_t Hash, StringRef Mapping) {
369ac40e819SIgor Kudrin   // The hash value of dummy mapping records is always zero.
370ac40e819SIgor Kudrin   if (Hash)
371ac40e819SIgor Kudrin     return false;
372ac40e819SIgor Kudrin   return RawCoverageMappingDummyChecker(Mapping).isDummy();
373ac40e819SIgor Kudrin }
374ac40e819SIgor Kudrin 
375dc707122SEaswaran Raman namespace {
376e78d131aSEugene Zelenko 
377dc707122SEaswaran Raman struct CovMapFuncRecordReader {
378e78d131aSEugene Zelenko   virtual ~CovMapFuncRecordReader() = default;
379e78d131aSEugene Zelenko 
3803739b95dSVedant Kumar   // The interface to read coverage mapping function records for a module.
3813739b95dSVedant Kumar   //
3823739b95dSVedant Kumar   // \p Buf points to the buffer containing the \c CovHeader of the coverage
3833739b95dSVedant Kumar   // mapping data associated with the module.
3843739b95dSVedant Kumar   //
3853739b95dSVedant Kumar   // Returns a pointer to the next \c CovHeader if it exists, or a pointer
3863739b95dSVedant Kumar   // greater than \p End if not.
3873739b95dSVedant Kumar   virtual Expected<const char *> readFunctionRecords(const char *Buf,
3883739b95dSVedant Kumar                                                      const char *End) = 0;
389e78d131aSEugene Zelenko 
390dc707122SEaswaran Raman   template <class IntPtrT, support::endianness Endian>
3919152fd17SVedant Kumar   static Expected<std::unique_ptr<CovMapFuncRecordReader>>
392e78d131aSEugene Zelenko   get(CovMapVersion Version, InstrProfSymtab &P,
393dc707122SEaswaran Raman       std::vector<BinaryCoverageReader::ProfileMappingRecord> &R,
394dc707122SEaswaran Raman       std::vector<StringRef> &F);
395dc707122SEaswaran Raman };
396dc707122SEaswaran Raman 
397dc707122SEaswaran Raman // A class for reading coverage mapping function records for a module.
398e78d131aSEugene Zelenko template <CovMapVersion Version, class IntPtrT, support::endianness Endian>
399dc707122SEaswaran Raman class VersionedCovMapFuncRecordReader : public CovMapFuncRecordReader {
40072208a82SEugene Zelenko   using FuncRecordType =
40172208a82SEugene Zelenko       typename CovMapTraits<Version, IntPtrT>::CovMapFuncRecordType;
40272208a82SEugene Zelenko   using NameRefType = typename CovMapTraits<Version, IntPtrT>::NameRefType;
403dc707122SEaswaran Raman 
404ac40e819SIgor Kudrin   // Maps function's name references to the indexes of their records
405ac40e819SIgor Kudrin   // in \c Records.
406e78d131aSEugene Zelenko   DenseMap<NameRefType, size_t> FunctionRecords;
407dc707122SEaswaran Raman   InstrProfSymtab &ProfileNames;
408dc707122SEaswaran Raman   std::vector<StringRef> &Filenames;
409dc707122SEaswaran Raman   std::vector<BinaryCoverageReader::ProfileMappingRecord> &Records;
410dc707122SEaswaran Raman 
411ac40e819SIgor Kudrin   // Add the record to the collection if we don't already have a record that
412ac40e819SIgor Kudrin   // points to the same function name. This is useful to ignore the redundant
413ac40e819SIgor Kudrin   // records for the functions with ODR linkage.
414ac40e819SIgor Kudrin   // In addition, prefer records with real coverage mapping data to dummy
415ac40e819SIgor Kudrin   // records, which were emitted for inline functions which were seen but
416ac40e819SIgor Kudrin   // not used in the corresponding translation unit.
417ac40e819SIgor Kudrin   Error insertFunctionRecordIfNeeded(const FuncRecordType *CFR,
418ac40e819SIgor Kudrin                                      StringRef Mapping, size_t FilenamesBegin) {
419ac40e819SIgor Kudrin     uint64_t FuncHash = CFR->template getFuncHash<Endian>();
420ac40e819SIgor Kudrin     NameRefType NameRef = CFR->template getFuncNameRef<Endian>();
421ac40e819SIgor Kudrin     auto InsertResult =
422ac40e819SIgor Kudrin         FunctionRecords.insert(std::make_pair(NameRef, Records.size()));
423ac40e819SIgor Kudrin     if (InsertResult.second) {
424ac40e819SIgor Kudrin       StringRef FuncName;
425ac40e819SIgor Kudrin       if (Error Err = CFR->template getFuncName<Endian>(ProfileNames, FuncName))
426ac40e819SIgor Kudrin         return Err;
427b5794ca9SVedant Kumar       if (FuncName.empty())
428b5794ca9SVedant Kumar         return make_error<InstrProfError>(instrprof_error::malformed);
429ac40e819SIgor Kudrin       Records.emplace_back(Version, FuncName, FuncHash, Mapping, FilenamesBegin,
430ac40e819SIgor Kudrin                            Filenames.size() - FilenamesBegin);
431ac40e819SIgor Kudrin       return Error::success();
432ac40e819SIgor Kudrin     }
433ac40e819SIgor Kudrin     // Update the existing record if it's a dummy and the new record is real.
434ac40e819SIgor Kudrin     size_t OldRecordIndex = InsertResult.first->second;
435ac40e819SIgor Kudrin     BinaryCoverageReader::ProfileMappingRecord &OldRecord =
436ac40e819SIgor Kudrin         Records[OldRecordIndex];
437ac40e819SIgor Kudrin     Expected<bool> OldIsDummyExpected = isCoverageMappingDummy(
438ac40e819SIgor Kudrin         OldRecord.FunctionHash, OldRecord.CoverageMapping);
439ac40e819SIgor Kudrin     if (Error Err = OldIsDummyExpected.takeError())
440ac40e819SIgor Kudrin       return Err;
441ac40e819SIgor Kudrin     if (!*OldIsDummyExpected)
442ac40e819SIgor Kudrin       return Error::success();
443ac40e819SIgor Kudrin     Expected<bool> NewIsDummyExpected =
444ac40e819SIgor Kudrin         isCoverageMappingDummy(FuncHash, Mapping);
445ac40e819SIgor Kudrin     if (Error Err = NewIsDummyExpected.takeError())
446ac40e819SIgor Kudrin       return Err;
447ac40e819SIgor Kudrin     if (*NewIsDummyExpected)
448ac40e819SIgor Kudrin       return Error::success();
449ac40e819SIgor Kudrin     OldRecord.FunctionHash = FuncHash;
450ac40e819SIgor Kudrin     OldRecord.CoverageMapping = Mapping;
451ac40e819SIgor Kudrin     OldRecord.FilenamesBegin = FilenamesBegin;
452ac40e819SIgor Kudrin     OldRecord.FilenamesSize = Filenames.size() - FilenamesBegin;
453ac40e819SIgor Kudrin     return Error::success();
454ac40e819SIgor Kudrin   }
455ac40e819SIgor Kudrin 
456dc707122SEaswaran Raman public:
457dc707122SEaswaran Raman   VersionedCovMapFuncRecordReader(
458dc707122SEaswaran Raman       InstrProfSymtab &P,
459dc707122SEaswaran Raman       std::vector<BinaryCoverageReader::ProfileMappingRecord> &R,
460dc707122SEaswaran Raman       std::vector<StringRef> &F)
461dc707122SEaswaran Raman       : ProfileNames(P), Filenames(F), Records(R) {}
462e78d131aSEugene Zelenko 
463e78d131aSEugene Zelenko   ~VersionedCovMapFuncRecordReader() override = default;
464dc707122SEaswaran Raman 
4653739b95dSVedant Kumar   Expected<const char *> readFunctionRecords(const char *Buf,
4663739b95dSVedant Kumar                                              const char *End) override {
467dc707122SEaswaran Raman     using namespace support;
468e78d131aSEugene Zelenko 
469dc707122SEaswaran Raman     if (Buf + sizeof(CovMapHeader) > End)
4709152fd17SVedant Kumar       return make_error<CoverageMapError>(coveragemap_error::malformed);
471e78d131aSEugene Zelenko     auto CovHeader = reinterpret_cast<const CovMapHeader *>(Buf);
472dc707122SEaswaran Raman     uint32_t NRecords = CovHeader->getNRecords<Endian>();
473dc707122SEaswaran Raman     uint32_t FilenamesSize = CovHeader->getFilenamesSize<Endian>();
474dc707122SEaswaran Raman     uint32_t CoverageSize = CovHeader->getCoverageSize<Endian>();
475dc707122SEaswaran Raman     assert((CovMapVersion)CovHeader->getVersion<Endian>() == Version);
476dc707122SEaswaran Raman     Buf = reinterpret_cast<const char *>(CovHeader + 1);
477dc707122SEaswaran Raman 
478dc707122SEaswaran Raman     // Skip past the function records, saving the start and end for later.
479dc707122SEaswaran Raman     const char *FunBuf = Buf;
480dc707122SEaswaran Raman     Buf += NRecords * sizeof(FuncRecordType);
481dc707122SEaswaran Raman     const char *FunEnd = Buf;
482dc707122SEaswaran Raman 
483dc707122SEaswaran Raman     // Get the filenames.
484dc707122SEaswaran Raman     if (Buf + FilenamesSize > End)
4859152fd17SVedant Kumar       return make_error<CoverageMapError>(coveragemap_error::malformed);
486dc707122SEaswaran Raman     size_t FilenamesBegin = Filenames.size();
487dc707122SEaswaran Raman     RawCoverageFilenamesReader Reader(StringRef(Buf, FilenamesSize), Filenames);
488dc707122SEaswaran Raman     if (auto Err = Reader.read())
4893739b95dSVedant Kumar       return std::move(Err);
490dc707122SEaswaran Raman     Buf += FilenamesSize;
491dc707122SEaswaran Raman 
492dc707122SEaswaran Raman     // We'll read the coverage mapping records in the loop below.
493dc707122SEaswaran Raman     const char *CovBuf = Buf;
494dc707122SEaswaran Raman     Buf += CoverageSize;
495dc707122SEaswaran Raman     const char *CovEnd = Buf;
496dc707122SEaswaran Raman 
497dc707122SEaswaran Raman     if (Buf > End)
4989152fd17SVedant Kumar       return make_error<CoverageMapError>(coveragemap_error::malformed);
499dc707122SEaswaran Raman     // Each coverage map has an alignment of 8, so we need to adjust alignment
500dc707122SEaswaran Raman     // before reading the next map.
501dc707122SEaswaran Raman     Buf += alignmentAdjustment(Buf, 8);
502dc707122SEaswaran Raman 
503dc707122SEaswaran Raman     auto CFR = reinterpret_cast<const FuncRecordType *>(FunBuf);
504dc707122SEaswaran Raman     while ((const char *)CFR < FunEnd) {
505dc707122SEaswaran Raman       // Read the function information
506dc707122SEaswaran Raman       uint32_t DataSize = CFR->template getDataSize<Endian>();
507dc707122SEaswaran Raman 
508dc707122SEaswaran Raman       // Now use that to read the coverage data.
509dc707122SEaswaran Raman       if (CovBuf + DataSize > CovEnd)
5109152fd17SVedant Kumar         return make_error<CoverageMapError>(coveragemap_error::malformed);
511dc707122SEaswaran Raman       auto Mapping = StringRef(CovBuf, DataSize);
512dc707122SEaswaran Raman       CovBuf += DataSize;
513dc707122SEaswaran Raman 
514ac40e819SIgor Kudrin       if (Error Err =
515ac40e819SIgor Kudrin               insertFunctionRecordIfNeeded(CFR, Mapping, FilenamesBegin))
5163739b95dSVedant Kumar         return std::move(Err);
517dc707122SEaswaran Raman       CFR++;
518dc707122SEaswaran Raman     }
5193739b95dSVedant Kumar     return Buf;
520dc707122SEaswaran Raman   }
521dc707122SEaswaran Raman };
522e78d131aSEugene Zelenko 
523dc707122SEaswaran Raman } // end anonymous namespace
524dc707122SEaswaran Raman 
525dc707122SEaswaran Raman template <class IntPtrT, support::endianness Endian>
5269152fd17SVedant Kumar Expected<std::unique_ptr<CovMapFuncRecordReader>> CovMapFuncRecordReader::get(
527e78d131aSEugene Zelenko     CovMapVersion Version, InstrProfSymtab &P,
528dc707122SEaswaran Raman     std::vector<BinaryCoverageReader::ProfileMappingRecord> &R,
529dc707122SEaswaran Raman     std::vector<StringRef> &F) {
530dc707122SEaswaran Raman   using namespace coverage;
531e78d131aSEugene Zelenko 
532dc707122SEaswaran Raman   switch (Version) {
533dc707122SEaswaran Raman   case CovMapVersion::Version1:
534dc707122SEaswaran Raman     return llvm::make_unique<VersionedCovMapFuncRecordReader<
535dc707122SEaswaran Raman         CovMapVersion::Version1, IntPtrT, Endian>>(P, R, F);
536dc707122SEaswaran Raman   case CovMapVersion::Version2:
537dc707122SEaswaran Raman     // Decompress the name data.
5389152fd17SVedant Kumar     if (Error E = P.create(P.getNameData()))
5399152fd17SVedant Kumar       return std::move(E);
540dc707122SEaswaran Raman     return llvm::make_unique<VersionedCovMapFuncRecordReader<
541dc707122SEaswaran Raman         CovMapVersion::Version2, IntPtrT, Endian>>(P, R, F);
542dc707122SEaswaran Raman   }
543dc707122SEaswaran Raman   llvm_unreachable("Unsupported version");
544dc707122SEaswaran Raman }
545dc707122SEaswaran Raman 
546dc707122SEaswaran Raman template <typename T, support::endianness Endian>
5479152fd17SVedant Kumar static Error readCoverageMappingData(
548dc707122SEaswaran Raman     InstrProfSymtab &ProfileNames, StringRef Data,
549dc707122SEaswaran Raman     std::vector<BinaryCoverageReader::ProfileMappingRecord> &Records,
550dc707122SEaswaran Raman     std::vector<StringRef> &Filenames) {
551dc707122SEaswaran Raman   using namespace coverage;
552e78d131aSEugene Zelenko 
553dc707122SEaswaran Raman   // Read the records in the coverage data section.
554dc707122SEaswaran Raman   auto CovHeader =
555e78d131aSEugene Zelenko       reinterpret_cast<const CovMapHeader *>(Data.data());
556dc707122SEaswaran Raman   CovMapVersion Version = (CovMapVersion)CovHeader->getVersion<Endian>();
557e78d131aSEugene Zelenko   if (Version > CovMapVersion::CurrentVersion)
5589152fd17SVedant Kumar     return make_error<CoverageMapError>(coveragemap_error::unsupported_version);
5599152fd17SVedant Kumar   Expected<std::unique_ptr<CovMapFuncRecordReader>> ReaderExpected =
560dc707122SEaswaran Raman       CovMapFuncRecordReader::get<T, Endian>(Version, ProfileNames, Records,
561dc707122SEaswaran Raman                                              Filenames);
5629152fd17SVedant Kumar   if (Error E = ReaderExpected.takeError())
5639152fd17SVedant Kumar     return E;
5649152fd17SVedant Kumar   auto Reader = std::move(ReaderExpected.get());
565dc707122SEaswaran Raman   for (const char *Buf = Data.data(), *End = Buf + Data.size(); Buf < End;) {
5663739b95dSVedant Kumar     auto NextHeaderOrErr = Reader->readFunctionRecords(Buf, End);
5673739b95dSVedant Kumar     if (auto E = NextHeaderOrErr.takeError())
5689152fd17SVedant Kumar       return E;
5693739b95dSVedant Kumar     Buf = NextHeaderOrErr.get();
570dc707122SEaswaran Raman   }
5719152fd17SVedant Kumar   return Error::success();
572dc707122SEaswaran Raman }
573e78d131aSEugene Zelenko 
574dc707122SEaswaran Raman static const char *TestingFormatMagic = "llvmcovmtestdata";
575dc707122SEaswaran Raman 
5769152fd17SVedant Kumar static Error loadTestingFormat(StringRef Data, InstrProfSymtab &ProfileNames,
577dc707122SEaswaran Raman                                StringRef &CoverageMapping,
578dc707122SEaswaran Raman                                uint8_t &BytesInAddress,
579dc707122SEaswaran Raman                                support::endianness &Endian) {
580dc707122SEaswaran Raman   BytesInAddress = 8;
581dc707122SEaswaran Raman   Endian = support::endianness::little;
582dc707122SEaswaran Raman 
583dc707122SEaswaran Raman   Data = Data.substr(StringRef(TestingFormatMagic).size());
58472208a82SEugene Zelenko   if (Data.empty())
5859152fd17SVedant Kumar     return make_error<CoverageMapError>(coveragemap_error::truncated);
586dc707122SEaswaran Raman   unsigned N = 0;
587dc707122SEaswaran Raman   auto ProfileNamesSize =
588dc707122SEaswaran Raman       decodeULEB128(reinterpret_cast<const uint8_t *>(Data.data()), &N);
589dc707122SEaswaran Raman   if (N > Data.size())
5909152fd17SVedant Kumar     return make_error<CoverageMapError>(coveragemap_error::malformed);
591dc707122SEaswaran Raman   Data = Data.substr(N);
59272208a82SEugene Zelenko   if (Data.empty())
5939152fd17SVedant Kumar     return make_error<CoverageMapError>(coveragemap_error::truncated);
594dc707122SEaswaran Raman   N = 0;
595dc707122SEaswaran Raman   uint64_t Address =
596dc707122SEaswaran Raman       decodeULEB128(reinterpret_cast<const uint8_t *>(Data.data()), &N);
597dc707122SEaswaran Raman   if (N > Data.size())
5989152fd17SVedant Kumar     return make_error<CoverageMapError>(coveragemap_error::malformed);
599dc707122SEaswaran Raman   Data = Data.substr(N);
600dc707122SEaswaran Raman   if (Data.size() < ProfileNamesSize)
6019152fd17SVedant Kumar     return make_error<CoverageMapError>(coveragemap_error::malformed);
6029152fd17SVedant Kumar   if (Error E = ProfileNames.create(Data.substr(0, ProfileNamesSize), Address))
6039152fd17SVedant Kumar     return E;
604dc707122SEaswaran Raman   CoverageMapping = Data.substr(ProfileNamesSize);
605eb103073SIgor Kudrin   // Skip the padding bytes because coverage map data has an alignment of 8.
60672208a82SEugene Zelenko   if (CoverageMapping.empty())
6079152fd17SVedant Kumar     return make_error<CoverageMapError>(coveragemap_error::truncated);
608eb103073SIgor Kudrin   size_t Pad = alignmentAdjustment(CoverageMapping.data(), 8);
609eb103073SIgor Kudrin   if (CoverageMapping.size() < Pad)
6109152fd17SVedant Kumar     return make_error<CoverageMapError>(coveragemap_error::malformed);
611eb103073SIgor Kudrin   CoverageMapping = CoverageMapping.substr(Pad);
6129152fd17SVedant Kumar   return Error::success();
613dc707122SEaswaran Raman }
614dc707122SEaswaran Raman 
6159152fd17SVedant Kumar static Expected<SectionRef> lookupSection(ObjectFile &OF, StringRef Name) {
616dc707122SEaswaran Raman   StringRef FoundName;
617dc707122SEaswaran Raman   for (const auto &Section : OF.sections()) {
618dc707122SEaswaran Raman     if (auto EC = Section.getName(FoundName))
6199152fd17SVedant Kumar       return errorCodeToError(EC);
620dc707122SEaswaran Raman     if (FoundName == Name)
621dc707122SEaswaran Raman       return Section;
622dc707122SEaswaran Raman   }
6239152fd17SVedant Kumar   return make_error<CoverageMapError>(coveragemap_error::no_data_found);
624dc707122SEaswaran Raman }
625dc707122SEaswaran Raman 
6269152fd17SVedant Kumar static Error loadBinaryFormat(MemoryBufferRef ObjectBuffer,
6279152fd17SVedant Kumar                               InstrProfSymtab &ProfileNames,
6289152fd17SVedant Kumar                               StringRef &CoverageMapping,
6299152fd17SVedant Kumar                               uint8_t &BytesInAddress,
630dc707122SEaswaran Raman                               support::endianness &Endian, StringRef Arch) {
631e78d131aSEugene Zelenko   auto BinOrErr = createBinary(ObjectBuffer);
632dc707122SEaswaran Raman   if (!BinOrErr)
6339152fd17SVedant Kumar     return BinOrErr.takeError();
634dc707122SEaswaran Raman   auto Bin = std::move(BinOrErr.get());
635dc707122SEaswaran Raman   std::unique_ptr<ObjectFile> OF;
636e78d131aSEugene Zelenko   if (auto *Universal = dyn_cast<MachOUniversalBinary>(Bin.get())) {
637dc707122SEaswaran Raman     // If we have a universal binary, try to look up the object for the
638dc707122SEaswaran Raman     // appropriate architecture.
639dc707122SEaswaran Raman     auto ObjectFileOrErr = Universal->getObjectForArch(Arch);
6409acb1099SKevin Enderby     if (!ObjectFileOrErr)
6419acb1099SKevin Enderby       return ObjectFileOrErr.takeError();
642dc707122SEaswaran Raman     OF = std::move(ObjectFileOrErr.get());
643e78d131aSEugene Zelenko   } else if (isa<ObjectFile>(Bin.get())) {
644dc707122SEaswaran Raman     // For any other object file, upcast and take ownership.
645e78d131aSEugene Zelenko     OF.reset(cast<ObjectFile>(Bin.release()));
646dc707122SEaswaran Raman     // If we've asked for a particular arch, make sure they match.
647dc707122SEaswaran Raman     if (!Arch.empty() && OF->getArch() != Triple(Arch).getArch())
6489152fd17SVedant Kumar       return errorCodeToError(object_error::arch_not_found);
649dc707122SEaswaran Raman   } else
650dc707122SEaswaran Raman     // We can only handle object files.
6519152fd17SVedant Kumar     return make_error<CoverageMapError>(coveragemap_error::malformed);
652dc707122SEaswaran Raman 
653dc707122SEaswaran Raman   // The coverage uses native pointer sizes for the object it's written in.
654dc707122SEaswaran Raman   BytesInAddress = OF->getBytesInAddress();
655dc707122SEaswaran Raman   Endian = OF->isLittleEndian() ? support::endianness::little
656dc707122SEaswaran Raman                                 : support::endianness::big;
657dc707122SEaswaran Raman 
658dc707122SEaswaran Raman   // Look for the sections that we are interested in.
6591a6a2b64SVedant Kumar   auto ObjFormat = OF->getTripleObjectFormat();
6604a5ddf80SXinliang David Li   auto NamesSection =
6611a6a2b64SVedant Kumar       lookupSection(*OF, getInstrProfSectionName(IPSK_name, ObjFormat,
6621a6a2b64SVedant Kumar                                                  /*AddSegmentInfo=*/false));
6639152fd17SVedant Kumar   if (auto E = NamesSection.takeError())
6649152fd17SVedant Kumar     return E;
6654a5ddf80SXinliang David Li   auto CoverageSection =
6661a6a2b64SVedant Kumar       lookupSection(*OF, getInstrProfSectionName(IPSK_covmap, ObjFormat,
6671a6a2b64SVedant Kumar                                                  /*AddSegmentInfo=*/false));
6689152fd17SVedant Kumar   if (auto E = CoverageSection.takeError())
6699152fd17SVedant Kumar     return E;
670dc707122SEaswaran Raman 
671dc707122SEaswaran Raman   // Get the contents of the given sections.
6729152fd17SVedant Kumar   if (auto EC = CoverageSection->getContents(CoverageMapping))
6739152fd17SVedant Kumar     return errorCodeToError(EC);
6749152fd17SVedant Kumar   if (Error E = ProfileNames.create(*NamesSection))
6759152fd17SVedant Kumar     return E;
676dc707122SEaswaran Raman 
6779152fd17SVedant Kumar   return Error::success();
678dc707122SEaswaran Raman }
679dc707122SEaswaran Raman 
6809152fd17SVedant Kumar Expected<std::unique_ptr<BinaryCoverageReader>>
681a30139d5SVedant Kumar BinaryCoverageReader::create(std::unique_ptr<MemoryBuffer> &ObjectBuffer,
682a30139d5SVedant Kumar                              StringRef Arch) {
683dc707122SEaswaran Raman   std::unique_ptr<BinaryCoverageReader> Reader(new BinaryCoverageReader());
684dc707122SEaswaran Raman 
685dc707122SEaswaran Raman   StringRef Coverage;
686dc707122SEaswaran Raman   uint8_t BytesInAddress;
687dc707122SEaswaran Raman   support::endianness Endian;
68841af4309SMehdi Amini   Error E = Error::success();
6899152fd17SVedant Kumar   consumeError(std::move(E));
690a30139d5SVedant Kumar   if (ObjectBuffer->getBuffer().startswith(TestingFormatMagic))
691dc707122SEaswaran Raman     // This is a special format used for testing.
692a30139d5SVedant Kumar     E = loadTestingFormat(ObjectBuffer->getBuffer(), Reader->ProfileNames,
693dc707122SEaswaran Raman                           Coverage, BytesInAddress, Endian);
694dc707122SEaswaran Raman   else
695a30139d5SVedant Kumar     E = loadBinaryFormat(ObjectBuffer->getMemBufferRef(), Reader->ProfileNames,
696dc707122SEaswaran Raman                          Coverage, BytesInAddress, Endian, Arch);
6979152fd17SVedant Kumar   if (E)
6989152fd17SVedant Kumar     return std::move(E);
699dc707122SEaswaran Raman 
700dc707122SEaswaran Raman   if (BytesInAddress == 4 && Endian == support::endianness::little)
7019152fd17SVedant Kumar     E = readCoverageMappingData<uint32_t, support::endianness::little>(
702dc707122SEaswaran Raman         Reader->ProfileNames, Coverage, Reader->MappingRecords,
703dc707122SEaswaran Raman         Reader->Filenames);
704dc707122SEaswaran Raman   else if (BytesInAddress == 4 && Endian == support::endianness::big)
7059152fd17SVedant Kumar     E = readCoverageMappingData<uint32_t, support::endianness::big>(
706dc707122SEaswaran Raman         Reader->ProfileNames, Coverage, Reader->MappingRecords,
707dc707122SEaswaran Raman         Reader->Filenames);
708dc707122SEaswaran Raman   else if (BytesInAddress == 8 && Endian == support::endianness::little)
7099152fd17SVedant Kumar     E = readCoverageMappingData<uint64_t, support::endianness::little>(
710dc707122SEaswaran Raman         Reader->ProfileNames, Coverage, Reader->MappingRecords,
711dc707122SEaswaran Raman         Reader->Filenames);
712dc707122SEaswaran Raman   else if (BytesInAddress == 8 && Endian == support::endianness::big)
7139152fd17SVedant Kumar     E = readCoverageMappingData<uint64_t, support::endianness::big>(
714dc707122SEaswaran Raman         Reader->ProfileNames, Coverage, Reader->MappingRecords,
715dc707122SEaswaran Raman         Reader->Filenames);
716dc707122SEaswaran Raman   else
7179152fd17SVedant Kumar     return make_error<CoverageMapError>(coveragemap_error::malformed);
7189152fd17SVedant Kumar   if (E)
7199152fd17SVedant Kumar     return std::move(E);
720dc707122SEaswaran Raman   return std::move(Reader);
721dc707122SEaswaran Raman }
722dc707122SEaswaran Raman 
7239152fd17SVedant Kumar Error BinaryCoverageReader::readNextRecord(CoverageMappingRecord &Record) {
724dc707122SEaswaran Raman   if (CurrentRecord >= MappingRecords.size())
7259152fd17SVedant Kumar     return make_error<CoverageMapError>(coveragemap_error::eof);
726dc707122SEaswaran Raman 
727dc707122SEaswaran Raman   FunctionsFilenames.clear();
728dc707122SEaswaran Raman   Expressions.clear();
729dc707122SEaswaran Raman   MappingRegions.clear();
730dc707122SEaswaran Raman   auto &R = MappingRecords[CurrentRecord];
731dc707122SEaswaran Raman   RawCoverageMappingReader Reader(
732dc707122SEaswaran Raman       R.CoverageMapping,
733dc707122SEaswaran Raman       makeArrayRef(Filenames).slice(R.FilenamesBegin, R.FilenamesSize),
734dc707122SEaswaran Raman       FunctionsFilenames, Expressions, MappingRegions);
735dc707122SEaswaran Raman   if (auto Err = Reader.read())
736dc707122SEaswaran Raman     return Err;
737dc707122SEaswaran Raman 
738dc707122SEaswaran Raman   Record.FunctionName = R.FunctionName;
739dc707122SEaswaran Raman   Record.FunctionHash = R.FunctionHash;
740dc707122SEaswaran Raman   Record.Filenames = FunctionsFilenames;
741dc707122SEaswaran Raman   Record.Expressions = Expressions;
742dc707122SEaswaran Raman   Record.MappingRegions = MappingRegions;
743dc707122SEaswaran Raman 
744dc707122SEaswaran Raman   ++CurrentRecord;
7459152fd17SVedant Kumar   return Error::success();
746dc707122SEaswaran Raman }
747