1de1ab26fSDiego Novillo //===- SampleProfReader.cpp - Read LLVM sample profile data ---------------===//
2de1ab26fSDiego Novillo //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6de1ab26fSDiego Novillo //
7de1ab26fSDiego Novillo //===----------------------------------------------------------------------===//
8de1ab26fSDiego Novillo //
9de1ab26fSDiego Novillo // This file implements the class that reads LLVM sample profiles. It
10bb5605caSDiego Novillo // supports three file formats: text, binary and gcov.
11de1ab26fSDiego Novillo //
12bb5605caSDiego Novillo // The textual representation is useful for debugging and testing purposes. The
13bb5605caSDiego Novillo // binary representation is more compact, resulting in smaller file sizes.
14de1ab26fSDiego Novillo //
15bb5605caSDiego Novillo // The gcov encoding is the one generated by GCC's AutoFDO profile creation
16bb5605caSDiego Novillo // tool (https://github.com/google/autofdo)
17de1ab26fSDiego Novillo //
18bb5605caSDiego Novillo // All three encodings can be used interchangeably as an input sample profile.
19de1ab26fSDiego Novillo //
20de1ab26fSDiego Novillo //===----------------------------------------------------------------------===//
21de1ab26fSDiego Novillo 
22de1ab26fSDiego Novillo #include "llvm/ProfileData/SampleProfReader.h"
23b93483dbSDiego Novillo #include "llvm/ADT/DenseMap.h"
2440ee23dbSEaswaran Raman #include "llvm/ADT/STLExtras.h"
25e78d131aSEugene Zelenko #include "llvm/ADT/StringRef.h"
26e78d131aSEugene Zelenko #include "llvm/IR/ProfileSummary.h"
27e78d131aSEugene Zelenko #include "llvm/ProfileData/ProfileCommon.h"
28e78d131aSEugene Zelenko #include "llvm/ProfileData/SampleProf.h"
29b523790aSWei Mi #include "llvm/Support/Compression.h"
30de1ab26fSDiego Novillo #include "llvm/Support/ErrorOr.h"
31c572e92cSDiego Novillo #include "llvm/Support/LEB128.h"
32de1ab26fSDiego Novillo #include "llvm/Support/LineIterator.h"
336a14325dSWei Mi #include "llvm/Support/MD5.h"
34c572e92cSDiego Novillo #include "llvm/Support/MemoryBuffer.h"
35e78d131aSEugene Zelenko #include "llvm/Support/raw_ostream.h"
36e78d131aSEugene Zelenko #include <algorithm>
37e78d131aSEugene Zelenko #include <cstddef>
38e78d131aSEugene Zelenko #include <cstdint>
39e78d131aSEugene Zelenko #include <limits>
40e78d131aSEugene Zelenko #include <memory>
41e78d131aSEugene Zelenko #include <system_error>
42e78d131aSEugene Zelenko #include <vector>
43de1ab26fSDiego Novillo 
44de1ab26fSDiego Novillo using namespace llvm;
45e78d131aSEugene Zelenko using namespace sampleprof;
46de1ab26fSDiego Novillo 
475f8f34e4SAdrian Prantl /// Dump the function profile for \p FName.
48de1ab26fSDiego Novillo ///
49de1ab26fSDiego Novillo /// \param FName Name of the function to print.
50d5336ae2SDiego Novillo /// \param OS Stream to emit the output to.
51d5336ae2SDiego Novillo void SampleProfileReader::dumpFunctionProfile(StringRef FName,
52d5336ae2SDiego Novillo                                               raw_ostream &OS) {
538e415a82SDiego Novillo   OS << "Function: " << FName << ": " << Profiles[FName];
54de1ab26fSDiego Novillo }
55de1ab26fSDiego Novillo 
565f8f34e4SAdrian Prantl /// Dump all the function profiles found on stream \p OS.
57d5336ae2SDiego Novillo void SampleProfileReader::dump(raw_ostream &OS) {
58d5336ae2SDiego Novillo   for (const auto &I : Profiles)
59d5336ae2SDiego Novillo     dumpFunctionProfile(I.getKey(), OS);
60de1ab26fSDiego Novillo }
61de1ab26fSDiego Novillo 
625f8f34e4SAdrian Prantl /// Parse \p Input as function head.
636722688eSDehao Chen ///
646722688eSDehao Chen /// Parse one line of \p Input, and update function name in \p FName,
656722688eSDehao Chen /// function's total sample count in \p NumSamples, function's entry
666722688eSDehao Chen /// count in \p NumHeadSamples.
676722688eSDehao Chen ///
686722688eSDehao Chen /// \returns true if parsing is successful.
696722688eSDehao Chen static bool ParseHead(const StringRef &Input, StringRef &FName,
7038be3330SDiego Novillo                       uint64_t &NumSamples, uint64_t &NumHeadSamples) {
716722688eSDehao Chen   if (Input[0] == ' ')
726722688eSDehao Chen     return false;
736722688eSDehao Chen   size_t n2 = Input.rfind(':');
746722688eSDehao Chen   size_t n1 = Input.rfind(':', n2 - 1);
756722688eSDehao Chen   FName = Input.substr(0, n1);
766722688eSDehao Chen   if (Input.substr(n1 + 1, n2 - n1 - 1).getAsInteger(10, NumSamples))
776722688eSDehao Chen     return false;
786722688eSDehao Chen   if (Input.substr(n2 + 1).getAsInteger(10, NumHeadSamples))
796722688eSDehao Chen     return false;
806722688eSDehao Chen   return true;
816722688eSDehao Chen }
826722688eSDehao Chen 
835f8f34e4SAdrian Prantl /// Returns true if line offset \p L is legal (only has 16 bits).
8457d1dda5SDehao Chen static bool isOffsetLegal(unsigned L) { return (L & 0xffff) == L; }
8510042412SDehao Chen 
865f8f34e4SAdrian Prantl /// Parse \p Input as line sample.
876722688eSDehao Chen ///
886722688eSDehao Chen /// \param Input input line.
896722688eSDehao Chen /// \param IsCallsite true if the line represents an inlined callsite.
906722688eSDehao Chen /// \param Depth the depth of the inline stack.
916722688eSDehao Chen /// \param NumSamples total samples of the line/inlined callsite.
926722688eSDehao Chen /// \param LineOffset line offset to the start of the function.
936722688eSDehao Chen /// \param Discriminator discriminator of the line.
946722688eSDehao Chen /// \param TargetCountMap map from indirect call target to count.
956722688eSDehao Chen ///
966722688eSDehao Chen /// returns true if parsing is successful.
9738be3330SDiego Novillo static bool ParseLine(const StringRef &Input, bool &IsCallsite, uint32_t &Depth,
9838be3330SDiego Novillo                       uint64_t &NumSamples, uint32_t &LineOffset,
9938be3330SDiego Novillo                       uint32_t &Discriminator, StringRef &CalleeName,
10038be3330SDiego Novillo                       DenseMap<StringRef, uint64_t> &TargetCountMap) {
1016722688eSDehao Chen   for (Depth = 0; Input[Depth] == ' '; Depth++)
1026722688eSDehao Chen     ;
1036722688eSDehao Chen   if (Depth == 0)
1046722688eSDehao Chen     return false;
1056722688eSDehao Chen 
1066722688eSDehao Chen   size_t n1 = Input.find(':');
1076722688eSDehao Chen   StringRef Loc = Input.substr(Depth, n1 - Depth);
1086722688eSDehao Chen   size_t n2 = Loc.find('.');
1096722688eSDehao Chen   if (n2 == StringRef::npos) {
11010042412SDehao Chen     if (Loc.getAsInteger(10, LineOffset) || !isOffsetLegal(LineOffset))
1116722688eSDehao Chen       return false;
1126722688eSDehao Chen     Discriminator = 0;
1136722688eSDehao Chen   } else {
1146722688eSDehao Chen     if (Loc.substr(0, n2).getAsInteger(10, LineOffset))
1156722688eSDehao Chen       return false;
1166722688eSDehao Chen     if (Loc.substr(n2 + 1).getAsInteger(10, Discriminator))
1176722688eSDehao Chen       return false;
1186722688eSDehao Chen   }
1196722688eSDehao Chen 
1206722688eSDehao Chen   StringRef Rest = Input.substr(n1 + 2);
1216722688eSDehao Chen   if (Rest[0] >= '0' && Rest[0] <= '9') {
1226722688eSDehao Chen     IsCallsite = false;
1236722688eSDehao Chen     size_t n3 = Rest.find(' ');
1246722688eSDehao Chen     if (n3 == StringRef::npos) {
1256722688eSDehao Chen       if (Rest.getAsInteger(10, NumSamples))
1266722688eSDehao Chen         return false;
1276722688eSDehao Chen     } else {
1286722688eSDehao Chen       if (Rest.substr(0, n3).getAsInteger(10, NumSamples))
1296722688eSDehao Chen         return false;
1306722688eSDehao Chen     }
131984ab0f1SWei Mi     // Find call targets and their sample counts.
132984ab0f1SWei Mi     // Note: In some cases, there are symbols in the profile which are not
133984ab0f1SWei Mi     // mangled. To accommodate such cases, use colon + integer pairs as the
134984ab0f1SWei Mi     // anchor points.
135984ab0f1SWei Mi     // An example:
136984ab0f1SWei Mi     // _M_construct<char *>:1000 string_view<std::allocator<char> >:437
137984ab0f1SWei Mi     // ":1000" and ":437" are used as anchor points so the string above will
138984ab0f1SWei Mi     // be interpreted as
139984ab0f1SWei Mi     // target: _M_construct<char *>
140984ab0f1SWei Mi     // count: 1000
141984ab0f1SWei Mi     // target: string_view<std::allocator<char> >
142984ab0f1SWei Mi     // count: 437
1436722688eSDehao Chen     while (n3 != StringRef::npos) {
1446722688eSDehao Chen       n3 += Rest.substr(n3).find_first_not_of(' ');
1456722688eSDehao Chen       Rest = Rest.substr(n3);
146984ab0f1SWei Mi       n3 = Rest.find_first_of(':');
147984ab0f1SWei Mi       if (n3 == StringRef::npos || n3 == 0)
1486722688eSDehao Chen         return false;
149984ab0f1SWei Mi 
150984ab0f1SWei Mi       StringRef Target;
151984ab0f1SWei Mi       uint64_t count, n4;
152984ab0f1SWei Mi       while (true) {
153984ab0f1SWei Mi         // Get the segment after the current colon.
154984ab0f1SWei Mi         StringRef AfterColon = Rest.substr(n3 + 1);
155984ab0f1SWei Mi         // Get the target symbol before the current colon.
156984ab0f1SWei Mi         Target = Rest.substr(0, n3);
157984ab0f1SWei Mi         // Check if the word after the current colon is an integer.
158984ab0f1SWei Mi         n4 = AfterColon.find_first_of(' ');
159984ab0f1SWei Mi         n4 = (n4 != StringRef::npos) ? n3 + n4 + 1 : Rest.size();
160984ab0f1SWei Mi         StringRef WordAfterColon = Rest.substr(n3 + 1, n4 - n3 - 1);
161984ab0f1SWei Mi         if (!WordAfterColon.getAsInteger(10, count))
162984ab0f1SWei Mi           break;
163984ab0f1SWei Mi 
164984ab0f1SWei Mi         // Try to find the next colon.
165984ab0f1SWei Mi         uint64_t n5 = AfterColon.find_first_of(':');
166984ab0f1SWei Mi         if (n5 == StringRef::npos)
167984ab0f1SWei Mi           return false;
168984ab0f1SWei Mi         n3 += n5 + 1;
169984ab0f1SWei Mi       }
170984ab0f1SWei Mi 
171984ab0f1SWei Mi       // An anchor point is found. Save the {target, count} pair
172984ab0f1SWei Mi       TargetCountMap[Target] = count;
173984ab0f1SWei Mi       if (n4 == Rest.size())
174984ab0f1SWei Mi         break;
175984ab0f1SWei Mi       // Change n3 to the next blank space after colon + integer pair.
176984ab0f1SWei Mi       n3 = n4;
1776722688eSDehao Chen     }
1786722688eSDehao Chen   } else {
1796722688eSDehao Chen     IsCallsite = true;
18038be3330SDiego Novillo     size_t n3 = Rest.find_last_of(':');
1816722688eSDehao Chen     CalleeName = Rest.substr(0, n3);
1826722688eSDehao Chen     if (Rest.substr(n3 + 1).getAsInteger(10, NumSamples))
1836722688eSDehao Chen       return false;
1846722688eSDehao Chen   }
1856722688eSDehao Chen   return true;
1866722688eSDehao Chen }
1876722688eSDehao Chen 
1885f8f34e4SAdrian Prantl /// Load samples from a text file.
189de1ab26fSDiego Novillo ///
190de1ab26fSDiego Novillo /// See the documentation at the top of the file for an explanation of
191de1ab26fSDiego Novillo /// the expected format.
192de1ab26fSDiego Novillo ///
193de1ab26fSDiego Novillo /// \returns true if the file was loaded successfully, false otherwise.
1948c8ec1f6SWei Mi std::error_code SampleProfileReaderText::readImpl() {
195c572e92cSDiego Novillo   line_iterator LineIt(*Buffer, /*SkipBlanks=*/true, '#');
19648dd080cSNathan Slingerland   sampleprof_error Result = sampleprof_error::success;
197de1ab26fSDiego Novillo 
198aae1ed8eSDiego Novillo   InlineCallStack InlineStack;
1996722688eSDehao Chen 
2006722688eSDehao Chen   for (; !LineIt.is_at_eof(); ++LineIt) {
2016722688eSDehao Chen     if ((*LineIt)[(*LineIt).find_first_not_of(' ')] == '#')
2026722688eSDehao Chen       continue;
203de1ab26fSDiego Novillo     // Read the header of each function.
204de1ab26fSDiego Novillo     //
205de1ab26fSDiego Novillo     // Note that for function identifiers we are actually expecting
206de1ab26fSDiego Novillo     // mangled names, but we may not always get them. This happens when
207de1ab26fSDiego Novillo     // the compiler decides not to emit the function (e.g., it was inlined
208de1ab26fSDiego Novillo     // and removed). In this case, the binary will not have the linkage
209de1ab26fSDiego Novillo     // name for the function, so the profiler will emit the function's
210de1ab26fSDiego Novillo     // unmangled name, which may contain characters like ':' and '>' in its
211de1ab26fSDiego Novillo     // name (member functions, templates, etc).
212de1ab26fSDiego Novillo     //
213de1ab26fSDiego Novillo     // The only requirement we place on the identifier, then, is that it
214de1ab26fSDiego Novillo     // should not begin with a number.
2156722688eSDehao Chen     if ((*LineIt)[0] != ' ') {
21638be3330SDiego Novillo       uint64_t NumSamples, NumHeadSamples;
2176722688eSDehao Chen       StringRef FName;
2186722688eSDehao Chen       if (!ParseHead(*LineIt, FName, NumSamples, NumHeadSamples)) {
2193376a787SDiego Novillo         reportError(LineIt.line_number(),
220de1ab26fSDiego Novillo                     "Expected 'mangled_name:NUM:NUM', found " + *LineIt);
221c572e92cSDiego Novillo         return sampleprof_error::malformed;
222de1ab26fSDiego Novillo       }
223de1ab26fSDiego Novillo       Profiles[FName] = FunctionSamples();
224de1ab26fSDiego Novillo       FunctionSamples &FProfile = Profiles[FName];
22557d1dda5SDehao Chen       FProfile.setName(FName);
22648dd080cSNathan Slingerland       MergeResult(Result, FProfile.addTotalSamples(NumSamples));
22748dd080cSNathan Slingerland       MergeResult(Result, FProfile.addHeadSamples(NumHeadSamples));
2286722688eSDehao Chen       InlineStack.clear();
2296722688eSDehao Chen       InlineStack.push_back(&FProfile);
2306722688eSDehao Chen     } else {
23138be3330SDiego Novillo       uint64_t NumSamples;
2326722688eSDehao Chen       StringRef FName;
23338be3330SDiego Novillo       DenseMap<StringRef, uint64_t> TargetCountMap;
2346722688eSDehao Chen       bool IsCallsite;
23538be3330SDiego Novillo       uint32_t Depth, LineOffset, Discriminator;
2366722688eSDehao Chen       if (!ParseLine(*LineIt, IsCallsite, Depth, NumSamples, LineOffset,
2376722688eSDehao Chen                      Discriminator, FName, TargetCountMap)) {
2383376a787SDiego Novillo         reportError(LineIt.line_number(),
2393376a787SDiego Novillo                     "Expected 'NUM[.NUM]: NUM[ mangled_name:NUM]*', found " +
2403376a787SDiego Novillo                         *LineIt);
241c572e92cSDiego Novillo         return sampleprof_error::malformed;
242de1ab26fSDiego Novillo       }
2436722688eSDehao Chen       if (IsCallsite) {
2446722688eSDehao Chen         while (InlineStack.size() > Depth) {
2456722688eSDehao Chen           InlineStack.pop_back();
246c572e92cSDiego Novillo         }
2476722688eSDehao Chen         FunctionSamples &FSamples = InlineStack.back()->functionSamplesAt(
248adcd0268SBenjamin Kramer             LineLocation(LineOffset, Discriminator))[std::string(FName)];
24957d1dda5SDehao Chen         FSamples.setName(FName);
25048dd080cSNathan Slingerland         MergeResult(Result, FSamples.addTotalSamples(NumSamples));
2516722688eSDehao Chen         InlineStack.push_back(&FSamples);
2526722688eSDehao Chen       } else {
2536722688eSDehao Chen         while (InlineStack.size() > Depth) {
2546722688eSDehao Chen           InlineStack.pop_back();
2556722688eSDehao Chen         }
2566722688eSDehao Chen         FunctionSamples &FProfile = *InlineStack.back();
2576722688eSDehao Chen         for (const auto &name_count : TargetCountMap) {
25848dd080cSNathan Slingerland           MergeResult(Result, FProfile.addCalledTargetSamples(
25948dd080cSNathan Slingerland                                   LineOffset, Discriminator, name_count.first,
26048dd080cSNathan Slingerland                                   name_count.second));
261c572e92cSDiego Novillo         }
26248dd080cSNathan Slingerland         MergeResult(Result, FProfile.addBodySamples(LineOffset, Discriminator,
26348dd080cSNathan Slingerland                                                     NumSamples));
2646722688eSDehao Chen       }
265de1ab26fSDiego Novillo     }
266de1ab26fSDiego Novillo   }
26740ee23dbSEaswaran Raman   if (Result == sampleprof_error::success)
26840ee23dbSEaswaran Raman     computeSummary();
269de1ab26fSDiego Novillo 
27048dd080cSNathan Slingerland   return Result;
271de1ab26fSDiego Novillo }
272de1ab26fSDiego Novillo 
2734f823667SNathan Slingerland bool SampleProfileReaderText::hasFormat(const MemoryBuffer &Buffer) {
2744f823667SNathan Slingerland   bool result = false;
2754f823667SNathan Slingerland 
2764f823667SNathan Slingerland   // Check that the first non-comment line is a valid function header.
2774f823667SNathan Slingerland   line_iterator LineIt(Buffer, /*SkipBlanks=*/true, '#');
2784f823667SNathan Slingerland   if (!LineIt.is_at_eof()) {
2794f823667SNathan Slingerland     if ((*LineIt)[0] != ' ') {
2804f823667SNathan Slingerland       uint64_t NumSamples, NumHeadSamples;
2814f823667SNathan Slingerland       StringRef FName;
2824f823667SNathan Slingerland       result = ParseHead(*LineIt, FName, NumSamples, NumHeadSamples);
2834f823667SNathan Slingerland     }
2844f823667SNathan Slingerland   }
2854f823667SNathan Slingerland 
2864f823667SNathan Slingerland   return result;
2874f823667SNathan Slingerland }
2884f823667SNathan Slingerland 
289d5336ae2SDiego Novillo template <typename T> ErrorOr<T> SampleProfileReaderBinary::readNumber() {
290c572e92cSDiego Novillo   unsigned NumBytesRead = 0;
291c572e92cSDiego Novillo   std::error_code EC;
292c572e92cSDiego Novillo   uint64_t Val = decodeULEB128(Data, &NumBytesRead);
293c572e92cSDiego Novillo 
294c572e92cSDiego Novillo   if (Val > std::numeric_limits<T>::max())
295c572e92cSDiego Novillo     EC = sampleprof_error::malformed;
296c572e92cSDiego Novillo   else if (Data + NumBytesRead > End)
297c572e92cSDiego Novillo     EC = sampleprof_error::truncated;
298c572e92cSDiego Novillo   else
299c572e92cSDiego Novillo     EC = sampleprof_error::success;
300c572e92cSDiego Novillo 
301c572e92cSDiego Novillo   if (EC) {
3023376a787SDiego Novillo     reportError(0, EC.message());
303c572e92cSDiego Novillo     return EC;
304c572e92cSDiego Novillo   }
305c572e92cSDiego Novillo 
306c572e92cSDiego Novillo   Data += NumBytesRead;
307c572e92cSDiego Novillo   return static_cast<T>(Val);
308c572e92cSDiego Novillo }
309c572e92cSDiego Novillo 
310c572e92cSDiego Novillo ErrorOr<StringRef> SampleProfileReaderBinary::readString() {
311c572e92cSDiego Novillo   std::error_code EC;
312c572e92cSDiego Novillo   StringRef Str(reinterpret_cast<const char *>(Data));
313c572e92cSDiego Novillo   if (Data + Str.size() + 1 > End) {
314c572e92cSDiego Novillo     EC = sampleprof_error::truncated;
3153376a787SDiego Novillo     reportError(0, EC.message());
316c572e92cSDiego Novillo     return EC;
317c572e92cSDiego Novillo   }
318c572e92cSDiego Novillo 
319c572e92cSDiego Novillo   Data += Str.size() + 1;
320c572e92cSDiego Novillo   return Str;
321c572e92cSDiego Novillo }
322c572e92cSDiego Novillo 
323a0c0857eSWei Mi template <typename T>
3246a14325dSWei Mi ErrorOr<T> SampleProfileReaderBinary::readUnencodedNumber() {
3256a14325dSWei Mi   std::error_code EC;
3266a14325dSWei Mi 
3276a14325dSWei Mi   if (Data + sizeof(T) > End) {
3286a14325dSWei Mi     EC = sampleprof_error::truncated;
3296a14325dSWei Mi     reportError(0, EC.message());
3306a14325dSWei Mi     return EC;
3316a14325dSWei Mi   }
3326a14325dSWei Mi 
3336a14325dSWei Mi   using namespace support;
3346a14325dSWei Mi   T Val = endian::readNext<T, little, unaligned>(Data);
3356a14325dSWei Mi   return Val;
3366a14325dSWei Mi }
3376a14325dSWei Mi 
3386a14325dSWei Mi template <typename T>
339a0c0857eSWei Mi inline ErrorOr<uint32_t> SampleProfileReaderBinary::readStringIndex(T &Table) {
340760c5a8fSDiego Novillo   std::error_code EC;
34138be3330SDiego Novillo   auto Idx = readNumber<uint32_t>();
342760c5a8fSDiego Novillo   if (std::error_code EC = Idx.getError())
343760c5a8fSDiego Novillo     return EC;
344a0c0857eSWei Mi   if (*Idx >= Table.size())
345760c5a8fSDiego Novillo     return sampleprof_error::truncated_name_table;
346a0c0857eSWei Mi   return *Idx;
347a0c0857eSWei Mi }
348a0c0857eSWei Mi 
349be907324SWei Mi ErrorOr<StringRef> SampleProfileReaderBinary::readStringFromTable() {
350a0c0857eSWei Mi   auto Idx = readStringIndex(NameTable);
351a0c0857eSWei Mi   if (std::error_code EC = Idx.getError())
352a0c0857eSWei Mi     return EC;
353a0c0857eSWei Mi 
354760c5a8fSDiego Novillo   return NameTable[*Idx];
355760c5a8fSDiego Novillo }
356760c5a8fSDiego Novillo 
357a0c0857eSWei Mi ErrorOr<StringRef> SampleProfileReaderCompactBinary::readStringFromTable() {
358a0c0857eSWei Mi   auto Idx = readStringIndex(NameTable);
359a0c0857eSWei Mi   if (std::error_code EC = Idx.getError())
360a0c0857eSWei Mi     return EC;
361a0c0857eSWei Mi 
362a0c0857eSWei Mi   return StringRef(NameTable[*Idx]);
363a0c0857eSWei Mi }
364a0c0857eSWei Mi 
365a7f1e8efSDiego Novillo std::error_code
366a7f1e8efSDiego Novillo SampleProfileReaderBinary::readProfile(FunctionSamples &FProfile) {
367b93483dbSDiego Novillo   auto NumSamples = readNumber<uint64_t>();
368b93483dbSDiego Novillo   if (std::error_code EC = NumSamples.getError())
369c572e92cSDiego Novillo     return EC;
370b93483dbSDiego Novillo   FProfile.addTotalSamples(*NumSamples);
371c572e92cSDiego Novillo 
372c572e92cSDiego Novillo   // Read the samples in the body.
37338be3330SDiego Novillo   auto NumRecords = readNumber<uint32_t>();
374c572e92cSDiego Novillo   if (std::error_code EC = NumRecords.getError())
375c572e92cSDiego Novillo     return EC;
376a7f1e8efSDiego Novillo 
37738be3330SDiego Novillo   for (uint32_t I = 0; I < *NumRecords; ++I) {
378c572e92cSDiego Novillo     auto LineOffset = readNumber<uint64_t>();
379c572e92cSDiego Novillo     if (std::error_code EC = LineOffset.getError())
380c572e92cSDiego Novillo       return EC;
381c572e92cSDiego Novillo 
38210042412SDehao Chen     if (!isOffsetLegal(*LineOffset)) {
38310042412SDehao Chen       return std::error_code();
38410042412SDehao Chen     }
38510042412SDehao Chen 
386c572e92cSDiego Novillo     auto Discriminator = readNumber<uint64_t>();
387c572e92cSDiego Novillo     if (std::error_code EC = Discriminator.getError())
388c572e92cSDiego Novillo       return EC;
389c572e92cSDiego Novillo 
390c572e92cSDiego Novillo     auto NumSamples = readNumber<uint64_t>();
391c572e92cSDiego Novillo     if (std::error_code EC = NumSamples.getError())
392c572e92cSDiego Novillo       return EC;
393c572e92cSDiego Novillo 
39438be3330SDiego Novillo     auto NumCalls = readNumber<uint32_t>();
395c572e92cSDiego Novillo     if (std::error_code EC = NumCalls.getError())
396c572e92cSDiego Novillo       return EC;
397c572e92cSDiego Novillo 
39838be3330SDiego Novillo     for (uint32_t J = 0; J < *NumCalls; ++J) {
399760c5a8fSDiego Novillo       auto CalledFunction(readStringFromTable());
400c572e92cSDiego Novillo       if (std::error_code EC = CalledFunction.getError())
401c572e92cSDiego Novillo         return EC;
402c572e92cSDiego Novillo 
403c572e92cSDiego Novillo       auto CalledFunctionSamples = readNumber<uint64_t>();
404c572e92cSDiego Novillo       if (std::error_code EC = CalledFunctionSamples.getError())
405c572e92cSDiego Novillo         return EC;
406c572e92cSDiego Novillo 
407c572e92cSDiego Novillo       FProfile.addCalledTargetSamples(*LineOffset, *Discriminator,
408a7f1e8efSDiego Novillo                                       *CalledFunction, *CalledFunctionSamples);
409c572e92cSDiego Novillo     }
410c572e92cSDiego Novillo 
411c572e92cSDiego Novillo     FProfile.addBodySamples(*LineOffset, *Discriminator, *NumSamples);
412c572e92cSDiego Novillo   }
413a7f1e8efSDiego Novillo 
414a7f1e8efSDiego Novillo   // Read all the samples for inlined function calls.
41538be3330SDiego Novillo   auto NumCallsites = readNumber<uint32_t>();
416a7f1e8efSDiego Novillo   if (std::error_code EC = NumCallsites.getError())
417a7f1e8efSDiego Novillo     return EC;
418a7f1e8efSDiego Novillo 
41938be3330SDiego Novillo   for (uint32_t J = 0; J < *NumCallsites; ++J) {
420a7f1e8efSDiego Novillo     auto LineOffset = readNumber<uint64_t>();
421a7f1e8efSDiego Novillo     if (std::error_code EC = LineOffset.getError())
422a7f1e8efSDiego Novillo       return EC;
423a7f1e8efSDiego Novillo 
424a7f1e8efSDiego Novillo     auto Discriminator = readNumber<uint64_t>();
425a7f1e8efSDiego Novillo     if (std::error_code EC = Discriminator.getError())
426a7f1e8efSDiego Novillo       return EC;
427a7f1e8efSDiego Novillo 
428760c5a8fSDiego Novillo     auto FName(readStringFromTable());
429a7f1e8efSDiego Novillo     if (std::error_code EC = FName.getError())
430a7f1e8efSDiego Novillo       return EC;
431a7f1e8efSDiego Novillo 
4322c7ca9b5SDehao Chen     FunctionSamples &CalleeProfile = FProfile.functionSamplesAt(
433adcd0268SBenjamin Kramer         LineLocation(*LineOffset, *Discriminator))[std::string(*FName)];
43457d1dda5SDehao Chen     CalleeProfile.setName(*FName);
435a7f1e8efSDiego Novillo     if (std::error_code EC = readProfile(CalleeProfile))
436a7f1e8efSDiego Novillo       return EC;
437a7f1e8efSDiego Novillo   }
438a7f1e8efSDiego Novillo 
439a7f1e8efSDiego Novillo   return sampleprof_error::success;
440a7f1e8efSDiego Novillo }
441a7f1e8efSDiego Novillo 
44209dcfe68SWei Mi std::error_code
44309dcfe68SWei Mi SampleProfileReaderBinary::readFuncProfile(const uint8_t *Start) {
44409dcfe68SWei Mi   Data = Start;
445b93483dbSDiego Novillo   auto NumHeadSamples = readNumber<uint64_t>();
446b93483dbSDiego Novillo   if (std::error_code EC = NumHeadSamples.getError())
447b93483dbSDiego Novillo     return EC;
448b93483dbSDiego Novillo 
449760c5a8fSDiego Novillo   auto FName(readStringFromTable());
450a7f1e8efSDiego Novillo   if (std::error_code EC = FName.getError())
451a7f1e8efSDiego Novillo     return EC;
452a7f1e8efSDiego Novillo 
453a7f1e8efSDiego Novillo   Profiles[*FName] = FunctionSamples();
454a7f1e8efSDiego Novillo   FunctionSamples &FProfile = Profiles[*FName];
45557d1dda5SDehao Chen   FProfile.setName(*FName);
456a7f1e8efSDiego Novillo 
457b93483dbSDiego Novillo   FProfile.addHeadSamples(*NumHeadSamples);
458b93483dbSDiego Novillo 
459a7f1e8efSDiego Novillo   if (std::error_code EC = readProfile(FProfile))
460a7f1e8efSDiego Novillo     return EC;
4616a14325dSWei Mi   return sampleprof_error::success;
462c572e92cSDiego Novillo }
463c572e92cSDiego Novillo 
4648c8ec1f6SWei Mi std::error_code SampleProfileReaderBinary::readImpl() {
4656a14325dSWei Mi   while (!at_eof()) {
46609dcfe68SWei Mi     if (std::error_code EC = readFuncProfile(Data))
4676a14325dSWei Mi       return EC;
4686a14325dSWei Mi   }
4696a14325dSWei Mi 
4706a14325dSWei Mi   return sampleprof_error::success;
4716a14325dSWei Mi }
4726a14325dSWei Mi 
473ebad6788SWei Mi std::error_code SampleProfileReaderExtBinary::readOneSection(
474ebad6788SWei Mi     const uint8_t *Start, uint64_t Size, const SecHdrTableEntry &Entry) {
475077a9c70SWei Mi   Data = Start;
476b523790aSWei Mi   End = Start + Size;
477ebad6788SWei Mi   switch (Entry.Type) {
478be907324SWei Mi   case SecProfSummary:
479be907324SWei Mi     if (std::error_code EC = readSummary())
480be907324SWei Mi       return EC;
481b49eac71SWei Mi     if (hasSecFlag(Entry, SecProfSummaryFlags::SecFlagPartial))
482b49eac71SWei Mi       Summary->setPartialProfile(true);
483be907324SWei Mi     break;
484be907324SWei Mi   case SecNameTable:
485ebad6788SWei Mi     if (std::error_code EC = readNameTableSec(
486ebad6788SWei Mi             hasSecFlag(Entry, SecNameTableFlags::SecFlagMD5Name)))
487be907324SWei Mi       return EC;
488be907324SWei Mi     break;
489be907324SWei Mi   case SecLBRProfile:
49009dcfe68SWei Mi     if (std::error_code EC = readFuncProfiles())
491be907324SWei Mi       return EC;
492be907324SWei Mi     break;
493798e59b8SWei Mi   case SecProfileSymbolList:
49409dcfe68SWei Mi     if (std::error_code EC = readProfileSymbolList())
49509dcfe68SWei Mi       return EC;
49609dcfe68SWei Mi     break;
49709dcfe68SWei Mi   case SecFuncOffsetTable:
49809dcfe68SWei Mi     if (std::error_code EC = readFuncOffsetTable())
499798e59b8SWei Mi       return EC;
500798e59b8SWei Mi     break;
501be907324SWei Mi   default:
502077a9c70SWei Mi     break;
503be907324SWei Mi   }
504077a9c70SWei Mi   return sampleprof_error::success;
505077a9c70SWei Mi }
506077a9c70SWei Mi 
50709dcfe68SWei Mi void SampleProfileReaderExtBinary::collectFuncsFrom(const Module &M) {
50809dcfe68SWei Mi   UseAllFuncs = false;
50909dcfe68SWei Mi   FuncsToUse.clear();
51009dcfe68SWei Mi   for (auto &F : M)
51109dcfe68SWei Mi     FuncsToUse.insert(FunctionSamples::getCanonicalFnName(F));
51209dcfe68SWei Mi }
51309dcfe68SWei Mi 
51409dcfe68SWei Mi std::error_code SampleProfileReaderExtBinary::readFuncOffsetTable() {
51509dcfe68SWei Mi   auto Size = readNumber<uint64_t>();
51609dcfe68SWei Mi   if (std::error_code EC = Size.getError())
51709dcfe68SWei Mi     return EC;
51809dcfe68SWei Mi 
51909dcfe68SWei Mi   FuncOffsetTable.reserve(*Size);
52009dcfe68SWei Mi   for (uint32_t I = 0; I < *Size; ++I) {
52109dcfe68SWei Mi     auto FName(readStringFromTable());
52209dcfe68SWei Mi     if (std::error_code EC = FName.getError())
52309dcfe68SWei Mi       return EC;
52409dcfe68SWei Mi 
52509dcfe68SWei Mi     auto Offset = readNumber<uint64_t>();
52609dcfe68SWei Mi     if (std::error_code EC = Offset.getError())
52709dcfe68SWei Mi       return EC;
52809dcfe68SWei Mi 
52909dcfe68SWei Mi     FuncOffsetTable[*FName] = *Offset;
53009dcfe68SWei Mi   }
53109dcfe68SWei Mi   return sampleprof_error::success;
53209dcfe68SWei Mi }
53309dcfe68SWei Mi 
53409dcfe68SWei Mi std::error_code SampleProfileReaderExtBinary::readFuncProfiles() {
53509dcfe68SWei Mi   const uint8_t *Start = Data;
53609dcfe68SWei Mi   if (UseAllFuncs) {
53709dcfe68SWei Mi     while (Data < End) {
53809dcfe68SWei Mi       if (std::error_code EC = readFuncProfile(Data))
53909dcfe68SWei Mi         return EC;
54009dcfe68SWei Mi     }
54109dcfe68SWei Mi     assert(Data == End && "More data is read than expected");
54209dcfe68SWei Mi     return sampleprof_error::success;
54309dcfe68SWei Mi   }
54409dcfe68SWei Mi 
5458c8ec1f6SWei Mi   if (Remapper) {
54609dcfe68SWei Mi     for (auto Name : FuncsToUse) {
5478c8ec1f6SWei Mi       Remapper->insert(Name);
5488c8ec1f6SWei Mi     }
5498c8ec1f6SWei Mi   }
5508c8ec1f6SWei Mi 
551ebad6788SWei Mi   if (useMD5()) {
552ebad6788SWei Mi     for (auto Name : FuncsToUse) {
553ebad6788SWei Mi       auto GUID = std::to_string(MD5Hash(Name));
554ebad6788SWei Mi       auto iter = FuncOffsetTable.find(StringRef(GUID));
555ebad6788SWei Mi       if (iter == FuncOffsetTable.end())
556ebad6788SWei Mi         continue;
557ebad6788SWei Mi       const uint8_t *FuncProfileAddr = Start + iter->second;
558ebad6788SWei Mi       assert(FuncProfileAddr < End && "out of LBRProfile section");
559ebad6788SWei Mi       if (std::error_code EC = readFuncProfile(FuncProfileAddr))
560ebad6788SWei Mi         return EC;
561ebad6788SWei Mi     }
562ebad6788SWei Mi   } else {
5638c8ec1f6SWei Mi     for (auto NameOffset : FuncOffsetTable) {
5648c8ec1f6SWei Mi       auto FuncName = NameOffset.first;
5658c8ec1f6SWei Mi       if (!FuncsToUse.count(FuncName) &&
5668c8ec1f6SWei Mi           (!Remapper || !Remapper->exist(FuncName)))
56709dcfe68SWei Mi         continue;
5688c8ec1f6SWei Mi       const uint8_t *FuncProfileAddr = Start + NameOffset.second;
56909dcfe68SWei Mi       assert(FuncProfileAddr < End && "out of LBRProfile section");
57009dcfe68SWei Mi       if (std::error_code EC = readFuncProfile(FuncProfileAddr))
57109dcfe68SWei Mi         return EC;
57209dcfe68SWei Mi     }
573ebad6788SWei Mi   }
5748c8ec1f6SWei Mi 
57509dcfe68SWei Mi   Data = End;
57609dcfe68SWei Mi   return sampleprof_error::success;
57709dcfe68SWei Mi }
57809dcfe68SWei Mi 
57909dcfe68SWei Mi std::error_code SampleProfileReaderExtBinary::readProfileSymbolList() {
580b523790aSWei Mi   if (!ProfSymList)
581b523790aSWei Mi     ProfSymList = std::make_unique<ProfileSymbolList>();
582b523790aSWei Mi 
58309dcfe68SWei Mi   if (std::error_code EC = ProfSymList->read(Data, End - Data))
584798e59b8SWei Mi     return EC;
585798e59b8SWei Mi 
58609dcfe68SWei Mi   Data = End;
587b523790aSWei Mi   return sampleprof_error::success;
588b523790aSWei Mi }
589b523790aSWei Mi 
590b523790aSWei Mi std::error_code SampleProfileReaderExtBinaryBase::decompressSection(
591b523790aSWei Mi     const uint8_t *SecStart, const uint64_t SecSize,
592b523790aSWei Mi     const uint8_t *&DecompressBuf, uint64_t &DecompressBufSize) {
593b523790aSWei Mi   Data = SecStart;
594b523790aSWei Mi   End = SecStart + SecSize;
595b523790aSWei Mi   auto DecompressSize = readNumber<uint64_t>();
596b523790aSWei Mi   if (std::error_code EC = DecompressSize.getError())
597b523790aSWei Mi     return EC;
598b523790aSWei Mi   DecompressBufSize = *DecompressSize;
599b523790aSWei Mi 
600798e59b8SWei Mi   auto CompressSize = readNumber<uint64_t>();
601798e59b8SWei Mi   if (std::error_code EC = CompressSize.getError())
602798e59b8SWei Mi     return EC;
603798e59b8SWei Mi 
604b523790aSWei Mi   if (!llvm::zlib::isAvailable())
605b523790aSWei Mi     return sampleprof_error::zlib_unavailable;
606798e59b8SWei Mi 
607b523790aSWei Mi   StringRef CompressedStrings(reinterpret_cast<const char *>(Data),
608b523790aSWei Mi                               *CompressSize);
609b523790aSWei Mi   char *Buffer = Allocator.Allocate<char>(DecompressBufSize);
610283df8cfSWei Mi   size_t UCSize = DecompressBufSize;
611b523790aSWei Mi   llvm::Error E =
612283df8cfSWei Mi       zlib::uncompress(CompressedStrings, Buffer, UCSize);
613b523790aSWei Mi   if (E)
614b523790aSWei Mi     return sampleprof_error::uncompress_failed;
615b523790aSWei Mi   DecompressBuf = reinterpret_cast<const uint8_t *>(Buffer);
616798e59b8SWei Mi   return sampleprof_error::success;
617798e59b8SWei Mi }
618798e59b8SWei Mi 
6198c8ec1f6SWei Mi std::error_code SampleProfileReaderExtBinaryBase::readImpl() {
620077a9c70SWei Mi   const uint8_t *BufStart =
621077a9c70SWei Mi       reinterpret_cast<const uint8_t *>(Buffer->getBufferStart());
622077a9c70SWei Mi 
623077a9c70SWei Mi   for (auto &Entry : SecHdrTable) {
624077a9c70SWei Mi     // Skip empty section.
625077a9c70SWei Mi     if (!Entry.Size)
626077a9c70SWei Mi       continue;
627b523790aSWei Mi 
628077a9c70SWei Mi     const uint8_t *SecStart = BufStart + Entry.Offset;
629b523790aSWei Mi     uint64_t SecSize = Entry.Size;
630b523790aSWei Mi 
631b523790aSWei Mi     // If the section is compressed, decompress it into a buffer
632b523790aSWei Mi     // DecompressBuf before reading the actual data. The pointee of
633b523790aSWei Mi     // 'Data' will be changed to buffer hold by DecompressBuf
634b523790aSWei Mi     // temporarily when reading the actual data.
635ebad6788SWei Mi     bool isCompressed = hasSecFlag(Entry, SecCommonFlags::SecFlagCompress);
636b523790aSWei Mi     if (isCompressed) {
637b523790aSWei Mi       const uint8_t *DecompressBuf;
638b523790aSWei Mi       uint64_t DecompressBufSize;
639b523790aSWei Mi       if (std::error_code EC = decompressSection(
640b523790aSWei Mi               SecStart, SecSize, DecompressBuf, DecompressBufSize))
641077a9c70SWei Mi         return EC;
642b523790aSWei Mi       SecStart = DecompressBuf;
643b523790aSWei Mi       SecSize = DecompressBufSize;
644b523790aSWei Mi     }
645b523790aSWei Mi 
646ebad6788SWei Mi     if (std::error_code EC = readOneSection(SecStart, SecSize, Entry))
647b523790aSWei Mi       return EC;
648b523790aSWei Mi     if (Data != SecStart + SecSize)
649be907324SWei Mi       return sampleprof_error::malformed;
650b523790aSWei Mi 
651b523790aSWei Mi     // Change the pointee of 'Data' from DecompressBuf to original Buffer.
652b523790aSWei Mi     if (isCompressed) {
653b523790aSWei Mi       Data = BufStart + Entry.Offset;
654b523790aSWei Mi       End = BufStart + Buffer->getBufferSize();
655b523790aSWei Mi     }
656be907324SWei Mi   }
657be907324SWei Mi 
658be907324SWei Mi   return sampleprof_error::success;
659be907324SWei Mi }
660be907324SWei Mi 
6618c8ec1f6SWei Mi std::error_code SampleProfileReaderCompactBinary::readImpl() {
662d3289544SWenlei He   std::vector<uint64_t> OffsetsToUse;
663d3289544SWenlei He   if (UseAllFuncs) {
664d3289544SWenlei He     for (auto FuncEntry : FuncOffsetTable) {
665d3289544SWenlei He       OffsetsToUse.push_back(FuncEntry.second);
666d3289544SWenlei He     }
667d3289544SWenlei He   }
668d3289544SWenlei He   else {
6696a14325dSWei Mi     for (auto Name : FuncsToUse) {
6706a14325dSWei Mi       auto GUID = std::to_string(MD5Hash(Name));
6716a14325dSWei Mi       auto iter = FuncOffsetTable.find(StringRef(GUID));
6726a14325dSWei Mi       if (iter == FuncOffsetTable.end())
6736a14325dSWei Mi         continue;
674d3289544SWenlei He       OffsetsToUse.push_back(iter->second);
675d3289544SWenlei He     }
676d3289544SWenlei He   }
677d3289544SWenlei He 
678d3289544SWenlei He   for (auto Offset : OffsetsToUse) {
6796a14325dSWei Mi     const uint8_t *SavedData = Data;
68009dcfe68SWei Mi     if (std::error_code EC = readFuncProfile(
68109dcfe68SWei Mi             reinterpret_cast<const uint8_t *>(Buffer->getBufferStart()) +
68209dcfe68SWei Mi             Offset))
6836a14325dSWei Mi       return EC;
6846a14325dSWei Mi     Data = SavedData;
6856a14325dSWei Mi   }
686c572e92cSDiego Novillo   return sampleprof_error::success;
687c572e92cSDiego Novillo }
688c572e92cSDiego Novillo 
689a0c0857eSWei Mi std::error_code SampleProfileReaderRawBinary::verifySPMagic(uint64_t Magic) {
690a0c0857eSWei Mi   if (Magic == SPMagic())
691a0c0857eSWei Mi     return sampleprof_error::success;
692a0c0857eSWei Mi   return sampleprof_error::bad_magic;
693a0c0857eSWei Mi }
694a0c0857eSWei Mi 
695be907324SWei Mi std::error_code SampleProfileReaderExtBinary::verifySPMagic(uint64_t Magic) {
696be907324SWei Mi   if (Magic == SPMagic(SPF_Ext_Binary))
697be907324SWei Mi     return sampleprof_error::success;
698be907324SWei Mi   return sampleprof_error::bad_magic;
699be907324SWei Mi }
700be907324SWei Mi 
701a0c0857eSWei Mi std::error_code
702a0c0857eSWei Mi SampleProfileReaderCompactBinary::verifySPMagic(uint64_t Magic) {
703a0c0857eSWei Mi   if (Magic == SPMagic(SPF_Compact_Binary))
704a0c0857eSWei Mi     return sampleprof_error::success;
705a0c0857eSWei Mi   return sampleprof_error::bad_magic;
706a0c0857eSWei Mi }
707a0c0857eSWei Mi 
708be907324SWei Mi std::error_code SampleProfileReaderBinary::readNameTable() {
709a0c0857eSWei Mi   auto Size = readNumber<uint32_t>();
710a0c0857eSWei Mi   if (std::error_code EC = Size.getError())
711a0c0857eSWei Mi     return EC;
712a0c0857eSWei Mi   NameTable.reserve(*Size);
713a0c0857eSWei Mi   for (uint32_t I = 0; I < *Size; ++I) {
714a0c0857eSWei Mi     auto Name(readString());
715a0c0857eSWei Mi     if (std::error_code EC = Name.getError())
716a0c0857eSWei Mi       return EC;
717a0c0857eSWei Mi     NameTable.push_back(*Name);
718a0c0857eSWei Mi   }
719a0c0857eSWei Mi 
720a0c0857eSWei Mi   return sampleprof_error::success;
721a0c0857eSWei Mi }
722a0c0857eSWei Mi 
723ebad6788SWei Mi std::error_code SampleProfileReaderExtBinary::readMD5NameTable() {
724ebad6788SWei Mi   auto Size = readNumber<uint64_t>();
725ebad6788SWei Mi   if (std::error_code EC = Size.getError())
726ebad6788SWei Mi     return EC;
727ebad6788SWei Mi   NameTable.reserve(*Size);
728ebad6788SWei Mi   MD5StringBuf = std::make_unique<std::vector<std::string>>();
729ebad6788SWei Mi   MD5StringBuf->reserve(*Size);
730ebad6788SWei Mi   for (uint32_t I = 0; I < *Size; ++I) {
731ebad6788SWei Mi     auto FID = readNumber<uint64_t>();
732ebad6788SWei Mi     if (std::error_code EC = FID.getError())
733ebad6788SWei Mi       return EC;
734ebad6788SWei Mi     MD5StringBuf->push_back(std::to_string(*FID));
735ebad6788SWei Mi     // NameTable is a vector of StringRef. Here it is pushing back a
736ebad6788SWei Mi     // StringRef initialized with the last string in MD5stringBuf.
737ebad6788SWei Mi     NameTable.push_back(MD5StringBuf->back());
738ebad6788SWei Mi   }
739ebad6788SWei Mi   return sampleprof_error::success;
740ebad6788SWei Mi }
741ebad6788SWei Mi 
742ebad6788SWei Mi std::error_code SampleProfileReaderExtBinary::readNameTableSec(bool IsMD5) {
743ebad6788SWei Mi   if (IsMD5)
744ebad6788SWei Mi     return readMD5NameTable();
745ebad6788SWei Mi   return SampleProfileReaderBinary::readNameTable();
746ebad6788SWei Mi }
747ebad6788SWei Mi 
748a0c0857eSWei Mi std::error_code SampleProfileReaderCompactBinary::readNameTable() {
749a0c0857eSWei Mi   auto Size = readNumber<uint64_t>();
750a0c0857eSWei Mi   if (std::error_code EC = Size.getError())
751a0c0857eSWei Mi     return EC;
752a0c0857eSWei Mi   NameTable.reserve(*Size);
753a0c0857eSWei Mi   for (uint32_t I = 0; I < *Size; ++I) {
754a0c0857eSWei Mi     auto FID = readNumber<uint64_t>();
755a0c0857eSWei Mi     if (std::error_code EC = FID.getError())
756a0c0857eSWei Mi       return EC;
757a0c0857eSWei Mi     NameTable.push_back(std::to_string(*FID));
758a0c0857eSWei Mi   }
759a0c0857eSWei Mi   return sampleprof_error::success;
760a0c0857eSWei Mi }
761a0c0857eSWei Mi 
762be907324SWei Mi std::error_code SampleProfileReaderExtBinaryBase::readSecHdrTableEntry() {
763be907324SWei Mi   SecHdrTableEntry Entry;
764be907324SWei Mi   auto Type = readUnencodedNumber<uint64_t>();
765be907324SWei Mi   if (std::error_code EC = Type.getError())
766be907324SWei Mi     return EC;
767be907324SWei Mi   Entry.Type = static_cast<SecType>(*Type);
768c572e92cSDiego Novillo 
769b523790aSWei Mi   auto Flags = readUnencodedNumber<uint64_t>();
770b523790aSWei Mi   if (std::error_code EC = Flags.getError())
771be907324SWei Mi     return EC;
772b523790aSWei Mi   Entry.Flags = *Flags;
773be907324SWei Mi 
774be907324SWei Mi   auto Offset = readUnencodedNumber<uint64_t>();
775be907324SWei Mi   if (std::error_code EC = Offset.getError())
776be907324SWei Mi     return EC;
777be907324SWei Mi   Entry.Offset = *Offset;
778be907324SWei Mi 
779be907324SWei Mi   auto Size = readUnencodedNumber<uint64_t>();
780be907324SWei Mi   if (std::error_code EC = Size.getError())
781be907324SWei Mi     return EC;
782be907324SWei Mi   Entry.Size = *Size;
783be907324SWei Mi 
784be907324SWei Mi   SecHdrTable.push_back(std::move(Entry));
785be907324SWei Mi   return sampleprof_error::success;
786be907324SWei Mi }
787be907324SWei Mi 
788be907324SWei Mi std::error_code SampleProfileReaderExtBinaryBase::readSecHdrTable() {
789be907324SWei Mi   auto EntryNum = readUnencodedNumber<uint64_t>();
790be907324SWei Mi   if (std::error_code EC = EntryNum.getError())
791be907324SWei Mi     return EC;
792be907324SWei Mi 
793be907324SWei Mi   for (uint32_t i = 0; i < (*EntryNum); i++)
794be907324SWei Mi     if (std::error_code EC = readSecHdrTableEntry())
795be907324SWei Mi       return EC;
796be907324SWei Mi 
797be907324SWei Mi   return sampleprof_error::success;
798be907324SWei Mi }
799be907324SWei Mi 
800be907324SWei Mi std::error_code SampleProfileReaderExtBinaryBase::readHeader() {
801be907324SWei Mi   const uint8_t *BufStart =
802be907324SWei Mi       reinterpret_cast<const uint8_t *>(Buffer->getBufferStart());
803be907324SWei Mi   Data = BufStart;
804be907324SWei Mi   End = BufStart + Buffer->getBufferSize();
805be907324SWei Mi 
806be907324SWei Mi   if (std::error_code EC = readMagicIdent())
807be907324SWei Mi     return EC;
808be907324SWei Mi 
809be907324SWei Mi   if (std::error_code EC = readSecHdrTable())
810be907324SWei Mi     return EC;
811be907324SWei Mi 
812be907324SWei Mi   return sampleprof_error::success;
813be907324SWei Mi }
814be907324SWei Mi 
815eee532cdSWei Mi uint64_t SampleProfileReaderExtBinaryBase::getSectionSize(SecType Type) {
816eee532cdSWei Mi   for (auto &Entry : SecHdrTable) {
817eee532cdSWei Mi     if (Entry.Type == Type)
818eee532cdSWei Mi       return Entry.Size;
819eee532cdSWei Mi   }
820eee532cdSWei Mi   return 0;
821eee532cdSWei Mi }
822eee532cdSWei Mi 
823eee532cdSWei Mi uint64_t SampleProfileReaderExtBinaryBase::getFileSize() {
82409dcfe68SWei Mi   // Sections in SecHdrTable is not necessarily in the same order as
82509dcfe68SWei Mi   // sections in the profile because section like FuncOffsetTable needs
82609dcfe68SWei Mi   // to be written after section LBRProfile but needs to be read before
82709dcfe68SWei Mi   // section LBRProfile, so we cannot simply use the last entry in
82809dcfe68SWei Mi   // SecHdrTable to calculate the file size.
82909dcfe68SWei Mi   uint64_t FileSize = 0;
83009dcfe68SWei Mi   for (auto &Entry : SecHdrTable) {
83109dcfe68SWei Mi     FileSize = std::max(Entry.Offset + Entry.Size, FileSize);
83209dcfe68SWei Mi   }
83309dcfe68SWei Mi   return FileSize;
834eee532cdSWei Mi }
835eee532cdSWei Mi 
836b49eac71SWei Mi static std::string getSecFlagsStr(const SecHdrTableEntry &Entry) {
837b49eac71SWei Mi   std::string Flags;
838b49eac71SWei Mi   if (hasSecFlag(Entry, SecCommonFlags::SecFlagCompress))
839b49eac71SWei Mi     Flags.append("{compressed,");
840b49eac71SWei Mi   else
841b49eac71SWei Mi     Flags.append("{");
842b49eac71SWei Mi 
843b49eac71SWei Mi   switch (Entry.Type) {
844b49eac71SWei Mi   case SecNameTable:
845b49eac71SWei Mi     if (hasSecFlag(Entry, SecNameTableFlags::SecFlagMD5Name))
846b49eac71SWei Mi       Flags.append("md5,");
847b49eac71SWei Mi     break;
848b49eac71SWei Mi   case SecProfSummary:
849b49eac71SWei Mi     if (hasSecFlag(Entry, SecProfSummaryFlags::SecFlagPartial))
850b49eac71SWei Mi       Flags.append("partial,");
851b49eac71SWei Mi     break;
852b49eac71SWei Mi   default:
853b49eac71SWei Mi     break;
854b49eac71SWei Mi   }
855b49eac71SWei Mi   char &last = Flags.back();
856b49eac71SWei Mi   if (last == ',')
857b49eac71SWei Mi     last = '}';
858b49eac71SWei Mi   else
859b49eac71SWei Mi     Flags.append("}");
860b49eac71SWei Mi   return Flags;
861b49eac71SWei Mi }
862b49eac71SWei Mi 
863eee532cdSWei Mi bool SampleProfileReaderExtBinaryBase::dumpSectionInfo(raw_ostream &OS) {
864eee532cdSWei Mi   uint64_t TotalSecsSize = 0;
865eee532cdSWei Mi   for (auto &Entry : SecHdrTable) {
866eee532cdSWei Mi     OS << getSecName(Entry.Type) << " - Offset: " << Entry.Offset
867b49eac71SWei Mi        << ", Size: " << Entry.Size << ", Flags: " << getSecFlagsStr(Entry)
868b49eac71SWei Mi        << "\n";
869b49eac71SWei Mi     ;
870eee532cdSWei Mi     TotalSecsSize += getSectionSize(Entry.Type);
871eee532cdSWei Mi   }
872eee532cdSWei Mi   uint64_t HeaderSize = SecHdrTable.front().Offset;
873eee532cdSWei Mi   assert(HeaderSize + TotalSecsSize == getFileSize() &&
874eee532cdSWei Mi          "Size of 'header + sections' doesn't match the total size of profile");
875eee532cdSWei Mi 
876eee532cdSWei Mi   OS << "Header Size: " << HeaderSize << "\n";
877eee532cdSWei Mi   OS << "Total Sections Size: " << TotalSecsSize << "\n";
878eee532cdSWei Mi   OS << "File Size: " << getFileSize() << "\n";
879eee532cdSWei Mi   return true;
880eee532cdSWei Mi }
881eee532cdSWei Mi 
882be907324SWei Mi std::error_code SampleProfileReaderBinary::readMagicIdent() {
883c572e92cSDiego Novillo   // Read and check the magic identifier.
884c572e92cSDiego Novillo   auto Magic = readNumber<uint64_t>();
885c572e92cSDiego Novillo   if (std::error_code EC = Magic.getError())
886c572e92cSDiego Novillo     return EC;
887a0c0857eSWei Mi   else if (std::error_code EC = verifySPMagic(*Magic))
888c6b96c8dSWei Mi     return EC;
889c572e92cSDiego Novillo 
890c572e92cSDiego Novillo   // Read the version number.
891c572e92cSDiego Novillo   auto Version = readNumber<uint64_t>();
892c572e92cSDiego Novillo   if (std::error_code EC = Version.getError())
893c572e92cSDiego Novillo     return EC;
894c572e92cSDiego Novillo   else if (*Version != SPVersion())
895c572e92cSDiego Novillo     return sampleprof_error::unsupported_version;
896c572e92cSDiego Novillo 
897be907324SWei Mi   return sampleprof_error::success;
898be907324SWei Mi }
899be907324SWei Mi 
900be907324SWei Mi std::error_code SampleProfileReaderBinary::readHeader() {
901be907324SWei Mi   Data = reinterpret_cast<const uint8_t *>(Buffer->getBufferStart());
902be907324SWei Mi   End = Data + Buffer->getBufferSize();
903be907324SWei Mi 
904be907324SWei Mi   if (std::error_code EC = readMagicIdent())
905be907324SWei Mi     return EC;
906be907324SWei Mi 
90740ee23dbSEaswaran Raman   if (std::error_code EC = readSummary())
90840ee23dbSEaswaran Raman     return EC;
90940ee23dbSEaswaran Raman 
910a0c0857eSWei Mi   if (std::error_code EC = readNameTable())
911760c5a8fSDiego Novillo     return EC;
912c572e92cSDiego Novillo   return sampleprof_error::success;
913c572e92cSDiego Novillo }
914c572e92cSDiego Novillo 
9156a14325dSWei Mi std::error_code SampleProfileReaderCompactBinary::readHeader() {
9166a14325dSWei Mi   SampleProfileReaderBinary::readHeader();
9176a14325dSWei Mi   if (std::error_code EC = readFuncOffsetTable())
9186a14325dSWei Mi     return EC;
9196a14325dSWei Mi   return sampleprof_error::success;
9206a14325dSWei Mi }
9216a14325dSWei Mi 
9226a14325dSWei Mi std::error_code SampleProfileReaderCompactBinary::readFuncOffsetTable() {
9236a14325dSWei Mi   auto TableOffset = readUnencodedNumber<uint64_t>();
9246a14325dSWei Mi   if (std::error_code EC = TableOffset.getError())
9256a14325dSWei Mi     return EC;
9266a14325dSWei Mi 
9276a14325dSWei Mi   const uint8_t *SavedData = Data;
9286a14325dSWei Mi   const uint8_t *TableStart =
9296a14325dSWei Mi       reinterpret_cast<const uint8_t *>(Buffer->getBufferStart()) +
9306a14325dSWei Mi       *TableOffset;
9316a14325dSWei Mi   Data = TableStart;
9326a14325dSWei Mi 
9336a14325dSWei Mi   auto Size = readNumber<uint64_t>();
9346a14325dSWei Mi   if (std::error_code EC = Size.getError())
9356a14325dSWei Mi     return EC;
9366a14325dSWei Mi 
9376a14325dSWei Mi   FuncOffsetTable.reserve(*Size);
9386a14325dSWei Mi   for (uint32_t I = 0; I < *Size; ++I) {
9396a14325dSWei Mi     auto FName(readStringFromTable());
9406a14325dSWei Mi     if (std::error_code EC = FName.getError())
9416a14325dSWei Mi       return EC;
9426a14325dSWei Mi 
9436a14325dSWei Mi     auto Offset = readNumber<uint64_t>();
9446a14325dSWei Mi     if (std::error_code EC = Offset.getError())
9456a14325dSWei Mi       return EC;
9466a14325dSWei Mi 
9476a14325dSWei Mi     FuncOffsetTable[*FName] = *Offset;
9486a14325dSWei Mi   }
9496a14325dSWei Mi   End = TableStart;
9506a14325dSWei Mi   Data = SavedData;
9516a14325dSWei Mi   return sampleprof_error::success;
9526a14325dSWei Mi }
9536a14325dSWei Mi 
95409dcfe68SWei Mi void SampleProfileReaderCompactBinary::collectFuncsFrom(const Module &M) {
955d3289544SWenlei He   UseAllFuncs = false;
9566a14325dSWei Mi   FuncsToUse.clear();
95709dcfe68SWei Mi   for (auto &F : M)
95809dcfe68SWei Mi     FuncsToUse.insert(FunctionSamples::getCanonicalFnName(F));
9596a14325dSWei Mi }
9606a14325dSWei Mi 
96140ee23dbSEaswaran Raman std::error_code SampleProfileReaderBinary::readSummaryEntry(
96240ee23dbSEaswaran Raman     std::vector<ProfileSummaryEntry> &Entries) {
96340ee23dbSEaswaran Raman   auto Cutoff = readNumber<uint64_t>();
96440ee23dbSEaswaran Raman   if (std::error_code EC = Cutoff.getError())
96540ee23dbSEaswaran Raman     return EC;
96640ee23dbSEaswaran Raman 
96740ee23dbSEaswaran Raman   auto MinBlockCount = readNumber<uint64_t>();
96840ee23dbSEaswaran Raman   if (std::error_code EC = MinBlockCount.getError())
96940ee23dbSEaswaran Raman     return EC;
97040ee23dbSEaswaran Raman 
97140ee23dbSEaswaran Raman   auto NumBlocks = readNumber<uint64_t>();
97240ee23dbSEaswaran Raman   if (std::error_code EC = NumBlocks.getError())
97340ee23dbSEaswaran Raman     return EC;
97440ee23dbSEaswaran Raman 
97540ee23dbSEaswaran Raman   Entries.emplace_back(*Cutoff, *MinBlockCount, *NumBlocks);
97640ee23dbSEaswaran Raman   return sampleprof_error::success;
97740ee23dbSEaswaran Raman }
97840ee23dbSEaswaran Raman 
97940ee23dbSEaswaran Raman std::error_code SampleProfileReaderBinary::readSummary() {
98040ee23dbSEaswaran Raman   auto TotalCount = readNumber<uint64_t>();
98140ee23dbSEaswaran Raman   if (std::error_code EC = TotalCount.getError())
98240ee23dbSEaswaran Raman     return EC;
98340ee23dbSEaswaran Raman 
98440ee23dbSEaswaran Raman   auto MaxBlockCount = readNumber<uint64_t>();
98540ee23dbSEaswaran Raman   if (std::error_code EC = MaxBlockCount.getError())
98640ee23dbSEaswaran Raman     return EC;
98740ee23dbSEaswaran Raman 
98840ee23dbSEaswaran Raman   auto MaxFunctionCount = readNumber<uint64_t>();
98940ee23dbSEaswaran Raman   if (std::error_code EC = MaxFunctionCount.getError())
99040ee23dbSEaswaran Raman     return EC;
99140ee23dbSEaswaran Raman 
99240ee23dbSEaswaran Raman   auto NumBlocks = readNumber<uint64_t>();
99340ee23dbSEaswaran Raman   if (std::error_code EC = NumBlocks.getError())
99440ee23dbSEaswaran Raman     return EC;
99540ee23dbSEaswaran Raman 
99640ee23dbSEaswaran Raman   auto NumFunctions = readNumber<uint64_t>();
99740ee23dbSEaswaran Raman   if (std::error_code EC = NumFunctions.getError())
99840ee23dbSEaswaran Raman     return EC;
99940ee23dbSEaswaran Raman 
100040ee23dbSEaswaran Raman   auto NumSummaryEntries = readNumber<uint64_t>();
100140ee23dbSEaswaran Raman   if (std::error_code EC = NumSummaryEntries.getError())
100240ee23dbSEaswaran Raman     return EC;
100340ee23dbSEaswaran Raman 
100440ee23dbSEaswaran Raman   std::vector<ProfileSummaryEntry> Entries;
100540ee23dbSEaswaran Raman   for (unsigned i = 0; i < *NumSummaryEntries; i++) {
100640ee23dbSEaswaran Raman     std::error_code EC = readSummaryEntry(Entries);
100740ee23dbSEaswaran Raman     if (EC != sampleprof_error::success)
100840ee23dbSEaswaran Raman       return EC;
100940ee23dbSEaswaran Raman   }
10100eaee545SJonas Devlieghere   Summary = std::make_unique<ProfileSummary>(
10117cefdb81SEaswaran Raman       ProfileSummary::PSK_Sample, Entries, *TotalCount, *MaxBlockCount, 0,
10127cefdb81SEaswaran Raman       *MaxFunctionCount, *NumBlocks, *NumFunctions);
101340ee23dbSEaswaran Raman 
101440ee23dbSEaswaran Raman   return sampleprof_error::success;
101540ee23dbSEaswaran Raman }
101640ee23dbSEaswaran Raman 
1017a0c0857eSWei Mi bool SampleProfileReaderRawBinary::hasFormat(const MemoryBuffer &Buffer) {
1018c572e92cSDiego Novillo   const uint8_t *Data =
1019c572e92cSDiego Novillo       reinterpret_cast<const uint8_t *>(Buffer.getBufferStart());
1020c572e92cSDiego Novillo   uint64_t Magic = decodeULEB128(Data);
1021c572e92cSDiego Novillo   return Magic == SPMagic();
1022c572e92cSDiego Novillo }
1023c572e92cSDiego Novillo 
1024be907324SWei Mi bool SampleProfileReaderExtBinary::hasFormat(const MemoryBuffer &Buffer) {
1025be907324SWei Mi   const uint8_t *Data =
1026be907324SWei Mi       reinterpret_cast<const uint8_t *>(Buffer.getBufferStart());
1027be907324SWei Mi   uint64_t Magic = decodeULEB128(Data);
1028be907324SWei Mi   return Magic == SPMagic(SPF_Ext_Binary);
1029be907324SWei Mi }
1030be907324SWei Mi 
1031a0c0857eSWei Mi bool SampleProfileReaderCompactBinary::hasFormat(const MemoryBuffer &Buffer) {
1032a0c0857eSWei Mi   const uint8_t *Data =
1033a0c0857eSWei Mi       reinterpret_cast<const uint8_t *>(Buffer.getBufferStart());
1034a0c0857eSWei Mi   uint64_t Magic = decodeULEB128(Data);
1035a0c0857eSWei Mi   return Magic == SPMagic(SPF_Compact_Binary);
1036a0c0857eSWei Mi }
1037a0c0857eSWei Mi 
10383376a787SDiego Novillo std::error_code SampleProfileReaderGCC::skipNextWord() {
10393376a787SDiego Novillo   uint32_t dummy;
10403376a787SDiego Novillo   if (!GcovBuffer.readInt(dummy))
10413376a787SDiego Novillo     return sampleprof_error::truncated;
10423376a787SDiego Novillo   return sampleprof_error::success;
10433376a787SDiego Novillo }
10443376a787SDiego Novillo 
10453376a787SDiego Novillo template <typename T> ErrorOr<T> SampleProfileReaderGCC::readNumber() {
10463376a787SDiego Novillo   if (sizeof(T) <= sizeof(uint32_t)) {
10473376a787SDiego Novillo     uint32_t Val;
10483376a787SDiego Novillo     if (GcovBuffer.readInt(Val) && Val <= std::numeric_limits<T>::max())
10493376a787SDiego Novillo       return static_cast<T>(Val);
10503376a787SDiego Novillo   } else if (sizeof(T) <= sizeof(uint64_t)) {
10513376a787SDiego Novillo     uint64_t Val;
10523376a787SDiego Novillo     if (GcovBuffer.readInt64(Val) && Val <= std::numeric_limits<T>::max())
10533376a787SDiego Novillo       return static_cast<T>(Val);
10543376a787SDiego Novillo   }
10553376a787SDiego Novillo 
10563376a787SDiego Novillo   std::error_code EC = sampleprof_error::malformed;
10573376a787SDiego Novillo   reportError(0, EC.message());
10583376a787SDiego Novillo   return EC;
10593376a787SDiego Novillo }
10603376a787SDiego Novillo 
10613376a787SDiego Novillo ErrorOr<StringRef> SampleProfileReaderGCC::readString() {
10623376a787SDiego Novillo   StringRef Str;
10633376a787SDiego Novillo   if (!GcovBuffer.readString(Str))
10643376a787SDiego Novillo     return sampleprof_error::truncated;
10653376a787SDiego Novillo   return Str;
10663376a787SDiego Novillo }
10673376a787SDiego Novillo 
10683376a787SDiego Novillo std::error_code SampleProfileReaderGCC::readHeader() {
10693376a787SDiego Novillo   // Read the magic identifier.
10703376a787SDiego Novillo   if (!GcovBuffer.readGCDAFormat())
10713376a787SDiego Novillo     return sampleprof_error::unrecognized_format;
10723376a787SDiego Novillo 
10733376a787SDiego Novillo   // Read the version number. Note - the GCC reader does not validate this
10743376a787SDiego Novillo   // version, but the profile creator generates v704.
10753376a787SDiego Novillo   GCOV::GCOVVersion version;
10763376a787SDiego Novillo   if (!GcovBuffer.readGCOVVersion(version))
10773376a787SDiego Novillo     return sampleprof_error::unrecognized_format;
10783376a787SDiego Novillo 
1079*2d00eb17SFangrui Song   if (version != GCOV::V407)
10803376a787SDiego Novillo     return sampleprof_error::unsupported_version;
10813376a787SDiego Novillo 
10823376a787SDiego Novillo   // Skip the empty integer.
10833376a787SDiego Novillo   if (std::error_code EC = skipNextWord())
10843376a787SDiego Novillo     return EC;
10853376a787SDiego Novillo 
10863376a787SDiego Novillo   return sampleprof_error::success;
10873376a787SDiego Novillo }
10883376a787SDiego Novillo 
10893376a787SDiego Novillo std::error_code SampleProfileReaderGCC::readSectionTag(uint32_t Expected) {
10903376a787SDiego Novillo   uint32_t Tag;
10913376a787SDiego Novillo   if (!GcovBuffer.readInt(Tag))
10923376a787SDiego Novillo     return sampleprof_error::truncated;
10933376a787SDiego Novillo 
10943376a787SDiego Novillo   if (Tag != Expected)
10953376a787SDiego Novillo     return sampleprof_error::malformed;
10963376a787SDiego Novillo 
10973376a787SDiego Novillo   if (std::error_code EC = skipNextWord())
10983376a787SDiego Novillo     return EC;
10993376a787SDiego Novillo 
11003376a787SDiego Novillo   return sampleprof_error::success;
11013376a787SDiego Novillo }
11023376a787SDiego Novillo 
11033376a787SDiego Novillo std::error_code SampleProfileReaderGCC::readNameTable() {
11043376a787SDiego Novillo   if (std::error_code EC = readSectionTag(GCOVTagAFDOFileNames))
11053376a787SDiego Novillo     return EC;
11063376a787SDiego Novillo 
11073376a787SDiego Novillo   uint32_t Size;
11083376a787SDiego Novillo   if (!GcovBuffer.readInt(Size))
11093376a787SDiego Novillo     return sampleprof_error::truncated;
11103376a787SDiego Novillo 
11113376a787SDiego Novillo   for (uint32_t I = 0; I < Size; ++I) {
11123376a787SDiego Novillo     StringRef Str;
11133376a787SDiego Novillo     if (!GcovBuffer.readString(Str))
11143376a787SDiego Novillo       return sampleprof_error::truncated;
1115adcd0268SBenjamin Kramer     Names.push_back(std::string(Str));
11163376a787SDiego Novillo   }
11173376a787SDiego Novillo 
11183376a787SDiego Novillo   return sampleprof_error::success;
11193376a787SDiego Novillo }
11203376a787SDiego Novillo 
11213376a787SDiego Novillo std::error_code SampleProfileReaderGCC::readFunctionProfiles() {
11223376a787SDiego Novillo   if (std::error_code EC = readSectionTag(GCOVTagAFDOFunction))
11233376a787SDiego Novillo     return EC;
11243376a787SDiego Novillo 
11253376a787SDiego Novillo   uint32_t NumFunctions;
11263376a787SDiego Novillo   if (!GcovBuffer.readInt(NumFunctions))
11273376a787SDiego Novillo     return sampleprof_error::truncated;
11283376a787SDiego Novillo 
1129aae1ed8eSDiego Novillo   InlineCallStack Stack;
11303376a787SDiego Novillo   for (uint32_t I = 0; I < NumFunctions; ++I)
1131aae1ed8eSDiego Novillo     if (std::error_code EC = readOneFunctionProfile(Stack, true, 0))
11323376a787SDiego Novillo       return EC;
11333376a787SDiego Novillo 
113440ee23dbSEaswaran Raman   computeSummary();
11353376a787SDiego Novillo   return sampleprof_error::success;
11363376a787SDiego Novillo }
11373376a787SDiego Novillo 
1138aae1ed8eSDiego Novillo std::error_code SampleProfileReaderGCC::readOneFunctionProfile(
1139aae1ed8eSDiego Novillo     const InlineCallStack &InlineStack, bool Update, uint32_t Offset) {
11403376a787SDiego Novillo   uint64_t HeadCount = 0;
1141aae1ed8eSDiego Novillo   if (InlineStack.size() == 0)
11423376a787SDiego Novillo     if (!GcovBuffer.readInt64(HeadCount))
11433376a787SDiego Novillo       return sampleprof_error::truncated;
11443376a787SDiego Novillo 
11453376a787SDiego Novillo   uint32_t NameIdx;
11463376a787SDiego Novillo   if (!GcovBuffer.readInt(NameIdx))
11473376a787SDiego Novillo     return sampleprof_error::truncated;
11483376a787SDiego Novillo 
11493376a787SDiego Novillo   StringRef Name(Names[NameIdx]);
11503376a787SDiego Novillo 
11513376a787SDiego Novillo   uint32_t NumPosCounts;
11523376a787SDiego Novillo   if (!GcovBuffer.readInt(NumPosCounts))
11533376a787SDiego Novillo     return sampleprof_error::truncated;
11543376a787SDiego Novillo 
1155aae1ed8eSDiego Novillo   uint32_t NumCallsites;
1156aae1ed8eSDiego Novillo   if (!GcovBuffer.readInt(NumCallsites))
11573376a787SDiego Novillo     return sampleprof_error::truncated;
11583376a787SDiego Novillo 
1159aae1ed8eSDiego Novillo   FunctionSamples *FProfile = nullptr;
1160aae1ed8eSDiego Novillo   if (InlineStack.size() == 0) {
1161aae1ed8eSDiego Novillo     // If this is a top function that we have already processed, do not
1162aae1ed8eSDiego Novillo     // update its profile again.  This happens in the presence of
1163aae1ed8eSDiego Novillo     // function aliases.  Since these aliases share the same function
1164aae1ed8eSDiego Novillo     // body, there will be identical replicated profiles for the
1165aae1ed8eSDiego Novillo     // original function.  In this case, we simply not bother updating
1166aae1ed8eSDiego Novillo     // the profile of the original function.
1167aae1ed8eSDiego Novillo     FProfile = &Profiles[Name];
1168aae1ed8eSDiego Novillo     FProfile->addHeadSamples(HeadCount);
1169aae1ed8eSDiego Novillo     if (FProfile->getTotalSamples() > 0)
11703376a787SDiego Novillo       Update = false;
1171aae1ed8eSDiego Novillo   } else {
1172aae1ed8eSDiego Novillo     // Otherwise, we are reading an inlined instance. The top of the
1173aae1ed8eSDiego Novillo     // inline stack contains the profile of the caller. Insert this
1174aae1ed8eSDiego Novillo     // callee in the caller's CallsiteMap.
1175aae1ed8eSDiego Novillo     FunctionSamples *CallerProfile = InlineStack.front();
1176aae1ed8eSDiego Novillo     uint32_t LineOffset = Offset >> 16;
1177aae1ed8eSDiego Novillo     uint32_t Discriminator = Offset & 0xffff;
1178aae1ed8eSDiego Novillo     FProfile = &CallerProfile->functionSamplesAt(
1179adcd0268SBenjamin Kramer         LineLocation(LineOffset, Discriminator))[std::string(Name)];
11803376a787SDiego Novillo   }
118157d1dda5SDehao Chen   FProfile->setName(Name);
11823376a787SDiego Novillo 
11833376a787SDiego Novillo   for (uint32_t I = 0; I < NumPosCounts; ++I) {
11843376a787SDiego Novillo     uint32_t Offset;
11853376a787SDiego Novillo     if (!GcovBuffer.readInt(Offset))
11863376a787SDiego Novillo       return sampleprof_error::truncated;
11873376a787SDiego Novillo 
11883376a787SDiego Novillo     uint32_t NumTargets;
11893376a787SDiego Novillo     if (!GcovBuffer.readInt(NumTargets))
11903376a787SDiego Novillo       return sampleprof_error::truncated;
11913376a787SDiego Novillo 
11923376a787SDiego Novillo     uint64_t Count;
11933376a787SDiego Novillo     if (!GcovBuffer.readInt64(Count))
11943376a787SDiego Novillo       return sampleprof_error::truncated;
11953376a787SDiego Novillo 
1196aae1ed8eSDiego Novillo     // The line location is encoded in the offset as:
1197aae1ed8eSDiego Novillo     //   high 16 bits: line offset to the start of the function.
1198aae1ed8eSDiego Novillo     //   low 16 bits: discriminator.
1199aae1ed8eSDiego Novillo     uint32_t LineOffset = Offset >> 16;
1200aae1ed8eSDiego Novillo     uint32_t Discriminator = Offset & 0xffff;
12013376a787SDiego Novillo 
1202aae1ed8eSDiego Novillo     InlineCallStack NewStack;
1203aae1ed8eSDiego Novillo     NewStack.push_back(FProfile);
1204aae1ed8eSDiego Novillo     NewStack.insert(NewStack.end(), InlineStack.begin(), InlineStack.end());
1205aae1ed8eSDiego Novillo     if (Update) {
1206aae1ed8eSDiego Novillo       // Walk up the inline stack, adding the samples on this line to
1207aae1ed8eSDiego Novillo       // the total sample count of the callers in the chain.
1208aae1ed8eSDiego Novillo       for (auto CallerProfile : NewStack)
1209aae1ed8eSDiego Novillo         CallerProfile->addTotalSamples(Count);
1210aae1ed8eSDiego Novillo 
1211aae1ed8eSDiego Novillo       // Update the body samples for the current profile.
1212aae1ed8eSDiego Novillo       FProfile->addBodySamples(LineOffset, Discriminator, Count);
1213aae1ed8eSDiego Novillo     }
1214aae1ed8eSDiego Novillo 
1215aae1ed8eSDiego Novillo     // Process the list of functions called at an indirect call site.
1216aae1ed8eSDiego Novillo     // These are all the targets that a function pointer (or virtual
1217aae1ed8eSDiego Novillo     // function) resolved at runtime.
12183376a787SDiego Novillo     for (uint32_t J = 0; J < NumTargets; J++) {
12193376a787SDiego Novillo       uint32_t HistVal;
12203376a787SDiego Novillo       if (!GcovBuffer.readInt(HistVal))
12213376a787SDiego Novillo         return sampleprof_error::truncated;
12223376a787SDiego Novillo 
12233376a787SDiego Novillo       if (HistVal != HIST_TYPE_INDIR_CALL_TOPN)
12243376a787SDiego Novillo         return sampleprof_error::malformed;
12253376a787SDiego Novillo 
12263376a787SDiego Novillo       uint64_t TargetIdx;
12273376a787SDiego Novillo       if (!GcovBuffer.readInt64(TargetIdx))
12283376a787SDiego Novillo         return sampleprof_error::truncated;
12293376a787SDiego Novillo       StringRef TargetName(Names[TargetIdx]);
12303376a787SDiego Novillo 
12313376a787SDiego Novillo       uint64_t TargetCount;
12323376a787SDiego Novillo       if (!GcovBuffer.readInt64(TargetCount))
12333376a787SDiego Novillo         return sampleprof_error::truncated;
12343376a787SDiego Novillo 
1235920677a9SDehao Chen       if (Update)
1236920677a9SDehao Chen         FProfile->addCalledTargetSamples(LineOffset, Discriminator,
1237aae1ed8eSDiego Novillo                                          TargetName, TargetCount);
12383376a787SDiego Novillo     }
12393376a787SDiego Novillo   }
12403376a787SDiego Novillo 
1241aae1ed8eSDiego Novillo   // Process all the inlined callers into the current function. These
1242aae1ed8eSDiego Novillo   // are all the callsites that were inlined into this function.
1243aae1ed8eSDiego Novillo   for (uint32_t I = 0; I < NumCallsites; I++) {
12443376a787SDiego Novillo     // The offset is encoded as:
12453376a787SDiego Novillo     //   high 16 bits: line offset to the start of the function.
12463376a787SDiego Novillo     //   low 16 bits: discriminator.
12473376a787SDiego Novillo     uint32_t Offset;
12483376a787SDiego Novillo     if (!GcovBuffer.readInt(Offset))
12493376a787SDiego Novillo       return sampleprof_error::truncated;
1250aae1ed8eSDiego Novillo     InlineCallStack NewStack;
1251aae1ed8eSDiego Novillo     NewStack.push_back(FProfile);
1252aae1ed8eSDiego Novillo     NewStack.insert(NewStack.end(), InlineStack.begin(), InlineStack.end());
1253aae1ed8eSDiego Novillo     if (std::error_code EC = readOneFunctionProfile(NewStack, Update, Offset))
12543376a787SDiego Novillo       return EC;
12553376a787SDiego Novillo   }
12563376a787SDiego Novillo 
12573376a787SDiego Novillo   return sampleprof_error::success;
12583376a787SDiego Novillo }
12593376a787SDiego Novillo 
12605f8f34e4SAdrian Prantl /// Read a GCC AutoFDO profile.
12613376a787SDiego Novillo ///
12623376a787SDiego Novillo /// This format is generated by the Linux Perf conversion tool at
12633376a787SDiego Novillo /// https://github.com/google/autofdo.
12648c8ec1f6SWei Mi std::error_code SampleProfileReaderGCC::readImpl() {
12653376a787SDiego Novillo   // Read the string table.
12663376a787SDiego Novillo   if (std::error_code EC = readNameTable())
12673376a787SDiego Novillo     return EC;
12683376a787SDiego Novillo 
12693376a787SDiego Novillo   // Read the source profile.
12703376a787SDiego Novillo   if (std::error_code EC = readFunctionProfiles())
12713376a787SDiego Novillo     return EC;
12723376a787SDiego Novillo 
12733376a787SDiego Novillo   return sampleprof_error::success;
12743376a787SDiego Novillo }
12753376a787SDiego Novillo 
12763376a787SDiego Novillo bool SampleProfileReaderGCC::hasFormat(const MemoryBuffer &Buffer) {
12773376a787SDiego Novillo   StringRef Magic(reinterpret_cast<const char *>(Buffer.getBufferStart()));
12783376a787SDiego Novillo   return Magic == "adcg*704";
12793376a787SDiego Novillo }
12803376a787SDiego Novillo 
12818c8ec1f6SWei Mi void SampleProfileReaderItaniumRemapper::applyRemapping(LLVMContext &Ctx) {
1282ebad6788SWei Mi   // If the reader uses MD5 to represent string, we can't remap it because
128328436358SRichard Smith   // we don't know what the original function names were.
1284ebad6788SWei Mi   if (Reader.useMD5()) {
128528436358SRichard Smith     Ctx.diagnose(DiagnosticInfoSampleProfile(
12868c8ec1f6SWei Mi         Reader.getBuffer()->getBufferIdentifier(),
128728436358SRichard Smith         "Profile data remapping cannot be applied to profile data "
128828436358SRichard Smith         "in compact format (original mangled names are not available).",
128928436358SRichard Smith         DS_Warning));
12908c8ec1f6SWei Mi     return;
129128436358SRichard Smith   }
129228436358SRichard Smith 
12938c8ec1f6SWei Mi   assert(Remappings && "should be initialized while creating remapper");
12948c8ec1f6SWei Mi   for (auto &Sample : Reader.getProfiles())
12958c8ec1f6SWei Mi     if (auto Key = Remappings->insert(Sample.first()))
129628436358SRichard Smith       SampleMap.insert({Key, &Sample.second});
129728436358SRichard Smith 
12988c8ec1f6SWei Mi   RemappingApplied = true;
129928436358SRichard Smith }
130028436358SRichard Smith 
130128436358SRichard Smith FunctionSamples *
130228436358SRichard Smith SampleProfileReaderItaniumRemapper::getSamplesFor(StringRef Fname) {
13038c8ec1f6SWei Mi   if (auto Key = Remappings->lookup(Fname))
130428436358SRichard Smith     return SampleMap.lookup(Key);
13058c8ec1f6SWei Mi   return nullptr;
130628436358SRichard Smith }
130728436358SRichard Smith 
13085f8f34e4SAdrian Prantl /// Prepare a memory buffer for the contents of \p Filename.
1309de1ab26fSDiego Novillo ///
1310c572e92cSDiego Novillo /// \returns an error code indicating the status of the buffer.
1311fcd55607SDiego Novillo static ErrorOr<std::unique_ptr<MemoryBuffer>>
13120da23a27SBenjamin Kramer setupMemoryBuffer(const Twine &Filename) {
1313c572e92cSDiego Novillo   auto BufferOrErr = MemoryBuffer::getFileOrSTDIN(Filename);
1314c572e92cSDiego Novillo   if (std::error_code EC = BufferOrErr.getError())
1315c572e92cSDiego Novillo     return EC;
1316fcd55607SDiego Novillo   auto Buffer = std::move(BufferOrErr.get());
1317c572e92cSDiego Novillo 
1318c572e92cSDiego Novillo   // Sanity check the file.
1319260fe3ecSZachary Turner   if (uint64_t(Buffer->getBufferSize()) > std::numeric_limits<uint32_t>::max())
1320c572e92cSDiego Novillo     return sampleprof_error::too_large;
1321c572e92cSDiego Novillo 
1322c55cf4afSBill Wendling   return std::move(Buffer);
1323c572e92cSDiego Novillo }
1324c572e92cSDiego Novillo 
13255f8f34e4SAdrian Prantl /// Create a sample profile reader based on the format of the input file.
1326c572e92cSDiego Novillo ///
1327c572e92cSDiego Novillo /// \param Filename The file to open.
1328c572e92cSDiego Novillo ///
1329c572e92cSDiego Novillo /// \param C The LLVM context to use to emit diagnostics.
1330c572e92cSDiego Novillo ///
13318c8ec1f6SWei Mi /// \param RemapFilename The file used for profile remapping.
13328c8ec1f6SWei Mi ///
1333c572e92cSDiego Novillo /// \returns an error code indicating the status of the created reader.
1334fcd55607SDiego Novillo ErrorOr<std::unique_ptr<SampleProfileReader>>
13358c8ec1f6SWei Mi SampleProfileReader::create(const std::string Filename, LLVMContext &C,
13368c8ec1f6SWei Mi                             const std::string RemapFilename) {
1337fcd55607SDiego Novillo   auto BufferOrError = setupMemoryBuffer(Filename);
1338fcd55607SDiego Novillo   if (std::error_code EC = BufferOrError.getError())
1339c572e92cSDiego Novillo     return EC;
13408c8ec1f6SWei Mi   return create(BufferOrError.get(), C, RemapFilename);
134151abea74SNathan Slingerland }
1342c572e92cSDiego Novillo 
134328436358SRichard Smith /// Create a sample profile remapper from the given input, to remap the
134428436358SRichard Smith /// function names in the given profile data.
134528436358SRichard Smith ///
134628436358SRichard Smith /// \param Filename The file to open.
134728436358SRichard Smith ///
13488c8ec1f6SWei Mi /// \param Reader The profile reader the remapper is going to be applied to.
13498c8ec1f6SWei Mi ///
135028436358SRichard Smith /// \param C The LLVM context to use to emit diagnostics.
135128436358SRichard Smith ///
135228436358SRichard Smith /// \returns an error code indicating the status of the created reader.
13538c8ec1f6SWei Mi ErrorOr<std::unique_ptr<SampleProfileReaderItaniumRemapper>>
13548c8ec1f6SWei Mi SampleProfileReaderItaniumRemapper::create(const std::string Filename,
13558c8ec1f6SWei Mi                                            SampleProfileReader &Reader,
13568c8ec1f6SWei Mi                                            LLVMContext &C) {
135728436358SRichard Smith   auto BufferOrError = setupMemoryBuffer(Filename);
135828436358SRichard Smith   if (std::error_code EC = BufferOrError.getError())
135928436358SRichard Smith     return EC;
13608c8ec1f6SWei Mi   return create(BufferOrError.get(), Reader, C);
13618c8ec1f6SWei Mi }
13628c8ec1f6SWei Mi 
13638c8ec1f6SWei Mi /// Create a sample profile remapper from the given input, to remap the
13648c8ec1f6SWei Mi /// function names in the given profile data.
13658c8ec1f6SWei Mi ///
13668c8ec1f6SWei Mi /// \param B The memory buffer to create the reader from (assumes ownership).
13678c8ec1f6SWei Mi ///
13688c8ec1f6SWei Mi /// \param C The LLVM context to use to emit diagnostics.
13698c8ec1f6SWei Mi ///
13708c8ec1f6SWei Mi /// \param Reader The profile reader the remapper is going to be applied to.
13718c8ec1f6SWei Mi ///
13728c8ec1f6SWei Mi /// \returns an error code indicating the status of the created reader.
13738c8ec1f6SWei Mi ErrorOr<std::unique_ptr<SampleProfileReaderItaniumRemapper>>
13748c8ec1f6SWei Mi SampleProfileReaderItaniumRemapper::create(std::unique_ptr<MemoryBuffer> &B,
13758c8ec1f6SWei Mi                                            SampleProfileReader &Reader,
13768c8ec1f6SWei Mi                                            LLVMContext &C) {
13778c8ec1f6SWei Mi   auto Remappings = std::make_unique<SymbolRemappingReader>();
13788c8ec1f6SWei Mi   if (Error E = Remappings->read(*B.get())) {
13798c8ec1f6SWei Mi     handleAllErrors(
13808c8ec1f6SWei Mi         std::move(E), [&](const SymbolRemappingParseError &ParseError) {
13818c8ec1f6SWei Mi           C.diagnose(DiagnosticInfoSampleProfile(B->getBufferIdentifier(),
13828c8ec1f6SWei Mi                                                  ParseError.getLineNum(),
13838c8ec1f6SWei Mi                                                  ParseError.getMessage()));
13848c8ec1f6SWei Mi         });
13858c8ec1f6SWei Mi     return sampleprof_error::malformed;
13868c8ec1f6SWei Mi   }
13878c8ec1f6SWei Mi 
13880eaee545SJonas Devlieghere   return std::make_unique<SampleProfileReaderItaniumRemapper>(
13898c8ec1f6SWei Mi       std::move(B), std::move(Remappings), Reader);
139028436358SRichard Smith }
139128436358SRichard Smith 
13925f8f34e4SAdrian Prantl /// Create a sample profile reader based on the format of the input data.
139351abea74SNathan Slingerland ///
139451abea74SNathan Slingerland /// \param B The memory buffer to create the reader from (assumes ownership).
139551abea74SNathan Slingerland ///
139651abea74SNathan Slingerland /// \param C The LLVM context to use to emit diagnostics.
139751abea74SNathan Slingerland ///
13988c8ec1f6SWei Mi /// \param RemapFilename The file used for profile remapping.
13998c8ec1f6SWei Mi ///
140051abea74SNathan Slingerland /// \returns an error code indicating the status of the created reader.
140151abea74SNathan Slingerland ErrorOr<std::unique_ptr<SampleProfileReader>>
14028c8ec1f6SWei Mi SampleProfileReader::create(std::unique_ptr<MemoryBuffer> &B, LLVMContext &C,
14038c8ec1f6SWei Mi                             const std::string RemapFilename) {
1404fcd55607SDiego Novillo   std::unique_ptr<SampleProfileReader> Reader;
1405a0c0857eSWei Mi   if (SampleProfileReaderRawBinary::hasFormat(*B))
1406a0c0857eSWei Mi     Reader.reset(new SampleProfileReaderRawBinary(std::move(B), C));
1407be907324SWei Mi   else if (SampleProfileReaderExtBinary::hasFormat(*B))
1408be907324SWei Mi     Reader.reset(new SampleProfileReaderExtBinary(std::move(B), C));
1409a0c0857eSWei Mi   else if (SampleProfileReaderCompactBinary::hasFormat(*B))
1410a0c0857eSWei Mi     Reader.reset(new SampleProfileReaderCompactBinary(std::move(B), C));
141151abea74SNathan Slingerland   else if (SampleProfileReaderGCC::hasFormat(*B))
141251abea74SNathan Slingerland     Reader.reset(new SampleProfileReaderGCC(std::move(B), C));
141351abea74SNathan Slingerland   else if (SampleProfileReaderText::hasFormat(*B))
141451abea74SNathan Slingerland     Reader.reset(new SampleProfileReaderText(std::move(B), C));
14154f823667SNathan Slingerland   else
14164f823667SNathan Slingerland     return sampleprof_error::unrecognized_format;
1417c572e92cSDiego Novillo 
14188c8ec1f6SWei Mi   if (!RemapFilename.empty()) {
14198c8ec1f6SWei Mi     auto ReaderOrErr =
14208c8ec1f6SWei Mi         SampleProfileReaderItaniumRemapper::create(RemapFilename, *Reader, C);
14218c8ec1f6SWei Mi     if (std::error_code EC = ReaderOrErr.getError()) {
14228c8ec1f6SWei Mi       std::string Msg = "Could not create remapper: " + EC.message();
14238c8ec1f6SWei Mi       C.diagnose(DiagnosticInfoSampleProfile(RemapFilename, Msg));
14248c8ec1f6SWei Mi       return EC;
14258c8ec1f6SWei Mi     }
14268c8ec1f6SWei Mi     Reader->Remapper = std::move(ReaderOrErr.get());
14278c8ec1f6SWei Mi   }
14288c8ec1f6SWei Mi 
142994d44c97SWei Mi   FunctionSamples::Format = Reader->getFormat();
1430be907324SWei Mi   if (std::error_code EC = Reader->readHeader()) {
1431fcd55607SDiego Novillo     return EC;
1432be907324SWei Mi   }
1433fcd55607SDiego Novillo 
1434c55cf4afSBill Wendling   return std::move(Reader);
1435de1ab26fSDiego Novillo }
143640ee23dbSEaswaran Raman 
143740ee23dbSEaswaran Raman // For text and GCC file formats, we compute the summary after reading the
143840ee23dbSEaswaran Raman // profile. Binary format has the profile summary in its header.
143940ee23dbSEaswaran Raman void SampleProfileReader::computeSummary() {
1440e5a17e3fSEaswaran Raman   SampleProfileSummaryBuilder Builder(ProfileSummaryBuilder::DefaultCutoffs);
144140ee23dbSEaswaran Raman   for (const auto &I : Profiles) {
144240ee23dbSEaswaran Raman     const FunctionSamples &Profile = I.second;
1443e5a17e3fSEaswaran Raman     Builder.addRecord(Profile);
144440ee23dbSEaswaran Raman   }
144538de59e4SBenjamin Kramer   Summary = Builder.getSummary();
144640ee23dbSEaswaran Raman }
1447