1 //===- SampleProfReader.cpp - Read LLVM sample profile data ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the class that reads LLVM sample profiles. It
11 // supports three file formats: text, binary and gcov.
13 // The textual representation is useful for debugging and testing purposes. The
14 // binary representation is more compact, resulting in smaller file sizes.
16 // The gcov encoding is the one generated by GCC's AutoFDO profile creation
17 // tool (https://github.com/google/autofdo)
19 // All three encodings can be used interchangeably as an input sample profile.
21 //===----------------------------------------------------------------------===//
23 #include "llvm/ProfileData/SampleProfReader.h"
24 #include "llvm/ADT/DenseMap.h"
25 #include "llvm/ADT/SmallVector.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/ErrorOr.h"
28 #include "llvm/Support/LEB128.h"
29 #include "llvm/Support/LineIterator.h"
30 #include "llvm/Support/MemoryBuffer.h"
32 using namespace llvm::sampleprof;
35 /// \brief Dump the function profile for \p FName.
37 /// \param FName Name of the function to print.
38 /// \param OS Stream to emit the output to.
39 void SampleProfileReader::dumpFunctionProfile(StringRef FName,
41 OS << "Function: " << FName << ": " << Profiles[FName];
44 /// \brief Dump all the function profiles found on stream \p OS.
45 void SampleProfileReader::dump(raw_ostream &OS) {
46 for (const auto &I : Profiles)
47 dumpFunctionProfile(I.getKey(), OS);
50 /// \brief Parse \p Input as function head.
52 /// Parse one line of \p Input, and update function name in \p FName,
53 /// function's total sample count in \p NumSamples, function's entry
54 /// count in \p NumHeadSamples.
56 /// \returns true if parsing is successful.
57 static bool ParseHead(const StringRef &Input, StringRef &FName,
58 uint64_t &NumSamples, uint64_t &NumHeadSamples) {
61 size_t n2 = Input.rfind(':');
62 size_t n1 = Input.rfind(':', n2 - 1);
63 FName = Input.substr(0, n1);
64 if (Input.substr(n1 + 1, n2 - n1 - 1).getAsInteger(10, NumSamples))
66 if (Input.substr(n2 + 1).getAsInteger(10, NumHeadSamples))
72 /// \brief Returns true if line offset \p L is legal (only has 16 bits).
73 static bool isOffsetLegal(unsigned L) {
74 return (L & 0xffff) == L;
77 /// \brief Parse \p Input as line sample.
79 /// \param Input input line.
80 /// \param IsCallsite true if the line represents an inlined callsite.
81 /// \param Depth the depth of the inline stack.
82 /// \param NumSamples total samples of the line/inlined callsite.
83 /// \param LineOffset line offset to the start of the function.
84 /// \param Discriminator discriminator of the line.
85 /// \param TargetCountMap map from indirect call target to count.
87 /// returns true if parsing is successful.
88 static bool ParseLine(const StringRef &Input, bool &IsCallsite, uint32_t &Depth,
89 uint64_t &NumSamples, uint32_t &LineOffset,
90 uint32_t &Discriminator, StringRef &CalleeName,
91 DenseMap<StringRef, uint64_t> &TargetCountMap) {
92 for (Depth = 0; Input[Depth] == ' '; Depth++)
97 size_t n1 = Input.find(':');
98 StringRef Loc = Input.substr(Depth, n1 - Depth);
99 size_t n2 = Loc.find('.');
100 if (n2 == StringRef::npos) {
101 if (Loc.getAsInteger(10, LineOffset) || !isOffsetLegal(LineOffset))
105 if (Loc.substr(0, n2).getAsInteger(10, LineOffset))
107 if (Loc.substr(n2 + 1).getAsInteger(10, Discriminator))
111 StringRef Rest = Input.substr(n1 + 2);
112 if (Rest[0] >= '0' && Rest[0] <= '9') {
114 size_t n3 = Rest.find(' ');
115 if (n3 == StringRef::npos) {
116 if (Rest.getAsInteger(10, NumSamples))
119 if (Rest.substr(0, n3).getAsInteger(10, NumSamples))
122 while (n3 != StringRef::npos) {
123 n3 += Rest.substr(n3).find_first_not_of(' ');
124 Rest = Rest.substr(n3);
126 StringRef pair = Rest;
127 if (n3 != StringRef::npos) {
128 pair = Rest.substr(0, n3);
130 size_t n4 = pair.find(':');
132 if (pair.substr(n4 + 1).getAsInteger(10, count))
134 TargetCountMap[pair.substr(0, n4)] = count;
138 size_t n3 = Rest.find_last_of(':');
139 CalleeName = Rest.substr(0, n3);
140 if (Rest.substr(n3 + 1).getAsInteger(10, NumSamples))
146 /// \brief Load samples from a text file.
148 /// See the documentation at the top of the file for an explanation of
149 /// the expected format.
151 /// \returns true if the file was loaded successfully, false otherwise.
152 std::error_code SampleProfileReaderText::read() {
153 line_iterator LineIt(*Buffer, /*SkipBlanks=*/true, '#');
155 InlineCallStack InlineStack;
157 for (; !LineIt.is_at_eof(); ++LineIt) {
158 if ((*LineIt)[(*LineIt).find_first_not_of(' ')] == '#')
160 // Read the header of each function.
162 // Note that for function identifiers we are actually expecting
163 // mangled names, but we may not always get them. This happens when
164 // the compiler decides not to emit the function (e.g., it was inlined
165 // and removed). In this case, the binary will not have the linkage
166 // name for the function, so the profiler will emit the function's
167 // unmangled name, which may contain characters like ':' and '>' in its
168 // name (member functions, templates, etc).
170 // The only requirement we place on the identifier, then, is that it
171 // should not begin with a number.
172 if ((*LineIt)[0] != ' ') {
173 uint64_t NumSamples, NumHeadSamples;
175 if (!ParseHead(*LineIt, FName, NumSamples, NumHeadSamples)) {
176 reportError(LineIt.line_number(),
177 "Expected 'mangled_name:NUM:NUM', found " + *LineIt);
178 return sampleprof_error::malformed;
180 Profiles[FName] = FunctionSamples();
181 FunctionSamples &FProfile = Profiles[FName];
182 FProfile.addTotalSamples(NumSamples);
183 FProfile.addHeadSamples(NumHeadSamples);
185 InlineStack.push_back(&FProfile);
189 DenseMap<StringRef, uint64_t> TargetCountMap;
191 uint32_t Depth, LineOffset, Discriminator;
192 if (!ParseLine(*LineIt, IsCallsite, Depth, NumSamples, LineOffset,
193 Discriminator, FName, TargetCountMap)) {
194 reportError(LineIt.line_number(),
195 "Expected 'NUM[.NUM]: NUM[ mangled_name:NUM]*', found " +
197 return sampleprof_error::malformed;
200 while (InlineStack.size() > Depth) {
201 InlineStack.pop_back();
203 FunctionSamples &FSamples = InlineStack.back()->functionSamplesAt(
204 CallsiteLocation(LineOffset, Discriminator, FName));
205 FSamples.addTotalSamples(NumSamples);
206 InlineStack.push_back(&FSamples);
208 while (InlineStack.size() > Depth) {
209 InlineStack.pop_back();
211 FunctionSamples &FProfile = *InlineStack.back();
212 for (const auto &name_count : TargetCountMap) {
213 FProfile.addCalledTargetSamples(LineOffset, Discriminator,
214 name_count.first, name_count.second);
216 FProfile.addBodySamples(LineOffset, Discriminator, NumSamples);
221 return sampleprof_error::success;
224 bool SampleProfileReaderText::hasFormat(const MemoryBuffer &Buffer) {
227 // Check that the first non-comment line is a valid function header.
228 line_iterator LineIt(Buffer, /*SkipBlanks=*/true, '#');
229 if (!LineIt.is_at_eof()) {
230 if ((*LineIt)[0] != ' ') {
231 uint64_t NumSamples, NumHeadSamples;
233 result = ParseHead(*LineIt, FName, NumSamples, NumHeadSamples);
240 template <typename T> ErrorOr<T> SampleProfileReaderBinary::readNumber() {
241 unsigned NumBytesRead = 0;
243 uint64_t Val = decodeULEB128(Data, &NumBytesRead);
245 if (Val > std::numeric_limits<T>::max())
246 EC = sampleprof_error::malformed;
247 else if (Data + NumBytesRead > End)
248 EC = sampleprof_error::truncated;
250 EC = sampleprof_error::success;
253 reportError(0, EC.message());
257 Data += NumBytesRead;
258 return static_cast<T>(Val);
261 ErrorOr<StringRef> SampleProfileReaderBinary::readString() {
263 StringRef Str(reinterpret_cast<const char *>(Data));
264 if (Data + Str.size() + 1 > End) {
265 EC = sampleprof_error::truncated;
266 reportError(0, EC.message());
270 Data += Str.size() + 1;
274 ErrorOr<StringRef> SampleProfileReaderBinary::readStringFromTable() {
276 auto Idx = readNumber<uint32_t>();
277 if (std::error_code EC = Idx.getError())
279 if (*Idx >= NameTable.size())
280 return sampleprof_error::truncated_name_table;
281 return NameTable[*Idx];
285 SampleProfileReaderBinary::readProfile(FunctionSamples &FProfile) {
286 auto NumSamples = readNumber<uint64_t>();
287 if (std::error_code EC = NumSamples.getError())
289 FProfile.addTotalSamples(*NumSamples);
291 // Read the samples in the body.
292 auto NumRecords = readNumber<uint32_t>();
293 if (std::error_code EC = NumRecords.getError())
296 for (uint32_t I = 0; I < *NumRecords; ++I) {
297 auto LineOffset = readNumber<uint64_t>();
298 if (std::error_code EC = LineOffset.getError())
301 if (!isOffsetLegal(*LineOffset)) {
302 return std::error_code();
305 auto Discriminator = readNumber<uint64_t>();
306 if (std::error_code EC = Discriminator.getError())
309 auto NumSamples = readNumber<uint64_t>();
310 if (std::error_code EC = NumSamples.getError())
313 auto NumCalls = readNumber<uint32_t>();
314 if (std::error_code EC = NumCalls.getError())
317 for (uint32_t J = 0; J < *NumCalls; ++J) {
318 auto CalledFunction(readStringFromTable());
319 if (std::error_code EC = CalledFunction.getError())
322 auto CalledFunctionSamples = readNumber<uint64_t>();
323 if (std::error_code EC = CalledFunctionSamples.getError())
326 FProfile.addCalledTargetSamples(*LineOffset, *Discriminator,
327 *CalledFunction, *CalledFunctionSamples);
330 FProfile.addBodySamples(*LineOffset, *Discriminator, *NumSamples);
333 // Read all the samples for inlined function calls.
334 auto NumCallsites = readNumber<uint32_t>();
335 if (std::error_code EC = NumCallsites.getError())
338 for (uint32_t J = 0; J < *NumCallsites; ++J) {
339 auto LineOffset = readNumber<uint64_t>();
340 if (std::error_code EC = LineOffset.getError())
343 auto Discriminator = readNumber<uint64_t>();
344 if (std::error_code EC = Discriminator.getError())
347 auto FName(readStringFromTable());
348 if (std::error_code EC = FName.getError())
351 FunctionSamples &CalleeProfile = FProfile.functionSamplesAt(
352 CallsiteLocation(*LineOffset, *Discriminator, *FName));
353 if (std::error_code EC = readProfile(CalleeProfile))
357 return sampleprof_error::success;
360 std::error_code SampleProfileReaderBinary::read() {
362 auto NumHeadSamples = readNumber<uint64_t>();
363 if (std::error_code EC = NumHeadSamples.getError())
366 auto FName(readStringFromTable());
367 if (std::error_code EC = FName.getError())
370 Profiles[*FName] = FunctionSamples();
371 FunctionSamples &FProfile = Profiles[*FName];
373 FProfile.addHeadSamples(*NumHeadSamples);
375 if (std::error_code EC = readProfile(FProfile))
379 return sampleprof_error::success;
382 std::error_code SampleProfileReaderBinary::readHeader() {
383 Data = reinterpret_cast<const uint8_t *>(Buffer->getBufferStart());
384 End = Data + Buffer->getBufferSize();
386 // Read and check the magic identifier.
387 auto Magic = readNumber<uint64_t>();
388 if (std::error_code EC = Magic.getError())
390 else if (*Magic != SPMagic())
391 return sampleprof_error::bad_magic;
393 // Read the version number.
394 auto Version = readNumber<uint64_t>();
395 if (std::error_code EC = Version.getError())
397 else if (*Version != SPVersion())
398 return sampleprof_error::unsupported_version;
400 // Read the name table.
401 auto Size = readNumber<uint32_t>();
402 if (std::error_code EC = Size.getError())
404 NameTable.reserve(*Size);
405 for (uint32_t I = 0; I < *Size; ++I) {
406 auto Name(readString());
407 if (std::error_code EC = Name.getError())
409 NameTable.push_back(*Name);
412 return sampleprof_error::success;
415 bool SampleProfileReaderBinary::hasFormat(const MemoryBuffer &Buffer) {
416 const uint8_t *Data =
417 reinterpret_cast<const uint8_t *>(Buffer.getBufferStart());
418 uint64_t Magic = decodeULEB128(Data);
419 return Magic == SPMagic();
422 std::error_code SampleProfileReaderGCC::skipNextWord() {
424 if (!GcovBuffer.readInt(dummy))
425 return sampleprof_error::truncated;
426 return sampleprof_error::success;
429 template <typename T> ErrorOr<T> SampleProfileReaderGCC::readNumber() {
430 if (sizeof(T) <= sizeof(uint32_t)) {
432 if (GcovBuffer.readInt(Val) && Val <= std::numeric_limits<T>::max())
433 return static_cast<T>(Val);
434 } else if (sizeof(T) <= sizeof(uint64_t)) {
436 if (GcovBuffer.readInt64(Val) && Val <= std::numeric_limits<T>::max())
437 return static_cast<T>(Val);
440 std::error_code EC = sampleprof_error::malformed;
441 reportError(0, EC.message());
445 ErrorOr<StringRef> SampleProfileReaderGCC::readString() {
447 if (!GcovBuffer.readString(Str))
448 return sampleprof_error::truncated;
452 std::error_code SampleProfileReaderGCC::readHeader() {
453 // Read the magic identifier.
454 if (!GcovBuffer.readGCDAFormat())
455 return sampleprof_error::unrecognized_format;
457 // Read the version number. Note - the GCC reader does not validate this
458 // version, but the profile creator generates v704.
459 GCOV::GCOVVersion version;
460 if (!GcovBuffer.readGCOVVersion(version))
461 return sampleprof_error::unrecognized_format;
463 if (version != GCOV::V704)
464 return sampleprof_error::unsupported_version;
466 // Skip the empty integer.
467 if (std::error_code EC = skipNextWord())
470 return sampleprof_error::success;
473 std::error_code SampleProfileReaderGCC::readSectionTag(uint32_t Expected) {
475 if (!GcovBuffer.readInt(Tag))
476 return sampleprof_error::truncated;
479 return sampleprof_error::malformed;
481 if (std::error_code EC = skipNextWord())
484 return sampleprof_error::success;
487 std::error_code SampleProfileReaderGCC::readNameTable() {
488 if (std::error_code EC = readSectionTag(GCOVTagAFDOFileNames))
492 if (!GcovBuffer.readInt(Size))
493 return sampleprof_error::truncated;
495 for (uint32_t I = 0; I < Size; ++I) {
497 if (!GcovBuffer.readString(Str))
498 return sampleprof_error::truncated;
499 Names.push_back(Str);
502 return sampleprof_error::success;
505 std::error_code SampleProfileReaderGCC::readFunctionProfiles() {
506 if (std::error_code EC = readSectionTag(GCOVTagAFDOFunction))
509 uint32_t NumFunctions;
510 if (!GcovBuffer.readInt(NumFunctions))
511 return sampleprof_error::truncated;
513 InlineCallStack Stack;
514 for (uint32_t I = 0; I < NumFunctions; ++I)
515 if (std::error_code EC = readOneFunctionProfile(Stack, true, 0))
518 return sampleprof_error::success;
521 std::error_code SampleProfileReaderGCC::readOneFunctionProfile(
522 const InlineCallStack &InlineStack, bool Update, uint32_t Offset) {
523 uint64_t HeadCount = 0;
524 if (InlineStack.size() == 0)
525 if (!GcovBuffer.readInt64(HeadCount))
526 return sampleprof_error::truncated;
529 if (!GcovBuffer.readInt(NameIdx))
530 return sampleprof_error::truncated;
532 StringRef Name(Names[NameIdx]);
534 uint32_t NumPosCounts;
535 if (!GcovBuffer.readInt(NumPosCounts))
536 return sampleprof_error::truncated;
538 uint32_t NumCallsites;
539 if (!GcovBuffer.readInt(NumCallsites))
540 return sampleprof_error::truncated;
542 FunctionSamples *FProfile = nullptr;
543 if (InlineStack.size() == 0) {
544 // If this is a top function that we have already processed, do not
545 // update its profile again. This happens in the presence of
546 // function aliases. Since these aliases share the same function
547 // body, there will be identical replicated profiles for the
548 // original function. In this case, we simply not bother updating
549 // the profile of the original function.
550 FProfile = &Profiles[Name];
551 FProfile->addHeadSamples(HeadCount);
552 if (FProfile->getTotalSamples() > 0)
555 // Otherwise, we are reading an inlined instance. The top of the
556 // inline stack contains the profile of the caller. Insert this
557 // callee in the caller's CallsiteMap.
558 FunctionSamples *CallerProfile = InlineStack.front();
559 uint32_t LineOffset = Offset >> 16;
560 uint32_t Discriminator = Offset & 0xffff;
561 FProfile = &CallerProfile->functionSamplesAt(
562 CallsiteLocation(LineOffset, Discriminator, Name));
565 for (uint32_t I = 0; I < NumPosCounts; ++I) {
567 if (!GcovBuffer.readInt(Offset))
568 return sampleprof_error::truncated;
571 if (!GcovBuffer.readInt(NumTargets))
572 return sampleprof_error::truncated;
575 if (!GcovBuffer.readInt64(Count))
576 return sampleprof_error::truncated;
578 // The line location is encoded in the offset as:
579 // high 16 bits: line offset to the start of the function.
580 // low 16 bits: discriminator.
581 uint32_t LineOffset = Offset >> 16;
582 uint32_t Discriminator = Offset & 0xffff;
584 InlineCallStack NewStack;
585 NewStack.push_back(FProfile);
586 NewStack.insert(NewStack.end(), InlineStack.begin(), InlineStack.end());
588 // Walk up the inline stack, adding the samples on this line to
589 // the total sample count of the callers in the chain.
590 for (auto CallerProfile : NewStack)
591 CallerProfile->addTotalSamples(Count);
593 // Update the body samples for the current profile.
594 FProfile->addBodySamples(LineOffset, Discriminator, Count);
597 // Process the list of functions called at an indirect call site.
598 // These are all the targets that a function pointer (or virtual
599 // function) resolved at runtime.
600 for (uint32_t J = 0; J < NumTargets; J++) {
602 if (!GcovBuffer.readInt(HistVal))
603 return sampleprof_error::truncated;
605 if (HistVal != HIST_TYPE_INDIR_CALL_TOPN)
606 return sampleprof_error::malformed;
609 if (!GcovBuffer.readInt64(TargetIdx))
610 return sampleprof_error::truncated;
611 StringRef TargetName(Names[TargetIdx]);
613 uint64_t TargetCount;
614 if (!GcovBuffer.readInt64(TargetCount))
615 return sampleprof_error::truncated;
618 FunctionSamples &TargetProfile = Profiles[TargetName];
619 TargetProfile.addCalledTargetSamples(LineOffset, Discriminator,
620 TargetName, TargetCount);
625 // Process all the inlined callers into the current function. These
626 // are all the callsites that were inlined into this function.
627 for (uint32_t I = 0; I < NumCallsites; I++) {
628 // The offset is encoded as:
629 // high 16 bits: line offset to the start of the function.
630 // low 16 bits: discriminator.
632 if (!GcovBuffer.readInt(Offset))
633 return sampleprof_error::truncated;
634 InlineCallStack NewStack;
635 NewStack.push_back(FProfile);
636 NewStack.insert(NewStack.end(), InlineStack.begin(), InlineStack.end());
637 if (std::error_code EC = readOneFunctionProfile(NewStack, Update, Offset))
641 return sampleprof_error::success;
644 /// \brief Read a GCC AutoFDO profile.
646 /// This format is generated by the Linux Perf conversion tool at
647 /// https://github.com/google/autofdo.
648 std::error_code SampleProfileReaderGCC::read() {
649 // Read the string table.
650 if (std::error_code EC = readNameTable())
653 // Read the source profile.
654 if (std::error_code EC = readFunctionProfiles())
657 return sampleprof_error::success;
660 bool SampleProfileReaderGCC::hasFormat(const MemoryBuffer &Buffer) {
661 StringRef Magic(reinterpret_cast<const char *>(Buffer.getBufferStart()));
662 return Magic == "adcg*704";
665 /// \brief Prepare a memory buffer for the contents of \p Filename.
667 /// \returns an error code indicating the status of the buffer.
668 static ErrorOr<std::unique_ptr<MemoryBuffer>>
669 setupMemoryBuffer(std::string Filename) {
670 auto BufferOrErr = MemoryBuffer::getFileOrSTDIN(Filename);
671 if (std::error_code EC = BufferOrErr.getError())
673 auto Buffer = std::move(BufferOrErr.get());
675 // Sanity check the file.
676 if (Buffer->getBufferSize() > std::numeric_limits<uint32_t>::max())
677 return sampleprof_error::too_large;
679 return std::move(Buffer);
682 /// \brief Create a sample profile reader based on the format of the input file.
684 /// \param Filename The file to open.
686 /// \param Reader The reader to instantiate according to \p Filename's format.
688 /// \param C The LLVM context to use to emit diagnostics.
690 /// \returns an error code indicating the status of the created reader.
691 ErrorOr<std::unique_ptr<SampleProfileReader>>
692 SampleProfileReader::create(StringRef Filename, LLVMContext &C) {
693 auto BufferOrError = setupMemoryBuffer(Filename);
694 if (std::error_code EC = BufferOrError.getError())
697 auto Buffer = std::move(BufferOrError.get());
698 std::unique_ptr<SampleProfileReader> Reader;
699 if (SampleProfileReaderBinary::hasFormat(*Buffer))
700 Reader.reset(new SampleProfileReaderBinary(std::move(Buffer), C));
701 else if (SampleProfileReaderGCC::hasFormat(*Buffer))
702 Reader.reset(new SampleProfileReaderGCC(std::move(Buffer), C));
703 else if (SampleProfileReaderText::hasFormat(*Buffer))
704 Reader.reset(new SampleProfileReaderText(std::move(Buffer), C));
706 return sampleprof_error::unrecognized_format;
708 if (std::error_code EC = Reader->readHeader())
711 return std::move(Reader);