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