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