LLVM 24.0.0git
InstrProf.cpp
Go to the documentation of this file.
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
15#include "llvm/ADT/ArrayRef.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"
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"
31#include "llvm/IR/Type.h"
38#include "llvm/Support/Debug.h"
39#include "llvm/Support/Endian.h"
40#include "llvm/Support/Error.h"
42#include "llvm/Support/LEB128.h"
44#include "llvm/Support/Path.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
66 "static-func-full-module-prefix", cl::init(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.
79 "static-func-strip-dirname-prefix", cl::init(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
84 const std::string &ErrMsg = "") {
85 std::string Msg;
87
88 switch (Err) {
90 OS << "success";
91 break;
93 OS << "end of File";
94 break;
96 OS << "unrecognized instrumentation profile encoding format";
97 break;
99 OS << "invalid instrumentation profile data (bad magic)";
100 break;
102 OS << "invalid instrumentation profile data (file header is corrupt)";
103 break;
105 OS << "invalid instrumentation profile data (file is incomplete or header "
106 "is corrupt)";
107 break;
109 OS << "unsupported instrumentation profile format version";
110 break;
112 OS << "unsupported instrumentation profile hash type";
113 break;
115 OS << "too much profile data";
116 break;
118 OS << "truncated profile data";
119 break;
121 OS << "malformed instrumentation profile data";
122 break;
124 OS << "debug info/binary for correlation is required";
125 break;
127 OS << "debug info/binary for correlation is not necessary";
128 break;
130 OS << "unable to correlate profile";
131 break;
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;
138 OS << "no profile data available for function";
139 break;
141 OS << "function control flow change detected (hash mismatch)";
142 break;
144 OS << "function basic block count change detected (counter mismatch)";
145 break;
147 OS << "function bitmap size change detected (bitmap size mismatch)";
148 break;
150 OS << "counter overflow";
151 break;
153 OS << "function value site count change detected (counter mismatch)";
154 break;
156 OS << "failed to compress data (zlib)";
157 break;
159 OS << "failed to uncompress data (zlib)";
160 break;
162 OS << "empty raw profile file";
163 break;
165 OS << "profile uses zlib compression but the profile reader was built "
166 "without zlib support";
167 break;
169 OS << "raw profile version mismatch";
170 break;
172 OS << "excessively large counter value suggests corrupted profile data";
173 break;
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(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,
212};
213
214const char *InstrProfSectNameCoff[] = {
215#define INSTR_PROF_SECT_ENTRY(Kind, SectNameCommon, SectNameCoff, Prefix) \
216 SectNameCoff,
218};
219
220const char *InstrProfSectNamePrefix[] = {
221#define INSTR_PROF_SECT_ENTRY(Kind, SectNameCommon, SectNameCoff, Prefix) \
222 Prefix,
224};
225
226} // namespace
227
228namespace llvm {
229
231 "enable-name-compression",
232 cl::desc("Enable name/filename string compression"), cl::init(true));
233
235 "enable-vtable-value-profiling", cl::init(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
241 "enable-vtable-profile-use", cl::init(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
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, Msg);
267}
268
269char InstrProfError::ID = 0;
270
273
276
277uint64_t ProfOStream::tell() const { return OS.tell(); }
278void ProfOStream::write(uint64_t V) { LE.write<uint64_t>(V); }
281
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(K.Pos);
290 for (uint64_t Elem : K.D)
291 write(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(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 =
304 Data.replace(K.Pos + I * sizeof(uint64_t), sizeof(uint64_t),
305 (const char *)&Bytes, sizeof(uint64_t));
306 }
307 }
308 }
309}
310
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(1);
319
320 std::string NewName = std::string(Name);
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(0, "<unknown>:");
328 else
329 NewName = NewName.insert(0, 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;
343 LastPos = Pos;
344 --Count;
345 }
346 if (Count == 0)
347 break;
348 }
349 return PathNameStr.substr(LastPos);
350}
351
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(FileName, 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
374 StringRef FileName) {
375 return GlobalValue::getGlobalIdentifier(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, GO.getLinkage(), FileName);
386 }
387
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(F);
401 return getPGOFuncName(F.getName(), F.getLinkage(), FileName, Version);
402 }
403
404 return getPGOFuncName(F.getName(), GlobalValue::ExternalLinkage, "");
405}
406
407// See getIRPGOObjectName() for a discription of the format.
408std::pair<StringRef, StringRef> getParsedIRPGOName(StringRef IRPGOName) {
409 auto [FileName, MangledName] = IRPGOName.split(GlobalIdentifierDelimiter);
410 if (MangledName.empty())
411 return std::make_pair(StringRef(), IRPGOName);
412 return std::make_pair(FileName, MangledName);
413}
414
416 if (FileName.empty())
417 return PGOFuncName;
418 // Drop the file name including ':' or ';'. See getIRPGONameForGlobalObject as
419 // well.
420 if (PGOFuncName.starts_with(FileName))
421 PGOFuncName = PGOFuncName.drop_front(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,
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(InvalidChars);
438 while (FoundPos != std::string::npos) {
439 VarName[FoundPos] = '_';
440 FoundPos = VarName.find_first_of(InvalidChars, 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
451 // Hide the symbol so that we correctly get a copy for each executable.
452 if (!GlobalValue::isLocalLinkage(FuncNameVar->getLinkage()))
454}
455
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.
464 else if (Linkage == GlobalValue::AvailableExternallyLinkage)
466 else if (Linkage == GlobalValue::InternalLinkage ||
469
470 auto *Value =
471 ConstantDataArray::getString(M.getContext(), PGOFuncName, false);
472 auto *FuncNameVar =
473 new GlobalVariable(M, Value->getType(), true, Linkage, Value,
474 getPGOFuncNameVarName(PGOFuncName, Linkage));
475
476 setPGOFuncVisibility(M, FuncNameVar);
477 return FuncNameVar;
478}
479
481 return createPGOFuncNameVar(*F.getParent(), F.getLinkage(), PGOFuncName);
482}
483
484Error InstrProfSymtab::create(Module &M, bool InLTO, bool AddCanonical,
485 bool KeyImportedAliasesByAliasGUID) {
486 for (Function &F : M) {
487 // Function may not have a name: like using asm("") to overwrite the name.
488 // Ignore in this case.
489 if (!F.hasName())
490 continue;
491 auto IRPGOFuncName = getIRPGOObjectName(F, InLTO);
492 if (Error E = addFuncWithName(F, IRPGOFuncName, AddCanonical,
493 KeyImportedAliasesByAliasGUID))
494 return E;
495 // Also use getPGOFuncName() so that we can find records from older profiles
496 auto PGOFuncName = getPGOFuncName(F, InLTO);
497 if (PGOFuncName != IRPGOFuncName)
498 if (Error E = addFuncWithName(F, PGOFuncName, AddCanonical,
499 KeyImportedAliasesByAliasGUID))
500 return E;
501 }
502
503 for (GlobalVariable &G : M.globals()) {
504 if (!G.hasName() || !G.hasMetadata(LLVMContext::MD_type))
505 continue;
506 if (Error E = addVTableWithName(G, getIRPGOObjectName(G, InLTO)))
507 return E;
508 }
509
510 Sorted = false;
511 finalizeSymtab();
512 return Error::success();
513}
514
515Error InstrProfSymtab::addVTableWithName(GlobalVariable &VTable,
516 StringRef VTablePGOName) {
517 // Key each name by its own hash, so profiles that recorded that name can find
518 // the vtable.
519 auto NameToGUIDMap = [&](StringRef Name) -> Error {
520 if (Error E = addSymbolName(Name))
521 return E;
522
523 bool Inserted = true;
524 std::tie(std::ignore, Inserted) = MD5VTableMap.try_emplace(
526 if (!Inserted)
527 LLVM_DEBUG(dbgs() << "GUID conflict within one module");
528 return Error::success();
529 };
530 if (Error E = NameToGUIDMap(VTablePGOName))
531 return E;
532
533 // Also key the vtable by its GUID, so it can still be found if LTO has
534 // renamed it. See addFuncWithName.
535 if (auto GUID = VTable.getGUIDIfAssigned();
536 GUID &&
537 *GUID != GlobalValue::getGUIDAssumingExternalLinkage(VTablePGOName))
538 MD5VTableMap.try_emplace(*GUID, &VTable);
539
540 StringRef CanonicalName = getCanonicalName(VTablePGOName);
541 if (!CanonicalName.empty() && CanonicalName != VTablePGOName)
542 return NameToGUIDMap(CanonicalName);
543
544 return Error::success();
545}
546
548 std::function<Error(StringRef)> NameCallback) {
549 const uint8_t *P = NameStrings.bytes_begin();
550 const uint8_t *EndP = NameStrings.bytes_end();
551 while (P < EndP) {
552 uint32_t N;
553 uint64_t UncompressedSize = decodeULEB128(P, &N);
554 P += N;
555 uint64_t CompressedSize = decodeULEB128(P, &N);
556 P += N;
557 const bool IsCompressed = (CompressedSize != 0);
558 SmallVector<uint8_t, 128> UncompressedNameStrings;
559 StringRef NameStrings;
560 if (IsCompressed) {
563
564 if (Error E = compression::zlib::decompress(ArrayRef(P, CompressedSize),
565 UncompressedNameStrings,
566 UncompressedSize)) {
567 consumeError(std::move(E));
569 }
570 P += CompressedSize;
571 NameStrings = toStringRef(UncompressedNameStrings);
572 } else {
573 NameStrings =
574 StringRef(reinterpret_cast<const char *>(P), UncompressedSize);
575 P += UncompressedSize;
576 }
577 // Now parse the name strings.
579 NameStrings.split(Names, getInstrProfNameSeparator());
580 for (StringRef &Name : Names)
581 if (Error E = NameCallback(Name))
582 return E;
583
584 while (P < EndP && *P == 0)
585 P++;
586 }
587 return Error::success();
588}
589
591 return readAndDecodeStrings(NameStrings,
592 [&](StringRef S) { return addFuncName(S); });
593}
594
596 StringRef VTableNameStrings) {
598 FuncNameStrings, [&](StringRef S) { return addFuncName(S); }))
599 return E;
600
601 return readAndDecodeStrings(VTableNameStrings,
602 [&](StringRef S) { return addVTableName(S); });
603}
604
606 StringRef CompressedVTableStrings) {
607 return readAndDecodeStrings(CompressedVTableStrings,
608 [&](StringRef S) { return addVTableName(S); });
609}
610
612 // In ThinLTO, local function may have been promoted to global and have
613 // suffix ".llvm." added to the function name. We need to add the
614 // stripped function name to the symbol table so that we can find a match
615 // from profile.
616 //
617 // ".__uniq." suffix is used to differentiate internal linkage functions in
618 // different modules and should be kept. This is the only suffix with the
619 // pattern ".xxx" which is kept before matching, other suffixes ".llvm." and
620 // ".part" will be stripped.
621 //
622 // Leverage the common canonicalization logic from FunctionSamples. Instead of
623 // removing all suffixes except ".__uniq.", explicitly specify the ones to be
624 // removed. This avoids the issue of colliding the canonical names of
625 // coroutine function with its await suspend wrappers or with its post-split
626 // clones. i.e. coro function foo, its wrappers
627 // (foo.__await_suspend_wrapper__init, and foo.__await_suspend_wrapper__final)
628 // and its post-split clones (foo.resume, foo.cleanup) are all canonicalized
629 // to "foo" otherwise, which can make the symtab lookup return unexpected
630 // result.
631 const SmallVector<StringRef> SuffixesToRemove{".llvm.", ".part."};
632 return FunctionSamples::getCanonicalFnName(PGOName, SuffixesToRemove);
633}
635Error InstrProfSymtab::addFuncWithName(Function &F, StringRef PGOFuncName,
636 bool AddCanonical,
637 bool KeyImportedAliasesByAliasGUID) {
638 // Key each name by its own hash, so profiles that recorded that name can find
639 // the function. This is called once per name, e.g. a second time with the
640 // deprecated PGO name, for profiles from older compilers.
641 auto NameToGUIDMap = [&](StringRef Name) -> Error {
642 if (Error E = addFuncName(Name))
643 return E;
644 MD5FuncMap.emplace_back(Function::getGUIDAssumingExternalLinkage(Name), &F);
645 return Error::success();
646 };
647 if (Error E = NameToGUIDMap(PGOFuncName))
648 return E;
649
650 // Also key the function by its GUID, if it has one. The GUID is the hash of
651 // the function's name when the GUID was assigned, so this still finds the
652 // function if LTO has renamed it since. This used to need !PGOFuncName.
653 // If requested, key an imported copy of an alias by the alias's GUID instead
654 // of the aliasee's GUID retained in its !guid metadata (see create()).
655 std::optional<GlobalValue::GUID> GUID;
656 MDNode *AliasGUIDMD = KeyImportedAliasesByAliasGUID
657 ? F.getMetadata("thinlto_alias_guid")
658 : nullptr;
659 if (AliasGUIDMD)
660 GUID = mdconst::extract<ConstantInt>(AliasGUIDMD->getOperand(0))
661 ->getZExtValue();
662 else
663 GUID = F.getGUIDIfAssigned();
664 if (GUID && *GUID != Function::getGUIDAssumingExternalLinkage(PGOFuncName))
665 MD5FuncMap.emplace_back(*GUID, &F);
667 if (!AddCanonical)
668 return Error::success();
669
670 StringRef CanonicalFuncName = getCanonicalName(PGOFuncName);
671 if (!CanonicalFuncName.empty() && CanonicalFuncName != PGOFuncName)
672 return NameToGUIDMap(CanonicalFuncName);
673
674 return Error::success();
675}
676
677uint64_t InstrProfSymtab::getVTableHashFromAddress(uint64_t Address) const {
678 // Given a runtime address, look up the hash value in the interval map, and
679 // fallback to value 0 if a hash value is not found.
680 return VTableAddrMap.lookup(Address, 0);
681}
682
683uint64_t InstrProfSymtab::getFunctionHashFromAddress(uint64_t Address) const {
684 finalizeSymtab();
685 auto It = partition_point(AddrToMD5Map, [=](std::pair<uint64_t, uint64_t> A) {
686 return A.first < Address;
687 });
688 // Raw function pointer collected by value profiler may be from
689 // external functions that are not instrumented. They won't have
690 // mapping data to be used by the deserializer. Force the value to
691 // be 0 in this case.
692 if (It != AddrToMD5Map.end() && It->first == Address)
693 return (uint64_t)It->second;
694 return 0;
695}
696
698 SmallVector<StringRef, 0> Sorted(NameTab.keys());
699 llvm::sort(Sorted);
700 for (StringRef S : Sorted)
701 OS << S << '\n';
702}
703
705 bool DoCompression, std::string &Result) {
706 assert(!NameStrs.empty() && "No name data to emit");
707
708 uint8_t Header[20], *P = Header;
709 std::string UncompressedNameStrings =
710 join(NameStrs.begin(), NameStrs.end(), getInstrProfNameSeparator());
711
712 assert(StringRef(UncompressedNameStrings)
713 .count(getInstrProfNameSeparator()) == (NameStrs.size() - 1) &&
714 "PGO name is invalid (contains separator token)");
715
716 unsigned EncLen = encodeULEB128(UncompressedNameStrings.length(), P);
717 P += EncLen;
718
719 auto WriteStringToResult = [&](size_t CompressedLen, StringRef InputStr) {
720 EncLen = encodeULEB128(CompressedLen, P);
721 P += EncLen;
722 char *HeaderStr = reinterpret_cast<char *>(&Header[0]);
723 unsigned HeaderLen = P - &Header[0];
724 Result.append(HeaderStr, HeaderLen);
725 Result += InputStr;
726 return Error::success();
727 };
728
729 if (!DoCompression) {
730 return WriteStringToResult(0, UncompressedNameStrings);
731 }
732
733 SmallVector<uint8_t, 128> CompressedNameStrings;
734 compression::zlib::compress(arrayRefFromStringRef(UncompressedNameStrings),
735 CompressedNameStrings,
737
738 return WriteStringToResult(CompressedNameStrings.size(),
739 toStringRef(CompressedNameStrings));
740}
741
743 auto *Arr = cast<ConstantDataArray>(NameVar->getInitializer());
744 StringRef NameStr =
745 Arr->isCString() ? Arr->getAsCString() : Arr->getAsString();
746 return NameStr;
747}
748
750 std::string &Result, bool DoCompression) {
751 std::vector<std::string> NameStrs;
752 for (auto *NameVar : NameVars) {
753 NameStrs.push_back(std::string(getPGOFuncNameVarInitializer(NameVar)));
754 }
756 NameStrs, compression::zlib::isAvailable() && DoCompression, Result);
757}
758
760 std::string &Result, bool DoCompression) {
761 std::vector<std::string> VTableNameStrs;
762 for (auto *VTable : VTables)
763 VTableNameStrs.push_back(getIRPGOObjectName(*VTable));
765 VTableNameStrs, compression::zlib::isAvailable() && DoCompression,
766 Result);
767}
768
770 uint64_t FuncSum = 0;
771 Sum.NumEntries += Counts.size();
772 for (uint64_t Count : Counts)
773 FuncSum += Count;
774 Sum.CountSum += FuncSum;
775
776 for (uint32_t VK = IPVK_First; VK <= IPVK_Last; ++VK) {
777 uint64_t KindSum = 0;
779 for (size_t I = 0; I < NumValueSites; ++I) {
780 for (const auto &V : getValueArrayForSite(VK, I))
781 KindSum += V.Count;
782 }
783 Sum.ValueCounts[VK] += KindSum;
784 }
785}
786
788 uint32_t ValueKind,
789 OverlapStats &Overlap,
790 OverlapStats &FuncLevelOverlap) {
791 this->sortByTargetValues();
792 Input.sortByTargetValues();
793 double Score = 0.0f, FuncLevelScore = 0.0f;
794 auto I = ValueData.begin();
795 auto IE = ValueData.end();
796 auto J = Input.ValueData.begin();
797 auto JE = Input.ValueData.end();
798 while (I != IE && J != JE) {
799 if (I->Value == J->Value) {
800 Score += OverlapStats::score(I->Count, J->Count,
801 Overlap.Base.ValueCounts[ValueKind],
802 Overlap.Test.ValueCounts[ValueKind]);
803 FuncLevelScore += OverlapStats::score(
804 I->Count, J->Count, FuncLevelOverlap.Base.ValueCounts[ValueKind],
805 FuncLevelOverlap.Test.ValueCounts[ValueKind]);
806 ++I;
807 } else if (I->Value < J->Value) {
808 ++I;
809 continue;
810 }
811 ++J;
812 }
813 Overlap.Overlap.ValueCounts[ValueKind] += Score;
814 FuncLevelOverlap.Overlap.ValueCounts[ValueKind] += FuncLevelScore;
815}
816
817// Return false on mismatch.
820 OverlapStats &Overlap,
821 OverlapStats &FuncLevelOverlap) {
822 uint32_t ThisNumValueSites = getNumValueSites(ValueKind);
823 assert(ThisNumValueSites == Other.getNumValueSites(ValueKind));
824 if (!ThisNumValueSites)
825 return;
826
827 std::vector<InstrProfValueSiteRecord> &ThisSiteRecords =
828 getOrCreateValueSitesForKind(ValueKind);
830 Other.getValueSitesForKind(ValueKind);
831 for (uint32_t I = 0; I < ThisNumValueSites; I++)
832 ThisSiteRecords[I].overlap(OtherSiteRecords[I], ValueKind, Overlap,
833 FuncLevelOverlap);
834}
835
837 OverlapStats &FuncLevelOverlap,
838 uint64_t ValueCutoff) {
839 // FuncLevel CountSum for other should already computed and nonzero.
840 assert(FuncLevelOverlap.Test.CountSum >= 1.0f);
841 accumulateCounts(FuncLevelOverlap.Base);
842 bool Mismatch = (Counts.size() != Other.Counts.size());
843
844 // Check if the value profiles mismatch.
845 if (!Mismatch) {
846 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind) {
847 uint32_t ThisNumValueSites = getNumValueSites(Kind);
848 uint32_t OtherNumValueSites = Other.getNumValueSites(Kind);
849 if (ThisNumValueSites != OtherNumValueSites) {
850 Mismatch = true;
851 break;
852 }
853 }
854 }
855 if (Mismatch) {
856 Overlap.addOneMismatch(FuncLevelOverlap.Test);
857 return;
858 }
859
860 // Compute overlap for value counts.
861 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
862 overlapValueProfData(Kind, Other, Overlap, FuncLevelOverlap);
863
864 double Score = 0.0;
865 uint64_t MaxCount = 0;
866 // Compute overlap for edge counts.
867 for (size_t I = 0, E = Other.Counts.size(); I < E; ++I) {
868 Score += OverlapStats::score(Counts[I], Other.Counts[I],
869 Overlap.Base.CountSum, Overlap.Test.CountSum);
870 MaxCount = std::max(Other.Counts[I], MaxCount);
871 }
872 Overlap.Overlap.CountSum += Score;
873 Overlap.Overlap.NumEntries += 1;
874
875 if (MaxCount >= ValueCutoff) {
876 double FuncScore = 0.0;
877 for (size_t I = 0, E = Other.Counts.size(); I < E; ++I)
878 FuncScore += OverlapStats::score(Counts[I], Other.Counts[I],
879 FuncLevelOverlap.Base.CountSum,
880 FuncLevelOverlap.Test.CountSum);
881 FuncLevelOverlap.Overlap.CountSum = FuncScore;
882 FuncLevelOverlap.Overlap.NumEntries = Other.Counts.size();
883 FuncLevelOverlap.Valid = true;
884 }
885}
886
888 uint64_t Weight,
889 function_ref<void(instrprof_error)> Warn) {
890 this->sortByTargetValues();
891 Input.sortByTargetValues();
892 auto I = ValueData.begin();
893 auto IE = ValueData.end();
894 std::vector<InstrProfValueData> Merged;
895 Merged.reserve(std::max(ValueData.size(), Input.ValueData.size()));
896 for (const InstrProfValueData &J : Input.ValueData) {
897 while (I != IE && I->Value < J.Value) {
898 Merged.push_back(*I);
899 ++I;
900 }
901 if (I != IE && I->Value == J.Value) {
902 bool Overflowed;
903 I->Count = SaturatingMultiplyAdd(J.Count, Weight, I->Count, &Overflowed);
904 if (Overflowed)
906 Merged.push_back(*I);
907 ++I;
908 continue;
909 }
910 Merged.push_back(J);
911 }
912 Merged.insert(Merged.end(), I, IE);
913 ValueData = std::move(Merged);
914}
915
916void InstrProfValueSiteRecord::scale(uint64_t N, uint64_t D,
917 function_ref<void(instrprof_error)> Warn) {
918 for (InstrProfValueData &I : ValueData) {
919 bool Overflowed;
920 I.Count = SaturatingMultiply(I.Count, N, &Overflowed) / D;
921 if (Overflowed)
923 }
924}
925
926// Merge Value Profile data from Src record to this record for ValueKind.
927// Scale merged value counts by \p Weight.
928void InstrProfRecord::mergeValueProfData(
929 uint32_t ValueKind, InstrProfRecord &Src, uint64_t Weight,
930 function_ref<void(instrprof_error)> Warn) {
931 uint32_t ThisNumValueSites = getNumValueSites(ValueKind);
932 uint32_t OtherNumValueSites = Src.getNumValueSites(ValueKind);
933 if (ThisNumValueSites != OtherNumValueSites) {
935 return;
936 }
937 if (!ThisNumValueSites)
938 return;
939 std::vector<InstrProfValueSiteRecord> &ThisSiteRecords =
940 getOrCreateValueSitesForKind(ValueKind);
942 Src.getValueSitesForKind(ValueKind);
943 for (uint32_t I = 0; I < ThisNumValueSites; I++)
944 ThisSiteRecords[I].merge(OtherSiteRecords[I], Weight, Warn);
945}
946
948 if (UniformCounts.empty())
949 return;
950
951 if (UniformCounts.size() != Counts.size()) {
952 UniformityBits.clear();
953 return;
954 }
955
956 UniformityBits.assign((Counts.size() + 7) / 8, 0xFF);
957 for (size_t I = 0, E = Counts.size(); I < E; ++I) {
958 uint64_t TotalCount = Counts[I];
959 uint64_t UniformCount = UniformCounts[I];
960 uint64_t MinUniformCount = TotalCount - TotalCount / 10;
961 bool IsUniform = UniformCount >= MinUniformCount;
962 if (!IsUniform)
963 UniformityBits[I / 8] &= ~(1 << (I % 8));
964 }
965}
966
967static void mergeUniformityBits(std::vector<uint8_t> &Dst,
968 ArrayRef<uint8_t> Src) {
969 if (Dst.empty()) {
970 Dst.assign(Src.begin(), Src.end());
971 return;
972 }
973 if (Src.empty())
974 return;
975
976 if (Dst.size() != Src.size()) {
977 Dst.clear();
978 return;
979 }
980
981 for (size_t I = 0, E = Src.size(); I < E; ++I)
982 Dst[I] &= Src[I];
983}
984
986 function_ref<void(instrprof_error)> Warn) {
987 // If the number of counters doesn't match we either have bad data
988 // or a hash collision.
989 if (Counts.size() != Other.Counts.size()) {
991 return;
992 }
993
995 Other.computeBlockUniformity();
996
997 // Special handling of the first count as the PseudoCount.
998 CountPseudoKind OtherKind = Other.getCountPseudoKind();
1000 if (OtherKind != NotPseudo || ThisKind != NotPseudo) {
1001 // We don't allow the merge of a profile with pseudo counts and
1002 // a normal profile (i.e. without pesudo counts).
1003 // Profile supplimenation should be done after the profile merge.
1004 if (OtherKind == NotPseudo || ThisKind == NotPseudo) {
1006 return;
1007 }
1008 if (OtherKind == PseudoHot || ThisKind == PseudoHot)
1010 else
1012 return;
1013 }
1014 OffloadDeviceWaveSize = Other.OffloadDeviceWaveSize;
1015 bool HasUniformCounts = !UniformCounts.empty();
1016 bool OtherHasUniformCounts = !Other.UniformCounts.empty();
1017 for (size_t I = 0, E = Other.Counts.size(); I < E; ++I) {
1018 bool Overflowed;
1019 uint64_t Value =
1020 SaturatingMultiplyAdd(Other.Counts[I], Weight, Counts[I], &Overflowed);
1021 if (Value > getInstrMaxCountValue()) {
1023 Overflowed = true;
1024 }
1025 Counts[I] = Value;
1026 if (Overflowed)
1028 }
1029
1030 if (HasUniformCounts && OtherHasUniformCounts) {
1031 if (UniformCounts.size() != Other.UniformCounts.size()) {
1032 UniformCounts.clear();
1033 UniformityBits.clear();
1034 } else {
1035 for (size_t I = 0, E = Other.UniformCounts.size(); I < E; ++I) {
1036 bool Overflowed;
1037 UniformCounts[I] = SaturatingMultiplyAdd(Other.UniformCounts[I], Weight,
1038 UniformCounts[I], &Overflowed);
1041 Overflowed = true;
1042 }
1043 if (Overflowed)
1045 }
1047 }
1048 } else {
1049 UniformCounts.clear();
1050 mergeUniformityBits(UniformityBits, Other.UniformityBits);
1051 }
1052
1053 // If the number of bitmap bytes doesn't match we either have bad data
1054 // or a hash collision.
1055 if (BitmapBytes.size() != Other.BitmapBytes.size()) {
1057 return;
1058 }
1059
1060 // Bitmap bytes are merged by simply ORing them together.
1061 for (size_t I = 0, E = Other.BitmapBytes.size(); I < E; ++I) {
1062 BitmapBytes[I] = Other.BitmapBytes[I] | BitmapBytes[I];
1063 }
1064
1065 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
1066 mergeValueProfData(Kind, Other, Weight, Warn);
1067}
1068
1069void InstrProfRecord::scaleValueProfData(
1070 uint32_t ValueKind, uint64_t N, uint64_t D,
1071 function_ref<void(instrprof_error)> Warn) {
1072 for (auto &R : getValueSitesForKind(ValueKind))
1073 R.scale(N, D, Warn);
1074}
1075
1076void InstrProfRecord::scale(uint64_t N, uint64_t D,
1077 function_ref<void(instrprof_error)> Warn) {
1078 assert(D != 0 && "D cannot be 0");
1079 for (auto &Count : this->Counts) {
1080 bool Overflowed;
1081 Count = SaturatingMultiply(Count, N, &Overflowed) / D;
1082 if (Count > getInstrMaxCountValue()) {
1084 Overflowed = true;
1085 }
1086 if (Overflowed)
1088 }
1089 for (auto &Count : this->UniformCounts) {
1090 bool Overflowed;
1091 Count = SaturatingMultiply(Count, N, &Overflowed) / D;
1092 if (Count > getInstrMaxCountValue()) {
1094 Overflowed = true;
1095 }
1096 if (Overflowed)
1098 }
1100 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
1101 scaleValueProfData(Kind, N, D, Warn);
1102}
1103
1104// Map indirect call target name hash to name string.
1105uint64_t InstrProfRecord::remapValue(uint64_t Value, uint32_t ValueKind,
1106 InstrProfSymtab *SymTab) {
1107 if (!SymTab)
1108 return Value;
1109
1110 if (ValueKind == IPVK_IndirectCallTarget)
1111 return SymTab->getFunctionHashFromAddress(Value);
1112
1113 if (ValueKind == IPVK_VTableTarget)
1114 return SymTab->getVTableHashFromAddress(Value);
1115
1116 return Value;
1117}
1118
1122 // Remap values.
1123 std::vector<InstrProfValueData> RemappedVD;
1124 RemappedVD.reserve(VData.size());
1125 for (const auto &V : VData) {
1126 uint64_t NewValue = remapValue(V.Value, ValueKind, ValueMap);
1127 RemappedVD.push_back({NewValue, V.Count});
1128 }
1129
1130 std::vector<InstrProfValueSiteRecord> &ValueSites =
1131 getOrCreateValueSitesForKind(ValueKind);
1132 assert(ValueSites.size() == Site);
1133
1134 // Add a new value site with remapped value profiling data.
1135 ValueSites.emplace_back(std::move(RemappedVD));
1136}
1137
1139 ArrayRef<TemporalProfTraceTy> Traces, std::vector<BPFunctionNode> &Nodes,
1140 bool RemoveOutlierUNs) {
1141 using IDT = BPFunctionNode::IDT;
1142 using UtilityNodeT = BPFunctionNode::UtilityNodeT;
1143 UtilityNodeT MaxUN = 0;
1144 DenseMap<IDT, size_t> IdToFirstTimestamp;
1145 DenseMap<IDT, UtilityNodeT> IdToFirstUN;
1147 // TODO: We need to use the Trace.Weight field to give more weight to more
1148 // important utilities
1149 for (auto &Trace : Traces) {
1150 size_t CutoffTimestamp = 1;
1151 for (size_t Timestamp = 0; Timestamp < Trace.FunctionNameRefs.size();
1152 Timestamp++) {
1153 IDT Id = Trace.FunctionNameRefs[Timestamp];
1154 auto [It, WasInserted] = IdToFirstTimestamp.try_emplace(Id, Timestamp);
1155 if (!WasInserted)
1156 It->getSecond() = std::min<size_t>(It->getSecond(), Timestamp);
1157 if (Timestamp >= CutoffTimestamp) {
1158 ++MaxUN;
1159 CutoffTimestamp = 2 * Timestamp;
1160 }
1161 IdToFirstUN.try_emplace(Id, MaxUN);
1162 }
1163 for (auto &[Id, FirstUN] : IdToFirstUN)
1164 for (auto UN = FirstUN; UN <= MaxUN; ++UN)
1165 IdToUNs[Id].push_back(UN);
1166 ++MaxUN;
1167 IdToFirstUN.clear();
1168 }
1169
1170 if (RemoveOutlierUNs) {
1172 for (auto &[Id, UNs] : IdToUNs)
1173 for (auto &UN : UNs)
1174 ++UNFrequency[UN];
1175 // Filter out utility nodes that are too infrequent or too prevalent to make
1176 // BalancedPartitioning more effective.
1177 for (auto &[Id, UNs] : IdToUNs)
1178 llvm::erase_if(UNs, [&](auto &UN) {
1179 unsigned Freq = UNFrequency[UN];
1180 return Freq <= 1 || 2 * Freq > IdToUNs.size();
1181 });
1182 }
1183
1184 for (auto &[Id, UNs] : IdToUNs)
1185 Nodes.emplace_back(Id, UNs);
1186
1187 // Since BalancedPartitioning is sensitive to the initial order, we explicitly
1188 // order nodes by their earliest timestamp.
1189 llvm::sort(Nodes, [&](auto &L, auto &R) {
1190 return std::make_pair(IdToFirstTimestamp[L.Id], L.Id) <
1191 std::make_pair(IdToFirstTimestamp[R.Id], R.Id);
1192 });
1193}
1194
1195#define INSTR_PROF_COMMON_API_IMPL
1197
1198/*!
1199 * ValueProfRecordClosure Interface implementation for InstrProfRecord
1200 * class. These C wrappers are used as adaptors so that C++ code can be
1201 * invoked as callbacks.
1202 */
1204 return reinterpret_cast<const InstrProfRecord *>(Record)->getNumValueKinds();
1205}
1206
1208 return reinterpret_cast<const InstrProfRecord *>(Record)
1209 ->getNumValueSites(VKind);
1210}
1211
1213 return reinterpret_cast<const InstrProfRecord *>(Record)
1214 ->getNumValueData(VKind);
1215}
1216
1218 uint32_t S) {
1219 const auto *IPR = reinterpret_cast<const InstrProfRecord *>(R);
1220 return IPR->getValueArrayForSite(VK, S).size();
1221}
1222
1223void getValueForSiteInstrProf(const void *R, InstrProfValueData *Dst,
1224 uint32_t K, uint32_t S) {
1225 const auto *IPR = reinterpret_cast<const InstrProfRecord *>(R);
1226 llvm::copy(IPR->getValueArrayForSite(K, S), Dst);
1227}
1228
1230 ValueProfData *VD = new (::operator new(TotalSizeInBytes)) ValueProfData();
1231 memset(VD, 0, TotalSizeInBytes);
1232 return VD;
1233}
1234
1244
1245// Wrapper implementation using the closure mechanism.
1246uint32_t ValueProfData::getSize(const InstrProfRecord &Record) {
1247 auto Closure = InstrProfRecordClosure;
1248 Closure.Record = &Record;
1249 return getValueProfDataSize(&Closure);
1250}
1251
1252// Wrapper implementation using the closure mechanism.
1253std::unique_ptr<ValueProfData>
1254ValueProfData::serializeFrom(const InstrProfRecord &Record) {
1256
1257 std::unique_ptr<ValueProfData> VPD(
1259 return VPD;
1260}
1261
1262void ValueProfRecord::deserializeTo(InstrProfRecord &Record,
1263 InstrProfSymtab *SymTab) {
1264 Record.reserveSites(Kind, NumValueSites);
1265
1266 InstrProfValueData *ValueData = getValueProfRecordValueData(this);
1267 for (uint64_t VSite = 0; VSite < NumValueSites; ++VSite) {
1268 uint8_t ValueDataCount = this->SiteCountArray[VSite];
1269 ArrayRef<InstrProfValueData> VDs(ValueData, ValueDataCount);
1270 Record.addValueData(Kind, VSite, VDs, SymTab);
1271 ValueData += ValueDataCount;
1272 }
1273}
1274
1275// For writing/serializing, Old is the host endianness, and New is
1276// byte order intended on disk. For Reading/deserialization, Old
1277// is the on-disk source endianness, and New is the host endianness.
1278void ValueProfRecord::swapBytes(llvm::endianness Old, llvm::endianness New) {
1279 using namespace support;
1280
1281 if (Old == New)
1282 return;
1283
1284 if (llvm::endianness::native != Old) {
1287 }
1288 uint32_t ND = getValueProfRecordNumValueData(this);
1289 InstrProfValueData *VD = getValueProfRecordValueData(this);
1290
1291 // No need to swap byte array: SiteCountArrray.
1292 for (uint32_t I = 0; I < ND; I++) {
1295 }
1296 if (llvm::endianness::native == Old) {
1299 }
1300}
1301
1302void ValueProfData::deserializeTo(InstrProfRecord &Record,
1303 InstrProfSymtab *SymTab) {
1304 if (NumValueKinds == 0)
1305 return;
1306
1307 ValueProfRecord *VR = getFirstValueProfRecord(this);
1308 for (uint32_t K = 0; K < NumValueKinds; K++) {
1309 VR->deserializeTo(Record, SymTab);
1310 VR = getValueProfRecordNext(VR);
1311 }
1312}
1313
1314static std::unique_ptr<ValueProfData> allocValueProfData(uint32_t TotalSize) {
1315 return std::unique_ptr<ValueProfData>(new (::operator new(TotalSize))
1316 ValueProfData());
1317}
1318
1319Error ValueProfData::checkIntegrity() {
1320 if (NumValueKinds > IPVK_Last + 1)
1322 instrprof_error::malformed, "number of value profile kinds is invalid");
1323 // Total size needs to be multiple of quadword size.
1324 if (TotalSize % sizeof(uint64_t))
1326 instrprof_error::malformed, "total size is not multiples of quardword");
1327
1328 ValueProfRecord *VR = getFirstValueProfRecord(this);
1329 for (uint32_t K = 0; K < this->NumValueKinds; K++) {
1330 if (VR->Kind > IPVK_Last)
1332 "value kind is invalid");
1333 VR = getValueProfRecordNext(VR);
1334 if ((char *)VR - (char *)this > (ptrdiff_t)TotalSize)
1337 "value profile address is greater than total size");
1338 }
1339 return Error::success();
1340}
1341
1343ValueProfData::getValueProfData(const unsigned char *D,
1344 const unsigned char *const BufferEnd,
1345 llvm::endianness Endianness) {
1346 using namespace support;
1347
1348 if (D + sizeof(ValueProfData) > BufferEnd)
1350
1351 const unsigned char *Header = D;
1352 uint32_t TotalSize = endian::readNext<uint32_t>(Header, Endianness);
1353
1354 if (D + TotalSize > BufferEnd)
1356
1357 std::unique_ptr<ValueProfData> VPD = allocValueProfData(TotalSize);
1358 memcpy(VPD.get(), D, TotalSize);
1359 // Byte swap.
1360 VPD->swapBytesToHost(Endianness);
1361
1362 Error E = VPD->checkIntegrity();
1363 if (E)
1364 return std::move(E);
1365
1366 return std::move(VPD);
1367}
1368
1369void ValueProfData::swapBytesToHost(llvm::endianness Endianness) {
1370 using namespace support;
1371
1372 if (Endianness == llvm::endianness::native)
1373 return;
1374
1377
1378 ValueProfRecord *VR = getFirstValueProfRecord(this);
1379 for (uint32_t K = 0; K < NumValueKinds; K++) {
1380 VR->swapBytes(Endianness, llvm::endianness::native);
1381 VR = getValueProfRecordNext(VR);
1382 }
1383}
1384
1385void ValueProfData::swapBytesFromHost(llvm::endianness Endianness) {
1386 using namespace support;
1387
1388 if (Endianness == llvm::endianness::native)
1389 return;
1390
1391 ValueProfRecord *VR = getFirstValueProfRecord(this);
1392 for (uint32_t K = 0; K < NumValueKinds; K++) {
1393 ValueProfRecord *NVR = getValueProfRecordNext(VR);
1394 VR->swapBytes(llvm::endianness::native, Endianness);
1395 VR = NVR;
1396 }
1399}
1400
1402 const InstrProfRecord &InstrProfR,
1403 InstrProfValueKind ValueKind, uint32_t SiteIdx,
1404 uint32_t MaxMDCount) {
1405 auto VDs = InstrProfR.getValueArrayForSite(ValueKind, SiteIdx);
1406 if (VDs.empty())
1407 return;
1408 uint64_t Sum = 0;
1409 for (const InstrProfValueData &V : VDs)
1410 Sum = SaturatingAdd(Sum, V.Count);
1411 annotateValueSite(M, Inst, VDs, Sum, ValueKind, MaxMDCount);
1412}
1413
1416 uint64_t Sum, InstrProfValueKind ValueKind,
1417 uint32_t MaxMDCount) {
1418 if (VDs.empty())
1419 return;
1420 LLVMContext &Ctx = M.getContext();
1421 MDBuilder MDHelper(Ctx);
1423 // Tag
1425 // Value Kind
1426 Vals.push_back(MDHelper.createConstant(
1427 ConstantInt::get(Type::getInt32Ty(Ctx), ValueKind)));
1428 // Total Count
1429 Vals.push_back(
1430 MDHelper.createConstant(ConstantInt::get(Type::getInt64Ty(Ctx), Sum)));
1431
1432 // Value Profile Data
1433 uint32_t MDCount = MaxMDCount;
1434 // Zero values might occur multiple times (e.g., multiple functions that
1435 // cannot be remapped). Deduplicate them to enforce the variant that
1436 // values are unique, which allows passes to make some simplifying
1437 // assumptions.
1438 // TODO(boomanaiden154): This fits more naturally in addValueData, but
1439 // preserving the current behavior is necessary for some error handling
1440 // paths. When that gets cleaned up, we should move this there.
1441 // TODO(boomanaiden154): We are also deduplicating non-zero values.
1442 // These are rare and should only come from corrupted profiles, so we
1443 // just skip them. Remove this when they are fixed properly in
1444 // llvm-profdata.
1445 uint64_t ZeroCount = 0;
1446 DenseSet<uint64_t> VisitedValues;
1447 for (const auto &VD : VDs) {
1448 auto [_, ValueInserted] = VisitedValues.insert(VD.Value);
1449 if (VD.Value != 0 && !ValueInserted)
1450 continue;
1451 if (VD.Value == 0) {
1452 ZeroCount += VD.Count;
1453 } else {
1454 Vals.push_back(MDHelper.createConstant(
1455 ConstantInt::get(Type::getInt64Ty(Ctx), VD.Value)));
1456 Vals.push_back(MDHelper.createConstant(
1457 ConstantInt::get(Type::getInt64Ty(Ctx), VD.Count)));
1458 }
1459 if (--MDCount == 0)
1460 break;
1461 }
1462 if (ZeroCount != 0) {
1463 Vals.push_back(
1464 MDHelper.createConstant(ConstantInt::get(Type::getInt64Ty(Ctx), 0)));
1465 Vals.push_back(MDHelper.createConstant(
1466 ConstantInt::get(Type::getInt64Ty(Ctx), ZeroCount)));
1467 }
1468 // Only add metadata if we have at least one value. Otherwise we will end
1469 // up adding invalid metadata in the case where the profile only has a
1470 // zero value with a zero count.
1471 if (Vals.size() >= 5)
1472 Inst.setMetadata(LLVMContext::MD_prof, MDNode::get(Ctx, Vals));
1473}
1474
1476 InstrProfValueKind ValueKind) {
1477 MDNode *MD = Inst.getMetadata(LLVMContext::MD_prof);
1478 if (!MD)
1479 return nullptr;
1480
1481 if (MD->getNumOperands() < 5)
1482 return nullptr;
1483
1485 if (!Tag || Tag->getString() != MDProfLabels::ValueProfile)
1486 return nullptr;
1487
1488 // Now check kind:
1490 if (!KindInt)
1491 return nullptr;
1492 if (KindInt->getZExtValue() != ValueKind)
1493 return nullptr;
1494
1495 return MD;
1496}
1497
1500 uint32_t MaxNumValueData, uint64_t &TotalC,
1501 bool GetNoICPValue) {
1502 // Four inline elements seem to work well in practice. With MaxNumValueData,
1503 // this array won't grow very big anyway.
1505 MDNode *MD = mayHaveValueProfileOfKind(Inst, ValueKind);
1506 if (!MD)
1507 return ValueData;
1508 const unsigned NOps = MD->getNumOperands();
1509 // Get total count
1511 if (!TotalCInt)
1512 return ValueData;
1513 TotalC = TotalCInt->getZExtValue();
1514
1515 ValueData.reserve((NOps - 3) / 2);
1516 for (unsigned I = 3; I < NOps; I += 2) {
1517 if (ValueData.size() >= MaxNumValueData)
1518 break;
1522 if (!Value || !Count) {
1523 ValueData.clear();
1524 return ValueData;
1525 }
1526 uint64_t CntValue = Count->getZExtValue();
1527 if (!GetNoICPValue && (CntValue == NOMORE_ICP_MAGICNUM))
1528 continue;
1529 InstrProfValueData V;
1530 V.Value = Value->getZExtValue();
1531 V.Count = CntValue;
1532 ValueData.push_back(V);
1533 }
1534 return ValueData;
1535}
1536
1537bool needsComdatForCounter(const GlobalObject &GO, const Module &M) {
1538 if (GO.hasComdat())
1539 return true;
1540
1541 if (!M.getTargetTriple().supportsCOMDAT())
1542 return false;
1543
1544 // See createPGOFuncNameVar for more details. To avoid link errors, profile
1545 // counters for function with available_externally linkage needs to be changed
1546 // to linkonce linkage. On ELF based systems, this leads to weak symbols to be
1547 // created. Without using comdat, duplicate entries won't be removed by the
1548 // linker leading to increased data segement size and raw profile size. Even
1549 // worse, since the referenced counter from profile per-function data object
1550 // will be resolved to the common strong definition, the profile counts for
1551 // available_externally functions will end up being duplicated in raw profile
1552 // data. This can result in distorted profile as the counts of those dups
1553 // will be accumulated by the profile merger.
1555 if (Linkage != GlobalValue::ExternalWeakLinkage &&
1557 return false;
1558
1559 return true;
1560}
1561
1562// Check if INSTR_PROF_RAW_VERSION_VAR is defined.
1563bool isIRPGOFlagSet(const Module *M) {
1564 const GlobalVariable *IRInstrVar =
1565 M->getNamedGlobal(INSTR_PROF_QUOTE(INSTR_PROF_RAW_VERSION_VAR));
1566 if (!IRInstrVar || IRInstrVar->hasLocalLinkage())
1567 return false;
1568
1569 // For CSPGO+LTO, this variable might be marked as non-prevailing and we only
1570 // have the decl.
1571 if (IRInstrVar->isDeclaration())
1572 return true;
1573
1574 // Check if the flag is set.
1575 if (!IRInstrVar->hasInitializer())
1576 return false;
1577
1578 auto *InitVal = dyn_cast_or_null<ConstantInt>(IRInstrVar->getInitializer());
1579 if (!InitVal)
1580 return false;
1581 return (InitVal->getZExtValue() & VARIANT_MASK_IR_PROF) != 0;
1582}
1583
1584// Check if we can safely rename this Comdat function.
1585bool canRenameComdatFunc(const Function &F, bool CheckAddressTaken) {
1586 if (F.getName().empty())
1587 return false;
1588 if (!needsComdatForCounter(F, *(F.getParent())))
1589 return false;
1590 // Unsafe to rename the address-taken function (which can be used in
1591 // function comparison).
1592 if (CheckAddressTaken && F.hasAddressTaken())
1593 return false;
1594 // Only safe to do if this function may be discarded if it is not used
1595 // in the compilation unit.
1596 if (!GlobalValue::isDiscardableIfUnused(F.getLinkage()))
1597 return false;
1598
1599 // For AvailableExternallyLinkage functions.
1600 if (!F.hasComdat()) {
1602 return true;
1603 }
1604 return true;
1605}
1606
1607// Create the variable for the profile file name.
1608void createProfileFileNameVar(Module &M, StringRef InstrProfileOutput) {
1609 if (InstrProfileOutput.empty())
1610 return;
1611 Constant *ProfileNameConst =
1612 ConstantDataArray::getString(M.getContext(), InstrProfileOutput, true);
1613 GlobalVariable *ProfileNameVar = new GlobalVariable(
1614 M, ProfileNameConst->getType(), true, GlobalValue::WeakAnyLinkage,
1617 Triple TT(M.getTargetTriple());
1618 if (TT.supportsCOMDAT()) {
1620 ProfileNameVar->setComdat(M.getOrInsertComdat(
1622 }
1623}
1624
1626 const std::string &TestFilename,
1627 bool IsCS) {
1628 auto GetProfileSum = [IsCS](const std::string &Filename,
1629 CountSumOrPercent &Sum) -> Error {
1630 // This function is only used from llvm-profdata that doesn't use any kind
1631 // of VFS. Just create a default RealFileSystem to read profiles.
1632 auto FS = vfs::getRealFileSystem();
1633 auto ReaderOrErr = InstrProfReader::create(Filename, *FS);
1634 if (Error E = ReaderOrErr.takeError()) {
1635 return E;
1636 }
1637 auto Reader = std::move(ReaderOrErr.get());
1638 Reader->accumulateCounts(Sum, IsCS);
1639 return Error::success();
1640 };
1641 auto Ret = GetProfileSum(BaseFilename, Base);
1642 if (Ret)
1643 return Ret;
1644 Ret = GetProfileSum(TestFilename, Test);
1645 if (Ret)
1646 return Ret;
1647 this->BaseFilename = &BaseFilename;
1648 this->TestFilename = &TestFilename;
1649 Valid = true;
1650 return Error::success();
1651}
1652
1654 Mismatch.NumEntries += 1;
1655 Mismatch.CountSum += MismatchFunc.CountSum / Test.CountSum;
1656 for (unsigned I = 0; I < IPVK_Last - IPVK_First + 1; I++) {
1657 if (Test.ValueCounts[I] >= 1.0f)
1658 Mismatch.ValueCounts[I] +=
1659 MismatchFunc.ValueCounts[I] / Test.ValueCounts[I];
1660 }
1661}
1662
1664 Unique.NumEntries += 1;
1665 Unique.CountSum += UniqueFunc.CountSum / Test.CountSum;
1666 for (unsigned I = 0; I < IPVK_Last - IPVK_First + 1; I++) {
1667 if (Test.ValueCounts[I] >= 1.0f)
1668 Unique.ValueCounts[I] += UniqueFunc.ValueCounts[I] / Test.ValueCounts[I];
1669 }
1670}
1671
1673 if (!Valid)
1674 return;
1675
1676 const char *EntryName =
1677 (Level == ProgramLevel ? "functions" : "edge counters");
1678 if (Level == ProgramLevel) {
1679 OS << "Profile overlap information for base_profile: " << *BaseFilename
1680 << " and test_profile: " << *TestFilename << "\nProgram level:\n";
1681 } else {
1682 OS << "Function level:\n"
1683 << " Function: " << FuncName << " (Hash=" << FuncHash << ")\n";
1684 }
1685
1686 OS << " # of " << EntryName << " overlap: " << Overlap.NumEntries << "\n";
1687 if (Mismatch.NumEntries)
1688 OS << " # of " << EntryName << " mismatch: " << Mismatch.NumEntries
1689 << "\n";
1690 if (Unique.NumEntries)
1691 OS << " # of " << EntryName
1692 << " only in test_profile: " << Unique.NumEntries << "\n";
1693
1694 OS << " Edge profile overlap: " << format("%.3f%%", Overlap.CountSum * 100)
1695 << "\n";
1696 if (Mismatch.NumEntries)
1697 OS << " Mismatched count percentage (Edge): "
1698 << format("%.3f%%", Mismatch.CountSum * 100) << "\n";
1699 if (Unique.NumEntries)
1700 OS << " Percentage of Edge profile only in test_profile: "
1701 << format("%.3f%%", Unique.CountSum * 100) << "\n";
1702 OS << " Edge profile base count sum: " << format("%.0f", Base.CountSum)
1703 << "\n"
1704 << " Edge profile test count sum: " << format("%.0f", Test.CountSum)
1705 << "\n";
1706
1707 for (unsigned I = 0; I < IPVK_Last - IPVK_First + 1; I++) {
1708 if (Base.ValueCounts[I] < 1.0f && Test.ValueCounts[I] < 1.0f)
1709 continue;
1710 char ProfileKindName[20] = {0};
1711 switch (I) {
1712 case IPVK_IndirectCallTarget:
1713 strncpy(ProfileKindName, "IndirectCall", 19);
1714 break;
1715 case IPVK_MemOPSize:
1716 strncpy(ProfileKindName, "MemOP", 19);
1717 break;
1718 case IPVK_VTableTarget:
1719 strncpy(ProfileKindName, "VTable", 19);
1720 break;
1721 default:
1722 snprintf(ProfileKindName, 19, "VP[%d]", I);
1723 break;
1724 }
1725 OS << " " << ProfileKindName
1726 << " profile overlap: " << format("%.3f%%", Overlap.ValueCounts[I] * 100)
1727 << "\n";
1728 if (Mismatch.NumEntries)
1729 OS << " Mismatched count percentage (" << ProfileKindName
1730 << "): " << format("%.3f%%", Mismatch.ValueCounts[I] * 100) << "\n";
1731 if (Unique.NumEntries)
1732 OS << " Percentage of " << ProfileKindName
1733 << " profile only in test_profile: "
1734 << format("%.3f%%", Unique.ValueCounts[I] * 100) << "\n";
1735 OS << " " << ProfileKindName
1736 << " profile base count sum: " << format("%.0f", Base.ValueCounts[I])
1737 << "\n"
1738 << " " << ProfileKindName
1739 << " profile test count sum: " << format("%.0f", Test.ValueCounts[I])
1740 << "\n";
1741 }
1742}
1743
1744namespace IndexedInstrProf {
1745Expected<Header> Header::readFromBuffer(const unsigned char *Buffer) {
1746 using namespace support;
1747 static_assert(std::is_standard_layout_v<Header>,
1748 "Use standard layout for Header for simplicity");
1749 Header H;
1750
1752 // Check the magic number.
1753 if (H.Magic != IndexedInstrProf::Magic)
1755
1756 // Read the version.
1758 if (H.getIndexedProfileVersion() >
1761
1763 "Please update the reader as needed when a new field is added "
1764 "or when indexed profile version gets bumped.");
1765
1766 Buffer += sizeof(uint64_t); // Skip Header.Unused field.
1769 if (H.getIndexedProfileVersion() >= 8)
1770 H.MemProfOffset =
1772 if (H.getIndexedProfileVersion() >= 9)
1773 H.BinaryIdOffset =
1775 // Version 11 is handled by this condition.
1776 if (H.getIndexedProfileVersion() >= 10)
1777 H.TemporalProfTracesOffset =
1779 if (H.getIndexedProfileVersion() >= 12)
1780 H.VTableNamesOffset =
1782 return H;
1783}
1784
1786 return GET_VERSION(Version);
1787}
1788
1789size_t Header::size() const {
1790 switch (getIndexedProfileVersion()) {
1791 // To retain backward compatibility, new fields must be appended to the end
1792 // of the header, and byte offset of existing fields shouldn't change when
1793 // indexed profile version gets incremented.
1794 static_assert(
1796 "Please update the size computation below if a new field has "
1797 "been added to the header; for a version bump without new "
1798 "fields, add a case statement to fall through to the latest version.");
1799 case 14ull: // UniformityBits added in record data, no header change
1800 case 13ull:
1801 case 12ull:
1802 return 72;
1803 case 11ull:
1804 [[fallthrough]];
1805 case 10ull:
1806 return 64;
1807 case 9ull:
1808 return 56;
1809 case 8ull:
1810 return 48;
1811 default: // Version7 (when the backwards compatible header was introduced).
1812 return 40;
1813 }
1814}
1815
1816} // namespace IndexedInstrProf
1817
1818} // end namespace llvm
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
aarch64 promote const
uint64_t uint64_t
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
#define _
Module.h This file contains the declarations for the Module class.
static cl::opt< bool > StaticFuncFullModulePrefix("static-func-full-module-prefix", cl::init(true), cl::Hidden, cl::desc("Use full module build paths in the profile counter names for " "static functions."))
static cl::opt< unsigned > StaticFuncStripDirNamePrefix("static-func-strip-dirname-prefix", cl::init(0), cl::Hidden, cl::desc("Strip specified level of directory name from source path in " "the profile counter name for static functions."))
static std::string getInstrProfErrString(instrprof_error Err, const std::string &ErrMsg="")
Definition InstrProf.cpp:83
#define INSTR_PROF_QUOTE(x)
#define GET_VERSION(V)
#define INSTR_PROF_PROFILE_NAME_VAR
#define INSTR_PROF_RAW_VERSION_VAR
#define VARIANT_MASK_IR_PROF
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define G(x, y, z)
Definition MD5.cpp:55
#define H(x, y, z)
Definition MD5.cpp:56
This file contains the declarations for metadata subclasses.
#define T
static constexpr StringLiteral Filename
#define P(N)
This file contains the declarations for profiling metadata utility functions.
const char * Msg
static const char * name
This file defines the SmallVector class.
This file contains some functions that are useful when dealing with strings.
#define LLVM_DEBUG(...)
Definition Debug.h:119
Defines the virtual file system interface vfs::FileSystem.
The Input class is used to parse a yaml document into in-memory structs and vectors.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
iterator end() const
Definition ArrayRef.h:130
size_t size() const
Get the array size.
Definition ArrayRef.h:141
iterator begin() const
Definition ArrayRef.h:129
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
static LLVM_ABI Constant * getString(LLVMContext &Context, StringRef Initializer, bool AddNull=true, bool ByteString=false)
This method constructs a CDS and initializes it with a text string.
This is the shared class of boolean and integer constants.
Definition Constants.h:87
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition Constants.h:168
This is an important base class in LLVM.
Definition Constant.h:44
unsigned size() const
Definition DenseMap.h:717
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:856
Implements a dense probed hash-table based set.
Definition DenseSet.h:281
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
static ErrorSuccess success()
Create a success value.
Definition Error.h:336
Tagged union holding either a T or a Error.
Definition Error.h:485
LLVM_ABI void setComdat(Comdat *C)
Definition Globals.cpp:287
bool hasComdat() const
static LLVM_ABI GUID getGUIDAssumingExternalLinkage(StringRef GlobalName)
Return a 64-bit global unique ID constructed from the name of a global symbol.
Definition Globals.cpp:80
static bool isLocalLinkage(LinkageTypes Linkage)
LLVM_ABI bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Definition Globals.cpp:408
LinkageTypes getLinkage() const
bool hasLocalLinkage() const
void setLinkage(LinkageTypes LT)
Module * getParent()
Get the module that this global value is contained inside of...
@ HiddenVisibility
The GV is hidden.
Definition GlobalValue.h:69
static LLVM_ABI std::string getGlobalIdentifier(StringRef Name, GlobalValue::LinkageTypes Linkage, StringRef FileName)
Return the modified name for a global value suitable to be used as the key for a global lookup (e....
Definition Globals.cpp:234
void setVisibility(VisibilityTypes V)
static bool isDiscardableIfUnused(LinkageTypes Linkage)
Whether the definition of this global may be discarded if it is not used in its compilation unit.
LinkageTypes
An enumeration for the kinds of linkage for global values.
Definition GlobalValue.h:52
@ PrivateLinkage
Like Internal, but omit from symbol table.
Definition GlobalValue.h:61
@ InternalLinkage
Rename collisions when linking (static functions).
Definition GlobalValue.h:60
@ LinkOnceAnyLinkage
Keep one copy of function when linking (inline)
Definition GlobalValue.h:55
@ ExternalLinkage
Externally visible function.
Definition GlobalValue.h:53
@ WeakAnyLinkage
Keep one copy of named function when linking (weak)
Definition GlobalValue.h:57
@ AvailableExternallyLinkage
Available for inspection, not emission.
Definition GlobalValue.h:54
@ ExternalWeakLinkage
ExternalWeak linkage description.
Definition GlobalValue.h:62
@ LinkOnceODRLinkage
Same, but only replaced by something equivalent.
Definition GlobalValue.h:56
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
bool hasInitializer() const
Definitions have initializers, declarations don't.
std::string message() const override
Return the error message as a string.
static LLVM_ABI Expected< std::unique_ptr< InstrProfReader > > create(const Twine &Path, vfs::FileSystem &FS, const InstrProfCorrelator *Correlator=nullptr, const object::BuildIDFetcher *BIDFetcher=nullptr, std::optional< ProfCorrelatorKind > BIDFetcherCorrelatorKind=std::nullopt, std::function< void(Error)> Warn=nullptr)
Factory method to create an appropriately typed reader for the given instrprof file.
A symbol table used for function [IR]PGO name look-up with keys (such as pointers,...
Definition InstrProf.h:500
static LLVM_ABI StringRef getCanonicalName(StringRef PGOName)
Error addSymbolName(StringRef SymbolName)
Definition InstrProf.h:648
Error addVTableName(StringRef VTableName)
Adds VTableName as a known symbol, and inserts it to a map that tracks all vtable names.
Definition InstrProf.h:670
LLVM_ABI void dumpNames(raw_ostream &OS) const
Dump the symbols in this table.
LLVM_ABI Error create(object::SectionRef &Section)
Create InstrProfSymtab from an object file section which contains function PGO names.
Error addFuncName(StringRef FuncName)
The method name is kept since there are many callers.
Definition InstrProf.h:666
LLVM_ABI Error initVTableNamesFromCompressedStrings(StringRef CompressedVTableNames)
Initialize 'this' with the set of vtable names encoded in CompressedVTableNames.
LLVM_ABI uint64_t getVTableHashFromAddress(uint64_t Address) const
Return a vtable's hash, or 0 if the vtable doesn't exist in this SymTab.
LLVM_ABI uint64_t getFunctionHashFromAddress(uint64_t Address) const
Return a function's hash, or 0, if the function isn't in this SymTab.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
LLVM_ABI ConstantAsMetadata * createConstant(Constant *C)
Return the given constant as metadata.
Definition MDBuilder.cpp:25
LLVM_ABI MDString * createString(StringRef Str)
Return the given string as metadata.
Definition MDBuilder.cpp:21
Metadata node.
Definition Metadata.h:1081
const MDOperand & getOperand(unsigned I) const
Definition Metadata.h:1437
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1579
unsigned getNumOperands() const
Return number of MDNode operands.
Definition Metadata.h:1443
A single uniqued string.
Definition Metadata.h:733
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
const std::string & getSourceFileName() const
Get the module's original source file name.
Definition Module.h:310
Represent a mutable reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:294
raw_ostream & OS
Definition InstrProf.h:87
LLVM_ABI uint64_t tell() const
LLVM_ABI void writeByte(uint8_t V)
LLVM_ABI void patch(ArrayRef< PatchItem > P)
LLVM_ABI void write32(uint32_t V)
support::endian::Writer LE
Definition InstrProf.h:88
LLVM_ABI ProfOStream(raw_fd_ostream &FD)
LLVM_ABI void write(uint64_t V)
void reserve(size_type N)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
std::pair< StringRef, StringRef > split(char Separator) const
Split into two substrings around the first occurrence of a separator character.
Definition StringRef.h:736
std::string str() const
Get the contents as an std::string.
Definition StringRef.h:222
const unsigned char * bytes_end() const
Definition StringRef.h:125
constexpr StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
Definition StringRef.h:597
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition StringRef.h:258
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
StringRef drop_front(size_t N=1) const
Return a StringRef equal to 'this' but with the first N elements dropped.
Definition StringRef.h:635
constexpr size_t size() const
Get the string size.
Definition StringRef.h:144
const unsigned char * bytes_begin() const
Definition StringRef.h:122
unsigned size() const
Definition Trace.h:96
Triple - Helper class for working with autoconf configuration names.
Definition Triple.h:48
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
Definition Type.cpp:300
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:299
See the file comment.
Definition ValueMap.h:84
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:315
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:209
An efficient, type-erasing, non-owning reference to a callable.
A raw_ostream that writes to a file descriptor.
uint64_t seek(uint64_t off)
Flushes the stream and repositions the underlying file descriptor position to the offset specified fr...
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
uint64_t tell() const
tell - Return the current offset with the file.
A raw_ostream that writes to an std::string.
std::string & str()
Returns the string's reference.
static StringRef getCanonicalFnName(const Function &F)
Return the canonical name for a function, taking into account suffix elision policy attributes.
const uint64_t Magic
Definition InstrProf.h:1193
initializer< Ty > init(const Ty &Val)
LLVM_ABI void compress(ArrayRef< uint8_t > Input, SmallVectorImpl< uint8_t > &CompressedBuffer, int Level=DefaultCompression)
LLVM_ABI Error decompress(ArrayRef< uint8_t > Input, uint8_t *Output, size_t &UncompressedSize)
LLVM_ABI bool isAvailable()
constexpr int BestSizeCompression
Definition Compression.h:40
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > dyn_extract(Y &&MD)
Extract a Value from Metadata, if any.
Definition Metadata.h:707
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract(Y &&MD)
Extract a Value from Metadata.
Definition Metadata.h:679
value_type byte_swap(value_type value, endianness endian)
Swap the bytes of value to match the given endianness.
Definition Endian.h:45
value_type readNext(const CharT *&memory, endianness endian)
Read a value of a particular endianness from a buffer, and increment the buffer past that value.
Definition Endian.h:67
LLVM_ABI bool is_separator(char value, Style style=Style::native)
Check whether the given char is a path separator on the host OS.
Definition Path.cpp:618
void swapByteOrder(T &Value)
LLVM_ABI IntrusiveRefCntPtr< FileSystem > getRealFileSystem()
Gets an vfs::FileSystem for the 'real' file system, as seen by the operating system.
This is an optimization pass for GlobalISel generic memory operations.
StringRef getInstrProfNameVarPrefix()
Return the name prefix of variables containing instrumented function names.
Definition InstrProf.h:131
LLVM_ABI std::string getPGOFuncName(const Function &F, bool InLTO=false, uint64_t Version=INSTR_PROF_INDEX_VERSION)
Please use getIRPGOObjectName for LLVM IR instrumentation.
ArrayRef< CharT > arrayRefFromStringRef(StringRef Input)
Construct an array ref of bytes from a string ref.
RelativeUniformCounterPtr ValuesPtrExpr NumValueSites[IPVK_Last+1]
Definition InstrProf.h:95
void getValueForSiteInstrProf(const void *R, InstrProfValueData *Dst, uint32_t K, uint32_t S)
LLVM_ABI cl::opt< bool > DoInstrProfNameCompression
LLVM_ABI StringRef getFuncNameWithoutPrefix(StringRef PGOFuncName, StringRef FileName="<unknown>")
Given a PGO function name, remove the filename prefix and return the original (static) function name.
auto partition_point(R &&Range, Predicate P)
Binary search for the first iterator in a range where a predicate is false.
Definition STLExtras.h:2145
INSTR_PROF_VISIBILITY ValueProfRecord * getValueProfRecordNext(ValueProfRecord *VPR)
Use this method to advance to the next This ValueProfRecord.
LLVM_ABI std::string getIRPGOObjectName(const GlobalObject &GO, bool InLTO=false)
LLVM_ABI std::pair< StringRef, StringRef > getParsedIRPGOName(StringRef IRPGOName)
static std::unique_ptr< ValueProfData > allocValueProfData(uint32_t TotalSize)
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr UniformCountersBegin(uintptr_t) UniformCountersBegin -(uintptr_t) DataBegin struct llvm::ValueProfData ValueProfData
This is the header of the data structure that defines the on-disk layout of the value profile data of...
MDNode * mayHaveValueProfileOfKind(const Instruction &Inst, InstrProfValueKind ValueKind)
LLVM_ABI std::string getInstrProfSectionName(InstrProfSectKind IPSK, Triple::ObjectFormatType OF, bool AddSegmentInfo=true)
Return the name of the profile section corresponding to IPSK.
cl::opt< bool > EnableVTableProfileUse("enable-vtable-profile-use", cl::init(false), cl::desc("If ThinLTO and WPD is enabled and this option is true, vtable " "profiles will be used by ICP pass for more efficient indirect " "call sequence. If false, type profiles won't be used."))
uint64_t getInstrMaxCountValue()
Return the max count value. We reserver a few large values for special use.
Definition InstrProf.h:97
LLVM_ABI bool needsComdatForCounter(const GlobalObject &GV, const Module &M)
Check if we can use Comdat for profile variables.
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
LLVM_ABI GlobalVariable * createPGOFuncNameVar(Function &F, StringRef PGOFuncName)
Create and return the global variable for function name used in PGO instrumentation.
LLVM_ABI void annotateValueSite(Module &M, Instruction &Inst, const InstrProfRecord &InstrProfR, InstrProfValueKind ValueKind, uint32_t SiteIndx, uint32_t MaxMDCount=3)
Get the value profile data for value site SiteIdx from InstrProfR and annotate the instruction Inst w...
INSTR_PROF_VISIBILITY uint32_t getValueProfDataSize(ValueProfRecordClosure *Closure)
Return the total size in bytes of the on-disk value profile data given the data stored in Record.
LLVM_ABI Error collectPGOFuncNameStrings(ArrayRef< GlobalVariable * > NameVars, std::string &Result, bool doCompression=true)
Produce Result string with the same format described above.
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
InstrProfSectKind
Definition InstrProf.h:91
LLVM_ABI Error readAndDecodeStrings(StringRef NameStrings, std::function< Error(StringRef)> NameCallback)
NameStrings is a string composed of one or more possibly encoded sub-strings.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI StringRef getPGOFuncNameVarInitializer(GlobalVariable *NameVar)
Return the initializer in string of the PGO name var NameVar.
std::enable_if_t< std::is_unsigned_v< T >, T > SaturatingMultiplyAdd(T X, T Y, T A, bool *ResultOverflowed=nullptr)
Multiply two unsigned integers, X and Y, and add the unsigned integer, A to the product.
Definition MathExtras.h:684
INSTR_PROF_VISIBILITY ValueProfRecord * getFirstValueProfRecord(ValueProfData *VPD)
Return the first ValueProfRecord instance.
StringRef getInstrProfNameSeparator()
Return the marker used to separate PGO names during serialization.
Definition InstrProf.h:225
LLVM_ABI SmallVector< InstrProfValueData, 4 > getValueProfDataFromInst(const Instruction &Inst, InstrProfValueKind ValueKind, uint32_t MaxNumValueData, uint64_t &TotalC, bool GetNoICPValue=false)
Extract the value profile data from Inst and returns them if Inst is annotated with value profile dat...
INSTR_PROF_VISIBILITY ValueProfData * serializeValueProfDataFrom(ValueProfRecordClosure *Closure, ValueProfData *DstData)
Extract value profile data of a function from the Closure and serialize the data into DstData if it i...
INSTR_PROF_VISIBILITY InstrProfValueData * getValueProfRecordValueData(ValueProfRecord *VPR)
Return the pointer to the start of value data array.
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
Definition Format.h:102
Error make_error(ArgTs &&... Args)
Make a Error instance representing failure using the given error info type.
Definition Error.h:340
@ Other
Any other memory.
Definition ModRef.h:68
std::string join(IteratorT Begin, IteratorT End, StringRef Separator)
Joins the strings in the range [Begin, End), adding Separator between the elements.
instrprof_error
Definition InstrProf.h:391
InstrProfValueKind
Definition InstrProf.h:324
std::enable_if_t< std::is_unsigned_v< T >, T > SaturatingMultiply(T X, T Y, bool *ResultOverflowed=nullptr)
Multiply two unsigned integers, X and Y, of type T.
Definition MathExtras.h:638
LLVM_ABI const std::error_category & instrprof_category()
LLVM_ABI Error collectVTableStrings(ArrayRef< GlobalVariable * > VTables, std::string &Result, bool doCompression)
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
auto count(R &&Range, const E &Element)
Wrapper function around std::count to count the number of times an element Element occurs in the give...
Definition STLExtras.h:2028
static StringRef getStrippedSourceFileName(const GlobalObject &GO)
ArrayRef(const T &OneElt) -> ArrayRef< T >
uint32_t getNumValueSitesInstrProf(const void *Record, uint32_t VKind)
OutputIt copy(R &&Range, OutputIt Out)
Definition STLExtras.h:1901
LLVM_ABI bool canRenameComdatFunc(const Function &F, bool CheckAddressTaken=false)
Check if we can safely rename this Comdat function.
LLVM_ABI void createProfileFileNameVar(Module &M, StringRef InstrProfileOutput)
constexpr char GlobalIdentifierDelimiter
Definition GlobalValue.h:47
LLVM_ABI Error collectGlobalObjectNameStrings(ArrayRef< std::string > NameStrs, bool doCompression, std::string &Result)
Given a vector of strings (names of global objects like functions or, virtual tables) NameStrs,...
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
Definition STLExtras.h:2208
void setPGOFuncVisibility(Module &M, GlobalVariable *FuncNameVar)
INSTR_PROF_VISIBILITY INSTR_PROF_INLINE uint32_t getValueProfRecordNumValueData(ValueProfRecord *This)
Return the total number of value data for This record.
unsigned encodeULEB128(uint64_t Value, raw_ostream &OS, unsigned PadTo=0)
Utility function to encode a ULEB128 value to an output stream.
Definition LEB128.h:79
uint32_t getNumValueDataForSiteInstrProf(const void *R, uint32_t VK, uint32_t S)
static ValueProfRecordClosure InstrProfRecordClosure
LLVM_ABI std::string getPGOFuncNameVarName(StringRef FuncName, GlobalValue::LinkageTypes Linkage)
Return the name of the global variable used to store a function name in PGO instrumentation.
static StringRef stripDirPrefix(StringRef PathNameStr, uint32_t NumPrefix)
static void mergeUniformityBits(std::vector< uint8_t > &Dst, ArrayRef< uint8_t > Src)
endianness
Definition bit.h:71
std::enable_if_t< std::is_unsigned_v< T >, T > SaturatingAdd(T X, T Y, bool *ResultOverflowed=nullptr)
Add two unsigned integers, X and Y, of type T.
Definition MathExtras.h:609
LLVM_ABI bool isGPUProfTarget(const Module &M)
Determines whether module targets a GPU eligable for PGO instrumentation.
LLVM_ABI bool isIRPGOFlagSet(const Module *M)
Check if INSTR_PROF_RAW_VERSION_VAR is defined.
void consumeError(Error Err)
Consume a Error without doing anything.
Definition Error.h:1106
const uint64_t NOMORE_ICP_MAGICNUM
Magic number in the value profile metadata showing a target has been promoted for the instruction and...
Definition Metadata.h:59
StringRef toStringRef(bool B)
Construct a string ref from a boolean.
uint32_t getNumValueKindsInstrProf(const void *Record)
ValueProfRecordClosure Interface implementation for InstrProfRecord class.
ValueProfData * allocValueProfDataInstrProf(size_t TotalSizeInBytes)
uint32_t getNumValueDataInstrProf(const void *Record, uint32_t VKind)
static std::string getIRPGONameForGlobalObject(const GlobalObject &GO, GlobalValue::LinkageTypes Linkage, StringRef FileName)
uint64_t decodeULEB128(const uint8_t *p, unsigned *n, const uint8_t *end, const char **error, ULEB128DecodeError *errorCode)
Utility function to decode a ULEB128 value and report a typed error.
Definition LEB128.h:145
cl::opt< bool > EnableVTableValueProfiling("enable-vtable-value-profiling", cl::init(false), cl::desc("If true, the virtual table address will be instrumented to know " "the types of a C++ pointer. The information is used in indirect " "call promotion to do selective vtable-based comparison."))
#define N
std::array< double, IPVK_Last - IPVK_First+1 > ValueCounts
Definition InstrProf.h:819
LLVM_ABI uint64_t getIndexedProfileVersion() const
LLVM_ABI size_t size() const
static LLVM_ABI Expected< Header > readFromBuffer(const unsigned char *Buffer)
Profiling information for a single function.
Definition InstrProf.h:907
LLVM_ABI void overlapValueProfData(uint32_t ValueKind, InstrProfRecord &Src, OverlapStats &Overlap, OverlapStats &FuncLevelOverlap)
Compute the overlap of value profile counts.
std::vector< uint64_t > Counts
Definition InstrProf.h:908
ArrayRef< InstrProfValueData > getValueArrayForSite(uint32_t ValueKind, uint32_t Site) const
Return the array of profiled values at Site.
Definition InstrProf.h:1153
uint16_t OffloadDeviceWaveSize
Definition InstrProf.h:917
CountPseudoKind getCountPseudoKind() const
Definition InstrProf.h:1036
LLVM_ABI void accumulateCounts(CountSumOrPercent &Sum) const
Compute the sums of all counts and store in Sum.
uint32_t getNumValueSites(uint32_t ValueKind) const
Return the number of instrumented sites for ValueKind.
Definition InstrProf.h:1148
std::vector< uint64_t > UniformCounts
For AMDGPU offload profiling: raw or merged uniform counters.
Definition InstrProf.h:912
void setPseudoCount(CountPseudoKind Kind)
Definition InstrProf.h:1044
LLVM_ABI void merge(InstrProfRecord &Other, uint64_t Weight, function_ref< void(instrprof_error)> Warn)
Merge the counts in Other into this one.
LLVM_ABI void addValueData(uint32_t ValueKind, uint32_t Site, ArrayRef< InstrProfValueData > VData, InstrProfSymtab *SymTab)
Add ValueData for ValueKind at value Site.
std::vector< uint8_t > UniformityBits
For AMDGPU offload profiling: 1 bit per basic block indicating whether the block is usually entered w...
Definition InstrProf.h:916
LLVM_ABI void overlap(InstrProfRecord &Other, OverlapStats &Overlap, OverlapStats &FuncLevelOverlap, uint64_t ValueCutoff)
Compute the overlap b/w this IntrprofRecord and Other.
std::vector< uint8_t > BitmapBytes
Definition InstrProf.h:909
LLVM_ABI void computeBlockUniformity()
Recompute uniformity metadata from raw uniform counters, when present.
LLVM_ABI void scale(uint64_t N, uint64_t D, function_ref< void(instrprof_error)> Warn)
Scale up profile counts (including value profile data) by a factor of (N / D).
void sortByTargetValues()
Sort ValueData ascending by Value.
Definition InstrProf.h:884
std::vector< InstrProfValueData > ValueData
Value profiling data pairs at a given value site.
Definition InstrProf.h:877
LLVM_ABI void merge(InstrProfValueSiteRecord &Input, uint64_t Weight, function_ref< void(instrprof_error)> Warn)
Merge data from another InstrProfValueSiteRecord Optionally scale merged counts by Weight.
LLVM_ABI void overlap(InstrProfValueSiteRecord &Input, uint32_t ValueKind, OverlapStats &Overlap, OverlapStats &FuncLevelOverlap)
Compute the overlap b/w this record and Input record.
LLVM_ABI void scale(uint64_t N, uint64_t D, function_ref< void(instrprof_error)> Warn)
Scale up value profile data counts by N (Numerator) / D (Denominator).
static LLVM_ABI const char * ValueProfile
LLVM_ABI void addOneMismatch(const CountSumOrPercent &MismatchFunc)
static double score(uint64_t Val1, uint64_t Val2, double Sum1, double Sum2)
Definition InstrProf.h:860
LLVM_ABI Error accumulateCounts(const std::string &BaseFilename, const std::string &TestFilename, bool IsCS)
LLVM_ABI void dump(raw_fd_ostream &OS) const
CountSumOrPercent Overlap
Definition InstrProf.h:836
CountSumOrPercent Base
Definition InstrProf.h:832
LLVM_ABI void addOneUnique(const CountSumOrPercent &UniqueFunc)
const std::string * BaseFilename
Definition InstrProf.h:840
const std::string * TestFilename
Definition InstrProf.h:841
CountSumOrPercent Unique
Definition InstrProf.h:838
CountSumOrPercent Mismatch
Definition InstrProf.h:837
StringRef FuncName
Definition InstrProf.h:842
OverlapStatsLevel Level
Definition InstrProf.h:839
CountSumOrPercent Test
Definition InstrProf.h:834
static LLVM_ABI void createBPFunctionNodes(ArrayRef< TemporalProfTraceTy > Traces, std::vector< BPFunctionNode > &Nodes, bool RemoveOutlierUNs=true)
Use a set of temporal profile traces to create a list of balanced partitioning function nodes used by...
This is the header of the data structure that defines the on-disk layout of the value profile data of...
Definition InstrProf.h:477
uint32_t NumValueKinds
Definition InstrProf.h:491