LLVM 23.0.0git
InstrProf.h
Go to the documentation of this file.
1//===- InstrProf.h - Instrumented profiling format support ------*- C++ -*-===//
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// Instrumentation-based profiling data is generated by instrumented
10// binaries through library functions in compiler-rt, and read by the clang
11// frontend to feed PGO.
12//
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_PROFILEDATA_INSTRPROF_H
16#define LLVM_PROFILEDATA_INSTRPROF_H
17
18#include "llvm/ADT/ArrayRef.h"
20#include "llvm/ADT/DenseMap.h"
22#include "llvm/ADT/STLExtras.h"
23#include "llvm/ADT/StringRef.h"
24#include "llvm/ADT/StringSet.h"
25#include "llvm/IR/GlobalValue.h"
32#include "llvm/Support/Error.h"
34#include "llvm/Support/MD5.h"
39#include <algorithm>
40#include <cassert>
41#include <cstddef>
42#include <cstdint>
43#include <cstring>
44#include <memory>
45#include <string>
46#include <system_error>
47#include <utility>
48#include <vector>
49
50namespace llvm {
51
52class Function;
53class GlobalVariable;
54struct InstrProfRecord;
55class InstrProfSymtab;
56class Instruction;
57class MDNode;
58class Module;
59
60// A struct to define how the data stream should be patched. For Indexed
61// profiling, only uint64_t data type is needed.
62struct PatchItem {
63 uint64_t Pos; // Where to patch.
64 ArrayRef<uint64_t> D; // An array of source data.
65};
66
67// A wrapper class to abstract writer stream with support of bytes
68// back patching.
70public:
73
74 [[nodiscard]] LLVM_ABI uint64_t tell() const;
79 // \c patch can only be called when all data is written and flushed.
80 // For raw_string_ostream, the patch is done on the target string
81 // directly and it won't be reflected in the stream's internal buffer.
83
84 // If \c OS is an instance of \c raw_fd_ostream, this field will be
85 // true. Otherwise, \c OS will be an raw_string_ostream.
89};
90
92#define INSTR_PROF_SECT_ENTRY(Kind, SectNameCommon, SectNameCoff, Prefix) Kind,
94};
96/// Return the max count value. We reserver a few large values for special use.
98 return std::numeric_limits<uint64_t>::max() - 2;
99}
100
101/// Return the name of the profile section corresponding to \p IPSK.
102///
103/// The name of the section depends on the object format type \p OF. If
104/// \p AddSegmentInfo is true, a segment prefix and additional linker hints may
105/// be added to the section name (this is the default).
108 bool AddSegmentInfo = true);
110/// Return the name profile runtime entry point to do value profiling
111/// for a given site.
115
116/// Return the name profile runtime entry point to do memop size value
117/// profiling.
121
122/// Return the prefix of the name of the variables to function as a filter.
123inline StringRef getInstrProfVarPrefix() { return "__prof"; }
124
125/// Return the name prefix of variables containing instrumented function names.
126inline StringRef getInstrProfNameVarPrefix() { return "__profn_"; }
127
128/// Return the name prefix of variables containing virtual table profile data.
129inline StringRef getInstrProfVTableVarPrefix() { return "__profvt_"; }
130
131/// Return the name prefix of variables containing per-function control data.
132inline StringRef getInstrProfDataVarPrefix() { return "__profd_"; }
133
134/// Return the name prefix of profile counter variables.
135inline StringRef getInstrProfCountersVarPrefix() { return "__profc_"; }
136
137/// Return the name prefix of profile bitmap variables.
138inline StringRef getInstrProfBitmapVarPrefix() { return "__profbm_"; }
140/// Return the name prefix of value profile variables.
141inline StringRef getInstrProfValuesVarPrefix() { return "__profvp_"; }
143/// Return the name of value profile node array variables:
144inline StringRef getInstrProfVNodesVarName() { return "__llvm_prf_vnodes"; }
145
146/// Return the name of the variable holding the strings (possibly compressed)
147/// of all function's PGO names.
148inline StringRef getInstrProfNamesVarName() { return "__llvm_prf_nm"; }
149
150inline StringRef getInstrProfVTableNamesVarName() { return "__llvm_prf_vnm"; }
151
152/// Return the name of a covarage mapping variable (internal linkage)
153/// for each instrumented source module. Such variables are allocated
154/// in the __llvm_covmap section.
156 return "__llvm_coverage_mapping";
159/// Return the name of the internal variable recording the array
160/// of PGO name vars referenced by the coverage mapping. The owning
161/// functions of those names are not emitted by FE (e.g, unused inline
162/// functions.)
164 return "__llvm_coverage_names";
167/// Return the name of function that registers all the per-function control
168/// data at program startup time by calling __llvm_register_function. This
169/// function has internal linkage and is called by __llvm_profile_init
170/// runtime method. This function is not generated for these platforms:
171/// Darwin, Linux, and FreeBSD.
173 return "__llvm_profile_register_functions";
175
176/// Return the name of the runtime interface that registers per-function control
177/// data for one instrumented function.
179 return "__llvm_profile_register_function";
180}
181
182/// Return the name of the runtime interface that registers the PGO name
183/// strings.
185 return "__llvm_profile_register_names_function";
186}
187
188/// Return the name of the runtime initialization method that is generated by
189/// the compiler. The function calls __llvm_profile_register_functions and
190/// __llvm_profile_override_default_filename functions if needed. This function
191/// has internal linkage and invoked at startup time via init_array.
192inline StringRef getInstrProfInitFuncName() { return "__llvm_profile_init"; }
193
194/// Return the name of the hook variable defined in profile runtime library.
195/// A reference to the variable causes the linker to link in the runtime
196/// initialization module (which defines the hook variable).
201/// Return the name of the compiler generated function that references the
202/// runtime hook variable. The function is a weak global.
204 return "__llvm_profile_runtime_user";
205}
206
210
214
215/// Return the marker used to separate PGO names during serialization.
216inline StringRef getInstrProfNameSeparator() { return "\01"; }
217
218/// Determines whether module targets a GPU eligable for PGO
219/// instrumentation
220LLVM_ABI bool isGPUProfTarget(const Module &M);
222/// Please use getIRPGOFuncName for LLVM IR instrumentation. This function is
223/// for front-end (Clang, etc) instrumentation.
224/// Return the modified name for function \c F suitable to be
225/// used the key for profile lookup. Variable \c InLTO indicates if this
226/// is called in LTO optimization passes.
227LLVM_ABI std::string
228getPGOFuncName(const Function &F, bool InLTO = false,
230
231/// Return the modified name for a function suitable to be
232/// used the key for profile lookup. The function's original
233/// name is \c RawFuncName and has linkage of type \c Linkage.
234/// The function is defined in module \c FileName.
235LLVM_ABI std::string
238
239/// \return the modified name for function \c F suitable to be
240/// used as the key for IRPGO profile lookup. \c InLTO indicates if this is
241/// called from LTO optimization passes.
242LLVM_ABI std::string getIRPGOFuncName(const Function &F, bool InLTO = false);
243
244/// \return the filename and the function name parsed from the output of
245/// \c getIRPGOFuncName()
246LLVM_ABI std::pair<StringRef, StringRef>
248
249/// Return the name of the global variable used to store a function
250/// name in PGO instrumentation. \c FuncName is the IRPGO function name
251/// (returned by \c getIRPGOFuncName) for LLVM IR instrumentation and PGO
252/// function name (returned by \c getPGOFuncName) for front-end instrumentation.
253LLVM_ABI std::string getPGOFuncNameVarName(StringRef FuncName,
255
256/// Create and return the global variable for function name used in PGO
257/// instrumentation. \c FuncName is the IRPGO function name (returned by
258/// \c getIRPGOFuncName) for LLVM IR instrumentation and PGO function name
259/// (returned by \c getPGOFuncName) for front-end instrumentation.
261 StringRef PGOFuncName);
262
263/// Create and return the global variable for function name used in PGO
264/// instrumentation. \c FuncName is the IRPGO function name (returned by
265/// \c getIRPGOFuncName) for LLVM IR instrumentation and PGO function name
266/// (returned by \c getPGOFuncName) for front-end instrumentation.
269 StringRef PGOFuncName);
270
271/// Return the initializer in string of the PGO name var \c NameVar.
273
274/// Given a PGO function name, remove the filename prefix and return
275/// the original (static) function name.
277 StringRef FileName = "<unknown>");
278
279/// Given a vector of strings (names of global objects like functions or,
280/// virtual tables) \c NameStrs, the method generates a combined string \c
281/// Result that is ready to be serialized. The \c Result string is comprised of
282/// three fields: The first field is the length of the uncompressed strings, and
283/// the the second field is the length of the zlib-compressed string. Both
284/// fields are encoded in ULEB128. If \c doCompress is false, the
285/// third field is the uncompressed strings; otherwise it is the
286/// compressed string. When the string compression is off, the
287/// second field will have value zero.
289 bool doCompression,
290 std::string &Result);
291
292/// Produce \c Result string with the same format described above. The input
293/// is vector of PGO function name variables that are referenced.
294/// The global variable element in 'NameVars' is a string containing the pgo
295/// name of a function. See `createPGOFuncNameVar` that creates these global
296/// variables.
298 std::string &Result,
299 bool doCompression = true);
302 std::string &Result, bool doCompression);
304/// Check if INSTR_PROF_RAW_VERSION_VAR is defined. This global is only being
305/// set in IR PGO compilation.
306LLVM_ABI bool isIRPGOFlagSet(const Module *M);
307
308/// Check if we can safely rename this Comdat function. Instances of the same
309/// comdat function may have different control flows thus can not share the
310/// same counter variable.
312 bool CheckAddressTaken = false);
313
315#define VALUE_PROF_KIND(Enumerator, Value, Descr) Enumerator = Value,
317};
318
319/// Get the value profile data for value site \p SiteIdx from \p InstrProfR
320/// and annotate the instruction \p Inst with the value profile meta data.
321/// Annotate up to \p MaxMDCount (default 3) number of records per value site.
323 const InstrProfRecord &InstrProfR,
324 InstrProfValueKind ValueKind, uint32_t SiteIndx,
325 uint32_t MaxMDCount = 3);
326
327/// Same as the above interface but using an ArrayRef, as well as \p Sum.
328/// This function will not annotate !prof metadata on the instruction if the
329/// referenced array is empty.
333 uint32_t MaxMDCount);
335// TODO: Unify metadata name 'PGOFuncName' and 'PGOName', by supporting read
336// of this metadata for backward compatibility and generating 'PGOName' only.
337/// Extract the value profile data from \p Inst and returns them if \p Inst is
338/// annotated with value profile data. Returns an empty vector otherwise.
341 uint32_t MaxNumValueData, uint64_t &TotalC,
342 bool GetNoICPValue = false);
343
344inline StringRef getPGOFuncNameMetadataName() { return "PGOFuncName"; }
346inline StringRef getPGONameMetadataName() { return "PGOName"; }
348/// Return the PGOFuncName meta data associated with a function.
350
351LLVM_ABI std::string getPGOName(const GlobalVariable &V, bool InLTO = false);
352
353/// Create the PGOFuncName meta data if PGOFuncName is different from
354/// function's raw name. This should only apply to internal linkage functions
355/// declared by users only.
356/// TODO: Update all callers to 'createPGONameMetadata' and deprecate this
357/// function.
359
360/// Create the PGOName metadata if a global object's PGO name is different from
361/// its mangled name. This should apply to local-linkage global objects only.
363
364/// Check if we can use Comdat for profile variables. This will eliminate
365/// the duplicated profile variables for Comdat functions.
366LLVM_ABI bool needsComdatForCounter(const GlobalObject &GV, const Module &M);
367
368/// \c NameStrings is a string composed of one or more possibly encoded
369/// sub-strings. The substrings are separated by `\01` (returned by
370/// InstrProf.h:getInstrProfNameSeparator). This method decodes the string and
371/// calls `NameCallback` for each substring.
373 StringRef NameStrings, std::function<Error(StringRef)> NameCallback);
374
375/// An enum describing the attributes of an instrumented profile.
376enum class InstrProfKind {
377 Unknown = 0x0,
378 // A frontend clang profile, incompatible with other attrs.
380 // An IR-level profile (default when -fprofile-generate is used).
382 // A profile with entry basic block instrumentation.
384 // A context sensitive IR-level profile.
386 // Use single byte probes for coverage.
388 // Only instrument the function entry basic block.
390 // A memory profile collected using -fprofile=memory.
391 MemProf = 0x40,
392 // A temporal profile.
394 // A profile with loop entry basic blocks instrumentation.
397};
398
399LLVM_ABI const std::error_category &instrprof_category();
400
429
430/// An ordered list of functions identified by their NameRef found in
431/// INSTR_PROF_DATA
433 std::vector<uint64_t> FunctionNameRefs;
435 TemporalProfTraceTy(std::initializer_list<uint64_t> Trace = {},
436 uint64_t Weight = 1)
438
439 /// Use a set of temporal profile traces to create a list of balanced
440 /// partitioning function nodes used by BalancedPartitioning to generate a
441 /// function order that reduces page faults during startup
442 LLVM_ABI static void
444 std::vector<BPFunctionNode> &Nodes,
445 bool RemoveOutlierUNs = true);
446};
447
448inline std::error_code make_error_code(instrprof_error E) {
449 return std::error_code(static_cast<int>(E), instrprof_category());
451
452class LLVM_ABI InstrProfError : public ErrorInfo<InstrProfError> {
453public:
455 : Err(Err), Msg(ErrStr.str()) {
456 assert(Err != instrprof_error::success && "Not an error");
457 }
458
459 std::string message() const override;
460
461 void log(raw_ostream &OS) const override { OS << message(); }
462
463 std::error_code convertToErrorCode() const override {
464 return make_error_code(Err);
465 }
466
467 instrprof_error get() const { return Err; }
468 const std::string &getMessage() const { return Msg; }
469
470 /// Consume an Error and return the raw enum value contained within it, and
471 /// the optional error message. The Error must either be a success value, or
472 /// contain a single InstrProfError.
473 static std::pair<instrprof_error, std::string> take(Error E) {
474 auto Err = instrprof_error::success;
475 std::string Msg = "";
476 handleAllErrors(std::move(E), [&Err, &Msg](const InstrProfError &IPE) {
477 assert(Err == instrprof_error::success && "Multiple errors encountered");
478 Err = IPE.get();
479 Msg = IPE.getMessage();
480 });
481 return {Err, Msg};
482 }
483
484 static char ID;
485
486private:
487 instrprof_error Err;
488 std::string Msg;
489};
490
491namespace object {
492
493class SectionRef;
494
495} // end namespace object
496
498
500
501} // end namespace IndexedInstrProf
502
503/// A symbol table used for function [IR]PGO name look-up with keys
504/// (such as pointers, md5hash values) to the function. A function's
505/// [IR]PGO name or name's md5hash are used in retrieving the profile
506/// data of the function. See \c getIRPGOFuncName() and \c getPGOFuncName
507/// methods for details how [IR]PGO name is formed.
509public:
510 using AddrHashMap = std::vector<std::pair<uint64_t, uint64_t>>;
511
512 // Returns the canonical name of the given PGOName. This shares the same
513 // logic of FunctionSamples::getCanonicalFnName() but only strips ".llvm."
514 // and ".part", and leaves out ".__uniq.".
516
517private:
518 using AddrIntervalMap =
520 StringRef Data;
521 uint64_t Address = 0;
522 // Unique name strings. Used to ensure entries in MD5NameMap (a vector that's
523 // going to be sorted) has unique MD5 keys in the first place.
524 StringSet<> NameTab;
525 // Records the unique virtual table names. This is used by InstrProfWriter to
526 // write out an on-disk chained hash table of virtual table names.
527 // InstrProfWriter stores per function profile data (keyed by function names)
528 // so it doesn't use a StringSet for function names.
529 StringSet<> VTableNames;
530 // A map from MD5 keys to function name strings.
531 mutable std::vector<std::pair<uint64_t, StringRef>> MD5NameMap;
532 // A map from MD5 keys to function define. We only populate this map
533 // when build the Symtab from a Module.
534 mutable std::vector<std::pair<uint64_t, Function *>> MD5FuncMap;
535 // A map from MD5 to the global variable. This map is only populated when
536 // building the symtab from a module. Use separate container instances for
537 // `MD5FuncMap` and `MD5VTableMap`.
538 // TODO: Unify the container type and the lambda function 'mapName' inside
539 // add{Func,VTable}WithName.
541 // A map from function runtime address to function name MD5 hash.
542 // This map is only populated and used by raw instr profile reader.
543 mutable AddrHashMap AddrToMD5Map;
545 AddrIntervalMap::Allocator VTableAddrMapAllocator;
546 // This map is only populated and used by raw instr profile reader.
547 AddrIntervalMap VTableAddrMap;
548
549 // "dirty" flag for the rest of the mutable state. lookup APIs (like
550 // getFunction) need the mutable state to be sorted.
551 mutable bool Sorted = false;
553 static StringRef getExternalSymbol() { return "** External Symbol **"; }
555 // Add the function into the symbol table, by creating the following
556 // map entries:
557 // name-set = {PGOFuncName} union {getCanonicalName(PGOFuncName)}
558 // - In MD5NameMap: <MD5Hash(name), name> for name in name-set
559 // - In MD5FuncMap: <MD5Hash(name), &F> for name in name-set
560 // The canonical name is only added if \c AddCanonical is true.
561 Error addFuncWithName(Function &F, StringRef PGOFuncName, bool AddCanonical);
562
563 // Add the vtable into the symbol table, by creating the following
564 // map entries:
565 // name-set = {PGOName} union {getCanonicalName(PGOName)}
566 // - In MD5NameMap: <MD5Hash(name), name> for name in name-set
567 // - In MD5VTableMap: <MD5Hash(name), name> for name in name-set
568 Error addVTableWithName(GlobalVariable &V, StringRef PGOVTableName);
569
570 // If the symtab is created by a series of calls to \c addFuncName, \c
571 // finalizeSymtab needs to be called before looking up function names.
572 // This is required because the underlying map is a vector (for space
573 // efficiency) which needs to be sorted. The API is `const` because it's part
574 // of the implementation detail of `const` APIs that need to first ensure this
575 // property of ordering on the other mutable state.
576 inline void finalizeSymtab() const;
577
578public:
579 InstrProfSymtab() : VTableAddrMap(VTableAddrMapAllocator) {}
580
581 // Not copyable or movable.
582 // Consider std::unique_ptr for move.
587
588 /// Create InstrProfSymtab from an object file section which
589 /// contains function PGO names. When section may contain raw
590 /// string data or string data in compressed form. This method
591 /// only initialize the symtab with reference to the data and
592 /// the section base address. The decompression will be delayed
593 /// until before it is used. See also \c create(StringRef) method.
595
596 /// \c NameStrings is a string composed of one of more sub-strings
597 /// encoded in the format described in \c collectPGOFuncNameStrings.
598 /// This method is a wrapper to \c readAndDecodeStrings method.
599 LLVM_ABI Error create(StringRef NameStrings);
600
601 /// Initialize symtab states with function names and vtable names. \c
602 /// FuncNameStrings is a string composed of one or more encoded function name
603 /// strings, and \c VTableNameStrings composes of one or more encoded vtable
604 /// names. This interface is solely used by raw profile reader.
605 LLVM_ABI Error create(StringRef FuncNameStrings, StringRef VTableNameStrings);
606
607 /// Initialize 'this' with the set of vtable names encoded in
608 /// \c CompressedVTableNames.
610 initVTableNamesFromCompressedStrings(StringRef CompressedVTableNames);
611
612 /// This interface is used by reader of CoverageMapping test
613 /// format.
614 inline Error create(StringRef D, uint64_t BaseAddr);
615
616 /// A wrapper interface to populate the PGO symtab with functions
617 /// decls from module \c M. This interface is used by transformation
618 /// passes such as indirect function call promotion. Variable \c InLTO
619 /// indicates if this is called from LTO optimization passes.
620 /// A canonical name, removing non-__uniq suffixes, is added if
621 /// \c AddCanonical is true.
622 LLVM_ABI Error create(Module &M, bool InLTO = false,
623 bool AddCanonical = true);
624
625 /// Create InstrProfSymtab from a set of names iteratable from
626 /// \p IterRange. This interface is used by IndexedProfReader.
627 template <typename NameIterRange>
628 Error create(const NameIterRange &IterRange);
629
630 /// Create InstrProfSymtab from a set of function names and vtable
631 /// names iteratable from \p IterRange. This interface is used by
632 /// IndexedProfReader.
633 template <typename FuncNameIterRange, typename VTableNameIterRange>
634 Error create(const FuncNameIterRange &FuncIterRange,
635 const VTableNameIterRange &VTableIterRange);
636
637 // Map the MD5 of the symbol name to the name.
639 if (SymbolName.empty())
641 "symbol name is empty");
642
643 // Insert into NameTab so that MD5NameMap (a vector that will be sorted)
644 // won't have duplicated entries in the first place.
645 auto Ins = NameTab.insert(SymbolName);
646 if (Ins.second) {
647 MD5NameMap.push_back(std::make_pair(
648 IndexedInstrProf::ComputeHash(SymbolName), Ins.first->getKey()));
649 Sorted = false;
650 }
651 return Error::success();
652 }
653
654 /// The method name is kept since there are many callers.
655 /// It just forwards to 'addSymbolName'.
656 Error addFuncName(StringRef FuncName) { return addSymbolName(FuncName); }
657
658 /// Adds VTableName as a known symbol, and inserts it to a map that
659 /// tracks all vtable names.
661 if (Error E = addSymbolName(VTableName))
662 return E;
663
664 // Record VTableName. InstrProfWriter uses this set. The comment around
665 // class member explains why.
666 VTableNames.insert(VTableName);
667 return Error::success();
668 }
669
670 const std::vector<std::pair<uint64_t, Function *>> &getIDToNameMap() const {
671 return MD5FuncMap;
672 }
673
674 const StringSet<> &getVTableNames() const { return VTableNames; }
675
676 /// Map a function address to its name's MD5 hash. This interface
677 /// is only used by the raw profiler reader.
678 void mapAddress(uint64_t Addr, uint64_t MD5Val) {
679 AddrToMD5Map.push_back(std::make_pair(Addr, MD5Val));
680 }
681
682 /// Map the address range (i.e., [start_address, end_address)) of a variable
683 /// to its names' MD5 hash. This interface is only used by the raw profile
684 /// reader.
685 void mapVTableAddress(uint64_t StartAddr, uint64_t EndAddr, uint64_t MD5Val) {
686 VTableAddrMap.insert(StartAddr, EndAddr, MD5Val);
687 }
688
689 /// Return a function's hash, or 0, if the function isn't in this SymTab.
691
692 /// Return a vtable's hash, or 0 if the vtable doesn't exist in this SymTab.
694
695 /// Return function's PGO name from the function name's symbol
696 /// address in the object file. If an error occurs, return
697 /// an empty string.
698 LLVM_ABI StringRef getFuncName(uint64_t FuncNameAddress,
699 size_t NameSize) const;
700
701 /// Return name of functions or global variables from the name's md5 hash
702 /// value. If not found, return an empty string.
703 inline StringRef getFuncOrVarName(uint64_t ValMD5Hash) const;
704
705 /// Just like getFuncOrVarName, except that it will return literal string
706 /// 'External Symbol' if the function or global variable is external to
707 /// this symbol table.
708 inline StringRef getFuncOrVarNameIfDefined(uint64_t ValMD5Hash) const;
709
710 /// True if Symbol is the value used to represent external symbols.
711 static bool isExternalSymbol(const StringRef &Symbol) {
712 return Symbol == InstrProfSymtab::getExternalSymbol();
713 }
714
715 /// Return function from the name's md5 hash. Return nullptr if not found.
716 inline Function *getFunction(uint64_t FuncMD5Hash) const;
717
718 /// Return the global variable corresponding to md5 hash. Return nullptr if
719 /// not found.
721
722 /// Return the name section data.
723 inline StringRef getNameData() const { return Data; }
724
725 /// Dump the symbols in this table.
726 LLVM_ABI void dumpNames(raw_ostream &OS) const;
727};
728
730 Data = D;
731 Address = BaseAddr;
732 return Error::success();
733}
734
735template <typename NameIterRange>
736Error InstrProfSymtab::create(const NameIterRange &IterRange) {
737 for (auto Name : IterRange)
738 if (Error E = addFuncName(Name))
739 return E;
740
741 finalizeSymtab();
742 return Error::success();
743}
744
745template <typename FuncNameIterRange, typename VTableNameIterRange>
746Error InstrProfSymtab::create(const FuncNameIterRange &FuncIterRange,
747 const VTableNameIterRange &VTableIterRange) {
748 // Iterate elements by StringRef rather than by const reference.
749 // StringRef is small enough, so the loop is efficient whether
750 // element in the range is std::string or StringRef.
751 for (StringRef Name : FuncIterRange)
752 if (Error E = addFuncName(Name))
753 return E;
754
755 for (StringRef VTableName : VTableIterRange)
756 if (Error E = addVTableName(VTableName))
757 return E;
758
759 finalizeSymtab();
760 return Error::success();
761}
762
763void InstrProfSymtab::finalizeSymtab() const {
764 if (Sorted)
765 return;
766 llvm::sort(MD5NameMap, less_first());
767 llvm::stable_sort(MD5FuncMap, less_first());
768 llvm::sort(AddrToMD5Map, less_first());
769 AddrToMD5Map.erase(llvm::unique(AddrToMD5Map), AddrToMD5Map.end());
770 Sorted = true;
771}
772
775 if (Ret.empty())
776 return InstrProfSymtab::getExternalSymbol();
777 return Ret;
778}
779
781 finalizeSymtab();
782 auto Result = llvm::lower_bound(MD5NameMap, MD5Hash,
783 [](const std::pair<uint64_t, StringRef> &LHS,
784 uint64_t RHS) { return LHS.first < RHS; });
785 if (Result != MD5NameMap.end() && Result->first == MD5Hash)
786 return Result->second;
787 return StringRef();
788}
789
791 finalizeSymtab();
792 auto Result = llvm::lower_bound(MD5FuncMap, FuncMD5Hash,
793 [](const std::pair<uint64_t, Function *> &LHS,
794 uint64_t RHS) { return LHS.first < RHS; });
795 if (Result != MD5FuncMap.end() && Result->first == FuncMD5Hash)
796 return Result->second;
797 return nullptr;
798}
799
801 return MD5VTableMap.lookup(MD5Hash);
802}
803
804// To store the sums of profile count values, or the percentage of
805// the sums of the total count values.
808 double CountSum = 0.0f;
809 std::array<double, IPVK_Last - IPVK_First + 1> ValueCounts = {};
810 CountSumOrPercent() = default;
811 void reset() {
812 NumEntries = 0;
813 CountSum = 0.0f;
814 ValueCounts.fill(0.0f);
815 }
816};
817
818// Function level or program level overlap information.
821 // Sum of the total count values for the base profile.
823 // Sum of the total count values for the test profile.
825 // Overlap lap score. Should be in range of [0.0f to 1.0f].
830 const std::string *BaseFilename = nullptr;
831 const std::string *TestFilename = nullptr;
834 bool Valid = false;
835
837
838 LLVM_ABI void dump(raw_fd_ostream &OS) const;
839
840 void setFuncInfo(StringRef Name, uint64_t Hash) {
841 FuncName = Name;
842 FuncHash = Hash;
843 }
844
845 LLVM_ABI Error accumulateCounts(const std::string &BaseFilename,
846 const std::string &TestFilename, bool IsCS);
847 LLVM_ABI void addOneMismatch(const CountSumOrPercent &MismatchFunc);
848 LLVM_ABI void addOneUnique(const CountSumOrPercent &UniqueFunc);
849
850 static inline double score(uint64_t Val1, uint64_t Val2, double Sum1,
851 double Sum2) {
852 if (Sum1 < 1.0f || Sum2 < 1.0f)
853 return 0.0f;
854 return std::min(Val1 / Sum1, Val2 / Sum2);
855 }
856};
857
858// This is used to filter the functions whose overlap information
859// to be output.
864
866 /// Value profiling data pairs at a given value site.
867 std::vector<InstrProfValueData> ValueData;
868
870 InstrProfValueSiteRecord(std::vector<InstrProfValueData> &&VD)
871 : ValueData(VD) {}
872
873 /// Sort ValueData ascending by Value
876 [](const InstrProfValueData &L, const InstrProfValueData &R) {
877 return L.Value < R.Value;
878 });
879 }
880 /// Sort ValueData Descending by Count
881 inline void sortByCount();
882
883 /// Merge data from another InstrProfValueSiteRecord
884 /// Optionally scale merged counts by \p Weight.
886 function_ref<void(instrprof_error)> Warn);
887 /// Scale up value profile data counts by N (Numerator) / D (Denominator).
889 function_ref<void(instrprof_error)> Warn);
890
891 /// Compute the overlap b/w this record and Input record.
893 OverlapStats &Overlap, OverlapStats &FuncLevelOverlap);
894};
895
896/// Profiling information for a single function.
898 std::vector<uint64_t> Counts;
899 std::vector<uint8_t> BitmapBytes;
900
901 InstrProfRecord() = default;
902 InstrProfRecord(std::vector<uint64_t> Counts) : Counts(std::move(Counts)) {}
903 InstrProfRecord(std::vector<uint64_t> Counts,
904 std::vector<uint8_t> BitmapBytes)
909 ValueData(RHS.ValueData
910 ? std::make_unique<ValueProfData>(*RHS.ValueData)
911 : nullptr) {}
914 Counts = RHS.Counts;
915 BitmapBytes = RHS.BitmapBytes;
916 if (!RHS.ValueData) {
917 ValueData = nullptr;
918 return *this;
919 }
920 if (!ValueData)
921 ValueData = std::make_unique<ValueProfData>(*RHS.ValueData);
922 else
923 *ValueData = *RHS.ValueData;
924 return *this;
925 }
926
927 /// Return the number of value profile kinds with non-zero number
928 /// of profile sites.
929 inline uint32_t getNumValueKinds() const;
930 /// Return the number of instrumented sites for ValueKind.
931 inline uint32_t getNumValueSites(uint32_t ValueKind) const;
932
933 /// Return the total number of ValueData for ValueKind.
934 inline uint32_t getNumValueData(uint32_t ValueKind) const;
935
936 /// Return the array of profiled values at \p Site.
938 uint32_t Site) const;
939
940 /// Reserve space for NumValueSites sites.
941 inline void reserveSites(uint32_t ValueKind, uint32_t NumValueSites);
942
943 /// Add ValueData for ValueKind at value Site. We do not support adding sites
944 /// out of order. Site must go up from 0 one by one.
945 LLVM_ABI void addValueData(uint32_t ValueKind, uint32_t Site,
947 InstrProfSymtab *SymTab);
948
949 /// Merge the counts in \p Other into this one.
950 /// Optionally scale merged counts by \p Weight.
952 function_ref<void(instrprof_error)> Warn);
953
954 /// Scale up profile counts (including value profile data) by
955 /// a factor of (N / D).
957 function_ref<void(instrprof_error)> Warn);
958
959 /// Sort value profile data (per site) by count.
961 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
962 for (auto &SR : getValueSitesForKind(Kind))
963 SR.sortByCount();
964 }
965
966 /// Clear value data entries and edge counters.
967 void Clear() {
968 Counts.clear();
970 }
971
972 /// Clear value data entries
973 void clearValueData() { ValueData = nullptr; }
974
975 /// Compute the sums of all counts and store in Sum.
977
978 /// Compute the overlap b/w this IntrprofRecord and Other.
980 OverlapStats &FuncLevelOverlap, uint64_t ValueCutoff);
981
982 /// Compute the overlap of value profile counts.
984 OverlapStats &Overlap,
985 OverlapStats &FuncLevelOverlap);
986
997 uint64_t FirstCount = Counts[0];
998 if (FirstCount == (uint64_t)HotFunctionVal)
999 return PseudoHot;
1000 if (FirstCount == (uint64_t)WarmFunctionVal)
1001 return PseudoWarm;
1002 return NotPseudo;
1003 }
1005 if (Kind == PseudoHot)
1007 else if (Kind == PseudoWarm)
1009 }
1010
1011private:
1012 using ValueProfData = std::array<std::vector<InstrProfValueSiteRecord>,
1013 IPVK_Last - IPVK_First + 1>;
1014 std::unique_ptr<ValueProfData> ValueData;
1015
1017 getValueSitesForKind(uint32_t ValueKind) {
1018 // Cast to /add/ const (should be an implicit_cast, ideally, if that's ever
1019 // implemented in LLVM) to call the const overload of this function, then
1020 // cast away the constness from the result.
1021 auto AR = const_cast<const InstrProfRecord *>(this)->getValueSitesForKind(
1022 ValueKind);
1023 return MutableArrayRef(
1024 const_cast<InstrProfValueSiteRecord *>(AR.data()), AR.size());
1025 }
1027 getValueSitesForKind(uint32_t ValueKind) const {
1028 if (!ValueData)
1029 return {};
1030 assert(IPVK_First <= ValueKind && ValueKind <= IPVK_Last &&
1031 "Unknown value kind!");
1032 return (*ValueData)[ValueKind - IPVK_First];
1033 }
1034
1035 std::vector<InstrProfValueSiteRecord> &
1036 getOrCreateValueSitesForKind(uint32_t ValueKind) {
1037 if (!ValueData)
1038 ValueData = std::make_unique<ValueProfData>();
1039 assert(IPVK_First <= ValueKind && ValueKind <= IPVK_Last &&
1040 "Unknown value kind!");
1041 return (*ValueData)[ValueKind - IPVK_First];
1042 }
1043
1044 // Map indirect call target name hash to name string.
1045 uint64_t remapValue(uint64_t Value, uint32_t ValueKind,
1046 InstrProfSymtab *SymTab);
1047
1048 // Merge Value Profile data from Src record to this record for ValueKind.
1049 // Scale merged value counts by \p Weight.
1050 void mergeValueProfData(uint32_t ValkeKind, InstrProfRecord &Src,
1051 uint64_t Weight,
1052 function_ref<void(instrprof_error)> Warn);
1053
1054 // Scale up value profile data count by N (Numerator) / D (Denominator).
1055 void scaleValueProfData(uint32_t ValueKind, uint64_t N, uint64_t D,
1056 function_ref<void(instrprof_error)> Warn);
1057};
1058
1062
1063 // We reserve the highest 4 bits as flags.
1064 static constexpr uint64_t FUNC_HASH_MASK = 0x0FFF'FFFF'FFFF'FFFF;
1065 // The 60th bit is for context sensitive profile record.
1066 static constexpr unsigned CS_FLAG_IN_FUNC_HASH = 60;
1067
1073 std::vector<uint64_t> Counts,
1074 std::vector<uint8_t> BitmapBytes)
1076 Hash(Hash) {}
1077
1079 return ((FuncHash >> CS_FLAG_IN_FUNC_HASH) & 1);
1080 }
1084};
1085
1087 uint32_t NumValueKinds = 0;
1088 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
1089 NumValueKinds += !(getValueSitesForKind(Kind).empty());
1090 return NumValueKinds;
1091}
1092
1094 uint32_t N = 0;
1095 for (const auto &SR : getValueSitesForKind(ValueKind))
1096 N += SR.ValueData.size();
1097 return N;
1098}
1099
1101 return getValueSitesForKind(ValueKind).size();
1102}
1103
1106 return getValueSitesForKind(ValueKind)[Site].ValueData;
1107}
1108
1110 if (!NumValueSites)
1111 return;
1112 getOrCreateValueSitesForKind(ValueKind).reserve(NumValueSites);
1113}
1114
1115// Include definitions for value profile data
1116#define INSTR_PROF_VALUE_PROF_DATA
1118
1121 ValueData, [](const InstrProfValueData &L, const InstrProfValueData &R) {
1122 return L.Count > R.Count;
1123 });
1124 // Now truncate
1125 size_t max_s = INSTR_PROF_MAX_NUM_VAL_PER_SITE;
1126 if (ValueData.size() > max_s)
1127 ValueData.resize(max_s);
1128}
1129
1130namespace IndexedInstrProf {
1131
1132enum class HashT : uint32_t {
1135};
1136
1138 switch (Type) {
1139 case HashT::MD5:
1140 return MD5Hash(K);
1141 }
1142 llvm_unreachable("Unhandled hash type");
1143}
1144
1145const uint64_t Magic = 0x8169666f72706cff; // "\xfflprofi\x81"
1146
1148 // Version 1 is the first version. In this version, the value of
1149 // a key/value pair can only include profile data of a single function.
1150 // Due to this restriction, the number of block counters for a given
1151 // function is not recorded but derived from the length of the value.
1153 // The version 2 format supports recording profile data of multiple
1154 // functions which share the same key in one value field. To support this,
1155 // the number block counters is recorded as an uint64_t field right after the
1156 // function structural hash.
1158 // Version 3 supports value profile data. The value profile data is expected
1159 // to follow the block counter profile data.
1161 // In this version, profile summary data \c IndexedInstrProf::Summary is
1162 // stored after the profile header.
1164 // In this version, the frontend PGO stable hash algorithm defaults to V2.
1166 // In this version, the frontend PGO stable hash algorithm got fixed and
1167 // may produce hashes different from Version5.
1169 // An additional counter is added around logical operators.
1171 // An additional (optional) memory profile type is added.
1173 // Binary ids are added.
1175 // An additional (optional) temporal profile traces section is added.
1177 // An additional field is used for bitmap bytes.
1179 // VTable profiling, decision record and bitmap are modified for mcdc.
1181 // In this version, the frontend PGO stable hash algorithm defaults to V4.
1183 // The current version is 13.
1185};
1187
1189
1191
1192// This structure defines the file header of the LLVM profile
1193// data file in indexed-format. Please update llvm/docs/InstrProfileFormat.rst
1194// as appropriate when updating the indexed profile format.
1195struct Header {
1197 // The lower 32 bits specify the version of the indexed profile.
1198 // The most significant 32 bits are reserved to specify the variant types of
1199 // the profile.
1201 uint64_t Unused = 0; // Becomes unused since version 4
1203 // This field records the offset of this hash table's metadata (i.e., the
1204 // number of buckets and entries), which follows right after the payload of
1205 // the entire hash table.
1211 // New fields should only be added at the end to ensure that the size
1212 // computation is correct. The methods below need to be updated to ensure that
1213 // the new field is read correctly.
1214
1215 // Reads a header struct from the buffer. Header fields are in machine native
1216 // endianness.
1217 LLVM_ABI static Expected<Header> readFromBuffer(const unsigned char *Buffer);
1218
1219 // Returns the size of the header in bytes for all valid fields based on the
1220 // version. I.e a older version header will return a smaller size.
1221 LLVM_ABI size_t size() const;
1222
1223 // Return the indexed profile version, i.e., the least significant 32 bits
1224 // in Header.Version.
1226};
1227
1228// Profile summary data recorded in the profile data file in indexed
1229// format. It is introduced in version 4. The summary data follows
1230// right after the profile file header.
1231struct Summary {
1232 struct Entry {
1233 uint64_t Cutoff; ///< The required percentile of total execution count.
1234 uint64_t
1235 MinBlockCount; ///< The minimum execution count for this percentile.
1236 uint64_t NumBlocks; ///< Number of blocks >= the minumum execution count.
1237 };
1238 // The field kind enumerator to assigned value mapping should remain
1239 // unchanged when a new kind is added or an old kind gets deleted in
1240 // the future.
1242 /// The total number of functions instrumented.
1244 /// Total number of instrumented blocks/edges.
1246 /// The maximal execution count among all functions.
1247 /// This field does not exist for profile data from IR based
1248 /// instrumentation.
1250 /// Max block count of the program.
1252 /// Max internal block count of the program (excluding entry blocks).
1254 /// The sum of all instrumented block counts.
1257 };
1258
1259 // The number of summmary fields following the summary header.
1261 // The number of Cutoff Entries (Summary::Entry) following summary fields.
1263
1264 Summary() = delete;
1265 Summary(uint32_t Size) { memset(this, 0, Size); }
1266
1267 void operator delete(void *ptr) { ::operator delete(ptr); }
1268
1270 return sizeof(Summary) + NumCutoffEntries * sizeof(Entry) +
1271 NumSumFields * sizeof(uint64_t);
1272 }
1273
1275 return reinterpret_cast<const uint64_t *>(this + 1);
1276 }
1277
1279 return reinterpret_cast<uint64_t *>(this + 1);
1280 }
1281
1282 const Entry *getCutoffEntryBase() const {
1283 return reinterpret_cast<const Entry *>(
1285 }
1286
1288 return reinterpret_cast<Entry *>(&getSummaryDataBase()[NumSummaryFields]);
1289 }
1290
1292 return getSummaryDataBase()[K];
1293 }
1294
1296 getSummaryDataBase()[K] = V;
1297 }
1298
1299 const Entry &getEntry(uint32_t I) const { return getCutoffEntryBase()[I]; }
1300
1302 Entry &ER = getCutoffEntryBase()[I];
1303 ER.Cutoff = E.Cutoff;
1304 ER.MinBlockCount = E.MinCount;
1305 ER.NumBlocks = E.NumCounts;
1306 }
1307};
1308
1309inline std::unique_ptr<Summary> allocSummary(uint32_t TotalSize) {
1310 return std::unique_ptr<Summary>(new (::operator new(TotalSize))
1311 Summary(TotalSize));
1312}
1313
1314} // end namespace IndexedInstrProf
1315
1316namespace RawInstrProf {
1317
1318// Version 1: First version
1319// Version 2: Added value profile data section. Per-function control data
1320// struct has more fields to describe value profile information.
1321// Version 3: Compressed name section support. Function PGO name reference
1322// from control data struct is changed from raw pointer to Name's MD5 value.
1323// Version 4: ValueDataBegin and ValueDataSizes fields are removed from the
1324// raw header.
1325// Version 5: Bit 60 of FuncHash is reserved for the flag for the context
1326// sensitive records.
1327// Version 6: Added binary id.
1328// Version 7: Reorder binary id and include version in signature.
1329// Version 8: Use relative counter pointer.
1330// Version 9: Added relative bitmap bytes pointer and count used by MC/DC.
1331// Version 10: Added vtable, a new type of value profile data.
1333
1334template <class IntPtrT> inline uint64_t getMagic();
1335template <> inline uint64_t getMagic<uint64_t>() {
1337}
1338
1339template <> inline uint64_t getMagic<uint32_t>() {
1341}
1342
1343// Per-function profile data header/control structure.
1344// The definition should match the structure defined in
1345// compiler-rt/lib/profile/InstrProfiling.h.
1346// It should also match the synthesized type in
1347// Transforms/Instrumentation/InstrProfiling.cpp:getOrCreateRegionCounters.
1348template <class IntPtrT> struct alignas(8) ProfileData {
1349#define INSTR_PROF_DATA(Type, LLVMType, Name, Init) Type Name;
1351};
1352
1353template <class IntPtrT> struct alignas(8) VTableProfileData {
1354#define INSTR_PROF_VTABLE_DATA(Type, LLVMType, Name, Init) Type Name;
1356};
1357
1358// File header structure of the LLVM profile data in raw format.
1359// The definition should match the header referenced in
1360// compiler-rt/lib/profile/InstrProfilingFile.c and
1361// InstrProfilingBuffer.c.
1362struct Header {
1363#define INSTR_PROF_RAW_HEADER(Type, Name, Init) const Type Name;
1365};
1366
1367} // end namespace RawInstrProf
1368
1369// Create the variable for the profile file name.
1370LLVM_ABI void createProfileFileNameVar(Module &M, StringRef InstrProfileOutput);
1371
1372// Whether to compress function names in profile records, and filenames in
1373// code coverage mappings. Used by the Instrumentation library and unit tests.
1375
1376} // end namespace llvm
1377#endif // LLVM_PROFILEDATA_INSTRPROF_H
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define LLVM_ABI
Definition Compiler.h:213
DXIL Finalize Linkage
This file defines the DenseMap class.
#define INSTR_PROF_QUOTE(x)
#define INSTR_PROF_RAW_MAGIC_32
#define INSTR_PROF_MAX_NUM_VAL_PER_SITE
#define INSTR_PROF_RAW_VERSION
#define INSTR_PROF_PROFILE_BITMAP_BIAS_VAR
#define INSTR_PROF_INDEX_VERSION
#define INSTR_PROF_PROFILE_COUNTER_BIAS_VAR
#define INSTR_PROF_VALUE_PROF_FUNC_STR
#define INSTR_PROF_RAW_MAGIC_64
#define INSTR_PROF_PROFILE_RUNTIME_VAR
#define INSTR_PROF_VALUE_PROF_MEMOP_FUNC_STR
This file implements a coalescing interval map for small objects.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define P(N)
This file contains some templates that are useful if you are working with the STL at all.
StringSet - A set-like wrapper for the StringMap.
Value * RHS
Value * LHS
The Input class is used to parse a yaml document into in-memory structs and vectors.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
Base class for user error types.
Definition Error.h:354
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
static ErrorSuccess success()
Create a success value.
Definition Error.h:336
Tagged union holding either a T or a Error.
Definition Error.h:485
LinkageTypes
An enumeration for the kinds of linkage for global values.
Definition GlobalValue.h:52
void log(raw_ostream &OS) const override
Print an error message to an output stream.
Definition InstrProf.h:461
static std::pair< instrprof_error, std::string > take(Error E)
Consume an Error and return the raw enum value contained within it, and the optional error message.
Definition InstrProf.h:473
const std::string & getMessage() const
Definition InstrProf.h:468
instrprof_error get() const
Definition InstrProf.h:467
std::error_code convertToErrorCode() const override
Convert this error to a std::error_code.
Definition InstrProf.h:463
std::string message() const override
Return the error message as a string.
InstrProfError(instrprof_error Err, const Twine &ErrStr=Twine())
Definition InstrProf.h:454
A symbol table used for function [IR]PGO name look-up with keys (such as pointers,...
Definition InstrProf.h:508
StringRef getFuncOrVarName(uint64_t ValMD5Hash) const
Return name of functions or global variables from the name's md5 hash value.
Definition InstrProf.h:780
static LLVM_ABI StringRef getCanonicalName(StringRef PGOName)
static bool isExternalSymbol(const StringRef &Symbol)
True if Symbol is the value used to represent external symbols.
Definition InstrProf.h:711
const std::vector< std::pair< uint64_t, Function * > > & getIDToNameMap() const
Definition InstrProf.h:670
Error addSymbolName(StringRef SymbolName)
Definition InstrProf.h:638
LLVM_ABI StringRef getFuncName(uint64_t FuncNameAddress, size_t NameSize) const
Return function's PGO name from the function name's symbol address in the object file.
InstrProfSymtab & operator=(InstrProfSymtab &&)=delete
GlobalVariable * getGlobalVariable(uint64_t MD5Hash) const
Return the global variable corresponding to md5 hash.
Definition InstrProf.h:800
StringRef getFuncOrVarNameIfDefined(uint64_t ValMD5Hash) const
Just like getFuncOrVarName, except that it will return literal string 'External Symbol' if the functi...
Definition InstrProf.h:773
void mapAddress(uint64_t Addr, uint64_t MD5Val)
Map a function address to its name's MD5 hash.
Definition InstrProf.h:678
Error addVTableName(StringRef VTableName)
Adds VTableName as a known symbol, and inserts it to a map that tracks all vtable names.
Definition InstrProf.h:660
std::vector< std::pair< uint64_t, uint64_t > > AddrHashMap
Definition InstrProf.h:510
LLVM_ABI void dumpNames(raw_ostream &OS) const
Dump the symbols in this table.
StringRef getNameData() const
Return the name section data.
Definition InstrProf.h:723
LLVM_ABI Error create(object::SectionRef &Section)
Create InstrProfSymtab from an object file section which contains function PGO names.
Error addFuncName(StringRef FuncName)
The method name is kept since there are many callers.
Definition InstrProf.h:656
void mapVTableAddress(uint64_t StartAddr, uint64_t EndAddr, uint64_t MD5Val)
Map the address range (i.e., [start_address, end_address)) of a variable to its names' MD5 hash.
Definition InstrProf.h:685
LLVM_ABI Error initVTableNamesFromCompressedStrings(StringRef CompressedVTableNames)
Initialize 'this' with the set of vtable names encoded in CompressedVTableNames.
const StringSet & getVTableNames() const
Definition InstrProf.h:674
LLVM_ABI uint64_t getVTableHashFromAddress(uint64_t Address) const
Return a vtable's hash, or 0 if the vtable doesn't exist in this SymTab.
Function * getFunction(uint64_t FuncMD5Hash) const
Return function from the name's md5 hash. Return nullptr if not found.
Definition InstrProf.h:790
InstrProfSymtab & operator=(const InstrProfSymtab &)=delete
InstrProfSymtab(InstrProfSymtab &&)=delete
InstrProfSymtab(const InstrProfSymtab &)=delete
LLVM_ABI uint64_t getFunctionHashFromAddress(uint64_t Address) const
Return a function's hash, or 0, if the function isn't in this SymTab.
Metadata node.
Definition Metadata.h:1080
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
MutableArrayRef - Represent a mutable reference to an array (0 or more elements consecutively in memo...
Definition ArrayRef.h:298
raw_ostream & OS
Definition InstrProf.h:87
LLVM_ABI uint64_t tell() const
LLVM_ABI void writeByte(uint8_t V)
LLVM_ABI void patch(ArrayRef< PatchItem > P)
LLVM_ABI void write32(uint32_t V)
support::endian::Writer LE
Definition InstrProf.h:88
LLVM_ABI ProfOStream(raw_fd_ostream &FD)
LLVM_ABI void write(uint64_t V)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:55
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:140
StringSet - A wrapper for StringMap that provides set-like functionality.
Definition StringSet.h:25
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
An efficient, type-erasing, non-owning reference to a callable.
This is a value type class that represents a single section in the list of sections in the object fil...
Definition ObjectFile.h:83
A raw_ostream that writes to a file descriptor.
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
A raw_ostream that writes to an std::string.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
std::unique_ptr< Summary > allocSummary(uint32_t TotalSize)
Definition InstrProf.h:1309
uint64_t ComputeHash(StringRef K)
Definition InstrProf.h:1190
const uint64_t Version
Definition InstrProf.h:1186
const uint64_t Magic
Definition InstrProf.h:1145
uint64_t getMagic()
const uint64_t Version
Definition InstrProf.h:1332
uint64_t getMagic< uint32_t >()
Definition InstrProf.h:1339
uint64_t getMagic< uint64_t >()
Definition InstrProf.h:1335
constexpr size_t NameSize
Definition XCOFF.h:30
uint64_t MD5Hash(const FunctionId &Obj)
Definition FunctionId.h:167
This is an optimization pass for GlobalISel generic memory operations.
FunctionAddr VTableAddr Value
Definition InstrProf.h:137
void stable_sort(R &&Range)
Definition STLExtras.h:2115
StringRef getInstrProfNameVarPrefix()
Return the name prefix of variables containing instrumented function names.
Definition InstrProf.h:126
LLVM_ABI std::string getPGOFuncName(const Function &F, bool InLTO=false, uint64_t Version=INSTR_PROF_INDEX_VERSION)
Please use getIRPGOFuncName for LLVM IR instrumentation.
StringRef getInstrProfRuntimeHookVarName()
Return the name of the hook variable defined in profile runtime library.
Definition InstrProf.h:197
LLVM_ABI void createPGOFuncNameMetadata(Function &F, StringRef PGOFuncName)
Create the PGOFuncName meta data if PGOFuncName is different from function's raw name.
LLVM_ABI std::string getIRPGOFuncName(const Function &F, bool InLTO=false)
std::error_code make_error_code(BitcodeError E)
StringRef getPGOFuncNameMetadataName()
Definition InstrProf.h:344
StringRef getCoverageMappingVarName()
Return the name of a covarage mapping variable (internal linkage) for each instrumented source module...
Definition InstrProf.h:155
void handleAllErrors(Error E, HandlerTs &&... Handlers)
Behaves the same as handleErrors, except that by contract all errors must be handled by the given han...
Definition Error.h:1013
StringRef getInstrProfBitmapVarPrefix()
Return the name prefix of profile bitmap variables.
Definition InstrProf.h:138
LLVM_ABI cl::opt< bool > DoInstrProfNameCompression
LLVM_ABI StringRef getFuncNameWithoutPrefix(StringRef PGOFuncName, StringRef FileName="<unknown>")
Given a PGO function name, remove the filename prefix and return the original (static) function name.
FuncHash
Definition InstrProf.h:78
LLVM_ABI void createPGONameMetadata(GlobalObject &GO, StringRef PGOName)
Create the PGOName metadata if a global object's PGO name is different from its mangled name.
StringRef getInstrProfVTableNamesVarName()
Definition InstrProf.h:150
LLVM_ABI std::pair< StringRef, StringRef > getParsedIRPGOName(StringRef IRPGOName)
auto unique(Range &&R, Predicate P)
Definition STLExtras.h:2133
LLVM_ABI MDNode * getPGOFuncNameMetadata(const Function &F)
Return the PGOFuncName meta data associated with a function.
StringRef getInstrProfDataVarPrefix()
Return the name prefix of variables containing per-function control data.
Definition InstrProf.h:132
StringRef getCoverageUnusedNamesVarName()
Return the name of the internal variable recording the array of PGO name vars referenced by the cover...
Definition InstrProf.h:163
LLVM_ABI std::string getInstrProfSectionName(InstrProfSectKind IPSK, Triple::ObjectFormatType OF, bool AddSegmentInfo=true)
Return the name of the profile section corresponding to IPSK.
uint64_t getInstrMaxCountValue()
Return the max count value. We reserver a few large values for special use.
Definition InstrProf.h:97
LLVM_ABI bool needsComdatForCounter(const GlobalObject &GV, const Module &M)
Check if we can use Comdat for profile variables.
LLVM_ABI std::string getPGOName(const GlobalVariable &V, bool InLTO=false)
StringRef getInstrProfInitFuncName()
Return the name of the runtime initialization method that is generated by the compiler.
Definition InstrProf.h:192
StringRef getInstrProfValuesVarPrefix()
Return the name prefix of value profile variables.
Definition InstrProf.h:141
StringRef getInstrProfCounterBiasVarName()
Definition InstrProf.h:207
LLVM_ABI GlobalVariable * createPGOFuncNameVar(Function &F, StringRef PGOFuncName)
Create and return the global variable for function name used in PGO instrumentation.
LLVM_ABI void annotateValueSite(Module &M, Instruction &Inst, const InstrProfRecord &InstrProfR, InstrProfValueKind ValueKind, uint32_t SiteIndx, uint32_t MaxMDCount=3)
Get the value profile data for value site SiteIdx from InstrProfR and annotate the instruction Inst w...
StringRef getInstrProfRuntimeHookVarUseFuncName()
Return the name of the compiler generated function that references the runtime hook variable.
Definition InstrProf.h:203
StringRef getInstrProfRegFuncsName()
Return the name of function that registers all the per-function control data at program startup time ...
Definition InstrProf.h:172
LLVM_ABI Error collectPGOFuncNameStrings(ArrayRef< GlobalVariable * > NameVars, std::string &Result, bool doCompression=true)
Produce Result string with the same format described above.
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1635
InstrProfSectKind
Definition InstrProf.h:91
LLVM_ABI Error readAndDecodeStrings(StringRef NameStrings, std::function< Error(StringRef)> NameCallback)
NameStrings is a string composed of one or more possibly encoded sub-strings.
StringRef getInstrProfCountersVarPrefix()
Return the name prefix of profile counter variables.
Definition InstrProf.h:135
FunctionAddr NumValueSites[IPVK_Last+1]
Definition InstrProf.h:93
LLVM_ABI StringRef getPGOFuncNameVarInitializer(GlobalVariable *NameVar)
Return the initializer in string of the PGO name var NameVar.
StringRef getInstrProfBitmapBiasVarName()
Definition InstrProf.h:211
StringRef getInstrProfNameSeparator()
Return the marker used to separate PGO names during serialization.
Definition InstrProf.h:216
LLVM_ABI SmallVector< InstrProfValueData, 4 > getValueProfDataFromInst(const Instruction &Inst, InstrProfValueKind ValueKind, uint32_t MaxNumValueData, uint64_t &TotalC, bool GetNoICPValue=false)
Extract the value profile data from Inst and returns them if Inst is annotated with value profile dat...
StringRef getInstrProfValueProfMemOpFuncName()
Return the name profile runtime entry point to do memop size value profiling.
Definition InstrProf.h:118
MutableArrayRef(T &OneElt) -> MutableArrayRef< T >
Error make_error(ArgTs &&... Args)
Make a Error instance representing failure using the given error info type.
Definition Error.h:340
@ Other
Any other memory.
Definition ModRef.h:68
instrprof_error
Definition InstrProf.h:401
InstrProfValueKind
Definition InstrProf.h:314
StringRef getInstrProfNamesRegFuncName()
Return the name of the runtime interface that registers the PGO name strings.
Definition InstrProf.h:184
auto lower_bound(R &&Range, T &&Value)
Provide wrappers to std::lower_bound which take ranges instead of having to pass begin/end explicitly...
Definition STLExtras.h:2051
LLVM_ABI const std::error_category & instrprof_category()
StringRef getInstrProfVarPrefix()
Return the prefix of the name of the variables to function as a filter.
Definition InstrProf.h:123
LLVM_ABI Error collectVTableStrings(ArrayRef< GlobalVariable * > VTables, std::string &Result, bool doCompression)
ArrayRef(const T &OneElt) -> ArrayRef< T >
LLVM_ABI bool canRenameComdatFunc(const Function &F, bool CheckAddressTaken=false)
Check if we can safely rename this Comdat function.
LLVM_ABI void createProfileFileNameVar(Module &M, StringRef InstrProfileOutput)
LLVM_ABI Error collectGlobalObjectNameStrings(ArrayRef< std::string > NameStrs, bool doCompression, std::string &Result)
Given a vector of strings (names of global objects like functions or, virtual tables) NameStrs,...
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1916
StringRef getInstrProfValueProfFuncName()
Return the name profile runtime entry point to do value profiling for a given site.
Definition InstrProf.h:112
StringRef getInstrProfRegFuncName()
Return the name of the runtime interface that registers per-function control data for one instrumente...
Definition InstrProf.h:178
LLVM_ABI std::string getPGOFuncNameVarName(StringRef FuncName, GlobalValue::LinkageTypes Linkage)
Return the name of the global variable used to store a function name in PGO instrumentation.
StringRef getInstrProfNamesVarName()
Return the name of the variable holding the strings (possibly compressed) of all function's PGO names...
Definition InstrProf.h:148
LogicalResult success(bool IsSuccess=true)
Utility function to generate a LogicalResult.
LLVM_ABI bool isGPUProfTarget(const Module &M)
Determines whether module targets a GPU eligable for PGO instrumentation.
LLVM_ABI bool isIRPGOFlagSet(const Module *M)
Check if INSTR_PROF_RAW_VERSION_VAR is defined.
StringRef getPGONameMetadataName()
Definition InstrProf.h:346
StringRef getInstrProfVNodesVarName()
Return the name of value profile node array variables:
Definition InstrProf.h:144
StringRef getInstrProfVTableVarPrefix()
Return the name prefix of variables containing virtual table profile data.
Definition InstrProf.h:129
InstrProfKind
An enum describing the attributes of an instrumented profile.
Definition InstrProf.h:376
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:870
#define N
std::array< double, IPVK_Last - IPVK_First+1 > ValueCounts
Definition InstrProf.h:809
LLVM_ABI uint64_t getIndexedProfileVersion() const
LLVM_ABI size_t size() const
static LLVM_ABI Expected< Header > readFromBuffer(const unsigned char *Buffer)
uint64_t Cutoff
The required percentile of total execution count.
Definition InstrProf.h:1233
uint64_t NumBlocks
Number of blocks >= the minumum execution count.
Definition InstrProf.h:1236
uint64_t MinBlockCount
The minimum execution count for this percentile.
Definition InstrProf.h:1235
const Entry * getCutoffEntryBase() const
Definition InstrProf.h:1282
uint64_t get(SummaryFieldKind K) const
Definition InstrProf.h:1291
void set(SummaryFieldKind K, uint64_t V)
Definition InstrProf.h:1295
void setEntry(uint32_t I, const ProfileSummaryEntry &E)
Definition InstrProf.h:1301
@ TotalNumFunctions
The total number of functions instrumented.
Definition InstrProf.h:1243
@ TotalNumBlocks
Total number of instrumented blocks/edges.
Definition InstrProf.h:1245
@ MaxFunctionCount
The maximal execution count among all functions.
Definition InstrProf.h:1249
@ TotalBlockCount
The sum of all instrumented block counts.
Definition InstrProf.h:1255
@ MaxBlockCount
Max block count of the program.
Definition InstrProf.h:1251
@ MaxInternalBlockCount
Max internal block count of the program (excluding entry blocks).
Definition InstrProf.h:1253
const uint64_t * getSummaryDataBase() const
Definition InstrProf.h:1274
static uint32_t getSize(uint32_t NumSumFields, uint32_t NumCutoffEntries)
Definition InstrProf.h:1269
const Entry & getEntry(uint32_t I) const
Definition InstrProf.h:1299
Profiling information for a single function.
Definition InstrProf.h:897
LLVM_ABI void overlapValueProfData(uint32_t ValueKind, InstrProfRecord &Src, OverlapStats &Overlap, OverlapStats &FuncLevelOverlap)
Compute the overlap of value profile counts.
std::vector< uint64_t > Counts
Definition InstrProf.h:898
ArrayRef< InstrProfValueData > getValueArrayForSite(uint32_t ValueKind, uint32_t Site) const
Return the array of profiled values at Site.
Definition InstrProf.h:1105
CountPseudoKind getCountPseudoKind() const
Definition InstrProf.h:996
InstrProfRecord(std::vector< uint64_t > Counts)
Definition InstrProf.h:902
LLVM_ABI void accumulateCounts(CountSumOrPercent &Sum) const
Compute the sums of all counts and store in Sum.
uint32_t getNumValueSites(uint32_t ValueKind) const
Return the number of instrumented sites for ValueKind.
Definition InstrProf.h:1100
uint32_t getNumValueKinds() const
Return the number of value profile kinds with non-zero number of profile sites.
Definition InstrProf.h:1086
void setPseudoCount(CountPseudoKind Kind)
Definition InstrProf.h:1004
InstrProfRecord(InstrProfRecord &&)=default
uint32_t getNumValueData(uint32_t ValueKind) const
Return the total number of ValueData for ValueKind.
Definition InstrProf.h:1093
LLVM_ABI void merge(InstrProfRecord &Other, uint64_t Weight, function_ref< void(instrprof_error)> Warn)
Merge the counts in Other into this one.
LLVM_ABI void addValueData(uint32_t ValueKind, uint32_t Site, ArrayRef< InstrProfValueData > VData, InstrProfSymtab *SymTab)
Add ValueData for ValueKind at value Site.
InstrProfRecord & operator=(const InstrProfRecord &RHS)
Definition InstrProf.h:913
void clearValueData()
Clear value data entries.
Definition InstrProf.h:973
InstrProfRecord(const InstrProfRecord &RHS)
Definition InstrProf.h:907
InstrProfRecord(std::vector< uint64_t > Counts, std::vector< uint8_t > BitmapBytes)
Definition InstrProf.h:903
void reserveSites(uint32_t ValueKind, uint32_t NumValueSites)
Reserve space for NumValueSites sites.
Definition InstrProf.h:1109
LLVM_ABI void overlap(InstrProfRecord &Other, OverlapStats &Overlap, OverlapStats &FuncLevelOverlap, uint64_t ValueCutoff)
Compute the overlap b/w this IntrprofRecord and Other.
void sortValueData()
Sort value profile data (per site) by count.
Definition InstrProf.h:960
std::vector< uint8_t > BitmapBytes
Definition InstrProf.h:899
InstrProfRecord & operator=(InstrProfRecord &&)=default
void Clear()
Clear value data entries and edge counters.
Definition InstrProf.h:967
LLVM_ABI void scale(uint64_t N, uint64_t D, function_ref< void(instrprof_error)> Warn)
Scale up profile counts (including value profile data) by a factor of (N / D).
void sortByCount()
Sort ValueData Descending by Count.
Definition InstrProf.h:1119
InstrProfValueSiteRecord(std::vector< InstrProfValueData > &&VD)
Definition InstrProf.h:870
void sortByTargetValues()
Sort ValueData ascending by Value.
Definition InstrProf.h:874
std::vector< InstrProfValueData > ValueData
Value profiling data pairs at a given value site.
Definition InstrProf.h:867
LLVM_ABI void merge(InstrProfValueSiteRecord &Input, uint64_t Weight, function_ref< void(instrprof_error)> Warn)
Merge data from another InstrProfValueSiteRecord Optionally scale merged counts by Weight.
LLVM_ABI void overlap(InstrProfValueSiteRecord &Input, uint32_t ValueKind, OverlapStats &Overlap, OverlapStats &FuncLevelOverlap)
Compute the overlap b/w this record and Input record.
LLVM_ABI void scale(uint64_t N, uint64_t D, function_ref< void(instrprof_error)> Warn)
Scale up value profile data counts by N (Numerator) / D (Denominator).
static bool hasCSFlagInHash(uint64_t FuncHash)
Definition InstrProf.h:1078
NamedInstrProfRecord(StringRef Name, uint64_t Hash, std::vector< uint64_t > Counts)
Definition InstrProf.h:1069
NamedInstrProfRecord(StringRef Name, uint64_t Hash, std::vector< uint64_t > Counts, std::vector< uint8_t > BitmapBytes)
Definition InstrProf.h:1072
static void setCSFlagInHash(uint64_t &FuncHash)
Definition InstrProf.h:1081
static constexpr uint64_t FUNC_HASH_MASK
Definition InstrProf.h:1064
static constexpr unsigned CS_FLAG_IN_FUNC_HASH
Definition InstrProf.h:1066
const std::string NameFilter
Definition InstrProf.h:862
LLVM_ABI void addOneMismatch(const CountSumOrPercent &MismatchFunc)
static double score(uint64_t Val1, uint64_t Val2, double Sum1, double Sum2)
Definition InstrProf.h:850
LLVM_ABI Error accumulateCounts(const std::string &BaseFilename, const std::string &TestFilename, bool IsCS)
LLVM_ABI void dump(raw_fd_ostream &OS) const
CountSumOrPercent Overlap
Definition InstrProf.h:826
CountSumOrPercent Base
Definition InstrProf.h:822
LLVM_ABI void addOneUnique(const CountSumOrPercent &UniqueFunc)
const std::string * BaseFilename
Definition InstrProf.h:830
const std::string * TestFilename
Definition InstrProf.h:831
void setFuncInfo(StringRef Name, uint64_t Hash)
Definition InstrProf.h:840
CountSumOrPercent Unique
Definition InstrProf.h:828
CountSumOrPercent Mismatch
Definition InstrProf.h:827
StringRef FuncName
Definition InstrProf.h:832
OverlapStatsLevel Level
Definition InstrProf.h:829
OverlapStats(OverlapStatsLevel L=ProgramLevel)
Definition InstrProf.h:836
CountSumOrPercent Test
Definition InstrProf.h:824
uint64_t Pos
Definition InstrProf.h:63
ArrayRef< uint64_t > D
Definition InstrProf.h:64
FunctionAddr VTableAddr uintptr_t uintptr_t Version
Definition InstrProf.h:334
static LLVM_ABI void createBPFunctionNodes(ArrayRef< TemporalProfTraceTy > Traces, std::vector< BPFunctionNode > &Nodes, bool RemoveOutlierUNs=true)
Use a set of temporal profile traces to create a list of balanced partitioning function nodes used by...
std::vector< uint64_t > FunctionNameRefs
Definition InstrProf.h:433
TemporalProfTraceTy(std::initializer_list< uint64_t > Trace={}, uint64_t Weight=1)
Definition InstrProf.h:435
Per-function header/control data structure for value profiling data in indexed format.
Definition InstrProf.h:456
Function object to check whether the first component of a container supported by std::get (like std::...
Definition STLExtras.h:1438
Adapter to write values to a stream in a particular byte order.