xref: /freebsd-src/contrib/llvm-project/llvm/lib/Transforms/IPO/SampleProfileProbe.cpp (revision fe6060f10f634930ff71b7c50291ddc610da2475)
1e8d8bef9SDimitry Andric //===- SampleProfileProbe.cpp - Pseudo probe Instrumentation -------------===//
2e8d8bef9SDimitry Andric //
3e8d8bef9SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e8d8bef9SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5e8d8bef9SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6e8d8bef9SDimitry Andric //
7e8d8bef9SDimitry Andric //===----------------------------------------------------------------------===//
8e8d8bef9SDimitry Andric //
9e8d8bef9SDimitry Andric // This file implements the SampleProfileProber transformation.
10e8d8bef9SDimitry Andric //
11e8d8bef9SDimitry Andric //===----------------------------------------------------------------------===//
12e8d8bef9SDimitry Andric 
13e8d8bef9SDimitry Andric #include "llvm/Transforms/IPO/SampleProfileProbe.h"
14e8d8bef9SDimitry Andric #include "llvm/ADT/Statistic.h"
15d409305fSDimitry Andric #include "llvm/Analysis/BlockFrequencyInfo.h"
16e8d8bef9SDimitry Andric #include "llvm/Analysis/TargetLibraryInfo.h"
17e8d8bef9SDimitry Andric #include "llvm/IR/BasicBlock.h"
18e8d8bef9SDimitry Andric #include "llvm/IR/CFG.h"
19e8d8bef9SDimitry Andric #include "llvm/IR/Constant.h"
20e8d8bef9SDimitry Andric #include "llvm/IR/Constants.h"
21e8d8bef9SDimitry Andric #include "llvm/IR/DebugInfoMetadata.h"
22e8d8bef9SDimitry Andric #include "llvm/IR/GlobalValue.h"
23e8d8bef9SDimitry Andric #include "llvm/IR/GlobalVariable.h"
24e8d8bef9SDimitry Andric #include "llvm/IR/IRBuilder.h"
25e8d8bef9SDimitry Andric #include "llvm/IR/Instruction.h"
26e8d8bef9SDimitry Andric #include "llvm/IR/MDBuilder.h"
27e8d8bef9SDimitry Andric #include "llvm/ProfileData/SampleProf.h"
28e8d8bef9SDimitry Andric #include "llvm/Support/CRC.h"
29d409305fSDimitry Andric #include "llvm/Support/CommandLine.h"
30e8d8bef9SDimitry Andric #include "llvm/Transforms/Instrumentation.h"
31e8d8bef9SDimitry Andric #include "llvm/Transforms/Utils/ModuleUtils.h"
32d409305fSDimitry Andric #include <unordered_set>
33e8d8bef9SDimitry Andric #include <vector>
34e8d8bef9SDimitry Andric 
35e8d8bef9SDimitry Andric using namespace llvm;
36e8d8bef9SDimitry Andric #define DEBUG_TYPE "sample-profile-probe"
37e8d8bef9SDimitry Andric 
38e8d8bef9SDimitry Andric STATISTIC(ArtificialDbgLine,
39e8d8bef9SDimitry Andric           "Number of probes that have an artificial debug line");
40e8d8bef9SDimitry Andric 
41d409305fSDimitry Andric static cl::opt<bool>
42d409305fSDimitry Andric     VerifyPseudoProbe("verify-pseudo-probe", cl::init(false), cl::Hidden,
43d409305fSDimitry Andric                       cl::desc("Do pseudo probe verification"));
44d409305fSDimitry Andric 
45d409305fSDimitry Andric static cl::list<std::string> VerifyPseudoProbeFuncList(
46d409305fSDimitry Andric     "verify-pseudo-probe-funcs", cl::Hidden,
47d409305fSDimitry Andric     cl::desc("The option to specify the name of the functions to verify."));
48d409305fSDimitry Andric 
49d409305fSDimitry Andric static cl::opt<bool>
50d409305fSDimitry Andric     UpdatePseudoProbe("update-pseudo-probe", cl::init(true), cl::Hidden,
51d409305fSDimitry Andric                       cl::desc("Update pseudo probe distribution factor"));
52d409305fSDimitry Andric 
53*fe6060f1SDimitry Andric static uint64_t getCallStackHash(const DILocation *DIL) {
54*fe6060f1SDimitry Andric   uint64_t Hash = 0;
55*fe6060f1SDimitry Andric   const DILocation *InlinedAt = DIL ? DIL->getInlinedAt() : nullptr;
56*fe6060f1SDimitry Andric   while (InlinedAt) {
57*fe6060f1SDimitry Andric     Hash ^= MD5Hash(std::to_string(InlinedAt->getLine()));
58*fe6060f1SDimitry Andric     Hash ^= MD5Hash(std::to_string(InlinedAt->getColumn()));
59*fe6060f1SDimitry Andric     const DISubprogram *SP = InlinedAt->getScope()->getSubprogram();
60*fe6060f1SDimitry Andric     // Use linkage name for C++ if possible.
61*fe6060f1SDimitry Andric     auto Name = SP->getLinkageName();
62*fe6060f1SDimitry Andric     if (Name.empty())
63*fe6060f1SDimitry Andric       Name = SP->getName();
64*fe6060f1SDimitry Andric     Hash ^= MD5Hash(Name);
65*fe6060f1SDimitry Andric     InlinedAt = InlinedAt->getInlinedAt();
66*fe6060f1SDimitry Andric   }
67*fe6060f1SDimitry Andric   return Hash;
68*fe6060f1SDimitry Andric }
69*fe6060f1SDimitry Andric 
70*fe6060f1SDimitry Andric static uint64_t computeCallStackHash(const Instruction &Inst) {
71*fe6060f1SDimitry Andric   return getCallStackHash(Inst.getDebugLoc());
72*fe6060f1SDimitry Andric }
73*fe6060f1SDimitry Andric 
74d409305fSDimitry Andric bool PseudoProbeVerifier::shouldVerifyFunction(const Function *F) {
75d409305fSDimitry Andric   // Skip function declaration.
76d409305fSDimitry Andric   if (F->isDeclaration())
77d409305fSDimitry Andric     return false;
78d409305fSDimitry Andric   // Skip function that will not be emitted into object file. The prevailing
79d409305fSDimitry Andric   // defintion will be verified instead.
80d409305fSDimitry Andric   if (F->hasAvailableExternallyLinkage())
81d409305fSDimitry Andric     return false;
82d409305fSDimitry Andric   // Do a name matching.
83d409305fSDimitry Andric   static std::unordered_set<std::string> VerifyFuncNames(
84d409305fSDimitry Andric       VerifyPseudoProbeFuncList.begin(), VerifyPseudoProbeFuncList.end());
85d409305fSDimitry Andric   return VerifyFuncNames.empty() || VerifyFuncNames.count(F->getName().str());
86d409305fSDimitry Andric }
87d409305fSDimitry Andric 
88d409305fSDimitry Andric void PseudoProbeVerifier::registerCallbacks(PassInstrumentationCallbacks &PIC) {
89d409305fSDimitry Andric   if (VerifyPseudoProbe) {
90d409305fSDimitry Andric     PIC.registerAfterPassCallback(
91d409305fSDimitry Andric         [this](StringRef P, Any IR, const PreservedAnalyses &) {
92d409305fSDimitry Andric           this->runAfterPass(P, IR);
93d409305fSDimitry Andric         });
94d409305fSDimitry Andric   }
95d409305fSDimitry Andric }
96d409305fSDimitry Andric 
97d409305fSDimitry Andric // Callback to run after each transformation for the new pass manager.
98d409305fSDimitry Andric void PseudoProbeVerifier::runAfterPass(StringRef PassID, Any IR) {
99d409305fSDimitry Andric   std::string Banner =
100d409305fSDimitry Andric       "\n*** Pseudo Probe Verification After " + PassID.str() + " ***\n";
101d409305fSDimitry Andric   dbgs() << Banner;
102d409305fSDimitry Andric   if (any_isa<const Module *>(IR))
103d409305fSDimitry Andric     runAfterPass(any_cast<const Module *>(IR));
104d409305fSDimitry Andric   else if (any_isa<const Function *>(IR))
105d409305fSDimitry Andric     runAfterPass(any_cast<const Function *>(IR));
106d409305fSDimitry Andric   else if (any_isa<const LazyCallGraph::SCC *>(IR))
107d409305fSDimitry Andric     runAfterPass(any_cast<const LazyCallGraph::SCC *>(IR));
108d409305fSDimitry Andric   else if (any_isa<const Loop *>(IR))
109d409305fSDimitry Andric     runAfterPass(any_cast<const Loop *>(IR));
110d409305fSDimitry Andric   else
111d409305fSDimitry Andric     llvm_unreachable("Unknown IR unit");
112d409305fSDimitry Andric }
113d409305fSDimitry Andric 
114d409305fSDimitry Andric void PseudoProbeVerifier::runAfterPass(const Module *M) {
115d409305fSDimitry Andric   for (const Function &F : *M)
116d409305fSDimitry Andric     runAfterPass(&F);
117d409305fSDimitry Andric }
118d409305fSDimitry Andric 
119d409305fSDimitry Andric void PseudoProbeVerifier::runAfterPass(const LazyCallGraph::SCC *C) {
120d409305fSDimitry Andric   for (const LazyCallGraph::Node &N : *C)
121d409305fSDimitry Andric     runAfterPass(&N.getFunction());
122d409305fSDimitry Andric }
123d409305fSDimitry Andric 
124d409305fSDimitry Andric void PseudoProbeVerifier::runAfterPass(const Function *F) {
125d409305fSDimitry Andric   if (!shouldVerifyFunction(F))
126d409305fSDimitry Andric     return;
127d409305fSDimitry Andric   ProbeFactorMap ProbeFactors;
128d409305fSDimitry Andric   for (const auto &BB : *F)
129d409305fSDimitry Andric     collectProbeFactors(&BB, ProbeFactors);
130d409305fSDimitry Andric   verifyProbeFactors(F, ProbeFactors);
131d409305fSDimitry Andric }
132d409305fSDimitry Andric 
133d409305fSDimitry Andric void PseudoProbeVerifier::runAfterPass(const Loop *L) {
134d409305fSDimitry Andric   const Function *F = L->getHeader()->getParent();
135d409305fSDimitry Andric   runAfterPass(F);
136d409305fSDimitry Andric }
137d409305fSDimitry Andric 
138d409305fSDimitry Andric void PseudoProbeVerifier::collectProbeFactors(const BasicBlock *Block,
139d409305fSDimitry Andric                                               ProbeFactorMap &ProbeFactors) {
140d409305fSDimitry Andric   for (const auto &I : *Block) {
141*fe6060f1SDimitry Andric     if (Optional<PseudoProbe> Probe = extractProbe(I)) {
142*fe6060f1SDimitry Andric       uint64_t Hash = computeCallStackHash(I);
143*fe6060f1SDimitry Andric       ProbeFactors[{Probe->Id, Hash}] += Probe->Factor;
144*fe6060f1SDimitry Andric     }
145d409305fSDimitry Andric   }
146d409305fSDimitry Andric }
147d409305fSDimitry Andric 
148d409305fSDimitry Andric void PseudoProbeVerifier::verifyProbeFactors(
149d409305fSDimitry Andric     const Function *F, const ProbeFactorMap &ProbeFactors) {
150d409305fSDimitry Andric   bool BannerPrinted = false;
151d409305fSDimitry Andric   auto &PrevProbeFactors = FunctionProbeFactors[F->getName()];
152d409305fSDimitry Andric   for (const auto &I : ProbeFactors) {
153d409305fSDimitry Andric     float CurProbeFactor = I.second;
154d409305fSDimitry Andric     if (PrevProbeFactors.count(I.first)) {
155d409305fSDimitry Andric       float PrevProbeFactor = PrevProbeFactors[I.first];
156d409305fSDimitry Andric       if (std::abs(CurProbeFactor - PrevProbeFactor) >
157d409305fSDimitry Andric           DistributionFactorVariance) {
158d409305fSDimitry Andric         if (!BannerPrinted) {
159d409305fSDimitry Andric           dbgs() << "Function " << F->getName() << ":\n";
160d409305fSDimitry Andric           BannerPrinted = true;
161d409305fSDimitry Andric         }
162*fe6060f1SDimitry Andric         dbgs() << "Probe " << I.first.first << "\tprevious factor "
163d409305fSDimitry Andric                << format("%0.2f", PrevProbeFactor) << "\tcurrent factor "
164d409305fSDimitry Andric                << format("%0.2f", CurProbeFactor) << "\n";
165d409305fSDimitry Andric       }
166d409305fSDimitry Andric     }
167d409305fSDimitry Andric 
168d409305fSDimitry Andric     // Update
169d409305fSDimitry Andric     PrevProbeFactors[I.first] = I.second;
170d409305fSDimitry Andric   }
171d409305fSDimitry Andric }
172d409305fSDimitry Andric 
173e8d8bef9SDimitry Andric PseudoProbeManager::PseudoProbeManager(const Module &M) {
174e8d8bef9SDimitry Andric   if (NamedMDNode *FuncInfo = M.getNamedMetadata(PseudoProbeDescMetadataName)) {
175e8d8bef9SDimitry Andric     for (const auto *Operand : FuncInfo->operands()) {
176e8d8bef9SDimitry Andric       const auto *MD = cast<MDNode>(Operand);
177e8d8bef9SDimitry Andric       auto GUID =
178e8d8bef9SDimitry Andric           mdconst::dyn_extract<ConstantInt>(MD->getOperand(0))->getZExtValue();
179e8d8bef9SDimitry Andric       auto Hash =
180e8d8bef9SDimitry Andric           mdconst::dyn_extract<ConstantInt>(MD->getOperand(1))->getZExtValue();
181e8d8bef9SDimitry Andric       GUIDToProbeDescMap.try_emplace(GUID, PseudoProbeDescriptor(GUID, Hash));
182e8d8bef9SDimitry Andric     }
183e8d8bef9SDimitry Andric   }
184e8d8bef9SDimitry Andric }
185e8d8bef9SDimitry Andric 
186e8d8bef9SDimitry Andric const PseudoProbeDescriptor *
187e8d8bef9SDimitry Andric PseudoProbeManager::getDesc(const Function &F) const {
188e8d8bef9SDimitry Andric   auto I = GUIDToProbeDescMap.find(
189e8d8bef9SDimitry Andric       Function::getGUID(FunctionSamples::getCanonicalFnName(F)));
190e8d8bef9SDimitry Andric   return I == GUIDToProbeDescMap.end() ? nullptr : &I->second;
191e8d8bef9SDimitry Andric }
192e8d8bef9SDimitry Andric 
193e8d8bef9SDimitry Andric bool PseudoProbeManager::moduleIsProbed(const Module &M) const {
194e8d8bef9SDimitry Andric   return M.getNamedMetadata(PseudoProbeDescMetadataName);
195e8d8bef9SDimitry Andric }
196e8d8bef9SDimitry Andric 
197e8d8bef9SDimitry Andric bool PseudoProbeManager::profileIsValid(const Function &F,
198e8d8bef9SDimitry Andric                                         const FunctionSamples &Samples) const {
199e8d8bef9SDimitry Andric   const auto *Desc = getDesc(F);
200e8d8bef9SDimitry Andric   if (!Desc) {
201e8d8bef9SDimitry Andric     LLVM_DEBUG(dbgs() << "Probe descriptor missing for Function " << F.getName()
202e8d8bef9SDimitry Andric                       << "\n");
203e8d8bef9SDimitry Andric     return false;
204e8d8bef9SDimitry Andric   } else {
205e8d8bef9SDimitry Andric     if (Desc->getFunctionHash() != Samples.getFunctionHash()) {
206e8d8bef9SDimitry Andric       LLVM_DEBUG(dbgs() << "Hash mismatch for Function " << F.getName()
207e8d8bef9SDimitry Andric                         << "\n");
208e8d8bef9SDimitry Andric       return false;
209e8d8bef9SDimitry Andric     }
210e8d8bef9SDimitry Andric   }
211e8d8bef9SDimitry Andric   return true;
212e8d8bef9SDimitry Andric }
213e8d8bef9SDimitry Andric 
214e8d8bef9SDimitry Andric SampleProfileProber::SampleProfileProber(Function &Func,
215e8d8bef9SDimitry Andric                                          const std::string &CurModuleUniqueId)
216e8d8bef9SDimitry Andric     : F(&Func), CurModuleUniqueId(CurModuleUniqueId) {
217e8d8bef9SDimitry Andric   BlockProbeIds.clear();
218e8d8bef9SDimitry Andric   CallProbeIds.clear();
219e8d8bef9SDimitry Andric   LastProbeId = (uint32_t)PseudoProbeReservedId::Last;
220e8d8bef9SDimitry Andric   computeProbeIdForBlocks();
221e8d8bef9SDimitry Andric   computeProbeIdForCallsites();
222e8d8bef9SDimitry Andric   computeCFGHash();
223e8d8bef9SDimitry Andric }
224e8d8bef9SDimitry Andric 
225e8d8bef9SDimitry Andric // Compute Hash value for the CFG: the lower 32 bits are CRC32 of the index
226e8d8bef9SDimitry Andric // value of each BB in the CFG. The higher 32 bits record the number of edges
227e8d8bef9SDimitry Andric // preceded by the number of indirect calls.
228e8d8bef9SDimitry Andric // This is derived from FuncPGOInstrumentation<Edge, BBInfo>::computeCFGHash().
229e8d8bef9SDimitry Andric void SampleProfileProber::computeCFGHash() {
230e8d8bef9SDimitry Andric   std::vector<uint8_t> Indexes;
231e8d8bef9SDimitry Andric   JamCRC JC;
232e8d8bef9SDimitry Andric   for (auto &BB : *F) {
233e8d8bef9SDimitry Andric     auto *TI = BB.getTerminator();
234e8d8bef9SDimitry Andric     for (unsigned I = 0, E = TI->getNumSuccessors(); I != E; ++I) {
235e8d8bef9SDimitry Andric       auto *Succ = TI->getSuccessor(I);
236e8d8bef9SDimitry Andric       auto Index = getBlockId(Succ);
237e8d8bef9SDimitry Andric       for (int J = 0; J < 4; J++)
238e8d8bef9SDimitry Andric         Indexes.push_back((uint8_t)(Index >> (J * 8)));
239e8d8bef9SDimitry Andric     }
240e8d8bef9SDimitry Andric   }
241e8d8bef9SDimitry Andric 
242e8d8bef9SDimitry Andric   JC.update(Indexes);
243e8d8bef9SDimitry Andric 
244e8d8bef9SDimitry Andric   FunctionHash = (uint64_t)CallProbeIds.size() << 48 |
245e8d8bef9SDimitry Andric                  (uint64_t)Indexes.size() << 32 | JC.getCRC();
246e8d8bef9SDimitry Andric   // Reserve bit 60-63 for other information purpose.
247e8d8bef9SDimitry Andric   FunctionHash &= 0x0FFFFFFFFFFFFFFF;
248e8d8bef9SDimitry Andric   assert(FunctionHash && "Function checksum should not be zero");
249e8d8bef9SDimitry Andric   LLVM_DEBUG(dbgs() << "\nFunction Hash Computation for " << F->getName()
250e8d8bef9SDimitry Andric                     << ":\n"
251e8d8bef9SDimitry Andric                     << " CRC = " << JC.getCRC() << ", Edges = "
252e8d8bef9SDimitry Andric                     << Indexes.size() << ", ICSites = " << CallProbeIds.size()
253e8d8bef9SDimitry Andric                     << ", Hash = " << FunctionHash << "\n");
254e8d8bef9SDimitry Andric }
255e8d8bef9SDimitry Andric 
256e8d8bef9SDimitry Andric void SampleProfileProber::computeProbeIdForBlocks() {
257e8d8bef9SDimitry Andric   for (auto &BB : *F) {
258e8d8bef9SDimitry Andric     BlockProbeIds[&BB] = ++LastProbeId;
259e8d8bef9SDimitry Andric   }
260e8d8bef9SDimitry Andric }
261e8d8bef9SDimitry Andric 
262e8d8bef9SDimitry Andric void SampleProfileProber::computeProbeIdForCallsites() {
263e8d8bef9SDimitry Andric   for (auto &BB : *F) {
264e8d8bef9SDimitry Andric     for (auto &I : BB) {
265e8d8bef9SDimitry Andric       if (!isa<CallBase>(I))
266e8d8bef9SDimitry Andric         continue;
267e8d8bef9SDimitry Andric       if (isa<IntrinsicInst>(&I))
268e8d8bef9SDimitry Andric         continue;
269e8d8bef9SDimitry Andric       CallProbeIds[&I] = ++LastProbeId;
270e8d8bef9SDimitry Andric     }
271e8d8bef9SDimitry Andric   }
272e8d8bef9SDimitry Andric }
273e8d8bef9SDimitry Andric 
274e8d8bef9SDimitry Andric uint32_t SampleProfileProber::getBlockId(const BasicBlock *BB) const {
275e8d8bef9SDimitry Andric   auto I = BlockProbeIds.find(const_cast<BasicBlock *>(BB));
276e8d8bef9SDimitry Andric   return I == BlockProbeIds.end() ? 0 : I->second;
277e8d8bef9SDimitry Andric }
278e8d8bef9SDimitry Andric 
279e8d8bef9SDimitry Andric uint32_t SampleProfileProber::getCallsiteId(const Instruction *Call) const {
280e8d8bef9SDimitry Andric   auto Iter = CallProbeIds.find(const_cast<Instruction *>(Call));
281e8d8bef9SDimitry Andric   return Iter == CallProbeIds.end() ? 0 : Iter->second;
282e8d8bef9SDimitry Andric }
283e8d8bef9SDimitry Andric 
284e8d8bef9SDimitry Andric void SampleProfileProber::instrumentOneFunc(Function &F, TargetMachine *TM) {
285e8d8bef9SDimitry Andric   Module *M = F.getParent();
286e8d8bef9SDimitry Andric   MDBuilder MDB(F.getContext());
287e8d8bef9SDimitry Andric   // Compute a GUID without considering the function's linkage type. This is
288e8d8bef9SDimitry Andric   // fine since function name is the only key in the profile database.
289e8d8bef9SDimitry Andric   uint64_t Guid = Function::getGUID(F.getName());
290e8d8bef9SDimitry Andric 
291e8d8bef9SDimitry Andric   // Assign an artificial debug line to a probe that doesn't come with a real
292e8d8bef9SDimitry Andric   // line. A probe not having a debug line will get an incomplete inline
293e8d8bef9SDimitry Andric   // context. This will cause samples collected on the probe to be counted
294e8d8bef9SDimitry Andric   // into the base profile instead of a context profile. The line number
295e8d8bef9SDimitry Andric   // itself is not important though.
296e8d8bef9SDimitry Andric   auto AssignDebugLoc = [&](Instruction *I) {
297e8d8bef9SDimitry Andric     assert((isa<PseudoProbeInst>(I) || isa<CallBase>(I)) &&
298e8d8bef9SDimitry Andric            "Expecting pseudo probe or call instructions");
299e8d8bef9SDimitry Andric     if (!I->getDebugLoc()) {
300e8d8bef9SDimitry Andric       if (auto *SP = F.getSubprogram()) {
301e8d8bef9SDimitry Andric         auto DIL = DILocation::get(SP->getContext(), 0, 0, SP);
302e8d8bef9SDimitry Andric         I->setDebugLoc(DIL);
303e8d8bef9SDimitry Andric         ArtificialDbgLine++;
304e8d8bef9SDimitry Andric         LLVM_DEBUG({
305e8d8bef9SDimitry Andric           dbgs() << "\nIn Function " << F.getName()
306e8d8bef9SDimitry Andric                  << " Probe gets an artificial debug line\n";
307e8d8bef9SDimitry Andric           I->dump();
308e8d8bef9SDimitry Andric         });
309e8d8bef9SDimitry Andric       }
310e8d8bef9SDimitry Andric     }
311e8d8bef9SDimitry Andric   };
312e8d8bef9SDimitry Andric 
313e8d8bef9SDimitry Andric   // Probe basic blocks.
314e8d8bef9SDimitry Andric   for (auto &I : BlockProbeIds) {
315e8d8bef9SDimitry Andric     BasicBlock *BB = I.first;
316e8d8bef9SDimitry Andric     uint32_t Index = I.second;
317e8d8bef9SDimitry Andric     // Insert a probe before an instruction with a valid debug line number which
318e8d8bef9SDimitry Andric     // will be assigned to the probe. The line number will be used later to
319e8d8bef9SDimitry Andric     // model the inline context when the probe is inlined into other functions.
320e8d8bef9SDimitry Andric     // Debug instructions, phi nodes and lifetime markers do not have an valid
321e8d8bef9SDimitry Andric     // line number. Real instructions generated by optimizations may not come
322e8d8bef9SDimitry Andric     // with a line number either.
323e8d8bef9SDimitry Andric     auto HasValidDbgLine = [](Instruction *J) {
324e8d8bef9SDimitry Andric       return !isa<PHINode>(J) && !isa<DbgInfoIntrinsic>(J) &&
325e8d8bef9SDimitry Andric              !J->isLifetimeStartOrEnd() && J->getDebugLoc();
326e8d8bef9SDimitry Andric     };
327e8d8bef9SDimitry Andric 
328e8d8bef9SDimitry Andric     Instruction *J = &*BB->getFirstInsertionPt();
329e8d8bef9SDimitry Andric     while (J != BB->getTerminator() && !HasValidDbgLine(J)) {
330e8d8bef9SDimitry Andric       J = J->getNextNode();
331e8d8bef9SDimitry Andric     }
332e8d8bef9SDimitry Andric 
333e8d8bef9SDimitry Andric     IRBuilder<> Builder(J);
334e8d8bef9SDimitry Andric     assert(Builder.GetInsertPoint() != BB->end() &&
335e8d8bef9SDimitry Andric            "Cannot get the probing point");
336e8d8bef9SDimitry Andric     Function *ProbeFn =
337e8d8bef9SDimitry Andric         llvm::Intrinsic::getDeclaration(M, Intrinsic::pseudoprobe);
338e8d8bef9SDimitry Andric     Value *Args[] = {Builder.getInt64(Guid), Builder.getInt64(Index),
339d409305fSDimitry Andric                      Builder.getInt32(0),
340d409305fSDimitry Andric                      Builder.getInt64(PseudoProbeFullDistributionFactor)};
341e8d8bef9SDimitry Andric     auto *Probe = Builder.CreateCall(ProbeFn, Args);
342e8d8bef9SDimitry Andric     AssignDebugLoc(Probe);
343e8d8bef9SDimitry Andric   }
344e8d8bef9SDimitry Andric 
345e8d8bef9SDimitry Andric   // Probe both direct calls and indirect calls. Direct calls are probed so that
346e8d8bef9SDimitry Andric   // their probe ID can be used as an call site identifier to represent a
347e8d8bef9SDimitry Andric   // calling context.
348e8d8bef9SDimitry Andric   for (auto &I : CallProbeIds) {
349e8d8bef9SDimitry Andric     auto *Call = I.first;
350e8d8bef9SDimitry Andric     uint32_t Index = I.second;
351e8d8bef9SDimitry Andric     uint32_t Type = cast<CallBase>(Call)->getCalledFunction()
352e8d8bef9SDimitry Andric                         ? (uint32_t)PseudoProbeType::DirectCall
353e8d8bef9SDimitry Andric                         : (uint32_t)PseudoProbeType::IndirectCall;
354e8d8bef9SDimitry Andric     AssignDebugLoc(Call);
355e8d8bef9SDimitry Andric     // Levarge the 32-bit discriminator field of debug data to store the ID and
356e8d8bef9SDimitry Andric     // type of a callsite probe. This gets rid of the dependency on plumbing a
357e8d8bef9SDimitry Andric     // customized metadata through the codegen pipeline.
358d409305fSDimitry Andric     uint32_t V = PseudoProbeDwarfDiscriminator::packProbeData(
359d409305fSDimitry Andric         Index, Type, 0, PseudoProbeDwarfDiscriminator::FullDistributionFactor);
360e8d8bef9SDimitry Andric     if (auto DIL = Call->getDebugLoc()) {
361e8d8bef9SDimitry Andric       DIL = DIL->cloneWithDiscriminator(V);
362e8d8bef9SDimitry Andric       Call->setDebugLoc(DIL);
363e8d8bef9SDimitry Andric     }
364e8d8bef9SDimitry Andric   }
365e8d8bef9SDimitry Andric 
366e8d8bef9SDimitry Andric   // Create module-level metadata that contains function info necessary to
367e8d8bef9SDimitry Andric   // synthesize probe-based sample counts,  which are
368e8d8bef9SDimitry Andric   // - FunctionGUID
369e8d8bef9SDimitry Andric   // - FunctionHash.
370e8d8bef9SDimitry Andric   // - FunctionName
371e8d8bef9SDimitry Andric   auto Hash = getFunctionHash();
372e8d8bef9SDimitry Andric   auto *MD = MDB.createPseudoProbeDesc(Guid, Hash, &F);
373e8d8bef9SDimitry Andric   auto *NMD = M->getNamedMetadata(PseudoProbeDescMetadataName);
374e8d8bef9SDimitry Andric   assert(NMD && "llvm.pseudo_probe_desc should be pre-created");
375e8d8bef9SDimitry Andric   NMD->addOperand(MD);
376e8d8bef9SDimitry Andric 
377e8d8bef9SDimitry Andric   // Preserve a comdat group to hold all probes materialized later. This
378e8d8bef9SDimitry Andric   // allows that when the function is considered dead and removed, the
379e8d8bef9SDimitry Andric   // materialized probes are disposed too.
380e8d8bef9SDimitry Andric   // Imported functions are defined in another module. They do not need
381e8d8bef9SDimitry Andric   // the following handling since same care will be taken for them in their
382e8d8bef9SDimitry Andric   // original module. The pseudo probes inserted into an imported functions
383e8d8bef9SDimitry Andric   // above will naturally not be emitted since the imported function is free
384e8d8bef9SDimitry Andric   // from object emission. However they will be emitted together with the
385e8d8bef9SDimitry Andric   // inliner functions that the imported function is inlined into. We are not
386e8d8bef9SDimitry Andric   // creating a comdat group for an import function since it's useless anyway.
387e8d8bef9SDimitry Andric   if (!F.isDeclarationForLinker()) {
388e8d8bef9SDimitry Andric     if (TM) {
389e8d8bef9SDimitry Andric       auto Triple = TM->getTargetTriple();
390*fe6060f1SDimitry Andric       if (Triple.supportsCOMDAT() && TM->getFunctionSections())
391*fe6060f1SDimitry Andric         getOrCreateFunctionComdat(F, Triple);
392e8d8bef9SDimitry Andric     }
393e8d8bef9SDimitry Andric   }
394e8d8bef9SDimitry Andric }
395e8d8bef9SDimitry Andric 
396e8d8bef9SDimitry Andric PreservedAnalyses SampleProfileProbePass::run(Module &M,
397e8d8bef9SDimitry Andric                                               ModuleAnalysisManager &AM) {
398e8d8bef9SDimitry Andric   auto ModuleId = getUniqueModuleId(&M);
399e8d8bef9SDimitry Andric   // Create the pseudo probe desc metadata beforehand.
400e8d8bef9SDimitry Andric   // Note that modules with only data but no functions will require this to
401e8d8bef9SDimitry Andric   // be set up so that they will be known as probed later.
402e8d8bef9SDimitry Andric   M.getOrInsertNamedMetadata(PseudoProbeDescMetadataName);
403e8d8bef9SDimitry Andric 
404e8d8bef9SDimitry Andric   for (auto &F : M) {
405e8d8bef9SDimitry Andric     if (F.isDeclaration())
406e8d8bef9SDimitry Andric       continue;
407e8d8bef9SDimitry Andric     SampleProfileProber ProbeManager(F, ModuleId);
408e8d8bef9SDimitry Andric     ProbeManager.instrumentOneFunc(F, TM);
409e8d8bef9SDimitry Andric   }
410e8d8bef9SDimitry Andric 
411e8d8bef9SDimitry Andric   return PreservedAnalyses::none();
412e8d8bef9SDimitry Andric }
413d409305fSDimitry Andric 
414d409305fSDimitry Andric void PseudoProbeUpdatePass::runOnFunction(Function &F,
415d409305fSDimitry Andric                                           FunctionAnalysisManager &FAM) {
416d409305fSDimitry Andric   BlockFrequencyInfo &BFI = FAM.getResult<BlockFrequencyAnalysis>(F);
417d409305fSDimitry Andric   auto BBProfileCount = [&BFI](BasicBlock *BB) {
418d409305fSDimitry Andric     return BFI.getBlockProfileCount(BB)
419d409305fSDimitry Andric                ? BFI.getBlockProfileCount(BB).getValue()
420d409305fSDimitry Andric                : 0;
421d409305fSDimitry Andric   };
422d409305fSDimitry Andric 
423d409305fSDimitry Andric   // Collect the sum of execution weight for each probe.
424d409305fSDimitry Andric   ProbeFactorMap ProbeFactors;
425d409305fSDimitry Andric   for (auto &Block : F) {
426d409305fSDimitry Andric     for (auto &I : Block) {
427*fe6060f1SDimitry Andric       if (Optional<PseudoProbe> Probe = extractProbe(I)) {
428*fe6060f1SDimitry Andric         uint64_t Hash = computeCallStackHash(I);
429*fe6060f1SDimitry Andric         ProbeFactors[{Probe->Id, Hash}] += BBProfileCount(&Block);
430*fe6060f1SDimitry Andric       }
431d409305fSDimitry Andric     }
432d409305fSDimitry Andric   }
433d409305fSDimitry Andric 
434d409305fSDimitry Andric   // Fix up over-counted probes.
435d409305fSDimitry Andric   for (auto &Block : F) {
436d409305fSDimitry Andric     for (auto &I : Block) {
437d409305fSDimitry Andric       if (Optional<PseudoProbe> Probe = extractProbe(I)) {
438*fe6060f1SDimitry Andric         uint64_t Hash = computeCallStackHash(I);
439*fe6060f1SDimitry Andric         float Sum = ProbeFactors[{Probe->Id, Hash}];
440d409305fSDimitry Andric         if (Sum != 0)
441d409305fSDimitry Andric           setProbeDistributionFactor(I, BBProfileCount(&Block) / Sum);
442d409305fSDimitry Andric       }
443d409305fSDimitry Andric     }
444d409305fSDimitry Andric   }
445d409305fSDimitry Andric }
446d409305fSDimitry Andric 
447d409305fSDimitry Andric PreservedAnalyses PseudoProbeUpdatePass::run(Module &M,
448d409305fSDimitry Andric                                              ModuleAnalysisManager &AM) {
449d409305fSDimitry Andric   if (UpdatePseudoProbe) {
450d409305fSDimitry Andric     for (auto &F : M) {
451d409305fSDimitry Andric       if (F.isDeclaration())
452d409305fSDimitry Andric         continue;
453d409305fSDimitry Andric       FunctionAnalysisManager &FAM =
454d409305fSDimitry Andric           AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
455d409305fSDimitry Andric       runOnFunction(F, FAM);
456d409305fSDimitry Andric     }
457d409305fSDimitry Andric   }
458d409305fSDimitry Andric   return PreservedAnalyses::none();
459d409305fSDimitry Andric }
460