1de1ab26fSDiego Novillo //===- SampleProfReader.cpp - Read LLVM sample profile data ---------------===//
2de1ab26fSDiego Novillo //
3de1ab26fSDiego Novillo //                      The LLVM Compiler Infrastructure
4de1ab26fSDiego Novillo //
5de1ab26fSDiego Novillo // This file is distributed under the University of Illinois Open Source
6de1ab26fSDiego Novillo // License. See LICENSE.TXT for details.
7de1ab26fSDiego Novillo //
8de1ab26fSDiego Novillo //===----------------------------------------------------------------------===//
9de1ab26fSDiego Novillo //
10de1ab26fSDiego Novillo // This file implements the class that reads LLVM sample profiles. It
11c572e92cSDiego Novillo // supports two file formats: text and binary. The textual representation
12c572e92cSDiego Novillo // is useful for debugging and testing purposes. The binary representation
13de1ab26fSDiego Novillo // is more compact, resulting in smaller file sizes. However, they can
14de1ab26fSDiego Novillo // both be used interchangeably.
15de1ab26fSDiego Novillo //
16de1ab26fSDiego Novillo // NOTE: If you are making changes to the file format, please remember
17de1ab26fSDiego Novillo //       to document them in the Clang documentation at
18de1ab26fSDiego Novillo //       tools/clang/docs/UsersManual.rst.
19de1ab26fSDiego Novillo //
20de1ab26fSDiego Novillo // Text format
21de1ab26fSDiego Novillo // -----------
22de1ab26fSDiego Novillo //
23de1ab26fSDiego Novillo // Sample profiles are written as ASCII text. The file is divided into
24de1ab26fSDiego Novillo // sections, which correspond to each of the functions executed at runtime.
25de1ab26fSDiego Novillo // Each section has the following format
26de1ab26fSDiego Novillo //
27de1ab26fSDiego Novillo //     function1:total_samples:total_head_samples
28de1ab26fSDiego Novillo //      offset1[.discriminator]: number_of_samples [fn1:num fn2:num ... ]
29de1ab26fSDiego Novillo //      offset2[.discriminator]: number_of_samples [fn3:num fn4:num ... ]
30de1ab26fSDiego Novillo //      ...
31de1ab26fSDiego Novillo //      offsetN[.discriminator]: number_of_samples [fn5:num fn6:num ... ]
326722688eSDehao Chen //      offsetA[.discriminator]: fnA:num_of_total_samples
336722688eSDehao Chen //       offsetA1[.discriminator]: number_of_samples [fn7:num fn8:num ... ]
346722688eSDehao Chen //       ...
35de1ab26fSDiego Novillo //
366722688eSDehao Chen // This is a nested tree in which the identation represent the nest level
376722688eSDehao Chen // of the inline stack. There is no blank line in the file. And the spacing
386722688eSDehao Chen // within a single line is fixed. Additional spaces will result in an error
396722688eSDehao Chen // while reading the file.
406722688eSDehao Chen //
416722688eSDehao Chen // Inline stack is a stack of source locations in which the top of the stack
426722688eSDehao Chen // represents the leaf function, and the bottom of the stack represents the
436722688eSDehao Chen // actual symbol in which the instruction belongs.
44de1ab26fSDiego Novillo //
45de1ab26fSDiego Novillo // Function names must be mangled in order for the profile loader to
46de1ab26fSDiego Novillo // match them in the current translation unit. The two numbers in the
47de1ab26fSDiego Novillo // function header specify how many total samples were accumulated in the
48de1ab26fSDiego Novillo // function (first number), and the total number of samples accumulated
49de1ab26fSDiego Novillo // in the prologue of the function (second number). This head sample
50de1ab26fSDiego Novillo // count provides an indicator of how frequently the function is invoked.
51de1ab26fSDiego Novillo //
526722688eSDehao Chen // There are two types of lines in the function body.
536722688eSDehao Chen //
546722688eSDehao Chen // * Sampled line represents the profile information of a source location.
556722688eSDehao Chen // * Callsite line represents the profile inofrmation of a callsite.
566722688eSDehao Chen //
57de1ab26fSDiego Novillo // Each sampled line may contain several items. Some are optional (marked
58de1ab26fSDiego Novillo // below):
59de1ab26fSDiego Novillo //
60de1ab26fSDiego Novillo // a. Source line offset. This number represents the line number
61de1ab26fSDiego Novillo //    in the function where the sample was collected. The line number is
62de1ab26fSDiego Novillo //    always relative to the line where symbol of the function is
63de1ab26fSDiego Novillo //    defined. So, if the function has its header at line 280, the offset
64de1ab26fSDiego Novillo //    13 is at line 293 in the file.
65de1ab26fSDiego Novillo //
66de1ab26fSDiego Novillo //    Note that this offset should never be a negative number. This could
67de1ab26fSDiego Novillo //    happen in cases like macros. The debug machinery will register the
68de1ab26fSDiego Novillo //    line number at the point of macro expansion. So, if the macro was
69de1ab26fSDiego Novillo //    expanded in a line before the start of the function, the profile
70de1ab26fSDiego Novillo //    converter should emit a 0 as the offset (this means that the optimizers
71de1ab26fSDiego Novillo //    will not be able to associate a meaningful weight to the instructions
72de1ab26fSDiego Novillo //    in the macro).
73de1ab26fSDiego Novillo //
74de1ab26fSDiego Novillo // b. [OPTIONAL] Discriminator. This is used if the sampled program
75de1ab26fSDiego Novillo //    was compiled with DWARF discriminator support
76de1ab26fSDiego Novillo //    (http://wiki.dwarfstd.org/index.php?title=Path_Discriminators).
77de1ab26fSDiego Novillo //    DWARF discriminators are unsigned integer values that allow the
78de1ab26fSDiego Novillo //    compiler to distinguish between multiple execution paths on the
79de1ab26fSDiego Novillo //    same source line location.
80de1ab26fSDiego Novillo //
81de1ab26fSDiego Novillo //    For example, consider the line of code ``if (cond) foo(); else bar();``.
82de1ab26fSDiego Novillo //    If the predicate ``cond`` is true 80% of the time, then the edge
83de1ab26fSDiego Novillo //    into function ``foo`` should be considered to be taken most of the
84de1ab26fSDiego Novillo //    time. But both calls to ``foo`` and ``bar`` are at the same source
85de1ab26fSDiego Novillo //    line, so a sample count at that line is not sufficient. The
86de1ab26fSDiego Novillo //    compiler needs to know which part of that line is taken more
87de1ab26fSDiego Novillo //    frequently.
88de1ab26fSDiego Novillo //
89de1ab26fSDiego Novillo //    This is what discriminators provide. In this case, the calls to
90de1ab26fSDiego Novillo //    ``foo`` and ``bar`` will be at the same line, but will have
91de1ab26fSDiego Novillo //    different discriminator values. This allows the compiler to correctly
92de1ab26fSDiego Novillo //    set edge weights into ``foo`` and ``bar``.
93de1ab26fSDiego Novillo //
94de1ab26fSDiego Novillo // c. Number of samples. This is an integer quantity representing the
95de1ab26fSDiego Novillo //    number of samples collected by the profiler at this source
96de1ab26fSDiego Novillo //    location.
97de1ab26fSDiego Novillo //
98de1ab26fSDiego Novillo // d. [OPTIONAL] Potential call targets and samples. If present, this
99de1ab26fSDiego Novillo //    line contains a call instruction. This models both direct and
100de1ab26fSDiego Novillo //    number of samples. For example,
101de1ab26fSDiego Novillo //
102de1ab26fSDiego Novillo //      130: 7  foo:3  bar:2  baz:7
103de1ab26fSDiego Novillo //
104de1ab26fSDiego Novillo //    The above means that at relative line offset 130 there is a call
105de1ab26fSDiego Novillo //    instruction that calls one of ``foo()``, ``bar()`` and ``baz()``,
106de1ab26fSDiego Novillo //    with ``baz()`` being the relatively more frequently called target.
107de1ab26fSDiego Novillo //
1086722688eSDehao Chen // Each callsite line may contain several items. Some are optional.
1096722688eSDehao Chen //
1106722688eSDehao Chen // a. Source line offset. This number represents the line number of the
1116722688eSDehao Chen //    callsite that is inlined in the profiled binary.
1126722688eSDehao Chen //
1136722688eSDehao Chen // b. [OPTIONAL] Discriminator. Same as the discriminator for sampled line.
1146722688eSDehao Chen //
1156722688eSDehao Chen // c. Number of samples. This is an integer quantity representing the
1166722688eSDehao Chen //    total number of samples collected for the inlined instance at this
1176722688eSDehao Chen //    callsite
118de1ab26fSDiego Novillo //===----------------------------------------------------------------------===//
119de1ab26fSDiego Novillo 
120de1ab26fSDiego Novillo #include "llvm/ProfileData/SampleProfReader.h"
121de1ab26fSDiego Novillo #include "llvm/Support/Debug.h"
122de1ab26fSDiego Novillo #include "llvm/Support/ErrorOr.h"
123c572e92cSDiego Novillo #include "llvm/Support/LEB128.h"
124de1ab26fSDiego Novillo #include "llvm/Support/LineIterator.h"
125c572e92cSDiego Novillo #include "llvm/Support/MemoryBuffer.h"
1266722688eSDehao Chen #include "llvm/ADT/DenseMap.h"
1276722688eSDehao Chen #include "llvm/ADT/SmallVector.h"
128de1ab26fSDiego Novillo 
129c572e92cSDiego Novillo using namespace llvm::sampleprof;
130de1ab26fSDiego Novillo using namespace llvm;
131de1ab26fSDiego Novillo 
132de1ab26fSDiego Novillo /// \brief Print the samples collected for a function on stream \p OS.
133de1ab26fSDiego Novillo ///
134de1ab26fSDiego Novillo /// \param OS Stream to emit the output to.
135*aae1ed8eSDiego Novillo void FunctionSamples::print(raw_ostream &OS, unsigned Indent) const {
136de1ab26fSDiego Novillo   OS << TotalSamples << ", " << TotalHeadSamples << ", " << BodySamples.size()
137de1ab26fSDiego Novillo      << " sampled lines\n";
138d5336ae2SDiego Novillo   for (const auto &SI : BodySamples) {
139d5336ae2SDiego Novillo     LineLocation Loc = SI.first;
140d5336ae2SDiego Novillo     const SampleRecord &Sample = SI.second;
141*aae1ed8eSDiego Novillo     OS.indent(Indent);
142*aae1ed8eSDiego Novillo     OS << "line offset: " << Loc.LineOffset
143c572e92cSDiego Novillo        << ", discriminator: " << Loc.Discriminator
144c572e92cSDiego Novillo        << ", number of samples: " << Sample.getSamples();
145c572e92cSDiego Novillo     if (Sample.hasCalls()) {
146c572e92cSDiego Novillo       OS << ", calls:";
147d5336ae2SDiego Novillo       for (const auto &I : Sample.getCallTargets())
148d5336ae2SDiego Novillo         OS << " " << I.first() << ":" << I.second;
149c572e92cSDiego Novillo     }
150c572e92cSDiego Novillo     OS << "\n";
151c572e92cSDiego Novillo   }
152*aae1ed8eSDiego Novillo   for (const auto &CS : CallsiteSamples) {
153*aae1ed8eSDiego Novillo     CallsiteLocation Loc = CS.first;
154*aae1ed8eSDiego Novillo     const FunctionSamples &CalleeSamples = CS.second;
155*aae1ed8eSDiego Novillo     OS.indent(Indent);
156*aae1ed8eSDiego Novillo     OS << "line offset: " << Loc.LineOffset
157*aae1ed8eSDiego Novillo        << ", discriminator: " << Loc.Discriminator
158*aae1ed8eSDiego Novillo        << ", inlined callee: " << Loc.CalleeName << ": ";
159*aae1ed8eSDiego Novillo     CalleeSamples.print(OS, Indent + 2);
160*aae1ed8eSDiego Novillo   }
161de1ab26fSDiego Novillo }
162de1ab26fSDiego Novillo 
163de1ab26fSDiego Novillo /// \brief Dump the function profile for \p FName.
164de1ab26fSDiego Novillo ///
165de1ab26fSDiego Novillo /// \param FName Name of the function to print.
166d5336ae2SDiego Novillo /// \param OS Stream to emit the output to.
167d5336ae2SDiego Novillo void SampleProfileReader::dumpFunctionProfile(StringRef FName,
168d5336ae2SDiego Novillo                                               raw_ostream &OS) {
169d5336ae2SDiego Novillo   OS << "Function: " << FName << ": ";
170d5336ae2SDiego Novillo   Profiles[FName].print(OS);
171de1ab26fSDiego Novillo }
172de1ab26fSDiego Novillo 
173d5336ae2SDiego Novillo /// \brief Dump all the function profiles found on stream \p OS.
174d5336ae2SDiego Novillo void SampleProfileReader::dump(raw_ostream &OS) {
175d5336ae2SDiego Novillo   for (const auto &I : Profiles)
176d5336ae2SDiego Novillo     dumpFunctionProfile(I.getKey(), OS);
177de1ab26fSDiego Novillo }
178de1ab26fSDiego Novillo 
1796722688eSDehao Chen /// \brief Parse \p Input as function head.
1806722688eSDehao Chen ///
1816722688eSDehao Chen /// Parse one line of \p Input, and update function name in \p FName,
1826722688eSDehao Chen /// function's total sample count in \p NumSamples, function's entry
1836722688eSDehao Chen /// count in \p NumHeadSamples.
1846722688eSDehao Chen ///
1856722688eSDehao Chen /// \returns true if parsing is successful.
1866722688eSDehao Chen static bool ParseHead(const StringRef &Input, StringRef &FName,
1876722688eSDehao Chen                       unsigned &NumSamples, unsigned &NumHeadSamples) {
1886722688eSDehao Chen   if (Input[0] == ' ')
1896722688eSDehao Chen     return false;
1906722688eSDehao Chen   size_t n2 = Input.rfind(':');
1916722688eSDehao Chen   size_t n1 = Input.rfind(':', n2 - 1);
1926722688eSDehao Chen   FName = Input.substr(0, n1);
1936722688eSDehao Chen   if (Input.substr(n1 + 1, n2 - n1 - 1).getAsInteger(10, NumSamples))
1946722688eSDehao Chen     return false;
1956722688eSDehao Chen   if (Input.substr(n2 + 1).getAsInteger(10, NumHeadSamples))
1966722688eSDehao Chen     return false;
1976722688eSDehao Chen   return true;
1986722688eSDehao Chen }
1996722688eSDehao Chen 
2006722688eSDehao Chen /// \brief Parse \p Input as line sample.
2016722688eSDehao Chen ///
2026722688eSDehao Chen /// \param Input input line.
2036722688eSDehao Chen /// \param IsCallsite true if the line represents an inlined callsite.
2046722688eSDehao Chen /// \param Depth the depth of the inline stack.
2056722688eSDehao Chen /// \param NumSamples total samples of the line/inlined callsite.
2066722688eSDehao Chen /// \param LineOffset line offset to the start of the function.
2076722688eSDehao Chen /// \param Discriminator discriminator of the line.
2086722688eSDehao Chen /// \param TargetCountMap map from indirect call target to count.
2096722688eSDehao Chen ///
2106722688eSDehao Chen /// returns true if parsing is successful.
2116722688eSDehao Chen static bool ParseLine(const StringRef &Input, bool &IsCallsite, unsigned &Depth,
2126722688eSDehao Chen                       unsigned &NumSamples, unsigned &LineOffset,
2136722688eSDehao Chen                       unsigned &Discriminator, StringRef &CalleeName,
2146722688eSDehao Chen                       DenseMap<StringRef, unsigned> &TargetCountMap) {
2156722688eSDehao Chen   for (Depth = 0; Input[Depth] == ' '; Depth++)
2166722688eSDehao Chen     ;
2176722688eSDehao Chen   if (Depth == 0)
2186722688eSDehao Chen     return false;
2196722688eSDehao Chen 
2206722688eSDehao Chen   size_t n1 = Input.find(':');
2216722688eSDehao Chen   StringRef Loc = Input.substr(Depth, n1 - Depth);
2226722688eSDehao Chen   size_t n2 = Loc.find('.');
2236722688eSDehao Chen   if (n2 == StringRef::npos) {
2246722688eSDehao Chen     if (Loc.getAsInteger(10, LineOffset))
2256722688eSDehao Chen       return false;
2266722688eSDehao Chen     Discriminator = 0;
2276722688eSDehao Chen   } else {
2286722688eSDehao Chen     if (Loc.substr(0, n2).getAsInteger(10, LineOffset))
2296722688eSDehao Chen       return false;
2306722688eSDehao Chen     if (Loc.substr(n2 + 1).getAsInteger(10, Discriminator))
2316722688eSDehao Chen       return false;
2326722688eSDehao Chen   }
2336722688eSDehao Chen 
2346722688eSDehao Chen   StringRef Rest = Input.substr(n1 + 2);
2356722688eSDehao Chen   if (Rest[0] >= '0' && Rest[0] <= '9') {
2366722688eSDehao Chen     IsCallsite = false;
2376722688eSDehao Chen     size_t n3 = Rest.find(' ');
2386722688eSDehao Chen     if (n3 == StringRef::npos) {
2396722688eSDehao Chen       if (Rest.getAsInteger(10, NumSamples))
2406722688eSDehao Chen         return false;
2416722688eSDehao Chen     } else {
2426722688eSDehao Chen       if (Rest.substr(0, n3).getAsInteger(10, NumSamples))
2436722688eSDehao Chen         return false;
2446722688eSDehao Chen     }
2456722688eSDehao Chen     while (n3 != StringRef::npos) {
2466722688eSDehao Chen       n3 += Rest.substr(n3).find_first_not_of(' ');
2476722688eSDehao Chen       Rest = Rest.substr(n3);
2486722688eSDehao Chen       n3 = Rest.find(' ');
2496722688eSDehao Chen       StringRef pair = Rest;
2506722688eSDehao Chen       if (n3 != StringRef::npos) {
2516722688eSDehao Chen         pair = Rest.substr(0, n3);
2526722688eSDehao Chen       }
2536722688eSDehao Chen       int n4 = pair.find(':');
2546722688eSDehao Chen       unsigned count;
2556722688eSDehao Chen       if (pair.substr(n4 + 1).getAsInteger(10, count))
2566722688eSDehao Chen         return false;
2576722688eSDehao Chen       TargetCountMap[pair.substr(0, n4)] = count;
2586722688eSDehao Chen     }
2596722688eSDehao Chen   } else {
2606722688eSDehao Chen     IsCallsite = true;
2616722688eSDehao Chen     int n3 = Rest.find_last_of(':');
2626722688eSDehao Chen     CalleeName = Rest.substr(0, n3);
2636722688eSDehao Chen     if (Rest.substr(n3 + 1).getAsInteger(10, NumSamples))
2646722688eSDehao Chen       return false;
2656722688eSDehao Chen   }
2666722688eSDehao Chen   return true;
2676722688eSDehao Chen }
2686722688eSDehao Chen 
269de1ab26fSDiego Novillo /// \brief Load samples from a text file.
270de1ab26fSDiego Novillo ///
271de1ab26fSDiego Novillo /// See the documentation at the top of the file for an explanation of
272de1ab26fSDiego Novillo /// the expected format.
273de1ab26fSDiego Novillo ///
274de1ab26fSDiego Novillo /// \returns true if the file was loaded successfully, false otherwise.
275c572e92cSDiego Novillo std::error_code SampleProfileReaderText::read() {
276c572e92cSDiego Novillo   line_iterator LineIt(*Buffer, /*SkipBlanks=*/true, '#');
277de1ab26fSDiego Novillo 
278*aae1ed8eSDiego Novillo   InlineCallStack InlineStack;
2796722688eSDehao Chen 
2806722688eSDehao Chen   for (; !LineIt.is_at_eof(); ++LineIt) {
2816722688eSDehao Chen     if ((*LineIt)[(*LineIt).find_first_not_of(' ')] == '#')
2826722688eSDehao Chen       continue;
283de1ab26fSDiego Novillo     // Read the header of each function.
284de1ab26fSDiego Novillo     //
285de1ab26fSDiego Novillo     // Note that for function identifiers we are actually expecting
286de1ab26fSDiego Novillo     // mangled names, but we may not always get them. This happens when
287de1ab26fSDiego Novillo     // the compiler decides not to emit the function (e.g., it was inlined
288de1ab26fSDiego Novillo     // and removed). In this case, the binary will not have the linkage
289de1ab26fSDiego Novillo     // name for the function, so the profiler will emit the function's
290de1ab26fSDiego Novillo     // unmangled name, which may contain characters like ':' and '>' in its
291de1ab26fSDiego Novillo     // name (member functions, templates, etc).
292de1ab26fSDiego Novillo     //
293de1ab26fSDiego Novillo     // The only requirement we place on the identifier, then, is that it
294de1ab26fSDiego Novillo     // should not begin with a number.
2956722688eSDehao Chen     if ((*LineIt)[0] != ' ') {
2966722688eSDehao Chen       unsigned NumSamples, NumHeadSamples;
2976722688eSDehao Chen       StringRef FName;
2986722688eSDehao Chen       if (!ParseHead(*LineIt, FName, NumSamples, NumHeadSamples)) {
2993376a787SDiego Novillo         reportError(LineIt.line_number(),
300de1ab26fSDiego Novillo                     "Expected 'mangled_name:NUM:NUM', found " + *LineIt);
301c572e92cSDiego Novillo         return sampleprof_error::malformed;
302de1ab26fSDiego Novillo       }
303de1ab26fSDiego Novillo       Profiles[FName] = FunctionSamples();
304de1ab26fSDiego Novillo       FunctionSamples &FProfile = Profiles[FName];
305de1ab26fSDiego Novillo       FProfile.addTotalSamples(NumSamples);
306de1ab26fSDiego Novillo       FProfile.addHeadSamples(NumHeadSamples);
3076722688eSDehao Chen       InlineStack.clear();
3086722688eSDehao Chen       InlineStack.push_back(&FProfile);
3096722688eSDehao Chen     } else {
3106722688eSDehao Chen       unsigned NumSamples;
3116722688eSDehao Chen       StringRef FName;
3126722688eSDehao Chen       DenseMap<StringRef, unsigned> TargetCountMap;
3136722688eSDehao Chen       bool IsCallsite;
3146722688eSDehao Chen       unsigned Depth, LineOffset, Discriminator;
3156722688eSDehao Chen       if (!ParseLine(*LineIt, IsCallsite, Depth, NumSamples, LineOffset,
3166722688eSDehao Chen                      Discriminator, FName, TargetCountMap)) {
3173376a787SDiego Novillo         reportError(LineIt.line_number(),
3183376a787SDiego Novillo                     "Expected 'NUM[.NUM]: NUM[ mangled_name:NUM]*', found " +
3193376a787SDiego Novillo                         *LineIt);
320c572e92cSDiego Novillo         return sampleprof_error::malformed;
321de1ab26fSDiego Novillo       }
3226722688eSDehao Chen       if (IsCallsite) {
3236722688eSDehao Chen         while (InlineStack.size() > Depth) {
3246722688eSDehao Chen           InlineStack.pop_back();
325c572e92cSDiego Novillo         }
3266722688eSDehao Chen         FunctionSamples &FSamples = InlineStack.back()->functionSamplesAt(
3276722688eSDehao Chen             CallsiteLocation(LineOffset, Discriminator, FName));
3286722688eSDehao Chen         FSamples.addTotalSamples(NumSamples);
3296722688eSDehao Chen         InlineStack.push_back(&FSamples);
3306722688eSDehao Chen       } else {
3316722688eSDehao Chen         while (InlineStack.size() > Depth) {
3326722688eSDehao Chen           InlineStack.pop_back();
3336722688eSDehao Chen         }
3346722688eSDehao Chen         FunctionSamples &FProfile = *InlineStack.back();
3356722688eSDehao Chen         for (const auto &name_count : TargetCountMap) {
336c572e92cSDiego Novillo           FProfile.addCalledTargetSamples(LineOffset, Discriminator,
3376722688eSDehao Chen                                           name_count.first, name_count.second);
338c572e92cSDiego Novillo         }
339de1ab26fSDiego Novillo         FProfile.addBodySamples(LineOffset, Discriminator, NumSamples);
3406722688eSDehao Chen       }
341de1ab26fSDiego Novillo     }
342de1ab26fSDiego Novillo   }
343de1ab26fSDiego Novillo 
344c572e92cSDiego Novillo   return sampleprof_error::success;
345de1ab26fSDiego Novillo }
346de1ab26fSDiego Novillo 
347d5336ae2SDiego Novillo template <typename T> ErrorOr<T> SampleProfileReaderBinary::readNumber() {
348c572e92cSDiego Novillo   unsigned NumBytesRead = 0;
349c572e92cSDiego Novillo   std::error_code EC;
350c572e92cSDiego Novillo   uint64_t Val = decodeULEB128(Data, &NumBytesRead);
351c572e92cSDiego Novillo 
352c572e92cSDiego Novillo   if (Val > std::numeric_limits<T>::max())
353c572e92cSDiego Novillo     EC = sampleprof_error::malformed;
354c572e92cSDiego Novillo   else if (Data + NumBytesRead > End)
355c572e92cSDiego Novillo     EC = sampleprof_error::truncated;
356c572e92cSDiego Novillo   else
357c572e92cSDiego Novillo     EC = sampleprof_error::success;
358c572e92cSDiego Novillo 
359c572e92cSDiego Novillo   if (EC) {
3603376a787SDiego Novillo     reportError(0, EC.message());
361c572e92cSDiego Novillo     return EC;
362c572e92cSDiego Novillo   }
363c572e92cSDiego Novillo 
364c572e92cSDiego Novillo   Data += NumBytesRead;
365c572e92cSDiego Novillo   return static_cast<T>(Val);
366c572e92cSDiego Novillo }
367c572e92cSDiego Novillo 
368c572e92cSDiego Novillo ErrorOr<StringRef> SampleProfileReaderBinary::readString() {
369c572e92cSDiego Novillo   std::error_code EC;
370c572e92cSDiego Novillo   StringRef Str(reinterpret_cast<const char *>(Data));
371c572e92cSDiego Novillo   if (Data + Str.size() + 1 > End) {
372c572e92cSDiego Novillo     EC = sampleprof_error::truncated;
3733376a787SDiego Novillo     reportError(0, EC.message());
374c572e92cSDiego Novillo     return EC;
375c572e92cSDiego Novillo   }
376c572e92cSDiego Novillo 
377c572e92cSDiego Novillo   Data += Str.size() + 1;
378c572e92cSDiego Novillo   return Str;
379c572e92cSDiego Novillo }
380c572e92cSDiego Novillo 
381c572e92cSDiego Novillo std::error_code SampleProfileReaderBinary::read() {
382c572e92cSDiego Novillo   while (!at_eof()) {
383c572e92cSDiego Novillo     auto FName(readString());
384c572e92cSDiego Novillo     if (std::error_code EC = FName.getError())
385c572e92cSDiego Novillo       return EC;
386c572e92cSDiego Novillo 
387c572e92cSDiego Novillo     Profiles[*FName] = FunctionSamples();
388c572e92cSDiego Novillo     FunctionSamples &FProfile = Profiles[*FName];
389c572e92cSDiego Novillo 
390c572e92cSDiego Novillo     auto Val = readNumber<unsigned>();
391c572e92cSDiego Novillo     if (std::error_code EC = Val.getError())
392c572e92cSDiego Novillo       return EC;
393c572e92cSDiego Novillo     FProfile.addTotalSamples(*Val);
394c572e92cSDiego Novillo 
395c572e92cSDiego Novillo     Val = readNumber<unsigned>();
396c572e92cSDiego Novillo     if (std::error_code EC = Val.getError())
397c572e92cSDiego Novillo       return EC;
398c572e92cSDiego Novillo     FProfile.addHeadSamples(*Val);
399c572e92cSDiego Novillo 
400c572e92cSDiego Novillo     // Read the samples in the body.
401c572e92cSDiego Novillo     auto NumRecords = readNumber<unsigned>();
402c572e92cSDiego Novillo     if (std::error_code EC = NumRecords.getError())
403c572e92cSDiego Novillo       return EC;
404c572e92cSDiego Novillo     for (unsigned I = 0; I < *NumRecords; ++I) {
405c572e92cSDiego Novillo       auto LineOffset = readNumber<uint64_t>();
406c572e92cSDiego Novillo       if (std::error_code EC = LineOffset.getError())
407c572e92cSDiego Novillo         return EC;
408c572e92cSDiego Novillo 
409c572e92cSDiego Novillo       auto Discriminator = readNumber<uint64_t>();
410c572e92cSDiego Novillo       if (std::error_code EC = Discriminator.getError())
411c572e92cSDiego Novillo         return EC;
412c572e92cSDiego Novillo 
413c572e92cSDiego Novillo       auto NumSamples = readNumber<uint64_t>();
414c572e92cSDiego Novillo       if (std::error_code EC = NumSamples.getError())
415c572e92cSDiego Novillo         return EC;
416c572e92cSDiego Novillo 
417c572e92cSDiego Novillo       auto NumCalls = readNumber<unsigned>();
418c572e92cSDiego Novillo       if (std::error_code EC = NumCalls.getError())
419c572e92cSDiego Novillo         return EC;
420c572e92cSDiego Novillo 
421c572e92cSDiego Novillo       for (unsigned J = 0; J < *NumCalls; ++J) {
422c572e92cSDiego Novillo         auto CalledFunction(readString());
423c572e92cSDiego Novillo         if (std::error_code EC = CalledFunction.getError())
424c572e92cSDiego Novillo           return EC;
425c572e92cSDiego Novillo 
426c572e92cSDiego Novillo         auto CalledFunctionSamples = readNumber<uint64_t>();
427c572e92cSDiego Novillo         if (std::error_code EC = CalledFunctionSamples.getError())
428c572e92cSDiego Novillo           return EC;
429c572e92cSDiego Novillo 
430c572e92cSDiego Novillo         FProfile.addCalledTargetSamples(*LineOffset, *Discriminator,
431c572e92cSDiego Novillo                                         *CalledFunction,
432c572e92cSDiego Novillo                                         *CalledFunctionSamples);
433c572e92cSDiego Novillo       }
434c572e92cSDiego Novillo 
435c572e92cSDiego Novillo       FProfile.addBodySamples(*LineOffset, *Discriminator, *NumSamples);
436c572e92cSDiego Novillo     }
437c572e92cSDiego Novillo   }
438c572e92cSDiego Novillo 
439c572e92cSDiego Novillo   return sampleprof_error::success;
440c572e92cSDiego Novillo }
441c572e92cSDiego Novillo 
442c572e92cSDiego Novillo std::error_code SampleProfileReaderBinary::readHeader() {
443c572e92cSDiego Novillo   Data = reinterpret_cast<const uint8_t *>(Buffer->getBufferStart());
444c572e92cSDiego Novillo   End = Data + Buffer->getBufferSize();
445c572e92cSDiego Novillo 
446c572e92cSDiego Novillo   // Read and check the magic identifier.
447c572e92cSDiego Novillo   auto Magic = readNumber<uint64_t>();
448c572e92cSDiego Novillo   if (std::error_code EC = Magic.getError())
449c572e92cSDiego Novillo     return EC;
450c572e92cSDiego Novillo   else if (*Magic != SPMagic())
451c572e92cSDiego Novillo     return sampleprof_error::bad_magic;
452c572e92cSDiego Novillo 
453c572e92cSDiego Novillo   // Read the version number.
454c572e92cSDiego Novillo   auto Version = readNumber<uint64_t>();
455c572e92cSDiego Novillo   if (std::error_code EC = Version.getError())
456c572e92cSDiego Novillo     return EC;
457c572e92cSDiego Novillo   else if (*Version != SPVersion())
458c572e92cSDiego Novillo     return sampleprof_error::unsupported_version;
459c572e92cSDiego Novillo 
460c572e92cSDiego Novillo   return sampleprof_error::success;
461c572e92cSDiego Novillo }
462c572e92cSDiego Novillo 
463c572e92cSDiego Novillo bool SampleProfileReaderBinary::hasFormat(const MemoryBuffer &Buffer) {
464c572e92cSDiego Novillo   const uint8_t *Data =
465c572e92cSDiego Novillo       reinterpret_cast<const uint8_t *>(Buffer.getBufferStart());
466c572e92cSDiego Novillo   uint64_t Magic = decodeULEB128(Data);
467c572e92cSDiego Novillo   return Magic == SPMagic();
468c572e92cSDiego Novillo }
469c572e92cSDiego Novillo 
4703376a787SDiego Novillo bool SourceInfo::operator<(const SourceInfo &P) const {
4713376a787SDiego Novillo   if (Line != P.Line)
4723376a787SDiego Novillo     return Line < P.Line;
4733376a787SDiego Novillo   if (StartLine != P.StartLine)
4743376a787SDiego Novillo     return StartLine < P.StartLine;
4753376a787SDiego Novillo   if (Discriminator != P.Discriminator)
4763376a787SDiego Novillo     return Discriminator < P.Discriminator;
4773376a787SDiego Novillo   return FuncName < P.FuncName;
4783376a787SDiego Novillo }
4793376a787SDiego Novillo 
4803376a787SDiego Novillo std::error_code SampleProfileReaderGCC::skipNextWord() {
4813376a787SDiego Novillo   uint32_t dummy;
4823376a787SDiego Novillo   if (!GcovBuffer.readInt(dummy))
4833376a787SDiego Novillo     return sampleprof_error::truncated;
4843376a787SDiego Novillo   return sampleprof_error::success;
4853376a787SDiego Novillo }
4863376a787SDiego Novillo 
4873376a787SDiego Novillo template <typename T> ErrorOr<T> SampleProfileReaderGCC::readNumber() {
4883376a787SDiego Novillo   if (sizeof(T) <= sizeof(uint32_t)) {
4893376a787SDiego Novillo     uint32_t Val;
4903376a787SDiego Novillo     if (GcovBuffer.readInt(Val) && Val <= std::numeric_limits<T>::max())
4913376a787SDiego Novillo       return static_cast<T>(Val);
4923376a787SDiego Novillo   } else if (sizeof(T) <= sizeof(uint64_t)) {
4933376a787SDiego Novillo     uint64_t Val;
4943376a787SDiego Novillo     if (GcovBuffer.readInt64(Val) && Val <= std::numeric_limits<T>::max())
4953376a787SDiego Novillo       return static_cast<T>(Val);
4963376a787SDiego Novillo   }
4973376a787SDiego Novillo 
4983376a787SDiego Novillo   std::error_code EC = sampleprof_error::malformed;
4993376a787SDiego Novillo   reportError(0, EC.message());
5003376a787SDiego Novillo   return EC;
5013376a787SDiego Novillo }
5023376a787SDiego Novillo 
5033376a787SDiego Novillo ErrorOr<StringRef> SampleProfileReaderGCC::readString() {
5043376a787SDiego Novillo   StringRef Str;
5053376a787SDiego Novillo   if (!GcovBuffer.readString(Str))
5063376a787SDiego Novillo     return sampleprof_error::truncated;
5073376a787SDiego Novillo   return Str;
5083376a787SDiego Novillo }
5093376a787SDiego Novillo 
5103376a787SDiego Novillo std::error_code SampleProfileReaderGCC::readHeader() {
5113376a787SDiego Novillo   // Read the magic identifier.
5123376a787SDiego Novillo   if (!GcovBuffer.readGCDAFormat())
5133376a787SDiego Novillo     return sampleprof_error::unrecognized_format;
5143376a787SDiego Novillo 
5153376a787SDiego Novillo   // Read the version number. Note - the GCC reader does not validate this
5163376a787SDiego Novillo   // version, but the profile creator generates v704.
5173376a787SDiego Novillo   GCOV::GCOVVersion version;
5183376a787SDiego Novillo   if (!GcovBuffer.readGCOVVersion(version))
5193376a787SDiego Novillo     return sampleprof_error::unrecognized_format;
5203376a787SDiego Novillo 
5213376a787SDiego Novillo   if (version != GCOV::V704)
5223376a787SDiego Novillo     return sampleprof_error::unsupported_version;
5233376a787SDiego Novillo 
5243376a787SDiego Novillo   // Skip the empty integer.
5253376a787SDiego Novillo   if (std::error_code EC = skipNextWord())
5263376a787SDiego Novillo     return EC;
5273376a787SDiego Novillo 
5283376a787SDiego Novillo   return sampleprof_error::success;
5293376a787SDiego Novillo }
5303376a787SDiego Novillo 
5313376a787SDiego Novillo std::error_code SampleProfileReaderGCC::readSectionTag(uint32_t Expected) {
5323376a787SDiego Novillo   uint32_t Tag;
5333376a787SDiego Novillo   if (!GcovBuffer.readInt(Tag))
5343376a787SDiego Novillo     return sampleprof_error::truncated;
5353376a787SDiego Novillo 
5363376a787SDiego Novillo   if (Tag != Expected)
5373376a787SDiego Novillo     return sampleprof_error::malformed;
5383376a787SDiego Novillo 
5393376a787SDiego Novillo   if (std::error_code EC = skipNextWord())
5403376a787SDiego Novillo     return EC;
5413376a787SDiego Novillo 
5423376a787SDiego Novillo   return sampleprof_error::success;
5433376a787SDiego Novillo }
5443376a787SDiego Novillo 
5453376a787SDiego Novillo std::error_code SampleProfileReaderGCC::readNameTable() {
5463376a787SDiego Novillo   if (std::error_code EC = readSectionTag(GCOVTagAFDOFileNames))
5473376a787SDiego Novillo     return EC;
5483376a787SDiego Novillo 
5493376a787SDiego Novillo   uint32_t Size;
5503376a787SDiego Novillo   if (!GcovBuffer.readInt(Size))
5513376a787SDiego Novillo     return sampleprof_error::truncated;
5523376a787SDiego Novillo 
5533376a787SDiego Novillo   for (uint32_t I = 0; I < Size; ++I) {
5543376a787SDiego Novillo     StringRef Str;
5553376a787SDiego Novillo     if (!GcovBuffer.readString(Str))
5563376a787SDiego Novillo       return sampleprof_error::truncated;
5573376a787SDiego Novillo     Names.push_back(Str);
5583376a787SDiego Novillo   }
5593376a787SDiego Novillo 
5603376a787SDiego Novillo   return sampleprof_error::success;
5613376a787SDiego Novillo }
5623376a787SDiego Novillo 
5633376a787SDiego Novillo std::error_code SampleProfileReaderGCC::readFunctionProfiles() {
5643376a787SDiego Novillo   if (std::error_code EC = readSectionTag(GCOVTagAFDOFunction))
5653376a787SDiego Novillo     return EC;
5663376a787SDiego Novillo 
5673376a787SDiego Novillo   uint32_t NumFunctions;
5683376a787SDiego Novillo   if (!GcovBuffer.readInt(NumFunctions))
5693376a787SDiego Novillo     return sampleprof_error::truncated;
5703376a787SDiego Novillo 
571*aae1ed8eSDiego Novillo   InlineCallStack Stack;
5723376a787SDiego Novillo   for (uint32_t I = 0; I < NumFunctions; ++I)
573*aae1ed8eSDiego Novillo     if (std::error_code EC = readOneFunctionProfile(Stack, true, 0))
5743376a787SDiego Novillo       return EC;
5753376a787SDiego Novillo 
5763376a787SDiego Novillo   return sampleprof_error::success;
5773376a787SDiego Novillo }
5783376a787SDiego Novillo 
579*aae1ed8eSDiego Novillo std::error_code SampleProfileReaderGCC::readOneFunctionProfile(
580*aae1ed8eSDiego Novillo     const InlineCallStack &InlineStack, bool Update, uint32_t Offset) {
5813376a787SDiego Novillo   uint64_t HeadCount = 0;
582*aae1ed8eSDiego Novillo   if (InlineStack.size() == 0)
5833376a787SDiego Novillo     if (!GcovBuffer.readInt64(HeadCount))
5843376a787SDiego Novillo       return sampleprof_error::truncated;
5853376a787SDiego Novillo 
5863376a787SDiego Novillo   uint32_t NameIdx;
5873376a787SDiego Novillo   if (!GcovBuffer.readInt(NameIdx))
5883376a787SDiego Novillo     return sampleprof_error::truncated;
5893376a787SDiego Novillo 
5903376a787SDiego Novillo   StringRef Name(Names[NameIdx]);
5913376a787SDiego Novillo 
5923376a787SDiego Novillo   uint32_t NumPosCounts;
5933376a787SDiego Novillo   if (!GcovBuffer.readInt(NumPosCounts))
5943376a787SDiego Novillo     return sampleprof_error::truncated;
5953376a787SDiego Novillo 
596*aae1ed8eSDiego Novillo   uint32_t NumCallsites;
597*aae1ed8eSDiego Novillo   if (!GcovBuffer.readInt(NumCallsites))
5983376a787SDiego Novillo     return sampleprof_error::truncated;
5993376a787SDiego Novillo 
600*aae1ed8eSDiego Novillo   FunctionSamples *FProfile = nullptr;
601*aae1ed8eSDiego Novillo   if (InlineStack.size() == 0) {
602*aae1ed8eSDiego Novillo     // If this is a top function that we have already processed, do not
603*aae1ed8eSDiego Novillo     // update its profile again.  This happens in the presence of
604*aae1ed8eSDiego Novillo     // function aliases.  Since these aliases share the same function
605*aae1ed8eSDiego Novillo     // body, there will be identical replicated profiles for the
606*aae1ed8eSDiego Novillo     // original function.  In this case, we simply not bother updating
607*aae1ed8eSDiego Novillo     // the profile of the original function.
608*aae1ed8eSDiego Novillo     FProfile = &Profiles[Name];
609*aae1ed8eSDiego Novillo     FProfile->addHeadSamples(HeadCount);
610*aae1ed8eSDiego Novillo     if (FProfile->getTotalSamples() > 0)
6113376a787SDiego Novillo       Update = false;
612*aae1ed8eSDiego Novillo   } else {
613*aae1ed8eSDiego Novillo     // Otherwise, we are reading an inlined instance. The top of the
614*aae1ed8eSDiego Novillo     // inline stack contains the profile of the caller. Insert this
615*aae1ed8eSDiego Novillo     // callee in the caller's CallsiteMap.
616*aae1ed8eSDiego Novillo     FunctionSamples *CallerProfile = InlineStack.front();
617*aae1ed8eSDiego Novillo     uint32_t LineOffset = Offset >> 16;
618*aae1ed8eSDiego Novillo     uint32_t Discriminator = Offset & 0xffff;
619*aae1ed8eSDiego Novillo     FProfile = &CallerProfile->functionSamplesAt(
620*aae1ed8eSDiego Novillo         CallsiteLocation(LineOffset, Discriminator, Name));
6213376a787SDiego Novillo   }
6223376a787SDiego Novillo 
6233376a787SDiego Novillo   for (uint32_t I = 0; I < NumPosCounts; ++I) {
6243376a787SDiego Novillo     uint32_t Offset;
6253376a787SDiego Novillo     if (!GcovBuffer.readInt(Offset))
6263376a787SDiego Novillo       return sampleprof_error::truncated;
6273376a787SDiego Novillo 
6283376a787SDiego Novillo     uint32_t NumTargets;
6293376a787SDiego Novillo     if (!GcovBuffer.readInt(NumTargets))
6303376a787SDiego Novillo       return sampleprof_error::truncated;
6313376a787SDiego Novillo 
6323376a787SDiego Novillo     uint64_t Count;
6333376a787SDiego Novillo     if (!GcovBuffer.readInt64(Count))
6343376a787SDiego Novillo       return sampleprof_error::truncated;
6353376a787SDiego Novillo 
636*aae1ed8eSDiego Novillo     // The line location is encoded in the offset as:
637*aae1ed8eSDiego Novillo     //   high 16 bits: line offset to the start of the function.
638*aae1ed8eSDiego Novillo     //   low 16 bits: discriminator.
639*aae1ed8eSDiego Novillo     uint32_t LineOffset = Offset >> 16;
640*aae1ed8eSDiego Novillo     uint32_t Discriminator = Offset & 0xffff;
6413376a787SDiego Novillo 
642*aae1ed8eSDiego Novillo     InlineCallStack NewStack;
643*aae1ed8eSDiego Novillo     NewStack.push_back(FProfile);
644*aae1ed8eSDiego Novillo     NewStack.insert(NewStack.end(), InlineStack.begin(), InlineStack.end());
645*aae1ed8eSDiego Novillo     if (Update) {
646*aae1ed8eSDiego Novillo       // Walk up the inline stack, adding the samples on this line to
647*aae1ed8eSDiego Novillo       // the total sample count of the callers in the chain.
648*aae1ed8eSDiego Novillo       for (auto CallerProfile : NewStack)
649*aae1ed8eSDiego Novillo         CallerProfile->addTotalSamples(Count);
650*aae1ed8eSDiego Novillo 
651*aae1ed8eSDiego Novillo       // Update the body samples for the current profile.
652*aae1ed8eSDiego Novillo       FProfile->addBodySamples(LineOffset, Discriminator, Count);
653*aae1ed8eSDiego Novillo     }
654*aae1ed8eSDiego Novillo 
655*aae1ed8eSDiego Novillo     // Process the list of functions called at an indirect call site.
656*aae1ed8eSDiego Novillo     // These are all the targets that a function pointer (or virtual
657*aae1ed8eSDiego Novillo     // function) resolved at runtime.
6583376a787SDiego Novillo     for (uint32_t J = 0; J < NumTargets; J++) {
6593376a787SDiego Novillo       uint32_t HistVal;
6603376a787SDiego Novillo       if (!GcovBuffer.readInt(HistVal))
6613376a787SDiego Novillo         return sampleprof_error::truncated;
6623376a787SDiego Novillo 
6633376a787SDiego Novillo       if (HistVal != HIST_TYPE_INDIR_CALL_TOPN)
6643376a787SDiego Novillo         return sampleprof_error::malformed;
6653376a787SDiego Novillo 
6663376a787SDiego Novillo       uint64_t TargetIdx;
6673376a787SDiego Novillo       if (!GcovBuffer.readInt64(TargetIdx))
6683376a787SDiego Novillo         return sampleprof_error::truncated;
6693376a787SDiego Novillo       StringRef TargetName(Names[TargetIdx]);
6703376a787SDiego Novillo 
6713376a787SDiego Novillo       uint64_t TargetCount;
6723376a787SDiego Novillo       if (!GcovBuffer.readInt64(TargetCount))
6733376a787SDiego Novillo         return sampleprof_error::truncated;
6743376a787SDiego Novillo 
6753376a787SDiego Novillo       if (Update) {
6763376a787SDiego Novillo         FunctionSamples &TargetProfile = Profiles[TargetName];
677*aae1ed8eSDiego Novillo         TargetProfile.addCalledTargetSamples(LineOffset, Discriminator,
678*aae1ed8eSDiego Novillo                                              TargetName, TargetCount);
6793376a787SDiego Novillo       }
6803376a787SDiego Novillo     }
6813376a787SDiego Novillo   }
6823376a787SDiego Novillo 
683*aae1ed8eSDiego Novillo   // Process all the inlined callers into the current function. These
684*aae1ed8eSDiego Novillo   // are all the callsites that were inlined into this function.
685*aae1ed8eSDiego Novillo   for (uint32_t I = 0; I < NumCallsites; I++) {
6863376a787SDiego Novillo     // The offset is encoded as:
6873376a787SDiego Novillo     //   high 16 bits: line offset to the start of the function.
6883376a787SDiego Novillo     //   low 16 bits: discriminator.
6893376a787SDiego Novillo     uint32_t Offset;
6903376a787SDiego Novillo     if (!GcovBuffer.readInt(Offset))
6913376a787SDiego Novillo       return sampleprof_error::truncated;
692*aae1ed8eSDiego Novillo     InlineCallStack NewStack;
693*aae1ed8eSDiego Novillo     NewStack.push_back(FProfile);
694*aae1ed8eSDiego Novillo     NewStack.insert(NewStack.end(), InlineStack.begin(), InlineStack.end());
695*aae1ed8eSDiego Novillo     if (std::error_code EC = readOneFunctionProfile(NewStack, Update, Offset))
6963376a787SDiego Novillo       return EC;
6973376a787SDiego Novillo   }
6983376a787SDiego Novillo 
6993376a787SDiego Novillo   return sampleprof_error::success;
7003376a787SDiego Novillo }
7013376a787SDiego Novillo 
7023376a787SDiego Novillo /// \brief Read a GCC AutoFDO profile.
7033376a787SDiego Novillo ///
7043376a787SDiego Novillo /// This format is generated by the Linux Perf conversion tool at
7053376a787SDiego Novillo /// https://github.com/google/autofdo.
7063376a787SDiego Novillo std::error_code SampleProfileReaderGCC::read() {
7073376a787SDiego Novillo   // Read the string table.
7083376a787SDiego Novillo   if (std::error_code EC = readNameTable())
7093376a787SDiego Novillo     return EC;
7103376a787SDiego Novillo 
7113376a787SDiego Novillo   // Read the source profile.
7123376a787SDiego Novillo   if (std::error_code EC = readFunctionProfiles())
7133376a787SDiego Novillo     return EC;
7143376a787SDiego Novillo 
7153376a787SDiego Novillo   return sampleprof_error::success;
7163376a787SDiego Novillo }
7173376a787SDiego Novillo 
7183376a787SDiego Novillo bool SampleProfileReaderGCC::hasFormat(const MemoryBuffer &Buffer) {
7193376a787SDiego Novillo   StringRef Magic(reinterpret_cast<const char *>(Buffer.getBufferStart()));
7203376a787SDiego Novillo   return Magic == "adcg*704";
7213376a787SDiego Novillo }
7223376a787SDiego Novillo 
723c572e92cSDiego Novillo /// \brief Prepare a memory buffer for the contents of \p Filename.
724de1ab26fSDiego Novillo ///
725c572e92cSDiego Novillo /// \returns an error code indicating the status of the buffer.
726fcd55607SDiego Novillo static ErrorOr<std::unique_ptr<MemoryBuffer>>
727fcd55607SDiego Novillo setupMemoryBuffer(std::string Filename) {
728c572e92cSDiego Novillo   auto BufferOrErr = MemoryBuffer::getFileOrSTDIN(Filename);
729c572e92cSDiego Novillo   if (std::error_code EC = BufferOrErr.getError())
730c572e92cSDiego Novillo     return EC;
731fcd55607SDiego Novillo   auto Buffer = std::move(BufferOrErr.get());
732c572e92cSDiego Novillo 
733c572e92cSDiego Novillo   // Sanity check the file.
734c572e92cSDiego Novillo   if (Buffer->getBufferSize() > std::numeric_limits<unsigned>::max())
735c572e92cSDiego Novillo     return sampleprof_error::too_large;
736c572e92cSDiego Novillo 
737fcd55607SDiego Novillo   return std::move(Buffer);
738c572e92cSDiego Novillo }
739c572e92cSDiego Novillo 
740c572e92cSDiego Novillo /// \brief Create a sample profile reader based on the format of the input file.
741c572e92cSDiego Novillo ///
742c572e92cSDiego Novillo /// \param Filename The file to open.
743c572e92cSDiego Novillo ///
744c572e92cSDiego Novillo /// \param Reader The reader to instantiate according to \p Filename's format.
745c572e92cSDiego Novillo ///
746c572e92cSDiego Novillo /// \param C The LLVM context to use to emit diagnostics.
747c572e92cSDiego Novillo ///
748c572e92cSDiego Novillo /// \returns an error code indicating the status of the created reader.
749fcd55607SDiego Novillo ErrorOr<std::unique_ptr<SampleProfileReader>>
750fcd55607SDiego Novillo SampleProfileReader::create(StringRef Filename, LLVMContext &C) {
751fcd55607SDiego Novillo   auto BufferOrError = setupMemoryBuffer(Filename);
752fcd55607SDiego Novillo   if (std::error_code EC = BufferOrError.getError())
753c572e92cSDiego Novillo     return EC;
754c572e92cSDiego Novillo 
755fcd55607SDiego Novillo   auto Buffer = std::move(BufferOrError.get());
756fcd55607SDiego Novillo   std::unique_ptr<SampleProfileReader> Reader;
757c572e92cSDiego Novillo   if (SampleProfileReaderBinary::hasFormat(*Buffer))
758c572e92cSDiego Novillo     Reader.reset(new SampleProfileReaderBinary(std::move(Buffer), C));
7593376a787SDiego Novillo   else if (SampleProfileReaderGCC::hasFormat(*Buffer))
7603376a787SDiego Novillo     Reader.reset(new SampleProfileReaderGCC(std::move(Buffer), C));
761c572e92cSDiego Novillo   else
762c572e92cSDiego Novillo     Reader.reset(new SampleProfileReaderText(std::move(Buffer), C));
763c572e92cSDiego Novillo 
764fcd55607SDiego Novillo   if (std::error_code EC = Reader->readHeader())
765fcd55607SDiego Novillo     return EC;
766fcd55607SDiego Novillo 
767fcd55607SDiego Novillo   return std::move(Reader);
768de1ab26fSDiego Novillo }
769