1 //===-- MemoryProfileInfo.cpp - memory profile info ------------------------==// 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 #include "llvm/Analysis/MemoryProfileInfo.h" 14 #include "llvm/IR/Constants.h" 15 #include "llvm/Support/CommandLine.h" 16 17 using namespace llvm; 18 using namespace llvm::memprof; 19 20 #define DEBUG_TYPE "memory-profile-info" 21 22 // Upper bound on lifetime access density (accesses per byte per lifetime sec) 23 // for marking an allocation cold. 24 cl::opt<float> MemProfLifetimeAccessDensityColdThreshold( 25 "memprof-lifetime-access-density-cold-threshold", cl::init(0.05), 26 cl::Hidden, 27 cl::desc("The threshold the lifetime access density (accesses per byte per " 28 "lifetime sec) must be under to consider an allocation cold")); 29 30 // Lower bound on lifetime to mark an allocation cold (in addition to accesses 31 // per byte per sec above). This is to avoid pessimizing short lived objects. 32 cl::opt<unsigned> MemProfAveLifetimeColdThreshold( 33 "memprof-ave-lifetime-cold-threshold", cl::init(200), cl::Hidden, 34 cl::desc("The average lifetime (s) for an allocation to be considered " 35 "cold")); 36 37 // Lower bound on average lifetime accesses density (total life time access 38 // density / alloc count) for marking an allocation hot. 39 cl::opt<unsigned> MemProfMinAveLifetimeAccessDensityHotThreshold( 40 "memprof-min-ave-lifetime-access-density-hot-threshold", cl::init(1000), 41 cl::Hidden, 42 cl::desc("The minimum TotalLifetimeAccessDensity / AllocCount for an " 43 "allocation to be considered hot")); 44 45 cl::opt<bool> MemProfReportHintedSizes( 46 "memprof-report-hinted-sizes", cl::init(false), cl::Hidden, 47 cl::desc("Report total allocation sizes of hinted allocations")); 48 49 AllocationType llvm::memprof::getAllocType(uint64_t TotalLifetimeAccessDensity, 50 uint64_t AllocCount, 51 uint64_t TotalLifetime) { 52 // The access densities are multiplied by 100 to hold 2 decimal places of 53 // precision, so need to divide by 100. 54 if (((float)TotalLifetimeAccessDensity) / AllocCount / 100 < 55 MemProfLifetimeAccessDensityColdThreshold 56 // Lifetime is expected to be in ms, so convert the threshold to ms. 57 && ((float)TotalLifetime) / AllocCount >= 58 MemProfAveLifetimeColdThreshold * 1000) 59 return AllocationType::Cold; 60 61 // The access densities are multiplied by 100 to hold 2 decimal places of 62 // precision, so need to divide by 100. 63 if (((float)TotalLifetimeAccessDensity) / AllocCount / 100 > 64 MemProfMinAveLifetimeAccessDensityHotThreshold) 65 return AllocationType::Hot; 66 67 return AllocationType::NotCold; 68 } 69 70 MDNode *llvm::memprof::buildCallstackMetadata(ArrayRef<uint64_t> CallStack, 71 LLVMContext &Ctx) { 72 SmallVector<Metadata *, 8> StackVals; 73 StackVals.reserve(CallStack.size()); 74 for (auto Id : CallStack) { 75 auto *StackValMD = 76 ValueAsMetadata::get(ConstantInt::get(Type::getInt64Ty(Ctx), Id)); 77 StackVals.push_back(StackValMD); 78 } 79 return MDNode::get(Ctx, StackVals); 80 } 81 82 MDNode *llvm::memprof::getMIBStackNode(const MDNode *MIB) { 83 assert(MIB->getNumOperands() >= 2); 84 // The stack metadata is the first operand of each memprof MIB metadata. 85 return cast<MDNode>(MIB->getOperand(0)); 86 } 87 88 AllocationType llvm::memprof::getMIBAllocType(const MDNode *MIB) { 89 assert(MIB->getNumOperands() >= 2); 90 // The allocation type is currently the second operand of each memprof 91 // MIB metadata. This will need to change as we add additional allocation 92 // types that can be applied based on the allocation profile data. 93 auto *MDS = dyn_cast<MDString>(MIB->getOperand(1)); 94 assert(MDS); 95 if (MDS->getString() == "cold") { 96 return AllocationType::Cold; 97 } else if (MDS->getString() == "hot") { 98 return AllocationType::Hot; 99 } 100 return AllocationType::NotCold; 101 } 102 103 std::string llvm::memprof::getAllocTypeAttributeString(AllocationType Type) { 104 switch (Type) { 105 case AllocationType::NotCold: 106 return "notcold"; 107 break; 108 case AllocationType::Cold: 109 return "cold"; 110 break; 111 case AllocationType::Hot: 112 return "hot"; 113 break; 114 default: 115 assert(false && "Unexpected alloc type"); 116 } 117 llvm_unreachable("invalid alloc type"); 118 } 119 120 static void addAllocTypeAttribute(LLVMContext &Ctx, CallBase *CI, 121 AllocationType AllocType) { 122 auto AllocTypeString = getAllocTypeAttributeString(AllocType); 123 auto A = llvm::Attribute::get(Ctx, "memprof", AllocTypeString); 124 CI->addFnAttr(A); 125 } 126 127 bool llvm::memprof::hasSingleAllocType(uint8_t AllocTypes) { 128 const unsigned NumAllocTypes = llvm::popcount(AllocTypes); 129 assert(NumAllocTypes != 0); 130 return NumAllocTypes == 1; 131 } 132 133 void CallStackTrie::addCallStack( 134 AllocationType AllocType, ArrayRef<uint64_t> StackIds, 135 std::vector<ContextTotalSize> ContextSizeInfo) { 136 bool First = true; 137 CallStackTrieNode *Curr = nullptr; 138 for (auto StackId : StackIds) { 139 // If this is the first stack frame, add or update alloc node. 140 if (First) { 141 First = false; 142 if (Alloc) { 143 assert(AllocStackId == StackId); 144 Alloc->AllocTypes |= static_cast<uint8_t>(AllocType); 145 } else { 146 AllocStackId = StackId; 147 Alloc = new CallStackTrieNode(AllocType); 148 } 149 Curr = Alloc; 150 continue; 151 } 152 // Update existing caller node if it exists. 153 auto Next = Curr->Callers.find(StackId); 154 if (Next != Curr->Callers.end()) { 155 Curr = Next->second; 156 Curr->AllocTypes |= static_cast<uint8_t>(AllocType); 157 continue; 158 } 159 // Otherwise add a new caller node. 160 auto *New = new CallStackTrieNode(AllocType); 161 Curr->Callers[StackId] = New; 162 Curr = New; 163 } 164 assert(Curr); 165 Curr->ContextSizeInfo.insert(Curr->ContextSizeInfo.end(), 166 ContextSizeInfo.begin(), ContextSizeInfo.end()); 167 std::vector<ContextTotalSize> AllContextSizeInfo; 168 collectContextSizeInfo(Curr, AllContextSizeInfo); 169 } 170 171 void CallStackTrie::addCallStack(MDNode *MIB) { 172 MDNode *StackMD = getMIBStackNode(MIB); 173 assert(StackMD); 174 std::vector<uint64_t> CallStack; 175 CallStack.reserve(StackMD->getNumOperands()); 176 for (const auto &MIBStackIter : StackMD->operands()) { 177 auto *StackId = mdconst::dyn_extract<ConstantInt>(MIBStackIter); 178 assert(StackId); 179 CallStack.push_back(StackId->getZExtValue()); 180 } 181 std::vector<ContextTotalSize> ContextSizeInfo; 182 // Collect the context size information if it exists. 183 if (MIB->getNumOperands() > 2) { 184 for (unsigned I = 2; I < MIB->getNumOperands(); I++) { 185 MDNode *ContextSizePair = dyn_cast<MDNode>(MIB->getOperand(I)); 186 assert(ContextSizePair->getNumOperands() == 2); 187 uint64_t FullStackId = 188 mdconst::dyn_extract<ConstantInt>(ContextSizePair->getOperand(0)) 189 ->getZExtValue(); 190 uint64_t TotalSize = 191 mdconst::dyn_extract<ConstantInt>(ContextSizePair->getOperand(1)) 192 ->getZExtValue(); 193 ContextSizeInfo.push_back({FullStackId, TotalSize}); 194 } 195 } 196 addCallStack(getMIBAllocType(MIB), CallStack, std::move(ContextSizeInfo)); 197 } 198 199 static MDNode *createMIBNode(LLVMContext &Ctx, ArrayRef<uint64_t> MIBCallStack, 200 AllocationType AllocType, 201 ArrayRef<ContextTotalSize> ContextSizeInfo) { 202 SmallVector<Metadata *> MIBPayload( 203 {buildCallstackMetadata(MIBCallStack, Ctx)}); 204 MIBPayload.push_back( 205 MDString::get(Ctx, getAllocTypeAttributeString(AllocType))); 206 if (!ContextSizeInfo.empty()) { 207 for (const auto &[FullStackId, TotalSize] : ContextSizeInfo) { 208 auto *FullStackIdMD = ValueAsMetadata::get( 209 ConstantInt::get(Type::getInt64Ty(Ctx), FullStackId)); 210 auto *TotalSizeMD = ValueAsMetadata::get( 211 ConstantInt::get(Type::getInt64Ty(Ctx), TotalSize)); 212 auto *ContextSizeMD = MDNode::get(Ctx, {FullStackIdMD, TotalSizeMD}); 213 MIBPayload.push_back(ContextSizeMD); 214 } 215 } 216 return MDNode::get(Ctx, MIBPayload); 217 } 218 219 void CallStackTrie::collectContextSizeInfo( 220 CallStackTrieNode *Node, std::vector<ContextTotalSize> &ContextSizeInfo) { 221 ContextSizeInfo.insert(ContextSizeInfo.end(), Node->ContextSizeInfo.begin(), 222 Node->ContextSizeInfo.end()); 223 for (auto &Caller : Node->Callers) 224 collectContextSizeInfo(Caller.second, ContextSizeInfo); 225 } 226 227 // Recursive helper to trim contexts and create metadata nodes. 228 // Caller should have pushed Node's loc to MIBCallStack. Doing this in the 229 // caller makes it simpler to handle the many early returns in this method. 230 bool CallStackTrie::buildMIBNodes(CallStackTrieNode *Node, LLVMContext &Ctx, 231 std::vector<uint64_t> &MIBCallStack, 232 std::vector<Metadata *> &MIBNodes, 233 bool CalleeHasAmbiguousCallerContext) { 234 // Trim context below the first node in a prefix with a single alloc type. 235 // Add an MIB record for the current call stack prefix. 236 if (hasSingleAllocType(Node->AllocTypes)) { 237 std::vector<ContextTotalSize> ContextSizeInfo; 238 collectContextSizeInfo(Node, ContextSizeInfo); 239 MIBNodes.push_back(createMIBNode( 240 Ctx, MIBCallStack, (AllocationType)Node->AllocTypes, ContextSizeInfo)); 241 return true; 242 } 243 244 // We don't have a single allocation for all the contexts sharing this prefix, 245 // so recursively descend into callers in trie. 246 if (!Node->Callers.empty()) { 247 bool NodeHasAmbiguousCallerContext = Node->Callers.size() > 1; 248 bool AddedMIBNodesForAllCallerContexts = true; 249 for (auto &Caller : Node->Callers) { 250 MIBCallStack.push_back(Caller.first); 251 AddedMIBNodesForAllCallerContexts &= 252 buildMIBNodes(Caller.second, Ctx, MIBCallStack, MIBNodes, 253 NodeHasAmbiguousCallerContext); 254 // Remove Caller. 255 MIBCallStack.pop_back(); 256 } 257 if (AddedMIBNodesForAllCallerContexts) 258 return true; 259 // We expect that the callers should be forced to add MIBs to disambiguate 260 // the context in this case (see below). 261 assert(!NodeHasAmbiguousCallerContext); 262 } 263 264 // If we reached here, then this node does not have a single allocation type, 265 // and we didn't add metadata for a longer call stack prefix including any of 266 // Node's callers. That means we never hit a single allocation type along all 267 // call stacks with this prefix. This can happen due to recursion collapsing 268 // or the stack being deeper than tracked by the profiler runtime, leading to 269 // contexts with different allocation types being merged. In that case, we 270 // trim the context just below the deepest context split, which is this 271 // node if the callee has an ambiguous caller context (multiple callers), 272 // since the recursive calls above returned false. Conservatively give it 273 // non-cold allocation type. 274 if (!CalleeHasAmbiguousCallerContext) 275 return false; 276 std::vector<ContextTotalSize> ContextSizeInfo; 277 collectContextSizeInfo(Node, ContextSizeInfo); 278 MIBNodes.push_back(createMIBNode(Ctx, MIBCallStack, AllocationType::NotCold, 279 ContextSizeInfo)); 280 return true; 281 } 282 283 // Build and attach the minimal necessary MIB metadata. If the alloc has a 284 // single allocation type, add a function attribute instead. Returns true if 285 // memprof metadata attached, false if not (attribute added). 286 bool CallStackTrie::buildAndAttachMIBMetadata(CallBase *CI) { 287 auto &Ctx = CI->getContext(); 288 if (hasSingleAllocType(Alloc->AllocTypes)) { 289 addAllocTypeAttribute(Ctx, CI, (AllocationType)Alloc->AllocTypes); 290 if (MemProfReportHintedSizes) { 291 std::vector<ContextTotalSize> ContextSizeInfo; 292 collectContextSizeInfo(Alloc, ContextSizeInfo); 293 for (const auto &[FullStackId, TotalSize] : ContextSizeInfo) { 294 errs() 295 << "MemProf hinting: Total size for full allocation context hash " 296 << FullStackId << " and single alloc type " 297 << getAllocTypeAttributeString((AllocationType)Alloc->AllocTypes) 298 << ": " << TotalSize << "\n"; 299 } 300 } 301 return false; 302 } 303 std::vector<uint64_t> MIBCallStack; 304 MIBCallStack.push_back(AllocStackId); 305 std::vector<Metadata *> MIBNodes; 306 assert(!Alloc->Callers.empty() && "addCallStack has not been called yet"); 307 // The last parameter is meant to say whether the callee of the given node 308 // has more than one caller. Here the node being passed in is the alloc 309 // and it has no callees. So it's false. 310 if (buildMIBNodes(Alloc, Ctx, MIBCallStack, MIBNodes, false)) { 311 assert(MIBCallStack.size() == 1 && 312 "Should only be left with Alloc's location in stack"); 313 CI->setMetadata(LLVMContext::MD_memprof, MDNode::get(Ctx, MIBNodes)); 314 return true; 315 } 316 // If there exists corner case that CallStackTrie has one chain to leaf 317 // and all node in the chain have multi alloc type, conservatively give 318 // it non-cold allocation type. 319 // FIXME: Avoid this case before memory profile created. 320 addAllocTypeAttribute(Ctx, CI, AllocationType::NotCold); 321 return false; 322 } 323 324 template <> 325 CallStack<MDNode, MDNode::op_iterator>::CallStackIterator::CallStackIterator( 326 const MDNode *N, bool End) 327 : N(N) { 328 if (!N) 329 return; 330 Iter = End ? N->op_end() : N->op_begin(); 331 } 332 333 template <> 334 uint64_t 335 CallStack<MDNode, MDNode::op_iterator>::CallStackIterator::operator*() { 336 assert(Iter != N->op_end()); 337 ConstantInt *StackIdCInt = mdconst::dyn_extract<ConstantInt>(*Iter); 338 assert(StackIdCInt); 339 return StackIdCInt->getZExtValue(); 340 } 341 342 template <> uint64_t CallStack<MDNode, MDNode::op_iterator>::back() const { 343 assert(N); 344 return mdconst::dyn_extract<ConstantInt>(N->operands().back()) 345 ->getZExtValue(); 346 } 347