17330f729Sjoerg //===- InstrProfWriter.cpp - Instrumented profiling writer ----------------===//
27330f729Sjoerg //
37330f729Sjoerg // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
47330f729Sjoerg // See https://llvm.org/LICENSE.txt for license information.
57330f729Sjoerg // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
67330f729Sjoerg //
77330f729Sjoerg //===----------------------------------------------------------------------===//
87330f729Sjoerg //
97330f729Sjoerg // This file contains support for writing profiling data for clang's
107330f729Sjoerg // instrumentation based PGO and coverage.
117330f729Sjoerg //
127330f729Sjoerg //===----------------------------------------------------------------------===//
137330f729Sjoerg
147330f729Sjoerg #include "llvm/ProfileData/InstrProfWriter.h"
157330f729Sjoerg #include "llvm/ADT/STLExtras.h"
167330f729Sjoerg #include "llvm/ADT/StringRef.h"
177330f729Sjoerg #include "llvm/IR/ProfileSummary.h"
187330f729Sjoerg #include "llvm/ProfileData/InstrProf.h"
197330f729Sjoerg #include "llvm/ProfileData/ProfileCommon.h"
207330f729Sjoerg #include "llvm/Support/Endian.h"
217330f729Sjoerg #include "llvm/Support/EndianStream.h"
227330f729Sjoerg #include "llvm/Support/Error.h"
237330f729Sjoerg #include "llvm/Support/MemoryBuffer.h"
247330f729Sjoerg #include "llvm/Support/OnDiskHashTable.h"
257330f729Sjoerg #include "llvm/Support/raw_ostream.h"
267330f729Sjoerg #include <algorithm>
277330f729Sjoerg #include <cstdint>
287330f729Sjoerg #include <memory>
297330f729Sjoerg #include <string>
307330f729Sjoerg #include <tuple>
317330f729Sjoerg #include <utility>
327330f729Sjoerg #include <vector>
337330f729Sjoerg
347330f729Sjoerg using namespace llvm;
357330f729Sjoerg
367330f729Sjoerg // A struct to define how the data stream should be patched. For Indexed
377330f729Sjoerg // profiling, only uint64_t data type is needed.
387330f729Sjoerg struct PatchItem {
397330f729Sjoerg uint64_t Pos; // Where to patch.
407330f729Sjoerg uint64_t *D; // Pointer to an array of source data.
417330f729Sjoerg int N; // Number of elements in \c D array.
427330f729Sjoerg };
437330f729Sjoerg
447330f729Sjoerg namespace llvm {
457330f729Sjoerg
467330f729Sjoerg // A wrapper class to abstract writer stream with support of bytes
477330f729Sjoerg // back patching.
487330f729Sjoerg class ProfOStream {
497330f729Sjoerg public:
ProfOStream(raw_fd_ostream & FD)507330f729Sjoerg ProfOStream(raw_fd_ostream &FD)
517330f729Sjoerg : IsFDOStream(true), OS(FD), LE(FD, support::little) {}
ProfOStream(raw_string_ostream & STR)527330f729Sjoerg ProfOStream(raw_string_ostream &STR)
537330f729Sjoerg : IsFDOStream(false), OS(STR), LE(STR, support::little) {}
547330f729Sjoerg
tell()557330f729Sjoerg uint64_t tell() { return OS.tell(); }
write(uint64_t V)567330f729Sjoerg void write(uint64_t V) { LE.write<uint64_t>(V); }
577330f729Sjoerg
587330f729Sjoerg // \c patch can only be called when all data is written and flushed.
597330f729Sjoerg // For raw_string_ostream, the patch is done on the target string
607330f729Sjoerg // directly and it won't be reflected in the stream's internal buffer.
patch(PatchItem * P,int NItems)617330f729Sjoerg void patch(PatchItem *P, int NItems) {
627330f729Sjoerg using namespace support;
637330f729Sjoerg
647330f729Sjoerg if (IsFDOStream) {
657330f729Sjoerg raw_fd_ostream &FDOStream = static_cast<raw_fd_ostream &>(OS);
667330f729Sjoerg for (int K = 0; K < NItems; K++) {
677330f729Sjoerg FDOStream.seek(P[K].Pos);
687330f729Sjoerg for (int I = 0; I < P[K].N; I++)
697330f729Sjoerg write(P[K].D[I]);
707330f729Sjoerg }
717330f729Sjoerg } else {
727330f729Sjoerg raw_string_ostream &SOStream = static_cast<raw_string_ostream &>(OS);
737330f729Sjoerg std::string &Data = SOStream.str(); // with flush
747330f729Sjoerg for (int K = 0; K < NItems; K++) {
757330f729Sjoerg for (int I = 0; I < P[K].N; I++) {
767330f729Sjoerg uint64_t Bytes = endian::byte_swap<uint64_t, little>(P[K].D[I]);
777330f729Sjoerg Data.replace(P[K].Pos + I * sizeof(uint64_t), sizeof(uint64_t),
787330f729Sjoerg (const char *)&Bytes, sizeof(uint64_t));
797330f729Sjoerg }
807330f729Sjoerg }
817330f729Sjoerg }
827330f729Sjoerg }
837330f729Sjoerg
847330f729Sjoerg // If \c OS is an instance of \c raw_fd_ostream, this field will be
857330f729Sjoerg // true. Otherwise, \c OS will be an raw_string_ostream.
867330f729Sjoerg bool IsFDOStream;
877330f729Sjoerg raw_ostream &OS;
887330f729Sjoerg support::endian::Writer LE;
897330f729Sjoerg };
907330f729Sjoerg
917330f729Sjoerg class InstrProfRecordWriterTrait {
927330f729Sjoerg public:
937330f729Sjoerg using key_type = StringRef;
947330f729Sjoerg using key_type_ref = StringRef;
957330f729Sjoerg
967330f729Sjoerg using data_type = const InstrProfWriter::ProfilingData *const;
977330f729Sjoerg using data_type_ref = const InstrProfWriter::ProfilingData *const;
987330f729Sjoerg
997330f729Sjoerg using hash_value_type = uint64_t;
1007330f729Sjoerg using offset_type = uint64_t;
1017330f729Sjoerg
1027330f729Sjoerg support::endianness ValueProfDataEndianness = support::little;
1037330f729Sjoerg InstrProfSummaryBuilder *SummaryBuilder;
1047330f729Sjoerg InstrProfSummaryBuilder *CSSummaryBuilder;
1057330f729Sjoerg
1067330f729Sjoerg InstrProfRecordWriterTrait() = default;
1077330f729Sjoerg
ComputeHash(key_type_ref K)1087330f729Sjoerg static hash_value_type ComputeHash(key_type_ref K) {
1097330f729Sjoerg return IndexedInstrProf::ComputeHash(K);
1107330f729Sjoerg }
1117330f729Sjoerg
1127330f729Sjoerg static std::pair<offset_type, offset_type>
EmitKeyDataLength(raw_ostream & Out,key_type_ref K,data_type_ref V)1137330f729Sjoerg EmitKeyDataLength(raw_ostream &Out, key_type_ref K, data_type_ref V) {
1147330f729Sjoerg using namespace support;
1157330f729Sjoerg
1167330f729Sjoerg endian::Writer LE(Out, little);
1177330f729Sjoerg
1187330f729Sjoerg offset_type N = K.size();
1197330f729Sjoerg LE.write<offset_type>(N);
1207330f729Sjoerg
1217330f729Sjoerg offset_type M = 0;
1227330f729Sjoerg for (const auto &ProfileData : *V) {
1237330f729Sjoerg const InstrProfRecord &ProfRecord = ProfileData.second;
1247330f729Sjoerg M += sizeof(uint64_t); // The function hash
1257330f729Sjoerg M += sizeof(uint64_t); // The size of the Counts vector
1267330f729Sjoerg M += ProfRecord.Counts.size() * sizeof(uint64_t);
1277330f729Sjoerg
1287330f729Sjoerg // Value data
1297330f729Sjoerg M += ValueProfData::getSize(ProfileData.second);
1307330f729Sjoerg }
1317330f729Sjoerg LE.write<offset_type>(M);
1327330f729Sjoerg
1337330f729Sjoerg return std::make_pair(N, M);
1347330f729Sjoerg }
1357330f729Sjoerg
EmitKey(raw_ostream & Out,key_type_ref K,offset_type N)1367330f729Sjoerg void EmitKey(raw_ostream &Out, key_type_ref K, offset_type N) {
1377330f729Sjoerg Out.write(K.data(), N);
1387330f729Sjoerg }
1397330f729Sjoerg
EmitData(raw_ostream & Out,key_type_ref,data_type_ref V,offset_type)1407330f729Sjoerg void EmitData(raw_ostream &Out, key_type_ref, data_type_ref V, offset_type) {
1417330f729Sjoerg using namespace support;
1427330f729Sjoerg
1437330f729Sjoerg endian::Writer LE(Out, little);
1447330f729Sjoerg for (const auto &ProfileData : *V) {
1457330f729Sjoerg const InstrProfRecord &ProfRecord = ProfileData.second;
1467330f729Sjoerg if (NamedInstrProfRecord::hasCSFlagInHash(ProfileData.first))
1477330f729Sjoerg CSSummaryBuilder->addRecord(ProfRecord);
1487330f729Sjoerg else
1497330f729Sjoerg SummaryBuilder->addRecord(ProfRecord);
1507330f729Sjoerg
1517330f729Sjoerg LE.write<uint64_t>(ProfileData.first); // Function hash
1527330f729Sjoerg LE.write<uint64_t>(ProfRecord.Counts.size());
1537330f729Sjoerg for (uint64_t I : ProfRecord.Counts)
1547330f729Sjoerg LE.write<uint64_t>(I);
1557330f729Sjoerg
1567330f729Sjoerg // Write value data
1577330f729Sjoerg std::unique_ptr<ValueProfData> VDataPtr =
1587330f729Sjoerg ValueProfData::serializeFrom(ProfileData.second);
1597330f729Sjoerg uint32_t S = VDataPtr->getSize();
1607330f729Sjoerg VDataPtr->swapBytesFromHost(ValueProfDataEndianness);
1617330f729Sjoerg Out.write((const char *)VDataPtr.get(), S);
1627330f729Sjoerg }
1637330f729Sjoerg }
1647330f729Sjoerg };
1657330f729Sjoerg
1667330f729Sjoerg } // end namespace llvm
1677330f729Sjoerg
InstrProfWriter(bool Sparse,bool InstrEntryBBEnabled)168*82d56013Sjoerg InstrProfWriter::InstrProfWriter(bool Sparse, bool InstrEntryBBEnabled)
169*82d56013Sjoerg : Sparse(Sparse), InstrEntryBBEnabled(InstrEntryBBEnabled),
170*82d56013Sjoerg InfoObj(new InstrProfRecordWriterTrait()) {}
1717330f729Sjoerg
~InstrProfWriter()1727330f729Sjoerg InstrProfWriter::~InstrProfWriter() { delete InfoObj; }
1737330f729Sjoerg
1747330f729Sjoerg // Internal interface for testing purpose only.
setValueProfDataEndianness(support::endianness Endianness)1757330f729Sjoerg void InstrProfWriter::setValueProfDataEndianness(
1767330f729Sjoerg support::endianness Endianness) {
1777330f729Sjoerg InfoObj->ValueProfDataEndianness = Endianness;
1787330f729Sjoerg }
1797330f729Sjoerg
setOutputSparse(bool Sparse)1807330f729Sjoerg void InstrProfWriter::setOutputSparse(bool Sparse) {
1817330f729Sjoerg this->Sparse = Sparse;
1827330f729Sjoerg }
1837330f729Sjoerg
addRecord(NamedInstrProfRecord && I,uint64_t Weight,function_ref<void (Error)> Warn)1847330f729Sjoerg void InstrProfWriter::addRecord(NamedInstrProfRecord &&I, uint64_t Weight,
1857330f729Sjoerg function_ref<void(Error)> Warn) {
1867330f729Sjoerg auto Name = I.Name;
1877330f729Sjoerg auto Hash = I.Hash;
1887330f729Sjoerg addRecord(Name, Hash, std::move(I), Weight, Warn);
1897330f729Sjoerg }
1907330f729Sjoerg
overlapRecord(NamedInstrProfRecord && Other,OverlapStats & Overlap,OverlapStats & FuncLevelOverlap,const OverlapFuncFilters & FuncFilter)1917330f729Sjoerg void InstrProfWriter::overlapRecord(NamedInstrProfRecord &&Other,
1927330f729Sjoerg OverlapStats &Overlap,
1937330f729Sjoerg OverlapStats &FuncLevelOverlap,
1947330f729Sjoerg const OverlapFuncFilters &FuncFilter) {
1957330f729Sjoerg auto Name = Other.Name;
1967330f729Sjoerg auto Hash = Other.Hash;
1977330f729Sjoerg Other.accumulateCounts(FuncLevelOverlap.Test);
1987330f729Sjoerg if (FunctionData.find(Name) == FunctionData.end()) {
1997330f729Sjoerg Overlap.addOneUnique(FuncLevelOverlap.Test);
2007330f729Sjoerg return;
2017330f729Sjoerg }
2027330f729Sjoerg if (FuncLevelOverlap.Test.CountSum < 1.0f) {
2037330f729Sjoerg Overlap.Overlap.NumEntries += 1;
2047330f729Sjoerg return;
2057330f729Sjoerg }
2067330f729Sjoerg auto &ProfileDataMap = FunctionData[Name];
2077330f729Sjoerg bool NewFunc;
2087330f729Sjoerg ProfilingData::iterator Where;
2097330f729Sjoerg std::tie(Where, NewFunc) =
2107330f729Sjoerg ProfileDataMap.insert(std::make_pair(Hash, InstrProfRecord()));
2117330f729Sjoerg if (NewFunc) {
2127330f729Sjoerg Overlap.addOneMismatch(FuncLevelOverlap.Test);
2137330f729Sjoerg return;
2147330f729Sjoerg }
2157330f729Sjoerg InstrProfRecord &Dest = Where->second;
2167330f729Sjoerg
2177330f729Sjoerg uint64_t ValueCutoff = FuncFilter.ValueCutoff;
2187330f729Sjoerg if (!FuncFilter.NameFilter.empty() &&
2197330f729Sjoerg Name.find(FuncFilter.NameFilter) != Name.npos)
2207330f729Sjoerg ValueCutoff = 0;
2217330f729Sjoerg
2227330f729Sjoerg Dest.overlap(Other, Overlap, FuncLevelOverlap, ValueCutoff);
2237330f729Sjoerg }
2247330f729Sjoerg
addRecord(StringRef Name,uint64_t Hash,InstrProfRecord && I,uint64_t Weight,function_ref<void (Error)> Warn)2257330f729Sjoerg void InstrProfWriter::addRecord(StringRef Name, uint64_t Hash,
2267330f729Sjoerg InstrProfRecord &&I, uint64_t Weight,
2277330f729Sjoerg function_ref<void(Error)> Warn) {
2287330f729Sjoerg auto &ProfileDataMap = FunctionData[Name];
2297330f729Sjoerg
2307330f729Sjoerg bool NewFunc;
2317330f729Sjoerg ProfilingData::iterator Where;
2327330f729Sjoerg std::tie(Where, NewFunc) =
2337330f729Sjoerg ProfileDataMap.insert(std::make_pair(Hash, InstrProfRecord()));
2347330f729Sjoerg InstrProfRecord &Dest = Where->second;
2357330f729Sjoerg
2367330f729Sjoerg auto MapWarn = [&](instrprof_error E) {
2377330f729Sjoerg Warn(make_error<InstrProfError>(E));
2387330f729Sjoerg };
2397330f729Sjoerg
2407330f729Sjoerg if (NewFunc) {
2417330f729Sjoerg // We've never seen a function with this name and hash, add it.
2427330f729Sjoerg Dest = std::move(I);
2437330f729Sjoerg if (Weight > 1)
244*82d56013Sjoerg Dest.scale(Weight, 1, MapWarn);
2457330f729Sjoerg } else {
2467330f729Sjoerg // We're updating a function we've seen before.
2477330f729Sjoerg Dest.merge(I, Weight, MapWarn);
2487330f729Sjoerg }
2497330f729Sjoerg
2507330f729Sjoerg Dest.sortValueData();
2517330f729Sjoerg }
2527330f729Sjoerg
mergeRecordsFromWriter(InstrProfWriter && IPW,function_ref<void (Error)> Warn)2537330f729Sjoerg void InstrProfWriter::mergeRecordsFromWriter(InstrProfWriter &&IPW,
2547330f729Sjoerg function_ref<void(Error)> Warn) {
2557330f729Sjoerg for (auto &I : IPW.FunctionData)
2567330f729Sjoerg for (auto &Func : I.getValue())
2577330f729Sjoerg addRecord(I.getKey(), Func.first, std::move(Func.second), 1, Warn);
2587330f729Sjoerg }
2597330f729Sjoerg
shouldEncodeData(const ProfilingData & PD)2607330f729Sjoerg bool InstrProfWriter::shouldEncodeData(const ProfilingData &PD) {
2617330f729Sjoerg if (!Sparse)
2627330f729Sjoerg return true;
2637330f729Sjoerg for (const auto &Func : PD) {
2647330f729Sjoerg const InstrProfRecord &IPR = Func.second;
2657330f729Sjoerg if (llvm::any_of(IPR.Counts, [](uint64_t Count) { return Count > 0; }))
2667330f729Sjoerg return true;
2677330f729Sjoerg }
2687330f729Sjoerg return false;
2697330f729Sjoerg }
2707330f729Sjoerg
setSummary(IndexedInstrProf::Summary * TheSummary,ProfileSummary & PS)2717330f729Sjoerg static void setSummary(IndexedInstrProf::Summary *TheSummary,
2727330f729Sjoerg ProfileSummary &PS) {
2737330f729Sjoerg using namespace IndexedInstrProf;
2747330f729Sjoerg
2757330f729Sjoerg std::vector<ProfileSummaryEntry> &Res = PS.getDetailedSummary();
2767330f729Sjoerg TheSummary->NumSummaryFields = Summary::NumKinds;
2777330f729Sjoerg TheSummary->NumCutoffEntries = Res.size();
2787330f729Sjoerg TheSummary->set(Summary::MaxFunctionCount, PS.getMaxFunctionCount());
2797330f729Sjoerg TheSummary->set(Summary::MaxBlockCount, PS.getMaxCount());
2807330f729Sjoerg TheSummary->set(Summary::MaxInternalBlockCount, PS.getMaxInternalCount());
2817330f729Sjoerg TheSummary->set(Summary::TotalBlockCount, PS.getTotalCount());
2827330f729Sjoerg TheSummary->set(Summary::TotalNumBlocks, PS.getNumCounts());
2837330f729Sjoerg TheSummary->set(Summary::TotalNumFunctions, PS.getNumFunctions());
2847330f729Sjoerg for (unsigned I = 0; I < Res.size(); I++)
2857330f729Sjoerg TheSummary->setEntry(I, Res[I]);
2867330f729Sjoerg }
2877330f729Sjoerg
writeImpl(ProfOStream & OS)288*82d56013Sjoerg Error InstrProfWriter::writeImpl(ProfOStream &OS) {
2897330f729Sjoerg using namespace IndexedInstrProf;
2907330f729Sjoerg
2917330f729Sjoerg OnDiskChainedHashTableGenerator<InstrProfRecordWriterTrait> Generator;
2927330f729Sjoerg
2937330f729Sjoerg InstrProfSummaryBuilder ISB(ProfileSummaryBuilder::DefaultCutoffs);
2947330f729Sjoerg InfoObj->SummaryBuilder = &ISB;
2957330f729Sjoerg InstrProfSummaryBuilder CSISB(ProfileSummaryBuilder::DefaultCutoffs);
2967330f729Sjoerg InfoObj->CSSummaryBuilder = &CSISB;
2977330f729Sjoerg
2987330f729Sjoerg // Populate the hash table generator.
2997330f729Sjoerg for (const auto &I : FunctionData)
3007330f729Sjoerg if (shouldEncodeData(I.getValue()))
3017330f729Sjoerg Generator.insert(I.getKey(), &I.getValue());
3027330f729Sjoerg // Write the header.
3037330f729Sjoerg IndexedInstrProf::Header Header;
3047330f729Sjoerg Header.Magic = IndexedInstrProf::Magic;
3057330f729Sjoerg Header.Version = IndexedInstrProf::ProfVersion::CurrentVersion;
3067330f729Sjoerg if (ProfileKind == PF_IRLevel)
3077330f729Sjoerg Header.Version |= VARIANT_MASK_IR_PROF;
3087330f729Sjoerg if (ProfileKind == PF_IRLevelWithCS) {
3097330f729Sjoerg Header.Version |= VARIANT_MASK_IR_PROF;
3107330f729Sjoerg Header.Version |= VARIANT_MASK_CSIR_PROF;
3117330f729Sjoerg }
312*82d56013Sjoerg if (InstrEntryBBEnabled)
313*82d56013Sjoerg Header.Version |= VARIANT_MASK_INSTR_ENTRY;
314*82d56013Sjoerg
3157330f729Sjoerg Header.Unused = 0;
3167330f729Sjoerg Header.HashType = static_cast<uint64_t>(IndexedInstrProf::HashType);
3177330f729Sjoerg Header.HashOffset = 0;
3187330f729Sjoerg int N = sizeof(IndexedInstrProf::Header) / sizeof(uint64_t);
3197330f729Sjoerg
3207330f729Sjoerg // Only write out all the fields except 'HashOffset'. We need
3217330f729Sjoerg // to remember the offset of that field to allow back patching
3227330f729Sjoerg // later.
3237330f729Sjoerg for (int I = 0; I < N - 1; I++)
3247330f729Sjoerg OS.write(reinterpret_cast<uint64_t *>(&Header)[I]);
3257330f729Sjoerg
3267330f729Sjoerg // Save the location of Header.HashOffset field in \c OS.
3277330f729Sjoerg uint64_t HashTableStartFieldOffset = OS.tell();
3287330f729Sjoerg // Reserve the space for HashOffset field.
3297330f729Sjoerg OS.write(0);
3307330f729Sjoerg
3317330f729Sjoerg // Reserve space to write profile summary data.
3327330f729Sjoerg uint32_t NumEntries = ProfileSummaryBuilder::DefaultCutoffs.size();
3337330f729Sjoerg uint32_t SummarySize = Summary::getSize(Summary::NumKinds, NumEntries);
3347330f729Sjoerg // Remember the summary offset.
3357330f729Sjoerg uint64_t SummaryOffset = OS.tell();
3367330f729Sjoerg for (unsigned I = 0; I < SummarySize / sizeof(uint64_t); I++)
3377330f729Sjoerg OS.write(0);
3387330f729Sjoerg uint64_t CSSummaryOffset = 0;
3397330f729Sjoerg uint64_t CSSummarySize = 0;
3407330f729Sjoerg if (ProfileKind == PF_IRLevelWithCS) {
3417330f729Sjoerg CSSummaryOffset = OS.tell();
3427330f729Sjoerg CSSummarySize = SummarySize / sizeof(uint64_t);
3437330f729Sjoerg for (unsigned I = 0; I < CSSummarySize; I++)
3447330f729Sjoerg OS.write(0);
3457330f729Sjoerg }
3467330f729Sjoerg
3477330f729Sjoerg // Write the hash table.
3487330f729Sjoerg uint64_t HashTableStart = Generator.Emit(OS.OS, *InfoObj);
3497330f729Sjoerg
3507330f729Sjoerg // Allocate space for data to be serialized out.
3517330f729Sjoerg std::unique_ptr<IndexedInstrProf::Summary> TheSummary =
3527330f729Sjoerg IndexedInstrProf::allocSummary(SummarySize);
3537330f729Sjoerg // Compute the Summary and copy the data to the data
3547330f729Sjoerg // structure to be serialized out (to disk or buffer).
3557330f729Sjoerg std::unique_ptr<ProfileSummary> PS = ISB.getSummary();
3567330f729Sjoerg setSummary(TheSummary.get(), *PS);
3577330f729Sjoerg InfoObj->SummaryBuilder = nullptr;
3587330f729Sjoerg
3597330f729Sjoerg // For Context Sensitive summary.
3607330f729Sjoerg std::unique_ptr<IndexedInstrProf::Summary> TheCSSummary = nullptr;
3617330f729Sjoerg if (ProfileKind == PF_IRLevelWithCS) {
3627330f729Sjoerg TheCSSummary = IndexedInstrProf::allocSummary(SummarySize);
3637330f729Sjoerg std::unique_ptr<ProfileSummary> CSPS = CSISB.getSummary();
3647330f729Sjoerg setSummary(TheCSSummary.get(), *CSPS);
3657330f729Sjoerg }
3667330f729Sjoerg InfoObj->CSSummaryBuilder = nullptr;
3677330f729Sjoerg
3687330f729Sjoerg // Now do the final patch:
3697330f729Sjoerg PatchItem PatchItems[] = {
3707330f729Sjoerg // Patch the Header.HashOffset field.
3717330f729Sjoerg {HashTableStartFieldOffset, &HashTableStart, 1},
3727330f729Sjoerg // Patch the summary data.
3737330f729Sjoerg {SummaryOffset, reinterpret_cast<uint64_t *>(TheSummary.get()),
3747330f729Sjoerg (int)(SummarySize / sizeof(uint64_t))},
3757330f729Sjoerg {CSSummaryOffset, reinterpret_cast<uint64_t *>(TheCSSummary.get()),
3767330f729Sjoerg (int)CSSummarySize}};
3777330f729Sjoerg
3787330f729Sjoerg OS.patch(PatchItems, sizeof(PatchItems) / sizeof(*PatchItems));
379*82d56013Sjoerg
380*82d56013Sjoerg for (const auto &I : FunctionData)
381*82d56013Sjoerg for (const auto &F : I.getValue())
382*82d56013Sjoerg if (Error E = validateRecord(F.second))
383*82d56013Sjoerg return E;
384*82d56013Sjoerg
385*82d56013Sjoerg return Error::success();
3867330f729Sjoerg }
3877330f729Sjoerg
write(raw_fd_ostream & OS)388*82d56013Sjoerg Error InstrProfWriter::write(raw_fd_ostream &OS) {
3897330f729Sjoerg // Write the hash table.
3907330f729Sjoerg ProfOStream POS(OS);
391*82d56013Sjoerg return writeImpl(POS);
3927330f729Sjoerg }
3937330f729Sjoerg
writeBuffer()3947330f729Sjoerg std::unique_ptr<MemoryBuffer> InstrProfWriter::writeBuffer() {
3957330f729Sjoerg std::string Data;
3967330f729Sjoerg raw_string_ostream OS(Data);
3977330f729Sjoerg ProfOStream POS(OS);
3987330f729Sjoerg // Write the hash table.
399*82d56013Sjoerg if (Error E = writeImpl(POS))
400*82d56013Sjoerg return nullptr;
4017330f729Sjoerg // Return this in an aligned memory buffer.
4027330f729Sjoerg return MemoryBuffer::getMemBufferCopy(Data);
4037330f729Sjoerg }
4047330f729Sjoerg
4057330f729Sjoerg static const char *ValueProfKindStr[] = {
4067330f729Sjoerg #define VALUE_PROF_KIND(Enumerator, Value, Descr) #Enumerator,
4077330f729Sjoerg #include "llvm/ProfileData/InstrProfData.inc"
4087330f729Sjoerg };
4097330f729Sjoerg
validateRecord(const InstrProfRecord & Func)410*82d56013Sjoerg Error InstrProfWriter::validateRecord(const InstrProfRecord &Func) {
411*82d56013Sjoerg for (uint32_t VK = 0; VK <= IPVK_Last; VK++) {
412*82d56013Sjoerg uint32_t NS = Func.getNumValueSites(VK);
413*82d56013Sjoerg if (!NS)
414*82d56013Sjoerg continue;
415*82d56013Sjoerg for (uint32_t S = 0; S < NS; S++) {
416*82d56013Sjoerg uint32_t ND = Func.getNumValueDataForSite(VK, S);
417*82d56013Sjoerg std::unique_ptr<InstrProfValueData[]> VD = Func.getValueForSite(VK, S);
418*82d56013Sjoerg bool WasZero = false;
419*82d56013Sjoerg for (uint32_t I = 0; I < ND; I++)
420*82d56013Sjoerg if ((VK != IPVK_IndirectCallTarget) && (VD[I].Value == 0)) {
421*82d56013Sjoerg if (WasZero)
422*82d56013Sjoerg return make_error<InstrProfError>(instrprof_error::invalid_prof);
423*82d56013Sjoerg WasZero = true;
424*82d56013Sjoerg }
425*82d56013Sjoerg }
426*82d56013Sjoerg }
427*82d56013Sjoerg
428*82d56013Sjoerg return Error::success();
429*82d56013Sjoerg }
430*82d56013Sjoerg
writeRecordInText(StringRef Name,uint64_t Hash,const InstrProfRecord & Func,InstrProfSymtab & Symtab,raw_fd_ostream & OS)4317330f729Sjoerg void InstrProfWriter::writeRecordInText(StringRef Name, uint64_t Hash,
4327330f729Sjoerg const InstrProfRecord &Func,
4337330f729Sjoerg InstrProfSymtab &Symtab,
4347330f729Sjoerg raw_fd_ostream &OS) {
4357330f729Sjoerg OS << Name << "\n";
4367330f729Sjoerg OS << "# Func Hash:\n" << Hash << "\n";
4377330f729Sjoerg OS << "# Num Counters:\n" << Func.Counts.size() << "\n";
4387330f729Sjoerg OS << "# Counter Values:\n";
4397330f729Sjoerg for (uint64_t Count : Func.Counts)
4407330f729Sjoerg OS << Count << "\n";
4417330f729Sjoerg
4427330f729Sjoerg uint32_t NumValueKinds = Func.getNumValueKinds();
4437330f729Sjoerg if (!NumValueKinds) {
4447330f729Sjoerg OS << "\n";
4457330f729Sjoerg return;
4467330f729Sjoerg }
4477330f729Sjoerg
4487330f729Sjoerg OS << "# Num Value Kinds:\n" << Func.getNumValueKinds() << "\n";
4497330f729Sjoerg for (uint32_t VK = 0; VK < IPVK_Last + 1; VK++) {
4507330f729Sjoerg uint32_t NS = Func.getNumValueSites(VK);
4517330f729Sjoerg if (!NS)
4527330f729Sjoerg continue;
4537330f729Sjoerg OS << "# ValueKind = " << ValueProfKindStr[VK] << ":\n" << VK << "\n";
4547330f729Sjoerg OS << "# NumValueSites:\n" << NS << "\n";
4557330f729Sjoerg for (uint32_t S = 0; S < NS; S++) {
4567330f729Sjoerg uint32_t ND = Func.getNumValueDataForSite(VK, S);
4577330f729Sjoerg OS << ND << "\n";
4587330f729Sjoerg std::unique_ptr<InstrProfValueData[]> VD = Func.getValueForSite(VK, S);
4597330f729Sjoerg for (uint32_t I = 0; I < ND; I++) {
4607330f729Sjoerg if (VK == IPVK_IndirectCallTarget)
4617330f729Sjoerg OS << Symtab.getFuncNameOrExternalSymbol(VD[I].Value) << ":"
4627330f729Sjoerg << VD[I].Count << "\n";
4637330f729Sjoerg else
4647330f729Sjoerg OS << VD[I].Value << ":" << VD[I].Count << "\n";
4657330f729Sjoerg }
4667330f729Sjoerg }
4677330f729Sjoerg }
4687330f729Sjoerg
4697330f729Sjoerg OS << "\n";
4707330f729Sjoerg }
4717330f729Sjoerg
writeText(raw_fd_ostream & OS)4727330f729Sjoerg Error InstrProfWriter::writeText(raw_fd_ostream &OS) {
4737330f729Sjoerg if (ProfileKind == PF_IRLevel)
4747330f729Sjoerg OS << "# IR level Instrumentation Flag\n:ir\n";
4757330f729Sjoerg else if (ProfileKind == PF_IRLevelWithCS)
4767330f729Sjoerg OS << "# CSIR level Instrumentation Flag\n:csir\n";
477*82d56013Sjoerg if (InstrEntryBBEnabled)
478*82d56013Sjoerg OS << "# Always instrument the function entry block\n:entry_first\n";
4797330f729Sjoerg InstrProfSymtab Symtab;
4807330f729Sjoerg
4817330f729Sjoerg using FuncPair = detail::DenseMapPair<uint64_t, InstrProfRecord>;
4827330f729Sjoerg using RecordType = std::pair<StringRef, FuncPair>;
4837330f729Sjoerg SmallVector<RecordType, 4> OrderedFuncData;
4847330f729Sjoerg
4857330f729Sjoerg for (const auto &I : FunctionData) {
4867330f729Sjoerg if (shouldEncodeData(I.getValue())) {
4877330f729Sjoerg if (Error E = Symtab.addFuncName(I.getKey()))
4887330f729Sjoerg return E;
4897330f729Sjoerg for (const auto &Func : I.getValue())
4907330f729Sjoerg OrderedFuncData.push_back(std::make_pair(I.getKey(), Func));
4917330f729Sjoerg }
4927330f729Sjoerg }
4937330f729Sjoerg
4947330f729Sjoerg llvm::sort(OrderedFuncData, [](const RecordType &A, const RecordType &B) {
4957330f729Sjoerg return std::tie(A.first, A.second.first) <
4967330f729Sjoerg std::tie(B.first, B.second.first);
4977330f729Sjoerg });
4987330f729Sjoerg
4997330f729Sjoerg for (const auto &record : OrderedFuncData) {
5007330f729Sjoerg const StringRef &Name = record.first;
5017330f729Sjoerg const FuncPair &Func = record.second;
5027330f729Sjoerg writeRecordInText(Name, Func.first, Func.second, Symtab, OS);
5037330f729Sjoerg }
5047330f729Sjoerg
505*82d56013Sjoerg for (const auto &record : OrderedFuncData) {
506*82d56013Sjoerg const FuncPair &Func = record.second;
507*82d56013Sjoerg if (Error E = validateRecord(Func.second))
508*82d56013Sjoerg return E;
509*82d56013Sjoerg }
510*82d56013Sjoerg
5117330f729Sjoerg return Error::success();
5127330f729Sjoerg }
513