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"
29*6745ffe4SRong Xu #include "llvm/Support/CommandLine.h"
30b523790aSWei Mi #include "llvm/Support/Compression.h"
31de1ab26fSDiego Novillo #include "llvm/Support/ErrorOr.h"
32c572e92cSDiego Novillo #include "llvm/Support/LEB128.h"
33de1ab26fSDiego Novillo #include "llvm/Support/LineIterator.h"
346a14325dSWei Mi #include "llvm/Support/MD5.h"
35c572e92cSDiego Novillo #include "llvm/Support/MemoryBuffer.h"
36e78d131aSEugene Zelenko #include "llvm/Support/raw_ostream.h"
37e78d131aSEugene Zelenko #include <algorithm>
38e78d131aSEugene Zelenko #include <cstddef>
39e78d131aSEugene Zelenko #include <cstdint>
40e78d131aSEugene Zelenko #include <limits>
41e78d131aSEugene Zelenko #include <memory>
42a5d30421SWenlei He #include <set>
43e78d131aSEugene Zelenko #include <system_error>
44e78d131aSEugene Zelenko #include <vector>
45de1ab26fSDiego Novillo 
46de1ab26fSDiego Novillo using namespace llvm;
47e78d131aSEugene Zelenko using namespace sampleprof;
48de1ab26fSDiego Novillo 
49*6745ffe4SRong Xu #define DEBUG_TYPE "samplepgo-reader"
50*6745ffe4SRong Xu 
51*6745ffe4SRong Xu // This internal option specifies if the profile uses FS discriminators.
52*6745ffe4SRong Xu // It only applies to text, binary and compact binary format profiles.
53*6745ffe4SRong Xu // For ext-binary format profiles, the flag is set in the summary.
54*6745ffe4SRong Xu static cl::opt<bool> ProfileIsFSDisciminator(
55*6745ffe4SRong Xu     "profile-isfs", cl::Hidden, cl::init(false),
56*6745ffe4SRong Xu     cl::desc("Profile uses flow senstive discriminators"));
57*6745ffe4SRong Xu 
585f8f34e4SAdrian Prantl /// Dump the function profile for \p FName.
59de1ab26fSDiego Novillo ///
60de1ab26fSDiego Novillo /// \param FName Name of the function to print.
61d5336ae2SDiego Novillo /// \param OS Stream to emit the output to.
62d5336ae2SDiego Novillo void SampleProfileReader::dumpFunctionProfile(StringRef FName,
63d5336ae2SDiego Novillo                                               raw_ostream &OS) {
648e415a82SDiego Novillo   OS << "Function: " << FName << ": " << Profiles[FName];
65de1ab26fSDiego Novillo }
66de1ab26fSDiego Novillo 
675f8f34e4SAdrian Prantl /// Dump all the function profiles found on stream \p OS.
68d5336ae2SDiego Novillo void SampleProfileReader::dump(raw_ostream &OS) {
69d5336ae2SDiego Novillo   for (const auto &I : Profiles)
70d5336ae2SDiego Novillo     dumpFunctionProfile(I.getKey(), OS);
71de1ab26fSDiego Novillo }
72de1ab26fSDiego Novillo 
735f8f34e4SAdrian Prantl /// Parse \p Input as function head.
746722688eSDehao Chen ///
756722688eSDehao Chen /// Parse one line of \p Input, and update function name in \p FName,
766722688eSDehao Chen /// function's total sample count in \p NumSamples, function's entry
776722688eSDehao Chen /// count in \p NumHeadSamples.
786722688eSDehao Chen ///
796722688eSDehao Chen /// \returns true if parsing is successful.
806722688eSDehao Chen static bool ParseHead(const StringRef &Input, StringRef &FName,
8138be3330SDiego Novillo                       uint64_t &NumSamples, uint64_t &NumHeadSamples) {
826722688eSDehao Chen   if (Input[0] == ' ')
836722688eSDehao Chen     return false;
846722688eSDehao Chen   size_t n2 = Input.rfind(':');
856722688eSDehao Chen   size_t n1 = Input.rfind(':', n2 - 1);
866722688eSDehao Chen   FName = Input.substr(0, n1);
876722688eSDehao Chen   if (Input.substr(n1 + 1, n2 - n1 - 1).getAsInteger(10, NumSamples))
886722688eSDehao Chen     return false;
896722688eSDehao Chen   if (Input.substr(n2 + 1).getAsInteger(10, NumHeadSamples))
906722688eSDehao Chen     return false;
916722688eSDehao Chen   return true;
926722688eSDehao Chen }
936722688eSDehao Chen 
945f8f34e4SAdrian Prantl /// Returns true if line offset \p L is legal (only has 16 bits).
9557d1dda5SDehao Chen static bool isOffsetLegal(unsigned L) { return (L & 0xffff) == L; }
9610042412SDehao Chen 
97ac068e01SHongtao Yu /// Parse \p Input that contains metadata.
98ac068e01SHongtao Yu /// Possible metadata:
99ac068e01SHongtao Yu /// - CFG Checksum information:
100ac068e01SHongtao Yu ///     !CFGChecksum: 12345
1011410db70SWenlei He /// - CFG Checksum information:
1021410db70SWenlei He ///     !Attributes: 1
103ac068e01SHongtao Yu /// Stores the FunctionHash (a.k.a. CFG Checksum) into \p FunctionHash.
1041410db70SWenlei He static bool parseMetadata(const StringRef &Input, uint64_t &FunctionHash,
1051410db70SWenlei He                           uint32_t &Attributes) {
1061410db70SWenlei He   if (Input.startswith("!CFGChecksum:")) {
107ac068e01SHongtao Yu     StringRef CFGInfo = Input.substr(strlen("!CFGChecksum:")).trim();
108ac068e01SHongtao Yu     return !CFGInfo.getAsInteger(10, FunctionHash);
109ac068e01SHongtao Yu   }
110ac068e01SHongtao Yu 
1111410db70SWenlei He   if (Input.startswith("!Attributes:")) {
1121410db70SWenlei He     StringRef Attrib = Input.substr(strlen("!Attributes:")).trim();
1131410db70SWenlei He     return !Attrib.getAsInteger(10, Attributes);
1141410db70SWenlei He   }
1151410db70SWenlei He 
1161410db70SWenlei He   return false;
1171410db70SWenlei He }
1181410db70SWenlei He 
119ac068e01SHongtao Yu enum class LineType {
120ac068e01SHongtao Yu   CallSiteProfile,
121ac068e01SHongtao Yu   BodyProfile,
122ac068e01SHongtao Yu   Metadata,
123ac068e01SHongtao Yu };
124ac068e01SHongtao Yu 
1255f8f34e4SAdrian Prantl /// Parse \p Input as line sample.
1266722688eSDehao Chen ///
1276722688eSDehao Chen /// \param Input input line.
128ac068e01SHongtao Yu /// \param LineTy Type of this line.
1296722688eSDehao Chen /// \param Depth the depth of the inline stack.
1306722688eSDehao Chen /// \param NumSamples total samples of the line/inlined callsite.
1316722688eSDehao Chen /// \param LineOffset line offset to the start of the function.
1326722688eSDehao Chen /// \param Discriminator discriminator of the line.
1336722688eSDehao Chen /// \param TargetCountMap map from indirect call target to count.
134ac068e01SHongtao Yu /// \param FunctionHash the function's CFG hash, used by pseudo probe.
1356722688eSDehao Chen ///
1366722688eSDehao Chen /// returns true if parsing is successful.
137ac068e01SHongtao Yu static bool ParseLine(const StringRef &Input, LineType &LineTy, uint32_t &Depth,
13838be3330SDiego Novillo                       uint64_t &NumSamples, uint32_t &LineOffset,
13938be3330SDiego Novillo                       uint32_t &Discriminator, StringRef &CalleeName,
140ac068e01SHongtao Yu                       DenseMap<StringRef, uint64_t> &TargetCountMap,
1411410db70SWenlei He                       uint64_t &FunctionHash, uint32_t &Attributes) {
1426722688eSDehao Chen   for (Depth = 0; Input[Depth] == ' '; Depth++)
1436722688eSDehao Chen     ;
1446722688eSDehao Chen   if (Depth == 0)
1456722688eSDehao Chen     return false;
1466722688eSDehao Chen 
147ac068e01SHongtao Yu   if (Depth == 1 && Input[Depth] == '!') {
148ac068e01SHongtao Yu     LineTy = LineType::Metadata;
1491410db70SWenlei He     return parseMetadata(Input.substr(Depth), FunctionHash, Attributes);
150ac068e01SHongtao Yu   }
151ac068e01SHongtao Yu 
1526722688eSDehao Chen   size_t n1 = Input.find(':');
1536722688eSDehao Chen   StringRef Loc = Input.substr(Depth, n1 - Depth);
1546722688eSDehao Chen   size_t n2 = Loc.find('.');
1556722688eSDehao Chen   if (n2 == StringRef::npos) {
15610042412SDehao Chen     if (Loc.getAsInteger(10, LineOffset) || !isOffsetLegal(LineOffset))
1576722688eSDehao Chen       return false;
1586722688eSDehao Chen     Discriminator = 0;
1596722688eSDehao Chen   } else {
1606722688eSDehao Chen     if (Loc.substr(0, n2).getAsInteger(10, LineOffset))
1616722688eSDehao Chen       return false;
1626722688eSDehao Chen     if (Loc.substr(n2 + 1).getAsInteger(10, Discriminator))
1636722688eSDehao Chen       return false;
1646722688eSDehao Chen   }
1656722688eSDehao Chen 
1666722688eSDehao Chen   StringRef Rest = Input.substr(n1 + 2);
167551aaa24SKazu Hirata   if (isDigit(Rest[0])) {
168ac068e01SHongtao Yu     LineTy = LineType::BodyProfile;
1696722688eSDehao Chen     size_t n3 = Rest.find(' ');
1706722688eSDehao Chen     if (n3 == StringRef::npos) {
1716722688eSDehao Chen       if (Rest.getAsInteger(10, NumSamples))
1726722688eSDehao Chen         return false;
1736722688eSDehao Chen     } else {
1746722688eSDehao Chen       if (Rest.substr(0, n3).getAsInteger(10, NumSamples))
1756722688eSDehao Chen         return false;
1766722688eSDehao Chen     }
177984ab0f1SWei Mi     // Find call targets and their sample counts.
178984ab0f1SWei Mi     // Note: In some cases, there are symbols in the profile which are not
179984ab0f1SWei Mi     // mangled. To accommodate such cases, use colon + integer pairs as the
180984ab0f1SWei Mi     // anchor points.
181984ab0f1SWei Mi     // An example:
182984ab0f1SWei Mi     // _M_construct<char *>:1000 string_view<std::allocator<char> >:437
183984ab0f1SWei Mi     // ":1000" and ":437" are used as anchor points so the string above will
184984ab0f1SWei Mi     // be interpreted as
185984ab0f1SWei Mi     // target: _M_construct<char *>
186984ab0f1SWei Mi     // count: 1000
187984ab0f1SWei Mi     // target: string_view<std::allocator<char> >
188984ab0f1SWei Mi     // count: 437
1896722688eSDehao Chen     while (n3 != StringRef::npos) {
1906722688eSDehao Chen       n3 += Rest.substr(n3).find_first_not_of(' ');
1916722688eSDehao Chen       Rest = Rest.substr(n3);
192984ab0f1SWei Mi       n3 = Rest.find_first_of(':');
193984ab0f1SWei Mi       if (n3 == StringRef::npos || n3 == 0)
1946722688eSDehao Chen         return false;
195984ab0f1SWei Mi 
196984ab0f1SWei Mi       StringRef Target;
197984ab0f1SWei Mi       uint64_t count, n4;
198984ab0f1SWei Mi       while (true) {
199984ab0f1SWei Mi         // Get the segment after the current colon.
200984ab0f1SWei Mi         StringRef AfterColon = Rest.substr(n3 + 1);
201984ab0f1SWei Mi         // Get the target symbol before the current colon.
202984ab0f1SWei Mi         Target = Rest.substr(0, n3);
203984ab0f1SWei Mi         // Check if the word after the current colon is an integer.
204984ab0f1SWei Mi         n4 = AfterColon.find_first_of(' ');
205984ab0f1SWei Mi         n4 = (n4 != StringRef::npos) ? n3 + n4 + 1 : Rest.size();
206984ab0f1SWei Mi         StringRef WordAfterColon = Rest.substr(n3 + 1, n4 - n3 - 1);
207984ab0f1SWei Mi         if (!WordAfterColon.getAsInteger(10, count))
208984ab0f1SWei Mi           break;
209984ab0f1SWei Mi 
210984ab0f1SWei Mi         // Try to find the next colon.
211984ab0f1SWei Mi         uint64_t n5 = AfterColon.find_first_of(':');
212984ab0f1SWei Mi         if (n5 == StringRef::npos)
213984ab0f1SWei Mi           return false;
214984ab0f1SWei Mi         n3 += n5 + 1;
215984ab0f1SWei Mi       }
216984ab0f1SWei Mi 
217984ab0f1SWei Mi       // An anchor point is found. Save the {target, count} pair
218984ab0f1SWei Mi       TargetCountMap[Target] = count;
219984ab0f1SWei Mi       if (n4 == Rest.size())
220984ab0f1SWei Mi         break;
221984ab0f1SWei Mi       // Change n3 to the next blank space after colon + integer pair.
222984ab0f1SWei Mi       n3 = n4;
2236722688eSDehao Chen     }
2246722688eSDehao Chen   } else {
225ac068e01SHongtao Yu     LineTy = LineType::CallSiteProfile;
22638be3330SDiego Novillo     size_t n3 = Rest.find_last_of(':');
2276722688eSDehao Chen     CalleeName = Rest.substr(0, n3);
2286722688eSDehao Chen     if (Rest.substr(n3 + 1).getAsInteger(10, NumSamples))
2296722688eSDehao Chen       return false;
2306722688eSDehao Chen   }
2316722688eSDehao Chen   return true;
2326722688eSDehao Chen }
2336722688eSDehao Chen 
2345f8f34e4SAdrian Prantl /// Load samples from a text file.
235de1ab26fSDiego Novillo ///
236de1ab26fSDiego Novillo /// See the documentation at the top of the file for an explanation of
237de1ab26fSDiego Novillo /// the expected format.
238de1ab26fSDiego Novillo ///
239de1ab26fSDiego Novillo /// \returns true if the file was loaded successfully, false otherwise.
2408c8ec1f6SWei Mi std::error_code SampleProfileReaderText::readImpl() {
241c572e92cSDiego Novillo   line_iterator LineIt(*Buffer, /*SkipBlanks=*/true, '#');
24248dd080cSNathan Slingerland   sampleprof_error Result = sampleprof_error::success;
243de1ab26fSDiego Novillo 
244aae1ed8eSDiego Novillo   InlineCallStack InlineStack;
245ac068e01SHongtao Yu   uint32_t ProbeProfileCount = 0;
246ac068e01SHongtao Yu 
247ac068e01SHongtao Yu   // SeenMetadata tracks whether we have processed metadata for the current
248ac068e01SHongtao Yu   // top-level function profile.
249ac068e01SHongtao Yu   bool SeenMetadata = false;
2506722688eSDehao Chen 
251*6745ffe4SRong Xu   ProfileIsFS = ProfileIsFSDisciminator;
2526722688eSDehao Chen   for (; !LineIt.is_at_eof(); ++LineIt) {
2536722688eSDehao Chen     if ((*LineIt)[(*LineIt).find_first_not_of(' ')] == '#')
2546722688eSDehao Chen       continue;
255de1ab26fSDiego Novillo     // Read the header of each function.
256de1ab26fSDiego Novillo     //
257de1ab26fSDiego Novillo     // Note that for function identifiers we are actually expecting
258de1ab26fSDiego Novillo     // mangled names, but we may not always get them. This happens when
259de1ab26fSDiego Novillo     // the compiler decides not to emit the function (e.g., it was inlined
260de1ab26fSDiego Novillo     // and removed). In this case, the binary will not have the linkage
261de1ab26fSDiego Novillo     // name for the function, so the profiler will emit the function's
262de1ab26fSDiego Novillo     // unmangled name, which may contain characters like ':' and '>' in its
263de1ab26fSDiego Novillo     // name (member functions, templates, etc).
264de1ab26fSDiego Novillo     //
265de1ab26fSDiego Novillo     // The only requirement we place on the identifier, then, is that it
266de1ab26fSDiego Novillo     // should not begin with a number.
2676722688eSDehao Chen     if ((*LineIt)[0] != ' ') {
26838be3330SDiego Novillo       uint64_t NumSamples, NumHeadSamples;
2696722688eSDehao Chen       StringRef FName;
2706722688eSDehao Chen       if (!ParseHead(*LineIt, FName, NumSamples, NumHeadSamples)) {
2713376a787SDiego Novillo         reportError(LineIt.line_number(),
272de1ab26fSDiego Novillo                     "Expected 'mangled_name:NUM:NUM', found " + *LineIt);
273c572e92cSDiego Novillo         return sampleprof_error::malformed;
274de1ab26fSDiego Novillo       }
275ac068e01SHongtao Yu       SeenMetadata = false;
2766b989a17SWenlei He       SampleContext FContext(FName);
2776b989a17SWenlei He       if (FContext.hasContext())
2786b989a17SWenlei He         ++CSProfileCount;
2796b989a17SWenlei He       Profiles[FContext] = FunctionSamples();
2806b989a17SWenlei He       FunctionSamples &FProfile = Profiles[FContext];
2817e99bddfSHongtao Yu       FProfile.setName(FContext.getNameWithoutContext());
2826b989a17SWenlei He       FProfile.setContext(FContext);
28348dd080cSNathan Slingerland       MergeResult(Result, FProfile.addTotalSamples(NumSamples));
28448dd080cSNathan Slingerland       MergeResult(Result, FProfile.addHeadSamples(NumHeadSamples));
2856722688eSDehao Chen       InlineStack.clear();
2866722688eSDehao Chen       InlineStack.push_back(&FProfile);
2876722688eSDehao Chen     } else {
28838be3330SDiego Novillo       uint64_t NumSamples;
2896722688eSDehao Chen       StringRef FName;
29038be3330SDiego Novillo       DenseMap<StringRef, uint64_t> TargetCountMap;
29138be3330SDiego Novillo       uint32_t Depth, LineOffset, Discriminator;
292ac068e01SHongtao Yu       LineType LineTy;
2931410db70SWenlei He       uint64_t FunctionHash = 0;
2941410db70SWenlei He       uint32_t Attributes = 0;
295ac068e01SHongtao Yu       if (!ParseLine(*LineIt, LineTy, Depth, NumSamples, LineOffset,
2961410db70SWenlei He                      Discriminator, FName, TargetCountMap, FunctionHash,
2971410db70SWenlei He                      Attributes)) {
2983376a787SDiego Novillo         reportError(LineIt.line_number(),
2993376a787SDiego Novillo                     "Expected 'NUM[.NUM]: NUM[ mangled_name:NUM]*', found " +
3003376a787SDiego Novillo                         *LineIt);
301c572e92cSDiego Novillo         return sampleprof_error::malformed;
302de1ab26fSDiego Novillo       }
303ac068e01SHongtao Yu       if (SeenMetadata && LineTy != LineType::Metadata) {
304ac068e01SHongtao Yu         // Metadata must be put at the end of a function profile.
305ac068e01SHongtao Yu         reportError(LineIt.line_number(),
306ac068e01SHongtao Yu                     "Found non-metadata after metadata: " + *LineIt);
307ac068e01SHongtao Yu         return sampleprof_error::malformed;
308ac068e01SHongtao Yu       }
309*6745ffe4SRong Xu 
310*6745ffe4SRong Xu       // Here we handle FS discriminators.
311*6745ffe4SRong Xu       Discriminator &= getDiscriminatorMask();
312*6745ffe4SRong Xu 
3136722688eSDehao Chen       while (InlineStack.size() > Depth) {
3146722688eSDehao Chen         InlineStack.pop_back();
315c572e92cSDiego Novillo       }
316ac068e01SHongtao Yu       switch (LineTy) {
317ac068e01SHongtao Yu       case LineType::CallSiteProfile: {
3186722688eSDehao Chen         FunctionSamples &FSamples = InlineStack.back()->functionSamplesAt(
319adcd0268SBenjamin Kramer             LineLocation(LineOffset, Discriminator))[std::string(FName)];
32057d1dda5SDehao Chen         FSamples.setName(FName);
32148dd080cSNathan Slingerland         MergeResult(Result, FSamples.addTotalSamples(NumSamples));
3226722688eSDehao Chen         InlineStack.push_back(&FSamples);
323ac068e01SHongtao Yu         break;
324ac068e01SHongtao Yu       }
325ac068e01SHongtao Yu       case LineType::BodyProfile: {
3266722688eSDehao Chen         while (InlineStack.size() > Depth) {
3276722688eSDehao Chen           InlineStack.pop_back();
3286722688eSDehao Chen         }
3296722688eSDehao Chen         FunctionSamples &FProfile = *InlineStack.back();
3306722688eSDehao Chen         for (const auto &name_count : TargetCountMap) {
33148dd080cSNathan Slingerland           MergeResult(Result, FProfile.addCalledTargetSamples(
33248dd080cSNathan Slingerland                                   LineOffset, Discriminator, name_count.first,
33348dd080cSNathan Slingerland                                   name_count.second));
334c572e92cSDiego Novillo         }
33548dd080cSNathan Slingerland         MergeResult(Result, FProfile.addBodySamples(LineOffset, Discriminator,
33648dd080cSNathan Slingerland                                                     NumSamples));
337ac068e01SHongtao Yu         break;
338ac068e01SHongtao Yu       }
339ac068e01SHongtao Yu       case LineType::Metadata: {
340ac068e01SHongtao Yu         FunctionSamples &FProfile = *InlineStack.back();
3411410db70SWenlei He         if (FunctionHash) {
342ac068e01SHongtao Yu           FProfile.setFunctionHash(FunctionHash);
343ac068e01SHongtao Yu           ++ProbeProfileCount;
3441410db70SWenlei He         }
3451410db70SWenlei He         if (Attributes)
3461410db70SWenlei He           FProfile.getContext().setAllAttributes(Attributes);
347ac068e01SHongtao Yu         SeenMetadata = true;
348ac068e01SHongtao Yu         break;
349ac068e01SHongtao Yu       }
3506722688eSDehao Chen       }
351de1ab26fSDiego Novillo     }
352de1ab26fSDiego Novillo   }
3536b989a17SWenlei He 
3547e99bddfSHongtao Yu   assert((CSProfileCount == 0 || CSProfileCount == Profiles.size()) &&
3556b989a17SWenlei He          "Cannot have both context-sensitive and regular profile");
3566b989a17SWenlei He   ProfileIsCS = (CSProfileCount > 0);
357ac068e01SHongtao Yu   assert((ProbeProfileCount == 0 || ProbeProfileCount == Profiles.size()) &&
358ac068e01SHongtao Yu          "Cannot have both probe-based profiles and regular profiles");
359ac068e01SHongtao Yu   ProfileIsProbeBased = (ProbeProfileCount > 0);
360ac068e01SHongtao Yu   FunctionSamples::ProfileIsProbeBased = ProfileIsProbeBased;
3617e99bddfSHongtao Yu   FunctionSamples::ProfileIsCS = ProfileIsCS;
3626b989a17SWenlei He 
36340ee23dbSEaswaran Raman   if (Result == sampleprof_error::success)
36440ee23dbSEaswaran Raman     computeSummary();
365de1ab26fSDiego Novillo 
36648dd080cSNathan Slingerland   return Result;
367de1ab26fSDiego Novillo }
368de1ab26fSDiego Novillo 
3694f823667SNathan Slingerland bool SampleProfileReaderText::hasFormat(const MemoryBuffer &Buffer) {
3704f823667SNathan Slingerland   bool result = false;
3714f823667SNathan Slingerland 
3724f823667SNathan Slingerland   // Check that the first non-comment line is a valid function header.
3734f823667SNathan Slingerland   line_iterator LineIt(Buffer, /*SkipBlanks=*/true, '#');
3744f823667SNathan Slingerland   if (!LineIt.is_at_eof()) {
3754f823667SNathan Slingerland     if ((*LineIt)[0] != ' ') {
3764f823667SNathan Slingerland       uint64_t NumSamples, NumHeadSamples;
3774f823667SNathan Slingerland       StringRef FName;
3784f823667SNathan Slingerland       result = ParseHead(*LineIt, FName, NumSamples, NumHeadSamples);
3794f823667SNathan Slingerland     }
3804f823667SNathan Slingerland   }
3814f823667SNathan Slingerland 
3824f823667SNathan Slingerland   return result;
3834f823667SNathan Slingerland }
3844f823667SNathan Slingerland 
385d5336ae2SDiego Novillo template <typename T> ErrorOr<T> SampleProfileReaderBinary::readNumber() {
386c572e92cSDiego Novillo   unsigned NumBytesRead = 0;
387c572e92cSDiego Novillo   std::error_code EC;
388c572e92cSDiego Novillo   uint64_t Val = decodeULEB128(Data, &NumBytesRead);
389c572e92cSDiego Novillo 
390c572e92cSDiego Novillo   if (Val > std::numeric_limits<T>::max())
391c572e92cSDiego Novillo     EC = sampleprof_error::malformed;
392c572e92cSDiego Novillo   else if (Data + NumBytesRead > End)
393c572e92cSDiego Novillo     EC = sampleprof_error::truncated;
394c572e92cSDiego Novillo   else
395c572e92cSDiego Novillo     EC = sampleprof_error::success;
396c572e92cSDiego Novillo 
397c572e92cSDiego Novillo   if (EC) {
3983376a787SDiego Novillo     reportError(0, EC.message());
399c572e92cSDiego Novillo     return EC;
400c572e92cSDiego Novillo   }
401c572e92cSDiego Novillo 
402c572e92cSDiego Novillo   Data += NumBytesRead;
403c572e92cSDiego Novillo   return static_cast<T>(Val);
404c572e92cSDiego Novillo }
405c572e92cSDiego Novillo 
406c572e92cSDiego Novillo ErrorOr<StringRef> SampleProfileReaderBinary::readString() {
407c572e92cSDiego Novillo   std::error_code EC;
408c572e92cSDiego Novillo   StringRef Str(reinterpret_cast<const char *>(Data));
409c572e92cSDiego Novillo   if (Data + Str.size() + 1 > End) {
410c572e92cSDiego Novillo     EC = sampleprof_error::truncated;
4113376a787SDiego Novillo     reportError(0, EC.message());
412c572e92cSDiego Novillo     return EC;
413c572e92cSDiego Novillo   }
414c572e92cSDiego Novillo 
415c572e92cSDiego Novillo   Data += Str.size() + 1;
416c572e92cSDiego Novillo   return Str;
417c572e92cSDiego Novillo }
418c572e92cSDiego Novillo 
419a0c0857eSWei Mi template <typename T>
4206a14325dSWei Mi ErrorOr<T> SampleProfileReaderBinary::readUnencodedNumber() {
4216a14325dSWei Mi   std::error_code EC;
4226a14325dSWei Mi 
4236a14325dSWei Mi   if (Data + sizeof(T) > End) {
4246a14325dSWei Mi     EC = sampleprof_error::truncated;
4256a14325dSWei Mi     reportError(0, EC.message());
4266a14325dSWei Mi     return EC;
4276a14325dSWei Mi   }
4286a14325dSWei Mi 
4296a14325dSWei Mi   using namespace support;
4306a14325dSWei Mi   T Val = endian::readNext<T, little, unaligned>(Data);
4316a14325dSWei Mi   return Val;
4326a14325dSWei Mi }
4336a14325dSWei Mi 
4346a14325dSWei Mi template <typename T>
435a0c0857eSWei Mi inline ErrorOr<uint32_t> SampleProfileReaderBinary::readStringIndex(T &Table) {
436760c5a8fSDiego Novillo   std::error_code EC;
43738be3330SDiego Novillo   auto Idx = readNumber<uint32_t>();
438760c5a8fSDiego Novillo   if (std::error_code EC = Idx.getError())
439760c5a8fSDiego Novillo     return EC;
440a0c0857eSWei Mi   if (*Idx >= Table.size())
441760c5a8fSDiego Novillo     return sampleprof_error::truncated_name_table;
442a0c0857eSWei Mi   return *Idx;
443a0c0857eSWei Mi }
444a0c0857eSWei Mi 
445be907324SWei Mi ErrorOr<StringRef> SampleProfileReaderBinary::readStringFromTable() {
446a0c0857eSWei Mi   auto Idx = readStringIndex(NameTable);
447a0c0857eSWei Mi   if (std::error_code EC = Idx.getError())
448a0c0857eSWei Mi     return EC;
449a0c0857eSWei Mi 
450760c5a8fSDiego Novillo   return NameTable[*Idx];
451760c5a8fSDiego Novillo }
452760c5a8fSDiego Novillo 
45364e76853SWei Mi ErrorOr<StringRef> SampleProfileReaderExtBinaryBase::readStringFromTable() {
45464e76853SWei Mi   if (!FixedLengthMD5)
45564e76853SWei Mi     return SampleProfileReaderBinary::readStringFromTable();
45664e76853SWei Mi 
45764e76853SWei Mi   // read NameTable index.
45864e76853SWei Mi   auto Idx = readStringIndex(NameTable);
45964e76853SWei Mi   if (std::error_code EC = Idx.getError())
46064e76853SWei Mi     return EC;
46164e76853SWei Mi 
46264e76853SWei Mi   // Check whether the name to be accessed has been accessed before,
46364e76853SWei Mi   // if not, read it from memory directly.
46464e76853SWei Mi   StringRef &SR = NameTable[*Idx];
46564e76853SWei Mi   if (SR.empty()) {
46664e76853SWei Mi     const uint8_t *SavedData = Data;
46764e76853SWei Mi     Data = MD5NameMemStart + ((*Idx) * sizeof(uint64_t));
46864e76853SWei Mi     auto FID = readUnencodedNumber<uint64_t>();
46964e76853SWei Mi     if (std::error_code EC = FID.getError())
47064e76853SWei Mi       return EC;
47164e76853SWei Mi     // Save the string converted from uint64_t in MD5StringBuf. All the
47264e76853SWei Mi     // references to the name are all StringRefs refering to the string
47364e76853SWei Mi     // in MD5StringBuf.
47464e76853SWei Mi     MD5StringBuf->push_back(std::to_string(*FID));
47564e76853SWei Mi     SR = MD5StringBuf->back();
47664e76853SWei Mi     Data = SavedData;
47764e76853SWei Mi   }
47864e76853SWei Mi   return SR;
47964e76853SWei Mi }
48064e76853SWei Mi 
481a0c0857eSWei Mi ErrorOr<StringRef> SampleProfileReaderCompactBinary::readStringFromTable() {
482a0c0857eSWei Mi   auto Idx = readStringIndex(NameTable);
483a0c0857eSWei Mi   if (std::error_code EC = Idx.getError())
484a0c0857eSWei Mi     return EC;
485a0c0857eSWei Mi 
486a0c0857eSWei Mi   return StringRef(NameTable[*Idx]);
487a0c0857eSWei Mi }
488a0c0857eSWei Mi 
489a7f1e8efSDiego Novillo std::error_code
490a7f1e8efSDiego Novillo SampleProfileReaderBinary::readProfile(FunctionSamples &FProfile) {
491b93483dbSDiego Novillo   auto NumSamples = readNumber<uint64_t>();
492b93483dbSDiego Novillo   if (std::error_code EC = NumSamples.getError())
493c572e92cSDiego Novillo     return EC;
494b93483dbSDiego Novillo   FProfile.addTotalSamples(*NumSamples);
495c572e92cSDiego Novillo 
496c572e92cSDiego Novillo   // Read the samples in the body.
49738be3330SDiego Novillo   auto NumRecords = readNumber<uint32_t>();
498c572e92cSDiego Novillo   if (std::error_code EC = NumRecords.getError())
499c572e92cSDiego Novillo     return EC;
500a7f1e8efSDiego Novillo 
50138be3330SDiego Novillo   for (uint32_t I = 0; I < *NumRecords; ++I) {
502c572e92cSDiego Novillo     auto LineOffset = readNumber<uint64_t>();
503c572e92cSDiego Novillo     if (std::error_code EC = LineOffset.getError())
504c572e92cSDiego Novillo       return EC;
505c572e92cSDiego Novillo 
50610042412SDehao Chen     if (!isOffsetLegal(*LineOffset)) {
50710042412SDehao Chen       return std::error_code();
50810042412SDehao Chen     }
50910042412SDehao Chen 
510c572e92cSDiego Novillo     auto Discriminator = readNumber<uint64_t>();
511c572e92cSDiego Novillo     if (std::error_code EC = Discriminator.getError())
512c572e92cSDiego Novillo       return EC;
513c572e92cSDiego Novillo 
514c572e92cSDiego Novillo     auto NumSamples = readNumber<uint64_t>();
515c572e92cSDiego Novillo     if (std::error_code EC = NumSamples.getError())
516c572e92cSDiego Novillo       return EC;
517c572e92cSDiego Novillo 
51838be3330SDiego Novillo     auto NumCalls = readNumber<uint32_t>();
519c572e92cSDiego Novillo     if (std::error_code EC = NumCalls.getError())
520c572e92cSDiego Novillo       return EC;
521c572e92cSDiego Novillo 
522*6745ffe4SRong Xu     // Here we handle FS discriminators:
523*6745ffe4SRong Xu     uint32_t DiscriminatorVal = (*Discriminator) & getDiscriminatorMask();
524*6745ffe4SRong Xu 
52538be3330SDiego Novillo     for (uint32_t J = 0; J < *NumCalls; ++J) {
526760c5a8fSDiego Novillo       auto CalledFunction(readStringFromTable());
527c572e92cSDiego Novillo       if (std::error_code EC = CalledFunction.getError())
528c572e92cSDiego Novillo         return EC;
529c572e92cSDiego Novillo 
530c572e92cSDiego Novillo       auto CalledFunctionSamples = readNumber<uint64_t>();
531c572e92cSDiego Novillo       if (std::error_code EC = CalledFunctionSamples.getError())
532c572e92cSDiego Novillo         return EC;
533c572e92cSDiego Novillo 
534*6745ffe4SRong Xu       FProfile.addCalledTargetSamples(*LineOffset, DiscriminatorVal,
535a7f1e8efSDiego Novillo                                       *CalledFunction, *CalledFunctionSamples);
536c572e92cSDiego Novillo     }
537c572e92cSDiego Novillo 
538*6745ffe4SRong Xu     FProfile.addBodySamples(*LineOffset, DiscriminatorVal, *NumSamples);
539c572e92cSDiego Novillo   }
540a7f1e8efSDiego Novillo 
541a7f1e8efSDiego Novillo   // Read all the samples for inlined function calls.
54238be3330SDiego Novillo   auto NumCallsites = readNumber<uint32_t>();
543a7f1e8efSDiego Novillo   if (std::error_code EC = NumCallsites.getError())
544a7f1e8efSDiego Novillo     return EC;
545a7f1e8efSDiego Novillo 
54638be3330SDiego Novillo   for (uint32_t J = 0; J < *NumCallsites; ++J) {
547a7f1e8efSDiego Novillo     auto LineOffset = readNumber<uint64_t>();
548a7f1e8efSDiego Novillo     if (std::error_code EC = LineOffset.getError())
549a7f1e8efSDiego Novillo       return EC;
550a7f1e8efSDiego Novillo 
551a7f1e8efSDiego Novillo     auto Discriminator = readNumber<uint64_t>();
552a7f1e8efSDiego Novillo     if (std::error_code EC = Discriminator.getError())
553a7f1e8efSDiego Novillo       return EC;
554a7f1e8efSDiego Novillo 
555760c5a8fSDiego Novillo     auto FName(readStringFromTable());
556a7f1e8efSDiego Novillo     if (std::error_code EC = FName.getError())
557a7f1e8efSDiego Novillo       return EC;
558a7f1e8efSDiego Novillo 
559*6745ffe4SRong Xu     // Here we handle FS discriminators:
560*6745ffe4SRong Xu     uint32_t DiscriminatorVal = (*Discriminator) & getDiscriminatorMask();
561*6745ffe4SRong Xu 
5622c7ca9b5SDehao Chen     FunctionSamples &CalleeProfile = FProfile.functionSamplesAt(
563*6745ffe4SRong Xu         LineLocation(*LineOffset, DiscriminatorVal))[std::string(*FName)];
56457d1dda5SDehao Chen     CalleeProfile.setName(*FName);
565a7f1e8efSDiego Novillo     if (std::error_code EC = readProfile(CalleeProfile))
566a7f1e8efSDiego Novillo       return EC;
567a7f1e8efSDiego Novillo   }
568a7f1e8efSDiego Novillo 
569a7f1e8efSDiego Novillo   return sampleprof_error::success;
570a7f1e8efSDiego Novillo }
571a7f1e8efSDiego Novillo 
57209dcfe68SWei Mi std::error_code
57309dcfe68SWei Mi SampleProfileReaderBinary::readFuncProfile(const uint8_t *Start) {
57409dcfe68SWei Mi   Data = Start;
575b93483dbSDiego Novillo   auto NumHeadSamples = readNumber<uint64_t>();
576b93483dbSDiego Novillo   if (std::error_code EC = NumHeadSamples.getError())
577b93483dbSDiego Novillo     return EC;
578b93483dbSDiego Novillo 
579760c5a8fSDiego Novillo   auto FName(readStringFromTable());
580a7f1e8efSDiego Novillo   if (std::error_code EC = FName.getError())
581a7f1e8efSDiego Novillo     return EC;
582a7f1e8efSDiego Novillo 
5837e99bddfSHongtao Yu   SampleContext FContext(*FName);
5847e99bddfSHongtao Yu   Profiles[FContext] = FunctionSamples();
5857e99bddfSHongtao Yu   FunctionSamples &FProfile = Profiles[FContext];
5867e99bddfSHongtao Yu   FProfile.setName(FContext.getNameWithoutContext());
5877e99bddfSHongtao Yu   FProfile.setContext(FContext);
588b93483dbSDiego Novillo   FProfile.addHeadSamples(*NumHeadSamples);
589b93483dbSDiego Novillo 
5907e99bddfSHongtao Yu   if (FContext.hasContext())
5917e99bddfSHongtao Yu     CSProfileCount++;
5927e99bddfSHongtao Yu 
593a7f1e8efSDiego Novillo   if (std::error_code EC = readProfile(FProfile))
594a7f1e8efSDiego Novillo     return EC;
5956a14325dSWei Mi   return sampleprof_error::success;
596c572e92cSDiego Novillo }
597c572e92cSDiego Novillo 
5988c8ec1f6SWei Mi std::error_code SampleProfileReaderBinary::readImpl() {
599*6745ffe4SRong Xu   ProfileIsFS = ProfileIsFSDisciminator;
6006a14325dSWei Mi   while (!at_eof()) {
60109dcfe68SWei Mi     if (std::error_code EC = readFuncProfile(Data))
6026a14325dSWei Mi       return EC;
6036a14325dSWei Mi   }
6046a14325dSWei Mi 
6056a14325dSWei Mi   return sampleprof_error::success;
6066a14325dSWei Mi }
6076a14325dSWei Mi 
60893953d41SWei Mi std::error_code SampleProfileReaderExtBinaryBase::readOneSection(
609ebad6788SWei Mi     const uint8_t *Start, uint64_t Size, const SecHdrTableEntry &Entry) {
610077a9c70SWei Mi   Data = Start;
611b523790aSWei Mi   End = Start + Size;
612ebad6788SWei Mi   switch (Entry.Type) {
613be907324SWei Mi   case SecProfSummary:
614be907324SWei Mi     if (std::error_code EC = readSummary())
615be907324SWei Mi       return EC;
616b49eac71SWei Mi     if (hasSecFlag(Entry, SecProfSummaryFlags::SecFlagPartial))
617b49eac71SWei Mi       Summary->setPartialProfile(true);
618a5d30421SWenlei He     if (hasSecFlag(Entry, SecProfSummaryFlags::SecFlagFullContext))
619a5d30421SWenlei He       FunctionSamples::ProfileIsCS = ProfileIsCS = true;
620*6745ffe4SRong Xu     if (hasSecFlag(Entry, SecProfSummaryFlags::SecFlagFSDiscriminator))
621*6745ffe4SRong Xu       FunctionSamples::ProfileIsFS = ProfileIsFS = true;
622be907324SWei Mi     break;
62364e76853SWei Mi   case SecNameTable: {
62464e76853SWei Mi     FixedLengthMD5 =
62564e76853SWei Mi         hasSecFlag(Entry, SecNameTableFlags::SecFlagFixedLengthMD5);
62664e76853SWei Mi     bool UseMD5 = hasSecFlag(Entry, SecNameTableFlags::SecFlagMD5Name);
62764e76853SWei Mi     assert((!FixedLengthMD5 || UseMD5) &&
62864e76853SWei Mi            "If FixedLengthMD5 is true, UseMD5 has to be true");
629ee35784aSWei Mi     FunctionSamples::HasUniqSuffix =
630ee35784aSWei Mi         hasSecFlag(Entry, SecNameTableFlags::SecFlagUniqSuffix);
63164e76853SWei Mi     if (std::error_code EC = readNameTableSec(UseMD5))
632be907324SWei Mi       return EC;
633be907324SWei Mi     break;
63464e76853SWei Mi   }
635be907324SWei Mi   case SecLBRProfile:
63609dcfe68SWei Mi     if (std::error_code EC = readFuncProfiles())
637be907324SWei Mi       return EC;
638be907324SWei Mi     break;
63909dcfe68SWei Mi   case SecFuncOffsetTable:
64009dcfe68SWei Mi     if (std::error_code EC = readFuncOffsetTable())
641798e59b8SWei Mi       return EC;
642798e59b8SWei Mi     break;
6431410db70SWenlei He   case SecFuncMetadata: {
644ac068e01SHongtao Yu     ProfileIsProbeBased =
645ac068e01SHongtao Yu         hasSecFlag(Entry, SecFuncMetadataFlags::SecFlagIsProbeBased);
646ac068e01SHongtao Yu     FunctionSamples::ProfileIsProbeBased = ProfileIsProbeBased;
6471410db70SWenlei He     bool HasAttribute =
6481410db70SWenlei He         hasSecFlag(Entry, SecFuncMetadataFlags::SecFlagHasAttribute);
6491410db70SWenlei He     if (std::error_code EC = readFuncMetadata(HasAttribute))
650ac068e01SHongtao Yu       return EC;
651ac068e01SHongtao Yu     break;
6521410db70SWenlei He   }
65393953d41SWei Mi   case SecProfileSymbolList:
65493953d41SWei Mi     if (std::error_code EC = readProfileSymbolList())
65593953d41SWei Mi       return EC;
65693953d41SWei Mi     break;
657be907324SWei Mi   default:
65893953d41SWei Mi     if (std::error_code EC = readCustomSection(Entry))
65993953d41SWei Mi       return EC;
660077a9c70SWei Mi     break;
661be907324SWei Mi   }
662077a9c70SWei Mi   return sampleprof_error::success;
663077a9c70SWei Mi }
664077a9c70SWei Mi 
665ee35784aSWei Mi bool SampleProfileReaderExtBinaryBase::collectFuncsFromModule() {
666ee35784aSWei Mi   if (!M)
667ee35784aSWei Mi     return false;
66809dcfe68SWei Mi   FuncsToUse.clear();
669ee35784aSWei Mi   for (auto &F : *M)
67009dcfe68SWei Mi     FuncsToUse.insert(FunctionSamples::getCanonicalFnName(F));
671ee35784aSWei Mi   return true;
67209dcfe68SWei Mi }
67309dcfe68SWei Mi 
67493953d41SWei Mi std::error_code SampleProfileReaderExtBinaryBase::readFuncOffsetTable() {
675a906e3ecSWei Mi   // If there are more than one FuncOffsetTable, the profile read associated
676a906e3ecSWei Mi   // with previous FuncOffsetTable has to be done before next FuncOffsetTable
677a906e3ecSWei Mi   // is read.
678a906e3ecSWei Mi   FuncOffsetTable.clear();
679a906e3ecSWei Mi 
68009dcfe68SWei Mi   auto Size = readNumber<uint64_t>();
68109dcfe68SWei Mi   if (std::error_code EC = Size.getError())
68209dcfe68SWei Mi     return EC;
68309dcfe68SWei Mi 
68409dcfe68SWei Mi   FuncOffsetTable.reserve(*Size);
68509dcfe68SWei Mi   for (uint32_t I = 0; I < *Size; ++I) {
68609dcfe68SWei Mi     auto FName(readStringFromTable());
68709dcfe68SWei Mi     if (std::error_code EC = FName.getError())
68809dcfe68SWei Mi       return EC;
68909dcfe68SWei Mi 
69009dcfe68SWei Mi     auto Offset = readNumber<uint64_t>();
69109dcfe68SWei Mi     if (std::error_code EC = Offset.getError())
69209dcfe68SWei Mi       return EC;
69309dcfe68SWei Mi 
69409dcfe68SWei Mi     FuncOffsetTable[*FName] = *Offset;
69509dcfe68SWei Mi   }
69609dcfe68SWei Mi   return sampleprof_error::success;
69709dcfe68SWei Mi }
69809dcfe68SWei Mi 
69993953d41SWei Mi std::error_code SampleProfileReaderExtBinaryBase::readFuncProfiles() {
700ee35784aSWei Mi   // Collect functions used by current module if the Reader has been
701ee35784aSWei Mi   // given a module.
702ee35784aSWei Mi   // collectFuncsFromModule uses FunctionSamples::getCanonicalFnName
703ee35784aSWei Mi   // which will query FunctionSamples::HasUniqSuffix, so it has to be
704ee35784aSWei Mi   // called after FunctionSamples::HasUniqSuffix is set, i.e. after
705ee35784aSWei Mi   // NameTable section is read.
706ee35784aSWei Mi   bool LoadFuncsToBeUsed = collectFuncsFromModule();
707ee35784aSWei Mi 
708ee35784aSWei Mi   // When LoadFuncsToBeUsed is false, load all the function profiles.
70909dcfe68SWei Mi   const uint8_t *Start = Data;
710ee35784aSWei Mi   if (!LoadFuncsToBeUsed) {
71109dcfe68SWei Mi     while (Data < End) {
71209dcfe68SWei Mi       if (std::error_code EC = readFuncProfile(Data))
71309dcfe68SWei Mi         return EC;
71409dcfe68SWei Mi     }
71509dcfe68SWei Mi     assert(Data == End && "More data is read than expected");
7167e99bddfSHongtao Yu   } else {
717ee35784aSWei Mi     // Load function profiles on demand.
7188c8ec1f6SWei Mi     if (Remapper) {
71909dcfe68SWei Mi       for (auto Name : FuncsToUse) {
7208c8ec1f6SWei Mi         Remapper->insert(Name);
7218c8ec1f6SWei Mi       }
7228c8ec1f6SWei Mi     }
7238c8ec1f6SWei Mi 
724ebad6788SWei Mi     if (useMD5()) {
725ebad6788SWei Mi       for (auto Name : FuncsToUse) {
726ebad6788SWei Mi         auto GUID = std::to_string(MD5Hash(Name));
727ebad6788SWei Mi         auto iter = FuncOffsetTable.find(StringRef(GUID));
728ebad6788SWei Mi         if (iter == FuncOffsetTable.end())
729ebad6788SWei Mi           continue;
730ebad6788SWei Mi         const uint8_t *FuncProfileAddr = Start + iter->second;
731ebad6788SWei Mi         assert(FuncProfileAddr < End && "out of LBRProfile section");
732ebad6788SWei Mi         if (std::error_code EC = readFuncProfile(FuncProfileAddr))
733ebad6788SWei Mi           return EC;
734ebad6788SWei Mi       }
735a5d30421SWenlei He     } else if (FunctionSamples::ProfileIsCS) {
736a5d30421SWenlei He       // Compute the ordered set of names, so we can
737a5d30421SWenlei He       // get all context profiles under a subtree by
738a5d30421SWenlei He       // iterating through the ordered names.
739a5d30421SWenlei He       struct Comparer {
740a5d30421SWenlei He         // Ignore the closing ']' when ordering context
741a5d30421SWenlei He         bool operator()(const StringRef &L, const StringRef &R) const {
742a5d30421SWenlei He           return L.substr(0, L.size() - 1) < R.substr(0, R.size() - 1);
743a5d30421SWenlei He         }
744a5d30421SWenlei He       };
745a5d30421SWenlei He       std::set<StringRef, Comparer> OrderedNames;
746a5d30421SWenlei He       for (auto Name : FuncOffsetTable) {
747a5d30421SWenlei He         OrderedNames.insert(Name.first);
748a5d30421SWenlei He       }
749a5d30421SWenlei He 
750a5d30421SWenlei He       // For each function in current module, load all
751a5d30421SWenlei He       // context profiles for the function.
752a5d30421SWenlei He       for (auto NameOffset : FuncOffsetTable) {
753a5d30421SWenlei He         StringRef ContextName = NameOffset.first;
754a5d30421SWenlei He         SampleContext FContext(ContextName);
755a5d30421SWenlei He         auto FuncName = FContext.getNameWithoutContext();
756a5d30421SWenlei He         if (!FuncsToUse.count(FuncName) &&
757a5d30421SWenlei He             (!Remapper || !Remapper->exist(FuncName)))
758a5d30421SWenlei He           continue;
759a5d30421SWenlei He 
760a5d30421SWenlei He         // For each context profile we need, try to load
761a5d30421SWenlei He         // all context profile in the subtree. This can
762a5d30421SWenlei He         // help profile guided importing for ThinLTO.
763a5d30421SWenlei He         auto It = OrderedNames.find(ContextName);
764a5d30421SWenlei He         while (It != OrderedNames.end() &&
765a5d30421SWenlei He                It->startswith(ContextName.substr(0, ContextName.size() - 1))) {
766a5d30421SWenlei He           const uint8_t *FuncProfileAddr = Start + FuncOffsetTable[*It];
767a5d30421SWenlei He           assert(FuncProfileAddr < End && "out of LBRProfile section");
768a5d30421SWenlei He           if (std::error_code EC = readFuncProfile(FuncProfileAddr))
769a5d30421SWenlei He             return EC;
770a5d30421SWenlei He           // Remove loaded context profile so we won't
771a5d30421SWenlei He           // load it repeatedly.
772a5d30421SWenlei He           It = OrderedNames.erase(It);
773a5d30421SWenlei He         }
774a5d30421SWenlei He       }
775ebad6788SWei Mi     } else {
7768c8ec1f6SWei Mi       for (auto NameOffset : FuncOffsetTable) {
7777e99bddfSHongtao Yu         SampleContext FContext(NameOffset.first);
7787e99bddfSHongtao Yu         auto FuncName = FContext.getNameWithoutContext();
7798c8ec1f6SWei Mi         if (!FuncsToUse.count(FuncName) &&
7808c8ec1f6SWei Mi             (!Remapper || !Remapper->exist(FuncName)))
78109dcfe68SWei Mi           continue;
7828c8ec1f6SWei Mi         const uint8_t *FuncProfileAddr = Start + NameOffset.second;
78309dcfe68SWei Mi         assert(FuncProfileAddr < End && "out of LBRProfile section");
78409dcfe68SWei Mi         if (std::error_code EC = readFuncProfile(FuncProfileAddr))
78509dcfe68SWei Mi           return EC;
78609dcfe68SWei Mi       }
787ebad6788SWei Mi     }
78809dcfe68SWei Mi     Data = End;
7897e99bddfSHongtao Yu   }
7907e99bddfSHongtao Yu   assert((CSProfileCount == 0 || CSProfileCount == Profiles.size()) &&
7917e99bddfSHongtao Yu          "Cannot have both context-sensitive and regular profile");
792a5d30421SWenlei He   assert(ProfileIsCS == (CSProfileCount > 0) &&
793a5d30421SWenlei He          "Section flag should be consistent with actual profile");
79409dcfe68SWei Mi   return sampleprof_error::success;
79509dcfe68SWei Mi }
79609dcfe68SWei Mi 
79793953d41SWei Mi std::error_code SampleProfileReaderExtBinaryBase::readProfileSymbolList() {
798b523790aSWei Mi   if (!ProfSymList)
799b523790aSWei Mi     ProfSymList = std::make_unique<ProfileSymbolList>();
800b523790aSWei Mi 
80109dcfe68SWei Mi   if (std::error_code EC = ProfSymList->read(Data, End - Data))
802798e59b8SWei Mi     return EC;
803798e59b8SWei Mi 
80409dcfe68SWei Mi   Data = End;
805b523790aSWei Mi   return sampleprof_error::success;
806b523790aSWei Mi }
807b523790aSWei Mi 
808b523790aSWei Mi std::error_code SampleProfileReaderExtBinaryBase::decompressSection(
809b523790aSWei Mi     const uint8_t *SecStart, const uint64_t SecSize,
810b523790aSWei Mi     const uint8_t *&DecompressBuf, uint64_t &DecompressBufSize) {
811b523790aSWei Mi   Data = SecStart;
812b523790aSWei Mi   End = SecStart + SecSize;
813b523790aSWei Mi   auto DecompressSize = readNumber<uint64_t>();
814b523790aSWei Mi   if (std::error_code EC = DecompressSize.getError())
815b523790aSWei Mi     return EC;
816b523790aSWei Mi   DecompressBufSize = *DecompressSize;
817b523790aSWei Mi 
818798e59b8SWei Mi   auto CompressSize = readNumber<uint64_t>();
819798e59b8SWei Mi   if (std::error_code EC = CompressSize.getError())
820798e59b8SWei Mi     return EC;
821798e59b8SWei Mi 
822b523790aSWei Mi   if (!llvm::zlib::isAvailable())
823b523790aSWei Mi     return sampleprof_error::zlib_unavailable;
824798e59b8SWei Mi 
825b523790aSWei Mi   StringRef CompressedStrings(reinterpret_cast<const char *>(Data),
826b523790aSWei Mi                               *CompressSize);
827b523790aSWei Mi   char *Buffer = Allocator.Allocate<char>(DecompressBufSize);
828283df8cfSWei Mi   size_t UCSize = DecompressBufSize;
829b523790aSWei Mi   llvm::Error E =
830283df8cfSWei Mi       zlib::uncompress(CompressedStrings, Buffer, UCSize);
831b523790aSWei Mi   if (E)
832b523790aSWei Mi     return sampleprof_error::uncompress_failed;
833b523790aSWei Mi   DecompressBuf = reinterpret_cast<const uint8_t *>(Buffer);
834798e59b8SWei Mi   return sampleprof_error::success;
835798e59b8SWei Mi }
836798e59b8SWei Mi 
8378c8ec1f6SWei Mi std::error_code SampleProfileReaderExtBinaryBase::readImpl() {
838077a9c70SWei Mi   const uint8_t *BufStart =
839077a9c70SWei Mi       reinterpret_cast<const uint8_t *>(Buffer->getBufferStart());
840077a9c70SWei Mi 
841077a9c70SWei Mi   for (auto &Entry : SecHdrTable) {
842077a9c70SWei Mi     // Skip empty section.
843077a9c70SWei Mi     if (!Entry.Size)
844077a9c70SWei Mi       continue;
845b523790aSWei Mi 
84621b1ad03SWei Mi     // Skip sections without context when SkipFlatProf is true.
84721b1ad03SWei Mi     if (SkipFlatProf && hasSecFlag(Entry, SecCommonFlags::SecFlagFlat))
84821b1ad03SWei Mi       continue;
84921b1ad03SWei Mi 
850077a9c70SWei Mi     const uint8_t *SecStart = BufStart + Entry.Offset;
851b523790aSWei Mi     uint64_t SecSize = Entry.Size;
852b523790aSWei Mi 
853b523790aSWei Mi     // If the section is compressed, decompress it into a buffer
854b523790aSWei Mi     // DecompressBuf before reading the actual data. The pointee of
855b523790aSWei Mi     // 'Data' will be changed to buffer hold by DecompressBuf
856b523790aSWei Mi     // temporarily when reading the actual data.
857ebad6788SWei Mi     bool isCompressed = hasSecFlag(Entry, SecCommonFlags::SecFlagCompress);
858b523790aSWei Mi     if (isCompressed) {
859b523790aSWei Mi       const uint8_t *DecompressBuf;
860b523790aSWei Mi       uint64_t DecompressBufSize;
861b523790aSWei Mi       if (std::error_code EC = decompressSection(
862b523790aSWei Mi               SecStart, SecSize, DecompressBuf, DecompressBufSize))
863077a9c70SWei Mi         return EC;
864b523790aSWei Mi       SecStart = DecompressBuf;
865b523790aSWei Mi       SecSize = DecompressBufSize;
866b523790aSWei Mi     }
867b523790aSWei Mi 
868ebad6788SWei Mi     if (std::error_code EC = readOneSection(SecStart, SecSize, Entry))
869b523790aSWei Mi       return EC;
870b523790aSWei Mi     if (Data != SecStart + SecSize)
871be907324SWei Mi       return sampleprof_error::malformed;
872b523790aSWei Mi 
873b523790aSWei Mi     // Change the pointee of 'Data' from DecompressBuf to original Buffer.
874b523790aSWei Mi     if (isCompressed) {
875b523790aSWei Mi       Data = BufStart + Entry.Offset;
876b523790aSWei Mi       End = BufStart + Buffer->getBufferSize();
877b523790aSWei Mi     }
878be907324SWei Mi   }
879be907324SWei Mi 
880be907324SWei Mi   return sampleprof_error::success;
881be907324SWei Mi }
882be907324SWei Mi 
8838c8ec1f6SWei Mi std::error_code SampleProfileReaderCompactBinary::readImpl() {
884ee35784aSWei Mi   // Collect functions used by current module if the Reader has been
885ee35784aSWei Mi   // given a module.
886ee35784aSWei Mi   bool LoadFuncsToBeUsed = collectFuncsFromModule();
887*6745ffe4SRong Xu   ProfileIsFS = ProfileIsFSDisciminator;
888d3289544SWenlei He   std::vector<uint64_t> OffsetsToUse;
889ee35784aSWei Mi   if (!LoadFuncsToBeUsed) {
890ee35784aSWei Mi     // load all the function profiles.
891d3289544SWenlei He     for (auto FuncEntry : FuncOffsetTable) {
892d3289544SWenlei He       OffsetsToUse.push_back(FuncEntry.second);
893d3289544SWenlei He     }
894ee35784aSWei Mi   } else {
895ee35784aSWei Mi     // load function profiles on demand.
8966a14325dSWei Mi     for (auto Name : FuncsToUse) {
8976a14325dSWei Mi       auto GUID = std::to_string(MD5Hash(Name));
8986a14325dSWei Mi       auto iter = FuncOffsetTable.find(StringRef(GUID));
8996a14325dSWei Mi       if (iter == FuncOffsetTable.end())
9006a14325dSWei Mi         continue;
901d3289544SWenlei He       OffsetsToUse.push_back(iter->second);
902d3289544SWenlei He     }
903d3289544SWenlei He   }
904d3289544SWenlei He 
905d3289544SWenlei He   for (auto Offset : OffsetsToUse) {
9066a14325dSWei Mi     const uint8_t *SavedData = Data;
90709dcfe68SWei Mi     if (std::error_code EC = readFuncProfile(
90809dcfe68SWei Mi             reinterpret_cast<const uint8_t *>(Buffer->getBufferStart()) +
90909dcfe68SWei Mi             Offset))
9106a14325dSWei Mi       return EC;
9116a14325dSWei Mi     Data = SavedData;
9126a14325dSWei Mi   }
913c572e92cSDiego Novillo   return sampleprof_error::success;
914c572e92cSDiego Novillo }
915c572e92cSDiego Novillo 
916a0c0857eSWei Mi std::error_code SampleProfileReaderRawBinary::verifySPMagic(uint64_t Magic) {
917a0c0857eSWei Mi   if (Magic == SPMagic())
918a0c0857eSWei Mi     return sampleprof_error::success;
919a0c0857eSWei Mi   return sampleprof_error::bad_magic;
920a0c0857eSWei Mi }
921a0c0857eSWei Mi 
922be907324SWei Mi std::error_code SampleProfileReaderExtBinary::verifySPMagic(uint64_t Magic) {
923be907324SWei Mi   if (Magic == SPMagic(SPF_Ext_Binary))
924be907324SWei Mi     return sampleprof_error::success;
925be907324SWei Mi   return sampleprof_error::bad_magic;
926be907324SWei Mi }
927be907324SWei Mi 
928a0c0857eSWei Mi std::error_code
929a0c0857eSWei Mi SampleProfileReaderCompactBinary::verifySPMagic(uint64_t Magic) {
930a0c0857eSWei Mi   if (Magic == SPMagic(SPF_Compact_Binary))
931a0c0857eSWei Mi     return sampleprof_error::success;
932a0c0857eSWei Mi   return sampleprof_error::bad_magic;
933a0c0857eSWei Mi }
934a0c0857eSWei Mi 
935be907324SWei Mi std::error_code SampleProfileReaderBinary::readNameTable() {
936a0c0857eSWei Mi   auto Size = readNumber<uint32_t>();
937a0c0857eSWei Mi   if (std::error_code EC = Size.getError())
938a0c0857eSWei Mi     return EC;
939a906e3ecSWei Mi   NameTable.reserve(*Size + NameTable.size());
940a0c0857eSWei Mi   for (uint32_t I = 0; I < *Size; ++I) {
941a0c0857eSWei Mi     auto Name(readString());
942a0c0857eSWei Mi     if (std::error_code EC = Name.getError())
943a0c0857eSWei Mi       return EC;
944a0c0857eSWei Mi     NameTable.push_back(*Name);
945a0c0857eSWei Mi   }
946a0c0857eSWei Mi 
947a0c0857eSWei Mi   return sampleprof_error::success;
948a0c0857eSWei Mi }
949a0c0857eSWei Mi 
95093953d41SWei Mi std::error_code SampleProfileReaderExtBinaryBase::readMD5NameTable() {
951ebad6788SWei Mi   auto Size = readNumber<uint64_t>();
952ebad6788SWei Mi   if (std::error_code EC = Size.getError())
953ebad6788SWei Mi     return EC;
954ebad6788SWei Mi   MD5StringBuf = std::make_unique<std::vector<std::string>>();
955ebad6788SWei Mi   MD5StringBuf->reserve(*Size);
95664e76853SWei Mi   if (FixedLengthMD5) {
95764e76853SWei Mi     // Preallocate and initialize NameTable so we can check whether a name
95864e76853SWei Mi     // index has been read before by checking whether the element in the
95964e76853SWei Mi     // NameTable is empty, meanwhile readStringIndex can do the boundary
96064e76853SWei Mi     // check using the size of NameTable.
96164e76853SWei Mi     NameTable.resize(*Size + NameTable.size());
96264e76853SWei Mi 
96364e76853SWei Mi     MD5NameMemStart = Data;
96464e76853SWei Mi     Data = Data + (*Size) * sizeof(uint64_t);
96564e76853SWei Mi     return sampleprof_error::success;
96664e76853SWei Mi   }
96764e76853SWei Mi   NameTable.reserve(*Size);
968ebad6788SWei Mi   for (uint32_t I = 0; I < *Size; ++I) {
969ebad6788SWei Mi     auto FID = readNumber<uint64_t>();
970ebad6788SWei Mi     if (std::error_code EC = FID.getError())
971ebad6788SWei Mi       return EC;
972ebad6788SWei Mi     MD5StringBuf->push_back(std::to_string(*FID));
973ebad6788SWei Mi     // NameTable is a vector of StringRef. Here it is pushing back a
974ebad6788SWei Mi     // StringRef initialized with the last string in MD5stringBuf.
975ebad6788SWei Mi     NameTable.push_back(MD5StringBuf->back());
976ebad6788SWei Mi   }
977ebad6788SWei Mi   return sampleprof_error::success;
978ebad6788SWei Mi }
979ebad6788SWei Mi 
98093953d41SWei Mi std::error_code SampleProfileReaderExtBinaryBase::readNameTableSec(bool IsMD5) {
981ebad6788SWei Mi   if (IsMD5)
982ebad6788SWei Mi     return readMD5NameTable();
983ebad6788SWei Mi   return SampleProfileReaderBinary::readNameTable();
984ebad6788SWei Mi }
985ebad6788SWei Mi 
9861410db70SWenlei He std::error_code
9871410db70SWenlei He SampleProfileReaderExtBinaryBase::readFuncMetadata(bool ProfileHasAttribute) {
988224fee82SHongtao Yu   while (Data < End) {
989ac068e01SHongtao Yu     auto FName(readStringFromTable());
990ac068e01SHongtao Yu     if (std::error_code EC = FName.getError())
991ac068e01SHongtao Yu       return EC;
992ac068e01SHongtao Yu 
9931410db70SWenlei He     SampleContext FContext(*FName);
9941410db70SWenlei He     bool ProfileInMap = Profiles.count(FContext);
9951410db70SWenlei He 
9961410db70SWenlei He     if (ProfileIsProbeBased) {
997ac068e01SHongtao Yu       auto Checksum = readNumber<uint64_t>();
998ac068e01SHongtao Yu       if (std::error_code EC = Checksum.getError())
999ac068e01SHongtao Yu         return EC;
10001410db70SWenlei He       if (ProfileInMap)
10017e99bddfSHongtao Yu         Profiles[FContext].setFunctionHash(*Checksum);
1002ac068e01SHongtao Yu     }
1003224fee82SHongtao Yu 
10041410db70SWenlei He     if (ProfileHasAttribute) {
10051410db70SWenlei He       auto Attributes = readNumber<uint32_t>();
10061410db70SWenlei He       if (std::error_code EC = Attributes.getError())
10071410db70SWenlei He         return EC;
10081410db70SWenlei He       if (ProfileInMap)
10091410db70SWenlei He         Profiles[FContext].getContext().setAllAttributes(*Attributes);
10101410db70SWenlei He     }
10111410db70SWenlei He   }
10121410db70SWenlei He 
1013224fee82SHongtao Yu   assert(Data == End && "More data is read than expected");
1014ac068e01SHongtao Yu   return sampleprof_error::success;
1015ac068e01SHongtao Yu }
1016ac068e01SHongtao Yu 
1017a0c0857eSWei Mi std::error_code SampleProfileReaderCompactBinary::readNameTable() {
1018a0c0857eSWei Mi   auto Size = readNumber<uint64_t>();
1019a0c0857eSWei Mi   if (std::error_code EC = Size.getError())
1020a0c0857eSWei Mi     return EC;
1021a0c0857eSWei Mi   NameTable.reserve(*Size);
1022a0c0857eSWei Mi   for (uint32_t I = 0; I < *Size; ++I) {
1023a0c0857eSWei Mi     auto FID = readNumber<uint64_t>();
1024a0c0857eSWei Mi     if (std::error_code EC = FID.getError())
1025a0c0857eSWei Mi       return EC;
1026a0c0857eSWei Mi     NameTable.push_back(std::to_string(*FID));
1027a0c0857eSWei Mi   }
1028a0c0857eSWei Mi   return sampleprof_error::success;
1029a0c0857eSWei Mi }
1030a0c0857eSWei Mi 
1031a906e3ecSWei Mi std::error_code
1032a906e3ecSWei Mi SampleProfileReaderExtBinaryBase::readSecHdrTableEntry(uint32_t Idx) {
1033be907324SWei Mi   SecHdrTableEntry Entry;
1034be907324SWei Mi   auto Type = readUnencodedNumber<uint64_t>();
1035be907324SWei Mi   if (std::error_code EC = Type.getError())
1036be907324SWei Mi     return EC;
1037be907324SWei Mi   Entry.Type = static_cast<SecType>(*Type);
1038c572e92cSDiego Novillo 
1039b523790aSWei Mi   auto Flags = readUnencodedNumber<uint64_t>();
1040b523790aSWei Mi   if (std::error_code EC = Flags.getError())
1041be907324SWei Mi     return EC;
1042b523790aSWei Mi   Entry.Flags = *Flags;
1043be907324SWei Mi 
1044be907324SWei Mi   auto Offset = readUnencodedNumber<uint64_t>();
1045be907324SWei Mi   if (std::error_code EC = Offset.getError())
1046be907324SWei Mi     return EC;
1047be907324SWei Mi   Entry.Offset = *Offset;
1048be907324SWei Mi 
1049be907324SWei Mi   auto Size = readUnencodedNumber<uint64_t>();
1050be907324SWei Mi   if (std::error_code EC = Size.getError())
1051be907324SWei Mi     return EC;
1052be907324SWei Mi   Entry.Size = *Size;
1053be907324SWei Mi 
1054a906e3ecSWei Mi   Entry.LayoutIndex = Idx;
1055be907324SWei Mi   SecHdrTable.push_back(std::move(Entry));
1056be907324SWei Mi   return sampleprof_error::success;
1057be907324SWei Mi }
1058be907324SWei Mi 
1059be907324SWei Mi std::error_code SampleProfileReaderExtBinaryBase::readSecHdrTable() {
1060be907324SWei Mi   auto EntryNum = readUnencodedNumber<uint64_t>();
1061be907324SWei Mi   if (std::error_code EC = EntryNum.getError())
1062be907324SWei Mi     return EC;
1063be907324SWei Mi 
1064be907324SWei Mi   for (uint32_t i = 0; i < (*EntryNum); i++)
1065a906e3ecSWei Mi     if (std::error_code EC = readSecHdrTableEntry(i))
1066be907324SWei Mi       return EC;
1067be907324SWei Mi 
1068be907324SWei Mi   return sampleprof_error::success;
1069be907324SWei Mi }
1070be907324SWei Mi 
1071be907324SWei Mi std::error_code SampleProfileReaderExtBinaryBase::readHeader() {
1072be907324SWei Mi   const uint8_t *BufStart =
1073be907324SWei Mi       reinterpret_cast<const uint8_t *>(Buffer->getBufferStart());
1074be907324SWei Mi   Data = BufStart;
1075be907324SWei Mi   End = BufStart + Buffer->getBufferSize();
1076be907324SWei Mi 
1077be907324SWei Mi   if (std::error_code EC = readMagicIdent())
1078be907324SWei Mi     return EC;
1079be907324SWei Mi 
1080be907324SWei Mi   if (std::error_code EC = readSecHdrTable())
1081be907324SWei Mi     return EC;
1082be907324SWei Mi 
1083be907324SWei Mi   return sampleprof_error::success;
1084be907324SWei Mi }
1085be907324SWei Mi 
1086eee532cdSWei Mi uint64_t SampleProfileReaderExtBinaryBase::getSectionSize(SecType Type) {
1087a906e3ecSWei Mi   uint64_t Size = 0;
1088eee532cdSWei Mi   for (auto &Entry : SecHdrTable) {
1089eee532cdSWei Mi     if (Entry.Type == Type)
1090a906e3ecSWei Mi       Size += Entry.Size;
1091eee532cdSWei Mi   }
1092a906e3ecSWei Mi   return Size;
1093eee532cdSWei Mi }
1094eee532cdSWei Mi 
1095eee532cdSWei Mi uint64_t SampleProfileReaderExtBinaryBase::getFileSize() {
109609dcfe68SWei Mi   // Sections in SecHdrTable is not necessarily in the same order as
109709dcfe68SWei Mi   // sections in the profile because section like FuncOffsetTable needs
109809dcfe68SWei Mi   // to be written after section LBRProfile but needs to be read before
109909dcfe68SWei Mi   // section LBRProfile, so we cannot simply use the last entry in
110009dcfe68SWei Mi   // SecHdrTable to calculate the file size.
110109dcfe68SWei Mi   uint64_t FileSize = 0;
110209dcfe68SWei Mi   for (auto &Entry : SecHdrTable) {
110309dcfe68SWei Mi     FileSize = std::max(Entry.Offset + Entry.Size, FileSize);
110409dcfe68SWei Mi   }
110509dcfe68SWei Mi   return FileSize;
1106eee532cdSWei Mi }
1107eee532cdSWei Mi 
1108b49eac71SWei Mi static std::string getSecFlagsStr(const SecHdrTableEntry &Entry) {
1109b49eac71SWei Mi   std::string Flags;
1110b49eac71SWei Mi   if (hasSecFlag(Entry, SecCommonFlags::SecFlagCompress))
1111b49eac71SWei Mi     Flags.append("{compressed,");
1112b49eac71SWei Mi   else
1113b49eac71SWei Mi     Flags.append("{");
1114b49eac71SWei Mi 
111521b1ad03SWei Mi   if (hasSecFlag(Entry, SecCommonFlags::SecFlagFlat))
111621b1ad03SWei Mi     Flags.append("flat,");
111721b1ad03SWei Mi 
1118b49eac71SWei Mi   switch (Entry.Type) {
1119b49eac71SWei Mi   case SecNameTable:
112064e76853SWei Mi     if (hasSecFlag(Entry, SecNameTableFlags::SecFlagFixedLengthMD5))
112164e76853SWei Mi       Flags.append("fixlenmd5,");
112264e76853SWei Mi     else if (hasSecFlag(Entry, SecNameTableFlags::SecFlagMD5Name))
1123b49eac71SWei Mi       Flags.append("md5,");
1124ee35784aSWei Mi     if (hasSecFlag(Entry, SecNameTableFlags::SecFlagUniqSuffix))
1125ee35784aSWei Mi       Flags.append("uniq,");
1126b49eac71SWei Mi     break;
1127b49eac71SWei Mi   case SecProfSummary:
1128b49eac71SWei Mi     if (hasSecFlag(Entry, SecProfSummaryFlags::SecFlagPartial))
1129b49eac71SWei Mi       Flags.append("partial,");
1130a5d30421SWenlei He     if (hasSecFlag(Entry, SecProfSummaryFlags::SecFlagFullContext))
1131a5d30421SWenlei He       Flags.append("context,");
1132*6745ffe4SRong Xu     if (hasSecFlag(Entry, SecProfSummaryFlags::SecFlagFSDiscriminator))
1133*6745ffe4SRong Xu       Flags.append("fs-discriminator,");
1134b49eac71SWei Mi     break;
1135b49eac71SWei Mi   default:
1136b49eac71SWei Mi     break;
1137b49eac71SWei Mi   }
1138b49eac71SWei Mi   char &last = Flags.back();
1139b49eac71SWei Mi   if (last == ',')
1140b49eac71SWei Mi     last = '}';
1141b49eac71SWei Mi   else
1142b49eac71SWei Mi     Flags.append("}");
1143b49eac71SWei Mi   return Flags;
1144b49eac71SWei Mi }
1145b49eac71SWei Mi 
1146eee532cdSWei Mi bool SampleProfileReaderExtBinaryBase::dumpSectionInfo(raw_ostream &OS) {
1147eee532cdSWei Mi   uint64_t TotalSecsSize = 0;
1148eee532cdSWei Mi   for (auto &Entry : SecHdrTable) {
1149eee532cdSWei Mi     OS << getSecName(Entry.Type) << " - Offset: " << Entry.Offset
1150b49eac71SWei Mi        << ", Size: " << Entry.Size << ", Flags: " << getSecFlagsStr(Entry)
1151b49eac71SWei Mi        << "\n";
1152b49eac71SWei Mi     ;
1153a906e3ecSWei Mi     TotalSecsSize += Entry.Size;
1154eee532cdSWei Mi   }
1155eee532cdSWei Mi   uint64_t HeaderSize = SecHdrTable.front().Offset;
1156eee532cdSWei Mi   assert(HeaderSize + TotalSecsSize == getFileSize() &&
1157eee532cdSWei Mi          "Size of 'header + sections' doesn't match the total size of profile");
1158eee532cdSWei Mi 
1159eee532cdSWei Mi   OS << "Header Size: " << HeaderSize << "\n";
1160eee532cdSWei Mi   OS << "Total Sections Size: " << TotalSecsSize << "\n";
1161eee532cdSWei Mi   OS << "File Size: " << getFileSize() << "\n";
1162eee532cdSWei Mi   return true;
1163eee532cdSWei Mi }
1164eee532cdSWei Mi 
1165be907324SWei Mi std::error_code SampleProfileReaderBinary::readMagicIdent() {
1166c572e92cSDiego Novillo   // Read and check the magic identifier.
1167c572e92cSDiego Novillo   auto Magic = readNumber<uint64_t>();
1168c572e92cSDiego Novillo   if (std::error_code EC = Magic.getError())
1169c572e92cSDiego Novillo     return EC;
1170a0c0857eSWei Mi   else if (std::error_code EC = verifySPMagic(*Magic))
1171c6b96c8dSWei Mi     return EC;
1172c572e92cSDiego Novillo 
1173c572e92cSDiego Novillo   // Read the version number.
1174c572e92cSDiego Novillo   auto Version = readNumber<uint64_t>();
1175c572e92cSDiego Novillo   if (std::error_code EC = Version.getError())
1176c572e92cSDiego Novillo     return EC;
1177c572e92cSDiego Novillo   else if (*Version != SPVersion())
1178c572e92cSDiego Novillo     return sampleprof_error::unsupported_version;
1179c572e92cSDiego Novillo 
1180be907324SWei Mi   return sampleprof_error::success;
1181be907324SWei Mi }
1182be907324SWei Mi 
1183be907324SWei Mi std::error_code SampleProfileReaderBinary::readHeader() {
1184be907324SWei Mi   Data = reinterpret_cast<const uint8_t *>(Buffer->getBufferStart());
1185be907324SWei Mi   End = Data + Buffer->getBufferSize();
1186be907324SWei Mi 
1187be907324SWei Mi   if (std::error_code EC = readMagicIdent())
1188be907324SWei Mi     return EC;
1189be907324SWei Mi 
119040ee23dbSEaswaran Raman   if (std::error_code EC = readSummary())
119140ee23dbSEaswaran Raman     return EC;
119240ee23dbSEaswaran Raman 
1193a0c0857eSWei Mi   if (std::error_code EC = readNameTable())
1194760c5a8fSDiego Novillo     return EC;
1195c572e92cSDiego Novillo   return sampleprof_error::success;
1196c572e92cSDiego Novillo }
1197c572e92cSDiego Novillo 
11986a14325dSWei Mi std::error_code SampleProfileReaderCompactBinary::readHeader() {
11996a14325dSWei Mi   SampleProfileReaderBinary::readHeader();
12006a14325dSWei Mi   if (std::error_code EC = readFuncOffsetTable())
12016a14325dSWei Mi     return EC;
12026a14325dSWei Mi   return sampleprof_error::success;
12036a14325dSWei Mi }
12046a14325dSWei Mi 
12056a14325dSWei Mi std::error_code SampleProfileReaderCompactBinary::readFuncOffsetTable() {
12066a14325dSWei Mi   auto TableOffset = readUnencodedNumber<uint64_t>();
12076a14325dSWei Mi   if (std::error_code EC = TableOffset.getError())
12086a14325dSWei Mi     return EC;
12096a14325dSWei Mi 
12106a14325dSWei Mi   const uint8_t *SavedData = Data;
12116a14325dSWei Mi   const uint8_t *TableStart =
12126a14325dSWei Mi       reinterpret_cast<const uint8_t *>(Buffer->getBufferStart()) +
12136a14325dSWei Mi       *TableOffset;
12146a14325dSWei Mi   Data = TableStart;
12156a14325dSWei Mi 
12166a14325dSWei Mi   auto Size = readNumber<uint64_t>();
12176a14325dSWei Mi   if (std::error_code EC = Size.getError())
12186a14325dSWei Mi     return EC;
12196a14325dSWei Mi 
12206a14325dSWei Mi   FuncOffsetTable.reserve(*Size);
12216a14325dSWei Mi   for (uint32_t I = 0; I < *Size; ++I) {
12226a14325dSWei Mi     auto FName(readStringFromTable());
12236a14325dSWei Mi     if (std::error_code EC = FName.getError())
12246a14325dSWei Mi       return EC;
12256a14325dSWei Mi 
12266a14325dSWei Mi     auto Offset = readNumber<uint64_t>();
12276a14325dSWei Mi     if (std::error_code EC = Offset.getError())
12286a14325dSWei Mi       return EC;
12296a14325dSWei Mi 
12306a14325dSWei Mi     FuncOffsetTable[*FName] = *Offset;
12316a14325dSWei Mi   }
12326a14325dSWei Mi   End = TableStart;
12336a14325dSWei Mi   Data = SavedData;
12346a14325dSWei Mi   return sampleprof_error::success;
12356a14325dSWei Mi }
12366a14325dSWei Mi 
1237ee35784aSWei Mi bool SampleProfileReaderCompactBinary::collectFuncsFromModule() {
1238ee35784aSWei Mi   if (!M)
1239ee35784aSWei Mi     return false;
12406a14325dSWei Mi   FuncsToUse.clear();
1241ee35784aSWei Mi   for (auto &F : *M)
124209dcfe68SWei Mi     FuncsToUse.insert(FunctionSamples::getCanonicalFnName(F));
1243ee35784aSWei Mi   return true;
12446a14325dSWei Mi }
12456a14325dSWei Mi 
124640ee23dbSEaswaran Raman std::error_code SampleProfileReaderBinary::readSummaryEntry(
124740ee23dbSEaswaran Raman     std::vector<ProfileSummaryEntry> &Entries) {
124840ee23dbSEaswaran Raman   auto Cutoff = readNumber<uint64_t>();
124940ee23dbSEaswaran Raman   if (std::error_code EC = Cutoff.getError())
125040ee23dbSEaswaran Raman     return EC;
125140ee23dbSEaswaran Raman 
125240ee23dbSEaswaran Raman   auto MinBlockCount = readNumber<uint64_t>();
125340ee23dbSEaswaran Raman   if (std::error_code EC = MinBlockCount.getError())
125440ee23dbSEaswaran Raman     return EC;
125540ee23dbSEaswaran Raman 
125640ee23dbSEaswaran Raman   auto NumBlocks = readNumber<uint64_t>();
125740ee23dbSEaswaran Raman   if (std::error_code EC = NumBlocks.getError())
125840ee23dbSEaswaran Raman     return EC;
125940ee23dbSEaswaran Raman 
126040ee23dbSEaswaran Raman   Entries.emplace_back(*Cutoff, *MinBlockCount, *NumBlocks);
126140ee23dbSEaswaran Raman   return sampleprof_error::success;
126240ee23dbSEaswaran Raman }
126340ee23dbSEaswaran Raman 
126440ee23dbSEaswaran Raman std::error_code SampleProfileReaderBinary::readSummary() {
126540ee23dbSEaswaran Raman   auto TotalCount = readNumber<uint64_t>();
126640ee23dbSEaswaran Raman   if (std::error_code EC = TotalCount.getError())
126740ee23dbSEaswaran Raman     return EC;
126840ee23dbSEaswaran Raman 
126940ee23dbSEaswaran Raman   auto MaxBlockCount = readNumber<uint64_t>();
127040ee23dbSEaswaran Raman   if (std::error_code EC = MaxBlockCount.getError())
127140ee23dbSEaswaran Raman     return EC;
127240ee23dbSEaswaran Raman 
127340ee23dbSEaswaran Raman   auto MaxFunctionCount = readNumber<uint64_t>();
127440ee23dbSEaswaran Raman   if (std::error_code EC = MaxFunctionCount.getError())
127540ee23dbSEaswaran Raman     return EC;
127640ee23dbSEaswaran Raman 
127740ee23dbSEaswaran Raman   auto NumBlocks = readNumber<uint64_t>();
127840ee23dbSEaswaran Raman   if (std::error_code EC = NumBlocks.getError())
127940ee23dbSEaswaran Raman     return EC;
128040ee23dbSEaswaran Raman 
128140ee23dbSEaswaran Raman   auto NumFunctions = readNumber<uint64_t>();
128240ee23dbSEaswaran Raman   if (std::error_code EC = NumFunctions.getError())
128340ee23dbSEaswaran Raman     return EC;
128440ee23dbSEaswaran Raman 
128540ee23dbSEaswaran Raman   auto NumSummaryEntries = readNumber<uint64_t>();
128640ee23dbSEaswaran Raman   if (std::error_code EC = NumSummaryEntries.getError())
128740ee23dbSEaswaran Raman     return EC;
128840ee23dbSEaswaran Raman 
128940ee23dbSEaswaran Raman   std::vector<ProfileSummaryEntry> Entries;
129040ee23dbSEaswaran Raman   for (unsigned i = 0; i < *NumSummaryEntries; i++) {
129140ee23dbSEaswaran Raman     std::error_code EC = readSummaryEntry(Entries);
129240ee23dbSEaswaran Raman     if (EC != sampleprof_error::success)
129340ee23dbSEaswaran Raman       return EC;
129440ee23dbSEaswaran Raman   }
12950eaee545SJonas Devlieghere   Summary = std::make_unique<ProfileSummary>(
12967cefdb81SEaswaran Raman       ProfileSummary::PSK_Sample, Entries, *TotalCount, *MaxBlockCount, 0,
12977cefdb81SEaswaran Raman       *MaxFunctionCount, *NumBlocks, *NumFunctions);
129840ee23dbSEaswaran Raman 
129940ee23dbSEaswaran Raman   return sampleprof_error::success;
130040ee23dbSEaswaran Raman }
130140ee23dbSEaswaran Raman 
1302a0c0857eSWei Mi bool SampleProfileReaderRawBinary::hasFormat(const MemoryBuffer &Buffer) {
1303c572e92cSDiego Novillo   const uint8_t *Data =
1304c572e92cSDiego Novillo       reinterpret_cast<const uint8_t *>(Buffer.getBufferStart());
1305c572e92cSDiego Novillo   uint64_t Magic = decodeULEB128(Data);
1306c572e92cSDiego Novillo   return Magic == SPMagic();
1307c572e92cSDiego Novillo }
1308c572e92cSDiego Novillo 
1309be907324SWei Mi bool SampleProfileReaderExtBinary::hasFormat(const MemoryBuffer &Buffer) {
1310be907324SWei Mi   const uint8_t *Data =
1311be907324SWei Mi       reinterpret_cast<const uint8_t *>(Buffer.getBufferStart());
1312be907324SWei Mi   uint64_t Magic = decodeULEB128(Data);
1313be907324SWei Mi   return Magic == SPMagic(SPF_Ext_Binary);
1314be907324SWei Mi }
1315be907324SWei Mi 
1316a0c0857eSWei Mi bool SampleProfileReaderCompactBinary::hasFormat(const MemoryBuffer &Buffer) {
1317a0c0857eSWei Mi   const uint8_t *Data =
1318a0c0857eSWei Mi       reinterpret_cast<const uint8_t *>(Buffer.getBufferStart());
1319a0c0857eSWei Mi   uint64_t Magic = decodeULEB128(Data);
1320a0c0857eSWei Mi   return Magic == SPMagic(SPF_Compact_Binary);
1321a0c0857eSWei Mi }
1322a0c0857eSWei Mi 
13233376a787SDiego Novillo std::error_code SampleProfileReaderGCC::skipNextWord() {
13243376a787SDiego Novillo   uint32_t dummy;
13253376a787SDiego Novillo   if (!GcovBuffer.readInt(dummy))
13263376a787SDiego Novillo     return sampleprof_error::truncated;
13273376a787SDiego Novillo   return sampleprof_error::success;
13283376a787SDiego Novillo }
13293376a787SDiego Novillo 
13303376a787SDiego Novillo template <typename T> ErrorOr<T> SampleProfileReaderGCC::readNumber() {
13313376a787SDiego Novillo   if (sizeof(T) <= sizeof(uint32_t)) {
13323376a787SDiego Novillo     uint32_t Val;
13333376a787SDiego Novillo     if (GcovBuffer.readInt(Val) && Val <= std::numeric_limits<T>::max())
13343376a787SDiego Novillo       return static_cast<T>(Val);
13353376a787SDiego Novillo   } else if (sizeof(T) <= sizeof(uint64_t)) {
13363376a787SDiego Novillo     uint64_t Val;
13373376a787SDiego Novillo     if (GcovBuffer.readInt64(Val) && Val <= std::numeric_limits<T>::max())
13383376a787SDiego Novillo       return static_cast<T>(Val);
13393376a787SDiego Novillo   }
13403376a787SDiego Novillo 
13413376a787SDiego Novillo   std::error_code EC = sampleprof_error::malformed;
13423376a787SDiego Novillo   reportError(0, EC.message());
13433376a787SDiego Novillo   return EC;
13443376a787SDiego Novillo }
13453376a787SDiego Novillo 
13463376a787SDiego Novillo ErrorOr<StringRef> SampleProfileReaderGCC::readString() {
13473376a787SDiego Novillo   StringRef Str;
13483376a787SDiego Novillo   if (!GcovBuffer.readString(Str))
13493376a787SDiego Novillo     return sampleprof_error::truncated;
13503376a787SDiego Novillo   return Str;
13513376a787SDiego Novillo }
13523376a787SDiego Novillo 
13533376a787SDiego Novillo std::error_code SampleProfileReaderGCC::readHeader() {
13543376a787SDiego Novillo   // Read the magic identifier.
13553376a787SDiego Novillo   if (!GcovBuffer.readGCDAFormat())
13563376a787SDiego Novillo     return sampleprof_error::unrecognized_format;
13573376a787SDiego Novillo 
13583376a787SDiego Novillo   // Read the version number. Note - the GCC reader does not validate this
13593376a787SDiego Novillo   // version, but the profile creator generates v704.
13603376a787SDiego Novillo   GCOV::GCOVVersion version;
13613376a787SDiego Novillo   if (!GcovBuffer.readGCOVVersion(version))
13623376a787SDiego Novillo     return sampleprof_error::unrecognized_format;
13633376a787SDiego Novillo 
13642d00eb17SFangrui Song   if (version != GCOV::V407)
13653376a787SDiego Novillo     return sampleprof_error::unsupported_version;
13663376a787SDiego Novillo 
13673376a787SDiego Novillo   // Skip the empty integer.
13683376a787SDiego Novillo   if (std::error_code EC = skipNextWord())
13693376a787SDiego Novillo     return EC;
13703376a787SDiego Novillo 
13713376a787SDiego Novillo   return sampleprof_error::success;
13723376a787SDiego Novillo }
13733376a787SDiego Novillo 
13743376a787SDiego Novillo std::error_code SampleProfileReaderGCC::readSectionTag(uint32_t Expected) {
13753376a787SDiego Novillo   uint32_t Tag;
13763376a787SDiego Novillo   if (!GcovBuffer.readInt(Tag))
13773376a787SDiego Novillo     return sampleprof_error::truncated;
13783376a787SDiego Novillo 
13793376a787SDiego Novillo   if (Tag != Expected)
13803376a787SDiego Novillo     return sampleprof_error::malformed;
13813376a787SDiego Novillo 
13823376a787SDiego Novillo   if (std::error_code EC = skipNextWord())
13833376a787SDiego Novillo     return EC;
13843376a787SDiego Novillo 
13853376a787SDiego Novillo   return sampleprof_error::success;
13863376a787SDiego Novillo }
13873376a787SDiego Novillo 
13883376a787SDiego Novillo std::error_code SampleProfileReaderGCC::readNameTable() {
13893376a787SDiego Novillo   if (std::error_code EC = readSectionTag(GCOVTagAFDOFileNames))
13903376a787SDiego Novillo     return EC;
13913376a787SDiego Novillo 
13923376a787SDiego Novillo   uint32_t Size;
13933376a787SDiego Novillo   if (!GcovBuffer.readInt(Size))
13943376a787SDiego Novillo     return sampleprof_error::truncated;
13953376a787SDiego Novillo 
13963376a787SDiego Novillo   for (uint32_t I = 0; I < Size; ++I) {
13973376a787SDiego Novillo     StringRef Str;
13983376a787SDiego Novillo     if (!GcovBuffer.readString(Str))
13993376a787SDiego Novillo       return sampleprof_error::truncated;
1400adcd0268SBenjamin Kramer     Names.push_back(std::string(Str));
14013376a787SDiego Novillo   }
14023376a787SDiego Novillo 
14033376a787SDiego Novillo   return sampleprof_error::success;
14043376a787SDiego Novillo }
14053376a787SDiego Novillo 
14063376a787SDiego Novillo std::error_code SampleProfileReaderGCC::readFunctionProfiles() {
14073376a787SDiego Novillo   if (std::error_code EC = readSectionTag(GCOVTagAFDOFunction))
14083376a787SDiego Novillo     return EC;
14093376a787SDiego Novillo 
14103376a787SDiego Novillo   uint32_t NumFunctions;
14113376a787SDiego Novillo   if (!GcovBuffer.readInt(NumFunctions))
14123376a787SDiego Novillo     return sampleprof_error::truncated;
14133376a787SDiego Novillo 
1414aae1ed8eSDiego Novillo   InlineCallStack Stack;
14153376a787SDiego Novillo   for (uint32_t I = 0; I < NumFunctions; ++I)
1416aae1ed8eSDiego Novillo     if (std::error_code EC = readOneFunctionProfile(Stack, true, 0))
14173376a787SDiego Novillo       return EC;
14183376a787SDiego Novillo 
141940ee23dbSEaswaran Raman   computeSummary();
14203376a787SDiego Novillo   return sampleprof_error::success;
14213376a787SDiego Novillo }
14223376a787SDiego Novillo 
1423aae1ed8eSDiego Novillo std::error_code SampleProfileReaderGCC::readOneFunctionProfile(
1424aae1ed8eSDiego Novillo     const InlineCallStack &InlineStack, bool Update, uint32_t Offset) {
14253376a787SDiego Novillo   uint64_t HeadCount = 0;
1426aae1ed8eSDiego Novillo   if (InlineStack.size() == 0)
14273376a787SDiego Novillo     if (!GcovBuffer.readInt64(HeadCount))
14283376a787SDiego Novillo       return sampleprof_error::truncated;
14293376a787SDiego Novillo 
14303376a787SDiego Novillo   uint32_t NameIdx;
14313376a787SDiego Novillo   if (!GcovBuffer.readInt(NameIdx))
14323376a787SDiego Novillo     return sampleprof_error::truncated;
14333376a787SDiego Novillo 
14343376a787SDiego Novillo   StringRef Name(Names[NameIdx]);
14353376a787SDiego Novillo 
14363376a787SDiego Novillo   uint32_t NumPosCounts;
14373376a787SDiego Novillo   if (!GcovBuffer.readInt(NumPosCounts))
14383376a787SDiego Novillo     return sampleprof_error::truncated;
14393376a787SDiego Novillo 
1440aae1ed8eSDiego Novillo   uint32_t NumCallsites;
1441aae1ed8eSDiego Novillo   if (!GcovBuffer.readInt(NumCallsites))
14423376a787SDiego Novillo     return sampleprof_error::truncated;
14433376a787SDiego Novillo 
1444aae1ed8eSDiego Novillo   FunctionSamples *FProfile = nullptr;
1445aae1ed8eSDiego Novillo   if (InlineStack.size() == 0) {
1446aae1ed8eSDiego Novillo     // If this is a top function that we have already processed, do not
1447aae1ed8eSDiego Novillo     // update its profile again.  This happens in the presence of
1448aae1ed8eSDiego Novillo     // function aliases.  Since these aliases share the same function
1449aae1ed8eSDiego Novillo     // body, there will be identical replicated profiles for the
1450aae1ed8eSDiego Novillo     // original function.  In this case, we simply not bother updating
1451aae1ed8eSDiego Novillo     // the profile of the original function.
1452aae1ed8eSDiego Novillo     FProfile = &Profiles[Name];
1453aae1ed8eSDiego Novillo     FProfile->addHeadSamples(HeadCount);
1454aae1ed8eSDiego Novillo     if (FProfile->getTotalSamples() > 0)
14553376a787SDiego Novillo       Update = false;
1456aae1ed8eSDiego Novillo   } else {
1457aae1ed8eSDiego Novillo     // Otherwise, we are reading an inlined instance. The top of the
1458aae1ed8eSDiego Novillo     // inline stack contains the profile of the caller. Insert this
1459aae1ed8eSDiego Novillo     // callee in the caller's CallsiteMap.
1460aae1ed8eSDiego Novillo     FunctionSamples *CallerProfile = InlineStack.front();
1461aae1ed8eSDiego Novillo     uint32_t LineOffset = Offset >> 16;
1462aae1ed8eSDiego Novillo     uint32_t Discriminator = Offset & 0xffff;
1463aae1ed8eSDiego Novillo     FProfile = &CallerProfile->functionSamplesAt(
1464adcd0268SBenjamin Kramer         LineLocation(LineOffset, Discriminator))[std::string(Name)];
14653376a787SDiego Novillo   }
146657d1dda5SDehao Chen   FProfile->setName(Name);
14673376a787SDiego Novillo 
14683376a787SDiego Novillo   for (uint32_t I = 0; I < NumPosCounts; ++I) {
14693376a787SDiego Novillo     uint32_t Offset;
14703376a787SDiego Novillo     if (!GcovBuffer.readInt(Offset))
14713376a787SDiego Novillo       return sampleprof_error::truncated;
14723376a787SDiego Novillo 
14733376a787SDiego Novillo     uint32_t NumTargets;
14743376a787SDiego Novillo     if (!GcovBuffer.readInt(NumTargets))
14753376a787SDiego Novillo       return sampleprof_error::truncated;
14763376a787SDiego Novillo 
14773376a787SDiego Novillo     uint64_t Count;
14783376a787SDiego Novillo     if (!GcovBuffer.readInt64(Count))
14793376a787SDiego Novillo       return sampleprof_error::truncated;
14803376a787SDiego Novillo 
1481aae1ed8eSDiego Novillo     // The line location is encoded in the offset as:
1482aae1ed8eSDiego Novillo     //   high 16 bits: line offset to the start of the function.
1483aae1ed8eSDiego Novillo     //   low 16 bits: discriminator.
1484aae1ed8eSDiego Novillo     uint32_t LineOffset = Offset >> 16;
1485aae1ed8eSDiego Novillo     uint32_t Discriminator = Offset & 0xffff;
14863376a787SDiego Novillo 
1487aae1ed8eSDiego Novillo     InlineCallStack NewStack;
1488aae1ed8eSDiego Novillo     NewStack.push_back(FProfile);
14891d0bc055SKazu Hirata     llvm::append_range(NewStack, InlineStack);
1490aae1ed8eSDiego Novillo     if (Update) {
1491aae1ed8eSDiego Novillo       // Walk up the inline stack, adding the samples on this line to
1492aae1ed8eSDiego Novillo       // the total sample count of the callers in the chain.
1493aae1ed8eSDiego Novillo       for (auto CallerProfile : NewStack)
1494aae1ed8eSDiego Novillo         CallerProfile->addTotalSamples(Count);
1495aae1ed8eSDiego Novillo 
1496aae1ed8eSDiego Novillo       // Update the body samples for the current profile.
1497aae1ed8eSDiego Novillo       FProfile->addBodySamples(LineOffset, Discriminator, Count);
1498aae1ed8eSDiego Novillo     }
1499aae1ed8eSDiego Novillo 
1500aae1ed8eSDiego Novillo     // Process the list of functions called at an indirect call site.
1501aae1ed8eSDiego Novillo     // These are all the targets that a function pointer (or virtual
1502aae1ed8eSDiego Novillo     // function) resolved at runtime.
15033376a787SDiego Novillo     for (uint32_t J = 0; J < NumTargets; J++) {
15043376a787SDiego Novillo       uint32_t HistVal;
15053376a787SDiego Novillo       if (!GcovBuffer.readInt(HistVal))
15063376a787SDiego Novillo         return sampleprof_error::truncated;
15073376a787SDiego Novillo 
15083376a787SDiego Novillo       if (HistVal != HIST_TYPE_INDIR_CALL_TOPN)
15093376a787SDiego Novillo         return sampleprof_error::malformed;
15103376a787SDiego Novillo 
15113376a787SDiego Novillo       uint64_t TargetIdx;
15123376a787SDiego Novillo       if (!GcovBuffer.readInt64(TargetIdx))
15133376a787SDiego Novillo         return sampleprof_error::truncated;
15143376a787SDiego Novillo       StringRef TargetName(Names[TargetIdx]);
15153376a787SDiego Novillo 
15163376a787SDiego Novillo       uint64_t TargetCount;
15173376a787SDiego Novillo       if (!GcovBuffer.readInt64(TargetCount))
15183376a787SDiego Novillo         return sampleprof_error::truncated;
15193376a787SDiego Novillo 
1520920677a9SDehao Chen       if (Update)
1521920677a9SDehao Chen         FProfile->addCalledTargetSamples(LineOffset, Discriminator,
1522aae1ed8eSDiego Novillo                                          TargetName, TargetCount);
15233376a787SDiego Novillo     }
15243376a787SDiego Novillo   }
15253376a787SDiego Novillo 
1526aae1ed8eSDiego Novillo   // Process all the inlined callers into the current function. These
1527aae1ed8eSDiego Novillo   // are all the callsites that were inlined into this function.
1528aae1ed8eSDiego Novillo   for (uint32_t I = 0; I < NumCallsites; I++) {
15293376a787SDiego Novillo     // The offset is encoded as:
15303376a787SDiego Novillo     //   high 16 bits: line offset to the start of the function.
15313376a787SDiego Novillo     //   low 16 bits: discriminator.
15323376a787SDiego Novillo     uint32_t Offset;
15333376a787SDiego Novillo     if (!GcovBuffer.readInt(Offset))
15343376a787SDiego Novillo       return sampleprof_error::truncated;
1535aae1ed8eSDiego Novillo     InlineCallStack NewStack;
1536aae1ed8eSDiego Novillo     NewStack.push_back(FProfile);
15371d0bc055SKazu Hirata     llvm::append_range(NewStack, InlineStack);
1538aae1ed8eSDiego Novillo     if (std::error_code EC = readOneFunctionProfile(NewStack, Update, Offset))
15393376a787SDiego Novillo       return EC;
15403376a787SDiego Novillo   }
15413376a787SDiego Novillo 
15423376a787SDiego Novillo   return sampleprof_error::success;
15433376a787SDiego Novillo }
15443376a787SDiego Novillo 
15455f8f34e4SAdrian Prantl /// Read a GCC AutoFDO profile.
15463376a787SDiego Novillo ///
15473376a787SDiego Novillo /// This format is generated by the Linux Perf conversion tool at
15483376a787SDiego Novillo /// https://github.com/google/autofdo.
15498c8ec1f6SWei Mi std::error_code SampleProfileReaderGCC::readImpl() {
1550*6745ffe4SRong Xu   assert(!ProfileIsFSDisciminator && "Gcc profiles not support FSDisciminator");
15513376a787SDiego Novillo   // Read the string table.
15523376a787SDiego Novillo   if (std::error_code EC = readNameTable())
15533376a787SDiego Novillo     return EC;
15543376a787SDiego Novillo 
15553376a787SDiego Novillo   // Read the source profile.
15563376a787SDiego Novillo   if (std::error_code EC = readFunctionProfiles())
15573376a787SDiego Novillo     return EC;
15583376a787SDiego Novillo 
15593376a787SDiego Novillo   return sampleprof_error::success;
15603376a787SDiego Novillo }
15613376a787SDiego Novillo 
15623376a787SDiego Novillo bool SampleProfileReaderGCC::hasFormat(const MemoryBuffer &Buffer) {
15633376a787SDiego Novillo   StringRef Magic(reinterpret_cast<const char *>(Buffer.getBufferStart()));
15643376a787SDiego Novillo   return Magic == "adcg*704";
15653376a787SDiego Novillo }
15663376a787SDiego Novillo 
15678c8ec1f6SWei Mi void SampleProfileReaderItaniumRemapper::applyRemapping(LLVMContext &Ctx) {
1568ebad6788SWei Mi   // If the reader uses MD5 to represent string, we can't remap it because
156928436358SRichard Smith   // we don't know what the original function names were.
1570ebad6788SWei Mi   if (Reader.useMD5()) {
157128436358SRichard Smith     Ctx.diagnose(DiagnosticInfoSampleProfile(
15728c8ec1f6SWei Mi         Reader.getBuffer()->getBufferIdentifier(),
157328436358SRichard Smith         "Profile data remapping cannot be applied to profile data "
157428436358SRichard Smith         "in compact format (original mangled names are not available).",
157528436358SRichard Smith         DS_Warning));
15768c8ec1f6SWei Mi     return;
157728436358SRichard Smith   }
157828436358SRichard Smith 
15796b989a17SWenlei He   // CSSPGO-TODO: Remapper is not yet supported.
15806b989a17SWenlei He   // We will need to remap the entire context string.
15818c8ec1f6SWei Mi   assert(Remappings && "should be initialized while creating remapper");
1582c67ccf5fSWei Mi   for (auto &Sample : Reader.getProfiles()) {
1583c67ccf5fSWei Mi     DenseSet<StringRef> NamesInSample;
1584c67ccf5fSWei Mi     Sample.second.findAllNames(NamesInSample);
1585c67ccf5fSWei Mi     for (auto &Name : NamesInSample)
1586c67ccf5fSWei Mi       if (auto Key = Remappings->insert(Name))
1587c67ccf5fSWei Mi         NameMap.insert({Key, Name});
1588c67ccf5fSWei Mi   }
158928436358SRichard Smith 
15908c8ec1f6SWei Mi   RemappingApplied = true;
159128436358SRichard Smith }
159228436358SRichard Smith 
1593c67ccf5fSWei Mi Optional<StringRef>
1594c67ccf5fSWei Mi SampleProfileReaderItaniumRemapper::lookUpNameInProfile(StringRef Fname) {
15958c8ec1f6SWei Mi   if (auto Key = Remappings->lookup(Fname))
1596c67ccf5fSWei Mi     return NameMap.lookup(Key);
1597c67ccf5fSWei Mi   return None;
159828436358SRichard Smith }
159928436358SRichard Smith 
16005f8f34e4SAdrian Prantl /// Prepare a memory buffer for the contents of \p Filename.
1601de1ab26fSDiego Novillo ///
1602c572e92cSDiego Novillo /// \returns an error code indicating the status of the buffer.
1603fcd55607SDiego Novillo static ErrorOr<std::unique_ptr<MemoryBuffer>>
16040da23a27SBenjamin Kramer setupMemoryBuffer(const Twine &Filename) {
1605e71994a2SJonathan Crowther   auto BufferOrErr = MemoryBuffer::getFileOrSTDIN(Filename, /*IsText=*/true);
1606c572e92cSDiego Novillo   if (std::error_code EC = BufferOrErr.getError())
1607c572e92cSDiego Novillo     return EC;
1608fcd55607SDiego Novillo   auto Buffer = std::move(BufferOrErr.get());
1609c572e92cSDiego Novillo 
1610c572e92cSDiego Novillo   // Sanity check the file.
1611260fe3ecSZachary Turner   if (uint64_t(Buffer->getBufferSize()) > std::numeric_limits<uint32_t>::max())
1612c572e92cSDiego Novillo     return sampleprof_error::too_large;
1613c572e92cSDiego Novillo 
1614c55cf4afSBill Wendling   return std::move(Buffer);
1615c572e92cSDiego Novillo }
1616c572e92cSDiego Novillo 
16175f8f34e4SAdrian Prantl /// Create a sample profile reader based on the format of the input file.
1618c572e92cSDiego Novillo ///
1619c572e92cSDiego Novillo /// \param Filename The file to open.
1620c572e92cSDiego Novillo ///
1621c572e92cSDiego Novillo /// \param C The LLVM context to use to emit diagnostics.
1622c572e92cSDiego Novillo ///
16238c8ec1f6SWei Mi /// \param RemapFilename The file used for profile remapping.
16248c8ec1f6SWei Mi ///
1625c572e92cSDiego Novillo /// \returns an error code indicating the status of the created reader.
1626fcd55607SDiego Novillo ErrorOr<std::unique_ptr<SampleProfileReader>>
16278c8ec1f6SWei Mi SampleProfileReader::create(const std::string Filename, LLVMContext &C,
16288c8ec1f6SWei Mi                             const std::string RemapFilename) {
1629fcd55607SDiego Novillo   auto BufferOrError = setupMemoryBuffer(Filename);
1630fcd55607SDiego Novillo   if (std::error_code EC = BufferOrError.getError())
1631c572e92cSDiego Novillo     return EC;
16328c8ec1f6SWei Mi   return create(BufferOrError.get(), C, RemapFilename);
163351abea74SNathan Slingerland }
1634c572e92cSDiego Novillo 
163528436358SRichard Smith /// Create a sample profile remapper from the given input, to remap the
163628436358SRichard Smith /// function names in the given profile data.
163728436358SRichard Smith ///
163828436358SRichard Smith /// \param Filename The file to open.
163928436358SRichard Smith ///
16408c8ec1f6SWei Mi /// \param Reader The profile reader the remapper is going to be applied to.
16418c8ec1f6SWei Mi ///
164228436358SRichard Smith /// \param C The LLVM context to use to emit diagnostics.
164328436358SRichard Smith ///
164428436358SRichard Smith /// \returns an error code indicating the status of the created reader.
16458c8ec1f6SWei Mi ErrorOr<std::unique_ptr<SampleProfileReaderItaniumRemapper>>
16468c8ec1f6SWei Mi SampleProfileReaderItaniumRemapper::create(const std::string Filename,
16478c8ec1f6SWei Mi                                            SampleProfileReader &Reader,
16488c8ec1f6SWei Mi                                            LLVMContext &C) {
164928436358SRichard Smith   auto BufferOrError = setupMemoryBuffer(Filename);
165028436358SRichard Smith   if (std::error_code EC = BufferOrError.getError())
165128436358SRichard Smith     return EC;
16528c8ec1f6SWei Mi   return create(BufferOrError.get(), Reader, C);
16538c8ec1f6SWei Mi }
16548c8ec1f6SWei Mi 
16558c8ec1f6SWei Mi /// Create a sample profile remapper from the given input, to remap the
16568c8ec1f6SWei Mi /// function names in the given profile data.
16578c8ec1f6SWei Mi ///
16588c8ec1f6SWei Mi /// \param B The memory buffer to create the reader from (assumes ownership).
16598c8ec1f6SWei Mi ///
16608c8ec1f6SWei Mi /// \param C The LLVM context to use to emit diagnostics.
16618c8ec1f6SWei Mi ///
16628c8ec1f6SWei Mi /// \param Reader The profile reader the remapper is going to be applied to.
16638c8ec1f6SWei Mi ///
16648c8ec1f6SWei Mi /// \returns an error code indicating the status of the created reader.
16658c8ec1f6SWei Mi ErrorOr<std::unique_ptr<SampleProfileReaderItaniumRemapper>>
16668c8ec1f6SWei Mi SampleProfileReaderItaniumRemapper::create(std::unique_ptr<MemoryBuffer> &B,
16678c8ec1f6SWei Mi                                            SampleProfileReader &Reader,
16688c8ec1f6SWei Mi                                            LLVMContext &C) {
16698c8ec1f6SWei Mi   auto Remappings = std::make_unique<SymbolRemappingReader>();
16708c8ec1f6SWei Mi   if (Error E = Remappings->read(*B.get())) {
16718c8ec1f6SWei Mi     handleAllErrors(
16728c8ec1f6SWei Mi         std::move(E), [&](const SymbolRemappingParseError &ParseError) {
16738c8ec1f6SWei Mi           C.diagnose(DiagnosticInfoSampleProfile(B->getBufferIdentifier(),
16748c8ec1f6SWei Mi                                                  ParseError.getLineNum(),
16758c8ec1f6SWei Mi                                                  ParseError.getMessage()));
16768c8ec1f6SWei Mi         });
16778c8ec1f6SWei Mi     return sampleprof_error::malformed;
16788c8ec1f6SWei Mi   }
16798c8ec1f6SWei Mi 
16800eaee545SJonas Devlieghere   return std::make_unique<SampleProfileReaderItaniumRemapper>(
16818c8ec1f6SWei Mi       std::move(B), std::move(Remappings), Reader);
168228436358SRichard Smith }
168328436358SRichard Smith 
16845f8f34e4SAdrian Prantl /// Create a sample profile reader based on the format of the input data.
168551abea74SNathan Slingerland ///
168651abea74SNathan Slingerland /// \param B The memory buffer to create the reader from (assumes ownership).
168751abea74SNathan Slingerland ///
168851abea74SNathan Slingerland /// \param C The LLVM context to use to emit diagnostics.
168951abea74SNathan Slingerland ///
16908c8ec1f6SWei Mi /// \param RemapFilename The file used for profile remapping.
16918c8ec1f6SWei Mi ///
169251abea74SNathan Slingerland /// \returns an error code indicating the status of the created reader.
169351abea74SNathan Slingerland ErrorOr<std::unique_ptr<SampleProfileReader>>
16948c8ec1f6SWei Mi SampleProfileReader::create(std::unique_ptr<MemoryBuffer> &B, LLVMContext &C,
16958c8ec1f6SWei Mi                             const std::string RemapFilename) {
1696fcd55607SDiego Novillo   std::unique_ptr<SampleProfileReader> Reader;
1697a0c0857eSWei Mi   if (SampleProfileReaderRawBinary::hasFormat(*B))
1698a0c0857eSWei Mi     Reader.reset(new SampleProfileReaderRawBinary(std::move(B), C));
1699be907324SWei Mi   else if (SampleProfileReaderExtBinary::hasFormat(*B))
1700be907324SWei Mi     Reader.reset(new SampleProfileReaderExtBinary(std::move(B), C));
1701a0c0857eSWei Mi   else if (SampleProfileReaderCompactBinary::hasFormat(*B))
1702a0c0857eSWei Mi     Reader.reset(new SampleProfileReaderCompactBinary(std::move(B), C));
170351abea74SNathan Slingerland   else if (SampleProfileReaderGCC::hasFormat(*B))
170451abea74SNathan Slingerland     Reader.reset(new SampleProfileReaderGCC(std::move(B), C));
170551abea74SNathan Slingerland   else if (SampleProfileReaderText::hasFormat(*B))
170651abea74SNathan Slingerland     Reader.reset(new SampleProfileReaderText(std::move(B), C));
17074f823667SNathan Slingerland   else
17084f823667SNathan Slingerland     return sampleprof_error::unrecognized_format;
1709c572e92cSDiego Novillo 
17108c8ec1f6SWei Mi   if (!RemapFilename.empty()) {
17118c8ec1f6SWei Mi     auto ReaderOrErr =
17128c8ec1f6SWei Mi         SampleProfileReaderItaniumRemapper::create(RemapFilename, *Reader, C);
17138c8ec1f6SWei Mi     if (std::error_code EC = ReaderOrErr.getError()) {
17148c8ec1f6SWei Mi       std::string Msg = "Could not create remapper: " + EC.message();
17158c8ec1f6SWei Mi       C.diagnose(DiagnosticInfoSampleProfile(RemapFilename, Msg));
17168c8ec1f6SWei Mi       return EC;
17178c8ec1f6SWei Mi     }
17188c8ec1f6SWei Mi     Reader->Remapper = std::move(ReaderOrErr.get());
17198c8ec1f6SWei Mi   }
17208c8ec1f6SWei Mi 
172194d44c97SWei Mi   FunctionSamples::Format = Reader->getFormat();
1722be907324SWei Mi   if (std::error_code EC = Reader->readHeader()) {
1723fcd55607SDiego Novillo     return EC;
1724be907324SWei Mi   }
1725fcd55607SDiego Novillo 
1726c55cf4afSBill Wendling   return std::move(Reader);
1727de1ab26fSDiego Novillo }
172840ee23dbSEaswaran Raman 
172940ee23dbSEaswaran Raman // For text and GCC file formats, we compute the summary after reading the
173040ee23dbSEaswaran Raman // profile. Binary format has the profile summary in its header.
173140ee23dbSEaswaran Raman void SampleProfileReader::computeSummary() {
1732e5a17e3fSEaswaran Raman   SampleProfileSummaryBuilder Builder(ProfileSummaryBuilder::DefaultCutoffs);
1733801d9cc7SWenlei He   Summary = Builder.computeSummaryForProfiles(Profiles);
173440ee23dbSEaswaran Raman }
1735