LLVM 19.0.0git
MemProfReader.h
Go to the documentation of this file.
1//===- MemProfReader.h - Instrumented memory profiling reader ---*- 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 reading MemProf profiling data.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_PROFILEDATA_MEMPROFREADER_H_
14#define LLVM_PROFILEDATA_MEMPROFREADER_H_
15
16#include "llvm/ADT/DenseMap.h"
17#include "llvm/ADT/MapVector.h"
18#include "llvm/ADT/StringRef.h"
21#include "llvm/IR/GlobalValue.h"
22#include "llvm/Object/Binary.h"
27#include "llvm/Support/Error.h"
29
30#include <functional>
31
32namespace llvm {
33namespace memprof {
34// A class for memprof profile data populated directly from external
35// sources.
37public:
38 // The MemProfReader only holds memory profile information.
40
41 using GuidMemProfRecordPair = std::pair<GlobalValue::GUID, MemProfRecord>;
43 Iterator end() { return Iterator(); }
45 Iter = FunctionProfileData.begin();
46 return Iterator(this);
47 }
48
49 // Return a const reference to the internal Id to Frame mappings.
51 return IdToFrame;
52 }
53
54 // Return a const reference to the internal Id to call stacks.
56 getCallStacks() const {
57 return CSIdToCallStack;
58 }
59
60 // Return a const reference to the internal function profile data.
64 }
65
66 virtual Error
68 std::function<const Frame(const FrameId)> Callback = nullptr) {
69 if (FunctionProfileData.empty())
70 return make_error<InstrProfError>(instrprof_error::empty_raw_profile);
71
72 if (Iter == FunctionProfileData.end())
73 return make_error<InstrProfError>(instrprof_error::eof);
74
75 if (Callback == nullptr)
76 Callback =
77 std::bind(&MemProfReader::idToFrame, this, std::placeholders::_1);
78
80 CSIdToCallStack, Callback);
81
82 const IndexedMemProfRecord &IndexedRecord = Iter->second;
83 GuidRecord = {
84 Iter->first,
85 IndexedRecord.toMemProfRecord(CSIdConv),
86 };
87 if (CSIdConv.LastUnmappedId)
88 return make_error<InstrProfError>(instrprof_error::hash_mismatch);
89 Iter++;
90 return Error::success();
91 }
92
93 // Allow default construction for derived classes which can populate the
94 // contents after construction.
95 MemProfReader() = default;
96 virtual ~MemProfReader() = default;
97
98 // Initialize the MemProfReader with the frame mappings and profile contents.
102
103 // Initialize the MemProfReader with the frame mappings, call stack mappings,
104 // and profile contents.
109 : IdToFrame(std::move(FrameIdMap)), CSIdToCallStack(std::move(CSIdMap)),
110 FunctionProfileData(std::move(ProfData)) {}
111
112protected:
113 // A helper method to extract the frame from the IdToFrame map.
114 const Frame &idToFrame(const FrameId Id) const {
115 auto It = IdToFrame.find(Id);
116 assert(It != IdToFrame.end() && "Id not found in map.");
117 return It->getSecond();
118 }
119 // A mapping from FrameId (a hash of the contents) to the frame.
121 // A mapping from CallStackId to the call stack.
123 // A mapping from function GUID, hash of the canonical function symbol to the
124 // memprof profile data for that function, i.e allocation and callsite info.
126 // An iterator to the internal function profile data structure.
128};
129
130// Map from id (recorded from sanitizer stack depot) to virtual addresses for
131// each program counter address in the callstack.
133
134// Specializes the MemProfReader class to populate the contents from raw binary
135// memprof profiles from instrumentation based profiling.
136class RawMemProfReader final : public MemProfReader {
137public:
140 virtual ~RawMemProfReader() override = default;
141
142 // Prints the contents of the profile in YAML format.
143 void printYAML(raw_ostream &OS);
144
145 // Return true if the \p DataBuffer starts with magic bytes indicating it is
146 // a raw binary memprof profile.
147 static bool hasFormat(const MemoryBuffer &DataBuffer);
148 // Return true if the file at \p Path starts with magic bytes indicating it is
149 // a raw binary memprof profile.
150 static bool hasFormat(const StringRef Path);
151
152 // Create a RawMemProfReader after sanity checking the contents of the file at
153 // \p Path or the \p Buffer. The binary from which the profile has been
154 // collected is specified via a path in \p ProfiledBinary.
156 create(const Twine &Path, StringRef ProfiledBinary, bool KeepName = false);
158 create(std::unique_ptr<MemoryBuffer> Buffer, StringRef ProfiledBinary,
159 bool KeepName = false);
160
161 // Returns a list of build ids recorded in the segment information.
162 static std::vector<std::string> peekBuildIds(MemoryBuffer *DataBuffer);
163
164 virtual Error
166 std::function<const Frame(const FrameId)> Callback) override;
167
168 // Constructor for unittests only.
169 RawMemProfReader(std::unique_ptr<llvm::symbolize::SymbolizableModule> Sym,
172 CallStackMap &SM, bool KeepName = false)
173 : SegmentInfo(Seg.begin(), Seg.end()), CallstackProfileData(Prof),
174 StackMap(SM), KeepSymbolName(KeepName) {
175 // We don't call initialize here since there is no raw profile to read. The
176 // test should pass in the raw profile as structured data.
177
178 // If there is an error here then the mock symbolizer has not been
179 // initialized properly.
180 if (Error E = symbolizeAndFilterStackFrames(std::move(Sym)))
181 report_fatal_error(std::move(E));
182 if (Error E = mapRawProfileToRecords())
183 report_fatal_error(std::move(E));
184 }
185
186private:
188 : Binary(std::move(Bin)), KeepSymbolName(KeepName) {}
189 // Initializes the RawMemProfReader with the contents in `DataBuffer`.
190 Error initialize(std::unique_ptr<MemoryBuffer> DataBuffer);
191 // Read and parse the contents of the `DataBuffer` as a binary format profile.
192 Error readRawProfile(std::unique_ptr<MemoryBuffer> DataBuffer);
193 // Initialize the segment mapping information for symbolization.
194 Error setupForSymbolization();
195 // Symbolize and cache all the virtual addresses we encounter in the
196 // callstacks from the raw profile. Also prune callstack frames which we can't
197 // symbolize or those that belong to the runtime. For profile entries where
198 // the entire callstack is pruned, we drop the entry from the profile.
199 Error symbolizeAndFilterStackFrames(
200 std::unique_ptr<llvm::symbolize::SymbolizableModule> Symbolizer);
201 // Construct memprof records for each function and store it in the
202 // `FunctionProfileData` map. A function may have allocation profile data or
203 // callsite data or both.
204 Error mapRawProfileToRecords();
205
206 object::SectionedAddress getModuleOffset(uint64_t VirtualAddress);
207
208 // The profiled binary.
210 // The preferred load address of the executable segment.
211 uint64_t PreferredTextSegmentAddress = 0;
212 // The base address of the text segment in the process during profiling.
213 uint64_t ProfiledTextSegmentStart = 0;
214 // The limit address of the text segment in the process during profiling.
215 uint64_t ProfiledTextSegmentEnd = 0;
216
217 // The memory mapped segment information for all executable segments in the
218 // profiled binary (filtered from the raw profile using the build id).
220
221 // A map from callstack id (same as key in CallStackMap below) to the heap
222 // information recorded for that allocation context.
223 llvm::MapVector<uint64_t, MemInfoBlock> CallstackProfileData;
224 CallStackMap StackMap;
225
226 // Cached symbolization from PC to Frame.
228
229 // Whether to keep the symbol name for each frame after hashing.
230 bool KeepSymbolName = false;
231 // A mapping of the hash to symbol name, only used if KeepSymbolName is true.
233};
234} // namespace memprof
235} // namespace llvm
236
237#endif // LLVM_PROFILEDATA_MEMPROFREADER_H_
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file defines the DenseMap class.
Symbol * Sym
Definition: ELF_riscv.cpp:479
This file implements a map that provides insertion order iteration.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
raw_pwrite_stream & OS
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
A file format agnostic iterator over profiling data.
This class implements a map that also provides access to all stored values in a deterministic order.
Definition: MapVector.h:36
typename VectorType::iterator iterator
Definition: MapVector.h:49
This interface provides simple read-only access to a block of memory, and provides simple methods for...
Definition: MemoryBuffer.h:51
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
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
const Frame & idToFrame(const FrameId Id) const
virtual ~MemProfReader()=default
InstrProfIterator< GuidMemProfRecordPair, MemProfReader > Iterator
Definition: MemProfReader.h:42
InstrProfKind getProfileKind() const
Definition: MemProfReader.h:39
const llvm::DenseMap< CallStackId, llvm::SmallVector< FrameId > > & getCallStacks() const
Definition: MemProfReader.h:56
const llvm::DenseMap< FrameId, Frame > & getFrameMapping() const
Definition: MemProfReader.h:50
virtual Error readNextRecord(GuidMemProfRecordPair &GuidRecord, std::function< const Frame(const FrameId)> Callback=nullptr)
Definition: MemProfReader.h:67
MemProfReader(llvm::DenseMap< FrameId, Frame > FrameIdMap, llvm::DenseMap< CallStackId, llvm::SmallVector< FrameId > > CSIdMap, llvm::MapVector< GlobalValue::GUID, IndexedMemProfRecord > ProfData)
llvm::DenseMap< FrameId, Frame > IdToFrame
llvm::MapVector< GlobalValue::GUID, IndexedMemProfRecord >::iterator Iter
const llvm::MapVector< GlobalValue::GUID, IndexedMemProfRecord > & getProfileData() const
Definition: MemProfReader.h:62
llvm::MapVector< GlobalValue::GUID, IndexedMemProfRecord > FunctionProfileData
std::pair< GlobalValue::GUID, MemProfRecord > GuidMemProfRecordPair
Definition: MemProfReader.h:41
llvm::DenseMap< CallStackId, llvm::SmallVector< FrameId > > CSIdToCallStack
virtual ~RawMemProfReader() override=default
void printYAML(raw_ostream &OS)
RawMemProfReader & operator=(const RawMemProfReader &)=delete
RawMemProfReader(const RawMemProfReader &)=delete
static Expected< std::unique_ptr< RawMemProfReader > > create(const Twine &Path, StringRef ProfiledBinary, bool KeepName=false)
static std::vector< std::string > peekBuildIds(MemoryBuffer *DataBuffer)
virtual Error readNextRecord(GuidMemProfRecordPair &GuidRecord, std::function< const Frame(const FrameId)> Callback) override
RawMemProfReader(std::unique_ptr< llvm::symbolize::SymbolizableModule > Sym, llvm::SmallVectorImpl< SegmentEntry > &Seg, llvm::MapVector< uint64_t, MemInfoBlock > &Prof, CallStackMap &SM, bool KeepName=false)
static bool hasFormat(const MemoryBuffer &DataBuffer)
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:52
llvm::DenseMap< uint64_t, llvm::SmallVector< uint64_t > > CallStackMap
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Definition: Error.cpp:156
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:1849
InstrProfKind
An enum describing the attributes of an instrumented profile.
Definition: InstrProf.h:323
Implement std::hash so that hash_code can be used in STL containers.
Definition: BitVector.h:858
MemProfRecord toMemProfRecord(std::function< const llvm::SmallVector< Frame >(const CallStackId)> Callback) const
Definition: MemProf.cpp:245