LLVM 22.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 name prefix of variables containing instrumented function names.
123inline StringRef getInstrProfNameVarPrefix() { return "__profn_"; }
124
125/// Return the name prefix of variables containing virtual table profile data.
126inline StringRef getInstrProfVTableVarPrefix() { return "__profvt_"; }
127
128/// Return the name prefix of variables containing per-function control data.
129inline StringRef getInstrProfDataVarPrefix() { return "__profd_"; }
130
131/// Return the name prefix of profile counter variables.
132inline StringRef getInstrProfCountersVarPrefix() { return "__profc_"; }
133
134/// Return the name prefix of profile bitmap variables.
135inline StringRef getInstrProfBitmapVarPrefix() { return "__profbm_"; }
136
137/// Return the name prefix of value profile variables.
138inline StringRef getInstrProfValuesVarPrefix() { return "__profvp_"; }
140/// Return the name of value profile node array variables:
141inline StringRef getInstrProfVNodesVarName() { return "__llvm_prf_vnodes"; }
143/// Return the name of the variable holding the strings (possibly compressed)
144/// of all function's PGO names.
145inline StringRef getInstrProfNamesVarName() { return "__llvm_prf_nm"; }
146
147inline StringRef getInstrProfVTableNamesVarName() { return "__llvm_prf_vnm"; }
148
149/// Return the name of a covarage mapping variable (internal linkage)
150/// for each instrumented source module. Such variables are allocated
151/// in the __llvm_covmap section.
153 return "__llvm_coverage_mapping";
154}
156/// Return the name of the internal variable recording the array
157/// of PGO name vars referenced by the coverage mapping. The owning
158/// functions of those names are not emitted by FE (e.g, unused inline
159/// functions.)
161 return "__llvm_coverage_names";
162}
164/// Return the name of function that registers all the per-function control
165/// data at program startup time by calling __llvm_register_function. This
166/// function has internal linkage and is called by __llvm_profile_init
167/// runtime method. This function is not generated for these platforms:
168/// Darwin, Linux, and FreeBSD.
170 return "__llvm_profile_register_functions";
171}
172
173/// Return the name of the runtime interface that registers per-function control
174/// data for one instrumented function.
176 return "__llvm_profile_register_function";
177}
178
179/// Return the name of the runtime interface that registers the PGO name
180/// strings.
182 return "__llvm_profile_register_names_function";
183}
184
185/// Return the name of the runtime initialization method that is generated by
186/// the compiler. The function calls __llvm_profile_register_functions and
187/// __llvm_profile_override_default_filename functions if needed. This function
188/// has internal linkage and invoked at startup time via init_array.
189inline StringRef getInstrProfInitFuncName() { return "__llvm_profile_init"; }
190
191/// Return the name of the hook variable defined in profile runtime library.
192/// A reference to the variable causes the linker to link in the runtime
193/// initialization module (which defines the hook variable).
197
198/// Return the name of the compiler generated function that references the
199/// runtime hook variable. The function is a weak global.
201 return "__llvm_profile_runtime_user";
202}
203
207
211
212/// Return the marker used to separate PGO names during serialization.
213inline StringRef getInstrProfNameSeparator() { return "\01"; }
214
215/// Determines whether module targets a GPU eligable for PGO
216/// instrumentation
217LLVM_ABI bool isGPUProfTarget(const Module &M);
218
219/// Please use getIRPGOFuncName for LLVM IR instrumentation. This function is
220/// for front-end (Clang, etc) instrumentation.
221/// Return the modified name for function \c F suitable to be
222/// used the key for profile lookup. Variable \c InLTO indicates if this
223/// is called in LTO optimization passes.
224LLVM_ABI std::string
225getPGOFuncName(const Function &F, bool InLTO = false,
227
228/// Return the modified name for a function suitable to be
229/// used the key for profile lookup. The function's original
230/// name is \c RawFuncName and has linkage of type \c Linkage.
231/// The function is defined in module \c FileName.
232LLVM_ABI std::string
234 StringRef FileName, uint64_t Version = INSTR_PROF_INDEX_VERSION);
235
236/// \return the modified name for function \c F suitable to be
237/// used as the key for IRPGO profile lookup. \c InLTO indicates if this is
238/// called from LTO optimization passes.
239LLVM_ABI std::string getIRPGOFuncName(const Function &F, bool InLTO = false);
240
241/// \return the filename and the function name parsed from the output of
242/// \c getIRPGOFuncName()
243LLVM_ABI std::pair<StringRef, StringRef>
244getParsedIRPGOName(StringRef IRPGOName);
245
246/// Return the name of the global variable used to store a function
247/// name in PGO instrumentation. \c FuncName is the IRPGO function name
248/// (returned by \c getIRPGOFuncName) for LLVM IR instrumentation and PGO
249/// function name (returned by \c getPGOFuncName) for front-end instrumentation.
250LLVM_ABI std::string getPGOFuncNameVarName(StringRef FuncName,
252
253/// Create and return the global variable for function name used in PGO
254/// instrumentation. \c FuncName is the IRPGO function name (returned by
255/// \c getIRPGOFuncName) for LLVM IR instrumentation and PGO function name
256/// (returned by \c getPGOFuncName) for front-end instrumentation.
257LLVM_ABI GlobalVariable *createPGOFuncNameVar(Function &F,
258 StringRef PGOFuncName);
259
260/// Create and return the global variable for function name used in PGO
261/// instrumentation. \c FuncName is the IRPGO function name (returned by
262/// \c getIRPGOFuncName) for LLVM IR instrumentation and PGO function name
263/// (returned by \c getPGOFuncName) for front-end instrumentation.
264LLVM_ABI GlobalVariable *createPGOFuncNameVar(Module &M,
266 StringRef PGOFuncName);
268/// Return the initializer in string of the PGO name var \c NameVar.
271/// Given a PGO function name, remove the filename prefix and return
272/// the original (static) function name.
274 StringRef FileName = "<unknown>");
275
276/// Given a vector of strings (names of global objects like functions or,
277/// virtual tables) \c NameStrs, the method generates a combined string \c
278/// Result that is ready to be serialized. The \c Result string is comprised of
279/// three fields: The first field is the length of the uncompressed strings, and
280/// the the second field is the length of the zlib-compressed string. Both
281/// fields are encoded in ULEB128. If \c doCompress is false, the
282/// third field is the uncompressed strings; otherwise it is the
283/// compressed string. When the string compression is off, the
284/// second field will have value zero.
286 bool doCompression,
287 std::string &Result);
288
289/// Produce \c Result string with the same format described above. The input
290/// is vector of PGO function name variables that are referenced.
291/// The global variable element in 'NameVars' is a string containing the pgo
292/// name of a function. See `createPGOFuncNameVar` that creates these global
293/// variables.
295 std::string &Result,
296 bool doCompression = true);
299 std::string &Result, bool doCompression);
301/// Check if INSTR_PROF_RAW_VERSION_VAR is defined. This global is only being
302/// set in IR PGO compilation.
304
305/// Check if we can safely rename this Comdat function. Instances of the same
306/// comdat function may have different control flows thus can not share the
307/// same counter variable.
309 bool CheckAddressTaken = false);
310
312#define VALUE_PROF_KIND(Enumerator, Value, Descr) Enumerator = Value,
314};
316/// Get the value profile data for value site \p SiteIdx from \p InstrProfR
317/// and annotate the instruction \p Inst with the value profile meta data.
318/// Annotate up to \p MaxMDCount (default 3) number of records per value site.
320 const InstrProfRecord &InstrProfR,
321 InstrProfValueKind ValueKind, uint32_t SiteIndx,
322 uint32_t MaxMDCount = 3);
323
324/// Same as the above interface but using an ArrayRef, as well as \p Sum.
325/// This function will not annotate !prof metadata on the instruction if the
326/// referenced array is empty.
329 InstrProfValueKind ValueKind,
330 uint32_t MaxMDCount);
331
332// TODO: Unify metadata name 'PGOFuncName' and 'PGOName', by supporting read
333// of this metadata for backward compatibility and generating 'PGOName' only.
334/// Extract the value profile data from \p Inst and returns them if \p Inst is
335/// annotated with value profile data. Returns an empty vector otherwise.
338 uint32_t MaxNumValueData, uint64_t &TotalC,
339 bool GetNoICPValue = false);
340
341inline StringRef getPGOFuncNameMetadataName() { return "PGOFuncName"; }
342
343inline StringRef getPGONameMetadataName() { return "PGOName"; }
344
345/// Return the PGOFuncName meta data associated with a function.
346LLVM_ABI MDNode *getPGOFuncNameMetadata(const Function &F);
347
348LLVM_ABI std::string getPGOName(const GlobalVariable &V, bool InLTO = false);
349
350/// Create the PGOFuncName meta data if PGOFuncName is different from
351/// function's raw name. This should only apply to internal linkage functions
352/// declared by users only.
353/// TODO: Update all callers to 'createPGONameMetadata' and deprecate this
354/// function.
355LLVM_ABI void createPGOFuncNameMetadata(Function &F, StringRef PGOFuncName);
356
357/// Create the PGOName metadata if a global object's PGO name is different from
358/// its mangled name. This should apply to local-linkage global objects only.
359LLVM_ABI void createPGONameMetadata(GlobalObject &GO, StringRef PGOName);
360
361/// Check if we can use Comdat for profile variables. This will eliminate
362/// the duplicated profile variables for Comdat functions.
363LLVM_ABI bool needsComdatForCounter(const GlobalObject &GV, const Module &M);
364
365/// \c NameStrings is a string composed of one or more possibly encoded
366/// sub-strings. The substrings are separated by `\01` (returned by
367/// InstrProf.h:getInstrProfNameSeparator). This method decodes the string and
368/// calls `NameCallback` for each substring.
370 StringRef NameStrings, std::function<Error(StringRef)> NameCallback);
371
372/// An enum describing the attributes of an instrumented profile.
373enum class InstrProfKind {
374 Unknown = 0x0,
375 // A frontend clang profile, incompatible with other attrs.
377 // An IR-level profile (default when -fprofile-generate is used).
379 // A profile with entry basic block instrumentation.
381 // A context sensitive IR-level profile.
383 // Use single byte probes for coverage.
385 // Only instrument the function entry basic block.
387 // A memory profile collected using -fprofile=memory.
388 MemProf = 0x40,
389 // A temporal profile.
391 // A profile with loop entry basic blocks instrumentation.
394};
395
396LLVM_ABI const std::error_category &instrprof_category();
397
426
427/// An ordered list of functions identified by their NameRef found in
428/// INSTR_PROF_DATA
430 std::vector<uint64_t> FunctionNameRefs;
432 TemporalProfTraceTy(std::initializer_list<uint64_t> Trace = {},
433 uint64_t Weight = 1)
435
436 /// Use a set of temporal profile traces to create a list of balanced
437 /// partitioning function nodes used by BalancedPartitioning to generate a
438 /// function order that reduces page faults during startup
439 LLVM_ABI static void
441 std::vector<BPFunctionNode> &Nodes,
442 bool RemoveOutlierUNs = true);
443};
444
445inline std::error_code make_error_code(instrprof_error E) {
446 return std::error_code(static_cast<int>(E), instrprof_category());
447}
448
449class LLVM_ABI InstrProfError : public ErrorInfo<InstrProfError> {
450public:
452 : Err(Err), Msg(ErrStr.str()) {
453 assert(Err != instrprof_error::success && "Not an error");
454 }
455
456 std::string message() const override;
457
458 void log(raw_ostream &OS) const override { OS << message(); }
459
460 std::error_code convertToErrorCode() const override {
461 return make_error_code(Err);
462 }
463
464 instrprof_error get() const { return Err; }
465 const std::string &getMessage() const { return Msg; }
466
467 /// Consume an Error and return the raw enum value contained within it, and
468 /// the optional error message. The Error must either be a success value, or
469 /// contain a single InstrProfError.
470 static std::pair<instrprof_error, std::string> take(Error E) {
471 auto Err = instrprof_error::success;
472 std::string Msg = "";
473 handleAllErrors(std::move(E), [&Err, &Msg](const InstrProfError &IPE) {
474 assert(Err == instrprof_error::success && "Multiple errors encountered");
475 Err = IPE.get();
476 Msg = IPE.getMessage();
477 });
478 return {Err, Msg};
479 }
480
481 static char ID;
482
483private:
484 instrprof_error Err;
485 std::string Msg;
486};
487
488namespace object {
489
490class SectionRef;
492} // end namespace object
493
495
497
498} // end namespace IndexedInstrProf
499
500/// A symbol table used for function [IR]PGO name look-up with keys
501/// (such as pointers, md5hash values) to the function. A function's
502/// [IR]PGO name or name's md5hash are used in retrieving the profile
503/// data of the function. See \c getIRPGOFuncName() and \c getPGOFuncName
504/// methods for details how [IR]PGO name is formed.
506public:
507 using AddrHashMap = std::vector<std::pair<uint64_t, uint64_t>>;
509 // Returns the canonical name of the given PGOName. In a canonical name, all
510 // suffixes that begins with "." except ".__uniq." are stripped.
511 // FIXME: Unify this with `FunctionSamples::getCanonicalFnName`.
513
514private:
515 using AddrIntervalMap =
518 uint64_t Address = 0;
519 // Unique name strings. Used to ensure entries in MD5NameMap (a vector that's
520 // going to be sorted) has unique MD5 keys in the first place.
521 StringSet<> NameTab;
522 // Records the unique virtual table names. This is used by InstrProfWriter to
523 // write out an on-disk chained hash table of virtual table names.
524 // InstrProfWriter stores per function profile data (keyed by function names)
525 // so it doesn't use a StringSet for function names.
526 StringSet<> VTableNames;
527 // A map from MD5 keys to function name strings.
528 mutable std::vector<std::pair<uint64_t, StringRef>> MD5NameMap;
529 // A map from MD5 keys to function define. We only populate this map
530 // when build the Symtab from a Module.
531 mutable std::vector<std::pair<uint64_t, Function *>> MD5FuncMap;
532 // A map from MD5 to the global variable. This map is only populated when
533 // building the symtab from a module. Use separate container instances for
534 // `MD5FuncMap` and `MD5VTableMap`.
535 // TODO: Unify the container type and the lambda function 'mapName' inside
536 // add{Func,VTable}WithName.
537 mutable DenseMap<uint64_t, GlobalVariable *> MD5VTableMap;
538 // A map from function runtime address to function name MD5 hash.
539 // This map is only populated and used by raw instr profile reader.
540 mutable AddrHashMap AddrToMD5Map;
541
542 AddrIntervalMap::Allocator VTableAddrMapAllocator;
543 // This map is only populated and used by raw instr profile reader.
544 AddrIntervalMap VTableAddrMap;
545
546 // "dirty" flag for the rest of the mutable state. lookup APIs (like
547 // getFunction) need the mutable state to be sorted.
548 mutable bool Sorted = false;
549
550 static StringRef getExternalSymbol() { return "** External Symbol **"; }
551
552 // Add the function into the symbol table, by creating the following
553 // map entries:
554 // name-set = {PGOFuncName} union {getCanonicalName(PGOFuncName)}
555 // - In MD5NameMap: <MD5Hash(name), name> for name in name-set
556 // - In MD5FuncMap: <MD5Hash(name), &F> for name in name-set
557 // The canonical name is only added if \c AddCanonical is true.
558 Error addFuncWithName(Function &F, StringRef PGOFuncName, bool AddCanonical);
559
560 // Add the vtable into the symbol table, by creating the following
561 // map entries:
562 // name-set = {PGOName} union {getCanonicalName(PGOName)}
563 // - In MD5NameMap: <MD5Hash(name), name> for name in name-set
564 // - In MD5VTableMap: <MD5Hash(name), name> for name in name-set
565 Error addVTableWithName(GlobalVariable &V, StringRef PGOVTableName);
566
567 // If the symtab is created by a series of calls to \c addFuncName, \c
568 // finalizeSymtab needs to be called before looking up function names.
569 // This is required because the underlying map is a vector (for space
570 // efficiency) which needs to be sorted. The API is `const` because it's part
571 // of the implementation detail of `const` APIs that need to first ensure this
572 // property of ordering on the other mutable state.
573 inline void finalizeSymtab() const;
574
575public:
576 InstrProfSymtab() : VTableAddrMap(VTableAddrMapAllocator) {}
577
578 // Not copyable or movable.
579 // Consider std::unique_ptr for move.
584
585 /// Create InstrProfSymtab from an object file section which
586 /// contains function PGO names. When section may contain raw
587 /// string data or string data in compressed form. This method
588 /// only initialize the symtab with reference to the data and
589 /// the section base address. The decompression will be delayed
590 /// until before it is used. See also \c create(StringRef) method.
592
593 /// \c NameStrings is a string composed of one of more sub-strings
594 /// encoded in the format described in \c collectPGOFuncNameStrings.
595 /// This method is a wrapper to \c readAndDecodeStrings method.
596 LLVM_ABI Error create(StringRef NameStrings);
597
598 /// Initialize symtab states with function names and vtable names. \c
599 /// FuncNameStrings is a string composed of one or more encoded function name
600 /// strings, and \c VTableNameStrings composes of one or more encoded vtable
601 /// names. This interface is solely used by raw profile reader.
602 LLVM_ABI Error create(StringRef FuncNameStrings, StringRef VTableNameStrings);
603
604 /// Initialize 'this' with the set of vtable names encoded in
605 /// \c CompressedVTableNames.
607 initVTableNamesFromCompressedStrings(StringRef CompressedVTableNames);
608
609 /// This interface is used by reader of CoverageMapping test
610 /// format.
611 inline Error create(StringRef D, uint64_t BaseAddr);
612
613 /// A wrapper interface to populate the PGO symtab with functions
614 /// decls from module \c M. This interface is used by transformation
615 /// passes such as indirect function call promotion. Variable \c InLTO
616 /// indicates if this is called from LTO optimization passes.
617 /// A canonical name, removing non-__uniq suffixes, is added if
618 /// \c AddCanonical is true.
619 LLVM_ABI Error create(Module &M, bool InLTO = false,
620 bool AddCanonical = true);
621
622 /// Create InstrProfSymtab from a set of names iteratable from
623 /// \p IterRange. This interface is used by IndexedProfReader.
624 template <typename NameIterRange>
625 Error create(const NameIterRange &IterRange);
626
627 /// Create InstrProfSymtab from a set of function names and vtable
628 /// names iteratable from \p IterRange. This interface is used by
629 /// IndexedProfReader.
630 template <typename FuncNameIterRange, typename VTableNameIterRange>
631 Error create(const FuncNameIterRange &FuncIterRange,
632 const VTableNameIterRange &VTableIterRange);
633
634 // Map the MD5 of the symbol name to the name.
636 if (SymbolName.empty())
638 "symbol name is empty");
639
640 // Insert into NameTab so that MD5NameMap (a vector that will be sorted)
641 // won't have duplicated entries in the first place.
642 auto Ins = NameTab.insert(SymbolName);
643 if (Ins.second) {
644 MD5NameMap.push_back(std::make_pair(
645 IndexedInstrProf::ComputeHash(SymbolName), Ins.first->getKey()));
646 Sorted = false;
647 }
648 return Error::success();
649 }
650
651 /// The method name is kept since there are many callers.
652 /// It just forwards to 'addSymbolName'.
653 Error addFuncName(StringRef FuncName) { return addSymbolName(FuncName); }
654
655 /// Adds VTableName as a known symbol, and inserts it to a map that
656 /// tracks all vtable names.
658 if (Error E = addSymbolName(VTableName))
659 return E;
660
661 // Record VTableName. InstrProfWriter uses this set. The comment around
662 // class member explains why.
663 VTableNames.insert(VTableName);
664 return Error::success();
665 }
666
667 const std::vector<std::pair<uint64_t, Function *>> &getIDToNameMap() const {
668 return MD5FuncMap;
669 }
670
671 const StringSet<> &getVTableNames() const { return VTableNames; }
672
673 /// Map a function address to its name's MD5 hash. This interface
674 /// is only used by the raw profiler reader.
675 void mapAddress(uint64_t Addr, uint64_t MD5Val) {
676 AddrToMD5Map.push_back(std::make_pair(Addr, MD5Val));
677 }
678
679 /// Map the address range (i.e., [start_address, end_address)) of a variable
680 /// to its names' MD5 hash. This interface is only used by the raw profile
681 /// reader.
682 void mapVTableAddress(uint64_t StartAddr, uint64_t EndAddr, uint64_t MD5Val) {
683 VTableAddrMap.insert(StartAddr, EndAddr, MD5Val);
684 }
685
686 /// Return a function's hash, or 0, if the function isn't in this SymTab.
688
689 /// Return a vtable's hash, or 0 if the vtable doesn't exist in this SymTab.
691
692 /// Return function's PGO name from the function name's symbol
693 /// address in the object file. If an error occurs, return
694 /// an empty string.
695 LLVM_ABI StringRef getFuncName(uint64_t FuncNameAddress,
696 size_t NameSize) const;
697
698 /// Return name of functions or global variables from the name's md5 hash
699 /// value. If not found, return an empty string.
700 inline StringRef getFuncOrVarName(uint64_t ValMD5Hash) const;
701
702 /// Just like getFuncOrVarName, except that it will return literal string
703 /// 'External Symbol' if the function or global variable is external to
704 /// this symbol table.
705 inline StringRef getFuncOrVarNameIfDefined(uint64_t ValMD5Hash) const;
706
707 /// True if Symbol is the value used to represent external symbols.
708 static bool isExternalSymbol(const StringRef &Symbol) {
709 return Symbol == InstrProfSymtab::getExternalSymbol();
710 }
711
712 /// Return function from the name's md5 hash. Return nullptr if not found.
713 inline Function *getFunction(uint64_t FuncMD5Hash) const;
714
715 /// Return the global variable corresponding to md5 hash. Return nullptr if
716 /// not found.
718
719 /// Return the name section data.
720 inline StringRef getNameData() const { return Data; }
721
722 /// Dump the symbols in this table.
723 LLVM_ABI void dumpNames(raw_ostream &OS) const;
724};
725
727 Data = D;
728 Address = BaseAddr;
729 return Error::success();
730}
731
732template <typename NameIterRange>
733Error InstrProfSymtab::create(const NameIterRange &IterRange) {
734 for (auto Name : IterRange)
735 if (Error E = addFuncName(Name))
736 return E;
737
738 finalizeSymtab();
739 return Error::success();
740}
741
742template <typename FuncNameIterRange, typename VTableNameIterRange>
743Error InstrProfSymtab::create(const FuncNameIterRange &FuncIterRange,
744 const VTableNameIterRange &VTableIterRange) {
745 // Iterate elements by StringRef rather than by const reference.
746 // StringRef is small enough, so the loop is efficient whether
747 // element in the range is std::string or StringRef.
748 for (StringRef Name : FuncIterRange)
749 if (Error E = addFuncName(Name))
750 return E;
751
752 for (StringRef VTableName : VTableIterRange)
753 if (Error E = addVTableName(VTableName))
754 return E;
755
756 finalizeSymtab();
757 return Error::success();
758}
759
760void InstrProfSymtab::finalizeSymtab() const {
761 if (Sorted)
762 return;
763 llvm::sort(MD5NameMap, less_first());
764 llvm::sort(MD5FuncMap, less_first());
765 llvm::sort(AddrToMD5Map, less_first());
766 AddrToMD5Map.erase(llvm::unique(AddrToMD5Map), AddrToMD5Map.end());
767 Sorted = true;
768}
769
772 if (Ret.empty())
773 return InstrProfSymtab::getExternalSymbol();
774 return Ret;
775}
776
778 finalizeSymtab();
779 auto Result = llvm::lower_bound(MD5NameMap, MD5Hash,
780 [](const std::pair<uint64_t, StringRef> &LHS,
781 uint64_t RHS) { return LHS.first < RHS; });
782 if (Result != MD5NameMap.end() && Result->first == MD5Hash)
783 return Result->second;
784 return StringRef();
785}
786
788 finalizeSymtab();
789 auto Result = llvm::lower_bound(MD5FuncMap, FuncMD5Hash,
790 [](const std::pair<uint64_t, Function *> &LHS,
791 uint64_t RHS) { return LHS.first < RHS; });
792 if (Result != MD5FuncMap.end() && Result->first == FuncMD5Hash)
793 return Result->second;
794 return nullptr;
795}
796
798 return MD5VTableMap.lookup(MD5Hash);
799}
800
801// To store the sums of profile count values, or the percentage of
802// the sums of the total count values.
805 double CountSum = 0.0f;
806 std::array<double, IPVK_Last - IPVK_First + 1> ValueCounts = {};
807 CountSumOrPercent() = default;
808 void reset() {
809 NumEntries = 0;
810 CountSum = 0.0f;
811 ValueCounts.fill(0.0f);
812 }
813};
814
815// Function level or program level overlap information.
818 // Sum of the total count values for the base profile.
820 // Sum of the total count values for the test profile.
822 // Overlap lap score. Should be in range of [0.0f to 1.0f].
827 const std::string *BaseFilename = nullptr;
828 const std::string *TestFilename = nullptr;
831 bool Valid = false;
832
834
835 LLVM_ABI void dump(raw_fd_ostream &OS) const;
836
837 void setFuncInfo(StringRef Name, uint64_t Hash) {
838 FuncName = Name;
839 FuncHash = Hash;
840 }
841
842 LLVM_ABI Error accumulateCounts(const std::string &BaseFilename,
843 const std::string &TestFilename, bool IsCS);
844 LLVM_ABI void addOneMismatch(const CountSumOrPercent &MismatchFunc);
845 LLVM_ABI void addOneUnique(const CountSumOrPercent &UniqueFunc);
846
847 static inline double score(uint64_t Val1, uint64_t Val2, double Sum1,
848 double Sum2) {
849 if (Sum1 < 1.0f || Sum2 < 1.0f)
850 return 0.0f;
851 return std::min(Val1 / Sum1, Val2 / Sum2);
852 }
853};
854
855// This is used to filter the functions whose overlap information
856// to be output.
861
863 /// Value profiling data pairs at a given value site.
864 std::vector<InstrProfValueData> ValueData;
865
867 InstrProfValueSiteRecord(std::vector<InstrProfValueData> &&VD)
868 : ValueData(VD) {}
869
870 /// Sort ValueData ascending by Value
873 [](const InstrProfValueData &L, const InstrProfValueData &R) {
874 return L.Value < R.Value;
875 });
876 }
877 /// Sort ValueData Descending by Count
878 inline void sortByCount();
879
880 /// Merge data from another InstrProfValueSiteRecord
881 /// Optionally scale merged counts by \p Weight.
883 function_ref<void(instrprof_error)> Warn);
884 /// Scale up value profile data counts by N (Numerator) / D (Denominator).
886 function_ref<void(instrprof_error)> Warn);
887
888 /// Compute the overlap b/w this record and Input record.
890 OverlapStats &Overlap, OverlapStats &FuncLevelOverlap);
891};
892
893/// Profiling information for a single function.
895 std::vector<uint64_t> Counts;
896 std::vector<uint8_t> BitmapBytes;
897
898 InstrProfRecord() = default;
899 InstrProfRecord(std::vector<uint64_t> Counts) : Counts(std::move(Counts)) {}
900 InstrProfRecord(std::vector<uint64_t> Counts,
901 std::vector<uint8_t> BitmapBytes)
906 ValueData(RHS.ValueData
907 ? std::make_unique<ValueProfData>(*RHS.ValueData)
908 : nullptr) {}
911 Counts = RHS.Counts;
912 BitmapBytes = RHS.BitmapBytes;
913 if (!RHS.ValueData) {
914 ValueData = nullptr;
915 return *this;
916 }
917 if (!ValueData)
918 ValueData = std::make_unique<ValueProfData>(*RHS.ValueData);
919 else
920 *ValueData = *RHS.ValueData;
921 return *this;
922 }
923
924 /// Return the number of value profile kinds with non-zero number
925 /// of profile sites.
926 inline uint32_t getNumValueKinds() const;
927 /// Return the number of instrumented sites for ValueKind.
928 inline uint32_t getNumValueSites(uint32_t ValueKind) const;
929
930 /// Return the total number of ValueData for ValueKind.
931 inline uint32_t getNumValueData(uint32_t ValueKind) const;
932
933 /// Return the array of profiled values at \p Site.
935 uint32_t Site) const;
936
937 /// Reserve space for NumValueSites sites.
938 inline void reserveSites(uint32_t ValueKind, uint32_t NumValueSites);
939
940 /// Add ValueData for ValueKind at value Site. We do not support adding sites
941 /// out of order. Site must go up from 0 one by one.
942 LLVM_ABI void addValueData(uint32_t ValueKind, uint32_t Site,
944 InstrProfSymtab *SymTab);
945
946 /// Merge the counts in \p Other into this one.
947 /// Optionally scale merged counts by \p Weight.
949 function_ref<void(instrprof_error)> Warn);
950
951 /// Scale up profile counts (including value profile data) by
952 /// a factor of (N / D).
954 function_ref<void(instrprof_error)> Warn);
955
956 /// Sort value profile data (per site) by count.
958 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
959 for (auto &SR : getValueSitesForKind(Kind))
960 SR.sortByCount();
961 }
962
963 /// Clear value data entries and edge counters.
964 void Clear() {
965 Counts.clear();
967 }
968
969 /// Clear value data entries
970 void clearValueData() { ValueData = nullptr; }
971
972 /// Compute the sums of all counts and store in Sum.
974
975 /// Compute the overlap b/w this IntrprofRecord and Other.
977 OverlapStats &FuncLevelOverlap, uint64_t ValueCutoff);
978
979 /// Compute the overlap of value profile counts.
981 OverlapStats &Overlap,
982 OverlapStats &FuncLevelOverlap);
983
994 uint64_t FirstCount = Counts[0];
995 if (FirstCount == (uint64_t)HotFunctionVal)
996 return PseudoHot;
997 if (FirstCount == (uint64_t)WarmFunctionVal)
998 return PseudoWarm;
999 return NotPseudo;
1000 }
1002 if (Kind == PseudoHot)
1004 else if (Kind == PseudoWarm)
1006 }
1007
1008private:
1009 using ValueProfData = std::array<std::vector<InstrProfValueSiteRecord>,
1010 IPVK_Last - IPVK_First + 1>;
1011 std::unique_ptr<ValueProfData> ValueData;
1012
1014 getValueSitesForKind(uint32_t ValueKind) {
1015 // Cast to /add/ const (should be an implicit_cast, ideally, if that's ever
1016 // implemented in LLVM) to call the const overload of this function, then
1017 // cast away the constness from the result.
1018 auto AR = const_cast<const InstrProfRecord *>(this)->getValueSitesForKind(
1019 ValueKind);
1020 return MutableArrayRef(
1021 const_cast<InstrProfValueSiteRecord *>(AR.data()), AR.size());
1022 }
1024 getValueSitesForKind(uint32_t ValueKind) const {
1025 if (!ValueData)
1026 return {};
1027 assert(IPVK_First <= ValueKind && ValueKind <= IPVK_Last &&
1028 "Unknown value kind!");
1029 return (*ValueData)[ValueKind - IPVK_First];
1030 }
1031
1032 std::vector<InstrProfValueSiteRecord> &
1033 getOrCreateValueSitesForKind(uint32_t ValueKind) {
1034 if (!ValueData)
1035 ValueData = std::make_unique<ValueProfData>();
1036 assert(IPVK_First <= ValueKind && ValueKind <= IPVK_Last &&
1037 "Unknown value kind!");
1038 return (*ValueData)[ValueKind - IPVK_First];
1039 }
1040
1041 // Map indirect call target name hash to name string.
1042 uint64_t remapValue(uint64_t Value, uint32_t ValueKind,
1043 InstrProfSymtab *SymTab);
1044
1045 // Merge Value Profile data from Src record to this record for ValueKind.
1046 // Scale merged value counts by \p Weight.
1047 void mergeValueProfData(uint32_t ValkeKind, InstrProfRecord &Src,
1048 uint64_t Weight,
1049 function_ref<void(instrprof_error)> Warn);
1050
1051 // Scale up value profile data count by N (Numerator) / D (Denominator).
1052 void scaleValueProfData(uint32_t ValueKind, uint64_t N, uint64_t D,
1053 function_ref<void(instrprof_error)> Warn);
1054};
1055
1059
1060 // We reserve the highest 4 bits as flags.
1061 static constexpr uint64_t FUNC_HASH_MASK = 0x0FFF'FFFF'FFFF'FFFF;
1062 // The 60th bit is for context sensitive profile record.
1063 static constexpr unsigned CS_FLAG_IN_FUNC_HASH = 60;
1064
1070 std::vector<uint64_t> Counts,
1071 std::vector<uint8_t> BitmapBytes)
1073 Hash(Hash) {}
1074
1076 return ((FuncHash >> CS_FLAG_IN_FUNC_HASH) & 1);
1077 }
1081};
1082
1084 uint32_t NumValueKinds = 0;
1085 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
1086 NumValueKinds += !(getValueSitesForKind(Kind).empty());
1087 return NumValueKinds;
1088}
1089
1091 uint32_t N = 0;
1092 for (const auto &SR : getValueSitesForKind(ValueKind))
1093 N += SR.ValueData.size();
1094 return N;
1095}
1096
1098 return getValueSitesForKind(ValueKind).size();
1099}
1100
1103 return getValueSitesForKind(ValueKind)[Site].ValueData;
1104}
1105
1107 if (!NumValueSites)
1108 return;
1109 getOrCreateValueSitesForKind(ValueKind).reserve(NumValueSites);
1110}
1111
1112// Include definitions for value profile data
1113#define INSTR_PROF_VALUE_PROF_DATA
1115
1118 ValueData, [](const InstrProfValueData &L, const InstrProfValueData &R) {
1119 return L.Count > R.Count;
1120 });
1121 // Now truncate
1122 size_t max_s = INSTR_PROF_MAX_NUM_VAL_PER_SITE;
1123 if (ValueData.size() > max_s)
1124 ValueData.resize(max_s);
1125}
1126
1127namespace IndexedInstrProf {
1128
1129enum class HashT : uint32_t {
1132};
1133
1135 switch (Type) {
1136 case HashT::MD5:
1137 return MD5Hash(K);
1138 }
1139 llvm_unreachable("Unhandled hash type");
1140}
1141
1142const uint64_t Magic = 0x8169666f72706cff; // "\xfflprofi\x81"
1143
1145 // Version 1 is the first version. In this version, the value of
1146 // a key/value pair can only include profile data of a single function.
1147 // Due to this restriction, the number of block counters for a given
1148 // function is not recorded but derived from the length of the value.
1150 // The version 2 format supports recording profile data of multiple
1151 // functions which share the same key in one value field. To support this,
1152 // the number block counters is recorded as an uint64_t field right after the
1153 // function structural hash.
1155 // Version 3 supports value profile data. The value profile data is expected
1156 // to follow the block counter profile data.
1158 // In this version, profile summary data \c IndexedInstrProf::Summary is
1159 // stored after the profile header.
1161 // In this version, the frontend PGO stable hash algorithm defaults to V2.
1163 // In this version, the frontend PGO stable hash algorithm got fixed and
1164 // may produce hashes different from Version5.
1166 // An additional counter is added around logical operators.
1168 // An additional (optional) memory profile type is added.
1170 // Binary ids are added.
1172 // An additional (optional) temporal profile traces section is added.
1174 // An additional field is used for bitmap bytes.
1176 // VTable profiling, decision record and bitmap are modified for mcdc.
1178 // In this version, the frontend PGO stable hash algorithm defaults to V4.
1180 // The current version is 13.
1182};
1184
1186
1188
1189// This structure defines the file header of the LLVM profile
1190// data file in indexed-format. Please update llvm/docs/InstrProfileFormat.rst
1191// as appropriate when updating the indexed profile format.
1192struct Header {
1194 // The lower 32 bits specify the version of the indexed profile.
1195 // The most significant 32 bits are reserved to specify the variant types of
1196 // the profile.
1198 uint64_t Unused = 0; // Becomes unused since version 4
1200 // This field records the offset of this hash table's metadata (i.e., the
1201 // number of buckets and entries), which follows right after the payload of
1202 // the entire hash table.
1208 // New fields should only be added at the end to ensure that the size
1209 // computation is correct. The methods below need to be updated to ensure that
1210 // the new field is read correctly.
1211
1212 // Reads a header struct from the buffer. Header fields are in machine native
1213 // endianness.
1214 LLVM_ABI static Expected<Header> readFromBuffer(const unsigned char *Buffer);
1215
1216 // Returns the size of the header in bytes for all valid fields based on the
1217 // version. I.e a older version header will return a smaller size.
1218 LLVM_ABI size_t size() const;
1219
1220 // Return the indexed profile version, i.e., the least significant 32 bits
1221 // in Header.Version.
1223};
1224
1225// Profile summary data recorded in the profile data file in indexed
1226// format. It is introduced in version 4. The summary data follows
1227// right after the profile file header.
1228struct Summary {
1229 struct Entry {
1230 uint64_t Cutoff; ///< The required percentile of total execution count.
1231 uint64_t
1232 MinBlockCount; ///< The minimum execution count for this percentile.
1233 uint64_t NumBlocks; ///< Number of blocks >= the minumum execution count.
1234 };
1235 // The field kind enumerator to assigned value mapping should remain
1236 // unchanged when a new kind is added or an old kind gets deleted in
1237 // the future.
1239 /// The total number of functions instrumented.
1241 /// Total number of instrumented blocks/edges.
1243 /// The maximal execution count among all functions.
1244 /// This field does not exist for profile data from IR based
1245 /// instrumentation.
1247 /// Max block count of the program.
1249 /// Max internal block count of the program (excluding entry blocks).
1251 /// The sum of all instrumented block counts.
1254 };
1255
1256 // The number of summmary fields following the summary header.
1258 // The number of Cutoff Entries (Summary::Entry) following summary fields.
1260
1261 Summary() = delete;
1262 Summary(uint32_t Size) { memset(this, 0, Size); }
1263
1264 void operator delete(void *ptr) { ::operator delete(ptr); }
1265
1267 return sizeof(Summary) + NumCutoffEntries * sizeof(Entry) +
1268 NumSumFields * sizeof(uint64_t);
1269 }
1270
1272 return reinterpret_cast<const uint64_t *>(this + 1);
1273 }
1274
1276 return reinterpret_cast<uint64_t *>(this + 1);
1277 }
1278
1279 const Entry *getCutoffEntryBase() const {
1280 return reinterpret_cast<const Entry *>(
1282 }
1283
1285 return reinterpret_cast<Entry *>(&getSummaryDataBase()[NumSummaryFields]);
1286 }
1287
1289 return getSummaryDataBase()[K];
1290 }
1291
1293 getSummaryDataBase()[K] = V;
1294 }
1295
1296 const Entry &getEntry(uint32_t I) const { return getCutoffEntryBase()[I]; }
1297
1299 Entry &ER = getCutoffEntryBase()[I];
1300 ER.Cutoff = E.Cutoff;
1301 ER.MinBlockCount = E.MinCount;
1302 ER.NumBlocks = E.NumCounts;
1303 }
1304};
1305
1306inline std::unique_ptr<Summary> allocSummary(uint32_t TotalSize) {
1307 return std::unique_ptr<Summary>(new (::operator new(TotalSize))
1308 Summary(TotalSize));
1309}
1310
1311} // end namespace IndexedInstrProf
1312
1313namespace RawInstrProf {
1314
1315// Version 1: First version
1316// Version 2: Added value profile data section. Per-function control data
1317// struct has more fields to describe value profile information.
1318// Version 3: Compressed name section support. Function PGO name reference
1319// from control data struct is changed from raw pointer to Name's MD5 value.
1320// Version 4: ValueDataBegin and ValueDataSizes fields are removed from the
1321// raw header.
1322// Version 5: Bit 60 of FuncHash is reserved for the flag for the context
1323// sensitive records.
1324// Version 6: Added binary id.
1325// Version 7: Reorder binary id and include version in signature.
1326// Version 8: Use relative counter pointer.
1327// Version 9: Added relative bitmap bytes pointer and count used by MC/DC.
1328// Version 10: Added vtable, a new type of value profile data.
1330
1331template <class IntPtrT> inline uint64_t getMagic();
1332template <> inline uint64_t getMagic<uint64_t>() {
1334}
1335
1336template <> inline uint64_t getMagic<uint32_t>() {
1338}
1339
1340// Per-function profile data header/control structure.
1341// The definition should match the structure defined in
1342// compiler-rt/lib/profile/InstrProfiling.h.
1343// It should also match the synthesized type in
1344// Transforms/Instrumentation/InstrProfiling.cpp:getOrCreateRegionCounters.
1345template <class IntPtrT> struct alignas(8) ProfileData {
1346#define INSTR_PROF_DATA(Type, LLVMType, Name, Init) Type Name;
1348};
1349
1350template <class IntPtrT> struct alignas(8) VTableProfileData {
1351#define INSTR_PROF_VTABLE_DATA(Type, LLVMType, Name, Init) Type Name;
1353};
1354
1355// File header structure of the LLVM profile data in raw format.
1356// The definition should match the header referenced in
1357// compiler-rt/lib/profile/InstrProfilingFile.c and
1358// InstrProfilingBuffer.c.
1359struct Header {
1360#define INSTR_PROF_RAW_HEADER(Type, Name, Init) const Type Name;
1362};
1363
1364} // end namespace RawInstrProf
1365
1366// Create the variable for the profile file name.
1367LLVM_ABI void createProfileFileNameVar(Module &M, StringRef InstrProfileOutput);
1368
1369// Whether to compress function names in profile records, and filenames in
1370// code coverage mappings. Used by the Instrumentation library and unit tests.
1372
1373} // end namespace llvm
1374#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
Machine Check Debug Module
#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:41
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:458
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:470
const std::string & getMessage() const
Definition InstrProf.h:465
instrprof_error get() const
Definition InstrProf.h:464
std::error_code convertToErrorCode() const override
Convert this error to a std::error_code.
Definition InstrProf.h:460
std::string message() const override
Return the error message as a string.
InstrProfError(instrprof_error Err, const Twine &ErrStr=Twine())
Definition InstrProf.h:451
A symbol table used for function [IR]PGO name look-up with keys (such as pointers,...
Definition InstrProf.h:505
StringRef getFuncOrVarName(uint64_t ValMD5Hash) const
Return name of functions or global variables from the name's md5 hash value.
Definition InstrProf.h:777
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:708
const std::vector< std::pair< uint64_t, Function * > > & getIDToNameMap() const
Definition InstrProf.h:667
Error addSymbolName(StringRef SymbolName)
Definition InstrProf.h:635
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:797
StringRef getFuncOrVarNameIfDefined(uint64_t ValMD5Hash) const
Just like getFuncOrVarName, except that it will return literal string 'External Symbol' if the functi...
Definition InstrProf.h:770
void mapAddress(uint64_t Addr, uint64_t MD5Val)
Map a function address to its name's MD5 hash.
Definition InstrProf.h:675
Error addVTableName(StringRef VTableName)
Adds VTableName as a known symbol, and inserts it to a map that tracks all vtable names.
Definition InstrProf.h:657
std::vector< std::pair< uint64_t, uint64_t > > AddrHashMap
Definition InstrProf.h:507
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:720
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:653
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:682
LLVM_ABI Error initVTableNamesFromCompressedStrings(StringRef CompressedVTableNames)
Initialize 'this' with the set of vtable names encoded in CompressedVTableNames.
const StringSet & getVTableNames() const
Definition InstrProf.h:671
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:787
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:1078
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:299
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.
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
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:45
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:1306
uint64_t ComputeHash(StringRef K)
Definition InstrProf.h:1187
const uint64_t Version
Definition InstrProf.h:1183
const uint64_t Magic
Definition InstrProf.h:1142
uint64_t getMagic()
const uint64_t Version
Definition InstrProf.h:1329
uint64_t getMagic< uint32_t >()
Definition InstrProf.h:1336
uint64_t getMagic< uint64_t >()
Definition InstrProf.h:1332
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:2058
StringRef getInstrProfNameVarPrefix()
Return the name prefix of variables containing instrumented function names.
Definition InstrProf.h:123
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:194
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:341
StringRef getCoverageMappingVarName()
Return the name of a covarage mapping variable (internal linkage) for each instrumented source module...
Definition InstrProf.h:152
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:990
StringRef getInstrProfBitmapVarPrefix()
Return the name prefix of profile bitmap variables.
Definition InstrProf.h:135
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:147
LLVM_ABI std::pair< StringRef, StringRef > getParsedIRPGOName(StringRef IRPGOName)
auto unique(Range &&R, Predicate P)
Definition STLExtras.h:2076
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:129
StringRef getCoverageUnusedNamesVarName()
Return the name of the internal variable recording the array of PGO name vars referenced by the cover...
Definition InstrProf.h:160
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:189
StringRef getInstrProfValuesVarPrefix()
Return the name prefix of value profile variables.
Definition InstrProf.h:138
StringRef getInstrProfCounterBiasVarName()
Definition InstrProf.h:204
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:200
StringRef getInstrProfRegFuncsName()
Return the name of function that registers all the per-function control data at program startup time ...
Definition InstrProf.h:169
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:1622
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:132
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:208
StringRef getInstrProfNameSeparator()
Return the marker used to separate PGO names during serialization.
Definition InstrProf.h:213
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
@ LLVM_MARK_AS_BITMASK_ENUM
Definition ModRef.h:37
@ Other
Any other memory.
Definition ModRef.h:68
FunctionAddr VTableAddr uintptr_t uintptr_t Data
Definition InstrProf.h:189
instrprof_error
Definition InstrProf.h:398
InstrProfValueKind
Definition InstrProf.h:311
StringRef getInstrProfNamesRegFuncName()
Return the name of the runtime interface that registers the PGO name strings.
Definition InstrProf.h:181
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:1994
LLVM_ABI const std::error_category & instrprof_category()
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:1867
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:175
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:145
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:343
StringRef getInstrProfVNodesVarName()
Return the name of value profile node array variables:
Definition InstrProf.h:141
StringRef getInstrProfVTableVarPrefix()
Return the name prefix of variables containing virtual table profile data.
Definition InstrProf.h:126
InstrProfKind
An enum describing the attributes of an instrumented profile.
Definition InstrProf.h:373
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:867
#define N
std::array< double, IPVK_Last - IPVK_First+1 > ValueCounts
Definition InstrProf.h:806
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:1230
uint64_t NumBlocks
Number of blocks >= the minumum execution count.
Definition InstrProf.h:1233
uint64_t MinBlockCount
The minimum execution count for this percentile.
Definition InstrProf.h:1232
const Entry * getCutoffEntryBase() const
Definition InstrProf.h:1279
uint64_t get(SummaryFieldKind K) const
Definition InstrProf.h:1288
void set(SummaryFieldKind K, uint64_t V)
Definition InstrProf.h:1292
void setEntry(uint32_t I, const ProfileSummaryEntry &E)
Definition InstrProf.h:1298
@ TotalNumFunctions
The total number of functions instrumented.
Definition InstrProf.h:1240
@ TotalNumBlocks
Total number of instrumented blocks/edges.
Definition InstrProf.h:1242
@ MaxFunctionCount
The maximal execution count among all functions.
Definition InstrProf.h:1246
@ TotalBlockCount
The sum of all instrumented block counts.
Definition InstrProf.h:1252
@ MaxBlockCount
Max block count of the program.
Definition InstrProf.h:1248
@ MaxInternalBlockCount
Max internal block count of the program (excluding entry blocks).
Definition InstrProf.h:1250
const uint64_t * getSummaryDataBase() const
Definition InstrProf.h:1271
static uint32_t getSize(uint32_t NumSumFields, uint32_t NumCutoffEntries)
Definition InstrProf.h:1266
const Entry & getEntry(uint32_t I) const
Definition InstrProf.h:1296
Profiling information for a single function.
Definition InstrProf.h:894
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:895
ArrayRef< InstrProfValueData > getValueArrayForSite(uint32_t ValueKind, uint32_t Site) const
Return the array of profiled values at Site.
Definition InstrProf.h:1102
CountPseudoKind getCountPseudoKind() const
Definition InstrProf.h:993
InstrProfRecord(std::vector< uint64_t > Counts)
Definition InstrProf.h:899
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:1097
uint32_t getNumValueKinds() const
Return the number of value profile kinds with non-zero number of profile sites.
Definition InstrProf.h:1083
void setPseudoCount(CountPseudoKind Kind)
Definition InstrProf.h:1001
InstrProfRecord(InstrProfRecord &&)=default
uint32_t getNumValueData(uint32_t ValueKind) const
Return the total number of ValueData for ValueKind.
Definition InstrProf.h:1090
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:910
void clearValueData()
Clear value data entries.
Definition InstrProf.h:970
InstrProfRecord(const InstrProfRecord &RHS)
Definition InstrProf.h:904
InstrProfRecord(std::vector< uint64_t > Counts, std::vector< uint8_t > BitmapBytes)
Definition InstrProf.h:900
void reserveSites(uint32_t ValueKind, uint32_t NumValueSites)
Reserve space for NumValueSites sites.
Definition InstrProf.h:1106
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:957
std::vector< uint8_t > BitmapBytes
Definition InstrProf.h:896
InstrProfRecord & operator=(InstrProfRecord &&)=default
void Clear()
Clear value data entries and edge counters.
Definition InstrProf.h:964
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:1116
InstrProfValueSiteRecord(std::vector< InstrProfValueData > &&VD)
Definition InstrProf.h:867
void sortByTargetValues()
Sort ValueData ascending by Value.
Definition InstrProf.h:871
std::vector< InstrProfValueData > ValueData
Value profiling data pairs at a given value site.
Definition InstrProf.h:864
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:1075
NamedInstrProfRecord(StringRef Name, uint64_t Hash, std::vector< uint64_t > Counts)
Definition InstrProf.h:1066
NamedInstrProfRecord(StringRef Name, uint64_t Hash, std::vector< uint64_t > Counts, std::vector< uint8_t > BitmapBytes)
Definition InstrProf.h:1069
static void setCSFlagInHash(uint64_t &FuncHash)
Definition InstrProf.h:1078
static constexpr uint64_t FUNC_HASH_MASK
Definition InstrProf.h:1061
static constexpr unsigned CS_FLAG_IN_FUNC_HASH
Definition InstrProf.h:1063
const std::string NameFilter
Definition InstrProf.h:859
LLVM_ABI void addOneMismatch(const CountSumOrPercent &MismatchFunc)
static double score(uint64_t Val1, uint64_t Val2, double Sum1, double Sum2)
Definition InstrProf.h:847
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:823
CountSumOrPercent Base
Definition InstrProf.h:819
LLVM_ABI void addOneUnique(const CountSumOrPercent &UniqueFunc)
const std::string * BaseFilename
Definition InstrProf.h:827
const std::string * TestFilename
Definition InstrProf.h:828
void setFuncInfo(StringRef Name, uint64_t Hash)
Definition InstrProf.h:837
CountSumOrPercent Unique
Definition InstrProf.h:825
CountSumOrPercent Mismatch
Definition InstrProf.h:824
StringRef FuncName
Definition InstrProf.h:829
OverlapStatsLevel Level
Definition InstrProf.h:826
OverlapStats(OverlapStatsLevel L=ProgramLevel)
Definition InstrProf.h:833
CountSumOrPercent Test
Definition InstrProf.h:821
uint64_t Pos
Definition InstrProf.h:63
ArrayRef< uint64_t > D
Definition InstrProf.h:64
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:430
TemporalProfTraceTy(std::initializer_list< uint64_t > Trace={}, uint64_t Weight=1)
Definition InstrProf.h:432
Per-function header/control data structure for value profiling data in indexed format.
Definition InstrProf.h:424
Function object to check whether the first component of a container supported by std::get (like std::...
Definition STLExtras.h:1425
Adapter to write values to a stream in a particular byte order.