1 //===- SampleProfile.cpp - Incorporate sample profiles into the IR --------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the SampleProfileLoader transformation. This pass
11 // reads a profile file generated by a sampling profiler (e.g. Linux Perf -
12 // http://perf.wiki.kernel.org/) and generates IR metadata to reflect the
13 // profile information in the given profile.
15 // This pass generates branch weight annotations on the IR:
17 // - prof: Represents branch weights. This annotation is added to branches
18 // to indicate the weights of each edge coming out of the branch.
19 // The weight of each edge is the weight of the target block for
20 // that edge. The weight of a block B is computed as the maximum
21 // number of samples found in B.
23 //===----------------------------------------------------------------------===//
25 #include "llvm/ADT/DenseMap.h"
26 #include "llvm/ADT/SmallPtrSet.h"
27 #include "llvm/ADT/SmallSet.h"
28 #include "llvm/ADT/StringRef.h"
29 #include "llvm/Analysis/LoopInfo.h"
30 #include "llvm/Analysis/PostDominators.h"
31 #include "llvm/IR/Constants.h"
32 #include "llvm/IR/DebugInfo.h"
33 #include "llvm/IR/DiagnosticInfo.h"
34 #include "llvm/IR/Dominators.h"
35 #include "llvm/IR/Function.h"
36 #include "llvm/IR/InstIterator.h"
37 #include "llvm/IR/Instructions.h"
38 #include "llvm/IR/LLVMContext.h"
39 #include "llvm/IR/MDBuilder.h"
40 #include "llvm/IR/Metadata.h"
41 #include "llvm/IR/Module.h"
42 #include "llvm/Pass.h"
43 #include "llvm/ProfileData/SampleProfReader.h"
44 #include "llvm/Support/CommandLine.h"
45 #include "llvm/Support/Debug.h"
46 #include "llvm/Support/ErrorOr.h"
47 #include "llvm/Support/raw_ostream.h"
48 #include "llvm/Transforms/IPO.h"
49 #include "llvm/Transforms/Utils/Cloning.h"
53 using namespace sampleprof;
55 #define DEBUG_TYPE "sample-profile"
57 // Command line option to specify the file to read samples from. This is
58 // mainly used for debugging.
59 static cl::opt<std::string> SampleProfileFile(
60 "sample-profile-file", cl::init(""), cl::value_desc("filename"),
61 cl::desc("Profile file loaded by -sample-profile"), cl::Hidden);
62 static cl::opt<unsigned> SampleProfileMaxPropagateIterations(
63 "sample-profile-max-propagate-iterations", cl::init(100),
64 cl::desc("Maximum number of iterations to go through when propagating "
65 "sample block/edge weights through the CFG."));
66 static cl::opt<unsigned> SampleProfileRecordCoverage(
67 "sample-profile-check-record-coverage", cl::init(0), cl::value_desc("N"),
68 cl::desc("Emit a warning if less than N% of records in the input profile "
69 "are matched to the IR."));
70 static cl::opt<unsigned> SampleProfileSampleCoverage(
71 "sample-profile-check-sample-coverage", cl::init(0), cl::value_desc("N"),
72 cl::desc("Emit a warning if less than N% of samples in the input profile "
73 "are matched to the IR."));
74 static cl::opt<double> SampleProfileHotThreshold(
75 "sample-profile-inline-hot-threshold", cl::init(0.1), cl::value_desc("N"),
76 cl::desc("Inlined functions that account for more than N% of all samples "
77 "collected in the parent function, will be inlined again."));
80 typedef DenseMap<const BasicBlock *, uint64_t> BlockWeightMap;
81 typedef DenseMap<const BasicBlock *, const BasicBlock *> EquivalenceClassMap;
82 typedef std::pair<const BasicBlock *, const BasicBlock *> Edge;
83 typedef DenseMap<Edge, uint64_t> EdgeWeightMap;
84 typedef DenseMap<const BasicBlock *, SmallVector<const BasicBlock *, 8>>
87 /// \brief Sample profile pass.
89 /// This pass reads profile data from the file specified by
90 /// -sample-profile-file and annotates every affected function with the
91 /// profile information found in that file.
92 class SampleProfileLoader : public ModulePass {
94 // Class identification, replacement for typeinfo
97 SampleProfileLoader(StringRef Name = SampleProfileFile)
98 : ModulePass(ID), DT(nullptr), PDT(nullptr), LI(nullptr), Reader(),
99 Samples(nullptr), Filename(Name), ProfileIsValid(false) {
100 initializeSampleProfileLoaderPass(*PassRegistry::getPassRegistry());
103 bool doInitialization(Module &M) override;
105 void dump() { Reader->dump(); }
107 const char *getPassName() const override { return "Sample profile pass"; }
109 bool runOnModule(Module &M) override;
111 void getAnalysisUsage(AnalysisUsage &AU) const override {
112 AU.setPreservesCFG();
116 bool runOnFunction(Function &F);
117 unsigned getFunctionLoc(Function &F);
118 bool emitAnnotations(Function &F);
119 ErrorOr<uint64_t> getInstWeight(const Instruction &I) const;
120 ErrorOr<uint64_t> getBlockWeight(const BasicBlock *BB) const;
121 const FunctionSamples *findCalleeFunctionSamples(const CallInst &I) const;
122 const FunctionSamples *findFunctionSamples(const Instruction &I) const;
123 bool inlineHotFunctions(Function &F);
124 void printEdgeWeight(raw_ostream &OS, Edge E);
125 void printBlockWeight(raw_ostream &OS, const BasicBlock *BB) const;
126 void printBlockEquivalence(raw_ostream &OS, const BasicBlock *BB);
127 bool computeBlockWeights(Function &F);
128 void findEquivalenceClasses(Function &F);
129 void findEquivalencesFor(BasicBlock *BB1,
130 SmallVector<BasicBlock *, 8> Descendants,
131 DominatorTreeBase<BasicBlock> *DomTree);
132 void propagateWeights(Function &F);
133 uint64_t visitEdge(Edge E, unsigned *NumUnknownEdges, Edge *UnknownEdge);
134 void buildEdges(Function &F);
135 bool propagateThroughEdges(Function &F);
136 void computeDominanceAndLoopInfo(Function &F);
137 unsigned getOffset(unsigned L, unsigned H) const;
138 void clearFunctionData();
140 /// \brief Map basic blocks to their computed weights.
142 /// The weight of a basic block is defined to be the maximum
143 /// of all the instruction weights in that block.
144 BlockWeightMap BlockWeights;
146 /// \brief Map edges to their computed weights.
148 /// Edge weights are computed by propagating basic block weights in
149 /// SampleProfile::propagateWeights.
150 EdgeWeightMap EdgeWeights;
152 /// \brief Set of visited blocks during propagation.
153 SmallPtrSet<const BasicBlock *, 128> VisitedBlocks;
155 /// \brief Set of visited edges during propagation.
156 SmallSet<Edge, 128> VisitedEdges;
158 /// \brief Equivalence classes for block weights.
160 /// Two blocks BB1 and BB2 are in the same equivalence class if they
161 /// dominate and post-dominate each other, and they are in the same loop
162 /// nest. When this happens, the two blocks are guaranteed to execute
163 /// the same number of times.
164 EquivalenceClassMap EquivalenceClass;
166 /// \brief Dominance, post-dominance and loop information.
167 std::unique_ptr<DominatorTree> DT;
168 std::unique_ptr<DominatorTreeBase<BasicBlock>> PDT;
169 std::unique_ptr<LoopInfo> LI;
171 /// \brief Predecessors for each basic block in the CFG.
172 BlockEdgeMap Predecessors;
174 /// \brief Successors for each basic block in the CFG.
175 BlockEdgeMap Successors;
177 /// \brief Profile reader object.
178 std::unique_ptr<SampleProfileReader> Reader;
180 /// \brief Samples collected for the body of this function.
181 FunctionSamples *Samples;
183 /// \brief Name of the profile file to load.
186 /// \brief Flag indicating whether the profile input loaded successfully.
190 class SampleCoverageTracker {
192 SampleCoverageTracker() : SampleCoverage(), TotalUsedSamples(0) {}
194 bool markSamplesUsed(const FunctionSamples *FS, uint32_t LineOffset,
195 uint32_t Discriminator, uint64_t Samples);
196 unsigned computeCoverage(unsigned Used, unsigned Total) const;
197 unsigned countUsedRecords(const FunctionSamples *FS) const;
198 unsigned countBodyRecords(const FunctionSamples *FS) const;
199 uint64_t getTotalUsedSamples() const { return TotalUsedSamples; }
200 uint64_t countBodySamples(const FunctionSamples *FS) const;
202 SampleCoverage.clear();
203 TotalUsedSamples = 0;
207 typedef DenseMap<LineLocation, unsigned> BodySampleCoverageMap;
208 typedef DenseMap<const FunctionSamples *, BodySampleCoverageMap>
209 FunctionSamplesCoverageMap;
211 /// Coverage map for sampling records.
213 /// This map keeps a record of sampling records that have been matched to
214 /// an IR instruction. This is used to detect some form of staleness in
215 /// profiles (see flag -sample-profile-check-coverage).
217 /// Each entry in the map corresponds to a FunctionSamples instance. This is
218 /// another map that counts how many times the sample record at the
219 /// given location has been used.
220 FunctionSamplesCoverageMap SampleCoverage;
222 /// Number of samples used from the profile.
224 /// When a sampling record is used for the first time, the samples from
225 /// that record are added to this accumulator. Coverage is later computed
226 /// based on the total number of samples available in this function and
229 /// Note that this accumulator tracks samples used from a single function
230 /// and all the inlined callsites. Strictly, we should have a map of counters
231 /// keyed by FunctionSamples pointers, but these stats are cleared after
232 /// every function, so we just need to keep a single counter.
233 uint64_t TotalUsedSamples;
236 SampleCoverageTracker CoverageTracker;
238 /// Return true if the given callsite is hot wrt to its caller.
240 /// Functions that were inlined in the original binary will be represented
241 /// in the inline stack in the sample profile. If the profile shows that
242 /// the original inline decision was "good" (i.e., the callsite is executed
243 /// frequently), then we will recreate the inline decision and apply the
244 /// profile from the inlined callsite.
246 /// To decide whether an inlined callsite is hot, we compute the fraction
247 /// of samples used by the callsite with respect to the total number of samples
248 /// collected in the caller.
250 /// If that fraction is larger than the default given by
251 /// SampleProfileHotThreshold, the callsite will be inlined again.
252 bool callsiteIsHot(const FunctionSamples *CallerFS,
253 const FunctionSamples *CallsiteFS) {
255 return false; // The callsite was not inlined in the original binary.
257 uint64_t ParentTotalSamples = CallerFS->getTotalSamples();
258 if (ParentTotalSamples == 0)
259 return false; // Avoid division by zero.
261 uint64_t CallsiteTotalSamples = CallsiteFS->getTotalSamples();
262 if (CallsiteTotalSamples == 0)
263 return false; // Callsite is trivially cold.
265 double PercentSamples =
266 (double)CallsiteTotalSamples / (double)ParentTotalSamples * 100.0;
267 return PercentSamples >= SampleProfileHotThreshold;
272 /// Mark as used the sample record for the given function samples at
273 /// (LineOffset, Discriminator).
275 /// \returns true if this is the first time we mark the given record.
276 bool SampleCoverageTracker::markSamplesUsed(const FunctionSamples *FS,
278 uint32_t Discriminator,
280 LineLocation Loc(LineOffset, Discriminator);
281 unsigned &Count = SampleCoverage[FS][Loc];
282 bool FirstTime = (++Count == 1);
284 TotalUsedSamples += Samples;
288 /// Return the number of sample records that were applied from this profile.
290 /// This count does not include records from cold inlined callsites.
292 SampleCoverageTracker::countUsedRecords(const FunctionSamples *FS) const {
293 auto I = SampleCoverage.find(FS);
295 // The size of the coverage map for FS represents the number of records
296 // that were marked used at least once.
297 unsigned Count = (I != SampleCoverage.end()) ? I->second.size() : 0;
299 // If there are inlined callsites in this function, count the samples found
300 // in the respective bodies. However, do not bother counting callees with 0
301 // total samples, these are callees that were never invoked at runtime.
302 for (const auto &I : FS->getCallsiteSamples()) {
303 const FunctionSamples *CalleeSamples = &I.second;
304 if (callsiteIsHot(FS, CalleeSamples))
305 Count += countUsedRecords(CalleeSamples);
311 /// Return the number of sample records in the body of this profile.
313 /// This count does not include records from cold inlined callsites.
315 SampleCoverageTracker::countBodyRecords(const FunctionSamples *FS) const {
316 unsigned Count = FS->getBodySamples().size();
318 // Only count records in hot callsites.
319 for (const auto &I : FS->getCallsiteSamples()) {
320 const FunctionSamples *CalleeSamples = &I.second;
321 if (callsiteIsHot(FS, CalleeSamples))
322 Count += countBodyRecords(CalleeSamples);
328 /// Return the number of samples collected in the body of this profile.
330 /// This count does not include samples from cold inlined callsites.
332 SampleCoverageTracker::countBodySamples(const FunctionSamples *FS) const {
334 for (const auto &I : FS->getBodySamples())
335 Total += I.second.getSamples();
337 // Only count samples in hot callsites.
338 for (const auto &I : FS->getCallsiteSamples()) {
339 const FunctionSamples *CalleeSamples = &I.second;
340 if (callsiteIsHot(FS, CalleeSamples))
341 Total += countBodySamples(CalleeSamples);
347 /// Return the fraction of sample records used in this profile.
349 /// The returned value is an unsigned integer in the range 0-100 indicating
350 /// the percentage of sample records that were used while applying this
351 /// profile to the associated function.
352 unsigned SampleCoverageTracker::computeCoverage(unsigned Used,
353 unsigned Total) const {
354 assert(Used <= Total &&
355 "number of used records cannot exceed the total number of records");
356 return Total > 0 ? Used * 100 / Total : 100;
359 /// Clear all the per-function data used to load samples and propagate weights.
360 void SampleProfileLoader::clearFunctionData() {
361 BlockWeights.clear();
363 VisitedBlocks.clear();
364 VisitedEdges.clear();
365 EquivalenceClass.clear();
369 Predecessors.clear();
371 CoverageTracker.clear();
374 /// \brief Returns the offset of lineno \p L to head_lineno \p H
377 /// \param H Header lineno of the function
379 /// \returns offset to the header lineno. 16 bits are used to represent offset.
380 /// We assume that a single function will not exceed 65535 LOC.
381 unsigned SampleProfileLoader::getOffset(unsigned L, unsigned H) const {
382 return (L - H) & 0xffff;
385 /// \brief Print the weight of edge \p E on stream \p OS.
387 /// \param OS Stream to emit the output to.
388 /// \param E Edge to print.
389 void SampleProfileLoader::printEdgeWeight(raw_ostream &OS, Edge E) {
390 OS << "weight[" << E.first->getName() << "->" << E.second->getName()
391 << "]: " << EdgeWeights[E] << "\n";
394 /// \brief Print the equivalence class of block \p BB on stream \p OS.
396 /// \param OS Stream to emit the output to.
397 /// \param BB Block to print.
398 void SampleProfileLoader::printBlockEquivalence(raw_ostream &OS,
399 const BasicBlock *BB) {
400 const BasicBlock *Equiv = EquivalenceClass[BB];
401 OS << "equivalence[" << BB->getName()
402 << "]: " << ((Equiv) ? EquivalenceClass[BB]->getName() : "NONE") << "\n";
405 /// \brief Print the weight of block \p BB on stream \p OS.
407 /// \param OS Stream to emit the output to.
408 /// \param BB Block to print.
409 void SampleProfileLoader::printBlockWeight(raw_ostream &OS,
410 const BasicBlock *BB) const {
411 const auto &I = BlockWeights.find(BB);
412 uint64_t W = (I == BlockWeights.end() ? 0 : I->second);
413 OS << "weight[" << BB->getName() << "]: " << W << "\n";
416 /// \brief Get the weight for an instruction.
418 /// The "weight" of an instruction \p Inst is the number of samples
419 /// collected on that instruction at runtime. To retrieve it, we
420 /// need to compute the line number of \p Inst relative to the start of its
421 /// function. We use HeaderLineno to compute the offset. We then
422 /// look up the samples collected for \p Inst using BodySamples.
424 /// \param Inst Instruction to query.
426 /// \returns the weight of \p Inst.
428 SampleProfileLoader::getInstWeight(const Instruction &Inst) const {
429 DebugLoc DLoc = Inst.getDebugLoc();
431 return std::error_code();
433 const FunctionSamples *FS = findFunctionSamples(Inst);
435 return std::error_code();
437 const DILocation *DIL = DLoc;
438 unsigned Lineno = DLoc.getLine();
439 unsigned HeaderLineno = DIL->getScope()->getSubprogram()->getLine();
441 uint32_t LineOffset = getOffset(Lineno, HeaderLineno);
442 uint32_t Discriminator = DIL->getDiscriminator();
443 ErrorOr<uint64_t> R = FS->findSamplesAt(LineOffset, Discriminator);
446 CoverageTracker.markSamplesUsed(FS, LineOffset, Discriminator, R.get());
448 const Function *F = Inst.getParent()->getParent();
449 LLVMContext &Ctx = F->getContext();
450 emitOptimizationRemark(
451 Ctx, DEBUG_TYPE, *F, DLoc,
452 Twine("Applied ") + Twine(*R) + " samples from profile (offset: " +
454 ((Discriminator) ? Twine(".") + Twine(Discriminator) : "") + ")");
456 DEBUG(dbgs() << " " << Lineno << "." << DIL->getDiscriminator() << ":"
457 << Inst << " (line offset: " << Lineno - HeaderLineno << "."
458 << DIL->getDiscriminator() << " - weight: " << R.get()
464 /// \brief Compute the weight of a basic block.
466 /// The weight of basic block \p BB is the maximum weight of all the
467 /// instructions in BB.
469 /// \param BB The basic block to query.
471 /// \returns the weight for \p BB.
473 SampleProfileLoader::getBlockWeight(const BasicBlock *BB) const {
476 for (auto &I : BB->getInstList()) {
477 const ErrorOr<uint64_t> &R = getInstWeight(I);
478 if (R && R.get() >= Weight) {
486 return std::error_code();
489 /// \brief Compute and store the weights of every basic block.
491 /// This populates the BlockWeights map by computing
492 /// the weights of every basic block in the CFG.
494 /// \param F The function to query.
495 bool SampleProfileLoader::computeBlockWeights(Function &F) {
496 bool Changed = false;
497 DEBUG(dbgs() << "Block weights\n");
498 for (const auto &BB : F) {
499 ErrorOr<uint64_t> Weight = getBlockWeight(&BB);
501 BlockWeights[&BB] = Weight.get();
502 VisitedBlocks.insert(&BB);
505 DEBUG(printBlockWeight(dbgs(), &BB));
511 /// \brief Get the FunctionSamples for a call instruction.
513 /// The FunctionSamples of a call instruction \p Inst is the inlined
514 /// instance in which that call instruction is calling to. It contains
515 /// all samples that resides in the inlined instance. We first find the
516 /// inlined instance in which the call instruction is from, then we
517 /// traverse its children to find the callsite with the matching
518 /// location and callee function name.
520 /// \param Inst Call instruction to query.
522 /// \returns The FunctionSamples pointer to the inlined instance.
523 const FunctionSamples *
524 SampleProfileLoader::findCalleeFunctionSamples(const CallInst &Inst) const {
525 const DILocation *DIL = Inst.getDebugLoc();
529 DISubprogram *SP = DIL->getScope()->getSubprogram();
533 Function *CalleeFunc = Inst.getCalledFunction();
538 StringRef CalleeName = CalleeFunc->getName();
539 const FunctionSamples *FS = findFunctionSamples(Inst);
543 return FS->findFunctionSamplesAt(
544 CallsiteLocation(getOffset(DIL->getLine(), SP->getLine()),
545 DIL->getDiscriminator(), CalleeName));
548 /// \brief Get the FunctionSamples for an instruction.
550 /// The FunctionSamples of an instruction \p Inst is the inlined instance
551 /// in which that instruction is coming from. We traverse the inline stack
552 /// of that instruction, and match it with the tree nodes in the profile.
554 /// \param Inst Instruction to query.
556 /// \returns the FunctionSamples pointer to the inlined instance.
557 const FunctionSamples *
558 SampleProfileLoader::findFunctionSamples(const Instruction &Inst) const {
559 SmallVector<CallsiteLocation, 10> S;
560 const DILocation *DIL = Inst.getDebugLoc();
564 StringRef CalleeName;
565 for (const DILocation *DIL = Inst.getDebugLoc(); DIL;
566 DIL = DIL->getInlinedAt()) {
567 DISubprogram *SP = DIL->getScope()->getSubprogram();
570 if (!CalleeName.empty()) {
571 S.push_back(CallsiteLocation(getOffset(DIL->getLine(), SP->getLine()),
572 DIL->getDiscriminator(), CalleeName));
574 CalleeName = SP->getLinkageName();
578 const FunctionSamples *FS = Samples;
579 for (int i = S.size() - 1; i >= 0 && FS != nullptr; i--) {
580 FS = FS->findFunctionSamplesAt(S[i]);
585 /// \brief Iteratively inline hot callsites of a function.
587 /// Iteratively traverse all callsites of the function \p F, and find if
588 /// the corresponding inlined instance exists and is hot in profile. If
589 /// it is hot enough, inline the callsites and adds new callsites of the
590 /// callee into the caller.
592 /// TODO: investigate the possibility of not invoking InlineFunction directly.
594 /// \param F function to perform iterative inlining.
596 /// \returns True if there is any inline happened.
597 bool SampleProfileLoader::inlineHotFunctions(Function &F) {
598 bool Changed = false;
599 LLVMContext &Ctx = F.getContext();
601 bool LocalChanged = false;
602 SmallVector<CallInst *, 10> CIS;
604 for (auto &I : BB.getInstList()) {
605 CallInst *CI = dyn_cast<CallInst>(&I);
606 if (CI && callsiteIsHot(Samples, findCalleeFunctionSamples(*CI)))
610 for (auto CI : CIS) {
611 InlineFunctionInfo IFI;
612 Function *CalledFunction = CI->getCalledFunction();
613 DebugLoc DLoc = CI->getDebugLoc();
614 uint64_t NumSamples = findCalleeFunctionSamples(*CI)->getTotalSamples();
615 if (InlineFunction(CI, IFI)) {
617 emitOptimizationRemark(Ctx, DEBUG_TYPE, F, DLoc,
618 Twine("inlined hot callee '") +
619 CalledFunction->getName() + "' with " +
620 Twine(NumSamples) + " samples into '" +
633 /// \brief Find equivalence classes for the given block.
635 /// This finds all the blocks that are guaranteed to execute the same
636 /// number of times as \p BB1. To do this, it traverses all the
637 /// descendants of \p BB1 in the dominator or post-dominator tree.
639 /// A block BB2 will be in the same equivalence class as \p BB1 if
640 /// the following holds:
642 /// 1- \p BB1 is a descendant of BB2 in the opposite tree. So, if BB2
643 /// is a descendant of \p BB1 in the dominator tree, then BB2 should
644 /// dominate BB1 in the post-dominator tree.
646 /// 2- Both BB2 and \p BB1 must be in the same loop.
648 /// For every block BB2 that meets those two requirements, we set BB2's
649 /// equivalence class to \p BB1.
651 /// \param BB1 Block to check.
652 /// \param Descendants Descendants of \p BB1 in either the dom or pdom tree.
653 /// \param DomTree Opposite dominator tree. If \p Descendants is filled
654 /// with blocks from \p BB1's dominator tree, then
655 /// this is the post-dominator tree, and vice versa.
656 void SampleProfileLoader::findEquivalencesFor(
657 BasicBlock *BB1, SmallVector<BasicBlock *, 8> Descendants,
658 DominatorTreeBase<BasicBlock> *DomTree) {
659 const BasicBlock *EC = EquivalenceClass[BB1];
660 uint64_t Weight = BlockWeights[EC];
661 for (const auto *BB2 : Descendants) {
662 bool IsDomParent = DomTree->dominates(BB2, BB1);
663 bool IsInSameLoop = LI->getLoopFor(BB1) == LI->getLoopFor(BB2);
664 if (BB1 != BB2 && IsDomParent && IsInSameLoop) {
665 EquivalenceClass[BB2] = EC;
667 // If BB2 is heavier than BB1, make BB2 have the same weight
670 // Note that we don't worry about the opposite situation here
671 // (when BB2 is lighter than BB1). We will deal with this
672 // during the propagation phase. Right now, we just want to
673 // make sure that BB1 has the largest weight of all the
674 // members of its equivalence set.
675 Weight = std::max(Weight, BlockWeights[BB2]);
678 BlockWeights[EC] = Weight;
681 /// \brief Find equivalence classes.
683 /// Since samples may be missing from blocks, we can fill in the gaps by setting
684 /// the weights of all the blocks in the same equivalence class to the same
685 /// weight. To compute the concept of equivalence, we use dominance and loop
686 /// information. Two blocks B1 and B2 are in the same equivalence class if B1
687 /// dominates B2, B2 post-dominates B1 and both are in the same loop.
689 /// \param F The function to query.
690 void SampleProfileLoader::findEquivalenceClasses(Function &F) {
691 SmallVector<BasicBlock *, 8> DominatedBBs;
692 DEBUG(dbgs() << "\nBlock equivalence classes\n");
693 // Find equivalence sets based on dominance and post-dominance information.
695 BasicBlock *BB1 = &BB;
697 // Compute BB1's equivalence class once.
698 if (EquivalenceClass.count(BB1)) {
699 DEBUG(printBlockEquivalence(dbgs(), BB1));
703 // By default, blocks are in their own equivalence class.
704 EquivalenceClass[BB1] = BB1;
706 // Traverse all the blocks dominated by BB1. We are looking for
707 // every basic block BB2 such that:
709 // 1- BB1 dominates BB2.
710 // 2- BB2 post-dominates BB1.
711 // 3- BB1 and BB2 are in the same loop nest.
713 // If all those conditions hold, it means that BB2 is executed
714 // as many times as BB1, so they are placed in the same equivalence
715 // class by making BB2's equivalence class be BB1.
716 DominatedBBs.clear();
717 DT->getDescendants(BB1, DominatedBBs);
718 findEquivalencesFor(BB1, DominatedBBs, PDT.get());
720 DEBUG(printBlockEquivalence(dbgs(), BB1));
723 // Assign weights to equivalence classes.
725 // All the basic blocks in the same equivalence class will execute
726 // the same number of times. Since we know that the head block in
727 // each equivalence class has the largest weight, assign that weight
728 // to all the blocks in that equivalence class.
729 DEBUG(dbgs() << "\nAssign the same weight to all blocks in the same class\n");
731 const BasicBlock *BB = &BI;
732 const BasicBlock *EquivBB = EquivalenceClass[BB];
734 BlockWeights[BB] = BlockWeights[EquivBB];
735 DEBUG(printBlockWeight(dbgs(), BB));
739 /// \brief Visit the given edge to decide if it has a valid weight.
741 /// If \p E has not been visited before, we copy to \p UnknownEdge
742 /// and increment the count of unknown edges.
744 /// \param E Edge to visit.
745 /// \param NumUnknownEdges Current number of unknown edges.
746 /// \param UnknownEdge Set if E has not been visited before.
748 /// \returns E's weight, if known. Otherwise, return 0.
749 uint64_t SampleProfileLoader::visitEdge(Edge E, unsigned *NumUnknownEdges,
751 if (!VisitedEdges.count(E)) {
752 (*NumUnknownEdges)++;
757 return EdgeWeights[E];
760 /// \brief Propagate weights through incoming/outgoing edges.
762 /// If the weight of a basic block is known, and there is only one edge
763 /// with an unknown weight, we can calculate the weight of that edge.
765 /// Similarly, if all the edges have a known count, we can calculate the
766 /// count of the basic block, if needed.
768 /// \param F Function to process.
770 /// \returns True if new weights were assigned to edges or blocks.
771 bool SampleProfileLoader::propagateThroughEdges(Function &F) {
772 bool Changed = false;
773 DEBUG(dbgs() << "\nPropagation through edges\n");
774 for (const auto &BI : F) {
775 const BasicBlock *BB = &BI;
776 const BasicBlock *EC = EquivalenceClass[BB];
778 // Visit all the predecessor and successor edges to determine
779 // which ones have a weight assigned already. Note that it doesn't
780 // matter that we only keep track of a single unknown edge. The
781 // only case we are interested in handling is when only a single
782 // edge is unknown (see setEdgeOrBlockWeight).
783 for (unsigned i = 0; i < 2; i++) {
784 uint64_t TotalWeight = 0;
785 unsigned NumUnknownEdges = 0;
786 Edge UnknownEdge, SelfReferentialEdge;
789 // First, visit all predecessor edges.
790 for (auto *Pred : Predecessors[BB]) {
791 Edge E = std::make_pair(Pred, BB);
792 TotalWeight += visitEdge(E, &NumUnknownEdges, &UnknownEdge);
793 if (E.first == E.second)
794 SelfReferentialEdge = E;
797 // On the second round, visit all successor edges.
798 for (auto *Succ : Successors[BB]) {
799 Edge E = std::make_pair(BB, Succ);
800 TotalWeight += visitEdge(E, &NumUnknownEdges, &UnknownEdge);
804 // After visiting all the edges, there are three cases that we
805 // can handle immediately:
807 // - All the edge weights are known (i.e., NumUnknownEdges == 0).
808 // In this case, we simply check that the sum of all the edges
809 // is the same as BB's weight. If not, we change BB's weight
810 // to match. Additionally, if BB had not been visited before,
811 // we mark it visited.
813 // - Only one edge is unknown and BB has already been visited.
814 // In this case, we can compute the weight of the edge by
815 // subtracting the total block weight from all the known
816 // edge weights. If the edges weight more than BB, then the
817 // edge of the last remaining edge is set to zero.
819 // - There exists a self-referential edge and the weight of BB is
820 // known. In this case, this edge can be based on BB's weight.
821 // We add up all the other known edges and set the weight on
822 // the self-referential edge as we did in the previous case.
824 // In any other case, we must continue iterating. Eventually,
825 // all edges will get a weight, or iteration will stop when
826 // it reaches SampleProfileMaxPropagateIterations.
827 if (NumUnknownEdges <= 1) {
828 uint64_t &BBWeight = BlockWeights[EC];
829 if (NumUnknownEdges == 0) {
830 // If we already know the weight of all edges, the weight of the
831 // basic block can be computed. It should be no larger than the sum
832 // of all edge weights.
833 if (TotalWeight > BBWeight) {
834 BBWeight = TotalWeight;
836 DEBUG(dbgs() << "All edge weights for " << BB->getName()
837 << " known. Set weight for block: ";
838 printBlockWeight(dbgs(), BB););
840 if (VisitedBlocks.insert(EC).second)
842 } else if (NumUnknownEdges == 1 && VisitedBlocks.count(EC)) {
843 // If there is a single unknown edge and the block has been
844 // visited, then we can compute E's weight.
845 if (BBWeight >= TotalWeight)
846 EdgeWeights[UnknownEdge] = BBWeight - TotalWeight;
848 EdgeWeights[UnknownEdge] = 0;
849 VisitedEdges.insert(UnknownEdge);
851 DEBUG(dbgs() << "Set weight for edge: ";
852 printEdgeWeight(dbgs(), UnknownEdge));
854 } else if (SelfReferentialEdge.first && VisitedBlocks.count(EC)) {
855 uint64_t &BBWeight = BlockWeights[BB];
856 // We have a self-referential edge and the weight of BB is known.
857 if (BBWeight >= TotalWeight)
858 EdgeWeights[SelfReferentialEdge] = BBWeight - TotalWeight;
860 EdgeWeights[SelfReferentialEdge] = 0;
861 VisitedEdges.insert(SelfReferentialEdge);
863 DEBUG(dbgs() << "Set self-referential edge weight to: ";
864 printEdgeWeight(dbgs(), SelfReferentialEdge));
872 /// \brief Build in/out edge lists for each basic block in the CFG.
874 /// We are interested in unique edges. If a block B1 has multiple
875 /// edges to another block B2, we only add a single B1->B2 edge.
876 void SampleProfileLoader::buildEdges(Function &F) {
878 BasicBlock *B1 = &BI;
880 // Add predecessors for B1.
881 SmallPtrSet<BasicBlock *, 16> Visited;
882 if (!Predecessors[B1].empty())
883 llvm_unreachable("Found a stale predecessors list in a basic block.");
884 for (pred_iterator PI = pred_begin(B1), PE = pred_end(B1); PI != PE; ++PI) {
885 BasicBlock *B2 = *PI;
886 if (Visited.insert(B2).second)
887 Predecessors[B1].push_back(B2);
890 // Add successors for B1.
892 if (!Successors[B1].empty())
893 llvm_unreachable("Found a stale successors list in a basic block.");
894 for (succ_iterator SI = succ_begin(B1), SE = succ_end(B1); SI != SE; ++SI) {
895 BasicBlock *B2 = *SI;
896 if (Visited.insert(B2).second)
897 Successors[B1].push_back(B2);
902 /// \brief Propagate weights into edges
904 /// The following rules are applied to every block BB in the CFG:
906 /// - If BB has a single predecessor/successor, then the weight
907 /// of that edge is the weight of the block.
909 /// - If all incoming or outgoing edges are known except one, and the
910 /// weight of the block is already known, the weight of the unknown
911 /// edge will be the weight of the block minus the sum of all the known
912 /// edges. If the sum of all the known edges is larger than BB's weight,
913 /// we set the unknown edge weight to zero.
915 /// - If there is a self-referential edge, and the weight of the block is
916 /// known, the weight for that edge is set to the weight of the block
917 /// minus the weight of the other incoming edges to that block (if
919 void SampleProfileLoader::propagateWeights(Function &F) {
923 // Add an entry count to the function using the samples gathered
924 // at the function entry.
925 F.setEntryCount(Samples->getHeadSamples());
927 // Before propagation starts, build, for each block, a list of
928 // unique predecessors and successors. This is necessary to handle
929 // identical edges in multiway branches. Since we visit all blocks and all
930 // edges of the CFG, it is cleaner to build these lists once at the start
934 // Propagate until we converge or we go past the iteration limit.
935 while (Changed && I++ < SampleProfileMaxPropagateIterations) {
936 Changed = propagateThroughEdges(F);
939 // Generate MD_prof metadata for every branch instruction using the
940 // edge weights computed during propagation.
941 DEBUG(dbgs() << "\nPropagation complete. Setting branch weights\n");
942 LLVMContext &Ctx = F.getContext();
945 BasicBlock *BB = &BI;
946 TerminatorInst *TI = BB->getTerminator();
947 if (TI->getNumSuccessors() == 1)
949 if (!isa<BranchInst>(TI) && !isa<SwitchInst>(TI))
952 DEBUG(dbgs() << "\nGetting weights for branch at line "
953 << TI->getDebugLoc().getLine() << ".\n");
954 SmallVector<uint32_t, 4> Weights;
955 uint32_t MaxWeight = 0;
957 for (unsigned I = 0; I < TI->getNumSuccessors(); ++I) {
958 BasicBlock *Succ = TI->getSuccessor(I);
959 Edge E = std::make_pair(BB, Succ);
960 uint64_t Weight = EdgeWeights[E];
961 DEBUG(dbgs() << "\t"; printEdgeWeight(dbgs(), E));
962 // Use uint32_t saturated arithmetic to adjust the incoming weights,
963 // if needed. Sample counts in profiles are 64-bit unsigned values,
964 // but internally branch weights are expressed as 32-bit values.
965 if (Weight > std::numeric_limits<uint32_t>::max()) {
966 DEBUG(dbgs() << " (saturated due to uint32_t overflow)");
967 Weight = std::numeric_limits<uint32_t>::max();
969 Weights.push_back(static_cast<uint32_t>(Weight));
971 if (Weight > MaxWeight) {
973 MaxDestLoc = Succ->getFirstNonPHIOrDbgOrLifetime()->getDebugLoc();
978 // Only set weights if there is at least one non-zero weight.
979 // In any other case, let the analyzer set weights.
981 DEBUG(dbgs() << "SUCCESS. Found non-zero weights.\n");
982 TI->setMetadata(llvm::LLVMContext::MD_prof,
983 MDB.createBranchWeights(Weights));
984 DebugLoc BranchLoc = TI->getDebugLoc();
985 emitOptimizationRemark(
986 Ctx, DEBUG_TYPE, F, MaxDestLoc,
987 Twine("most popular destination for conditional branches at ") +
988 ((BranchLoc) ? Twine(BranchLoc->getFilename() + ":" +
989 Twine(BranchLoc.getLine()) + ":" +
990 Twine(BranchLoc.getCol()))
991 : Twine("<UNKNOWN LOCATION>")));
993 DEBUG(dbgs() << "SKIPPED. All branch weights are zero.\n");
998 /// \brief Get the line number for the function header.
1000 /// This looks up function \p F in the current compilation unit and
1001 /// retrieves the line number where the function is defined. This is
1002 /// line 0 for all the samples read from the profile file. Every line
1003 /// number is relative to this line.
1005 /// \param F Function object to query.
1007 /// \returns the line number where \p F is defined. If it returns 0,
1008 /// it means that there is no debug information available for \p F.
1009 unsigned SampleProfileLoader::getFunctionLoc(Function &F) {
1010 if (DISubprogram *S = getDISubprogram(&F))
1011 return S->getLine();
1013 // If the start of \p F is missing, emit a diagnostic to inform the user
1014 // about the missed opportunity.
1015 F.getContext().diagnose(DiagnosticInfoSampleProfile(
1016 "No debug information found in function " + F.getName() +
1017 ": Function profile not used",
1022 void SampleProfileLoader::computeDominanceAndLoopInfo(Function &F) {
1023 DT.reset(new DominatorTree);
1026 PDT.reset(new DominatorTreeBase<BasicBlock>(true));
1027 PDT->recalculate(F);
1029 LI.reset(new LoopInfo);
1033 /// \brief Generate branch weight metadata for all branches in \p F.
1035 /// Branch weights are computed out of instruction samples using a
1036 /// propagation heuristic. Propagation proceeds in 3 phases:
1038 /// 1- Assignment of block weights. All the basic blocks in the function
1039 /// are initial assigned the same weight as their most frequently
1040 /// executed instruction.
1042 /// 2- Creation of equivalence classes. Since samples may be missing from
1043 /// blocks, we can fill in the gaps by setting the weights of all the
1044 /// blocks in the same equivalence class to the same weight. To compute
1045 /// the concept of equivalence, we use dominance and loop information.
1046 /// Two blocks B1 and B2 are in the same equivalence class if B1
1047 /// dominates B2, B2 post-dominates B1 and both are in the same loop.
1049 /// 3- Propagation of block weights into edges. This uses a simple
1050 /// propagation heuristic. The following rules are applied to every
1051 /// block BB in the CFG:
1053 /// - If BB has a single predecessor/successor, then the weight
1054 /// of that edge is the weight of the block.
1056 /// - If all the edges are known except one, and the weight of the
1057 /// block is already known, the weight of the unknown edge will
1058 /// be the weight of the block minus the sum of all the known
1059 /// edges. If the sum of all the known edges is larger than BB's weight,
1060 /// we set the unknown edge weight to zero.
1062 /// - If there is a self-referential edge, and the weight of the block is
1063 /// known, the weight for that edge is set to the weight of the block
1064 /// minus the weight of the other incoming edges to that block (if
1067 /// Since this propagation is not guaranteed to finalize for every CFG, we
1068 /// only allow it to proceed for a limited number of iterations (controlled
1069 /// by -sample-profile-max-propagate-iterations).
1071 /// FIXME: Try to replace this propagation heuristic with a scheme
1072 /// that is guaranteed to finalize. A work-list approach similar to
1073 /// the standard value propagation algorithm used by SSA-CCP might
1076 /// Once all the branch weights are computed, we emit the MD_prof
1077 /// metadata on BB using the computed values for each of its branches.
1079 /// \param F The function to query.
1081 /// \returns true if \p F was modified. Returns false, otherwise.
1082 bool SampleProfileLoader::emitAnnotations(Function &F) {
1083 bool Changed = false;
1085 if (getFunctionLoc(F) == 0)
1088 DEBUG(dbgs() << "Line number for the first instruction in " << F.getName()
1089 << ": " << getFunctionLoc(F) << "\n");
1091 Changed |= inlineHotFunctions(F);
1093 // Compute basic block weights.
1094 Changed |= computeBlockWeights(F);
1097 // Compute dominance and loop info needed for propagation.
1098 computeDominanceAndLoopInfo(F);
1100 // Find equivalence classes.
1101 findEquivalenceClasses(F);
1103 // Propagate weights to all edges.
1104 propagateWeights(F);
1107 // If coverage checking was requested, compute it now.
1108 if (SampleProfileRecordCoverage) {
1109 unsigned Used = CoverageTracker.countUsedRecords(Samples);
1110 unsigned Total = CoverageTracker.countBodyRecords(Samples);
1111 unsigned Coverage = CoverageTracker.computeCoverage(Used, Total);
1112 if (Coverage < SampleProfileRecordCoverage) {
1113 F.getContext().diagnose(DiagnosticInfoSampleProfile(
1114 getDISubprogram(&F)->getFilename(), getFunctionLoc(F),
1115 Twine(Used) + " of " + Twine(Total) + " available profile records (" +
1116 Twine(Coverage) + "%) were applied",
1121 if (SampleProfileSampleCoverage) {
1122 uint64_t Used = CoverageTracker.getTotalUsedSamples();
1123 uint64_t Total = CoverageTracker.countBodySamples(Samples);
1124 unsigned Coverage = CoverageTracker.computeCoverage(Used, Total);
1125 if (Coverage < SampleProfileSampleCoverage) {
1126 F.getContext().diagnose(DiagnosticInfoSampleProfile(
1127 getDISubprogram(&F)->getFilename(), getFunctionLoc(F),
1128 Twine(Used) + " of " + Twine(Total) + " available profile samples (" +
1129 Twine(Coverage) + "%) were applied",
1136 char SampleProfileLoader::ID = 0;
1137 INITIALIZE_PASS_BEGIN(SampleProfileLoader, "sample-profile",
1138 "Sample Profile loader", false, false)
1139 INITIALIZE_PASS_DEPENDENCY(AddDiscriminators)
1140 INITIALIZE_PASS_END(SampleProfileLoader, "sample-profile",
1141 "Sample Profile loader", false, false)
1143 bool SampleProfileLoader::doInitialization(Module &M) {
1144 auto &Ctx = M.getContext();
1145 auto ReaderOrErr = SampleProfileReader::create(Filename, Ctx);
1146 if (std::error_code EC = ReaderOrErr.getError()) {
1147 std::string Msg = "Could not open profile: " + EC.message();
1148 Ctx.diagnose(DiagnosticInfoSampleProfile(Filename, Msg));
1151 Reader = std::move(ReaderOrErr.get());
1152 ProfileIsValid = (Reader->read() == sampleprof_error::success);
1156 ModulePass *llvm::createSampleProfileLoaderPass() {
1157 return new SampleProfileLoader(SampleProfileFile);
1160 ModulePass *llvm::createSampleProfileLoaderPass(StringRef Name) {
1161 return new SampleProfileLoader(Name);
1164 bool SampleProfileLoader::runOnModule(Module &M) {
1165 if (!ProfileIsValid)
1168 bool retval = false;
1170 if (!F.isDeclaration()) {
1171 clearFunctionData();
1172 retval |= runOnFunction(F);
1177 bool SampleProfileLoader::runOnFunction(Function &F) {
1178 Samples = Reader->getSamplesFor(F);
1179 if (!Samples->empty())
1180 return emitAnnotations(F);