Home | History | Annotate | Download | only in ProfileData
      1 //=-- InstrProfWriter.cpp - Instrumented profiling writer -------------------=//
      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 contains support for writing profiling data for clang's
     11 // instrumentation based PGO and coverage.
     12 //
     13 //===----------------------------------------------------------------------===//
     14 
     15 #include "llvm/ProfileData/InstrProfWriter.h"
     16 #include "llvm/ADT/StringExtras.h"
     17 #include "llvm/Support/EndianStream.h"
     18 #include "llvm/Support/OnDiskHashTable.h"
     19 #include <tuple>
     20 
     21 using namespace llvm;
     22 
     23 // A struct to define how the data stream should be patched. For Indexed
     24 // profiling, only uint64_t data type is needed.
     25 struct PatchItem {
     26   uint64_t Pos; // Where to patch.
     27   uint64_t *D;  // Pointer to an array of source data.
     28   int N;        // Number of elements in \c D array.
     29 };
     30 
     31 namespace llvm {
     32 // A wrapper class to abstract writer stream with support of bytes
     33 // back patching.
     34 class ProfOStream {
     35 
     36 public:
     37   ProfOStream(llvm::raw_fd_ostream &FD) : IsFDOStream(true), OS(FD), LE(FD) {}
     38   ProfOStream(llvm::raw_string_ostream &STR)
     39       : IsFDOStream(false), OS(STR), LE(STR) {}
     40 
     41   uint64_t tell() { return OS.tell(); }
     42   void write(uint64_t V) { LE.write<uint64_t>(V); }
     43   // \c patch can only be called when all data is written and flushed.
     44   // For raw_string_ostream, the patch is done on the target string
     45   // directly and it won't be reflected in the stream's internal buffer.
     46   void patch(PatchItem *P, int NItems) {
     47     using namespace support;
     48     if (IsFDOStream) {
     49       llvm::raw_fd_ostream &FDOStream = static_cast<llvm::raw_fd_ostream &>(OS);
     50       for (int K = 0; K < NItems; K++) {
     51         FDOStream.seek(P[K].Pos);
     52         for (int I = 0; I < P[K].N; I++)
     53           write(P[K].D[I]);
     54       }
     55     } else {
     56       llvm::raw_string_ostream &SOStream =
     57           static_cast<llvm::raw_string_ostream &>(OS);
     58       std::string &Data = SOStream.str(); // with flush
     59       for (int K = 0; K < NItems; K++) {
     60         for (int I = 0; I < P[K].N; I++) {
     61           uint64_t Bytes = endian::byte_swap<uint64_t, little>(P[K].D[I]);
     62           Data.replace(P[K].Pos + I * sizeof(uint64_t), sizeof(uint64_t),
     63                        (const char *)&Bytes, sizeof(uint64_t));
     64         }
     65       }
     66     }
     67   }
     68   // If \c OS is an instance of \c raw_fd_ostream, this field will be
     69   // true. Otherwise, \c OS will be an raw_string_ostream.
     70   bool IsFDOStream;
     71   raw_ostream &OS;
     72   support::endian::Writer<support::little> LE;
     73 };
     74 
     75 class InstrProfRecordWriterTrait {
     76 public:
     77   typedef StringRef key_type;
     78   typedef StringRef key_type_ref;
     79 
     80   typedef const InstrProfWriter::ProfilingData *const data_type;
     81   typedef const InstrProfWriter::ProfilingData *const data_type_ref;
     82 
     83   typedef uint64_t hash_value_type;
     84   typedef uint64_t offset_type;
     85 
     86   support::endianness ValueProfDataEndianness;
     87   InstrProfSummaryBuilder *SummaryBuilder;
     88 
     89   InstrProfRecordWriterTrait() : ValueProfDataEndianness(support::little) {}
     90   static hash_value_type ComputeHash(key_type_ref K) {
     91     return IndexedInstrProf::ComputeHash(K);
     92   }
     93 
     94   static std::pair<offset_type, offset_type>
     95   EmitKeyDataLength(raw_ostream &Out, key_type_ref K, data_type_ref V) {
     96     using namespace llvm::support;
     97     endian::Writer<little> LE(Out);
     98 
     99     offset_type N = K.size();
    100     LE.write<offset_type>(N);
    101 
    102     offset_type M = 0;
    103     for (const auto &ProfileData : *V) {
    104       const InstrProfRecord &ProfRecord = ProfileData.second;
    105       M += sizeof(uint64_t); // The function hash
    106       M += sizeof(uint64_t); // The size of the Counts vector
    107       M += ProfRecord.Counts.size() * sizeof(uint64_t);
    108 
    109       // Value data
    110       M += ValueProfData::getSize(ProfileData.second);
    111     }
    112     LE.write<offset_type>(M);
    113 
    114     return std::make_pair(N, M);
    115   }
    116 
    117   void EmitKey(raw_ostream &Out, key_type_ref K, offset_type N) {
    118     Out.write(K.data(), N);
    119   }
    120 
    121   void EmitData(raw_ostream &Out, key_type_ref, data_type_ref V, offset_type) {
    122     using namespace llvm::support;
    123     endian::Writer<little> LE(Out);
    124     for (const auto &ProfileData : *V) {
    125       const InstrProfRecord &ProfRecord = ProfileData.second;
    126       SummaryBuilder->addRecord(ProfRecord);
    127 
    128       LE.write<uint64_t>(ProfileData.first); // Function hash
    129       LE.write<uint64_t>(ProfRecord.Counts.size());
    130       for (uint64_t I : ProfRecord.Counts)
    131         LE.write<uint64_t>(I);
    132 
    133       // Write value data
    134       std::unique_ptr<ValueProfData> VDataPtr =
    135           ValueProfData::serializeFrom(ProfileData.second);
    136       uint32_t S = VDataPtr->getSize();
    137       VDataPtr->swapBytesFromHost(ValueProfDataEndianness);
    138       Out.write((const char *)VDataPtr.get(), S);
    139     }
    140   }
    141 };
    142 }
    143 
    144 InstrProfWriter::InstrProfWriter(bool Sparse)
    145     : Sparse(Sparse), FunctionData(), ProfileKind(PF_Unknown),
    146       InfoObj(new InstrProfRecordWriterTrait()) {}
    147 
    148 InstrProfWriter::~InstrProfWriter() { delete InfoObj; }
    149 
    150 // Internal interface for testing purpose only.
    151 void InstrProfWriter::setValueProfDataEndianness(
    152     support::endianness Endianness) {
    153   InfoObj->ValueProfDataEndianness = Endianness;
    154 }
    155 void InstrProfWriter::setOutputSparse(bool Sparse) {
    156   this->Sparse = Sparse;
    157 }
    158 
    159 Error InstrProfWriter::addRecord(InstrProfRecord &&I, uint64_t Weight) {
    160   auto &ProfileDataMap = FunctionData[I.Name];
    161 
    162   bool NewFunc;
    163   ProfilingData::iterator Where;
    164   std::tie(Where, NewFunc) =
    165       ProfileDataMap.insert(std::make_pair(I.Hash, InstrProfRecord()));
    166   InstrProfRecord &Dest = Where->second;
    167 
    168   if (NewFunc) {
    169     // We've never seen a function with this name and hash, add it.
    170     Dest = std::move(I);
    171     // Fix up the name to avoid dangling reference.
    172     Dest.Name = FunctionData.find(Dest.Name)->getKey();
    173     if (Weight > 1)
    174       Dest.scale(Weight);
    175   } else {
    176     // We're updating a function we've seen before.
    177     Dest.merge(I, Weight);
    178   }
    179 
    180   Dest.sortValueData();
    181 
    182   return Dest.takeError();
    183 }
    184 
    185 bool InstrProfWriter::shouldEncodeData(const ProfilingData &PD) {
    186   if (!Sparse)
    187     return true;
    188   for (const auto &Func : PD) {
    189     const InstrProfRecord &IPR = Func.second;
    190     if (std::any_of(IPR.Counts.begin(), IPR.Counts.end(),
    191                     [](uint64_t Count) { return Count > 0; }))
    192       return true;
    193   }
    194   return false;
    195 }
    196 
    197 static void setSummary(IndexedInstrProf::Summary *TheSummary,
    198                        ProfileSummary &PS) {
    199   using namespace IndexedInstrProf;
    200   std::vector<ProfileSummaryEntry> &Res = PS.getDetailedSummary();
    201   TheSummary->NumSummaryFields = Summary::NumKinds;
    202   TheSummary->NumCutoffEntries = Res.size();
    203   TheSummary->set(Summary::MaxFunctionCount, PS.getMaxFunctionCount());
    204   TheSummary->set(Summary::MaxBlockCount, PS.getMaxCount());
    205   TheSummary->set(Summary::MaxInternalBlockCount, PS.getMaxInternalCount());
    206   TheSummary->set(Summary::TotalBlockCount, PS.getTotalCount());
    207   TheSummary->set(Summary::TotalNumBlocks, PS.getNumCounts());
    208   TheSummary->set(Summary::TotalNumFunctions, PS.getNumFunctions());
    209   for (unsigned I = 0; I < Res.size(); I++)
    210     TheSummary->setEntry(I, Res[I]);
    211 }
    212 
    213 void InstrProfWriter::writeImpl(ProfOStream &OS) {
    214   OnDiskChainedHashTableGenerator<InstrProfRecordWriterTrait> Generator;
    215 
    216   using namespace IndexedInstrProf;
    217   InstrProfSummaryBuilder ISB(ProfileSummaryBuilder::DefaultCutoffs);
    218   InfoObj->SummaryBuilder = &ISB;
    219 
    220   // Populate the hash table generator.
    221   for (const auto &I : FunctionData)
    222     if (shouldEncodeData(I.getValue()))
    223       Generator.insert(I.getKey(), &I.getValue());
    224   // Write the header.
    225   IndexedInstrProf::Header Header;
    226   Header.Magic = IndexedInstrProf::Magic;
    227   Header.Version = IndexedInstrProf::ProfVersion::CurrentVersion;
    228   if (ProfileKind == PF_IRLevel)
    229     Header.Version |= VARIANT_MASK_IR_PROF;
    230   Header.Unused = 0;
    231   Header.HashType = static_cast<uint64_t>(IndexedInstrProf::HashType);
    232   Header.HashOffset = 0;
    233   int N = sizeof(IndexedInstrProf::Header) / sizeof(uint64_t);
    234 
    235   // Only write out all the fields except 'HashOffset'. We need
    236   // to remember the offset of that field to allow back patching
    237   // later.
    238   for (int I = 0; I < N - 1; I++)
    239     OS.write(reinterpret_cast<uint64_t *>(&Header)[I]);
    240 
    241   // Save the location of Header.HashOffset field in \c OS.
    242   uint64_t HashTableStartFieldOffset = OS.tell();
    243   // Reserve the space for HashOffset field.
    244   OS.write(0);
    245 
    246   // Reserve space to write profile summary data.
    247   uint32_t NumEntries = ProfileSummaryBuilder::DefaultCutoffs.size();
    248   uint32_t SummarySize = Summary::getSize(Summary::NumKinds, NumEntries);
    249   // Remember the summary offset.
    250   uint64_t SummaryOffset = OS.tell();
    251   for (unsigned I = 0; I < SummarySize / sizeof(uint64_t); I++)
    252     OS.write(0);
    253 
    254   // Write the hash table.
    255   uint64_t HashTableStart = Generator.Emit(OS.OS, *InfoObj);
    256 
    257   // Allocate space for data to be serialized out.
    258   std::unique_ptr<IndexedInstrProf::Summary> TheSummary =
    259       IndexedInstrProf::allocSummary(SummarySize);
    260   // Compute the Summary and copy the data to the data
    261   // structure to be serialized out (to disk or buffer).
    262   std::unique_ptr<ProfileSummary> PS = ISB.getSummary();
    263   setSummary(TheSummary.get(), *PS);
    264   InfoObj->SummaryBuilder = 0;
    265 
    266   // Now do the final patch:
    267   PatchItem PatchItems[] = {
    268       // Patch the Header.HashOffset field.
    269       {HashTableStartFieldOffset, &HashTableStart, 1},
    270       // Patch the summary data.
    271       {SummaryOffset, reinterpret_cast<uint64_t *>(TheSummary.get()),
    272        (int)(SummarySize / sizeof(uint64_t))}};
    273   OS.patch(PatchItems, sizeof(PatchItems) / sizeof(*PatchItems));
    274 }
    275 
    276 void InstrProfWriter::write(raw_fd_ostream &OS) {
    277   // Write the hash table.
    278   ProfOStream POS(OS);
    279   writeImpl(POS);
    280 }
    281 
    282 std::unique_ptr<MemoryBuffer> InstrProfWriter::writeBuffer() {
    283   std::string Data;
    284   llvm::raw_string_ostream OS(Data);
    285   ProfOStream POS(OS);
    286   // Write the hash table.
    287   writeImpl(POS);
    288   // Return this in an aligned memory buffer.
    289   return MemoryBuffer::getMemBufferCopy(Data);
    290 }
    291 
    292 static const char *ValueProfKindStr[] = {
    293 #define VALUE_PROF_KIND(Enumerator, Value) #Enumerator,
    294 #include "llvm/ProfileData/InstrProfData.inc"
    295 };
    296 
    297 void InstrProfWriter::writeRecordInText(const InstrProfRecord &Func,
    298                                         InstrProfSymtab &Symtab,
    299                                         raw_fd_ostream &OS) {
    300   OS << Func.Name << "\n";
    301   OS << "# Func Hash:\n" << Func.Hash << "\n";
    302   OS << "# Num Counters:\n" << Func.Counts.size() << "\n";
    303   OS << "# Counter Values:\n";
    304   for (uint64_t Count : Func.Counts)
    305     OS << Count << "\n";
    306 
    307   uint32_t NumValueKinds = Func.getNumValueKinds();
    308   if (!NumValueKinds) {
    309     OS << "\n";
    310     return;
    311   }
    312 
    313   OS << "# Num Value Kinds:\n" << Func.getNumValueKinds() << "\n";
    314   for (uint32_t VK = 0; VK < IPVK_Last + 1; VK++) {
    315     uint32_t NS = Func.getNumValueSites(VK);
    316     if (!NS)
    317       continue;
    318     OS << "# ValueKind = " << ValueProfKindStr[VK] << ":\n" << VK << "\n";
    319     OS << "# NumValueSites:\n" << NS << "\n";
    320     for (uint32_t S = 0; S < NS; S++) {
    321       uint32_t ND = Func.getNumValueDataForSite(VK, S);
    322       OS << ND << "\n";
    323       std::unique_ptr<InstrProfValueData[]> VD = Func.getValueForSite(VK, S);
    324       for (uint32_t I = 0; I < ND; I++) {
    325         if (VK == IPVK_IndirectCallTarget)
    326           OS << Symtab.getFuncName(VD[I].Value) << ":" << VD[I].Count << "\n";
    327         else
    328           OS << VD[I].Value << ":" << VD[I].Count << "\n";
    329       }
    330     }
    331   }
    332 
    333   OS << "\n";
    334 }
    335 
    336 void InstrProfWriter::writeText(raw_fd_ostream &OS) {
    337   if (ProfileKind == PF_IRLevel)
    338     OS << "# IR level Instrumentation Flag\n:ir\n";
    339   InstrProfSymtab Symtab;
    340   for (const auto &I : FunctionData)
    341     if (shouldEncodeData(I.getValue()))
    342       Symtab.addFuncName(I.getKey());
    343   Symtab.finalizeSymtab();
    344 
    345   for (const auto &I : FunctionData)
    346     if (shouldEncodeData(I.getValue()))
    347       for (const auto &Func : I.getValue())
    348         writeRecordInText(Func.second, Symtab, OS);
    349 }
    350