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 
22 #include "llvm/ProfileData/SampleProfReader.h"
23 #include "llvm/ADT/DenseMap.h"
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/ADT/StringRef.h"
26 #include "llvm/IR/ProfileSummary.h"
27 #include "llvm/ProfileData/ProfileCommon.h"
28 #include "llvm/ProfileData/SampleProf.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/Compression.h"
31 #include "llvm/Support/ErrorOr.h"
32 #include "llvm/Support/LEB128.h"
33 #include "llvm/Support/LineIterator.h"
34 #include "llvm/Support/MD5.h"
35 #include "llvm/Support/MemoryBuffer.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include <algorithm>
38 #include <cstddef>
39 #include <cstdint>
40 #include <limits>
41 #include <memory>
42 #include <set>
43 #include <system_error>
44 #include <vector>
45 
46 using namespace llvm;
47 using namespace sampleprof;
48 
49 #define DEBUG_TYPE "samplepgo-reader"
50 
51 // This internal option specifies if the profile uses FS discriminators.
52 // It only applies to text, binary and compact binary format profiles.
53 // For ext-binary format profiles, the flag is set in the summary.
54 static cl::opt<bool> ProfileIsFSDisciminator(
55     "profile-isfs", cl::Hidden, cl::init(false),
56     cl::desc("Profile uses flow sensitive discriminators"));
57 
58 /// Dump the function profile for \p FName.
59 ///
60 /// \param FName Name of the function to print.
61 /// \param OS Stream to emit the output to.
62 void SampleProfileReader::dumpFunctionProfile(SampleContext FContext,
63                                               raw_ostream &OS) {
64   OS << "Function: " << FContext.toString() << ": " << Profiles[FContext];
65 }
66 
67 /// Dump all the function profiles found on stream \p OS.
68 void SampleProfileReader::dump(raw_ostream &OS) {
69   std::vector<NameFunctionSamples> V;
70   sortFuncProfiles(Profiles, V);
71   for (const auto &I : V)
72     dumpFunctionProfile(I.first, OS);
73 }
74 
75 /// Parse \p Input as function head.
76 ///
77 /// Parse one line of \p Input, and update function name in \p FName,
78 /// function's total sample count in \p NumSamples, function's entry
79 /// count in \p NumHeadSamples.
80 ///
81 /// \returns true if parsing is successful.
82 static bool ParseHead(const StringRef &Input, StringRef &FName,
83                       uint64_t &NumSamples, uint64_t &NumHeadSamples) {
84   if (Input[0] == ' ')
85     return false;
86   size_t n2 = Input.rfind(':');
87   size_t n1 = Input.rfind(':', n2 - 1);
88   FName = Input.substr(0, n1);
89   if (Input.substr(n1 + 1, n2 - n1 - 1).getAsInteger(10, NumSamples))
90     return false;
91   if (Input.substr(n2 + 1).getAsInteger(10, NumHeadSamples))
92     return false;
93   return true;
94 }
95 
96 /// Returns true if line offset \p L is legal (only has 16 bits).
97 static bool isOffsetLegal(unsigned L) { return (L & 0xffff) == L; }
98 
99 /// Parse \p Input that contains metadata.
100 /// Possible metadata:
101 /// - CFG Checksum information:
102 ///     !CFGChecksum: 12345
103 /// - CFG Checksum information:
104 ///     !Attributes: 1
105 /// Stores the FunctionHash (a.k.a. CFG Checksum) into \p FunctionHash.
106 static bool parseMetadata(const StringRef &Input, uint64_t &FunctionHash,
107                           uint32_t &Attributes) {
108   if (Input.startswith("!CFGChecksum:")) {
109     StringRef CFGInfo = Input.substr(strlen("!CFGChecksum:")).trim();
110     return !CFGInfo.getAsInteger(10, FunctionHash);
111   }
112 
113   if (Input.startswith("!Attributes:")) {
114     StringRef Attrib = Input.substr(strlen("!Attributes:")).trim();
115     return !Attrib.getAsInteger(10, Attributes);
116   }
117 
118   return false;
119 }
120 
121 enum class LineType {
122   CallSiteProfile,
123   BodyProfile,
124   Metadata,
125 };
126 
127 /// Parse \p Input as line sample.
128 ///
129 /// \param Input input line.
130 /// \param LineTy Type of this line.
131 /// \param Depth the depth of the inline stack.
132 /// \param NumSamples total samples of the line/inlined callsite.
133 /// \param LineOffset line offset to the start of the function.
134 /// \param Discriminator discriminator of the line.
135 /// \param TargetCountMap map from indirect call target to count.
136 /// \param FunctionHash the function's CFG hash, used by pseudo probe.
137 ///
138 /// returns true if parsing is successful.
139 static bool ParseLine(const StringRef &Input, LineType &LineTy, uint32_t &Depth,
140                       uint64_t &NumSamples, uint32_t &LineOffset,
141                       uint32_t &Discriminator, StringRef &CalleeName,
142                       DenseMap<StringRef, uint64_t> &TargetCountMap,
143                       uint64_t &FunctionHash, uint32_t &Attributes) {
144   for (Depth = 0; Input[Depth] == ' '; Depth++)
145     ;
146   if (Depth == 0)
147     return false;
148 
149   if (Depth == 1 && Input[Depth] == '!') {
150     LineTy = LineType::Metadata;
151     return parseMetadata(Input.substr(Depth), FunctionHash, Attributes);
152   }
153 
154   size_t n1 = Input.find(':');
155   StringRef Loc = Input.substr(Depth, n1 - Depth);
156   size_t n2 = Loc.find('.');
157   if (n2 == StringRef::npos) {
158     if (Loc.getAsInteger(10, LineOffset) || !isOffsetLegal(LineOffset))
159       return false;
160     Discriminator = 0;
161   } else {
162     if (Loc.substr(0, n2).getAsInteger(10, LineOffset))
163       return false;
164     if (Loc.substr(n2 + 1).getAsInteger(10, Discriminator))
165       return false;
166   }
167 
168   StringRef Rest = Input.substr(n1 + 2);
169   if (isDigit(Rest[0])) {
170     LineTy = LineType::BodyProfile;
171     size_t n3 = Rest.find(' ');
172     if (n3 == StringRef::npos) {
173       if (Rest.getAsInteger(10, NumSamples))
174         return false;
175     } else {
176       if (Rest.substr(0, n3).getAsInteger(10, NumSamples))
177         return false;
178     }
179     // Find call targets and their sample counts.
180     // Note: In some cases, there are symbols in the profile which are not
181     // mangled. To accommodate such cases, use colon + integer pairs as the
182     // anchor points.
183     // An example:
184     // _M_construct<char *>:1000 string_view<std::allocator<char> >:437
185     // ":1000" and ":437" are used as anchor points so the string above will
186     // be interpreted as
187     // target: _M_construct<char *>
188     // count: 1000
189     // target: string_view<std::allocator<char> >
190     // count: 437
191     while (n3 != StringRef::npos) {
192       n3 += Rest.substr(n3).find_first_not_of(' ');
193       Rest = Rest.substr(n3);
194       n3 = Rest.find_first_of(':');
195       if (n3 == StringRef::npos || n3 == 0)
196         return false;
197 
198       StringRef Target;
199       uint64_t count, n4;
200       while (true) {
201         // Get the segment after the current colon.
202         StringRef AfterColon = Rest.substr(n3 + 1);
203         // Get the target symbol before the current colon.
204         Target = Rest.substr(0, n3);
205         // Check if the word after the current colon is an integer.
206         n4 = AfterColon.find_first_of(' ');
207         n4 = (n4 != StringRef::npos) ? n3 + n4 + 1 : Rest.size();
208         StringRef WordAfterColon = Rest.substr(n3 + 1, n4 - n3 - 1);
209         if (!WordAfterColon.getAsInteger(10, count))
210           break;
211 
212         // Try to find the next colon.
213         uint64_t n5 = AfterColon.find_first_of(':');
214         if (n5 == StringRef::npos)
215           return false;
216         n3 += n5 + 1;
217       }
218 
219       // An anchor point is found. Save the {target, count} pair
220       TargetCountMap[Target] = count;
221       if (n4 == Rest.size())
222         break;
223       // Change n3 to the next blank space after colon + integer pair.
224       n3 = n4;
225     }
226   } else {
227     LineTy = LineType::CallSiteProfile;
228     size_t n3 = Rest.find_last_of(':');
229     CalleeName = Rest.substr(0, n3);
230     if (Rest.substr(n3 + 1).getAsInteger(10, NumSamples))
231       return false;
232   }
233   return true;
234 }
235 
236 /// Load samples from a text file.
237 ///
238 /// See the documentation at the top of the file for an explanation of
239 /// the expected format.
240 ///
241 /// \returns true if the file was loaded successfully, false otherwise.
242 std::error_code SampleProfileReaderText::readImpl() {
243   line_iterator LineIt(*Buffer, /*SkipBlanks=*/true, '#');
244   sampleprof_error Result = sampleprof_error::success;
245 
246   InlineCallStack InlineStack;
247   uint32_t ProbeProfileCount = 0;
248 
249   // SeenMetadata tracks whether we have processed metadata for the current
250   // top-level function profile.
251   bool SeenMetadata = false;
252 
253   ProfileIsFS = ProfileIsFSDisciminator;
254   FunctionSamples::ProfileIsFS = ProfileIsFS;
255   for (; !LineIt.is_at_eof(); ++LineIt) {
256     if ((*LineIt)[(*LineIt).find_first_not_of(' ')] == '#')
257       continue;
258     // Read the header of each function.
259     //
260     // Note that for function identifiers we are actually expecting
261     // mangled names, but we may not always get them. This happens when
262     // the compiler decides not to emit the function (e.g., it was inlined
263     // and removed). In this case, the binary will not have the linkage
264     // name for the function, so the profiler will emit the function's
265     // unmangled name, which may contain characters like ':' and '>' in its
266     // name (member functions, templates, etc).
267     //
268     // The only requirement we place on the identifier, then, is that it
269     // should not begin with a number.
270     if ((*LineIt)[0] != ' ') {
271       uint64_t NumSamples, NumHeadSamples;
272       StringRef FName;
273       if (!ParseHead(*LineIt, FName, NumSamples, NumHeadSamples)) {
274         reportError(LineIt.line_number(),
275                     "Expected 'mangled_name:NUM:NUM', found " + *LineIt);
276         return sampleprof_error::malformed;
277       }
278       SeenMetadata = false;
279       SampleContext FContext(FName, CSNameTable);
280       if (FContext.hasContext())
281         ++CSProfileCount;
282       Profiles[FContext] = FunctionSamples();
283       FunctionSamples &FProfile = Profiles[FContext];
284       FProfile.setContext(FContext);
285       MergeResult(Result, FProfile.addTotalSamples(NumSamples));
286       MergeResult(Result, FProfile.addHeadSamples(NumHeadSamples));
287       InlineStack.clear();
288       InlineStack.push_back(&FProfile);
289     } else {
290       uint64_t NumSamples;
291       StringRef FName;
292       DenseMap<StringRef, uint64_t> TargetCountMap;
293       uint32_t Depth, LineOffset, Discriminator;
294       LineType LineTy;
295       uint64_t FunctionHash = 0;
296       uint32_t Attributes = 0;
297       if (!ParseLine(*LineIt, LineTy, Depth, NumSamples, LineOffset,
298                      Discriminator, FName, TargetCountMap, FunctionHash,
299                      Attributes)) {
300         reportError(LineIt.line_number(),
301                     "Expected 'NUM[.NUM]: NUM[ mangled_name:NUM]*', found " +
302                         *LineIt);
303         return sampleprof_error::malformed;
304       }
305       if (SeenMetadata && LineTy != LineType::Metadata) {
306         // Metadata must be put at the end of a function profile.
307         reportError(LineIt.line_number(),
308                     "Found non-metadata after metadata: " + *LineIt);
309         return sampleprof_error::malformed;
310       }
311 
312       // Here we handle FS discriminators.
313       Discriminator &= getDiscriminatorMask();
314 
315       while (InlineStack.size() > Depth) {
316         InlineStack.pop_back();
317       }
318       switch (LineTy) {
319       case LineType::CallSiteProfile: {
320         FunctionSamples &FSamples = InlineStack.back()->functionSamplesAt(
321             LineLocation(LineOffset, Discriminator))[std::string(FName)];
322         FSamples.setName(FName);
323         MergeResult(Result, FSamples.addTotalSamples(NumSamples));
324         InlineStack.push_back(&FSamples);
325         break;
326       }
327       case LineType::BodyProfile: {
328         while (InlineStack.size() > Depth) {
329           InlineStack.pop_back();
330         }
331         FunctionSamples &FProfile = *InlineStack.back();
332         for (const auto &name_count : TargetCountMap) {
333           MergeResult(Result, FProfile.addCalledTargetSamples(
334                                   LineOffset, Discriminator, name_count.first,
335                                   name_count.second));
336         }
337         MergeResult(Result, FProfile.addBodySamples(LineOffset, Discriminator,
338                                                     NumSamples));
339         break;
340       }
341       case LineType::Metadata: {
342         FunctionSamples &FProfile = *InlineStack.back();
343         if (FunctionHash) {
344           FProfile.setFunctionHash(FunctionHash);
345           ++ProbeProfileCount;
346         }
347         if (Attributes)
348           FProfile.getContext().setAllAttributes(Attributes);
349         SeenMetadata = true;
350         break;
351       }
352       }
353     }
354   }
355 
356   assert((CSProfileCount == 0 || CSProfileCount == Profiles.size()) &&
357          "Cannot have both context-sensitive and regular profile");
358   ProfileIsCS = (CSProfileCount > 0);
359   assert((ProbeProfileCount == 0 || ProbeProfileCount == Profiles.size()) &&
360          "Cannot have both probe-based profiles and regular profiles");
361   ProfileIsProbeBased = (ProbeProfileCount > 0);
362   FunctionSamples::ProfileIsProbeBased = ProfileIsProbeBased;
363   FunctionSamples::ProfileIsCS = ProfileIsCS;
364 
365   if (Result == sampleprof_error::success)
366     computeSummary();
367 
368   return Result;
369 }
370 
371 bool SampleProfileReaderText::hasFormat(const MemoryBuffer &Buffer) {
372   bool result = false;
373 
374   // Check that the first non-comment line is a valid function header.
375   line_iterator LineIt(Buffer, /*SkipBlanks=*/true, '#');
376   if (!LineIt.is_at_eof()) {
377     if ((*LineIt)[0] != ' ') {
378       uint64_t NumSamples, NumHeadSamples;
379       StringRef FName;
380       result = ParseHead(*LineIt, FName, NumSamples, NumHeadSamples);
381     }
382   }
383 
384   return result;
385 }
386 
387 template <typename T> ErrorOr<T> SampleProfileReaderBinary::readNumber() {
388   unsigned NumBytesRead = 0;
389   std::error_code EC;
390   uint64_t Val = decodeULEB128(Data, &NumBytesRead);
391 
392   if (Val > std::numeric_limits<T>::max())
393     EC = sampleprof_error::malformed;
394   else if (Data + NumBytesRead > End)
395     EC = sampleprof_error::truncated;
396   else
397     EC = sampleprof_error::success;
398 
399   if (EC) {
400     reportError(0, EC.message());
401     return EC;
402   }
403 
404   Data += NumBytesRead;
405   return static_cast<T>(Val);
406 }
407 
408 ErrorOr<StringRef> SampleProfileReaderBinary::readString() {
409   std::error_code EC;
410   StringRef Str(reinterpret_cast<const char *>(Data));
411   if (Data + Str.size() + 1 > End) {
412     EC = sampleprof_error::truncated;
413     reportError(0, EC.message());
414     return EC;
415   }
416 
417   Data += Str.size() + 1;
418   return Str;
419 }
420 
421 template <typename T>
422 ErrorOr<T> SampleProfileReaderBinary::readUnencodedNumber() {
423   std::error_code EC;
424 
425   if (Data + sizeof(T) > End) {
426     EC = sampleprof_error::truncated;
427     reportError(0, EC.message());
428     return EC;
429   }
430 
431   using namespace support;
432   T Val = endian::readNext<T, little, unaligned>(Data);
433   return Val;
434 }
435 
436 template <typename T>
437 inline ErrorOr<uint32_t> SampleProfileReaderBinary::readStringIndex(T &Table) {
438   std::error_code EC;
439   auto Idx = readNumber<uint32_t>();
440   if (std::error_code EC = Idx.getError())
441     return EC;
442   if (*Idx >= Table.size())
443     return sampleprof_error::truncated_name_table;
444   return *Idx;
445 }
446 
447 ErrorOr<StringRef> SampleProfileReaderBinary::readStringFromTable() {
448   auto Idx = readStringIndex(NameTable);
449   if (std::error_code EC = Idx.getError())
450     return EC;
451 
452   return NameTable[*Idx];
453 }
454 
455 ErrorOr<SampleContext> SampleProfileReaderBinary::readSampleContextFromTable() {
456   auto FName(readStringFromTable());
457   if (std::error_code EC = FName.getError())
458     return EC;
459   return SampleContext(*FName);
460 }
461 
462 ErrorOr<StringRef> SampleProfileReaderExtBinaryBase::readStringFromTable() {
463   if (!FixedLengthMD5)
464     return SampleProfileReaderBinary::readStringFromTable();
465 
466   // read NameTable index.
467   auto Idx = readStringIndex(NameTable);
468   if (std::error_code EC = Idx.getError())
469     return EC;
470 
471   // Check whether the name to be accessed has been accessed before,
472   // if not, read it from memory directly.
473   StringRef &SR = NameTable[*Idx];
474   if (SR.empty()) {
475     const uint8_t *SavedData = Data;
476     Data = MD5NameMemStart + ((*Idx) * sizeof(uint64_t));
477     auto FID = readUnencodedNumber<uint64_t>();
478     if (std::error_code EC = FID.getError())
479       return EC;
480     // Save the string converted from uint64_t in MD5StringBuf. All the
481     // references to the name are all StringRefs refering to the string
482     // in MD5StringBuf.
483     MD5StringBuf->push_back(std::to_string(*FID));
484     SR = MD5StringBuf->back();
485     Data = SavedData;
486   }
487   return SR;
488 }
489 
490 ErrorOr<StringRef> SampleProfileReaderCompactBinary::readStringFromTable() {
491   auto Idx = readStringIndex(NameTable);
492   if (std::error_code EC = Idx.getError())
493     return EC;
494 
495   return StringRef(NameTable[*Idx]);
496 }
497 
498 std::error_code
499 SampleProfileReaderBinary::readProfile(FunctionSamples &FProfile) {
500   auto NumSamples = readNumber<uint64_t>();
501   if (std::error_code EC = NumSamples.getError())
502     return EC;
503   FProfile.addTotalSamples(*NumSamples);
504 
505   // Read the samples in the body.
506   auto NumRecords = readNumber<uint32_t>();
507   if (std::error_code EC = NumRecords.getError())
508     return EC;
509 
510   for (uint32_t I = 0; I < *NumRecords; ++I) {
511     auto LineOffset = readNumber<uint64_t>();
512     if (std::error_code EC = LineOffset.getError())
513       return EC;
514 
515     if (!isOffsetLegal(*LineOffset)) {
516       return std::error_code();
517     }
518 
519     auto Discriminator = readNumber<uint64_t>();
520     if (std::error_code EC = Discriminator.getError())
521       return EC;
522 
523     auto NumSamples = readNumber<uint64_t>();
524     if (std::error_code EC = NumSamples.getError())
525       return EC;
526 
527     auto NumCalls = readNumber<uint32_t>();
528     if (std::error_code EC = NumCalls.getError())
529       return EC;
530 
531     // Here we handle FS discriminators:
532     uint32_t DiscriminatorVal = (*Discriminator) & getDiscriminatorMask();
533 
534     for (uint32_t J = 0; J < *NumCalls; ++J) {
535       auto CalledFunction(readStringFromTable());
536       if (std::error_code EC = CalledFunction.getError())
537         return EC;
538 
539       auto CalledFunctionSamples = readNumber<uint64_t>();
540       if (std::error_code EC = CalledFunctionSamples.getError())
541         return EC;
542 
543       FProfile.addCalledTargetSamples(*LineOffset, DiscriminatorVal,
544                                       *CalledFunction, *CalledFunctionSamples);
545     }
546 
547     FProfile.addBodySamples(*LineOffset, DiscriminatorVal, *NumSamples);
548   }
549 
550   // Read all the samples for inlined function calls.
551   auto NumCallsites = readNumber<uint32_t>();
552   if (std::error_code EC = NumCallsites.getError())
553     return EC;
554 
555   for (uint32_t J = 0; J < *NumCallsites; ++J) {
556     auto LineOffset = readNumber<uint64_t>();
557     if (std::error_code EC = LineOffset.getError())
558       return EC;
559 
560     auto Discriminator = readNumber<uint64_t>();
561     if (std::error_code EC = Discriminator.getError())
562       return EC;
563 
564     auto FName(readStringFromTable());
565     if (std::error_code EC = FName.getError())
566       return EC;
567 
568     // Here we handle FS discriminators:
569     uint32_t DiscriminatorVal = (*Discriminator) & getDiscriminatorMask();
570 
571     FunctionSamples &CalleeProfile = FProfile.functionSamplesAt(
572         LineLocation(*LineOffset, DiscriminatorVal))[std::string(*FName)];
573     CalleeProfile.setName(*FName);
574     if (std::error_code EC = readProfile(CalleeProfile))
575       return EC;
576   }
577 
578   return sampleprof_error::success;
579 }
580 
581 std::error_code
582 SampleProfileReaderBinary::readFuncProfile(const uint8_t *Start) {
583   Data = Start;
584   auto NumHeadSamples = readNumber<uint64_t>();
585   if (std::error_code EC = NumHeadSamples.getError())
586     return EC;
587 
588   ErrorOr<SampleContext> FContext(readSampleContextFromTable());
589   if (std::error_code EC = FContext.getError())
590     return EC;
591 
592   Profiles[*FContext] = FunctionSamples();
593   FunctionSamples &FProfile = Profiles[*FContext];
594   FProfile.setContext(*FContext);
595   FProfile.addHeadSamples(*NumHeadSamples);
596 
597   if (FContext->hasContext())
598     CSProfileCount++;
599 
600   if (std::error_code EC = readProfile(FProfile))
601     return EC;
602   return sampleprof_error::success;
603 }
604 
605 std::error_code SampleProfileReaderBinary::readImpl() {
606   ProfileIsFS = ProfileIsFSDisciminator;
607   FunctionSamples::ProfileIsFS = ProfileIsFS;
608   while (!at_eof()) {
609     if (std::error_code EC = readFuncProfile(Data))
610       return EC;
611   }
612 
613   return sampleprof_error::success;
614 }
615 
616 ErrorOr<SampleContextFrames>
617 SampleProfileReaderExtBinaryBase::readContextFromTable() {
618   auto ContextIdx = readNumber<uint32_t>();
619   if (std::error_code EC = ContextIdx.getError())
620     return EC;
621   if (*ContextIdx >= CSNameTable->size())
622     return sampleprof_error::truncated_name_table;
623   return (*CSNameTable)[*ContextIdx];
624 }
625 
626 ErrorOr<SampleContext>
627 SampleProfileReaderExtBinaryBase::readSampleContextFromTable() {
628   if (ProfileIsCS) {
629     auto FContext(readContextFromTable());
630     if (std::error_code EC = FContext.getError())
631       return EC;
632     return SampleContext(*FContext);
633   } else {
634     auto FName(readStringFromTable());
635     if (std::error_code EC = FName.getError())
636       return EC;
637     return SampleContext(*FName);
638   }
639 }
640 
641 std::error_code SampleProfileReaderExtBinaryBase::readOneSection(
642     const uint8_t *Start, uint64_t Size, const SecHdrTableEntry &Entry) {
643   Data = Start;
644   End = Start + Size;
645   switch (Entry.Type) {
646   case SecProfSummary:
647     if (std::error_code EC = readSummary())
648       return EC;
649     if (hasSecFlag(Entry, SecProfSummaryFlags::SecFlagPartial))
650       Summary->setPartialProfile(true);
651     if (hasSecFlag(Entry, SecProfSummaryFlags::SecFlagFullContext))
652       FunctionSamples::ProfileIsCS = ProfileIsCS = true;
653     if (hasSecFlag(Entry, SecProfSummaryFlags::SecFlagFSDiscriminator))
654       FunctionSamples::ProfileIsFS = ProfileIsFS = true;
655     break;
656   case SecNameTable: {
657     FixedLengthMD5 =
658         hasSecFlag(Entry, SecNameTableFlags::SecFlagFixedLengthMD5);
659     bool UseMD5 = hasSecFlag(Entry, SecNameTableFlags::SecFlagMD5Name);
660     assert((!FixedLengthMD5 || UseMD5) &&
661            "If FixedLengthMD5 is true, UseMD5 has to be true");
662     FunctionSamples::HasUniqSuffix =
663         hasSecFlag(Entry, SecNameTableFlags::SecFlagUniqSuffix);
664     if (std::error_code EC = readNameTableSec(UseMD5))
665       return EC;
666     break;
667   }
668   case SecCSNameTable: {
669     if (std::error_code EC = readCSNameTableSec())
670       return EC;
671     break;
672   }
673   case SecLBRProfile:
674     if (std::error_code EC = readFuncProfiles())
675       return EC;
676     break;
677   case SecFuncOffsetTable:
678     if (std::error_code EC = readFuncOffsetTable())
679       return EC;
680     break;
681   case SecFuncMetadata: {
682     ProfileIsProbeBased =
683         hasSecFlag(Entry, SecFuncMetadataFlags::SecFlagIsProbeBased);
684     FunctionSamples::ProfileIsProbeBased = ProfileIsProbeBased;
685     bool HasAttribute =
686         hasSecFlag(Entry, SecFuncMetadataFlags::SecFlagHasAttribute);
687     if (std::error_code EC = readFuncMetadata(HasAttribute))
688       return EC;
689     break;
690   }
691   case SecProfileSymbolList:
692     if (std::error_code EC = readProfileSymbolList())
693       return EC;
694     break;
695   default:
696     if (std::error_code EC = readCustomSection(Entry))
697       return EC;
698     break;
699   }
700   return sampleprof_error::success;
701 }
702 
703 bool SampleProfileReaderExtBinaryBase::collectFuncsFromModule() {
704   if (!M)
705     return false;
706   FuncsToUse.clear();
707   for (auto &F : *M)
708     FuncsToUse.insert(FunctionSamples::getCanonicalFnName(F));
709   return true;
710 }
711 
712 std::error_code SampleProfileReaderExtBinaryBase::readFuncOffsetTable() {
713   // If there are more than one FuncOffsetTable, the profile read associated
714   // with previous FuncOffsetTable has to be done before next FuncOffsetTable
715   // is read.
716   FuncOffsetTable.clear();
717 
718   auto Size = readNumber<uint64_t>();
719   if (std::error_code EC = Size.getError())
720     return EC;
721 
722   FuncOffsetTable.reserve(*Size);
723   for (uint32_t I = 0; I < *Size; ++I) {
724     auto FName(readSampleContextFromTable());
725     if (std::error_code EC = FName.getError())
726       return EC;
727 
728     auto Offset = readNumber<uint64_t>();
729     if (std::error_code EC = Offset.getError())
730       return EC;
731 
732     FuncOffsetTable[*FName] = *Offset;
733   }
734   return sampleprof_error::success;
735 }
736 
737 std::error_code SampleProfileReaderExtBinaryBase::readFuncProfiles() {
738   // Collect functions used by current module if the Reader has been
739   // given a module.
740   // collectFuncsFromModule uses FunctionSamples::getCanonicalFnName
741   // which will query FunctionSamples::HasUniqSuffix, so it has to be
742   // called after FunctionSamples::HasUniqSuffix is set, i.e. after
743   // NameTable section is read.
744   bool LoadFuncsToBeUsed = collectFuncsFromModule();
745 
746   // When LoadFuncsToBeUsed is false, load all the function profiles.
747   const uint8_t *Start = Data;
748   if (!LoadFuncsToBeUsed) {
749     while (Data < End) {
750       if (std::error_code EC = readFuncProfile(Data))
751         return EC;
752     }
753     assert(Data == End && "More data is read than expected");
754   } else {
755     // Load function profiles on demand.
756     if (Remapper) {
757       for (auto Name : FuncsToUse) {
758         Remapper->insert(Name);
759       }
760     }
761 
762     if (ProfileIsCS) {
763       // Compute the ordered set of names, so we can
764       // get all context profiles under a subtree by
765       // iterating through the ordered names.
766       std::set<SampleContext> OrderedContexts;
767       for (auto Name : FuncOffsetTable) {
768         OrderedContexts.insert(Name.first);
769       }
770 
771       DenseSet<uint64_t> FuncGuidsToUse;
772       if (useMD5()) {
773         for (auto Name : FuncsToUse)
774           FuncGuidsToUse.insert(Function::getGUID(Name));
775       }
776 
777       // For each function in current module, load all
778       // context profiles for the function.
779       for (auto NameOffset : FuncOffsetTable) {
780         SampleContext FContext = NameOffset.first;
781         auto FuncName = FContext.getName();
782         if ((useMD5() && !FuncGuidsToUse.count(std::stoull(FuncName.data()))) ||
783             (!useMD5() && !FuncsToUse.count(FuncName) &&
784              (!Remapper || !Remapper->exist(FuncName))))
785           continue;
786 
787         // For each context profile we need, try to load
788         // all context profile in the subtree. This can
789         // help profile guided importing for ThinLTO.
790         auto It = OrderedContexts.find(FContext);
791         while (It != OrderedContexts.end() && FContext.IsPrefixOf(*It)) {
792           const uint8_t *FuncProfileAddr = Start + FuncOffsetTable[*It];
793           assert(FuncProfileAddr < End && "out of LBRProfile section");
794           if (std::error_code EC = readFuncProfile(FuncProfileAddr))
795             return EC;
796           // Remove loaded context profile so we won't
797           // load it repeatedly.
798           It = OrderedContexts.erase(It);
799         }
800       }
801     } else {
802       if (useMD5()) {
803         for (auto Name : FuncsToUse) {
804           auto GUID = std::to_string(MD5Hash(Name));
805           auto iter = FuncOffsetTable.find(StringRef(GUID));
806           if (iter == FuncOffsetTable.end())
807             continue;
808           const uint8_t *FuncProfileAddr = Start + iter->second;
809           assert(FuncProfileAddr < End && "out of LBRProfile section");
810           if (std::error_code EC = readFuncProfile(FuncProfileAddr))
811             return EC;
812         }
813       } else {
814         for (auto NameOffset : FuncOffsetTable) {
815           SampleContext FContext(NameOffset.first);
816           auto FuncName = FContext.getName();
817           if (!FuncsToUse.count(FuncName) &&
818               (!Remapper || !Remapper->exist(FuncName)))
819             continue;
820           const uint8_t *FuncProfileAddr = Start + NameOffset.second;
821           assert(FuncProfileAddr < End && "out of LBRProfile section");
822           if (std::error_code EC = readFuncProfile(FuncProfileAddr))
823             return EC;
824         }
825       }
826     }
827     Data = End;
828   }
829   assert((CSProfileCount == 0 || CSProfileCount == Profiles.size()) &&
830          "Cannot have both context-sensitive and regular profile");
831   assert((!CSProfileCount || ProfileIsCS) &&
832          "Section flag should be consistent with actual profile");
833   return sampleprof_error::success;
834 }
835 
836 std::error_code SampleProfileReaderExtBinaryBase::readProfileSymbolList() {
837   if (!ProfSymList)
838     ProfSymList = std::make_unique<ProfileSymbolList>();
839 
840   if (std::error_code EC = ProfSymList->read(Data, End - Data))
841     return EC;
842 
843   Data = End;
844   return sampleprof_error::success;
845 }
846 
847 std::error_code SampleProfileReaderExtBinaryBase::decompressSection(
848     const uint8_t *SecStart, const uint64_t SecSize,
849     const uint8_t *&DecompressBuf, uint64_t &DecompressBufSize) {
850   Data = SecStart;
851   End = SecStart + SecSize;
852   auto DecompressSize = readNumber<uint64_t>();
853   if (std::error_code EC = DecompressSize.getError())
854     return EC;
855   DecompressBufSize = *DecompressSize;
856 
857   auto CompressSize = readNumber<uint64_t>();
858   if (std::error_code EC = CompressSize.getError())
859     return EC;
860 
861   if (!llvm::zlib::isAvailable())
862     return sampleprof_error::zlib_unavailable;
863 
864   StringRef CompressedStrings(reinterpret_cast<const char *>(Data),
865                               *CompressSize);
866   char *Buffer = Allocator.Allocate<char>(DecompressBufSize);
867   size_t UCSize = DecompressBufSize;
868   llvm::Error E =
869       zlib::uncompress(CompressedStrings, Buffer, UCSize);
870   if (E)
871     return sampleprof_error::uncompress_failed;
872   DecompressBuf = reinterpret_cast<const uint8_t *>(Buffer);
873   return sampleprof_error::success;
874 }
875 
876 std::error_code SampleProfileReaderExtBinaryBase::readImpl() {
877   const uint8_t *BufStart =
878       reinterpret_cast<const uint8_t *>(Buffer->getBufferStart());
879 
880   for (auto &Entry : SecHdrTable) {
881     // Skip empty section.
882     if (!Entry.Size)
883       continue;
884 
885     // Skip sections without context when SkipFlatProf is true.
886     if (SkipFlatProf && hasSecFlag(Entry, SecCommonFlags::SecFlagFlat))
887       continue;
888 
889     const uint8_t *SecStart = BufStart + Entry.Offset;
890     uint64_t SecSize = Entry.Size;
891 
892     // If the section is compressed, decompress it into a buffer
893     // DecompressBuf before reading the actual data. The pointee of
894     // 'Data' will be changed to buffer hold by DecompressBuf
895     // temporarily when reading the actual data.
896     bool isCompressed = hasSecFlag(Entry, SecCommonFlags::SecFlagCompress);
897     if (isCompressed) {
898       const uint8_t *DecompressBuf;
899       uint64_t DecompressBufSize;
900       if (std::error_code EC = decompressSection(
901               SecStart, SecSize, DecompressBuf, DecompressBufSize))
902         return EC;
903       SecStart = DecompressBuf;
904       SecSize = DecompressBufSize;
905     }
906 
907     if (std::error_code EC = readOneSection(SecStart, SecSize, Entry))
908       return EC;
909     if (Data != SecStart + SecSize)
910       return sampleprof_error::malformed;
911 
912     // Change the pointee of 'Data' from DecompressBuf to original Buffer.
913     if (isCompressed) {
914       Data = BufStart + Entry.Offset;
915       End = BufStart + Buffer->getBufferSize();
916     }
917   }
918 
919   return sampleprof_error::success;
920 }
921 
922 std::error_code SampleProfileReaderCompactBinary::readImpl() {
923   // Collect functions used by current module if the Reader has been
924   // given a module.
925   bool LoadFuncsToBeUsed = collectFuncsFromModule();
926   ProfileIsFS = ProfileIsFSDisciminator;
927   FunctionSamples::ProfileIsFS = ProfileIsFS;
928   std::vector<uint64_t> OffsetsToUse;
929   if (!LoadFuncsToBeUsed) {
930     // load all the function profiles.
931     for (auto FuncEntry : FuncOffsetTable) {
932       OffsetsToUse.push_back(FuncEntry.second);
933     }
934   } else {
935     // load function profiles on demand.
936     for (auto Name : FuncsToUse) {
937       auto GUID = std::to_string(MD5Hash(Name));
938       auto iter = FuncOffsetTable.find(StringRef(GUID));
939       if (iter == FuncOffsetTable.end())
940         continue;
941       OffsetsToUse.push_back(iter->second);
942     }
943   }
944 
945   for (auto Offset : OffsetsToUse) {
946     const uint8_t *SavedData = Data;
947     if (std::error_code EC = readFuncProfile(
948             reinterpret_cast<const uint8_t *>(Buffer->getBufferStart()) +
949             Offset))
950       return EC;
951     Data = SavedData;
952   }
953   return sampleprof_error::success;
954 }
955 
956 std::error_code SampleProfileReaderRawBinary::verifySPMagic(uint64_t Magic) {
957   if (Magic == SPMagic())
958     return sampleprof_error::success;
959   return sampleprof_error::bad_magic;
960 }
961 
962 std::error_code SampleProfileReaderExtBinary::verifySPMagic(uint64_t Magic) {
963   if (Magic == SPMagic(SPF_Ext_Binary))
964     return sampleprof_error::success;
965   return sampleprof_error::bad_magic;
966 }
967 
968 std::error_code
969 SampleProfileReaderCompactBinary::verifySPMagic(uint64_t Magic) {
970   if (Magic == SPMagic(SPF_Compact_Binary))
971     return sampleprof_error::success;
972   return sampleprof_error::bad_magic;
973 }
974 
975 std::error_code SampleProfileReaderBinary::readNameTable() {
976   auto Size = readNumber<uint32_t>();
977   if (std::error_code EC = Size.getError())
978     return EC;
979   NameTable.reserve(*Size + NameTable.size());
980   for (uint32_t I = 0; I < *Size; ++I) {
981     auto Name(readString());
982     if (std::error_code EC = Name.getError())
983       return EC;
984     NameTable.push_back(*Name);
985   }
986 
987   return sampleprof_error::success;
988 }
989 
990 std::error_code SampleProfileReaderExtBinaryBase::readMD5NameTable() {
991   auto Size = readNumber<uint64_t>();
992   if (std::error_code EC = Size.getError())
993     return EC;
994   MD5StringBuf = std::make_unique<std::vector<std::string>>();
995   MD5StringBuf->reserve(*Size);
996   if (FixedLengthMD5) {
997     // Preallocate and initialize NameTable so we can check whether a name
998     // index has been read before by checking whether the element in the
999     // NameTable is empty, meanwhile readStringIndex can do the boundary
1000     // check using the size of NameTable.
1001     NameTable.resize(*Size + NameTable.size());
1002 
1003     MD5NameMemStart = Data;
1004     Data = Data + (*Size) * sizeof(uint64_t);
1005     return sampleprof_error::success;
1006   }
1007   NameTable.reserve(*Size);
1008   for (uint32_t I = 0; I < *Size; ++I) {
1009     auto FID = readNumber<uint64_t>();
1010     if (std::error_code EC = FID.getError())
1011       return EC;
1012     MD5StringBuf->push_back(std::to_string(*FID));
1013     // NameTable is a vector of StringRef. Here it is pushing back a
1014     // StringRef initialized with the last string in MD5stringBuf.
1015     NameTable.push_back(MD5StringBuf->back());
1016   }
1017   return sampleprof_error::success;
1018 }
1019 
1020 std::error_code SampleProfileReaderExtBinaryBase::readNameTableSec(bool IsMD5) {
1021   if (IsMD5)
1022     return readMD5NameTable();
1023   return SampleProfileReaderBinary::readNameTable();
1024 }
1025 
1026 // Read in the CS name table section, which basically contains a list of context
1027 // vectors. Each element of a context vector, aka a frame, refers to the
1028 // underlying raw function names that are stored in the name table, as well as
1029 // a callsite identifier that only makes sense for non-leaf frames.
1030 std::error_code SampleProfileReaderExtBinaryBase::readCSNameTableSec() {
1031   auto Size = readNumber<uint32_t>();
1032   if (std::error_code EC = Size.getError())
1033     return EC;
1034 
1035   std::vector<SampleContextFrameVector> *PNameVec =
1036       new std::vector<SampleContextFrameVector>();
1037   PNameVec->reserve(*Size);
1038   for (uint32_t I = 0; I < *Size; ++I) {
1039     PNameVec->emplace_back(SampleContextFrameVector());
1040     auto ContextSize = readNumber<uint32_t>();
1041     if (std::error_code EC = ContextSize.getError())
1042       return EC;
1043     for (uint32_t J = 0; J < *ContextSize; ++J) {
1044       auto FName(readStringFromTable());
1045       if (std::error_code EC = FName.getError())
1046         return EC;
1047       auto LineOffset = readNumber<uint64_t>();
1048       if (std::error_code EC = LineOffset.getError())
1049         return EC;
1050 
1051       if (!isOffsetLegal(*LineOffset))
1052         return std::error_code();
1053 
1054       auto Discriminator = readNumber<uint64_t>();
1055       if (std::error_code EC = Discriminator.getError())
1056         return EC;
1057 
1058       PNameVec->back().emplace_back(
1059           FName.get(), LineLocation(LineOffset.get(), Discriminator.get()));
1060     }
1061   }
1062 
1063   // From this point the underlying object of CSNameTable should be immutable.
1064   CSNameTable.reset(PNameVec);
1065   return sampleprof_error::success;
1066 }
1067 
1068 std::error_code
1069 SampleProfileReaderExtBinaryBase::readFuncMetadata(bool ProfileHasAttribute) {
1070   while (Data < End) {
1071     auto FContext(readSampleContextFromTable());
1072     if (std::error_code EC = FContext.getError())
1073       return EC;
1074 
1075     bool ProfileInMap = Profiles.count(*FContext);
1076     if (ProfileIsProbeBased) {
1077       auto Checksum = readNumber<uint64_t>();
1078       if (std::error_code EC = Checksum.getError())
1079         return EC;
1080       if (ProfileInMap)
1081         Profiles[*FContext].setFunctionHash(*Checksum);
1082     }
1083 
1084     if (ProfileHasAttribute) {
1085       auto Attributes = readNumber<uint32_t>();
1086       if (std::error_code EC = Attributes.getError())
1087         return EC;
1088       if (ProfileInMap)
1089         Profiles[*FContext].getContext().setAllAttributes(*Attributes);
1090     }
1091   }
1092 
1093   assert(Data == End && "More data is read than expected");
1094   return sampleprof_error::success;
1095 }
1096 
1097 std::error_code SampleProfileReaderCompactBinary::readNameTable() {
1098   auto Size = readNumber<uint64_t>();
1099   if (std::error_code EC = Size.getError())
1100     return EC;
1101   NameTable.reserve(*Size);
1102   for (uint32_t I = 0; I < *Size; ++I) {
1103     auto FID = readNumber<uint64_t>();
1104     if (std::error_code EC = FID.getError())
1105       return EC;
1106     NameTable.push_back(std::to_string(*FID));
1107   }
1108   return sampleprof_error::success;
1109 }
1110 
1111 std::error_code
1112 SampleProfileReaderExtBinaryBase::readSecHdrTableEntry(uint32_t Idx) {
1113   SecHdrTableEntry Entry;
1114   auto Type = readUnencodedNumber<uint64_t>();
1115   if (std::error_code EC = Type.getError())
1116     return EC;
1117   Entry.Type = static_cast<SecType>(*Type);
1118 
1119   auto Flags = readUnencodedNumber<uint64_t>();
1120   if (std::error_code EC = Flags.getError())
1121     return EC;
1122   Entry.Flags = *Flags;
1123 
1124   auto Offset = readUnencodedNumber<uint64_t>();
1125   if (std::error_code EC = Offset.getError())
1126     return EC;
1127   Entry.Offset = *Offset;
1128 
1129   auto Size = readUnencodedNumber<uint64_t>();
1130   if (std::error_code EC = Size.getError())
1131     return EC;
1132   Entry.Size = *Size;
1133 
1134   Entry.LayoutIndex = Idx;
1135   SecHdrTable.push_back(std::move(Entry));
1136   return sampleprof_error::success;
1137 }
1138 
1139 std::error_code SampleProfileReaderExtBinaryBase::readSecHdrTable() {
1140   auto EntryNum = readUnencodedNumber<uint64_t>();
1141   if (std::error_code EC = EntryNum.getError())
1142     return EC;
1143 
1144   for (uint32_t i = 0; i < (*EntryNum); i++)
1145     if (std::error_code EC = readSecHdrTableEntry(i))
1146       return EC;
1147 
1148   return sampleprof_error::success;
1149 }
1150 
1151 std::error_code SampleProfileReaderExtBinaryBase::readHeader() {
1152   const uint8_t *BufStart =
1153       reinterpret_cast<const uint8_t *>(Buffer->getBufferStart());
1154   Data = BufStart;
1155   End = BufStart + Buffer->getBufferSize();
1156 
1157   if (std::error_code EC = readMagicIdent())
1158     return EC;
1159 
1160   if (std::error_code EC = readSecHdrTable())
1161     return EC;
1162 
1163   return sampleprof_error::success;
1164 }
1165 
1166 uint64_t SampleProfileReaderExtBinaryBase::getSectionSize(SecType Type) {
1167   uint64_t Size = 0;
1168   for (auto &Entry : SecHdrTable) {
1169     if (Entry.Type == Type)
1170       Size += Entry.Size;
1171   }
1172   return Size;
1173 }
1174 
1175 uint64_t SampleProfileReaderExtBinaryBase::getFileSize() {
1176   // Sections in SecHdrTable is not necessarily in the same order as
1177   // sections in the profile because section like FuncOffsetTable needs
1178   // to be written after section LBRProfile but needs to be read before
1179   // section LBRProfile, so we cannot simply use the last entry in
1180   // SecHdrTable to calculate the file size.
1181   uint64_t FileSize = 0;
1182   for (auto &Entry : SecHdrTable) {
1183     FileSize = std::max(Entry.Offset + Entry.Size, FileSize);
1184   }
1185   return FileSize;
1186 }
1187 
1188 static std::string getSecFlagsStr(const SecHdrTableEntry &Entry) {
1189   std::string Flags;
1190   if (hasSecFlag(Entry, SecCommonFlags::SecFlagCompress))
1191     Flags.append("{compressed,");
1192   else
1193     Flags.append("{");
1194 
1195   if (hasSecFlag(Entry, SecCommonFlags::SecFlagFlat))
1196     Flags.append("flat,");
1197 
1198   switch (Entry.Type) {
1199   case SecNameTable:
1200     if (hasSecFlag(Entry, SecNameTableFlags::SecFlagFixedLengthMD5))
1201       Flags.append("fixlenmd5,");
1202     else if (hasSecFlag(Entry, SecNameTableFlags::SecFlagMD5Name))
1203       Flags.append("md5,");
1204     if (hasSecFlag(Entry, SecNameTableFlags::SecFlagUniqSuffix))
1205       Flags.append("uniq,");
1206     break;
1207   case SecProfSummary:
1208     if (hasSecFlag(Entry, SecProfSummaryFlags::SecFlagPartial))
1209       Flags.append("partial,");
1210     if (hasSecFlag(Entry, SecProfSummaryFlags::SecFlagFullContext))
1211       Flags.append("context,");
1212     if (hasSecFlag(Entry, SecProfSummaryFlags::SecFlagFSDiscriminator))
1213       Flags.append("fs-discriminator,");
1214     break;
1215   default:
1216     break;
1217   }
1218   char &last = Flags.back();
1219   if (last == ',')
1220     last = '}';
1221   else
1222     Flags.append("}");
1223   return Flags;
1224 }
1225 
1226 bool SampleProfileReaderExtBinaryBase::dumpSectionInfo(raw_ostream &OS) {
1227   uint64_t TotalSecsSize = 0;
1228   for (auto &Entry : SecHdrTable) {
1229     OS << getSecName(Entry.Type) << " - Offset: " << Entry.Offset
1230        << ", Size: " << Entry.Size << ", Flags: " << getSecFlagsStr(Entry)
1231        << "\n";
1232     ;
1233     TotalSecsSize += Entry.Size;
1234   }
1235   uint64_t HeaderSize = SecHdrTable.front().Offset;
1236   assert(HeaderSize + TotalSecsSize == getFileSize() &&
1237          "Size of 'header + sections' doesn't match the total size of profile");
1238 
1239   OS << "Header Size: " << HeaderSize << "\n";
1240   OS << "Total Sections Size: " << TotalSecsSize << "\n";
1241   OS << "File Size: " << getFileSize() << "\n";
1242   return true;
1243 }
1244 
1245 std::error_code SampleProfileReaderBinary::readMagicIdent() {
1246   // Read and check the magic identifier.
1247   auto Magic = readNumber<uint64_t>();
1248   if (std::error_code EC = Magic.getError())
1249     return EC;
1250   else if (std::error_code EC = verifySPMagic(*Magic))
1251     return EC;
1252 
1253   // Read the version number.
1254   auto Version = readNumber<uint64_t>();
1255   if (std::error_code EC = Version.getError())
1256     return EC;
1257   else if (*Version != SPVersion())
1258     return sampleprof_error::unsupported_version;
1259 
1260   return sampleprof_error::success;
1261 }
1262 
1263 std::error_code SampleProfileReaderBinary::readHeader() {
1264   Data = reinterpret_cast<const uint8_t *>(Buffer->getBufferStart());
1265   End = Data + Buffer->getBufferSize();
1266 
1267   if (std::error_code EC = readMagicIdent())
1268     return EC;
1269 
1270   if (std::error_code EC = readSummary())
1271     return EC;
1272 
1273   if (std::error_code EC = readNameTable())
1274     return EC;
1275   return sampleprof_error::success;
1276 }
1277 
1278 std::error_code SampleProfileReaderCompactBinary::readHeader() {
1279   SampleProfileReaderBinary::readHeader();
1280   if (std::error_code EC = readFuncOffsetTable())
1281     return EC;
1282   return sampleprof_error::success;
1283 }
1284 
1285 std::error_code SampleProfileReaderCompactBinary::readFuncOffsetTable() {
1286   auto TableOffset = readUnencodedNumber<uint64_t>();
1287   if (std::error_code EC = TableOffset.getError())
1288     return EC;
1289 
1290   const uint8_t *SavedData = Data;
1291   const uint8_t *TableStart =
1292       reinterpret_cast<const uint8_t *>(Buffer->getBufferStart()) +
1293       *TableOffset;
1294   Data = TableStart;
1295 
1296   auto Size = readNumber<uint64_t>();
1297   if (std::error_code EC = Size.getError())
1298     return EC;
1299 
1300   FuncOffsetTable.reserve(*Size);
1301   for (uint32_t I = 0; I < *Size; ++I) {
1302     auto FName(readStringFromTable());
1303     if (std::error_code EC = FName.getError())
1304       return EC;
1305 
1306     auto Offset = readNumber<uint64_t>();
1307     if (std::error_code EC = Offset.getError())
1308       return EC;
1309 
1310     FuncOffsetTable[*FName] = *Offset;
1311   }
1312   End = TableStart;
1313   Data = SavedData;
1314   return sampleprof_error::success;
1315 }
1316 
1317 bool SampleProfileReaderCompactBinary::collectFuncsFromModule() {
1318   if (!M)
1319     return false;
1320   FuncsToUse.clear();
1321   for (auto &F : *M)
1322     FuncsToUse.insert(FunctionSamples::getCanonicalFnName(F));
1323   return true;
1324 }
1325 
1326 std::error_code SampleProfileReaderBinary::readSummaryEntry(
1327     std::vector<ProfileSummaryEntry> &Entries) {
1328   auto Cutoff = readNumber<uint64_t>();
1329   if (std::error_code EC = Cutoff.getError())
1330     return EC;
1331 
1332   auto MinBlockCount = readNumber<uint64_t>();
1333   if (std::error_code EC = MinBlockCount.getError())
1334     return EC;
1335 
1336   auto NumBlocks = readNumber<uint64_t>();
1337   if (std::error_code EC = NumBlocks.getError())
1338     return EC;
1339 
1340   Entries.emplace_back(*Cutoff, *MinBlockCount, *NumBlocks);
1341   return sampleprof_error::success;
1342 }
1343 
1344 std::error_code SampleProfileReaderBinary::readSummary() {
1345   auto TotalCount = readNumber<uint64_t>();
1346   if (std::error_code EC = TotalCount.getError())
1347     return EC;
1348 
1349   auto MaxBlockCount = readNumber<uint64_t>();
1350   if (std::error_code EC = MaxBlockCount.getError())
1351     return EC;
1352 
1353   auto MaxFunctionCount = readNumber<uint64_t>();
1354   if (std::error_code EC = MaxFunctionCount.getError())
1355     return EC;
1356 
1357   auto NumBlocks = readNumber<uint64_t>();
1358   if (std::error_code EC = NumBlocks.getError())
1359     return EC;
1360 
1361   auto NumFunctions = readNumber<uint64_t>();
1362   if (std::error_code EC = NumFunctions.getError())
1363     return EC;
1364 
1365   auto NumSummaryEntries = readNumber<uint64_t>();
1366   if (std::error_code EC = NumSummaryEntries.getError())
1367     return EC;
1368 
1369   std::vector<ProfileSummaryEntry> Entries;
1370   for (unsigned i = 0; i < *NumSummaryEntries; i++) {
1371     std::error_code EC = readSummaryEntry(Entries);
1372     if (EC != sampleprof_error::success)
1373       return EC;
1374   }
1375   Summary = std::make_unique<ProfileSummary>(
1376       ProfileSummary::PSK_Sample, Entries, *TotalCount, *MaxBlockCount, 0,
1377       *MaxFunctionCount, *NumBlocks, *NumFunctions);
1378 
1379   return sampleprof_error::success;
1380 }
1381 
1382 bool SampleProfileReaderRawBinary::hasFormat(const MemoryBuffer &Buffer) {
1383   const uint8_t *Data =
1384       reinterpret_cast<const uint8_t *>(Buffer.getBufferStart());
1385   uint64_t Magic = decodeULEB128(Data);
1386   return Magic == SPMagic();
1387 }
1388 
1389 bool SampleProfileReaderExtBinary::hasFormat(const MemoryBuffer &Buffer) {
1390   const uint8_t *Data =
1391       reinterpret_cast<const uint8_t *>(Buffer.getBufferStart());
1392   uint64_t Magic = decodeULEB128(Data);
1393   return Magic == SPMagic(SPF_Ext_Binary);
1394 }
1395 
1396 bool SampleProfileReaderCompactBinary::hasFormat(const MemoryBuffer &Buffer) {
1397   const uint8_t *Data =
1398       reinterpret_cast<const uint8_t *>(Buffer.getBufferStart());
1399   uint64_t Magic = decodeULEB128(Data);
1400   return Magic == SPMagic(SPF_Compact_Binary);
1401 }
1402 
1403 std::error_code SampleProfileReaderGCC::skipNextWord() {
1404   uint32_t dummy;
1405   if (!GcovBuffer.readInt(dummy))
1406     return sampleprof_error::truncated;
1407   return sampleprof_error::success;
1408 }
1409 
1410 template <typename T> ErrorOr<T> SampleProfileReaderGCC::readNumber() {
1411   if (sizeof(T) <= sizeof(uint32_t)) {
1412     uint32_t Val;
1413     if (GcovBuffer.readInt(Val) && Val <= std::numeric_limits<T>::max())
1414       return static_cast<T>(Val);
1415   } else if (sizeof(T) <= sizeof(uint64_t)) {
1416     uint64_t Val;
1417     if (GcovBuffer.readInt64(Val) && Val <= std::numeric_limits<T>::max())
1418       return static_cast<T>(Val);
1419   }
1420 
1421   std::error_code EC = sampleprof_error::malformed;
1422   reportError(0, EC.message());
1423   return EC;
1424 }
1425 
1426 ErrorOr<StringRef> SampleProfileReaderGCC::readString() {
1427   StringRef Str;
1428   if (!GcovBuffer.readString(Str))
1429     return sampleprof_error::truncated;
1430   return Str;
1431 }
1432 
1433 std::error_code SampleProfileReaderGCC::readHeader() {
1434   // Read the magic identifier.
1435   if (!GcovBuffer.readGCDAFormat())
1436     return sampleprof_error::unrecognized_format;
1437 
1438   // Read the version number. Note - the GCC reader does not validate this
1439   // version, but the profile creator generates v704.
1440   GCOV::GCOVVersion version;
1441   if (!GcovBuffer.readGCOVVersion(version))
1442     return sampleprof_error::unrecognized_format;
1443 
1444   if (version != GCOV::V407)
1445     return sampleprof_error::unsupported_version;
1446 
1447   // Skip the empty integer.
1448   if (std::error_code EC = skipNextWord())
1449     return EC;
1450 
1451   return sampleprof_error::success;
1452 }
1453 
1454 std::error_code SampleProfileReaderGCC::readSectionTag(uint32_t Expected) {
1455   uint32_t Tag;
1456   if (!GcovBuffer.readInt(Tag))
1457     return sampleprof_error::truncated;
1458 
1459   if (Tag != Expected)
1460     return sampleprof_error::malformed;
1461 
1462   if (std::error_code EC = skipNextWord())
1463     return EC;
1464 
1465   return sampleprof_error::success;
1466 }
1467 
1468 std::error_code SampleProfileReaderGCC::readNameTable() {
1469   if (std::error_code EC = readSectionTag(GCOVTagAFDOFileNames))
1470     return EC;
1471 
1472   uint32_t Size;
1473   if (!GcovBuffer.readInt(Size))
1474     return sampleprof_error::truncated;
1475 
1476   for (uint32_t I = 0; I < Size; ++I) {
1477     StringRef Str;
1478     if (!GcovBuffer.readString(Str))
1479       return sampleprof_error::truncated;
1480     Names.push_back(std::string(Str));
1481   }
1482 
1483   return sampleprof_error::success;
1484 }
1485 
1486 std::error_code SampleProfileReaderGCC::readFunctionProfiles() {
1487   if (std::error_code EC = readSectionTag(GCOVTagAFDOFunction))
1488     return EC;
1489 
1490   uint32_t NumFunctions;
1491   if (!GcovBuffer.readInt(NumFunctions))
1492     return sampleprof_error::truncated;
1493 
1494   InlineCallStack Stack;
1495   for (uint32_t I = 0; I < NumFunctions; ++I)
1496     if (std::error_code EC = readOneFunctionProfile(Stack, true, 0))
1497       return EC;
1498 
1499   computeSummary();
1500   return sampleprof_error::success;
1501 }
1502 
1503 std::error_code SampleProfileReaderGCC::readOneFunctionProfile(
1504     const InlineCallStack &InlineStack, bool Update, uint32_t Offset) {
1505   uint64_t HeadCount = 0;
1506   if (InlineStack.size() == 0)
1507     if (!GcovBuffer.readInt64(HeadCount))
1508       return sampleprof_error::truncated;
1509 
1510   uint32_t NameIdx;
1511   if (!GcovBuffer.readInt(NameIdx))
1512     return sampleprof_error::truncated;
1513 
1514   StringRef Name(Names[NameIdx]);
1515 
1516   uint32_t NumPosCounts;
1517   if (!GcovBuffer.readInt(NumPosCounts))
1518     return sampleprof_error::truncated;
1519 
1520   uint32_t NumCallsites;
1521   if (!GcovBuffer.readInt(NumCallsites))
1522     return sampleprof_error::truncated;
1523 
1524   FunctionSamples *FProfile = nullptr;
1525   if (InlineStack.size() == 0) {
1526     // If this is a top function that we have already processed, do not
1527     // update its profile again.  This happens in the presence of
1528     // function aliases.  Since these aliases share the same function
1529     // body, there will be identical replicated profiles for the
1530     // original function.  In this case, we simply not bother updating
1531     // the profile of the original function.
1532     FProfile = &Profiles[Name];
1533     FProfile->addHeadSamples(HeadCount);
1534     if (FProfile->getTotalSamples() > 0)
1535       Update = false;
1536   } else {
1537     // Otherwise, we are reading an inlined instance. The top of the
1538     // inline stack contains the profile of the caller. Insert this
1539     // callee in the caller's CallsiteMap.
1540     FunctionSamples *CallerProfile = InlineStack.front();
1541     uint32_t LineOffset = Offset >> 16;
1542     uint32_t Discriminator = Offset & 0xffff;
1543     FProfile = &CallerProfile->functionSamplesAt(
1544         LineLocation(LineOffset, Discriminator))[std::string(Name)];
1545   }
1546   FProfile->setName(Name);
1547 
1548   for (uint32_t I = 0; I < NumPosCounts; ++I) {
1549     uint32_t Offset;
1550     if (!GcovBuffer.readInt(Offset))
1551       return sampleprof_error::truncated;
1552 
1553     uint32_t NumTargets;
1554     if (!GcovBuffer.readInt(NumTargets))
1555       return sampleprof_error::truncated;
1556 
1557     uint64_t Count;
1558     if (!GcovBuffer.readInt64(Count))
1559       return sampleprof_error::truncated;
1560 
1561     // The line location is encoded in the offset as:
1562     //   high 16 bits: line offset to the start of the function.
1563     //   low 16 bits: discriminator.
1564     uint32_t LineOffset = Offset >> 16;
1565     uint32_t Discriminator = Offset & 0xffff;
1566 
1567     InlineCallStack NewStack;
1568     NewStack.push_back(FProfile);
1569     llvm::append_range(NewStack, InlineStack);
1570     if (Update) {
1571       // Walk up the inline stack, adding the samples on this line to
1572       // the total sample count of the callers in the chain.
1573       for (auto CallerProfile : NewStack)
1574         CallerProfile->addTotalSamples(Count);
1575 
1576       // Update the body samples for the current profile.
1577       FProfile->addBodySamples(LineOffset, Discriminator, Count);
1578     }
1579 
1580     // Process the list of functions called at an indirect call site.
1581     // These are all the targets that a function pointer (or virtual
1582     // function) resolved at runtime.
1583     for (uint32_t J = 0; J < NumTargets; J++) {
1584       uint32_t HistVal;
1585       if (!GcovBuffer.readInt(HistVal))
1586         return sampleprof_error::truncated;
1587 
1588       if (HistVal != HIST_TYPE_INDIR_CALL_TOPN)
1589         return sampleprof_error::malformed;
1590 
1591       uint64_t TargetIdx;
1592       if (!GcovBuffer.readInt64(TargetIdx))
1593         return sampleprof_error::truncated;
1594       StringRef TargetName(Names[TargetIdx]);
1595 
1596       uint64_t TargetCount;
1597       if (!GcovBuffer.readInt64(TargetCount))
1598         return sampleprof_error::truncated;
1599 
1600       if (Update)
1601         FProfile->addCalledTargetSamples(LineOffset, Discriminator,
1602                                          TargetName, TargetCount);
1603     }
1604   }
1605 
1606   // Process all the inlined callers into the current function. These
1607   // are all the callsites that were inlined into this function.
1608   for (uint32_t I = 0; I < NumCallsites; I++) {
1609     // The offset is encoded as:
1610     //   high 16 bits: line offset to the start of the function.
1611     //   low 16 bits: discriminator.
1612     uint32_t Offset;
1613     if (!GcovBuffer.readInt(Offset))
1614       return sampleprof_error::truncated;
1615     InlineCallStack NewStack;
1616     NewStack.push_back(FProfile);
1617     llvm::append_range(NewStack, InlineStack);
1618     if (std::error_code EC = readOneFunctionProfile(NewStack, Update, Offset))
1619       return EC;
1620   }
1621 
1622   return sampleprof_error::success;
1623 }
1624 
1625 /// Read a GCC AutoFDO profile.
1626 ///
1627 /// This format is generated by the Linux Perf conversion tool at
1628 /// https://github.com/google/autofdo.
1629 std::error_code SampleProfileReaderGCC::readImpl() {
1630   assert(!ProfileIsFSDisciminator && "Gcc profiles not support FSDisciminator");
1631   // Read the string table.
1632   if (std::error_code EC = readNameTable())
1633     return EC;
1634 
1635   // Read the source profile.
1636   if (std::error_code EC = readFunctionProfiles())
1637     return EC;
1638 
1639   return sampleprof_error::success;
1640 }
1641 
1642 bool SampleProfileReaderGCC::hasFormat(const MemoryBuffer &Buffer) {
1643   StringRef Magic(reinterpret_cast<const char *>(Buffer.getBufferStart()));
1644   return Magic == "adcg*704";
1645 }
1646 
1647 void SampleProfileReaderItaniumRemapper::applyRemapping(LLVMContext &Ctx) {
1648   // If the reader uses MD5 to represent string, we can't remap it because
1649   // we don't know what the original function names were.
1650   if (Reader.useMD5()) {
1651     Ctx.diagnose(DiagnosticInfoSampleProfile(
1652         Reader.getBuffer()->getBufferIdentifier(),
1653         "Profile data remapping cannot be applied to profile data "
1654         "in compact format (original mangled names are not available).",
1655         DS_Warning));
1656     return;
1657   }
1658 
1659   // CSSPGO-TODO: Remapper is not yet supported.
1660   // We will need to remap the entire context string.
1661   assert(Remappings && "should be initialized while creating remapper");
1662   for (auto &Sample : Reader.getProfiles()) {
1663     DenseSet<StringRef> NamesInSample;
1664     Sample.second.findAllNames(NamesInSample);
1665     for (auto &Name : NamesInSample)
1666       if (auto Key = Remappings->insert(Name))
1667         NameMap.insert({Key, Name});
1668   }
1669 
1670   RemappingApplied = true;
1671 }
1672 
1673 Optional<StringRef>
1674 SampleProfileReaderItaniumRemapper::lookUpNameInProfile(StringRef Fname) {
1675   if (auto Key = Remappings->lookup(Fname))
1676     return NameMap.lookup(Key);
1677   return None;
1678 }
1679 
1680 /// Prepare a memory buffer for the contents of \p Filename.
1681 ///
1682 /// \returns an error code indicating the status of the buffer.
1683 static ErrorOr<std::unique_ptr<MemoryBuffer>>
1684 setupMemoryBuffer(const Twine &Filename) {
1685   auto BufferOrErr = MemoryBuffer::getFileOrSTDIN(Filename, /*IsText=*/true);
1686   if (std::error_code EC = BufferOrErr.getError())
1687     return EC;
1688   auto Buffer = std::move(BufferOrErr.get());
1689 
1690   // Sanity check the file.
1691   if (uint64_t(Buffer->getBufferSize()) > std::numeric_limits<uint32_t>::max())
1692     return sampleprof_error::too_large;
1693 
1694   return std::move(Buffer);
1695 }
1696 
1697 /// Create a sample profile reader based on the format of the input file.
1698 ///
1699 /// \param Filename The file to open.
1700 ///
1701 /// \param C The LLVM context to use to emit diagnostics.
1702 ///
1703 /// \param P The FSDiscriminatorPass.
1704 ///
1705 /// \param RemapFilename The file used for profile remapping.
1706 ///
1707 /// \returns an error code indicating the status of the created reader.
1708 ErrorOr<std::unique_ptr<SampleProfileReader>>
1709 SampleProfileReader::create(const std::string Filename, LLVMContext &C,
1710                             FSDiscriminatorPass P,
1711                             const std::string RemapFilename) {
1712   auto BufferOrError = setupMemoryBuffer(Filename);
1713   if (std::error_code EC = BufferOrError.getError())
1714     return EC;
1715   return create(BufferOrError.get(), C, P, RemapFilename);
1716 }
1717 
1718 /// Create a sample profile remapper from the given input, to remap the
1719 /// function names in the given profile data.
1720 ///
1721 /// \param Filename The file to open.
1722 ///
1723 /// \param Reader The profile reader the remapper is going to be applied to.
1724 ///
1725 /// \param C The LLVM context to use to emit diagnostics.
1726 ///
1727 /// \returns an error code indicating the status of the created reader.
1728 ErrorOr<std::unique_ptr<SampleProfileReaderItaniumRemapper>>
1729 SampleProfileReaderItaniumRemapper::create(const std::string Filename,
1730                                            SampleProfileReader &Reader,
1731                                            LLVMContext &C) {
1732   auto BufferOrError = setupMemoryBuffer(Filename);
1733   if (std::error_code EC = BufferOrError.getError())
1734     return EC;
1735   return create(BufferOrError.get(), Reader, C);
1736 }
1737 
1738 /// Create a sample profile remapper from the given input, to remap the
1739 /// function names in the given profile data.
1740 ///
1741 /// \param B The memory buffer to create the reader from (assumes ownership).
1742 ///
1743 /// \param C The LLVM context to use to emit diagnostics.
1744 ///
1745 /// \param Reader The profile reader the remapper is going to be applied to.
1746 ///
1747 /// \returns an error code indicating the status of the created reader.
1748 ErrorOr<std::unique_ptr<SampleProfileReaderItaniumRemapper>>
1749 SampleProfileReaderItaniumRemapper::create(std::unique_ptr<MemoryBuffer> &B,
1750                                            SampleProfileReader &Reader,
1751                                            LLVMContext &C) {
1752   auto Remappings = std::make_unique<SymbolRemappingReader>();
1753   if (Error E = Remappings->read(*B.get())) {
1754     handleAllErrors(
1755         std::move(E), [&](const SymbolRemappingParseError &ParseError) {
1756           C.diagnose(DiagnosticInfoSampleProfile(B->getBufferIdentifier(),
1757                                                  ParseError.getLineNum(),
1758                                                  ParseError.getMessage()));
1759         });
1760     return sampleprof_error::malformed;
1761   }
1762 
1763   return std::make_unique<SampleProfileReaderItaniumRemapper>(
1764       std::move(B), std::move(Remappings), Reader);
1765 }
1766 
1767 /// Create a sample profile reader based on the format of the input data.
1768 ///
1769 /// \param B The memory buffer to create the reader from (assumes ownership).
1770 ///
1771 /// \param C The LLVM context to use to emit diagnostics.
1772 ///
1773 /// \param P The FSDiscriminatorPass.
1774 ///
1775 /// \param RemapFilename The file used for profile remapping.
1776 ///
1777 /// \returns an error code indicating the status of the created reader.
1778 ErrorOr<std::unique_ptr<SampleProfileReader>>
1779 SampleProfileReader::create(std::unique_ptr<MemoryBuffer> &B, LLVMContext &C,
1780                             FSDiscriminatorPass P,
1781                             const std::string RemapFilename) {
1782   std::unique_ptr<SampleProfileReader> Reader;
1783   if (SampleProfileReaderRawBinary::hasFormat(*B))
1784     Reader.reset(new SampleProfileReaderRawBinary(std::move(B), C));
1785   else if (SampleProfileReaderExtBinary::hasFormat(*B))
1786     Reader.reset(new SampleProfileReaderExtBinary(std::move(B), C));
1787   else if (SampleProfileReaderCompactBinary::hasFormat(*B))
1788     Reader.reset(new SampleProfileReaderCompactBinary(std::move(B), C));
1789   else if (SampleProfileReaderGCC::hasFormat(*B))
1790     Reader.reset(new SampleProfileReaderGCC(std::move(B), C));
1791   else if (SampleProfileReaderText::hasFormat(*B))
1792     Reader.reset(new SampleProfileReaderText(std::move(B), C));
1793   else
1794     return sampleprof_error::unrecognized_format;
1795 
1796   if (!RemapFilename.empty()) {
1797     auto ReaderOrErr =
1798         SampleProfileReaderItaniumRemapper::create(RemapFilename, *Reader, C);
1799     if (std::error_code EC = ReaderOrErr.getError()) {
1800       std::string Msg = "Could not create remapper: " + EC.message();
1801       C.diagnose(DiagnosticInfoSampleProfile(RemapFilename, Msg));
1802       return EC;
1803     }
1804     Reader->Remapper = std::move(ReaderOrErr.get());
1805   }
1806 
1807   FunctionSamples::Format = Reader->getFormat();
1808   if (std::error_code EC = Reader->readHeader()) {
1809     return EC;
1810   }
1811 
1812   Reader->setDiscriminatorMaskedBitFrom(P);
1813 
1814   return std::move(Reader);
1815 }
1816 
1817 // For text and GCC file formats, we compute the summary after reading the
1818 // profile. Binary format has the profile summary in its header.
1819 void SampleProfileReader::computeSummary() {
1820   SampleProfileSummaryBuilder Builder(ProfileSummaryBuilder::DefaultCutoffs);
1821   Summary = Builder.computeSummaryForProfiles(Profiles);
1822 }
1823