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