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> SampleProfileReaderCompactBinary::readStringFromTable() {
371   auto Idx = readStringIndex(NameTable);
372   if (std::error_code EC = Idx.getError())
373     return EC;
374 
375   return StringRef(NameTable[*Idx]);
376 }
377 
378 std::error_code
379 SampleProfileReaderBinary::readProfile(FunctionSamples &FProfile) {
380   auto NumSamples = readNumber<uint64_t>();
381   if (std::error_code EC = NumSamples.getError())
382     return EC;
383   FProfile.addTotalSamples(*NumSamples);
384 
385   // Read the samples in the body.
386   auto NumRecords = readNumber<uint32_t>();
387   if (std::error_code EC = NumRecords.getError())
388     return EC;
389 
390   for (uint32_t I = 0; I < *NumRecords; ++I) {
391     auto LineOffset = readNumber<uint64_t>();
392     if (std::error_code EC = LineOffset.getError())
393       return EC;
394 
395     if (!isOffsetLegal(*LineOffset)) {
396       return std::error_code();
397     }
398 
399     auto Discriminator = readNumber<uint64_t>();
400     if (std::error_code EC = Discriminator.getError())
401       return EC;
402 
403     auto NumSamples = readNumber<uint64_t>();
404     if (std::error_code EC = NumSamples.getError())
405       return EC;
406 
407     auto NumCalls = readNumber<uint32_t>();
408     if (std::error_code EC = NumCalls.getError())
409       return EC;
410 
411     for (uint32_t J = 0; J < *NumCalls; ++J) {
412       auto CalledFunction(readStringFromTable());
413       if (std::error_code EC = CalledFunction.getError())
414         return EC;
415 
416       auto CalledFunctionSamples = readNumber<uint64_t>();
417       if (std::error_code EC = CalledFunctionSamples.getError())
418         return EC;
419 
420       FProfile.addCalledTargetSamples(*LineOffset, *Discriminator,
421                                       *CalledFunction, *CalledFunctionSamples);
422     }
423 
424     FProfile.addBodySamples(*LineOffset, *Discriminator, *NumSamples);
425   }
426 
427   // Read all the samples for inlined function calls.
428   auto NumCallsites = readNumber<uint32_t>();
429   if (std::error_code EC = NumCallsites.getError())
430     return EC;
431 
432   for (uint32_t J = 0; J < *NumCallsites; ++J) {
433     auto LineOffset = readNumber<uint64_t>();
434     if (std::error_code EC = LineOffset.getError())
435       return EC;
436 
437     auto Discriminator = readNumber<uint64_t>();
438     if (std::error_code EC = Discriminator.getError())
439       return EC;
440 
441     auto FName(readStringFromTable());
442     if (std::error_code EC = FName.getError())
443       return EC;
444 
445     FunctionSamples &CalleeProfile = FProfile.functionSamplesAt(
446         LineLocation(*LineOffset, *Discriminator))[std::string(*FName)];
447     CalleeProfile.setName(*FName);
448     if (std::error_code EC = readProfile(CalleeProfile))
449       return EC;
450   }
451 
452   return sampleprof_error::success;
453 }
454 
455 std::error_code
456 SampleProfileReaderBinary::readFuncProfile(const uint8_t *Start) {
457   Data = Start;
458   auto NumHeadSamples = readNumber<uint64_t>();
459   if (std::error_code EC = NumHeadSamples.getError())
460     return EC;
461 
462   auto FName(readStringFromTable());
463   if (std::error_code EC = FName.getError())
464     return EC;
465 
466   Profiles[*FName] = FunctionSamples();
467   FunctionSamples &FProfile = Profiles[*FName];
468   FProfile.setName(*FName);
469 
470   FProfile.addHeadSamples(*NumHeadSamples);
471 
472   if (std::error_code EC = readProfile(FProfile))
473     return EC;
474   return sampleprof_error::success;
475 }
476 
477 std::error_code SampleProfileReaderBinary::readImpl() {
478   while (!at_eof()) {
479     if (std::error_code EC = readFuncProfile(Data))
480       return EC;
481   }
482 
483   return sampleprof_error::success;
484 }
485 
486 std::error_code SampleProfileReaderExtBinaryBase::readOneSection(
487     const uint8_t *Start, uint64_t Size, const SecHdrTableEntry &Entry) {
488   Data = Start;
489   End = Start + Size;
490   switch (Entry.Type) {
491   case SecProfSummary:
492     if (std::error_code EC = readSummary())
493       return EC;
494     if (hasSecFlag(Entry, SecProfSummaryFlags::SecFlagPartial))
495       Summary->setPartialProfile(true);
496     break;
497   case SecNameTable:
498     if (std::error_code EC = readNameTableSec(
499             hasSecFlag(Entry, SecNameTableFlags::SecFlagMD5Name)))
500       return EC;
501     break;
502   case SecLBRProfile:
503     if (std::error_code EC = readFuncProfiles())
504       return EC;
505     break;
506   case SecFuncOffsetTable:
507     if (std::error_code EC = readFuncOffsetTable())
508       return EC;
509     break;
510   case SecProfileSymbolList:
511     if (std::error_code EC = readProfileSymbolList())
512       return EC;
513     break;
514   default:
515     if (std::error_code EC = readCustomSection(Entry))
516       return EC;
517     break;
518   }
519   return sampleprof_error::success;
520 }
521 
522 void SampleProfileReaderExtBinaryBase::collectFuncsFrom(const Module &M) {
523   UseAllFuncs = false;
524   FuncsToUse.clear();
525   for (auto &F : M)
526     FuncsToUse.insert(FunctionSamples::getCanonicalFnName(F));
527 }
528 
529 std::error_code SampleProfileReaderExtBinaryBase::readFuncOffsetTable() {
530   auto Size = readNumber<uint64_t>();
531   if (std::error_code EC = Size.getError())
532     return EC;
533 
534   FuncOffsetTable.reserve(*Size);
535   for (uint32_t I = 0; I < *Size; ++I) {
536     auto FName(readStringFromTable());
537     if (std::error_code EC = FName.getError())
538       return EC;
539 
540     auto Offset = readNumber<uint64_t>();
541     if (std::error_code EC = Offset.getError())
542       return EC;
543 
544     FuncOffsetTable[*FName] = *Offset;
545   }
546   return sampleprof_error::success;
547 }
548 
549 std::error_code SampleProfileReaderExtBinaryBase::readFuncProfiles() {
550   const uint8_t *Start = Data;
551   if (UseAllFuncs) {
552     while (Data < End) {
553       if (std::error_code EC = readFuncProfile(Data))
554         return EC;
555     }
556     assert(Data == End && "More data is read than expected");
557     return sampleprof_error::success;
558   }
559 
560   if (Remapper) {
561     for (auto Name : FuncsToUse) {
562       Remapper->insert(Name);
563     }
564   }
565 
566   if (useMD5()) {
567     for (auto Name : FuncsToUse) {
568       auto GUID = std::to_string(MD5Hash(Name));
569       auto iter = FuncOffsetTable.find(StringRef(GUID));
570       if (iter == FuncOffsetTable.end())
571         continue;
572       const uint8_t *FuncProfileAddr = Start + iter->second;
573       assert(FuncProfileAddr < End && "out of LBRProfile section");
574       if (std::error_code EC = readFuncProfile(FuncProfileAddr))
575         return EC;
576     }
577   } else {
578     for (auto NameOffset : FuncOffsetTable) {
579       auto FuncName = NameOffset.first;
580       if (!FuncsToUse.count(FuncName) &&
581           (!Remapper || !Remapper->exist(FuncName)))
582         continue;
583       const uint8_t *FuncProfileAddr = Start + NameOffset.second;
584       assert(FuncProfileAddr < End && "out of LBRProfile section");
585       if (std::error_code EC = readFuncProfile(FuncProfileAddr))
586         return EC;
587     }
588   }
589 
590   Data = End;
591   return sampleprof_error::success;
592 }
593 
594 std::error_code SampleProfileReaderExtBinaryBase::readProfileSymbolList() {
595   if (!ProfSymList)
596     ProfSymList = std::make_unique<ProfileSymbolList>();
597 
598   if (std::error_code EC = ProfSymList->read(Data, End - Data))
599     return EC;
600 
601   Data = End;
602   return sampleprof_error::success;
603 }
604 
605 std::error_code SampleProfileReaderExtBinaryBase::decompressSection(
606     const uint8_t *SecStart, const uint64_t SecSize,
607     const uint8_t *&DecompressBuf, uint64_t &DecompressBufSize) {
608   Data = SecStart;
609   End = SecStart + SecSize;
610   auto DecompressSize = readNumber<uint64_t>();
611   if (std::error_code EC = DecompressSize.getError())
612     return EC;
613   DecompressBufSize = *DecompressSize;
614 
615   auto CompressSize = readNumber<uint64_t>();
616   if (std::error_code EC = CompressSize.getError())
617     return EC;
618 
619   if (!llvm::zlib::isAvailable())
620     return sampleprof_error::zlib_unavailable;
621 
622   StringRef CompressedStrings(reinterpret_cast<const char *>(Data),
623                               *CompressSize);
624   char *Buffer = Allocator.Allocate<char>(DecompressBufSize);
625   size_t UCSize = DecompressBufSize;
626   llvm::Error E =
627       zlib::uncompress(CompressedStrings, Buffer, UCSize);
628   if (E)
629     return sampleprof_error::uncompress_failed;
630   DecompressBuf = reinterpret_cast<const uint8_t *>(Buffer);
631   return sampleprof_error::success;
632 }
633 
634 std::error_code SampleProfileReaderExtBinaryBase::readImpl() {
635   const uint8_t *BufStart =
636       reinterpret_cast<const uint8_t *>(Buffer->getBufferStart());
637 
638   for (auto &Entry : SecHdrTable) {
639     // Skip empty section.
640     if (!Entry.Size)
641       continue;
642 
643     const uint8_t *SecStart = BufStart + Entry.Offset;
644     uint64_t SecSize = Entry.Size;
645 
646     // If the section is compressed, decompress it into a buffer
647     // DecompressBuf before reading the actual data. The pointee of
648     // 'Data' will be changed to buffer hold by DecompressBuf
649     // temporarily when reading the actual data.
650     bool isCompressed = hasSecFlag(Entry, SecCommonFlags::SecFlagCompress);
651     if (isCompressed) {
652       const uint8_t *DecompressBuf;
653       uint64_t DecompressBufSize;
654       if (std::error_code EC = decompressSection(
655               SecStart, SecSize, DecompressBuf, DecompressBufSize))
656         return EC;
657       SecStart = DecompressBuf;
658       SecSize = DecompressBufSize;
659     }
660 
661     if (std::error_code EC = readOneSection(SecStart, SecSize, Entry))
662       return EC;
663     if (Data != SecStart + SecSize)
664       return sampleprof_error::malformed;
665 
666     // Change the pointee of 'Data' from DecompressBuf to original Buffer.
667     if (isCompressed) {
668       Data = BufStart + Entry.Offset;
669       End = BufStart + Buffer->getBufferSize();
670     }
671   }
672 
673   return sampleprof_error::success;
674 }
675 
676 std::error_code SampleProfileReaderCompactBinary::readImpl() {
677   std::vector<uint64_t> OffsetsToUse;
678   if (UseAllFuncs) {
679     for (auto FuncEntry : FuncOffsetTable) {
680       OffsetsToUse.push_back(FuncEntry.second);
681     }
682   }
683   else {
684     for (auto Name : FuncsToUse) {
685       auto GUID = std::to_string(MD5Hash(Name));
686       auto iter = FuncOffsetTable.find(StringRef(GUID));
687       if (iter == FuncOffsetTable.end())
688         continue;
689       OffsetsToUse.push_back(iter->second);
690     }
691   }
692 
693   for (auto Offset : OffsetsToUse) {
694     const uint8_t *SavedData = Data;
695     if (std::error_code EC = readFuncProfile(
696             reinterpret_cast<const uint8_t *>(Buffer->getBufferStart()) +
697             Offset))
698       return EC;
699     Data = SavedData;
700   }
701   return sampleprof_error::success;
702 }
703 
704 std::error_code SampleProfileReaderRawBinary::verifySPMagic(uint64_t Magic) {
705   if (Magic == SPMagic())
706     return sampleprof_error::success;
707   return sampleprof_error::bad_magic;
708 }
709 
710 std::error_code SampleProfileReaderExtBinary::verifySPMagic(uint64_t Magic) {
711   if (Magic == SPMagic(SPF_Ext_Binary))
712     return sampleprof_error::success;
713   return sampleprof_error::bad_magic;
714 }
715 
716 std::error_code
717 SampleProfileReaderCompactBinary::verifySPMagic(uint64_t Magic) {
718   if (Magic == SPMagic(SPF_Compact_Binary))
719     return sampleprof_error::success;
720   return sampleprof_error::bad_magic;
721 }
722 
723 std::error_code SampleProfileReaderBinary::readNameTable() {
724   auto Size = readNumber<uint32_t>();
725   if (std::error_code EC = Size.getError())
726     return EC;
727   NameTable.reserve(*Size);
728   for (uint32_t I = 0; I < *Size; ++I) {
729     auto Name(readString());
730     if (std::error_code EC = Name.getError())
731       return EC;
732     NameTable.push_back(*Name);
733   }
734 
735   return sampleprof_error::success;
736 }
737 
738 std::error_code SampleProfileReaderExtBinaryBase::readMD5NameTable() {
739   auto Size = readNumber<uint64_t>();
740   if (std::error_code EC = Size.getError())
741     return EC;
742   NameTable.reserve(*Size);
743   MD5StringBuf = std::make_unique<std::vector<std::string>>();
744   MD5StringBuf->reserve(*Size);
745   for (uint32_t I = 0; I < *Size; ++I) {
746     auto FID = readNumber<uint64_t>();
747     if (std::error_code EC = FID.getError())
748       return EC;
749     MD5StringBuf->push_back(std::to_string(*FID));
750     // NameTable is a vector of StringRef. Here it is pushing back a
751     // StringRef initialized with the last string in MD5stringBuf.
752     NameTable.push_back(MD5StringBuf->back());
753   }
754   return sampleprof_error::success;
755 }
756 
757 std::error_code SampleProfileReaderExtBinaryBase::readNameTableSec(bool IsMD5) {
758   if (IsMD5)
759     return readMD5NameTable();
760   return SampleProfileReaderBinary::readNameTable();
761 }
762 
763 std::error_code SampleProfileReaderCompactBinary::readNameTable() {
764   auto Size = readNumber<uint64_t>();
765   if (std::error_code EC = Size.getError())
766     return EC;
767   NameTable.reserve(*Size);
768   for (uint32_t I = 0; I < *Size; ++I) {
769     auto FID = readNumber<uint64_t>();
770     if (std::error_code EC = FID.getError())
771       return EC;
772     NameTable.push_back(std::to_string(*FID));
773   }
774   return sampleprof_error::success;
775 }
776 
777 std::error_code SampleProfileReaderExtBinaryBase::readSecHdrTableEntry() {
778   SecHdrTableEntry Entry;
779   auto Type = readUnencodedNumber<uint64_t>();
780   if (std::error_code EC = Type.getError())
781     return EC;
782   Entry.Type = static_cast<SecType>(*Type);
783 
784   auto Flags = readUnencodedNumber<uint64_t>();
785   if (std::error_code EC = Flags.getError())
786     return EC;
787   Entry.Flags = *Flags;
788 
789   auto Offset = readUnencodedNumber<uint64_t>();
790   if (std::error_code EC = Offset.getError())
791     return EC;
792   Entry.Offset = *Offset;
793 
794   auto Size = readUnencodedNumber<uint64_t>();
795   if (std::error_code EC = Size.getError())
796     return EC;
797   Entry.Size = *Size;
798 
799   SecHdrTable.push_back(std::move(Entry));
800   return sampleprof_error::success;
801 }
802 
803 std::error_code SampleProfileReaderExtBinaryBase::readSecHdrTable() {
804   auto EntryNum = readUnencodedNumber<uint64_t>();
805   if (std::error_code EC = EntryNum.getError())
806     return EC;
807 
808   for (uint32_t i = 0; i < (*EntryNum); i++)
809     if (std::error_code EC = readSecHdrTableEntry())
810       return EC;
811 
812   return sampleprof_error::success;
813 }
814 
815 std::error_code SampleProfileReaderExtBinaryBase::readHeader() {
816   const uint8_t *BufStart =
817       reinterpret_cast<const uint8_t *>(Buffer->getBufferStart());
818   Data = BufStart;
819   End = BufStart + Buffer->getBufferSize();
820 
821   if (std::error_code EC = readMagicIdent())
822     return EC;
823 
824   if (std::error_code EC = readSecHdrTable())
825     return EC;
826 
827   return sampleprof_error::success;
828 }
829 
830 uint64_t SampleProfileReaderExtBinaryBase::getSectionSize(SecType Type) {
831   for (auto &Entry : SecHdrTable) {
832     if (Entry.Type == Type)
833       return Entry.Size;
834   }
835   return 0;
836 }
837 
838 uint64_t SampleProfileReaderExtBinaryBase::getFileSize() {
839   // Sections in SecHdrTable is not necessarily in the same order as
840   // sections in the profile because section like FuncOffsetTable needs
841   // to be written after section LBRProfile but needs to be read before
842   // section LBRProfile, so we cannot simply use the last entry in
843   // SecHdrTable to calculate the file size.
844   uint64_t FileSize = 0;
845   for (auto &Entry : SecHdrTable) {
846     FileSize = std::max(Entry.Offset + Entry.Size, FileSize);
847   }
848   return FileSize;
849 }
850 
851 static std::string getSecFlagsStr(const SecHdrTableEntry &Entry) {
852   std::string Flags;
853   if (hasSecFlag(Entry, SecCommonFlags::SecFlagCompress))
854     Flags.append("{compressed,");
855   else
856     Flags.append("{");
857 
858   switch (Entry.Type) {
859   case SecNameTable:
860     if (hasSecFlag(Entry, SecNameTableFlags::SecFlagMD5Name))
861       Flags.append("md5,");
862     break;
863   case SecProfSummary:
864     if (hasSecFlag(Entry, SecProfSummaryFlags::SecFlagPartial))
865       Flags.append("partial,");
866     break;
867   default:
868     break;
869   }
870   char &last = Flags.back();
871   if (last == ',')
872     last = '}';
873   else
874     Flags.append("}");
875   return Flags;
876 }
877 
878 bool SampleProfileReaderExtBinaryBase::dumpSectionInfo(raw_ostream &OS) {
879   uint64_t TotalSecsSize = 0;
880   for (auto &Entry : SecHdrTable) {
881     OS << getSecName(Entry.Type) << " - Offset: " << Entry.Offset
882        << ", Size: " << Entry.Size << ", Flags: " << getSecFlagsStr(Entry)
883        << "\n";
884     ;
885     TotalSecsSize += getSectionSize(Entry.Type);
886   }
887   uint64_t HeaderSize = SecHdrTable.front().Offset;
888   assert(HeaderSize + TotalSecsSize == getFileSize() &&
889          "Size of 'header + sections' doesn't match the total size of profile");
890 
891   OS << "Header Size: " << HeaderSize << "\n";
892   OS << "Total Sections Size: " << TotalSecsSize << "\n";
893   OS << "File Size: " << getFileSize() << "\n";
894   return true;
895 }
896 
897 std::error_code SampleProfileReaderBinary::readMagicIdent() {
898   // Read and check the magic identifier.
899   auto Magic = readNumber<uint64_t>();
900   if (std::error_code EC = Magic.getError())
901     return EC;
902   else if (std::error_code EC = verifySPMagic(*Magic))
903     return EC;
904 
905   // Read the version number.
906   auto Version = readNumber<uint64_t>();
907   if (std::error_code EC = Version.getError())
908     return EC;
909   else if (*Version != SPVersion())
910     return sampleprof_error::unsupported_version;
911 
912   return sampleprof_error::success;
913 }
914 
915 std::error_code SampleProfileReaderBinary::readHeader() {
916   Data = reinterpret_cast<const uint8_t *>(Buffer->getBufferStart());
917   End = Data + Buffer->getBufferSize();
918 
919   if (std::error_code EC = readMagicIdent())
920     return EC;
921 
922   if (std::error_code EC = readSummary())
923     return EC;
924 
925   if (std::error_code EC = readNameTable())
926     return EC;
927   return sampleprof_error::success;
928 }
929 
930 std::error_code SampleProfileReaderCompactBinary::readHeader() {
931   SampleProfileReaderBinary::readHeader();
932   if (std::error_code EC = readFuncOffsetTable())
933     return EC;
934   return sampleprof_error::success;
935 }
936 
937 std::error_code SampleProfileReaderCompactBinary::readFuncOffsetTable() {
938   auto TableOffset = readUnencodedNumber<uint64_t>();
939   if (std::error_code EC = TableOffset.getError())
940     return EC;
941 
942   const uint8_t *SavedData = Data;
943   const uint8_t *TableStart =
944       reinterpret_cast<const uint8_t *>(Buffer->getBufferStart()) +
945       *TableOffset;
946   Data = TableStart;
947 
948   auto Size = readNumber<uint64_t>();
949   if (std::error_code EC = Size.getError())
950     return EC;
951 
952   FuncOffsetTable.reserve(*Size);
953   for (uint32_t I = 0; I < *Size; ++I) {
954     auto FName(readStringFromTable());
955     if (std::error_code EC = FName.getError())
956       return EC;
957 
958     auto Offset = readNumber<uint64_t>();
959     if (std::error_code EC = Offset.getError())
960       return EC;
961 
962     FuncOffsetTable[*FName] = *Offset;
963   }
964   End = TableStart;
965   Data = SavedData;
966   return sampleprof_error::success;
967 }
968 
969 void SampleProfileReaderCompactBinary::collectFuncsFrom(const Module &M) {
970   UseAllFuncs = false;
971   FuncsToUse.clear();
972   for (auto &F : M)
973     FuncsToUse.insert(FunctionSamples::getCanonicalFnName(F));
974 }
975 
976 std::error_code SampleProfileReaderBinary::readSummaryEntry(
977     std::vector<ProfileSummaryEntry> &Entries) {
978   auto Cutoff = readNumber<uint64_t>();
979   if (std::error_code EC = Cutoff.getError())
980     return EC;
981 
982   auto MinBlockCount = readNumber<uint64_t>();
983   if (std::error_code EC = MinBlockCount.getError())
984     return EC;
985 
986   auto NumBlocks = readNumber<uint64_t>();
987   if (std::error_code EC = NumBlocks.getError())
988     return EC;
989 
990   Entries.emplace_back(*Cutoff, *MinBlockCount, *NumBlocks);
991   return sampleprof_error::success;
992 }
993 
994 std::error_code SampleProfileReaderBinary::readSummary() {
995   auto TotalCount = readNumber<uint64_t>();
996   if (std::error_code EC = TotalCount.getError())
997     return EC;
998 
999   auto MaxBlockCount = readNumber<uint64_t>();
1000   if (std::error_code EC = MaxBlockCount.getError())
1001     return EC;
1002 
1003   auto MaxFunctionCount = readNumber<uint64_t>();
1004   if (std::error_code EC = MaxFunctionCount.getError())
1005     return EC;
1006 
1007   auto NumBlocks = readNumber<uint64_t>();
1008   if (std::error_code EC = NumBlocks.getError())
1009     return EC;
1010 
1011   auto NumFunctions = readNumber<uint64_t>();
1012   if (std::error_code EC = NumFunctions.getError())
1013     return EC;
1014 
1015   auto NumSummaryEntries = readNumber<uint64_t>();
1016   if (std::error_code EC = NumSummaryEntries.getError())
1017     return EC;
1018 
1019   std::vector<ProfileSummaryEntry> Entries;
1020   for (unsigned i = 0; i < *NumSummaryEntries; i++) {
1021     std::error_code EC = readSummaryEntry(Entries);
1022     if (EC != sampleprof_error::success)
1023       return EC;
1024   }
1025   Summary = std::make_unique<ProfileSummary>(
1026       ProfileSummary::PSK_Sample, Entries, *TotalCount, *MaxBlockCount, 0,
1027       *MaxFunctionCount, *NumBlocks, *NumFunctions);
1028 
1029   return sampleprof_error::success;
1030 }
1031 
1032 bool SampleProfileReaderRawBinary::hasFormat(const MemoryBuffer &Buffer) {
1033   const uint8_t *Data =
1034       reinterpret_cast<const uint8_t *>(Buffer.getBufferStart());
1035   uint64_t Magic = decodeULEB128(Data);
1036   return Magic == SPMagic();
1037 }
1038 
1039 bool SampleProfileReaderExtBinary::hasFormat(const MemoryBuffer &Buffer) {
1040   const uint8_t *Data =
1041       reinterpret_cast<const uint8_t *>(Buffer.getBufferStart());
1042   uint64_t Magic = decodeULEB128(Data);
1043   return Magic == SPMagic(SPF_Ext_Binary);
1044 }
1045 
1046 bool SampleProfileReaderCompactBinary::hasFormat(const MemoryBuffer &Buffer) {
1047   const uint8_t *Data =
1048       reinterpret_cast<const uint8_t *>(Buffer.getBufferStart());
1049   uint64_t Magic = decodeULEB128(Data);
1050   return Magic == SPMagic(SPF_Compact_Binary);
1051 }
1052 
1053 std::error_code SampleProfileReaderGCC::skipNextWord() {
1054   uint32_t dummy;
1055   if (!GcovBuffer.readInt(dummy))
1056     return sampleprof_error::truncated;
1057   return sampleprof_error::success;
1058 }
1059 
1060 template <typename T> ErrorOr<T> SampleProfileReaderGCC::readNumber() {
1061   if (sizeof(T) <= sizeof(uint32_t)) {
1062     uint32_t Val;
1063     if (GcovBuffer.readInt(Val) && Val <= std::numeric_limits<T>::max())
1064       return static_cast<T>(Val);
1065   } else if (sizeof(T) <= sizeof(uint64_t)) {
1066     uint64_t Val;
1067     if (GcovBuffer.readInt64(Val) && Val <= std::numeric_limits<T>::max())
1068       return static_cast<T>(Val);
1069   }
1070 
1071   std::error_code EC = sampleprof_error::malformed;
1072   reportError(0, EC.message());
1073   return EC;
1074 }
1075 
1076 ErrorOr<StringRef> SampleProfileReaderGCC::readString() {
1077   StringRef Str;
1078   if (!GcovBuffer.readString(Str))
1079     return sampleprof_error::truncated;
1080   return Str;
1081 }
1082 
1083 std::error_code SampleProfileReaderGCC::readHeader() {
1084   // Read the magic identifier.
1085   if (!GcovBuffer.readGCDAFormat())
1086     return sampleprof_error::unrecognized_format;
1087 
1088   // Read the version number. Note - the GCC reader does not validate this
1089   // version, but the profile creator generates v704.
1090   GCOV::GCOVVersion version;
1091   if (!GcovBuffer.readGCOVVersion(version))
1092     return sampleprof_error::unrecognized_format;
1093 
1094   if (version != GCOV::V407)
1095     return sampleprof_error::unsupported_version;
1096 
1097   // Skip the empty integer.
1098   if (std::error_code EC = skipNextWord())
1099     return EC;
1100 
1101   return sampleprof_error::success;
1102 }
1103 
1104 std::error_code SampleProfileReaderGCC::readSectionTag(uint32_t Expected) {
1105   uint32_t Tag;
1106   if (!GcovBuffer.readInt(Tag))
1107     return sampleprof_error::truncated;
1108 
1109   if (Tag != Expected)
1110     return sampleprof_error::malformed;
1111 
1112   if (std::error_code EC = skipNextWord())
1113     return EC;
1114 
1115   return sampleprof_error::success;
1116 }
1117 
1118 std::error_code SampleProfileReaderGCC::readNameTable() {
1119   if (std::error_code EC = readSectionTag(GCOVTagAFDOFileNames))
1120     return EC;
1121 
1122   uint32_t Size;
1123   if (!GcovBuffer.readInt(Size))
1124     return sampleprof_error::truncated;
1125 
1126   for (uint32_t I = 0; I < Size; ++I) {
1127     StringRef Str;
1128     if (!GcovBuffer.readString(Str))
1129       return sampleprof_error::truncated;
1130     Names.push_back(std::string(Str));
1131   }
1132 
1133   return sampleprof_error::success;
1134 }
1135 
1136 std::error_code SampleProfileReaderGCC::readFunctionProfiles() {
1137   if (std::error_code EC = readSectionTag(GCOVTagAFDOFunction))
1138     return EC;
1139 
1140   uint32_t NumFunctions;
1141   if (!GcovBuffer.readInt(NumFunctions))
1142     return sampleprof_error::truncated;
1143 
1144   InlineCallStack Stack;
1145   for (uint32_t I = 0; I < NumFunctions; ++I)
1146     if (std::error_code EC = readOneFunctionProfile(Stack, true, 0))
1147       return EC;
1148 
1149   computeSummary();
1150   return sampleprof_error::success;
1151 }
1152 
1153 std::error_code SampleProfileReaderGCC::readOneFunctionProfile(
1154     const InlineCallStack &InlineStack, bool Update, uint32_t Offset) {
1155   uint64_t HeadCount = 0;
1156   if (InlineStack.size() == 0)
1157     if (!GcovBuffer.readInt64(HeadCount))
1158       return sampleprof_error::truncated;
1159 
1160   uint32_t NameIdx;
1161   if (!GcovBuffer.readInt(NameIdx))
1162     return sampleprof_error::truncated;
1163 
1164   StringRef Name(Names[NameIdx]);
1165 
1166   uint32_t NumPosCounts;
1167   if (!GcovBuffer.readInt(NumPosCounts))
1168     return sampleprof_error::truncated;
1169 
1170   uint32_t NumCallsites;
1171   if (!GcovBuffer.readInt(NumCallsites))
1172     return sampleprof_error::truncated;
1173 
1174   FunctionSamples *FProfile = nullptr;
1175   if (InlineStack.size() == 0) {
1176     // If this is a top function that we have already processed, do not
1177     // update its profile again.  This happens in the presence of
1178     // function aliases.  Since these aliases share the same function
1179     // body, there will be identical replicated profiles for the
1180     // original function.  In this case, we simply not bother updating
1181     // the profile of the original function.
1182     FProfile = &Profiles[Name];
1183     FProfile->addHeadSamples(HeadCount);
1184     if (FProfile->getTotalSamples() > 0)
1185       Update = false;
1186   } else {
1187     // Otherwise, we are reading an inlined instance. The top of the
1188     // inline stack contains the profile of the caller. Insert this
1189     // callee in the caller's CallsiteMap.
1190     FunctionSamples *CallerProfile = InlineStack.front();
1191     uint32_t LineOffset = Offset >> 16;
1192     uint32_t Discriminator = Offset & 0xffff;
1193     FProfile = &CallerProfile->functionSamplesAt(
1194         LineLocation(LineOffset, Discriminator))[std::string(Name)];
1195   }
1196   FProfile->setName(Name);
1197 
1198   for (uint32_t I = 0; I < NumPosCounts; ++I) {
1199     uint32_t Offset;
1200     if (!GcovBuffer.readInt(Offset))
1201       return sampleprof_error::truncated;
1202 
1203     uint32_t NumTargets;
1204     if (!GcovBuffer.readInt(NumTargets))
1205       return sampleprof_error::truncated;
1206 
1207     uint64_t Count;
1208     if (!GcovBuffer.readInt64(Count))
1209       return sampleprof_error::truncated;
1210 
1211     // The line location is encoded in the offset as:
1212     //   high 16 bits: line offset to the start of the function.
1213     //   low 16 bits: discriminator.
1214     uint32_t LineOffset = Offset >> 16;
1215     uint32_t Discriminator = Offset & 0xffff;
1216 
1217     InlineCallStack NewStack;
1218     NewStack.push_back(FProfile);
1219     NewStack.insert(NewStack.end(), InlineStack.begin(), InlineStack.end());
1220     if (Update) {
1221       // Walk up the inline stack, adding the samples on this line to
1222       // the total sample count of the callers in the chain.
1223       for (auto CallerProfile : NewStack)
1224         CallerProfile->addTotalSamples(Count);
1225 
1226       // Update the body samples for the current profile.
1227       FProfile->addBodySamples(LineOffset, Discriminator, Count);
1228     }
1229 
1230     // Process the list of functions called at an indirect call site.
1231     // These are all the targets that a function pointer (or virtual
1232     // function) resolved at runtime.
1233     for (uint32_t J = 0; J < NumTargets; J++) {
1234       uint32_t HistVal;
1235       if (!GcovBuffer.readInt(HistVal))
1236         return sampleprof_error::truncated;
1237 
1238       if (HistVal != HIST_TYPE_INDIR_CALL_TOPN)
1239         return sampleprof_error::malformed;
1240 
1241       uint64_t TargetIdx;
1242       if (!GcovBuffer.readInt64(TargetIdx))
1243         return sampleprof_error::truncated;
1244       StringRef TargetName(Names[TargetIdx]);
1245 
1246       uint64_t TargetCount;
1247       if (!GcovBuffer.readInt64(TargetCount))
1248         return sampleprof_error::truncated;
1249 
1250       if (Update)
1251         FProfile->addCalledTargetSamples(LineOffset, Discriminator,
1252                                          TargetName, TargetCount);
1253     }
1254   }
1255 
1256   // Process all the inlined callers into the current function. These
1257   // are all the callsites that were inlined into this function.
1258   for (uint32_t I = 0; I < NumCallsites; I++) {
1259     // The offset is encoded as:
1260     //   high 16 bits: line offset to the start of the function.
1261     //   low 16 bits: discriminator.
1262     uint32_t Offset;
1263     if (!GcovBuffer.readInt(Offset))
1264       return sampleprof_error::truncated;
1265     InlineCallStack NewStack;
1266     NewStack.push_back(FProfile);
1267     NewStack.insert(NewStack.end(), InlineStack.begin(), InlineStack.end());
1268     if (std::error_code EC = readOneFunctionProfile(NewStack, Update, Offset))
1269       return EC;
1270   }
1271 
1272   return sampleprof_error::success;
1273 }
1274 
1275 /// Read a GCC AutoFDO profile.
1276 ///
1277 /// This format is generated by the Linux Perf conversion tool at
1278 /// https://github.com/google/autofdo.
1279 std::error_code SampleProfileReaderGCC::readImpl() {
1280   // Read the string table.
1281   if (std::error_code EC = readNameTable())
1282     return EC;
1283 
1284   // Read the source profile.
1285   if (std::error_code EC = readFunctionProfiles())
1286     return EC;
1287 
1288   return sampleprof_error::success;
1289 }
1290 
1291 bool SampleProfileReaderGCC::hasFormat(const MemoryBuffer &Buffer) {
1292   StringRef Magic(reinterpret_cast<const char *>(Buffer.getBufferStart()));
1293   return Magic == "adcg*704";
1294 }
1295 
1296 void SampleProfileReaderItaniumRemapper::applyRemapping(LLVMContext &Ctx) {
1297   // If the reader uses MD5 to represent string, we can't remap it because
1298   // we don't know what the original function names were.
1299   if (Reader.useMD5()) {
1300     Ctx.diagnose(DiagnosticInfoSampleProfile(
1301         Reader.getBuffer()->getBufferIdentifier(),
1302         "Profile data remapping cannot be applied to profile data "
1303         "in compact format (original mangled names are not available).",
1304         DS_Warning));
1305     return;
1306   }
1307 
1308   // CSSPGO-TODO: Remapper is not yet supported.
1309   // We will need to remap the entire context string.
1310   assert(Remappings && "should be initialized while creating remapper");
1311   for (auto &Sample : Reader.getProfiles()) {
1312     DenseSet<StringRef> NamesInSample;
1313     Sample.second.findAllNames(NamesInSample);
1314     for (auto &Name : NamesInSample)
1315       if (auto Key = Remappings->insert(Name))
1316         NameMap.insert({Key, Name});
1317   }
1318 
1319   RemappingApplied = true;
1320 }
1321 
1322 Optional<StringRef>
1323 SampleProfileReaderItaniumRemapper::lookUpNameInProfile(StringRef Fname) {
1324   if (auto Key = Remappings->lookup(Fname))
1325     return NameMap.lookup(Key);
1326   return None;
1327 }
1328 
1329 /// Prepare a memory buffer for the contents of \p Filename.
1330 ///
1331 /// \returns an error code indicating the status of the buffer.
1332 static ErrorOr<std::unique_ptr<MemoryBuffer>>
1333 setupMemoryBuffer(const Twine &Filename) {
1334   auto BufferOrErr = MemoryBuffer::getFileOrSTDIN(Filename);
1335   if (std::error_code EC = BufferOrErr.getError())
1336     return EC;
1337   auto Buffer = std::move(BufferOrErr.get());
1338 
1339   // Sanity check the file.
1340   if (uint64_t(Buffer->getBufferSize()) > std::numeric_limits<uint32_t>::max())
1341     return sampleprof_error::too_large;
1342 
1343   return std::move(Buffer);
1344 }
1345 
1346 /// Create a sample profile reader based on the format of the input file.
1347 ///
1348 /// \param Filename The file to open.
1349 ///
1350 /// \param C The LLVM context to use to emit diagnostics.
1351 ///
1352 /// \param RemapFilename The file used for profile remapping.
1353 ///
1354 /// \returns an error code indicating the status of the created reader.
1355 ErrorOr<std::unique_ptr<SampleProfileReader>>
1356 SampleProfileReader::create(const std::string Filename, LLVMContext &C,
1357                             const std::string RemapFilename) {
1358   auto BufferOrError = setupMemoryBuffer(Filename);
1359   if (std::error_code EC = BufferOrError.getError())
1360     return EC;
1361   return create(BufferOrError.get(), C, RemapFilename);
1362 }
1363 
1364 /// Create a sample profile remapper from the given input, to remap the
1365 /// function names in the given profile data.
1366 ///
1367 /// \param Filename The file to open.
1368 ///
1369 /// \param Reader The profile reader the remapper is going to be applied to.
1370 ///
1371 /// \param C The LLVM context to use to emit diagnostics.
1372 ///
1373 /// \returns an error code indicating the status of the created reader.
1374 ErrorOr<std::unique_ptr<SampleProfileReaderItaniumRemapper>>
1375 SampleProfileReaderItaniumRemapper::create(const std::string Filename,
1376                                            SampleProfileReader &Reader,
1377                                            LLVMContext &C) {
1378   auto BufferOrError = setupMemoryBuffer(Filename);
1379   if (std::error_code EC = BufferOrError.getError())
1380     return EC;
1381   return create(BufferOrError.get(), Reader, C);
1382 }
1383 
1384 /// Create a sample profile remapper from the given input, to remap the
1385 /// function names in the given profile data.
1386 ///
1387 /// \param B The memory buffer to create the reader from (assumes ownership).
1388 ///
1389 /// \param C The LLVM context to use to emit diagnostics.
1390 ///
1391 /// \param Reader The profile reader the remapper is going to be applied to.
1392 ///
1393 /// \returns an error code indicating the status of the created reader.
1394 ErrorOr<std::unique_ptr<SampleProfileReaderItaniumRemapper>>
1395 SampleProfileReaderItaniumRemapper::create(std::unique_ptr<MemoryBuffer> &B,
1396                                            SampleProfileReader &Reader,
1397                                            LLVMContext &C) {
1398   auto Remappings = std::make_unique<SymbolRemappingReader>();
1399   if (Error E = Remappings->read(*B.get())) {
1400     handleAllErrors(
1401         std::move(E), [&](const SymbolRemappingParseError &ParseError) {
1402           C.diagnose(DiagnosticInfoSampleProfile(B->getBufferIdentifier(),
1403                                                  ParseError.getLineNum(),
1404                                                  ParseError.getMessage()));
1405         });
1406     return sampleprof_error::malformed;
1407   }
1408 
1409   return std::make_unique<SampleProfileReaderItaniumRemapper>(
1410       std::move(B), std::move(Remappings), Reader);
1411 }
1412 
1413 /// Create a sample profile reader based on the format of the input data.
1414 ///
1415 /// \param B The memory buffer to create the reader from (assumes ownership).
1416 ///
1417 /// \param C The LLVM context to use to emit diagnostics.
1418 ///
1419 /// \param RemapFilename The file used for profile remapping.
1420 ///
1421 /// \returns an error code indicating the status of the created reader.
1422 ErrorOr<std::unique_ptr<SampleProfileReader>>
1423 SampleProfileReader::create(std::unique_ptr<MemoryBuffer> &B, LLVMContext &C,
1424                             const std::string RemapFilename) {
1425   std::unique_ptr<SampleProfileReader> Reader;
1426   if (SampleProfileReaderRawBinary::hasFormat(*B))
1427     Reader.reset(new SampleProfileReaderRawBinary(std::move(B), C));
1428   else if (SampleProfileReaderExtBinary::hasFormat(*B))
1429     Reader.reset(new SampleProfileReaderExtBinary(std::move(B), C));
1430   else if (SampleProfileReaderCompactBinary::hasFormat(*B))
1431     Reader.reset(new SampleProfileReaderCompactBinary(std::move(B), C));
1432   else if (SampleProfileReaderGCC::hasFormat(*B))
1433     Reader.reset(new SampleProfileReaderGCC(std::move(B), C));
1434   else if (SampleProfileReaderText::hasFormat(*B))
1435     Reader.reset(new SampleProfileReaderText(std::move(B), C));
1436   else
1437     return sampleprof_error::unrecognized_format;
1438 
1439   if (!RemapFilename.empty()) {
1440     auto ReaderOrErr =
1441         SampleProfileReaderItaniumRemapper::create(RemapFilename, *Reader, C);
1442     if (std::error_code EC = ReaderOrErr.getError()) {
1443       std::string Msg = "Could not create remapper: " + EC.message();
1444       C.diagnose(DiagnosticInfoSampleProfile(RemapFilename, Msg));
1445       return EC;
1446     }
1447     Reader->Remapper = std::move(ReaderOrErr.get());
1448   }
1449 
1450   FunctionSamples::Format = Reader->getFormat();
1451   if (std::error_code EC = Reader->readHeader()) {
1452     return EC;
1453   }
1454 
1455   return std::move(Reader);
1456 }
1457 
1458 // For text and GCC file formats, we compute the summary after reading the
1459 // profile. Binary format has the profile summary in its header.
1460 void SampleProfileReader::computeSummary() {
1461   SampleProfileSummaryBuilder Builder(ProfileSummaryBuilder::DefaultCutoffs);
1462   for (const auto &I : Profiles) {
1463     const FunctionSamples &Profile = I.second;
1464     Builder.addRecord(Profile);
1465   }
1466   Summary = Builder.getSummary();
1467 }
1468