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/BlockFrequencyInfo.h"
16#include "llvm/Analysis/EHUtils.h"
17#include "llvm/Analysis/LoopInfo.h"
18#include "llvm/IR/BasicBlock.h"
19#include "llvm/IR/Constants.h"
20#include "llvm/IR/DebugInfoMetadata.h"
21#include "llvm/IR/DiagnosticInfo.h"
22#include "llvm/IR/IRBuilder.h"
23#include "llvm/IR/Instruction.h"
24#include "llvm/IR/IntrinsicInst.h"
25#include "llvm/IR/MDBuilder.h"
26#include "llvm/IR/PseudoProbe.h"
27#include "llvm/ProfileData/SampleProf.h"
28#include "llvm/Support/CRC.h"
29#include "llvm/Support/CommandLine.h"
30#include "llvm/Target/TargetMachine.h"
31#include "llvm/Transforms/Instrumentation.h"
32#include "llvm/Transforms/Utils/ModuleUtils.h"
33#include <unordered_set>
34#include <vector>
35
36using namespace llvm;
37#define DEBUG_TYPE "pseudo-probe"
38
39STATISTIC(ArtificialDbgLine,
40 "Number of probes that have an artificial debug line");
41
42static cl::opt<bool>
43 VerifyPseudoProbe("verify-pseudo-probe", cl::init(Val: false), cl::Hidden,
44 cl::desc("Do pseudo probe verification"));
45
46static cl::list<std::string> VerifyPseudoProbeFuncList(
47 "verify-pseudo-probe-funcs", cl::Hidden,
48 cl::desc("The option to specify the name of the functions to verify."));
49
50static cl::opt<bool>
51 UpdatePseudoProbe("update-pseudo-probe", cl::init(Val: true), cl::Hidden,
52 cl::desc("Update pseudo probe distribution factor"));
53
54static uint64_t getCallStackHash(const DILocation *DIL) {
55 uint64_t Hash = 0;
56 const DILocation *InlinedAt = DIL ? DIL->getInlinedAt() : nullptr;
57 while (InlinedAt) {
58 Hash ^= MD5Hash(Str: std::to_string(val: InlinedAt->getLine()));
59 Hash ^= MD5Hash(Str: std::to_string(val: InlinedAt->getColumn()));
60 auto Name = InlinedAt->getSubprogramLinkageName();
61 Hash ^= MD5Hash(Str: Name);
62 InlinedAt = InlinedAt->getInlinedAt();
63 }
64 return Hash;
65}
66
67static uint64_t computeCallStackHash(const Instruction &Inst) {
68 return getCallStackHash(DIL: Inst.getDebugLoc());
69}
70
71bool PseudoProbeVerifier::shouldVerifyFunction(const Function *F) {
72 // Skip function declaration.
73 if (F->isDeclaration())
74 return false;
75 // Skip function that will not be emitted into object file. The prevailing
76 // defintion will be verified instead.
77 if (F->hasAvailableExternallyLinkage())
78 return false;
79 // Do a name matching.
80 static std::unordered_set<std::string> VerifyFuncNames(
81 VerifyPseudoProbeFuncList.begin(), VerifyPseudoProbeFuncList.end());
82 return VerifyFuncNames.empty() || VerifyFuncNames.count(x: F->getName().str());
83}
84
85void PseudoProbeVerifier::registerCallbacks(PassInstrumentationCallbacks &PIC) {
86 if (VerifyPseudoProbe) {
87 PIC.registerAfterPassCallback(
88 C: [this](StringRef P, Any IR, const PreservedAnalyses &) {
89 this->runAfterPass(PassID: P, IR);
90 });
91 }
92}
93
94// Callback to run after each transformation for the new pass manager.
95void PseudoProbeVerifier::runAfterPass(StringRef PassID, Any IR) {
96 std::string Banner =
97 "\n*** Pseudo Probe Verification After " + PassID.str() + " ***\n";
98 dbgs() << Banner;
99 if (const auto **M = llvm::any_cast<const Module *>(Value: &IR))
100 runAfterPass(M: *M);
101 else if (const auto **F = llvm::any_cast<const Function *>(Value: &IR))
102 runAfterPass(F: *F);
103 else if (const auto **C = llvm::any_cast<const LazyCallGraph::SCC *>(Value: &IR))
104 runAfterPass(C: *C);
105 else if (const auto **L = llvm::any_cast<const Loop *>(Value: &IR))
106 runAfterPass(L: *L);
107 else
108 llvm_unreachable("Unknown IR unit");
109}
110
111void PseudoProbeVerifier::runAfterPass(const Module *M) {
112 for (const Function &F : *M)
113 runAfterPass(F: &F);
114}
115
116void PseudoProbeVerifier::runAfterPass(const LazyCallGraph::SCC *C) {
117 for (const LazyCallGraph::Node &N : *C)
118 runAfterPass(F: &N.getFunction());
119}
120
121void PseudoProbeVerifier::runAfterPass(const Function *F) {
122 if (!shouldVerifyFunction(F))
123 return;
124 ProbeFactorMap ProbeFactors;
125 for (const auto &BB : *F)
126 collectProbeFactors(BB: &BB, ProbeFactors);
127 verifyProbeFactors(F, ProbeFactors);
128}
129
130void PseudoProbeVerifier::runAfterPass(const Loop *L) {
131 const Function *F = L->getHeader()->getParent();
132 runAfterPass(F);
133}
134
135void PseudoProbeVerifier::collectProbeFactors(const BasicBlock *Block,
136 ProbeFactorMap &ProbeFactors) {
137 for (const auto &I : *Block) {
138 if (std::optional<PseudoProbe> Probe = extractProbe(Inst: I)) {
139 uint64_t Hash = computeCallStackHash(Inst: I);
140 ProbeFactors[{Probe->Id, Hash}] += Probe->Factor;
141 }
142 }
143}
144
145void PseudoProbeVerifier::verifyProbeFactors(
146 const Function *F, const ProbeFactorMap &ProbeFactors) {
147 bool BannerPrinted = false;
148 auto &PrevProbeFactors = FunctionProbeFactors[F->getName()];
149 for (const auto &I : ProbeFactors) {
150 float CurProbeFactor = I.second;
151 if (PrevProbeFactors.count(x: I.first)) {
152 float PrevProbeFactor = PrevProbeFactors[I.first];
153 if (std::abs(x: CurProbeFactor - PrevProbeFactor) >
154 DistributionFactorVariance) {
155 if (!BannerPrinted) {
156 dbgs() << "Function " << F->getName() << ":\n";
157 BannerPrinted = true;
158 }
159 dbgs() << "Probe " << I.first.first << "\tprevious factor "
160 << format(Fmt: "%0.2f", Vals: PrevProbeFactor) << "\tcurrent factor "
161 << format(Fmt: "%0.2f", Vals: CurProbeFactor) << "\n";
162 }
163 }
164
165 // Update
166 PrevProbeFactors[I.first] = I.second;
167 }
168}
169
170SampleProfileProber::SampleProfileProber(Function &Func,
171 const std::string &CurModuleUniqueId)
172 : F(&Func), CurModuleUniqueId(CurModuleUniqueId) {
173 BlockProbeIds.clear();
174 CallProbeIds.clear();
175 LastProbeId = (uint32_t)PseudoProbeReservedId::Last;
176
177 DenseSet<BasicBlock *> BlocksToIgnore;
178 DenseSet<BasicBlock *> BlocksAndCallsToIgnore;
179 computeBlocksToIgnore(BlocksToIgnore, BlocksAndCallsToIgnore);
180
181 computeProbeId(BlocksToIgnore, BlocksAndCallsToIgnore);
182 computeCFGHash(BlocksToIgnore);
183}
184
185// Two purposes to compute the blocks to ignore:
186// 1. Reduce the IR size.
187// 2. Make the instrumentation(checksum) stable. e.g. the frondend may
188// generate unstable IR while optimizing nounwind attribute, some versions are
189// optimized with the call-to-invoke conversion, while other versions do not.
190// This discrepancy in probe ID could cause profile mismatching issues.
191// Note that those ignored blocks are either cold blocks or new split blocks
192// whose original blocks are instrumented, so it shouldn't degrade the profile
193// quality.
194void SampleProfileProber::computeBlocksToIgnore(
195 DenseSet<BasicBlock *> &BlocksToIgnore,
196 DenseSet<BasicBlock *> &BlocksAndCallsToIgnore) {
197 // Ignore the cold EH and unreachable blocks and calls.
198 computeEHOnlyBlocks(F&: *F, EHBlocks&: BlocksAndCallsToIgnore);
199 findUnreachableBlocks(BlocksToIgnore&: BlocksAndCallsToIgnore);
200
201 BlocksToIgnore.insert(I: BlocksAndCallsToIgnore.begin(),
202 E: BlocksAndCallsToIgnore.end());
203
204 // Handle the call-to-invoke conversion case: make sure that the probe id and
205 // callsite id are consistent before and after the block split. For block
206 // probe, we only keep the head block probe id and ignore the block ids of the
207 // normal dests. For callsite probe, it's different to block probe, there is
208 // no additional callsite in the normal dests, so we don't ignore the
209 // callsites.
210 findInvokeNormalDests(InvokeNormalDests&: BlocksToIgnore);
211}
212
213// Unreachable blocks and calls are always cold, ignore them.
214void SampleProfileProber::findUnreachableBlocks(
215 DenseSet<BasicBlock *> &BlocksToIgnore) {
216 for (auto &BB : *F) {
217 if (&BB != &F->getEntryBlock() && pred_size(BB: &BB) == 0)
218 BlocksToIgnore.insert(V: &BB);
219 }
220}
221
222// In call-to-invoke conversion, basic block can be split into multiple blocks,
223// only instrument probe in the head block, ignore the normal dests.
224void SampleProfileProber::findInvokeNormalDests(
225 DenseSet<BasicBlock *> &InvokeNormalDests) {
226 for (auto &BB : *F) {
227 auto *TI = BB.getTerminator();
228 if (auto *II = dyn_cast<InvokeInst>(Val: TI)) {
229 auto *ND = II->getNormalDest();
230 InvokeNormalDests.insert(V: ND);
231
232 // The normal dest and the try/catch block are connected by an
233 // unconditional branch.
234 while (pred_size(BB: ND) == 1) {
235 auto *Pred = *pred_begin(BB: ND);
236 if (succ_size(BB: Pred) == 1) {
237 InvokeNormalDests.insert(V: Pred);
238 ND = Pred;
239 } else
240 break;
241 }
242 }
243 }
244}
245
246// The call-to-invoke conversion splits the original block into a list of block,
247// we need to compute the hash using the original block's successors to keep the
248// CFG Hash consistent. For a given head block, we keep searching the
249// succesor(normal dest or unconditional branch dest) to find the tail block,
250// the tail block's successors are the original block's successors.
251const Instruction *SampleProfileProber::getOriginalTerminator(
252 const BasicBlock *Head, const DenseSet<BasicBlock *> &BlocksToIgnore) {
253 auto *TI = Head->getTerminator();
254 if (auto *II = dyn_cast<InvokeInst>(Val: TI)) {
255 return getOriginalTerminator(Head: II->getNormalDest(), BlocksToIgnore);
256 } else if (succ_size(BB: Head) == 1 &&
257 BlocksToIgnore.contains(V: *succ_begin(BB: Head))) {
258 // Go to the unconditional branch dest.
259 return getOriginalTerminator(Head: *succ_begin(BB: Head), BlocksToIgnore);
260 }
261 return TI;
262}
263
264// Compute Hash value for the CFG: the lower 32 bits are CRC32 of the index
265// value of each BB in the CFG. The higher 32 bits record the number of edges
266// preceded by the number of indirect calls.
267// This is derived from FuncPGOInstrumentation<Edge, BBInfo>::computeCFGHash().
268void SampleProfileProber::computeCFGHash(
269 const DenseSet<BasicBlock *> &BlocksToIgnore) {
270 std::vector<uint8_t> Indexes;
271 JamCRC JC;
272 for (auto &BB : *F) {
273 if (BlocksToIgnore.contains(V: &BB))
274 continue;
275
276 auto *TI = getOriginalTerminator(Head: &BB, BlocksToIgnore);
277 for (unsigned I = 0, E = TI->getNumSuccessors(); I != E; ++I) {
278 auto *Succ = TI->getSuccessor(Idx: I);
279 auto Index = getBlockId(BB: Succ);
280 // Ingore ignored-block(zero ID) to avoid unstable checksum.
281 if (Index == 0)
282 continue;
283 for (int J = 0; J < 4; J++)
284 Indexes.push_back(x: (uint8_t)(Index >> (J * 8)));
285 }
286 }
287
288 JC.update(Data: Indexes);
289
290 FunctionHash = (uint64_t)CallProbeIds.size() << 48 |
291 (uint64_t)Indexes.size() << 32 | JC.getCRC();
292 // Reserve bit 60-63 for other information purpose.
293 FunctionHash &= 0x0FFFFFFFFFFFFFFF;
294 assert(FunctionHash && "Function checksum should not be zero");
295 LLVM_DEBUG(dbgs() << "\nFunction Hash Computation for " << F->getName()
296 << ":\n"
297 << " CRC = " << JC.getCRC() << ", Edges = "
298 << Indexes.size() << ", ICSites = " << CallProbeIds.size()
299 << ", Hash = " << FunctionHash << "\n");
300}
301
302void SampleProfileProber::computeProbeId(
303 const DenseSet<BasicBlock *> &BlocksToIgnore,
304 const DenseSet<BasicBlock *> &BlocksAndCallsToIgnore) {
305 LLVMContext &Ctx = F->getContext();
306 Module *M = F->getParent();
307
308 for (auto &BB : *F) {
309 if (!BlocksToIgnore.contains(V: &BB))
310 BlockProbeIds[&BB] = ++LastProbeId;
311
312 if (BlocksAndCallsToIgnore.contains(V: &BB))
313 continue;
314 for (auto &I : BB) {
315 if (!isa<CallBase>(Val: I) || isa<IntrinsicInst>(Val: &I))
316 continue;
317
318 // The current implementation uses the lower 16 bits of the discriminator
319 // so anything larger than 0xFFFF will be ignored.
320 if (LastProbeId >= 0xFFFF) {
321 std::string Msg = "Pseudo instrumentation incomplete for " +
322 std::string(F->getName()) + " because it's too large";
323 Ctx.diagnose(
324 DI: DiagnosticInfoSampleProfile(M->getName().data(), Msg, DS_Warning));
325 return;
326 }
327
328 CallProbeIds[&I] = ++LastProbeId;
329 }
330 }
331}
332
333uint32_t SampleProfileProber::getBlockId(const BasicBlock *BB) const {
334 auto I = BlockProbeIds.find(x: const_cast<BasicBlock *>(BB));
335 return I == BlockProbeIds.end() ? 0 : I->second;
336}
337
338uint32_t SampleProfileProber::getCallsiteId(const Instruction *Call) const {
339 auto Iter = CallProbeIds.find(x: const_cast<Instruction *>(Call));
340 return Iter == CallProbeIds.end() ? 0 : Iter->second;
341}
342
343void SampleProfileProber::instrumentOneFunc(Function &F, TargetMachine *TM) {
344 Module *M = F.getParent();
345 MDBuilder MDB(F.getContext());
346 // Since the GUID from probe desc and inline stack are computed seperately, we
347 // need to make sure their names are consistent, so here also use the name
348 // from debug info.
349 StringRef FName = F.getName();
350 if (auto *SP = F.getSubprogram()) {
351 FName = SP->getLinkageName();
352 if (FName.empty())
353 FName = SP->getName();
354 }
355 uint64_t Guid = Function::getGUID(GlobalName: FName);
356
357 // Assign an artificial debug line to a probe that doesn't come with a real
358 // line. A probe not having a debug line will get an incomplete inline
359 // context. This will cause samples collected on the probe to be counted
360 // into the base profile instead of a context profile. The line number
361 // itself is not important though.
362 auto AssignDebugLoc = [&](Instruction *I) {
363 assert((isa<PseudoProbeInst>(I) || isa<CallBase>(I)) &&
364 "Expecting pseudo probe or call instructions");
365 if (!I->getDebugLoc()) {
366 if (auto *SP = F.getSubprogram()) {
367 auto DIL = DILocation::get(Context&: SP->getContext(), Line: 0, Column: 0, Scope: SP);
368 I->setDebugLoc(DIL);
369 ArtificialDbgLine++;
370 LLVM_DEBUG({
371 dbgs() << "\nIn Function " << F.getName()
372 << " Probe gets an artificial debug line\n";
373 I->dump();
374 });
375 }
376 }
377 };
378
379 // Probe basic blocks.
380 for (auto &I : BlockProbeIds) {
381 BasicBlock *BB = I.first;
382 uint32_t Index = I.second;
383 // Insert a probe before an instruction with a valid debug line number which
384 // will be assigned to the probe. The line number will be used later to
385 // model the inline context when the probe is inlined into other functions.
386 // Debug instructions, phi nodes and lifetime markers do not have an valid
387 // line number. Real instructions generated by optimizations may not come
388 // with a line number either.
389 auto HasValidDbgLine = [](Instruction *J) {
390 return !isa<PHINode>(Val: J) && !isa<DbgInfoIntrinsic>(Val: J) &&
391 !J->isLifetimeStartOrEnd() && J->getDebugLoc();
392 };
393
394 Instruction *J = &*BB->getFirstInsertionPt();
395 while (J != BB->getTerminator() && !HasValidDbgLine(J)) {
396 J = J->getNextNode();
397 }
398
399 IRBuilder<> Builder(J);
400 assert(Builder.GetInsertPoint() != BB->end() &&
401 "Cannot get the probing point");
402 Function *ProbeFn =
403 llvm::Intrinsic::getDeclaration(M, Intrinsic::id: pseudoprobe);
404 Value *Args[] = {Builder.getInt64(C: Guid), Builder.getInt64(C: Index),
405 Builder.getInt32(C: 0),
406 Builder.getInt64(C: PseudoProbeFullDistributionFactor)};
407 auto *Probe = Builder.CreateCall(Callee: ProbeFn, Args);
408 AssignDebugLoc(Probe);
409 // Reset the dwarf discriminator if the debug location comes with any. The
410 // discriminator field may be used by FS-AFDO later in the pipeline.
411 if (auto DIL = Probe->getDebugLoc()) {
412 if (DIL->getDiscriminator()) {
413 DIL = DIL->cloneWithDiscriminator(0);
414 Probe->setDebugLoc(DIL);
415 }
416 }
417 }
418
419 // Probe both direct calls and indirect calls. Direct calls are probed so that
420 // their probe ID can be used as an call site identifier to represent a
421 // calling context.
422 for (auto &I : CallProbeIds) {
423 auto *Call = I.first;
424 uint32_t Index = I.second;
425 uint32_t Type = cast<CallBase>(Val: Call)->getCalledFunction()
426 ? (uint32_t)PseudoProbeType::DirectCall
427 : (uint32_t)PseudoProbeType::IndirectCall;
428 AssignDebugLoc(Call);
429 if (auto DIL = Call->getDebugLoc()) {
430 // Levarge the 32-bit discriminator field of debug data to store the ID
431 // and type of a callsite probe. This gets rid of the dependency on
432 // plumbing a customized metadata through the codegen pipeline.
433 uint32_t V = PseudoProbeDwarfDiscriminator::packProbeData(
434 Index, Type, Flags: 0,
435 Factor: PseudoProbeDwarfDiscriminator::FullDistributionFactor);
436 DIL = DIL->cloneWithDiscriminator(Discriminator: V);
437 Call->setDebugLoc(DIL);
438 }
439 }
440
441 // Create module-level metadata that contains function info necessary to
442 // synthesize probe-based sample counts, which are
443 // - FunctionGUID
444 // - FunctionHash.
445 // - FunctionName
446 auto Hash = getFunctionHash();
447 auto *MD = MDB.createPseudoProbeDesc(GUID: Guid, Hash, FName);
448 auto *NMD = M->getNamedMetadata(Name: PseudoProbeDescMetadataName);
449 assert(NMD && "llvm.pseudo_probe_desc should be pre-created");
450 NMD->addOperand(M: MD);
451}
452
453PreservedAnalyses SampleProfileProbePass::run(Module &M,
454 ModuleAnalysisManager &AM) {
455 auto ModuleId = getUniqueModuleId(M: &M);
456 // Create the pseudo probe desc metadata beforehand.
457 // Note that modules with only data but no functions will require this to
458 // be set up so that they will be known as probed later.
459 M.getOrInsertNamedMetadata(Name: PseudoProbeDescMetadataName);
460
461 for (auto &F : M) {
462 if (F.isDeclaration())
463 continue;
464 SampleProfileProber ProbeManager(F, ModuleId);
465 ProbeManager.instrumentOneFunc(F, TM);
466 }
467
468 return PreservedAnalyses::none();
469}
470
471void PseudoProbeUpdatePass::runOnFunction(Function &F,
472 FunctionAnalysisManager &FAM) {
473 BlockFrequencyInfo &BFI = FAM.getResult<BlockFrequencyAnalysis>(IR&: F);
474 auto BBProfileCount = [&BFI](BasicBlock *BB) {
475 return BFI.getBlockProfileCount(BB).value_or(u: 0);
476 };
477
478 // Collect the sum of execution weight for each probe.
479 ProbeFactorMap ProbeFactors;
480 for (auto &Block : F) {
481 for (auto &I : Block) {
482 if (std::optional<PseudoProbe> Probe = extractProbe(Inst: I)) {
483 uint64_t Hash = computeCallStackHash(Inst: I);
484 ProbeFactors[{Probe->Id, Hash}] += BBProfileCount(&Block);
485 }
486 }
487 }
488
489 // Fix up over-counted probes.
490 for (auto &Block : F) {
491 for (auto &I : Block) {
492 if (std::optional<PseudoProbe> Probe = extractProbe(Inst: I)) {
493 uint64_t Hash = computeCallStackHash(Inst: I);
494 float Sum = ProbeFactors[{Probe->Id, Hash}];
495 if (Sum != 0)
496 setProbeDistributionFactor(Inst&: I, Factor: BBProfileCount(&Block) / Sum);
497 }
498 }
499 }
500}
501
502PreservedAnalyses PseudoProbeUpdatePass::run(Module &M,
503 ModuleAnalysisManager &AM) {
504 if (UpdatePseudoProbe) {
505 for (auto &F : M) {
506 if (F.isDeclaration())
507 continue;
508 FunctionAnalysisManager &FAM =
509 AM.getResult<FunctionAnalysisManagerModuleProxy>(IR&: M).getManager();
510 runOnFunction(F, FAM);
511 }
512 }
513 return PreservedAnalyses::none();
514}
515

source code of llvm/lib/Transforms/IPO/SampleProfileProbe.cpp