1 //===- SampleProfileProbe.cpp - Pseudo probe Instrumentation -------------===// 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 implements the SampleProfileProber transformation. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "llvm/Transforms/IPO/SampleProfileProbe.h" 14 #include "llvm/ADT/Statistic.h" 15 #include "llvm/Analysis/TargetLibraryInfo.h" 16 #include "llvm/IR/BasicBlock.h" 17 #include "llvm/IR/CFG.h" 18 #include "llvm/IR/Constant.h" 19 #include "llvm/IR/Constants.h" 20 #include "llvm/IR/DebugInfoMetadata.h" 21 #include "llvm/IR/GlobalValue.h" 22 #include "llvm/IR/GlobalVariable.h" 23 #include "llvm/IR/IRBuilder.h" 24 #include "llvm/IR/Instruction.h" 25 #include "llvm/IR/MDBuilder.h" 26 #include "llvm/ProfileData/SampleProf.h" 27 #include "llvm/Support/CRC.h" 28 #include "llvm/Transforms/Instrumentation.h" 29 #include "llvm/Transforms/Utils/ModuleUtils.h" 30 #include <vector> 31 32 using namespace llvm; 33 #define DEBUG_TYPE "sample-profile-probe" 34 35 STATISTIC(ArtificialDbgLine, 36 "Number of probes that have an artificial debug line"); 37 38 PseudoProbeManager::PseudoProbeManager(const Module &M) { 39 if (NamedMDNode *FuncInfo = M.getNamedMetadata(PseudoProbeDescMetadataName)) { 40 for (const auto *Operand : FuncInfo->operands()) { 41 const auto *MD = cast<MDNode>(Operand); 42 auto GUID = 43 mdconst::dyn_extract<ConstantInt>(MD->getOperand(0))->getZExtValue(); 44 auto Hash = 45 mdconst::dyn_extract<ConstantInt>(MD->getOperand(1))->getZExtValue(); 46 GUIDToProbeDescMap.try_emplace(GUID, PseudoProbeDescriptor(GUID, Hash)); 47 } 48 } 49 } 50 51 const PseudoProbeDescriptor * 52 PseudoProbeManager::getDesc(const Function &F) const { 53 auto I = GUIDToProbeDescMap.find( 54 Function::getGUID(FunctionSamples::getCanonicalFnName(F))); 55 return I == GUIDToProbeDescMap.end() ? nullptr : &I->second; 56 } 57 58 bool PseudoProbeManager::moduleIsProbed(const Module &M) const { 59 return M.getNamedMetadata(PseudoProbeDescMetadataName); 60 } 61 62 bool PseudoProbeManager::profileIsValid(const Function &F, 63 const FunctionSamples &Samples) const { 64 const auto *Desc = getDesc(F); 65 if (!Desc) { 66 LLVM_DEBUG(dbgs() << "Probe descriptor missing for Function " << F.getName() 67 << "\n"); 68 return false; 69 } else { 70 if (Desc->getFunctionHash() != Samples.getFunctionHash()) { 71 LLVM_DEBUG(dbgs() << "Hash mismatch for Function " << F.getName() 72 << "\n"); 73 return false; 74 } 75 } 76 return true; 77 } 78 79 SampleProfileProber::SampleProfileProber(Function &Func, 80 const std::string &CurModuleUniqueId) 81 : F(&Func), CurModuleUniqueId(CurModuleUniqueId) { 82 BlockProbeIds.clear(); 83 CallProbeIds.clear(); 84 LastProbeId = (uint32_t)PseudoProbeReservedId::Last; 85 computeProbeIdForBlocks(); 86 computeProbeIdForCallsites(); 87 computeCFGHash(); 88 } 89 90 // Compute Hash value for the CFG: the lower 32 bits are CRC32 of the index 91 // value of each BB in the CFG. The higher 32 bits record the number of edges 92 // preceded by the number of indirect calls. 93 // This is derived from FuncPGOInstrumentation<Edge, BBInfo>::computeCFGHash(). 94 void SampleProfileProber::computeCFGHash() { 95 std::vector<uint8_t> Indexes; 96 JamCRC JC; 97 for (auto &BB : *F) { 98 auto *TI = BB.getTerminator(); 99 for (unsigned I = 0, E = TI->getNumSuccessors(); I != E; ++I) { 100 auto *Succ = TI->getSuccessor(I); 101 auto Index = getBlockId(Succ); 102 for (int J = 0; J < 4; J++) 103 Indexes.push_back((uint8_t)(Index >> (J * 8))); 104 } 105 } 106 107 JC.update(Indexes); 108 109 FunctionHash = (uint64_t)CallProbeIds.size() << 48 | 110 (uint64_t)Indexes.size() << 32 | JC.getCRC(); 111 // Reserve bit 60-63 for other information purpose. 112 FunctionHash &= 0x0FFFFFFFFFFFFFFF; 113 assert(FunctionHash && "Function checksum should not be zero"); 114 LLVM_DEBUG(dbgs() << "\nFunction Hash Computation for " << F->getName() 115 << ":\n" 116 << " CRC = " << JC.getCRC() << ", Edges = " 117 << Indexes.size() << ", ICSites = " << CallProbeIds.size() 118 << ", Hash = " << FunctionHash << "\n"); 119 } 120 121 void SampleProfileProber::computeProbeIdForBlocks() { 122 for (auto &BB : *F) { 123 BlockProbeIds[&BB] = ++LastProbeId; 124 } 125 } 126 127 void SampleProfileProber::computeProbeIdForCallsites() { 128 for (auto &BB : *F) { 129 for (auto &I : BB) { 130 if (!isa<CallBase>(I)) 131 continue; 132 if (isa<IntrinsicInst>(&I)) 133 continue; 134 CallProbeIds[&I] = ++LastProbeId; 135 } 136 } 137 } 138 139 uint32_t SampleProfileProber::getBlockId(const BasicBlock *BB) const { 140 auto I = BlockProbeIds.find(const_cast<BasicBlock *>(BB)); 141 return I == BlockProbeIds.end() ? 0 : I->second; 142 } 143 144 uint32_t SampleProfileProber::getCallsiteId(const Instruction *Call) const { 145 auto Iter = CallProbeIds.find(const_cast<Instruction *>(Call)); 146 return Iter == CallProbeIds.end() ? 0 : Iter->second; 147 } 148 149 void SampleProfileProber::instrumentOneFunc(Function &F, TargetMachine *TM) { 150 Module *M = F.getParent(); 151 MDBuilder MDB(F.getContext()); 152 // Compute a GUID without considering the function's linkage type. This is 153 // fine since function name is the only key in the profile database. 154 uint64_t Guid = Function::getGUID(F.getName()); 155 156 // Assign an artificial debug line to a probe that doesn't come with a real 157 // line. A probe not having a debug line will get an incomplete inline 158 // context. This will cause samples collected on the probe to be counted 159 // into the base profile instead of a context profile. The line number 160 // itself is not important though. 161 auto AssignDebugLoc = [&](Instruction *I) { 162 assert((isa<PseudoProbeInst>(I) || isa<CallBase>(I)) && 163 "Expecting pseudo probe or call instructions"); 164 if (!I->getDebugLoc()) { 165 if (auto *SP = F.getSubprogram()) { 166 auto DIL = DILocation::get(SP->getContext(), 0, 0, SP); 167 I->setDebugLoc(DIL); 168 ArtificialDbgLine++; 169 LLVM_DEBUG({ 170 dbgs() << "\nIn Function " << F.getName() 171 << " Probe gets an artificial debug line\n"; 172 I->dump(); 173 }); 174 } 175 } 176 }; 177 178 // Probe basic blocks. 179 for (auto &I : BlockProbeIds) { 180 BasicBlock *BB = I.first; 181 uint32_t Index = I.second; 182 // Insert a probe before an instruction with a valid debug line number which 183 // will be assigned to the probe. The line number will be used later to 184 // model the inline context when the probe is inlined into other functions. 185 // Debug instructions, phi nodes and lifetime markers do not have an valid 186 // line number. Real instructions generated by optimizations may not come 187 // with a line number either. 188 auto HasValidDbgLine = [](Instruction *J) { 189 return !isa<PHINode>(J) && !isa<DbgInfoIntrinsic>(J) && 190 !J->isLifetimeStartOrEnd() && J->getDebugLoc(); 191 }; 192 193 Instruction *J = &*BB->getFirstInsertionPt(); 194 while (J != BB->getTerminator() && !HasValidDbgLine(J)) { 195 J = J->getNextNode(); 196 } 197 198 IRBuilder<> Builder(J); 199 assert(Builder.GetInsertPoint() != BB->end() && 200 "Cannot get the probing point"); 201 Function *ProbeFn = 202 llvm::Intrinsic::getDeclaration(M, Intrinsic::pseudoprobe); 203 Value *Args[] = {Builder.getInt64(Guid), Builder.getInt64(Index), 204 Builder.getInt32(0)}; 205 auto *Probe = Builder.CreateCall(ProbeFn, Args); 206 AssignDebugLoc(Probe); 207 } 208 209 // Probe both direct calls and indirect calls. Direct calls are probed so that 210 // their probe ID can be used as an call site identifier to represent a 211 // calling context. 212 for (auto &I : CallProbeIds) { 213 auto *Call = I.first; 214 uint32_t Index = I.second; 215 uint32_t Type = cast<CallBase>(Call)->getCalledFunction() 216 ? (uint32_t)PseudoProbeType::DirectCall 217 : (uint32_t)PseudoProbeType::IndirectCall; 218 AssignDebugLoc(Call); 219 // Levarge the 32-bit discriminator field of debug data to store the ID and 220 // type of a callsite probe. This gets rid of the dependency on plumbing a 221 // customized metadata through the codegen pipeline. 222 uint32_t V = PseudoProbeDwarfDiscriminator::packProbeData(Index, Type); 223 if (auto DIL = Call->getDebugLoc()) { 224 DIL = DIL->cloneWithDiscriminator(V); 225 Call->setDebugLoc(DIL); 226 } 227 } 228 229 // Create module-level metadata that contains function info necessary to 230 // synthesize probe-based sample counts, which are 231 // - FunctionGUID 232 // - FunctionHash. 233 // - FunctionName 234 auto Hash = getFunctionHash(); 235 auto *MD = MDB.createPseudoProbeDesc(Guid, Hash, &F); 236 auto *NMD = M->getNamedMetadata(PseudoProbeDescMetadataName); 237 assert(NMD && "llvm.pseudo_probe_desc should be pre-created"); 238 NMD->addOperand(MD); 239 240 // Preserve a comdat group to hold all probes materialized later. This 241 // allows that when the function is considered dead and removed, the 242 // materialized probes are disposed too. 243 // Imported functions are defined in another module. They do not need 244 // the following handling since same care will be taken for them in their 245 // original module. The pseudo probes inserted into an imported functions 246 // above will naturally not be emitted since the imported function is free 247 // from object emission. However they will be emitted together with the 248 // inliner functions that the imported function is inlined into. We are not 249 // creating a comdat group for an import function since it's useless anyway. 250 if (!F.isDeclarationForLinker()) { 251 if (TM) { 252 auto Triple = TM->getTargetTriple(); 253 if (Triple.supportsCOMDAT() && TM->getFunctionSections()) { 254 GetOrCreateFunctionComdat(F, Triple, CurModuleUniqueId); 255 } 256 } 257 } 258 } 259 260 PreservedAnalyses SampleProfileProbePass::run(Module &M, 261 ModuleAnalysisManager &AM) { 262 auto ModuleId = getUniqueModuleId(&M); 263 // Create the pseudo probe desc metadata beforehand. 264 // Note that modules with only data but no functions will require this to 265 // be set up so that they will be known as probed later. 266 M.getOrInsertNamedMetadata(PseudoProbeDescMetadataName); 267 268 for (auto &F : M) { 269 if (F.isDeclaration()) 270 continue; 271 SampleProfileProber ProbeManager(F, ModuleId); 272 ProbeManager.instrumentOneFunc(F, TM); 273 } 274 275 return PreservedAnalyses::none(); 276 } 277