172208a82SEugene Zelenko //===- CoverageMappingReader.cpp - Code coverage mapping reader -----------===//
2dc707122SEaswaran Raman //
3*2946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4*2946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
5*2946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6dc707122SEaswaran Raman //
7dc707122SEaswaran Raman //===----------------------------------------------------------------------===//
8dc707122SEaswaran Raman //
9dc707122SEaswaran Raman // This file contains support for reading coverage mapping data for
10dc707122SEaswaran Raman // instrumentation based coverage.
11dc707122SEaswaran Raman //
12dc707122SEaswaran Raman //===----------------------------------------------------------------------===//
13dc707122SEaswaran Raman 
144a5ddf80SXinliang David Li #include "llvm/ProfileData/Coverage/CoverageMappingReader.h"
15e78d131aSEugene Zelenko #include "llvm/ADT/ArrayRef.h"
16ac40e819SIgor Kudrin #include "llvm/ADT/DenseMap.h"
17e78d131aSEugene Zelenko #include "llvm/ADT/STLExtras.h"
184a5ddf80SXinliang David Li #include "llvm/ADT/SmallVector.h"
19e78d131aSEugene Zelenko #include "llvm/ADT/StringRef.h"
20e78d131aSEugene Zelenko #include "llvm/ADT/Triple.h"
21e78d131aSEugene Zelenko #include "llvm/Object/Binary.h"
22e78d131aSEugene Zelenko #include "llvm/Object/Error.h"
23dc707122SEaswaran Raman #include "llvm/Object/MachOUniversal.h"
24dc707122SEaswaran Raman #include "llvm/Object/ObjectFile.h"
25e78d131aSEugene Zelenko #include "llvm/ProfileData/InstrProf.h"
26e78d131aSEugene Zelenko #include "llvm/Support/Casting.h"
27dc707122SEaswaran Raman #include "llvm/Support/Debug.h"
284a5ddf80SXinliang David Li #include "llvm/Support/Endian.h"
29e78d131aSEugene Zelenko #include "llvm/Support/Error.h"
30e78d131aSEugene Zelenko #include "llvm/Support/ErrorHandling.h"
31dc707122SEaswaran Raman #include "llvm/Support/LEB128.h"
32dc707122SEaswaran Raman #include "llvm/Support/MathExtras.h"
33dc707122SEaswaran Raman #include "llvm/Support/raw_ostream.h"
34e78d131aSEugene Zelenko #include <vector>
35dc707122SEaswaran Raman 
36dc707122SEaswaran Raman using namespace llvm;
37dc707122SEaswaran Raman using namespace coverage;
38dc707122SEaswaran Raman using namespace object;
39dc707122SEaswaran Raman 
40dc707122SEaswaran Raman #define DEBUG_TYPE "coverage-mapping"
41dc707122SEaswaran Raman 
42dc707122SEaswaran Raman void CoverageMappingIterator::increment() {
43bae83970SVedant Kumar   if (ReadErr != coveragemap_error::success)
44bae83970SVedant Kumar     return;
45bae83970SVedant Kumar 
46dc707122SEaswaran Raman   // Check if all the records were read or if an error occurred while reading
47dc707122SEaswaran Raman   // the next record.
48bae83970SVedant Kumar   if (auto E = Reader->readNextRecord(Record))
499152fd17SVedant Kumar     handleAllErrors(std::move(E), [&](const CoverageMapError &CME) {
509152fd17SVedant Kumar       if (CME.get() == coveragemap_error::eof)
51dc707122SEaswaran Raman         *this = CoverageMappingIterator();
529152fd17SVedant Kumar       else
53bae83970SVedant Kumar         ReadErr = CME.get();
549152fd17SVedant Kumar     });
559152fd17SVedant Kumar }
56dc707122SEaswaran Raman 
579152fd17SVedant Kumar Error RawCoverageReader::readULEB128(uint64_t &Result) {
5872208a82SEugene Zelenko   if (Data.empty())
599152fd17SVedant Kumar     return make_error<CoverageMapError>(coveragemap_error::truncated);
60dc707122SEaswaran Raman   unsigned N = 0;
61dc707122SEaswaran Raman   Result = decodeULEB128(reinterpret_cast<const uint8_t *>(Data.data()), &N);
62dc707122SEaswaran Raman   if (N > Data.size())
639152fd17SVedant Kumar     return make_error<CoverageMapError>(coveragemap_error::malformed);
64dc707122SEaswaran Raman   Data = Data.substr(N);
659152fd17SVedant Kumar   return Error::success();
66dc707122SEaswaran Raman }
67dc707122SEaswaran Raman 
689152fd17SVedant Kumar Error RawCoverageReader::readIntMax(uint64_t &Result, uint64_t MaxPlus1) {
69dc707122SEaswaran Raman   if (auto Err = readULEB128(Result))
70dc707122SEaswaran Raman     return Err;
71dc707122SEaswaran Raman   if (Result >= MaxPlus1)
729152fd17SVedant Kumar     return make_error<CoverageMapError>(coveragemap_error::malformed);
739152fd17SVedant Kumar   return Error::success();
74dc707122SEaswaran Raman }
75dc707122SEaswaran Raman 
769152fd17SVedant Kumar Error RawCoverageReader::readSize(uint64_t &Result) {
77dc707122SEaswaran Raman   if (auto Err = readULEB128(Result))
78dc707122SEaswaran Raman     return Err;
79dc707122SEaswaran Raman   // Sanity check the number.
80dc707122SEaswaran Raman   if (Result > Data.size())
819152fd17SVedant Kumar     return make_error<CoverageMapError>(coveragemap_error::malformed);
829152fd17SVedant Kumar   return Error::success();
83dc707122SEaswaran Raman }
84dc707122SEaswaran Raman 
859152fd17SVedant Kumar Error RawCoverageReader::readString(StringRef &Result) {
86dc707122SEaswaran Raman   uint64_t Length;
87dc707122SEaswaran Raman   if (auto Err = readSize(Length))
88dc707122SEaswaran Raman     return Err;
89dc707122SEaswaran Raman   Result = Data.substr(0, Length);
90dc707122SEaswaran Raman   Data = Data.substr(Length);
919152fd17SVedant Kumar   return Error::success();
92dc707122SEaswaran Raman }
93dc707122SEaswaran Raman 
949152fd17SVedant Kumar Error RawCoverageFilenamesReader::read() {
95dc707122SEaswaran Raman   uint64_t NumFilenames;
96dc707122SEaswaran Raman   if (auto Err = readSize(NumFilenames))
97dc707122SEaswaran Raman     return Err;
98dc707122SEaswaran Raman   for (size_t I = 0; I < NumFilenames; ++I) {
99dc707122SEaswaran Raman     StringRef Filename;
100dc707122SEaswaran Raman     if (auto Err = readString(Filename))
101dc707122SEaswaran Raman       return Err;
102dc707122SEaswaran Raman     Filenames.push_back(Filename);
103dc707122SEaswaran Raman   }
1049152fd17SVedant Kumar   return Error::success();
105dc707122SEaswaran Raman }
106dc707122SEaswaran Raman 
1079152fd17SVedant Kumar Error RawCoverageMappingReader::decodeCounter(unsigned Value, Counter &C) {
108dc707122SEaswaran Raman   auto Tag = Value & Counter::EncodingTagMask;
109dc707122SEaswaran Raman   switch (Tag) {
110dc707122SEaswaran Raman   case Counter::Zero:
111dc707122SEaswaran Raman     C = Counter::getZero();
1129152fd17SVedant Kumar     return Error::success();
113dc707122SEaswaran Raman   case Counter::CounterValueReference:
114dc707122SEaswaran Raman     C = Counter::getCounter(Value >> Counter::EncodingTagBits);
1159152fd17SVedant Kumar     return Error::success();
116dc707122SEaswaran Raman   default:
117dc707122SEaswaran Raman     break;
118dc707122SEaswaran Raman   }
119dc707122SEaswaran Raman   Tag -= Counter::Expression;
120dc707122SEaswaran Raman   switch (Tag) {
121dc707122SEaswaran Raman   case CounterExpression::Subtract:
122dc707122SEaswaran Raman   case CounterExpression::Add: {
123dc707122SEaswaran Raman     auto ID = Value >> Counter::EncodingTagBits;
124dc707122SEaswaran Raman     if (ID >= Expressions.size())
1259152fd17SVedant Kumar       return make_error<CoverageMapError>(coveragemap_error::malformed);
126dc707122SEaswaran Raman     Expressions[ID].Kind = CounterExpression::ExprKind(Tag);
127dc707122SEaswaran Raman     C = Counter::getExpression(ID);
128dc707122SEaswaran Raman     break;
129dc707122SEaswaran Raman   }
130dc707122SEaswaran Raman   default:
1319152fd17SVedant Kumar     return make_error<CoverageMapError>(coveragemap_error::malformed);
132dc707122SEaswaran Raman   }
1339152fd17SVedant Kumar   return Error::success();
134dc707122SEaswaran Raman }
135dc707122SEaswaran Raman 
1369152fd17SVedant Kumar Error RawCoverageMappingReader::readCounter(Counter &C) {
137dc707122SEaswaran Raman   uint64_t EncodedCounter;
138dc707122SEaswaran Raman   if (auto Err =
139dc707122SEaswaran Raman           readIntMax(EncodedCounter, std::numeric_limits<unsigned>::max()))
140dc707122SEaswaran Raman     return Err;
141dc707122SEaswaran Raman   if (auto Err = decodeCounter(EncodedCounter, C))
142dc707122SEaswaran Raman     return Err;
1439152fd17SVedant Kumar   return Error::success();
144dc707122SEaswaran Raman }
145dc707122SEaswaran Raman 
146dc707122SEaswaran Raman static const unsigned EncodingExpansionRegionBit = 1
147dc707122SEaswaran Raman                                                    << Counter::EncodingTagBits;
148dc707122SEaswaran Raman 
1495f8f34e4SAdrian Prantl /// Read the sub-array of regions for the given inferred file id.
150dc707122SEaswaran Raman /// \param NumFileIDs the number of file ids that are defined for this
151dc707122SEaswaran Raman /// function.
1529152fd17SVedant Kumar Error RawCoverageMappingReader::readMappingRegionsSubArray(
153dc707122SEaswaran Raman     std::vector<CounterMappingRegion> &MappingRegions, unsigned InferredFileID,
154dc707122SEaswaran Raman     size_t NumFileIDs) {
155dc707122SEaswaran Raman   uint64_t NumRegions;
156dc707122SEaswaran Raman   if (auto Err = readSize(NumRegions))
157dc707122SEaswaran Raman     return Err;
158dc707122SEaswaran Raman   unsigned LineStart = 0;
159dc707122SEaswaran Raman   for (size_t I = 0; I < NumRegions; ++I) {
160dc707122SEaswaran Raman     Counter C;
161dc707122SEaswaran Raman     CounterMappingRegion::RegionKind Kind = CounterMappingRegion::CodeRegion;
162dc707122SEaswaran Raman 
163dc707122SEaswaran Raman     // Read the combined counter + region kind.
164dc707122SEaswaran Raman     uint64_t EncodedCounterAndRegion;
165dc707122SEaswaran Raman     if (auto Err = readIntMax(EncodedCounterAndRegion,
166dc707122SEaswaran Raman                               std::numeric_limits<unsigned>::max()))
167dc707122SEaswaran Raman       return Err;
168dc707122SEaswaran Raman     unsigned Tag = EncodedCounterAndRegion & Counter::EncodingTagMask;
169dc707122SEaswaran Raman     uint64_t ExpandedFileID = 0;
170dc707122SEaswaran Raman     if (Tag != Counter::Zero) {
171dc707122SEaswaran Raman       if (auto Err = decodeCounter(EncodedCounterAndRegion, C))
172dc707122SEaswaran Raman         return Err;
173dc707122SEaswaran Raman     } else {
174dc707122SEaswaran Raman       // Is it an expansion region?
175dc707122SEaswaran Raman       if (EncodedCounterAndRegion & EncodingExpansionRegionBit) {
176dc707122SEaswaran Raman         Kind = CounterMappingRegion::ExpansionRegion;
177dc707122SEaswaran Raman         ExpandedFileID = EncodedCounterAndRegion >>
178dc707122SEaswaran Raman                          Counter::EncodingCounterTagAndExpansionRegionTagBits;
179dc707122SEaswaran Raman         if (ExpandedFileID >= NumFileIDs)
1809152fd17SVedant Kumar           return make_error<CoverageMapError>(coveragemap_error::malformed);
181dc707122SEaswaran Raman       } else {
182dc707122SEaswaran Raman         switch (EncodedCounterAndRegion >>
183dc707122SEaswaran Raman                 Counter::EncodingCounterTagAndExpansionRegionTagBits) {
184dc707122SEaswaran Raman         case CounterMappingRegion::CodeRegion:
185dc707122SEaswaran Raman           // Don't do anything when we have a code region with a zero counter.
186dc707122SEaswaran Raman           break;
187dc707122SEaswaran Raman         case CounterMappingRegion::SkippedRegion:
188dc707122SEaswaran Raman           Kind = CounterMappingRegion::SkippedRegion;
189dc707122SEaswaran Raman           break;
190dc707122SEaswaran Raman         default:
1919152fd17SVedant Kumar           return make_error<CoverageMapError>(coveragemap_error::malformed);
192dc707122SEaswaran Raman         }
193dc707122SEaswaran Raman       }
194dc707122SEaswaran Raman     }
195dc707122SEaswaran Raman 
196dc707122SEaswaran Raman     // Read the source range.
197dc707122SEaswaran Raman     uint64_t LineStartDelta, ColumnStart, NumLines, ColumnEnd;
198dc707122SEaswaran Raman     if (auto Err =
199dc707122SEaswaran Raman             readIntMax(LineStartDelta, std::numeric_limits<unsigned>::max()))
200dc707122SEaswaran Raman       return Err;
201dc707122SEaswaran Raman     if (auto Err = readULEB128(ColumnStart))
202dc707122SEaswaran Raman       return Err;
203dc707122SEaswaran Raman     if (ColumnStart > std::numeric_limits<unsigned>::max())
2049152fd17SVedant Kumar       return make_error<CoverageMapError>(coveragemap_error::malformed);
205dc707122SEaswaran Raman     if (auto Err = readIntMax(NumLines, std::numeric_limits<unsigned>::max()))
206dc707122SEaswaran Raman       return Err;
207dc707122SEaswaran Raman     if (auto Err = readIntMax(ColumnEnd, std::numeric_limits<unsigned>::max()))
208dc707122SEaswaran Raman       return Err;
209dc707122SEaswaran Raman     LineStart += LineStartDelta;
210ad8f637bSVedant Kumar 
211ad8f637bSVedant Kumar     // If the high bit of ColumnEnd is set, this is a gap region.
212ad8f637bSVedant Kumar     if (ColumnEnd & (1U << 31)) {
213ad8f637bSVedant Kumar       Kind = CounterMappingRegion::GapRegion;
214ad8f637bSVedant Kumar       ColumnEnd &= ~(1U << 31);
215ad8f637bSVedant Kumar     }
216ad8f637bSVedant Kumar 
217dc707122SEaswaran Raman     // Adjust the column locations for the empty regions that are supposed to
218dc707122SEaswaran Raman     // cover whole lines. Those regions should be encoded with the
219dc707122SEaswaran Raman     // column range (1 -> std::numeric_limits<unsigned>::max()), but because
220dc707122SEaswaran Raman     // the encoded std::numeric_limits<unsigned>::max() is several bytes long,
221dc707122SEaswaran Raman     // we set the column range to (0 -> 0) to ensure that the column start and
222dc707122SEaswaran Raman     // column end take up one byte each.
223dc707122SEaswaran Raman     // The std::numeric_limits<unsigned>::max() is used to represent a column
224dc707122SEaswaran Raman     // position at the end of the line without knowing the length of that line.
225dc707122SEaswaran Raman     if (ColumnStart == 0 && ColumnEnd == 0) {
226dc707122SEaswaran Raman       ColumnStart = 1;
227dc707122SEaswaran Raman       ColumnEnd = std::numeric_limits<unsigned>::max();
228dc707122SEaswaran Raman     }
229dc707122SEaswaran Raman 
230d34e60caSNicola Zaghen     LLVM_DEBUG({
231dc707122SEaswaran Raman       dbgs() << "Counter in file " << InferredFileID << " " << LineStart << ":"
232dc707122SEaswaran Raman              << ColumnStart << " -> " << (LineStart + NumLines) << ":"
233dc707122SEaswaran Raman              << ColumnEnd << ", ";
234dc707122SEaswaran Raman       if (Kind == CounterMappingRegion::ExpansionRegion)
235dc707122SEaswaran Raman         dbgs() << "Expands to file " << ExpandedFileID;
236dc707122SEaswaran Raman       else
237dc707122SEaswaran Raman         CounterMappingContext(Expressions).dump(C, dbgs());
238dc707122SEaswaran Raman       dbgs() << "\n";
239dc707122SEaswaran Raman     });
240dc707122SEaswaran Raman 
241bae83970SVedant Kumar     auto CMR = CounterMappingRegion(C, InferredFileID, ExpandedFileID,
242bae83970SVedant Kumar                                     LineStart, ColumnStart,
243bae83970SVedant Kumar                                     LineStart + NumLines, ColumnEnd, Kind);
244bae83970SVedant Kumar     if (CMR.startLoc() > CMR.endLoc())
245bae83970SVedant Kumar       return make_error<CoverageMapError>(coveragemap_error::malformed);
246bae83970SVedant Kumar     MappingRegions.push_back(CMR);
247dc707122SEaswaran Raman   }
2489152fd17SVedant Kumar   return Error::success();
249dc707122SEaswaran Raman }
250dc707122SEaswaran Raman 
2519152fd17SVedant Kumar Error RawCoverageMappingReader::read() {
252dc707122SEaswaran Raman   // Read the virtual file mapping.
253e78d131aSEugene Zelenko   SmallVector<unsigned, 8> VirtualFileMapping;
254dc707122SEaswaran Raman   uint64_t NumFileMappings;
255dc707122SEaswaran Raman   if (auto Err = readSize(NumFileMappings))
256dc707122SEaswaran Raman     return Err;
257dc707122SEaswaran Raman   for (size_t I = 0; I < NumFileMappings; ++I) {
258dc707122SEaswaran Raman     uint64_t FilenameIndex;
259dc707122SEaswaran Raman     if (auto Err = readIntMax(FilenameIndex, TranslationUnitFilenames.size()))
260dc707122SEaswaran Raman       return Err;
261dc707122SEaswaran Raman     VirtualFileMapping.push_back(FilenameIndex);
262dc707122SEaswaran Raman   }
263dc707122SEaswaran Raman 
264dc707122SEaswaran Raman   // Construct the files using unique filenames and virtual file mapping.
265dc707122SEaswaran Raman   for (auto I : VirtualFileMapping) {
266dc707122SEaswaran Raman     Filenames.push_back(TranslationUnitFilenames[I]);
267dc707122SEaswaran Raman   }
268dc707122SEaswaran Raman 
269dc707122SEaswaran Raman   // Read the expressions.
270dc707122SEaswaran Raman   uint64_t NumExpressions;
271dc707122SEaswaran Raman   if (auto Err = readSize(NumExpressions))
272dc707122SEaswaran Raman     return Err;
273dc707122SEaswaran Raman   // Create an array of dummy expressions that get the proper counters
274dc707122SEaswaran Raman   // when the expressions are read, and the proper kinds when the counters
275dc707122SEaswaran Raman   // are decoded.
276dc707122SEaswaran Raman   Expressions.resize(
277dc707122SEaswaran Raman       NumExpressions,
278dc707122SEaswaran Raman       CounterExpression(CounterExpression::Subtract, Counter(), Counter()));
279dc707122SEaswaran Raman   for (size_t I = 0; I < NumExpressions; ++I) {
280dc707122SEaswaran Raman     if (auto Err = readCounter(Expressions[I].LHS))
281dc707122SEaswaran Raman       return Err;
282dc707122SEaswaran Raman     if (auto Err = readCounter(Expressions[I].RHS))
283dc707122SEaswaran Raman       return Err;
284dc707122SEaswaran Raman   }
285dc707122SEaswaran Raman 
286dc707122SEaswaran Raman   // Read the mapping regions sub-arrays.
287dc707122SEaswaran Raman   for (unsigned InferredFileID = 0, S = VirtualFileMapping.size();
288dc707122SEaswaran Raman        InferredFileID < S; ++InferredFileID) {
289dc707122SEaswaran Raman     if (auto Err = readMappingRegionsSubArray(MappingRegions, InferredFileID,
290dc707122SEaswaran Raman                                               VirtualFileMapping.size()))
291dc707122SEaswaran Raman       return Err;
292dc707122SEaswaran Raman   }
293dc707122SEaswaran Raman 
294dc707122SEaswaran Raman   // Set the counters for the expansion regions.
295dc707122SEaswaran Raman   // i.e. Counter of expansion region = counter of the first region
296dc707122SEaswaran Raman   // from the expanded file.
297dc707122SEaswaran Raman   // Perform multiple passes to correctly propagate the counters through
298dc707122SEaswaran Raman   // all the nested expansion regions.
299dc707122SEaswaran Raman   SmallVector<CounterMappingRegion *, 8> FileIDExpansionRegionMapping;
300dc707122SEaswaran Raman   FileIDExpansionRegionMapping.resize(VirtualFileMapping.size(), nullptr);
301dc707122SEaswaran Raman   for (unsigned Pass = 1, S = VirtualFileMapping.size(); Pass < S; ++Pass) {
302dc707122SEaswaran Raman     for (auto &R : MappingRegions) {
303dc707122SEaswaran Raman       if (R.Kind != CounterMappingRegion::ExpansionRegion)
304dc707122SEaswaran Raman         continue;
305dc707122SEaswaran Raman       assert(!FileIDExpansionRegionMapping[R.ExpandedFileID]);
306dc707122SEaswaran Raman       FileIDExpansionRegionMapping[R.ExpandedFileID] = &R;
307dc707122SEaswaran Raman     }
308dc707122SEaswaran Raman     for (auto &R : MappingRegions) {
309dc707122SEaswaran Raman       if (FileIDExpansionRegionMapping[R.FileID]) {
310dc707122SEaswaran Raman         FileIDExpansionRegionMapping[R.FileID]->Count = R.Count;
311dc707122SEaswaran Raman         FileIDExpansionRegionMapping[R.FileID] = nullptr;
312dc707122SEaswaran Raman       }
313dc707122SEaswaran Raman     }
314dc707122SEaswaran Raman   }
315dc707122SEaswaran Raman 
3169152fd17SVedant Kumar   return Error::success();
317dc707122SEaswaran Raman }
318dc707122SEaswaran Raman 
319ac40e819SIgor Kudrin Expected<bool> RawCoverageMappingDummyChecker::isDummy() {
320ac40e819SIgor Kudrin   // A dummy coverage mapping data consists of just one region with zero count.
321ac40e819SIgor Kudrin   uint64_t NumFileMappings;
322ac40e819SIgor Kudrin   if (Error Err = readSize(NumFileMappings))
323ac40e819SIgor Kudrin     return std::move(Err);
324ac40e819SIgor Kudrin   if (NumFileMappings != 1)
325ac40e819SIgor Kudrin     return false;
326ac40e819SIgor Kudrin   // We don't expect any specific value for the filename index, just skip it.
327ac40e819SIgor Kudrin   uint64_t FilenameIndex;
328ac40e819SIgor Kudrin   if (Error Err =
329ac40e819SIgor Kudrin           readIntMax(FilenameIndex, std::numeric_limits<unsigned>::max()))
330ac40e819SIgor Kudrin     return std::move(Err);
331ac40e819SIgor Kudrin   uint64_t NumExpressions;
332ac40e819SIgor Kudrin   if (Error Err = readSize(NumExpressions))
333ac40e819SIgor Kudrin     return std::move(Err);
334ac40e819SIgor Kudrin   if (NumExpressions != 0)
335ac40e819SIgor Kudrin     return false;
336ac40e819SIgor Kudrin   uint64_t NumRegions;
337ac40e819SIgor Kudrin   if (Error Err = readSize(NumRegions))
338ac40e819SIgor Kudrin     return std::move(Err);
339ac40e819SIgor Kudrin   if (NumRegions != 1)
340ac40e819SIgor Kudrin     return false;
341ac40e819SIgor Kudrin   uint64_t EncodedCounterAndRegion;
342ac40e819SIgor Kudrin   if (Error Err = readIntMax(EncodedCounterAndRegion,
343ac40e819SIgor Kudrin                              std::numeric_limits<unsigned>::max()))
344ac40e819SIgor Kudrin     return std::move(Err);
345ac40e819SIgor Kudrin   unsigned Tag = EncodedCounterAndRegion & Counter::EncodingTagMask;
346ac40e819SIgor Kudrin   return Tag == Counter::Zero;
347ac40e819SIgor Kudrin }
348ac40e819SIgor Kudrin 
3499152fd17SVedant Kumar Error InstrProfSymtab::create(SectionRef &Section) {
3509152fd17SVedant Kumar   if (auto EC = Section.getContents(Data))
3519152fd17SVedant Kumar     return errorCodeToError(EC);
352dc707122SEaswaran Raman   Address = Section.getAddress();
3539152fd17SVedant Kumar   return Error::success();
354dc707122SEaswaran Raman }
355dc707122SEaswaran Raman 
356dc707122SEaswaran Raman StringRef InstrProfSymtab::getFuncName(uint64_t Pointer, size_t Size) {
357dc707122SEaswaran Raman   if (Pointer < Address)
358dc707122SEaswaran Raman     return StringRef();
359dc707122SEaswaran Raman   auto Offset = Pointer - Address;
360dc707122SEaswaran Raman   if (Offset + Size > Data.size())
361dc707122SEaswaran Raman     return StringRef();
362dc707122SEaswaran Raman   return Data.substr(Pointer - Address, Size);
363dc707122SEaswaran Raman }
364dc707122SEaswaran Raman 
365ac40e819SIgor Kudrin // Check if the mapping data is a dummy, i.e. is emitted for an unused function.
366ac40e819SIgor Kudrin static Expected<bool> isCoverageMappingDummy(uint64_t Hash, StringRef Mapping) {
367ac40e819SIgor Kudrin   // The hash value of dummy mapping records is always zero.
368ac40e819SIgor Kudrin   if (Hash)
369ac40e819SIgor Kudrin     return false;
370ac40e819SIgor Kudrin   return RawCoverageMappingDummyChecker(Mapping).isDummy();
371ac40e819SIgor Kudrin }
372ac40e819SIgor Kudrin 
373dc707122SEaswaran Raman namespace {
374e78d131aSEugene Zelenko 
375dc707122SEaswaran Raman struct CovMapFuncRecordReader {
376e78d131aSEugene Zelenko   virtual ~CovMapFuncRecordReader() = default;
377e78d131aSEugene Zelenko 
3783739b95dSVedant Kumar   // The interface to read coverage mapping function records for a module.
3793739b95dSVedant Kumar   //
3803739b95dSVedant Kumar   // \p Buf points to the buffer containing the \c CovHeader of the coverage
3813739b95dSVedant Kumar   // mapping data associated with the module.
3823739b95dSVedant Kumar   //
3833739b95dSVedant Kumar   // Returns a pointer to the next \c CovHeader if it exists, or a pointer
3843739b95dSVedant Kumar   // greater than \p End if not.
3853739b95dSVedant Kumar   virtual Expected<const char *> readFunctionRecords(const char *Buf,
3863739b95dSVedant Kumar                                                      const char *End) = 0;
387e78d131aSEugene Zelenko 
388dc707122SEaswaran Raman   template <class IntPtrT, support::endianness Endian>
3899152fd17SVedant Kumar   static Expected<std::unique_ptr<CovMapFuncRecordReader>>
390e78d131aSEugene Zelenko   get(CovMapVersion Version, InstrProfSymtab &P,
391dc707122SEaswaran Raman       std::vector<BinaryCoverageReader::ProfileMappingRecord> &R,
392dc707122SEaswaran Raman       std::vector<StringRef> &F);
393dc707122SEaswaran Raman };
394dc707122SEaswaran Raman 
395dc707122SEaswaran Raman // A class for reading coverage mapping function records for a module.
396e78d131aSEugene Zelenko template <CovMapVersion Version, class IntPtrT, support::endianness Endian>
397dc707122SEaswaran Raman class VersionedCovMapFuncRecordReader : public CovMapFuncRecordReader {
39872208a82SEugene Zelenko   using FuncRecordType =
39972208a82SEugene Zelenko       typename CovMapTraits<Version, IntPtrT>::CovMapFuncRecordType;
40072208a82SEugene Zelenko   using NameRefType = typename CovMapTraits<Version, IntPtrT>::NameRefType;
401dc707122SEaswaran Raman 
402ac40e819SIgor Kudrin   // Maps function's name references to the indexes of their records
403ac40e819SIgor Kudrin   // in \c Records.
404e78d131aSEugene Zelenko   DenseMap<NameRefType, size_t> FunctionRecords;
405dc707122SEaswaran Raman   InstrProfSymtab &ProfileNames;
406dc707122SEaswaran Raman   std::vector<StringRef> &Filenames;
407dc707122SEaswaran Raman   std::vector<BinaryCoverageReader::ProfileMappingRecord> &Records;
408dc707122SEaswaran Raman 
409ac40e819SIgor Kudrin   // Add the record to the collection if we don't already have a record that
410ac40e819SIgor Kudrin   // points to the same function name. This is useful to ignore the redundant
411ac40e819SIgor Kudrin   // records for the functions with ODR linkage.
412ac40e819SIgor Kudrin   // In addition, prefer records with real coverage mapping data to dummy
413ac40e819SIgor Kudrin   // records, which were emitted for inline functions which were seen but
414ac40e819SIgor Kudrin   // not used in the corresponding translation unit.
415ac40e819SIgor Kudrin   Error insertFunctionRecordIfNeeded(const FuncRecordType *CFR,
416ac40e819SIgor Kudrin                                      StringRef Mapping, size_t FilenamesBegin) {
417ac40e819SIgor Kudrin     uint64_t FuncHash = CFR->template getFuncHash<Endian>();
418ac40e819SIgor Kudrin     NameRefType NameRef = CFR->template getFuncNameRef<Endian>();
419ac40e819SIgor Kudrin     auto InsertResult =
420ac40e819SIgor Kudrin         FunctionRecords.insert(std::make_pair(NameRef, Records.size()));
421ac40e819SIgor Kudrin     if (InsertResult.second) {
422ac40e819SIgor Kudrin       StringRef FuncName;
423ac40e819SIgor Kudrin       if (Error Err = CFR->template getFuncName<Endian>(ProfileNames, FuncName))
424ac40e819SIgor Kudrin         return Err;
425b5794ca9SVedant Kumar       if (FuncName.empty())
426b5794ca9SVedant Kumar         return make_error<InstrProfError>(instrprof_error::malformed);
427ac40e819SIgor Kudrin       Records.emplace_back(Version, FuncName, FuncHash, Mapping, FilenamesBegin,
428ac40e819SIgor Kudrin                            Filenames.size() - FilenamesBegin);
429ac40e819SIgor Kudrin       return Error::success();
430ac40e819SIgor Kudrin     }
431ac40e819SIgor Kudrin     // Update the existing record if it's a dummy and the new record is real.
432ac40e819SIgor Kudrin     size_t OldRecordIndex = InsertResult.first->second;
433ac40e819SIgor Kudrin     BinaryCoverageReader::ProfileMappingRecord &OldRecord =
434ac40e819SIgor Kudrin         Records[OldRecordIndex];
435ac40e819SIgor Kudrin     Expected<bool> OldIsDummyExpected = isCoverageMappingDummy(
436ac40e819SIgor Kudrin         OldRecord.FunctionHash, OldRecord.CoverageMapping);
437ac40e819SIgor Kudrin     if (Error Err = OldIsDummyExpected.takeError())
438ac40e819SIgor Kudrin       return Err;
439ac40e819SIgor Kudrin     if (!*OldIsDummyExpected)
440ac40e819SIgor Kudrin       return Error::success();
441ac40e819SIgor Kudrin     Expected<bool> NewIsDummyExpected =
442ac40e819SIgor Kudrin         isCoverageMappingDummy(FuncHash, Mapping);
443ac40e819SIgor Kudrin     if (Error Err = NewIsDummyExpected.takeError())
444ac40e819SIgor Kudrin       return Err;
445ac40e819SIgor Kudrin     if (*NewIsDummyExpected)
446ac40e819SIgor Kudrin       return Error::success();
447ac40e819SIgor Kudrin     OldRecord.FunctionHash = FuncHash;
448ac40e819SIgor Kudrin     OldRecord.CoverageMapping = Mapping;
449ac40e819SIgor Kudrin     OldRecord.FilenamesBegin = FilenamesBegin;
450ac40e819SIgor Kudrin     OldRecord.FilenamesSize = Filenames.size() - FilenamesBegin;
451ac40e819SIgor Kudrin     return Error::success();
452ac40e819SIgor Kudrin   }
453ac40e819SIgor Kudrin 
454dc707122SEaswaran Raman public:
455dc707122SEaswaran Raman   VersionedCovMapFuncRecordReader(
456dc707122SEaswaran Raman       InstrProfSymtab &P,
457dc707122SEaswaran Raman       std::vector<BinaryCoverageReader::ProfileMappingRecord> &R,
458dc707122SEaswaran Raman       std::vector<StringRef> &F)
459dc707122SEaswaran Raman       : ProfileNames(P), Filenames(F), Records(R) {}
460e78d131aSEugene Zelenko 
461e78d131aSEugene Zelenko   ~VersionedCovMapFuncRecordReader() override = default;
462dc707122SEaswaran Raman 
4633739b95dSVedant Kumar   Expected<const char *> readFunctionRecords(const char *Buf,
4643739b95dSVedant Kumar                                              const char *End) override {
465dc707122SEaswaran Raman     using namespace support;
466e78d131aSEugene Zelenko 
467dc707122SEaswaran Raman     if (Buf + sizeof(CovMapHeader) > End)
4689152fd17SVedant Kumar       return make_error<CoverageMapError>(coveragemap_error::malformed);
469e78d131aSEugene Zelenko     auto CovHeader = reinterpret_cast<const CovMapHeader *>(Buf);
470dc707122SEaswaran Raman     uint32_t NRecords = CovHeader->getNRecords<Endian>();
471dc707122SEaswaran Raman     uint32_t FilenamesSize = CovHeader->getFilenamesSize<Endian>();
472dc707122SEaswaran Raman     uint32_t CoverageSize = CovHeader->getCoverageSize<Endian>();
473dc707122SEaswaran Raman     assert((CovMapVersion)CovHeader->getVersion<Endian>() == Version);
474dc707122SEaswaran Raman     Buf = reinterpret_cast<const char *>(CovHeader + 1);
475dc707122SEaswaran Raman 
476dc707122SEaswaran Raman     // Skip past the function records, saving the start and end for later.
477dc707122SEaswaran Raman     const char *FunBuf = Buf;
478dc707122SEaswaran Raman     Buf += NRecords * sizeof(FuncRecordType);
479dc707122SEaswaran Raman     const char *FunEnd = Buf;
480dc707122SEaswaran Raman 
481dc707122SEaswaran Raman     // Get the filenames.
482dc707122SEaswaran Raman     if (Buf + FilenamesSize > End)
4839152fd17SVedant Kumar       return make_error<CoverageMapError>(coveragemap_error::malformed);
484dc707122SEaswaran Raman     size_t FilenamesBegin = Filenames.size();
485dc707122SEaswaran Raman     RawCoverageFilenamesReader Reader(StringRef(Buf, FilenamesSize), Filenames);
486dc707122SEaswaran Raman     if (auto Err = Reader.read())
4873739b95dSVedant Kumar       return std::move(Err);
488dc707122SEaswaran Raman     Buf += FilenamesSize;
489dc707122SEaswaran Raman 
490dc707122SEaswaran Raman     // We'll read the coverage mapping records in the loop below.
491dc707122SEaswaran Raman     const char *CovBuf = Buf;
492dc707122SEaswaran Raman     Buf += CoverageSize;
493dc707122SEaswaran Raman     const char *CovEnd = Buf;
494dc707122SEaswaran Raman 
495dc707122SEaswaran Raman     if (Buf > End)
4969152fd17SVedant Kumar       return make_error<CoverageMapError>(coveragemap_error::malformed);
497dc707122SEaswaran Raman     // Each coverage map has an alignment of 8, so we need to adjust alignment
498dc707122SEaswaran Raman     // before reading the next map.
499dc707122SEaswaran Raman     Buf += alignmentAdjustment(Buf, 8);
500dc707122SEaswaran Raman 
501dc707122SEaswaran Raman     auto CFR = reinterpret_cast<const FuncRecordType *>(FunBuf);
502dc707122SEaswaran Raman     while ((const char *)CFR < FunEnd) {
503dc707122SEaswaran Raman       // Read the function information
504dc707122SEaswaran Raman       uint32_t DataSize = CFR->template getDataSize<Endian>();
505dc707122SEaswaran Raman 
506dc707122SEaswaran Raman       // Now use that to read the coverage data.
507dc707122SEaswaran Raman       if (CovBuf + DataSize > CovEnd)
5089152fd17SVedant Kumar         return make_error<CoverageMapError>(coveragemap_error::malformed);
509dc707122SEaswaran Raman       auto Mapping = StringRef(CovBuf, DataSize);
510dc707122SEaswaran Raman       CovBuf += DataSize;
511dc707122SEaswaran Raman 
512ac40e819SIgor Kudrin       if (Error Err =
513ac40e819SIgor Kudrin               insertFunctionRecordIfNeeded(CFR, Mapping, FilenamesBegin))
5143739b95dSVedant Kumar         return std::move(Err);
515dc707122SEaswaran Raman       CFR++;
516dc707122SEaswaran Raman     }
5173739b95dSVedant Kumar     return Buf;
518dc707122SEaswaran Raman   }
519dc707122SEaswaran Raman };
520e78d131aSEugene Zelenko 
521dc707122SEaswaran Raman } // end anonymous namespace
522dc707122SEaswaran Raman 
523dc707122SEaswaran Raman template <class IntPtrT, support::endianness Endian>
5249152fd17SVedant Kumar Expected<std::unique_ptr<CovMapFuncRecordReader>> CovMapFuncRecordReader::get(
525e78d131aSEugene Zelenko     CovMapVersion Version, InstrProfSymtab &P,
526dc707122SEaswaran Raman     std::vector<BinaryCoverageReader::ProfileMappingRecord> &R,
527dc707122SEaswaran Raman     std::vector<StringRef> &F) {
528dc707122SEaswaran Raman   using namespace coverage;
529e78d131aSEugene Zelenko 
530dc707122SEaswaran Raman   switch (Version) {
531dc707122SEaswaran Raman   case CovMapVersion::Version1:
532dc707122SEaswaran Raman     return llvm::make_unique<VersionedCovMapFuncRecordReader<
533dc707122SEaswaran Raman         CovMapVersion::Version1, IntPtrT, Endian>>(P, R, F);
534dc707122SEaswaran Raman   case CovMapVersion::Version2:
535ad8f637bSVedant Kumar   case CovMapVersion::Version3:
536dc707122SEaswaran Raman     // Decompress the name data.
5379152fd17SVedant Kumar     if (Error E = P.create(P.getNameData()))
5389152fd17SVedant Kumar       return std::move(E);
539ad8f637bSVedant Kumar     if (Version == CovMapVersion::Version2)
540dc707122SEaswaran Raman       return llvm::make_unique<VersionedCovMapFuncRecordReader<
541dc707122SEaswaran Raman           CovMapVersion::Version2, IntPtrT, Endian>>(P, R, F);
542ad8f637bSVedant Kumar     else
543ad8f637bSVedant Kumar       return llvm::make_unique<VersionedCovMapFuncRecordReader<
544ad8f637bSVedant Kumar           CovMapVersion::Version3, IntPtrT, Endian>>(P, R, F);
545dc707122SEaswaran Raman   }
546dc707122SEaswaran Raman   llvm_unreachable("Unsupported version");
547dc707122SEaswaran Raman }
548dc707122SEaswaran Raman 
549dc707122SEaswaran Raman template <typename T, support::endianness Endian>
5509152fd17SVedant Kumar static Error readCoverageMappingData(
551dc707122SEaswaran Raman     InstrProfSymtab &ProfileNames, StringRef Data,
552dc707122SEaswaran Raman     std::vector<BinaryCoverageReader::ProfileMappingRecord> &Records,
553dc707122SEaswaran Raman     std::vector<StringRef> &Filenames) {
554dc707122SEaswaran Raman   using namespace coverage;
555e78d131aSEugene Zelenko 
556dc707122SEaswaran Raman   // Read the records in the coverage data section.
557dc707122SEaswaran Raman   auto CovHeader =
558e78d131aSEugene Zelenko       reinterpret_cast<const CovMapHeader *>(Data.data());
559dc707122SEaswaran Raman   CovMapVersion Version = (CovMapVersion)CovHeader->getVersion<Endian>();
560e78d131aSEugene Zelenko   if (Version > CovMapVersion::CurrentVersion)
5619152fd17SVedant Kumar     return make_error<CoverageMapError>(coveragemap_error::unsupported_version);
5629152fd17SVedant Kumar   Expected<std::unique_ptr<CovMapFuncRecordReader>> ReaderExpected =
563dc707122SEaswaran Raman       CovMapFuncRecordReader::get<T, Endian>(Version, ProfileNames, Records,
564dc707122SEaswaran Raman                                              Filenames);
5659152fd17SVedant Kumar   if (Error E = ReaderExpected.takeError())
5669152fd17SVedant Kumar     return E;
5679152fd17SVedant Kumar   auto Reader = std::move(ReaderExpected.get());
568dc707122SEaswaran Raman   for (const char *Buf = Data.data(), *End = Buf + Data.size(); Buf < End;) {
5693739b95dSVedant Kumar     auto NextHeaderOrErr = Reader->readFunctionRecords(Buf, End);
5703739b95dSVedant Kumar     if (auto E = NextHeaderOrErr.takeError())
5719152fd17SVedant Kumar       return E;
5723739b95dSVedant Kumar     Buf = NextHeaderOrErr.get();
573dc707122SEaswaran Raman   }
5749152fd17SVedant Kumar   return Error::success();
575dc707122SEaswaran Raman }
576e78d131aSEugene Zelenko 
577dc707122SEaswaran Raman static const char *TestingFormatMagic = "llvmcovmtestdata";
578dc707122SEaswaran Raman 
5799152fd17SVedant Kumar static Error loadTestingFormat(StringRef Data, InstrProfSymtab &ProfileNames,
580dc707122SEaswaran Raman                                StringRef &CoverageMapping,
581dc707122SEaswaran Raman                                uint8_t &BytesInAddress,
582dc707122SEaswaran Raman                                support::endianness &Endian) {
583dc707122SEaswaran Raman   BytesInAddress = 8;
584dc707122SEaswaran Raman   Endian = support::endianness::little;
585dc707122SEaswaran Raman 
586dc707122SEaswaran Raman   Data = Data.substr(StringRef(TestingFormatMagic).size());
58772208a82SEugene Zelenko   if (Data.empty())
5889152fd17SVedant Kumar     return make_error<CoverageMapError>(coveragemap_error::truncated);
589dc707122SEaswaran Raman   unsigned N = 0;
590dc707122SEaswaran Raman   auto ProfileNamesSize =
591dc707122SEaswaran Raman       decodeULEB128(reinterpret_cast<const uint8_t *>(Data.data()), &N);
592dc707122SEaswaran Raman   if (N > Data.size())
5939152fd17SVedant Kumar     return make_error<CoverageMapError>(coveragemap_error::malformed);
594dc707122SEaswaran Raman   Data = Data.substr(N);
59572208a82SEugene Zelenko   if (Data.empty())
5969152fd17SVedant Kumar     return make_error<CoverageMapError>(coveragemap_error::truncated);
597dc707122SEaswaran Raman   N = 0;
598dc707122SEaswaran Raman   uint64_t Address =
599dc707122SEaswaran Raman       decodeULEB128(reinterpret_cast<const uint8_t *>(Data.data()), &N);
600dc707122SEaswaran Raman   if (N > Data.size())
6019152fd17SVedant Kumar     return make_error<CoverageMapError>(coveragemap_error::malformed);
602dc707122SEaswaran Raman   Data = Data.substr(N);
603dc707122SEaswaran Raman   if (Data.size() < ProfileNamesSize)
6049152fd17SVedant Kumar     return make_error<CoverageMapError>(coveragemap_error::malformed);
6059152fd17SVedant Kumar   if (Error E = ProfileNames.create(Data.substr(0, ProfileNamesSize), Address))
6069152fd17SVedant Kumar     return E;
607dc707122SEaswaran Raman   CoverageMapping = Data.substr(ProfileNamesSize);
608eb103073SIgor Kudrin   // Skip the padding bytes because coverage map data has an alignment of 8.
60972208a82SEugene Zelenko   if (CoverageMapping.empty())
6109152fd17SVedant Kumar     return make_error<CoverageMapError>(coveragemap_error::truncated);
611eb103073SIgor Kudrin   size_t Pad = alignmentAdjustment(CoverageMapping.data(), 8);
612eb103073SIgor Kudrin   if (CoverageMapping.size() < Pad)
6139152fd17SVedant Kumar     return make_error<CoverageMapError>(coveragemap_error::malformed);
614eb103073SIgor Kudrin   CoverageMapping = CoverageMapping.substr(Pad);
6159152fd17SVedant Kumar   return Error::success();
616dc707122SEaswaran Raman }
617dc707122SEaswaran Raman 
6189152fd17SVedant Kumar static Expected<SectionRef> lookupSection(ObjectFile &OF, StringRef Name) {
619dc707122SEaswaran Raman   StringRef FoundName;
620dc707122SEaswaran Raman   for (const auto &Section : OF.sections()) {
621dc707122SEaswaran Raman     if (auto EC = Section.getName(FoundName))
6229152fd17SVedant Kumar       return errorCodeToError(EC);
623dc707122SEaswaran Raman     if (FoundName == Name)
624dc707122SEaswaran Raman       return Section;
625dc707122SEaswaran Raman   }
6269152fd17SVedant Kumar   return make_error<CoverageMapError>(coveragemap_error::no_data_found);
627dc707122SEaswaran Raman }
628dc707122SEaswaran Raman 
6299152fd17SVedant Kumar static Error loadBinaryFormat(MemoryBufferRef ObjectBuffer,
6309152fd17SVedant Kumar                               InstrProfSymtab &ProfileNames,
6319152fd17SVedant Kumar                               StringRef &CoverageMapping,
6329152fd17SVedant Kumar                               uint8_t &BytesInAddress,
633dc707122SEaswaran Raman                               support::endianness &Endian, StringRef Arch) {
634e78d131aSEugene Zelenko   auto BinOrErr = createBinary(ObjectBuffer);
635dc707122SEaswaran Raman   if (!BinOrErr)
6369152fd17SVedant Kumar     return BinOrErr.takeError();
637dc707122SEaswaran Raman   auto Bin = std::move(BinOrErr.get());
638dc707122SEaswaran Raman   std::unique_ptr<ObjectFile> OF;
639e78d131aSEugene Zelenko   if (auto *Universal = dyn_cast<MachOUniversalBinary>(Bin.get())) {
640dc707122SEaswaran Raman     // If we have a universal binary, try to look up the object for the
641dc707122SEaswaran Raman     // appropriate architecture.
642dc707122SEaswaran Raman     auto ObjectFileOrErr = Universal->getObjectForArch(Arch);
6439acb1099SKevin Enderby     if (!ObjectFileOrErr)
6449acb1099SKevin Enderby       return ObjectFileOrErr.takeError();
645dc707122SEaswaran Raman     OF = std::move(ObjectFileOrErr.get());
646e78d131aSEugene Zelenko   } else if (isa<ObjectFile>(Bin.get())) {
647dc707122SEaswaran Raman     // For any other object file, upcast and take ownership.
648e78d131aSEugene Zelenko     OF.reset(cast<ObjectFile>(Bin.release()));
649dc707122SEaswaran Raman     // If we've asked for a particular arch, make sure they match.
650dc707122SEaswaran Raman     if (!Arch.empty() && OF->getArch() != Triple(Arch).getArch())
6519152fd17SVedant Kumar       return errorCodeToError(object_error::arch_not_found);
652dc707122SEaswaran Raman   } else
653dc707122SEaswaran Raman     // We can only handle object files.
6549152fd17SVedant Kumar     return make_error<CoverageMapError>(coveragemap_error::malformed);
655dc707122SEaswaran Raman 
656dc707122SEaswaran Raman   // The coverage uses native pointer sizes for the object it's written in.
657dc707122SEaswaran Raman   BytesInAddress = OF->getBytesInAddress();
658dc707122SEaswaran Raman   Endian = OF->isLittleEndian() ? support::endianness::little
659dc707122SEaswaran Raman                                 : support::endianness::big;
660dc707122SEaswaran Raman 
661dc707122SEaswaran Raman   // Look for the sections that we are interested in.
6621a6a2b64SVedant Kumar   auto ObjFormat = OF->getTripleObjectFormat();
6634a5ddf80SXinliang David Li   auto NamesSection =
6641a6a2b64SVedant Kumar       lookupSection(*OF, getInstrProfSectionName(IPSK_name, ObjFormat,
6651a6a2b64SVedant Kumar                                                  /*AddSegmentInfo=*/false));
6669152fd17SVedant Kumar   if (auto E = NamesSection.takeError())
6679152fd17SVedant Kumar     return E;
6684a5ddf80SXinliang David Li   auto CoverageSection =
6691a6a2b64SVedant Kumar       lookupSection(*OF, getInstrProfSectionName(IPSK_covmap, ObjFormat,
6701a6a2b64SVedant Kumar                                                  /*AddSegmentInfo=*/false));
6719152fd17SVedant Kumar   if (auto E = CoverageSection.takeError())
6729152fd17SVedant Kumar     return E;
673dc707122SEaswaran Raman 
674dc707122SEaswaran Raman   // Get the contents of the given sections.
6759152fd17SVedant Kumar   if (auto EC = CoverageSection->getContents(CoverageMapping))
6769152fd17SVedant Kumar     return errorCodeToError(EC);
6779152fd17SVedant Kumar   if (Error E = ProfileNames.create(*NamesSection))
6789152fd17SVedant Kumar     return E;
679dc707122SEaswaran Raman 
6809152fd17SVedant Kumar   return Error::success();
681dc707122SEaswaran Raman }
682dc707122SEaswaran Raman 
6839152fd17SVedant Kumar Expected<std::unique_ptr<BinaryCoverageReader>>
684a30139d5SVedant Kumar BinaryCoverageReader::create(std::unique_ptr<MemoryBuffer> &ObjectBuffer,
685a30139d5SVedant Kumar                              StringRef Arch) {
686dc707122SEaswaran Raman   std::unique_ptr<BinaryCoverageReader> Reader(new BinaryCoverageReader());
687dc707122SEaswaran Raman 
688dc707122SEaswaran Raman   StringRef Coverage;
689dc707122SEaswaran Raman   uint8_t BytesInAddress;
690dc707122SEaswaran Raman   support::endianness Endian;
69141af4309SMehdi Amini   Error E = Error::success();
6929152fd17SVedant Kumar   consumeError(std::move(E));
693a30139d5SVedant Kumar   if (ObjectBuffer->getBuffer().startswith(TestingFormatMagic))
694dc707122SEaswaran Raman     // This is a special format used for testing.
695a30139d5SVedant Kumar     E = loadTestingFormat(ObjectBuffer->getBuffer(), Reader->ProfileNames,
696dc707122SEaswaran Raman                           Coverage, BytesInAddress, Endian);
697dc707122SEaswaran Raman   else
698a30139d5SVedant Kumar     E = loadBinaryFormat(ObjectBuffer->getMemBufferRef(), Reader->ProfileNames,
699dc707122SEaswaran Raman                          Coverage, BytesInAddress, Endian, Arch);
7009152fd17SVedant Kumar   if (E)
7019152fd17SVedant Kumar     return std::move(E);
702dc707122SEaswaran Raman 
703dc707122SEaswaran Raman   if (BytesInAddress == 4 && Endian == support::endianness::little)
7049152fd17SVedant Kumar     E = readCoverageMappingData<uint32_t, support::endianness::little>(
705dc707122SEaswaran Raman         Reader->ProfileNames, Coverage, Reader->MappingRecords,
706dc707122SEaswaran Raman         Reader->Filenames);
707dc707122SEaswaran Raman   else if (BytesInAddress == 4 && Endian == support::endianness::big)
7089152fd17SVedant Kumar     E = readCoverageMappingData<uint32_t, support::endianness::big>(
709dc707122SEaswaran Raman         Reader->ProfileNames, Coverage, Reader->MappingRecords,
710dc707122SEaswaran Raman         Reader->Filenames);
711dc707122SEaswaran Raman   else if (BytesInAddress == 8 && Endian == support::endianness::little)
7129152fd17SVedant Kumar     E = readCoverageMappingData<uint64_t, support::endianness::little>(
713dc707122SEaswaran Raman         Reader->ProfileNames, Coverage, Reader->MappingRecords,
714dc707122SEaswaran Raman         Reader->Filenames);
715dc707122SEaswaran Raman   else if (BytesInAddress == 8 && Endian == support::endianness::big)
7169152fd17SVedant Kumar     E = readCoverageMappingData<uint64_t, support::endianness::big>(
717dc707122SEaswaran Raman         Reader->ProfileNames, Coverage, Reader->MappingRecords,
718dc707122SEaswaran Raman         Reader->Filenames);
719dc707122SEaswaran Raman   else
7209152fd17SVedant Kumar     return make_error<CoverageMapError>(coveragemap_error::malformed);
7219152fd17SVedant Kumar   if (E)
7229152fd17SVedant Kumar     return std::move(E);
723dc707122SEaswaran Raman   return std::move(Reader);
724dc707122SEaswaran Raman }
725dc707122SEaswaran Raman 
7269152fd17SVedant Kumar Error BinaryCoverageReader::readNextRecord(CoverageMappingRecord &Record) {
727dc707122SEaswaran Raman   if (CurrentRecord >= MappingRecords.size())
7289152fd17SVedant Kumar     return make_error<CoverageMapError>(coveragemap_error::eof);
729dc707122SEaswaran Raman 
730dc707122SEaswaran Raman   FunctionsFilenames.clear();
731dc707122SEaswaran Raman   Expressions.clear();
732dc707122SEaswaran Raman   MappingRegions.clear();
733dc707122SEaswaran Raman   auto &R = MappingRecords[CurrentRecord];
734dc707122SEaswaran Raman   RawCoverageMappingReader Reader(
735dc707122SEaswaran Raman       R.CoverageMapping,
736dc707122SEaswaran Raman       makeArrayRef(Filenames).slice(R.FilenamesBegin, R.FilenamesSize),
737dc707122SEaswaran Raman       FunctionsFilenames, Expressions, MappingRegions);
738dc707122SEaswaran Raman   if (auto Err = Reader.read())
739dc707122SEaswaran Raman     return Err;
740dc707122SEaswaran Raman 
741dc707122SEaswaran Raman   Record.FunctionName = R.FunctionName;
742dc707122SEaswaran Raman   Record.FunctionHash = R.FunctionHash;
743dc707122SEaswaran Raman   Record.Filenames = FunctionsFilenames;
744dc707122SEaswaran Raman   Record.Expressions = Expressions;
745dc707122SEaswaran Raman   Record.MappingRegions = MappingRegions;
746dc707122SEaswaran Raman 
747dc707122SEaswaran Raman   ++CurrentRecord;
7489152fd17SVedant Kumar   return Error::success();
749dc707122SEaswaran Raman }
750