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> SampleProfileCoverage(
67 "sample-profile-check-coverage", cl::init(0), cl::value_desc("N"),
68 cl::desc("Emit a warning if less than N% of samples in the input profile "
69 "are matched to the IR."));
72 typedef DenseMap<const BasicBlock *, uint64_t> BlockWeightMap;
73 typedef DenseMap<const BasicBlock *, const BasicBlock *> EquivalenceClassMap;
74 typedef std::pair<const BasicBlock *, const BasicBlock *> Edge;
75 typedef DenseMap<Edge, uint64_t> EdgeWeightMap;
76 typedef DenseMap<const BasicBlock *, SmallVector<const BasicBlock *, 8>>
79 /// \brief Sample profile pass.
81 /// This pass reads profile data from the file specified by
82 /// -sample-profile-file and annotates every affected function with the
83 /// profile information found in that file.
84 class SampleProfileLoader : public ModulePass {
86 // Class identification, replacement for typeinfo
89 SampleProfileLoader(StringRef Name = SampleProfileFile)
90 : ModulePass(ID), DT(nullptr), PDT(nullptr), LI(nullptr), Reader(),
91 Samples(nullptr), Filename(Name), ProfileIsValid(false) {
92 initializeSampleProfileLoaderPass(*PassRegistry::getPassRegistry());
95 bool doInitialization(Module &M) override;
97 void dump() { Reader->dump(); }
99 const char *getPassName() const override { return "Sample profile pass"; }
101 bool runOnModule(Module &M) override;
103 void getAnalysisUsage(AnalysisUsage &AU) const override {
104 AU.setPreservesCFG();
108 bool runOnFunction(Function &F);
109 unsigned getFunctionLoc(Function &F);
110 bool emitAnnotations(Function &F);
111 ErrorOr<uint64_t> getInstWeight(const Instruction &I) const;
112 ErrorOr<uint64_t> getBlockWeight(const BasicBlock *BB) const;
113 const FunctionSamples *findCalleeFunctionSamples(const CallInst &I) const;
114 const FunctionSamples *findFunctionSamples(const Instruction &I) const;
115 bool inlineHotFunctions(Function &F);
116 void printEdgeWeight(raw_ostream &OS, Edge E);
117 void printBlockWeight(raw_ostream &OS, const BasicBlock *BB) const;
118 void printBlockEquivalence(raw_ostream &OS, const BasicBlock *BB);
119 bool computeBlockWeights(Function &F);
120 void findEquivalenceClasses(Function &F);
121 void findEquivalencesFor(BasicBlock *BB1,
122 SmallVector<BasicBlock *, 8> Descendants,
123 DominatorTreeBase<BasicBlock> *DomTree);
124 void propagateWeights(Function &F);
125 uint64_t visitEdge(Edge E, unsigned *NumUnknownEdges, Edge *UnknownEdge);
126 void buildEdges(Function &F);
127 bool propagateThroughEdges(Function &F);
128 void computeDominanceAndLoopInfo(Function &F);
129 unsigned getOffset(unsigned L, unsigned H) const;
130 void clearFunctionData();
132 /// \brief Map basic blocks to their computed weights.
134 /// The weight of a basic block is defined to be the maximum
135 /// of all the instruction weights in that block.
136 BlockWeightMap BlockWeights;
138 /// \brief Map edges to their computed weights.
140 /// Edge weights are computed by propagating basic block weights in
141 /// SampleProfile::propagateWeights.
142 EdgeWeightMap EdgeWeights;
144 /// \brief Set of visited blocks during propagation.
145 SmallPtrSet<const BasicBlock *, 128> VisitedBlocks;
147 /// \brief Set of visited edges during propagation.
148 SmallSet<Edge, 128> VisitedEdges;
150 /// \brief Equivalence classes for block weights.
152 /// Two blocks BB1 and BB2 are in the same equivalence class if they
153 /// dominate and post-dominate each other, and they are in the same loop
154 /// nest. When this happens, the two blocks are guaranteed to execute
155 /// the same number of times.
156 EquivalenceClassMap EquivalenceClass;
158 /// \brief Dominance, post-dominance and loop information.
159 std::unique_ptr<DominatorTree> DT;
160 std::unique_ptr<DominatorTreeBase<BasicBlock>> PDT;
161 std::unique_ptr<LoopInfo> LI;
163 /// \brief Predecessors for each basic block in the CFG.
164 BlockEdgeMap Predecessors;
166 /// \brief Successors for each basic block in the CFG.
167 BlockEdgeMap Successors;
169 /// \brief Profile reader object.
170 std::unique_ptr<SampleProfileReader> Reader;
172 /// \brief Samples collected for the body of this function.
173 FunctionSamples *Samples;
175 /// \brief Name of the profile file to load.
178 /// \brief Flag indicating whether the profile input loaded successfully.
182 class SampleCoverageTracker {
184 SampleCoverageTracker() : SampleCoverage() {}
186 void markSamplesUsed(const FunctionSamples *Samples, uint32_t LineOffset,
187 uint32_t Discriminator);
188 unsigned computeCoverage(const FunctionSamples *Samples) const;
189 unsigned getNumUsedSamples(const FunctionSamples *Samples) const;
192 typedef DenseMap<LineLocation, unsigned> BodySampleCoverageMap;
193 typedef DenseMap<const FunctionSamples *, BodySampleCoverageMap>
194 FunctionSamplesCoverageMap;
196 /// Coverage map for sampling records.
198 /// This map keeps a record of sampling records that have been matched to
199 /// an IR instruction. This is used to detect some form of staleness in
200 /// profiles (see flag -sample-profile-check-coverage).
202 /// Each entry in the map corresponds to a FunctionSamples instance. This is
203 /// another map that counts how many times the sample record at the
204 /// given location has been used.
205 FunctionSamplesCoverageMap SampleCoverage;
208 SampleCoverageTracker CoverageTracker;
211 /// Mark as used the sample record for the given function samples at
212 /// (LineOffset, Discriminator).
213 void SampleCoverageTracker::markSamplesUsed(const FunctionSamples *Samples,
215 uint32_t Discriminator) {
216 BodySampleCoverageMap &Coverage = SampleCoverage[Samples];
217 Coverage[LineLocation(LineOffset, Discriminator)]++;
220 /// Return the number of sample records that were applied from this profile.
222 SampleCoverageTracker::getNumUsedSamples(const FunctionSamples *Samples) const {
223 auto I = SampleCoverage.find(Samples);
224 return (I != SampleCoverage.end()) ? I->second.size() : 0;
227 /// Return the fraction of sample records used in this profile.
229 /// The returned value is an unsigned integer in the range 0-100 indicating
230 /// the percentage of sample records that were used while applying this
231 /// profile to the associated function.
233 SampleCoverageTracker::computeCoverage(const FunctionSamples *Samples) const {
234 uint32_t NumTotalRecords = Samples->getBodySamples().size();
235 uint32_t NumUsedRecords = getNumUsedSamples(Samples);
236 assert(NumUsedRecords <= NumTotalRecords &&
237 "number of used records cannot exceed the total number of records");
238 return NumTotalRecords > 0 ? NumUsedRecords * 100 / NumTotalRecords : 100;
241 /// Clear all the per-function data used to load samples and propagate weights.
242 void SampleProfileLoader::clearFunctionData() {
243 BlockWeights.clear();
245 VisitedBlocks.clear();
246 VisitedEdges.clear();
247 EquivalenceClass.clear();
251 Predecessors.clear();
255 /// \brief Returns the offset of lineno \p L to head_lineno \p H
258 /// \param H Header lineno of the function
260 /// \returns offset to the header lineno. 16 bits are used to represent offset.
261 /// We assume that a single function will not exceed 65535 LOC.
262 unsigned SampleProfileLoader::getOffset(unsigned L, unsigned H) const {
263 return (L - H) & 0xffff;
266 /// \brief Print the weight of edge \p E on stream \p OS.
268 /// \param OS Stream to emit the output to.
269 /// \param E Edge to print.
270 void SampleProfileLoader::printEdgeWeight(raw_ostream &OS, Edge E) {
271 OS << "weight[" << E.first->getName() << "->" << E.second->getName()
272 << "]: " << EdgeWeights[E] << "\n";
275 /// \brief Print the equivalence class of block \p BB on stream \p OS.
277 /// \param OS Stream to emit the output to.
278 /// \param BB Block to print.
279 void SampleProfileLoader::printBlockEquivalence(raw_ostream &OS,
280 const BasicBlock *BB) {
281 const BasicBlock *Equiv = EquivalenceClass[BB];
282 OS << "equivalence[" << BB->getName()
283 << "]: " << ((Equiv) ? EquivalenceClass[BB]->getName() : "NONE") << "\n";
286 /// \brief Print the weight of block \p BB on stream \p OS.
288 /// \param OS Stream to emit the output to.
289 /// \param BB Block to print.
290 void SampleProfileLoader::printBlockWeight(raw_ostream &OS,
291 const BasicBlock *BB) const {
292 const auto &I = BlockWeights.find(BB);
293 uint64_t W = (I == BlockWeights.end() ? 0 : I->second);
294 OS << "weight[" << BB->getName() << "]: " << W << "\n";
297 /// \brief Get the weight for an instruction.
299 /// The "weight" of an instruction \p Inst is the number of samples
300 /// collected on that instruction at runtime. To retrieve it, we
301 /// need to compute the line number of \p Inst relative to the start of its
302 /// function. We use HeaderLineno to compute the offset. We then
303 /// look up the samples collected for \p Inst using BodySamples.
305 /// \param Inst Instruction to query.
307 /// \returns the weight of \p Inst.
309 SampleProfileLoader::getInstWeight(const Instruction &Inst) const {
310 DebugLoc DLoc = Inst.getDebugLoc();
312 return std::error_code();
314 const FunctionSamples *FS = findFunctionSamples(Inst);
316 return std::error_code();
318 const DILocation *DIL = DLoc;
319 unsigned Lineno = DLoc.getLine();
320 unsigned HeaderLineno = DIL->getScope()->getSubprogram()->getLine();
322 uint32_t LineOffset = getOffset(Lineno, HeaderLineno);
323 uint32_t Discriminator = DIL->getDiscriminator();
324 ErrorOr<uint64_t> R = FS->findSamplesAt(LineOffset, Discriminator);
326 if (SampleProfileCoverage)
327 CoverageTracker.markSamplesUsed(FS, LineOffset, Discriminator);
328 DEBUG(dbgs() << " " << Lineno << "." << DIL->getDiscriminator() << ":"
329 << Inst << " (line offset: " << Lineno - HeaderLineno << "."
330 << DIL->getDiscriminator() << " - weight: " << R.get()
336 /// \brief Compute the weight of a basic block.
338 /// The weight of basic block \p BB is the maximum weight of all the
339 /// instructions in BB.
341 /// \param BB The basic block to query.
343 /// \returns the weight for \p BB.
345 SampleProfileLoader::getBlockWeight(const BasicBlock *BB) const {
348 for (auto &I : BB->getInstList()) {
349 const ErrorOr<uint64_t> &R = getInstWeight(I);
350 if (R && R.get() >= Weight) {
358 return std::error_code();
361 /// \brief Compute and store the weights of every basic block.
363 /// This populates the BlockWeights map by computing
364 /// the weights of every basic block in the CFG.
366 /// \param F The function to query.
367 bool SampleProfileLoader::computeBlockWeights(Function &F) {
368 bool Changed = false;
369 DEBUG(dbgs() << "Block weights\n");
370 for (const auto &BB : F) {
371 ErrorOr<uint64_t> Weight = getBlockWeight(&BB);
373 BlockWeights[&BB] = Weight.get();
374 VisitedBlocks.insert(&BB);
377 DEBUG(printBlockWeight(dbgs(), &BB));
380 if (SampleProfileCoverage) {
381 unsigned Coverage = CoverageTracker.computeCoverage(Samples);
382 if (Coverage < SampleProfileCoverage) {
383 StringRef Filename = getDISubprogram(&F)->getFilename();
384 F.getContext().diagnose(DiagnosticInfoSampleProfile(
385 Filename.str().c_str(), getFunctionLoc(F),
386 Twine(CoverageTracker.getNumUsedSamples(Samples)) + " of " +
387 Twine(Samples->getBodySamples().size()) +
388 " available profile records (" + Twine(Coverage) +
397 /// \brief Get the FunctionSamples for a call instruction.
399 /// The FunctionSamples of a call instruction \p Inst is the inlined
400 /// instance in which that call instruction is calling to. It contains
401 /// all samples that resides in the inlined instance. We first find the
402 /// inlined instance in which the call instruction is from, then we
403 /// traverse its children to find the callsite with the matching
404 /// location and callee function name.
406 /// \param Inst Call instruction to query.
408 /// \returns The FunctionSamples pointer to the inlined instance.
409 const FunctionSamples *
410 SampleProfileLoader::findCalleeFunctionSamples(const CallInst &Inst) const {
411 const DILocation *DIL = Inst.getDebugLoc();
415 DISubprogram *SP = DIL->getScope()->getSubprogram();
419 Function *CalleeFunc = Inst.getCalledFunction();
424 StringRef CalleeName = CalleeFunc->getName();
425 const FunctionSamples *FS = findFunctionSamples(Inst);
429 return FS->findFunctionSamplesAt(
430 CallsiteLocation(getOffset(DIL->getLine(), SP->getLine()),
431 DIL->getDiscriminator(), CalleeName));
434 /// \brief Get the FunctionSamples for an instruction.
436 /// The FunctionSamples of an instruction \p Inst is the inlined instance
437 /// in which that instruction is coming from. We traverse the inline stack
438 /// of that instruction, and match it with the tree nodes in the profile.
440 /// \param Inst Instruction to query.
442 /// \returns the FunctionSamples pointer to the inlined instance.
443 const FunctionSamples *
444 SampleProfileLoader::findFunctionSamples(const Instruction &Inst) const {
445 SmallVector<CallsiteLocation, 10> S;
446 const DILocation *DIL = Inst.getDebugLoc();
450 StringRef CalleeName;
451 for (const DILocation *DIL = Inst.getDebugLoc(); DIL;
452 DIL = DIL->getInlinedAt()) {
453 DISubprogram *SP = DIL->getScope()->getSubprogram();
456 if (!CalleeName.empty()) {
457 S.push_back(CallsiteLocation(getOffset(DIL->getLine(), SP->getLine()),
458 DIL->getDiscriminator(), CalleeName));
460 CalleeName = SP->getLinkageName();
464 const FunctionSamples *FS = Samples;
465 for (int i = S.size() - 1; i >= 0 && FS != nullptr; i--) {
466 FS = FS->findFunctionSamplesAt(S[i]);
471 /// \brief Iteratively inline hot callsites of a function.
473 /// Iteratively traverse all callsites of the function \p F, and find if
474 /// the corresponding inlined instance exists and is hot in profile. If
475 /// it is hot enough, inline the callsites and adds new callsites of the
476 /// callee into the caller.
478 /// TODO: investigate the possibility of not invoking InlineFunction directly.
480 /// \param F function to perform iterative inlining.
482 /// \returns True if there is any inline happened.
483 bool SampleProfileLoader::inlineHotFunctions(Function &F) {
484 bool Changed = false;
485 LLVMContext &Ctx = F.getContext();
487 bool LocalChanged = false;
488 SmallVector<CallInst *, 10> CIS;
490 for (auto &I : BB.getInstList()) {
491 CallInst *CI = dyn_cast<CallInst>(&I);
493 const FunctionSamples *FS = findCalleeFunctionSamples(*CI);
494 if (FS && FS->getTotalSamples() > 0) {
500 for (auto CI : CIS) {
501 InlineFunctionInfo IFI;
502 Function *CalledFunction = CI->getCalledFunction();
503 DebugLoc DLoc = CI->getDebugLoc();
504 uint64_t NumSamples = findCalleeFunctionSamples(*CI)->getTotalSamples();
505 if (InlineFunction(CI, IFI)) {
507 emitOptimizationRemark(Ctx, DEBUG_TYPE, F, DLoc,
508 Twine("inlined hot callee '") +
509 CalledFunction->getName() + "' with " +
510 Twine(NumSamples) + " samples into '" +
523 /// \brief Find equivalence classes for the given block.
525 /// This finds all the blocks that are guaranteed to execute the same
526 /// number of times as \p BB1. To do this, it traverses all the
527 /// descendants of \p BB1 in the dominator or post-dominator tree.
529 /// A block BB2 will be in the same equivalence class as \p BB1 if
530 /// the following holds:
532 /// 1- \p BB1 is a descendant of BB2 in the opposite tree. So, if BB2
533 /// is a descendant of \p BB1 in the dominator tree, then BB2 should
534 /// dominate BB1 in the post-dominator tree.
536 /// 2- Both BB2 and \p BB1 must be in the same loop.
538 /// For every block BB2 that meets those two requirements, we set BB2's
539 /// equivalence class to \p BB1.
541 /// \param BB1 Block to check.
542 /// \param Descendants Descendants of \p BB1 in either the dom or pdom tree.
543 /// \param DomTree Opposite dominator tree. If \p Descendants is filled
544 /// with blocks from \p BB1's dominator tree, then
545 /// this is the post-dominator tree, and vice versa.
546 void SampleProfileLoader::findEquivalencesFor(
547 BasicBlock *BB1, SmallVector<BasicBlock *, 8> Descendants,
548 DominatorTreeBase<BasicBlock> *DomTree) {
549 const BasicBlock *EC = EquivalenceClass[BB1];
550 uint64_t Weight = BlockWeights[EC];
551 for (const auto *BB2 : Descendants) {
552 bool IsDomParent = DomTree->dominates(BB2, BB1);
553 bool IsInSameLoop = LI->getLoopFor(BB1) == LI->getLoopFor(BB2);
554 if (BB1 != BB2 && IsDomParent && IsInSameLoop) {
555 EquivalenceClass[BB2] = EC;
557 // If BB2 is heavier than BB1, make BB2 have the same weight
560 // Note that we don't worry about the opposite situation here
561 // (when BB2 is lighter than BB1). We will deal with this
562 // during the propagation phase. Right now, we just want to
563 // make sure that BB1 has the largest weight of all the
564 // members of its equivalence set.
565 Weight = std::max(Weight, BlockWeights[BB2]);
568 BlockWeights[EC] = Weight;
571 /// \brief Find equivalence classes.
573 /// Since samples may be missing from blocks, we can fill in the gaps by setting
574 /// the weights of all the blocks in the same equivalence class to the same
575 /// weight. To compute the concept of equivalence, we use dominance and loop
576 /// information. Two blocks B1 and B2 are in the same equivalence class if B1
577 /// dominates B2, B2 post-dominates B1 and both are in the same loop.
579 /// \param F The function to query.
580 void SampleProfileLoader::findEquivalenceClasses(Function &F) {
581 SmallVector<BasicBlock *, 8> DominatedBBs;
582 DEBUG(dbgs() << "\nBlock equivalence classes\n");
583 // Find equivalence sets based on dominance and post-dominance information.
585 BasicBlock *BB1 = &BB;
587 // Compute BB1's equivalence class once.
588 if (EquivalenceClass.count(BB1)) {
589 DEBUG(printBlockEquivalence(dbgs(), BB1));
593 // By default, blocks are in their own equivalence class.
594 EquivalenceClass[BB1] = BB1;
596 // Traverse all the blocks dominated by BB1. We are looking for
597 // every basic block BB2 such that:
599 // 1- BB1 dominates BB2.
600 // 2- BB2 post-dominates BB1.
601 // 3- BB1 and BB2 are in the same loop nest.
603 // If all those conditions hold, it means that BB2 is executed
604 // as many times as BB1, so they are placed in the same equivalence
605 // class by making BB2's equivalence class be BB1.
606 DominatedBBs.clear();
607 DT->getDescendants(BB1, DominatedBBs);
608 findEquivalencesFor(BB1, DominatedBBs, PDT.get());
610 DEBUG(printBlockEquivalence(dbgs(), BB1));
613 // Assign weights to equivalence classes.
615 // All the basic blocks in the same equivalence class will execute
616 // the same number of times. Since we know that the head block in
617 // each equivalence class has the largest weight, assign that weight
618 // to all the blocks in that equivalence class.
619 DEBUG(dbgs() << "\nAssign the same weight to all blocks in the same class\n");
621 const BasicBlock *BB = &BI;
622 const BasicBlock *EquivBB = EquivalenceClass[BB];
624 BlockWeights[BB] = BlockWeights[EquivBB];
625 DEBUG(printBlockWeight(dbgs(), BB));
629 /// \brief Visit the given edge to decide if it has a valid weight.
631 /// If \p E has not been visited before, we copy to \p UnknownEdge
632 /// and increment the count of unknown edges.
634 /// \param E Edge to visit.
635 /// \param NumUnknownEdges Current number of unknown edges.
636 /// \param UnknownEdge Set if E has not been visited before.
638 /// \returns E's weight, if known. Otherwise, return 0.
639 uint64_t SampleProfileLoader::visitEdge(Edge E, unsigned *NumUnknownEdges,
641 if (!VisitedEdges.count(E)) {
642 (*NumUnknownEdges)++;
647 return EdgeWeights[E];
650 /// \brief Propagate weights through incoming/outgoing edges.
652 /// If the weight of a basic block is known, and there is only one edge
653 /// with an unknown weight, we can calculate the weight of that edge.
655 /// Similarly, if all the edges have a known count, we can calculate the
656 /// count of the basic block, if needed.
658 /// \param F Function to process.
660 /// \returns True if new weights were assigned to edges or blocks.
661 bool SampleProfileLoader::propagateThroughEdges(Function &F) {
662 bool Changed = false;
663 DEBUG(dbgs() << "\nPropagation through edges\n");
664 for (const auto &BI : F) {
665 const BasicBlock *BB = &BI;
666 const BasicBlock *EC = EquivalenceClass[BB];
668 // Visit all the predecessor and successor edges to determine
669 // which ones have a weight assigned already. Note that it doesn't
670 // matter that we only keep track of a single unknown edge. The
671 // only case we are interested in handling is when only a single
672 // edge is unknown (see setEdgeOrBlockWeight).
673 for (unsigned i = 0; i < 2; i++) {
674 uint64_t TotalWeight = 0;
675 unsigned NumUnknownEdges = 0;
676 Edge UnknownEdge, SelfReferentialEdge;
679 // First, visit all predecessor edges.
680 for (auto *Pred : Predecessors[BB]) {
681 Edge E = std::make_pair(Pred, BB);
682 TotalWeight += visitEdge(E, &NumUnknownEdges, &UnknownEdge);
683 if (E.first == E.second)
684 SelfReferentialEdge = E;
687 // On the second round, visit all successor edges.
688 for (auto *Succ : Successors[BB]) {
689 Edge E = std::make_pair(BB, Succ);
690 TotalWeight += visitEdge(E, &NumUnknownEdges, &UnknownEdge);
694 // After visiting all the edges, there are three cases that we
695 // can handle immediately:
697 // - All the edge weights are known (i.e., NumUnknownEdges == 0).
698 // In this case, we simply check that the sum of all the edges
699 // is the same as BB's weight. If not, we change BB's weight
700 // to match. Additionally, if BB had not been visited before,
701 // we mark it visited.
703 // - Only one edge is unknown and BB has already been visited.
704 // In this case, we can compute the weight of the edge by
705 // subtracting the total block weight from all the known
706 // edge weights. If the edges weight more than BB, then the
707 // edge of the last remaining edge is set to zero.
709 // - There exists a self-referential edge and the weight of BB is
710 // known. In this case, this edge can be based on BB's weight.
711 // We add up all the other known edges and set the weight on
712 // the self-referential edge as we did in the previous case.
714 // In any other case, we must continue iterating. Eventually,
715 // all edges will get a weight, or iteration will stop when
716 // it reaches SampleProfileMaxPropagateIterations.
717 if (NumUnknownEdges <= 1) {
718 uint64_t &BBWeight = BlockWeights[EC];
719 if (NumUnknownEdges == 0) {
720 // If we already know the weight of all edges, the weight of the
721 // basic block can be computed. It should be no larger than the sum
722 // of all edge weights.
723 if (TotalWeight > BBWeight) {
724 BBWeight = TotalWeight;
726 DEBUG(dbgs() << "All edge weights for " << BB->getName()
727 << " known. Set weight for block: ";
728 printBlockWeight(dbgs(), BB););
730 if (VisitedBlocks.insert(EC).second)
732 } else if (NumUnknownEdges == 1 && VisitedBlocks.count(EC)) {
733 // If there is a single unknown edge and the block has been
734 // visited, then we can compute E's weight.
735 if (BBWeight >= TotalWeight)
736 EdgeWeights[UnknownEdge] = BBWeight - TotalWeight;
738 EdgeWeights[UnknownEdge] = 0;
739 VisitedEdges.insert(UnknownEdge);
741 DEBUG(dbgs() << "Set weight for edge: ";
742 printEdgeWeight(dbgs(), UnknownEdge));
744 } else if (SelfReferentialEdge.first && VisitedBlocks.count(EC)) {
745 uint64_t &BBWeight = BlockWeights[BB];
746 // We have a self-referential edge and the weight of BB is known.
747 if (BBWeight >= TotalWeight)
748 EdgeWeights[SelfReferentialEdge] = BBWeight - TotalWeight;
750 EdgeWeights[SelfReferentialEdge] = 0;
751 VisitedEdges.insert(SelfReferentialEdge);
753 DEBUG(dbgs() << "Set self-referential edge weight to: ";
754 printEdgeWeight(dbgs(), SelfReferentialEdge));
762 /// \brief Build in/out edge lists for each basic block in the CFG.
764 /// We are interested in unique edges. If a block B1 has multiple
765 /// edges to another block B2, we only add a single B1->B2 edge.
766 void SampleProfileLoader::buildEdges(Function &F) {
768 BasicBlock *B1 = &BI;
770 // Add predecessors for B1.
771 SmallPtrSet<BasicBlock *, 16> Visited;
772 if (!Predecessors[B1].empty())
773 llvm_unreachable("Found a stale predecessors list in a basic block.");
774 for (pred_iterator PI = pred_begin(B1), PE = pred_end(B1); PI != PE; ++PI) {
775 BasicBlock *B2 = *PI;
776 if (Visited.insert(B2).second)
777 Predecessors[B1].push_back(B2);
780 // Add successors for B1.
782 if (!Successors[B1].empty())
783 llvm_unreachable("Found a stale successors list in a basic block.");
784 for (succ_iterator SI = succ_begin(B1), SE = succ_end(B1); SI != SE; ++SI) {
785 BasicBlock *B2 = *SI;
786 if (Visited.insert(B2).second)
787 Successors[B1].push_back(B2);
792 /// \brief Propagate weights into edges
794 /// The following rules are applied to every block BB in the CFG:
796 /// - If BB has a single predecessor/successor, then the weight
797 /// of that edge is the weight of the block.
799 /// - If all incoming or outgoing edges are known except one, and the
800 /// weight of the block is already known, the weight of the unknown
801 /// edge will be the weight of the block minus the sum of all the known
802 /// edges. If the sum of all the known edges is larger than BB's weight,
803 /// we set the unknown edge weight to zero.
805 /// - If there is a self-referential edge, and the weight of the block is
806 /// known, the weight for that edge is set to the weight of the block
807 /// minus the weight of the other incoming edges to that block (if
809 void SampleProfileLoader::propagateWeights(Function &F) {
813 // Add an entry count to the function using the samples gathered
814 // at the function entry.
815 F.setEntryCount(Samples->getHeadSamples());
817 // Before propagation starts, build, for each block, a list of
818 // unique predecessors and successors. This is necessary to handle
819 // identical edges in multiway branches. Since we visit all blocks and all
820 // edges of the CFG, it is cleaner to build these lists once at the start
824 // Propagate until we converge or we go past the iteration limit.
825 while (Changed && I++ < SampleProfileMaxPropagateIterations) {
826 Changed = propagateThroughEdges(F);
829 // Generate MD_prof metadata for every branch instruction using the
830 // edge weights computed during propagation.
831 DEBUG(dbgs() << "\nPropagation complete. Setting branch weights\n");
832 LLVMContext &Ctx = F.getContext();
835 BasicBlock *BB = &BI;
836 TerminatorInst *TI = BB->getTerminator();
837 if (TI->getNumSuccessors() == 1)
839 if (!isa<BranchInst>(TI) && !isa<SwitchInst>(TI))
842 DEBUG(dbgs() << "\nGetting weights for branch at line "
843 << TI->getDebugLoc().getLine() << ".\n");
844 SmallVector<uint32_t, 4> Weights;
845 uint32_t MaxWeight = 0;
847 for (unsigned I = 0; I < TI->getNumSuccessors(); ++I) {
848 BasicBlock *Succ = TI->getSuccessor(I);
849 Edge E = std::make_pair(BB, Succ);
850 uint64_t Weight = EdgeWeights[E];
851 DEBUG(dbgs() << "\t"; printEdgeWeight(dbgs(), E));
852 // Use uint32_t saturated arithmetic to adjust the incoming weights,
853 // if needed. Sample counts in profiles are 64-bit unsigned values,
854 // but internally branch weights are expressed as 32-bit values.
855 if (Weight > std::numeric_limits<uint32_t>::max()) {
856 DEBUG(dbgs() << " (saturated due to uint32_t overflow)");
857 Weight = std::numeric_limits<uint32_t>::max();
859 Weights.push_back(static_cast<uint32_t>(Weight));
861 if (Weight > MaxWeight) {
863 MaxDestLoc = Succ->getFirstNonPHIOrDbgOrLifetime()->getDebugLoc();
868 // Only set weights if there is at least one non-zero weight.
869 // In any other case, let the analyzer set weights.
871 DEBUG(dbgs() << "SUCCESS. Found non-zero weights.\n");
872 TI->setMetadata(llvm::LLVMContext::MD_prof,
873 MDB.createBranchWeights(Weights));
874 DebugLoc BranchLoc = TI->getDebugLoc();
875 emitOptimizationRemark(
876 Ctx, DEBUG_TYPE, F, MaxDestLoc,
877 Twine("most popular destination for conditional branches at ") +
878 ((BranchLoc) ? Twine(BranchLoc->getFilename() + ":" +
879 Twine(BranchLoc.getLine()) + ":" +
880 Twine(BranchLoc.getCol()))
881 : Twine("<UNKNOWN LOCATION>")));
883 DEBUG(dbgs() << "SKIPPED. All branch weights are zero.\n");
888 /// \brief Get the line number for the function header.
890 /// This looks up function \p F in the current compilation unit and
891 /// retrieves the line number where the function is defined. This is
892 /// line 0 for all the samples read from the profile file. Every line
893 /// number is relative to this line.
895 /// \param F Function object to query.
897 /// \returns the line number where \p F is defined. If it returns 0,
898 /// it means that there is no debug information available for \p F.
899 unsigned SampleProfileLoader::getFunctionLoc(Function &F) {
900 if (DISubprogram *S = getDISubprogram(&F))
903 // If the start of \p F is missing, emit a diagnostic to inform the user
904 // about the missed opportunity.
905 F.getContext().diagnose(DiagnosticInfoSampleProfile(
906 "No debug information found in function " + F.getName() +
907 ": Function profile not used",
912 void SampleProfileLoader::computeDominanceAndLoopInfo(Function &F) {
913 DT.reset(new DominatorTree);
916 PDT.reset(new DominatorTreeBase<BasicBlock>(true));
919 LI.reset(new LoopInfo);
923 /// \brief Generate branch weight metadata for all branches in \p F.
925 /// Branch weights are computed out of instruction samples using a
926 /// propagation heuristic. Propagation proceeds in 3 phases:
928 /// 1- Assignment of block weights. All the basic blocks in the function
929 /// are initial assigned the same weight as their most frequently
930 /// executed instruction.
932 /// 2- Creation of equivalence classes. Since samples may be missing from
933 /// blocks, we can fill in the gaps by setting the weights of all the
934 /// blocks in the same equivalence class to the same weight. To compute
935 /// the concept of equivalence, we use dominance and loop information.
936 /// Two blocks B1 and B2 are in the same equivalence class if B1
937 /// dominates B2, B2 post-dominates B1 and both are in the same loop.
939 /// 3- Propagation of block weights into edges. This uses a simple
940 /// propagation heuristic. The following rules are applied to every
941 /// block BB in the CFG:
943 /// - If BB has a single predecessor/successor, then the weight
944 /// of that edge is the weight of the block.
946 /// - If all the edges are known except one, and the weight of the
947 /// block is already known, the weight of the unknown edge will
948 /// be the weight of the block minus the sum of all the known
949 /// edges. If the sum of all the known edges is larger than BB's weight,
950 /// we set the unknown edge weight to zero.
952 /// - If there is a self-referential edge, and the weight of the block is
953 /// known, the weight for that edge is set to the weight of the block
954 /// minus the weight of the other incoming edges to that block (if
957 /// Since this propagation is not guaranteed to finalize for every CFG, we
958 /// only allow it to proceed for a limited number of iterations (controlled
959 /// by -sample-profile-max-propagate-iterations).
961 /// FIXME: Try to replace this propagation heuristic with a scheme
962 /// that is guaranteed to finalize. A work-list approach similar to
963 /// the standard value propagation algorithm used by SSA-CCP might
966 /// Once all the branch weights are computed, we emit the MD_prof
967 /// metadata on BB using the computed values for each of its branches.
969 /// \param F The function to query.
971 /// \returns true if \p F was modified. Returns false, otherwise.
972 bool SampleProfileLoader::emitAnnotations(Function &F) {
973 bool Changed = false;
975 if (getFunctionLoc(F) == 0)
978 DEBUG(dbgs() << "Line number for the first instruction in " << F.getName()
979 << ": " << getFunctionLoc(F) << "\n");
981 Changed |= inlineHotFunctions(F);
983 // Compute basic block weights.
984 Changed |= computeBlockWeights(F);
987 // Compute dominance and loop info needed for propagation.
988 computeDominanceAndLoopInfo(F);
990 // Find equivalence classes.
991 findEquivalenceClasses(F);
993 // Propagate weights to all edges.
1000 char SampleProfileLoader::ID = 0;
1001 INITIALIZE_PASS_BEGIN(SampleProfileLoader, "sample-profile",
1002 "Sample Profile loader", false, false)
1003 INITIALIZE_PASS_DEPENDENCY(AddDiscriminators)
1004 INITIALIZE_PASS_END(SampleProfileLoader, "sample-profile",
1005 "Sample Profile loader", false, false)
1007 bool SampleProfileLoader::doInitialization(Module &M) {
1008 auto &Ctx = M.getContext();
1009 auto ReaderOrErr = SampleProfileReader::create(Filename, Ctx);
1010 if (std::error_code EC = ReaderOrErr.getError()) {
1011 std::string Msg = "Could not open profile: " + EC.message();
1012 Ctx.diagnose(DiagnosticInfoSampleProfile(Filename.data(), Msg));
1015 Reader = std::move(ReaderOrErr.get());
1016 ProfileIsValid = (Reader->read() == sampleprof_error::success);
1020 ModulePass *llvm::createSampleProfileLoaderPass() {
1021 return new SampleProfileLoader(SampleProfileFile);
1024 ModulePass *llvm::createSampleProfileLoaderPass(StringRef Name) {
1025 return new SampleProfileLoader(Name);
1028 bool SampleProfileLoader::runOnModule(Module &M) {
1029 if (!ProfileIsValid)
1032 bool retval = false;
1034 if (!F.isDeclaration()) {
1035 clearFunctionData();
1036 retval |= runOnFunction(F);
1041 bool SampleProfileLoader::runOnFunction(Function &F) {
1042 Samples = Reader->getSamplesFor(F);
1043 if (!Samples->empty())
1044 return emitAnnotations(F);