InstrProfWriter.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515
  1. //===- InstrProfWriter.cpp - Instrumented profiling writer ----------------===//
  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 contains support for writing profiling data for clang's
  10. // instrumentation based PGO and coverage.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/ProfileData/InstrProfWriter.h"
  14. #include "llvm/ADT/STLExtras.h"
  15. #include "llvm/ADT/StringRef.h"
  16. #include "llvm/IR/ProfileSummary.h"
  17. #include "llvm/ProfileData/InstrProf.h"
  18. #include "llvm/ProfileData/ProfileCommon.h"
  19. #include "llvm/Support/Endian.h"
  20. #include "llvm/Support/EndianStream.h"
  21. #include "llvm/Support/Error.h"
  22. #include "llvm/Support/MemoryBuffer.h"
  23. #include "llvm/Support/OnDiskHashTable.h"
  24. #include "llvm/Support/raw_ostream.h"
  25. #include <algorithm>
  26. #include <cstdint>
  27. #include <memory>
  28. #include <string>
  29. #include <tuple>
  30. #include <utility>
  31. #include <vector>
  32. using namespace llvm;
  33. extern cl::opt<bool> DebugInfoCorrelate;
  34. // A struct to define how the data stream should be patched. For Indexed
  35. // profiling, only uint64_t data type is needed.
  36. struct PatchItem {
  37. uint64_t Pos; // Where to patch.
  38. uint64_t *D; // Pointer to an array of source data.
  39. int N; // Number of elements in \c D array.
  40. };
  41. namespace llvm {
  42. // A wrapper class to abstract writer stream with support of bytes
  43. // back patching.
  44. class ProfOStream {
  45. public:
  46. ProfOStream(raw_fd_ostream &FD)
  47. : IsFDOStream(true), OS(FD), LE(FD, support::little) {}
  48. ProfOStream(raw_string_ostream &STR)
  49. : IsFDOStream(false), OS(STR), LE(STR, support::little) {}
  50. uint64_t tell() { return OS.tell(); }
  51. void write(uint64_t V) { LE.write<uint64_t>(V); }
  52. // \c patch can only be called when all data is written and flushed.
  53. // For raw_string_ostream, the patch is done on the target string
  54. // directly and it won't be reflected in the stream's internal buffer.
  55. void patch(PatchItem *P, int NItems) {
  56. using namespace support;
  57. if (IsFDOStream) {
  58. raw_fd_ostream &FDOStream = static_cast<raw_fd_ostream &>(OS);
  59. for (int K = 0; K < NItems; K++) {
  60. FDOStream.seek(P[K].Pos);
  61. for (int I = 0; I < P[K].N; I++)
  62. write(P[K].D[I]);
  63. }
  64. } else {
  65. raw_string_ostream &SOStream = static_cast<raw_string_ostream &>(OS);
  66. std::string &Data = SOStream.str(); // with flush
  67. for (int K = 0; K < NItems; K++) {
  68. for (int I = 0; I < P[K].N; I++) {
  69. uint64_t Bytes = endian::byte_swap<uint64_t, little>(P[K].D[I]);
  70. Data.replace(P[K].Pos + I * sizeof(uint64_t), sizeof(uint64_t),
  71. (const char *)&Bytes, sizeof(uint64_t));
  72. }
  73. }
  74. }
  75. }
  76. // If \c OS is an instance of \c raw_fd_ostream, this field will be
  77. // true. Otherwise, \c OS will be an raw_string_ostream.
  78. bool IsFDOStream;
  79. raw_ostream &OS;
  80. support::endian::Writer LE;
  81. };
  82. class InstrProfRecordWriterTrait {
  83. public:
  84. using key_type = StringRef;
  85. using key_type_ref = StringRef;
  86. using data_type = const InstrProfWriter::ProfilingData *const;
  87. using data_type_ref = const InstrProfWriter::ProfilingData *const;
  88. using hash_value_type = uint64_t;
  89. using offset_type = uint64_t;
  90. support::endianness ValueProfDataEndianness = support::little;
  91. InstrProfSummaryBuilder *SummaryBuilder;
  92. InstrProfSummaryBuilder *CSSummaryBuilder;
  93. InstrProfRecordWriterTrait() = default;
  94. static hash_value_type ComputeHash(key_type_ref K) {
  95. return IndexedInstrProf::ComputeHash(K);
  96. }
  97. static std::pair<offset_type, offset_type>
  98. EmitKeyDataLength(raw_ostream &Out, key_type_ref K, data_type_ref V) {
  99. using namespace support;
  100. endian::Writer LE(Out, little);
  101. offset_type N = K.size();
  102. LE.write<offset_type>(N);
  103. offset_type M = 0;
  104. for (const auto &ProfileData : *V) {
  105. const InstrProfRecord &ProfRecord = ProfileData.second;
  106. M += sizeof(uint64_t); // The function hash
  107. M += sizeof(uint64_t); // The size of the Counts vector
  108. M += ProfRecord.Counts.size() * sizeof(uint64_t);
  109. // Value data
  110. M += ValueProfData::getSize(ProfileData.second);
  111. }
  112. LE.write<offset_type>(M);
  113. return std::make_pair(N, M);
  114. }
  115. void EmitKey(raw_ostream &Out, key_type_ref K, offset_type N) {
  116. Out.write(K.data(), N);
  117. }
  118. void EmitData(raw_ostream &Out, key_type_ref, data_type_ref V, offset_type) {
  119. using namespace support;
  120. endian::Writer LE(Out, little);
  121. for (const auto &ProfileData : *V) {
  122. const InstrProfRecord &ProfRecord = ProfileData.second;
  123. if (NamedInstrProfRecord::hasCSFlagInHash(ProfileData.first))
  124. CSSummaryBuilder->addRecord(ProfRecord);
  125. else
  126. SummaryBuilder->addRecord(ProfRecord);
  127. LE.write<uint64_t>(ProfileData.first); // Function hash
  128. LE.write<uint64_t>(ProfRecord.Counts.size());
  129. for (uint64_t I : ProfRecord.Counts)
  130. LE.write<uint64_t>(I);
  131. // Write value data
  132. std::unique_ptr<ValueProfData> VDataPtr =
  133. ValueProfData::serializeFrom(ProfileData.second);
  134. uint32_t S = VDataPtr->getSize();
  135. VDataPtr->swapBytesFromHost(ValueProfDataEndianness);
  136. Out.write((const char *)VDataPtr.get(), S);
  137. }
  138. }
  139. };
  140. } // end namespace llvm
  141. InstrProfWriter::InstrProfWriter(bool Sparse)
  142. : Sparse(Sparse), InfoObj(new InstrProfRecordWriterTrait()) {}
  143. InstrProfWriter::~InstrProfWriter() { delete InfoObj; }
  144. // Internal interface for testing purpose only.
  145. void InstrProfWriter::setValueProfDataEndianness(
  146. support::endianness Endianness) {
  147. InfoObj->ValueProfDataEndianness = Endianness;
  148. }
  149. void InstrProfWriter::setOutputSparse(bool Sparse) {
  150. this->Sparse = Sparse;
  151. }
  152. void InstrProfWriter::addRecord(NamedInstrProfRecord &&I, uint64_t Weight,
  153. function_ref<void(Error)> Warn) {
  154. auto Name = I.Name;
  155. auto Hash = I.Hash;
  156. addRecord(Name, Hash, std::move(I), Weight, Warn);
  157. }
  158. void InstrProfWriter::overlapRecord(NamedInstrProfRecord &&Other,
  159. OverlapStats &Overlap,
  160. OverlapStats &FuncLevelOverlap,
  161. const OverlapFuncFilters &FuncFilter) {
  162. auto Name = Other.Name;
  163. auto Hash = Other.Hash;
  164. Other.accumulateCounts(FuncLevelOverlap.Test);
  165. if (FunctionData.find(Name) == FunctionData.end()) {
  166. Overlap.addOneUnique(FuncLevelOverlap.Test);
  167. return;
  168. }
  169. if (FuncLevelOverlap.Test.CountSum < 1.0f) {
  170. Overlap.Overlap.NumEntries += 1;
  171. return;
  172. }
  173. auto &ProfileDataMap = FunctionData[Name];
  174. bool NewFunc;
  175. ProfilingData::iterator Where;
  176. std::tie(Where, NewFunc) =
  177. ProfileDataMap.insert(std::make_pair(Hash, InstrProfRecord()));
  178. if (NewFunc) {
  179. Overlap.addOneMismatch(FuncLevelOverlap.Test);
  180. return;
  181. }
  182. InstrProfRecord &Dest = Where->second;
  183. uint64_t ValueCutoff = FuncFilter.ValueCutoff;
  184. if (!FuncFilter.NameFilter.empty() && Name.contains(FuncFilter.NameFilter))
  185. ValueCutoff = 0;
  186. Dest.overlap(Other, Overlap, FuncLevelOverlap, ValueCutoff);
  187. }
  188. void InstrProfWriter::addRecord(StringRef Name, uint64_t Hash,
  189. InstrProfRecord &&I, uint64_t Weight,
  190. function_ref<void(Error)> Warn) {
  191. auto &ProfileDataMap = FunctionData[Name];
  192. bool NewFunc;
  193. ProfilingData::iterator Where;
  194. std::tie(Where, NewFunc) =
  195. ProfileDataMap.insert(std::make_pair(Hash, InstrProfRecord()));
  196. InstrProfRecord &Dest = Where->second;
  197. auto MapWarn = [&](instrprof_error E) {
  198. Warn(make_error<InstrProfError>(E));
  199. };
  200. if (NewFunc) {
  201. // We've never seen a function with this name and hash, add it.
  202. Dest = std::move(I);
  203. if (Weight > 1)
  204. Dest.scale(Weight, 1, MapWarn);
  205. } else {
  206. // We're updating a function we've seen before.
  207. Dest.merge(I, Weight, MapWarn);
  208. }
  209. Dest.sortValueData();
  210. }
  211. void InstrProfWriter::mergeRecordsFromWriter(InstrProfWriter &&IPW,
  212. function_ref<void(Error)> Warn) {
  213. for (auto &I : IPW.FunctionData)
  214. for (auto &Func : I.getValue())
  215. addRecord(I.getKey(), Func.first, std::move(Func.second), 1, Warn);
  216. }
  217. bool InstrProfWriter::shouldEncodeData(const ProfilingData &PD) {
  218. if (!Sparse)
  219. return true;
  220. for (const auto &Func : PD) {
  221. const InstrProfRecord &IPR = Func.second;
  222. if (llvm::any_of(IPR.Counts, [](uint64_t Count) { return Count > 0; }))
  223. return true;
  224. }
  225. return false;
  226. }
  227. static void setSummary(IndexedInstrProf::Summary *TheSummary,
  228. ProfileSummary &PS) {
  229. using namespace IndexedInstrProf;
  230. const std::vector<ProfileSummaryEntry> &Res = PS.getDetailedSummary();
  231. TheSummary->NumSummaryFields = Summary::NumKinds;
  232. TheSummary->NumCutoffEntries = Res.size();
  233. TheSummary->set(Summary::MaxFunctionCount, PS.getMaxFunctionCount());
  234. TheSummary->set(Summary::MaxBlockCount, PS.getMaxCount());
  235. TheSummary->set(Summary::MaxInternalBlockCount, PS.getMaxInternalCount());
  236. TheSummary->set(Summary::TotalBlockCount, PS.getTotalCount());
  237. TheSummary->set(Summary::TotalNumBlocks, PS.getNumCounts());
  238. TheSummary->set(Summary::TotalNumFunctions, PS.getNumFunctions());
  239. for (unsigned I = 0; I < Res.size(); I++)
  240. TheSummary->setEntry(I, Res[I]);
  241. }
  242. Error InstrProfWriter::writeImpl(ProfOStream &OS) {
  243. using namespace IndexedInstrProf;
  244. OnDiskChainedHashTableGenerator<InstrProfRecordWriterTrait> Generator;
  245. InstrProfSummaryBuilder ISB(ProfileSummaryBuilder::DefaultCutoffs);
  246. InfoObj->SummaryBuilder = &ISB;
  247. InstrProfSummaryBuilder CSISB(ProfileSummaryBuilder::DefaultCutoffs);
  248. InfoObj->CSSummaryBuilder = &CSISB;
  249. // Populate the hash table generator.
  250. for (const auto &I : FunctionData)
  251. if (shouldEncodeData(I.getValue()))
  252. Generator.insert(I.getKey(), &I.getValue());
  253. // Write the header.
  254. IndexedInstrProf::Header Header;
  255. Header.Magic = IndexedInstrProf::Magic;
  256. Header.Version = IndexedInstrProf::ProfVersion::CurrentVersion;
  257. if (static_cast<bool>(ProfileKind & InstrProfKind::IR))
  258. Header.Version |= VARIANT_MASK_IR_PROF;
  259. if (static_cast<bool>(ProfileKind & InstrProfKind::CS))
  260. Header.Version |= VARIANT_MASK_CSIR_PROF;
  261. if (static_cast<bool>(ProfileKind & InstrProfKind::BB))
  262. Header.Version |= VARIANT_MASK_INSTR_ENTRY;
  263. if (static_cast<bool>(ProfileKind & InstrProfKind::SingleByteCoverage))
  264. Header.Version |= VARIANT_MASK_BYTE_COVERAGE;
  265. if (static_cast<bool>(ProfileKind & InstrProfKind::FunctionEntryOnly))
  266. Header.Version |= VARIANT_MASK_FUNCTION_ENTRY_ONLY;
  267. Header.Unused = 0;
  268. Header.HashType = static_cast<uint64_t>(IndexedInstrProf::HashType);
  269. Header.HashOffset = 0;
  270. int N = sizeof(IndexedInstrProf::Header) / sizeof(uint64_t);
  271. // Only write out all the fields except 'HashOffset'. We need
  272. // to remember the offset of that field to allow back patching
  273. // later.
  274. for (int I = 0; I < N - 1; I++)
  275. OS.write(reinterpret_cast<uint64_t *>(&Header)[I]);
  276. // Save the location of Header.HashOffset field in \c OS.
  277. uint64_t HashTableStartFieldOffset = OS.tell();
  278. // Reserve the space for HashOffset field.
  279. OS.write(0);
  280. // Reserve space to write profile summary data.
  281. uint32_t NumEntries = ProfileSummaryBuilder::DefaultCutoffs.size();
  282. uint32_t SummarySize = Summary::getSize(Summary::NumKinds, NumEntries);
  283. // Remember the summary offset.
  284. uint64_t SummaryOffset = OS.tell();
  285. for (unsigned I = 0; I < SummarySize / sizeof(uint64_t); I++)
  286. OS.write(0);
  287. uint64_t CSSummaryOffset = 0;
  288. uint64_t CSSummarySize = 0;
  289. if (static_cast<bool>(ProfileKind & InstrProfKind::CS)) {
  290. CSSummaryOffset = OS.tell();
  291. CSSummarySize = SummarySize / sizeof(uint64_t);
  292. for (unsigned I = 0; I < CSSummarySize; I++)
  293. OS.write(0);
  294. }
  295. // Write the hash table.
  296. uint64_t HashTableStart = Generator.Emit(OS.OS, *InfoObj);
  297. // Allocate space for data to be serialized out.
  298. std::unique_ptr<IndexedInstrProf::Summary> TheSummary =
  299. IndexedInstrProf::allocSummary(SummarySize);
  300. // Compute the Summary and copy the data to the data
  301. // structure to be serialized out (to disk or buffer).
  302. std::unique_ptr<ProfileSummary> PS = ISB.getSummary();
  303. setSummary(TheSummary.get(), *PS);
  304. InfoObj->SummaryBuilder = nullptr;
  305. // For Context Sensitive summary.
  306. std::unique_ptr<IndexedInstrProf::Summary> TheCSSummary = nullptr;
  307. if (static_cast<bool>(ProfileKind & InstrProfKind::CS)) {
  308. TheCSSummary = IndexedInstrProf::allocSummary(SummarySize);
  309. std::unique_ptr<ProfileSummary> CSPS = CSISB.getSummary();
  310. setSummary(TheCSSummary.get(), *CSPS);
  311. }
  312. InfoObj->CSSummaryBuilder = nullptr;
  313. // Now do the final patch:
  314. PatchItem PatchItems[] = {
  315. // Patch the Header.HashOffset field.
  316. {HashTableStartFieldOffset, &HashTableStart, 1},
  317. // Patch the summary data.
  318. {SummaryOffset, reinterpret_cast<uint64_t *>(TheSummary.get()),
  319. (int)(SummarySize / sizeof(uint64_t))},
  320. {CSSummaryOffset, reinterpret_cast<uint64_t *>(TheCSSummary.get()),
  321. (int)CSSummarySize}};
  322. OS.patch(PatchItems, sizeof(PatchItems) / sizeof(*PatchItems));
  323. for (const auto &I : FunctionData)
  324. for (const auto &F : I.getValue())
  325. if (Error E = validateRecord(F.second))
  326. return E;
  327. return Error::success();
  328. }
  329. Error InstrProfWriter::write(raw_fd_ostream &OS) {
  330. // Write the hash table.
  331. ProfOStream POS(OS);
  332. return writeImpl(POS);
  333. }
  334. std::unique_ptr<MemoryBuffer> InstrProfWriter::writeBuffer() {
  335. std::string Data;
  336. raw_string_ostream OS(Data);
  337. ProfOStream POS(OS);
  338. // Write the hash table.
  339. if (Error E = writeImpl(POS))
  340. return nullptr;
  341. // Return this in an aligned memory buffer.
  342. return MemoryBuffer::getMemBufferCopy(Data);
  343. }
  344. static const char *ValueProfKindStr[] = {
  345. #define VALUE_PROF_KIND(Enumerator, Value, Descr) #Enumerator,
  346. #include "llvm/ProfileData/InstrProfData.inc"
  347. };
  348. Error InstrProfWriter::validateRecord(const InstrProfRecord &Func) {
  349. for (uint32_t VK = 0; VK <= IPVK_Last; VK++) {
  350. uint32_t NS = Func.getNumValueSites(VK);
  351. if (!NS)
  352. continue;
  353. for (uint32_t S = 0; S < NS; S++) {
  354. uint32_t ND = Func.getNumValueDataForSite(VK, S);
  355. std::unique_ptr<InstrProfValueData[]> VD = Func.getValueForSite(VK, S);
  356. bool WasZero = false;
  357. for (uint32_t I = 0; I < ND; I++)
  358. if ((VK != IPVK_IndirectCallTarget) && (VD[I].Value == 0)) {
  359. if (WasZero)
  360. return make_error<InstrProfError>(instrprof_error::invalid_prof);
  361. WasZero = true;
  362. }
  363. }
  364. }
  365. return Error::success();
  366. }
  367. void InstrProfWriter::writeRecordInText(StringRef Name, uint64_t Hash,
  368. const InstrProfRecord &Func,
  369. InstrProfSymtab &Symtab,
  370. raw_fd_ostream &OS) {
  371. OS << Name << "\n";
  372. OS << "# Func Hash:\n" << Hash << "\n";
  373. OS << "# Num Counters:\n" << Func.Counts.size() << "\n";
  374. OS << "# Counter Values:\n";
  375. for (uint64_t Count : Func.Counts)
  376. OS << Count << "\n";
  377. uint32_t NumValueKinds = Func.getNumValueKinds();
  378. if (!NumValueKinds) {
  379. OS << "\n";
  380. return;
  381. }
  382. OS << "# Num Value Kinds:\n" << Func.getNumValueKinds() << "\n";
  383. for (uint32_t VK = 0; VK < IPVK_Last + 1; VK++) {
  384. uint32_t NS = Func.getNumValueSites(VK);
  385. if (!NS)
  386. continue;
  387. OS << "# ValueKind = " << ValueProfKindStr[VK] << ":\n" << VK << "\n";
  388. OS << "# NumValueSites:\n" << NS << "\n";
  389. for (uint32_t S = 0; S < NS; S++) {
  390. uint32_t ND = Func.getNumValueDataForSite(VK, S);
  391. OS << ND << "\n";
  392. std::unique_ptr<InstrProfValueData[]> VD = Func.getValueForSite(VK, S);
  393. for (uint32_t I = 0; I < ND; I++) {
  394. if (VK == IPVK_IndirectCallTarget)
  395. OS << Symtab.getFuncNameOrExternalSymbol(VD[I].Value) << ":"
  396. << VD[I].Count << "\n";
  397. else
  398. OS << VD[I].Value << ":" << VD[I].Count << "\n";
  399. }
  400. }
  401. }
  402. OS << "\n";
  403. }
  404. Error InstrProfWriter::writeText(raw_fd_ostream &OS) {
  405. // Check CS first since it implies an IR level profile.
  406. if (static_cast<bool>(ProfileKind & InstrProfKind::CS))
  407. OS << "# CSIR level Instrumentation Flag\n:csir\n";
  408. else if (static_cast<bool>(ProfileKind & InstrProfKind::IR))
  409. OS << "# IR level Instrumentation Flag\n:ir\n";
  410. if (static_cast<bool>(ProfileKind & InstrProfKind::BB))
  411. OS << "# Always instrument the function entry block\n:entry_first\n";
  412. InstrProfSymtab Symtab;
  413. using FuncPair = detail::DenseMapPair<uint64_t, InstrProfRecord>;
  414. using RecordType = std::pair<StringRef, FuncPair>;
  415. SmallVector<RecordType, 4> OrderedFuncData;
  416. for (const auto &I : FunctionData) {
  417. if (shouldEncodeData(I.getValue())) {
  418. if (Error E = Symtab.addFuncName(I.getKey()))
  419. return E;
  420. for (const auto &Func : I.getValue())
  421. OrderedFuncData.push_back(std::make_pair(I.getKey(), Func));
  422. }
  423. }
  424. llvm::sort(OrderedFuncData, [](const RecordType &A, const RecordType &B) {
  425. return std::tie(A.first, A.second.first) <
  426. std::tie(B.first, B.second.first);
  427. });
  428. for (const auto &record : OrderedFuncData) {
  429. const StringRef &Name = record.first;
  430. const FuncPair &Func = record.second;
  431. writeRecordInText(Name, Func.first, Func.second, Symtab, OS);
  432. }
  433. for (const auto &record : OrderedFuncData) {
  434. const FuncPair &Func = record.second;
  435. if (Error E = validateRecord(Func.second))
  436. return E;
  437. }
  438. return Error::success();
  439. }