LLVM 18.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/STLExtras.h"
21#include "llvm/ADT/StringRef.h"
22#include "llvm/ADT/StringSet.h"
23#include "llvm/IR/GlobalValue.h"
29#include "llvm/Support/Error.h"
31#include "llvm/Support/MD5.h"
36#include <algorithm>
37#include <cassert>
38#include <cstddef>
39#include <cstdint>
40#include <cstring>
41#include <list>
42#include <memory>
43#include <string>
44#include <system_error>
45#include <utility>
46#include <vector>
47
48namespace llvm {
49
50class Function;
51class GlobalVariable;
52struct InstrProfRecord;
53class InstrProfSymtab;
54class Instruction;
55class MDNode;
56class Module;
57
59#define INSTR_PROF_SECT_ENTRY(Kind, SectNameCommon, SectNameCoff, Prefix) Kind,
61};
62
63/// Return the max count value. We reserver a few large values for special use.
65 return std::numeric_limits<uint64_t>::max() - 2;
66}
67
68/// Return the name of the profile section corresponding to \p IPSK.
69///
70/// The name of the section depends on the object format type \p OF. If
71/// \p AddSegmentInfo is true, a segment prefix and additional linker hints may
72/// be added to the section name (this is the default).
75 bool AddSegmentInfo = true);
76
77/// Return the name profile runtime entry point to do value profiling
78/// for a given site.
80 return INSTR_PROF_VALUE_PROF_FUNC_STR;
81}
82
83/// Return the name profile runtime entry point to do memop size value
84/// profiling.
86 return INSTR_PROF_VALUE_PROF_MEMOP_FUNC_STR;
87}
88
89/// Return the name prefix of variables containing instrumented function names.
90inline StringRef getInstrProfNameVarPrefix() { return "__profn_"; }
91
92/// Return the name prefix of variables containing per-function control data.
93inline StringRef getInstrProfDataVarPrefix() { return "__profd_"; }
94
95/// Return the name prefix of profile counter variables.
96inline StringRef getInstrProfCountersVarPrefix() { return "__profc_"; }
97
98/// Return the name prefix of profile bitmap variables.
99inline StringRef getInstrProfBitmapVarPrefix() { return "__profbm_"; }
100
101/// Return the name prefix of value profile variables.
102inline StringRef getInstrProfValuesVarPrefix() { return "__profvp_"; }
103
104/// Return the name of value profile node array variables:
105inline StringRef getInstrProfVNodesVarName() { return "__llvm_prf_vnodes"; }
106
107/// Return the name of the variable holding the strings (possibly compressed)
108/// of all function's PGO names.
110 return "__llvm_prf_nm";
111}
112
113/// Return the name of a covarage mapping variable (internal linkage)
114/// for each instrumented source module. Such variables are allocated
115/// in the __llvm_covmap section.
117 return "__llvm_coverage_mapping";
118}
119
120/// Return the name of the internal variable recording the array
121/// of PGO name vars referenced by the coverage mapping. The owning
122/// functions of those names are not emitted by FE (e.g, unused inline
123/// functions.)
125 return "__llvm_coverage_names";
126}
127
128/// Return the name of function that registers all the per-function control
129/// data at program startup time by calling __llvm_register_function. This
130/// function has internal linkage and is called by __llvm_profile_init
131/// runtime method. This function is not generated for these platforms:
132/// Darwin, Linux, and FreeBSD.
134 return "__llvm_profile_register_functions";
135}
136
137/// Return the name of the runtime interface that registers per-function control
138/// data for one instrumented function.
140 return "__llvm_profile_register_function";
141}
142
143/// Return the name of the runtime interface that registers the PGO name strings.
145 return "__llvm_profile_register_names_function";
146}
147
148/// Return the name of the runtime initialization method that is generated by
149/// the compiler. The function calls __llvm_profile_register_functions and
150/// __llvm_profile_override_default_filename functions if needed. This function
151/// has internal linkage and invoked at startup time via init_array.
152inline StringRef getInstrProfInitFuncName() { return "__llvm_profile_init"; }
153
154/// Return the name of the hook variable defined in profile runtime library.
155/// A reference to the variable causes the linker to link in the runtime
156/// initialization module (which defines the hook variable).
158 return INSTR_PROF_QUOTE(INSTR_PROF_PROFILE_RUNTIME_VAR);
159}
160
161/// Return the name of the compiler generated function that references the
162/// runtime hook variable. The function is a weak global.
164 return "__llvm_profile_runtime_user";
165}
166
168 return INSTR_PROF_QUOTE(INSTR_PROF_PROFILE_COUNTER_BIAS_VAR);
169}
170
171/// Return the marker used to separate PGO names during serialization.
172inline StringRef getInstrProfNameSeparator() { return "\01"; }
173
174/// Return the modified name for function \c F suitable to be
175/// used the key for profile lookup. Variable \c InLTO indicates if this
176/// is called in LTO optimization passes.
177std::string getPGOFuncName(const Function &F, bool InLTO = false,
178 uint64_t Version = INSTR_PROF_INDEX_VERSION);
179
180/// Return the modified name for a function suitable to be
181/// used the key for profile lookup. The function's original
182/// name is \c RawFuncName and has linkage of type \c Linkage.
183/// The function is defined in module \c FileName.
184std::string getPGOFuncName(StringRef RawFuncName,
186 StringRef FileName,
187 uint64_t Version = INSTR_PROF_INDEX_VERSION);
188
189/// \return the modified name for function \c F suitable to be
190/// used as the key for IRPGO profile lookup. \c InLTO indicates if this is
191/// called from LTO optimization passes.
192std::string getIRPGOFuncName(const Function &F, bool InLTO = false);
193
194/// \return the filename and the function name parsed from the output of
195/// \c getIRPGOFuncName()
196std::pair<StringRef, StringRef> getParsedIRPGOFuncName(StringRef IRPGOFuncName);
197
198/// Return the name of the global variable used to store a function
199/// name in PGO instrumentation. \c FuncName is the name of the function
200/// returned by the \c getPGOFuncName call.
201std::string getPGOFuncNameVarName(StringRef FuncName,
203
204/// Create and return the global variable for function name used in PGO
205/// instrumentation. \c FuncName is the name of the function returned
206/// by \c getPGOFuncName call.
207GlobalVariable *createPGOFuncNameVar(Function &F, StringRef PGOFuncName);
208
209/// Create and return the global variable for function name used in PGO
210/// instrumentation. /// \c FuncName is the name of the function
211/// returned by \c getPGOFuncName call, \c M is the owning module,
212/// and \c Linkage is the linkage of the instrumented function.
213GlobalVariable *createPGOFuncNameVar(Module &M,
215 StringRef PGOFuncName);
216
217/// Return the initializer in string of the PGO name var \c NameVar.
218StringRef getPGOFuncNameVarInitializer(GlobalVariable *NameVar);
219
220/// Given a PGO function name, remove the filename prefix and return
221/// the original (static) function name.
222StringRef getFuncNameWithoutPrefix(StringRef PGOFuncName,
223 StringRef FileName = "<unknown>");
224
225/// Given a vector of strings (names of global objects like functions or,
226/// virtual tables) \c NameStrs, the method generates a combined string \c
227/// Result that is ready to be serialized. The \c Result string is comprised of
228/// three fields: The first field is the length of the uncompressed strings, and
229/// the the second field is the length of the zlib-compressed string. Both
230/// fields are encoded in ULEB128. If \c doCompress is false, the
231/// third field is the uncompressed strings; otherwise it is the
232/// compressed string. When the string compression is off, the
233/// second field will have value zero.
234Error collectGlobalObjectNameStrings(ArrayRef<std::string> NameStrs,
235 bool doCompression, std::string &Result);
236
237/// Produce \c Result string with the same format described above. The input
238/// is vector of PGO function name variables that are referenced.
239/// The global variable element in 'NameVars' is a string containing the pgo
240/// name of a function. See `createPGOFuncNameVar` that creates these global
241/// variables.
242Error collectPGOFuncNameStrings(ArrayRef<GlobalVariable *> NameVars,
243 std::string &Result, bool doCompression = true);
244
245/// Check if INSTR_PROF_RAW_VERSION_VAR is defined. This global is only being
246/// set in IR PGO compilation.
247bool isIRPGOFlagSet(const Module *M);
248
249/// Check if we can safely rename this Comdat function. Instances of the same
250/// comdat function may have different control flows thus can not share the
251/// same counter variable.
252bool canRenameComdatFunc(const Function &F, bool CheckAddressTaken = false);
253
255#define VALUE_PROF_KIND(Enumerator, Value, Descr) Enumerator = Value,
257};
258
259/// Get the value profile data for value site \p SiteIdx from \p InstrProfR
260/// and annotate the instruction \p Inst with the value profile meta data.
261/// Annotate up to \p MaxMDCount (default 3) number of records per value site.
262void annotateValueSite(Module &M, Instruction &Inst,
263 const InstrProfRecord &InstrProfR,
264 InstrProfValueKind ValueKind, uint32_t SiteIndx,
265 uint32_t MaxMDCount = 3);
266
267/// Same as the above interface but using an ArrayRef, as well as \p Sum.
268void annotateValueSite(Module &M, Instruction &Inst,
269 ArrayRef<InstrProfValueData> VDs, uint64_t Sum,
270 InstrProfValueKind ValueKind, uint32_t MaxMDCount);
271
272/// Extract the value profile data from \p Inst which is annotated with
273/// value profile meta data. Return false if there is no value data annotated,
274/// otherwise return true.
275bool getValueProfDataFromInst(const Instruction &Inst,
276 InstrProfValueKind ValueKind,
277 uint32_t MaxNumValueData,
278 InstrProfValueData ValueData[],
279 uint32_t &ActualNumValueData, uint64_t &TotalC,
280 bool GetNoICPValue = false);
281
282inline StringRef getPGOFuncNameMetadataName() { return "PGOFuncName"; }
283
284/// Return the PGOFuncName meta data associated with a function.
285MDNode *getPGOFuncNameMetadata(const Function &F);
286
287/// Create the PGOFuncName meta data if PGOFuncName is different from
288/// function's raw name. This should only apply to internal linkage functions
289/// declared by users only.
290void createPGOFuncNameMetadata(Function &F, StringRef PGOFuncName);
291
292/// Check if we can use Comdat for profile variables. This will eliminate
293/// the duplicated profile variables for Comdat functions.
294bool needsComdatForCounter(const Function &F, const Module &M);
295
296/// An enum describing the attributes of an instrumented profile.
297enum class InstrProfKind {
298 Unknown = 0x0,
299 // A frontend clang profile, incompatible with other attrs.
301 // An IR-level profile (default when -fprofile-generate is used).
302 IRInstrumentation = 0x2,
303 // A profile with entry basic block instrumentation.
305 // A context sensitive IR-level profile.
306 ContextSensitive = 0x8,
307 // Use single byte probes for coverage.
308 SingleByteCoverage = 0x10,
309 // Only instrument the function entry basic block.
310 FunctionEntryOnly = 0x20,
311 // A memory profile collected using -fprofile=memory.
312 MemProf = 0x40,
313 // A temporal profile.
314 TemporalProfile = 0x80,
316};
317
318const std::error_category &instrprof_category();
319
320enum class instrprof_error {
321 success = 0,
322 eof,
324 bad_magic,
328 too_large,
329 truncated,
330 malformed,
347};
348
349/// An ordered list of functions identified by their NameRef found in
350/// INSTR_PROF_DATA
352 std::vector<uint64_t> FunctionNameRefs;
354 TemporalProfTraceTy(std::initializer_list<uint64_t> Trace = {},
355 uint64_t Weight = 1)
357
358 /// Use a set of temporal profile traces to create a list of balanced
359 /// partitioning function nodes used by BalancedPartitioning to generate a
360 /// function order that reduces page faults during startup
361 static std::vector<BPFunctionNode>
362 createBPFunctionNodes(ArrayRef<TemporalProfTraceTy> Traces);
363};
364
365inline std::error_code make_error_code(instrprof_error E) {
366 return std::error_code(static_cast<int>(E), instrprof_category());
367}
368
369class InstrProfError : public ErrorInfo<InstrProfError> {
370public:
372 : Err(Err), Msg(ErrStr.str()) {
373 assert(Err != instrprof_error::success && "Not an error");
374 }
375
376 std::string message() const override;
377
378 void log(raw_ostream &OS) const override { OS << message(); }
379
380 std::error_code convertToErrorCode() const override {
381 return make_error_code(Err);
382 }
383
384 instrprof_error get() const { return Err; }
385 const std::string &getMessage() const { return Msg; }
386
387 /// Consume an Error and return the raw enum value contained within it, and
388 /// the optional error message. The Error must either be a success value, or
389 /// contain a single InstrProfError.
390 static std::pair<instrprof_error, std::string> take(Error E) {
391 auto Err = instrprof_error::success;
392 std::string Msg = "";
393 handleAllErrors(std::move(E), [&Err, &Msg](const InstrProfError &IPE) {
394 assert(Err == instrprof_error::success && "Multiple errors encountered");
395 Err = IPE.get();
396 Msg = IPE.getMessage();
397 });
398 return {Err, Msg};
399 }
400
401 static char ID;
402
403private:
404 instrprof_error Err;
405 std::string Msg;
406};
407
408namespace object {
409
410class SectionRef;
411
412} // end namespace object
413
414namespace IndexedInstrProf {
415
417
418} // end namespace IndexedInstrProf
419
420/// A symbol table used for function PGO name look-up with keys
421/// (such as pointers, md5hash values) to the function. A function's
422/// PGO name or name's md5hash are used in retrieving the profile
423/// data of the function. See \c getPGOFuncName() method for details
424/// on how PGO name is formed.
426public:
427 using AddrHashMap = std::vector<std::pair<uint64_t, uint64_t>>;
428
429private:
430 StringRef Data;
431 uint64_t Address = 0;
432 // Unique name strings.
433 StringSet<> NameTab;
434 // A map from MD5 keys to function name strings.
435 std::vector<std::pair<uint64_t, StringRef>> MD5NameMap;
436 // A map from MD5 keys to function define. We only populate this map
437 // when build the Symtab from a Module.
438 std::vector<std::pair<uint64_t, Function *>> MD5FuncMap;
439 // A map from function runtime address to function name MD5 hash.
440 // This map is only populated and used by raw instr profile reader.
441 AddrHashMap AddrToMD5Map;
442 bool Sorted = false;
443
444 static StringRef getExternalSymbol() {
445 return "** External Symbol **";
446 }
447
448 Error addFuncWithName(Function &F, StringRef PGOFuncName);
449
450 // If the symtab is created by a series of calls to \c addFuncName, \c
451 // finalizeSymtab needs to be called before looking up function names.
452 // This is required because the underlying map is a vector (for space
453 // efficiency) which needs to be sorted.
454 inline void finalizeSymtab();
455
456public:
457 InstrProfSymtab() = default;
458
459 /// Create InstrProfSymtab from an object file section which
460 /// contains function PGO names. When section may contain raw
461 /// string data or string data in compressed form. This method
462 /// only initialize the symtab with reference to the data and
463 /// the section base address. The decompression will be delayed
464 /// until before it is used. See also \c create(StringRef) method.
466
467 /// \c NameStrings is a string composed of one of more sub-strings
468 /// encoded in the format described in \c collectPGOFuncNameStrings.
469 /// This method is a wrapper to \c readPGOFuncNameStrings method.
470 Error create(StringRef NameStrings);
471
472 /// This interface is used by reader of CoverageMapping test
473 /// format.
474 inline Error create(StringRef D, uint64_t BaseAddr);
475
476 /// A wrapper interface to populate the PGO symtab with functions
477 /// decls from module \c M. This interface is used by transformation
478 /// passes such as indirect function call promotion. Variable \c InLTO
479 /// indicates if this is called from LTO optimization passes.
480 Error create(Module &M, bool InLTO = false);
481
482 /// Create InstrProfSymtab from a set of names iteratable from
483 /// \p IterRange. This interface is used by IndexedProfReader.
484 template <typename NameIterRange> Error create(const NameIterRange &IterRange);
485
486 /// Update the symtab by adding \p FuncName to the table. This interface
487 /// is used by the raw and text profile readers.
489 if (FuncName.empty())
490 return make_error<InstrProfError>(instrprof_error::malformed,
491 "function name is empty");
492 auto Ins = NameTab.insert(FuncName);
493 if (Ins.second) {
494 MD5NameMap.push_back(std::make_pair(
495 IndexedInstrProf::ComputeHash(FuncName), Ins.first->getKey()));
496 Sorted = false;
497 }
498 return Error::success();
499 }
500
501 /// Map a function address to its name's MD5 hash. This interface
502 /// is only used by the raw profiler reader.
504 AddrToMD5Map.push_back(std::make_pair(Addr, MD5Val));
505 }
506
507 /// Return a function's hash, or 0, if the function isn't in this SymTab.
509
510 /// Return function's PGO name from the function name's symbol
511 /// address in the object file. If an error occurs, return
512 /// an empty string.
513 StringRef getFuncName(uint64_t FuncNameAddress, size_t NameSize);
514
515 /// Return name of functions or global variables from the name's md5 hash
516 /// value. If not found, return an empty string.
517 inline StringRef getFuncOrVarName(uint64_t ValMD5Hash);
518
519 /// Just like getFuncOrVarName, except that it will return literal string
520 /// 'External Symbol' if the function or global variable is external to
521 /// this symbol table.
523
524 /// True if Symbol is the value used to represent external symbols.
525 static bool isExternalSymbol(const StringRef &Symbol) {
526 return Symbol == InstrProfSymtab::getExternalSymbol();
527 }
528
529 /// Return function from the name's md5 hash. Return nullptr if not found.
530 inline Function *getFunction(uint64_t FuncMD5Hash);
531
532 /// Return the name section data.
533 inline StringRef getNameData() const { return Data; }
534
535 /// Dump the symbols in this table.
536 void dumpNames(raw_ostream &OS) const;
537};
538
540 Data = D;
541 Address = BaseAddr;
542 return Error::success();
543}
544
545template <typename NameIterRange>
546Error InstrProfSymtab::create(const NameIterRange &IterRange) {
547 for (auto Name : IterRange)
548 if (Error E = addFuncName(Name))
549 return E;
550
551 finalizeSymtab();
552 return Error::success();
553}
554
555void InstrProfSymtab::finalizeSymtab() {
556 if (Sorted)
557 return;
558 llvm::sort(MD5NameMap, less_first());
559 llvm::sort(MD5FuncMap, less_first());
560 llvm::sort(AddrToMD5Map, less_first());
561 AddrToMD5Map.erase(std::unique(AddrToMD5Map.begin(), AddrToMD5Map.end()),
562 AddrToMD5Map.end());
563 Sorted = true;
564}
565
568 if (ret.empty())
569 return InstrProfSymtab::getExternalSymbol();
570 return ret;
571}
572
574 finalizeSymtab();
575 auto Result = llvm::lower_bound(MD5NameMap, MD5Hash,
576 [](const std::pair<uint64_t, StringRef> &LHS,
577 uint64_t RHS) { return LHS.first < RHS; });
578 if (Result != MD5NameMap.end() && Result->first == MD5Hash)
579 return Result->second;
580 return StringRef();
581}
582
584 finalizeSymtab();
585 auto Result = llvm::lower_bound(MD5FuncMap, FuncMD5Hash,
586 [](const std::pair<uint64_t, Function *> &LHS,
587 uint64_t RHS) { return LHS.first < RHS; });
588 if (Result != MD5FuncMap.end() && Result->first == FuncMD5Hash)
589 return Result->second;
590 return nullptr;
591}
592
593// To store the sums of profile count values, or the percentage of
594// the sums of the total count values.
597 double CountSum;
598 double ValueCounts[IPVK_Last - IPVK_First + 1];
600 void reset() {
601 NumEntries = 0;
602 CountSum = 0.0f;
603 for (double &VC : ValueCounts)
604 VC = 0.0f;
605 }
606};
607
608// Function level or program level overlap information.
611 // Sum of the total count values for the base profile.
613 // Sum of the total count values for the test profile.
615 // Overlap lap score. Should be in range of [0.0f to 1.0f].
620 const std::string *BaseFilename;
621 const std::string *TestFilename;
624 bool Valid;
625
627 : Level(L), BaseFilename(nullptr), TestFilename(nullptr), FuncHash(0),
628 Valid(false) {}
629
630 void dump(raw_fd_ostream &OS) const;
631
633 FuncName = Name;
634 FuncHash = Hash;
635 }
636
637 Error accumulateCounts(const std::string &BaseFilename,
638 const std::string &TestFilename, bool IsCS);
639 void addOneMismatch(const CountSumOrPercent &MismatchFunc);
640 void addOneUnique(const CountSumOrPercent &UniqueFunc);
641
642 static inline double score(uint64_t Val1, uint64_t Val2, double Sum1,
643 double Sum2) {
644 if (Sum1 < 1.0f || Sum2 < 1.0f)
645 return 0.0f;
646 return std::min(Val1 / Sum1, Val2 / Sum2);
647 }
648};
649
650// This is used to filter the functions whose overlap information
651// to be output.
654 const std::string NameFilter;
655};
656
658 /// Value profiling data pairs at a given value site.
659 std::list<InstrProfValueData> ValueData;
660
662 template <class InputIterator>
663 InstrProfValueSiteRecord(InputIterator F, InputIterator L)
664 : ValueData(F, L) {}
665
666 /// Sort ValueData ascending by Value
668 ValueData.sort(
669 [](const InstrProfValueData &left, const InstrProfValueData &right) {
670 return left.Value < right.Value;
671 });
672 }
673 /// Sort ValueData Descending by Count
674 inline void sortByCount();
675
676 /// Merge data from another InstrProfValueSiteRecord
677 /// Optionally scale merged counts by \p Weight.
678 void merge(InstrProfValueSiteRecord &Input, uint64_t Weight,
679 function_ref<void(instrprof_error)> Warn);
680 /// Scale up value profile data counts by N (Numerator) / D (Denominator).
682
683 /// Compute the overlap b/w this record and Input record.
684 void overlap(InstrProfValueSiteRecord &Input, uint32_t ValueKind,
685 OverlapStats &Overlap, OverlapStats &FuncLevelOverlap);
686};
687
688/// Profiling information for a single function.
690 std::vector<uint64_t> Counts;
691 std::vector<uint8_t> BitmapBytes;
692
693 InstrProfRecord() = default;
694 InstrProfRecord(std::vector<uint64_t> Counts) : Counts(std::move(Counts)) {}
695 InstrProfRecord(std::vector<uint64_t> Counts,
696 std::vector<uint8_t> BitmapBytes)
701 ValueData(RHS.ValueData
702 ? std::make_unique<ValueProfData>(*RHS.ValueData)
703 : nullptr) {}
706 Counts = RHS.Counts;
707 BitmapBytes = RHS.BitmapBytes;
708 if (!RHS.ValueData) {
709 ValueData = nullptr;
710 return *this;
711 }
712 if (!ValueData)
713 ValueData = std::make_unique<ValueProfData>(*RHS.ValueData);
714 else
715 *ValueData = *RHS.ValueData;
716 return *this;
717 }
718
719 /// Return the number of value profile kinds with non-zero number
720 /// of profile sites.
721 inline uint32_t getNumValueKinds() const;
722 /// Return the number of instrumented sites for ValueKind.
723 inline uint32_t getNumValueSites(uint32_t ValueKind) const;
724
725 /// Return the total number of ValueData for ValueKind.
726 inline uint32_t getNumValueData(uint32_t ValueKind) const;
727
728 /// Return the number of value data collected for ValueKind at profiling
729 /// site: Site.
731 uint32_t Site) const;
732
733 /// Return the array of profiled values at \p Site. If \p TotalC
734 /// is not null, the total count of all target values at this site
735 /// will be stored in \c *TotalC.
736 inline std::unique_ptr<InstrProfValueData[]>
737 getValueForSite(uint32_t ValueKind, uint32_t Site,
738 uint64_t *TotalC = nullptr) const;
739
740 /// Get the target value/counts of kind \p ValueKind collected at site
741 /// \p Site and store the result in array \p Dest. Return the total
742 /// counts of all target values at this site.
743 inline uint64_t getValueForSite(InstrProfValueData Dest[], uint32_t ValueKind,
744 uint32_t Site) const;
745
746 /// Reserve space for NumValueSites sites.
747 inline void reserveSites(uint32_t ValueKind, uint32_t NumValueSites);
748
749 /// Add ValueData for ValueKind at value Site.
750 void addValueData(uint32_t ValueKind, uint32_t Site,
751 InstrProfValueData *VData, uint32_t N,
752 InstrProfSymtab *SymTab);
753
754 /// Merge the counts in \p Other into this one.
755 /// Optionally scale merged counts by \p Weight.
756 void merge(InstrProfRecord &Other, uint64_t Weight,
757 function_ref<void(instrprof_error)> Warn);
758
759 /// Scale up profile counts (including value profile data) by
760 /// a factor of (N / D).
762
763 /// Sort value profile data (per site) by count.
765 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
766 for (auto &SR : getValueSitesForKind(Kind))
767 SR.sortByCount();
768 }
769
770 /// Clear value data entries and edge counters.
771 void Clear() {
772 Counts.clear();
774 }
775
776 /// Clear value data entries
777 void clearValueData() { ValueData = nullptr; }
778
779 /// Compute the sums of all counts and store in Sum.
780 void accumulateCounts(CountSumOrPercent &Sum) const;
781
782 /// Compute the overlap b/w this IntrprofRecord and Other.
784 OverlapStats &FuncLevelOverlap, uint64_t ValueCutoff);
785
786 /// Compute the overlap of value profile counts.
787 void overlapValueProfData(uint32_t ValueKind, InstrProfRecord &Src,
788 OverlapStats &Overlap,
789 OverlapStats &FuncLevelOverlap);
790
795 };
799 };
801 uint64_t FirstCount = Counts[0];
802 if (FirstCount == (uint64_t)HotFunctionVal)
803 return PseudoHot;
804 if (FirstCount == (uint64_t)WarmFunctionVal)
805 return PseudoWarm;
806 return NotPseudo;
807 }
809 if (Kind == PseudoHot)
811 else if (Kind == PseudoWarm)
813 }
814
815private:
816 struct ValueProfData {
817 std::vector<InstrProfValueSiteRecord> IndirectCallSites;
818 std::vector<InstrProfValueSiteRecord> MemOPSizes;
819 };
820 std::unique_ptr<ValueProfData> ValueData;
821
822 MutableArrayRef<InstrProfValueSiteRecord>
823 getValueSitesForKind(uint32_t ValueKind) {
824 // Cast to /add/ const (should be an implicit_cast, ideally, if that's ever
825 // implemented in LLVM) to call the const overload of this function, then
826 // cast away the constness from the result.
827 auto AR = const_cast<const InstrProfRecord *>(this)->getValueSitesForKind(
828 ValueKind);
829 return MutableArrayRef(
830 const_cast<InstrProfValueSiteRecord *>(AR.data()), AR.size());
831 }
832 ArrayRef<InstrProfValueSiteRecord>
833 getValueSitesForKind(uint32_t ValueKind) const {
834 if (!ValueData)
835 return std::nullopt;
836 switch (ValueKind) {
837 case IPVK_IndirectCallTarget:
838 return ValueData->IndirectCallSites;
839 case IPVK_MemOPSize:
840 return ValueData->MemOPSizes;
841 default:
842 llvm_unreachable("Unknown value kind!");
843 }
844 }
845
846 std::vector<InstrProfValueSiteRecord> &
847 getOrCreateValueSitesForKind(uint32_t ValueKind) {
848 if (!ValueData)
849 ValueData = std::make_unique<ValueProfData>();
850 switch (ValueKind) {
851 case IPVK_IndirectCallTarget:
852 return ValueData->IndirectCallSites;
853 case IPVK_MemOPSize:
854 return ValueData->MemOPSizes;
855 default:
856 llvm_unreachable("Unknown value kind!");
857 }
858 }
859
860 // Map indirect call target name hash to name string.
861 uint64_t remapValue(uint64_t Value, uint32_t ValueKind,
862 InstrProfSymtab *SymTab);
863
864 // Merge Value Profile data from Src record to this record for ValueKind.
865 // Scale merged value counts by \p Weight.
866 void mergeValueProfData(uint32_t ValkeKind, InstrProfRecord &Src,
867 uint64_t Weight,
868 function_ref<void(instrprof_error)> Warn);
869
870 // Scale up value profile data count by N (Numerator) / D (Denominator).
871 void scaleValueProfData(uint32_t ValueKind, uint64_t N, uint64_t D,
872 function_ref<void(instrprof_error)> Warn);
873};
874
878
879 // We reserve this bit as the flag for context sensitive profile record.
880 static const int CS_FLAG_IN_FUNC_HASH = 60;
881
884 std::vector<uint64_t> Counts)
887 std::vector<uint64_t> Counts,
888 std::vector<uint8_t> BitmapBytes)
890 Hash(Hash) {}
891
892 static bool hasCSFlagInHash(uint64_t FuncHash) {
893 return ((FuncHash >> CS_FLAG_IN_FUNC_HASH) & 1);
894 }
895 static void setCSFlagInHash(uint64_t &FuncHash) {
896 FuncHash |= ((uint64_t)1 << CS_FLAG_IN_FUNC_HASH);
897 }
898};
899
901 uint32_t NumValueKinds = 0;
902 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
903 NumValueKinds += !(getValueSitesForKind(Kind).empty());
904 return NumValueKinds;
905}
906
908 uint32_t N = 0;
909 for (const auto &SR : getValueSitesForKind(ValueKind))
910 N += SR.ValueData.size();
911 return N;
912}
913
915 return getValueSitesForKind(ValueKind).size();
916}
917
919 uint32_t Site) const {
920 return getValueSitesForKind(ValueKind)[Site].ValueData.size();
921}
922
923std::unique_ptr<InstrProfValueData[]>
925 uint64_t *TotalC) const {
926 uint64_t Dummy = 0;
927 uint64_t &TotalCount = (TotalC == nullptr ? Dummy : *TotalC);
928 uint32_t N = getNumValueDataForSite(ValueKind, Site);
929 if (N == 0) {
930 TotalCount = 0;
931 return std::unique_ptr<InstrProfValueData[]>(nullptr);
932 }
933
934 auto VD = std::make_unique<InstrProfValueData[]>(N);
935 TotalCount = getValueForSite(VD.get(), ValueKind, Site);
936
937 return VD;
938}
939
941 uint32_t ValueKind,
942 uint32_t Site) const {
943 uint32_t I = 0;
944 uint64_t TotalCount = 0;
945 for (auto V : getValueSitesForKind(ValueKind)[Site].ValueData) {
946 Dest[I].Value = V.Value;
947 Dest[I].Count = V.Count;
948 TotalCount = SaturatingAdd(TotalCount, V.Count);
949 I++;
950 }
951 return TotalCount;
952}
953
954void InstrProfRecord::reserveSites(uint32_t ValueKind, uint32_t NumValueSites) {
955 if (!NumValueSites)
956 return;
957 getOrCreateValueSitesForKind(ValueKind).reserve(NumValueSites);
958}
959
960// Include definitions for value profile data
961#define INSTR_PROF_VALUE_PROF_DATA
963
965 ValueData.sort(
966 [](const InstrProfValueData &left, const InstrProfValueData &right) {
967 return left.Count > right.Count;
968 });
969 // Now truncate
970 size_t max_s = INSTR_PROF_MAX_NUM_VAL_PER_SITE;
971 if (ValueData.size() > max_s)
972 ValueData.resize(max_s);
973}
974
975namespace IndexedInstrProf {
976
977enum class HashT : uint32_t {
978 MD5,
979 Last = MD5
980};
981
983 switch (Type) {
984 case HashT::MD5:
985 return MD5Hash(K);
986 }
987 llvm_unreachable("Unhandled hash type");
988}
989
990const uint64_t Magic = 0x8169666f72706cff; // "\xfflprofi\x81"
991
993 // Version 1 is the first version. In this version, the value of
994 // a key/value pair can only include profile data of a single function.
995 // Due to this restriction, the number of block counters for a given
996 // function is not recorded but derived from the length of the value.
998 // The version 2 format supports recording profile data of multiple
999 // functions which share the same key in one value field. To support this,
1000 // the number block counters is recorded as an uint64_t field right after the
1001 // function structural hash.
1003 // Version 3 supports value profile data. The value profile data is expected
1004 // to follow the block counter profile data.
1006 // In this version, profile summary data \c IndexedInstrProf::Summary is
1007 // stored after the profile header.
1009 // In this version, the frontend PGO stable hash algorithm defaults to V2.
1011 // In this version, the frontend PGO stable hash algorithm got fixed and
1012 // may produce hashes different from Version5.
1014 // An additional counter is added around logical operators.
1016 // An additional (optional) memory profile type is added.
1018 // Binary ids are added.
1020 // An additional (optional) temporal profile traces section is added.
1022 // An additional field is used for bitmap bytes.
1024 // The current version is 11.
1025 CurrentVersion = INSTR_PROF_INDEX_VERSION
1028
1030
1032
1033// This structure defines the file header of the LLVM profile
1034// data file in indexed-format.
1035struct Header {
1038 uint64_t Unused; // Becomes unused since version 4
1044 // New fields should only be added at the end to ensure that the size
1045 // computation is correct. The methods below need to be updated to ensure that
1046 // the new field is read correctly.
1047
1048 // Reads a header struct from the buffer.
1049 static Expected<Header> readFromBuffer(const unsigned char *Buffer);
1050
1051 // Returns the size of the header in bytes for all valid fields based on the
1052 // version. I.e a older version header will return a smaller size.
1053 size_t size() const;
1054
1055 // Returns the format version in little endian. The header retains the version
1056 // in native endian of the compiler runtime.
1057 uint64_t formatVersion() const;
1058};
1059
1060// Profile summary data recorded in the profile data file in indexed
1061// format. It is introduced in version 4. The summary data follows
1062// right after the profile file header.
1063struct Summary {
1064 struct Entry {
1065 uint64_t Cutoff; ///< The required percentile of total execution count.
1066 uint64_t
1067 MinBlockCount; ///< The minimum execution count for this percentile.
1068 uint64_t NumBlocks; ///< Number of blocks >= the minumum execution count.
1069 };
1070 // The field kind enumerator to assigned value mapping should remain
1071 // unchanged when a new kind is added or an old kind gets deleted in
1072 // the future.
1074 /// The total number of functions instrumented.
1076 /// Total number of instrumented blocks/edges.
1078 /// The maximal execution count among all functions.
1079 /// This field does not exist for profile data from IR based
1080 /// instrumentation.
1082 /// Max block count of the program.
1084 /// Max internal block count of the program (excluding entry blocks).
1086 /// The sum of all instrumented block counts.
1090
1091 // The number of summmary fields following the summary header.
1093 // The number of Cutoff Entries (Summary::Entry) following summary fields.
1095
1096 Summary() = delete;
1097 Summary(uint32_t Size) { memset(this, 0, Size); }
1098
1099 void operator delete(void *ptr) { ::operator delete(ptr); }
1100
1102 return sizeof(Summary) + NumCutoffEntries * sizeof(Entry) +
1103 NumSumFields * sizeof(uint64_t);
1104 }
1105
1107 return reinterpret_cast<const uint64_t *>(this + 1);
1108 }
1109
1111 return reinterpret_cast<uint64_t *>(this + 1);
1112 }
1113
1114 const Entry *getCutoffEntryBase() const {
1115 return reinterpret_cast<const Entry *>(
1117 }
1118
1120 return reinterpret_cast<Entry *>(&getSummaryDataBase()[NumSummaryFields]);
1121 }
1122
1124 return getSummaryDataBase()[K];
1125 }
1126
1128 getSummaryDataBase()[K] = V;
1129 }
1130
1131 const Entry &getEntry(uint32_t I) const { return getCutoffEntryBase()[I]; }
1132
1134 Entry &ER = getCutoffEntryBase()[I];
1135 ER.Cutoff = E.Cutoff;
1136 ER.MinBlockCount = E.MinCount;
1137 ER.NumBlocks = E.NumCounts;
1138 }
1139};
1140
1141inline std::unique_ptr<Summary> allocSummary(uint32_t TotalSize) {
1142 return std::unique_ptr<Summary>(new (::operator new(TotalSize))
1143 Summary(TotalSize));
1144}
1145
1146} // end namespace IndexedInstrProf
1147
1148namespace RawInstrProf {
1149
1150// Version 1: First version
1151// Version 2: Added value profile data section. Per-function control data
1152// struct has more fields to describe value profile information.
1153// Version 3: Compressed name section support. Function PGO name reference
1154// from control data struct is changed from raw pointer to Name's MD5 value.
1155// Version 4: ValueDataBegin and ValueDataSizes fields are removed from the
1156// raw header.
1157// Version 5: Bit 60 of FuncHash is reserved for the flag for the context
1158// sensitive records.
1159// Version 6: Added binary id.
1160// Version 7: Reorder binary id and include version in signature.
1161// Version 8: Use relative counter pointer.
1162// Version 9: Added relative bitmap bytes pointer and count used by MC/DC.
1163const uint64_t Version = INSTR_PROF_RAW_VERSION;
1164
1165template <class IntPtrT> inline uint64_t getMagic();
1166template <> inline uint64_t getMagic<uint64_t>() {
1167 return INSTR_PROF_RAW_MAGIC_64;
1168}
1169
1170template <> inline uint64_t getMagic<uint32_t>() {
1171 return INSTR_PROF_RAW_MAGIC_32;
1172}
1173
1174// Per-function profile data header/control structure.
1175// The definition should match the structure defined in
1176// compiler-rt/lib/profile/InstrProfiling.h.
1177// It should also match the synthesized type in
1178// Transforms/Instrumentation/InstrProfiling.cpp:getOrCreateRegionCounters.
1179template <class IntPtrT> struct alignas(8) ProfileData {
1180 #define INSTR_PROF_DATA(Type, LLVMType, Name, Init) Type Name;
1182};
1183
1184// File header structure of the LLVM profile data in raw format.
1185// The definition should match the header referenced in
1186// compiler-rt/lib/profile/InstrProfilingFile.c and
1187// InstrProfilingBuffer.c.
1188struct Header {
1189#define INSTR_PROF_RAW_HEADER(Type, Name, Init) const Type Name;
1191};
1192
1193} // end namespace RawInstrProf
1194
1195// Create the variable for the profile file name.
1196void createProfileFileNameVar(Module &M, StringRef InstrProfileOutput);
1197
1198// Whether to compress function names in profile records, and filenames in
1199// code coverage mappings. Used by the Instrumentation library and unit tests.
1200extern cl::opt<bool> DoInstrProfNameCompression;
1201
1202} // end namespace llvm
1203#endif // LLVM_PROFILEDATA_INSTRPROF_H
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
uint64_t Addr
std::string Name
uint64_t Size
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
Machine Check Debug Module
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file contains some templates that are useful if you are working with the STL at all.
raw_pwrite_stream & OS
StringSet - A set-like wrapper for the StringMap.
Value * RHS
Value * LHS
Base class for user error types.
Definition: Error.h:352
Lightweight error class with error context and mandatory checking.
Definition: Error.h:160
static ErrorSuccess success()
Create a success value.
Definition: Error.h:334
Tagged union holding either a T or a Error.
Definition: Error.h:474
LinkageTypes
An enumeration for the kinds of linkage for global values.
Definition: GlobalValue.h:47
void log(raw_ostream &OS) const override
Print an error message to an output stream.
Definition: InstrProf.h:378
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:390
const std::string & getMessage() const
Definition: InstrProf.h:385
static char ID
Definition: InstrProf.h:401
instrprof_error get() const
Definition: InstrProf.h:384
std::error_code convertToErrorCode() const override
Convert this error to a std::error_code.
Definition: InstrProf.h:380
std::string message() const override
Return the error message as a string.
Definition: InstrProf.cpp:243
InstrProfError(instrprof_error Err, const Twine &ErrStr=Twine())
Definition: InstrProf.h:371
A symbol table used for function PGO name look-up with keys (such as pointers, md5hash values) to the...
Definition: InstrProf.h:425
static bool isExternalSymbol(const StringRef &Symbol)
True if Symbol is the value used to represent external symbols.
Definition: InstrProf.h:525
uint64_t getFunctionHashFromAddress(uint64_t Address)
Return a function's hash, or 0, if the function isn't in this SymTab.
Definition: InstrProf.cpp:546
std::vector< std::pair< uint64_t, uint64_t > > AddrHashMap
Definition: InstrProf.h:427
StringRef getFuncOrVarName(uint64_t ValMD5Hash)
Return name of functions or global variables from the name's md5 hash value.
Definition: InstrProf.h:573
void mapAddress(uint64_t Addr, uint64_t MD5Val)
Map a function address to its name's MD5 hash.
Definition: InstrProf.h:503
void dumpNames(raw_ostream &OS) const
Dump the symbols in this table.
Definition: InstrProf.cpp:560
Function * getFunction(uint64_t FuncMD5Hash)
Return function from the name's md5 hash. Return nullptr if not found.
Definition: InstrProf.h:583
StringRef getNameData() const
Return the name section data.
Definition: InstrProf.h:533
Error create(object::SectionRef &Section)
Create InstrProfSymtab from an object file section which contains function PGO names.
Error addFuncName(StringRef FuncName)
Update the symtab by adding FuncName to the table.
Definition: InstrProf.h:488
StringRef getFuncName(uint64_t FuncNameAddress, size_t NameSize)
Return function's PGO name from the function name's symbol address in the object file.
StringRef getFuncOrVarNameIfDefined(uint64_t ValMD5Hash)
Just like getFuncOrVarName, except that it will return literal string 'External Symbol' if the functi...
Definition: InstrProf.h:566
Definition: MD5.h:41
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
constexpr bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:134
StringSet - A wrapper for StringMap that provides set-like functionality.
Definition: StringSet.h:23
std::pair< typename Base::iterator, bool > insert(StringRef key)
Definition: StringSet.h:34
ObjectFormatType
Definition: Triple.h:281
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
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:81
A raw_ostream that writes to a file descriptor.
Definition: raw_ostream.h:454
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:52
#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:1141
uint64_t ComputeHash(StringRef K)
Definition: InstrProf.h:1031
const uint64_t Version
Definition: InstrProf.h:1027
const uint64_t Magic
Definition: InstrProf.h:990
const HashT HashType
Definition: InstrProf.h:1029
uint64_t getMagic()
const uint64_t Version
Definition: InstrProf.h:1163
uint64_t getMagic< uint32_t >()
Definition: InstrProf.h:1170
uint64_t getMagic< uint64_t >()
Definition: InstrProf.h:1166
constexpr size_t NameSize
Definition: XCOFF.h:29
uint64_t MD5Hash(const FunctionId &Obj)
Definition: FunctionId.h:167
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
bool getValueProfDataFromInst(const Instruction &Inst, InstrProfValueKind ValueKind, uint32_t MaxNumValueData, InstrProfValueData ValueData[], uint32_t &ActualNumValueData, uint64_t &TotalC, bool GetNoICPValue=false)
Extract the value profile data from Inst which is annotated with value profile meta data.
Definition: InstrProf.cpp:1202
StringRef getInstrProfNameVarPrefix()
Return the name prefix of variables containing instrumented function names.
Definition: InstrProf.h:90
std::string getPGOFuncName(const Function &F, bool InLTO=false, uint64_t Version=INSTR_PROF_INDEX_VERSION)
Return the modified name for function F suitable to be used the key for profile lookup.
Definition: InstrProf.cpp:359
StringRef getInstrProfRuntimeHookVarName()
Return the name of the hook variable defined in profile runtime library.
Definition: InstrProf.h:157
void createPGOFuncNameMetadata(Function &F, StringRef PGOFuncName)
Create the PGOFuncName meta data if PGOFuncName is different from function's raw name.
Definition: InstrProf.cpp:1262
std::string getIRPGOFuncName(const Function &F, bool InLTO=false)
Definition: InstrProf.cpp:351
std::error_code make_error_code(BitcodeError E)
StringRef getPGOFuncNameMetadataName()
Definition: InstrProf.h:282
StringRef getCoverageMappingVarName()
Return the name of a covarage mapping variable (internal linkage) for each instrumented source module...
Definition: InstrProf.h:116
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:970
StringRef getInstrProfBitmapVarPrefix()
Return the name prefix of profile bitmap variables.
Definition: InstrProf.h:99
cl::opt< bool > DoInstrProfNameCompression
StringRef getFuncNameWithoutPrefix(StringRef PGOFuncName, StringRef FileName="<unknown>")
Given a PGO function name, remove the filename prefix and return the original (static) function name.
Definition: InstrProf.cpp:384
MDNode * getPGOFuncNameMetadata(const Function &F)
Return the PGOFuncName meta data associated with a function.
Definition: InstrProf.cpp:1258
StringRef getInstrProfDataVarPrefix()
Return the name prefix of variables containing per-function control data.
Definition: InstrProf.h:93
StringRef getCoverageUnusedNamesVarName()
Return the name of the internal variable recording the array of PGO name vars referenced by the cover...
Definition: InstrProf.h:124
std::string getInstrProfSectionName(InstrProfSectKind IPSK, Triple::ObjectFormatType OF, bool AddSegmentInfo=true)
Return the name of the profile section corresponding to IPSK.
Definition: InstrProf.cpp:224
uint64_t getInstrMaxCountValue()
Return the max count value. We reserver a few large values for special use.
Definition: InstrProf.h:64
StringRef getInstrProfInitFuncName()
Return the name of the runtime initialization method that is generated by the compiler.
Definition: InstrProf.h:152
StringRef getInstrProfValuesVarPrefix()
Return the name prefix of value profile variables.
Definition: InstrProf.h:102
StringRef getInstrProfCounterBiasVarName()
Definition: InstrProf.h:167
GlobalVariable * createPGOFuncNameVar(Function &F, StringRef PGOFuncName)
Create and return the global variable for function name used in PGO instrumentation.
Definition: InstrProf.cpp:440
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...
Definition: InstrProf.cpp:1157
StringRef getInstrProfRuntimeHookVarUseFuncName()
Return the name of the compiler generated function that references the runtime hook variable.
Definition: InstrProf.h:163
std::pair< StringRef, StringRef > getParsedIRPGOFuncName(StringRef IRPGOFuncName)
Definition: InstrProf.cpp:377
StringRef getInstrProfRegFuncsName()
Return the name of function that registers all the per-function control data at program startup time ...
Definition: InstrProf.h:133
Error collectPGOFuncNameStrings(ArrayRef< GlobalVariable * > NameVars, std::string &Result, bool doCompression=true)
Produce Result string with the same format described above.
Definition: InstrProf.cpp:612
void sort(IteratorTy Start, IteratorTy End)
Definition: STLExtras.h:1651
InstrProfSectKind
Definition: InstrProf.h:58
StringRef getInstrProfCountersVarPrefix()
Return the name prefix of profile counter variables.
Definition: InstrProf.h:96
StringRef getPGOFuncNameVarInitializer(GlobalVariable *NameVar)
Return the initializer in string of the PGO name var NameVar.
Definition: InstrProf.cpp:605
StringRef getInstrProfNameSeparator()
Return the marker used to separate PGO names during serialization.
Definition: InstrProf.h:172
StringRef getInstrProfValueProfMemOpFuncName()
Return the name profile runtime entry point to do memop size value profiling.
Definition: InstrProf.h:85
@ Other
Any other memory.
instrprof_error
Definition: InstrProf.h:320
InstrProfValueKind
Definition: InstrProf.h:254
StringRef getInstrProfNamesRegFuncName()
Return the name of the runtime interface that registers the PGO name strings.
Definition: InstrProf.h:144
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:1945
const std::error_category & instrprof_category()
Definition: InstrProf.cpp:191
bool needsComdatForCounter(const Function &F, const Module &M)
Check if we can use Comdat for profile variables.
Definition: InstrProf.cpp:1274
bool canRenameComdatFunc(const Function &F, bool CheckAddressTaken=false)
Check if we can safely rename this Comdat function.
Definition: InstrProf.cpp:1322
void createProfileFileNameVar(Module &M, StringRef InstrProfileOutput)
Definition: InstrProf.cpp:1345
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,...
Definition: InstrProf.cpp:567
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:1853
StringRef getInstrProfValueProfFuncName()
Return the name profile runtime entry point to do value profiling for a given site.
Definition: InstrProf.h:79
StringRef getInstrProfRegFuncName()
Return the name of the runtime interface that registers per-function control data for one instrumente...
Definition: InstrProf.h:139
std::string getPGOFuncNameVarName(StringRef FuncName, GlobalValue::LinkageTypes Linkage)
Return the name of the global variable used to store a function name in PGO instrumentation.
Definition: InstrProf.cpp:395
std::enable_if_t< std::is_unsigned_v< T >, T > SaturatingAdd(T X, T Y, bool *ResultOverflowed=nullptr)
Add two unsigned integers, X and Y, of type T.
Definition: MathExtras.h:478
StringRef getInstrProfNamesVarName()
Return the name of the variable holding the strings (possibly compressed) of all function's PGO names...
Definition: InstrProf.h:109
bool isIRPGOFlagSet(const Module *M)
Check if INSTR_PROF_RAW_VERSION_VAR is defined.
Definition: InstrProf.cpp:1300
StringRef getInstrProfVNodesVarName()
Return the name of value profile node array variables:
Definition: InstrProf.h:105
InstrProfKind
An enum describing the attributes of an instrumented profile.
Definition: InstrProf.h:297
Implement std::hash so that hash_code can be used in STL containers.
Definition: BitVector.h:858
#define N
double ValueCounts[IPVK_Last - IPVK_First+1]
Definition: InstrProf.h:598
uint64_t formatVersion() const
Definition: InstrProf.cpp:1490
static Expected< Header > readFromBuffer(const unsigned char *Buffer)
Definition: InstrProf.cpp:1495
uint64_t Cutoff
The required percentile of total execution count.
Definition: InstrProf.h:1065
uint64_t NumBlocks
Number of blocks >= the minumum execution count.
Definition: InstrProf.h:1068
uint64_t MinBlockCount
The minimum execution count for this percentile.
Definition: InstrProf.h:1067
const Entry * getCutoffEntryBase() const
Definition: InstrProf.h:1114
uint64_t get(SummaryFieldKind K) const
Definition: InstrProf.h:1123
void set(SummaryFieldKind K, uint64_t V)
Definition: InstrProf.h:1127
void setEntry(uint32_t I, const ProfileSummaryEntry &E)
Definition: InstrProf.h:1133
@ TotalNumFunctions
The total number of functions instrumented.
Definition: InstrProf.h:1075
@ TotalNumBlocks
Total number of instrumented blocks/edges.
Definition: InstrProf.h:1077
@ MaxFunctionCount
The maximal execution count among all functions.
Definition: InstrProf.h:1081
@ TotalBlockCount
The sum of all instrumented block counts.
Definition: InstrProf.h:1087
@ MaxBlockCount
Max block count of the program.
Definition: InstrProf.h:1083
@ MaxInternalBlockCount
Max internal block count of the program (excluding entry blocks).
Definition: InstrProf.h:1085
const uint64_t * getSummaryDataBase() const
Definition: InstrProf.h:1106
static uint32_t getSize(uint32_t NumSumFields, uint32_t NumCutoffEntries)
Definition: InstrProf.h:1101
const Entry & getEntry(uint32_t I) const
Definition: InstrProf.h:1131
Profiling information for a single function.
Definition: InstrProf.h:689
void overlapValueProfData(uint32_t ValueKind, InstrProfRecord &Src, OverlapStats &Overlap, OverlapStats &FuncLevelOverlap)
Compute the overlap of value profile counts.
Definition: InstrProf.cpp:673
std::vector< uint64_t > Counts
Definition: InstrProf.h:690
CountPseudoKind getCountPseudoKind() const
Definition: InstrProf.h:800
InstrProfRecord(std::vector< uint64_t > Counts)
Definition: InstrProf.h:694
void accumulateCounts(CountSumOrPercent &Sum) const
Compute the sums of all counts and store in Sum.
Definition: InstrProf.cpp:622
uint32_t getNumValueSites(uint32_t ValueKind) const
Return the number of instrumented sites for ValueKind.
Definition: InstrProf.h:914
uint32_t getNumValueKinds() const
Return the number of value profile kinds with non-zero number of profile sites.
Definition: InstrProf.h:900
void setPseudoCount(CountPseudoKind Kind)
Definition: InstrProf.h:808
InstrProfRecord(InstrProfRecord &&)=default
uint32_t getNumValueData(uint32_t ValueKind) const
Return the total number of ValueData for ValueKind.
Definition: InstrProf.h:907
void merge(InstrProfRecord &Other, uint64_t Weight, function_ref< void(instrprof_error)> Warn)
Merge the counts in Other into this one.
Definition: InstrProf.cpp:795
void addValueData(uint32_t ValueKind, uint32_t Site, InstrProfValueData *VData, uint32_t N, InstrProfSymtab *SymTab)
Add ValueData for ValueKind at value Site.
Definition: InstrProf.cpp:887
InstrProfRecord & operator=(const InstrProfRecord &RHS)
Definition: InstrProf.h:705
void clearValueData()
Clear value data entries.
Definition: InstrProf.h:777
InstrProfRecord(const InstrProfRecord &RHS)
Definition: InstrProf.h:699
uint32_t getNumValueDataForSite(uint32_t ValueKind, uint32_t Site) const
Return the number of value data collected for ValueKind at profiling site: Site.
Definition: InstrProf.h:918
InstrProfRecord(std::vector< uint64_t > Counts, std::vector< uint8_t > BitmapBytes)
Definition: InstrProf.h:695
void reserveSites(uint32_t ValueKind, uint32_t NumValueSites)
Reserve space for NumValueSites sites.
Definition: InstrProf.h:954
void overlap(InstrProfRecord &Other, OverlapStats &Overlap, OverlapStats &FuncLevelOverlap, uint64_t ValueCutoff)
Compute the overlap b/w this IntrprofRecord and Other.
Definition: InstrProf.cpp:691
void sortValueData()
Sort value profile data (per site) by count.
Definition: InstrProf.h:764
std::vector< uint8_t > BitmapBytes
Definition: InstrProf.h:691
std::unique_ptr< InstrProfValueData[]> getValueForSite(uint32_t ValueKind, uint32_t Site, uint64_t *TotalC=nullptr) const
Return the array of profiled values at Site.
Definition: InstrProf.h:924
InstrProfRecord & operator=(InstrProfRecord &&)=default
void Clear()
Clear value data entries and edge counters.
Definition: InstrProf.h:771
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).
Definition: InstrProf.cpp:858
InstrProfValueSiteRecord(InputIterator F, InputIterator L)
Definition: InstrProf.h:663
void sortByCount()
Sort ValueData Descending by Count.
Definition: InstrProf.h:964
void sortByTargetValues()
Sort ValueData ascending by Value.
Definition: InstrProf.h:667
void merge(InstrProfValueSiteRecord &Input, uint64_t Weight, function_ref< void(instrprof_error)> Warn)
Merge data from another InstrProfValueSiteRecord Optionally scale merged counts by Weight.
Definition: InstrProf.cpp:742
void overlap(InstrProfValueSiteRecord &Input, uint32_t ValueKind, OverlapStats &Overlap, OverlapStats &FuncLevelOverlap)
Compute the overlap b/w this record and Input record.
Definition: InstrProf.cpp:642
std::list< InstrProfValueData > ValueData
Value profiling data pairs at a given value site.
Definition: InstrProf.h:659
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).
Definition: InstrProf.cpp:764
static bool hasCSFlagInHash(uint64_t FuncHash)
Definition: InstrProf.h:892
NamedInstrProfRecord(StringRef Name, uint64_t Hash, std::vector< uint64_t > Counts)
Definition: InstrProf.h:883
NamedInstrProfRecord(StringRef Name, uint64_t Hash, std::vector< uint64_t > Counts, std::vector< uint8_t > BitmapBytes)
Definition: InstrProf.h:886
static void setCSFlagInHash(uint64_t &FuncHash)
Definition: InstrProf.h:895
static const int CS_FLAG_IN_FUNC_HASH
Definition: InstrProf.h:880
const std::string NameFilter
Definition: InstrProf.h:654
void addOneMismatch(const CountSumOrPercent &MismatchFunc)
Definition: InstrProf.cpp:1390
static double score(uint64_t Val1, uint64_t Val2, double Sum1, double Sum2)
Definition: InstrProf.h:642
Error accumulateCounts(const std::string &BaseFilename, const std::string &TestFilename, bool IsCS)
Definition: InstrProf.cpp:1362
void dump(raw_fd_ostream &OS) const
Definition: InstrProf.cpp:1409
CountSumOrPercent Overlap
Definition: InstrProf.h:616
CountSumOrPercent Base
Definition: InstrProf.h:612
uint64_t FuncHash
Definition: InstrProf.h:623
void addOneUnique(const CountSumOrPercent &UniqueFunc)
Definition: InstrProf.cpp:1400
const std::string * BaseFilename
Definition: InstrProf.h:620
const std::string * TestFilename
Definition: InstrProf.h:621
void setFuncInfo(StringRef Name, uint64_t Hash)
Definition: InstrProf.h:632
CountSumOrPercent Unique
Definition: InstrProf.h:618
CountSumOrPercent Mismatch
Definition: InstrProf.h:617
StringRef FuncName
Definition: InstrProf.h:622
OverlapStatsLevel Level
Definition: InstrProf.h:619
OverlapStats(OverlapStatsLevel L=ProgramLevel)
Definition: InstrProf.h:626
CountSumOrPercent Test
Definition: InstrProf.h:614
An ordered list of functions identified by their NameRef found in INSTR_PROF_DATA.
Definition: InstrProf.h:351
static std::vector< BPFunctionNode > createBPFunctionNodes(ArrayRef< TemporalProfTraceTy > Traces)
Use a set of temporal profile traces to create a list of balanced partitioning function nodes used by...
Definition: InstrProf.cpp:901
std::vector< uint64_t > FunctionNameRefs
Definition: InstrProf.h:352
TemporalProfTraceTy(std::initializer_list< uint64_t > Trace={}, uint64_t Weight=1)
Definition: InstrProf.h:354
Function object to check whether the first component of a container supported by std::get (like std::...
Definition: STLExtras.h:1454