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 ... ]
32de1ab26fSDiego Novillo //
33de1ab26fSDiego Novillo // The file may contain blank lines between sections and within a
34de1ab26fSDiego Novillo // section. However, the spacing within a single line is fixed. Additional
35de1ab26fSDiego Novillo // spaces will result in an error while reading the file.
36de1ab26fSDiego Novillo //
37de1ab26fSDiego Novillo // Function names must be mangled in order for the profile loader to
38de1ab26fSDiego Novillo // match them in the current translation unit. The two numbers in the
39de1ab26fSDiego Novillo // function header specify how many total samples were accumulated in the
40de1ab26fSDiego Novillo // function (first number), and the total number of samples accumulated
41de1ab26fSDiego Novillo // in the prologue of the function (second number). This head sample
42de1ab26fSDiego Novillo // count provides an indicator of how frequently the function is invoked.
43de1ab26fSDiego Novillo //
44de1ab26fSDiego Novillo // Each sampled line may contain several items. Some are optional (marked
45de1ab26fSDiego Novillo // below):
46de1ab26fSDiego Novillo //
47de1ab26fSDiego Novillo // a. Source line offset. This number represents the line number
48de1ab26fSDiego Novillo //    in the function where the sample was collected. The line number is
49de1ab26fSDiego Novillo //    always relative to the line where symbol of the function is
50de1ab26fSDiego Novillo //    defined. So, if the function has its header at line 280, the offset
51de1ab26fSDiego Novillo //    13 is at line 293 in the file.
52de1ab26fSDiego Novillo //
53de1ab26fSDiego Novillo //    Note that this offset should never be a negative number. This could
54de1ab26fSDiego Novillo //    happen in cases like macros. The debug machinery will register the
55de1ab26fSDiego Novillo //    line number at the point of macro expansion. So, if the macro was
56de1ab26fSDiego Novillo //    expanded in a line before the start of the function, the profile
57de1ab26fSDiego Novillo //    converter should emit a 0 as the offset (this means that the optimizers
58de1ab26fSDiego Novillo //    will not be able to associate a meaningful weight to the instructions
59de1ab26fSDiego Novillo //    in the macro).
60de1ab26fSDiego Novillo //
61de1ab26fSDiego Novillo // b. [OPTIONAL] Discriminator. This is used if the sampled program
62de1ab26fSDiego Novillo //    was compiled with DWARF discriminator support
63de1ab26fSDiego Novillo //    (http://wiki.dwarfstd.org/index.php?title=Path_Discriminators).
64de1ab26fSDiego Novillo //    DWARF discriminators are unsigned integer values that allow the
65de1ab26fSDiego Novillo //    compiler to distinguish between multiple execution paths on the
66de1ab26fSDiego Novillo //    same source line location.
67de1ab26fSDiego Novillo //
68de1ab26fSDiego Novillo //    For example, consider the line of code ``if (cond) foo(); else bar();``.
69de1ab26fSDiego Novillo //    If the predicate ``cond`` is true 80% of the time, then the edge
70de1ab26fSDiego Novillo //    into function ``foo`` should be considered to be taken most of the
71de1ab26fSDiego Novillo //    time. But both calls to ``foo`` and ``bar`` are at the same source
72de1ab26fSDiego Novillo //    line, so a sample count at that line is not sufficient. The
73de1ab26fSDiego Novillo //    compiler needs to know which part of that line is taken more
74de1ab26fSDiego Novillo //    frequently.
75de1ab26fSDiego Novillo //
76de1ab26fSDiego Novillo //    This is what discriminators provide. In this case, the calls to
77de1ab26fSDiego Novillo //    ``foo`` and ``bar`` will be at the same line, but will have
78de1ab26fSDiego Novillo //    different discriminator values. This allows the compiler to correctly
79de1ab26fSDiego Novillo //    set edge weights into ``foo`` and ``bar``.
80de1ab26fSDiego Novillo //
81de1ab26fSDiego Novillo // c. Number of samples. This is an integer quantity representing the
82de1ab26fSDiego Novillo //    number of samples collected by the profiler at this source
83de1ab26fSDiego Novillo //    location.
84de1ab26fSDiego Novillo //
85de1ab26fSDiego Novillo // d. [OPTIONAL] Potential call targets and samples. If present, this
86de1ab26fSDiego Novillo //    line contains a call instruction. This models both direct and
87de1ab26fSDiego Novillo //    number of samples. For example,
88de1ab26fSDiego Novillo //
89de1ab26fSDiego Novillo //      130: 7  foo:3  bar:2  baz:7
90de1ab26fSDiego Novillo //
91de1ab26fSDiego Novillo //    The above means that at relative line offset 130 there is a call
92de1ab26fSDiego Novillo //    instruction that calls one of ``foo()``, ``bar()`` and ``baz()``,
93de1ab26fSDiego Novillo //    with ``baz()`` being the relatively more frequently called target.
94de1ab26fSDiego Novillo //
95de1ab26fSDiego Novillo //===----------------------------------------------------------------------===//
96de1ab26fSDiego Novillo 
97de1ab26fSDiego Novillo #include "llvm/ProfileData/SampleProfReader.h"
98de1ab26fSDiego Novillo #include "llvm/Support/Debug.h"
99de1ab26fSDiego Novillo #include "llvm/Support/ErrorOr.h"
100c572e92cSDiego Novillo #include "llvm/Support/LEB128.h"
101de1ab26fSDiego Novillo #include "llvm/Support/LineIterator.h"
102c572e92cSDiego Novillo #include "llvm/Support/MemoryBuffer.h"
103de1ab26fSDiego Novillo #include "llvm/Support/Regex.h"
104de1ab26fSDiego Novillo 
105c572e92cSDiego Novillo using namespace llvm::sampleprof;
106de1ab26fSDiego Novillo using namespace llvm;
107de1ab26fSDiego Novillo 
108de1ab26fSDiego Novillo /// \brief Print the samples collected for a function on stream \p OS.
109de1ab26fSDiego Novillo ///
110de1ab26fSDiego Novillo /// \param OS Stream to emit the output to.
111de1ab26fSDiego Novillo void FunctionSamples::print(raw_ostream &OS) {
112de1ab26fSDiego Novillo   OS << TotalSamples << ", " << TotalHeadSamples << ", " << BodySamples.size()
113de1ab26fSDiego Novillo      << " sampled lines\n";
114d5336ae2SDiego Novillo   for (const auto &SI : BodySamples) {
115d5336ae2SDiego Novillo     LineLocation Loc = SI.first;
116d5336ae2SDiego Novillo     const SampleRecord &Sample = SI.second;
117c572e92cSDiego Novillo     OS << "\tline offset: " << Loc.LineOffset
118c572e92cSDiego Novillo        << ", discriminator: " << Loc.Discriminator
119c572e92cSDiego Novillo        << ", number of samples: " << Sample.getSamples();
120c572e92cSDiego Novillo     if (Sample.hasCalls()) {
121c572e92cSDiego Novillo       OS << ", calls:";
122d5336ae2SDiego Novillo       for (const auto &I : Sample.getCallTargets())
123d5336ae2SDiego Novillo         OS << " " << I.first() << ":" << I.second;
124c572e92cSDiego Novillo     }
125c572e92cSDiego Novillo     OS << "\n";
126c572e92cSDiego Novillo   }
127de1ab26fSDiego Novillo   OS << "\n";
128de1ab26fSDiego Novillo }
129de1ab26fSDiego Novillo 
130de1ab26fSDiego Novillo /// \brief Dump the function profile for \p FName.
131de1ab26fSDiego Novillo ///
132de1ab26fSDiego Novillo /// \param FName Name of the function to print.
133d5336ae2SDiego Novillo /// \param OS Stream to emit the output to.
134d5336ae2SDiego Novillo void SampleProfileReader::dumpFunctionProfile(StringRef FName,
135d5336ae2SDiego Novillo                                               raw_ostream &OS) {
136d5336ae2SDiego Novillo   OS << "Function: " << FName << ": ";
137d5336ae2SDiego Novillo   Profiles[FName].print(OS);
138de1ab26fSDiego Novillo }
139de1ab26fSDiego Novillo 
140d5336ae2SDiego Novillo /// \brief Dump all the function profiles found on stream \p OS.
141d5336ae2SDiego Novillo void SampleProfileReader::dump(raw_ostream &OS) {
142d5336ae2SDiego Novillo   for (const auto &I : Profiles)
143d5336ae2SDiego Novillo     dumpFunctionProfile(I.getKey(), OS);
144de1ab26fSDiego Novillo }
145de1ab26fSDiego Novillo 
146de1ab26fSDiego Novillo /// \brief Load samples from a text file.
147de1ab26fSDiego Novillo ///
148de1ab26fSDiego Novillo /// See the documentation at the top of the file for an explanation of
149de1ab26fSDiego Novillo /// the expected format.
150de1ab26fSDiego Novillo ///
151de1ab26fSDiego Novillo /// \returns true if the file was loaded successfully, false otherwise.
152c572e92cSDiego Novillo std::error_code SampleProfileReaderText::read() {
153c572e92cSDiego Novillo   line_iterator LineIt(*Buffer, /*SkipBlanks=*/true, '#');
154de1ab26fSDiego Novillo 
155de1ab26fSDiego Novillo   // Read the profile of each function. Since each function may be
156de1ab26fSDiego Novillo   // mentioned more than once, and we are collecting flat profiles,
157de1ab26fSDiego Novillo   // accumulate samples as we parse them.
158de1ab26fSDiego Novillo   Regex HeadRE("^([^0-9].*):([0-9]+):([0-9]+)$");
159c572e92cSDiego Novillo   Regex LineSampleRE("^([0-9]+)\\.?([0-9]+)?: ([0-9]+)(.*)$");
160c572e92cSDiego Novillo   Regex CallSampleRE(" +([^0-9 ][^ ]*):([0-9]+)");
161de1ab26fSDiego Novillo   while (!LineIt.is_at_eof()) {
162de1ab26fSDiego Novillo     // Read the header of each function.
163de1ab26fSDiego Novillo     //
164de1ab26fSDiego Novillo     // Note that for function identifiers we are actually expecting
165de1ab26fSDiego Novillo     // mangled names, but we may not always get them. This happens when
166de1ab26fSDiego Novillo     // the compiler decides not to emit the function (e.g., it was inlined
167de1ab26fSDiego Novillo     // and removed). In this case, the binary will not have the linkage
168de1ab26fSDiego Novillo     // name for the function, so the profiler will emit the function's
169de1ab26fSDiego Novillo     // unmangled name, which may contain characters like ':' and '>' in its
170de1ab26fSDiego Novillo     // name (member functions, templates, etc).
171de1ab26fSDiego Novillo     //
172de1ab26fSDiego Novillo     // The only requirement we place on the identifier, then, is that it
173de1ab26fSDiego Novillo     // should not begin with a number.
174c572e92cSDiego Novillo     SmallVector<StringRef, 4> Matches;
175de1ab26fSDiego Novillo     if (!HeadRE.match(*LineIt, &Matches)) {
176de1ab26fSDiego Novillo       reportParseError(LineIt.line_number(),
177de1ab26fSDiego Novillo                        "Expected 'mangled_name:NUM:NUM', found " + *LineIt);
178c572e92cSDiego Novillo       return sampleprof_error::malformed;
179de1ab26fSDiego Novillo     }
180de1ab26fSDiego Novillo     assert(Matches.size() == 4);
181de1ab26fSDiego Novillo     StringRef FName = Matches[1];
182de1ab26fSDiego Novillo     unsigned NumSamples, NumHeadSamples;
183de1ab26fSDiego Novillo     Matches[2].getAsInteger(10, NumSamples);
184de1ab26fSDiego Novillo     Matches[3].getAsInteger(10, NumHeadSamples);
185de1ab26fSDiego Novillo     Profiles[FName] = FunctionSamples();
186de1ab26fSDiego Novillo     FunctionSamples &FProfile = Profiles[FName];
187de1ab26fSDiego Novillo     FProfile.addTotalSamples(NumSamples);
188de1ab26fSDiego Novillo     FProfile.addHeadSamples(NumHeadSamples);
189de1ab26fSDiego Novillo     ++LineIt;
190de1ab26fSDiego Novillo 
191de1ab26fSDiego Novillo     // Now read the body. The body of the function ends when we reach
192de1ab26fSDiego Novillo     // EOF or when we see the start of the next function.
193de1ab26fSDiego Novillo     while (!LineIt.is_at_eof() && isdigit((*LineIt)[0])) {
194c572e92cSDiego Novillo       if (!LineSampleRE.match(*LineIt, &Matches)) {
195de1ab26fSDiego Novillo         reportParseError(
196de1ab26fSDiego Novillo             LineIt.line_number(),
197de1ab26fSDiego Novillo             "Expected 'NUM[.NUM]: NUM[ mangled_name:NUM]*', found " + *LineIt);
198c572e92cSDiego Novillo         return sampleprof_error::malformed;
199de1ab26fSDiego Novillo       }
200de1ab26fSDiego Novillo       assert(Matches.size() == 5);
201de1ab26fSDiego Novillo       unsigned LineOffset, NumSamples, Discriminator = 0;
202de1ab26fSDiego Novillo       Matches[1].getAsInteger(10, LineOffset);
203de1ab26fSDiego Novillo       if (Matches[2] != "")
204de1ab26fSDiego Novillo         Matches[2].getAsInteger(10, Discriminator);
205de1ab26fSDiego Novillo       Matches[3].getAsInteger(10, NumSamples);
206de1ab26fSDiego Novillo 
207c572e92cSDiego Novillo       // If there are function calls in this line, generate a call sample
208c572e92cSDiego Novillo       // entry for each call.
209c572e92cSDiego Novillo       std::string CallsLine(Matches[4]);
210c572e92cSDiego Novillo       while (CallsLine != "") {
211c572e92cSDiego Novillo         SmallVector<StringRef, 3> CallSample;
212c572e92cSDiego Novillo         if (!CallSampleRE.match(CallsLine, &CallSample)) {
213c572e92cSDiego Novillo           reportParseError(LineIt.line_number(),
214c572e92cSDiego Novillo                            "Expected 'mangled_name:NUM', found " + CallsLine);
215c572e92cSDiego Novillo           return sampleprof_error::malformed;
216c572e92cSDiego Novillo         }
217c572e92cSDiego Novillo         StringRef CalledFunction = CallSample[1];
218c572e92cSDiego Novillo         unsigned CalledFunctionSamples;
219c572e92cSDiego Novillo         CallSample[2].getAsInteger(10, CalledFunctionSamples);
220c572e92cSDiego Novillo         FProfile.addCalledTargetSamples(LineOffset, Discriminator,
221c572e92cSDiego Novillo                                         CalledFunction, CalledFunctionSamples);
222c572e92cSDiego Novillo         CallsLine = CallSampleRE.sub("", CallsLine);
223c572e92cSDiego Novillo       }
224de1ab26fSDiego Novillo 
225de1ab26fSDiego Novillo       FProfile.addBodySamples(LineOffset, Discriminator, NumSamples);
226de1ab26fSDiego Novillo       ++LineIt;
227de1ab26fSDiego Novillo     }
228de1ab26fSDiego Novillo   }
229de1ab26fSDiego Novillo 
230c572e92cSDiego Novillo   return sampleprof_error::success;
231de1ab26fSDiego Novillo }
232de1ab26fSDiego Novillo 
233d5336ae2SDiego Novillo template <typename T> ErrorOr<T> SampleProfileReaderBinary::readNumber() {
234c572e92cSDiego Novillo   unsigned NumBytesRead = 0;
235c572e92cSDiego Novillo   std::error_code EC;
236c572e92cSDiego Novillo   uint64_t Val = decodeULEB128(Data, &NumBytesRead);
237c572e92cSDiego Novillo 
238c572e92cSDiego Novillo   if (Val > std::numeric_limits<T>::max())
239c572e92cSDiego Novillo     EC = sampleprof_error::malformed;
240c572e92cSDiego Novillo   else if (Data + NumBytesRead > End)
241c572e92cSDiego Novillo     EC = sampleprof_error::truncated;
242c572e92cSDiego Novillo   else
243c572e92cSDiego Novillo     EC = sampleprof_error::success;
244c572e92cSDiego Novillo 
245c572e92cSDiego Novillo   if (EC) {
246c572e92cSDiego Novillo     reportParseError(0, EC.message());
247c572e92cSDiego Novillo     return EC;
248c572e92cSDiego Novillo   }
249c572e92cSDiego Novillo 
250c572e92cSDiego Novillo   Data += NumBytesRead;
251c572e92cSDiego Novillo   return static_cast<T>(Val);
252c572e92cSDiego Novillo }
253c572e92cSDiego Novillo 
254c572e92cSDiego Novillo ErrorOr<StringRef> SampleProfileReaderBinary::readString() {
255c572e92cSDiego Novillo   std::error_code EC;
256c572e92cSDiego Novillo   StringRef Str(reinterpret_cast<const char *>(Data));
257c572e92cSDiego Novillo   if (Data + Str.size() + 1 > End) {
258c572e92cSDiego Novillo     EC = sampleprof_error::truncated;
259c572e92cSDiego Novillo     reportParseError(0, EC.message());
260c572e92cSDiego Novillo     return EC;
261c572e92cSDiego Novillo   }
262c572e92cSDiego Novillo 
263c572e92cSDiego Novillo   Data += Str.size() + 1;
264c572e92cSDiego Novillo   return Str;
265c572e92cSDiego Novillo }
266c572e92cSDiego Novillo 
267c572e92cSDiego Novillo std::error_code SampleProfileReaderBinary::read() {
268c572e92cSDiego Novillo   while (!at_eof()) {
269c572e92cSDiego Novillo     auto FName(readString());
270c572e92cSDiego Novillo     if (std::error_code EC = FName.getError())
271c572e92cSDiego Novillo       return EC;
272c572e92cSDiego Novillo 
273c572e92cSDiego Novillo     Profiles[*FName] = FunctionSamples();
274c572e92cSDiego Novillo     FunctionSamples &FProfile = Profiles[*FName];
275c572e92cSDiego Novillo 
276c572e92cSDiego Novillo     auto Val = readNumber<unsigned>();
277c572e92cSDiego Novillo     if (std::error_code EC = Val.getError())
278c572e92cSDiego Novillo       return EC;
279c572e92cSDiego Novillo     FProfile.addTotalSamples(*Val);
280c572e92cSDiego Novillo 
281c572e92cSDiego Novillo     Val = readNumber<unsigned>();
282c572e92cSDiego Novillo     if (std::error_code EC = Val.getError())
283c572e92cSDiego Novillo       return EC;
284c572e92cSDiego Novillo     FProfile.addHeadSamples(*Val);
285c572e92cSDiego Novillo 
286c572e92cSDiego Novillo     // Read the samples in the body.
287c572e92cSDiego Novillo     auto NumRecords = readNumber<unsigned>();
288c572e92cSDiego Novillo     if (std::error_code EC = NumRecords.getError())
289c572e92cSDiego Novillo       return EC;
290c572e92cSDiego Novillo     for (unsigned I = 0; I < *NumRecords; ++I) {
291c572e92cSDiego Novillo       auto LineOffset = readNumber<uint64_t>();
292c572e92cSDiego Novillo       if (std::error_code EC = LineOffset.getError())
293c572e92cSDiego Novillo         return EC;
294c572e92cSDiego Novillo 
295c572e92cSDiego Novillo       auto Discriminator = readNumber<uint64_t>();
296c572e92cSDiego Novillo       if (std::error_code EC = Discriminator.getError())
297c572e92cSDiego Novillo         return EC;
298c572e92cSDiego Novillo 
299c572e92cSDiego Novillo       auto NumSamples = readNumber<uint64_t>();
300c572e92cSDiego Novillo       if (std::error_code EC = NumSamples.getError())
301c572e92cSDiego Novillo         return EC;
302c572e92cSDiego Novillo 
303c572e92cSDiego Novillo       auto NumCalls = readNumber<unsigned>();
304c572e92cSDiego Novillo       if (std::error_code EC = NumCalls.getError())
305c572e92cSDiego Novillo         return EC;
306c572e92cSDiego Novillo 
307c572e92cSDiego Novillo       for (unsigned J = 0; J < *NumCalls; ++J) {
308c572e92cSDiego Novillo         auto CalledFunction(readString());
309c572e92cSDiego Novillo         if (std::error_code EC = CalledFunction.getError())
310c572e92cSDiego Novillo           return EC;
311c572e92cSDiego Novillo 
312c572e92cSDiego Novillo         auto CalledFunctionSamples = readNumber<uint64_t>();
313c572e92cSDiego Novillo         if (std::error_code EC = CalledFunctionSamples.getError())
314c572e92cSDiego Novillo           return EC;
315c572e92cSDiego Novillo 
316c572e92cSDiego Novillo         FProfile.addCalledTargetSamples(*LineOffset, *Discriminator,
317c572e92cSDiego Novillo                                         *CalledFunction,
318c572e92cSDiego Novillo                                         *CalledFunctionSamples);
319c572e92cSDiego Novillo       }
320c572e92cSDiego Novillo 
321c572e92cSDiego Novillo       FProfile.addBodySamples(*LineOffset, *Discriminator, *NumSamples);
322c572e92cSDiego Novillo     }
323c572e92cSDiego Novillo   }
324c572e92cSDiego Novillo 
325c572e92cSDiego Novillo   return sampleprof_error::success;
326c572e92cSDiego Novillo }
327c572e92cSDiego Novillo 
328c572e92cSDiego Novillo std::error_code SampleProfileReaderBinary::readHeader() {
329c572e92cSDiego Novillo   Data = reinterpret_cast<const uint8_t *>(Buffer->getBufferStart());
330c572e92cSDiego Novillo   End = Data + Buffer->getBufferSize();
331c572e92cSDiego Novillo 
332c572e92cSDiego Novillo   // Read and check the magic identifier.
333c572e92cSDiego Novillo   auto Magic = readNumber<uint64_t>();
334c572e92cSDiego Novillo   if (std::error_code EC = Magic.getError())
335c572e92cSDiego Novillo     return EC;
336c572e92cSDiego Novillo   else if (*Magic != SPMagic())
337c572e92cSDiego Novillo     return sampleprof_error::bad_magic;
338c572e92cSDiego Novillo 
339c572e92cSDiego Novillo   // Read the version number.
340c572e92cSDiego Novillo   auto Version = readNumber<uint64_t>();
341c572e92cSDiego Novillo   if (std::error_code EC = Version.getError())
342c572e92cSDiego Novillo     return EC;
343c572e92cSDiego Novillo   else if (*Version != SPVersion())
344c572e92cSDiego Novillo     return sampleprof_error::unsupported_version;
345c572e92cSDiego Novillo 
346c572e92cSDiego Novillo   return sampleprof_error::success;
347c572e92cSDiego Novillo }
348c572e92cSDiego Novillo 
349c572e92cSDiego Novillo bool SampleProfileReaderBinary::hasFormat(const MemoryBuffer &Buffer) {
350c572e92cSDiego Novillo   const uint8_t *Data =
351c572e92cSDiego Novillo       reinterpret_cast<const uint8_t *>(Buffer.getBufferStart());
352c572e92cSDiego Novillo   uint64_t Magic = decodeULEB128(Data);
353c572e92cSDiego Novillo   return Magic == SPMagic();
354c572e92cSDiego Novillo }
355c572e92cSDiego Novillo 
356c572e92cSDiego Novillo /// \brief Prepare a memory buffer for the contents of \p Filename.
357de1ab26fSDiego Novillo ///
358c572e92cSDiego Novillo /// \returns an error code indicating the status of the buffer.
359*fcd55607SDiego Novillo static ErrorOr<std::unique_ptr<MemoryBuffer>>
360*fcd55607SDiego Novillo setupMemoryBuffer(std::string Filename) {
361c572e92cSDiego Novillo   auto BufferOrErr = MemoryBuffer::getFileOrSTDIN(Filename);
362c572e92cSDiego Novillo   if (std::error_code EC = BufferOrErr.getError())
363c572e92cSDiego Novillo     return EC;
364*fcd55607SDiego Novillo   auto Buffer = std::move(BufferOrErr.get());
365c572e92cSDiego Novillo 
366c572e92cSDiego Novillo   // Sanity check the file.
367c572e92cSDiego Novillo   if (Buffer->getBufferSize() > std::numeric_limits<unsigned>::max())
368c572e92cSDiego Novillo     return sampleprof_error::too_large;
369c572e92cSDiego Novillo 
370*fcd55607SDiego Novillo   return std::move(Buffer);
371c572e92cSDiego Novillo }
372c572e92cSDiego Novillo 
373c572e92cSDiego Novillo /// \brief Create a sample profile reader based on the format of the input file.
374c572e92cSDiego Novillo ///
375c572e92cSDiego Novillo /// \param Filename The file to open.
376c572e92cSDiego Novillo ///
377c572e92cSDiego Novillo /// \param Reader The reader to instantiate according to \p Filename's format.
378c572e92cSDiego Novillo ///
379c572e92cSDiego Novillo /// \param C The LLVM context to use to emit diagnostics.
380c572e92cSDiego Novillo ///
381c572e92cSDiego Novillo /// \returns an error code indicating the status of the created reader.
382*fcd55607SDiego Novillo ErrorOr<std::unique_ptr<SampleProfileReader>>
383*fcd55607SDiego Novillo SampleProfileReader::create(StringRef Filename, LLVMContext &C) {
384*fcd55607SDiego Novillo   auto BufferOrError = setupMemoryBuffer(Filename);
385*fcd55607SDiego Novillo   if (std::error_code EC = BufferOrError.getError())
386c572e92cSDiego Novillo     return EC;
387c572e92cSDiego Novillo 
388*fcd55607SDiego Novillo   auto Buffer = std::move(BufferOrError.get());
389*fcd55607SDiego Novillo   std::unique_ptr<SampleProfileReader> Reader;
390c572e92cSDiego Novillo   if (SampleProfileReaderBinary::hasFormat(*Buffer))
391c572e92cSDiego Novillo     Reader.reset(new SampleProfileReaderBinary(std::move(Buffer), C));
392c572e92cSDiego Novillo   else
393c572e92cSDiego Novillo     Reader.reset(new SampleProfileReaderText(std::move(Buffer), C));
394c572e92cSDiego Novillo 
395*fcd55607SDiego Novillo   if (std::error_code EC = Reader->readHeader())
396*fcd55607SDiego Novillo     return EC;
397*fcd55607SDiego Novillo 
398*fcd55607SDiego Novillo   return std::move(Reader);
399de1ab26fSDiego Novillo }
400