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<unsigned> SampleProfileHotThreshold(
75 "sample-profile-inline-hot-threshold", cl::init(5), 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 uint64_t PercentSamples = CallsiteTotalSamples * 100 / ParentTotalSamples;
266 return PercentSamples >= SampleProfileHotThreshold;
271 /// Mark as used the sample record for the given function samples at
272 /// (LineOffset, Discriminator).
274 /// \returns true if this is the first time we mark the given record.
275 bool SampleCoverageTracker::markSamplesUsed(const FunctionSamples *FS,
277 uint32_t Discriminator,
279 LineLocation Loc(LineOffset, Discriminator);
280 unsigned &Count = SampleCoverage[FS][Loc];
281 bool FirstTime = (++Count == 1);
283 TotalUsedSamples += Samples;
287 /// Return the number of sample records that were applied from this profile.
289 /// This count does not include records from cold inlined callsites.
291 SampleCoverageTracker::countUsedRecords(const FunctionSamples *FS) const {
292 auto I = SampleCoverage.find(FS);
294 // The size of the coverage map for FS represents the number of records
295 // that were marked used at least once.
296 unsigned Count = (I != SampleCoverage.end()) ? I->second.size() : 0;
298 // If there are inlined callsites in this function, count the samples found
299 // in the respective bodies. However, do not bother counting callees with 0
300 // total samples, these are callees that were never invoked at runtime.
301 for (const auto &I : FS->getCallsiteSamples()) {
302 const FunctionSamples *CalleeSamples = &I.second;
303 if (callsiteIsHot(FS, CalleeSamples))
304 Count += countUsedRecords(CalleeSamples);
310 /// Return the number of sample records in the body of this profile.
312 /// This count does not include records from cold inlined callsites.
314 SampleCoverageTracker::countBodyRecords(const FunctionSamples *FS) const {
315 unsigned Count = FS->getBodySamples().size();
317 // Only count records in hot callsites.
318 for (const auto &I : FS->getCallsiteSamples()) {
319 const FunctionSamples *CalleeSamples = &I.second;
320 if (callsiteIsHot(FS, CalleeSamples))
321 Count += countBodyRecords(CalleeSamples);
327 /// Return the number of samples collected in the body of this profile.
329 /// This count does not include samples from cold inlined callsites.
331 SampleCoverageTracker::countBodySamples(const FunctionSamples *FS) const {
333 for (const auto &I : FS->getBodySamples())
334 Total += I.second.getSamples();
336 // Only count samples in hot callsites.
337 for (const auto &I : FS->getCallsiteSamples()) {
338 const FunctionSamples *CalleeSamples = &I.second;
339 if (callsiteIsHot(FS, CalleeSamples))
340 Total += countBodySamples(CalleeSamples);
346 /// Return the fraction of sample records used in this profile.
348 /// The returned value is an unsigned integer in the range 0-100 indicating
349 /// the percentage of sample records that were used while applying this
350 /// profile to the associated function.
351 unsigned SampleCoverageTracker::computeCoverage(unsigned Used,
352 unsigned Total) const {
353 assert(Used <= Total &&
354 "number of used records cannot exceed the total number of records");
355 return Total > 0 ? Used * 100 / Total : 100;
358 /// Clear all the per-function data used to load samples and propagate weights.
359 void SampleProfileLoader::clearFunctionData() {
360 BlockWeights.clear();
362 VisitedBlocks.clear();
363 VisitedEdges.clear();
364 EquivalenceClass.clear();
368 Predecessors.clear();
370 CoverageTracker.clear();
373 /// \brief Returns the offset of lineno \p L to head_lineno \p H
376 /// \param H Header lineno of the function
378 /// \returns offset to the header lineno. 16 bits are used to represent offset.
379 /// We assume that a single function will not exceed 65535 LOC.
380 unsigned SampleProfileLoader::getOffset(unsigned L, unsigned H) const {
381 return (L - H) & 0xffff;
384 /// \brief Print the weight of edge \p E on stream \p OS.
386 /// \param OS Stream to emit the output to.
387 /// \param E Edge to print.
388 void SampleProfileLoader::printEdgeWeight(raw_ostream &OS, Edge E) {
389 OS << "weight[" << E.first->getName() << "->" << E.second->getName()
390 << "]: " << EdgeWeights[E] << "\n";
393 /// \brief Print the equivalence class of block \p BB on stream \p OS.
395 /// \param OS Stream to emit the output to.
396 /// \param BB Block to print.
397 void SampleProfileLoader::printBlockEquivalence(raw_ostream &OS,
398 const BasicBlock *BB) {
399 const BasicBlock *Equiv = EquivalenceClass[BB];
400 OS << "equivalence[" << BB->getName()
401 << "]: " << ((Equiv) ? EquivalenceClass[BB]->getName() : "NONE") << "\n";
404 /// \brief Print the weight of block \p BB on stream \p OS.
406 /// \param OS Stream to emit the output to.
407 /// \param BB Block to print.
408 void SampleProfileLoader::printBlockWeight(raw_ostream &OS,
409 const BasicBlock *BB) const {
410 const auto &I = BlockWeights.find(BB);
411 uint64_t W = (I == BlockWeights.end() ? 0 : I->second);
412 OS << "weight[" << BB->getName() << "]: " << W << "\n";
415 /// \brief Get the weight for an instruction.
417 /// The "weight" of an instruction \p Inst is the number of samples
418 /// collected on that instruction at runtime. To retrieve it, we
419 /// need to compute the line number of \p Inst relative to the start of its
420 /// function. We use HeaderLineno to compute the offset. We then
421 /// look up the samples collected for \p Inst using BodySamples.
423 /// \param Inst Instruction to query.
425 /// \returns the weight of \p Inst.
427 SampleProfileLoader::getInstWeight(const Instruction &Inst) const {
428 DebugLoc DLoc = Inst.getDebugLoc();
430 return std::error_code();
432 const FunctionSamples *FS = findFunctionSamples(Inst);
434 return std::error_code();
436 const DILocation *DIL = DLoc;
437 unsigned Lineno = DLoc.getLine();
438 unsigned HeaderLineno = DIL->getScope()->getSubprogram()->getLine();
440 uint32_t LineOffset = getOffset(Lineno, HeaderLineno);
441 uint32_t Discriminator = DIL->getDiscriminator();
442 ErrorOr<uint64_t> R = FS->findSamplesAt(LineOffset, Discriminator);
445 CoverageTracker.markSamplesUsed(FS, LineOffset, Discriminator, R.get());
447 const Function *F = Inst.getParent()->getParent();
448 LLVMContext &Ctx = F->getContext();
449 emitOptimizationRemark(
450 Ctx, DEBUG_TYPE, *F, DLoc,
451 Twine("Applied ") + Twine(*R) + " samples from profile (offset: " +
453 ((Discriminator) ? Twine(".") + Twine(Discriminator) : "") + ")");
455 DEBUG(dbgs() << " " << Lineno << "." << DIL->getDiscriminator() << ":"
456 << Inst << " (line offset: " << Lineno - HeaderLineno << "."
457 << DIL->getDiscriminator() << " - weight: " << R.get()
463 /// \brief Compute the weight of a basic block.
465 /// The weight of basic block \p BB is the maximum weight of all the
466 /// instructions in BB.
468 /// \param BB The basic block to query.
470 /// \returns the weight for \p BB.
472 SampleProfileLoader::getBlockWeight(const BasicBlock *BB) const {
475 for (auto &I : BB->getInstList()) {
476 const ErrorOr<uint64_t> &R = getInstWeight(I);
477 if (R && R.get() >= Weight) {
485 return std::error_code();
488 /// \brief Compute and store the weights of every basic block.
490 /// This populates the BlockWeights map by computing
491 /// the weights of every basic block in the CFG.
493 /// \param F The function to query.
494 bool SampleProfileLoader::computeBlockWeights(Function &F) {
495 bool Changed = false;
496 DEBUG(dbgs() << "Block weights\n");
497 for (const auto &BB : F) {
498 ErrorOr<uint64_t> Weight = getBlockWeight(&BB);
500 BlockWeights[&BB] = Weight.get();
501 VisitedBlocks.insert(&BB);
504 DEBUG(printBlockWeight(dbgs(), &BB));
510 /// \brief Get the FunctionSamples for a call instruction.
512 /// The FunctionSamples of a call instruction \p Inst is the inlined
513 /// instance in which that call instruction is calling to. It contains
514 /// all samples that resides in the inlined instance. We first find the
515 /// inlined instance in which the call instruction is from, then we
516 /// traverse its children to find the callsite with the matching
517 /// location and callee function name.
519 /// \param Inst Call instruction to query.
521 /// \returns The FunctionSamples pointer to the inlined instance.
522 const FunctionSamples *
523 SampleProfileLoader::findCalleeFunctionSamples(const CallInst &Inst) const {
524 const DILocation *DIL = Inst.getDebugLoc();
528 DISubprogram *SP = DIL->getScope()->getSubprogram();
532 Function *CalleeFunc = Inst.getCalledFunction();
537 StringRef CalleeName = CalleeFunc->getName();
538 const FunctionSamples *FS = findFunctionSamples(Inst);
542 return FS->findFunctionSamplesAt(
543 CallsiteLocation(getOffset(DIL->getLine(), SP->getLine()),
544 DIL->getDiscriminator(), CalleeName));
547 /// \brief Get the FunctionSamples for an instruction.
549 /// The FunctionSamples of an instruction \p Inst is the inlined instance
550 /// in which that instruction is coming from. We traverse the inline stack
551 /// of that instruction, and match it with the tree nodes in the profile.
553 /// \param Inst Instruction to query.
555 /// \returns the FunctionSamples pointer to the inlined instance.
556 const FunctionSamples *
557 SampleProfileLoader::findFunctionSamples(const Instruction &Inst) const {
558 SmallVector<CallsiteLocation, 10> S;
559 const DILocation *DIL = Inst.getDebugLoc();
563 StringRef CalleeName;
564 for (const DILocation *DIL = Inst.getDebugLoc(); DIL;
565 DIL = DIL->getInlinedAt()) {
566 DISubprogram *SP = DIL->getScope()->getSubprogram();
569 if (!CalleeName.empty()) {
570 S.push_back(CallsiteLocation(getOffset(DIL->getLine(), SP->getLine()),
571 DIL->getDiscriminator(), CalleeName));
573 CalleeName = SP->getLinkageName();
577 const FunctionSamples *FS = Samples;
578 for (int i = S.size() - 1; i >= 0 && FS != nullptr; i--) {
579 FS = FS->findFunctionSamplesAt(S[i]);
584 /// \brief Iteratively inline hot callsites of a function.
586 /// Iteratively traverse all callsites of the function \p F, and find if
587 /// the corresponding inlined instance exists and is hot in profile. If
588 /// it is hot enough, inline the callsites and adds new callsites of the
589 /// callee into the caller.
591 /// TODO: investigate the possibility of not invoking InlineFunction directly.
593 /// \param F function to perform iterative inlining.
595 /// \returns True if there is any inline happened.
596 bool SampleProfileLoader::inlineHotFunctions(Function &F) {
597 bool Changed = false;
598 LLVMContext &Ctx = F.getContext();
600 bool LocalChanged = false;
601 SmallVector<CallInst *, 10> CIS;
603 for (auto &I : BB.getInstList()) {
604 CallInst *CI = dyn_cast<CallInst>(&I);
605 if (CI && callsiteIsHot(Samples, findCalleeFunctionSamples(*CI)))
609 for (auto CI : CIS) {
610 InlineFunctionInfo IFI;
611 Function *CalledFunction = CI->getCalledFunction();
612 DebugLoc DLoc = CI->getDebugLoc();
613 uint64_t NumSamples = findCalleeFunctionSamples(*CI)->getTotalSamples();
614 if (InlineFunction(CI, IFI)) {
616 emitOptimizationRemark(Ctx, DEBUG_TYPE, F, DLoc,
617 Twine("inlined hot callee '") +
618 CalledFunction->getName() + "' with " +
619 Twine(NumSamples) + " samples into '" +
632 /// \brief Find equivalence classes for the given block.
634 /// This finds all the blocks that are guaranteed to execute the same
635 /// number of times as \p BB1. To do this, it traverses all the
636 /// descendants of \p BB1 in the dominator or post-dominator tree.
638 /// A block BB2 will be in the same equivalence class as \p BB1 if
639 /// the following holds:
641 /// 1- \p BB1 is a descendant of BB2 in the opposite tree. So, if BB2
642 /// is a descendant of \p BB1 in the dominator tree, then BB2 should
643 /// dominate BB1 in the post-dominator tree.
645 /// 2- Both BB2 and \p BB1 must be in the same loop.
647 /// For every block BB2 that meets those two requirements, we set BB2's
648 /// equivalence class to \p BB1.
650 /// \param BB1 Block to check.
651 /// \param Descendants Descendants of \p BB1 in either the dom or pdom tree.
652 /// \param DomTree Opposite dominator tree. If \p Descendants is filled
653 /// with blocks from \p BB1's dominator tree, then
654 /// this is the post-dominator tree, and vice versa.
655 void SampleProfileLoader::findEquivalencesFor(
656 BasicBlock *BB1, SmallVector<BasicBlock *, 8> Descendants,
657 DominatorTreeBase<BasicBlock> *DomTree) {
658 const BasicBlock *EC = EquivalenceClass[BB1];
659 uint64_t Weight = BlockWeights[EC];
660 for (const auto *BB2 : Descendants) {
661 bool IsDomParent = DomTree->dominates(BB2, BB1);
662 bool IsInSameLoop = LI->getLoopFor(BB1) == LI->getLoopFor(BB2);
663 if (BB1 != BB2 && IsDomParent && IsInSameLoop) {
664 EquivalenceClass[BB2] = EC;
666 // If BB2 is heavier than BB1, make BB2 have the same weight
669 // Note that we don't worry about the opposite situation here
670 // (when BB2 is lighter than BB1). We will deal with this
671 // during the propagation phase. Right now, we just want to
672 // make sure that BB1 has the largest weight of all the
673 // members of its equivalence set.
674 Weight = std::max(Weight, BlockWeights[BB2]);
677 BlockWeights[EC] = Weight;
680 /// \brief Find equivalence classes.
682 /// Since samples may be missing from blocks, we can fill in the gaps by setting
683 /// the weights of all the blocks in the same equivalence class to the same
684 /// weight. To compute the concept of equivalence, we use dominance and loop
685 /// information. Two blocks B1 and B2 are in the same equivalence class if B1
686 /// dominates B2, B2 post-dominates B1 and both are in the same loop.
688 /// \param F The function to query.
689 void SampleProfileLoader::findEquivalenceClasses(Function &F) {
690 SmallVector<BasicBlock *, 8> DominatedBBs;
691 DEBUG(dbgs() << "\nBlock equivalence classes\n");
692 // Find equivalence sets based on dominance and post-dominance information.
694 BasicBlock *BB1 = &BB;
696 // Compute BB1's equivalence class once.
697 if (EquivalenceClass.count(BB1)) {
698 DEBUG(printBlockEquivalence(dbgs(), BB1));
702 // By default, blocks are in their own equivalence class.
703 EquivalenceClass[BB1] = BB1;
705 // Traverse all the blocks dominated by BB1. We are looking for
706 // every basic block BB2 such that:
708 // 1- BB1 dominates BB2.
709 // 2- BB2 post-dominates BB1.
710 // 3- BB1 and BB2 are in the same loop nest.
712 // If all those conditions hold, it means that BB2 is executed
713 // as many times as BB1, so they are placed in the same equivalence
714 // class by making BB2's equivalence class be BB1.
715 DominatedBBs.clear();
716 DT->getDescendants(BB1, DominatedBBs);
717 findEquivalencesFor(BB1, DominatedBBs, PDT.get());
719 DEBUG(printBlockEquivalence(dbgs(), BB1));
722 // Assign weights to equivalence classes.
724 // All the basic blocks in the same equivalence class will execute
725 // the same number of times. Since we know that the head block in
726 // each equivalence class has the largest weight, assign that weight
727 // to all the blocks in that equivalence class.
728 DEBUG(dbgs() << "\nAssign the same weight to all blocks in the same class\n");
730 const BasicBlock *BB = &BI;
731 const BasicBlock *EquivBB = EquivalenceClass[BB];
733 BlockWeights[BB] = BlockWeights[EquivBB];
734 DEBUG(printBlockWeight(dbgs(), BB));
738 /// \brief Visit the given edge to decide if it has a valid weight.
740 /// If \p E has not been visited before, we copy to \p UnknownEdge
741 /// and increment the count of unknown edges.
743 /// \param E Edge to visit.
744 /// \param NumUnknownEdges Current number of unknown edges.
745 /// \param UnknownEdge Set if E has not been visited before.
747 /// \returns E's weight, if known. Otherwise, return 0.
748 uint64_t SampleProfileLoader::visitEdge(Edge E, unsigned *NumUnknownEdges,
750 if (!VisitedEdges.count(E)) {
751 (*NumUnknownEdges)++;
756 return EdgeWeights[E];
759 /// \brief Propagate weights through incoming/outgoing edges.
761 /// If the weight of a basic block is known, and there is only one edge
762 /// with an unknown weight, we can calculate the weight of that edge.
764 /// Similarly, if all the edges have a known count, we can calculate the
765 /// count of the basic block, if needed.
767 /// \param F Function to process.
769 /// \returns True if new weights were assigned to edges or blocks.
770 bool SampleProfileLoader::propagateThroughEdges(Function &F) {
771 bool Changed = false;
772 DEBUG(dbgs() << "\nPropagation through edges\n");
773 for (const auto &BI : F) {
774 const BasicBlock *BB = &BI;
775 const BasicBlock *EC = EquivalenceClass[BB];
777 // Visit all the predecessor and successor edges to determine
778 // which ones have a weight assigned already. Note that it doesn't
779 // matter that we only keep track of a single unknown edge. The
780 // only case we are interested in handling is when only a single
781 // edge is unknown (see setEdgeOrBlockWeight).
782 for (unsigned i = 0; i < 2; i++) {
783 uint64_t TotalWeight = 0;
784 unsigned NumUnknownEdges = 0;
785 Edge UnknownEdge, SelfReferentialEdge;
788 // First, visit all predecessor edges.
789 for (auto *Pred : Predecessors[BB]) {
790 Edge E = std::make_pair(Pred, BB);
791 TotalWeight += visitEdge(E, &NumUnknownEdges, &UnknownEdge);
792 if (E.first == E.second)
793 SelfReferentialEdge = E;
796 // On the second round, visit all successor edges.
797 for (auto *Succ : Successors[BB]) {
798 Edge E = std::make_pair(BB, Succ);
799 TotalWeight += visitEdge(E, &NumUnknownEdges, &UnknownEdge);
803 // After visiting all the edges, there are three cases that we
804 // can handle immediately:
806 // - All the edge weights are known (i.e., NumUnknownEdges == 0).
807 // In this case, we simply check that the sum of all the edges
808 // is the same as BB's weight. If not, we change BB's weight
809 // to match. Additionally, if BB had not been visited before,
810 // we mark it visited.
812 // - Only one edge is unknown and BB has already been visited.
813 // In this case, we can compute the weight of the edge by
814 // subtracting the total block weight from all the known
815 // edge weights. If the edges weight more than BB, then the
816 // edge of the last remaining edge is set to zero.
818 // - There exists a self-referential edge and the weight of BB is
819 // known. In this case, this edge can be based on BB's weight.
820 // We add up all the other known edges and set the weight on
821 // the self-referential edge as we did in the previous case.
823 // In any other case, we must continue iterating. Eventually,
824 // all edges will get a weight, or iteration will stop when
825 // it reaches SampleProfileMaxPropagateIterations.
826 if (NumUnknownEdges <= 1) {
827 uint64_t &BBWeight = BlockWeights[EC];
828 if (NumUnknownEdges == 0) {
829 // If we already know the weight of all edges, the weight of the
830 // basic block can be computed. It should be no larger than the sum
831 // of all edge weights.
832 if (TotalWeight > BBWeight) {
833 BBWeight = TotalWeight;
835 DEBUG(dbgs() << "All edge weights for " << BB->getName()
836 << " known. Set weight for block: ";
837 printBlockWeight(dbgs(), BB););
839 if (VisitedBlocks.insert(EC).second)
841 } else if (NumUnknownEdges == 1 && VisitedBlocks.count(EC)) {
842 // If there is a single unknown edge and the block has been
843 // visited, then we can compute E's weight.
844 if (BBWeight >= TotalWeight)
845 EdgeWeights[UnknownEdge] = BBWeight - TotalWeight;
847 EdgeWeights[UnknownEdge] = 0;
848 VisitedEdges.insert(UnknownEdge);
850 DEBUG(dbgs() << "Set weight for edge: ";
851 printEdgeWeight(dbgs(), UnknownEdge));
853 } else if (SelfReferentialEdge.first && VisitedBlocks.count(EC)) {
854 uint64_t &BBWeight = BlockWeights[BB];
855 // We have a self-referential edge and the weight of BB is known.
856 if (BBWeight >= TotalWeight)
857 EdgeWeights[SelfReferentialEdge] = BBWeight - TotalWeight;
859 EdgeWeights[SelfReferentialEdge] = 0;
860 VisitedEdges.insert(SelfReferentialEdge);
862 DEBUG(dbgs() << "Set self-referential edge weight to: ";
863 printEdgeWeight(dbgs(), SelfReferentialEdge));
871 /// \brief Build in/out edge lists for each basic block in the CFG.
873 /// We are interested in unique edges. If a block B1 has multiple
874 /// edges to another block B2, we only add a single B1->B2 edge.
875 void SampleProfileLoader::buildEdges(Function &F) {
877 BasicBlock *B1 = &BI;
879 // Add predecessors for B1.
880 SmallPtrSet<BasicBlock *, 16> Visited;
881 if (!Predecessors[B1].empty())
882 llvm_unreachable("Found a stale predecessors list in a basic block.");
883 for (pred_iterator PI = pred_begin(B1), PE = pred_end(B1); PI != PE; ++PI) {
884 BasicBlock *B2 = *PI;
885 if (Visited.insert(B2).second)
886 Predecessors[B1].push_back(B2);
889 // Add successors for B1.
891 if (!Successors[B1].empty())
892 llvm_unreachable("Found a stale successors list in a basic block.");
893 for (succ_iterator SI = succ_begin(B1), SE = succ_end(B1); SI != SE; ++SI) {
894 BasicBlock *B2 = *SI;
895 if (Visited.insert(B2).second)
896 Successors[B1].push_back(B2);
901 /// \brief Propagate weights into edges
903 /// The following rules are applied to every block BB in the CFG:
905 /// - If BB has a single predecessor/successor, then the weight
906 /// of that edge is the weight of the block.
908 /// - If all incoming or outgoing edges are known except one, and the
909 /// weight of the block is already known, the weight of the unknown
910 /// edge will be the weight of the block minus the sum of all the known
911 /// edges. If the sum of all the known edges is larger than BB's weight,
912 /// we set the unknown edge weight to zero.
914 /// - If there is a self-referential edge, and the weight of the block is
915 /// known, the weight for that edge is set to the weight of the block
916 /// minus the weight of the other incoming edges to that block (if
918 void SampleProfileLoader::propagateWeights(Function &F) {
922 // Add an entry count to the function using the samples gathered
923 // at the function entry.
924 F.setEntryCount(Samples->getHeadSamples());
926 // Before propagation starts, build, for each block, a list of
927 // unique predecessors and successors. This is necessary to handle
928 // identical edges in multiway branches. Since we visit all blocks and all
929 // edges of the CFG, it is cleaner to build these lists once at the start
933 // Propagate until we converge or we go past the iteration limit.
934 while (Changed && I++ < SampleProfileMaxPropagateIterations) {
935 Changed = propagateThroughEdges(F);
938 // Generate MD_prof metadata for every branch instruction using the
939 // edge weights computed during propagation.
940 DEBUG(dbgs() << "\nPropagation complete. Setting branch weights\n");
941 LLVMContext &Ctx = F.getContext();
944 BasicBlock *BB = &BI;
945 TerminatorInst *TI = BB->getTerminator();
946 if (TI->getNumSuccessors() == 1)
948 if (!isa<BranchInst>(TI) && !isa<SwitchInst>(TI))
951 DEBUG(dbgs() << "\nGetting weights for branch at line "
952 << TI->getDebugLoc().getLine() << ".\n");
953 SmallVector<uint32_t, 4> Weights;
954 uint32_t MaxWeight = 0;
956 for (unsigned I = 0; I < TI->getNumSuccessors(); ++I) {
957 BasicBlock *Succ = TI->getSuccessor(I);
958 Edge E = std::make_pair(BB, Succ);
959 uint64_t Weight = EdgeWeights[E];
960 DEBUG(dbgs() << "\t"; printEdgeWeight(dbgs(), E));
961 // Use uint32_t saturated arithmetic to adjust the incoming weights,
962 // if needed. Sample counts in profiles are 64-bit unsigned values,
963 // but internally branch weights are expressed as 32-bit values.
964 if (Weight > std::numeric_limits<uint32_t>::max()) {
965 DEBUG(dbgs() << " (saturated due to uint32_t overflow)");
966 Weight = std::numeric_limits<uint32_t>::max();
968 Weights.push_back(static_cast<uint32_t>(Weight));
970 if (Weight > MaxWeight) {
972 MaxDestLoc = Succ->getFirstNonPHIOrDbgOrLifetime()->getDebugLoc();
977 // Only set weights if there is at least one non-zero weight.
978 // In any other case, let the analyzer set weights.
980 DEBUG(dbgs() << "SUCCESS. Found non-zero weights.\n");
981 TI->setMetadata(llvm::LLVMContext::MD_prof,
982 MDB.createBranchWeights(Weights));
983 DebugLoc BranchLoc = TI->getDebugLoc();
984 emitOptimizationRemark(
985 Ctx, DEBUG_TYPE, F, MaxDestLoc,
986 Twine("most popular destination for conditional branches at ") +
987 ((BranchLoc) ? Twine(BranchLoc->getFilename() + ":" +
988 Twine(BranchLoc.getLine()) + ":" +
989 Twine(BranchLoc.getCol()))
990 : Twine("<UNKNOWN LOCATION>")));
992 DEBUG(dbgs() << "SKIPPED. All branch weights are zero.\n");
997 /// \brief Get the line number for the function header.
999 /// This looks up function \p F in the current compilation unit and
1000 /// retrieves the line number where the function is defined. This is
1001 /// line 0 for all the samples read from the profile file. Every line
1002 /// number is relative to this line.
1004 /// \param F Function object to query.
1006 /// \returns the line number where \p F is defined. If it returns 0,
1007 /// it means that there is no debug information available for \p F.
1008 unsigned SampleProfileLoader::getFunctionLoc(Function &F) {
1009 if (DISubprogram *S = getDISubprogram(&F))
1010 return S->getLine();
1012 // If the start of \p F is missing, emit a diagnostic to inform the user
1013 // about the missed opportunity.
1014 F.getContext().diagnose(DiagnosticInfoSampleProfile(
1015 "No debug information found in function " + F.getName() +
1016 ": Function profile not used",
1021 void SampleProfileLoader::computeDominanceAndLoopInfo(Function &F) {
1022 DT.reset(new DominatorTree);
1025 PDT.reset(new DominatorTreeBase<BasicBlock>(true));
1026 PDT->recalculate(F);
1028 LI.reset(new LoopInfo);
1032 /// \brief Generate branch weight metadata for all branches in \p F.
1034 /// Branch weights are computed out of instruction samples using a
1035 /// propagation heuristic. Propagation proceeds in 3 phases:
1037 /// 1- Assignment of block weights. All the basic blocks in the function
1038 /// are initial assigned the same weight as their most frequently
1039 /// executed instruction.
1041 /// 2- Creation of equivalence classes. Since samples may be missing from
1042 /// blocks, we can fill in the gaps by setting the weights of all the
1043 /// blocks in the same equivalence class to the same weight. To compute
1044 /// the concept of equivalence, we use dominance and loop information.
1045 /// Two blocks B1 and B2 are in the same equivalence class if B1
1046 /// dominates B2, B2 post-dominates B1 and both are in the same loop.
1048 /// 3- Propagation of block weights into edges. This uses a simple
1049 /// propagation heuristic. The following rules are applied to every
1050 /// block BB in the CFG:
1052 /// - If BB has a single predecessor/successor, then the weight
1053 /// of that edge is the weight of the block.
1055 /// - If all the edges are known except one, and the weight of the
1056 /// block is already known, the weight of the unknown edge will
1057 /// be the weight of the block minus the sum of all the known
1058 /// edges. If the sum of all the known edges is larger than BB's weight,
1059 /// we set the unknown edge weight to zero.
1061 /// - If there is a self-referential edge, and the weight of the block is
1062 /// known, the weight for that edge is set to the weight of the block
1063 /// minus the weight of the other incoming edges to that block (if
1066 /// Since this propagation is not guaranteed to finalize for every CFG, we
1067 /// only allow it to proceed for a limited number of iterations (controlled
1068 /// by -sample-profile-max-propagate-iterations).
1070 /// FIXME: Try to replace this propagation heuristic with a scheme
1071 /// that is guaranteed to finalize. A work-list approach similar to
1072 /// the standard value propagation algorithm used by SSA-CCP might
1075 /// Once all the branch weights are computed, we emit the MD_prof
1076 /// metadata on BB using the computed values for each of its branches.
1078 /// \param F The function to query.
1080 /// \returns true if \p F was modified. Returns false, otherwise.
1081 bool SampleProfileLoader::emitAnnotations(Function &F) {
1082 bool Changed = false;
1084 if (getFunctionLoc(F) == 0)
1087 DEBUG(dbgs() << "Line number for the first instruction in " << F.getName()
1088 << ": " << getFunctionLoc(F) << "\n");
1090 Changed |= inlineHotFunctions(F);
1092 // Compute basic block weights.
1093 Changed |= computeBlockWeights(F);
1096 // Compute dominance and loop info needed for propagation.
1097 computeDominanceAndLoopInfo(F);
1099 // Find equivalence classes.
1100 findEquivalenceClasses(F);
1102 // Propagate weights to all edges.
1103 propagateWeights(F);
1106 // If coverage checking was requested, compute it now.
1107 if (SampleProfileRecordCoverage) {
1108 unsigned Used = CoverageTracker.countUsedRecords(Samples);
1109 unsigned Total = CoverageTracker.countBodyRecords(Samples);
1110 unsigned Coverage = CoverageTracker.computeCoverage(Used, Total);
1111 if (Coverage < SampleProfileRecordCoverage) {
1112 F.getContext().diagnose(DiagnosticInfoSampleProfile(
1113 getDISubprogram(&F)->getFilename(), getFunctionLoc(F),
1114 Twine(Used) + " of " + Twine(Total) + " available profile records (" +
1115 Twine(Coverage) + "%) were applied",
1120 if (SampleProfileSampleCoverage) {
1121 uint64_t Used = CoverageTracker.getTotalUsedSamples();
1122 uint64_t Total = CoverageTracker.countBodySamples(Samples);
1123 unsigned Coverage = CoverageTracker.computeCoverage(Used, Total);
1124 if (Coverage < SampleProfileSampleCoverage) {
1125 F.getContext().diagnose(DiagnosticInfoSampleProfile(
1126 getDISubprogram(&F)->getFilename(), getFunctionLoc(F),
1127 Twine(Used) + " of " + Twine(Total) + " available profile samples (" +
1128 Twine(Coverage) + "%) were applied",
1135 char SampleProfileLoader::ID = 0;
1136 INITIALIZE_PASS_BEGIN(SampleProfileLoader, "sample-profile",
1137 "Sample Profile loader", false, false)
1138 INITIALIZE_PASS_DEPENDENCY(AddDiscriminators)
1139 INITIALIZE_PASS_END(SampleProfileLoader, "sample-profile",
1140 "Sample Profile loader", false, false)
1142 bool SampleProfileLoader::doInitialization(Module &M) {
1143 auto &Ctx = M.getContext();
1144 auto ReaderOrErr = SampleProfileReader::create(Filename, Ctx);
1145 if (std::error_code EC = ReaderOrErr.getError()) {
1146 std::string Msg = "Could not open profile: " + EC.message();
1147 Ctx.diagnose(DiagnosticInfoSampleProfile(Filename, Msg));
1150 Reader = std::move(ReaderOrErr.get());
1151 ProfileIsValid = (Reader->read() == sampleprof_error::success);
1155 ModulePass *llvm::createSampleProfileLoaderPass() {
1156 return new SampleProfileLoader(SampleProfileFile);
1159 ModulePass *llvm::createSampleProfileLoaderPass(StringRef Name) {
1160 return new SampleProfileLoader(Name);
1163 bool SampleProfileLoader::runOnModule(Module &M) {
1164 if (!ProfileIsValid)
1167 bool retval = false;
1169 if (!F.isDeclaration()) {
1170 clearFunctionData();
1171 retval |= runOnFunction(F);
1176 bool SampleProfileLoader::runOnFunction(Function &F) {
1177 Samples = Reader->getSamplesFor(F);
1178 if (!Samples->empty())
1179 return emitAnnotations(F);