LLVM 22.0.0git
MemoryProfileInfo.h
Go to the documentation of this file.
1//===- llvm/Analysis/MemoryProfileInfo.h - memory profile info ---*- 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 utilities to analyze memory profile information.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_ANALYSIS_MEMORYPROFILEINFO_H
14#define LLVM_ANALYSIS_MEMORYPROFILEINFO_H
15
16#include "llvm/IR/Metadata.h"
19#include <map>
20
21namespace llvm {
22
24
25namespace memprof {
26
27/// Whether the alloc memeprof metadata will include context size info for all
28/// MIBs.
30
31/// Whether the alloc memprof metadata may include context size info for some
32/// MIBs (but possibly not all).
34
35/// Whether we need to record the context size info in the alloc trie used to
36/// build metadata.
38
39/// Build callstack metadata from the provided list of call stack ids. Returns
40/// the resulting metadata node.
42 LLVMContext &Ctx);
43
44/// Build metadata from the provided list of full stack id and profiled size, to
45/// use when reporting of hinted sizes is enabled.
48 LLVMContext &Ctx);
49
50/// Returns the stack node from an MIB metadata node.
52
53/// Returns the allocation type from an MIB metadata node.
55
56/// Returns the string to use in attributes with the given type.
58
59/// True if the AllocTypes bitmask contains just a single type.
60LLVM_ABI bool hasSingleAllocType(uint8_t AllocTypes);
61
62/// Removes any existing "ambiguous" memprof attribute. Called before we apply a
63/// specific allocation type such as "cold", "notcold", or "hot".
65
66/// Adds an "ambiguous" memprof attribute to call with a matched allocation
67/// profile but that we haven't yet been able to disambiguate.
69
70/// Class to build a trie of call stack contexts for a particular profiled
71/// allocation call, along with their associated allocation types.
72/// The allocation will be at the root of the trie, which is then used to
73/// compute the minimum lists of context ids needed to associate a call context
74/// with a single allocation type.
76private:
77 struct CallStackTrieNode {
78 // Allocation types for call context sharing the context prefix at this
79 // node.
80 uint8_t AllocTypes;
81 // If the user has requested reporting of hinted sizes, keep track of the
82 // associated full stack id and profiled sizes. Can have more than one
83 // after trimming (e.g. when building from metadata). This is only placed on
84 // the last (root-most) trie node for each allocation context.
85 std::vector<ContextTotalSize> ContextSizeInfo;
86 // Map of caller stack id to the corresponding child Trie node.
87 std::map<uint64_t, CallStackTrieNode *> Callers;
88 CallStackTrieNode(AllocationType Type)
89 : AllocTypes(static_cast<uint8_t>(Type)) {}
90 void addAllocType(AllocationType AllocType) {
91 AllocTypes |= static_cast<uint8_t>(AllocType);
92 }
93 void removeAllocType(AllocationType AllocType) {
94 AllocTypes &= ~static_cast<uint8_t>(AllocType);
95 }
96 bool hasAllocType(AllocationType AllocType) const {
97 return AllocTypes & static_cast<uint8_t>(AllocType);
98 }
99 };
100
101 // The node for the allocation at the root.
102 CallStackTrieNode *Alloc = nullptr;
103 // The allocation's leaf stack id.
104 uint64_t AllocStackId = 0;
105
106 // If the client provides a remarks emitter object, we will emit remarks on
107 // allocations for which we apply non-context sensitive allocation hints.
109
110 // The maximum size of a cold allocation context, from the profile summary.
111 uint64_t MaxColdSize;
112
113 // Tracks whether we have built the Trie from existing MD_memprof metadata. We
114 // apply different heuristics for determining whether to discard non-cold
115 // contexts when rebuilding as we have lost information available during the
116 // original profile match.
117 bool BuiltFromExistingMetadata = false;
118
119 void deleteTrieNode(CallStackTrieNode *Node) {
120 if (!Node)
121 return;
122 for (auto C : Node->Callers)
123 deleteTrieNode(C.second);
124 delete Node;
125 }
126
127 // Recursively build up a complete list of context size information from the
128 // trie nodes reached form the given Node, for hint size reporting.
129 void collectContextSizeInfo(CallStackTrieNode *Node,
130 std::vector<ContextTotalSize> &ContextSizeInfo);
131
132 // Recursively convert hot allocation types to notcold, since we don't
133 // actually do any cloning for hot contexts, to facilitate more aggressive
134 // pruning of contexts.
135 void convertHotToNotCold(CallStackTrieNode *Node);
136
137 // Recursive helper to trim contexts and create metadata nodes.
138 bool buildMIBNodes(CallStackTrieNode *Node, LLVMContext &Ctx,
139 std::vector<uint64_t> &MIBCallStack,
140 std::vector<Metadata *> &MIBNodes,
141 bool CalleeHasAmbiguousCallerContext, uint64_t &TotalBytes,
142 uint64_t &ColdBytes);
143
144public:
146 uint64_t MaxColdSize = 0)
147 : ORE(ORE), MaxColdSize(MaxColdSize) {}
148 ~CallStackTrie() { deleteTrieNode(Alloc); }
149
150 bool empty() const { return Alloc == nullptr; }
151
152 /// Add a call stack context with the given allocation type to the Trie.
153 /// The context is represented by the list of stack ids (computed during
154 /// matching via a debug location hash), expected to be in order from the
155 /// allocation call down to the bottom of the call stack (i.e. callee to
156 /// caller order).
157 LLVM_ABI void
159 std::vector<ContextTotalSize> ContextSizeInfo = {});
160
161 /// Add the call stack context along with its allocation type from the MIB
162 /// metadata to the Trie.
163 LLVM_ABI void addCallStack(MDNode *MIB);
164
165 /// Build and attach the minimal necessary MIB metadata. If the alloc has a
166 /// single allocation type, add a function attribute instead. The reason for
167 /// adding an attribute in this case is that it matches how the behavior for
168 /// allocation calls will be communicated to lib call simplification after
169 /// cloning or another optimization to distinguish the allocation types,
170 /// which is lower overhead and more direct than maintaining this metadata.
171 /// Returns true if memprof metadata attached, false if not (attribute added).
173
174 /// Add an attribute for the given allocation type to the call instruction.
175 /// If hinted by reporting is enabled, a message is emitted with the given
176 /// descriptor used to identify the category of single allocation type.
178 StringRef Descriptor);
179};
180
181/// Helper class to iterate through stack ids in both metadata (memprof MIB and
182/// callsite) and the corresponding ThinLTO summary data structures
183/// (CallsiteInfo and MIBInfo). This simplifies implementation of client code
184/// which doesn't need to worry about whether we are operating with IR (Regular
185/// LTO), or summary (ThinLTO).
186template <class NodeT, class IteratorT> class CallStack {
187public:
188 CallStack(const NodeT *N = nullptr) : N(N) {}
189
190 // Implement minimum required methods for range-based for loop.
191 // The default implementation assumes we are operating on ThinLTO data
192 // structures, which have a vector of StackIdIndices. There are specialized
193 // versions provided to iterate through metadata.
195 const NodeT *N = nullptr;
196 IteratorT Iter;
197 CallStackIterator(const NodeT *N, bool End);
199 bool operator==(const CallStackIterator &rhs) { return Iter == rhs.Iter; }
200 bool operator!=(const CallStackIterator &rhs) { return !(*this == rhs); }
201 void operator++() { ++Iter; }
202 };
203
204 bool empty() const { return N == nullptr; }
205
206 CallStackIterator begin() const;
207 CallStackIterator end() const { return CallStackIterator(N, /*End*/ true); }
208 CallStackIterator beginAfterSharedPrefix(const CallStack &Other);
209 uint64_t back() const;
210
211private:
212 const NodeT *N = nullptr;
213};
214
215template <class NodeT, class IteratorT>
217 const NodeT *N, bool End)
218 : N(N) {
219 if (!N) {
220 Iter = nullptr;
221 return;
222 }
223 Iter = End ? N->StackIdIndices.end() : N->StackIdIndices.begin();
224}
225
226template <class NodeT, class IteratorT>
228 assert(Iter != N->StackIdIndices.end());
229 return *Iter;
230}
231
232template <class NodeT, class IteratorT>
234 assert(N);
235 return N->StackIdIndices.back();
236}
237
238template <class NodeT, class IteratorT>
241 return CallStackIterator(N, /*End*/ false);
242}
243
244template <class NodeT, class IteratorT>
247 CallStackIterator Cur = begin();
248 for (CallStackIterator OtherCur = Other.begin();
249 Cur != end() && OtherCur != Other.end(); ++Cur, ++OtherCur)
250 assert(*Cur == *OtherCur);
251 return Cur;
252}
253
254/// Specializations for iterating through IR metadata stack contexts.
255template <>
258 const MDNode *N, bool End);
259template <>
262template <>
264
265} // end namespace memprof
266} // end namespace llvm
267
268#endif
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
#define LLVM_ABI
Definition Compiler.h:213
AllocType
This file contains the declarations for metadata subclasses.
ModuleSummaryIndex.h This file contains the declarations the classes that hold the module index and s...
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:41
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
Metadata node.
Definition Metadata.h:1077
The optimization diagnostic interface.
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:45
LLVM_ABI void addCallStack(AllocationType AllocType, ArrayRef< uint64_t > StackIds, std::vector< ContextTotalSize > ContextSizeInfo={})
Add a call stack context with the given allocation type to the Trie.
LLVM_ABI void addSingleAllocTypeAttribute(CallBase *CI, AllocationType AT, StringRef Descriptor)
Add an attribute for the given allocation type to the call instruction.
LLVM_ABI bool buildAndAttachMIBMetadata(CallBase *CI)
Build and attach the minimal necessary MIB metadata.
CallStackTrie(OptimizationRemarkEmitter *ORE=nullptr, uint64_t MaxColdSize=0)
Helper class to iterate through stack ids in both metadata (memprof MIB and callsite) and the corresp...
CallStack(const NodeT *N=nullptr)
CallStackIterator begin() const
CallStackIterator beginAfterSharedPrefix(const CallStack &Other)
CallStackIterator end() const
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
LLVM_ABI MDNode * buildCallstackMetadata(ArrayRef< uint64_t > CallStack, LLVMContext &Ctx)
Build callstack metadata from the provided list of call stack ids.
LLVM_ABI bool recordContextSizeInfoForAnalysis()
Whether we need to record the context size info in the alloc trie used to build metadata.
LLVM_ABI bool metadataIncludesAllContextSizeInfo()
Whether the alloc memeprof metadata will include context size info for all MIBs.
LLVM_ABI MDNode * buildContextSizeMetadata(ArrayRef< ContextTotalSize > ContextSizeInfo, LLVMContext &Ctx)
Build metadata from the provided list of full stack id and profiled size, to use when reporting of hi...
LLVM_ABI AllocationType getMIBAllocType(const MDNode *MIB)
Returns the allocation type from an MIB metadata node.
LLVM_ABI bool metadataMayIncludeContextSizeInfo()
Whether the alloc memprof metadata may include context size info for some MIBs (but possibly not all)...
LLVM_ABI bool hasSingleAllocType(uint8_t AllocTypes)
True if the AllocTypes bitmask contains just a single type.
LLVM_ABI std::string getAllocTypeAttributeString(AllocationType Type)
Returns the string to use in attributes with the given type.
LLVM_ABI MDNode * getMIBStackNode(const MDNode *MIB)
Returns the stack node from an MIB metadata node.
LLVM_ABI void removeAnyExistingAmbiguousAttribute(CallBase *CB)
Removes any existing "ambiguous" memprof attribute.
LLVM_ABI void addAmbiguousAttribute(CallBase *CB)
Adds an "ambiguous" memprof attribute to call with a matched allocation profile but that we haven't y...
This is an optimization pass for GlobalISel generic memory operations.
@ Other
Any other memory.
Definition ModRef.h:68
#define N
bool operator!=(const CallStackIterator &rhs)
bool operator==(const CallStackIterator &rhs)