SampleProfReader.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724
  1. //===- SampleProfReader.cpp - Read LLVM sample profile data ---------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements the class that reads LLVM sample profiles. It
  11. // supports three file formats: text, binary and gcov.
  12. //
  13. // The textual representation is useful for debugging and testing purposes. The
  14. // binary representation is more compact, resulting in smaller file sizes.
  15. //
  16. // The gcov encoding is the one generated by GCC's AutoFDO profile creation
  17. // tool (https://github.com/google/autofdo)
  18. //
  19. // All three encodings can be used interchangeably as an input sample profile.
  20. //
  21. //===----------------------------------------------------------------------===//
  22. #include "llvm/ProfileData/SampleProfReader.h"
  23. #include "llvm/ADT/DenseMap.h"
  24. #include "llvm/ADT/SmallVector.h"
  25. #include "llvm/Support/Debug.h"
  26. #include "llvm/Support/ErrorOr.h"
  27. #include "llvm/Support/LEB128.h"
  28. #include "llvm/Support/LineIterator.h"
  29. #include "llvm/Support/MemoryBuffer.h"
  30. using namespace llvm::sampleprof;
  31. using namespace llvm;
  32. /// \brief Dump the function profile for \p FName.
  33. ///
  34. /// \param FName Name of the function to print.
  35. /// \param OS Stream to emit the output to.
  36. void SampleProfileReader::dumpFunctionProfile(StringRef FName,
  37. raw_ostream &OS) {
  38. OS << "Function: " << FName << ": " << Profiles[FName];
  39. }
  40. /// \brief Dump all the function profiles found on stream \p OS.
  41. void SampleProfileReader::dump(raw_ostream &OS) {
  42. for (const auto &I : Profiles)
  43. dumpFunctionProfile(I.getKey(), OS);
  44. }
  45. /// \brief Parse \p Input as function head.
  46. ///
  47. /// Parse one line of \p Input, and update function name in \p FName,
  48. /// function's total sample count in \p NumSamples, function's entry
  49. /// count in \p NumHeadSamples.
  50. ///
  51. /// \returns true if parsing is successful.
  52. static bool ParseHead(const StringRef &Input, StringRef &FName,
  53. uint64_t &NumSamples, uint64_t &NumHeadSamples) {
  54. if (Input[0] == ' ')
  55. return false;
  56. size_t n2 = Input.rfind(':');
  57. size_t n1 = Input.rfind(':', n2 - 1);
  58. FName = Input.substr(0, n1);
  59. if (Input.substr(n1 + 1, n2 - n1 - 1).getAsInteger(10, NumSamples))
  60. return false;
  61. if (Input.substr(n2 + 1).getAsInteger(10, NumHeadSamples))
  62. return false;
  63. return true;
  64. }
  65. /// \brief Returns true if line offset \p L is legal (only has 16 bits).
  66. static bool isOffsetLegal(unsigned L) {
  67. return (L & 0xffff) == L;
  68. }
  69. /// \brief Parse \p Input as line sample.
  70. ///
  71. /// \param Input input line.
  72. /// \param IsCallsite true if the line represents an inlined callsite.
  73. /// \param Depth the depth of the inline stack.
  74. /// \param NumSamples total samples of the line/inlined callsite.
  75. /// \param LineOffset line offset to the start of the function.
  76. /// \param Discriminator discriminator of the line.
  77. /// \param TargetCountMap map from indirect call target to count.
  78. ///
  79. /// returns true if parsing is successful.
  80. static bool ParseLine(const StringRef &Input, bool &IsCallsite, uint32_t &Depth,
  81. uint64_t &NumSamples, uint32_t &LineOffset,
  82. uint32_t &Discriminator, StringRef &CalleeName,
  83. DenseMap<StringRef, uint64_t> &TargetCountMap) {
  84. for (Depth = 0; Input[Depth] == ' '; Depth++)
  85. ;
  86. if (Depth == 0)
  87. return false;
  88. size_t n1 = Input.find(':');
  89. StringRef Loc = Input.substr(Depth, n1 - Depth);
  90. size_t n2 = Loc.find('.');
  91. if (n2 == StringRef::npos) {
  92. if (Loc.getAsInteger(10, LineOffset) || !isOffsetLegal(LineOffset))
  93. return false;
  94. Discriminator = 0;
  95. } else {
  96. if (Loc.substr(0, n2).getAsInteger(10, LineOffset))
  97. return false;
  98. if (Loc.substr(n2 + 1).getAsInteger(10, Discriminator))
  99. return false;
  100. }
  101. StringRef Rest = Input.substr(n1 + 2);
  102. if (Rest[0] >= '0' && Rest[0] <= '9') {
  103. IsCallsite = false;
  104. size_t n3 = Rest.find(' ');
  105. if (n3 == StringRef::npos) {
  106. if (Rest.getAsInteger(10, NumSamples))
  107. return false;
  108. } else {
  109. if (Rest.substr(0, n3).getAsInteger(10, NumSamples))
  110. return false;
  111. }
  112. while (n3 != StringRef::npos) {
  113. n3 += Rest.substr(n3).find_first_not_of(' ');
  114. Rest = Rest.substr(n3);
  115. n3 = Rest.find(' ');
  116. StringRef pair = Rest;
  117. if (n3 != StringRef::npos) {
  118. pair = Rest.substr(0, n3);
  119. }
  120. size_t n4 = pair.find(':');
  121. uint64_t count;
  122. if (pair.substr(n4 + 1).getAsInteger(10, count))
  123. return false;
  124. TargetCountMap[pair.substr(0, n4)] = count;
  125. }
  126. } else {
  127. IsCallsite = true;
  128. size_t n3 = Rest.find_last_of(':');
  129. CalleeName = Rest.substr(0, n3);
  130. if (Rest.substr(n3 + 1).getAsInteger(10, NumSamples))
  131. return false;
  132. }
  133. return true;
  134. }
  135. /// \brief Load samples from a text file.
  136. ///
  137. /// See the documentation at the top of the file for an explanation of
  138. /// the expected format.
  139. ///
  140. /// \returns true if the file was loaded successfully, false otherwise.
  141. std::error_code SampleProfileReaderText::read() {
  142. line_iterator LineIt(*Buffer, /*SkipBlanks=*/true, '#');
  143. InlineCallStack InlineStack;
  144. for (; !LineIt.is_at_eof(); ++LineIt) {
  145. if ((*LineIt)[(*LineIt).find_first_not_of(' ')] == '#')
  146. continue;
  147. // Read the header of each function.
  148. //
  149. // Note that for function identifiers we are actually expecting
  150. // mangled names, but we may not always get them. This happens when
  151. // the compiler decides not to emit the function (e.g., it was inlined
  152. // and removed). In this case, the binary will not have the linkage
  153. // name for the function, so the profiler will emit the function's
  154. // unmangled name, which may contain characters like ':' and '>' in its
  155. // name (member functions, templates, etc).
  156. //
  157. // The only requirement we place on the identifier, then, is that it
  158. // should not begin with a number.
  159. if ((*LineIt)[0] != ' ') {
  160. uint64_t NumSamples, NumHeadSamples;
  161. StringRef FName;
  162. if (!ParseHead(*LineIt, FName, NumSamples, NumHeadSamples)) {
  163. reportError(LineIt.line_number(),
  164. "Expected 'mangled_name:NUM:NUM', found " + *LineIt);
  165. return sampleprof_error::malformed;
  166. }
  167. Profiles[FName] = FunctionSamples();
  168. FunctionSamples &FProfile = Profiles[FName];
  169. FProfile.addTotalSamples(NumSamples);
  170. FProfile.addHeadSamples(NumHeadSamples);
  171. InlineStack.clear();
  172. InlineStack.push_back(&FProfile);
  173. } else {
  174. uint64_t NumSamples;
  175. StringRef FName;
  176. DenseMap<StringRef, uint64_t> TargetCountMap;
  177. bool IsCallsite;
  178. uint32_t Depth, LineOffset, Discriminator;
  179. if (!ParseLine(*LineIt, IsCallsite, Depth, NumSamples, LineOffset,
  180. Discriminator, FName, TargetCountMap)) {
  181. reportError(LineIt.line_number(),
  182. "Expected 'NUM[.NUM]: NUM[ mangled_name:NUM]*', found " +
  183. *LineIt);
  184. return sampleprof_error::malformed;
  185. }
  186. if (IsCallsite) {
  187. while (InlineStack.size() > Depth) {
  188. InlineStack.pop_back();
  189. }
  190. FunctionSamples &FSamples = InlineStack.back()->functionSamplesAt(
  191. CallsiteLocation(LineOffset, Discriminator, FName));
  192. FSamples.addTotalSamples(NumSamples);
  193. InlineStack.push_back(&FSamples);
  194. } else {
  195. while (InlineStack.size() > Depth) {
  196. InlineStack.pop_back();
  197. }
  198. FunctionSamples &FProfile = *InlineStack.back();
  199. for (const auto &name_count : TargetCountMap) {
  200. FProfile.addCalledTargetSamples(LineOffset, Discriminator,
  201. name_count.first, name_count.second);
  202. }
  203. FProfile.addBodySamples(LineOffset, Discriminator, NumSamples);
  204. }
  205. }
  206. }
  207. return sampleprof_error::success;
  208. }
  209. bool SampleProfileReaderText::hasFormat(const MemoryBuffer &Buffer) {
  210. bool result = false;
  211. // Check that the first non-comment line is a valid function header.
  212. line_iterator LineIt(Buffer, /*SkipBlanks=*/true, '#');
  213. if (!LineIt.is_at_eof()) {
  214. if ((*LineIt)[0] != ' ') {
  215. uint64_t NumSamples, NumHeadSamples;
  216. StringRef FName;
  217. result = ParseHead(*LineIt, FName, NumSamples, NumHeadSamples);
  218. }
  219. }
  220. return result;
  221. }
  222. template <typename T> ErrorOr<T> SampleProfileReaderBinary::readNumber() {
  223. unsigned NumBytesRead = 0;
  224. std::error_code EC;
  225. uint64_t Val = decodeULEB128(Data, &NumBytesRead);
  226. if (Val > std::numeric_limits<T>::max())
  227. EC = sampleprof_error::malformed;
  228. else if (Data + NumBytesRead > End)
  229. EC = sampleprof_error::truncated;
  230. else
  231. EC = sampleprof_error::success;
  232. if (EC) {
  233. reportError(0, EC.message());
  234. return EC;
  235. }
  236. Data += NumBytesRead;
  237. return static_cast<T>(Val);
  238. }
  239. ErrorOr<StringRef> SampleProfileReaderBinary::readString() {
  240. std::error_code EC;
  241. StringRef Str(reinterpret_cast<const char *>(Data));
  242. if (Data + Str.size() + 1 > End) {
  243. EC = sampleprof_error::truncated;
  244. reportError(0, EC.message());
  245. return EC;
  246. }
  247. Data += Str.size() + 1;
  248. return Str;
  249. }
  250. ErrorOr<StringRef> SampleProfileReaderBinary::readStringFromTable() {
  251. std::error_code EC;
  252. auto Idx = readNumber<uint32_t>();
  253. if (std::error_code EC = Idx.getError())
  254. return EC;
  255. if (*Idx >= NameTable.size())
  256. return sampleprof_error::truncated_name_table;
  257. return NameTable[*Idx];
  258. }
  259. std::error_code
  260. SampleProfileReaderBinary::readProfile(FunctionSamples &FProfile) {
  261. auto NumSamples = readNumber<uint64_t>();
  262. if (std::error_code EC = NumSamples.getError())
  263. return EC;
  264. FProfile.addTotalSamples(*NumSamples);
  265. // Read the samples in the body.
  266. auto NumRecords = readNumber<uint32_t>();
  267. if (std::error_code EC = NumRecords.getError())
  268. return EC;
  269. for (uint32_t I = 0; I < *NumRecords; ++I) {
  270. auto LineOffset = readNumber<uint64_t>();
  271. if (std::error_code EC = LineOffset.getError())
  272. return EC;
  273. if (!isOffsetLegal(*LineOffset)) {
  274. return std::error_code();
  275. }
  276. auto Discriminator = readNumber<uint64_t>();
  277. if (std::error_code EC = Discriminator.getError())
  278. return EC;
  279. auto NumSamples = readNumber<uint64_t>();
  280. if (std::error_code EC = NumSamples.getError())
  281. return EC;
  282. auto NumCalls = readNumber<uint32_t>();
  283. if (std::error_code EC = NumCalls.getError())
  284. return EC;
  285. for (uint32_t J = 0; J < *NumCalls; ++J) {
  286. auto CalledFunction(readStringFromTable());
  287. if (std::error_code EC = CalledFunction.getError())
  288. return EC;
  289. auto CalledFunctionSamples = readNumber<uint64_t>();
  290. if (std::error_code EC = CalledFunctionSamples.getError())
  291. return EC;
  292. FProfile.addCalledTargetSamples(*LineOffset, *Discriminator,
  293. *CalledFunction, *CalledFunctionSamples);
  294. }
  295. FProfile.addBodySamples(*LineOffset, *Discriminator, *NumSamples);
  296. }
  297. // Read all the samples for inlined function calls.
  298. auto NumCallsites = readNumber<uint32_t>();
  299. if (std::error_code EC = NumCallsites.getError())
  300. return EC;
  301. for (uint32_t J = 0; J < *NumCallsites; ++J) {
  302. auto LineOffset = readNumber<uint64_t>();
  303. if (std::error_code EC = LineOffset.getError())
  304. return EC;
  305. auto Discriminator = readNumber<uint64_t>();
  306. if (std::error_code EC = Discriminator.getError())
  307. return EC;
  308. auto FName(readStringFromTable());
  309. if (std::error_code EC = FName.getError())
  310. return EC;
  311. FunctionSamples &CalleeProfile = FProfile.functionSamplesAt(
  312. CallsiteLocation(*LineOffset, *Discriminator, *FName));
  313. if (std::error_code EC = readProfile(CalleeProfile))
  314. return EC;
  315. }
  316. return sampleprof_error::success;
  317. }
  318. std::error_code SampleProfileReaderBinary::read() {
  319. while (!at_eof()) {
  320. auto NumHeadSamples = readNumber<uint64_t>();
  321. if (std::error_code EC = NumHeadSamples.getError())
  322. return EC;
  323. auto FName(readStringFromTable());
  324. if (std::error_code EC = FName.getError())
  325. return EC;
  326. Profiles[*FName] = FunctionSamples();
  327. FunctionSamples &FProfile = Profiles[*FName];
  328. FProfile.addHeadSamples(*NumHeadSamples);
  329. if (std::error_code EC = readProfile(FProfile))
  330. return EC;
  331. }
  332. return sampleprof_error::success;
  333. }
  334. std::error_code SampleProfileReaderBinary::readHeader() {
  335. Data = reinterpret_cast<const uint8_t *>(Buffer->getBufferStart());
  336. End = Data + Buffer->getBufferSize();
  337. // Read and check the magic identifier.
  338. auto Magic = readNumber<uint64_t>();
  339. if (std::error_code EC = Magic.getError())
  340. return EC;
  341. else if (*Magic != SPMagic())
  342. return sampleprof_error::bad_magic;
  343. // Read the version number.
  344. auto Version = readNumber<uint64_t>();
  345. if (std::error_code EC = Version.getError())
  346. return EC;
  347. else if (*Version != SPVersion())
  348. return sampleprof_error::unsupported_version;
  349. // Read the name table.
  350. auto Size = readNumber<uint32_t>();
  351. if (std::error_code EC = Size.getError())
  352. return EC;
  353. NameTable.reserve(*Size);
  354. for (uint32_t I = 0; I < *Size; ++I) {
  355. auto Name(readString());
  356. if (std::error_code EC = Name.getError())
  357. return EC;
  358. NameTable.push_back(*Name);
  359. }
  360. return sampleprof_error::success;
  361. }
  362. bool SampleProfileReaderBinary::hasFormat(const MemoryBuffer &Buffer) {
  363. const uint8_t *Data =
  364. reinterpret_cast<const uint8_t *>(Buffer.getBufferStart());
  365. uint64_t Magic = decodeULEB128(Data);
  366. return Magic == SPMagic();
  367. }
  368. std::error_code SampleProfileReaderGCC::skipNextWord() {
  369. uint32_t dummy;
  370. if (!GcovBuffer.readInt(dummy))
  371. return sampleprof_error::truncated;
  372. return sampleprof_error::success;
  373. }
  374. template <typename T> ErrorOr<T> SampleProfileReaderGCC::readNumber() {
  375. if (sizeof(T) <= sizeof(uint32_t)) {
  376. uint32_t Val;
  377. if (GcovBuffer.readInt(Val) && Val <= std::numeric_limits<T>::max())
  378. return static_cast<T>(Val);
  379. } else if (sizeof(T) <= sizeof(uint64_t)) {
  380. uint64_t Val;
  381. if (GcovBuffer.readInt64(Val) && Val <= std::numeric_limits<T>::max())
  382. return static_cast<T>(Val);
  383. }
  384. std::error_code EC = sampleprof_error::malformed;
  385. reportError(0, EC.message());
  386. return EC;
  387. }
  388. ErrorOr<StringRef> SampleProfileReaderGCC::readString() {
  389. StringRef Str;
  390. if (!GcovBuffer.readString(Str))
  391. return sampleprof_error::truncated;
  392. return Str;
  393. }
  394. std::error_code SampleProfileReaderGCC::readHeader() {
  395. // Read the magic identifier.
  396. if (!GcovBuffer.readGCDAFormat())
  397. return sampleprof_error::unrecognized_format;
  398. // Read the version number. Note - the GCC reader does not validate this
  399. // version, but the profile creator generates v704.
  400. GCOV::GCOVVersion version;
  401. if (!GcovBuffer.readGCOVVersion(version))
  402. return sampleprof_error::unrecognized_format;
  403. if (version != GCOV::V704)
  404. return sampleprof_error::unsupported_version;
  405. // Skip the empty integer.
  406. if (std::error_code EC = skipNextWord())
  407. return EC;
  408. return sampleprof_error::success;
  409. }
  410. std::error_code SampleProfileReaderGCC::readSectionTag(uint32_t Expected) {
  411. uint32_t Tag;
  412. if (!GcovBuffer.readInt(Tag))
  413. return sampleprof_error::truncated;
  414. if (Tag != Expected)
  415. return sampleprof_error::malformed;
  416. if (std::error_code EC = skipNextWord())
  417. return EC;
  418. return sampleprof_error::success;
  419. }
  420. std::error_code SampleProfileReaderGCC::readNameTable() {
  421. if (std::error_code EC = readSectionTag(GCOVTagAFDOFileNames))
  422. return EC;
  423. uint32_t Size;
  424. if (!GcovBuffer.readInt(Size))
  425. return sampleprof_error::truncated;
  426. for (uint32_t I = 0; I < Size; ++I) {
  427. StringRef Str;
  428. if (!GcovBuffer.readString(Str))
  429. return sampleprof_error::truncated;
  430. Names.push_back(Str);
  431. }
  432. return sampleprof_error::success;
  433. }
  434. std::error_code SampleProfileReaderGCC::readFunctionProfiles() {
  435. if (std::error_code EC = readSectionTag(GCOVTagAFDOFunction))
  436. return EC;
  437. uint32_t NumFunctions;
  438. if (!GcovBuffer.readInt(NumFunctions))
  439. return sampleprof_error::truncated;
  440. InlineCallStack Stack;
  441. for (uint32_t I = 0; I < NumFunctions; ++I)
  442. if (std::error_code EC = readOneFunctionProfile(Stack, true, 0))
  443. return EC;
  444. return sampleprof_error::success;
  445. }
  446. std::error_code SampleProfileReaderGCC::readOneFunctionProfile(
  447. const InlineCallStack &InlineStack, bool Update, uint32_t Offset) {
  448. uint64_t HeadCount = 0;
  449. if (InlineStack.size() == 0)
  450. if (!GcovBuffer.readInt64(HeadCount))
  451. return sampleprof_error::truncated;
  452. uint32_t NameIdx;
  453. if (!GcovBuffer.readInt(NameIdx))
  454. return sampleprof_error::truncated;
  455. StringRef Name(Names[NameIdx]);
  456. uint32_t NumPosCounts;
  457. if (!GcovBuffer.readInt(NumPosCounts))
  458. return sampleprof_error::truncated;
  459. uint32_t NumCallsites;
  460. if (!GcovBuffer.readInt(NumCallsites))
  461. return sampleprof_error::truncated;
  462. FunctionSamples *FProfile = nullptr;
  463. if (InlineStack.size() == 0) {
  464. // If this is a top function that we have already processed, do not
  465. // update its profile again. This happens in the presence of
  466. // function aliases. Since these aliases share the same function
  467. // body, there will be identical replicated profiles for the
  468. // original function. In this case, we simply not bother updating
  469. // the profile of the original function.
  470. FProfile = &Profiles[Name];
  471. FProfile->addHeadSamples(HeadCount);
  472. if (FProfile->getTotalSamples() > 0)
  473. Update = false;
  474. } else {
  475. // Otherwise, we are reading an inlined instance. The top of the
  476. // inline stack contains the profile of the caller. Insert this
  477. // callee in the caller's CallsiteMap.
  478. FunctionSamples *CallerProfile = InlineStack.front();
  479. uint32_t LineOffset = Offset >> 16;
  480. uint32_t Discriminator = Offset & 0xffff;
  481. FProfile = &CallerProfile->functionSamplesAt(
  482. CallsiteLocation(LineOffset, Discriminator, Name));
  483. }
  484. for (uint32_t I = 0; I < NumPosCounts; ++I) {
  485. uint32_t Offset;
  486. if (!GcovBuffer.readInt(Offset))
  487. return sampleprof_error::truncated;
  488. uint32_t NumTargets;
  489. if (!GcovBuffer.readInt(NumTargets))
  490. return sampleprof_error::truncated;
  491. uint64_t Count;
  492. if (!GcovBuffer.readInt64(Count))
  493. return sampleprof_error::truncated;
  494. // The line location is encoded in the offset as:
  495. // high 16 bits: line offset to the start of the function.
  496. // low 16 bits: discriminator.
  497. uint32_t LineOffset = Offset >> 16;
  498. uint32_t Discriminator = Offset & 0xffff;
  499. InlineCallStack NewStack;
  500. NewStack.push_back(FProfile);
  501. NewStack.insert(NewStack.end(), InlineStack.begin(), InlineStack.end());
  502. if (Update) {
  503. // Walk up the inline stack, adding the samples on this line to
  504. // the total sample count of the callers in the chain.
  505. for (auto CallerProfile : NewStack)
  506. CallerProfile->addTotalSamples(Count);
  507. // Update the body samples for the current profile.
  508. FProfile->addBodySamples(LineOffset, Discriminator, Count);
  509. }
  510. // Process the list of functions called at an indirect call site.
  511. // These are all the targets that a function pointer (or virtual
  512. // function) resolved at runtime.
  513. for (uint32_t J = 0; J < NumTargets; J++) {
  514. uint32_t HistVal;
  515. if (!GcovBuffer.readInt(HistVal))
  516. return sampleprof_error::truncated;
  517. if (HistVal != HIST_TYPE_INDIR_CALL_TOPN)
  518. return sampleprof_error::malformed;
  519. uint64_t TargetIdx;
  520. if (!GcovBuffer.readInt64(TargetIdx))
  521. return sampleprof_error::truncated;
  522. StringRef TargetName(Names[TargetIdx]);
  523. uint64_t TargetCount;
  524. if (!GcovBuffer.readInt64(TargetCount))
  525. return sampleprof_error::truncated;
  526. if (Update) {
  527. FunctionSamples &TargetProfile = Profiles[TargetName];
  528. TargetProfile.addCalledTargetSamples(LineOffset, Discriminator,
  529. TargetName, TargetCount);
  530. }
  531. }
  532. }
  533. // Process all the inlined callers into the current function. These
  534. // are all the callsites that were inlined into this function.
  535. for (uint32_t I = 0; I < NumCallsites; I++) {
  536. // The offset is encoded as:
  537. // high 16 bits: line offset to the start of the function.
  538. // low 16 bits: discriminator.
  539. uint32_t Offset;
  540. if (!GcovBuffer.readInt(Offset))
  541. return sampleprof_error::truncated;
  542. InlineCallStack NewStack;
  543. NewStack.push_back(FProfile);
  544. NewStack.insert(NewStack.end(), InlineStack.begin(), InlineStack.end());
  545. if (std::error_code EC = readOneFunctionProfile(NewStack, Update, Offset))
  546. return EC;
  547. }
  548. return sampleprof_error::success;
  549. }
  550. /// \brief Read a GCC AutoFDO profile.
  551. ///
  552. /// This format is generated by the Linux Perf conversion tool at
  553. /// https://github.com/google/autofdo.
  554. std::error_code SampleProfileReaderGCC::read() {
  555. // Read the string table.
  556. if (std::error_code EC = readNameTable())
  557. return EC;
  558. // Read the source profile.
  559. if (std::error_code EC = readFunctionProfiles())
  560. return EC;
  561. return sampleprof_error::success;
  562. }
  563. bool SampleProfileReaderGCC::hasFormat(const MemoryBuffer &Buffer) {
  564. StringRef Magic(reinterpret_cast<const char *>(Buffer.getBufferStart()));
  565. return Magic == "adcg*704";
  566. }
  567. /// \brief Prepare a memory buffer for the contents of \p Filename.
  568. ///
  569. /// \returns an error code indicating the status of the buffer.
  570. static ErrorOr<std::unique_ptr<MemoryBuffer>>
  571. setupMemoryBuffer(std::string Filename) {
  572. auto BufferOrErr = MemoryBuffer::getFileOrSTDIN(Filename);
  573. if (std::error_code EC = BufferOrErr.getError())
  574. return EC;
  575. auto Buffer = std::move(BufferOrErr.get());
  576. // Sanity check the file.
  577. if (Buffer->getBufferSize() > std::numeric_limits<uint32_t>::max())
  578. return sampleprof_error::too_large;
  579. return std::move(Buffer);
  580. }
  581. /// \brief Create a sample profile reader based on the format of the input file.
  582. ///
  583. /// \param Filename The file to open.
  584. ///
  585. /// \param Reader The reader to instantiate according to \p Filename's format.
  586. ///
  587. /// \param C The LLVM context to use to emit diagnostics.
  588. ///
  589. /// \returns an error code indicating the status of the created reader.
  590. ErrorOr<std::unique_ptr<SampleProfileReader>>
  591. SampleProfileReader::create(StringRef Filename, LLVMContext &C) {
  592. auto BufferOrError = setupMemoryBuffer(Filename);
  593. if (std::error_code EC = BufferOrError.getError())
  594. return EC;
  595. return create(BufferOrError.get(), C);
  596. }
  597. /// \brief Create a sample profile reader based on the format of the input data.
  598. ///
  599. /// \param B The memory buffer to create the reader from (assumes ownership).
  600. ///
  601. /// \param Reader The reader to instantiate according to \p Filename's format.
  602. ///
  603. /// \param C The LLVM context to use to emit diagnostics.
  604. ///
  605. /// \returns an error code indicating the status of the created reader.
  606. ErrorOr<std::unique_ptr<SampleProfileReader>>
  607. SampleProfileReader::create(std::unique_ptr<MemoryBuffer> &B, LLVMContext &C) {
  608. std::unique_ptr<SampleProfileReader> Reader;
  609. if (SampleProfileReaderBinary::hasFormat(*B))
  610. Reader.reset(new SampleProfileReaderBinary(std::move(B), C));
  611. else if (SampleProfileReaderGCC::hasFormat(*B))
  612. Reader.reset(new SampleProfileReaderGCC(std::move(B), C));
  613. else if (SampleProfileReaderText::hasFormat(*B))
  614. Reader.reset(new SampleProfileReaderText(std::move(B), C));
  615. else
  616. return sampleprof_error::unrecognized_format;
  617. if (std::error_code EC = Reader->readHeader())
  618. return EC;
  619. return std::move(Reader);
  620. }