LLVM 19.0.0git
InstrProfWriter.h
Go to the documentation of this file.
1//===- InstrProfWriter.h - Instrumented profiling writer --------*- 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// This file contains support for writing profiling data for instrumentation
10// based PGO and coverage.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_PROFILEDATA_INSTRPROFWRITER_H
15#define LLVM_PROFILEDATA_INSTRPROFWRITER_H
16
17#include "llvm/ADT/DenseMap.h"
18#include "llvm/ADT/MapVector.h"
19#include "llvm/ADT/StringMap.h"
20#include "llvm/IR/GlobalValue.h"
21#include "llvm/Object/BuildID.h"
24#include "llvm/Support/Error.h"
25#include <cstdint>
26#include <memory>
27#include <random>
28
29namespace llvm {
30
31/// Writer for instrumentation based profile data.
32class InstrProfRecordWriterTrait;
33class ProfOStream;
34class MemoryBuffer;
35class raw_fd_ostream;
36
38public:
40
41private:
42 bool Sparse;
43 StringMap<ProfilingData> FunctionData;
44 /// The maximum length of a single temporal profile trace.
45 uint64_t MaxTemporalProfTraceLength;
46 /// The maximum number of stored temporal profile traces.
47 uint64_t TemporalProfTraceReservoirSize;
48 /// The total number of temporal profile traces seen.
49 uint64_t TemporalProfTraceStreamSize = 0;
50 /// The list of temporal profile traces.
51 SmallVector<TemporalProfTraceTy> TemporalProfTraces;
52 std::mt19937 RNG;
53
54 // A map to hold memprof data per function. The lower 64 bits obtained from
55 // the md5 hash of the function name is used to index into the map.
57 MemProfRecordData;
58 // A map to hold frame id to frame mappings. The mappings are used to
59 // convert IndexedMemProfRecord to MemProfRecords with frame information
60 // inline.
62
63 // A map to hold call stack id to call stacks.
65 MemProfCallStackData;
66
67 // List of binary ids.
68 std::vector<llvm::object::BuildID> BinaryIds;
69
70 // Read the vtable names from raw instr profile reader.
71 StringSet<> VTableNames;
72
73 // An enum describing the attributes of the profile.
75 // Use raw pointer here for the incomplete type object.
77
78 // Temporary support for writing the previous version of the format, to enable
79 // some forward compatibility. Currently this suppresses the writing of the
80 // new vtable names section and header fields.
81 // TODO: Consider enabling this with future version changes as well, to ease
82 // deployment of newer versions of llvm-profdata.
83 bool WritePrevVersion = false;
84
85 // The MemProf version we should write.
86 memprof::IndexedVersion MemProfVersionRequested;
87
88 // Whether to serialize the full schema.
89 bool MemProfFullSchema;
90
91public:
93 bool Sparse = false, uint64_t TemporalProfTraceReservoirSize = 0,
94 uint64_t MaxTemporalProfTraceLength = 0, bool WritePrevVersion = false,
95 memprof::IndexedVersion MemProfVersionRequested = memprof::Version0,
96 bool MemProfFullSchema = false);
98
99 StringMap<ProfilingData> &getProfileData() { return FunctionData; }
100
101 /// Add function counts for the given function. If there are already counts
102 /// for this function and the hash and number of counts match, each counter is
103 /// summed. Optionally scale counts by \p Weight.
105 function_ref<void(Error)> Warn);
107 addRecord(std::move(I), 1, Warn);
108 }
109 void addVTableName(StringRef VTableName) { VTableNames.insert(VTableName); }
110
111 /// Add \p SrcTraces using reservoir sampling where \p SrcStreamSize is the
112 /// total number of temporal profiling traces the source has seen.
114 uint64_t SrcStreamSize);
115
116 /// Add a memprof record for a function identified by its \p Id.
119
120 /// Add a memprof frame identified by the hash of the contents of the frame in
121 /// \p FrameId.
123 function_ref<void(Error)> Warn);
124
125 /// Add a call stack identified by the hash of the contents of the call stack
126 /// in \p CallStack.
129 function_ref<void(Error)> Warn);
130
131 // Add a binary id to the binary ids list.
133
134 /// Merge existing function counts from the given writer.
136 function_ref<void(Error)> Warn);
137
138 /// Write the profile to \c OS
140
141 /// Write the profile to a string output stream \c OS
143
144 /// Write the profile in text format to \c OS
146
147 /// Write temporal profile trace data to the header in text format to \c OS
149 InstrProfSymtab &Symtab);
150
152
153 /// Write \c Record in text format to \c OS
154 static void writeRecordInText(StringRef Name, uint64_t Hash,
155 const InstrProfRecord &Counters,
157
158 /// Write the profile, returning the raw data. For testing.
159 std::unique_ptr<MemoryBuffer> writeBuffer();
160
161 /// Update the attributes of the current profile from the attributes
162 /// specified. An error is returned if IR and FE profiles are mixed.
164 // If the kind is unset, this is the first profile we are merging so just
165 // set it to the given type.
166 if (ProfileKind == InstrProfKind::Unknown) {
167 ProfileKind = Other;
168 return Error::success();
169 }
170
171 // Returns true if merging is should fail assuming A and B are incompatible.
172 auto testIncompatible = [&](InstrProfKind A, InstrProfKind B) {
173 return (static_cast<bool>(ProfileKind & A) &&
174 static_cast<bool>(Other & B)) ||
175 (static_cast<bool>(ProfileKind & B) &&
176 static_cast<bool>(Other & A));
177 };
178
179 // Check if the profiles are in-compatible. Clang frontend profiles can't be
180 // merged with other profile types.
181 if (static_cast<bool>(
184 return make_error<InstrProfError>(instrprof_error::unsupported_version);
185 }
186 if (testIncompatible(InstrProfKind::FunctionEntryOnly,
188 return make_error<InstrProfError>(
190 "cannot merge FunctionEntryOnly profiles and BB profiles together");
191 }
192
193 // Now we update the profile type with the bits that are set.
194 ProfileKind |= Other;
195 return Error::success();
196 }
197
198 InstrProfKind getProfileKind() const { return ProfileKind; }
199
201 return static_cast<bool>(ProfileKind & InstrProfKind::SingleByteCoverage);
202 }
203
204 // Internal interfaces for testing purpose only.
206 void setOutputSparse(bool Sparse);
208 MemProfVersionRequested = Version;
209 }
210 void setMemProfFullSchema(bool Full) { MemProfFullSchema = Full; }
211 // Compute the overlap b/w this object and Other. Program level result is
212 // stored in Overlap and function level result is stored in FuncLevelOverlap.
214 OverlapStats &FuncLevelOverlap,
215 const OverlapFuncFilters &FuncFilter);
216
217private:
219 uint64_t Weight, function_ref<void(Error)> Warn);
220 bool shouldEncodeData(const ProfilingData &PD);
221 /// Add \p Trace using reservoir sampling.
222 void addTemporalProfileTrace(TemporalProfTraceTy Trace);
223
224 Error writeImpl(ProfOStream &OS);
225};
226
227} // end namespace llvm
228
229#endif // LLVM_PROFILEDATA_INSTRPROFWRITER_H
This file defines the StringMap class.
This file declares a library for handling Build IDs and using them to find debug info.
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
This file defines the DenseMap class.
std::string Name
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
This file implements a map that provides insertion order iteration.
raw_pwrite_stream & OS
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
Lightweight error class with error context and mandatory checking.
Definition: Error.h:160
static ErrorSuccess success()
Create a success value.
Definition: Error.h:334
A symbol table used for function [IR]PGO name look-up with keys (such as pointers,...
Definition: InstrProf.h:451
bool hasSingleByteCoverage() const
void addVTableName(StringRef VTableName)
Error write(raw_fd_ostream &OS)
Write the profile to OS.
void addTemporalProfileTraces(SmallVectorImpl< TemporalProfTraceTy > &SrcTraces, uint64_t SrcStreamSize)
Add SrcTraces using reservoir sampling where SrcStreamSize is the total number of temporal profiling ...
void overlapRecord(NamedInstrProfRecord &&Other, OverlapStats &Overlap, OverlapStats &FuncLevelOverlap, const OverlapFuncFilters &FuncFilter)
Error writeText(raw_fd_ostream &OS)
Write the profile in text format to OS.
InstrProfKind getProfileKind() const
void addRecord(NamedInstrProfRecord &&I, function_ref< void(Error)> Warn)
void addBinaryIds(ArrayRef< llvm::object::BuildID > BIs)
void addMemProfRecord(const GlobalValue::GUID Id, const memprof::IndexedMemProfRecord &Record)
Add a memprof record for a function identified by its Id.
void setMemProfVersionRequested(memprof::IndexedVersion Version)
static void writeRecordInText(StringRef Name, uint64_t Hash, const InstrProfRecord &Counters, InstrProfSymtab &Symtab, raw_fd_ostream &OS)
Write Record in text format to OS.
void setValueProfDataEndianness(llvm::endianness Endianness)
bool addMemProfCallStack(const memprof::CallStackId CSId, const llvm::SmallVector< memprof::FrameId > &CallStack, function_ref< void(Error)> Warn)
Add a call stack identified by the hash of the contents of the call stack in CallStack.
void addRecord(NamedInstrProfRecord &&I, uint64_t Weight, function_ref< void(Error)> Warn)
Add function counts for the given function.
void mergeRecordsFromWriter(InstrProfWriter &&IPW, function_ref< void(Error)> Warn)
Merge existing function counts from the given writer.
Error mergeProfileKind(const InstrProfKind Other)
Update the attributes of the current profile from the attributes specified.
void writeTextTemporalProfTraceData(raw_fd_ostream &OS, InstrProfSymtab &Symtab)
Write temporal profile trace data to the header in text format to OS.
SmallDenseMap< uint64_t, InstrProfRecord > ProfilingData
std::unique_ptr< MemoryBuffer > writeBuffer()
Write the profile, returning the raw data. For testing.
bool addMemProfFrame(const memprof::FrameId, const memprof::Frame &F, function_ref< void(Error)> Warn)
Add a memprof frame identified by the hash of the contents of the frame in FrameId.
void setOutputSparse(bool Sparse)
StringMap< ProfilingData > & getProfileData()
void setMemProfFullSchema(bool Full)
Error validateRecord(const InstrProfRecord &Func)
This class implements a map that also provides access to all stored values in a deterministic order.
Definition: MapVector.h:36
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:586
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1209
StringMap - This is an unconventional map that is specialized for handling keys that are "strings",...
Definition: StringMap.h:127
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
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:38
An efficient, type-erasing, non-owning reference to a callable.
A raw_ostream that writes to a file descriptor.
Definition: raw_ostream.h:470
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:660
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
@ Other
Any other memory.
endianness
Definition: bit.h:70
InstrProfKind
An enum describing the attributes of an instrumented profile.
Definition: InstrProf.h:323
Profiling information for a single function.
Definition: InstrProf.h:808
An ordered list of functions identified by their NameRef found in INSTR_PROF_DATA.
Definition: InstrProf.h:377