1*1dad6247STeresa Johnson //===-- MemoryProfileInfo.cpp - memory profile info ------------------------==//
2*1dad6247STeresa Johnson //
3*1dad6247STeresa Johnson // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4*1dad6247STeresa Johnson // See https://llvm.org/LICENSE.txt for license information.
5*1dad6247STeresa Johnson // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6*1dad6247STeresa Johnson //
7*1dad6247STeresa Johnson //===----------------------------------------------------------------------===//
8*1dad6247STeresa Johnson //
9*1dad6247STeresa Johnson // This file contains utilities to analyze memory profile information.
10*1dad6247STeresa Johnson //
11*1dad6247STeresa Johnson //===----------------------------------------------------------------------===//
12*1dad6247STeresa Johnson 
13*1dad6247STeresa Johnson #include "llvm/Analysis/MemoryProfileInfo.h"
14*1dad6247STeresa Johnson #include "llvm/Support/CommandLine.h"
15*1dad6247STeresa Johnson 
16*1dad6247STeresa Johnson using namespace llvm;
17*1dad6247STeresa Johnson using namespace llvm::memprof;
18*1dad6247STeresa Johnson 
19*1dad6247STeresa Johnson #define DEBUG_TYPE "memory-profile-info"
20*1dad6247STeresa Johnson 
21*1dad6247STeresa Johnson // Upper bound on accesses per byte for marking an allocation cold.
22*1dad6247STeresa Johnson cl::opt<float> MemProfAccessesPerByteColdThreshold(
23*1dad6247STeresa Johnson     "memprof-accesses-per-byte-cold-threshold", cl::init(10.0), cl::Hidden,
24*1dad6247STeresa Johnson     cl::desc("The threshold the accesses per byte must be under to consider "
25*1dad6247STeresa Johnson              "an allocation cold"));
26*1dad6247STeresa Johnson 
27*1dad6247STeresa Johnson // Lower bound on lifetime to mark an allocation cold (in addition to accesses
28*1dad6247STeresa Johnson // per byte above). This is to avoid pessimizing short lived objects.
29*1dad6247STeresa Johnson cl::opt<unsigned> MemProfMinLifetimeColdThreshold(
30*1dad6247STeresa Johnson     "memprof-min-lifetime-cold-threshold", cl::init(200), cl::Hidden,
31*1dad6247STeresa Johnson     cl::desc("The minimum lifetime (s) for an allocation to be considered "
32*1dad6247STeresa Johnson              "cold"));
33*1dad6247STeresa Johnson 
getAllocType(uint64_t MaxAccessCount,uint64_t MinSize,uint64_t MinLifetime)34*1dad6247STeresa Johnson AllocationType llvm::memprof::getAllocType(uint64_t MaxAccessCount,
35*1dad6247STeresa Johnson                                            uint64_t MinSize,
36*1dad6247STeresa Johnson                                            uint64_t MinLifetime) {
37*1dad6247STeresa Johnson   if (((float)MaxAccessCount) / MinSize < MemProfAccessesPerByteColdThreshold &&
38*1dad6247STeresa Johnson       // MinLifetime is expected to be in ms, so convert the threshold to ms.
39*1dad6247STeresa Johnson       MinLifetime >= MemProfMinLifetimeColdThreshold * 1000)
40*1dad6247STeresa Johnson     return AllocationType::Cold;
41*1dad6247STeresa Johnson   return AllocationType::NotCold;
42*1dad6247STeresa Johnson }
43*1dad6247STeresa Johnson 
buildCallstackMetadata(ArrayRef<uint64_t> CallStack,LLVMContext & Ctx)44*1dad6247STeresa Johnson MDNode *llvm::memprof::buildCallstackMetadata(ArrayRef<uint64_t> CallStack,
45*1dad6247STeresa Johnson                                               LLVMContext &Ctx) {
46*1dad6247STeresa Johnson   std::vector<Metadata *> StackVals;
47*1dad6247STeresa Johnson   for (auto Id : CallStack) {
48*1dad6247STeresa Johnson     auto *StackValMD =
49*1dad6247STeresa Johnson         ValueAsMetadata::get(ConstantInt::get(Type::getInt64Ty(Ctx), Id));
50*1dad6247STeresa Johnson     StackVals.push_back(StackValMD);
51*1dad6247STeresa Johnson   }
52*1dad6247STeresa Johnson   return MDNode::get(Ctx, StackVals);
53*1dad6247STeresa Johnson }
54*1dad6247STeresa Johnson 
getMIBStackNode(const MDNode * MIB)55*1dad6247STeresa Johnson MDNode *llvm::memprof::getMIBStackNode(const MDNode *MIB) {
56*1dad6247STeresa Johnson   assert(MIB->getNumOperands() == 2);
57*1dad6247STeresa Johnson   // The stack metadata is the first operand of each memprof MIB metadata.
58*1dad6247STeresa Johnson   return cast<MDNode>(MIB->getOperand(0));
59*1dad6247STeresa Johnson }
60*1dad6247STeresa Johnson 
getMIBAllocType(const MDNode * MIB)61*1dad6247STeresa Johnson AllocationType llvm::memprof::getMIBAllocType(const MDNode *MIB) {
62*1dad6247STeresa Johnson   assert(MIB->getNumOperands() == 2);
63*1dad6247STeresa Johnson   // The allocation type is currently the second operand of each memprof
64*1dad6247STeresa Johnson   // MIB metadata. This will need to change as we add additional allocation
65*1dad6247STeresa Johnson   // types that can be applied based on the allocation profile data.
66*1dad6247STeresa Johnson   auto *MDS = dyn_cast<MDString>(MIB->getOperand(1));
67*1dad6247STeresa Johnson   assert(MDS);
68*1dad6247STeresa Johnson   if (MDS->getString().equals("cold"))
69*1dad6247STeresa Johnson     return AllocationType::Cold;
70*1dad6247STeresa Johnson   return AllocationType::NotCold;
71*1dad6247STeresa Johnson }
72*1dad6247STeresa Johnson 
getAllocTypeAttributeString(AllocationType Type)73*1dad6247STeresa Johnson static std::string getAllocTypeAttributeString(AllocationType Type) {
74*1dad6247STeresa Johnson   switch (Type) {
75*1dad6247STeresa Johnson   case AllocationType::NotCold:
76*1dad6247STeresa Johnson     return "notcold";
77*1dad6247STeresa Johnson     break;
78*1dad6247STeresa Johnson   case AllocationType::Cold:
79*1dad6247STeresa Johnson     return "cold";
80*1dad6247STeresa Johnson     break;
81*1dad6247STeresa Johnson   default:
82*1dad6247STeresa Johnson     assert(false && "Unexpected alloc type");
83*1dad6247STeresa Johnson   }
84*1dad6247STeresa Johnson   llvm_unreachable("invalid alloc type");
85*1dad6247STeresa Johnson }
86*1dad6247STeresa Johnson 
addAllocTypeAttribute(LLVMContext & Ctx,CallBase * CI,AllocationType AllocType)87*1dad6247STeresa Johnson static void addAllocTypeAttribute(LLVMContext &Ctx, CallBase *CI,
88*1dad6247STeresa Johnson                                   AllocationType AllocType) {
89*1dad6247STeresa Johnson   auto AllocTypeString = getAllocTypeAttributeString(AllocType);
90*1dad6247STeresa Johnson   auto A = llvm::Attribute::get(Ctx, "memprof", AllocTypeString);
91*1dad6247STeresa Johnson   CI->addFnAttr(A);
92*1dad6247STeresa Johnson }
93*1dad6247STeresa Johnson 
hasSingleAllocType(uint8_t AllocTypes)94*1dad6247STeresa Johnson static bool hasSingleAllocType(uint8_t AllocTypes) {
95*1dad6247STeresa Johnson   const unsigned NumAllocTypes = countPopulation(AllocTypes);
96*1dad6247STeresa Johnson   assert(NumAllocTypes != 0);
97*1dad6247STeresa Johnson   return NumAllocTypes == 1;
98*1dad6247STeresa Johnson }
99*1dad6247STeresa Johnson 
addCallStack(AllocationType AllocType,ArrayRef<uint64_t> StackIds)100*1dad6247STeresa Johnson void CallStackTrie::addCallStack(AllocationType AllocType,
101*1dad6247STeresa Johnson                                  ArrayRef<uint64_t> StackIds) {
102*1dad6247STeresa Johnson   bool First = true;
103*1dad6247STeresa Johnson   CallStackTrieNode *Curr = nullptr;
104*1dad6247STeresa Johnson   for (auto StackId : StackIds) {
105*1dad6247STeresa Johnson     // If this is the first stack frame, add or update alloc node.
106*1dad6247STeresa Johnson     if (First) {
107*1dad6247STeresa Johnson       First = false;
108*1dad6247STeresa Johnson       if (Alloc) {
109*1dad6247STeresa Johnson         assert(AllocStackId == StackId);
110*1dad6247STeresa Johnson         Alloc->AllocTypes |= static_cast<uint8_t>(AllocType);
111*1dad6247STeresa Johnson       } else {
112*1dad6247STeresa Johnson         AllocStackId = StackId;
113*1dad6247STeresa Johnson         Alloc = new CallStackTrieNode(AllocType);
114*1dad6247STeresa Johnson       }
115*1dad6247STeresa Johnson       Curr = Alloc;
116*1dad6247STeresa Johnson       continue;
117*1dad6247STeresa Johnson     }
118*1dad6247STeresa Johnson     // Update existing caller node if it exists.
119*1dad6247STeresa Johnson     auto Next = Curr->Callers.find(StackId);
120*1dad6247STeresa Johnson     if (Next != Curr->Callers.end()) {
121*1dad6247STeresa Johnson       Curr = Next->second;
122*1dad6247STeresa Johnson       Curr->AllocTypes |= static_cast<uint8_t>(AllocType);
123*1dad6247STeresa Johnson       continue;
124*1dad6247STeresa Johnson     }
125*1dad6247STeresa Johnson     // Otherwise add a new caller node.
126*1dad6247STeresa Johnson     auto *New = new CallStackTrieNode(AllocType);
127*1dad6247STeresa Johnson     Curr->Callers[StackId] = New;
128*1dad6247STeresa Johnson     Curr = New;
129*1dad6247STeresa Johnson   }
130*1dad6247STeresa Johnson   assert(Curr);
131*1dad6247STeresa Johnson }
132*1dad6247STeresa Johnson 
addCallStack(MDNode * MIB)133*1dad6247STeresa Johnson void CallStackTrie::addCallStack(MDNode *MIB) {
134*1dad6247STeresa Johnson   MDNode *StackMD = getMIBStackNode(MIB);
135*1dad6247STeresa Johnson   assert(StackMD);
136*1dad6247STeresa Johnson   std::vector<uint64_t> CallStack;
137*1dad6247STeresa Johnson   CallStack.reserve(StackMD->getNumOperands());
138*1dad6247STeresa Johnson   for (auto &MIBStackIter : StackMD->operands()) {
139*1dad6247STeresa Johnson     auto *StackId = mdconst::dyn_extract<ConstantInt>(MIBStackIter);
140*1dad6247STeresa Johnson     assert(StackId);
141*1dad6247STeresa Johnson     CallStack.push_back(StackId->getZExtValue());
142*1dad6247STeresa Johnson   }
143*1dad6247STeresa Johnson   addCallStack(getMIBAllocType(MIB), CallStack);
144*1dad6247STeresa Johnson }
145*1dad6247STeresa Johnson 
createMIBNode(LLVMContext & Ctx,std::vector<uint64_t> & MIBCallStack,AllocationType AllocType)146*1dad6247STeresa Johnson static MDNode *createMIBNode(LLVMContext &Ctx,
147*1dad6247STeresa Johnson                              std::vector<uint64_t> &MIBCallStack,
148*1dad6247STeresa Johnson                              AllocationType AllocType) {
149*1dad6247STeresa Johnson   std::vector<Metadata *> MIBPayload(
150*1dad6247STeresa Johnson       {buildCallstackMetadata(MIBCallStack, Ctx)});
151*1dad6247STeresa Johnson   MIBPayload.push_back(
152*1dad6247STeresa Johnson       MDString::get(Ctx, getAllocTypeAttributeString(AllocType)));
153*1dad6247STeresa Johnson   return MDNode::get(Ctx, MIBPayload);
154*1dad6247STeresa Johnson }
155*1dad6247STeresa Johnson 
156*1dad6247STeresa Johnson // Recursive helper to trim contexts and create metadata nodes.
157*1dad6247STeresa Johnson // Caller should have pushed Node's loc to MIBCallStack. Doing this in the
158*1dad6247STeresa Johnson // caller makes it simpler to handle the many early returns in this method.
buildMIBNodes(CallStackTrieNode * Node,LLVMContext & Ctx,std::vector<uint64_t> & MIBCallStack,std::vector<Metadata * > & MIBNodes,bool CalleeHasAmbiguousCallerContext)159*1dad6247STeresa Johnson bool CallStackTrie::buildMIBNodes(CallStackTrieNode *Node, LLVMContext &Ctx,
160*1dad6247STeresa Johnson                                   std::vector<uint64_t> &MIBCallStack,
161*1dad6247STeresa Johnson                                   std::vector<Metadata *> &MIBNodes,
162*1dad6247STeresa Johnson                                   bool CalleeHasAmbiguousCallerContext) {
163*1dad6247STeresa Johnson   // Trim context below the first node in a prefix with a single alloc type.
164*1dad6247STeresa Johnson   // Add an MIB record for the current call stack prefix.
165*1dad6247STeresa Johnson   if (hasSingleAllocType(Node->AllocTypes)) {
166*1dad6247STeresa Johnson     MIBNodes.push_back(
167*1dad6247STeresa Johnson         createMIBNode(Ctx, MIBCallStack, (AllocationType)Node->AllocTypes));
168*1dad6247STeresa Johnson     return true;
169*1dad6247STeresa Johnson   }
170*1dad6247STeresa Johnson 
171*1dad6247STeresa Johnson   // We don't have a single allocation for all the contexts sharing this prefix,
172*1dad6247STeresa Johnson   // so recursively descend into callers in trie.
173*1dad6247STeresa Johnson   if (!Node->Callers.empty()) {
174*1dad6247STeresa Johnson     bool NodeHasAmbiguousCallerContext = Node->Callers.size() > 1;
175*1dad6247STeresa Johnson     bool AddedMIBNodesForAllCallerContexts = true;
176*1dad6247STeresa Johnson     for (auto &Caller : Node->Callers) {
177*1dad6247STeresa Johnson       MIBCallStack.push_back(Caller.first);
178*1dad6247STeresa Johnson       AddedMIBNodesForAllCallerContexts &=
179*1dad6247STeresa Johnson           buildMIBNodes(Caller.second, Ctx, MIBCallStack, MIBNodes,
180*1dad6247STeresa Johnson                         NodeHasAmbiguousCallerContext);
181*1dad6247STeresa Johnson       // Remove Caller.
182*1dad6247STeresa Johnson       MIBCallStack.pop_back();
183*1dad6247STeresa Johnson     }
184*1dad6247STeresa Johnson     if (AddedMIBNodesForAllCallerContexts)
185*1dad6247STeresa Johnson       return true;
186*1dad6247STeresa Johnson     // We expect that the callers should be forced to add MIBs to disambiguate
187*1dad6247STeresa Johnson     // the context in this case (see below).
188*1dad6247STeresa Johnson     assert(!NodeHasAmbiguousCallerContext);
189*1dad6247STeresa Johnson   }
190*1dad6247STeresa Johnson 
191*1dad6247STeresa Johnson   // If we reached here, then this node does not have a single allocation type,
192*1dad6247STeresa Johnson   // and we didn't add metadata for a longer call stack prefix including any of
193*1dad6247STeresa Johnson   // Node's callers. That means we never hit a single allocation type along all
194*1dad6247STeresa Johnson   // call stacks with this prefix. This can happen due to recursion collapsing
195*1dad6247STeresa Johnson   // or the stack being deeper than tracked by the profiler runtime, leading to
196*1dad6247STeresa Johnson   // contexts with different allocation types being merged. In that case, we
197*1dad6247STeresa Johnson   // trim the context just below the deepest context split, which is this
198*1dad6247STeresa Johnson   // node if the callee has an ambiguous caller context (multiple callers),
199*1dad6247STeresa Johnson   // since the recursive calls above returned false. Conservatively give it
200*1dad6247STeresa Johnson   // non-cold allocation type.
201*1dad6247STeresa Johnson   if (!CalleeHasAmbiguousCallerContext)
202*1dad6247STeresa Johnson     return false;
203*1dad6247STeresa Johnson   MIBNodes.push_back(createMIBNode(Ctx, MIBCallStack, AllocationType::NotCold));
204*1dad6247STeresa Johnson   return true;
205*1dad6247STeresa Johnson }
206*1dad6247STeresa Johnson 
207*1dad6247STeresa Johnson // Build and attach the minimal necessary MIB metadata. If the alloc has a
208*1dad6247STeresa Johnson // single allocation type, add a function attribute instead. Returns true if
209*1dad6247STeresa Johnson // memprof metadata attached, false if not (attribute added).
buildAndAttachMIBMetadata(CallBase * CI)210*1dad6247STeresa Johnson bool CallStackTrie::buildAndAttachMIBMetadata(CallBase *CI) {
211*1dad6247STeresa Johnson   auto &Ctx = CI->getContext();
212*1dad6247STeresa Johnson   if (hasSingleAllocType(Alloc->AllocTypes)) {
213*1dad6247STeresa Johnson     addAllocTypeAttribute(Ctx, CI, (AllocationType)Alloc->AllocTypes);
214*1dad6247STeresa Johnson     return false;
215*1dad6247STeresa Johnson   }
216*1dad6247STeresa Johnson   std::vector<uint64_t> MIBCallStack;
217*1dad6247STeresa Johnson   MIBCallStack.push_back(AllocStackId);
218*1dad6247STeresa Johnson   std::vector<Metadata *> MIBNodes;
219*1dad6247STeresa Johnson   assert(!Alloc->Callers.empty() && "addCallStack has not been called yet");
220*1dad6247STeresa Johnson   buildMIBNodes(Alloc, Ctx, MIBCallStack, MIBNodes,
221*1dad6247STeresa Johnson                 /*CalleeHasAmbiguousCallerContext=*/true);
222*1dad6247STeresa Johnson   assert(MIBCallStack.size() == 1 &&
223*1dad6247STeresa Johnson          "Should only be left with Alloc's location in stack");
224*1dad6247STeresa Johnson   CI->setMetadata(LLVMContext::MD_memprof, MDNode::get(Ctx, MIBNodes));
225*1dad6247STeresa Johnson   return true;
226*1dad6247STeresa Johnson }
227