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