InstrProf: Rename ObjectFileCoverageMappingReader to BinaryCoverageReader
[oota-llvm.git] / lib / ProfileData / CoverageMappingReader.cpp
1 //=-- CoverageMappingReader.cpp - Code coverage mapping reader ----*- C++ -*-=//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains support for reading coverage mapping data for
11 // instrumentation based coverage.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/ProfileData/CoverageMappingReader.h"
16 #include "llvm/ADT/DenseSet.h"
17 #include "llvm/Object/ObjectFile.h"
18 #include "llvm/Support/Debug.h"
19 #include "llvm/Support/LEB128.h"
20
21 using namespace llvm;
22 using namespace coverage;
23 using namespace object;
24
25 #define DEBUG_TYPE "coverage-mapping"
26
27 void CoverageMappingIterator::increment() {
28   // Check if all the records were read or if an error occurred while reading
29   // the next record.
30   if (Reader->readNextRecord(Record))
31     *this = CoverageMappingIterator();
32 }
33
34 std::error_code RawCoverageReader::readULEB128(uint64_t &Result) {
35   if (Data.size() < 1)
36     return error(instrprof_error::truncated);
37   unsigned N = 0;
38   Result = decodeULEB128(reinterpret_cast<const uint8_t *>(Data.data()), &N);
39   if (N > Data.size())
40     return error(instrprof_error::malformed);
41   Data = Data.substr(N);
42   return success();
43 }
44
45 std::error_code RawCoverageReader::readIntMax(uint64_t &Result,
46                                               uint64_t MaxPlus1) {
47   if (auto Err = readULEB128(Result))
48     return Err;
49   if (Result >= MaxPlus1)
50     return error(instrprof_error::malformed);
51   return success();
52 }
53
54 std::error_code RawCoverageReader::readSize(uint64_t &Result) {
55   if (auto Err = readULEB128(Result))
56     return Err;
57   // Sanity check the number.
58   if (Result > Data.size())
59     return error(instrprof_error::malformed);
60   return success();
61 }
62
63 std::error_code RawCoverageReader::readString(StringRef &Result) {
64   uint64_t Length;
65   if (auto Err = readSize(Length))
66     return Err;
67   Result = Data.substr(0, Length);
68   Data = Data.substr(Length);
69   return success();
70 }
71
72 std::error_code RawCoverageFilenamesReader::read() {
73   uint64_t NumFilenames;
74   if (auto Err = readSize(NumFilenames))
75     return Err;
76   for (size_t I = 0; I < NumFilenames; ++I) {
77     StringRef Filename;
78     if (auto Err = readString(Filename))
79       return Err;
80     Filenames.push_back(Filename);
81   }
82   return success();
83 }
84
85 std::error_code RawCoverageMappingReader::decodeCounter(unsigned Value,
86                                                         Counter &C) {
87   auto Tag = Value & Counter::EncodingTagMask;
88   switch (Tag) {
89   case Counter::Zero:
90     C = Counter::getZero();
91     return success();
92   case Counter::CounterValueReference:
93     C = Counter::getCounter(Value >> Counter::EncodingTagBits);
94     return success();
95   default:
96     break;
97   }
98   Tag -= Counter::Expression;
99   switch (Tag) {
100   case CounterExpression::Subtract:
101   case CounterExpression::Add: {
102     auto ID = Value >> Counter::EncodingTagBits;
103     if (ID >= Expressions.size())
104       return error(instrprof_error::malformed);
105     Expressions[ID].Kind = CounterExpression::ExprKind(Tag);
106     C = Counter::getExpression(ID);
107     break;
108   }
109   default:
110     return error(instrprof_error::malformed);
111   }
112   return success();
113 }
114
115 std::error_code RawCoverageMappingReader::readCounter(Counter &C) {
116   uint64_t EncodedCounter;
117   if (auto Err =
118           readIntMax(EncodedCounter, std::numeric_limits<unsigned>::max()))
119     return Err;
120   if (auto Err = decodeCounter(EncodedCounter, C))
121     return Err;
122   return success();
123 }
124
125 static const unsigned EncodingExpansionRegionBit = 1
126                                                    << Counter::EncodingTagBits;
127
128 /// \brief Read the sub-array of regions for the given inferred file id.
129 /// \param NumFileIDs the number of file ids that are defined for this
130 /// function.
131 std::error_code RawCoverageMappingReader::readMappingRegionsSubArray(
132     std::vector<CounterMappingRegion> &MappingRegions, unsigned InferredFileID,
133     size_t NumFileIDs) {
134   uint64_t NumRegions;
135   if (auto Err = readSize(NumRegions))
136     return Err;
137   unsigned LineStart = 0;
138   for (size_t I = 0; I < NumRegions; ++I) {
139     Counter C;
140     CounterMappingRegion::RegionKind Kind = CounterMappingRegion::CodeRegion;
141
142     // Read the combined counter + region kind.
143     uint64_t EncodedCounterAndRegion;
144     if (auto Err = readIntMax(EncodedCounterAndRegion,
145                               std::numeric_limits<unsigned>::max()))
146       return Err;
147     unsigned Tag = EncodedCounterAndRegion & Counter::EncodingTagMask;
148     uint64_t ExpandedFileID = 0;
149     if (Tag != Counter::Zero) {
150       if (auto Err = decodeCounter(EncodedCounterAndRegion, C))
151         return Err;
152     } else {
153       // Is it an expansion region?
154       if (EncodedCounterAndRegion & EncodingExpansionRegionBit) {
155         Kind = CounterMappingRegion::ExpansionRegion;
156         ExpandedFileID = EncodedCounterAndRegion >>
157                          Counter::EncodingCounterTagAndExpansionRegionTagBits;
158         if (ExpandedFileID >= NumFileIDs)
159           return error(instrprof_error::malformed);
160       } else {
161         switch (EncodedCounterAndRegion >>
162                 Counter::EncodingCounterTagAndExpansionRegionTagBits) {
163         case CounterMappingRegion::CodeRegion:
164           // Don't do anything when we have a code region with a zero counter.
165           break;
166         case CounterMappingRegion::SkippedRegion:
167           Kind = CounterMappingRegion::SkippedRegion;
168           break;
169         default:
170           return error(instrprof_error::malformed);
171         }
172       }
173     }
174
175     // Read the source range.
176     uint64_t LineStartDelta, ColumnStart, NumLines, ColumnEnd;
177     if (auto Err =
178             readIntMax(LineStartDelta, std::numeric_limits<unsigned>::max()))
179       return Err;
180     if (auto Err = readULEB128(ColumnStart))
181       return Err;
182     if (ColumnStart > std::numeric_limits<unsigned>::max())
183       return error(instrprof_error::malformed);
184     if (auto Err = readIntMax(NumLines, std::numeric_limits<unsigned>::max()))
185       return Err;
186     if (auto Err = readIntMax(ColumnEnd, std::numeric_limits<unsigned>::max()))
187       return Err;
188     LineStart += LineStartDelta;
189     // Adjust the column locations for the empty regions that are supposed to
190     // cover whole lines. Those regions should be encoded with the
191     // column range (1 -> std::numeric_limits<unsigned>::max()), but because
192     // the encoded std::numeric_limits<unsigned>::max() is several bytes long,
193     // we set the column range to (0 -> 0) to ensure that the column start and
194     // column end take up one byte each.
195     // The std::numeric_limits<unsigned>::max() is used to represent a column
196     // position at the end of the line without knowing the length of that line.
197     if (ColumnStart == 0 && ColumnEnd == 0) {
198       ColumnStart = 1;
199       ColumnEnd = std::numeric_limits<unsigned>::max();
200     }
201
202     DEBUG({
203       dbgs() << "Counter in file " << InferredFileID << " " << LineStart << ":"
204              << ColumnStart << " -> " << (LineStart + NumLines) << ":"
205              << ColumnEnd << ", ";
206       if (Kind == CounterMappingRegion::ExpansionRegion)
207         dbgs() << "Expands to file " << ExpandedFileID;
208       else
209         CounterMappingContext(Expressions).dump(C, dbgs());
210       dbgs() << "\n";
211     });
212
213     MappingRegions.push_back(CounterMappingRegion(
214         C, InferredFileID, ExpandedFileID, LineStart, ColumnStart,
215         LineStart + NumLines, ColumnEnd, Kind));
216   }
217   return success();
218 }
219
220 std::error_code RawCoverageMappingReader::read() {
221
222   // Read the virtual file mapping.
223   llvm::SmallVector<unsigned, 8> VirtualFileMapping;
224   uint64_t NumFileMappings;
225   if (auto Err = readSize(NumFileMappings))
226     return Err;
227   for (size_t I = 0; I < NumFileMappings; ++I) {
228     uint64_t FilenameIndex;
229     if (auto Err = readIntMax(FilenameIndex, TranslationUnitFilenames.size()))
230       return Err;
231     VirtualFileMapping.push_back(FilenameIndex);
232   }
233
234   // Construct the files using unique filenames and virtual file mapping.
235   for (auto I : VirtualFileMapping) {
236     Filenames.push_back(TranslationUnitFilenames[I]);
237   }
238
239   // Read the expressions.
240   uint64_t NumExpressions;
241   if (auto Err = readSize(NumExpressions))
242     return Err;
243   // Create an array of dummy expressions that get the proper counters
244   // when the expressions are read, and the proper kinds when the counters
245   // are decoded.
246   Expressions.resize(
247       NumExpressions,
248       CounterExpression(CounterExpression::Subtract, Counter(), Counter()));
249   for (size_t I = 0; I < NumExpressions; ++I) {
250     if (auto Err = readCounter(Expressions[I].LHS))
251       return Err;
252     if (auto Err = readCounter(Expressions[I].RHS))
253       return Err;
254   }
255
256   // Read the mapping regions sub-arrays.
257   for (unsigned InferredFileID = 0, S = VirtualFileMapping.size();
258        InferredFileID < S; ++InferredFileID) {
259     if (auto Err = readMappingRegionsSubArray(MappingRegions, InferredFileID,
260                                               VirtualFileMapping.size()))
261       return Err;
262   }
263
264   // Set the counters for the expansion regions.
265   // i.e. Counter of expansion region = counter of the first region
266   // from the expanded file.
267   // Perform multiple passes to correctly propagate the counters through
268   // all the nested expansion regions.
269   SmallVector<CounterMappingRegion *, 8> FileIDExpansionRegionMapping;
270   FileIDExpansionRegionMapping.resize(VirtualFileMapping.size(), nullptr);
271   for (unsigned Pass = 1, S = VirtualFileMapping.size(); Pass < S; ++Pass) {
272     for (auto &R : MappingRegions) {
273       if (R.Kind != CounterMappingRegion::ExpansionRegion)
274         continue;
275       assert(!FileIDExpansionRegionMapping[R.ExpandedFileID]);
276       FileIDExpansionRegionMapping[R.ExpandedFileID] = &R;
277     }
278     for (auto &R : MappingRegions) {
279       if (FileIDExpansionRegionMapping[R.FileID]) {
280         FileIDExpansionRegionMapping[R.FileID]->Count = R.Count;
281         FileIDExpansionRegionMapping[R.FileID] = nullptr;
282       }
283     }
284   }
285
286   return success();
287 }
288
289 namespace {
290 /// \brief The coverage mapping data for a single function.
291 /// It points to the function's name.
292 template <typename IntPtrT> struct CoverageMappingFunctionRecord {
293   IntPtrT FunctionNamePtr;
294   uint32_t FunctionNameSize;
295   uint32_t CoverageMappingSize;
296   uint64_t FunctionHash;
297 };
298
299 /// \brief The coverage mapping data for a single translation unit.
300 /// It points to the array of function coverage mapping records and the encoded
301 /// filenames array.
302 template <typename IntPtrT> struct CoverageMappingTURecord {
303   uint32_t FunctionRecordsSize;
304   uint32_t FilenamesSize;
305   uint32_t CoverageMappingsSize;
306   uint32_t Version;
307 };
308
309 /// \brief A helper structure to access the data from a section
310 /// in an object file.
311 struct SectionData {
312   StringRef Data;
313   uint64_t Address;
314
315   std::error_code load(SectionRef &Section) {
316     if (auto Err = Section.getContents(Data))
317       return Err;
318     Address = Section.getAddress();
319     return instrprof_error::success;
320   }
321
322   std::error_code get(uint64_t Pointer, size_t Size, StringRef &Result) {
323     if (Pointer < Address)
324       return instrprof_error::malformed;
325     auto Offset = Pointer - Address;
326     if (Offset + Size > Data.size())
327       return instrprof_error::malformed;
328     Result = Data.substr(Pointer - Address, Size);
329     return instrprof_error::success;
330   }
331 };
332 }
333
334 template <typename T>
335 std::error_code readCoverageMappingData(
336     SectionData &ProfileNames, StringRef Data,
337     std::vector<BinaryCoverageReader::ProfileMappingRecord> &Records,
338     std::vector<StringRef> &Filenames) {
339   llvm::DenseSet<T> UniqueFunctionMappingData;
340
341   // Read the records in the coverage data section.
342   while (!Data.empty()) {
343     if (Data.size() < sizeof(CoverageMappingTURecord<T>))
344       return instrprof_error::malformed;
345     auto TU = reinterpret_cast<const CoverageMappingTURecord<T> *>(Data.data());
346     Data = Data.substr(sizeof(CoverageMappingTURecord<T>));
347     switch (TU->Version) {
348     case CoverageMappingVersion1:
349       break;
350     default:
351       return instrprof_error::unsupported_version;
352     }
353     auto Version = CoverageMappingVersion(TU->Version);
354
355     // Get the function records.
356     auto FunctionRecords =
357         reinterpret_cast<const CoverageMappingFunctionRecord<T> *>(Data.data());
358     if (Data.size() <
359         sizeof(CoverageMappingFunctionRecord<T>) * TU->FunctionRecordsSize)
360       return instrprof_error::malformed;
361     Data = Data.substr(sizeof(CoverageMappingFunctionRecord<T>) *
362                        TU->FunctionRecordsSize);
363
364     // Get the filenames.
365     if (Data.size() < TU->FilenamesSize)
366       return instrprof_error::malformed;
367     auto RawFilenames = Data.substr(0, TU->FilenamesSize);
368     Data = Data.substr(TU->FilenamesSize);
369     size_t FilenamesBegin = Filenames.size();
370     RawCoverageFilenamesReader Reader(RawFilenames, Filenames);
371     if (auto Err = Reader.read())
372       return Err;
373
374     // Get the coverage mappings.
375     if (Data.size() < TU->CoverageMappingsSize)
376       return instrprof_error::malformed;
377     auto CoverageMappings = Data.substr(0, TU->CoverageMappingsSize);
378     Data = Data.substr(TU->CoverageMappingsSize);
379
380     for (unsigned I = 0; I < TU->FunctionRecordsSize; ++I) {
381       auto &MappingRecord = FunctionRecords[I];
382
383       // Get the coverage mapping.
384       if (CoverageMappings.size() < MappingRecord.CoverageMappingSize)
385         return instrprof_error::malformed;
386       auto Mapping =
387           CoverageMappings.substr(0, MappingRecord.CoverageMappingSize);
388       CoverageMappings =
389           CoverageMappings.substr(MappingRecord.CoverageMappingSize);
390
391       // Ignore this record if we already have a record that points to the same
392       // function name.
393       // This is useful to ignore the redundant records for the functions
394       // with ODR linkage.
395       if (!UniqueFunctionMappingData.insert(MappingRecord.FunctionNamePtr)
396                .second)
397         continue;
398       StringRef FunctionName;
399       if (auto Err =
400               ProfileNames.get(MappingRecord.FunctionNamePtr,
401                                MappingRecord.FunctionNameSize, FunctionName))
402         return Err;
403       Records.push_back(BinaryCoverageReader::ProfileMappingRecord(
404           Version, FunctionName, MappingRecord.FunctionHash, Mapping,
405           FilenamesBegin, Filenames.size() - FilenamesBegin));
406     }
407   }
408
409   return instrprof_error::success;
410 }
411
412 static const char *TestingFormatMagic = "llvmcovmtestdata";
413
414 static std::error_code decodeTestingFormat(StringRef Data,
415                                            SectionData &ProfileNames,
416                                            StringRef &CoverageMapping) {
417   Data = Data.substr(StringRef(TestingFormatMagic).size());
418   if (Data.size() < 1)
419     return instrprof_error::truncated;
420   unsigned N = 0;
421   auto ProfileNamesSize =
422       decodeULEB128(reinterpret_cast<const uint8_t *>(Data.data()), &N);
423   if (N > Data.size())
424     return instrprof_error::malformed;
425   Data = Data.substr(N);
426   if (Data.size() < 1)
427     return instrprof_error::truncated;
428   N = 0;
429   ProfileNames.Address =
430       decodeULEB128(reinterpret_cast<const uint8_t *>(Data.data()), &N);
431   if (N > Data.size())
432     return instrprof_error::malformed;
433   Data = Data.substr(N);
434   if (Data.size() < ProfileNamesSize)
435     return instrprof_error::malformed;
436   ProfileNames.Data = Data.substr(0, ProfileNamesSize);
437   CoverageMapping = Data.substr(ProfileNamesSize);
438   return instrprof_error::success;
439 }
440
441 BinaryCoverageReader::BinaryCoverageReader(
442     std::unique_ptr<MemoryBuffer> &ObjectBuffer)
443     : CurrentRecord(0) {
444   if (ObjectBuffer->getBuffer().startswith(TestingFormatMagic)) {
445     // This is a special format used for testing.
446     SectionData ProfileNames;
447     StringRef CoverageMapping;
448     if (auto Err = decodeTestingFormat(ObjectBuffer->getBuffer(), ProfileNames,
449                                        CoverageMapping)) {
450       error(Err);
451       return;
452     }
453     error(readCoverageMappingData<uint64_t>(ProfileNames, CoverageMapping,
454                                             MappingRecords, Filenames));
455     Object = OwningBinary<ObjectFile>(std::unique_ptr<ObjectFile>(),
456                                       std::move(ObjectBuffer));
457     return;
458   }
459
460   auto File =
461       object::ObjectFile::createObjectFile(ObjectBuffer->getMemBufferRef());
462   if (!File)
463     error(File.getError());
464   else
465     Object = OwningBinary<ObjectFile>(std::move(File.get()),
466                                       std::move(ObjectBuffer));
467 }
468
469 std::error_code BinaryCoverageReader::readHeader() {
470   const ObjectFile *OF = Object.getBinary();
471   if (!OF)
472     return getError();
473   auto BytesInAddress = OF->getBytesInAddress();
474   if (BytesInAddress != 4 && BytesInAddress != 8)
475     return error(instrprof_error::malformed);
476
477   // Look for the sections that we are interested in.
478   int FoundSectionCount = 0;
479   SectionRef ProfileNames, CoverageMapping;
480   for (const auto &Section : OF->sections()) {
481     StringRef Name;
482     if (auto Err = Section.getName(Name))
483       return Err;
484     if (Name == "__llvm_prf_names") {
485       ProfileNames = Section;
486     } else if (Name == "__llvm_covmap") {
487       CoverageMapping = Section;
488     } else
489       continue;
490     ++FoundSectionCount;
491   }
492   if (FoundSectionCount != 2)
493     return error(instrprof_error::bad_header);
494
495   // Get the contents of the given sections.
496   StringRef Data;
497   if (auto Err = CoverageMapping.getContents(Data))
498     return Err;
499   SectionData ProfileNamesData;
500   if (auto Err = ProfileNamesData.load(ProfileNames))
501     return Err;
502
503   // Load the data from the found sections.
504   std::error_code Err;
505   if (BytesInAddress == 4)
506     Err = readCoverageMappingData<uint32_t>(ProfileNamesData, Data,
507                                             MappingRecords, Filenames);
508   else
509     Err = readCoverageMappingData<uint64_t>(ProfileNamesData, Data,
510                                             MappingRecords, Filenames);
511   if (Err)
512     return error(Err);
513
514   return success();
515 }
516
517 std::error_code
518 BinaryCoverageReader::readNextRecord(CoverageMappingRecord &Record) {
519   if (CurrentRecord >= MappingRecords.size())
520     return error(instrprof_error::eof);
521
522   FunctionsFilenames.clear();
523   Expressions.clear();
524   MappingRegions.clear();
525   auto &R = MappingRecords[CurrentRecord];
526   RawCoverageMappingReader Reader(
527       R.CoverageMapping,
528       makeArrayRef(Filenames).slice(R.FilenamesBegin, R.FilenamesSize),
529       FunctionsFilenames, Expressions, MappingRegions);
530   if (auto Err = Reader.read())
531     return Err;
532
533   Record.FunctionName = R.FunctionName;
534   Record.FunctionHash = R.FunctionHash;
535   Record.Filenames = FunctionsFilenames;
536   Record.Expressions = Expressions;
537   Record.MappingRegions = MappingRegions;
538
539   ++CurrentRecord;
540   return success();
541 }