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