23#define DEBUG_TYPE "memory-profile-info"
27 cl::desc(
"Report total allocation sizes of hinted allocations"));
34 cl::desc(
"Keep all non-cold contexts (increases cloning overheads)"));
38 cl::desc(
"Min percent of cold bytes to hint alloc cold during cloning"));
46 cl::desc(
"Min percent of cold bytes at a callsite to discard non-cold "
53 cl::desc(
"Min percent of max cold bytes for critical cold context"));
93 if (MDS->getString() ==
"cold") {
95 }
else if (MDS->getString() ==
"hot") {
113 assert(
false &&
"Unexpected alloc type");
120 assert(NumAllocTypes != 0);
121 return NumAllocTypes == 1;
144 std::vector<ContextTotalSize> ContextSizeInfo) {
146 CallStackTrieNode *Curr =
nullptr;
147 for (
auto StackId : StackIds) {
152 assert(AllocStackId == StackId);
153 Alloc->addAllocType(AllocType);
155 AllocStackId = StackId;
156 Alloc =
new CallStackTrieNode(AllocType);
162 auto [
Next, Inserted] = Curr->Callers.try_emplace(StackId);
165 Curr->addAllocType(AllocType);
169 auto *New =
new CallStackTrieNode(AllocType);
179 BuiltFromExistingMetadata =
true;
184 for (
const auto &MIBStackIter : StackMD->
operands()) {
187 CallStack.push_back(StackId->getZExtValue());
189 std::vector<ContextTotalSize> ContextSizeInfo;
201 ContextSizeInfo.push_back({FullStackId, TotalSize});
211 bool BuiltFromExistingMetadata,
218 if (ContextSizeInfo.
empty()) {
227 for (
const auto &[FullStackId, TotalSize] : ContextSizeInfo) {
228 TotalBytes += TotalSize;
229 bool LargeColdContext =
false;
231 ColdBytes += TotalSize;
237 LargeColdContext =
true;
248 auto *ContextSizeMD =
MDNode::get(Ctx, {FullStackIdMD, TotalSizeMD});
256void CallStackTrie::collectContextSizeInfo(
257 CallStackTrieNode *Node, std::vector<ContextTotalSize> &ContextSizeInfo) {
259 for (
auto &Caller :
Node->Callers)
260 collectContextSizeInfo(
Caller.second, ContextSizeInfo);
263void CallStackTrie::convertHotToNotCold(CallStackTrieNode *Node) {
268 for (
auto &Caller :
Node->Callers)
269 convertHotToNotCold(
Caller.second);
275 std::vector<Metadata *> &SavedMIBNodes,
276 unsigned CallerContextLength,
278 bool BuiltFromExistingMetadata) {
279 const bool MostlyCold =
298 auto EmitMessageForRemovedContexts = [](
const MDNode *MIBMD,
StringRef Tag,
310 errs() <<
"MemProf hinting: Total size for " << Tag
311 <<
" non-cold full allocation context hash " << FullStackId
312 << Extra <<
": " << TS <<
"\n";
320 auto NewColdMIBNodes =
327 const float PercentCold = ColdBytes * 100.0 / TotalBytes;
328 std::string PercentStr;
330 OS <<
format(
" for %5.2f%% cold bytes", PercentCold);
331 EmitMessageForRemovedContexts(MIBMD,
"discarded", OS.
str());
335 for (
auto *M : NewColdMIBNodes)
336 SavedMIBNodes.push_back(M);
367 bool LongerNotColdContextKept =
false;
368 for (
auto *MIB : NewMIBNodes) {
375 LongerNotColdContextKept =
true;
381 bool KeepFirstNewNotCold = !LongerNotColdContextKept;
393 if (KeepFirstNewNotCold) {
394 KeepFirstNewNotCold =
false;
398 EmitMessageForRemovedContexts(MIBMD,
"pruned",
"");
403 for (
auto *M : NewColdMIBNodes)
404 SavedMIBNodes.push_back(M);
411bool CallStackTrie::buildMIBNodes(CallStackTrieNode *Node, LLVMContext &Ctx,
412 std::vector<uint64_t> &MIBCallStack,
413 std::vector<Metadata *> &MIBNodes,
414 bool CalleeHasAmbiguousCallerContext,
415 uint64_t &TotalBytes, uint64_t &ColdBytes) {
419 std::vector<ContextTotalSize> ContextSizeInfo;
420 collectContextSizeInfo(Node, ContextSizeInfo);
423 MaxColdSize, BuiltFromExistingMetadata, TotalBytes, ColdBytes));
429 if (!
Node->Callers.empty()) {
430 bool NodeHasAmbiguousCallerContext =
Node->Callers.size() > 1;
431 bool AddedMIBNodesForAllCallerContexts =
true;
435 std::vector<Metadata *> NewMIBNodes;
438 uint64_t CallerTotalBytes = 0;
439 uint64_t CallerColdBytes = 0;
440 for (
auto &Caller :
Node->Callers) {
441 MIBCallStack.push_back(
Caller.first);
442 AddedMIBNodesForAllCallerContexts &= buildMIBNodes(
443 Caller.second, Ctx, MIBCallStack, NewMIBNodes,
444 NodeHasAmbiguousCallerContext, CallerTotalBytes, CallerColdBytes);
446 MIBCallStack.pop_back();
451 CallerTotalBytes, CallerColdBytes,
452 BuiltFromExistingMetadata);
453 TotalBytes += CallerTotalBytes;
454 ColdBytes += CallerColdBytes;
456 if (AddedMIBNodesForAllCallerContexts)
460 assert(!NodeHasAmbiguousCallerContext);
473 if (!CalleeHasAmbiguousCallerContext)
475 std::vector<ContextTotalSize> ContextSizeInfo;
476 collectContextSizeInfo(Node, ContextSizeInfo);
479 BuiltFromExistingMetadata, TotalBytes, ColdBytes));
492 std::vector<ContextTotalSize> ContextSizeInfo;
493 collectContextSizeInfo(Alloc, ContextSizeInfo);
494 for (
const auto &[FullStackId, TotalSize] : ContextSizeInfo) {
495 errs() <<
"MemProf hinting: Total size for full allocation context hash "
496 << FullStackId <<
" and " << Descriptor <<
" alloc type "
502 <<
ore::NV(
"AllocationCall", CI) <<
" in function "
504 <<
" marked with memprof allocation attribute "
505 <<
ore::NV(
"Attribute", AllocTypeString));
525 convertHotToNotCold(Alloc);
534 std::vector<uint64_t> MIBCallStack;
535 MIBCallStack.push_back(AllocStackId);
536 std::vector<Metadata *> MIBNodes;
539 assert(!Alloc->Callers.empty() &&
"addCallStack has not been called yet");
543 if (buildMIBNodes(Alloc, Ctx, MIBCallStack, MIBNodes,
546 assert(MIBCallStack.size() == 1 &&
547 "Should only be left with Alloc's location in stack");
567 Iter = End ?
N->op_end() :
N->op_begin();
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
LLVM_ABI cl::opt< bool > MemProfKeepAllNotColdContexts("memprof-keep-all-not-cold-contexts", cl::init(false), cl::Hidden, cl::desc("Keep all non-cold contexts (increases cloning overheads)"))
cl::opt< unsigned > MinPercentMaxColdSize("memprof-min-percent-max-cold-size", cl::init(100), cl::Hidden, cl::desc("Min percent of max cold bytes for critical cold context"))
cl::opt< bool > MemProfReportHintedSizes("memprof-report-hinted-sizes", cl::init(false), cl::Hidden, cl::desc("Report total allocation sizes of hinted allocations"))
cl::opt< unsigned > MinCallsiteColdBytePercent("memprof-callsite-cold-threshold", cl::init(100), cl::Hidden, cl::desc("Min percent of cold bytes at a callsite to discard non-cold " "contexts"))
static MDNode * createMIBNode(LLVMContext &Ctx, ArrayRef< uint64_t > MIBCallStack, AllocationType AllocType, ArrayRef< ContextTotalSize > ContextSizeInfo, const uint64_t MaxColdSize, bool BuiltFromExistingMetadata, uint64_t &TotalBytes, uint64_t &ColdBytes)
static void saveFilteredNewMIBNodes(std::vector< Metadata * > &NewMIBNodes, std::vector< Metadata * > &SavedMIBNodes, unsigned CallerContextLength, uint64_t TotalBytes, uint64_t ColdBytes, bool BuiltFromExistingMetadata)
cl::opt< unsigned > MinClonedColdBytePercent("memprof-cloning-cold-threshold", cl::init(100), cl::Hidden, cl::desc("Min percent of cold bytes to hint alloc cold during cloning"))
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
bool empty() const
empty - Check if the array is empty.
static LLVM_ABI Attribute get(LLVMContext &Context, AttrKind Kind, uint64_t Val=0)
Return a uniquified Attribute object.
LLVM_ABI StringRef getValueAsString() const
Return the attribute's value as a string.
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
void addFnAttr(Attribute::AttrKind Kind)
Adds the attribute to the function.
bool hasFnAttr(Attribute::AttrKind Kind) const
Determine whether this call has the given attribute.
Attribute getFnAttr(StringRef Kind) const
Get the attribute of a given kind for the function.
void removeFnAttr(Attribute::AttrKind Kind)
Removes the attribute from the function.
This is the shared class of boolean and integer constants.
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
This is an important class for using LLVM in a threaded context.
static LLVM_ABI MDNode * getMergedCallsiteMetadata(MDNode *A, MDNode *B)
const MDOperand & getOperand(unsigned I) const
ArrayRef< MDOperand > operands() const
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
unsigned getNumOperands() const
Return number of MDNode operands.
LLVM_ABI MDNode(LLVMContext &Context, unsigned ID, StorageType Storage, ArrayRef< Metadata * > Ops1, ArrayRef< Metadata * > Ops2={})
static LLVM_ABI MDNode * getMergedMemProfMetadata(MDNode *A, MDNode *B)
static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
void push_back(Metadata *MD)
Append an element to the tuple. This will resize the node.
void reserve(size_type N)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringRef - Represent a constant reference to a string, i.e.
The instances of the Type class are immutable: once they are created, they are never changed.
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
LLVM_ABI LLVMContext & getContext() const
All values hold a context through their type.
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.
Helper class to iterate through stack ids in both metadata (memprof MIB and callsite) and the corresp...
A raw_ostream that writes to an std::string.
std::string & str()
Returns the string's reference.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
initializer< Ty > init(const Ty &Val)
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > dyn_extract(Y &&MD)
Extract a Value from Metadata, if any.
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 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...
DiagnosticInfoOptimizationBase::Argument NV
NodeAddr< NodeBase * > Node
This is an optimization pass for GlobalISel generic memory operations.
int popcount(T Value) noexcept
Count the number of set bits in a value.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
iterator_range< filter_iterator< detail::IterOfRange< RangeT >, PredicateT > > make_filter_range(RangeT &&Range, PredicateT Pred)
Convenience function that takes a range of elements and a predicate, and return a new filter_iterator...
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
FunctionAddr VTableAddr Next
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
CallStackIterator(const NodeT *N, bool End)