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