1//===- InstrProf.cpp - Instrumented profiling format support --------------===//
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 clang's instrumentation based PGO and
10// coverage.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/ProfileData/InstrProf.h"
15#include "llvm/ADT/ArrayRef.h"
16#include "llvm/ADT/SmallVector.h"
17#include "llvm/ADT/StringExtras.h"
18#include "llvm/ADT/StringRef.h"
19#include "llvm/Config/config.h"
20#include "llvm/IR/Constant.h"
21#include "llvm/IR/Constants.h"
22#include "llvm/IR/Function.h"
23#include "llvm/IR/GlobalValue.h"
24#include "llvm/IR/GlobalVariable.h"
25#include "llvm/IR/Instruction.h"
26#include "llvm/IR/LLVMContext.h"
27#include "llvm/IR/MDBuilder.h"
28#include "llvm/IR/Metadata.h"
29#include "llvm/IR/Module.h"
30#include "llvm/IR/ProfDataUtils.h"
31#include "llvm/IR/Type.h"
32#include "llvm/ProfileData/InstrProfReader.h"
33#include "llvm/ProfileData/SampleProf.h"
34#include "llvm/Support/Casting.h"
35#include "llvm/Support/CommandLine.h"
36#include "llvm/Support/Compiler.h"
37#include "llvm/Support/Compression.h"
38#include "llvm/Support/Debug.h"
39#include "llvm/Support/Endian.h"
40#include "llvm/Support/Error.h"
41#include "llvm/Support/ErrorHandling.h"
42#include "llvm/Support/LEB128.h"
43#include "llvm/Support/MathExtras.h"
44#include "llvm/Support/Path.h"
45#include "llvm/Support/SwapByteOrder.h"
46#include "llvm/Support/VirtualFileSystem.h"
47#include "llvm/Support/raw_ostream.h"
48#include "llvm/TargetParser/Triple.h"
49#include <algorithm>
50#include <cassert>
51#include <cstddef>
52#include <cstdint>
53#include <cstring>
54#include <memory>
55#include <string>
56#include <system_error>
57#include <type_traits>
58#include <utility>
59#include <vector>
60
61using namespace llvm;
62
63#define DEBUG_TYPE "instrprof"
64
65static cl::opt<bool> StaticFuncFullModulePrefix(
66 "static-func-full-module-prefix", cl::init(Val: true), cl::Hidden,
67 cl::desc("Use full module build paths in the profile counter names for "
68 "static functions."));
69
70// This option is tailored to users that have different top-level directory in
71// profile-gen and profile-use compilation. Users need to specific the number
72// of levels to strip. A value larger than the number of directories in the
73// source file will strip all the directory names and only leave the basename.
74//
75// Note current ThinLTO module importing for the indirect-calls assumes
76// the source directory name not being stripped. A non-zero option value here
77// can potentially prevent some inter-module indirect-call-promotions.
78static cl::opt<unsigned> StaticFuncStripDirNamePrefix(
79 "static-func-strip-dirname-prefix", cl::init(Val: 0), cl::Hidden,
80 cl::desc("Strip specified level of directory name from source path in "
81 "the profile counter name for static functions."));
82
83static std::string getInstrProfErrString(instrprof_error Err,
84 const std::string &ErrMsg = "") {
85 std::string Msg;
86 raw_string_ostream OS(Msg);
87
88 switch (Err) {
89 case instrprof_error::success:
90 OS << "success";
91 break;
92 case instrprof_error::eof:
93 OS << "end of File";
94 break;
95 case instrprof_error::unrecognized_format:
96 OS << "unrecognized instrumentation profile encoding format";
97 break;
98 case instrprof_error::bad_magic:
99 OS << "invalid instrumentation profile data (bad magic)";
100 break;
101 case instrprof_error::bad_header:
102 OS << "invalid instrumentation profile data (file header is corrupt)";
103 break;
104 case instrprof_error::unsupported_version:
105 OS << "unsupported instrumentation profile format version";
106 break;
107 case instrprof_error::unsupported_hash_type:
108 OS << "unsupported instrumentation profile hash type";
109 break;
110 case instrprof_error::too_large:
111 OS << "too much profile data";
112 break;
113 case instrprof_error::truncated:
114 OS << "truncated profile data";
115 break;
116 case instrprof_error::malformed:
117 OS << "malformed instrumentation profile data";
118 break;
119 case instrprof_error::missing_correlation_info:
120 OS << "debug info/binary for correlation is required";
121 break;
122 case instrprof_error::unexpected_correlation_info:
123 OS << "debug info/binary for correlation is not necessary";
124 break;
125 case instrprof_error::unable_to_correlate_profile:
126 OS << "unable to correlate profile";
127 break;
128 case instrprof_error::invalid_prof:
129 OS << "invalid profile created. Please file a bug "
130 "at: " BUG_REPORT_URL
131 " and include the profraw files that caused this error.";
132 break;
133 case instrprof_error::unknown_function:
134 OS << "no profile data available for function";
135 break;
136 case instrprof_error::hash_mismatch:
137 OS << "function control flow change detected (hash mismatch)";
138 break;
139 case instrprof_error::count_mismatch:
140 OS << "function basic block count change detected (counter mismatch)";
141 break;
142 case instrprof_error::bitmap_mismatch:
143 OS << "function bitmap size change detected (bitmap size mismatch)";
144 break;
145 case instrprof_error::counter_overflow:
146 OS << "counter overflow";
147 break;
148 case instrprof_error::value_site_count_mismatch:
149 OS << "function value site count change detected (counter mismatch)";
150 break;
151 case instrprof_error::compress_failed:
152 OS << "failed to compress data (zlib)";
153 break;
154 case instrprof_error::uncompress_failed:
155 OS << "failed to uncompress data (zlib)";
156 break;
157 case instrprof_error::empty_raw_profile:
158 OS << "empty raw profile file";
159 break;
160 case instrprof_error::zlib_unavailable:
161 OS << "profile uses zlib compression but the profile reader was built "
162 "without zlib support";
163 break;
164 case instrprof_error::raw_profile_version_mismatch:
165 OS << "raw profile version mismatch";
166 break;
167 case instrprof_error::counter_value_too_large:
168 OS << "excessively large counter value suggests corrupted profile data";
169 break;
170 }
171
172 // If optional error message is not empty, append it to the message.
173 if (!ErrMsg.empty())
174 OS << ": " << ErrMsg;
175
176 return OS.str();
177}
178
179namespace {
180
181// FIXME: This class is only here to support the transition to llvm::Error. It
182// will be removed once this transition is complete. Clients should prefer to
183// deal with the Error value directly, rather than converting to error_code.
184class InstrProfErrorCategoryType : public std::error_category {
185 const char *name() const noexcept override { return "llvm.instrprof"; }
186
187 std::string message(int IE) const override {
188 return getInstrProfErrString(Err: static_cast<instrprof_error>(IE));
189 }
190};
191
192} // end anonymous namespace
193
194const std::error_category &llvm::instrprof_category() {
195 static InstrProfErrorCategoryType ErrorCategory;
196 return ErrorCategory;
197}
198
199namespace {
200
201const char *InstrProfSectNameCommon[] = {
202#define INSTR_PROF_SECT_ENTRY(Kind, SectNameCommon, SectNameCoff, Prefix) \
203 SectNameCommon,
204#include "llvm/ProfileData/InstrProfData.inc"
205};
206
207const char *InstrProfSectNameCoff[] = {
208#define INSTR_PROF_SECT_ENTRY(Kind, SectNameCommon, SectNameCoff, Prefix) \
209 SectNameCoff,
210#include "llvm/ProfileData/InstrProfData.inc"
211};
212
213const char *InstrProfSectNamePrefix[] = {
214#define INSTR_PROF_SECT_ENTRY(Kind, SectNameCommon, SectNameCoff, Prefix) \
215 Prefix,
216#include "llvm/ProfileData/InstrProfData.inc"
217};
218
219} // namespace
220
221namespace llvm {
222
223cl::opt<bool> DoInstrProfNameCompression(
224 "enable-name-compression",
225 cl::desc("Enable name/filename string compression"), cl::init(Val: true));
226
227cl::opt<bool> EnableVTableValueProfiling(
228 "enable-vtable-value-profiling", cl::init(Val: false),
229 cl::desc("If true, the virtual table address will be instrumented to know "
230 "the types of a C++ pointer. The information is used in indirect "
231 "call promotion to do selective vtable-based comparison."));
232
233cl::opt<bool> EnableVTableProfileUse(
234 "enable-vtable-profile-use", cl::init(Val: false),
235 cl::desc("If ThinLTO and WPD is enabled and this option is true, vtable "
236 "profiles will be used by ICP pass for more efficient indirect "
237 "call sequence. If false, type profiles won't be used."));
238
239std::string getInstrProfSectionName(InstrProfSectKind IPSK,
240 Triple::ObjectFormatType OF,
241 bool AddSegmentInfo) {
242 std::string SectName;
243
244 if (OF == Triple::MachO && AddSegmentInfo)
245 SectName = InstrProfSectNamePrefix[IPSK];
246
247 if (OF == Triple::COFF)
248 SectName += InstrProfSectNameCoff[IPSK];
249 else
250 SectName += InstrProfSectNameCommon[IPSK];
251
252 if (OF == Triple::MachO && IPSK == IPSK_data && AddSegmentInfo)
253 SectName += ",regular,live_support";
254
255 return SectName;
256}
257
258std::string InstrProfError::message() const {
259 return getInstrProfErrString(Err, ErrMsg: Msg);
260}
261
262char InstrProfError::ID = 0;
263
264ProfOStream::ProfOStream(raw_fd_ostream &FD)
265 : IsFDOStream(true), OS(FD), LE(FD, llvm::endianness::little) {}
266
267ProfOStream::ProfOStream(raw_string_ostream &STR)
268 : IsFDOStream(false), OS(STR), LE(STR, llvm::endianness::little) {}
269
270uint64_t ProfOStream::tell() const { return OS.tell(); }
271void ProfOStream::write(uint64_t V) { LE.write<uint64_t>(Val: V); }
272void ProfOStream::write32(uint32_t V) { LE.write<uint32_t>(Val: V); }
273void ProfOStream::writeByte(uint8_t V) { LE.write<uint8_t>(Val: V); }
274
275void ProfOStream::patch(ArrayRef<PatchItem> P) {
276 using namespace support;
277
278 if (IsFDOStream) {
279 raw_fd_ostream &FDOStream = static_cast<raw_fd_ostream &>(OS);
280 const uint64_t LastPos = FDOStream.tell();
281 for (const auto &K : P) {
282 FDOStream.seek(off: K.Pos);
283 for (uint64_t Elem : K.D)
284 write(V: Elem);
285 }
286 // Reset the stream to the last position after patching so that users
287 // don't accidentally overwrite data. This makes it consistent with
288 // the string stream below which replaces the data directly.
289 FDOStream.seek(off: LastPos);
290 } else {
291 raw_string_ostream &SOStream = static_cast<raw_string_ostream &>(OS);
292 std::string &Data = SOStream.str(); // with flush
293 for (const auto &K : P) {
294 for (int I = 0, E = K.D.size(); I != E; I++) {
295 uint64_t Bytes =
296 endian::byte_swap<uint64_t>(value: K.D[I], endian: llvm::endianness::little);
297 Data.replace(pos: K.Pos + I * sizeof(uint64_t), n1: sizeof(uint64_t),
298 s: (const char *)&Bytes, n2: sizeof(uint64_t));
299 }
300 }
301 }
302}
303
304std::string getPGOFuncName(StringRef Name, GlobalValue::LinkageTypes Linkage,
305 StringRef FileName,
306 [[maybe_unused]] uint64_t Version) {
307 // Value names may be prefixed with a binary '1' to indicate
308 // that the backend should not modify the symbols due to any platform
309 // naming convention. Do not include that '1' in the PGO profile name.
310 if (Name[0] == '\1')
311 Name = Name.substr(Start: 1);
312
313 std::string NewName = std::string(Name);
314 if (llvm::GlobalValue::isLocalLinkage(Linkage)) {
315 // For local symbols, prepend the main file name to distinguish them.
316 // Do not include the full path in the file name since there's no guarantee
317 // that it will stay the same, e.g., if the files are checked out from
318 // version control in different locations.
319 if (FileName.empty())
320 NewName = NewName.insert(pos: 0, s: "<unknown>:");
321 else
322 NewName = NewName.insert(pos1: 0, str: FileName.str() + ":");
323 }
324 return NewName;
325}
326
327// Strip NumPrefix level of directory name from PathNameStr. If the number of
328// directory separators is less than NumPrefix, strip all the directories and
329// leave base file name only.
330static StringRef stripDirPrefix(StringRef PathNameStr, uint32_t NumPrefix) {
331 uint32_t Count = NumPrefix;
332 uint32_t Pos = 0, LastPos = 0;
333 for (const auto &CI : PathNameStr) {
334 ++Pos;
335 if (llvm::sys::path::is_separator(value: CI)) {
336 LastPos = Pos;
337 --Count;
338 }
339 if (Count == 0)
340 break;
341 }
342 return PathNameStr.substr(Start: LastPos);
343}
344
345static StringRef getStrippedSourceFileName(const GlobalObject &GO) {
346 StringRef FileName(GO.getParent()->getSourceFileName());
347 uint32_t StripLevel = StaticFuncFullModulePrefix ? 0 : (uint32_t)-1;
348 if (StripLevel < StaticFuncStripDirNamePrefix)
349 StripLevel = StaticFuncStripDirNamePrefix;
350 if (StripLevel)
351 FileName = stripDirPrefix(PathNameStr: FileName, NumPrefix: StripLevel);
352 return FileName;
353}
354
355// The PGO name has the format [<filepath>;]<mangled-name> where <filepath>; is
356// provided if linkage is local and is used to discriminate possibly identical
357// mangled names. ";" is used because it is unlikely to be found in either
358// <filepath> or <mangled-name>.
359//
360// Older compilers used getPGOFuncName() which has the format
361// [<filepath>:]<mangled-name>. This caused trouble for Objective-C functions
362// which commonly have :'s in their names. We still need to compute this name to
363// lookup functions from profiles built by older compilers.
364static std::string
365getIRPGONameForGlobalObject(const GlobalObject &GO,
366 GlobalValue::LinkageTypes Linkage,
367 StringRef FileName) {
368 return GlobalValue::getGlobalIdentifier(Name: GO.getName(), Linkage, FileName);
369}
370
371static std::optional<std::string> lookupPGONameFromMetadata(MDNode *MD) {
372 if (MD != nullptr) {
373 StringRef S = cast<MDString>(Val: MD->getOperand(I: 0))->getString();
374 return S.str();
375 }
376 return {};
377}
378
379// Returns the PGO object name. This function has some special handling
380// when called in LTO optimization. The following only applies when calling in
381// LTO passes (when \c InLTO is true): LTO's internalization privatizes many
382// global linkage symbols. This happens after value profile annotation, but
383// those internal linkage functions should not have a source prefix.
384// Additionally, for ThinLTO mode, exported internal functions are promoted
385// and renamed. We need to ensure that the original internal PGO name is
386// used when computing the GUID that is compared against the profiled GUIDs.
387// To differentiate compiler generated internal symbols from original ones,
388// PGOFuncName meta data are created and attached to the original internal
389// symbols in the value profile annotation step
390// (PGOUseFunc::annotateIndirectCallSites). If a symbol does not have the meta
391// data, its original linkage must be non-internal.
392static std::string getIRPGOObjectName(const GlobalObject &GO, bool InLTO,
393 MDNode *PGONameMetadata) {
394 if (!InLTO) {
395 auto FileName = getStrippedSourceFileName(GO);
396 return getIRPGONameForGlobalObject(GO, Linkage: GO.getLinkage(), FileName);
397 }
398
399 // In LTO mode (when InLTO is true), first check if there is a meta data.
400 if (auto IRPGOFuncName = lookupPGONameFromMetadata(MD: PGONameMetadata))
401 return *IRPGOFuncName;
402
403 // If there is no meta data, the function must be a global before the value
404 // profile annotation pass. Its current linkage may be internal if it is
405 // internalized in LTO mode.
406 return getIRPGONameForGlobalObject(GO, Linkage: GlobalValue::ExternalLinkage, FileName: "");
407}
408
409// Returns the IRPGO function name and does special handling when called
410// in LTO optimization. See the comments of `getIRPGOObjectName` for details.
411std::string getIRPGOFuncName(const Function &F, bool InLTO) {
412 return getIRPGOObjectName(GO: F, InLTO, PGONameMetadata: getPGOFuncNameMetadata(F));
413}
414
415// Please use getIRPGOFuncName for LLVM IR instrumentation. This function is
416// for front-end (Clang, etc) instrumentation.
417// The implementation is kept for profile matching from older profiles.
418// This is similar to `getIRPGOFuncName` except that this function calls
419// 'getPGOFuncName' to get a name and `getIRPGOFuncName` calls
420// 'getIRPGONameForGlobalObject'. See the difference between two callees in the
421// comments of `getIRPGONameForGlobalObject`.
422std::string getPGOFuncName(const Function &F, bool InLTO, uint64_t Version) {
423 if (!InLTO) {
424 auto FileName = getStrippedSourceFileName(GO: F);
425 return getPGOFuncName(Name: F.getName(), Linkage: F.getLinkage(), FileName, Version);
426 }
427
428 // In LTO mode (when InLTO is true), first check if there is a meta data.
429 if (auto PGOFuncName = lookupPGONameFromMetadata(MD: getPGOFuncNameMetadata(F)))
430 return *PGOFuncName;
431
432 // If there is no meta data, the function must be a global before the value
433 // profile annotation pass. Its current linkage may be internal if it is
434 // internalized in LTO mode.
435 return getPGOFuncName(Name: F.getName(), Linkage: GlobalValue::ExternalLinkage, FileName: "");
436}
437
438std::string getPGOName(const GlobalVariable &V, bool InLTO) {
439 // PGONameMetadata should be set by compiler at profile use time
440 // and read by symtab creation to look up symbols corresponding to
441 // a MD5 hash.
442 return getIRPGOObjectName(GO: V, InLTO, PGONameMetadata: V.getMetadata(Kind: getPGONameMetadataName()));
443}
444
445// See getIRPGOObjectName() for a discription of the format.
446std::pair<StringRef, StringRef> getParsedIRPGOName(StringRef IRPGOName) {
447 auto [FileName, MangledName] = IRPGOName.split(Separator: GlobalIdentifierDelimiter);
448 if (MangledName.empty())
449 return std::make_pair(x: StringRef(), y&: IRPGOName);
450 return std::make_pair(x&: FileName, y&: MangledName);
451}
452
453StringRef getFuncNameWithoutPrefix(StringRef PGOFuncName, StringRef FileName) {
454 if (FileName.empty())
455 return PGOFuncName;
456 // Drop the file name including ':' or ';'. See getIRPGONameForGlobalObject as
457 // well.
458 if (PGOFuncName.starts_with(Prefix: FileName))
459 PGOFuncName = PGOFuncName.drop_front(N: FileName.size() + 1);
460 return PGOFuncName;
461}
462
463// \p FuncName is the string used as profile lookup key for the function. A
464// symbol is created to hold the name. Return the legalized symbol name.
465std::string getPGOFuncNameVarName(StringRef FuncName,
466 GlobalValue::LinkageTypes Linkage) {
467 std::string VarName = std::string(getInstrProfNameVarPrefix());
468 VarName += FuncName;
469
470 if (!GlobalValue::isLocalLinkage(Linkage))
471 return VarName;
472
473 // Now fix up illegal chars in local VarName that may upset the assembler.
474 const char InvalidChars[] = "-:;<>/\"'";
475 size_t FoundPos = VarName.find_first_of(s: InvalidChars);
476 while (FoundPos != std::string::npos) {
477 VarName[FoundPos] = '_';
478 FoundPos = VarName.find_first_of(s: InvalidChars, pos: FoundPos + 1);
479 }
480 return VarName;
481}
482
483bool isGPUProfTarget(const Module &M) {
484 const Triple &T = M.getTargetTriple();
485 return T.isGPU();
486}
487
488void setPGOFuncVisibility(Module &M, GlobalVariable *FuncNameVar) {
489 // Hide the symbol so that we correctly get a copy for each executable.
490 if (!GlobalValue::isLocalLinkage(Linkage: FuncNameVar->getLinkage()))
491 FuncNameVar->setVisibility(GlobalValue::HiddenVisibility);
492}
493
494GlobalVariable *createPGOFuncNameVar(Module &M,
495 GlobalValue::LinkageTypes Linkage,
496 StringRef PGOFuncName) {
497 // We generally want to match the function's linkage, but available_externally
498 // and extern_weak both have the wrong semantics, and anything that doesn't
499 // need to link across compilation units doesn't need to be visible at all.
500 if (Linkage == GlobalValue::ExternalWeakLinkage)
501 Linkage = GlobalValue::LinkOnceAnyLinkage;
502 else if (Linkage == GlobalValue::AvailableExternallyLinkage)
503 Linkage = GlobalValue::LinkOnceODRLinkage;
504 else if (Linkage == GlobalValue::InternalLinkage ||
505 Linkage == GlobalValue::ExternalLinkage)
506 Linkage = GlobalValue::PrivateLinkage;
507
508 auto *Value =
509 ConstantDataArray::getString(Context&: M.getContext(), Initializer: PGOFuncName, AddNull: false);
510 auto *FuncNameVar =
511 new GlobalVariable(M, Value->getType(), true, Linkage, Value,
512 getPGOFuncNameVarName(FuncName: PGOFuncName, Linkage));
513
514 setPGOFuncVisibility(M, FuncNameVar);
515 return FuncNameVar;
516}
517
518GlobalVariable *createPGOFuncNameVar(Function &F, StringRef PGOFuncName) {
519 return createPGOFuncNameVar(M&: *F.getParent(), Linkage: F.getLinkage(), PGOFuncName);
520}
521
522Error InstrProfSymtab::create(Module &M, bool InLTO, bool AddCanonical) {
523 for (Function &F : M) {
524 // Function may not have a name: like using asm("") to overwrite the name.
525 // Ignore in this case.
526 if (!F.hasName())
527 continue;
528 auto IRPGOFuncName = getIRPGOFuncName(F, InLTO);
529 if (Error E = addFuncWithName(F, PGOFuncName: IRPGOFuncName, AddCanonical))
530 return E;
531 // Also use getPGOFuncName() so that we can find records from older profiles
532 auto PGOFuncName = getPGOFuncName(F, InLTO);
533 if (PGOFuncName != IRPGOFuncName)
534 if (Error E = addFuncWithName(F, PGOFuncName, AddCanonical))
535 return E;
536 }
537
538 for (GlobalVariable &G : M.globals()) {
539 if (!G.hasName() || !G.hasMetadata(KindID: LLVMContext::MD_type))
540 continue;
541 if (Error E = addVTableWithName(V&: G, PGOVTableName: getPGOName(V: G, InLTO)))
542 return E;
543 }
544
545 Sorted = false;
546 finalizeSymtab();
547 return Error::success();
548}
549
550Error InstrProfSymtab::addVTableWithName(GlobalVariable &VTable,
551 StringRef VTablePGOName) {
552 auto NameToGUIDMap = [&](StringRef Name) -> Error {
553 if (Error E = addSymbolName(SymbolName: Name))
554 return E;
555
556 bool Inserted = true;
557 std::tie(args: std::ignore, args&: Inserted) = MD5VTableMap.try_emplace(
558 Key: GlobalValue::getGUIDAssumingExternalLinkage(GlobalName: Name), Args: &VTable);
559 if (!Inserted)
560 LLVM_DEBUG(dbgs() << "GUID conflict within one module");
561 return Error::success();
562 };
563 if (Error E = NameToGUIDMap(VTablePGOName))
564 return E;
565
566 StringRef CanonicalName = getCanonicalName(PGOName: VTablePGOName);
567 if (CanonicalName != VTablePGOName)
568 return NameToGUIDMap(CanonicalName);
569
570 return Error::success();
571}
572
573Error readAndDecodeStrings(StringRef NameStrings,
574 std::function<Error(StringRef)> NameCallback) {
575 const uint8_t *P = NameStrings.bytes_begin();
576 const uint8_t *EndP = NameStrings.bytes_end();
577 while (P < EndP) {
578 uint32_t N;
579 uint64_t UncompressedSize = decodeULEB128(p: P, n: &N);
580 P += N;
581 uint64_t CompressedSize = decodeULEB128(p: P, n: &N);
582 P += N;
583 const bool IsCompressed = (CompressedSize != 0);
584 SmallVector<uint8_t, 128> UncompressedNameStrings;
585 StringRef NameStrings;
586 if (IsCompressed) {
587 if (!llvm::compression::zlib::isAvailable())
588 return make_error<InstrProfError>(Args: instrprof_error::zlib_unavailable);
589
590 if (Error E = compression::zlib::decompress(Input: ArrayRef(P, CompressedSize),
591 Output&: UncompressedNameStrings,
592 UncompressedSize)) {
593 consumeError(Err: std::move(E));
594 return make_error<InstrProfError>(Args: instrprof_error::uncompress_failed);
595 }
596 P += CompressedSize;
597 NameStrings = toStringRef(Input: UncompressedNameStrings);
598 } else {
599 NameStrings =
600 StringRef(reinterpret_cast<const char *>(P), UncompressedSize);
601 P += UncompressedSize;
602 }
603 // Now parse the name strings.
604 SmallVector<StringRef, 0> Names;
605 NameStrings.split(A&: Names, Separator: getInstrProfNameSeparator());
606 for (StringRef &Name : Names)
607 if (Error E = NameCallback(Name))
608 return E;
609
610 while (P < EndP && *P == 0)
611 P++;
612 }
613 return Error::success();
614}
615
616Error InstrProfSymtab::create(StringRef NameStrings) {
617 return readAndDecodeStrings(NameStrings,
618 NameCallback: [&](StringRef S) { return addFuncName(FuncName: S); });
619}
620
621Error InstrProfSymtab::create(StringRef FuncNameStrings,
622 StringRef VTableNameStrings) {
623 if (Error E = readAndDecodeStrings(
624 NameStrings: FuncNameStrings, NameCallback: [&](StringRef S) { return addFuncName(FuncName: S); }))
625 return E;
626
627 return readAndDecodeStrings(NameStrings: VTableNameStrings,
628 NameCallback: [&](StringRef S) { return addVTableName(VTableName: S); });
629}
630
631Error InstrProfSymtab::initVTableNamesFromCompressedStrings(
632 StringRef CompressedVTableStrings) {
633 return readAndDecodeStrings(NameStrings: CompressedVTableStrings,
634 NameCallback: [&](StringRef S) { return addVTableName(VTableName: S); });
635}
636
637StringRef InstrProfSymtab::getCanonicalName(StringRef PGOName) {
638 // In ThinLTO, local function may have been promoted to global and have
639 // suffix ".llvm." added to the function name. We need to add the
640 // stripped function name to the symbol table so that we can find a match
641 // from profile.
642 //
643 // ".__uniq." suffix is used to differentiate internal linkage functions in
644 // different modules and should be kept. This is the only suffix with the
645 // pattern ".xxx" which is kept before matching, other suffixes ".llvm." and
646 // ".part" will be stripped.
647 //
648 // Leverage the common canonicalization logic from FunctionSamples. Instead of
649 // removing all suffixes except ".__uniq.", explicitly specify the ones to be
650 // removed. This avoids the issue of colliding the canonical names of
651 // coroutine function with its await suspend wrappers or with its post-split
652 // clones. i.e. coro function foo, its wrappers
653 // (foo.__await_suspend_wrapper__init, and foo.__await_suspend_wrapper__final)
654 // and its post-split clones (foo.resume, foo.cleanup) are all canonicalized
655 // to "foo" otherwise, which can make the symtab lookup return unexpected
656 // result.
657 const SmallVector<StringRef> SuffixesToRemove{".llvm.", ".part."};
658 return FunctionSamples::getCanonicalFnName(FnName: PGOName, Suffixes: SuffixesToRemove);
659}
660
661Error InstrProfSymtab::addFuncWithName(Function &F, StringRef PGOFuncName,
662 bool AddCanonical) {
663 auto NameToGUIDMap = [&](StringRef Name) -> Error {
664 if (Error E = addFuncName(FuncName: Name))
665 return E;
666 MD5FuncMap.emplace_back(args: Function::getGUIDAssumingExternalLinkage(GlobalName: Name), args: &F);
667 return Error::success();
668 };
669 if (Error E = NameToGUIDMap(PGOFuncName))
670 return E;
671
672 if (!AddCanonical)
673 return Error::success();
674
675 StringRef CanonicalFuncName = getCanonicalName(PGOName: PGOFuncName);
676 if (CanonicalFuncName != PGOFuncName)
677 return NameToGUIDMap(CanonicalFuncName);
678
679 return Error::success();
680}
681
682uint64_t InstrProfSymtab::getVTableHashFromAddress(uint64_t Address) const {
683 // Given a runtime address, look up the hash value in the interval map, and
684 // fallback to value 0 if a hash value is not found.
685 return VTableAddrMap.lookup(x: Address, NotFound: 0);
686}
687
688uint64_t InstrProfSymtab::getFunctionHashFromAddress(uint64_t Address) const {
689 finalizeSymtab();
690 auto It = partition_point(Range&: AddrToMD5Map, P: [=](std::pair<uint64_t, uint64_t> A) {
691 return A.first < Address;
692 });
693 // Raw function pointer collected by value profiler may be from
694 // external functions that are not instrumented. They won't have
695 // mapping data to be used by the deserializer. Force the value to
696 // be 0 in this case.
697 if (It != AddrToMD5Map.end() && It->first == Address)
698 return (uint64_t)It->second;
699 return 0;
700}
701
702void InstrProfSymtab::dumpNames(raw_ostream &OS) const {
703 SmallVector<StringRef, 0> Sorted(NameTab.keys());
704 llvm::sort(C&: Sorted);
705 for (StringRef S : Sorted)
706 OS << S << '\n';
707}
708
709Error collectGlobalObjectNameStrings(ArrayRef<std::string> NameStrs,
710 bool DoCompression, std::string &Result) {
711 assert(!NameStrs.empty() && "No name data to emit");
712
713 uint8_t Header[20], *P = Header;
714 std::string UncompressedNameStrings =
715 join(Begin: NameStrs.begin(), End: NameStrs.end(), Separator: getInstrProfNameSeparator());
716
717 assert(StringRef(UncompressedNameStrings)
718 .count(getInstrProfNameSeparator()) == (NameStrs.size() - 1) &&
719 "PGO name is invalid (contains separator token)");
720
721 unsigned EncLen = encodeULEB128(Value: UncompressedNameStrings.length(), p: P);
722 P += EncLen;
723
724 auto WriteStringToResult = [&](size_t CompressedLen, StringRef InputStr) {
725 EncLen = encodeULEB128(Value: CompressedLen, p: P);
726 P += EncLen;
727 char *HeaderStr = reinterpret_cast<char *>(&Header[0]);
728 unsigned HeaderLen = P - &Header[0];
729 Result.append(s: HeaderStr, n: HeaderLen);
730 Result += InputStr;
731 return Error::success();
732 };
733
734 if (!DoCompression) {
735 return WriteStringToResult(0, UncompressedNameStrings);
736 }
737
738 SmallVector<uint8_t, 128> CompressedNameStrings;
739 compression::zlib::compress(Input: arrayRefFromStringRef(Input: UncompressedNameStrings),
740 CompressedBuffer&: CompressedNameStrings,
741 Level: compression::zlib::BestSizeCompression);
742
743 return WriteStringToResult(CompressedNameStrings.size(),
744 toStringRef(Input: CompressedNameStrings));
745}
746
747StringRef getPGOFuncNameVarInitializer(GlobalVariable *NameVar) {
748 auto *Arr = cast<ConstantDataArray>(Val: NameVar->getInitializer());
749 StringRef NameStr =
750 Arr->isCString() ? Arr->getAsCString() : Arr->getAsString();
751 return NameStr;
752}
753
754Error collectPGOFuncNameStrings(ArrayRef<GlobalVariable *> NameVars,
755 std::string &Result, bool DoCompression) {
756 std::vector<std::string> NameStrs;
757 for (auto *NameVar : NameVars) {
758 NameStrs.push_back(x: std::string(getPGOFuncNameVarInitializer(NameVar)));
759 }
760 return collectGlobalObjectNameStrings(
761 NameStrs, DoCompression: compression::zlib::isAvailable() && DoCompression, Result);
762}
763
764Error collectVTableStrings(ArrayRef<GlobalVariable *> VTables,
765 std::string &Result, bool DoCompression) {
766 std::vector<std::string> VTableNameStrs;
767 for (auto *VTable : VTables)
768 VTableNameStrs.push_back(x: getPGOName(V: *VTable));
769 return collectGlobalObjectNameStrings(
770 NameStrs: VTableNameStrs, DoCompression: compression::zlib::isAvailable() && DoCompression,
771 Result);
772}
773
774void InstrProfRecord::accumulateCounts(CountSumOrPercent &Sum) const {
775 uint64_t FuncSum = 0;
776 Sum.NumEntries += Counts.size();
777 for (uint64_t Count : Counts)
778 FuncSum += Count;
779 Sum.CountSum += FuncSum;
780
781 for (uint32_t VK = IPVK_First; VK <= IPVK_Last; ++VK) {
782 uint64_t KindSum = 0;
783 uint32_t NumValueSites = getNumValueSites(ValueKind: VK);
784 for (size_t I = 0; I < NumValueSites; ++I) {
785 for (const auto &V : getValueArrayForSite(ValueKind: VK, Site: I))
786 KindSum += V.Count;
787 }
788 Sum.ValueCounts[VK] += KindSum;
789 }
790}
791
792void InstrProfValueSiteRecord::overlap(InstrProfValueSiteRecord &Input,
793 uint32_t ValueKind,
794 OverlapStats &Overlap,
795 OverlapStats &FuncLevelOverlap) {
796 this->sortByTargetValues();
797 Input.sortByTargetValues();
798 double Score = 0.0f, FuncLevelScore = 0.0f;
799 auto I = ValueData.begin();
800 auto IE = ValueData.end();
801 auto J = Input.ValueData.begin();
802 auto JE = Input.ValueData.end();
803 while (I != IE && J != JE) {
804 if (I->Value == J->Value) {
805 Score += OverlapStats::score(Val1: I->Count, Val2: J->Count,
806 Sum1: Overlap.Base.ValueCounts[ValueKind],
807 Sum2: Overlap.Test.ValueCounts[ValueKind]);
808 FuncLevelScore += OverlapStats::score(
809 Val1: I->Count, Val2: J->Count, Sum1: FuncLevelOverlap.Base.ValueCounts[ValueKind],
810 Sum2: FuncLevelOverlap.Test.ValueCounts[ValueKind]);
811 ++I;
812 } else if (I->Value < J->Value) {
813 ++I;
814 continue;
815 }
816 ++J;
817 }
818 Overlap.Overlap.ValueCounts[ValueKind] += Score;
819 FuncLevelOverlap.Overlap.ValueCounts[ValueKind] += FuncLevelScore;
820}
821
822// Return false on mismatch.
823void InstrProfRecord::overlapValueProfData(uint32_t ValueKind,
824 InstrProfRecord &Other,
825 OverlapStats &Overlap,
826 OverlapStats &FuncLevelOverlap) {
827 uint32_t ThisNumValueSites = getNumValueSites(ValueKind);
828 assert(ThisNumValueSites == Other.getNumValueSites(ValueKind));
829 if (!ThisNumValueSites)
830 return;
831
832 std::vector<InstrProfValueSiteRecord> &ThisSiteRecords =
833 getOrCreateValueSitesForKind(ValueKind);
834 MutableArrayRef<InstrProfValueSiteRecord> OtherSiteRecords =
835 Other.getValueSitesForKind(ValueKind);
836 for (uint32_t I = 0; I < ThisNumValueSites; I++)
837 ThisSiteRecords[I].overlap(Input&: OtherSiteRecords[I], ValueKind, Overlap,
838 FuncLevelOverlap);
839}
840
841void InstrProfRecord::overlap(InstrProfRecord &Other, OverlapStats &Overlap,
842 OverlapStats &FuncLevelOverlap,
843 uint64_t ValueCutoff) {
844 // FuncLevel CountSum for other should already computed and nonzero.
845 assert(FuncLevelOverlap.Test.CountSum >= 1.0f);
846 accumulateCounts(Sum&: FuncLevelOverlap.Base);
847 bool Mismatch = (Counts.size() != Other.Counts.size());
848
849 // Check if the value profiles mismatch.
850 if (!Mismatch) {
851 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind) {
852 uint32_t ThisNumValueSites = getNumValueSites(ValueKind: Kind);
853 uint32_t OtherNumValueSites = Other.getNumValueSites(ValueKind: Kind);
854 if (ThisNumValueSites != OtherNumValueSites) {
855 Mismatch = true;
856 break;
857 }
858 }
859 }
860 if (Mismatch) {
861 Overlap.addOneMismatch(MismatchFunc: FuncLevelOverlap.Test);
862 return;
863 }
864
865 // Compute overlap for value counts.
866 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
867 overlapValueProfData(ValueKind: Kind, Other, Overlap, FuncLevelOverlap);
868
869 double Score = 0.0;
870 uint64_t MaxCount = 0;
871 // Compute overlap for edge counts.
872 for (size_t I = 0, E = Other.Counts.size(); I < E; ++I) {
873 Score += OverlapStats::score(Val1: Counts[I], Val2: Other.Counts[I],
874 Sum1: Overlap.Base.CountSum, Sum2: Overlap.Test.CountSum);
875 MaxCount = std::max(a: Other.Counts[I], b: MaxCount);
876 }
877 Overlap.Overlap.CountSum += Score;
878 Overlap.Overlap.NumEntries += 1;
879
880 if (MaxCount >= ValueCutoff) {
881 double FuncScore = 0.0;
882 for (size_t I = 0, E = Other.Counts.size(); I < E; ++I)
883 FuncScore += OverlapStats::score(Val1: Counts[I], Val2: Other.Counts[I],
884 Sum1: FuncLevelOverlap.Base.CountSum,
885 Sum2: FuncLevelOverlap.Test.CountSum);
886 FuncLevelOverlap.Overlap.CountSum = FuncScore;
887 FuncLevelOverlap.Overlap.NumEntries = Other.Counts.size();
888 FuncLevelOverlap.Valid = true;
889 }
890}
891
892void InstrProfValueSiteRecord::merge(InstrProfValueSiteRecord &Input,
893 uint64_t Weight,
894 function_ref<void(instrprof_error)> Warn) {
895 this->sortByTargetValues();
896 Input.sortByTargetValues();
897 auto I = ValueData.begin();
898 auto IE = ValueData.end();
899 std::vector<InstrProfValueData> Merged;
900 Merged.reserve(n: std::max(a: ValueData.size(), b: Input.ValueData.size()));
901 for (const InstrProfValueData &J : Input.ValueData) {
902 while (I != IE && I->Value < J.Value) {
903 Merged.push_back(x: *I);
904 ++I;
905 }
906 if (I != IE && I->Value == J.Value) {
907 bool Overflowed;
908 I->Count = SaturatingMultiplyAdd(X: J.Count, Y: Weight, A: I->Count, ResultOverflowed: &Overflowed);
909 if (Overflowed)
910 Warn(instrprof_error::counter_overflow);
911 Merged.push_back(x: *I);
912 ++I;
913 continue;
914 }
915 Merged.push_back(x: J);
916 }
917 Merged.insert(position: Merged.end(), first: I, last: IE);
918 ValueData = std::move(Merged);
919}
920
921void InstrProfValueSiteRecord::scale(uint64_t N, uint64_t D,
922 function_ref<void(instrprof_error)> Warn) {
923 for (InstrProfValueData &I : ValueData) {
924 bool Overflowed;
925 I.Count = SaturatingMultiply(X: I.Count, Y: N, ResultOverflowed: &Overflowed) / D;
926 if (Overflowed)
927 Warn(instrprof_error::counter_overflow);
928 }
929}
930
931// Merge Value Profile data from Src record to this record for ValueKind.
932// Scale merged value counts by \p Weight.
933void InstrProfRecord::mergeValueProfData(
934 uint32_t ValueKind, InstrProfRecord &Src, uint64_t Weight,
935 function_ref<void(instrprof_error)> Warn) {
936 uint32_t ThisNumValueSites = getNumValueSites(ValueKind);
937 uint32_t OtherNumValueSites = Src.getNumValueSites(ValueKind);
938 if (ThisNumValueSites != OtherNumValueSites) {
939 Warn(instrprof_error::value_site_count_mismatch);
940 return;
941 }
942 if (!ThisNumValueSites)
943 return;
944 std::vector<InstrProfValueSiteRecord> &ThisSiteRecords =
945 getOrCreateValueSitesForKind(ValueKind);
946 MutableArrayRef<InstrProfValueSiteRecord> OtherSiteRecords =
947 Src.getValueSitesForKind(ValueKind);
948 for (uint32_t I = 0; I < ThisNumValueSites; I++)
949 ThisSiteRecords[I].merge(Input&: OtherSiteRecords[I], Weight, Warn);
950}
951
952void InstrProfRecord::computeBlockUniformity() {
953 if (UniformCounts.empty())
954 return;
955
956 if (UniformCounts.size() != Counts.size()) {
957 UniformityBits.clear();
958 return;
959 }
960
961 UniformityBits.assign(n: (Counts.size() + 7) / 8, val: 0xFF);
962 for (size_t I = 0, E = Counts.size(); I < E; ++I) {
963 uint64_t TotalCount = Counts[I];
964 uint64_t UniformCount = UniformCounts[I];
965 bool IsUniform =
966 TotalCount == 0 || (double)UniformCount / TotalCount >= 0.9;
967 if (!IsUniform)
968 UniformityBits[I / 8] &= ~(1 << (I % 8));
969 }
970}
971
972static void mergeUniformityBits(std::vector<uint8_t> &Dst,
973 ArrayRef<uint8_t> Src) {
974 if (Dst.empty()) {
975 Dst.assign(first: Src.begin(), last: Src.end());
976 return;
977 }
978 if (Src.empty())
979 return;
980
981 if (Dst.size() != Src.size()) {
982 Dst.clear();
983 return;
984 }
985
986 for (size_t I = 0, E = Src.size(); I < E; ++I)
987 Dst[I] &= Src[I];
988}
989
990void InstrProfRecord::merge(InstrProfRecord &Other, uint64_t Weight,
991 function_ref<void(instrprof_error)> Warn) {
992 // If the number of counters doesn't match we either have bad data
993 // or a hash collision.
994 if (Counts.size() != Other.Counts.size()) {
995 Warn(instrprof_error::count_mismatch);
996 return;
997 }
998
999 computeBlockUniformity();
1000 Other.computeBlockUniformity();
1001
1002 // Special handling of the first count as the PseudoCount.
1003 CountPseudoKind OtherKind = Other.getCountPseudoKind();
1004 CountPseudoKind ThisKind = getCountPseudoKind();
1005 if (OtherKind != NotPseudo || ThisKind != NotPseudo) {
1006 // We don't allow the merge of a profile with pseudo counts and
1007 // a normal profile (i.e. without pesudo counts).
1008 // Profile supplimenation should be done after the profile merge.
1009 if (OtherKind == NotPseudo || ThisKind == NotPseudo) {
1010 Warn(instrprof_error::count_mismatch);
1011 return;
1012 }
1013 if (OtherKind == PseudoHot || ThisKind == PseudoHot)
1014 setPseudoCount(PseudoHot);
1015 else
1016 setPseudoCount(PseudoWarm);
1017 return;
1018 }
1019 OffloadDeviceWaveSize = Other.OffloadDeviceWaveSize;
1020 bool HasUniformCounts = !UniformCounts.empty();
1021 bool OtherHasUniformCounts = !Other.UniformCounts.empty();
1022 for (size_t I = 0, E = Other.Counts.size(); I < E; ++I) {
1023 bool Overflowed;
1024 uint64_t Value =
1025 SaturatingMultiplyAdd(X: Other.Counts[I], Y: Weight, A: Counts[I], ResultOverflowed: &Overflowed);
1026 if (Value > getInstrMaxCountValue()) {
1027 Value = getInstrMaxCountValue();
1028 Overflowed = true;
1029 }
1030 Counts[I] = Value;
1031 if (Overflowed)
1032 Warn(instrprof_error::counter_overflow);
1033 }
1034
1035 if (HasUniformCounts && OtherHasUniformCounts) {
1036 if (UniformCounts.size() != Other.UniformCounts.size()) {
1037 UniformCounts.clear();
1038 UniformityBits.clear();
1039 } else {
1040 for (size_t I = 0, E = Other.UniformCounts.size(); I < E; ++I) {
1041 bool Overflowed;
1042 UniformCounts[I] = SaturatingMultiplyAdd(X: Other.UniformCounts[I], Y: Weight,
1043 A: UniformCounts[I], ResultOverflowed: &Overflowed);
1044 if (UniformCounts[I] > getInstrMaxCountValue()) {
1045 UniformCounts[I] = getInstrMaxCountValue();
1046 Overflowed = true;
1047 }
1048 if (Overflowed)
1049 Warn(instrprof_error::counter_overflow);
1050 }
1051 computeBlockUniformity();
1052 }
1053 } else {
1054 UniformCounts.clear();
1055 mergeUniformityBits(Dst&: UniformityBits, Src: Other.UniformityBits);
1056 }
1057
1058 // If the number of bitmap bytes doesn't match we either have bad data
1059 // or a hash collision.
1060 if (BitmapBytes.size() != Other.BitmapBytes.size()) {
1061 Warn(instrprof_error::bitmap_mismatch);
1062 return;
1063 }
1064
1065 // Bitmap bytes are merged by simply ORing them together.
1066 for (size_t I = 0, E = Other.BitmapBytes.size(); I < E; ++I) {
1067 BitmapBytes[I] = Other.BitmapBytes[I] | BitmapBytes[I];
1068 }
1069
1070 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
1071 mergeValueProfData(ValueKind: Kind, Src&: Other, Weight, Warn);
1072}
1073
1074void InstrProfRecord::scaleValueProfData(
1075 uint32_t ValueKind, uint64_t N, uint64_t D,
1076 function_ref<void(instrprof_error)> Warn) {
1077 for (auto &R : getValueSitesForKind(ValueKind))
1078 R.scale(N, D, Warn);
1079}
1080
1081void InstrProfRecord::scale(uint64_t N, uint64_t D,
1082 function_ref<void(instrprof_error)> Warn) {
1083 assert(D != 0 && "D cannot be 0");
1084 for (auto &Count : this->Counts) {
1085 bool Overflowed;
1086 Count = SaturatingMultiply(X: Count, Y: N, ResultOverflowed: &Overflowed) / D;
1087 if (Count > getInstrMaxCountValue()) {
1088 Count = getInstrMaxCountValue();
1089 Overflowed = true;
1090 }
1091 if (Overflowed)
1092 Warn(instrprof_error::counter_overflow);
1093 }
1094 for (auto &Count : this->UniformCounts) {
1095 bool Overflowed;
1096 Count = SaturatingMultiply(X: Count, Y: N, ResultOverflowed: &Overflowed) / D;
1097 if (Count > getInstrMaxCountValue()) {
1098 Count = getInstrMaxCountValue();
1099 Overflowed = true;
1100 }
1101 if (Overflowed)
1102 Warn(instrprof_error::counter_overflow);
1103 }
1104 computeBlockUniformity();
1105 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
1106 scaleValueProfData(ValueKind: Kind, N, D, Warn);
1107}
1108
1109// Map indirect call target name hash to name string.
1110uint64_t InstrProfRecord::remapValue(uint64_t Value, uint32_t ValueKind,
1111 InstrProfSymtab *SymTab) {
1112 if (!SymTab)
1113 return Value;
1114
1115 if (ValueKind == IPVK_IndirectCallTarget)
1116 return SymTab->getFunctionHashFromAddress(Address: Value);
1117
1118 if (ValueKind == IPVK_VTableTarget)
1119 return SymTab->getVTableHashFromAddress(Address: Value);
1120
1121 return Value;
1122}
1123
1124void InstrProfRecord::addValueData(uint32_t ValueKind, uint32_t Site,
1125 ArrayRef<InstrProfValueData> VData,
1126 InstrProfSymtab *ValueMap) {
1127 // Remap values.
1128 std::vector<InstrProfValueData> RemappedVD;
1129 RemappedVD.reserve(n: VData.size());
1130 for (const auto &V : VData) {
1131 uint64_t NewValue = remapValue(Value: V.Value, ValueKind, SymTab: ValueMap);
1132 RemappedVD.push_back(x: {.Value: NewValue, .Count: V.Count});
1133 }
1134
1135 std::vector<InstrProfValueSiteRecord> &ValueSites =
1136 getOrCreateValueSitesForKind(ValueKind);
1137 assert(ValueSites.size() == Site);
1138
1139 // Add a new value site with remapped value profiling data.
1140 ValueSites.emplace_back(args: std::move(RemappedVD));
1141}
1142
1143void TemporalProfTraceTy::createBPFunctionNodes(
1144 ArrayRef<TemporalProfTraceTy> Traces, std::vector<BPFunctionNode> &Nodes,
1145 bool RemoveOutlierUNs) {
1146 using IDT = BPFunctionNode::IDT;
1147 using UtilityNodeT = BPFunctionNode::UtilityNodeT;
1148 UtilityNodeT MaxUN = 0;
1149 DenseMap<IDT, size_t> IdToFirstTimestamp;
1150 DenseMap<IDT, UtilityNodeT> IdToFirstUN;
1151 DenseMap<IDT, SmallVector<UtilityNodeT>> IdToUNs;
1152 // TODO: We need to use the Trace.Weight field to give more weight to more
1153 // important utilities
1154 for (auto &Trace : Traces) {
1155 size_t CutoffTimestamp = 1;
1156 for (size_t Timestamp = 0; Timestamp < Trace.FunctionNameRefs.size();
1157 Timestamp++) {
1158 IDT Id = Trace.FunctionNameRefs[Timestamp];
1159 auto [It, WasInserted] = IdToFirstTimestamp.try_emplace(Key: Id, Args&: Timestamp);
1160 if (!WasInserted)
1161 It->getSecond() = std::min<size_t>(a: It->getSecond(), b: Timestamp);
1162 if (Timestamp >= CutoffTimestamp) {
1163 ++MaxUN;
1164 CutoffTimestamp = 2 * Timestamp;
1165 }
1166 IdToFirstUN.try_emplace(Key: Id, Args&: MaxUN);
1167 }
1168 for (auto &[Id, FirstUN] : IdToFirstUN)
1169 for (auto UN = FirstUN; UN <= MaxUN; ++UN)
1170 IdToUNs[Id].push_back(Elt: UN);
1171 ++MaxUN;
1172 IdToFirstUN.clear();
1173 }
1174
1175 if (RemoveOutlierUNs) {
1176 DenseMap<UtilityNodeT, unsigned> UNFrequency;
1177 for (auto &[Id, UNs] : IdToUNs)
1178 for (auto &UN : UNs)
1179 ++UNFrequency[UN];
1180 // Filter out utility nodes that are too infrequent or too prevalent to make
1181 // BalancedPartitioning more effective.
1182 for (auto &[Id, UNs] : IdToUNs)
1183 llvm::erase_if(C&: UNs, P: [&](auto &UN) {
1184 unsigned Freq = UNFrequency[UN];
1185 return Freq <= 1 || 2 * Freq > IdToUNs.size();
1186 });
1187 }
1188
1189 for (auto &[Id, UNs] : IdToUNs)
1190 Nodes.emplace_back(args&: Id, args&: UNs);
1191
1192 // Since BalancedPartitioning is sensitive to the initial order, we explicitly
1193 // order nodes by their earliest timestamp.
1194 llvm::sort(C&: Nodes, Comp: [&](auto &L, auto &R) {
1195 return std::make_pair(IdToFirstTimestamp[L.Id], L.Id) <
1196 std::make_pair(IdToFirstTimestamp[R.Id], R.Id);
1197 });
1198}
1199
1200#define INSTR_PROF_COMMON_API_IMPL
1201#include "llvm/ProfileData/InstrProfData.inc"
1202
1203/*!
1204 * ValueProfRecordClosure Interface implementation for InstrProfRecord
1205 * class. These C wrappers are used as adaptors so that C++ code can be
1206 * invoked as callbacks.
1207 */
1208uint32_t getNumValueKindsInstrProf(const void *Record) {
1209 return reinterpret_cast<const InstrProfRecord *>(Record)->getNumValueKinds();
1210}
1211
1212uint32_t getNumValueSitesInstrProf(const void *Record, uint32_t VKind) {
1213 return reinterpret_cast<const InstrProfRecord *>(Record)
1214 ->getNumValueSites(ValueKind: VKind);
1215}
1216
1217uint32_t getNumValueDataInstrProf(const void *Record, uint32_t VKind) {
1218 return reinterpret_cast<const InstrProfRecord *>(Record)
1219 ->getNumValueData(ValueKind: VKind);
1220}
1221
1222uint32_t getNumValueDataForSiteInstrProf(const void *R, uint32_t VK,
1223 uint32_t S) {
1224 const auto *IPR = reinterpret_cast<const InstrProfRecord *>(R);
1225 return IPR->getValueArrayForSite(ValueKind: VK, Site: S).size();
1226}
1227
1228void getValueForSiteInstrProf(const void *R, InstrProfValueData *Dst,
1229 uint32_t K, uint32_t S) {
1230 const auto *IPR = reinterpret_cast<const InstrProfRecord *>(R);
1231 llvm::copy(Range: IPR->getValueArrayForSite(ValueKind: K, Site: S), Out: Dst);
1232}
1233
1234ValueProfData *allocValueProfDataInstrProf(size_t TotalSizeInBytes) {
1235 ValueProfData *VD = new (::operator new(TotalSizeInBytes)) ValueProfData();
1236 memset(s: VD, c: 0, n: TotalSizeInBytes);
1237 return VD;
1238}
1239
1240static ValueProfRecordClosure InstrProfRecordClosure = {
1241 .Record: nullptr,
1242 .GetNumValueKinds: getNumValueKindsInstrProf,
1243 .GetNumValueSites: getNumValueSitesInstrProf,
1244 .GetNumValueData: getNumValueDataInstrProf,
1245 .GetNumValueDataForSite: getNumValueDataForSiteInstrProf,
1246 .RemapValueData: nullptr,
1247 .GetValueForSite: getValueForSiteInstrProf,
1248 .AllocValueProfData: allocValueProfDataInstrProf};
1249
1250// Wrapper implementation using the closure mechanism.
1251uint32_t ValueProfData::getSize(const InstrProfRecord &Record) {
1252 auto Closure = InstrProfRecordClosure;
1253 Closure.Record = &Record;
1254 return getValueProfDataSize(Closure: &Closure);
1255}
1256
1257// Wrapper implementation using the closure mechanism.
1258std::unique_ptr<ValueProfData>
1259ValueProfData::serializeFrom(const InstrProfRecord &Record) {
1260 InstrProfRecordClosure.Record = &Record;
1261
1262 std::unique_ptr<ValueProfData> VPD(
1263 serializeValueProfDataFrom(Closure: &InstrProfRecordClosure, DstData: nullptr));
1264 return VPD;
1265}
1266
1267void ValueProfRecord::deserializeTo(InstrProfRecord &Record,
1268 InstrProfSymtab *SymTab) {
1269 Record.reserveSites(ValueKind: Kind, NumValueSites);
1270
1271 InstrProfValueData *ValueData = getValueProfRecordValueData(This: this);
1272 for (uint64_t VSite = 0; VSite < NumValueSites; ++VSite) {
1273 uint8_t ValueDataCount = this->SiteCountArray[VSite];
1274 ArrayRef<InstrProfValueData> VDs(ValueData, ValueDataCount);
1275 Record.addValueData(ValueKind: Kind, Site: VSite, VData: VDs, ValueMap: SymTab);
1276 ValueData += ValueDataCount;
1277 }
1278}
1279
1280// For writing/serializing, Old is the host endianness, and New is
1281// byte order intended on disk. For Reading/deserialization, Old
1282// is the on-disk source endianness, and New is the host endianness.
1283void ValueProfRecord::swapBytes(llvm::endianness Old, llvm::endianness New) {
1284 using namespace support;
1285
1286 if (Old == New)
1287 return;
1288
1289 if (llvm::endianness::native != Old) {
1290 sys::swapByteOrder<uint32_t>(Value&: NumValueSites);
1291 sys::swapByteOrder<uint32_t>(Value&: Kind);
1292 }
1293 uint32_t ND = getValueProfRecordNumValueData(This: this);
1294 InstrProfValueData *VD = getValueProfRecordValueData(This: this);
1295
1296 // No need to swap byte array: SiteCountArrray.
1297 for (uint32_t I = 0; I < ND; I++) {
1298 sys::swapByteOrder<uint64_t>(Value&: VD[I].Value);
1299 sys::swapByteOrder<uint64_t>(Value&: VD[I].Count);
1300 }
1301 if (llvm::endianness::native == Old) {
1302 sys::swapByteOrder<uint32_t>(Value&: NumValueSites);
1303 sys::swapByteOrder<uint32_t>(Value&: Kind);
1304 }
1305}
1306
1307void ValueProfData::deserializeTo(InstrProfRecord &Record,
1308 InstrProfSymtab *SymTab) {
1309 if (NumValueKinds == 0)
1310 return;
1311
1312 ValueProfRecord *VR = getFirstValueProfRecord(This: this);
1313 for (uint32_t K = 0; K < NumValueKinds; K++) {
1314 VR->deserializeTo(Record, SymTab);
1315 VR = getValueProfRecordNext(This: VR);
1316 }
1317}
1318
1319static std::unique_ptr<ValueProfData> allocValueProfData(uint32_t TotalSize) {
1320 return std::unique_ptr<ValueProfData>(new (::operator new(TotalSize))
1321 ValueProfData());
1322}
1323
1324Error ValueProfData::checkIntegrity() {
1325 if (NumValueKinds > IPVK_Last + 1)
1326 return make_error<InstrProfError>(
1327 Args: instrprof_error::malformed, Args: "number of value profile kinds is invalid");
1328 // Total size needs to be multiple of quadword size.
1329 if (TotalSize % sizeof(uint64_t))
1330 return make_error<InstrProfError>(
1331 Args: instrprof_error::malformed, Args: "total size is not multiples of quardword");
1332
1333 ValueProfRecord *VR = getFirstValueProfRecord(This: this);
1334 for (uint32_t K = 0; K < this->NumValueKinds; K++) {
1335 if (VR->Kind > IPVK_Last)
1336 return make_error<InstrProfError>(Args: instrprof_error::malformed,
1337 Args: "value kind is invalid");
1338 VR = getValueProfRecordNext(This: VR);
1339 if ((char *)VR - (char *)this > (ptrdiff_t)TotalSize)
1340 return make_error<InstrProfError>(
1341 Args: instrprof_error::malformed,
1342 Args: "value profile address is greater than total size");
1343 }
1344 return Error::success();
1345}
1346
1347Expected<std::unique_ptr<ValueProfData>>
1348ValueProfData::getValueProfData(const unsigned char *D,
1349 const unsigned char *const BufferEnd,
1350 llvm::endianness Endianness) {
1351 using namespace support;
1352
1353 if (D + sizeof(ValueProfData) > BufferEnd)
1354 return make_error<InstrProfError>(Args: instrprof_error::truncated);
1355
1356 const unsigned char *Header = D;
1357 uint32_t TotalSize = endian::readNext<uint32_t>(memory&: Header, endian: Endianness);
1358
1359 if (D + TotalSize > BufferEnd)
1360 return make_error<InstrProfError>(Args: instrprof_error::too_large);
1361
1362 std::unique_ptr<ValueProfData> VPD = allocValueProfData(TotalSize);
1363 memcpy(dest: VPD.get(), src: D, n: TotalSize);
1364 // Byte swap.
1365 VPD->swapBytesToHost(Endianness);
1366
1367 Error E = VPD->checkIntegrity();
1368 if (E)
1369 return std::move(E);
1370
1371 return std::move(VPD);
1372}
1373
1374void ValueProfData::swapBytesToHost(llvm::endianness Endianness) {
1375 using namespace support;
1376
1377 if (Endianness == llvm::endianness::native)
1378 return;
1379
1380 sys::swapByteOrder<uint32_t>(Value&: TotalSize);
1381 sys::swapByteOrder<uint32_t>(Value&: NumValueKinds);
1382
1383 ValueProfRecord *VR = getFirstValueProfRecord(This: this);
1384 for (uint32_t K = 0; K < NumValueKinds; K++) {
1385 VR->swapBytes(Old: Endianness, New: llvm::endianness::native);
1386 VR = getValueProfRecordNext(This: VR);
1387 }
1388}
1389
1390void ValueProfData::swapBytesFromHost(llvm::endianness Endianness) {
1391 using namespace support;
1392
1393 if (Endianness == llvm::endianness::native)
1394 return;
1395
1396 ValueProfRecord *VR = getFirstValueProfRecord(This: this);
1397 for (uint32_t K = 0; K < NumValueKinds; K++) {
1398 ValueProfRecord *NVR = getValueProfRecordNext(This: VR);
1399 VR->swapBytes(Old: llvm::endianness::native, New: Endianness);
1400 VR = NVR;
1401 }
1402 sys::swapByteOrder<uint32_t>(Value&: TotalSize);
1403 sys::swapByteOrder<uint32_t>(Value&: NumValueKinds);
1404}
1405
1406void annotateValueSite(Module &M, Instruction &Inst,
1407 const InstrProfRecord &InstrProfR,
1408 InstrProfValueKind ValueKind, uint32_t SiteIdx,
1409 uint32_t MaxMDCount) {
1410 auto VDs = InstrProfR.getValueArrayForSite(ValueKind, Site: SiteIdx);
1411 if (VDs.empty())
1412 return;
1413 uint64_t Sum = 0;
1414 for (const InstrProfValueData &V : VDs)
1415 Sum = SaturatingAdd(X: Sum, Y: V.Count);
1416 annotateValueSite(M, Inst, VDs, Sum, ValueKind, MaxMDCount);
1417}
1418
1419void annotateValueSite(Module &M, Instruction &Inst,
1420 ArrayRef<InstrProfValueData> VDs,
1421 uint64_t Sum, InstrProfValueKind ValueKind,
1422 uint32_t MaxMDCount) {
1423 if (VDs.empty())
1424 return;
1425 LLVMContext &Ctx = M.getContext();
1426 MDBuilder MDHelper(Ctx);
1427 SmallVector<Metadata *, 3> Vals;
1428 // Tag
1429 Vals.push_back(Elt: MDHelper.createString(Str: MDProfLabels::ValueProfile));
1430 // Value Kind
1431 Vals.push_back(Elt: MDHelper.createConstant(
1432 C: ConstantInt::get(Ty: Type::getInt32Ty(C&: Ctx), V: ValueKind)));
1433 // Total Count
1434 Vals.push_back(
1435 Elt: MDHelper.createConstant(C: ConstantInt::get(Ty: Type::getInt64Ty(C&: Ctx), V: Sum)));
1436
1437 // Value Profile Data
1438 uint32_t MDCount = MaxMDCount;
1439 // Zero values might occur multiple times (e.g., multiple functions that
1440 // cannot be remapped). Deduplicate them to enforce the variant that
1441 // values are unique, which allows passes to make some simplifying
1442 // assumptions.
1443 // TODO(boomanaiden154): This fits more naturally in addValueData, but
1444 // preserving the current behavior is necessary for some error handling
1445 // paths. When that gets cleaned up, we should move this there.
1446 // TODO(boomanaiden154): We are also deduplicating non-zero values.
1447 // These are rare and should only come from corrupted profiles, so we
1448 // just skip them. Remove this when they are fixed properly in
1449 // llvm-profdata.
1450 uint64_t ZeroCount = 0;
1451 DenseSet<uint64_t> VisitedValues;
1452 for (const auto &VD : VDs) {
1453 auto [_, ValueInserted] = VisitedValues.insert(V: VD.Value);
1454 if (VD.Value != 0 && !ValueInserted)
1455 continue;
1456 if (VD.Value == 0) {
1457 ZeroCount += VD.Count;
1458 } else {
1459 Vals.push_back(Elt: MDHelper.createConstant(
1460 C: ConstantInt::get(Ty: Type::getInt64Ty(C&: Ctx), V: VD.Value)));
1461 Vals.push_back(Elt: MDHelper.createConstant(
1462 C: ConstantInt::get(Ty: Type::getInt64Ty(C&: Ctx), V: VD.Count)));
1463 }
1464 if (--MDCount == 0)
1465 break;
1466 }
1467 if (ZeroCount != 0) {
1468 Vals.push_back(
1469 Elt: MDHelper.createConstant(C: ConstantInt::get(Ty: Type::getInt64Ty(C&: Ctx), V: 0)));
1470 Vals.push_back(Elt: MDHelper.createConstant(
1471 C: ConstantInt::get(Ty: Type::getInt64Ty(C&: Ctx), V: ZeroCount)));
1472 }
1473 // Only add metadata if we have at least one value. Otherwise we will end
1474 // up adding invalid metadata in the case where the profile only has a
1475 // zero value with a zero count.
1476 if (Vals.size() >= 5)
1477 Inst.setMetadata(KindID: LLVMContext::MD_prof, Node: MDNode::get(Context&: Ctx, MDs: Vals));
1478}
1479
1480MDNode *mayHaveValueProfileOfKind(const Instruction &Inst,
1481 InstrProfValueKind ValueKind) {
1482 MDNode *MD = Inst.getMetadata(KindID: LLVMContext::MD_prof);
1483 if (!MD)
1484 return nullptr;
1485
1486 if (MD->getNumOperands() < 5)
1487 return nullptr;
1488
1489 MDString *Tag = cast<MDString>(Val: MD->getOperand(I: 0));
1490 if (!Tag || Tag->getString() != MDProfLabels::ValueProfile)
1491 return nullptr;
1492
1493 // Now check kind:
1494 ConstantInt *KindInt = mdconst::dyn_extract<ConstantInt>(MD: MD->getOperand(I: 1));
1495 if (!KindInt)
1496 return nullptr;
1497 if (KindInt->getZExtValue() != ValueKind)
1498 return nullptr;
1499
1500 return MD;
1501}
1502
1503SmallVector<InstrProfValueData, 4>
1504getValueProfDataFromInst(const Instruction &Inst, InstrProfValueKind ValueKind,
1505 uint32_t MaxNumValueData, uint64_t &TotalC,
1506 bool GetNoICPValue) {
1507 // Four inline elements seem to work well in practice. With MaxNumValueData,
1508 // this array won't grow very big anyway.
1509 SmallVector<InstrProfValueData, 4> ValueData;
1510 MDNode *MD = mayHaveValueProfileOfKind(Inst, ValueKind);
1511 if (!MD)
1512 return ValueData;
1513 const unsigned NOps = MD->getNumOperands();
1514 // Get total count
1515 ConstantInt *TotalCInt = mdconst::dyn_extract<ConstantInt>(MD: MD->getOperand(I: 2));
1516 if (!TotalCInt)
1517 return ValueData;
1518 TotalC = TotalCInt->getZExtValue();
1519
1520 ValueData.reserve(N: (NOps - 3) / 2);
1521 for (unsigned I = 3; I < NOps; I += 2) {
1522 if (ValueData.size() >= MaxNumValueData)
1523 break;
1524 ConstantInt *Value = mdconst::dyn_extract<ConstantInt>(MD: MD->getOperand(I));
1525 ConstantInt *Count =
1526 mdconst::dyn_extract<ConstantInt>(MD: MD->getOperand(I: I + 1));
1527 if (!Value || !Count) {
1528 ValueData.clear();
1529 return ValueData;
1530 }
1531 uint64_t CntValue = Count->getZExtValue();
1532 if (!GetNoICPValue && (CntValue == NOMORE_ICP_MAGICNUM))
1533 continue;
1534 InstrProfValueData V;
1535 V.Value = Value->getZExtValue();
1536 V.Count = CntValue;
1537 ValueData.push_back(Elt: V);
1538 }
1539 return ValueData;
1540}
1541
1542MDNode *getPGOFuncNameMetadata(const Function &F) {
1543 return F.getMetadata(Kind: getPGOFuncNameMetadataName());
1544}
1545
1546static void createPGONameMetadata(GlobalObject &GO, StringRef MetadataName,
1547 StringRef PGOName) {
1548 // Only for internal linkage functions or global variables. The name is not
1549 // the same as PGO name for these global objects.
1550 if (GO.getName() == PGOName)
1551 return;
1552
1553 // Don't create duplicated metadata.
1554 if (GO.getMetadata(Kind: MetadataName))
1555 return;
1556
1557 LLVMContext &C = GO.getContext();
1558 MDNode *N = MDNode::get(Context&: C, MDs: MDString::get(Context&: C, Str: PGOName));
1559 GO.setMetadata(Kind: MetadataName, Node: N);
1560}
1561
1562void createPGOFuncNameMetadata(Function &F, StringRef PGOFuncName) {
1563 return createPGONameMetadata(GO&: F, MetadataName: getPGOFuncNameMetadataName(), PGOName: PGOFuncName);
1564}
1565
1566void createPGONameMetadata(GlobalObject &GO, StringRef PGOName) {
1567 return createPGONameMetadata(GO, MetadataName: getPGONameMetadataName(), PGOName);
1568}
1569
1570bool needsComdatForCounter(const GlobalObject &GO, const Module &M) {
1571 if (GO.hasComdat())
1572 return true;
1573
1574 if (!M.getTargetTriple().supportsCOMDAT())
1575 return false;
1576
1577 // See createPGOFuncNameVar for more details. To avoid link errors, profile
1578 // counters for function with available_externally linkage needs to be changed
1579 // to linkonce linkage. On ELF based systems, this leads to weak symbols to be
1580 // created. Without using comdat, duplicate entries won't be removed by the
1581 // linker leading to increased data segement size and raw profile size. Even
1582 // worse, since the referenced counter from profile per-function data object
1583 // will be resolved to the common strong definition, the profile counts for
1584 // available_externally functions will end up being duplicated in raw profile
1585 // data. This can result in distorted profile as the counts of those dups
1586 // will be accumulated by the profile merger.
1587 GlobalValue::LinkageTypes Linkage = GO.getLinkage();
1588 if (Linkage != GlobalValue::ExternalWeakLinkage &&
1589 Linkage != GlobalValue::AvailableExternallyLinkage)
1590 return false;
1591
1592 return true;
1593}
1594
1595// Check if INSTR_PROF_RAW_VERSION_VAR is defined.
1596bool isIRPGOFlagSet(const Module *M) {
1597 const GlobalVariable *IRInstrVar =
1598 M->getNamedGlobal(INSTR_PROF_QUOTE(INSTR_PROF_RAW_VERSION_VAR));
1599 if (!IRInstrVar || IRInstrVar->hasLocalLinkage())
1600 return false;
1601
1602 // For CSPGO+LTO, this variable might be marked as non-prevailing and we only
1603 // have the decl.
1604 if (IRInstrVar->isDeclaration())
1605 return true;
1606
1607 // Check if the flag is set.
1608 if (!IRInstrVar->hasInitializer())
1609 return false;
1610
1611 auto *InitVal = dyn_cast_or_null<ConstantInt>(Val: IRInstrVar->getInitializer());
1612 if (!InitVal)
1613 return false;
1614 return (InitVal->getZExtValue() & VARIANT_MASK_IR_PROF) != 0;
1615}
1616
1617// Check if we can safely rename this Comdat function.
1618bool canRenameComdatFunc(const Function &F, bool CheckAddressTaken) {
1619 if (F.getName().empty())
1620 return false;
1621 if (!needsComdatForCounter(GO: F, M: *(F.getParent())))
1622 return false;
1623 // Unsafe to rename the address-taken function (which can be used in
1624 // function comparison).
1625 if (CheckAddressTaken && F.hasAddressTaken())
1626 return false;
1627 // Only safe to do if this function may be discarded if it is not used
1628 // in the compilation unit.
1629 if (!GlobalValue::isDiscardableIfUnused(Linkage: F.getLinkage()))
1630 return false;
1631
1632 // For AvailableExternallyLinkage functions.
1633 if (!F.hasComdat()) {
1634 assert(F.getLinkage() == GlobalValue::AvailableExternallyLinkage);
1635 return true;
1636 }
1637 return true;
1638}
1639
1640// Create the variable for the profile file name.
1641void createProfileFileNameVar(Module &M, StringRef InstrProfileOutput) {
1642 if (InstrProfileOutput.empty())
1643 return;
1644 Constant *ProfileNameConst =
1645 ConstantDataArray::getString(Context&: M.getContext(), Initializer: InstrProfileOutput, AddNull: true);
1646 GlobalVariable *ProfileNameVar = new GlobalVariable(
1647 M, ProfileNameConst->getType(), true, GlobalValue::WeakAnyLinkage,
1648 ProfileNameConst, INSTR_PROF_QUOTE(INSTR_PROF_PROFILE_NAME_VAR));
1649 ProfileNameVar->setVisibility(GlobalValue::HiddenVisibility);
1650 Triple TT(M.getTargetTriple());
1651 if (TT.supportsCOMDAT()) {
1652 ProfileNameVar->setLinkage(GlobalValue::ExternalLinkage);
1653 ProfileNameVar->setComdat(M.getOrInsertComdat(
1654 Name: StringRef(INSTR_PROF_QUOTE(INSTR_PROF_PROFILE_NAME_VAR))));
1655 }
1656}
1657
1658Error OverlapStats::accumulateCounts(const std::string &BaseFilename,
1659 const std::string &TestFilename,
1660 bool IsCS) {
1661 auto GetProfileSum = [IsCS](const std::string &Filename,
1662 CountSumOrPercent &Sum) -> Error {
1663 // This function is only used from llvm-profdata that doesn't use any kind
1664 // of VFS. Just create a default RealFileSystem to read profiles.
1665 auto FS = vfs::getRealFileSystem();
1666 auto ReaderOrErr = InstrProfReader::create(Path: Filename, FS&: *FS);
1667 if (Error E = ReaderOrErr.takeError()) {
1668 return E;
1669 }
1670 auto Reader = std::move(ReaderOrErr.get());
1671 Reader->accumulateCounts(Sum, IsCS);
1672 return Error::success();
1673 };
1674 auto Ret = GetProfileSum(BaseFilename, Base);
1675 if (Ret)
1676 return Ret;
1677 Ret = GetProfileSum(TestFilename, Test);
1678 if (Ret)
1679 return Ret;
1680 this->BaseFilename = &BaseFilename;
1681 this->TestFilename = &TestFilename;
1682 Valid = true;
1683 return Error::success();
1684}
1685
1686void OverlapStats::addOneMismatch(const CountSumOrPercent &MismatchFunc) {
1687 Mismatch.NumEntries += 1;
1688 Mismatch.CountSum += MismatchFunc.CountSum / Test.CountSum;
1689 for (unsigned I = 0; I < IPVK_Last - IPVK_First + 1; I++) {
1690 if (Test.ValueCounts[I] >= 1.0f)
1691 Mismatch.ValueCounts[I] +=
1692 MismatchFunc.ValueCounts[I] / Test.ValueCounts[I];
1693 }
1694}
1695
1696void OverlapStats::addOneUnique(const CountSumOrPercent &UniqueFunc) {
1697 Unique.NumEntries += 1;
1698 Unique.CountSum += UniqueFunc.CountSum / Test.CountSum;
1699 for (unsigned I = 0; I < IPVK_Last - IPVK_First + 1; I++) {
1700 if (Test.ValueCounts[I] >= 1.0f)
1701 Unique.ValueCounts[I] += UniqueFunc.ValueCounts[I] / Test.ValueCounts[I];
1702 }
1703}
1704
1705void OverlapStats::dump(raw_fd_ostream &OS) const {
1706 if (!Valid)
1707 return;
1708
1709 const char *EntryName =
1710 (Level == ProgramLevel ? "functions" : "edge counters");
1711 if (Level == ProgramLevel) {
1712 OS << "Profile overlap information for base_profile: " << *BaseFilename
1713 << " and test_profile: " << *TestFilename << "\nProgram level:\n";
1714 } else {
1715 OS << "Function level:\n"
1716 << " Function: " << FuncName << " (Hash=" << FuncHash << ")\n";
1717 }
1718
1719 OS << " # of " << EntryName << " overlap: " << Overlap.NumEntries << "\n";
1720 if (Mismatch.NumEntries)
1721 OS << " # of " << EntryName << " mismatch: " << Mismatch.NumEntries
1722 << "\n";
1723 if (Unique.NumEntries)
1724 OS << " # of " << EntryName
1725 << " only in test_profile: " << Unique.NumEntries << "\n";
1726
1727 OS << " Edge profile overlap: " << format(Fmt: "%.3f%%", Vals: Overlap.CountSum * 100)
1728 << "\n";
1729 if (Mismatch.NumEntries)
1730 OS << " Mismatched count percentage (Edge): "
1731 << format(Fmt: "%.3f%%", Vals: Mismatch.CountSum * 100) << "\n";
1732 if (Unique.NumEntries)
1733 OS << " Percentage of Edge profile only in test_profile: "
1734 << format(Fmt: "%.3f%%", Vals: Unique.CountSum * 100) << "\n";
1735 OS << " Edge profile base count sum: " << format(Fmt: "%.0f", Vals: Base.CountSum)
1736 << "\n"
1737 << " Edge profile test count sum: " << format(Fmt: "%.0f", Vals: Test.CountSum)
1738 << "\n";
1739
1740 for (unsigned I = 0; I < IPVK_Last - IPVK_First + 1; I++) {
1741 if (Base.ValueCounts[I] < 1.0f && Test.ValueCounts[I] < 1.0f)
1742 continue;
1743 char ProfileKindName[20] = {0};
1744 switch (I) {
1745 case IPVK_IndirectCallTarget:
1746 strncpy(dest: ProfileKindName, src: "IndirectCall", n: 19);
1747 break;
1748 case IPVK_MemOPSize:
1749 strncpy(dest: ProfileKindName, src: "MemOP", n: 19);
1750 break;
1751 case IPVK_VTableTarget:
1752 strncpy(dest: ProfileKindName, src: "VTable", n: 19);
1753 break;
1754 default:
1755 snprintf(s: ProfileKindName, maxlen: 19, format: "VP[%d]", I);
1756 break;
1757 }
1758 OS << " " << ProfileKindName
1759 << " profile overlap: " << format(Fmt: "%.3f%%", Vals: Overlap.ValueCounts[I] * 100)
1760 << "\n";
1761 if (Mismatch.NumEntries)
1762 OS << " Mismatched count percentage (" << ProfileKindName
1763 << "): " << format(Fmt: "%.3f%%", Vals: Mismatch.ValueCounts[I] * 100) << "\n";
1764 if (Unique.NumEntries)
1765 OS << " Percentage of " << ProfileKindName
1766 << " profile only in test_profile: "
1767 << format(Fmt: "%.3f%%", Vals: Unique.ValueCounts[I] * 100) << "\n";
1768 OS << " " << ProfileKindName
1769 << " profile base count sum: " << format(Fmt: "%.0f", Vals: Base.ValueCounts[I])
1770 << "\n"
1771 << " " << ProfileKindName
1772 << " profile test count sum: " << format(Fmt: "%.0f", Vals: Test.ValueCounts[I])
1773 << "\n";
1774 }
1775}
1776
1777namespace IndexedInstrProf {
1778Expected<Header> Header::readFromBuffer(const unsigned char *Buffer) {
1779 using namespace support;
1780 static_assert(std::is_standard_layout_v<Header>,
1781 "Use standard layout for Header for simplicity");
1782 Header H;
1783
1784 H.Magic = endian::readNext<uint64_t, llvm::endianness::little>(memory&: Buffer);
1785 // Check the magic number.
1786 if (H.Magic != IndexedInstrProf::Magic)
1787 return make_error<InstrProfError>(Args: instrprof_error::bad_magic);
1788
1789 // Read the version.
1790 H.Version = endian::readNext<uint64_t, llvm::endianness::little>(memory&: Buffer);
1791 if (H.getIndexedProfileVersion() >
1792 IndexedInstrProf::ProfVersion::CurrentVersion)
1793 return make_error<InstrProfError>(Args: instrprof_error::unsupported_version);
1794
1795 static_assert(IndexedInstrProf::ProfVersion::CurrentVersion == Version14,
1796 "Please update the reader as needed when a new field is added "
1797 "or when indexed profile version gets bumped.");
1798
1799 Buffer += sizeof(uint64_t); // Skip Header.Unused field.
1800 H.HashType = endian::readNext<uint64_t, llvm::endianness::little>(memory&: Buffer);
1801 H.HashOffset = endian::readNext<uint64_t, llvm::endianness::little>(memory&: Buffer);
1802 if (H.getIndexedProfileVersion() >= 8)
1803 H.MemProfOffset =
1804 endian::readNext<uint64_t, llvm::endianness::little>(memory&: Buffer);
1805 if (H.getIndexedProfileVersion() >= 9)
1806 H.BinaryIdOffset =
1807 endian::readNext<uint64_t, llvm::endianness::little>(memory&: Buffer);
1808 // Version 11 is handled by this condition.
1809 if (H.getIndexedProfileVersion() >= 10)
1810 H.TemporalProfTracesOffset =
1811 endian::readNext<uint64_t, llvm::endianness::little>(memory&: Buffer);
1812 if (H.getIndexedProfileVersion() >= 12)
1813 H.VTableNamesOffset =
1814 endian::readNext<uint64_t, llvm::endianness::little>(memory&: Buffer);
1815 return H;
1816}
1817
1818uint64_t Header::getIndexedProfileVersion() const {
1819 return GET_VERSION(Version);
1820}
1821
1822size_t Header::size() const {
1823 switch (getIndexedProfileVersion()) {
1824 // To retain backward compatibility, new fields must be appended to the end
1825 // of the header, and byte offset of existing fields shouldn't change when
1826 // indexed profile version gets incremented.
1827 static_assert(
1828 IndexedInstrProf::ProfVersion::CurrentVersion == Version14,
1829 "Please update the size computation below if a new field has "
1830 "been added to the header; for a version bump without new "
1831 "fields, add a case statement to fall through to the latest version.");
1832 case 14ull: // UniformityBits added in record data, no header change
1833 case 13ull:
1834 case 12ull:
1835 return 72;
1836 case 11ull:
1837 [[fallthrough]];
1838 case 10ull:
1839 return 64;
1840 case 9ull:
1841 return 56;
1842 case 8ull:
1843 return 48;
1844 default: // Version7 (when the backwards compatible header was introduced).
1845 return 40;
1846 }
1847}
1848
1849} // namespace IndexedInstrProf
1850
1851} // end namespace llvm
1852