xref: /openbsd-src/gnu/llvm/llvm/lib/ProfileData/InstrProf.cpp (revision d415bd752c734aee168c4ee86ff32e8cc249eb16)
109467b48Spatrick //===- InstrProf.cpp - Instrumented profiling format support --------------===//
209467b48Spatrick //
309467b48Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
409467b48Spatrick // See https://llvm.org/LICENSE.txt for license information.
509467b48Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
609467b48Spatrick //
709467b48Spatrick //===----------------------------------------------------------------------===//
809467b48Spatrick //
909467b48Spatrick // This file contains support for clang's instrumentation based PGO and
1009467b48Spatrick // coverage.
1109467b48Spatrick //
1209467b48Spatrick //===----------------------------------------------------------------------===//
1309467b48Spatrick 
1409467b48Spatrick #include "llvm/ProfileData/InstrProf.h"
1509467b48Spatrick #include "llvm/ADT/ArrayRef.h"
1609467b48Spatrick #include "llvm/ADT/SmallString.h"
1709467b48Spatrick #include "llvm/ADT/SmallVector.h"
1809467b48Spatrick #include "llvm/ADT/StringExtras.h"
1909467b48Spatrick #include "llvm/ADT/StringRef.h"
2009467b48Spatrick #include "llvm/ADT/Triple.h"
2173471bf0Spatrick #include "llvm/Config/config.h"
2209467b48Spatrick #include "llvm/IR/Constant.h"
2309467b48Spatrick #include "llvm/IR/Constants.h"
2409467b48Spatrick #include "llvm/IR/Function.h"
2509467b48Spatrick #include "llvm/IR/GlobalValue.h"
2609467b48Spatrick #include "llvm/IR/GlobalVariable.h"
2709467b48Spatrick #include "llvm/IR/Instruction.h"
2809467b48Spatrick #include "llvm/IR/LLVMContext.h"
2909467b48Spatrick #include "llvm/IR/MDBuilder.h"
3009467b48Spatrick #include "llvm/IR/Metadata.h"
3109467b48Spatrick #include "llvm/IR/Module.h"
3209467b48Spatrick #include "llvm/IR/Type.h"
3309467b48Spatrick #include "llvm/ProfileData/InstrProfReader.h"
3409467b48Spatrick #include "llvm/Support/Casting.h"
3509467b48Spatrick #include "llvm/Support/CommandLine.h"
3609467b48Spatrick #include "llvm/Support/Compiler.h"
3709467b48Spatrick #include "llvm/Support/Compression.h"
3809467b48Spatrick #include "llvm/Support/Endian.h"
3909467b48Spatrick #include "llvm/Support/Error.h"
4009467b48Spatrick #include "llvm/Support/ErrorHandling.h"
4109467b48Spatrick #include "llvm/Support/LEB128.h"
4209467b48Spatrick #include "llvm/Support/MathExtras.h"
4309467b48Spatrick #include "llvm/Support/Path.h"
4409467b48Spatrick #include "llvm/Support/SwapByteOrder.h"
4509467b48Spatrick #include <algorithm>
4609467b48Spatrick #include <cassert>
4709467b48Spatrick #include <cstddef>
4809467b48Spatrick #include <cstdint>
4909467b48Spatrick #include <cstring>
5009467b48Spatrick #include <memory>
5109467b48Spatrick #include <string>
5209467b48Spatrick #include <system_error>
53*d415bd75Srobert #include <type_traits>
5409467b48Spatrick #include <utility>
5509467b48Spatrick #include <vector>
5609467b48Spatrick 
5709467b48Spatrick using namespace llvm;
5809467b48Spatrick 
5909467b48Spatrick static cl::opt<bool> StaticFuncFullModulePrefix(
6009467b48Spatrick     "static-func-full-module-prefix", cl::init(true), cl::Hidden,
6109467b48Spatrick     cl::desc("Use full module build paths in the profile counter names for "
6209467b48Spatrick              "static functions."));
6309467b48Spatrick 
6409467b48Spatrick // This option is tailored to users that have different top-level directory in
6509467b48Spatrick // profile-gen and profile-use compilation. Users need to specific the number
6609467b48Spatrick // of levels to strip. A value larger than the number of directories in the
6709467b48Spatrick // source file will strip all the directory names and only leave the basename.
6809467b48Spatrick //
6909467b48Spatrick // Note current ThinLTO module importing for the indirect-calls assumes
7009467b48Spatrick // the source directory name not being stripped. A non-zero option value here
7109467b48Spatrick // can potentially prevent some inter-module indirect-call-promotions.
7209467b48Spatrick static cl::opt<unsigned> StaticFuncStripDirNamePrefix(
7309467b48Spatrick     "static-func-strip-dirname-prefix", cl::init(0), cl::Hidden,
7409467b48Spatrick     cl::desc("Strip specified level of directory name from source path in "
7509467b48Spatrick              "the profile counter name for static functions."));
7609467b48Spatrick 
getInstrProfErrString(instrprof_error Err,const std::string & ErrMsg="")77*d415bd75Srobert static std::string getInstrProfErrString(instrprof_error Err,
78*d415bd75Srobert                                          const std::string &ErrMsg = "") {
79*d415bd75Srobert   std::string Msg;
80*d415bd75Srobert   raw_string_ostream OS(Msg);
81*d415bd75Srobert 
8209467b48Spatrick   switch (Err) {
8309467b48Spatrick   case instrprof_error::success:
84*d415bd75Srobert     OS << "success";
85*d415bd75Srobert     break;
8609467b48Spatrick   case instrprof_error::eof:
87*d415bd75Srobert     OS << "end of File";
88*d415bd75Srobert     break;
8909467b48Spatrick   case instrprof_error::unrecognized_format:
90*d415bd75Srobert     OS << "unrecognized instrumentation profile encoding format";
91*d415bd75Srobert     break;
9209467b48Spatrick   case instrprof_error::bad_magic:
93*d415bd75Srobert     OS << "invalid instrumentation profile data (bad magic)";
94*d415bd75Srobert     break;
9509467b48Spatrick   case instrprof_error::bad_header:
96*d415bd75Srobert     OS << "invalid instrumentation profile data (file header is corrupt)";
97*d415bd75Srobert     break;
9809467b48Spatrick   case instrprof_error::unsupported_version:
99*d415bd75Srobert     OS << "unsupported instrumentation profile format version";
100*d415bd75Srobert     break;
10109467b48Spatrick   case instrprof_error::unsupported_hash_type:
102*d415bd75Srobert     OS << "unsupported instrumentation profile hash type";
103*d415bd75Srobert     break;
10409467b48Spatrick   case instrprof_error::too_large:
105*d415bd75Srobert     OS << "too much profile data";
106*d415bd75Srobert     break;
10709467b48Spatrick   case instrprof_error::truncated:
108*d415bd75Srobert     OS << "truncated profile data";
109*d415bd75Srobert     break;
11009467b48Spatrick   case instrprof_error::malformed:
111*d415bd75Srobert     OS << "malformed instrumentation profile data";
112*d415bd75Srobert     break;
113*d415bd75Srobert   case instrprof_error::missing_debug_info_for_correlation:
114*d415bd75Srobert     OS << "debug info for correlation is required";
115*d415bd75Srobert     break;
116*d415bd75Srobert   case instrprof_error::unexpected_debug_info_for_correlation:
117*d415bd75Srobert     OS << "debug info for correlation is not necessary";
118*d415bd75Srobert     break;
119*d415bd75Srobert   case instrprof_error::unable_to_correlate_profile:
120*d415bd75Srobert     OS << "unable to correlate profile";
121*d415bd75Srobert     break;
12273471bf0Spatrick   case instrprof_error::invalid_prof:
123*d415bd75Srobert     OS << "invalid profile created. Please file a bug "
12473471bf0Spatrick           "at: " BUG_REPORT_URL
12573471bf0Spatrick           " and include the profraw files that caused this error.";
126*d415bd75Srobert     break;
12709467b48Spatrick   case instrprof_error::unknown_function:
128*d415bd75Srobert     OS << "no profile data available for function";
129*d415bd75Srobert     break;
13009467b48Spatrick   case instrprof_error::hash_mismatch:
131*d415bd75Srobert     OS << "function control flow change detected (hash mismatch)";
132*d415bd75Srobert     break;
13309467b48Spatrick   case instrprof_error::count_mismatch:
134*d415bd75Srobert     OS << "function basic block count change detected (counter mismatch)";
135*d415bd75Srobert     break;
13609467b48Spatrick   case instrprof_error::counter_overflow:
137*d415bd75Srobert     OS << "counter overflow";
138*d415bd75Srobert     break;
13909467b48Spatrick   case instrprof_error::value_site_count_mismatch:
140*d415bd75Srobert     OS << "function value site count change detected (counter mismatch)";
141*d415bd75Srobert     break;
14209467b48Spatrick   case instrprof_error::compress_failed:
143*d415bd75Srobert     OS << "failed to compress data (zlib)";
144*d415bd75Srobert     break;
14509467b48Spatrick   case instrprof_error::uncompress_failed:
146*d415bd75Srobert     OS << "failed to uncompress data (zlib)";
147*d415bd75Srobert     break;
14809467b48Spatrick   case instrprof_error::empty_raw_profile:
149*d415bd75Srobert     OS << "empty raw profile file";
150*d415bd75Srobert     break;
15109467b48Spatrick   case instrprof_error::zlib_unavailable:
152*d415bd75Srobert     OS << "profile uses zlib compression but the profile reader was built "
15373471bf0Spatrick           "without zlib support";
154*d415bd75Srobert     break;
15509467b48Spatrick   }
156*d415bd75Srobert 
157*d415bd75Srobert   // If optional error message is not empty, append it to the message.
158*d415bd75Srobert   if (!ErrMsg.empty())
159*d415bd75Srobert     OS << ": " << ErrMsg;
160*d415bd75Srobert 
161*d415bd75Srobert   return OS.str();
16209467b48Spatrick }
16309467b48Spatrick 
16409467b48Spatrick namespace {
16509467b48Spatrick 
16609467b48Spatrick // FIXME: This class is only here to support the transition to llvm::Error. It
16709467b48Spatrick // will be removed once this transition is complete. Clients should prefer to
16809467b48Spatrick // deal with the Error value directly, rather than converting to error_code.
16909467b48Spatrick class InstrProfErrorCategoryType : public std::error_category {
name() const17009467b48Spatrick   const char *name() const noexcept override { return "llvm.instrprof"; }
17109467b48Spatrick 
message(int IE) const17209467b48Spatrick   std::string message(int IE) const override {
17309467b48Spatrick     return getInstrProfErrString(static_cast<instrprof_error>(IE));
17409467b48Spatrick   }
17509467b48Spatrick };
17609467b48Spatrick 
17709467b48Spatrick } // end anonymous namespace
17809467b48Spatrick 
instrprof_category()17909467b48Spatrick const std::error_category &llvm::instrprof_category() {
180*d415bd75Srobert   static InstrProfErrorCategoryType ErrorCategory;
181*d415bd75Srobert   return ErrorCategory;
18209467b48Spatrick }
18309467b48Spatrick 
18409467b48Spatrick namespace {
18509467b48Spatrick 
18609467b48Spatrick const char *InstrProfSectNameCommon[] = {
18709467b48Spatrick #define INSTR_PROF_SECT_ENTRY(Kind, SectNameCommon, SectNameCoff, Prefix)      \
18809467b48Spatrick   SectNameCommon,
18909467b48Spatrick #include "llvm/ProfileData/InstrProfData.inc"
19009467b48Spatrick };
19109467b48Spatrick 
19209467b48Spatrick const char *InstrProfSectNameCoff[] = {
19309467b48Spatrick #define INSTR_PROF_SECT_ENTRY(Kind, SectNameCommon, SectNameCoff, Prefix)      \
19409467b48Spatrick   SectNameCoff,
19509467b48Spatrick #include "llvm/ProfileData/InstrProfData.inc"
19609467b48Spatrick };
19709467b48Spatrick 
19809467b48Spatrick const char *InstrProfSectNamePrefix[] = {
19909467b48Spatrick #define INSTR_PROF_SECT_ENTRY(Kind, SectNameCommon, SectNameCoff, Prefix)      \
20009467b48Spatrick   Prefix,
20109467b48Spatrick #include "llvm/ProfileData/InstrProfData.inc"
20209467b48Spatrick };
20309467b48Spatrick 
20409467b48Spatrick } // namespace
20509467b48Spatrick 
20609467b48Spatrick namespace llvm {
20709467b48Spatrick 
208097a140dSpatrick cl::opt<bool> DoInstrProfNameCompression(
209097a140dSpatrick     "enable-name-compression",
210097a140dSpatrick     cl::desc("Enable name/filename string compression"), cl::init(true));
211097a140dSpatrick 
getInstrProfSectionName(InstrProfSectKind IPSK,Triple::ObjectFormatType OF,bool AddSegmentInfo)21209467b48Spatrick std::string getInstrProfSectionName(InstrProfSectKind IPSK,
21309467b48Spatrick                                     Triple::ObjectFormatType OF,
21409467b48Spatrick                                     bool AddSegmentInfo) {
21509467b48Spatrick   std::string SectName;
21609467b48Spatrick 
21709467b48Spatrick   if (OF == Triple::MachO && AddSegmentInfo)
21809467b48Spatrick     SectName = InstrProfSectNamePrefix[IPSK];
21909467b48Spatrick 
22009467b48Spatrick   if (OF == Triple::COFF)
22109467b48Spatrick     SectName += InstrProfSectNameCoff[IPSK];
22209467b48Spatrick   else
22309467b48Spatrick     SectName += InstrProfSectNameCommon[IPSK];
22409467b48Spatrick 
22509467b48Spatrick   if (OF == Triple::MachO && IPSK == IPSK_data && AddSegmentInfo)
22609467b48Spatrick     SectName += ",regular,live_support";
22709467b48Spatrick 
22809467b48Spatrick   return SectName;
22909467b48Spatrick }
23009467b48Spatrick 
addError(instrprof_error IE)23109467b48Spatrick void SoftInstrProfErrors::addError(instrprof_error IE) {
23209467b48Spatrick   if (IE == instrprof_error::success)
23309467b48Spatrick     return;
23409467b48Spatrick 
23509467b48Spatrick   if (FirstError == instrprof_error::success)
23609467b48Spatrick     FirstError = IE;
23709467b48Spatrick 
23809467b48Spatrick   switch (IE) {
23909467b48Spatrick   case instrprof_error::hash_mismatch:
24009467b48Spatrick     ++NumHashMismatches;
24109467b48Spatrick     break;
24209467b48Spatrick   case instrprof_error::count_mismatch:
24309467b48Spatrick     ++NumCountMismatches;
24409467b48Spatrick     break;
24509467b48Spatrick   case instrprof_error::counter_overflow:
24609467b48Spatrick     ++NumCounterOverflows;
24709467b48Spatrick     break;
24809467b48Spatrick   case instrprof_error::value_site_count_mismatch:
24909467b48Spatrick     ++NumValueSiteCountMismatches;
25009467b48Spatrick     break;
25109467b48Spatrick   default:
25209467b48Spatrick     llvm_unreachable("Not a soft error");
25309467b48Spatrick   }
25409467b48Spatrick }
25509467b48Spatrick 
message() const25609467b48Spatrick std::string InstrProfError::message() const {
257*d415bd75Srobert   return getInstrProfErrString(Err, Msg);
25809467b48Spatrick }
25909467b48Spatrick 
26009467b48Spatrick char InstrProfError::ID = 0;
26109467b48Spatrick 
getPGOFuncName(StringRef RawFuncName,GlobalValue::LinkageTypes Linkage,StringRef FileName,uint64_t Version LLVM_ATTRIBUTE_UNUSED)26209467b48Spatrick std::string getPGOFuncName(StringRef RawFuncName,
26309467b48Spatrick                            GlobalValue::LinkageTypes Linkage,
26409467b48Spatrick                            StringRef FileName,
26509467b48Spatrick                            uint64_t Version LLVM_ATTRIBUTE_UNUSED) {
26609467b48Spatrick   return GlobalValue::getGlobalIdentifier(RawFuncName, Linkage, FileName);
26709467b48Spatrick }
26809467b48Spatrick 
26909467b48Spatrick // Strip NumPrefix level of directory name from PathNameStr. If the number of
27009467b48Spatrick // directory separators is less than NumPrefix, strip all the directories and
27109467b48Spatrick // leave base file name only.
stripDirPrefix(StringRef PathNameStr,uint32_t NumPrefix)27209467b48Spatrick static StringRef stripDirPrefix(StringRef PathNameStr, uint32_t NumPrefix) {
27309467b48Spatrick   uint32_t Count = NumPrefix;
27409467b48Spatrick   uint32_t Pos = 0, LastPos = 0;
27509467b48Spatrick   for (auto & CI : PathNameStr) {
27609467b48Spatrick     ++Pos;
27709467b48Spatrick     if (llvm::sys::path::is_separator(CI)) {
27809467b48Spatrick       LastPos = Pos;
27909467b48Spatrick       --Count;
28009467b48Spatrick     }
28109467b48Spatrick     if (Count == 0)
28209467b48Spatrick       break;
28309467b48Spatrick   }
28409467b48Spatrick   return PathNameStr.substr(LastPos);
28509467b48Spatrick }
28609467b48Spatrick 
28709467b48Spatrick // Return the PGOFuncName. This function has some special handling when called
28809467b48Spatrick // in LTO optimization. The following only applies when calling in LTO passes
28909467b48Spatrick // (when \c InLTO is true): LTO's internalization privatizes many global linkage
29009467b48Spatrick // symbols. This happens after value profile annotation, but those internal
29109467b48Spatrick // linkage functions should not have a source prefix.
29209467b48Spatrick // Additionally, for ThinLTO mode, exported internal functions are promoted
29309467b48Spatrick // and renamed. We need to ensure that the original internal PGO name is
29409467b48Spatrick // used when computing the GUID that is compared against the profiled GUIDs.
29509467b48Spatrick // To differentiate compiler generated internal symbols from original ones,
29609467b48Spatrick // PGOFuncName meta data are created and attached to the original internal
29709467b48Spatrick // symbols in the value profile annotation step
29809467b48Spatrick // (PGOUseFunc::annotateIndirectCallSites). If a symbol does not have the meta
29909467b48Spatrick // data, its original linkage must be non-internal.
getPGOFuncName(const Function & F,bool InLTO,uint64_t Version)30009467b48Spatrick std::string getPGOFuncName(const Function &F, bool InLTO, uint64_t Version) {
30109467b48Spatrick   if (!InLTO) {
30209467b48Spatrick     StringRef FileName(F.getParent()->getSourceFileName());
30309467b48Spatrick     uint32_t StripLevel = StaticFuncFullModulePrefix ? 0 : (uint32_t)-1;
30409467b48Spatrick     if (StripLevel < StaticFuncStripDirNamePrefix)
30509467b48Spatrick       StripLevel = StaticFuncStripDirNamePrefix;
30609467b48Spatrick     if (StripLevel)
30709467b48Spatrick       FileName = stripDirPrefix(FileName, StripLevel);
30809467b48Spatrick     return getPGOFuncName(F.getName(), F.getLinkage(), FileName, Version);
30909467b48Spatrick   }
31009467b48Spatrick 
31109467b48Spatrick   // In LTO mode (when InLTO is true), first check if there is a meta data.
31209467b48Spatrick   if (MDNode *MD = getPGOFuncNameMetadata(F)) {
31309467b48Spatrick     StringRef S = cast<MDString>(MD->getOperand(0))->getString();
31409467b48Spatrick     return S.str();
31509467b48Spatrick   }
31609467b48Spatrick 
31709467b48Spatrick   // If there is no meta data, the function must be a global before the value
31809467b48Spatrick   // profile annotation pass. Its current linkage may be internal if it is
31909467b48Spatrick   // internalized in LTO mode.
32009467b48Spatrick   return getPGOFuncName(F.getName(), GlobalValue::ExternalLinkage, "");
32109467b48Spatrick }
32209467b48Spatrick 
getFuncNameWithoutPrefix(StringRef PGOFuncName,StringRef FileName)32309467b48Spatrick StringRef getFuncNameWithoutPrefix(StringRef PGOFuncName, StringRef FileName) {
32409467b48Spatrick   if (FileName.empty())
32509467b48Spatrick     return PGOFuncName;
32609467b48Spatrick   // Drop the file name including ':'. See also getPGOFuncName.
32709467b48Spatrick   if (PGOFuncName.startswith(FileName))
32809467b48Spatrick     PGOFuncName = PGOFuncName.drop_front(FileName.size() + 1);
32909467b48Spatrick   return PGOFuncName;
33009467b48Spatrick }
33109467b48Spatrick 
33209467b48Spatrick // \p FuncName is the string used as profile lookup key for the function. A
33309467b48Spatrick // symbol is created to hold the name. Return the legalized symbol name.
getPGOFuncNameVarName(StringRef FuncName,GlobalValue::LinkageTypes Linkage)33409467b48Spatrick std::string getPGOFuncNameVarName(StringRef FuncName,
33509467b48Spatrick                                   GlobalValue::LinkageTypes Linkage) {
336097a140dSpatrick   std::string VarName = std::string(getInstrProfNameVarPrefix());
33709467b48Spatrick   VarName += FuncName;
33809467b48Spatrick 
33909467b48Spatrick   if (!GlobalValue::isLocalLinkage(Linkage))
34009467b48Spatrick     return VarName;
34109467b48Spatrick 
34209467b48Spatrick   // Now fix up illegal chars in local VarName that may upset the assembler.
34309467b48Spatrick   const char *InvalidChars = "-:<>/\"'";
34409467b48Spatrick   size_t found = VarName.find_first_of(InvalidChars);
34509467b48Spatrick   while (found != std::string::npos) {
34609467b48Spatrick     VarName[found] = '_';
34709467b48Spatrick     found = VarName.find_first_of(InvalidChars, found + 1);
34809467b48Spatrick   }
34909467b48Spatrick   return VarName;
35009467b48Spatrick }
35109467b48Spatrick 
createPGOFuncNameVar(Module & M,GlobalValue::LinkageTypes Linkage,StringRef PGOFuncName)35209467b48Spatrick GlobalVariable *createPGOFuncNameVar(Module &M,
35309467b48Spatrick                                      GlobalValue::LinkageTypes Linkage,
35409467b48Spatrick                                      StringRef PGOFuncName) {
35509467b48Spatrick   // We generally want to match the function's linkage, but available_externally
35609467b48Spatrick   // and extern_weak both have the wrong semantics, and anything that doesn't
35709467b48Spatrick   // need to link across compilation units doesn't need to be visible at all.
35809467b48Spatrick   if (Linkage == GlobalValue::ExternalWeakLinkage)
35909467b48Spatrick     Linkage = GlobalValue::LinkOnceAnyLinkage;
36009467b48Spatrick   else if (Linkage == GlobalValue::AvailableExternallyLinkage)
36109467b48Spatrick     Linkage = GlobalValue::LinkOnceODRLinkage;
36209467b48Spatrick   else if (Linkage == GlobalValue::InternalLinkage ||
36309467b48Spatrick            Linkage == GlobalValue::ExternalLinkage)
36409467b48Spatrick     Linkage = GlobalValue::PrivateLinkage;
36509467b48Spatrick 
36609467b48Spatrick   auto *Value =
36709467b48Spatrick       ConstantDataArray::getString(M.getContext(), PGOFuncName, false);
36809467b48Spatrick   auto FuncNameVar =
36909467b48Spatrick       new GlobalVariable(M, Value->getType(), true, Linkage, Value,
37009467b48Spatrick                          getPGOFuncNameVarName(PGOFuncName, Linkage));
37109467b48Spatrick 
37209467b48Spatrick   // Hide the symbol so that we correctly get a copy for each executable.
37309467b48Spatrick   if (!GlobalValue::isLocalLinkage(FuncNameVar->getLinkage()))
37409467b48Spatrick     FuncNameVar->setVisibility(GlobalValue::HiddenVisibility);
37509467b48Spatrick 
37609467b48Spatrick   return FuncNameVar;
37709467b48Spatrick }
37809467b48Spatrick 
createPGOFuncNameVar(Function & F,StringRef PGOFuncName)37909467b48Spatrick GlobalVariable *createPGOFuncNameVar(Function &F, StringRef PGOFuncName) {
38009467b48Spatrick   return createPGOFuncNameVar(*F.getParent(), F.getLinkage(), PGOFuncName);
38109467b48Spatrick }
38209467b48Spatrick 
create(Module & M,bool InLTO)38309467b48Spatrick Error InstrProfSymtab::create(Module &M, bool InLTO) {
38409467b48Spatrick   for (Function &F : M) {
38509467b48Spatrick     // Function may not have a name: like using asm("") to overwrite the name.
38609467b48Spatrick     // Ignore in this case.
38709467b48Spatrick     if (!F.hasName())
38809467b48Spatrick       continue;
38909467b48Spatrick     const std::string &PGOFuncName = getPGOFuncName(F, InLTO);
39009467b48Spatrick     if (Error E = addFuncName(PGOFuncName))
39109467b48Spatrick       return E;
39209467b48Spatrick     MD5FuncMap.emplace_back(Function::getGUID(PGOFuncName), &F);
39309467b48Spatrick     // In ThinLTO, local function may have been promoted to global and have
39473471bf0Spatrick     // suffix ".llvm." added to the function name. We need to add the
39573471bf0Spatrick     // stripped function name to the symbol table so that we can find a match
39673471bf0Spatrick     // from profile.
39773471bf0Spatrick     //
39873471bf0Spatrick     // We may have other suffixes similar as ".llvm." which are needed to
39973471bf0Spatrick     // be stripped before the matching, but ".__uniq." suffix which is used
40073471bf0Spatrick     // to differentiate internal linkage functions in different modules
40173471bf0Spatrick     // should be kept. Now this is the only suffix with the pattern ".xxx"
40273471bf0Spatrick     // which is kept before matching.
40373471bf0Spatrick     const std::string UniqSuffix = ".__uniq.";
40473471bf0Spatrick     auto pos = PGOFuncName.find(UniqSuffix);
40573471bf0Spatrick     // Search '.' after ".__uniq." if ".__uniq." exists, otherwise
40673471bf0Spatrick     // search '.' from the beginning.
40773471bf0Spatrick     if (pos != std::string::npos)
40873471bf0Spatrick       pos += UniqSuffix.length();
40973471bf0Spatrick     else
41073471bf0Spatrick       pos = 0;
41173471bf0Spatrick     pos = PGOFuncName.find('.', pos);
41273471bf0Spatrick     if (pos != std::string::npos && pos != 0) {
41309467b48Spatrick       const std::string &OtherFuncName = PGOFuncName.substr(0, pos);
41409467b48Spatrick       if (Error E = addFuncName(OtherFuncName))
41509467b48Spatrick         return E;
41609467b48Spatrick       MD5FuncMap.emplace_back(Function::getGUID(OtherFuncName), &F);
41709467b48Spatrick     }
41809467b48Spatrick   }
41909467b48Spatrick   Sorted = false;
42009467b48Spatrick   finalizeSymtab();
42109467b48Spatrick   return Error::success();
42209467b48Spatrick }
42309467b48Spatrick 
getFunctionHashFromAddress(uint64_t Address)42409467b48Spatrick uint64_t InstrProfSymtab::getFunctionHashFromAddress(uint64_t Address) {
42509467b48Spatrick   finalizeSymtab();
42609467b48Spatrick   auto It = partition_point(AddrToMD5Map, [=](std::pair<uint64_t, uint64_t> A) {
42709467b48Spatrick     return A.first < Address;
42809467b48Spatrick   });
42909467b48Spatrick   // Raw function pointer collected by value profiler may be from
43009467b48Spatrick   // external functions that are not instrumented. They won't have
43109467b48Spatrick   // mapping data to be used by the deserializer. Force the value to
43209467b48Spatrick   // be 0 in this case.
43309467b48Spatrick   if (It != AddrToMD5Map.end() && It->first == Address)
43409467b48Spatrick     return (uint64_t)It->second;
43509467b48Spatrick   return 0;
43609467b48Spatrick }
43709467b48Spatrick 
collectPGOFuncNameStrings(ArrayRef<std::string> NameStrs,bool doCompression,std::string & Result)43809467b48Spatrick Error collectPGOFuncNameStrings(ArrayRef<std::string> NameStrs,
43909467b48Spatrick                                 bool doCompression, std::string &Result) {
44009467b48Spatrick   assert(!NameStrs.empty() && "No name data to emit");
44109467b48Spatrick 
44209467b48Spatrick   uint8_t Header[16], *P = Header;
44309467b48Spatrick   std::string UncompressedNameStrings =
44409467b48Spatrick       join(NameStrs.begin(), NameStrs.end(), getInstrProfNameSeparator());
44509467b48Spatrick 
44609467b48Spatrick   assert(StringRef(UncompressedNameStrings)
44709467b48Spatrick                  .count(getInstrProfNameSeparator()) == (NameStrs.size() - 1) &&
44809467b48Spatrick          "PGO name is invalid (contains separator token)");
44909467b48Spatrick 
45009467b48Spatrick   unsigned EncLen = encodeULEB128(UncompressedNameStrings.length(), P);
45109467b48Spatrick   P += EncLen;
45209467b48Spatrick 
45309467b48Spatrick   auto WriteStringToResult = [&](size_t CompressedLen, StringRef InputStr) {
45409467b48Spatrick     EncLen = encodeULEB128(CompressedLen, P);
45509467b48Spatrick     P += EncLen;
45609467b48Spatrick     char *HeaderStr = reinterpret_cast<char *>(&Header[0]);
45709467b48Spatrick     unsigned HeaderLen = P - &Header[0];
45809467b48Spatrick     Result.append(HeaderStr, HeaderLen);
45909467b48Spatrick     Result += InputStr;
46009467b48Spatrick     return Error::success();
46109467b48Spatrick   };
46209467b48Spatrick 
46309467b48Spatrick   if (!doCompression) {
46409467b48Spatrick     return WriteStringToResult(0, UncompressedNameStrings);
46509467b48Spatrick   }
46609467b48Spatrick 
467*d415bd75Srobert   SmallVector<uint8_t, 128> CompressedNameStrings;
468*d415bd75Srobert   compression::zlib::compress(arrayRefFromStringRef(UncompressedNameStrings),
469*d415bd75Srobert                               CompressedNameStrings,
470*d415bd75Srobert                               compression::zlib::BestSizeCompression);
47109467b48Spatrick 
47209467b48Spatrick   return WriteStringToResult(CompressedNameStrings.size(),
473*d415bd75Srobert                              toStringRef(CompressedNameStrings));
47409467b48Spatrick }
47509467b48Spatrick 
getPGOFuncNameVarInitializer(GlobalVariable * NameVar)47609467b48Spatrick StringRef getPGOFuncNameVarInitializer(GlobalVariable *NameVar) {
47709467b48Spatrick   auto *Arr = cast<ConstantDataArray>(NameVar->getInitializer());
47809467b48Spatrick   StringRef NameStr =
47909467b48Spatrick       Arr->isCString() ? Arr->getAsCString() : Arr->getAsString();
48009467b48Spatrick   return NameStr;
48109467b48Spatrick }
48209467b48Spatrick 
collectPGOFuncNameStrings(ArrayRef<GlobalVariable * > NameVars,std::string & Result,bool doCompression)48309467b48Spatrick Error collectPGOFuncNameStrings(ArrayRef<GlobalVariable *> NameVars,
48409467b48Spatrick                                 std::string &Result, bool doCompression) {
48509467b48Spatrick   std::vector<std::string> NameStrs;
48609467b48Spatrick   for (auto *NameVar : NameVars) {
487097a140dSpatrick     NameStrs.push_back(std::string(getPGOFuncNameVarInitializer(NameVar)));
48809467b48Spatrick   }
48909467b48Spatrick   return collectPGOFuncNameStrings(
490*d415bd75Srobert       NameStrs, compression::zlib::isAvailable() && doCompression, Result);
49109467b48Spatrick }
49209467b48Spatrick 
readPGOFuncNameStrings(StringRef NameStrings,InstrProfSymtab & Symtab)49309467b48Spatrick Error readPGOFuncNameStrings(StringRef NameStrings, InstrProfSymtab &Symtab) {
49409467b48Spatrick   const uint8_t *P = NameStrings.bytes_begin();
49509467b48Spatrick   const uint8_t *EndP = NameStrings.bytes_end();
49609467b48Spatrick   while (P < EndP) {
49709467b48Spatrick     uint32_t N;
49809467b48Spatrick     uint64_t UncompressedSize = decodeULEB128(P, &N);
49909467b48Spatrick     P += N;
50009467b48Spatrick     uint64_t CompressedSize = decodeULEB128(P, &N);
50109467b48Spatrick     P += N;
50209467b48Spatrick     bool isCompressed = (CompressedSize != 0);
503*d415bd75Srobert     SmallVector<uint8_t, 128> UncompressedNameStrings;
50409467b48Spatrick     StringRef NameStrings;
50509467b48Spatrick     if (isCompressed) {
506*d415bd75Srobert       if (!llvm::compression::zlib::isAvailable())
50709467b48Spatrick         return make_error<InstrProfError>(instrprof_error::zlib_unavailable);
50809467b48Spatrick 
509*d415bd75Srobert       if (Error E = compression::zlib::decompress(ArrayRef(P, CompressedSize),
510*d415bd75Srobert                                                   UncompressedNameStrings,
51109467b48Spatrick                                                   UncompressedSize)) {
51209467b48Spatrick         consumeError(std::move(E));
51309467b48Spatrick         return make_error<InstrProfError>(instrprof_error::uncompress_failed);
51409467b48Spatrick       }
51509467b48Spatrick       P += CompressedSize;
516*d415bd75Srobert       NameStrings = toStringRef(UncompressedNameStrings);
51709467b48Spatrick     } else {
51809467b48Spatrick       NameStrings =
51909467b48Spatrick           StringRef(reinterpret_cast<const char *>(P), UncompressedSize);
52009467b48Spatrick       P += UncompressedSize;
52109467b48Spatrick     }
52209467b48Spatrick     // Now parse the name strings.
52309467b48Spatrick     SmallVector<StringRef, 0> Names;
52409467b48Spatrick     NameStrings.split(Names, getInstrProfNameSeparator());
52509467b48Spatrick     for (StringRef &Name : Names)
52609467b48Spatrick       if (Error E = Symtab.addFuncName(Name))
52709467b48Spatrick         return E;
52809467b48Spatrick 
52909467b48Spatrick     while (P < EndP && *P == 0)
53009467b48Spatrick       P++;
53109467b48Spatrick   }
53209467b48Spatrick   return Error::success();
53309467b48Spatrick }
53409467b48Spatrick 
accumulateCounts(CountSumOrPercent & Sum) const53509467b48Spatrick void InstrProfRecord::accumulateCounts(CountSumOrPercent &Sum) const {
53609467b48Spatrick   uint64_t FuncSum = 0;
53709467b48Spatrick   Sum.NumEntries += Counts.size();
538*d415bd75Srobert   for (uint64_t Count : Counts)
539*d415bd75Srobert     FuncSum += Count;
54009467b48Spatrick   Sum.CountSum += FuncSum;
54109467b48Spatrick 
54209467b48Spatrick   for (uint32_t VK = IPVK_First; VK <= IPVK_Last; ++VK) {
54309467b48Spatrick     uint64_t KindSum = 0;
54409467b48Spatrick     uint32_t NumValueSites = getNumValueSites(VK);
54509467b48Spatrick     for (size_t I = 0; I < NumValueSites; ++I) {
54609467b48Spatrick       uint32_t NV = getNumValueDataForSite(VK, I);
54709467b48Spatrick       std::unique_ptr<InstrProfValueData[]> VD = getValueForSite(VK, I);
54809467b48Spatrick       for (uint32_t V = 0; V < NV; V++)
54909467b48Spatrick         KindSum += VD[V].Count;
55009467b48Spatrick     }
55109467b48Spatrick     Sum.ValueCounts[VK] += KindSum;
55209467b48Spatrick   }
55309467b48Spatrick }
55409467b48Spatrick 
overlap(InstrProfValueSiteRecord & Input,uint32_t ValueKind,OverlapStats & Overlap,OverlapStats & FuncLevelOverlap)55509467b48Spatrick void InstrProfValueSiteRecord::overlap(InstrProfValueSiteRecord &Input,
55609467b48Spatrick                                        uint32_t ValueKind,
55709467b48Spatrick                                        OverlapStats &Overlap,
55809467b48Spatrick                                        OverlapStats &FuncLevelOverlap) {
55909467b48Spatrick   this->sortByTargetValues();
56009467b48Spatrick   Input.sortByTargetValues();
56109467b48Spatrick   double Score = 0.0f, FuncLevelScore = 0.0f;
56209467b48Spatrick   auto I = ValueData.begin();
56309467b48Spatrick   auto IE = ValueData.end();
56409467b48Spatrick   auto J = Input.ValueData.begin();
56509467b48Spatrick   auto JE = Input.ValueData.end();
56609467b48Spatrick   while (I != IE && J != JE) {
56709467b48Spatrick     if (I->Value == J->Value) {
56809467b48Spatrick       Score += OverlapStats::score(I->Count, J->Count,
56909467b48Spatrick                                    Overlap.Base.ValueCounts[ValueKind],
57009467b48Spatrick                                    Overlap.Test.ValueCounts[ValueKind]);
57109467b48Spatrick       FuncLevelScore += OverlapStats::score(
57209467b48Spatrick           I->Count, J->Count, FuncLevelOverlap.Base.ValueCounts[ValueKind],
57309467b48Spatrick           FuncLevelOverlap.Test.ValueCounts[ValueKind]);
57409467b48Spatrick       ++I;
57509467b48Spatrick     } else if (I->Value < J->Value) {
57609467b48Spatrick       ++I;
57709467b48Spatrick       continue;
57809467b48Spatrick     }
57909467b48Spatrick     ++J;
58009467b48Spatrick   }
58109467b48Spatrick   Overlap.Overlap.ValueCounts[ValueKind] += Score;
58209467b48Spatrick   FuncLevelOverlap.Overlap.ValueCounts[ValueKind] += FuncLevelScore;
58309467b48Spatrick }
58409467b48Spatrick 
58509467b48Spatrick // Return false on mismatch.
overlapValueProfData(uint32_t ValueKind,InstrProfRecord & Other,OverlapStats & Overlap,OverlapStats & FuncLevelOverlap)58609467b48Spatrick void InstrProfRecord::overlapValueProfData(uint32_t ValueKind,
58709467b48Spatrick                                            InstrProfRecord &Other,
58809467b48Spatrick                                            OverlapStats &Overlap,
58909467b48Spatrick                                            OverlapStats &FuncLevelOverlap) {
59009467b48Spatrick   uint32_t ThisNumValueSites = getNumValueSites(ValueKind);
59109467b48Spatrick   assert(ThisNumValueSites == Other.getNumValueSites(ValueKind));
59209467b48Spatrick   if (!ThisNumValueSites)
59309467b48Spatrick     return;
59409467b48Spatrick 
59509467b48Spatrick   std::vector<InstrProfValueSiteRecord> &ThisSiteRecords =
59609467b48Spatrick       getOrCreateValueSitesForKind(ValueKind);
59709467b48Spatrick   MutableArrayRef<InstrProfValueSiteRecord> OtherSiteRecords =
59809467b48Spatrick       Other.getValueSitesForKind(ValueKind);
59909467b48Spatrick   for (uint32_t I = 0; I < ThisNumValueSites; I++)
60009467b48Spatrick     ThisSiteRecords[I].overlap(OtherSiteRecords[I], ValueKind, Overlap,
60109467b48Spatrick                                FuncLevelOverlap);
60209467b48Spatrick }
60309467b48Spatrick 
overlap(InstrProfRecord & Other,OverlapStats & Overlap,OverlapStats & FuncLevelOverlap,uint64_t ValueCutoff)60409467b48Spatrick void InstrProfRecord::overlap(InstrProfRecord &Other, OverlapStats &Overlap,
60509467b48Spatrick                               OverlapStats &FuncLevelOverlap,
60609467b48Spatrick                               uint64_t ValueCutoff) {
60709467b48Spatrick   // FuncLevel CountSum for other should already computed and nonzero.
60809467b48Spatrick   assert(FuncLevelOverlap.Test.CountSum >= 1.0f);
60909467b48Spatrick   accumulateCounts(FuncLevelOverlap.Base);
61009467b48Spatrick   bool Mismatch = (Counts.size() != Other.Counts.size());
61109467b48Spatrick 
61209467b48Spatrick   // Check if the value profiles mismatch.
61309467b48Spatrick   if (!Mismatch) {
61409467b48Spatrick     for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind) {
61509467b48Spatrick       uint32_t ThisNumValueSites = getNumValueSites(Kind);
61609467b48Spatrick       uint32_t OtherNumValueSites = Other.getNumValueSites(Kind);
61709467b48Spatrick       if (ThisNumValueSites != OtherNumValueSites) {
61809467b48Spatrick         Mismatch = true;
61909467b48Spatrick         break;
62009467b48Spatrick       }
62109467b48Spatrick     }
62209467b48Spatrick   }
62309467b48Spatrick   if (Mismatch) {
62409467b48Spatrick     Overlap.addOneMismatch(FuncLevelOverlap.Test);
62509467b48Spatrick     return;
62609467b48Spatrick   }
62709467b48Spatrick 
62809467b48Spatrick   // Compute overlap for value counts.
62909467b48Spatrick   for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
63009467b48Spatrick     overlapValueProfData(Kind, Other, Overlap, FuncLevelOverlap);
63109467b48Spatrick 
63209467b48Spatrick   double Score = 0.0;
63309467b48Spatrick   uint64_t MaxCount = 0;
63409467b48Spatrick   // Compute overlap for edge counts.
63509467b48Spatrick   for (size_t I = 0, E = Other.Counts.size(); I < E; ++I) {
63609467b48Spatrick     Score += OverlapStats::score(Counts[I], Other.Counts[I],
63709467b48Spatrick                                  Overlap.Base.CountSum, Overlap.Test.CountSum);
63809467b48Spatrick     MaxCount = std::max(Other.Counts[I], MaxCount);
63909467b48Spatrick   }
64009467b48Spatrick   Overlap.Overlap.CountSum += Score;
64109467b48Spatrick   Overlap.Overlap.NumEntries += 1;
64209467b48Spatrick 
64309467b48Spatrick   if (MaxCount >= ValueCutoff) {
64409467b48Spatrick     double FuncScore = 0.0;
64509467b48Spatrick     for (size_t I = 0, E = Other.Counts.size(); I < E; ++I)
64609467b48Spatrick       FuncScore += OverlapStats::score(Counts[I], Other.Counts[I],
64709467b48Spatrick                                        FuncLevelOverlap.Base.CountSum,
64809467b48Spatrick                                        FuncLevelOverlap.Test.CountSum);
64909467b48Spatrick     FuncLevelOverlap.Overlap.CountSum = FuncScore;
65009467b48Spatrick     FuncLevelOverlap.Overlap.NumEntries = Other.Counts.size();
65109467b48Spatrick     FuncLevelOverlap.Valid = true;
65209467b48Spatrick   }
65309467b48Spatrick }
65409467b48Spatrick 
merge(InstrProfValueSiteRecord & Input,uint64_t Weight,function_ref<void (instrprof_error)> Warn)65509467b48Spatrick void InstrProfValueSiteRecord::merge(InstrProfValueSiteRecord &Input,
65609467b48Spatrick                                      uint64_t Weight,
65709467b48Spatrick                                      function_ref<void(instrprof_error)> Warn) {
65809467b48Spatrick   this->sortByTargetValues();
65909467b48Spatrick   Input.sortByTargetValues();
66009467b48Spatrick   auto I = ValueData.begin();
66109467b48Spatrick   auto IE = ValueData.end();
662*d415bd75Srobert   for (const InstrProfValueData &J : Input.ValueData) {
663*d415bd75Srobert     while (I != IE && I->Value < J.Value)
66409467b48Spatrick       ++I;
665*d415bd75Srobert     if (I != IE && I->Value == J.Value) {
66609467b48Spatrick       bool Overflowed;
667*d415bd75Srobert       I->Count = SaturatingMultiplyAdd(J.Count, Weight, I->Count, &Overflowed);
66809467b48Spatrick       if (Overflowed)
66909467b48Spatrick         Warn(instrprof_error::counter_overflow);
67009467b48Spatrick       ++I;
67109467b48Spatrick       continue;
67209467b48Spatrick     }
673*d415bd75Srobert     ValueData.insert(I, J);
67409467b48Spatrick   }
67509467b48Spatrick }
67609467b48Spatrick 
scale(uint64_t N,uint64_t D,function_ref<void (instrprof_error)> Warn)67773471bf0Spatrick void InstrProfValueSiteRecord::scale(uint64_t N, uint64_t D,
67809467b48Spatrick                                      function_ref<void(instrprof_error)> Warn) {
679*d415bd75Srobert   for (InstrProfValueData &I : ValueData) {
68009467b48Spatrick     bool Overflowed;
681*d415bd75Srobert     I.Count = SaturatingMultiply(I.Count, N, &Overflowed) / D;
68209467b48Spatrick     if (Overflowed)
68309467b48Spatrick       Warn(instrprof_error::counter_overflow);
68409467b48Spatrick   }
68509467b48Spatrick }
68609467b48Spatrick 
68709467b48Spatrick // Merge Value Profile data from Src record to this record for ValueKind.
68809467b48Spatrick // Scale merged value counts by \p Weight.
mergeValueProfData(uint32_t ValueKind,InstrProfRecord & Src,uint64_t Weight,function_ref<void (instrprof_error)> Warn)68909467b48Spatrick void InstrProfRecord::mergeValueProfData(
69009467b48Spatrick     uint32_t ValueKind, InstrProfRecord &Src, uint64_t Weight,
69109467b48Spatrick     function_ref<void(instrprof_error)> Warn) {
69209467b48Spatrick   uint32_t ThisNumValueSites = getNumValueSites(ValueKind);
69309467b48Spatrick   uint32_t OtherNumValueSites = Src.getNumValueSites(ValueKind);
69409467b48Spatrick   if (ThisNumValueSites != OtherNumValueSites) {
69509467b48Spatrick     Warn(instrprof_error::value_site_count_mismatch);
69609467b48Spatrick     return;
69709467b48Spatrick   }
69809467b48Spatrick   if (!ThisNumValueSites)
69909467b48Spatrick     return;
70009467b48Spatrick   std::vector<InstrProfValueSiteRecord> &ThisSiteRecords =
70109467b48Spatrick       getOrCreateValueSitesForKind(ValueKind);
70209467b48Spatrick   MutableArrayRef<InstrProfValueSiteRecord> OtherSiteRecords =
70309467b48Spatrick       Src.getValueSitesForKind(ValueKind);
70409467b48Spatrick   for (uint32_t I = 0; I < ThisNumValueSites; I++)
70509467b48Spatrick     ThisSiteRecords[I].merge(OtherSiteRecords[I], Weight, Warn);
70609467b48Spatrick }
70709467b48Spatrick 
merge(InstrProfRecord & Other,uint64_t Weight,function_ref<void (instrprof_error)> Warn)70809467b48Spatrick void InstrProfRecord::merge(InstrProfRecord &Other, uint64_t Weight,
70909467b48Spatrick                             function_ref<void(instrprof_error)> Warn) {
71009467b48Spatrick   // If the number of counters doesn't match we either have bad data
71109467b48Spatrick   // or a hash collision.
71209467b48Spatrick   if (Counts.size() != Other.Counts.size()) {
71309467b48Spatrick     Warn(instrprof_error::count_mismatch);
71409467b48Spatrick     return;
71509467b48Spatrick   }
71609467b48Spatrick 
717*d415bd75Srobert   // Special handling of the first count as the PseudoCount.
718*d415bd75Srobert   CountPseudoKind OtherKind = Other.getCountPseudoKind();
719*d415bd75Srobert   CountPseudoKind ThisKind = getCountPseudoKind();
720*d415bd75Srobert   if (OtherKind != NotPseudo || ThisKind != NotPseudo) {
721*d415bd75Srobert     // We don't allow the merge of a profile with pseudo counts and
722*d415bd75Srobert     // a normal profile (i.e. without pesudo counts).
723*d415bd75Srobert     // Profile supplimenation should be done after the profile merge.
724*d415bd75Srobert     if (OtherKind == NotPseudo || ThisKind == NotPseudo) {
725*d415bd75Srobert       Warn(instrprof_error::count_mismatch);
726*d415bd75Srobert       return;
727*d415bd75Srobert     }
728*d415bd75Srobert     if (OtherKind == PseudoHot || ThisKind == PseudoHot)
729*d415bd75Srobert       setPseudoCount(PseudoHot);
730*d415bd75Srobert     else
731*d415bd75Srobert       setPseudoCount(PseudoWarm);
732*d415bd75Srobert     return;
733*d415bd75Srobert   }
734*d415bd75Srobert 
73509467b48Spatrick   for (size_t I = 0, E = Other.Counts.size(); I < E; ++I) {
73609467b48Spatrick     bool Overflowed;
737*d415bd75Srobert     uint64_t Value =
73809467b48Spatrick         SaturatingMultiplyAdd(Other.Counts[I], Weight, Counts[I], &Overflowed);
739*d415bd75Srobert     if (Value > getInstrMaxCountValue()) {
740*d415bd75Srobert       Value = getInstrMaxCountValue();
741*d415bd75Srobert       Overflowed = true;
742*d415bd75Srobert     }
743*d415bd75Srobert     Counts[I] = Value;
74409467b48Spatrick     if (Overflowed)
74509467b48Spatrick       Warn(instrprof_error::counter_overflow);
74609467b48Spatrick   }
74709467b48Spatrick 
74809467b48Spatrick   for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
74909467b48Spatrick     mergeValueProfData(Kind, Other, Weight, Warn);
75009467b48Spatrick }
75109467b48Spatrick 
scaleValueProfData(uint32_t ValueKind,uint64_t N,uint64_t D,function_ref<void (instrprof_error)> Warn)75209467b48Spatrick void InstrProfRecord::scaleValueProfData(
75373471bf0Spatrick     uint32_t ValueKind, uint64_t N, uint64_t D,
75409467b48Spatrick     function_ref<void(instrprof_error)> Warn) {
75509467b48Spatrick   for (auto &R : getValueSitesForKind(ValueKind))
75673471bf0Spatrick     R.scale(N, D, Warn);
75709467b48Spatrick }
75809467b48Spatrick 
scale(uint64_t N,uint64_t D,function_ref<void (instrprof_error)> Warn)75973471bf0Spatrick void InstrProfRecord::scale(uint64_t N, uint64_t D,
76009467b48Spatrick                             function_ref<void(instrprof_error)> Warn) {
76173471bf0Spatrick   assert(D != 0 && "D cannot be 0");
76209467b48Spatrick   for (auto &Count : this->Counts) {
76309467b48Spatrick     bool Overflowed;
76473471bf0Spatrick     Count = SaturatingMultiply(Count, N, &Overflowed) / D;
765*d415bd75Srobert     if (Count > getInstrMaxCountValue()) {
766*d415bd75Srobert       Count = getInstrMaxCountValue();
767*d415bd75Srobert       Overflowed = true;
768*d415bd75Srobert     }
76909467b48Spatrick     if (Overflowed)
77009467b48Spatrick       Warn(instrprof_error::counter_overflow);
77109467b48Spatrick   }
77209467b48Spatrick   for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
77373471bf0Spatrick     scaleValueProfData(Kind, N, D, Warn);
77409467b48Spatrick }
77509467b48Spatrick 
77609467b48Spatrick // Map indirect call target name hash to name string.
remapValue(uint64_t Value,uint32_t ValueKind,InstrProfSymtab * SymTab)77709467b48Spatrick uint64_t InstrProfRecord::remapValue(uint64_t Value, uint32_t ValueKind,
77809467b48Spatrick                                      InstrProfSymtab *SymTab) {
77909467b48Spatrick   if (!SymTab)
78009467b48Spatrick     return Value;
78109467b48Spatrick 
78209467b48Spatrick   if (ValueKind == IPVK_IndirectCallTarget)
78309467b48Spatrick     return SymTab->getFunctionHashFromAddress(Value);
78409467b48Spatrick 
78509467b48Spatrick   return Value;
78609467b48Spatrick }
78709467b48Spatrick 
addValueData(uint32_t ValueKind,uint32_t Site,InstrProfValueData * VData,uint32_t N,InstrProfSymtab * ValueMap)78809467b48Spatrick void InstrProfRecord::addValueData(uint32_t ValueKind, uint32_t Site,
78909467b48Spatrick                                    InstrProfValueData *VData, uint32_t N,
79009467b48Spatrick                                    InstrProfSymtab *ValueMap) {
79109467b48Spatrick   for (uint32_t I = 0; I < N; I++) {
79209467b48Spatrick     VData[I].Value = remapValue(VData[I].Value, ValueKind, ValueMap);
79309467b48Spatrick   }
79409467b48Spatrick   std::vector<InstrProfValueSiteRecord> &ValueSites =
79509467b48Spatrick       getOrCreateValueSitesForKind(ValueKind);
79609467b48Spatrick   if (N == 0)
79709467b48Spatrick     ValueSites.emplace_back();
79809467b48Spatrick   else
79909467b48Spatrick     ValueSites.emplace_back(VData, VData + N);
80009467b48Spatrick }
80109467b48Spatrick 
80209467b48Spatrick #define INSTR_PROF_COMMON_API_IMPL
80309467b48Spatrick #include "llvm/ProfileData/InstrProfData.inc"
80409467b48Spatrick 
80509467b48Spatrick /*!
80609467b48Spatrick  * ValueProfRecordClosure Interface implementation for  InstrProfRecord
80709467b48Spatrick  *  class. These C wrappers are used as adaptors so that C++ code can be
80809467b48Spatrick  *  invoked as callbacks.
80909467b48Spatrick  */
getNumValueKindsInstrProf(const void * Record)81009467b48Spatrick uint32_t getNumValueKindsInstrProf(const void *Record) {
81109467b48Spatrick   return reinterpret_cast<const InstrProfRecord *>(Record)->getNumValueKinds();
81209467b48Spatrick }
81309467b48Spatrick 
getNumValueSitesInstrProf(const void * Record,uint32_t VKind)81409467b48Spatrick uint32_t getNumValueSitesInstrProf(const void *Record, uint32_t VKind) {
81509467b48Spatrick   return reinterpret_cast<const InstrProfRecord *>(Record)
81609467b48Spatrick       ->getNumValueSites(VKind);
81709467b48Spatrick }
81809467b48Spatrick 
getNumValueDataInstrProf(const void * Record,uint32_t VKind)81909467b48Spatrick uint32_t getNumValueDataInstrProf(const void *Record, uint32_t VKind) {
82009467b48Spatrick   return reinterpret_cast<const InstrProfRecord *>(Record)
82109467b48Spatrick       ->getNumValueData(VKind);
82209467b48Spatrick }
82309467b48Spatrick 
getNumValueDataForSiteInstrProf(const void * R,uint32_t VK,uint32_t S)82409467b48Spatrick uint32_t getNumValueDataForSiteInstrProf(const void *R, uint32_t VK,
82509467b48Spatrick                                          uint32_t S) {
82609467b48Spatrick   return reinterpret_cast<const InstrProfRecord *>(R)
82709467b48Spatrick       ->getNumValueDataForSite(VK, S);
82809467b48Spatrick }
82909467b48Spatrick 
getValueForSiteInstrProf(const void * R,InstrProfValueData * Dst,uint32_t K,uint32_t S)83009467b48Spatrick void getValueForSiteInstrProf(const void *R, InstrProfValueData *Dst,
83109467b48Spatrick                               uint32_t K, uint32_t S) {
83209467b48Spatrick   reinterpret_cast<const InstrProfRecord *>(R)->getValueForSite(Dst, K, S);
83309467b48Spatrick }
83409467b48Spatrick 
allocValueProfDataInstrProf(size_t TotalSizeInBytes)83509467b48Spatrick ValueProfData *allocValueProfDataInstrProf(size_t TotalSizeInBytes) {
83609467b48Spatrick   ValueProfData *VD =
83709467b48Spatrick       (ValueProfData *)(new (::operator new(TotalSizeInBytes)) ValueProfData());
83809467b48Spatrick   memset(VD, 0, TotalSizeInBytes);
83909467b48Spatrick   return VD;
84009467b48Spatrick }
84109467b48Spatrick 
84209467b48Spatrick static ValueProfRecordClosure InstrProfRecordClosure = {
84309467b48Spatrick     nullptr,
84409467b48Spatrick     getNumValueKindsInstrProf,
84509467b48Spatrick     getNumValueSitesInstrProf,
84609467b48Spatrick     getNumValueDataInstrProf,
84709467b48Spatrick     getNumValueDataForSiteInstrProf,
84809467b48Spatrick     nullptr,
84909467b48Spatrick     getValueForSiteInstrProf,
85009467b48Spatrick     allocValueProfDataInstrProf};
85109467b48Spatrick 
85209467b48Spatrick // Wrapper implementation using the closure mechanism.
getSize(const InstrProfRecord & Record)85309467b48Spatrick uint32_t ValueProfData::getSize(const InstrProfRecord &Record) {
85409467b48Spatrick   auto Closure = InstrProfRecordClosure;
85509467b48Spatrick   Closure.Record = &Record;
85609467b48Spatrick   return getValueProfDataSize(&Closure);
85709467b48Spatrick }
85809467b48Spatrick 
85909467b48Spatrick // Wrapper implementation using the closure mechanism.
86009467b48Spatrick std::unique_ptr<ValueProfData>
serializeFrom(const InstrProfRecord & Record)86109467b48Spatrick ValueProfData::serializeFrom(const InstrProfRecord &Record) {
86209467b48Spatrick   InstrProfRecordClosure.Record = &Record;
86309467b48Spatrick 
86409467b48Spatrick   std::unique_ptr<ValueProfData> VPD(
86509467b48Spatrick       serializeValueProfDataFrom(&InstrProfRecordClosure, nullptr));
86609467b48Spatrick   return VPD;
86709467b48Spatrick }
86809467b48Spatrick 
deserializeTo(InstrProfRecord & Record,InstrProfSymtab * SymTab)86909467b48Spatrick void ValueProfRecord::deserializeTo(InstrProfRecord &Record,
87009467b48Spatrick                                     InstrProfSymtab *SymTab) {
87109467b48Spatrick   Record.reserveSites(Kind, NumValueSites);
87209467b48Spatrick 
87309467b48Spatrick   InstrProfValueData *ValueData = getValueProfRecordValueData(this);
87409467b48Spatrick   for (uint64_t VSite = 0; VSite < NumValueSites; ++VSite) {
87509467b48Spatrick     uint8_t ValueDataCount = this->SiteCountArray[VSite];
87609467b48Spatrick     Record.addValueData(Kind, VSite, ValueData, ValueDataCount, SymTab);
87709467b48Spatrick     ValueData += ValueDataCount;
87809467b48Spatrick   }
87909467b48Spatrick }
88009467b48Spatrick 
88109467b48Spatrick // For writing/serializing,  Old is the host endianness, and  New is
88209467b48Spatrick // byte order intended on disk. For Reading/deserialization, Old
88309467b48Spatrick // is the on-disk source endianness, and New is the host endianness.
swapBytes(support::endianness Old,support::endianness New)88409467b48Spatrick void ValueProfRecord::swapBytes(support::endianness Old,
88509467b48Spatrick                                 support::endianness New) {
88609467b48Spatrick   using namespace support;
88709467b48Spatrick 
88809467b48Spatrick   if (Old == New)
88909467b48Spatrick     return;
89009467b48Spatrick 
89109467b48Spatrick   if (getHostEndianness() != Old) {
89209467b48Spatrick     sys::swapByteOrder<uint32_t>(NumValueSites);
89309467b48Spatrick     sys::swapByteOrder<uint32_t>(Kind);
89409467b48Spatrick   }
89509467b48Spatrick   uint32_t ND = getValueProfRecordNumValueData(this);
89609467b48Spatrick   InstrProfValueData *VD = getValueProfRecordValueData(this);
89709467b48Spatrick 
89809467b48Spatrick   // No need to swap byte array: SiteCountArrray.
89909467b48Spatrick   for (uint32_t I = 0; I < ND; I++) {
90009467b48Spatrick     sys::swapByteOrder<uint64_t>(VD[I].Value);
90109467b48Spatrick     sys::swapByteOrder<uint64_t>(VD[I].Count);
90209467b48Spatrick   }
90309467b48Spatrick   if (getHostEndianness() == Old) {
90409467b48Spatrick     sys::swapByteOrder<uint32_t>(NumValueSites);
90509467b48Spatrick     sys::swapByteOrder<uint32_t>(Kind);
90609467b48Spatrick   }
90709467b48Spatrick }
90809467b48Spatrick 
deserializeTo(InstrProfRecord & Record,InstrProfSymtab * SymTab)90909467b48Spatrick void ValueProfData::deserializeTo(InstrProfRecord &Record,
91009467b48Spatrick                                   InstrProfSymtab *SymTab) {
91109467b48Spatrick   if (NumValueKinds == 0)
91209467b48Spatrick     return;
91309467b48Spatrick 
91409467b48Spatrick   ValueProfRecord *VR = getFirstValueProfRecord(this);
91509467b48Spatrick   for (uint32_t K = 0; K < NumValueKinds; K++) {
91609467b48Spatrick     VR->deserializeTo(Record, SymTab);
91709467b48Spatrick     VR = getValueProfRecordNext(VR);
91809467b48Spatrick   }
91909467b48Spatrick }
92009467b48Spatrick 
92109467b48Spatrick template <class T>
swapToHostOrder(const unsigned char * & D,support::endianness Orig)92209467b48Spatrick static T swapToHostOrder(const unsigned char *&D, support::endianness Orig) {
92309467b48Spatrick   using namespace support;
92409467b48Spatrick 
92509467b48Spatrick   if (Orig == little)
92609467b48Spatrick     return endian::readNext<T, little, unaligned>(D);
92709467b48Spatrick   else
92809467b48Spatrick     return endian::readNext<T, big, unaligned>(D);
92909467b48Spatrick }
93009467b48Spatrick 
allocValueProfData(uint32_t TotalSize)93109467b48Spatrick static std::unique_ptr<ValueProfData> allocValueProfData(uint32_t TotalSize) {
93209467b48Spatrick   return std::unique_ptr<ValueProfData>(new (::operator new(TotalSize))
93309467b48Spatrick                                             ValueProfData());
93409467b48Spatrick }
93509467b48Spatrick 
checkIntegrity()93609467b48Spatrick Error ValueProfData::checkIntegrity() {
93709467b48Spatrick   if (NumValueKinds > IPVK_Last + 1)
938*d415bd75Srobert     return make_error<InstrProfError>(
939*d415bd75Srobert         instrprof_error::malformed, "number of value profile kinds is invalid");
940*d415bd75Srobert   // Total size needs to be multiple of quadword size.
94109467b48Spatrick   if (TotalSize % sizeof(uint64_t))
942*d415bd75Srobert     return make_error<InstrProfError>(
943*d415bd75Srobert         instrprof_error::malformed, "total size is not multiples of quardword");
94409467b48Spatrick 
94509467b48Spatrick   ValueProfRecord *VR = getFirstValueProfRecord(this);
94609467b48Spatrick   for (uint32_t K = 0; K < this->NumValueKinds; K++) {
94709467b48Spatrick     if (VR->Kind > IPVK_Last)
948*d415bd75Srobert       return make_error<InstrProfError>(instrprof_error::malformed,
949*d415bd75Srobert                                         "value kind is invalid");
95009467b48Spatrick     VR = getValueProfRecordNext(VR);
95109467b48Spatrick     if ((char *)VR - (char *)this > (ptrdiff_t)TotalSize)
952*d415bd75Srobert       return make_error<InstrProfError>(
953*d415bd75Srobert           instrprof_error::malformed,
954*d415bd75Srobert           "value profile address is greater than total size");
95509467b48Spatrick   }
95609467b48Spatrick   return Error::success();
95709467b48Spatrick }
95809467b48Spatrick 
95909467b48Spatrick Expected<std::unique_ptr<ValueProfData>>
getValueProfData(const unsigned char * D,const unsigned char * const BufferEnd,support::endianness Endianness)96009467b48Spatrick ValueProfData::getValueProfData(const unsigned char *D,
96109467b48Spatrick                                 const unsigned char *const BufferEnd,
96209467b48Spatrick                                 support::endianness Endianness) {
96309467b48Spatrick   using namespace support;
96409467b48Spatrick 
96509467b48Spatrick   if (D + sizeof(ValueProfData) > BufferEnd)
96609467b48Spatrick     return make_error<InstrProfError>(instrprof_error::truncated);
96709467b48Spatrick 
96809467b48Spatrick   const unsigned char *Header = D;
96909467b48Spatrick   uint32_t TotalSize = swapToHostOrder<uint32_t>(Header, Endianness);
97009467b48Spatrick   if (D + TotalSize > BufferEnd)
97109467b48Spatrick     return make_error<InstrProfError>(instrprof_error::too_large);
97209467b48Spatrick 
97309467b48Spatrick   std::unique_ptr<ValueProfData> VPD = allocValueProfData(TotalSize);
97409467b48Spatrick   memcpy(VPD.get(), D, TotalSize);
97509467b48Spatrick   // Byte swap.
97609467b48Spatrick   VPD->swapBytesToHost(Endianness);
97709467b48Spatrick 
97809467b48Spatrick   Error E = VPD->checkIntegrity();
97909467b48Spatrick   if (E)
98009467b48Spatrick     return std::move(E);
98109467b48Spatrick 
98209467b48Spatrick   return std::move(VPD);
98309467b48Spatrick }
98409467b48Spatrick 
swapBytesToHost(support::endianness Endianness)98509467b48Spatrick void ValueProfData::swapBytesToHost(support::endianness Endianness) {
98609467b48Spatrick   using namespace support;
98709467b48Spatrick 
98809467b48Spatrick   if (Endianness == getHostEndianness())
98909467b48Spatrick     return;
99009467b48Spatrick 
99109467b48Spatrick   sys::swapByteOrder<uint32_t>(TotalSize);
99209467b48Spatrick   sys::swapByteOrder<uint32_t>(NumValueKinds);
99309467b48Spatrick 
99409467b48Spatrick   ValueProfRecord *VR = getFirstValueProfRecord(this);
99509467b48Spatrick   for (uint32_t K = 0; K < NumValueKinds; K++) {
99609467b48Spatrick     VR->swapBytes(Endianness, getHostEndianness());
99709467b48Spatrick     VR = getValueProfRecordNext(VR);
99809467b48Spatrick   }
99909467b48Spatrick }
100009467b48Spatrick 
swapBytesFromHost(support::endianness Endianness)100109467b48Spatrick void ValueProfData::swapBytesFromHost(support::endianness Endianness) {
100209467b48Spatrick   using namespace support;
100309467b48Spatrick 
100409467b48Spatrick   if (Endianness == getHostEndianness())
100509467b48Spatrick     return;
100609467b48Spatrick 
100709467b48Spatrick   ValueProfRecord *VR = getFirstValueProfRecord(this);
100809467b48Spatrick   for (uint32_t K = 0; K < NumValueKinds; K++) {
100909467b48Spatrick     ValueProfRecord *NVR = getValueProfRecordNext(VR);
101009467b48Spatrick     VR->swapBytes(getHostEndianness(), Endianness);
101109467b48Spatrick     VR = NVR;
101209467b48Spatrick   }
101309467b48Spatrick   sys::swapByteOrder<uint32_t>(TotalSize);
101409467b48Spatrick   sys::swapByteOrder<uint32_t>(NumValueKinds);
101509467b48Spatrick }
101609467b48Spatrick 
annotateValueSite(Module & M,Instruction & Inst,const InstrProfRecord & InstrProfR,InstrProfValueKind ValueKind,uint32_t SiteIdx,uint32_t MaxMDCount)101709467b48Spatrick void annotateValueSite(Module &M, Instruction &Inst,
101809467b48Spatrick                        const InstrProfRecord &InstrProfR,
101909467b48Spatrick                        InstrProfValueKind ValueKind, uint32_t SiteIdx,
102009467b48Spatrick                        uint32_t MaxMDCount) {
102109467b48Spatrick   uint32_t NV = InstrProfR.getNumValueDataForSite(ValueKind, SiteIdx);
102209467b48Spatrick   if (!NV)
102309467b48Spatrick     return;
102409467b48Spatrick 
102509467b48Spatrick   uint64_t Sum = 0;
102609467b48Spatrick   std::unique_ptr<InstrProfValueData[]> VD =
102709467b48Spatrick       InstrProfR.getValueForSite(ValueKind, SiteIdx, &Sum);
102809467b48Spatrick 
102909467b48Spatrick   ArrayRef<InstrProfValueData> VDs(VD.get(), NV);
103009467b48Spatrick   annotateValueSite(M, Inst, VDs, Sum, ValueKind, MaxMDCount);
103109467b48Spatrick }
103209467b48Spatrick 
annotateValueSite(Module & M,Instruction & Inst,ArrayRef<InstrProfValueData> VDs,uint64_t Sum,InstrProfValueKind ValueKind,uint32_t MaxMDCount)103309467b48Spatrick void annotateValueSite(Module &M, Instruction &Inst,
103409467b48Spatrick                        ArrayRef<InstrProfValueData> VDs,
103509467b48Spatrick                        uint64_t Sum, InstrProfValueKind ValueKind,
103609467b48Spatrick                        uint32_t MaxMDCount) {
103709467b48Spatrick   LLVMContext &Ctx = M.getContext();
103809467b48Spatrick   MDBuilder MDHelper(Ctx);
103909467b48Spatrick   SmallVector<Metadata *, 3> Vals;
104009467b48Spatrick   // Tag
104109467b48Spatrick   Vals.push_back(MDHelper.createString("VP"));
104209467b48Spatrick   // Value Kind
104309467b48Spatrick   Vals.push_back(MDHelper.createConstant(
104409467b48Spatrick       ConstantInt::get(Type::getInt32Ty(Ctx), ValueKind)));
104509467b48Spatrick   // Total Count
104609467b48Spatrick   Vals.push_back(
104709467b48Spatrick       MDHelper.createConstant(ConstantInt::get(Type::getInt64Ty(Ctx), Sum)));
104809467b48Spatrick 
104909467b48Spatrick   // Value Profile Data
105009467b48Spatrick   uint32_t MDCount = MaxMDCount;
105109467b48Spatrick   for (auto &VD : VDs) {
105209467b48Spatrick     Vals.push_back(MDHelper.createConstant(
105309467b48Spatrick         ConstantInt::get(Type::getInt64Ty(Ctx), VD.Value)));
105409467b48Spatrick     Vals.push_back(MDHelper.createConstant(
105509467b48Spatrick         ConstantInt::get(Type::getInt64Ty(Ctx), VD.Count)));
105609467b48Spatrick     if (--MDCount == 0)
105709467b48Spatrick       break;
105809467b48Spatrick   }
105909467b48Spatrick   Inst.setMetadata(LLVMContext::MD_prof, MDNode::get(Ctx, Vals));
106009467b48Spatrick }
106109467b48Spatrick 
getValueProfDataFromInst(const Instruction & Inst,InstrProfValueKind ValueKind,uint32_t MaxNumValueData,InstrProfValueData ValueData[],uint32_t & ActualNumValueData,uint64_t & TotalC,bool GetNoICPValue)106209467b48Spatrick bool getValueProfDataFromInst(const Instruction &Inst,
106309467b48Spatrick                               InstrProfValueKind ValueKind,
106409467b48Spatrick                               uint32_t MaxNumValueData,
106509467b48Spatrick                               InstrProfValueData ValueData[],
106673471bf0Spatrick                               uint32_t &ActualNumValueData, uint64_t &TotalC,
106773471bf0Spatrick                               bool GetNoICPValue) {
106809467b48Spatrick   MDNode *MD = Inst.getMetadata(LLVMContext::MD_prof);
106909467b48Spatrick   if (!MD)
107009467b48Spatrick     return false;
107109467b48Spatrick 
107209467b48Spatrick   unsigned NOps = MD->getNumOperands();
107309467b48Spatrick 
107409467b48Spatrick   if (NOps < 5)
107509467b48Spatrick     return false;
107609467b48Spatrick 
107709467b48Spatrick   // Operand 0 is a string tag "VP":
107809467b48Spatrick   MDString *Tag = cast<MDString>(MD->getOperand(0));
107909467b48Spatrick   if (!Tag)
108009467b48Spatrick     return false;
108109467b48Spatrick 
108209467b48Spatrick   if (!Tag->getString().equals("VP"))
108309467b48Spatrick     return false;
108409467b48Spatrick 
108509467b48Spatrick   // Now check kind:
108609467b48Spatrick   ConstantInt *KindInt = mdconst::dyn_extract<ConstantInt>(MD->getOperand(1));
108709467b48Spatrick   if (!KindInt)
108809467b48Spatrick     return false;
108909467b48Spatrick   if (KindInt->getZExtValue() != ValueKind)
109009467b48Spatrick     return false;
109109467b48Spatrick 
109209467b48Spatrick   // Get total count
109309467b48Spatrick   ConstantInt *TotalCInt = mdconst::dyn_extract<ConstantInt>(MD->getOperand(2));
109409467b48Spatrick   if (!TotalCInt)
109509467b48Spatrick     return false;
109609467b48Spatrick   TotalC = TotalCInt->getZExtValue();
109709467b48Spatrick 
109809467b48Spatrick   ActualNumValueData = 0;
109909467b48Spatrick 
110009467b48Spatrick   for (unsigned I = 3; I < NOps; I += 2) {
110109467b48Spatrick     if (ActualNumValueData >= MaxNumValueData)
110209467b48Spatrick       break;
110309467b48Spatrick     ConstantInt *Value = mdconst::dyn_extract<ConstantInt>(MD->getOperand(I));
110409467b48Spatrick     ConstantInt *Count =
110509467b48Spatrick         mdconst::dyn_extract<ConstantInt>(MD->getOperand(I + 1));
110609467b48Spatrick     if (!Value || !Count)
110709467b48Spatrick       return false;
110873471bf0Spatrick     uint64_t CntValue = Count->getZExtValue();
110973471bf0Spatrick     if (!GetNoICPValue && (CntValue == NOMORE_ICP_MAGICNUM))
111073471bf0Spatrick       continue;
111109467b48Spatrick     ValueData[ActualNumValueData].Value = Value->getZExtValue();
111273471bf0Spatrick     ValueData[ActualNumValueData].Count = CntValue;
111309467b48Spatrick     ActualNumValueData++;
111409467b48Spatrick   }
111509467b48Spatrick   return true;
111609467b48Spatrick }
111709467b48Spatrick 
getPGOFuncNameMetadata(const Function & F)111809467b48Spatrick MDNode *getPGOFuncNameMetadata(const Function &F) {
111909467b48Spatrick   return F.getMetadata(getPGOFuncNameMetadataName());
112009467b48Spatrick }
112109467b48Spatrick 
createPGOFuncNameMetadata(Function & F,StringRef PGOFuncName)112209467b48Spatrick void createPGOFuncNameMetadata(Function &F, StringRef PGOFuncName) {
112309467b48Spatrick   // Only for internal linkage functions.
112409467b48Spatrick   if (PGOFuncName == F.getName())
112509467b48Spatrick       return;
112609467b48Spatrick   // Don't create duplicated meta-data.
112709467b48Spatrick   if (getPGOFuncNameMetadata(F))
112809467b48Spatrick     return;
112909467b48Spatrick   LLVMContext &C = F.getContext();
113009467b48Spatrick   MDNode *N = MDNode::get(C, MDString::get(C, PGOFuncName));
113109467b48Spatrick   F.setMetadata(getPGOFuncNameMetadataName(), N);
113209467b48Spatrick }
113309467b48Spatrick 
needsComdatForCounter(const Function & F,const Module & M)113409467b48Spatrick bool needsComdatForCounter(const Function &F, const Module &M) {
113509467b48Spatrick   if (F.hasComdat())
113609467b48Spatrick     return true;
113709467b48Spatrick 
113809467b48Spatrick   if (!Triple(M.getTargetTriple()).supportsCOMDAT())
113909467b48Spatrick     return false;
114009467b48Spatrick 
114109467b48Spatrick   // See createPGOFuncNameVar for more details. To avoid link errors, profile
114209467b48Spatrick   // counters for function with available_externally linkage needs to be changed
114309467b48Spatrick   // to linkonce linkage. On ELF based systems, this leads to weak symbols to be
114409467b48Spatrick   // created. Without using comdat, duplicate entries won't be removed by the
114509467b48Spatrick   // linker leading to increased data segement size and raw profile size. Even
114609467b48Spatrick   // worse, since the referenced counter from profile per-function data object
114709467b48Spatrick   // will be resolved to the common strong definition, the profile counts for
114809467b48Spatrick   // available_externally functions will end up being duplicated in raw profile
114909467b48Spatrick   // data. This can result in distorted profile as the counts of those dups
115009467b48Spatrick   // will be accumulated by the profile merger.
115109467b48Spatrick   GlobalValue::LinkageTypes Linkage = F.getLinkage();
115209467b48Spatrick   if (Linkage != GlobalValue::ExternalWeakLinkage &&
115309467b48Spatrick       Linkage != GlobalValue::AvailableExternallyLinkage)
115409467b48Spatrick     return false;
115509467b48Spatrick 
115609467b48Spatrick   return true;
115709467b48Spatrick }
115809467b48Spatrick 
115909467b48Spatrick // Check if INSTR_PROF_RAW_VERSION_VAR is defined.
isIRPGOFlagSet(const Module * M)116009467b48Spatrick bool isIRPGOFlagSet(const Module *M) {
116109467b48Spatrick   auto IRInstrVar =
116209467b48Spatrick       M->getNamedGlobal(INSTR_PROF_QUOTE(INSTR_PROF_RAW_VERSION_VAR));
1163*d415bd75Srobert   if (!IRInstrVar || IRInstrVar->hasLocalLinkage())
116409467b48Spatrick     return false;
116509467b48Spatrick 
1166*d415bd75Srobert   // For CSPGO+LTO, this variable might be marked as non-prevailing and we only
1167*d415bd75Srobert   // have the decl.
1168*d415bd75Srobert   if (IRInstrVar->isDeclaration())
1169*d415bd75Srobert     return true;
1170*d415bd75Srobert 
117109467b48Spatrick   // Check if the flag is set.
117209467b48Spatrick   if (!IRInstrVar->hasInitializer())
117309467b48Spatrick     return false;
117409467b48Spatrick 
117509467b48Spatrick   auto *InitVal = dyn_cast_or_null<ConstantInt>(IRInstrVar->getInitializer());
117609467b48Spatrick   if (!InitVal)
117709467b48Spatrick     return false;
117809467b48Spatrick   return (InitVal->getZExtValue() & VARIANT_MASK_IR_PROF) != 0;
117909467b48Spatrick }
118009467b48Spatrick 
118109467b48Spatrick // Check if we can safely rename this Comdat function.
canRenameComdatFunc(const Function & F,bool CheckAddressTaken)118209467b48Spatrick bool canRenameComdatFunc(const Function &F, bool CheckAddressTaken) {
118309467b48Spatrick   if (F.getName().empty())
118409467b48Spatrick     return false;
118509467b48Spatrick   if (!needsComdatForCounter(F, *(F.getParent())))
118609467b48Spatrick     return false;
118709467b48Spatrick   // Unsafe to rename the address-taken function (which can be used in
118809467b48Spatrick   // function comparison).
118909467b48Spatrick   if (CheckAddressTaken && F.hasAddressTaken())
119009467b48Spatrick     return false;
119109467b48Spatrick   // Only safe to do if this function may be discarded if it is not used
119209467b48Spatrick   // in the compilation unit.
119309467b48Spatrick   if (!GlobalValue::isDiscardableIfUnused(F.getLinkage()))
119409467b48Spatrick     return false;
119509467b48Spatrick 
119609467b48Spatrick   // For AvailableExternallyLinkage functions.
119709467b48Spatrick   if (!F.hasComdat()) {
119809467b48Spatrick     assert(F.getLinkage() == GlobalValue::AvailableExternallyLinkage);
119909467b48Spatrick     return true;
120009467b48Spatrick   }
120109467b48Spatrick   return true;
120209467b48Spatrick }
120309467b48Spatrick 
120409467b48Spatrick // Create the variable for the profile file name.
createProfileFileNameVar(Module & M,StringRef InstrProfileOutput)120509467b48Spatrick void createProfileFileNameVar(Module &M, StringRef InstrProfileOutput) {
120609467b48Spatrick   if (InstrProfileOutput.empty())
120709467b48Spatrick     return;
120809467b48Spatrick   Constant *ProfileNameConst =
120909467b48Spatrick       ConstantDataArray::getString(M.getContext(), InstrProfileOutput, true);
121009467b48Spatrick   GlobalVariable *ProfileNameVar = new GlobalVariable(
121109467b48Spatrick       M, ProfileNameConst->getType(), true, GlobalValue::WeakAnyLinkage,
121209467b48Spatrick       ProfileNameConst, INSTR_PROF_QUOTE(INSTR_PROF_PROFILE_NAME_VAR));
1213*d415bd75Srobert   ProfileNameVar->setVisibility(GlobalValue::HiddenVisibility);
121409467b48Spatrick   Triple TT(M.getTargetTriple());
121509467b48Spatrick   if (TT.supportsCOMDAT()) {
121609467b48Spatrick     ProfileNameVar->setLinkage(GlobalValue::ExternalLinkage);
121709467b48Spatrick     ProfileNameVar->setComdat(M.getOrInsertComdat(
121809467b48Spatrick         StringRef(INSTR_PROF_QUOTE(INSTR_PROF_PROFILE_NAME_VAR))));
121909467b48Spatrick   }
122009467b48Spatrick }
122109467b48Spatrick 
accumulateCounts(const std::string & BaseFilename,const std::string & TestFilename,bool IsCS)122209467b48Spatrick Error OverlapStats::accumulateCounts(const std::string &BaseFilename,
122309467b48Spatrick                                      const std::string &TestFilename,
122409467b48Spatrick                                      bool IsCS) {
122509467b48Spatrick   auto getProfileSum = [IsCS](const std::string &Filename,
122609467b48Spatrick                               CountSumOrPercent &Sum) -> Error {
122709467b48Spatrick     auto ReaderOrErr = InstrProfReader::create(Filename);
122809467b48Spatrick     if (Error E = ReaderOrErr.takeError()) {
122909467b48Spatrick       return E;
123009467b48Spatrick     }
123109467b48Spatrick     auto Reader = std::move(ReaderOrErr.get());
123209467b48Spatrick     Reader->accumulateCounts(Sum, IsCS);
123309467b48Spatrick     return Error::success();
123409467b48Spatrick   };
123509467b48Spatrick   auto Ret = getProfileSum(BaseFilename, Base);
123609467b48Spatrick   if (Ret)
123709467b48Spatrick     return Ret;
123809467b48Spatrick   Ret = getProfileSum(TestFilename, Test);
123909467b48Spatrick   if (Ret)
124009467b48Spatrick     return Ret;
124109467b48Spatrick   this->BaseFilename = &BaseFilename;
124209467b48Spatrick   this->TestFilename = &TestFilename;
124309467b48Spatrick   Valid = true;
124409467b48Spatrick   return Error::success();
124509467b48Spatrick }
124609467b48Spatrick 
addOneMismatch(const CountSumOrPercent & MismatchFunc)124709467b48Spatrick void OverlapStats::addOneMismatch(const CountSumOrPercent &MismatchFunc) {
124809467b48Spatrick   Mismatch.NumEntries += 1;
124909467b48Spatrick   Mismatch.CountSum += MismatchFunc.CountSum / Test.CountSum;
125009467b48Spatrick   for (unsigned I = 0; I < IPVK_Last - IPVK_First + 1; I++) {
125109467b48Spatrick     if (Test.ValueCounts[I] >= 1.0f)
125209467b48Spatrick       Mismatch.ValueCounts[I] +=
125309467b48Spatrick           MismatchFunc.ValueCounts[I] / Test.ValueCounts[I];
125409467b48Spatrick   }
125509467b48Spatrick }
125609467b48Spatrick 
addOneUnique(const CountSumOrPercent & UniqueFunc)125709467b48Spatrick void OverlapStats::addOneUnique(const CountSumOrPercent &UniqueFunc) {
125809467b48Spatrick   Unique.NumEntries += 1;
125909467b48Spatrick   Unique.CountSum += UniqueFunc.CountSum / Test.CountSum;
126009467b48Spatrick   for (unsigned I = 0; I < IPVK_Last - IPVK_First + 1; I++) {
126109467b48Spatrick     if (Test.ValueCounts[I] >= 1.0f)
126209467b48Spatrick       Unique.ValueCounts[I] += UniqueFunc.ValueCounts[I] / Test.ValueCounts[I];
126309467b48Spatrick   }
126409467b48Spatrick }
126509467b48Spatrick 
dump(raw_fd_ostream & OS) const126609467b48Spatrick void OverlapStats::dump(raw_fd_ostream &OS) const {
126709467b48Spatrick   if (!Valid)
126809467b48Spatrick     return;
126909467b48Spatrick 
127009467b48Spatrick   const char *EntryName =
127109467b48Spatrick       (Level == ProgramLevel ? "functions" : "edge counters");
127209467b48Spatrick   if (Level == ProgramLevel) {
127309467b48Spatrick     OS << "Profile overlap infomation for base_profile: " << *BaseFilename
127409467b48Spatrick        << " and test_profile: " << *TestFilename << "\nProgram level:\n";
127509467b48Spatrick   } else {
127609467b48Spatrick     OS << "Function level:\n"
127709467b48Spatrick        << "  Function: " << FuncName << " (Hash=" << FuncHash << ")\n";
127809467b48Spatrick   }
127909467b48Spatrick 
128009467b48Spatrick   OS << "  # of " << EntryName << " overlap: " << Overlap.NumEntries << "\n";
128109467b48Spatrick   if (Mismatch.NumEntries)
128209467b48Spatrick     OS << "  # of " << EntryName << " mismatch: " << Mismatch.NumEntries
128309467b48Spatrick        << "\n";
128409467b48Spatrick   if (Unique.NumEntries)
128509467b48Spatrick     OS << "  # of " << EntryName
128609467b48Spatrick        << " only in test_profile: " << Unique.NumEntries << "\n";
128709467b48Spatrick 
128809467b48Spatrick   OS << "  Edge profile overlap: " << format("%.3f%%", Overlap.CountSum * 100)
128909467b48Spatrick      << "\n";
129009467b48Spatrick   if (Mismatch.NumEntries)
129109467b48Spatrick     OS << "  Mismatched count percentage (Edge): "
129209467b48Spatrick        << format("%.3f%%", Mismatch.CountSum * 100) << "\n";
129309467b48Spatrick   if (Unique.NumEntries)
129409467b48Spatrick     OS << "  Percentage of Edge profile only in test_profile: "
129509467b48Spatrick        << format("%.3f%%", Unique.CountSum * 100) << "\n";
129609467b48Spatrick   OS << "  Edge profile base count sum: " << format("%.0f", Base.CountSum)
129709467b48Spatrick      << "\n"
129809467b48Spatrick      << "  Edge profile test count sum: " << format("%.0f", Test.CountSum)
129909467b48Spatrick      << "\n";
130009467b48Spatrick 
130109467b48Spatrick   for (unsigned I = 0; I < IPVK_Last - IPVK_First + 1; I++) {
130209467b48Spatrick     if (Base.ValueCounts[I] < 1.0f && Test.ValueCounts[I] < 1.0f)
130309467b48Spatrick       continue;
130409467b48Spatrick     char ProfileKindName[20];
130509467b48Spatrick     switch (I) {
130609467b48Spatrick     case IPVK_IndirectCallTarget:
130709467b48Spatrick       strncpy(ProfileKindName, "IndirectCall", 19);
130809467b48Spatrick       break;
130909467b48Spatrick     case IPVK_MemOPSize:
131009467b48Spatrick       strncpy(ProfileKindName, "MemOP", 19);
131109467b48Spatrick       break;
131209467b48Spatrick     default:
131309467b48Spatrick       snprintf(ProfileKindName, 19, "VP[%d]", I);
131409467b48Spatrick       break;
131509467b48Spatrick     }
131609467b48Spatrick     OS << "  " << ProfileKindName
131709467b48Spatrick        << " profile overlap: " << format("%.3f%%", Overlap.ValueCounts[I] * 100)
131809467b48Spatrick        << "\n";
131909467b48Spatrick     if (Mismatch.NumEntries)
132009467b48Spatrick       OS << "  Mismatched count percentage (" << ProfileKindName
132109467b48Spatrick          << "): " << format("%.3f%%", Mismatch.ValueCounts[I] * 100) << "\n";
132209467b48Spatrick     if (Unique.NumEntries)
132309467b48Spatrick       OS << "  Percentage of " << ProfileKindName
132409467b48Spatrick          << " profile only in test_profile: "
132509467b48Spatrick          << format("%.3f%%", Unique.ValueCounts[I] * 100) << "\n";
132609467b48Spatrick     OS << "  " << ProfileKindName
132709467b48Spatrick        << " profile base count sum: " << format("%.0f", Base.ValueCounts[I])
132809467b48Spatrick        << "\n"
132909467b48Spatrick        << "  " << ProfileKindName
133009467b48Spatrick        << " profile test count sum: " << format("%.0f", Test.ValueCounts[I])
133109467b48Spatrick        << "\n";
133209467b48Spatrick   }
133309467b48Spatrick }
133409467b48Spatrick 
1335*d415bd75Srobert namespace IndexedInstrProf {
1336*d415bd75Srobert // A C++14 compatible version of the offsetof macro.
1337*d415bd75Srobert template <typename T1, typename T2>
offsetOf(T1 T2::* Member)1338*d415bd75Srobert inline size_t constexpr offsetOf(T1 T2::*Member) {
1339*d415bd75Srobert   constexpr T2 Object{};
1340*d415bd75Srobert   return size_t(&(Object.*Member)) - size_t(&Object);
1341*d415bd75Srobert }
1342*d415bd75Srobert 
read(const unsigned char * Buffer,size_t Offset)1343*d415bd75Srobert static inline uint64_t read(const unsigned char *Buffer, size_t Offset) {
1344*d415bd75Srobert   return *reinterpret_cast<const uint64_t *>(Buffer + Offset);
1345*d415bd75Srobert }
1346*d415bd75Srobert 
formatVersion() const1347*d415bd75Srobert uint64_t Header::formatVersion() const {
1348*d415bd75Srobert   using namespace support;
1349*d415bd75Srobert   return endian::byte_swap<uint64_t, little>(Version);
1350*d415bd75Srobert }
1351*d415bd75Srobert 
readFromBuffer(const unsigned char * Buffer)1352*d415bd75Srobert Expected<Header> Header::readFromBuffer(const unsigned char *Buffer) {
1353*d415bd75Srobert   using namespace support;
1354*d415bd75Srobert   static_assert(std::is_standard_layout_v<Header>,
1355*d415bd75Srobert                 "The header should be standard layout type since we use offset "
1356*d415bd75Srobert                 "of fields to read.");
1357*d415bd75Srobert   Header H;
1358*d415bd75Srobert 
1359*d415bd75Srobert   H.Magic = read(Buffer, offsetOf(&Header::Magic));
1360*d415bd75Srobert   // Check the magic number.
1361*d415bd75Srobert   uint64_t Magic = endian::byte_swap<uint64_t, little>(H.Magic);
1362*d415bd75Srobert   if (Magic != IndexedInstrProf::Magic)
1363*d415bd75Srobert     return make_error<InstrProfError>(instrprof_error::bad_magic);
1364*d415bd75Srobert 
1365*d415bd75Srobert   // Read the version.
1366*d415bd75Srobert   H.Version = read(Buffer, offsetOf(&Header::Version));
1367*d415bd75Srobert   if (GET_VERSION(H.formatVersion()) >
1368*d415bd75Srobert       IndexedInstrProf::ProfVersion::CurrentVersion)
1369*d415bd75Srobert     return make_error<InstrProfError>(instrprof_error::unsupported_version);
1370*d415bd75Srobert 
1371*d415bd75Srobert   switch (GET_VERSION(H.formatVersion())) {
1372*d415bd75Srobert     // When a new field is added in the header add a case statement here to
1373*d415bd75Srobert     // populate it.
1374*d415bd75Srobert     static_assert(
1375*d415bd75Srobert         IndexedInstrProf::ProfVersion::CurrentVersion == Version9,
1376*d415bd75Srobert         "Please update the reading code below if a new field has been added, "
1377*d415bd75Srobert         "if not add a case statement to fall through to the latest version.");
1378*d415bd75Srobert   case 9ull:
1379*d415bd75Srobert     H.BinaryIdOffset = read(Buffer, offsetOf(&Header::BinaryIdOffset));
1380*d415bd75Srobert     [[fallthrough]];
1381*d415bd75Srobert   case 8ull:
1382*d415bd75Srobert     H.MemProfOffset = read(Buffer, offsetOf(&Header::MemProfOffset));
1383*d415bd75Srobert     [[fallthrough]];
1384*d415bd75Srobert   default: // Version7 (when the backwards compatible header was introduced).
1385*d415bd75Srobert     H.HashType = read(Buffer, offsetOf(&Header::HashType));
1386*d415bd75Srobert     H.HashOffset = read(Buffer, offsetOf(&Header::HashOffset));
1387*d415bd75Srobert   }
1388*d415bd75Srobert 
1389*d415bd75Srobert   return H;
1390*d415bd75Srobert }
1391*d415bd75Srobert 
size() const1392*d415bd75Srobert size_t Header::size() const {
1393*d415bd75Srobert   switch (GET_VERSION(formatVersion())) {
1394*d415bd75Srobert     // When a new field is added to the header add a case statement here to
1395*d415bd75Srobert     // compute the size as offset of the new field + size of the new field. This
1396*d415bd75Srobert     // relies on the field being added to the end of the list.
1397*d415bd75Srobert     static_assert(IndexedInstrProf::ProfVersion::CurrentVersion == Version9,
1398*d415bd75Srobert                   "Please update the size computation below if a new field has "
1399*d415bd75Srobert                   "been added to the header, if not add a case statement to "
1400*d415bd75Srobert                   "fall through to the latest version.");
1401*d415bd75Srobert   case 9ull:
1402*d415bd75Srobert     return offsetOf(&Header::BinaryIdOffset) + sizeof(Header::BinaryIdOffset);
1403*d415bd75Srobert   case 8ull:
1404*d415bd75Srobert     return offsetOf(&Header::MemProfOffset) + sizeof(Header::MemProfOffset);
1405*d415bd75Srobert   default: // Version7 (when the backwards compatible header was introduced).
1406*d415bd75Srobert     return offsetOf(&Header::HashOffset) + sizeof(Header::HashOffset);
1407*d415bd75Srobert   }
1408*d415bd75Srobert }
1409*d415bd75Srobert 
1410*d415bd75Srobert } // namespace IndexedInstrProf
1411*d415bd75Srobert 
141209467b48Spatrick } // end namespace llvm
1413