23#define DEBUG_TYPE "memory-profile-info"
29 cl::desc(
"Report total allocation sizes of hinted allocations"));
36 cl::desc(
"Keep all non-cold contexts (increases cloning overheads)"));
40 cl::desc(
"Min percent of cold bytes to hint alloc cold during cloning"));
48 cl::desc(
"Min percent of cold bytes at a callsite to discard non-cold "
55 cl::desc(
"Min percent of max cold bytes for critical cold context"));
61 cl::desc(
"Keep context size information in memprof metadata"));
65 cl::desc(
"Apply ambiguous memprof attribute to ambiguous allocations"));
108 if (MDS->getString() ==
"cold") {
110 }
else if (MDS->getString() ==
"hot") {
128 assert(
false &&
"Unexpected alloc type");
135 assert(NumAllocTypes != 0);
136 return NumAllocTypes == 1;
161 std::vector<ContextTotalSize> ContextSizeInfo) {
163 CallStackTrieNode *Curr =
nullptr;
164 for (
auto StackId : StackIds) {
169 assert(AllocStackId == StackId);
170 Alloc->addAllocType(AllocType);
172 AllocStackId = StackId;
173 Alloc =
new CallStackTrieNode(AllocType);
179 auto [
Next, Inserted] = Curr->Callers.try_emplace(StackId);
182 Curr->addAllocType(AllocType);
186 auto *New =
new CallStackTrieNode(AllocType);
195 return ContextSizeTypePair(CTS,
202 BuiltFromExistingMetadata =
true;
207 for (
const auto &MIBStackIter : StackMD->
operands()) {
210 CallStack.push_back(StackId->getZExtValue());
212 std::vector<ContextTotalSize> ContextSizeInfo;
224 ContextSizeInfo.push_back({FullStackId, TotalSize});
234 bool BuiltFromExistingMetadata,
241 if (ContextInfo.
empty()) {
250 for (
const auto &[CSI, AT] : ContextInfo) {
251 const auto &[FullStackId, TotalSize] = CSI;
252 TotalBytes += TotalSize;
253 bool LargeColdContext =
false;
255 ColdBytes += TotalSize;
262 if (BuiltFromExistingMetadata ||
265 LargeColdContext =
true;
276 auto *ContextSizeMD =
MDNode::get(Ctx, {FullStackIdMD, TotalSizeMD});
284void CallStackTrie::collectContextInfo(
285 CallStackTrieNode *Node, std::vector<ContextSizeTypePair> &ContextInfo) {
287 for (
auto &Caller :
Node->Callers)
288 collectContextInfo(
Caller.second, ContextInfo);
291void CallStackTrie::convertHotToNotCold(CallStackTrieNode *Node) {
296 for (
auto &Caller :
Node->Callers)
297 convertHotToNotCold(
Caller.second);
306 errs() <<
"MemProf hinting: Total size for " << Tag
307 <<
" non-cold full allocation context hash " << FullStackId << Extra
308 <<
": " << TotalSize <<
"\n";
314 std::vector<Metadata *> &SavedMIBNodes,
315 unsigned CallerContextLength,
317 bool BuiltFromExistingMetadata) {
318 const bool MostlyCold =
337 auto EmitMessageForRemovedContexts = [](
const MDNode *MIBMD,
StringRef Tag,
357 auto NewColdMIBNodes =
364 const float PercentCold = ColdBytes * 100.0 / TotalBytes;
365 std::string PercentStr;
367 OS <<
format(
" for %5.2f%% cold bytes", PercentCold);
368 EmitMessageForRemovedContexts(MIBMD,
"discarded", OS.
str());
372 for (
auto *M : NewColdMIBNodes)
373 SavedMIBNodes.push_back(M);
404 bool LongerNotColdContextKept =
false;
405 for (
auto *MIB : NewMIBNodes) {
412 LongerNotColdContextKept =
true;
418 bool KeepFirstNewNotCold = !LongerNotColdContextKept;
430 if (KeepFirstNewNotCold) {
431 KeepFirstNewNotCold =
false;
435 EmitMessageForRemovedContexts(MIBMD,
"pruned",
"");
440 for (
auto *M : NewColdMIBNodes)
441 SavedMIBNodes.push_back(M);
448bool CallStackTrie::buildMIBNodes(CallStackTrieNode *Node, LLVMContext &Ctx,
449 std::vector<uint64_t> &MIBCallStack,
450 std::vector<Metadata *> &MIBNodes,
451 bool CalleeHasAmbiguousCallerContext,
452 uint64_t &TotalBytes, uint64_t &ColdBytes) {
456 std::vector<ContextSizeTypePair> ContextInfo;
457 collectContextInfo(Node, ContextInfo);
460 MaxColdSize, BuiltFromExistingMetadata, TotalBytes, ColdBytes));
466 if (!
Node->Callers.empty()) {
467 bool NodeHasAmbiguousCallerContext =
Node->Callers.size() > 1;
468 bool AddedMIBNodesForAllCallerContexts =
true;
472 std::vector<Metadata *> NewMIBNodes;
475 uint64_t CallerTotalBytes = 0;
476 uint64_t CallerColdBytes = 0;
477 for (
auto &Caller :
Node->Callers) {
478 MIBCallStack.push_back(
Caller.first);
479 AddedMIBNodesForAllCallerContexts &= buildMIBNodes(
480 Caller.second, Ctx, MIBCallStack, NewMIBNodes,
481 NodeHasAmbiguousCallerContext, CallerTotalBytes, CallerColdBytes);
483 MIBCallStack.pop_back();
488 CallerTotalBytes, CallerColdBytes,
489 BuiltFromExistingMetadata);
490 TotalBytes += CallerTotalBytes;
491 ColdBytes += CallerColdBytes;
493 if (AddedMIBNodesForAllCallerContexts)
497 assert(!NodeHasAmbiguousCallerContext);
510 if (!CalleeHasAmbiguousCallerContext)
512 std::vector<ContextSizeTypePair> ContextInfo;
513 collectContextInfo(Node, ContextInfo);
516 BuiltFromExistingMetadata, TotalBytes, ColdBytes));
529 std::vector<ContextSizeTypePair> ContextInfo;
530 collectContextInfo(Alloc, ContextInfo);
534 if (ContextInfo.empty()) {
537 <<
ore::NV(
"AllocationCall", CI) <<
" in function "
539 <<
" marked with memprof allocation attribute "
540 <<
ore::NV(
"Attribute", AllocTypeString));
545 for (
const auto &[CSI, OrigAT] : ContextInfo) {
546 const auto &[FullStackId, TotalSize] = CSI;
556 errs() <<
"MemProf hinting: Total size for full allocation context hash "
557 << FullStackId <<
" and " << Descriptor <<
" alloc type "
561 <<
ore::NV(
"AllocationCall", CI) <<
" in function "
563 <<
" marked with memprof allocation attribute "
564 <<
ore::NV(
"Attribute", AllocTypeString)
565 <<
" for full allocation context hash "
566 <<
ore::NV(
"FullStackId", FullStackId) <<
" with total size "
567 <<
ore::NV(
"TotalSize", TotalSize));
588 convertHotToNotCold(Alloc);
597 std::vector<uint64_t> MIBCallStack;
598 MIBCallStack.push_back(AllocStackId);
599 std::vector<Metadata *> MIBNodes;
602 assert(!Alloc->Callers.empty() &&
"addCallStack has not been called yet");
606 if (buildMIBNodes(Alloc, Ctx, MIBCallStack, MIBNodes,
609 assert(MIBCallStack.size() == 1 &&
610 "Should only be left with Alloc's location in stack");
630 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...
static void emitIgnoredNonColdContextMessage(StringRef Tag, uint64_t FullStackId, StringRef Extra, uint64_t TotalSize)
static void saveFilteredNewMIBNodes(std::vector< Metadata * > &NewMIBNodes, std::vector< Metadata * > &SavedMIBNodes, unsigned CallerContextLength, uint64_t TotalBytes, uint64_t ColdBytes, bool BuiltFromExistingMetadata)
static MDNode * createMIBNode(LLVMContext &Ctx, ArrayRef< uint64_t > MIBCallStack, AllocationType AllocType, ArrayRef< ContextSizeTypePair > ContextInfo, const uint64_t MaxColdSize, bool BuiltFromExistingMetadata, uint64_t &TotalBytes, uint64_t &ColdBytes)
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)
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.
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"))
cl::opt< bool > MemProfReportHintedSizes("memprof-report-hinted-sizes", cl::init(false), cl::Hidden, cl::desc("Report total allocation sizes of hinted allocations"))
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.
constexpr int popcount(T Value) noexcept
Count the number of set bits in a value.
auto map_range(ContainerTy &&C, FuncTy F)
Return a range that applies F to the elements of C.
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)"))
LLVM_ABI cl::opt< bool > MemProfUseAmbiguousAttributes("memprof-ambiguous-attributes", cl::init(true), cl::Hidden, cl::desc("Apply ambiguous memprof attribute to ambiguous 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"))
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.
cl::opt< bool > MemProfKeepContextSizeInfo("memprof-keep-context-size-info", cl::init(false), cl::Hidden, cl::desc("Keep context size information in memprof metadata"))
FunctionAddr VTableAddr Next
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
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"))
CallStackIterator(const NodeT *N, bool End)