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"
29de1ab26fSDiego Novillo #include "llvm/Support/ErrorOr.h"
30c572e92cSDiego Novillo #include "llvm/Support/LEB128.h"
31de1ab26fSDiego Novillo #include "llvm/Support/LineIterator.h"
326a14325dSWei Mi #include "llvm/Support/MD5.h"
33c572e92cSDiego Novillo #include "llvm/Support/MemoryBuffer.h"
34e78d131aSEugene Zelenko #include "llvm/Support/raw_ostream.h"
35e78d131aSEugene Zelenko #include <algorithm>
36e78d131aSEugene Zelenko #include <cstddef>
37e78d131aSEugene Zelenko #include <cstdint>
38e78d131aSEugene Zelenko #include <limits>
39e78d131aSEugene Zelenko #include <memory>
40e78d131aSEugene Zelenko #include <system_error>
41e78d131aSEugene Zelenko #include <vector>
42de1ab26fSDiego Novillo 
43de1ab26fSDiego Novillo using namespace llvm;
44e78d131aSEugene Zelenko using namespace sampleprof;
45de1ab26fSDiego Novillo 
465f8f34e4SAdrian Prantl /// Dump the function profile for \p FName.
47de1ab26fSDiego Novillo ///
48de1ab26fSDiego Novillo /// \param FName Name of the function to print.
49d5336ae2SDiego Novillo /// \param OS Stream to emit the output to.
50d5336ae2SDiego Novillo void SampleProfileReader::dumpFunctionProfile(StringRef FName,
51d5336ae2SDiego Novillo                                               raw_ostream &OS) {
528e415a82SDiego Novillo   OS << "Function: " << FName << ": " << Profiles[FName];
53de1ab26fSDiego Novillo }
54de1ab26fSDiego Novillo 
555f8f34e4SAdrian Prantl /// Dump all the function profiles found on stream \p OS.
56d5336ae2SDiego Novillo void SampleProfileReader::dump(raw_ostream &OS) {
57d5336ae2SDiego Novillo   for (const auto &I : Profiles)
58d5336ae2SDiego Novillo     dumpFunctionProfile(I.getKey(), OS);
59de1ab26fSDiego Novillo }
60de1ab26fSDiego Novillo 
615f8f34e4SAdrian Prantl /// Parse \p Input as function head.
626722688eSDehao Chen ///
636722688eSDehao Chen /// Parse one line of \p Input, and update function name in \p FName,
646722688eSDehao Chen /// function's total sample count in \p NumSamples, function's entry
656722688eSDehao Chen /// count in \p NumHeadSamples.
666722688eSDehao Chen ///
676722688eSDehao Chen /// \returns true if parsing is successful.
686722688eSDehao Chen static bool ParseHead(const StringRef &Input, StringRef &FName,
6938be3330SDiego Novillo                       uint64_t &NumSamples, uint64_t &NumHeadSamples) {
706722688eSDehao Chen   if (Input[0] == ' ')
716722688eSDehao Chen     return false;
726722688eSDehao Chen   size_t n2 = Input.rfind(':');
736722688eSDehao Chen   size_t n1 = Input.rfind(':', n2 - 1);
746722688eSDehao Chen   FName = Input.substr(0, n1);
756722688eSDehao Chen   if (Input.substr(n1 + 1, n2 - n1 - 1).getAsInteger(10, NumSamples))
766722688eSDehao Chen     return false;
776722688eSDehao Chen   if (Input.substr(n2 + 1).getAsInteger(10, NumHeadSamples))
786722688eSDehao Chen     return false;
796722688eSDehao Chen   return true;
806722688eSDehao Chen }
816722688eSDehao Chen 
825f8f34e4SAdrian Prantl /// Returns true if line offset \p L is legal (only has 16 bits).
8357d1dda5SDehao Chen static bool isOffsetLegal(unsigned L) { return (L & 0xffff) == L; }
8410042412SDehao Chen 
855f8f34e4SAdrian Prantl /// Parse \p Input as line sample.
866722688eSDehao Chen ///
876722688eSDehao Chen /// \param Input input line.
886722688eSDehao Chen /// \param IsCallsite true if the line represents an inlined callsite.
896722688eSDehao Chen /// \param Depth the depth of the inline stack.
906722688eSDehao Chen /// \param NumSamples total samples of the line/inlined callsite.
916722688eSDehao Chen /// \param LineOffset line offset to the start of the function.
926722688eSDehao Chen /// \param Discriminator discriminator of the line.
936722688eSDehao Chen /// \param TargetCountMap map from indirect call target to count.
946722688eSDehao Chen ///
956722688eSDehao Chen /// returns true if parsing is successful.
9638be3330SDiego Novillo static bool ParseLine(const StringRef &Input, bool &IsCallsite, uint32_t &Depth,
9738be3330SDiego Novillo                       uint64_t &NumSamples, uint32_t &LineOffset,
9838be3330SDiego Novillo                       uint32_t &Discriminator, StringRef &CalleeName,
9938be3330SDiego Novillo                       DenseMap<StringRef, uint64_t> &TargetCountMap) {
1006722688eSDehao Chen   for (Depth = 0; Input[Depth] == ' '; Depth++)
1016722688eSDehao Chen     ;
1026722688eSDehao Chen   if (Depth == 0)
1036722688eSDehao Chen     return false;
1046722688eSDehao Chen 
1056722688eSDehao Chen   size_t n1 = Input.find(':');
1066722688eSDehao Chen   StringRef Loc = Input.substr(Depth, n1 - Depth);
1076722688eSDehao Chen   size_t n2 = Loc.find('.');
1086722688eSDehao Chen   if (n2 == StringRef::npos) {
10910042412SDehao Chen     if (Loc.getAsInteger(10, LineOffset) || !isOffsetLegal(LineOffset))
1106722688eSDehao Chen       return false;
1116722688eSDehao Chen     Discriminator = 0;
1126722688eSDehao Chen   } else {
1136722688eSDehao Chen     if (Loc.substr(0, n2).getAsInteger(10, LineOffset))
1146722688eSDehao Chen       return false;
1156722688eSDehao Chen     if (Loc.substr(n2 + 1).getAsInteger(10, Discriminator))
1166722688eSDehao Chen       return false;
1176722688eSDehao Chen   }
1186722688eSDehao Chen 
1196722688eSDehao Chen   StringRef Rest = Input.substr(n1 + 2);
1206722688eSDehao Chen   if (Rest[0] >= '0' && Rest[0] <= '9') {
1216722688eSDehao Chen     IsCallsite = false;
1226722688eSDehao Chen     size_t n3 = Rest.find(' ');
1236722688eSDehao Chen     if (n3 == StringRef::npos) {
1246722688eSDehao Chen       if (Rest.getAsInteger(10, NumSamples))
1256722688eSDehao Chen         return false;
1266722688eSDehao Chen     } else {
1276722688eSDehao Chen       if (Rest.substr(0, n3).getAsInteger(10, NumSamples))
1286722688eSDehao Chen         return false;
1296722688eSDehao Chen     }
130984ab0f1SWei Mi     // Find call targets and their sample counts.
131984ab0f1SWei Mi     // Note: In some cases, there are symbols in the profile which are not
132984ab0f1SWei Mi     // mangled. To accommodate such cases, use colon + integer pairs as the
133984ab0f1SWei Mi     // anchor points.
134984ab0f1SWei Mi     // An example:
135984ab0f1SWei Mi     // _M_construct<char *>:1000 string_view<std::allocator<char> >:437
136984ab0f1SWei Mi     // ":1000" and ":437" are used as anchor points so the string above will
137984ab0f1SWei Mi     // be interpreted as
138984ab0f1SWei Mi     // target: _M_construct<char *>
139984ab0f1SWei Mi     // count: 1000
140984ab0f1SWei Mi     // target: string_view<std::allocator<char> >
141984ab0f1SWei Mi     // count: 437
1426722688eSDehao Chen     while (n3 != StringRef::npos) {
1436722688eSDehao Chen       n3 += Rest.substr(n3).find_first_not_of(' ');
1446722688eSDehao Chen       Rest = Rest.substr(n3);
145984ab0f1SWei Mi       n3 = Rest.find_first_of(':');
146984ab0f1SWei Mi       if (n3 == StringRef::npos || n3 == 0)
1476722688eSDehao Chen         return false;
148984ab0f1SWei Mi 
149984ab0f1SWei Mi       StringRef Target;
150984ab0f1SWei Mi       uint64_t count, n4;
151984ab0f1SWei Mi       while (true) {
152984ab0f1SWei Mi         // Get the segment after the current colon.
153984ab0f1SWei Mi         StringRef AfterColon = Rest.substr(n3 + 1);
154984ab0f1SWei Mi         // Get the target symbol before the current colon.
155984ab0f1SWei Mi         Target = Rest.substr(0, n3);
156984ab0f1SWei Mi         // Check if the word after the current colon is an integer.
157984ab0f1SWei Mi         n4 = AfterColon.find_first_of(' ');
158984ab0f1SWei Mi         n4 = (n4 != StringRef::npos) ? n3 + n4 + 1 : Rest.size();
159984ab0f1SWei Mi         StringRef WordAfterColon = Rest.substr(n3 + 1, n4 - n3 - 1);
160984ab0f1SWei Mi         if (!WordAfterColon.getAsInteger(10, count))
161984ab0f1SWei Mi           break;
162984ab0f1SWei Mi 
163984ab0f1SWei Mi         // Try to find the next colon.
164984ab0f1SWei Mi         uint64_t n5 = AfterColon.find_first_of(':');
165984ab0f1SWei Mi         if (n5 == StringRef::npos)
166984ab0f1SWei Mi           return false;
167984ab0f1SWei Mi         n3 += n5 + 1;
168984ab0f1SWei Mi       }
169984ab0f1SWei Mi 
170984ab0f1SWei Mi       // An anchor point is found. Save the {target, count} pair
171984ab0f1SWei Mi       TargetCountMap[Target] = count;
172984ab0f1SWei Mi       if (n4 == Rest.size())
173984ab0f1SWei Mi         break;
174984ab0f1SWei Mi       // Change n3 to the next blank space after colon + integer pair.
175984ab0f1SWei Mi       n3 = n4;
1766722688eSDehao Chen     }
1776722688eSDehao Chen   } else {
1786722688eSDehao Chen     IsCallsite = true;
17938be3330SDiego Novillo     size_t n3 = Rest.find_last_of(':');
1806722688eSDehao Chen     CalleeName = Rest.substr(0, n3);
1816722688eSDehao Chen     if (Rest.substr(n3 + 1).getAsInteger(10, NumSamples))
1826722688eSDehao Chen       return false;
1836722688eSDehao Chen   }
1846722688eSDehao Chen   return true;
1856722688eSDehao Chen }
1866722688eSDehao Chen 
1875f8f34e4SAdrian Prantl /// Load samples from a text file.
188de1ab26fSDiego Novillo ///
189de1ab26fSDiego Novillo /// See the documentation at the top of the file for an explanation of
190de1ab26fSDiego Novillo /// the expected format.
191de1ab26fSDiego Novillo ///
192de1ab26fSDiego Novillo /// \returns true if the file was loaded successfully, false otherwise.
193c572e92cSDiego Novillo std::error_code SampleProfileReaderText::read() {
194c572e92cSDiego Novillo   line_iterator LineIt(*Buffer, /*SkipBlanks=*/true, '#');
19548dd080cSNathan Slingerland   sampleprof_error Result = sampleprof_error::success;
196de1ab26fSDiego Novillo 
197aae1ed8eSDiego Novillo   InlineCallStack InlineStack;
1986722688eSDehao Chen 
1996722688eSDehao Chen   for (; !LineIt.is_at_eof(); ++LineIt) {
2006722688eSDehao Chen     if ((*LineIt)[(*LineIt).find_first_not_of(' ')] == '#')
2016722688eSDehao Chen       continue;
202de1ab26fSDiego Novillo     // Read the header of each function.
203de1ab26fSDiego Novillo     //
204de1ab26fSDiego Novillo     // Note that for function identifiers we are actually expecting
205de1ab26fSDiego Novillo     // mangled names, but we may not always get them. This happens when
206de1ab26fSDiego Novillo     // the compiler decides not to emit the function (e.g., it was inlined
207de1ab26fSDiego Novillo     // and removed). In this case, the binary will not have the linkage
208de1ab26fSDiego Novillo     // name for the function, so the profiler will emit the function's
209de1ab26fSDiego Novillo     // unmangled name, which may contain characters like ':' and '>' in its
210de1ab26fSDiego Novillo     // name (member functions, templates, etc).
211de1ab26fSDiego Novillo     //
212de1ab26fSDiego Novillo     // The only requirement we place on the identifier, then, is that it
213de1ab26fSDiego Novillo     // should not begin with a number.
2146722688eSDehao Chen     if ((*LineIt)[0] != ' ') {
21538be3330SDiego Novillo       uint64_t NumSamples, NumHeadSamples;
2166722688eSDehao Chen       StringRef FName;
2176722688eSDehao Chen       if (!ParseHead(*LineIt, FName, NumSamples, NumHeadSamples)) {
2183376a787SDiego Novillo         reportError(LineIt.line_number(),
219de1ab26fSDiego Novillo                     "Expected 'mangled_name:NUM:NUM', found " + *LineIt);
220c572e92cSDiego Novillo         return sampleprof_error::malformed;
221de1ab26fSDiego Novillo       }
222de1ab26fSDiego Novillo       Profiles[FName] = FunctionSamples();
223de1ab26fSDiego Novillo       FunctionSamples &FProfile = Profiles[FName];
22457d1dda5SDehao Chen       FProfile.setName(FName);
22548dd080cSNathan Slingerland       MergeResult(Result, FProfile.addTotalSamples(NumSamples));
22648dd080cSNathan Slingerland       MergeResult(Result, FProfile.addHeadSamples(NumHeadSamples));
2276722688eSDehao Chen       InlineStack.clear();
2286722688eSDehao Chen       InlineStack.push_back(&FProfile);
2296722688eSDehao Chen     } else {
23038be3330SDiego Novillo       uint64_t NumSamples;
2316722688eSDehao Chen       StringRef FName;
23238be3330SDiego Novillo       DenseMap<StringRef, uint64_t> TargetCountMap;
2336722688eSDehao Chen       bool IsCallsite;
23438be3330SDiego Novillo       uint32_t Depth, LineOffset, Discriminator;
2356722688eSDehao Chen       if (!ParseLine(*LineIt, IsCallsite, Depth, NumSamples, LineOffset,
2366722688eSDehao Chen                      Discriminator, FName, TargetCountMap)) {
2373376a787SDiego Novillo         reportError(LineIt.line_number(),
2383376a787SDiego Novillo                     "Expected 'NUM[.NUM]: NUM[ mangled_name:NUM]*', found " +
2393376a787SDiego Novillo                         *LineIt);
240c572e92cSDiego Novillo         return sampleprof_error::malformed;
241de1ab26fSDiego Novillo       }
2426722688eSDehao Chen       if (IsCallsite) {
2436722688eSDehao Chen         while (InlineStack.size() > Depth) {
2446722688eSDehao Chen           InlineStack.pop_back();
245c572e92cSDiego Novillo         }
2466722688eSDehao Chen         FunctionSamples &FSamples = InlineStack.back()->functionSamplesAt(
2472c7ca9b5SDehao Chen             LineLocation(LineOffset, Discriminator))[FName];
24857d1dda5SDehao Chen         FSamples.setName(FName);
24948dd080cSNathan Slingerland         MergeResult(Result, FSamples.addTotalSamples(NumSamples));
2506722688eSDehao Chen         InlineStack.push_back(&FSamples);
2516722688eSDehao Chen       } else {
2526722688eSDehao Chen         while (InlineStack.size() > Depth) {
2536722688eSDehao Chen           InlineStack.pop_back();
2546722688eSDehao Chen         }
2556722688eSDehao Chen         FunctionSamples &FProfile = *InlineStack.back();
2566722688eSDehao Chen         for (const auto &name_count : TargetCountMap) {
25748dd080cSNathan Slingerland           MergeResult(Result, FProfile.addCalledTargetSamples(
25848dd080cSNathan Slingerland                                   LineOffset, Discriminator, name_count.first,
25948dd080cSNathan Slingerland                                   name_count.second));
260c572e92cSDiego Novillo         }
26148dd080cSNathan Slingerland         MergeResult(Result, FProfile.addBodySamples(LineOffset, Discriminator,
26248dd080cSNathan Slingerland                                                     NumSamples));
2636722688eSDehao Chen       }
264de1ab26fSDiego Novillo     }
265de1ab26fSDiego Novillo   }
26640ee23dbSEaswaran Raman   if (Result == sampleprof_error::success)
26740ee23dbSEaswaran Raman     computeSummary();
268de1ab26fSDiego Novillo 
26948dd080cSNathan Slingerland   return Result;
270de1ab26fSDiego Novillo }
271de1ab26fSDiego Novillo 
2724f823667SNathan Slingerland bool SampleProfileReaderText::hasFormat(const MemoryBuffer &Buffer) {
2734f823667SNathan Slingerland   bool result = false;
2744f823667SNathan Slingerland 
2754f823667SNathan Slingerland   // Check that the first non-comment line is a valid function header.
2764f823667SNathan Slingerland   line_iterator LineIt(Buffer, /*SkipBlanks=*/true, '#');
2774f823667SNathan Slingerland   if (!LineIt.is_at_eof()) {
2784f823667SNathan Slingerland     if ((*LineIt)[0] != ' ') {
2794f823667SNathan Slingerland       uint64_t NumSamples, NumHeadSamples;
2804f823667SNathan Slingerland       StringRef FName;
2814f823667SNathan Slingerland       result = ParseHead(*LineIt, FName, NumSamples, NumHeadSamples);
2824f823667SNathan Slingerland     }
2834f823667SNathan Slingerland   }
2844f823667SNathan Slingerland 
2854f823667SNathan Slingerland   return result;
2864f823667SNathan Slingerland }
2874f823667SNathan Slingerland 
288d5336ae2SDiego Novillo template <typename T> ErrorOr<T> SampleProfileReaderBinary::readNumber() {
289c572e92cSDiego Novillo   unsigned NumBytesRead = 0;
290c572e92cSDiego Novillo   std::error_code EC;
291c572e92cSDiego Novillo   uint64_t Val = decodeULEB128(Data, &NumBytesRead);
292c572e92cSDiego Novillo 
293c572e92cSDiego Novillo   if (Val > std::numeric_limits<T>::max())
294c572e92cSDiego Novillo     EC = sampleprof_error::malformed;
295c572e92cSDiego Novillo   else if (Data + NumBytesRead > End)
296c572e92cSDiego Novillo     EC = sampleprof_error::truncated;
297c572e92cSDiego Novillo   else
298c572e92cSDiego Novillo     EC = sampleprof_error::success;
299c572e92cSDiego Novillo 
300c572e92cSDiego Novillo   if (EC) {
3013376a787SDiego Novillo     reportError(0, EC.message());
302c572e92cSDiego Novillo     return EC;
303c572e92cSDiego Novillo   }
304c572e92cSDiego Novillo 
305c572e92cSDiego Novillo   Data += NumBytesRead;
306c572e92cSDiego Novillo   return static_cast<T>(Val);
307c572e92cSDiego Novillo }
308c572e92cSDiego Novillo 
309c572e92cSDiego Novillo ErrorOr<StringRef> SampleProfileReaderBinary::readString() {
310c572e92cSDiego Novillo   std::error_code EC;
311c572e92cSDiego Novillo   StringRef Str(reinterpret_cast<const char *>(Data));
312c572e92cSDiego Novillo   if (Data + Str.size() + 1 > End) {
313c572e92cSDiego Novillo     EC = sampleprof_error::truncated;
3143376a787SDiego Novillo     reportError(0, EC.message());
315c572e92cSDiego Novillo     return EC;
316c572e92cSDiego Novillo   }
317c572e92cSDiego Novillo 
318c572e92cSDiego Novillo   Data += Str.size() + 1;
319c572e92cSDiego Novillo   return Str;
320c572e92cSDiego Novillo }
321c572e92cSDiego Novillo 
322a0c0857eSWei Mi template <typename T>
3236a14325dSWei Mi ErrorOr<T> SampleProfileReaderBinary::readUnencodedNumber() {
3246a14325dSWei Mi   std::error_code EC;
3256a14325dSWei Mi 
3266a14325dSWei Mi   if (Data + sizeof(T) > End) {
3276a14325dSWei Mi     EC = sampleprof_error::truncated;
3286a14325dSWei Mi     reportError(0, EC.message());
3296a14325dSWei Mi     return EC;
3306a14325dSWei Mi   }
3316a14325dSWei Mi 
3326a14325dSWei Mi   using namespace support;
3336a14325dSWei Mi   T Val = endian::readNext<T, little, unaligned>(Data);
3346a14325dSWei Mi   return Val;
3356a14325dSWei Mi }
3366a14325dSWei Mi 
3376a14325dSWei Mi template <typename T>
338a0c0857eSWei Mi inline ErrorOr<uint32_t> SampleProfileReaderBinary::readStringIndex(T &Table) {
339760c5a8fSDiego Novillo   std::error_code EC;
34038be3330SDiego Novillo   auto Idx = readNumber<uint32_t>();
341760c5a8fSDiego Novillo   if (std::error_code EC = Idx.getError())
342760c5a8fSDiego Novillo     return EC;
343a0c0857eSWei Mi   if (*Idx >= Table.size())
344760c5a8fSDiego Novillo     return sampleprof_error::truncated_name_table;
345a0c0857eSWei Mi   return *Idx;
346a0c0857eSWei Mi }
347a0c0857eSWei Mi 
348be907324SWei Mi ErrorOr<StringRef> SampleProfileReaderBinary::readStringFromTable() {
349a0c0857eSWei Mi   auto Idx = readStringIndex(NameTable);
350a0c0857eSWei Mi   if (std::error_code EC = Idx.getError())
351a0c0857eSWei Mi     return EC;
352a0c0857eSWei Mi 
353760c5a8fSDiego Novillo   return NameTable[*Idx];
354760c5a8fSDiego Novillo }
355760c5a8fSDiego Novillo 
356a0c0857eSWei Mi ErrorOr<StringRef> SampleProfileReaderCompactBinary::readStringFromTable() {
357a0c0857eSWei Mi   auto Idx = readStringIndex(NameTable);
358a0c0857eSWei Mi   if (std::error_code EC = Idx.getError())
359a0c0857eSWei Mi     return EC;
360a0c0857eSWei Mi 
361a0c0857eSWei Mi   return StringRef(NameTable[*Idx]);
362a0c0857eSWei Mi }
363a0c0857eSWei Mi 
364a7f1e8efSDiego Novillo std::error_code
365a7f1e8efSDiego Novillo SampleProfileReaderBinary::readProfile(FunctionSamples &FProfile) {
366b93483dbSDiego Novillo   auto NumSamples = readNumber<uint64_t>();
367b93483dbSDiego Novillo   if (std::error_code EC = NumSamples.getError())
368c572e92cSDiego Novillo     return EC;
369b93483dbSDiego Novillo   FProfile.addTotalSamples(*NumSamples);
370c572e92cSDiego Novillo 
371c572e92cSDiego Novillo   // Read the samples in the body.
37238be3330SDiego Novillo   auto NumRecords = readNumber<uint32_t>();
373c572e92cSDiego Novillo   if (std::error_code EC = NumRecords.getError())
374c572e92cSDiego Novillo     return EC;
375a7f1e8efSDiego Novillo 
37638be3330SDiego Novillo   for (uint32_t I = 0; I < *NumRecords; ++I) {
377c572e92cSDiego Novillo     auto LineOffset = readNumber<uint64_t>();
378c572e92cSDiego Novillo     if (std::error_code EC = LineOffset.getError())
379c572e92cSDiego Novillo       return EC;
380c572e92cSDiego Novillo 
38110042412SDehao Chen     if (!isOffsetLegal(*LineOffset)) {
38210042412SDehao Chen       return std::error_code();
38310042412SDehao Chen     }
38410042412SDehao Chen 
385c572e92cSDiego Novillo     auto Discriminator = readNumber<uint64_t>();
386c572e92cSDiego Novillo     if (std::error_code EC = Discriminator.getError())
387c572e92cSDiego Novillo       return EC;
388c572e92cSDiego Novillo 
389c572e92cSDiego Novillo     auto NumSamples = readNumber<uint64_t>();
390c572e92cSDiego Novillo     if (std::error_code EC = NumSamples.getError())
391c572e92cSDiego Novillo       return EC;
392c572e92cSDiego Novillo 
39338be3330SDiego Novillo     auto NumCalls = readNumber<uint32_t>();
394c572e92cSDiego Novillo     if (std::error_code EC = NumCalls.getError())
395c572e92cSDiego Novillo       return EC;
396c572e92cSDiego Novillo 
39738be3330SDiego Novillo     for (uint32_t J = 0; J < *NumCalls; ++J) {
398760c5a8fSDiego Novillo       auto CalledFunction(readStringFromTable());
399c572e92cSDiego Novillo       if (std::error_code EC = CalledFunction.getError())
400c572e92cSDiego Novillo         return EC;
401c572e92cSDiego Novillo 
402c572e92cSDiego Novillo       auto CalledFunctionSamples = readNumber<uint64_t>();
403c572e92cSDiego Novillo       if (std::error_code EC = CalledFunctionSamples.getError())
404c572e92cSDiego Novillo         return EC;
405c572e92cSDiego Novillo 
406c572e92cSDiego Novillo       FProfile.addCalledTargetSamples(*LineOffset, *Discriminator,
407a7f1e8efSDiego Novillo                                       *CalledFunction, *CalledFunctionSamples);
408c572e92cSDiego Novillo     }
409c572e92cSDiego Novillo 
410c572e92cSDiego Novillo     FProfile.addBodySamples(*LineOffset, *Discriminator, *NumSamples);
411c572e92cSDiego Novillo   }
412a7f1e8efSDiego Novillo 
413a7f1e8efSDiego Novillo   // Read all the samples for inlined function calls.
41438be3330SDiego Novillo   auto NumCallsites = readNumber<uint32_t>();
415a7f1e8efSDiego Novillo   if (std::error_code EC = NumCallsites.getError())
416a7f1e8efSDiego Novillo     return EC;
417a7f1e8efSDiego Novillo 
41838be3330SDiego Novillo   for (uint32_t J = 0; J < *NumCallsites; ++J) {
419a7f1e8efSDiego Novillo     auto LineOffset = readNumber<uint64_t>();
420a7f1e8efSDiego Novillo     if (std::error_code EC = LineOffset.getError())
421a7f1e8efSDiego Novillo       return EC;
422a7f1e8efSDiego Novillo 
423a7f1e8efSDiego Novillo     auto Discriminator = readNumber<uint64_t>();
424a7f1e8efSDiego Novillo     if (std::error_code EC = Discriminator.getError())
425a7f1e8efSDiego Novillo       return EC;
426a7f1e8efSDiego Novillo 
427760c5a8fSDiego Novillo     auto FName(readStringFromTable());
428a7f1e8efSDiego Novillo     if (std::error_code EC = FName.getError())
429a7f1e8efSDiego Novillo       return EC;
430a7f1e8efSDiego Novillo 
4312c7ca9b5SDehao Chen     FunctionSamples &CalleeProfile = FProfile.functionSamplesAt(
4322c7ca9b5SDehao Chen         LineLocation(*LineOffset, *Discriminator))[*FName];
43357d1dda5SDehao Chen     CalleeProfile.setName(*FName);
434a7f1e8efSDiego Novillo     if (std::error_code EC = readProfile(CalleeProfile))
435a7f1e8efSDiego Novillo       return EC;
436a7f1e8efSDiego Novillo   }
437a7f1e8efSDiego Novillo 
438a7f1e8efSDiego Novillo   return sampleprof_error::success;
439a7f1e8efSDiego Novillo }
440a7f1e8efSDiego Novillo 
4416a14325dSWei Mi std::error_code SampleProfileReaderBinary::readFuncProfile() {
442b93483dbSDiego Novillo   auto NumHeadSamples = readNumber<uint64_t>();
443b93483dbSDiego Novillo   if (std::error_code EC = NumHeadSamples.getError())
444b93483dbSDiego Novillo     return EC;
445b93483dbSDiego Novillo 
446760c5a8fSDiego Novillo   auto FName(readStringFromTable());
447a7f1e8efSDiego Novillo   if (std::error_code EC = FName.getError())
448a7f1e8efSDiego Novillo     return EC;
449a7f1e8efSDiego Novillo 
450a7f1e8efSDiego Novillo   Profiles[*FName] = FunctionSamples();
451a7f1e8efSDiego Novillo   FunctionSamples &FProfile = Profiles[*FName];
45257d1dda5SDehao Chen   FProfile.setName(*FName);
453a7f1e8efSDiego Novillo 
454b93483dbSDiego Novillo   FProfile.addHeadSamples(*NumHeadSamples);
455b93483dbSDiego Novillo 
456a7f1e8efSDiego Novillo   if (std::error_code EC = readProfile(FProfile))
457a7f1e8efSDiego Novillo     return EC;
4586a14325dSWei Mi   return sampleprof_error::success;
459c572e92cSDiego Novillo }
460c572e92cSDiego Novillo 
4616a14325dSWei Mi std::error_code SampleProfileReaderBinary::read() {
4626a14325dSWei Mi   while (!at_eof()) {
4636a14325dSWei Mi     if (std::error_code EC = readFuncProfile())
4646a14325dSWei Mi       return EC;
4656a14325dSWei Mi   }
4666a14325dSWei Mi 
4676a14325dSWei Mi   return sampleprof_error::success;
4686a14325dSWei Mi }
4696a14325dSWei Mi 
470077a9c70SWei Mi std::error_code
471077a9c70SWei Mi SampleProfileReaderExtBinary::readOneSection(const uint8_t *Start,
472077a9c70SWei Mi                                              uint64_t Size, SecType Type) {
473077a9c70SWei Mi   Data = Start;
474077a9c70SWei Mi   switch (Type) {
475be907324SWei Mi   case SecProfSummary:
476be907324SWei Mi     if (std::error_code EC = readSummary())
477be907324SWei Mi       return EC;
478be907324SWei Mi     break;
479be907324SWei Mi   case SecNameTable:
480be907324SWei Mi     if (std::error_code EC = readNameTable())
481be907324SWei Mi       return EC;
482be907324SWei Mi     break;
483be907324SWei Mi   case SecLBRProfile:
484077a9c70SWei Mi     while (Data < Start + Size) {
485be907324SWei Mi       if (std::error_code EC = readFuncProfile())
486be907324SWei Mi         return EC;
487be907324SWei Mi     }
488be907324SWei Mi     break;
489798e59b8SWei Mi   case SecProfileSymbolList:
490798e59b8SWei Mi     if (std::error_code EC = readProfileSymbolList())
491798e59b8SWei Mi       return EC;
492798e59b8SWei Mi     break;
493be907324SWei Mi   default:
494077a9c70SWei Mi     break;
495be907324SWei Mi   }
496077a9c70SWei Mi   return sampleprof_error::success;
497077a9c70SWei Mi }
498077a9c70SWei Mi 
499798e59b8SWei Mi std::error_code SampleProfileReaderExtBinary::readProfileSymbolList() {
500798e59b8SWei Mi   auto UncompressSize = readNumber<uint64_t>();
501798e59b8SWei Mi   if (std::error_code EC = UncompressSize.getError())
502798e59b8SWei Mi     return EC;
503798e59b8SWei Mi 
504798e59b8SWei Mi   auto CompressSize = readNumber<uint64_t>();
505798e59b8SWei Mi   if (std::error_code EC = CompressSize.getError())
506798e59b8SWei Mi     return EC;
507798e59b8SWei Mi 
508798e59b8SWei Mi   if (!ProfSymList)
509798e59b8SWei Mi     ProfSymList = std::make_unique<ProfileSymbolList>();
510798e59b8SWei Mi 
511798e59b8SWei Mi   if (std::error_code EC =
512798e59b8SWei Mi           ProfSymList->read(*CompressSize, *UncompressSize, Data))
513798e59b8SWei Mi     return EC;
514798e59b8SWei Mi 
515798e59b8SWei Mi   // CompressSize is zero only when ProfileSymbolList is not compressed.
516798e59b8SWei Mi   if (*CompressSize == 0)
517798e59b8SWei Mi     Data = Data + *UncompressSize;
518798e59b8SWei Mi   else
519798e59b8SWei Mi     Data = Data + *CompressSize;
520798e59b8SWei Mi   return sampleprof_error::success;
521798e59b8SWei Mi }
522798e59b8SWei Mi 
523077a9c70SWei Mi std::error_code SampleProfileReaderExtBinaryBase::read() {
524077a9c70SWei Mi   const uint8_t *BufStart =
525077a9c70SWei Mi       reinterpret_cast<const uint8_t *>(Buffer->getBufferStart());
526077a9c70SWei Mi 
527077a9c70SWei Mi   for (auto &Entry : SecHdrTable) {
528077a9c70SWei Mi     // Skip empty section.
529077a9c70SWei Mi     if (!Entry.Size)
530077a9c70SWei Mi       continue;
531077a9c70SWei Mi     const uint8_t *SecStart = BufStart + Entry.Offset;
532077a9c70SWei Mi     if (std::error_code EC = readOneSection(SecStart, Entry.Size, Entry.Type))
533077a9c70SWei Mi       return EC;
534077a9c70SWei Mi     if (Data != SecStart + Entry.Size)
535be907324SWei Mi       return sampleprof_error::malformed;
536be907324SWei Mi   }
537be907324SWei Mi 
538be907324SWei Mi   return sampleprof_error::success;
539be907324SWei Mi }
540be907324SWei Mi 
5416a14325dSWei Mi std::error_code SampleProfileReaderCompactBinary::read() {
542d3289544SWenlei He   std::vector<uint64_t> OffsetsToUse;
543d3289544SWenlei He   if (UseAllFuncs) {
544d3289544SWenlei He     for (auto FuncEntry : FuncOffsetTable) {
545d3289544SWenlei He       OffsetsToUse.push_back(FuncEntry.second);
546d3289544SWenlei He     }
547d3289544SWenlei He   }
548d3289544SWenlei He   else {
5496a14325dSWei Mi     for (auto Name : FuncsToUse) {
5506a14325dSWei Mi       auto GUID = std::to_string(MD5Hash(Name));
5516a14325dSWei Mi       auto iter = FuncOffsetTable.find(StringRef(GUID));
5526a14325dSWei Mi       if (iter == FuncOffsetTable.end())
5536a14325dSWei Mi         continue;
554d3289544SWenlei He       OffsetsToUse.push_back(iter->second);
555d3289544SWenlei He     }
556d3289544SWenlei He   }
557d3289544SWenlei He 
558d3289544SWenlei He   for (auto Offset : OffsetsToUse) {
5596a14325dSWei Mi     const uint8_t *SavedData = Data;
5606a14325dSWei Mi     Data = reinterpret_cast<const uint8_t *>(Buffer->getBufferStart()) +
561d3289544SWenlei He            Offset;
5626a14325dSWei Mi     if (std::error_code EC = readFuncProfile())
5636a14325dSWei Mi       return EC;
5646a14325dSWei Mi     Data = SavedData;
5656a14325dSWei Mi   }
566c572e92cSDiego Novillo   return sampleprof_error::success;
567c572e92cSDiego Novillo }
568c572e92cSDiego Novillo 
569a0c0857eSWei Mi std::error_code SampleProfileReaderRawBinary::verifySPMagic(uint64_t Magic) {
570a0c0857eSWei Mi   if (Magic == SPMagic())
571a0c0857eSWei Mi     return sampleprof_error::success;
572a0c0857eSWei Mi   return sampleprof_error::bad_magic;
573a0c0857eSWei Mi }
574a0c0857eSWei Mi 
575be907324SWei Mi std::error_code SampleProfileReaderExtBinary::verifySPMagic(uint64_t Magic) {
576be907324SWei Mi   if (Magic == SPMagic(SPF_Ext_Binary))
577be907324SWei Mi     return sampleprof_error::success;
578be907324SWei Mi   return sampleprof_error::bad_magic;
579be907324SWei Mi }
580be907324SWei Mi 
581a0c0857eSWei Mi std::error_code
582a0c0857eSWei Mi SampleProfileReaderCompactBinary::verifySPMagic(uint64_t Magic) {
583a0c0857eSWei Mi   if (Magic == SPMagic(SPF_Compact_Binary))
584a0c0857eSWei Mi     return sampleprof_error::success;
585a0c0857eSWei Mi   return sampleprof_error::bad_magic;
586a0c0857eSWei Mi }
587a0c0857eSWei Mi 
588be907324SWei Mi std::error_code SampleProfileReaderBinary::readNameTable() {
589a0c0857eSWei Mi   auto Size = readNumber<uint32_t>();
590a0c0857eSWei Mi   if (std::error_code EC = Size.getError())
591a0c0857eSWei Mi     return EC;
592a0c0857eSWei Mi   NameTable.reserve(*Size);
593a0c0857eSWei Mi   for (uint32_t I = 0; I < *Size; ++I) {
594a0c0857eSWei Mi     auto Name(readString());
595a0c0857eSWei Mi     if (std::error_code EC = Name.getError())
596a0c0857eSWei Mi       return EC;
597a0c0857eSWei Mi     NameTable.push_back(*Name);
598a0c0857eSWei Mi   }
599a0c0857eSWei Mi 
600a0c0857eSWei Mi   return sampleprof_error::success;
601a0c0857eSWei Mi }
602a0c0857eSWei Mi 
603a0c0857eSWei Mi std::error_code SampleProfileReaderCompactBinary::readNameTable() {
604a0c0857eSWei Mi   auto Size = readNumber<uint64_t>();
605a0c0857eSWei Mi   if (std::error_code EC = Size.getError())
606a0c0857eSWei Mi     return EC;
607a0c0857eSWei Mi   NameTable.reserve(*Size);
608a0c0857eSWei Mi   for (uint32_t I = 0; I < *Size; ++I) {
609a0c0857eSWei Mi     auto FID = readNumber<uint64_t>();
610a0c0857eSWei Mi     if (std::error_code EC = FID.getError())
611a0c0857eSWei Mi       return EC;
612a0c0857eSWei Mi     NameTable.push_back(std::to_string(*FID));
613a0c0857eSWei Mi   }
614a0c0857eSWei Mi   return sampleprof_error::success;
615a0c0857eSWei Mi }
616a0c0857eSWei Mi 
617be907324SWei Mi std::error_code SampleProfileReaderExtBinaryBase::readSecHdrTableEntry() {
618be907324SWei Mi   SecHdrTableEntry Entry;
619be907324SWei Mi   auto Type = readUnencodedNumber<uint64_t>();
620be907324SWei Mi   if (std::error_code EC = Type.getError())
621be907324SWei Mi     return EC;
622be907324SWei Mi   Entry.Type = static_cast<SecType>(*Type);
623c572e92cSDiego Novillo 
624be907324SWei Mi   auto Flag = readUnencodedNumber<uint64_t>();
625be907324SWei Mi   if (std::error_code EC = Flag.getError())
626be907324SWei Mi     return EC;
627be907324SWei Mi   Entry.Flag = *Flag;
628be907324SWei Mi 
629be907324SWei Mi   auto Offset = readUnencodedNumber<uint64_t>();
630be907324SWei Mi   if (std::error_code EC = Offset.getError())
631be907324SWei Mi     return EC;
632be907324SWei Mi   Entry.Offset = *Offset;
633be907324SWei Mi 
634be907324SWei Mi   auto Size = readUnencodedNumber<uint64_t>();
635be907324SWei Mi   if (std::error_code EC = Size.getError())
636be907324SWei Mi     return EC;
637be907324SWei Mi   Entry.Size = *Size;
638be907324SWei Mi 
639be907324SWei Mi   SecHdrTable.push_back(std::move(Entry));
640be907324SWei Mi   return sampleprof_error::success;
641be907324SWei Mi }
642be907324SWei Mi 
643be907324SWei Mi std::error_code SampleProfileReaderExtBinaryBase::readSecHdrTable() {
644be907324SWei Mi   auto EntryNum = readUnencodedNumber<uint64_t>();
645be907324SWei Mi   if (std::error_code EC = EntryNum.getError())
646be907324SWei Mi     return EC;
647be907324SWei Mi 
648be907324SWei Mi   for (uint32_t i = 0; i < (*EntryNum); i++)
649be907324SWei Mi     if (std::error_code EC = readSecHdrTableEntry())
650be907324SWei Mi       return EC;
651be907324SWei Mi 
652be907324SWei Mi   return sampleprof_error::success;
653be907324SWei Mi }
654be907324SWei Mi 
655be907324SWei Mi std::error_code SampleProfileReaderExtBinaryBase::readHeader() {
656be907324SWei Mi   const uint8_t *BufStart =
657be907324SWei Mi       reinterpret_cast<const uint8_t *>(Buffer->getBufferStart());
658be907324SWei Mi   Data = BufStart;
659be907324SWei Mi   End = BufStart + Buffer->getBufferSize();
660be907324SWei Mi 
661be907324SWei Mi   if (std::error_code EC = readMagicIdent())
662be907324SWei Mi     return EC;
663be907324SWei Mi 
664be907324SWei Mi   if (std::error_code EC = readSecHdrTable())
665be907324SWei Mi     return EC;
666be907324SWei Mi 
667be907324SWei Mi   return sampleprof_error::success;
668be907324SWei Mi }
669be907324SWei Mi 
670*eee532cdSWei Mi uint64_t SampleProfileReaderExtBinaryBase::getSectionSize(SecType Type) {
671*eee532cdSWei Mi   for (auto &Entry : SecHdrTable) {
672*eee532cdSWei Mi     if (Entry.Type == Type)
673*eee532cdSWei Mi       return Entry.Size;
674*eee532cdSWei Mi   }
675*eee532cdSWei Mi   return 0;
676*eee532cdSWei Mi }
677*eee532cdSWei Mi 
678*eee532cdSWei Mi uint64_t SampleProfileReaderExtBinaryBase::getFileSize() {
679*eee532cdSWei Mi   auto &LastEntry = SecHdrTable.back();
680*eee532cdSWei Mi   return LastEntry.Offset + LastEntry.Size;
681*eee532cdSWei Mi }
682*eee532cdSWei Mi 
683*eee532cdSWei Mi bool SampleProfileReaderExtBinaryBase::dumpSectionInfo(raw_ostream &OS) {
684*eee532cdSWei Mi   uint64_t TotalSecsSize = 0;
685*eee532cdSWei Mi   for (auto &Entry : SecHdrTable) {
686*eee532cdSWei Mi     OS << getSecName(Entry.Type) << " - Offset: " << Entry.Offset
687*eee532cdSWei Mi        << ", Size: " << Entry.Size << "\n";
688*eee532cdSWei Mi     TotalSecsSize += getSectionSize(Entry.Type);
689*eee532cdSWei Mi   }
690*eee532cdSWei Mi   uint64_t HeaderSize = SecHdrTable.front().Offset;
691*eee532cdSWei Mi   assert(HeaderSize + TotalSecsSize == getFileSize() &&
692*eee532cdSWei Mi          "Size of 'header + sections' doesn't match the total size of profile");
693*eee532cdSWei Mi 
694*eee532cdSWei Mi   OS << "Header Size: " << HeaderSize << "\n";
695*eee532cdSWei Mi   OS << "Total Sections Size: " << TotalSecsSize << "\n";
696*eee532cdSWei Mi   OS << "File Size: " << getFileSize() << "\n";
697*eee532cdSWei Mi   return true;
698*eee532cdSWei Mi }
699*eee532cdSWei Mi 
700be907324SWei Mi std::error_code SampleProfileReaderBinary::readMagicIdent() {
701c572e92cSDiego Novillo   // Read and check the magic identifier.
702c572e92cSDiego Novillo   auto Magic = readNumber<uint64_t>();
703c572e92cSDiego Novillo   if (std::error_code EC = Magic.getError())
704c572e92cSDiego Novillo     return EC;
705a0c0857eSWei Mi   else if (std::error_code EC = verifySPMagic(*Magic))
706c6b96c8dSWei Mi     return EC;
707c572e92cSDiego Novillo 
708c572e92cSDiego Novillo   // Read the version number.
709c572e92cSDiego Novillo   auto Version = readNumber<uint64_t>();
710c572e92cSDiego Novillo   if (std::error_code EC = Version.getError())
711c572e92cSDiego Novillo     return EC;
712c572e92cSDiego Novillo   else if (*Version != SPVersion())
713c572e92cSDiego Novillo     return sampleprof_error::unsupported_version;
714c572e92cSDiego Novillo 
715be907324SWei Mi   return sampleprof_error::success;
716be907324SWei Mi }
717be907324SWei Mi 
718be907324SWei Mi std::error_code SampleProfileReaderBinary::readHeader() {
719be907324SWei Mi   Data = reinterpret_cast<const uint8_t *>(Buffer->getBufferStart());
720be907324SWei Mi   End = Data + Buffer->getBufferSize();
721be907324SWei Mi 
722be907324SWei Mi   if (std::error_code EC = readMagicIdent())
723be907324SWei Mi     return EC;
724be907324SWei Mi 
72540ee23dbSEaswaran Raman   if (std::error_code EC = readSummary())
72640ee23dbSEaswaran Raman     return EC;
72740ee23dbSEaswaran Raman 
728a0c0857eSWei Mi   if (std::error_code EC = readNameTable())
729760c5a8fSDiego Novillo     return EC;
730c572e92cSDiego Novillo   return sampleprof_error::success;
731c572e92cSDiego Novillo }
732c572e92cSDiego Novillo 
7336a14325dSWei Mi std::error_code SampleProfileReaderCompactBinary::readHeader() {
7346a14325dSWei Mi   SampleProfileReaderBinary::readHeader();
7356a14325dSWei Mi   if (std::error_code EC = readFuncOffsetTable())
7366a14325dSWei Mi     return EC;
7376a14325dSWei Mi   return sampleprof_error::success;
7386a14325dSWei Mi }
7396a14325dSWei Mi 
7406a14325dSWei Mi std::error_code SampleProfileReaderCompactBinary::readFuncOffsetTable() {
7416a14325dSWei Mi   auto TableOffset = readUnencodedNumber<uint64_t>();
7426a14325dSWei Mi   if (std::error_code EC = TableOffset.getError())
7436a14325dSWei Mi     return EC;
7446a14325dSWei Mi 
7456a14325dSWei Mi   const uint8_t *SavedData = Data;
7466a14325dSWei Mi   const uint8_t *TableStart =
7476a14325dSWei Mi       reinterpret_cast<const uint8_t *>(Buffer->getBufferStart()) +
7486a14325dSWei Mi       *TableOffset;
7496a14325dSWei Mi   Data = TableStart;
7506a14325dSWei Mi 
7516a14325dSWei Mi   auto Size = readNumber<uint64_t>();
7526a14325dSWei Mi   if (std::error_code EC = Size.getError())
7536a14325dSWei Mi     return EC;
7546a14325dSWei Mi 
7556a14325dSWei Mi   FuncOffsetTable.reserve(*Size);
7566a14325dSWei Mi   for (uint32_t I = 0; I < *Size; ++I) {
7576a14325dSWei Mi     auto FName(readStringFromTable());
7586a14325dSWei Mi     if (std::error_code EC = FName.getError())
7596a14325dSWei Mi       return EC;
7606a14325dSWei Mi 
7616a14325dSWei Mi     auto Offset = readNumber<uint64_t>();
7626a14325dSWei Mi     if (std::error_code EC = Offset.getError())
7636a14325dSWei Mi       return EC;
7646a14325dSWei Mi 
7656a14325dSWei Mi     FuncOffsetTable[*FName] = *Offset;
7666a14325dSWei Mi   }
7676a14325dSWei Mi   End = TableStart;
7686a14325dSWei Mi   Data = SavedData;
7696a14325dSWei Mi   return sampleprof_error::success;
7706a14325dSWei Mi }
7716a14325dSWei Mi 
7726a14325dSWei Mi void SampleProfileReaderCompactBinary::collectFuncsToUse(const Module &M) {
773d3289544SWenlei He   UseAllFuncs = false;
7746a14325dSWei Mi   FuncsToUse.clear();
7756a14325dSWei Mi   for (auto &F : M) {
7769f96f1f1SThan McIntosh     StringRef CanonName = FunctionSamples::getCanonicalFnName(F);
7779f96f1f1SThan McIntosh     FuncsToUse.insert(CanonName);
7786a14325dSWei Mi   }
7796a14325dSWei Mi }
7806a14325dSWei Mi 
78140ee23dbSEaswaran Raman std::error_code SampleProfileReaderBinary::readSummaryEntry(
78240ee23dbSEaswaran Raman     std::vector<ProfileSummaryEntry> &Entries) {
78340ee23dbSEaswaran Raman   auto Cutoff = readNumber<uint64_t>();
78440ee23dbSEaswaran Raman   if (std::error_code EC = Cutoff.getError())
78540ee23dbSEaswaran Raman     return EC;
78640ee23dbSEaswaran Raman 
78740ee23dbSEaswaran Raman   auto MinBlockCount = readNumber<uint64_t>();
78840ee23dbSEaswaran Raman   if (std::error_code EC = MinBlockCount.getError())
78940ee23dbSEaswaran Raman     return EC;
79040ee23dbSEaswaran Raman 
79140ee23dbSEaswaran Raman   auto NumBlocks = readNumber<uint64_t>();
79240ee23dbSEaswaran Raman   if (std::error_code EC = NumBlocks.getError())
79340ee23dbSEaswaran Raman     return EC;
79440ee23dbSEaswaran Raman 
79540ee23dbSEaswaran Raman   Entries.emplace_back(*Cutoff, *MinBlockCount, *NumBlocks);
79640ee23dbSEaswaran Raman   return sampleprof_error::success;
79740ee23dbSEaswaran Raman }
79840ee23dbSEaswaran Raman 
79940ee23dbSEaswaran Raman std::error_code SampleProfileReaderBinary::readSummary() {
80040ee23dbSEaswaran Raman   auto TotalCount = readNumber<uint64_t>();
80140ee23dbSEaswaran Raman   if (std::error_code EC = TotalCount.getError())
80240ee23dbSEaswaran Raman     return EC;
80340ee23dbSEaswaran Raman 
80440ee23dbSEaswaran Raman   auto MaxBlockCount = readNumber<uint64_t>();
80540ee23dbSEaswaran Raman   if (std::error_code EC = MaxBlockCount.getError())
80640ee23dbSEaswaran Raman     return EC;
80740ee23dbSEaswaran Raman 
80840ee23dbSEaswaran Raman   auto MaxFunctionCount = readNumber<uint64_t>();
80940ee23dbSEaswaran Raman   if (std::error_code EC = MaxFunctionCount.getError())
81040ee23dbSEaswaran Raman     return EC;
81140ee23dbSEaswaran Raman 
81240ee23dbSEaswaran Raman   auto NumBlocks = readNumber<uint64_t>();
81340ee23dbSEaswaran Raman   if (std::error_code EC = NumBlocks.getError())
81440ee23dbSEaswaran Raman     return EC;
81540ee23dbSEaswaran Raman 
81640ee23dbSEaswaran Raman   auto NumFunctions = readNumber<uint64_t>();
81740ee23dbSEaswaran Raman   if (std::error_code EC = NumFunctions.getError())
81840ee23dbSEaswaran Raman     return EC;
81940ee23dbSEaswaran Raman 
82040ee23dbSEaswaran Raman   auto NumSummaryEntries = readNumber<uint64_t>();
82140ee23dbSEaswaran Raman   if (std::error_code EC = NumSummaryEntries.getError())
82240ee23dbSEaswaran Raman     return EC;
82340ee23dbSEaswaran Raman 
82440ee23dbSEaswaran Raman   std::vector<ProfileSummaryEntry> Entries;
82540ee23dbSEaswaran Raman   for (unsigned i = 0; i < *NumSummaryEntries; i++) {
82640ee23dbSEaswaran Raman     std::error_code EC = readSummaryEntry(Entries);
82740ee23dbSEaswaran Raman     if (EC != sampleprof_error::success)
82840ee23dbSEaswaran Raman       return EC;
82940ee23dbSEaswaran Raman   }
8300eaee545SJonas Devlieghere   Summary = std::make_unique<ProfileSummary>(
8317cefdb81SEaswaran Raman       ProfileSummary::PSK_Sample, Entries, *TotalCount, *MaxBlockCount, 0,
8327cefdb81SEaswaran Raman       *MaxFunctionCount, *NumBlocks, *NumFunctions);
83340ee23dbSEaswaran Raman 
83440ee23dbSEaswaran Raman   return sampleprof_error::success;
83540ee23dbSEaswaran Raman }
83640ee23dbSEaswaran Raman 
837a0c0857eSWei Mi bool SampleProfileReaderRawBinary::hasFormat(const MemoryBuffer &Buffer) {
838c572e92cSDiego Novillo   const uint8_t *Data =
839c572e92cSDiego Novillo       reinterpret_cast<const uint8_t *>(Buffer.getBufferStart());
840c572e92cSDiego Novillo   uint64_t Magic = decodeULEB128(Data);
841c572e92cSDiego Novillo   return Magic == SPMagic();
842c572e92cSDiego Novillo }
843c572e92cSDiego Novillo 
844be907324SWei Mi bool SampleProfileReaderExtBinary::hasFormat(const MemoryBuffer &Buffer) {
845be907324SWei Mi   const uint8_t *Data =
846be907324SWei Mi       reinterpret_cast<const uint8_t *>(Buffer.getBufferStart());
847be907324SWei Mi   uint64_t Magic = decodeULEB128(Data);
848be907324SWei Mi   return Magic == SPMagic(SPF_Ext_Binary);
849be907324SWei Mi }
850be907324SWei Mi 
851a0c0857eSWei Mi bool SampleProfileReaderCompactBinary::hasFormat(const MemoryBuffer &Buffer) {
852a0c0857eSWei Mi   const uint8_t *Data =
853a0c0857eSWei Mi       reinterpret_cast<const uint8_t *>(Buffer.getBufferStart());
854a0c0857eSWei Mi   uint64_t Magic = decodeULEB128(Data);
855a0c0857eSWei Mi   return Magic == SPMagic(SPF_Compact_Binary);
856a0c0857eSWei Mi }
857a0c0857eSWei Mi 
8583376a787SDiego Novillo std::error_code SampleProfileReaderGCC::skipNextWord() {
8593376a787SDiego Novillo   uint32_t dummy;
8603376a787SDiego Novillo   if (!GcovBuffer.readInt(dummy))
8613376a787SDiego Novillo     return sampleprof_error::truncated;
8623376a787SDiego Novillo   return sampleprof_error::success;
8633376a787SDiego Novillo }
8643376a787SDiego Novillo 
8653376a787SDiego Novillo template <typename T> ErrorOr<T> SampleProfileReaderGCC::readNumber() {
8663376a787SDiego Novillo   if (sizeof(T) <= sizeof(uint32_t)) {
8673376a787SDiego Novillo     uint32_t Val;
8683376a787SDiego Novillo     if (GcovBuffer.readInt(Val) && Val <= std::numeric_limits<T>::max())
8693376a787SDiego Novillo       return static_cast<T>(Val);
8703376a787SDiego Novillo   } else if (sizeof(T) <= sizeof(uint64_t)) {
8713376a787SDiego Novillo     uint64_t Val;
8723376a787SDiego Novillo     if (GcovBuffer.readInt64(Val) && Val <= std::numeric_limits<T>::max())
8733376a787SDiego Novillo       return static_cast<T>(Val);
8743376a787SDiego Novillo   }
8753376a787SDiego Novillo 
8763376a787SDiego Novillo   std::error_code EC = sampleprof_error::malformed;
8773376a787SDiego Novillo   reportError(0, EC.message());
8783376a787SDiego Novillo   return EC;
8793376a787SDiego Novillo }
8803376a787SDiego Novillo 
8813376a787SDiego Novillo ErrorOr<StringRef> SampleProfileReaderGCC::readString() {
8823376a787SDiego Novillo   StringRef Str;
8833376a787SDiego Novillo   if (!GcovBuffer.readString(Str))
8843376a787SDiego Novillo     return sampleprof_error::truncated;
8853376a787SDiego Novillo   return Str;
8863376a787SDiego Novillo }
8873376a787SDiego Novillo 
8883376a787SDiego Novillo std::error_code SampleProfileReaderGCC::readHeader() {
8893376a787SDiego Novillo   // Read the magic identifier.
8903376a787SDiego Novillo   if (!GcovBuffer.readGCDAFormat())
8913376a787SDiego Novillo     return sampleprof_error::unrecognized_format;
8923376a787SDiego Novillo 
8933376a787SDiego Novillo   // Read the version number. Note - the GCC reader does not validate this
8943376a787SDiego Novillo   // version, but the profile creator generates v704.
8953376a787SDiego Novillo   GCOV::GCOVVersion version;
8963376a787SDiego Novillo   if (!GcovBuffer.readGCOVVersion(version))
8973376a787SDiego Novillo     return sampleprof_error::unrecognized_format;
8983376a787SDiego Novillo 
8993376a787SDiego Novillo   if (version != GCOV::V704)
9003376a787SDiego Novillo     return sampleprof_error::unsupported_version;
9013376a787SDiego Novillo 
9023376a787SDiego Novillo   // Skip the empty integer.
9033376a787SDiego Novillo   if (std::error_code EC = skipNextWord())
9043376a787SDiego Novillo     return EC;
9053376a787SDiego Novillo 
9063376a787SDiego Novillo   return sampleprof_error::success;
9073376a787SDiego Novillo }
9083376a787SDiego Novillo 
9093376a787SDiego Novillo std::error_code SampleProfileReaderGCC::readSectionTag(uint32_t Expected) {
9103376a787SDiego Novillo   uint32_t Tag;
9113376a787SDiego Novillo   if (!GcovBuffer.readInt(Tag))
9123376a787SDiego Novillo     return sampleprof_error::truncated;
9133376a787SDiego Novillo 
9143376a787SDiego Novillo   if (Tag != Expected)
9153376a787SDiego Novillo     return sampleprof_error::malformed;
9163376a787SDiego Novillo 
9173376a787SDiego Novillo   if (std::error_code EC = skipNextWord())
9183376a787SDiego Novillo     return EC;
9193376a787SDiego Novillo 
9203376a787SDiego Novillo   return sampleprof_error::success;
9213376a787SDiego Novillo }
9223376a787SDiego Novillo 
9233376a787SDiego Novillo std::error_code SampleProfileReaderGCC::readNameTable() {
9243376a787SDiego Novillo   if (std::error_code EC = readSectionTag(GCOVTagAFDOFileNames))
9253376a787SDiego Novillo     return EC;
9263376a787SDiego Novillo 
9273376a787SDiego Novillo   uint32_t Size;
9283376a787SDiego Novillo   if (!GcovBuffer.readInt(Size))
9293376a787SDiego Novillo     return sampleprof_error::truncated;
9303376a787SDiego Novillo 
9313376a787SDiego Novillo   for (uint32_t I = 0; I < Size; ++I) {
9323376a787SDiego Novillo     StringRef Str;
9333376a787SDiego Novillo     if (!GcovBuffer.readString(Str))
9343376a787SDiego Novillo       return sampleprof_error::truncated;
9353376a787SDiego Novillo     Names.push_back(Str);
9363376a787SDiego Novillo   }
9373376a787SDiego Novillo 
9383376a787SDiego Novillo   return sampleprof_error::success;
9393376a787SDiego Novillo }
9403376a787SDiego Novillo 
9413376a787SDiego Novillo std::error_code SampleProfileReaderGCC::readFunctionProfiles() {
9423376a787SDiego Novillo   if (std::error_code EC = readSectionTag(GCOVTagAFDOFunction))
9433376a787SDiego Novillo     return EC;
9443376a787SDiego Novillo 
9453376a787SDiego Novillo   uint32_t NumFunctions;
9463376a787SDiego Novillo   if (!GcovBuffer.readInt(NumFunctions))
9473376a787SDiego Novillo     return sampleprof_error::truncated;
9483376a787SDiego Novillo 
949aae1ed8eSDiego Novillo   InlineCallStack Stack;
9503376a787SDiego Novillo   for (uint32_t I = 0; I < NumFunctions; ++I)
951aae1ed8eSDiego Novillo     if (std::error_code EC = readOneFunctionProfile(Stack, true, 0))
9523376a787SDiego Novillo       return EC;
9533376a787SDiego Novillo 
95440ee23dbSEaswaran Raman   computeSummary();
9553376a787SDiego Novillo   return sampleprof_error::success;
9563376a787SDiego Novillo }
9573376a787SDiego Novillo 
958aae1ed8eSDiego Novillo std::error_code SampleProfileReaderGCC::readOneFunctionProfile(
959aae1ed8eSDiego Novillo     const InlineCallStack &InlineStack, bool Update, uint32_t Offset) {
9603376a787SDiego Novillo   uint64_t HeadCount = 0;
961aae1ed8eSDiego Novillo   if (InlineStack.size() == 0)
9623376a787SDiego Novillo     if (!GcovBuffer.readInt64(HeadCount))
9633376a787SDiego Novillo       return sampleprof_error::truncated;
9643376a787SDiego Novillo 
9653376a787SDiego Novillo   uint32_t NameIdx;
9663376a787SDiego Novillo   if (!GcovBuffer.readInt(NameIdx))
9673376a787SDiego Novillo     return sampleprof_error::truncated;
9683376a787SDiego Novillo 
9693376a787SDiego Novillo   StringRef Name(Names[NameIdx]);
9703376a787SDiego Novillo 
9713376a787SDiego Novillo   uint32_t NumPosCounts;
9723376a787SDiego Novillo   if (!GcovBuffer.readInt(NumPosCounts))
9733376a787SDiego Novillo     return sampleprof_error::truncated;
9743376a787SDiego Novillo 
975aae1ed8eSDiego Novillo   uint32_t NumCallsites;
976aae1ed8eSDiego Novillo   if (!GcovBuffer.readInt(NumCallsites))
9773376a787SDiego Novillo     return sampleprof_error::truncated;
9783376a787SDiego Novillo 
979aae1ed8eSDiego Novillo   FunctionSamples *FProfile = nullptr;
980aae1ed8eSDiego Novillo   if (InlineStack.size() == 0) {
981aae1ed8eSDiego Novillo     // If this is a top function that we have already processed, do not
982aae1ed8eSDiego Novillo     // update its profile again.  This happens in the presence of
983aae1ed8eSDiego Novillo     // function aliases.  Since these aliases share the same function
984aae1ed8eSDiego Novillo     // body, there will be identical replicated profiles for the
985aae1ed8eSDiego Novillo     // original function.  In this case, we simply not bother updating
986aae1ed8eSDiego Novillo     // the profile of the original function.
987aae1ed8eSDiego Novillo     FProfile = &Profiles[Name];
988aae1ed8eSDiego Novillo     FProfile->addHeadSamples(HeadCount);
989aae1ed8eSDiego Novillo     if (FProfile->getTotalSamples() > 0)
9903376a787SDiego Novillo       Update = false;
991aae1ed8eSDiego Novillo   } else {
992aae1ed8eSDiego Novillo     // Otherwise, we are reading an inlined instance. The top of the
993aae1ed8eSDiego Novillo     // inline stack contains the profile of the caller. Insert this
994aae1ed8eSDiego Novillo     // callee in the caller's CallsiteMap.
995aae1ed8eSDiego Novillo     FunctionSamples *CallerProfile = InlineStack.front();
996aae1ed8eSDiego Novillo     uint32_t LineOffset = Offset >> 16;
997aae1ed8eSDiego Novillo     uint32_t Discriminator = Offset & 0xffff;
998aae1ed8eSDiego Novillo     FProfile = &CallerProfile->functionSamplesAt(
9992c7ca9b5SDehao Chen         LineLocation(LineOffset, Discriminator))[Name];
10003376a787SDiego Novillo   }
100157d1dda5SDehao Chen   FProfile->setName(Name);
10023376a787SDiego Novillo 
10033376a787SDiego Novillo   for (uint32_t I = 0; I < NumPosCounts; ++I) {
10043376a787SDiego Novillo     uint32_t Offset;
10053376a787SDiego Novillo     if (!GcovBuffer.readInt(Offset))
10063376a787SDiego Novillo       return sampleprof_error::truncated;
10073376a787SDiego Novillo 
10083376a787SDiego Novillo     uint32_t NumTargets;
10093376a787SDiego Novillo     if (!GcovBuffer.readInt(NumTargets))
10103376a787SDiego Novillo       return sampleprof_error::truncated;
10113376a787SDiego Novillo 
10123376a787SDiego Novillo     uint64_t Count;
10133376a787SDiego Novillo     if (!GcovBuffer.readInt64(Count))
10143376a787SDiego Novillo       return sampleprof_error::truncated;
10153376a787SDiego Novillo 
1016aae1ed8eSDiego Novillo     // The line location is encoded in the offset as:
1017aae1ed8eSDiego Novillo     //   high 16 bits: line offset to the start of the function.
1018aae1ed8eSDiego Novillo     //   low 16 bits: discriminator.
1019aae1ed8eSDiego Novillo     uint32_t LineOffset = Offset >> 16;
1020aae1ed8eSDiego Novillo     uint32_t Discriminator = Offset & 0xffff;
10213376a787SDiego Novillo 
1022aae1ed8eSDiego Novillo     InlineCallStack NewStack;
1023aae1ed8eSDiego Novillo     NewStack.push_back(FProfile);
1024aae1ed8eSDiego Novillo     NewStack.insert(NewStack.end(), InlineStack.begin(), InlineStack.end());
1025aae1ed8eSDiego Novillo     if (Update) {
1026aae1ed8eSDiego Novillo       // Walk up the inline stack, adding the samples on this line to
1027aae1ed8eSDiego Novillo       // the total sample count of the callers in the chain.
1028aae1ed8eSDiego Novillo       for (auto CallerProfile : NewStack)
1029aae1ed8eSDiego Novillo         CallerProfile->addTotalSamples(Count);
1030aae1ed8eSDiego Novillo 
1031aae1ed8eSDiego Novillo       // Update the body samples for the current profile.
1032aae1ed8eSDiego Novillo       FProfile->addBodySamples(LineOffset, Discriminator, Count);
1033aae1ed8eSDiego Novillo     }
1034aae1ed8eSDiego Novillo 
1035aae1ed8eSDiego Novillo     // Process the list of functions called at an indirect call site.
1036aae1ed8eSDiego Novillo     // These are all the targets that a function pointer (or virtual
1037aae1ed8eSDiego Novillo     // function) resolved at runtime.
10383376a787SDiego Novillo     for (uint32_t J = 0; J < NumTargets; J++) {
10393376a787SDiego Novillo       uint32_t HistVal;
10403376a787SDiego Novillo       if (!GcovBuffer.readInt(HistVal))
10413376a787SDiego Novillo         return sampleprof_error::truncated;
10423376a787SDiego Novillo 
10433376a787SDiego Novillo       if (HistVal != HIST_TYPE_INDIR_CALL_TOPN)
10443376a787SDiego Novillo         return sampleprof_error::malformed;
10453376a787SDiego Novillo 
10463376a787SDiego Novillo       uint64_t TargetIdx;
10473376a787SDiego Novillo       if (!GcovBuffer.readInt64(TargetIdx))
10483376a787SDiego Novillo         return sampleprof_error::truncated;
10493376a787SDiego Novillo       StringRef TargetName(Names[TargetIdx]);
10503376a787SDiego Novillo 
10513376a787SDiego Novillo       uint64_t TargetCount;
10523376a787SDiego Novillo       if (!GcovBuffer.readInt64(TargetCount))
10533376a787SDiego Novillo         return sampleprof_error::truncated;
10543376a787SDiego Novillo 
1055920677a9SDehao Chen       if (Update)
1056920677a9SDehao Chen         FProfile->addCalledTargetSamples(LineOffset, Discriminator,
1057aae1ed8eSDiego Novillo                                          TargetName, TargetCount);
10583376a787SDiego Novillo     }
10593376a787SDiego Novillo   }
10603376a787SDiego Novillo 
1061aae1ed8eSDiego Novillo   // Process all the inlined callers into the current function. These
1062aae1ed8eSDiego Novillo   // are all the callsites that were inlined into this function.
1063aae1ed8eSDiego Novillo   for (uint32_t I = 0; I < NumCallsites; I++) {
10643376a787SDiego Novillo     // The offset is encoded as:
10653376a787SDiego Novillo     //   high 16 bits: line offset to the start of the function.
10663376a787SDiego Novillo     //   low 16 bits: discriminator.
10673376a787SDiego Novillo     uint32_t Offset;
10683376a787SDiego Novillo     if (!GcovBuffer.readInt(Offset))
10693376a787SDiego Novillo       return sampleprof_error::truncated;
1070aae1ed8eSDiego Novillo     InlineCallStack NewStack;
1071aae1ed8eSDiego Novillo     NewStack.push_back(FProfile);
1072aae1ed8eSDiego Novillo     NewStack.insert(NewStack.end(), InlineStack.begin(), InlineStack.end());
1073aae1ed8eSDiego Novillo     if (std::error_code EC = readOneFunctionProfile(NewStack, Update, Offset))
10743376a787SDiego Novillo       return EC;
10753376a787SDiego Novillo   }
10763376a787SDiego Novillo 
10773376a787SDiego Novillo   return sampleprof_error::success;
10783376a787SDiego Novillo }
10793376a787SDiego Novillo 
10805f8f34e4SAdrian Prantl /// Read a GCC AutoFDO profile.
10813376a787SDiego Novillo ///
10823376a787SDiego Novillo /// This format is generated by the Linux Perf conversion tool at
10833376a787SDiego Novillo /// https://github.com/google/autofdo.
10843376a787SDiego Novillo std::error_code SampleProfileReaderGCC::read() {
10853376a787SDiego Novillo   // Read the string table.
10863376a787SDiego Novillo   if (std::error_code EC = readNameTable())
10873376a787SDiego Novillo     return EC;
10883376a787SDiego Novillo 
10893376a787SDiego Novillo   // Read the source profile.
10903376a787SDiego Novillo   if (std::error_code EC = readFunctionProfiles())
10913376a787SDiego Novillo     return EC;
10923376a787SDiego Novillo 
10933376a787SDiego Novillo   return sampleprof_error::success;
10943376a787SDiego Novillo }
10953376a787SDiego Novillo 
10963376a787SDiego Novillo bool SampleProfileReaderGCC::hasFormat(const MemoryBuffer &Buffer) {
10973376a787SDiego Novillo   StringRef Magic(reinterpret_cast<const char *>(Buffer.getBufferStart()));
10983376a787SDiego Novillo   return Magic == "adcg*704";
10993376a787SDiego Novillo }
11003376a787SDiego Novillo 
110128436358SRichard Smith std::error_code SampleProfileReaderItaniumRemapper::read() {
110228436358SRichard Smith   // If the underlying data is in compact format, we can't remap it because
110328436358SRichard Smith   // we don't know what the original function names were.
110428436358SRichard Smith   if (getFormat() == SPF_Compact_Binary) {
110528436358SRichard Smith     Ctx.diagnose(DiagnosticInfoSampleProfile(
110628436358SRichard Smith         Buffer->getBufferIdentifier(),
110728436358SRichard Smith         "Profile data remapping cannot be applied to profile data "
110828436358SRichard Smith         "in compact format (original mangled names are not available).",
110928436358SRichard Smith         DS_Warning));
111028436358SRichard Smith     return sampleprof_error::success;
111128436358SRichard Smith   }
111228436358SRichard Smith 
111328436358SRichard Smith   if (Error E = Remappings.read(*Buffer)) {
111428436358SRichard Smith     handleAllErrors(
111528436358SRichard Smith         std::move(E), [&](const SymbolRemappingParseError &ParseError) {
111628436358SRichard Smith           reportError(ParseError.getLineNum(), ParseError.getMessage());
111728436358SRichard Smith         });
111828436358SRichard Smith     return sampleprof_error::malformed;
111928436358SRichard Smith   }
112028436358SRichard Smith 
112128436358SRichard Smith   for (auto &Sample : getProfiles())
112228436358SRichard Smith     if (auto Key = Remappings.insert(Sample.first()))
112328436358SRichard Smith       SampleMap.insert({Key, &Sample.second});
112428436358SRichard Smith 
112528436358SRichard Smith   return sampleprof_error::success;
112628436358SRichard Smith }
112728436358SRichard Smith 
112828436358SRichard Smith FunctionSamples *
112928436358SRichard Smith SampleProfileReaderItaniumRemapper::getSamplesFor(StringRef Fname) {
113028436358SRichard Smith   if (auto Key = Remappings.lookup(Fname))
113128436358SRichard Smith     return SampleMap.lookup(Key);
113228436358SRichard Smith   return SampleProfileReader::getSamplesFor(Fname);
113328436358SRichard Smith }
113428436358SRichard Smith 
11355f8f34e4SAdrian Prantl /// Prepare a memory buffer for the contents of \p Filename.
1136de1ab26fSDiego Novillo ///
1137c572e92cSDiego Novillo /// \returns an error code indicating the status of the buffer.
1138fcd55607SDiego Novillo static ErrorOr<std::unique_ptr<MemoryBuffer>>
11390da23a27SBenjamin Kramer setupMemoryBuffer(const Twine &Filename) {
1140c572e92cSDiego Novillo   auto BufferOrErr = MemoryBuffer::getFileOrSTDIN(Filename);
1141c572e92cSDiego Novillo   if (std::error_code EC = BufferOrErr.getError())
1142c572e92cSDiego Novillo     return EC;
1143fcd55607SDiego Novillo   auto Buffer = std::move(BufferOrErr.get());
1144c572e92cSDiego Novillo 
1145c572e92cSDiego Novillo   // Sanity check the file.
1146260fe3ecSZachary Turner   if (uint64_t(Buffer->getBufferSize()) > std::numeric_limits<uint32_t>::max())
1147c572e92cSDiego Novillo     return sampleprof_error::too_large;
1148c572e92cSDiego Novillo 
1149fcd55607SDiego Novillo   return std::move(Buffer);
1150c572e92cSDiego Novillo }
1151c572e92cSDiego Novillo 
11525f8f34e4SAdrian Prantl /// Create a sample profile reader based on the format of the input file.
1153c572e92cSDiego Novillo ///
1154c572e92cSDiego Novillo /// \param Filename The file to open.
1155c572e92cSDiego Novillo ///
1156c572e92cSDiego Novillo /// \param C The LLVM context to use to emit diagnostics.
1157c572e92cSDiego Novillo ///
1158c572e92cSDiego Novillo /// \returns an error code indicating the status of the created reader.
1159fcd55607SDiego Novillo ErrorOr<std::unique_ptr<SampleProfileReader>>
11600da23a27SBenjamin Kramer SampleProfileReader::create(const Twine &Filename, LLVMContext &C) {
1161fcd55607SDiego Novillo   auto BufferOrError = setupMemoryBuffer(Filename);
1162fcd55607SDiego Novillo   if (std::error_code EC = BufferOrError.getError())
1163c572e92cSDiego Novillo     return EC;
116451abea74SNathan Slingerland   return create(BufferOrError.get(), C);
116551abea74SNathan Slingerland }
1166c572e92cSDiego Novillo 
116728436358SRichard Smith /// Create a sample profile remapper from the given input, to remap the
116828436358SRichard Smith /// function names in the given profile data.
116928436358SRichard Smith ///
117028436358SRichard Smith /// \param Filename The file to open.
117128436358SRichard Smith ///
117228436358SRichard Smith /// \param C The LLVM context to use to emit diagnostics.
117328436358SRichard Smith ///
117428436358SRichard Smith /// \param Underlying The underlying profile data reader to remap.
117528436358SRichard Smith ///
117628436358SRichard Smith /// \returns an error code indicating the status of the created reader.
117728436358SRichard Smith ErrorOr<std::unique_ptr<SampleProfileReader>>
117828436358SRichard Smith SampleProfileReaderItaniumRemapper::create(
117928436358SRichard Smith     const Twine &Filename, LLVMContext &C,
118028436358SRichard Smith     std::unique_ptr<SampleProfileReader> Underlying) {
118128436358SRichard Smith   auto BufferOrError = setupMemoryBuffer(Filename);
118228436358SRichard Smith   if (std::error_code EC = BufferOrError.getError())
118328436358SRichard Smith     return EC;
11840eaee545SJonas Devlieghere   return std::make_unique<SampleProfileReaderItaniumRemapper>(
118528436358SRichard Smith       std::move(BufferOrError.get()), C, std::move(Underlying));
118628436358SRichard Smith }
118728436358SRichard Smith 
11885f8f34e4SAdrian Prantl /// Create a sample profile reader based on the format of the input data.
118951abea74SNathan Slingerland ///
119051abea74SNathan Slingerland /// \param B The memory buffer to create the reader from (assumes ownership).
119151abea74SNathan Slingerland ///
119251abea74SNathan Slingerland /// \param C The LLVM context to use to emit diagnostics.
119351abea74SNathan Slingerland ///
119451abea74SNathan Slingerland /// \returns an error code indicating the status of the created reader.
119551abea74SNathan Slingerland ErrorOr<std::unique_ptr<SampleProfileReader>>
119651abea74SNathan Slingerland SampleProfileReader::create(std::unique_ptr<MemoryBuffer> &B, LLVMContext &C) {
1197fcd55607SDiego Novillo   std::unique_ptr<SampleProfileReader> Reader;
1198a0c0857eSWei Mi   if (SampleProfileReaderRawBinary::hasFormat(*B))
1199a0c0857eSWei Mi     Reader.reset(new SampleProfileReaderRawBinary(std::move(B), C));
1200be907324SWei Mi   else if (SampleProfileReaderExtBinary::hasFormat(*B))
1201be907324SWei Mi     Reader.reset(new SampleProfileReaderExtBinary(std::move(B), C));
1202a0c0857eSWei Mi   else if (SampleProfileReaderCompactBinary::hasFormat(*B))
1203a0c0857eSWei Mi     Reader.reset(new SampleProfileReaderCompactBinary(std::move(B), C));
120451abea74SNathan Slingerland   else if (SampleProfileReaderGCC::hasFormat(*B))
120551abea74SNathan Slingerland     Reader.reset(new SampleProfileReaderGCC(std::move(B), C));
120651abea74SNathan Slingerland   else if (SampleProfileReaderText::hasFormat(*B))
120751abea74SNathan Slingerland     Reader.reset(new SampleProfileReaderText(std::move(B), C));
12084f823667SNathan Slingerland   else
12094f823667SNathan Slingerland     return sampleprof_error::unrecognized_format;
1210c572e92cSDiego Novillo 
121194d44c97SWei Mi   FunctionSamples::Format = Reader->getFormat();
1212be907324SWei Mi   if (std::error_code EC = Reader->readHeader()) {
1213fcd55607SDiego Novillo     return EC;
1214be907324SWei Mi   }
1215fcd55607SDiego Novillo 
1216fcd55607SDiego Novillo   return std::move(Reader);
1217de1ab26fSDiego Novillo }
121840ee23dbSEaswaran Raman 
121940ee23dbSEaswaran Raman // For text and GCC file formats, we compute the summary after reading the
122040ee23dbSEaswaran Raman // profile. Binary format has the profile summary in its header.
122140ee23dbSEaswaran Raman void SampleProfileReader::computeSummary() {
1222e5a17e3fSEaswaran Raman   SampleProfileSummaryBuilder Builder(ProfileSummaryBuilder::DefaultCutoffs);
122340ee23dbSEaswaran Raman   for (const auto &I : Profiles) {
122440ee23dbSEaswaran Raman     const FunctionSamples &Profile = I.second;
1225e5a17e3fSEaswaran Raman     Builder.addRecord(Profile);
122640ee23dbSEaswaran Raman   }
122738de59e4SBenjamin Kramer   Summary = Builder.getSummary();
122840ee23dbSEaswaran Raman }
1229