1*e78d131aSEugene Zelenko //===- CoverageMappingReader.cpp - Code coverage mapping reader -*- C++ -*-===//
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 
15*e78d131aSEugene Zelenko #include "llvm/ADT/ArrayRef.h"
16ac40e819SIgor Kudrin #include "llvm/ADT/DenseMap.h"
17*e78d131aSEugene Zelenko #include "llvm/ADT/SmallVector.h"
18*e78d131aSEugene Zelenko #include "llvm/ADT/STLExtras.h"
19*e78d131aSEugene Zelenko #include "llvm/ADT/StringRef.h"
20*e78d131aSEugene Zelenko #include "llvm/ADT/Triple.h"
21*e78d131aSEugene Zelenko #include "llvm/Object/Binary.h"
22*e78d131aSEugene Zelenko #include "llvm/Object/Error.h"
23dc707122SEaswaran Raman #include "llvm/Object/MachOUniversal.h"
24dc707122SEaswaran Raman #include "llvm/Object/ObjectFile.h"
25*e78d131aSEugene Zelenko #include "llvm/ProfileData/Coverage/CoverageMappingReader.h"
26*e78d131aSEugene Zelenko #include "llvm/ProfileData/InstrProf.h"
27*e78d131aSEugene Zelenko #include "llvm/Support/Casting.h"
28dc707122SEaswaran Raman #include "llvm/Support/Debug.h"
29*e78d131aSEugene Zelenko #include "llvm/Support/Error.h"
30*e78d131aSEugene Zelenko #include "llvm/Support/ErrorHandling.h"
31dc707122SEaswaran Raman #include "llvm/Support/Endian.h"
32dc707122SEaswaran Raman #include "llvm/Support/LEB128.h"
33dc707122SEaswaran Raman #include "llvm/Support/MathExtras.h"
34dc707122SEaswaran Raman #include "llvm/Support/raw_ostream.h"
35*e78d131aSEugene Zelenko #include <algorithm>
36*e78d131aSEugene Zelenko #include <cassert>
37*e78d131aSEugene Zelenko #include <cstddef>
38*e78d131aSEugene Zelenko #include <cstdint>
39*e78d131aSEugene Zelenko #include <limits>
40*e78d131aSEugene Zelenko #include <memory>
41*e78d131aSEugene Zelenko #include <utility>
42*e78d131aSEugene Zelenko #include <vector>
43dc707122SEaswaran Raman 
44dc707122SEaswaran Raman using namespace llvm;
45dc707122SEaswaran Raman using namespace coverage;
46dc707122SEaswaran Raman using namespace object;
47dc707122SEaswaran Raman 
48dc707122SEaswaran Raman #define DEBUG_TYPE "coverage-mapping"
49dc707122SEaswaran Raman 
50dc707122SEaswaran Raman void CoverageMappingIterator::increment() {
51dc707122SEaswaran Raman   // Check if all the records were read or if an error occurred while reading
52dc707122SEaswaran Raman   // the next record.
539152fd17SVedant Kumar   if (auto E = Reader->readNextRecord(Record)) {
549152fd17SVedant Kumar     handleAllErrors(std::move(E), [&](const CoverageMapError &CME) {
559152fd17SVedant Kumar       if (CME.get() == coveragemap_error::eof)
56dc707122SEaswaran Raman         *this = CoverageMappingIterator();
579152fd17SVedant Kumar       else
589152fd17SVedant Kumar         llvm_unreachable("Unexpected error in coverage mapping iterator");
599152fd17SVedant Kumar     });
609152fd17SVedant Kumar   }
61dc707122SEaswaran Raman }
62dc707122SEaswaran Raman 
639152fd17SVedant Kumar Error RawCoverageReader::readULEB128(uint64_t &Result) {
64dc707122SEaswaran Raman   if (Data.size() < 1)
659152fd17SVedant Kumar     return make_error<CoverageMapError>(coveragemap_error::truncated);
66dc707122SEaswaran Raman   unsigned N = 0;
67dc707122SEaswaran Raman   Result = decodeULEB128(reinterpret_cast<const uint8_t *>(Data.data()), &N);
68dc707122SEaswaran Raman   if (N > Data.size())
699152fd17SVedant Kumar     return make_error<CoverageMapError>(coveragemap_error::malformed);
70dc707122SEaswaran Raman   Data = Data.substr(N);
719152fd17SVedant Kumar   return Error::success();
72dc707122SEaswaran Raman }
73dc707122SEaswaran Raman 
749152fd17SVedant Kumar Error RawCoverageReader::readIntMax(uint64_t &Result, uint64_t MaxPlus1) {
75dc707122SEaswaran Raman   if (auto Err = readULEB128(Result))
76dc707122SEaswaran Raman     return Err;
77dc707122SEaswaran Raman   if (Result >= MaxPlus1)
789152fd17SVedant Kumar     return make_error<CoverageMapError>(coveragemap_error::malformed);
799152fd17SVedant Kumar   return Error::success();
80dc707122SEaswaran Raman }
81dc707122SEaswaran Raman 
829152fd17SVedant Kumar Error RawCoverageReader::readSize(uint64_t &Result) {
83dc707122SEaswaran Raman   if (auto Err = readULEB128(Result))
84dc707122SEaswaran Raman     return Err;
85dc707122SEaswaran Raman   // Sanity check the number.
86dc707122SEaswaran Raman   if (Result > Data.size())
879152fd17SVedant Kumar     return make_error<CoverageMapError>(coveragemap_error::malformed);
889152fd17SVedant Kumar   return Error::success();
89dc707122SEaswaran Raman }
90dc707122SEaswaran Raman 
919152fd17SVedant Kumar Error RawCoverageReader::readString(StringRef &Result) {
92dc707122SEaswaran Raman   uint64_t Length;
93dc707122SEaswaran Raman   if (auto Err = readSize(Length))
94dc707122SEaswaran Raman     return Err;
95dc707122SEaswaran Raman   Result = Data.substr(0, Length);
96dc707122SEaswaran Raman   Data = Data.substr(Length);
979152fd17SVedant Kumar   return Error::success();
98dc707122SEaswaran Raman }
99dc707122SEaswaran Raman 
1009152fd17SVedant Kumar Error RawCoverageFilenamesReader::read() {
101dc707122SEaswaran Raman   uint64_t NumFilenames;
102dc707122SEaswaran Raman   if (auto Err = readSize(NumFilenames))
103dc707122SEaswaran Raman     return Err;
104dc707122SEaswaran Raman   for (size_t I = 0; I < NumFilenames; ++I) {
105dc707122SEaswaran Raman     StringRef Filename;
106dc707122SEaswaran Raman     if (auto Err = readString(Filename))
107dc707122SEaswaran Raman       return Err;
108dc707122SEaswaran Raman     Filenames.push_back(Filename);
109dc707122SEaswaran Raman   }
1109152fd17SVedant Kumar   return Error::success();
111dc707122SEaswaran Raman }
112dc707122SEaswaran Raman 
1139152fd17SVedant Kumar Error RawCoverageMappingReader::decodeCounter(unsigned Value, Counter &C) {
114dc707122SEaswaran Raman   auto Tag = Value & Counter::EncodingTagMask;
115dc707122SEaswaran Raman   switch (Tag) {
116dc707122SEaswaran Raman   case Counter::Zero:
117dc707122SEaswaran Raman     C = Counter::getZero();
1189152fd17SVedant Kumar     return Error::success();
119dc707122SEaswaran Raman   case Counter::CounterValueReference:
120dc707122SEaswaran Raman     C = Counter::getCounter(Value >> Counter::EncodingTagBits);
1219152fd17SVedant Kumar     return Error::success();
122dc707122SEaswaran Raman   default:
123dc707122SEaswaran Raman     break;
124dc707122SEaswaran Raman   }
125dc707122SEaswaran Raman   Tag -= Counter::Expression;
126dc707122SEaswaran Raman   switch (Tag) {
127dc707122SEaswaran Raman   case CounterExpression::Subtract:
128dc707122SEaswaran Raman   case CounterExpression::Add: {
129dc707122SEaswaran Raman     auto ID = Value >> Counter::EncodingTagBits;
130dc707122SEaswaran Raman     if (ID >= Expressions.size())
1319152fd17SVedant Kumar       return make_error<CoverageMapError>(coveragemap_error::malformed);
132dc707122SEaswaran Raman     Expressions[ID].Kind = CounterExpression::ExprKind(Tag);
133dc707122SEaswaran Raman     C = Counter::getExpression(ID);
134dc707122SEaswaran Raman     break;
135dc707122SEaswaran Raman   }
136dc707122SEaswaran Raman   default:
1379152fd17SVedant Kumar     return make_error<CoverageMapError>(coveragemap_error::malformed);
138dc707122SEaswaran Raman   }
1399152fd17SVedant Kumar   return Error::success();
140dc707122SEaswaran Raman }
141dc707122SEaswaran Raman 
1429152fd17SVedant Kumar Error RawCoverageMappingReader::readCounter(Counter &C) {
143dc707122SEaswaran Raman   uint64_t EncodedCounter;
144dc707122SEaswaran Raman   if (auto Err =
145dc707122SEaswaran Raman           readIntMax(EncodedCounter, std::numeric_limits<unsigned>::max()))
146dc707122SEaswaran Raman     return Err;
147dc707122SEaswaran Raman   if (auto Err = decodeCounter(EncodedCounter, C))
148dc707122SEaswaran Raman     return Err;
1499152fd17SVedant Kumar   return Error::success();
150dc707122SEaswaran Raman }
151dc707122SEaswaran Raman 
152dc707122SEaswaran Raman static const unsigned EncodingExpansionRegionBit = 1
153dc707122SEaswaran Raman                                                    << Counter::EncodingTagBits;
154dc707122SEaswaran Raman 
155dc707122SEaswaran Raman /// \brief Read the sub-array of regions for the given inferred file id.
156dc707122SEaswaran Raman /// \param NumFileIDs the number of file ids that are defined for this
157dc707122SEaswaran Raman /// function.
1589152fd17SVedant Kumar Error RawCoverageMappingReader::readMappingRegionsSubArray(
159dc707122SEaswaran Raman     std::vector<CounterMappingRegion> &MappingRegions, unsigned InferredFileID,
160dc707122SEaswaran Raman     size_t NumFileIDs) {
161dc707122SEaswaran Raman   uint64_t NumRegions;
162dc707122SEaswaran Raman   if (auto Err = readSize(NumRegions))
163dc707122SEaswaran Raman     return Err;
164dc707122SEaswaran Raman   unsigned LineStart = 0;
165dc707122SEaswaran Raman   for (size_t I = 0; I < NumRegions; ++I) {
166dc707122SEaswaran Raman     Counter C;
167dc707122SEaswaran Raman     CounterMappingRegion::RegionKind Kind = CounterMappingRegion::CodeRegion;
168dc707122SEaswaran Raman 
169dc707122SEaswaran Raman     // Read the combined counter + region kind.
170dc707122SEaswaran Raman     uint64_t EncodedCounterAndRegion;
171dc707122SEaswaran Raman     if (auto Err = readIntMax(EncodedCounterAndRegion,
172dc707122SEaswaran Raman                               std::numeric_limits<unsigned>::max()))
173dc707122SEaswaran Raman       return Err;
174dc707122SEaswaran Raman     unsigned Tag = EncodedCounterAndRegion & Counter::EncodingTagMask;
175dc707122SEaswaran Raman     uint64_t ExpandedFileID = 0;
176dc707122SEaswaran Raman     if (Tag != Counter::Zero) {
177dc707122SEaswaran Raman       if (auto Err = decodeCounter(EncodedCounterAndRegion, C))
178dc707122SEaswaran Raman         return Err;
179dc707122SEaswaran Raman     } else {
180dc707122SEaswaran Raman       // Is it an expansion region?
181dc707122SEaswaran Raman       if (EncodedCounterAndRegion & EncodingExpansionRegionBit) {
182dc707122SEaswaran Raman         Kind = CounterMappingRegion::ExpansionRegion;
183dc707122SEaswaran Raman         ExpandedFileID = EncodedCounterAndRegion >>
184dc707122SEaswaran Raman                          Counter::EncodingCounterTagAndExpansionRegionTagBits;
185dc707122SEaswaran Raman         if (ExpandedFileID >= NumFileIDs)
1869152fd17SVedant Kumar           return make_error<CoverageMapError>(coveragemap_error::malformed);
187dc707122SEaswaran Raman       } else {
188dc707122SEaswaran Raman         switch (EncodedCounterAndRegion >>
189dc707122SEaswaran Raman                 Counter::EncodingCounterTagAndExpansionRegionTagBits) {
190dc707122SEaswaran Raman         case CounterMappingRegion::CodeRegion:
191dc707122SEaswaran Raman           // Don't do anything when we have a code region with a zero counter.
192dc707122SEaswaran Raman           break;
193dc707122SEaswaran Raman         case CounterMappingRegion::SkippedRegion:
194dc707122SEaswaran Raman           Kind = CounterMappingRegion::SkippedRegion;
195dc707122SEaswaran Raman           break;
196dc707122SEaswaran Raman         default:
1979152fd17SVedant Kumar           return make_error<CoverageMapError>(coveragemap_error::malformed);
198dc707122SEaswaran Raman         }
199dc707122SEaswaran Raman       }
200dc707122SEaswaran Raman     }
201dc707122SEaswaran Raman 
202dc707122SEaswaran Raman     // Read the source range.
203dc707122SEaswaran Raman     uint64_t LineStartDelta, ColumnStart, NumLines, ColumnEnd;
204dc707122SEaswaran Raman     if (auto Err =
205dc707122SEaswaran Raman             readIntMax(LineStartDelta, std::numeric_limits<unsigned>::max()))
206dc707122SEaswaran Raman       return Err;
207dc707122SEaswaran Raman     if (auto Err = readULEB128(ColumnStart))
208dc707122SEaswaran Raman       return Err;
209dc707122SEaswaran Raman     if (ColumnStart > std::numeric_limits<unsigned>::max())
2109152fd17SVedant Kumar       return make_error<CoverageMapError>(coveragemap_error::malformed);
211dc707122SEaswaran Raman     if (auto Err = readIntMax(NumLines, std::numeric_limits<unsigned>::max()))
212dc707122SEaswaran Raman       return Err;
213dc707122SEaswaran Raman     if (auto Err = readIntMax(ColumnEnd, std::numeric_limits<unsigned>::max()))
214dc707122SEaswaran Raman       return Err;
215dc707122SEaswaran Raman     LineStart += LineStartDelta;
216dc707122SEaswaran Raman     // Adjust the column locations for the empty regions that are supposed to
217dc707122SEaswaran Raman     // cover whole lines. Those regions should be encoded with the
218dc707122SEaswaran Raman     // column range (1 -> std::numeric_limits<unsigned>::max()), but because
219dc707122SEaswaran Raman     // the encoded std::numeric_limits<unsigned>::max() is several bytes long,
220dc707122SEaswaran Raman     // we set the column range to (0 -> 0) to ensure that the column start and
221dc707122SEaswaran Raman     // column end take up one byte each.
222dc707122SEaswaran Raman     // The std::numeric_limits<unsigned>::max() is used to represent a column
223dc707122SEaswaran Raman     // position at the end of the line without knowing the length of that line.
224dc707122SEaswaran Raman     if (ColumnStart == 0 && ColumnEnd == 0) {
225dc707122SEaswaran Raman       ColumnStart = 1;
226dc707122SEaswaran Raman       ColumnEnd = std::numeric_limits<unsigned>::max();
227dc707122SEaswaran Raman     }
228dc707122SEaswaran Raman 
229dc707122SEaswaran Raman     DEBUG({
230dc707122SEaswaran Raman       dbgs() << "Counter in file " << InferredFileID << " " << LineStart << ":"
231dc707122SEaswaran Raman              << ColumnStart << " -> " << (LineStart + NumLines) << ":"
232dc707122SEaswaran Raman              << ColumnEnd << ", ";
233dc707122SEaswaran Raman       if (Kind == CounterMappingRegion::ExpansionRegion)
234dc707122SEaswaran Raman         dbgs() << "Expands to file " << ExpandedFileID;
235dc707122SEaswaran Raman       else
236dc707122SEaswaran Raman         CounterMappingContext(Expressions).dump(C, dbgs());
237dc707122SEaswaran Raman       dbgs() << "\n";
238dc707122SEaswaran Raman     });
239dc707122SEaswaran Raman 
240dc707122SEaswaran Raman     MappingRegions.push_back(CounterMappingRegion(
241dc707122SEaswaran Raman         C, InferredFileID, ExpandedFileID, LineStart, ColumnStart,
242dc707122SEaswaran Raman         LineStart + NumLines, ColumnEnd, Kind));
243dc707122SEaswaran Raman   }
2449152fd17SVedant Kumar   return Error::success();
245dc707122SEaswaran Raman }
246dc707122SEaswaran Raman 
2479152fd17SVedant Kumar Error RawCoverageMappingReader::read() {
248dc707122SEaswaran Raman   // Read the virtual file mapping.
249*e78d131aSEugene Zelenko   SmallVector<unsigned, 8> VirtualFileMapping;
250dc707122SEaswaran Raman   uint64_t NumFileMappings;
251dc707122SEaswaran Raman   if (auto Err = readSize(NumFileMappings))
252dc707122SEaswaran Raman     return Err;
253dc707122SEaswaran Raman   for (size_t I = 0; I < NumFileMappings; ++I) {
254dc707122SEaswaran Raman     uint64_t FilenameIndex;
255dc707122SEaswaran Raman     if (auto Err = readIntMax(FilenameIndex, TranslationUnitFilenames.size()))
256dc707122SEaswaran Raman       return Err;
257dc707122SEaswaran Raman     VirtualFileMapping.push_back(FilenameIndex);
258dc707122SEaswaran Raman   }
259dc707122SEaswaran Raman 
260dc707122SEaswaran Raman   // Construct the files using unique filenames and virtual file mapping.
261dc707122SEaswaran Raman   for (auto I : VirtualFileMapping) {
262dc707122SEaswaran Raman     Filenames.push_back(TranslationUnitFilenames[I]);
263dc707122SEaswaran Raman   }
264dc707122SEaswaran Raman 
265dc707122SEaswaran Raman   // Read the expressions.
266dc707122SEaswaran Raman   uint64_t NumExpressions;
267dc707122SEaswaran Raman   if (auto Err = readSize(NumExpressions))
268dc707122SEaswaran Raman     return Err;
269dc707122SEaswaran Raman   // Create an array of dummy expressions that get the proper counters
270dc707122SEaswaran Raman   // when the expressions are read, and the proper kinds when the counters
271dc707122SEaswaran Raman   // are decoded.
272dc707122SEaswaran Raman   Expressions.resize(
273dc707122SEaswaran Raman       NumExpressions,
274dc707122SEaswaran Raman       CounterExpression(CounterExpression::Subtract, Counter(), Counter()));
275dc707122SEaswaran Raman   for (size_t I = 0; I < NumExpressions; ++I) {
276dc707122SEaswaran Raman     if (auto Err = readCounter(Expressions[I].LHS))
277dc707122SEaswaran Raman       return Err;
278dc707122SEaswaran Raman     if (auto Err = readCounter(Expressions[I].RHS))
279dc707122SEaswaran Raman       return Err;
280dc707122SEaswaran Raman   }
281dc707122SEaswaran Raman 
282dc707122SEaswaran Raman   // Read the mapping regions sub-arrays.
283dc707122SEaswaran Raman   for (unsigned InferredFileID = 0, S = VirtualFileMapping.size();
284dc707122SEaswaran Raman        InferredFileID < S; ++InferredFileID) {
285dc707122SEaswaran Raman     if (auto Err = readMappingRegionsSubArray(MappingRegions, InferredFileID,
286dc707122SEaswaran Raman                                               VirtualFileMapping.size()))
287dc707122SEaswaran Raman       return Err;
288dc707122SEaswaran Raman   }
289dc707122SEaswaran Raman 
290dc707122SEaswaran Raman   // Set the counters for the expansion regions.
291dc707122SEaswaran Raman   // i.e. Counter of expansion region = counter of the first region
292dc707122SEaswaran Raman   // from the expanded file.
293dc707122SEaswaran Raman   // Perform multiple passes to correctly propagate the counters through
294dc707122SEaswaran Raman   // all the nested expansion regions.
295dc707122SEaswaran Raman   SmallVector<CounterMappingRegion *, 8> FileIDExpansionRegionMapping;
296dc707122SEaswaran Raman   FileIDExpansionRegionMapping.resize(VirtualFileMapping.size(), nullptr);
297dc707122SEaswaran Raman   for (unsigned Pass = 1, S = VirtualFileMapping.size(); Pass < S; ++Pass) {
298dc707122SEaswaran Raman     for (auto &R : MappingRegions) {
299dc707122SEaswaran Raman       if (R.Kind != CounterMappingRegion::ExpansionRegion)
300dc707122SEaswaran Raman         continue;
301dc707122SEaswaran Raman       assert(!FileIDExpansionRegionMapping[R.ExpandedFileID]);
302dc707122SEaswaran Raman       FileIDExpansionRegionMapping[R.ExpandedFileID] = &R;
303dc707122SEaswaran Raman     }
304dc707122SEaswaran Raman     for (auto &R : MappingRegions) {
305dc707122SEaswaran Raman       if (FileIDExpansionRegionMapping[R.FileID]) {
306dc707122SEaswaran Raman         FileIDExpansionRegionMapping[R.FileID]->Count = R.Count;
307dc707122SEaswaran Raman         FileIDExpansionRegionMapping[R.FileID] = nullptr;
308dc707122SEaswaran Raman       }
309dc707122SEaswaran Raman     }
310dc707122SEaswaran Raman   }
311dc707122SEaswaran Raman 
3129152fd17SVedant Kumar   return Error::success();
313dc707122SEaswaran Raman }
314dc707122SEaswaran Raman 
315ac40e819SIgor Kudrin Expected<bool> RawCoverageMappingDummyChecker::isDummy() {
316ac40e819SIgor Kudrin   // A dummy coverage mapping data consists of just one region with zero count.
317ac40e819SIgor Kudrin   uint64_t NumFileMappings;
318ac40e819SIgor Kudrin   if (Error Err = readSize(NumFileMappings))
319ac40e819SIgor Kudrin     return std::move(Err);
320ac40e819SIgor Kudrin   if (NumFileMappings != 1)
321ac40e819SIgor Kudrin     return false;
322ac40e819SIgor Kudrin   // We don't expect any specific value for the filename index, just skip it.
323ac40e819SIgor Kudrin   uint64_t FilenameIndex;
324ac40e819SIgor Kudrin   if (Error Err =
325ac40e819SIgor Kudrin           readIntMax(FilenameIndex, std::numeric_limits<unsigned>::max()))
326ac40e819SIgor Kudrin     return std::move(Err);
327ac40e819SIgor Kudrin   uint64_t NumExpressions;
328ac40e819SIgor Kudrin   if (Error Err = readSize(NumExpressions))
329ac40e819SIgor Kudrin     return std::move(Err);
330ac40e819SIgor Kudrin   if (NumExpressions != 0)
331ac40e819SIgor Kudrin     return false;
332ac40e819SIgor Kudrin   uint64_t NumRegions;
333ac40e819SIgor Kudrin   if (Error Err = readSize(NumRegions))
334ac40e819SIgor Kudrin     return std::move(Err);
335ac40e819SIgor Kudrin   if (NumRegions != 1)
336ac40e819SIgor Kudrin     return false;
337ac40e819SIgor Kudrin   uint64_t EncodedCounterAndRegion;
338ac40e819SIgor Kudrin   if (Error Err = readIntMax(EncodedCounterAndRegion,
339ac40e819SIgor Kudrin                              std::numeric_limits<unsigned>::max()))
340ac40e819SIgor Kudrin     return std::move(Err);
341ac40e819SIgor Kudrin   unsigned Tag = EncodedCounterAndRegion & Counter::EncodingTagMask;
342ac40e819SIgor Kudrin   return Tag == Counter::Zero;
343ac40e819SIgor Kudrin }
344ac40e819SIgor Kudrin 
3459152fd17SVedant Kumar Error InstrProfSymtab::create(SectionRef &Section) {
3469152fd17SVedant Kumar   if (auto EC = Section.getContents(Data))
3479152fd17SVedant Kumar     return errorCodeToError(EC);
348dc707122SEaswaran Raman   Address = Section.getAddress();
3499152fd17SVedant Kumar   return Error::success();
350dc707122SEaswaran Raman }
351dc707122SEaswaran Raman 
352dc707122SEaswaran Raman StringRef InstrProfSymtab::getFuncName(uint64_t Pointer, size_t Size) {
353dc707122SEaswaran Raman   if (Pointer < Address)
354dc707122SEaswaran Raman     return StringRef();
355dc707122SEaswaran Raman   auto Offset = Pointer - Address;
356dc707122SEaswaran Raman   if (Offset + Size > Data.size())
357dc707122SEaswaran Raman     return StringRef();
358dc707122SEaswaran Raman   return Data.substr(Pointer - Address, Size);
359dc707122SEaswaran Raman }
360dc707122SEaswaran Raman 
361ac40e819SIgor Kudrin // Check if the mapping data is a dummy, i.e. is emitted for an unused function.
362ac40e819SIgor Kudrin static Expected<bool> isCoverageMappingDummy(uint64_t Hash, StringRef Mapping) {
363ac40e819SIgor Kudrin   // The hash value of dummy mapping records is always zero.
364ac40e819SIgor Kudrin   if (Hash)
365ac40e819SIgor Kudrin     return false;
366ac40e819SIgor Kudrin   return RawCoverageMappingDummyChecker(Mapping).isDummy();
367ac40e819SIgor Kudrin }
368ac40e819SIgor Kudrin 
369dc707122SEaswaran Raman namespace {
370*e78d131aSEugene Zelenko 
371dc707122SEaswaran Raman struct CovMapFuncRecordReader {
372*e78d131aSEugene Zelenko   virtual ~CovMapFuncRecordReader() = default;
373*e78d131aSEugene Zelenko 
3743739b95dSVedant Kumar   // The interface to read coverage mapping function records for a module.
3753739b95dSVedant Kumar   //
3763739b95dSVedant Kumar   // \p Buf points to the buffer containing the \c CovHeader of the coverage
3773739b95dSVedant Kumar   // mapping data associated with the module.
3783739b95dSVedant Kumar   //
3793739b95dSVedant Kumar   // Returns a pointer to the next \c CovHeader if it exists, or a pointer
3803739b95dSVedant Kumar   // greater than \p End if not.
3813739b95dSVedant Kumar   virtual Expected<const char *> readFunctionRecords(const char *Buf,
3823739b95dSVedant Kumar                                                      const char *End) = 0;
383*e78d131aSEugene Zelenko 
384dc707122SEaswaran Raman   template <class IntPtrT, support::endianness Endian>
3859152fd17SVedant Kumar   static Expected<std::unique_ptr<CovMapFuncRecordReader>>
386*e78d131aSEugene Zelenko   get(CovMapVersion Version, InstrProfSymtab &P,
387dc707122SEaswaran Raman       std::vector<BinaryCoverageReader::ProfileMappingRecord> &R,
388dc707122SEaswaran Raman       std::vector<StringRef> &F);
389dc707122SEaswaran Raman };
390dc707122SEaswaran Raman 
391dc707122SEaswaran Raman // A class for reading coverage mapping function records for a module.
392*e78d131aSEugene Zelenko template <CovMapVersion Version, class IntPtrT, support::endianness Endian>
393dc707122SEaswaran Raman class VersionedCovMapFuncRecordReader : public CovMapFuncRecordReader {
394*e78d131aSEugene Zelenko   typedef typename CovMapTraits<
395dc707122SEaswaran Raman       Version, IntPtrT>::CovMapFuncRecordType FuncRecordType;
396*e78d131aSEugene Zelenko   typedef typename CovMapTraits<Version, IntPtrT>::NameRefType  NameRefType;
397dc707122SEaswaran Raman 
398ac40e819SIgor Kudrin   // Maps function's name references to the indexes of their records
399ac40e819SIgor Kudrin   // in \c Records.
400*e78d131aSEugene Zelenko   DenseMap<NameRefType, size_t> FunctionRecords;
401dc707122SEaswaran Raman   InstrProfSymtab &ProfileNames;
402dc707122SEaswaran Raman   std::vector<StringRef> &Filenames;
403dc707122SEaswaran Raman   std::vector<BinaryCoverageReader::ProfileMappingRecord> &Records;
404dc707122SEaswaran Raman 
405ac40e819SIgor Kudrin   // Add the record to the collection if we don't already have a record that
406ac40e819SIgor Kudrin   // points to the same function name. This is useful to ignore the redundant
407ac40e819SIgor Kudrin   // records for the functions with ODR linkage.
408ac40e819SIgor Kudrin   // In addition, prefer records with real coverage mapping data to dummy
409ac40e819SIgor Kudrin   // records, which were emitted for inline functions which were seen but
410ac40e819SIgor Kudrin   // not used in the corresponding translation unit.
411ac40e819SIgor Kudrin   Error insertFunctionRecordIfNeeded(const FuncRecordType *CFR,
412ac40e819SIgor Kudrin                                      StringRef Mapping, size_t FilenamesBegin) {
413ac40e819SIgor Kudrin     uint64_t FuncHash = CFR->template getFuncHash<Endian>();
414ac40e819SIgor Kudrin     NameRefType NameRef = CFR->template getFuncNameRef<Endian>();
415ac40e819SIgor Kudrin     auto InsertResult =
416ac40e819SIgor Kudrin         FunctionRecords.insert(std::make_pair(NameRef, Records.size()));
417ac40e819SIgor Kudrin     if (InsertResult.second) {
418ac40e819SIgor Kudrin       StringRef FuncName;
419ac40e819SIgor Kudrin       if (Error Err = CFR->template getFuncName<Endian>(ProfileNames, FuncName))
420ac40e819SIgor Kudrin         return Err;
421ac40e819SIgor Kudrin       Records.emplace_back(Version, FuncName, FuncHash, Mapping, FilenamesBegin,
422ac40e819SIgor Kudrin                            Filenames.size() - FilenamesBegin);
423ac40e819SIgor Kudrin       return Error::success();
424ac40e819SIgor Kudrin     }
425ac40e819SIgor Kudrin     // Update the existing record if it's a dummy and the new record is real.
426ac40e819SIgor Kudrin     size_t OldRecordIndex = InsertResult.first->second;
427ac40e819SIgor Kudrin     BinaryCoverageReader::ProfileMappingRecord &OldRecord =
428ac40e819SIgor Kudrin         Records[OldRecordIndex];
429ac40e819SIgor Kudrin     Expected<bool> OldIsDummyExpected = isCoverageMappingDummy(
430ac40e819SIgor Kudrin         OldRecord.FunctionHash, OldRecord.CoverageMapping);
431ac40e819SIgor Kudrin     if (Error Err = OldIsDummyExpected.takeError())
432ac40e819SIgor Kudrin       return Err;
433ac40e819SIgor Kudrin     if (!*OldIsDummyExpected)
434ac40e819SIgor Kudrin       return Error::success();
435ac40e819SIgor Kudrin     Expected<bool> NewIsDummyExpected =
436ac40e819SIgor Kudrin         isCoverageMappingDummy(FuncHash, Mapping);
437ac40e819SIgor Kudrin     if (Error Err = NewIsDummyExpected.takeError())
438ac40e819SIgor Kudrin       return Err;
439ac40e819SIgor Kudrin     if (*NewIsDummyExpected)
440ac40e819SIgor Kudrin       return Error::success();
441ac40e819SIgor Kudrin     OldRecord.FunctionHash = FuncHash;
442ac40e819SIgor Kudrin     OldRecord.CoverageMapping = Mapping;
443ac40e819SIgor Kudrin     OldRecord.FilenamesBegin = FilenamesBegin;
444ac40e819SIgor Kudrin     OldRecord.FilenamesSize = Filenames.size() - FilenamesBegin;
445ac40e819SIgor Kudrin     return Error::success();
446ac40e819SIgor Kudrin   }
447ac40e819SIgor Kudrin 
448dc707122SEaswaran Raman public:
449dc707122SEaswaran Raman   VersionedCovMapFuncRecordReader(
450dc707122SEaswaran Raman       InstrProfSymtab &P,
451dc707122SEaswaran Raman       std::vector<BinaryCoverageReader::ProfileMappingRecord> &R,
452dc707122SEaswaran Raman       std::vector<StringRef> &F)
453dc707122SEaswaran Raman       : ProfileNames(P), Filenames(F), Records(R) {}
454*e78d131aSEugene Zelenko 
455*e78d131aSEugene Zelenko   ~VersionedCovMapFuncRecordReader() override = default;
456dc707122SEaswaran Raman 
4573739b95dSVedant Kumar   Expected<const char *> readFunctionRecords(const char *Buf,
4583739b95dSVedant Kumar                                              const char *End) override {
459dc707122SEaswaran Raman     using namespace support;
460*e78d131aSEugene Zelenko 
461dc707122SEaswaran Raman     if (Buf + sizeof(CovMapHeader) > End)
4629152fd17SVedant Kumar       return make_error<CoverageMapError>(coveragemap_error::malformed);
463*e78d131aSEugene Zelenko     auto CovHeader = reinterpret_cast<const CovMapHeader *>(Buf);
464dc707122SEaswaran Raman     uint32_t NRecords = CovHeader->getNRecords<Endian>();
465dc707122SEaswaran Raman     uint32_t FilenamesSize = CovHeader->getFilenamesSize<Endian>();
466dc707122SEaswaran Raman     uint32_t CoverageSize = CovHeader->getCoverageSize<Endian>();
467dc707122SEaswaran Raman     assert((CovMapVersion)CovHeader->getVersion<Endian>() == Version);
468dc707122SEaswaran Raman     Buf = reinterpret_cast<const char *>(CovHeader + 1);
469dc707122SEaswaran Raman 
470dc707122SEaswaran Raman     // Skip past the function records, saving the start and end for later.
471dc707122SEaswaran Raman     const char *FunBuf = Buf;
472dc707122SEaswaran Raman     Buf += NRecords * sizeof(FuncRecordType);
473dc707122SEaswaran Raman     const char *FunEnd = Buf;
474dc707122SEaswaran Raman 
475dc707122SEaswaran Raman     // Get the filenames.
476dc707122SEaswaran Raman     if (Buf + FilenamesSize > End)
4779152fd17SVedant Kumar       return make_error<CoverageMapError>(coveragemap_error::malformed);
478dc707122SEaswaran Raman     size_t FilenamesBegin = Filenames.size();
479dc707122SEaswaran Raman     RawCoverageFilenamesReader Reader(StringRef(Buf, FilenamesSize), Filenames);
480dc707122SEaswaran Raman     if (auto Err = Reader.read())
4813739b95dSVedant Kumar       return std::move(Err);
482dc707122SEaswaran Raman     Buf += FilenamesSize;
483dc707122SEaswaran Raman 
484dc707122SEaswaran Raman     // We'll read the coverage mapping records in the loop below.
485dc707122SEaswaran Raman     const char *CovBuf = Buf;
486dc707122SEaswaran Raman     Buf += CoverageSize;
487dc707122SEaswaran Raman     const char *CovEnd = Buf;
488dc707122SEaswaran Raman 
489dc707122SEaswaran Raman     if (Buf > End)
4909152fd17SVedant Kumar       return make_error<CoverageMapError>(coveragemap_error::malformed);
491dc707122SEaswaran Raman     // Each coverage map has an alignment of 8, so we need to adjust alignment
492dc707122SEaswaran Raman     // before reading the next map.
493dc707122SEaswaran Raman     Buf += alignmentAdjustment(Buf, 8);
494dc707122SEaswaran Raman 
495dc707122SEaswaran Raman     auto CFR = reinterpret_cast<const FuncRecordType *>(FunBuf);
496dc707122SEaswaran Raman     while ((const char *)CFR < FunEnd) {
497dc707122SEaswaran Raman       // Read the function information
498dc707122SEaswaran Raman       uint32_t DataSize = CFR->template getDataSize<Endian>();
499dc707122SEaswaran Raman 
500dc707122SEaswaran Raman       // Now use that to read the coverage data.
501dc707122SEaswaran Raman       if (CovBuf + DataSize > CovEnd)
5029152fd17SVedant Kumar         return make_error<CoverageMapError>(coveragemap_error::malformed);
503dc707122SEaswaran Raman       auto Mapping = StringRef(CovBuf, DataSize);
504dc707122SEaswaran Raman       CovBuf += DataSize;
505dc707122SEaswaran Raman 
506ac40e819SIgor Kudrin       if (Error Err =
507ac40e819SIgor Kudrin               insertFunctionRecordIfNeeded(CFR, Mapping, FilenamesBegin))
5083739b95dSVedant Kumar         return std::move(Err);
509dc707122SEaswaran Raman       CFR++;
510dc707122SEaswaran Raman     }
5113739b95dSVedant Kumar     return Buf;
512dc707122SEaswaran Raman   }
513dc707122SEaswaran Raman };
514*e78d131aSEugene Zelenko 
515dc707122SEaswaran Raman } // end anonymous namespace
516dc707122SEaswaran Raman 
517dc707122SEaswaran Raman template <class IntPtrT, support::endianness Endian>
5189152fd17SVedant Kumar Expected<std::unique_ptr<CovMapFuncRecordReader>> CovMapFuncRecordReader::get(
519*e78d131aSEugene Zelenko     CovMapVersion Version, InstrProfSymtab &P,
520dc707122SEaswaran Raman     std::vector<BinaryCoverageReader::ProfileMappingRecord> &R,
521dc707122SEaswaran Raman     std::vector<StringRef> &F) {
522dc707122SEaswaran Raman   using namespace coverage;
523*e78d131aSEugene Zelenko 
524dc707122SEaswaran Raman   switch (Version) {
525dc707122SEaswaran Raman   case CovMapVersion::Version1:
526dc707122SEaswaran Raman     return llvm::make_unique<VersionedCovMapFuncRecordReader<
527dc707122SEaswaran Raman         CovMapVersion::Version1, IntPtrT, Endian>>(P, R, F);
528dc707122SEaswaran Raman   case CovMapVersion::Version2:
529dc707122SEaswaran Raman     // Decompress the name data.
5309152fd17SVedant Kumar     if (Error E = P.create(P.getNameData()))
5319152fd17SVedant Kumar       return std::move(E);
532dc707122SEaswaran Raman     return llvm::make_unique<VersionedCovMapFuncRecordReader<
533dc707122SEaswaran Raman         CovMapVersion::Version2, IntPtrT, Endian>>(P, R, F);
534dc707122SEaswaran Raman   }
535dc707122SEaswaran Raman   llvm_unreachable("Unsupported version");
536dc707122SEaswaran Raman }
537dc707122SEaswaran Raman 
538dc707122SEaswaran Raman template <typename T, support::endianness Endian>
5399152fd17SVedant Kumar static Error readCoverageMappingData(
540dc707122SEaswaran Raman     InstrProfSymtab &ProfileNames, StringRef Data,
541dc707122SEaswaran Raman     std::vector<BinaryCoverageReader::ProfileMappingRecord> &Records,
542dc707122SEaswaran Raman     std::vector<StringRef> &Filenames) {
543dc707122SEaswaran Raman   using namespace coverage;
544*e78d131aSEugene Zelenko 
545dc707122SEaswaran Raman   // Read the records in the coverage data section.
546dc707122SEaswaran Raman   auto CovHeader =
547*e78d131aSEugene Zelenko       reinterpret_cast<const CovMapHeader *>(Data.data());
548dc707122SEaswaran Raman   CovMapVersion Version = (CovMapVersion)CovHeader->getVersion<Endian>();
549*e78d131aSEugene Zelenko   if (Version > CovMapVersion::CurrentVersion)
5509152fd17SVedant Kumar     return make_error<CoverageMapError>(coveragemap_error::unsupported_version);
5519152fd17SVedant Kumar   Expected<std::unique_ptr<CovMapFuncRecordReader>> ReaderExpected =
552dc707122SEaswaran Raman       CovMapFuncRecordReader::get<T, Endian>(Version, ProfileNames, Records,
553dc707122SEaswaran Raman                                              Filenames);
5549152fd17SVedant Kumar   if (Error E = ReaderExpected.takeError())
5559152fd17SVedant Kumar     return E;
5569152fd17SVedant Kumar   auto Reader = std::move(ReaderExpected.get());
557dc707122SEaswaran Raman   for (const char *Buf = Data.data(), *End = Buf + Data.size(); Buf < End;) {
5583739b95dSVedant Kumar     auto NextHeaderOrErr = Reader->readFunctionRecords(Buf, End);
5593739b95dSVedant Kumar     if (auto E = NextHeaderOrErr.takeError())
5609152fd17SVedant Kumar       return E;
5613739b95dSVedant Kumar     Buf = NextHeaderOrErr.get();
562dc707122SEaswaran Raman   }
5639152fd17SVedant Kumar   return Error::success();
564dc707122SEaswaran Raman }
565*e78d131aSEugene Zelenko 
566dc707122SEaswaran Raman static const char *TestingFormatMagic = "llvmcovmtestdata";
567dc707122SEaswaran Raman 
5689152fd17SVedant Kumar static Error loadTestingFormat(StringRef Data, InstrProfSymtab &ProfileNames,
569dc707122SEaswaran Raman                                StringRef &CoverageMapping,
570dc707122SEaswaran Raman                                uint8_t &BytesInAddress,
571dc707122SEaswaran Raman                                support::endianness &Endian) {
572dc707122SEaswaran Raman   BytesInAddress = 8;
573dc707122SEaswaran Raman   Endian = support::endianness::little;
574dc707122SEaswaran Raman 
575dc707122SEaswaran Raman   Data = Data.substr(StringRef(TestingFormatMagic).size());
576dc707122SEaswaran Raman   if (Data.size() < 1)
5779152fd17SVedant Kumar     return make_error<CoverageMapError>(coveragemap_error::truncated);
578dc707122SEaswaran Raman   unsigned N = 0;
579dc707122SEaswaran Raman   auto ProfileNamesSize =
580dc707122SEaswaran Raman       decodeULEB128(reinterpret_cast<const uint8_t *>(Data.data()), &N);
581dc707122SEaswaran Raman   if (N > Data.size())
5829152fd17SVedant Kumar     return make_error<CoverageMapError>(coveragemap_error::malformed);
583dc707122SEaswaran Raman   Data = Data.substr(N);
584dc707122SEaswaran Raman   if (Data.size() < 1)
5859152fd17SVedant Kumar     return make_error<CoverageMapError>(coveragemap_error::truncated);
586dc707122SEaswaran Raman   N = 0;
587dc707122SEaswaran Raman   uint64_t Address =
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);
592dc707122SEaswaran Raman   if (Data.size() < ProfileNamesSize)
5939152fd17SVedant Kumar     return make_error<CoverageMapError>(coveragemap_error::malformed);
5949152fd17SVedant Kumar   if (Error E = ProfileNames.create(Data.substr(0, ProfileNamesSize), Address))
5959152fd17SVedant Kumar     return E;
596dc707122SEaswaran Raman   CoverageMapping = Data.substr(ProfileNamesSize);
597eb103073SIgor Kudrin   // Skip the padding bytes because coverage map data has an alignment of 8.
598eb103073SIgor Kudrin   if (CoverageMapping.size() < 1)
5999152fd17SVedant Kumar     return make_error<CoverageMapError>(coveragemap_error::truncated);
600eb103073SIgor Kudrin   size_t Pad = alignmentAdjustment(CoverageMapping.data(), 8);
601eb103073SIgor Kudrin   if (CoverageMapping.size() < Pad)
6029152fd17SVedant Kumar     return make_error<CoverageMapError>(coveragemap_error::malformed);
603eb103073SIgor Kudrin   CoverageMapping = CoverageMapping.substr(Pad);
6049152fd17SVedant Kumar   return Error::success();
605dc707122SEaswaran Raman }
606dc707122SEaswaran Raman 
6079152fd17SVedant Kumar static Expected<SectionRef> lookupSection(ObjectFile &OF, StringRef Name) {
608dc707122SEaswaran Raman   StringRef FoundName;
609dc707122SEaswaran Raman   for (const auto &Section : OF.sections()) {
610dc707122SEaswaran Raman     if (auto EC = Section.getName(FoundName))
6119152fd17SVedant Kumar       return errorCodeToError(EC);
612dc707122SEaswaran Raman     if (FoundName == Name)
613dc707122SEaswaran Raman       return Section;
614dc707122SEaswaran Raman   }
6159152fd17SVedant Kumar   return make_error<CoverageMapError>(coveragemap_error::no_data_found);
616dc707122SEaswaran Raman }
617dc707122SEaswaran Raman 
6189152fd17SVedant Kumar static Error loadBinaryFormat(MemoryBufferRef ObjectBuffer,
6199152fd17SVedant Kumar                               InstrProfSymtab &ProfileNames,
6209152fd17SVedant Kumar                               StringRef &CoverageMapping,
6219152fd17SVedant Kumar                               uint8_t &BytesInAddress,
622dc707122SEaswaran Raman                               support::endianness &Endian, StringRef Arch) {
623*e78d131aSEugene Zelenko   auto BinOrErr = createBinary(ObjectBuffer);
624dc707122SEaswaran Raman   if (!BinOrErr)
6259152fd17SVedant Kumar     return BinOrErr.takeError();
626dc707122SEaswaran Raman   auto Bin = std::move(BinOrErr.get());
627dc707122SEaswaran Raman   std::unique_ptr<ObjectFile> OF;
628*e78d131aSEugene Zelenko   if (auto *Universal = dyn_cast<MachOUniversalBinary>(Bin.get())) {
629dc707122SEaswaran Raman     // If we have a universal binary, try to look up the object for the
630dc707122SEaswaran Raman     // appropriate architecture.
631dc707122SEaswaran Raman     auto ObjectFileOrErr = Universal->getObjectForArch(Arch);
6329acb1099SKevin Enderby     if (!ObjectFileOrErr)
6339acb1099SKevin Enderby       return ObjectFileOrErr.takeError();
634dc707122SEaswaran Raman     OF = std::move(ObjectFileOrErr.get());
635*e78d131aSEugene Zelenko   } else if (isa<ObjectFile>(Bin.get())) {
636dc707122SEaswaran Raman     // For any other object file, upcast and take ownership.
637*e78d131aSEugene Zelenko     OF.reset(cast<ObjectFile>(Bin.release()));
638dc707122SEaswaran Raman     // If we've asked for a particular arch, make sure they match.
639dc707122SEaswaran Raman     if (!Arch.empty() && OF->getArch() != Triple(Arch).getArch())
6409152fd17SVedant Kumar       return errorCodeToError(object_error::arch_not_found);
641dc707122SEaswaran Raman   } else
642dc707122SEaswaran Raman     // We can only handle object files.
6439152fd17SVedant Kumar     return make_error<CoverageMapError>(coveragemap_error::malformed);
644dc707122SEaswaran Raman 
645dc707122SEaswaran Raman   // The coverage uses native pointer sizes for the object it's written in.
646dc707122SEaswaran Raman   BytesInAddress = OF->getBytesInAddress();
647dc707122SEaswaran Raman   Endian = OF->isLittleEndian() ? support::endianness::little
648dc707122SEaswaran Raman                                 : support::endianness::big;
649dc707122SEaswaran Raman 
650dc707122SEaswaran Raman   // Look for the sections that we are interested in.
651dc707122SEaswaran Raman   auto NamesSection = lookupSection(*OF, getInstrProfNameSectionName(false));
6529152fd17SVedant Kumar   if (auto E = NamesSection.takeError())
6539152fd17SVedant Kumar     return E;
654dc707122SEaswaran Raman   auto CoverageSection =
655dc707122SEaswaran Raman       lookupSection(*OF, getInstrProfCoverageSectionName(false));
6569152fd17SVedant Kumar   if (auto E = CoverageSection.takeError())
6579152fd17SVedant Kumar     return E;
658dc707122SEaswaran Raman 
659dc707122SEaswaran Raman   // Get the contents of the given sections.
6609152fd17SVedant Kumar   if (auto EC = CoverageSection->getContents(CoverageMapping))
6619152fd17SVedant Kumar     return errorCodeToError(EC);
6629152fd17SVedant Kumar   if (Error E = ProfileNames.create(*NamesSection))
6639152fd17SVedant Kumar     return E;
664dc707122SEaswaran Raman 
6659152fd17SVedant Kumar   return Error::success();
666dc707122SEaswaran Raman }
667dc707122SEaswaran Raman 
6689152fd17SVedant Kumar Expected<std::unique_ptr<BinaryCoverageReader>>
669a30139d5SVedant Kumar BinaryCoverageReader::create(std::unique_ptr<MemoryBuffer> &ObjectBuffer,
670a30139d5SVedant Kumar                              StringRef Arch) {
671dc707122SEaswaran Raman   std::unique_ptr<BinaryCoverageReader> Reader(new BinaryCoverageReader());
672dc707122SEaswaran Raman 
673dc707122SEaswaran Raman   StringRef Coverage;
674dc707122SEaswaran Raman   uint8_t BytesInAddress;
675dc707122SEaswaran Raman   support::endianness Endian;
67641af4309SMehdi Amini   Error E = Error::success();
6779152fd17SVedant Kumar   consumeError(std::move(E));
678a30139d5SVedant Kumar   if (ObjectBuffer->getBuffer().startswith(TestingFormatMagic))
679dc707122SEaswaran Raman     // This is a special format used for testing.
680a30139d5SVedant Kumar     E = loadTestingFormat(ObjectBuffer->getBuffer(), Reader->ProfileNames,
681dc707122SEaswaran Raman                           Coverage, BytesInAddress, Endian);
682dc707122SEaswaran Raman   else
683a30139d5SVedant Kumar     E = loadBinaryFormat(ObjectBuffer->getMemBufferRef(), Reader->ProfileNames,
684dc707122SEaswaran Raman                          Coverage, BytesInAddress, Endian, Arch);
6859152fd17SVedant Kumar   if (E)
6869152fd17SVedant Kumar     return std::move(E);
687dc707122SEaswaran Raman 
688dc707122SEaswaran Raman   if (BytesInAddress == 4 && Endian == support::endianness::little)
6899152fd17SVedant Kumar     E = readCoverageMappingData<uint32_t, support::endianness::little>(
690dc707122SEaswaran Raman         Reader->ProfileNames, Coverage, Reader->MappingRecords,
691dc707122SEaswaran Raman         Reader->Filenames);
692dc707122SEaswaran Raman   else if (BytesInAddress == 4 && Endian == support::endianness::big)
6939152fd17SVedant Kumar     E = readCoverageMappingData<uint32_t, support::endianness::big>(
694dc707122SEaswaran Raman         Reader->ProfileNames, Coverage, Reader->MappingRecords,
695dc707122SEaswaran Raman         Reader->Filenames);
696dc707122SEaswaran Raman   else if (BytesInAddress == 8 && Endian == support::endianness::little)
6979152fd17SVedant Kumar     E = readCoverageMappingData<uint64_t, support::endianness::little>(
698dc707122SEaswaran Raman         Reader->ProfileNames, Coverage, Reader->MappingRecords,
699dc707122SEaswaran Raman         Reader->Filenames);
700dc707122SEaswaran Raman   else if (BytesInAddress == 8 && Endian == support::endianness::big)
7019152fd17SVedant Kumar     E = readCoverageMappingData<uint64_t, support::endianness::big>(
702dc707122SEaswaran Raman         Reader->ProfileNames, Coverage, Reader->MappingRecords,
703dc707122SEaswaran Raman         Reader->Filenames);
704dc707122SEaswaran Raman   else
7059152fd17SVedant Kumar     return make_error<CoverageMapError>(coveragemap_error::malformed);
7069152fd17SVedant Kumar   if (E)
7079152fd17SVedant Kumar     return std::move(E);
708dc707122SEaswaran Raman   return std::move(Reader);
709dc707122SEaswaran Raman }
710dc707122SEaswaran Raman 
7119152fd17SVedant Kumar Error BinaryCoverageReader::readNextRecord(CoverageMappingRecord &Record) {
712dc707122SEaswaran Raman   if (CurrentRecord >= MappingRecords.size())
7139152fd17SVedant Kumar     return make_error<CoverageMapError>(coveragemap_error::eof);
714dc707122SEaswaran Raman 
715dc707122SEaswaran Raman   FunctionsFilenames.clear();
716dc707122SEaswaran Raman   Expressions.clear();
717dc707122SEaswaran Raman   MappingRegions.clear();
718dc707122SEaswaran Raman   auto &R = MappingRecords[CurrentRecord];
719dc707122SEaswaran Raman   RawCoverageMappingReader Reader(
720dc707122SEaswaran Raman       R.CoverageMapping,
721dc707122SEaswaran Raman       makeArrayRef(Filenames).slice(R.FilenamesBegin, R.FilenamesSize),
722dc707122SEaswaran Raman       FunctionsFilenames, Expressions, MappingRegions);
723dc707122SEaswaran Raman   if (auto Err = Reader.read())
724dc707122SEaswaran Raman     return Err;
725dc707122SEaswaran Raman 
726dc707122SEaswaran Raman   Record.FunctionName = R.FunctionName;
727dc707122SEaswaran Raman   Record.FunctionHash = R.FunctionHash;
728dc707122SEaswaran Raman   Record.Filenames = FunctionsFilenames;
729dc707122SEaswaran Raman   Record.Expressions = Expressions;
730dc707122SEaswaran Raman   Record.MappingRegions = MappingRegions;
731dc707122SEaswaran Raman 
732dc707122SEaswaran Raman   ++CurrentRecord;
7339152fd17SVedant Kumar   return Error::success();
734dc707122SEaswaran Raman }
735