LLVM 24.0.0git
SampleProfReader.cpp
Go to the documentation of this file.
1//===- SampleProfReader.cpp - Read LLVM sample profile data ---------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the class that reads LLVM sample profiles. It
10// supports three file formats: text, binary and gcov.
11//
12// The textual representation is useful for debugging and testing purposes. The
13// binary representation is more compact, resulting in smaller file sizes.
14//
15// The gcov encoding is the one generated by GCC's AutoFDO profile creation
16// tool (https://github.com/google/autofdo)
17//
18// All three encodings can be used interchangeably as an input sample profile.
19//
20//===----------------------------------------------------------------------===//
21
23#include "llvm/ADT/DenseMap.h"
24#include "llvm/ADT/STLExtras.h"
25#include "llvm/ADT/SmallSet.h"
26#include "llvm/ADT/StringRef.h"
27#include "llvm/IR/Module.h"
34#include "llvm/Support/JSON.h"
35#include "llvm/Support/LEB128.h"
37#include "llvm/Support/MD5.h"
42#include <algorithm>
43#include <cstddef>
44#include <cstdint>
45#include <cstring>
46#include <limits>
47#include <memory>
48#include <system_error>
49#include <vector>
50
51using namespace llvm;
52using namespace sampleprof;
53
54#define DEBUG_TYPE "samplepgo-reader"
55
56// This internal option specifies if the profile uses FS discriminators.
57// It only applies to text, and binary format profiles.
58// For ext-binary format profiles, the flag is set in the summary.
60 "profile-isfs", cl::Hidden, cl::init(false),
61 cl::desc("Profile uses flow sensitive discriminators"));
62
63static cl::opt<bool>
64 LazyLoadNameTable("sample-profile-lazy-load-name-table", cl::init(true),
66 cl::desc("Lazy load the name table from the profile."));
67
68// FIXME: Remove this temporary option once performance testing of #230386 is
69// complete.
71 "sample-profile-allow-reread-loaded-profile", cl::init(false), cl::Hidden,
72 cl::desc("Allow incremental reads with a remapper to re-read already "
73 "loaded profiles and accumulate duplicate vtable counts."));
74
75/// Dump the function profile for \p FName.
76///
77/// \param FContext Name + context of the function to print.
78/// \param OS Stream to emit the output to.
80 raw_ostream &OS) {
81 OS << "Function: " << FS.getContext().toString() << ": " << FS;
82}
83
84/// Dump all the function profiles found on stream \p OS.
86 std::vector<NameFunctionSamples> V;
88 for (const auto &I : V)
89 dumpFunctionProfile(*I.second, OS);
90}
91
93 json::OStream &JOS, bool TopLevel = false) {
94 auto DumpBody = [&](const BodySampleMap &BodySamples) {
95 for (const auto &I : BodySamples) {
96 const LineLocation &Loc = I.first;
97 const SampleRecord &Sample = I.second;
98 JOS.object([&] {
99 JOS.attribute("line", Loc.LineOffset);
100 if (Loc.Discriminator)
101 JOS.attribute("discriminator", Loc.Discriminator);
102 JOS.attribute("samples", Sample.getSamples());
103
104 auto CallTargets = Sample.getSortedCallTargets();
105 if (!CallTargets.empty()) {
106 JOS.attributeArray("calls", [&] {
107 for (const auto &J : CallTargets) {
108 JOS.object([&] {
109 JOS.attribute("function", J.first.str());
110 JOS.attribute("samples", J.second);
111 });
112 }
113 });
114 }
115 });
116 }
117 };
118
119 auto DumpCallsiteSamples = [&](const CallsiteSampleMap &CallsiteSamples) {
120 for (const auto &I : CallsiteSamples)
121 for (const auto &FS : I.second) {
122 const LineLocation &Loc = I.first;
123 const FunctionSamples &CalleeSamples = FS.second;
124 JOS.object([&] {
125 JOS.attribute("line", Loc.LineOffset);
126 if (Loc.Discriminator)
127 JOS.attribute("discriminator", Loc.Discriminator);
128 JOS.attributeArray(
129 "samples", [&] { dumpFunctionProfileJson(CalleeSamples, JOS); });
130 });
131 }
132 };
133
134 JOS.object([&] {
135 JOS.attribute("name", S.getFunction().str());
136 JOS.attribute("total", S.getTotalSamples());
137 if (TopLevel)
138 JOS.attribute("head", S.getHeadSamples());
139
140 const auto &BodySamples = S.getBodySamples();
141 if (!BodySamples.empty())
142 JOS.attributeArray("body", [&] { DumpBody(BodySamples); });
143
144 const auto &CallsiteSamples = S.getCallsiteSamples();
145 if (!CallsiteSamples.empty())
146 JOS.attributeArray("callsites",
147 [&] { DumpCallsiteSamples(CallsiteSamples); });
148 });
149}
150
151/// Dump all the function profiles found on stream \p OS in the JSON format.
153 std::vector<NameFunctionSamples> V;
155 json::OStream JOS(OS, 2);
156 JOS.arrayBegin();
157 for (const auto &F : V)
158 dumpFunctionProfileJson(*F.second, JOS, true);
159 JOS.arrayEnd();
160
161 // Emit a newline character at the end as json::OStream doesn't emit one.
162 OS << "\n";
163}
164
165/// Parse \p Input as function head.
166///
167/// Parse one line of \p Input, and update function name in \p FName,
168/// function's total sample count in \p NumSamples, function's entry
169/// count in \p NumHeadSamples.
170///
171/// \returns true if parsing is successful.
172static bool ParseHead(const StringRef &Input, StringRef &FName,
173 uint64_t &NumSamples, uint64_t &NumHeadSamples) {
174 if (Input[0] == ' ')
175 return false;
176 size_t n2 = Input.rfind(':');
177 size_t n1 = Input.rfind(':', n2 - 1);
178 FName = Input.substr(0, n1);
179 if (Input.substr(n1 + 1, n2 - n1 - 1).getAsInteger(10, NumSamples))
180 return false;
181 if (Input.substr(n2 + 1).getAsInteger(10, NumHeadSamples))
182 return false;
183 return true;
184}
185
186/// Returns true if line offset \p L is legal (only has 16 bits).
187static bool isOffsetLegal(unsigned L) { return (L & 0xffff) == L; }
188
189/// Parse \p Input that contains metadata.
190/// Possible metadata:
191/// - CFG Checksum information:
192/// !CFGChecksum: 12345
193/// - CFG Checksum information:
194/// !Attributes: 1
195/// Stores the FunctionHash (a.k.a. CFG Checksum) into \p FunctionHash.
196static bool parseMetadata(const StringRef &Input, uint64_t &FunctionHash,
197 uint32_t &Attributes) {
198 if (Input.starts_with("!CFGChecksum:")) {
199 StringRef CFGInfo = Input.substr(strlen("!CFGChecksum:")).trim();
200 return !CFGInfo.getAsInteger(10, FunctionHash);
201 }
202
203 if (Input.starts_with("!Attributes:")) {
204 StringRef Attrib = Input.substr(strlen("!Attributes:")).trim();
205 return !Attrib.getAsInteger(10, Attributes);
206 }
207
208 return false;
209}
210
217
218// Parse `Input` as a white-space separated list of `vtable:count` pairs. An
219// example input line is `_ZTVbar:1471 _ZTVfoo:630`.
222 for (size_t Index = Input.find_first_not_of(' '); Index != StringRef::npos;) {
223 size_t ColonIndex = Input.find(':', Index);
224 if (ColonIndex == StringRef::npos)
225 return false; // No colon found, invalid format.
226 StringRef TypeName = Input.substr(Index, ColonIndex - Index);
227 // CountIndex is the start index of count.
228 size_t CountStartIndex = ColonIndex + 1;
229 // NextIndex is the start index after the 'target:count' pair.
230 size_t NextIndex = Input.find_first_of(' ', CountStartIndex);
232 if (Input.substr(CountStartIndex, NextIndex - CountStartIndex)
233 .getAsInteger(10, Count))
234 return false; // Invalid count.
235 // Error on duplicated type names in one line of input.
236 auto [Iter, Inserted] = TypeCountMap.insert({TypeName, Count});
237 if (!Inserted)
238 return false;
239 Index = (NextIndex == StringRef::npos)
241 : Input.find_first_not_of(' ', NextIndex);
242 }
243 return true;
244}
245
246/// Parse \p Input as line sample.
247///
248/// \param Input input line.
249/// \param LineTy Type of this line.
250/// \param Depth the depth of the inline stack.
251/// \param NumSamples total samples of the line/inlined callsite.
252/// \param LineOffset line offset to the start of the function.
253/// \param Discriminator discriminator of the line.
254/// \param TargetCountMap map from indirect call target to count.
255/// \param FunctionHash the function's CFG hash, used by pseudo probe.
256///
257/// returns true if parsing is successful.
258static bool ParseLine(const StringRef &Input, LineType &LineTy, uint32_t &Depth,
259 uint64_t &NumSamples, uint32_t &LineOffset,
260 uint32_t &Discriminator, StringRef &CalleeName,
261 DenseMap<StringRef, uint64_t> &TargetCountMap,
263 uint64_t &FunctionHash, uint32_t &Attributes,
264 bool &IsFlat) {
265 for (Depth = 0; Input[Depth] == ' '; Depth++)
266 ;
267 if (Depth == 0)
268 return false;
269
270 if (Input[Depth] == '!') {
271 LineTy = LineType::Metadata;
272 // This metadata is only for manual inspection only. We already created a
273 // FunctionSamples and put it in the profile map, so there is no point
274 // to skip profiles even they have no use for ThinLTO.
275 if (Input == StringRef(" !Flat")) {
276 IsFlat = true;
277 return true;
278 }
279 return parseMetadata(Input.substr(Depth), FunctionHash, Attributes);
280 }
281
282 size_t n1 = Input.find(':');
283 StringRef Loc = Input.substr(Depth, n1 - Depth);
284 size_t n2 = Loc.find('.');
285 if (n2 == StringRef::npos) {
286 if (Loc.getAsInteger(10, LineOffset) || !isOffsetLegal(LineOffset))
287 return false;
288 Discriminator = 0;
289 } else {
290 if (Loc.substr(0, n2).getAsInteger(10, LineOffset))
291 return false;
292 if (Loc.substr(n2 + 1).getAsInteger(10, Discriminator))
293 return false;
294 }
295
296 StringRef Rest = Input.substr(n1 + 2);
297 if (isDigit(Rest[0])) {
298 LineTy = LineType::BodyProfile;
299 size_t n3 = Rest.find(' ');
300 if (n3 == StringRef::npos) {
301 if (Rest.getAsInteger(10, NumSamples))
302 return false;
303 } else {
304 if (Rest.substr(0, n3).getAsInteger(10, NumSamples))
305 return false;
306 }
307 // Find call targets and their sample counts.
308 // Note: In some cases, there are symbols in the profile which are not
309 // mangled. To accommodate such cases, use colon + integer pairs as the
310 // anchor points.
311 // An example:
312 // _M_construct<char *>:1000 string_view<std::allocator<char> >:437
313 // ":1000" and ":437" are used as anchor points so the string above will
314 // be interpreted as
315 // target: _M_construct<char *>
316 // count: 1000
317 // target: string_view<std::allocator<char> >
318 // count: 437
319 while (n3 != StringRef::npos) {
320 n3 += Rest.substr(n3).find_first_not_of(' ');
321 Rest = Rest.substr(n3);
322 n3 = Rest.find_first_of(':');
323 if (n3 == StringRef::npos || n3 == 0)
324 return false;
325
327 uint64_t count, n4;
328 while (true) {
329 // Get the segment after the current colon.
330 StringRef AfterColon = Rest.substr(n3 + 1);
331 // Get the target symbol before the current colon.
332 Target = Rest.substr(0, n3);
333 // Check if the word after the current colon is an integer.
334 n4 = AfterColon.find_first_of(' ');
335 n4 = (n4 != StringRef::npos) ? n3 + n4 + 1 : Rest.size();
336 StringRef WordAfterColon = Rest.substr(n3 + 1, n4 - n3 - 1);
337 if (!WordAfterColon.getAsInteger(10, count))
338 break;
339
340 // Try to find the next colon.
341 uint64_t n5 = AfterColon.find_first_of(':');
342 if (n5 == StringRef::npos)
343 return false;
344 n3 += n5 + 1;
345 }
346
347 // An anchor point is found. Save the {target, count} pair
348 TargetCountMap[Target] = count;
349 if (n4 == Rest.size())
350 break;
351 // Change n3 to the next blank space after colon + integer pair.
352 n3 = n4;
353 }
354 } else if (Rest.starts_with(kVTableProfPrefix)) {
356 return parseTypeCountMap(Rest.substr(strlen(kVTableProfPrefix)),
358 } else {
360 size_t n3 = Rest.find_last_of(':');
361 CalleeName = Rest.substr(0, n3);
362 if (Rest.substr(n3 + 1).getAsInteger(10, NumSamples))
363 return false;
364 }
365 return true;
366}
367
368/// Load samples from a text file.
369///
370/// See the documentation at the top of the file for an explanation of
371/// the expected format.
372///
373/// \returns true if the file was loaded successfully, false otherwise.
375 line_iterator LineIt(*Buffer, /*SkipBlanks=*/true, '#');
377
378 InlineCallStack InlineStack;
379 uint32_t TopLevelProbeProfileCount = 0;
380
381 // DepthMetadata tracks whether we have processed metadata for the current
382 // top-level or nested function profile.
383 uint32_t DepthMetadata = 0;
384
385 std::vector<SampleContext *> FlatSamples;
386
389 for (; !LineIt.is_at_eof(); ++LineIt) {
390 size_t pos = LineIt->find_first_not_of(' ');
391 if (pos == LineIt->npos || (*LineIt)[pos] == '#')
392 continue;
393 // Read the header of each function.
394 //
395 // Note that for function identifiers we are actually expecting
396 // mangled names, but we may not always get them. This happens when
397 // the compiler decides not to emit the function (e.g., it was inlined
398 // and removed). In this case, the binary will not have the linkage
399 // name for the function, so the profiler will emit the function's
400 // unmangled name, which may contain characters like ':' and '>' in its
401 // name (member functions, templates, etc).
402 //
403 // The only requirement we place on the identifier, then, is that it
404 // should not begin with a number.
405 if ((*LineIt)[0] != ' ') {
406 uint64_t NumSamples, NumHeadSamples;
407 StringRef FName;
408 if (!ParseHead(*LineIt, FName, NumSamples, NumHeadSamples)) {
409 reportError(LineIt.line_number(),
410 "Expected 'mangled_name:NUM:NUM', found " + *LineIt);
412 }
413 DepthMetadata = 0;
414 SampleContext FContext(FName, CSNameTable);
415 if (FContext.hasContext())
417 FunctionSamples &FProfile = Profiles.create(FContext);
418 mergeSampleProfErrors(Result, FProfile.addTotalSamples(NumSamples));
419 mergeSampleProfErrors(Result, FProfile.addHeadSamples(NumHeadSamples));
420 InlineStack.clear();
421 InlineStack.push_back(&FProfile);
422 } else {
423 uint64_t NumSamples;
424 StringRef FName;
425 DenseMap<StringRef, uint64_t> TargetCountMap;
427 uint32_t Depth, LineOffset, Discriminator;
429 uint64_t FunctionHash = 0;
430 uint32_t Attributes = 0;
431 bool IsFlat = false;
432 // TODO: Update ParseLine to return an error code instead of a bool and
433 // report it.
434 if (!ParseLine(*LineIt, LineTy, Depth, NumSamples, LineOffset,
435 Discriminator, FName, TargetCountMap, TypeCountMap,
436 FunctionHash, Attributes, IsFlat)) {
437 switch (LineTy) {
439 reportError(LineIt.line_number(),
440 "Cannot parse metadata: " + *LineIt);
441 break;
443 reportError(LineIt.line_number(),
444 "Expected 'vtables [mangled_vtable:NUM]+', found " +
445 *LineIt);
446 break;
447 default:
448 reportError(LineIt.line_number(),
449 "Expected 'NUM[.NUM]: NUM[ mangled_name:NUM]*', found " +
450 *LineIt);
451 }
453 }
454 if (LineTy != LineType::Metadata && Depth == DepthMetadata) {
455 // Metadata must be put at the end of a function profile.
456 reportError(LineIt.line_number(),
457 "Found non-metadata after metadata: " + *LineIt);
459 }
460
461 // Here we handle FS discriminators.
462 Discriminator &= getDiscriminatorMask();
463
464 while (InlineStack.size() > Depth) {
465 InlineStack.pop_back();
466 }
467 switch (LineTy) {
469 FunctionSamples &FSamples = InlineStack.back()->functionSamplesAt(
470 LineLocation(LineOffset, Discriminator))[FunctionId(FName)];
471 FSamples.setFunction(FunctionId(FName));
472 mergeSampleProfErrors(Result, FSamples.addTotalSamples(NumSamples));
473 InlineStack.push_back(&FSamples);
474 DepthMetadata = 0;
475 break;
476 }
477
480 Result, InlineStack.back()->addCallsiteVTableTypeProfAt(
481 LineLocation(LineOffset, Discriminator), TypeCountMap));
482 break;
483 }
484
486 FunctionSamples &FProfile = *InlineStack.back();
487 for (const auto &name_count : TargetCountMap) {
489 LineOffset, Discriminator,
490 FunctionId(name_count.first),
491 name_count.second));
492 }
494 Result,
495 FProfile.addBodySamples(LineOffset, Discriminator, NumSamples));
496 break;
497 }
498 case LineType::Metadata: {
499 FunctionSamples &FProfile = *InlineStack.back();
500 if (FunctionHash) {
501 FProfile.setFunctionHash(FunctionHash);
502 if (Depth == 1)
503 ++TopLevelProbeProfileCount;
504 }
505 FProfile.getContext().setAllAttributes(Attributes);
506 if (Attributes & (uint32_t)ContextShouldBeInlined)
507 ProfileIsPreInlined = true;
508 DepthMetadata = Depth;
509 if (IsFlat) {
510 if (Depth == 1)
511 FlatSamples.push_back(&FProfile.getContext());
512 else
514 Buffer->getBufferIdentifier(), LineIt.line_number(),
515 "!Flat may only be used at top level function.", DS_Warning));
516 }
517 break;
518 }
519 }
520 }
521 }
522
523 // Honor the option to skip flat functions. Since they are already added to
524 // the profile map, remove them all here.
525 if (SkipFlatProf)
526 for (SampleContext *FlatSample : FlatSamples)
527 Profiles.erase(*FlatSample);
528
529 assert((CSProfileCount == 0 || CSProfileCount == Profiles.size()) &&
530 "Cannot have both context-sensitive and regular profile");
532 assert((TopLevelProbeProfileCount == 0 ||
533 TopLevelProbeProfileCount == Profiles.size()) &&
534 "Cannot have both probe-based profiles and regular profiles");
535 ProfileIsProbeBased = (TopLevelProbeProfileCount > 0);
539
540 if (Result == sampleprof_error::success)
542
543 return Result;
544}
545
547 bool result = false;
548
549 // Check that the first non-comment line is a valid function header.
550 line_iterator LineIt(Buffer, /*SkipBlanks=*/true, '#');
551 if (!LineIt.is_at_eof()) {
552 if ((*LineIt)[0] != ' ') {
553 uint64_t NumSamples, NumHeadSamples;
554 StringRef FName;
555 result = ParseHead(*LineIt, FName, NumSamples, NumHeadSamples);
556 }
557 }
558
559 return result;
560}
561
562/// Emit a reader diagnostic for \p ProfError and return its error code.
563static std::error_code diagnoseReaderError(const SampleProfileReader &Reader,
564 sampleprof_error ProfError) {
565 std::error_code EC = ProfError;
566 Reader.reportError(0, EC.message());
567 return EC;
568}
569
571 if (Data >= End)
573
574 unsigned NumBytesRead = 0;
576 uint64_t Val = decodeULEB128(Data, &NumBytesRead, End, nullptr, &DecodeError);
577
578 // Preserve the distinction between incomplete input and an invalid value.
579 switch (DecodeError) {
581 break;
586 }
587
588 if (Val > std::numeric_limits<T>::max())
590
591 Data += NumBytesRead;
592 return static_cast<T>(Val);
593}
594
596 if (Data >= End)
598
599 const auto *Terminator = static_cast<const uint8_t *>(
600 std::memchr(Data, 0, static_cast<size_t>(End - Data)));
601 if (!Terminator)
603
604 StringRef Str(reinterpret_cast<const char *>(Data), Terminator - Data);
605 Data = Terminator + 1;
606 return Str;
607}
608
609template <typename T>
611 if (Data > End || static_cast<size_t>(End - Data) < sizeof(T))
613
614 using namespace support;
616 return Val;
617}
618
619template <typename T>
621 auto Idx = readNumber<size_t>();
622 if (std::error_code EC = Idx.getError())
623 return EC;
624 if (*Idx >= Table.size())
626 return *Idx;
627}
628
631 if (!NameTable)
633 auto Idx = readStringIndex(*NameTable);
634 if (std::error_code EC = Idx.getError())
635 return EC;
636 if (RetIdx)
637 *RetIdx = *Idx;
638 return (*NameTable)[*Idx];
639}
640
643 auto ContextIdx = readNumber<size_t>();
644 if (std::error_code EC = ContextIdx.getError())
645 return EC;
646 if (*ContextIdx >= CSNameTable.size())
648 if (RetIdx)
649 *RetIdx = *ContextIdx;
650 return CSNameTable[*ContextIdx];
651}
652
656 size_t Idx;
657 if (ProfileIsCS) {
658 auto FContext(readContextFromTable(&Idx));
659 if (std::error_code EC = FContext.getError())
660 return EC;
661 Context = SampleContext(*FContext);
662 } else {
663 auto FName(readStringFromTable(&Idx));
664 if (std::error_code EC = FName.getError())
665 return EC;
666 Context = SampleContext(*FName);
667 }
668 // Since MD5SampleContextStart may point to the profile's file data, need to
669 // make sure it is reading the same value on big endian CPU.
671 // Lazy computing of hash value, write back to the table to cache it. Only
672 // compute the context's hash value if it is being referenced for the first
673 // time.
674 if (Hash == 0) {
676 Hash = Context.getHashCode();
678 }
679 return std::make_pair(Context, Hash);
680}
681
682std::error_code
684 auto NumVTableTypes = readNumber<uint32_t>();
685 if (std::error_code EC = NumVTableTypes.getError())
686 return EC;
687 // With FS discriminators, M may already hold the types of another raw
688 // location that maps to the same masked location (see below), so reserve
689 // for both the existing and the incoming vtables.
690 M.reserve(M.size() + *NumVTableTypes);
691
692 for (uint32_t I = 0; I < *NumVTableTypes; ++I) {
693 auto VTableType(readStringFromTable());
694 if (std::error_code EC = VTableType.getError())
695 return EC;
696
697 auto VTableSamples = readNumber<uint64_t>();
698 if (std::error_code EC = VTableSamples.getError())
699 return EC;
700
701 auto [It, Inserted] = M.try_emplace(*VTableType, *VTableSamples);
702 if (Inserted)
703 continue;
704
705 // Without FS discriminators, the source profile should not have duplicate
706 // vtable records at the same location. Emit a warning about duplicate
707 // vtables and continue processing the profile, unless re-reading already
708 // loaded profiles is explicitly allowed.
711 Buffer->getBufferIdentifier(), 0,
712 "Duplicate vtable type " + VTableType->str() +
713 " at the same location. Additional counters will be ignored.",
714 DS_Warning));
715 continue;
716 }
717
718 // With flow-sensitive discriminators enabled in the profiled binary,
719 // several raw locations of the profiled instruction may map to the same
720 // masked location. Accumulate vtable counts for the same masked location,
721 // like body and callsite samples are accumulated.
722 It->second = SaturatingAdd(It->second, *VTableSamples);
723 }
725}
726
727std::error_code
730 "Cannot read vtable profiles if ReadVTableProf is false");
731
732 // Read the vtable type profile for the callsite.
733 auto NumCallsites = readNumber<uint32_t>();
734 if (std::error_code EC = NumCallsites.getError())
735 return EC;
736 FProfile.reserveCallsiteTypeCounts(*NumCallsites);
737
738 for (uint32_t I = 0; I < *NumCallsites; ++I) {
739 auto LineOffset = readNumber<uint64_t>();
740 if (std::error_code EC = LineOffset.getError())
741 return EC;
742
743 if (!isOffsetLegal(*LineOffset))
745
746 auto Discriminator = readNumber<uint64_t>();
747 if (std::error_code EC = Discriminator.getError())
748 return EC;
749
750 // Here we handle FS discriminators:
751 const uint32_t DiscriminatorVal = (*Discriminator) & getDiscriminatorMask();
752
753 if (std::error_code EC = readVTableTypeCountMap(FProfile.getTypeSamplesAt(
754 LineLocation(*LineOffset, DiscriminatorVal))))
755 return EC;
756 }
758}
759
760std::error_code
762 bool IsNested) {
763 if (ProfileSecRange.IsComposite && !IsNested) {
764 auto NumHeadSamples = readNumber<uint64_t>();
765 if (std::error_code EC = NumHeadSamples.getError())
766 return EC;
767 FProfile.addHeadSamples(*NumHeadSamples);
768 }
769 auto NumSamples = readNumber<uint64_t>();
770 if (std::error_code EC = NumSamples.getError())
771 return EC;
772 FProfile.addTotalSamples(*NumSamples);
773
774 // Read the samples in the body.
775 auto NumRecords = readNumber<uint32_t>();
776 if (std::error_code EC = NumRecords.getError())
777 return EC;
778 FProfile.reserveBodySamples(*NumRecords);
779
780 for (uint32_t I = 0; I < *NumRecords; ++I) {
781 auto LineOffset = readNumber<uint64_t>();
782 if (std::error_code EC = LineOffset.getError())
783 return EC;
784
785 if (!isOffsetLegal(*LineOffset)) {
787 }
788
789 auto Discriminator = readNumber<uint64_t>();
790 if (std::error_code EC = Discriminator.getError())
791 return EC;
792
793 auto NumSamples = readNumber<uint64_t>();
794 if (std::error_code EC = NumSamples.getError())
795 return EC;
796
797 auto NumCalls = readNumber<uint32_t>();
798 if (std::error_code EC = NumCalls.getError())
799 return EC;
800
801 // Here we handle FS discriminators:
802 uint32_t DiscriminatorVal = (*Discriminator) & getDiscriminatorMask();
803
804 for (uint32_t J = 0; J < *NumCalls; ++J) {
805 auto CalledFunction(readStringFromTable());
806 if (std::error_code EC = CalledFunction.getError())
807 return EC;
808
809 auto CalledFunctionSamples = readNumber<uint64_t>();
810 if (std::error_code EC = CalledFunctionSamples.getError())
811 return EC;
812
813 FProfile.addCalledTargetSamples(*LineOffset, DiscriminatorVal,
814 *CalledFunction, *CalledFunctionSamples);
815 }
816
817 FProfile.addBodySamples(*LineOffset, DiscriminatorVal, *NumSamples);
818 }
819
821}
822
823std::error_code
825 bool IsNested) {
826 // Read the number of profile types.
827 auto ProfNum = readNumber<uint64_t>();
828 if (std::error_code EC = ProfNum.getError())
829 return EC;
831 *ProfileTypeInfoOS << (IsNested ? "Nested function: " : "Function: ")
832 << FProfile.getContext().toString()
833 << "\n Profile blocks: " << *ProfNum << "\n";
834
835 // Each type identifies one logical payload for the function. Decoding the
836 // same type twice would merge absolute counters from malformed input.
837 SmallSet<uint64_t, 4> SeenTypes;
838
839 // Read the specified number of composite profiles.
840 for (uint64_t I = 0; I < *ProfNum; ++I) {
841 auto Type = readNumber<uint64_t>();
842 if (std::error_code EC = Type.getError())
843 return EC;
844 // Report the conflicting ID so malformed profiles can be diagnosed
845 // without inspecting their binary encoding.
846 if (!SeenTypes.insert(*Type).second) {
847 reportError(0, "Duplicate profile type ID: " + Twine(*Type));
849 }
850 auto Size = readNumber<uint64_t>();
851 if (std::error_code EC = Size.getError())
852 return EC;
854 *ProfileTypeInfoOS << " Type: " << *Type << " ("
856 << "), Payload size: " << *Size << "\n";
857 const uint64_t RemainingSize = End - Data;
858 // Diagnose a size that would let the payload cross its containing section.
859 if (*Size > RemainingSize) {
860 reportError(0, "Profile type ID " + Twine(*Type) +
861 " declares payload size " + Twine(*Size) +
862 ", but only " + Twine(RemainingSize) +
863 " bytes remain");
865 }
866
867 const uint8_t *PayloadEnd = Data + *Size;
868 std::error_code EC = sampleprof_error::success;
869 // Restrict field readers to the current payload so they reject fields that
870 // extend into the following payload.
871 SaveAndRestore<const uint8_t *> RestoreEnd(End, PayloadEnd);
872 switch (*Type) {
873 case ProfTypeLBR:
874 EC = readLBRProfile(FProfile, IsNested);
875 break;
876 default:
877 // Skip unknown profile types for forward compatibility.
879 Data = PayloadEnd;
880 break;
881 }
882
883 if (EC)
884 return EC;
885 // Reject trailing bytes because every known decoder must consume exactly
886 // the payload declared for its type.
887 if (Data != PayloadEnd) {
888 reportError(0,
889 "Profile type ID " + Twine(*Type) +
890 " did not consume its complete payload; unread bytes: " +
891 Twine(PayloadEnd - Data));
893 }
894 }
895
897}
898
899std::error_code
901 bool IsNested) {
902 if (ProfileSecRange.IsComposite) {
903 if (std::error_code EC = readCompositeProfile(FProfile, IsNested))
904 return EC;
905 } else {
906 if (std::error_code EC = readLBRProfile(FProfile, IsNested))
907 return EC;
908 }
909
910 // Read all the samples for inlined function calls.
911 auto NumCallsites = readNumber<uint32_t>();
912 if (std::error_code EC = NumCallsites.getError())
913 return EC;
914
915 for (uint32_t J = 0; J < *NumCallsites; ++J) {
916 auto LineOffset = readNumber<uint64_t>();
917 if (std::error_code EC = LineOffset.getError())
918 return EC;
919
920 auto Discriminator = readNumber<uint64_t>();
921 if (std::error_code EC = Discriminator.getError())
922 return EC;
923
924 auto FName(readStringFromTable());
925 if (std::error_code EC = FName.getError())
926 return EC;
927
928 // Here we handle FS discriminators:
929 uint32_t DiscriminatorVal = (*Discriminator) & getDiscriminatorMask();
930
931 FunctionSamples &CalleeProfile = FProfile.functionSamplesAt(
932 LineLocation(*LineOffset, DiscriminatorVal))[*FName];
933 CalleeProfile.setFunction(*FName);
934 if (std::error_code EC = readProfile(CalleeProfile, /*IsNested=*/true))
935 return EC;
936 }
937
938 if (ReadVTableProf)
939 return readCallsiteVTableProf(FProfile);
940
942}
943
944std::error_code
947 Data = Start;
948 ErrorOr<uint64_t> NumHeadSamples = 0;
949 if (!ProfileSecRange.IsComposite) {
950 NumHeadSamples = readNumber<uint64_t>();
951 if (std::error_code EC = NumHeadSamples.getError())
952 return EC;
953 }
954 auto FContextHash(readSampleContextFromTable());
955 if (std::error_code EC = FContextHash.getError())
956 return EC;
957
958 auto &[FContext, Hash] = *FContextHash;
959 // Use the cached hash value for insertion instead of recalculating it.
960 auto Res = Profiles.try_emplace(Hash, FContext, FunctionSamples());
961 FunctionSamples &FProfile = Res.first->second;
962 FProfile.setContext(FContext);
963 if (!ProfileSecRange.IsComposite)
964 FProfile.addHeadSamples(*NumHeadSamples);
965
966 if (FContext.hasContext())
968
969 if (std::error_code EC = readProfile(FProfile, /*IsNested=*/false))
970 return EC;
972}
973
974std::error_code
978
982 while (Data < End) {
983 if (std::error_code EC = readFuncProfile(Data))
984 return EC;
985 }
986
988}
989
991 const uint8_t *Start, uint64_t Size, const SecHdrTableEntry &Entry) {
992 Data = Start;
993 End = Start + Size;
994 switch (Entry.Type) {
995 case SecProfSummary:
996 if (std::error_code EC = readSummary())
997 return EC;
999 Summary->setPartialProfile(true);
1007 ReadVTableProf = true;
1008 break;
1009 case SecNameTable: {
1010 bool FixedLengthMD5 =
1012 bool UseMD5 = hasSecFlag(Entry, SecNameTableFlags::SecFlagMD5Name);
1013 // UseMD5 means if THIS section uses MD5, ProfileIsMD5 means if the entire
1014 // profile uses MD5 for function name matching in IPO passes.
1015 ProfileIsMD5 = ProfileIsMD5 || UseMD5;
1018 bool IsEytzinger = hasSecFlag(Entry, SecNameTableFlags::SecFlagEytzinger);
1019 if (std::error_code EC =
1020 readNameTableSec(UseMD5, FixedLengthMD5, IsEytzinger))
1021 return EC;
1022 break;
1023 }
1024 case SecCSNameTable: {
1025 if (std::error_code EC = readCSNameTableSec())
1026 return EC;
1027 break;
1028 }
1029 case SecLBRProfile:
1031 // Retain the section and its encoding for subsequent on-demand reads.
1032 ProfileSecRange = {Data, End, Entry.Type == SecCompositeProfile};
1033 if (std::error_code EC = readFuncProfiles())
1034 return EC;
1035 break;
1036 case SecFuncOffsetTable:
1038 // If module is absent, we are using LLVM tools, and need to read all
1039 // profiles, so skip reading the function offset table.
1040 if (!M) {
1041 Data = End;
1042 } else {
1043 bool IsEytzinger =
1045 bool IsFlat = hasSecFlag(Entry, SecCommonFlags::SecFlagFlat);
1046 // An unflagged function offset table inherently indexes the primary
1047 // Nested symbol span.
1048 bool IsNested = !IsFlat;
1049 assert((!ProfileIsCS ||
1051 IsEytzinger) &&
1052 "func offset table should always be sorted or in Eytzinger BFS "
1053 "order in CS profile");
1054 if (std::error_code EC = readFuncOffsetTable(IsEytzinger, IsNested))
1055 return EC;
1056 }
1057 break;
1058 case SecFuncMetadata: {
1064 if (std::error_code EC = readFuncMetadata())
1065 return EC;
1066 break;
1067 }
1069 if (std::error_code EC = readProfileSymbolList(
1071 return EC;
1072 break;
1073 default:
1074 if (std::error_code EC = readCustomSection(Entry))
1075 return EC;
1076 break;
1077 }
1079}
1080
1082 // If profile is CS, the function offset section is expected to consist of
1083 // sequences of contexts in pre-order layout
1084 // (e.g. [A, A:1 @ B, A:1 @ B:2.3 @ C] [D, D:1 @ E]), so that when a matched
1085 // context in the module is found, the profiles of all its callees are
1086 // recursively loaded. A list is needed since the order of profiles matters.
1087 if (ProfileIsCS)
1088 return true;
1089
1090 // If the profile is MD5, use the map container to lookup functions in
1091 // the module. A remapper has no use on MD5 names.
1092 if (useMD5())
1093 return false;
1094
1095 // Profile is not MD5 and if a remapper is present, the remapped name of
1096 // every function needed to be matched against the module, so use the list
1097 // container since each entry is accessed.
1098 if (Remapper)
1099 return true;
1100
1101 // Otherwise use the map container for faster lookup.
1102 // TODO: If the cardinality of the function offset section is much smaller
1103 // than the number of functions in the module, using the list container can
1104 // be always faster, but we need to figure out the constant factor to
1105 // determine the cutoff.
1106 return false;
1107}
1108
1109std::error_code
1111 SampleProfileMap &Profiles) {
1112 if (FuncsToUse.empty())
1114
1117 if (std::error_code EC = readFuncProfiles(FuncsToUse, Profiles))
1118 return EC;
1119 End = Data;
1120 DenseSet<FunctionSamples *> ProfilesToReadMetadata;
1121 for (auto FName : FuncsToUse) {
1122 auto I = Profiles.find(FName);
1123 if (I != Profiles.end())
1124 ProfilesToReadMetadata.insert(&I->second);
1125 }
1126
1127 if (std::error_code EC = readFuncMetadata(ProfilesToReadMetadata))
1128 return EC;
1130}
1131
1133 if (!M)
1134 return false;
1135 FuncsToUse.clear();
1136 for (auto &F : *M)
1138 return true;
1139}
1140
1141std::error_code
1143 bool IsNested) {
1144 if (IsEytzinger)
1145 return readEytzingerFuncOffsetTable(IsNested);
1147}
1148
1149std::error_code
1151 // If there are more than one function offset section, the profile associated
1152 // with the previous section has to be done reading before next one is read.
1153 FuncOffsetTable.reset();
1154
1155 size_t Size = End - Data;
1156 size_t SpanSize = NameTable->getEytzingerSpan(IsNested).size();
1157 if (Size != SpanSize * sizeof(uint32_t))
1159
1160 auto *Array = reinterpret_cast<const support::ulittle32_t *>(Data);
1161 ArrayRef<support::ulittle32_t> Offsets(Array, SpanSize);
1162
1163 FuncOffsetTable.emplace(EytzingerMode, NameTable->getEytzingerSpan(IsNested),
1164 Offsets);
1165
1166 Data = End;
1168}
1169
1171 // If there are more than one function offset section, the profile associated
1172 // with the previous section has to be done reading before next one is read.
1173 FuncOffsetTable.reset();
1174 FuncOffsetList.clear();
1175
1176 auto Size = readNumber<uint64_t>();
1177 if (std::error_code EC = Size.getError())
1178 return EC;
1179
1180 bool UseFuncOffsetList = useFuncOffsetList();
1181 if (UseFuncOffsetList)
1182 FuncOffsetList.reserve(*Size);
1183 else
1185
1186 for (uint64_t I = 0; I < *Size; ++I) {
1187 auto FContextHash(readSampleContextFromTable());
1188 if (std::error_code EC = FContextHash.getError())
1189 return EC;
1190
1191 auto &[FContext, Hash] = *FContextHash;
1193 if (std::error_code EC = Offset.getError())
1194 return EC;
1195
1196 if (UseFuncOffsetList)
1197 FuncOffsetList.emplace_back(FContext, *Offset);
1198 else
1199 // Because Porfiles replace existing value with new value if collision
1200 // happens, we also use the latest offset so that they are consistent.
1201 FuncOffsetTable->insert(Hash, *Offset);
1202 }
1203
1205}
1206
1209 const uint8_t *Start = Data;
1210
1211 if (Remapper) {
1212 for (auto Name : FuncsToUse) {
1213 Remapper->insert(Name);
1214 }
1215 }
1216
1217 if (FuncOffsetTable && FuncOffsetTable->isEytzinger() &&
1219 ArrayRef<support::ulittle32_t> Offsets = FuncOffsetTable->getFuncOffsets();
1220 if (Offsets.size() != FuncOffsetTable->getExpectedSize())
1222 for (const auto &[LocalIdx, RelOffset] : llvm::enumerate(Offsets)) {
1223 if (RelOffset == UINT32_MAX)
1224 continue;
1225 const uint8_t *FuncProfileAddr = Start + RelOffset;
1226 if (std::error_code EC = readFuncProfile(FuncProfileAddr, Profiles))
1227 return EC;
1228 }
1230 }
1231
1232 if (ProfileIsCS) {
1234 DenseSet<uint64_t> FuncGuidsToUse;
1235 if (useMD5()) {
1236 for (auto Name : FuncsToUse)
1238 }
1239
1240 // For each function in current module, load all context profiles for
1241 // the function as well as their callee contexts which can help profile
1242 // guided importing for ThinLTO. This can be achieved by walking
1243 // through an ordered context container, where contexts are laid out
1244 // as if they were walked in preorder of a context trie. While
1245 // traversing the trie, a link to the highest common ancestor node is
1246 // kept so that all of its decendants will be loaded.
1247 const SampleContext *CommonContext = nullptr;
1248 for (const auto &NameOffset : FuncOffsetList) {
1249 const auto &FContext = NameOffset.first;
1250 FunctionId FName = FContext.getFunction();
1251 StringRef FNameString;
1252 if (!useMD5())
1253 FNameString = FName.stringRef();
1254
1255 // For function in the current module, keep its farthest ancestor
1256 // context. This can be used to load itself and its child and
1257 // sibling contexts.
1258 if ((useMD5() && FuncGuidsToUse.count(FName.getHashCode())) ||
1259 (!useMD5() && (FuncsToUse.count(FNameString) ||
1260 (Remapper && Remapper->exist(FNameString))))) {
1261 if (!CommonContext || !CommonContext->isPrefixOf(FContext))
1262 CommonContext = &FContext;
1263 }
1264
1265 if (CommonContext == &FContext ||
1266 (CommonContext && CommonContext->isPrefixOf(FContext))) {
1267 // Load profile for the current context which originated from
1268 // the common ancestor.
1269 const uint8_t *FuncProfileAddr = Start + NameOffset.second;
1270 if (std::error_code EC = readFuncProfile(FuncProfileAddr))
1271 return EC;
1272 }
1273 }
1274 } else if (useMD5()) {
1276 for (auto Name : FuncsToUse) {
1277 auto GUID = MD5Hash(Name);
1278 if (auto Offset = FuncOffsetTable->lookup(GUID)) {
1279 const uint8_t *FuncProfileAddr = Start + *Offset;
1280 if (std::error_code EC = readFuncProfile(FuncProfileAddr, Profiles))
1281 return EC;
1282 }
1283 }
1284 } else if (Remapper) {
1286 for (auto NameOffset : FuncOffsetList) {
1287 SampleContext FContext(NameOffset.first);
1288 auto FuncName = FContext.getFunction();
1289 StringRef FuncNameStr = FuncName.stringRef();
1290 if (!FuncsToUse.count(FuncNameStr) && !Remapper->exist(FuncNameStr))
1291 continue;
1292 // This function may be called more than once on the same reader: once
1293 // for the module's functions and then incrementally (e.g. by
1294 // SampleProfileMatcher) for additional candidates. The remapper is
1295 // cumulative, so names inserted by an earlier call still match here.
1296 // Skip profiles that are already loaded; otherwise they would be read
1297 // again and merged into themselves.
1299 Profiles.find(FContext) != Profiles.end())
1300 continue;
1301 const uint8_t *FuncProfileAddr = Start + NameOffset.second;
1302 if (std::error_code EC = readFuncProfile(FuncProfileAddr, Profiles))
1303 return EC;
1304 }
1305 } else {
1307 for (auto Name : FuncsToUse) {
1308 if (auto Offset = FuncOffsetTable->lookup(MD5Hash(Name))) {
1309 const uint8_t *FuncProfileAddr = Start + *Offset;
1310 if (std::error_code EC = readFuncProfile(FuncProfileAddr, Profiles))
1311 return EC;
1312 }
1313 }
1314 }
1315
1317}
1318
1320 // Collect functions used by current module if the Reader has been
1321 // given a module.
1322 // collectFuncsFromModule uses FunctionSamples::getCanonicalFnName
1323 // which will query FunctionSamples::HasUniqSuffix, so it has to be
1324 // called after FunctionSamples::HasUniqSuffix is set, i.e. after
1325 // NameTable section is read.
1326 bool LoadFuncsToBeUsed = collectFuncsFromModule();
1327
1328 // When LoadFuncsToBeUsed is false, we are using LLVM tool, need to read all
1329 // profiles.
1330 if (!LoadFuncsToBeUsed) {
1331 while (Data < End) {
1332 if (std::error_code EC = readFuncProfile(Data))
1333 return EC;
1334 }
1335 assert(Data == End && "More data is read than expected");
1336 } else {
1337 // Load function profiles on demand.
1338 if (std::error_code EC = readFuncProfiles(FuncsToUse, Profiles))
1339 return EC;
1340 Data = End;
1341 }
1342 assert((CSProfileCount == 0 || CSProfileCount == Profiles.size()) &&
1343 "Cannot have both context-sensitive and regular profile");
1345 "Section flag should be consistent with actual profile");
1347}
1348
1349std::error_code
1355
1357 size_t Size = End - Data;
1358 if (Size % sizeof(uint64_t) != 0)
1360 const auto *Table = reinterpret_cast<const support::ulittle64_t *>(Data);
1361 size_t NumEntries = Size / sizeof(uint64_t);
1362 if (!ProfSymList)
1363 ProfSymList = std::make_unique<ProfileSymbolList>();
1364 ProfSymList->setColdGUIDTable(
1366 Data = End;
1368}
1369
1370std::error_code
1372 if (!ProfSymList)
1373 ProfSymList = std::make_unique<ProfileSymbolList>();
1374
1375 if (std::error_code EC = ProfSymList->read(Data, End - Data))
1376 return EC;
1377
1378 Data = End;
1380}
1381
1382std::error_code SampleProfileReaderExtBinaryBase::decompressSection(
1383 const uint8_t *SecStart, const uint64_t SecSize,
1384 const uint8_t *&DecompressBuf, uint64_t &DecompressBufSize) {
1385 Data = SecStart;
1386 End = SecStart + SecSize;
1387 auto DecompressSize = readNumber<uint64_t>();
1388 if (std::error_code EC = DecompressSize.getError())
1389 return EC;
1390 DecompressBufSize = *DecompressSize;
1391
1392 auto CompressSize = readNumber<uint64_t>();
1393 if (std::error_code EC = CompressSize.getError())
1394 return EC;
1395
1398
1399 uint8_t *Buffer = Allocator.Allocate<uint8_t>(DecompressBufSize);
1400 size_t UCSize = DecompressBufSize;
1402 Buffer, UCSize);
1403 if (E)
1405 DecompressBuf = reinterpret_cast<const uint8_t *>(Buffer);
1407}
1408
1410 const uint8_t *BufStart =
1411 reinterpret_cast<const uint8_t *>(Buffer->getBufferStart());
1412
1413 for (auto &Entry : SecHdrTable) {
1414 // Skip empty section.
1415 if (!Entry.Size)
1416 continue;
1417
1418 // Skip sections without inlined functions when SkipFlatProf is true.
1420 continue;
1421
1422 const uint8_t *SecStart = BufStart + Entry.Offset;
1423 uint64_t SecSize = Entry.Size;
1424
1425 // If the section is compressed, decompress it into a buffer
1426 // DecompressBuf before reading the actual data. The pointee of
1427 // 'Data' will be changed to buffer hold by DecompressBuf
1428 // temporarily when reading the actual data.
1429 bool isCompressed = hasSecFlag(Entry, SecCommonFlags::SecFlagCompress);
1430 if (isCompressed) {
1431 const uint8_t *DecompressBuf;
1432 uint64_t DecompressBufSize;
1433 if (std::error_code EC = decompressSection(
1434 SecStart, SecSize, DecompressBuf, DecompressBufSize))
1435 return EC;
1436 SecStart = DecompressBuf;
1437 SecSize = DecompressBufSize;
1438 }
1439
1440 if (std::error_code EC = readOneSection(SecStart, SecSize, Entry))
1441 return EC;
1442 if (Data != SecStart + SecSize)
1444
1445 // Change the pointee of 'Data' from DecompressBuf to original Buffer.
1446 if (isCompressed) {
1447 Data = BufStart + Entry.Offset;
1448 End = BufStart + Buffer->getBufferSize();
1449 }
1450 }
1451
1453}
1454
1455std::error_code SampleProfileReaderRawBinary::verifySPMagic(uint64_t Magic) {
1456 if (Magic == SPMagic())
1459}
1460
1461std::error_code SampleProfileReaderExtBinary::verifySPMagic(uint64_t Magic) {
1462 if (Magic == SPMagic(SPF_Ext_Binary))
1465}
1466
1468 auto Size = readNumber<size_t>();
1469 if (std::error_code EC = Size.getError())
1470 return EC;
1471
1472 // Normally if useMD5 is true, the name table should have MD5 values, not
1473 // strings, however in the case that ExtBinary profile has multiple name
1474 // tables mixing string and MD5, all of them have to be normalized to use MD5,
1475 // because optimization passes can only handle either type.
1476 bool UseMD5 = useMD5();
1477
1478 std::vector<FunctionId> TableVec;
1479 TableVec.reserve(*Size);
1480 if (!ProfileIsCS) {
1481 MD5SampleContextTable.clear();
1482 if (UseMD5)
1483 MD5SampleContextTable.reserve(*Size);
1484 else
1485 // If we are using strings, delay MD5 computation since only a portion of
1486 // names are used by top level functions. Use 0 to indicate MD5 value is
1487 // to be calculated as no known string has a MD5 value of 0.
1488 MD5SampleContextTable.resize(*Size);
1489 }
1490 for (size_t I = 0; I < *Size; ++I) {
1491 auto Name(readString());
1492 if (std::error_code EC = Name.getError())
1493 return EC;
1494 if (UseMD5) {
1495 FunctionId FID(*Name);
1496 if (!ProfileIsCS)
1497 MD5SampleContextTable.emplace_back(FID.getHashCode());
1498 TableVec.emplace_back(FID);
1499 } else
1500 TableVec.push_back(FunctionId(*Name));
1501 }
1502 if (!ProfileIsCS)
1504 if (UseMD5)
1505 NameTable =
1506 std::make_unique<MD5SampleProfileNameTable>(std::move(TableVec));
1507 else
1508 NameTable =
1509 std::make_unique<StringSampleProfileNameTable>(std::move(TableVec));
1511}
1512
1514 bool IsMD5, bool FixedLengthMD5, bool IsEytzinger) {
1515 if (IsEytzinger)
1516 return readNameTableSecEytzinger(IsMD5, FixedLengthMD5);
1517 return readNameTableSecLegacy(IsMD5, FixedLengthMD5);
1518}
1519
1520// Read the Eytzinger layout for SecNameTable from an ExtBinary MD5 profile.
1521//
1522// The section consists of three sequential ULEB128 symbol counts (Nested, Flat,
1523// and Inlinees) followed by their corresponding arrays of 64-bit MD5 hash keys
1524// laid out in Eytzinger order.
1526 bool IsMD5, bool FixedLengthMD5) {
1527 assert(IsMD5 && "Eytzinger name tables require MD5 representation");
1528 if (!IsMD5)
1530
1531 // Read the table sizes for Nested, flat, and inlinee symbols.
1532 std::array<uint64_t, static_cast<size_t>(EytzingerSpan::NumSpans)> Counts;
1533 for (uint64_t &Count : Counts) {
1534 auto ValOrErr = readNumber<uint64_t>();
1535 if (std::error_code EC = ValOrErr.getError())
1536 return EC;
1537 Count = *ValOrErr;
1538 }
1539 auto [NumNested, NumFlat, NumInlinees] = Counts;
1540
1541 // Guard against unsigned overflow in total entry computation.
1542 if (NumNested > std::numeric_limits<uint32_t>::max() ||
1543 NumFlat > std::numeric_limits<uint32_t>::max() ||
1544 NumInlinees > std::numeric_limits<uint32_t>::max())
1546
1547 uint64_t TotalEntries = NumNested + NumFlat + NumInlinees;
1548 if (static_cast<size_t>(End - Data) < TotalEntries * sizeof(uint64_t))
1550
1551 NameTable = std::make_unique<EytzingerSampleProfileNameTable>(
1552 reinterpret_cast<const support::ulittle64_t *>(Data), NumNested, NumFlat,
1553 NumInlinees);
1554
1555 if (!ProfileIsCS)
1556 MD5SampleContextStart = reinterpret_cast<const uint64_t *>(Data);
1557 Data = Data + TotalEntries * sizeof(uint64_t);
1559}
1560
1561std::error_code
1563 bool FixedLengthMD5) {
1564 if (FixedLengthMD5) {
1565 if (!IsMD5)
1566 errs() << "If FixedLengthMD5 is true, UseMD5 has to be true";
1567 auto Size = readNumber<size_t>();
1568 if (std::error_code EC = Size.getError())
1569 return EC;
1570
1571 assert(Data + (*Size) * sizeof(uint64_t) == End &&
1572 "Fixed length MD5 name table does not contain specified number of "
1573 "entries");
1574 if (Data + (*Size) * sizeof(uint64_t) > End)
1576
1577 if (LazyLoadNameTable) {
1578 NameTable = std::make_unique<LazySampleProfileNameTable>(Data, *Size);
1579 } else {
1580 std::vector<FunctionId> TableVec;
1581 TableVec.reserve(*Size);
1582 for (size_t I = 0; I < *Size; ++I) {
1583 using namespace support;
1584 uint64_t FID = endian::read<uint64_t, unaligned>(
1585 Data + I * sizeof(uint64_t), endianness::little);
1586 TableVec.emplace_back(FunctionId(FID));
1587 }
1588 NameTable =
1589 std::make_unique<MD5SampleProfileNameTable>(std::move(TableVec));
1590 }
1591 if (!ProfileIsCS)
1592 MD5SampleContextStart = reinterpret_cast<const uint64_t *>(Data);
1593 Data = Data + (*Size) * sizeof(uint64_t);
1595 }
1596
1597 if (IsMD5) {
1598 assert(!FixedLengthMD5 && "FixedLengthMD5 should be unreachable here");
1599 auto Size = readNumber<size_t>();
1600 if (std::error_code EC = Size.getError())
1601 return EC;
1602
1603 std::vector<FunctionId> TableVec;
1604 TableVec.reserve(*Size);
1605 if (!ProfileIsCS)
1606 MD5SampleContextTable.resize(*Size);
1607 for (size_t I = 0; I < *Size; ++I) {
1608 auto FID = readNumber<uint64_t>();
1609 if (std::error_code EC = FID.getError())
1610 return EC;
1611 if (!ProfileIsCS)
1613 TableVec.emplace_back(FunctionId(*FID));
1614 }
1615 if (!ProfileIsCS)
1617 NameTable =
1618 std::make_unique<MD5SampleProfileNameTable>(std::move(TableVec));
1620 }
1621
1623}
1624
1625// Read in the CS name table section, which basically contains a list of context
1626// vectors. Each element of a context vector, aka a frame, refers to the
1627// underlying raw function names that are stored in the name table, as well as
1628// a callsite identifier that only makes sense for non-leaf frames.
1630 auto Size = readNumber<size_t>();
1631 if (std::error_code EC = Size.getError())
1632 return EC;
1633
1634 CSNameTable.clear();
1635 CSNameTable.reserve(*Size);
1636 if (ProfileIsCS) {
1637 // Delay MD5 computation of CS context until they are needed. Use 0 to
1638 // indicate MD5 value is to be calculated as no known string has a MD5
1639 // value of 0.
1640 MD5SampleContextTable.clear();
1641 MD5SampleContextTable.resize(*Size);
1643 }
1644 for (size_t I = 0; I < *Size; ++I) {
1645 CSNameTable.emplace_back(SampleContextFrameVector());
1646 auto ContextSize = readNumber<uint32_t>();
1647 if (std::error_code EC = ContextSize.getError())
1648 return EC;
1649 for (uint32_t J = 0; J < *ContextSize; ++J) {
1650 auto FName(readStringFromTable());
1651 if (std::error_code EC = FName.getError())
1652 return EC;
1653 auto LineOffset = readNumber<uint64_t>();
1654 if (std::error_code EC = LineOffset.getError())
1655 return EC;
1656
1657 if (!isOffsetLegal(*LineOffset))
1659
1660 auto Discriminator = readNumber<uint64_t>();
1661 if (std::error_code EC = Discriminator.getError())
1662 return EC;
1663
1664 CSNameTable.back().emplace_back(
1665 FName.get(), LineLocation(LineOffset.get(), Discriminator.get()));
1666 }
1667 }
1668
1670}
1671
1672std::error_code
1674 if (Data < End) {
1675 if (ProfileIsProbeBased) {
1676 auto Checksum = readNumber<uint64_t>();
1677 if (std::error_code EC = Checksum.getError())
1678 return EC;
1679 if (FProfile)
1680 FProfile->setFunctionHash(*Checksum);
1681 }
1682
1683 if (ProfileHasAttribute) {
1684 auto Attributes = readNumber<uint32_t>();
1685 if (std::error_code EC = Attributes.getError())
1686 return EC;
1687 if (FProfile)
1688 FProfile->getContext().setAllAttributes(*Attributes);
1689 }
1690
1691 if (!ProfileIsCS) {
1692 // Read all the attributes for inlined function calls.
1693 auto NumCallsites = readNumber<uint32_t>();
1694 if (std::error_code EC = NumCallsites.getError())
1695 return EC;
1696
1697 for (uint32_t J = 0; J < *NumCallsites; ++J) {
1698 auto LineOffset = readNumber<uint64_t>();
1699 if (std::error_code EC = LineOffset.getError())
1700 return EC;
1701
1702 auto Discriminator = readNumber<uint64_t>();
1703 if (std::error_code EC = Discriminator.getError())
1704 return EC;
1705
1706 auto FContextHash(readSampleContextFromTable());
1707 if (std::error_code EC = FContextHash.getError())
1708 return EC;
1709
1710 auto &[FContext, Hash] = *FContextHash;
1711 FunctionSamples *CalleeProfile = nullptr;
1712 if (FProfile) {
1713 CalleeProfile = const_cast<FunctionSamples *>(
1715 *LineOffset, *Discriminator))[FContext.getFunction()]);
1716 }
1717 if (std::error_code EC = readFuncMetadata(CalleeProfile))
1718 return EC;
1719 }
1720 }
1721 }
1722
1724}
1725
1728 if (FuncMetadataIndex.empty())
1730
1731 for (auto *FProfile : Profiles) {
1732 auto R = FuncMetadataIndex.find(FProfile->getContext().getHashCode());
1733 if (R == FuncMetadataIndex.end())
1734 continue;
1735
1736 Data = R->second.first;
1737 End = R->second.second;
1738 if (std::error_code EC = readFuncMetadata(FProfile))
1739 return EC;
1740 assert(Data == End && "More data is read than expected");
1741 }
1743}
1744
1746 while (Data < End) {
1747 auto FContextHash(readSampleContextFromTable());
1748 if (std::error_code EC = FContextHash.getError())
1749 return EC;
1750 auto &[FContext, Hash] = *FContextHash;
1751 FunctionSamples *FProfile = nullptr;
1752 auto It = Profiles.find(FContext);
1753 if (It != Profiles.end())
1754 FProfile = &It->second;
1755
1756 const uint8_t *Start = Data;
1757 if (std::error_code EC = readFuncMetadata(FProfile))
1758 return EC;
1759
1760 FuncMetadataIndex[FContext.getHashCode()] = {Start, Data};
1761 }
1762
1763 assert(Data == End && "More data is read than expected");
1765}
1766
1767std::error_code
1769 SecHdrTableEntry Entry;
1771 if (std::error_code EC = Type.getError())
1772 return EC;
1773 Entry.Type = static_cast<SecType>(*Type);
1774
1775 // Reject a section whose encoding is newer than the declared file version.
1776 if ((Entry.Type == SecCompositeProfile ||
1777 Entry.Type == SecCompositeFuncOffsetTable) &&
1780
1781 auto Flags = readUnencodedNumber<uint64_t>();
1782 if (std::error_code EC = Flags.getError())
1783 return EC;
1784 Entry.Flags = *Flags;
1785
1787 if (std::error_code EC = Offset.getError())
1788 return EC;
1789 Entry.Offset = *Offset;
1790
1792 if (std::error_code EC = Size.getError())
1793 return EC;
1794 Entry.Size = *Size;
1795
1796 Entry.LayoutIndex = Idx;
1797 SecHdrTable.push_back(std::move(Entry));
1799}
1800
1802 auto EntryNum = readUnencodedNumber<uint64_t>();
1803 if (std::error_code EC = EntryNum.getError())
1804 return EC;
1805
1806 for (uint64_t i = 0; i < (*EntryNum); i++)
1807 if (std::error_code EC = readSecHdrTableEntry(i))
1808 return EC;
1809
1811}
1812
1814 const uint8_t *BufStart =
1815 reinterpret_cast<const uint8_t *>(Buffer->getBufferStart());
1816 Data = BufStart;
1817 End = BufStart + Buffer->getBufferSize();
1818
1819 if (std::error_code EC = readMagicIdent())
1820 return EC;
1821
1822 if (std::error_code EC = readSecHdrTable())
1823 return EC;
1824
1826}
1827
1829 uint64_t Size = 0;
1830 for (auto &Entry : SecHdrTable) {
1831 if (Entry.Type == Type)
1832 Size += Entry.Size;
1833 }
1834 return Size;
1835}
1836
1838 // Sections in SecHdrTable is not necessarily in the same order as
1839 // sections in the profile because section like FuncOffsetTable needs
1840 // to be written after section LBRProfile but needs to be read before
1841 // section LBRProfile, so we cannot simply use the last entry in
1842 // SecHdrTable to calculate the file size.
1843 uint64_t FileSize = 0;
1844 for (auto &Entry : SecHdrTable) {
1845 FileSize = std::max(Entry.Offset + Entry.Size, FileSize);
1846 }
1847 return FileSize;
1848}
1849
1850static std::string getSecFlagsStr(const SecHdrTableEntry &Entry) {
1851 std::string Flags;
1853 Flags.append("{compressed,");
1854 else
1855 Flags.append("{");
1856
1858 Flags.append("flat,");
1859
1860 switch (Entry.Type) {
1861 case SecNameTable:
1863 Flags.append("eytzinger,");
1865 Flags.append("fixlenmd5,");
1867 Flags.append("md5,");
1869 Flags.append("uniq,");
1870 break;
1871 case SecProfSummary:
1873 Flags.append("partial,");
1875 Flags.append("context,");
1877 Flags.append("preInlined,");
1879 Flags.append("fs-discriminator,");
1880 break;
1881 case SecFuncOffsetTable:
1884 Flags.append("ordered,");
1886 Flags.append("eytzinger,");
1887 break;
1888 case SecFuncMetadata:
1890 Flags.append("probe,");
1892 Flags.append("attr,");
1893 break;
1896 Flags.append("md5,");
1897 break;
1898 default:
1899 break;
1900 }
1901 char &last = Flags.back();
1902 if (last == ',')
1903 last = '}';
1904 else
1905 Flags.append("}");
1906 return Flags;
1907}
1908
1910 uint64_t TotalSecsSize = 0;
1911 for (auto &Entry : SecHdrTable) {
1912 OS << getSecName(Entry.Type) << " - Offset: " << Entry.Offset
1913 << ", Size: " << Entry.Size << ", Flags: " << getSecFlagsStr(Entry)
1914 << "\n";
1915 ;
1916 TotalSecsSize += Entry.Size;
1917 }
1918 uint64_t HeaderSize = SecHdrTable.front().Offset;
1919 assert(HeaderSize + TotalSecsSize == getFileSize() &&
1920 "Size of 'header + sections' doesn't match the total size of profile");
1921
1922 OS << "Header Size: " << HeaderSize << "\n";
1923 OS << "Total Sections Size: " << TotalSecsSize << "\n";
1924 OS << "File Size: " << getFileSize() << "\n";
1925 return true;
1926}
1927
1929 // Read and check the magic identifier.
1930 auto Magic = readNumber<uint64_t>();
1931 if (std::error_code EC = Magic.getError())
1932 return EC;
1933 else if (std::error_code EC = verifySPMagic(*Magic))
1934 return EC;
1935
1936 // Read the version number.
1938 if (std::error_code EC = Version.getError())
1939 return EC;
1943
1945}
1946
1948 Data = reinterpret_cast<const uint8_t *>(Buffer->getBufferStart());
1949 End = Data + Buffer->getBufferSize();
1950
1951 if (std::error_code EC = readMagicIdent())
1952 return EC;
1953
1954 if (std::error_code EC = readSummary())
1955 return EC;
1956
1957 if (std::error_code EC = readNameTable())
1958 return EC;
1960}
1961
1962std::error_code SampleProfileReaderBinary::readSummaryEntry(
1963 std::vector<ProfileSummaryEntry> &Entries) {
1964 auto Cutoff = readNumber<uint64_t>();
1965 if (std::error_code EC = Cutoff.getError())
1966 return EC;
1967
1968 auto MinBlockCount = readNumber<uint64_t>();
1969 if (std::error_code EC = MinBlockCount.getError())
1970 return EC;
1971
1972 auto NumBlocks = readNumber<uint64_t>();
1973 if (std::error_code EC = NumBlocks.getError())
1974 return EC;
1975
1976 Entries.emplace_back(*Cutoff, *MinBlockCount, *NumBlocks);
1978}
1979
1981 auto TotalCount = readNumber<uint64_t>();
1982 if (std::error_code EC = TotalCount.getError())
1983 return EC;
1984
1985 auto MaxBlockCount = readNumber<uint64_t>();
1986 if (std::error_code EC = MaxBlockCount.getError())
1987 return EC;
1988
1989 auto MaxFunctionCount = readNumber<uint64_t>();
1990 if (std::error_code EC = MaxFunctionCount.getError())
1991 return EC;
1992
1993 auto NumBlocks = readNumber<uint64_t>();
1994 if (std::error_code EC = NumBlocks.getError())
1995 return EC;
1996
1997 auto NumFunctions = readNumber<uint64_t>();
1998 if (std::error_code EC = NumFunctions.getError())
1999 return EC;
2000
2001 auto NumSummaryEntries = readNumber<uint64_t>();
2002 if (std::error_code EC = NumSummaryEntries.getError())
2003 return EC;
2004
2005 std::vector<ProfileSummaryEntry> Entries;
2006 for (unsigned i = 0; i < *NumSummaryEntries; i++) {
2007 std::error_code EC = readSummaryEntry(Entries);
2008 if (EC != sampleprof_error::success)
2009 return EC;
2010 }
2011 Summary = std::make_unique<ProfileSummary>(
2012 ProfileSummary::PSK_Sample, Entries, *TotalCount, *MaxBlockCount, 0,
2013 *MaxFunctionCount, *NumBlocks, *NumFunctions);
2014
2016}
2017
2018/// Return whether Buffer starts with ExpectedMagic without reading beyond it.
2019static bool hasBinaryFormat(const MemoryBuffer &Buffer,
2020 uint64_t ExpectedMagic) {
2021 const uint8_t *Data =
2022 reinterpret_cast<const uint8_t *>(Buffer.getBufferStart());
2023 const uint8_t *End = reinterpret_cast<const uint8_t *>(Buffer.getBufferEnd());
2025 uint64_t Magic = decodeULEB128(Data, nullptr, End, nullptr, &DecodeError);
2026 return DecodeError == ULEB128DecodeError::None && Magic == ExpectedMagic;
2027}
2028
2032
2036
2038 uint32_t dummy;
2039 if (!GcovBuffer.readInt(dummy))
2042}
2043
2045 if (sizeof(T) <= sizeof(uint32_t)) {
2046 uint32_t Val;
2047 if (GcovBuffer.readInt(Val) && Val <= std::numeric_limits<T>::max())
2048 return static_cast<T>(Val);
2049 } else if (sizeof(T) <= sizeof(uint64_t)) {
2050 uint64_t Val;
2051 if (GcovBuffer.readInt64(Val) && Val <= std::numeric_limits<T>::max())
2052 return static_cast<T>(Val);
2053 }
2054
2055 std::error_code EC = sampleprof_error::malformed;
2056 reportError(0, EC.message());
2057 return EC;
2058}
2059
2061 StringRef Str;
2062 if (!GcovBuffer.readString(Str))
2064 return Str;
2065}
2066
2068 // Read the magic identifier.
2069 if (!GcovBuffer.readGCDAFormat())
2071
2072 // Read the version number. Note - the GCC reader does not validate this
2073 // version, but the profile creator generates v704.
2074 GCOV::GCOVVersion version;
2075 if (!GcovBuffer.readGCOVVersion(version))
2077
2078 if (version != GCOV::V407)
2080
2081 // Skip the empty integer.
2082 if (std::error_code EC = skipNextWord())
2083 return EC;
2084
2086}
2087
2089 uint32_t Tag;
2090 if (!GcovBuffer.readInt(Tag))
2092
2093 if (Tag != Expected)
2095
2096 if (std::error_code EC = skipNextWord())
2097 return EC;
2098
2100}
2101
2103 if (std::error_code EC = readSectionTag(GCOVTagAFDOFileNames))
2104 return EC;
2105
2106 uint32_t Size;
2107 if (!GcovBuffer.readInt(Size))
2109
2110 for (uint32_t I = 0; I < Size; ++I) {
2111 StringRef Str;
2112 if (!GcovBuffer.readString(Str))
2114 Names.push_back(std::string(Str));
2115 }
2116
2118}
2119
2121 if (std::error_code EC = readSectionTag(GCOVTagAFDOFunction))
2122 return EC;
2123
2124 uint32_t NumFunctions;
2125 if (!GcovBuffer.readInt(NumFunctions))
2127
2128 InlineCallStack Stack;
2129 for (uint32_t I = 0; I < NumFunctions; ++I)
2130 if (std::error_code EC = readOneFunctionProfile(Stack, true, 0))
2131 return EC;
2132
2135}
2136
2138 const InlineCallStack &InlineStack, bool Update, uint32_t Offset) {
2139 uint64_t HeadCount = 0;
2140 if (InlineStack.size() == 0)
2141 if (!GcovBuffer.readInt64(HeadCount))
2143
2144 uint32_t NameIdx;
2145 if (!GcovBuffer.readInt(NameIdx))
2147
2148 StringRef Name(Names[NameIdx]);
2149
2150 uint32_t NumPosCounts;
2151 if (!GcovBuffer.readInt(NumPosCounts))
2153
2154 uint32_t NumCallsites;
2155 if (!GcovBuffer.readInt(NumCallsites))
2157
2158 FunctionSamples *FProfile = nullptr;
2159 if (InlineStack.size() == 0) {
2160 // If this is a top function that we have already processed, do not
2161 // update its profile again. This happens in the presence of
2162 // function aliases. Since these aliases share the same function
2163 // body, there will be identical replicated profiles for the
2164 // original function. In this case, we simply not bother updating
2165 // the profile of the original function.
2166 FProfile = &Profiles[FunctionId(Name)];
2167 FProfile->addHeadSamples(HeadCount);
2168 if (FProfile->getTotalSamples() > 0)
2169 Update = false;
2170 } else {
2171 // Otherwise, we are reading an inlined instance. The top of the
2172 // inline stack contains the profile of the caller. Insert this
2173 // callee in the caller's CallsiteMap.
2174 FunctionSamples *CallerProfile = InlineStack.front();
2175 uint32_t LineOffset = Offset >> 16;
2176 uint32_t Discriminator = Offset & 0xffff;
2177 FProfile = &CallerProfile->functionSamplesAt(
2178 LineLocation(LineOffset, Discriminator))[FunctionId(Name)];
2179 }
2180 FProfile->setFunction(FunctionId(Name));
2181 FProfile->reserveBodySamples(NumPosCounts);
2182
2183 for (uint32_t I = 0; I < NumPosCounts; ++I) {
2185 if (!GcovBuffer.readInt(Offset))
2187
2188 uint32_t NumTargets;
2189 if (!GcovBuffer.readInt(NumTargets))
2191
2192 uint64_t Count;
2193 if (!GcovBuffer.readInt64(Count))
2195
2196 // The line location is encoded in the offset as:
2197 // high 16 bits: line offset to the start of the function.
2198 // low 16 bits: discriminator.
2199 uint32_t LineOffset = Offset >> 16;
2200 uint32_t Discriminator = Offset & 0xffff;
2201
2202 InlineCallStack NewStack;
2203 NewStack.push_back(FProfile);
2204 llvm::append_range(NewStack, InlineStack);
2205 if (Update) {
2206 // Walk up the inline stack, adding the samples on this line to
2207 // the total sample count of the callers in the chain.
2208 for (auto *CallerProfile : NewStack)
2209 CallerProfile->addTotalSamples(Count);
2210
2211 // Update the body samples for the current profile.
2212 FProfile->addBodySamples(LineOffset, Discriminator, Count);
2213 }
2214
2215 // Process the list of functions called at an indirect call site.
2216 // These are all the targets that a function pointer (or virtual
2217 // function) resolved at runtime.
2218 for (uint32_t J = 0; J < NumTargets; J++) {
2219 uint32_t HistVal;
2220 if (!GcovBuffer.readInt(HistVal))
2222
2223 if (HistVal != HIST_TYPE_INDIR_CALL_TOPN)
2225
2226 uint64_t TargetIdx;
2227 if (!GcovBuffer.readInt64(TargetIdx))
2229 StringRef TargetName(Names[TargetIdx]);
2230
2231 uint64_t TargetCount;
2232 if (!GcovBuffer.readInt64(TargetCount))
2234
2235 if (Update)
2236 FProfile->addCalledTargetSamples(LineOffset, Discriminator,
2237 FunctionId(TargetName), TargetCount);
2238 }
2239 }
2240
2241 // Process all the inlined callers into the current function. These
2242 // are all the callsites that were inlined into this function.
2243 for (uint32_t I = 0; I < NumCallsites; I++) {
2244 // The offset is encoded as:
2245 // high 16 bits: line offset to the start of the function.
2246 // low 16 bits: discriminator.
2248 if (!GcovBuffer.readInt(Offset))
2250 InlineCallStack NewStack;
2251 NewStack.push_back(FProfile);
2252 llvm::append_range(NewStack, InlineStack);
2253 if (std::error_code EC = readOneFunctionProfile(NewStack, Update, Offset))
2254 return EC;
2255 }
2256
2258}
2259
2260/// Read a GCC AutoFDO profile.
2261///
2262/// This format is generated by the Linux Perf conversion tool at
2263/// https://github.com/google/autofdo.
2265 assert(!ProfileIsFSDisciminator && "Gcc profiles not support FSDisciminator");
2266 // Read the string table.
2267 if (std::error_code EC = readNameTable())
2268 return EC;
2269
2270 // Read the source profile.
2271 if (std::error_code EC = readFunctionProfiles())
2272 return EC;
2273
2275}
2276
2278 StringRef Contents = Buffer.getBuffer();
2279 // Preserve exact magic matching, including a magic-only eight-byte buffer.
2280 return Contents.starts_with("adcg*704") &&
2281 (Contents.size() == 8 || Contents[8] == '\0');
2282}
2283
2285 // If the reader uses MD5 to represent string, we can't remap it because
2286 // we don't know what the original function names were.
2287 if (Reader.useMD5()) {
2288 Ctx.diagnose(DiagnosticInfoSampleProfile(
2289 Reader.getBuffer()->getBufferIdentifier(),
2290 "Profile data remapping cannot be applied to profile data "
2291 "using MD5 names (original mangled names are not available).",
2292 DS_Warning));
2293 return;
2294 }
2295
2296 // CSSPGO-TODO: Remapper is not yet supported.
2297 // We will need to remap the entire context string.
2298 assert(Remappings && "should be initialized while creating remapper");
2299 for (auto &Sample : Reader.getProfiles()) {
2300 DenseSet<FunctionId> NamesInSample;
2301 Sample.second.findAllNames(NamesInSample);
2302 for (auto &Name : NamesInSample) {
2303 StringRef NameStr = Name.stringRef();
2304 if (auto Key = Remappings->insert(NameStr))
2305 NameMap.insert({Key, NameStr});
2306 }
2307 }
2308
2309 RemappingApplied = true;
2310}
2311
2312std::optional<StringRef>
2314 if (auto Key = Remappings->lookup(Fname)) {
2315 StringRef Result = NameMap.lookup(Key);
2316 if (!Result.empty())
2317 return Result;
2318 }
2319 return std::nullopt;
2320}
2321
2322/// Prepare a memory buffer for the contents of \p Filename.
2323///
2324/// \returns an error code indicating the status of the buffer.
2327 auto BufferOrErr = Filename.str() == "-" ? MemoryBuffer::getSTDIN()
2328 : FS.getBufferForFile(Filename);
2329 if (std::error_code EC = BufferOrErr.getError())
2330 return EC;
2331 auto Buffer = std::move(BufferOrErr.get());
2332
2333 return std::move(Buffer);
2334}
2335
2336/// Create a sample profile reader based on the format of the input file.
2337///
2338/// \param Filename The file to open.
2339///
2340/// \param C The LLVM context to use to emit diagnostics.
2341///
2342/// \param P The FSDiscriminatorPass.
2343///
2344/// \param RemapFilename The file used for profile remapping.
2345///
2346/// \returns an error code indicating the status of the created reader.
2347ErrorOr<std::unique_ptr<SampleProfileReader>>
2350 StringRef RemapFilename) {
2351 auto BufferOrError = setupMemoryBuffer(Filename, FS);
2352 if (std::error_code EC = BufferOrError.getError())
2353 return EC;
2354 return create(BufferOrError.get(), C, FS, P, RemapFilename);
2355}
2356
2357/// Create a sample profile remapper from the given input, to remap the
2358/// function names in the given profile data.
2359///
2360/// \param Filename The file to open.
2361///
2362/// \param Reader The profile reader the remapper is going to be applied to.
2363///
2364/// \param C The LLVM context to use to emit diagnostics.
2365///
2366/// \returns an error code indicating the status of the created reader.
2369 vfs::FileSystem &FS,
2370 SampleProfileReader &Reader,
2371 LLVMContext &C) {
2372 auto BufferOrError = setupMemoryBuffer(Filename, FS);
2373 if (std::error_code EC = BufferOrError.getError())
2374 return EC;
2375 return create(BufferOrError.get(), Reader, C);
2376}
2377
2378/// Create a sample profile remapper from the given input, to remap the
2379/// function names in the given profile data.
2380///
2381/// \param B The memory buffer to create the reader from (assumes ownership).
2382///
2383/// \param C The LLVM context to use to emit diagnostics.
2384///
2385/// \param Reader The profile reader the remapper is going to be applied to.
2386///
2387/// \returns an error code indicating the status of the created reader.
2389SampleProfileReaderItaniumRemapper::create(std::unique_ptr<MemoryBuffer> &B,
2390 SampleProfileReader &Reader,
2391 LLVMContext &C) {
2392 auto Remappings = std::make_unique<SymbolRemappingReader>();
2393 if (Error E = Remappings->read(*B)) {
2395 std::move(E), [&](const SymbolRemappingParseError &ParseError) {
2396 C.diagnose(DiagnosticInfoSampleProfile(B->getBufferIdentifier(),
2397 ParseError.getLineNum(),
2398 ParseError.getMessage()));
2399 });
2401 }
2402
2403 return std::make_unique<SampleProfileReaderItaniumRemapper>(
2404 std::move(B), std::move(Remappings), Reader);
2405}
2406
2407/// Create a sample profile reader based on the format of the input data.
2408///
2409/// \param B The memory buffer to create the reader from (assumes ownership).
2410///
2411/// \param C The LLVM context to use to emit diagnostics.
2412///
2413/// \param P The FSDiscriminatorPass.
2414///
2415/// \param RemapFilename The file used for profile remapping.
2416///
2417/// \returns an error code indicating the status of the created reader.
2419SampleProfileReader::create(std::unique_ptr<MemoryBuffer> &B, LLVMContext &C,
2421 StringRef RemapFilename) {
2422 std::unique_ptr<SampleProfileReader> Reader;
2424 Reader.reset(new SampleProfileReaderRawBinary(std::move(B), C));
2426 Reader.reset(new SampleProfileReaderExtBinary(std::move(B), C));
2428 Reader.reset(new SampleProfileReaderGCC(std::move(B), C));
2430 Reader.reset(new SampleProfileReaderText(std::move(B), C));
2431 else
2433
2434 if (!RemapFilename.empty()) {
2436 RemapFilename, FS, *Reader, C);
2437 if (std::error_code EC = ReaderOrErr.getError()) {
2438 std::string Msg = "Could not create remapper: " + EC.message();
2439 C.diagnose(DiagnosticInfoSampleProfile(RemapFilename, Msg));
2440 return EC;
2441 }
2442 Reader->Remapper = std::move(ReaderOrErr.get());
2443 }
2444
2445 if (std::error_code EC = Reader->readHeader()) {
2446 return EC;
2447 }
2448
2449 Reader->setDiscriminatorMaskedBitFrom(P);
2450
2451 return std::move(Reader);
2452}
2453
2454// For text and GCC file formats, we compute the summary after reading the
2455// profile. Binary format has the profile summary in its header.
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file defines the DenseMap class.
Provides ErrorOr<T> smart pointer.
Module.h This file contains the declarations for the Module class.
This file supports working with JSON data.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define T
static constexpr StringLiteral Filename
#define P(N)
const char * Msg
This file contains some templates that are useful if you are working with the STL at all.
static bool ParseHead(const StringRef &Input, StringRef &FName, uint64_t &NumSamples, uint64_t &NumHeadSamples)
Parse Input as function head.
static void dumpFunctionProfileJson(const FunctionSamples &S, json::OStream &JOS, bool TopLevel=false)
static bool isOffsetLegal(unsigned L)
Returns true if line offset L is legal (only has 16 bits).
static bool ParseLine(const StringRef &Input, LineType &LineTy, uint32_t &Depth, uint64_t &NumSamples, uint32_t &LineOffset, uint32_t &Discriminator, StringRef &CalleeName, DenseMap< StringRef, uint64_t > &TargetCountMap, DenseMap< StringRef, uint64_t > &TypeCountMap, uint64_t &FunctionHash, uint32_t &Attributes, bool &IsFlat)
Parse Input as line sample.
static cl::opt< bool > LazyLoadNameTable("sample-profile-lazy-load-name-table", cl::init(true), cl::Hidden, cl::desc("Lazy load the name table from the profile."))
static cl::opt< bool > ProfileIsFSDisciminator("profile-isfs", cl::Hidden, cl::init(false), cl::desc("Profile uses flow sensitive discriminators"))
static std::string getSecFlagsStr(const SecHdrTableEntry &Entry)
static std::error_code diagnoseReaderError(const SampleProfileReader &Reader, sampleprof_error ProfError)
Emit a reader diagnostic for ProfError and return its error code.
static bool hasBinaryFormat(const MemoryBuffer &Buffer, uint64_t ExpectedMagic)
Return whether Buffer starts with ExpectedMagic without reading beyond it.
static bool parseTypeCountMap(StringRef Input, DenseMap< StringRef, uint64_t > &TypeCountMap)
static bool parseMetadata(const StringRef &Input, uint64_t &FunctionHash, uint32_t &Attributes)
Parse Input that contains metadata.
static cl::opt< bool > AllowRereadLoadedProfile("sample-profile-allow-reread-loaded-profile", cl::init(false), cl::Hidden, cl::desc("Allow incremental reads with a remapper to re-read already " "loaded profiles and accumulate duplicate vtable counts."))
This file provides utility classes that use RAII to save and restore values.
This file defines the SmallSet class.
Defines the virtual file system interface vfs::FileSystem.
The Input class is used to parse a yaml document into in-memory structs and vectors.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
Implements a dense probed hash-table based set.
Definition DenseSet.h:283
Diagnostic information for the sample profiler.
Represents either an error or a value T.
Definition ErrorOr.h:56
std::error_code getError() const
Definition ErrorOr.h:152
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
Tagged union holding either a T or a Error.
Definition Error.h:485
Non-owning view of a buffer formatted as a complete binary search tree in Eytzinger (breadth-first) o...
Definition Eytzinger.h:30
static LLVM_ABI GUID getGUIDAssumingExternalLinkage(StringRef GlobalName)
Return a 64-bit global unique ID constructed from the name of a global symbol.
Definition Globals.cpp:80
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
This interface provides simple read-only access to a block of memory, and provides simple methods for...
const char * getBufferEnd() const
static ErrorOr< std::unique_ptr< MemoryBuffer > > getSTDIN()
Read all of stdin into a file buffer, and return it.
const char * getBufferStart() const
Root of the metadata hierarchy.
Definition Metadata.h:65
static LLVM_ABI const ArrayRef< uint32_t > DefaultCutoffs
A vector of useful cutoff values for detailed summary.
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition SmallSet.h:134
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
Definition SmallSet.h:184
void push_back(const T &Elt)
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
static constexpr size_t npos
Definition StringRef.h:58
bool getAsInteger(unsigned Radix, T &Result) const
Parse the current string as an integer of the specified radix.
Definition StringRef.h:482
constexpr StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
Definition StringRef.h:589
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition StringRef.h:258
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
constexpr size_t size() const
Get the string size.
Definition StringRef.h:144
size_t find_last_of(char C, size_t From=npos) const
Find the last character in the string that is C, or npos if not found.
Definition StringRef.h:413
size_t find_first_of(char C, size_t From=0) const
Find the first character in the string that is C, or npos if not found.
Definition StringRef.h:388
size_t find(char C, size_t From=0) const
Search for the first character C in the string.
Definition StringRef.h:290
LLVM_ABI size_t find_first_not_of(char C, size_t From=0) const
Find the first character in the string that is not C or npos if not found.
Target - Wrapper for Target specific information.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:210
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
Definition DenseSet.h:188
json::OStream allows writing well-formed JSON without materializing all structures as json::Value ahe...
Definition JSON.h:983
void object(Block Contents)
Emit an object whose elements are emitted in the provided Block.
Definition JSON.h:1013
void attribute(llvm::StringRef Key, const Value &Contents)
Emit an attribute whose value is self-contained (number, vector<int> etc).
Definition JSON.h:1038
LLVM_ABI void arrayBegin()
Definition JSON.cpp:845
void attributeArray(llvm::StringRef Key, Block Contents)
Emit an attribute whose value is an array with elements from the Block.
Definition JSON.h:1042
LLVM_ABI void arrayEnd()
Definition JSON.cpp:853
A forward iterator which reads text lines from a buffer.
int64_t line_number() const
Return the current line number. May return any number at EOF.
bool is_at_eof() const
Return true if we've reached EOF or are an "end" iterator.
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
This class represents a function that is read from a sample profile.
Definition FunctionId.h:36
StringRef stringRef() const
Convert to StringRef.
Definition FunctionId.h:108
uint64_t getHashCode() const
Get hash code of this object.
Definition FunctionId.h:123
std::string str() const
Convert to a string, usually for output purpose.
Definition FunctionId.h:97
Representation of the samples collected for a function.
Definition SampleProf.h:854
static LLVM_ABI std::atomic< bool > ProfileIsFS
If this profile uses flow sensitive discriminators.
static LLVM_ABI std::atomic< bool > ProfileIsPreInlined
sampleprof_error addTotalSamples(uint64_t Num, uint64_t Weight=1)
Definition SampleProf.h:861
uint64_t getHeadSamples() const
For top-level functions, return the total number of branch samples that have the function as the bran...
void setFunction(FunctionId NewFunctionID)
Set the name of the function.
const CallsiteSampleMap & getCallsiteSamples() const LLVM_LIFETIME_BOUND
Return all the callsite samples collected in the body of the function.
FunctionId getFunction() const
Return the function name.
SampleContext & getContext() const LLVM_LIFETIME_BOUND
FunctionSamplesMap & functionSamplesAt(const LineLocation &Loc) LLVM_LIFETIME_BOUND
Return the function samples at the given callsite location.
sampleprof_error addHeadSamples(uint64_t Num, uint64_t Weight=1)
Definition SampleProf.h:880
void reserveBodySamples(size_t NumEntries)
Definition SampleProf.h:908
TypeCountMap & getTypeSamplesAt(const LineLocation &Loc) LLVM_LIFETIME_BOUND
Returns the vtable access samples for the C++ types for Loc.
sampleprof_error addCalledTargetSamples(uint32_t LineOffset, uint32_t Discriminator, FunctionId Func, uint64_t Num, uint64_t Weight=1)
Definition SampleProf.h:894
static StringRef getCanonicalFnName(const Function &F)
Return the canonical name for a function, taking into account suffix elision policy attributes.
sampleprof_error addBodySamples(uint32_t LineOffset, uint32_t Discriminator, uint64_t Num, uint64_t Weight=1)
Definition SampleProf.h:888
static LLVM_ABI std::atomic< bool > HasUniqSuffix
Whether the profile contains any ".__uniq." suffix in a name.
void setFunctionHash(uint64_t Hash)
static LLVM_ABI std::atomic< bool > ProfileIsProbeBased
const BodySampleMap & getBodySamples() const LLVM_LIFETIME_BOUND
Return all the samples collected in the body of the function.
uint64_t getTotalSamples() const
Return the total number of samples collected inside the function.
void setContext(const SampleContext &FContext)
static LLVM_ABI std::atomic< bool > ProfileIsCS
void reserveCallsiteTypeCounts(size_t NumEntries)
Definition SampleProf.h:912
void setAllAttributes(uint32_t A)
Definition SampleProf.h:720
FunctionId getFunction() const
Definition SampleProf.h:726
std::string toString() const
Definition SampleProf.h:742
bool isPrefixOf(const SampleContext &That) const
Definition SampleProf.h:805
This class provides operator overloads to the map container using MD5 as the key type,...
iterator find(const SampleContext &Ctx)
std::error_code readNameTable()
Read the whole name table.
const uint8_t * Data
Points to the current location in the buffer.
std::error_code readCompositeProfile(FunctionSamples &FProfile, bool IsNested)
std::error_code readLBRProfile(FunctionSamples &FProfile, bool IsNested)
Read specific profile types.
ErrorOr< StringRef > readString()
Read a string from the profile.
std::unique_ptr< SampleProfileNameTable > NameTable
Function name table.
ErrorOr< T > readNumber()
Read a numeric value of type T from the profile.
ErrorOr< SampleContextFrames > readContextFromTable(size_t *RetIdx=nullptr)
Read a context indirectly via the CSNameTable.
ErrorOr< std::pair< SampleContext, uint64_t > > readSampleContextFromTable()
Read a context indirectly via the CSNameTable if the profile has context, otherwise same as readStrin...
std::error_code readHeader() override
Read and validate the file header.
const uint64_t * MD5SampleContextStart
The starting address of the table of MD5 values of sample contexts.
std::vector< SampleContextFrameVector > CSNameTable
CSNameTable is used to save full context vectors.
std::error_code readImpl() override
Read sample profiles from the associated file.
ErrorOr< FunctionId > readStringFromTable(size_t *RetIdx=nullptr)
Read a string indirectly via the name table. Optionally return the index.
std::vector< uint64_t > MD5SampleContextTable
Table to cache MD5 values of sample contexts corresponding to readSampleContextFromTable(),...
std::error_code readCallsiteVTableProf(FunctionSamples &FProfile)
Read all virtual functions' vtable access counts for FProfile.
ErrorOr< size_t > readStringIndex(T &Table)
Read the string index and check whether it overflows the table.
const uint8_t * End
Points to the end of the buffer.
std::error_code readProfile(FunctionSamples &FProfile, bool IsNested)
Read the contents of the given profile instance.
ErrorOr< T > readUnencodedNumber()
Read a numeric value of type T from the profile.
std::error_code readFuncProfile(const uint8_t *Start)
Read the next function profile instance.
std::error_code readVTableTypeCountMap(TypeCountMap &M)
Read bytes from the input buffer pointed by Data and decode them into M.
std::error_code readSummary()
Read profile summary.
std::error_code readMagicIdent()
Read the contents of Magic number and Version number.
std::error_code readNameTableSecEytzinger(bool IsMD5, bool FixedLengthMD5)
bool collectFuncsFromModule() override
Collect functions with definitions in Module M.
uint64_t getSectionSize(SecType Type)
Get the total size of all Type sections.
std::error_code readEytzingerFuncOffsetTable(bool IsNested)
virtual std::error_code readCustomSection(const SecHdrTableEntry &Entry)=0
std::vector< std::pair< SampleContext, uint64_t > > FuncOffsetList
The list version of FuncOffsetTable.
DenseSet< StringRef > FuncsToUse
The set containing the functions to use when compiling a module.
std::unique_ptr< ProfileSymbolList > ProfSymList
std::optional< SampleProfileFuncOffsetTable > FuncOffsetTable
The table mapping from a function context's MD5 to the offset of its FunctionSample towards file star...
std::error_code readNameTableSec(bool IsMD5, bool FixedLengthMD5, bool IsEytzinger=false)
bool useFuncOffsetList() const
Determine which container readFuncOffsetTable() should populate, the list FuncOffsetList or the map F...
std::error_code readImpl() override
Read sample profiles in extensible format from the associated file.
virtual std::error_code readOneSection(const uint8_t *Start, uint64_t Size, const SecHdrTableEntry &Entry)
bool dumpSectionInfo(raw_ostream &OS=dbgs()) override
std::error_code readFuncOffsetTable(bool IsEytzinger, bool IsNested)
std::error_code readNameTableSecLegacy(bool IsMD5, bool FixedLengthMD5)
std::error_code readHeader() override
Read and validate the file header.
uint64_t getFileSize()
Get the total size of header and all sections.
static bool hasFormat(const MemoryBuffer &Buffer)
Return true if Buffer is in the format supported by this class.
GCOVBuffer GcovBuffer
GCOV buffer containing the profile.
std::vector< std::string > Names
Function names in this profile.
std::error_code readImpl() override
Read sample profiles from the associated file.
std::error_code readHeader() override
Read and validate the file header.
std::error_code readOneFunctionProfile(const InlineCallStack &InlineStack, bool Update, uint32_t Offset)
static const uint32_t GCOVTagAFDOFileNames
GCOV tags used to separate sections in the profile file.
static bool hasFormat(const MemoryBuffer &Buffer)
Return true if Buffer is in the format supported by this class.
std::error_code readSectionTag(uint32_t Expected)
Read the section tag and check that it's the same as Expected.
static LLVM_ABI ErrorOr< std::unique_ptr< SampleProfileReaderItaniumRemapper > > create(StringRef Filename, vfs::FileSystem &FS, SampleProfileReader &Reader, LLVMContext &C)
Create a remapper from the given remapping file.
LLVM_ABI void applyRemapping(LLVMContext &Ctx)
Apply remappings to the profile read by Reader.
LLVM_ABI std::optional< StringRef > lookUpNameInProfile(StringRef FunctionName)
Return the equivalent name in the profile for FunctionName if it exists.
static bool hasFormat(const MemoryBuffer &Buffer)
Return true if Buffer is in the format supported by this class.
std::error_code readImpl() override
Read sample profiles from the associated file.
static bool hasFormat(const MemoryBuffer &Buffer)
Return true if Buffer is in the format supported by this class.
bool ReadVTableProf
If true, the profile has vtable profiles and reader should decode them to parse profiles correctly.
bool ProfileIsPreInlined
Whether function profile contains ShouldBeInlined contexts.
DenseMap< uint64_t, std::pair< const uint8_t *, const uint8_t * > > FuncMetadataIndex
uint32_t CSProfileCount
Number of context-sensitive profiles.
static LLVM_ABI ErrorOr< std::unique_ptr< SampleProfileReader > > create(StringRef Filename, LLVMContext &C, vfs::FileSystem &FS, FSDiscriminatorPass P=FSDiscriminatorPass::Base, StringRef RemapFilename="")
Create a sample profile reader appropriate to the file format.
LLVM_ABI void dump(raw_ostream &OS=dbgs())
Print all the profiles on stream OS.
bool useMD5() const
Return whether names in the profile are all MD5 numbers.
const Module * M
The current module being compiled if SampleProfileReader is used by compiler.
std::unique_ptr< MemoryBuffer > Buffer
Memory buffer holding the profile file.
std::unique_ptr< SampleProfileReaderItaniumRemapper > Remapper
bool ProfileHasAttribute
Whether the profile has attribute metadata.
bool SkipFlatProf
If SkipFlatProf is true, skip functions marked with !Flat in text mode or sections with SecFlagFlat f...
std::error_code read()
The interface to read sample profiles from the associated file.
ProfileSectionRange ProfileSecRange
Profile section most recently selected for on-demand loading.
bool ProfileIsCS
Whether function profiles are context-sensitive flat profiles.
bool ProfileIsMD5
Whether the profile uses MD5 for Sample Contexts and function names.
std::unique_ptr< ProfileSummary > Summary
Profile summary information.
LLVM_ABI void computeSummary()
Compute summary for this profile.
uint32_t getDiscriminatorMask() const
Get the bitmask the discriminators: For FS profiles, return the bit mask for this pass.
bool HasUnknownProfileTypes
Whether reading skipped at least one unknown composite profile block.
bool ProfileIsFS
Whether the function profiles use FS discriminators.
LLVM_ABI void dumpJson(raw_ostream &OS=dbgs())
Print all the profiles on stream OS in the JSON format.
SampleProfileMap Profiles
Map every function to its associated profile.
uint64_t FormatVersion
Format version of the profile.
LLVM_ABI void dumpFunctionProfile(const FunctionSamples &FS, raw_ostream &OS=dbgs())
Print the profile for FunctionSamples on stream OS.
bool ProfileIsProbeBased
Whether samples are collected based on pseudo probes.
void reportError(int64_t LineNumber, const Twine &Msg) const
Report a parse error message.
raw_ostream * ProfileTypeInfoOS
Optional stream for composite block structure; null disables the output.
LLVMContext & Ctx
LLVM context used to emit diagnostics.
Representation of a single sample record.
Definition SampleProf.h:423
The virtual file system interface.
GCOVVersion
Definition GCOV.h:43
@ V407
Definition GCOV.h:43
initializer< Ty > init(const Ty &Val)
LLVM_ABI Error decompress(ArrayRef< uint8_t > Input, uint8_t *Output, size_t &UncompressedSize)
LLVM_ABI bool isAvailable()
LLVM_ABI void sortFuncProfiles(const SampleProfileMap &ProfileMap, std::vector< NameFunctionSamples > &SortedProfiles)
static uint64_t SPMagic(SampleProfileFormat Format=SPF_Binary)
Definition SampleProf.h:114
static bool formatVersionIsSupported(uint64_t Version)
Definition SampleProf.h:136
std::map< LineLocation, FunctionSamplesMap > CallsiteSampleMap
Definition SampleProf.h:845
static bool hasSecFlag(const SecHdrTableEntry &Entry, SecFlagType Flag)
Definition SampleProf.h:336
SortedVectorMap< LineLocation, SampleRecord, 0 > BodySampleMap
Definition SampleProf.h:841
uint64_t MD5Hash(const FunctionId &Obj)
Definition FunctionId.h:167
constexpr EytzingerModeT EytzingerMode
@ SecFlagIsPreInlined
SecFlagIsPreInlined means this profile contains ShouldBeInlined contexts thus this is CS preinliner c...
Definition SampleProf.h:264
@ SecFlagHasVTableTypeProf
SecFlagHasVTableTypeProf means this profile contains vtable type profiles.
Definition SampleProf.h:267
@ SecFlagPartial
SecFlagPartial means the profile is for common/shared code.
Definition SampleProf.h:255
@ SecFlagFSDiscriminator
SecFlagFSDiscriminator means this profile uses flow-sensitive discriminators.
Definition SampleProf.h:261
@ SecFlagFullContext
SecFlagContext means this is context-sensitive flat profile for CSSPGO.
Definition SampleProf.h:258
static StringRef getProfTypeName(uint64_t Type)
Definition SampleProf.h:197
SmallVector< SampleContextFrame, 1 > SampleContextFrameVector
Definition SampleProf.h:614
static std::string getSecName(SecType Type)
Definition SampleProf.h:165
constexpr InMemoryModeT InMemoryMode
static constexpr uint64_t CompositeProfileVersion
Definition SampleProf.h:130
constexpr char kVTableProfPrefix[]
Definition SampleProf.h:97
SmallVector< FunctionSamples *, 10 > InlineCallStack
SortedVectorMap< FunctionId, uint64_t, 0 > TypeCountMap
Key represents type of a C++ polymorphic class type by its vtable and value represents its counter.
Definition SampleProf.h:403
uint64_t read64le(const void *P)
Definition Endian.h:415
void write64le(void *P, uint64_t V)
Definition Endian.h:458
value_type read(const void *memory, endianness endian)
Read a value of a particular endianness from memory.
Definition Endian.h:53
value_type readNext(const CharT *&memory, endianness endian)
Read a value of a particular endianness from a buffer, and increment the buffer past that value.
Definition Endian.h:67
detail::packed_endian_specific_integral< uint64_t, llvm::endianness::little, unaligned > ulittle64_t
Definition Endian.h:273
detail::packed_endian_specific_integral< uint32_t, llvm::endianness::little, unaligned > ulittle32_t
Definition Endian.h:270
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
static Expected< std::unique_ptr< MemoryBuffer > > setupMemoryBuffer(const Twine &Filename, vfs::FileSystem &FS)
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2575
void handleAllErrors(Error E, HandlerTs &&... Handlers)
Behaves the same as handleErrors, except that by contract all errors must be handled by the given han...
Definition Error.h:1013
ULEB128DecodeError
Identifies why ULEB128 decoding failed.
Definition LEB128.h:127
@ UnexpectedEnd
The encoding requires bytes beyond the supplied buffer.
Definition LEB128.h:131
@ None
No decoding error has been reported.
Definition LEB128.h:129
@ TooBig
The encoded value does not fit in uint64_t.
Definition LEB128.h:133
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2229
sampleprof_error mergeSampleProfErrors(sampleprof_error &Accumulator, sampleprof_error Result)
Definition SampleProf.h:75
sampleprof_error
Definition SampleProf.h:52
bool isDigit(char C)
Checks if character C is one of the 10 decimal digits.
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
auto count(R &&Range, const E &Element)
Wrapper function around std::count to count the number of times an element Element occurs in the give...
Definition STLExtras.h:2028
ArrayRef(const T &OneElt) -> ArrayRef< T >
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
std::enable_if_t< std::is_unsigned_v< T >, T > SaturatingAdd(T X, T Y, bool *ResultOverflowed=nullptr)
Add two unsigned integers, X and Y, of type T.
Definition MathExtras.h:609
uint64_t decodeULEB128(const uint8_t *p, unsigned *n, const uint8_t *end, const char **error, ULEB128DecodeError *errorCode)
Utility function to decode a ULEB128 value and report a typed error.
Definition LEB128.h:145
A utility class that uses RAII to save and restore the value of a variable.
Represents the relative location of an instruction.
Definition SampleProf.h:352
const uint8_t * Start
First byte of the retained section.
const uint8_t * End
One-past-the-end byte of the retained section.