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."));
68 typedef DenseMap<const BasicBlock *, unsigned> BlockWeightMap;
69 typedef DenseMap<const BasicBlock *, const BasicBlock *> EquivalenceClassMap;
70 typedef std::pair<const BasicBlock *, const BasicBlock *> Edge;
71 typedef DenseMap<Edge, unsigned> EdgeWeightMap;
72 typedef DenseMap<const BasicBlock *, SmallVector<const BasicBlock *, 8>>
75 /// \brief Sample profile pass.
77 /// This pass reads profile data from the file specified by
78 /// -sample-profile-file and annotates every affected function with the
79 /// profile information found in that file.
80 class SampleProfileLoader : public ModulePass {
82 // Class identification, replacement for typeinfo
85 SampleProfileLoader(StringRef Name = SampleProfileFile)
86 : ModulePass(ID), DT(nullptr), PDT(nullptr), LI(nullptr), Reader(),
87 Samples(nullptr), Filename(Name), ProfileIsValid(false) {
88 initializeSampleProfileLoaderPass(*PassRegistry::getPassRegistry());
91 bool doInitialization(Module &M) override;
93 void dump() { Reader->dump(); }
95 const char *getPassName() const override { return "Sample profile pass"; }
97 bool runOnModule(Module &M) override;
99 void getAnalysisUsage(AnalysisUsage &AU) const override {
100 AU.setPreservesCFG();
104 bool runOnFunction(Function &F);
105 unsigned getFunctionLoc(Function &F);
106 bool emitAnnotations(Function &F);
107 ErrorOr<unsigned> getInstWeight(const Instruction &I) const;
108 ErrorOr<unsigned> getBlockWeight(const BasicBlock *BB) const;
109 const FunctionSamples *findCalleeFunctionSamples(const CallInst &I) const;
110 const FunctionSamples *findFunctionSamples(const Instruction &I) const;
111 bool inlineHotFunctions(Function &F);
112 void printEdgeWeight(raw_ostream &OS, Edge E);
113 void printBlockWeight(raw_ostream &OS, const BasicBlock *BB) const;
114 void printBlockEquivalence(raw_ostream &OS, const BasicBlock *BB);
115 bool computeBlockWeights(Function &F);
116 void findEquivalenceClasses(Function &F);
117 void findEquivalencesFor(BasicBlock *BB1,
118 SmallVector<BasicBlock *, 8> Descendants,
119 DominatorTreeBase<BasicBlock> *DomTree);
120 void propagateWeights(Function &F);
121 unsigned visitEdge(Edge E, unsigned *NumUnknownEdges, Edge *UnknownEdge);
122 void buildEdges(Function &F);
123 bool propagateThroughEdges(Function &F);
124 void computeDominanceAndLoopInfo(Function &F);
126 /// \brief Line number for the function header. Used to compute absolute
127 /// line numbers from the relative line numbers found in the profile.
128 unsigned HeaderLineno;
130 /// \brief Map basic blocks to their computed weights.
132 /// The weight of a basic block is defined to be the maximum
133 /// of all the instruction weights in that block.
134 BlockWeightMap BlockWeights;
136 /// \brief Map edges to their computed weights.
138 /// Edge weights are computed by propagating basic block weights in
139 /// SampleProfile::propagateWeights.
140 EdgeWeightMap EdgeWeights;
142 /// \brief Set of visited blocks during propagation.
143 SmallPtrSet<const BasicBlock *, 128> VisitedBlocks;
145 /// \brief Set of visited edges during propagation.
146 SmallSet<Edge, 128> VisitedEdges;
148 /// \brief Equivalence classes for block weights.
150 /// Two blocks BB1 and BB2 are in the same equivalence class if they
151 /// dominate and post-dominate each other, and they are in the same loop
152 /// nest. When this happens, the two blocks are guaranteed to execute
153 /// the same number of times.
154 EquivalenceClassMap EquivalenceClass;
156 /// \brief Dominance, post-dominance and loop information.
157 std::unique_ptr<DominatorTree> DT;
158 std::unique_ptr<DominatorTreeBase<BasicBlock>> PDT;
159 std::unique_ptr<LoopInfo> LI;
161 /// \brief Predecessors for each basic block in the CFG.
162 BlockEdgeMap Predecessors;
164 /// \brief Successors for each basic block in the CFG.
165 BlockEdgeMap Successors;
167 /// \brief Profile reader object.
168 std::unique_ptr<SampleProfileReader> Reader;
170 /// \brief Samples collected for the body of this function.
171 FunctionSamples *Samples;
173 /// \brief Name of the profile file to load.
176 /// \brief Flag indicating whether the profile input loaded successfully.
181 /// \brief Print the weight of edge \p E on stream \p OS.
183 /// \param OS Stream to emit the output to.
184 /// \param E Edge to print.
185 void SampleProfileLoader::printEdgeWeight(raw_ostream &OS, Edge E) {
186 OS << "weight[" << E.first->getName() << "->" << E.second->getName()
187 << "]: " << EdgeWeights[E] << "\n";
190 /// \brief Print the equivalence class of block \p BB on stream \p OS.
192 /// \param OS Stream to emit the output to.
193 /// \param BB Block to print.
194 void SampleProfileLoader::printBlockEquivalence(raw_ostream &OS,
195 const BasicBlock *BB) {
196 const BasicBlock *Equiv = EquivalenceClass[BB];
197 OS << "equivalence[" << BB->getName()
198 << "]: " << ((Equiv) ? EquivalenceClass[BB]->getName() : "NONE") << "\n";
201 /// \brief Print the weight of block \p BB on stream \p OS.
203 /// \param OS Stream to emit the output to.
204 /// \param BB Block to print.
205 void SampleProfileLoader::printBlockWeight(raw_ostream &OS,
206 const BasicBlock *BB) const {
207 const auto &I = BlockWeights.find(BB);
208 unsigned W = (I == BlockWeights.end() ? 0 : I->second);
209 OS << "weight[" << BB->getName() << "]: " << W << "\n";
212 /// \brief Get the weight for an instruction.
214 /// The "weight" of an instruction \p Inst is the number of samples
215 /// collected on that instruction at runtime. To retrieve it, we
216 /// need to compute the line number of \p Inst relative to the start of its
217 /// function. We use HeaderLineno to compute the offset. We then
218 /// look up the samples collected for \p Inst using BodySamples.
220 /// \param Inst Instruction to query.
222 /// \returns the weight of \p Inst.
224 SampleProfileLoader::getInstWeight(const Instruction &Inst) const {
225 DebugLoc DLoc = Inst.getDebugLoc();
227 return std::error_code();
229 unsigned Lineno = DLoc.getLine();
230 if (Lineno < HeaderLineno)
231 return std::error_code();
233 const DILocation *DIL = DLoc;
234 const FunctionSamples *FS = findFunctionSamples(Inst);
236 return std::error_code();
237 ErrorOr<unsigned> R =
238 FS->findSamplesAt(Lineno - HeaderLineno, DIL->getDiscriminator());
240 DEBUG(dbgs() << " " << Lineno << "." << DIL->getDiscriminator() << ":"
241 << Inst << " (line offset: " << Lineno - HeaderLineno << "."
242 << DIL->getDiscriminator() << " - weight: " << R.get()
247 /// \brief Compute the weight of a basic block.
249 /// The weight of basic block \p BB is the maximum weight of all the
250 /// instructions in BB.
252 /// \param BB The basic block to query.
254 /// \returns the weight for \p BB.
256 SampleProfileLoader::getBlockWeight(const BasicBlock *BB) const {
259 for (auto &I : BB->getInstList()) {
260 const ErrorOr<unsigned> &R = getInstWeight(I);
261 if (R && R.get() >= Weight) {
269 return std::error_code();
272 /// \brief Compute and store the weights of every basic block.
274 /// This populates the BlockWeights map by computing
275 /// the weights of every basic block in the CFG.
277 /// \param F The function to query.
278 bool SampleProfileLoader::computeBlockWeights(Function &F) {
279 bool Changed = false;
280 DEBUG(dbgs() << "Block weights\n");
281 for (const auto &BB : F) {
282 ErrorOr<unsigned> Weight = getBlockWeight(&BB);
284 BlockWeights[&BB] = Weight.get();
287 DEBUG(printBlockWeight(dbgs(), &BB));
293 /// \brief Get the FunctionSamples for a call instruction.
295 /// The FunctionSamples of a call instruction \p Inst is the inlined
296 /// instance in which that call instruction is calling to. It contains
297 /// all samples that resides in the inlined instance. We first find the
298 /// inlined instance in which the call instruction is from, then we
299 /// traverse its children to find the callsite with the matching
300 /// location and callee function name.
302 /// \param Inst Call instruction to query.
304 /// \returns The FunctionSamples pointer to the inlined instance.
305 const FunctionSamples *
306 SampleProfileLoader::findCalleeFunctionSamples(const CallInst &Inst) const {
307 const DILocation *DIL = Inst.getDebugLoc();
311 DISubprogram *SP = DIL->getScope()->getSubprogram();
312 if (!SP || DIL->getLine() < SP->getLine())
315 Function *CalleeFunc = Inst.getCalledFunction();
320 StringRef CalleeName = CalleeFunc->getName();
321 const FunctionSamples *FS = findFunctionSamples(Inst);
325 return FS->findFunctionSamplesAt(CallsiteLocation(
326 DIL->getLine() - SP->getLine(), DIL->getDiscriminator(), CalleeName));
329 /// \brief Get the FunctionSamples for an instruction.
331 /// The FunctionSamples of an instruction \p Inst is the inlined instance
332 /// in which that instruction is coming from. We traverse the inline stack
333 /// of that instruction, and match it with the tree nodes in the profile.
335 /// \param Inst Instruction to query.
337 /// \returns the FunctionSamples pointer to the inlined instance.
338 const FunctionSamples *
339 SampleProfileLoader::findFunctionSamples(const Instruction &Inst) const {
340 SmallVector<CallsiteLocation, 10> S;
341 const DILocation *DIL = Inst.getDebugLoc();
345 StringRef CalleeName;
346 for (const DILocation *DIL = Inst.getDebugLoc(); DIL;
347 DIL = DIL->getInlinedAt()) {
348 DISubprogram *SP = DIL->getScope()->getSubprogram();
349 if (!SP || DIL->getLine() < SP->getLine())
351 if (!CalleeName.empty()) {
352 S.push_back(CallsiteLocation(DIL->getLine() - SP->getLine(),
353 DIL->getDiscriminator(), CalleeName));
355 CalleeName = SP->getLinkageName();
359 const FunctionSamples *FS = Samples;
360 for (int i = S.size() - 1; i >= 0 && FS != nullptr; i--) {
361 FS = FS->findFunctionSamplesAt(S[i]);
366 /// \brief Iteratively inline hot callsites of a function.
368 /// Iteratively traverse all callsites of the function \p F, and find if
369 /// the corresponding inlined instance exists and is hot in profile. If
370 /// it is hot enough, inline the callsites and adds new callsites of the
371 /// callee into the caller.
373 /// TODO: investigate the possibility of not invoking InlineFunction directly.
375 /// \param F function to perform iterative inlining.
377 /// \returns True if there is any inline happened.
378 bool SampleProfileLoader::inlineHotFunctions(Function &F) {
379 bool Changed = false;
381 bool LocalChanged = false;
382 SmallVector<CallInst *, 10> CIS;
384 for (auto &I : BB.getInstList()) {
385 CallInst *CI = dyn_cast<CallInst>(&I);
387 const FunctionSamples *FS = findCalleeFunctionSamples(*CI);
388 if (FS && FS->getTotalSamples() > 0) {
394 for (auto CI : CIS) {
395 InlineFunctionInfo IFI;
396 if (InlineFunction(CI, IFI))
408 /// \brief Find equivalence classes for the given block.
410 /// This finds all the blocks that are guaranteed to execute the same
411 /// number of times as \p BB1. To do this, it traverses all the
412 /// descendants of \p BB1 in the dominator or post-dominator tree.
414 /// A block BB2 will be in the same equivalence class as \p BB1 if
415 /// the following holds:
417 /// 1- \p BB1 is a descendant of BB2 in the opposite tree. So, if BB2
418 /// is a descendant of \p BB1 in the dominator tree, then BB2 should
419 /// dominate BB1 in the post-dominator tree.
421 /// 2- Both BB2 and \p BB1 must be in the same loop.
423 /// For every block BB2 that meets those two requirements, we set BB2's
424 /// equivalence class to \p BB1.
426 /// \param BB1 Block to check.
427 /// \param Descendants Descendants of \p BB1 in either the dom or pdom tree.
428 /// \param DomTree Opposite dominator tree. If \p Descendants is filled
429 /// with blocks from \p BB1's dominator tree, then
430 /// this is the post-dominator tree, and vice versa.
431 void SampleProfileLoader::findEquivalencesFor(
432 BasicBlock *BB1, SmallVector<BasicBlock *, 8> Descendants,
433 DominatorTreeBase<BasicBlock> *DomTree) {
434 for (const auto *BB2 : Descendants) {
435 bool IsDomParent = DomTree->dominates(BB2, BB1);
436 bool IsInSameLoop = LI->getLoopFor(BB1) == LI->getLoopFor(BB2);
437 if (BB1 != BB2 && VisitedBlocks.insert(BB2).second && IsDomParent &&
439 EquivalenceClass[BB2] = BB1;
441 // If BB2 is heavier than BB1, make BB2 have the same weight
444 // Note that we don't worry about the opposite situation here
445 // (when BB2 is lighter than BB1). We will deal with this
446 // during the propagation phase. Right now, we just want to
447 // make sure that BB1 has the largest weight of all the
448 // members of its equivalence set.
449 unsigned &BB1Weight = BlockWeights[BB1];
450 unsigned &BB2Weight = BlockWeights[BB2];
451 BB1Weight = std::max(BB1Weight, BB2Weight);
456 /// \brief Find equivalence classes.
458 /// Since samples may be missing from blocks, we can fill in the gaps by setting
459 /// the weights of all the blocks in the same equivalence class to the same
460 /// weight. To compute the concept of equivalence, we use dominance and loop
461 /// information. Two blocks B1 and B2 are in the same equivalence class if B1
462 /// dominates B2, B2 post-dominates B1 and both are in the same loop.
464 /// \param F The function to query.
465 void SampleProfileLoader::findEquivalenceClasses(Function &F) {
466 SmallVector<BasicBlock *, 8> DominatedBBs;
467 DEBUG(dbgs() << "\nBlock equivalence classes\n");
468 // Find equivalence sets based on dominance and post-dominance information.
470 BasicBlock *BB1 = &BB;
472 // Compute BB1's equivalence class once.
473 if (EquivalenceClass.count(BB1)) {
474 DEBUG(printBlockEquivalence(dbgs(), BB1));
478 // By default, blocks are in their own equivalence class.
479 EquivalenceClass[BB1] = BB1;
481 // Traverse all the blocks dominated by BB1. We are looking for
482 // every basic block BB2 such that:
484 // 1- BB1 dominates BB2.
485 // 2- BB2 post-dominates BB1.
486 // 3- BB1 and BB2 are in the same loop nest.
488 // If all those conditions hold, it means that BB2 is executed
489 // as many times as BB1, so they are placed in the same equivalence
490 // class by making BB2's equivalence class be BB1.
491 DominatedBBs.clear();
492 DT->getDescendants(BB1, DominatedBBs);
493 findEquivalencesFor(BB1, DominatedBBs, PDT.get());
495 // Repeat the same logic for all the blocks post-dominated by BB1.
496 // We are looking for every basic block BB2 such that:
498 // 1- BB1 post-dominates BB2.
499 // 2- BB2 dominates BB1.
500 // 3- BB1 and BB2 are in the same loop nest.
502 // If all those conditions hold, BB2's equivalence class is BB1.
503 DominatedBBs.clear();
504 PDT->getDescendants(BB1, DominatedBBs);
505 findEquivalencesFor(BB1, DominatedBBs, DT.get());
507 DEBUG(printBlockEquivalence(dbgs(), BB1));
510 // Assign weights to equivalence classes.
512 // All the basic blocks in the same equivalence class will execute
513 // the same number of times. Since we know that the head block in
514 // each equivalence class has the largest weight, assign that weight
515 // to all the blocks in that equivalence class.
516 DEBUG(dbgs() << "\nAssign the same weight to all blocks in the same class\n");
518 const BasicBlock *BB = &BI;
519 const BasicBlock *EquivBB = EquivalenceClass[BB];
521 BlockWeights[BB] = BlockWeights[EquivBB];
522 DEBUG(printBlockWeight(dbgs(), BB));
526 /// \brief Visit the given edge to decide if it has a valid weight.
528 /// If \p E has not been visited before, we copy to \p UnknownEdge
529 /// and increment the count of unknown edges.
531 /// \param E Edge to visit.
532 /// \param NumUnknownEdges Current number of unknown edges.
533 /// \param UnknownEdge Set if E has not been visited before.
535 /// \returns E's weight, if known. Otherwise, return 0.
536 unsigned SampleProfileLoader::visitEdge(Edge E, unsigned *NumUnknownEdges,
538 if (!VisitedEdges.count(E)) {
539 (*NumUnknownEdges)++;
544 return EdgeWeights[E];
547 /// \brief Propagate weights through incoming/outgoing edges.
549 /// If the weight of a basic block is known, and there is only one edge
550 /// with an unknown weight, we can calculate the weight of that edge.
552 /// Similarly, if all the edges have a known count, we can calculate the
553 /// count of the basic block, if needed.
555 /// \param F Function to process.
557 /// \returns True if new weights were assigned to edges or blocks.
558 bool SampleProfileLoader::propagateThroughEdges(Function &F) {
559 bool Changed = false;
560 DEBUG(dbgs() << "\nPropagation through edges\n");
562 BasicBlock *BB = &BI;
564 // Visit all the predecessor and successor edges to determine
565 // which ones have a weight assigned already. Note that it doesn't
566 // matter that we only keep track of a single unknown edge. The
567 // only case we are interested in handling is when only a single
568 // edge is unknown (see setEdgeOrBlockWeight).
569 for (unsigned i = 0; i < 2; i++) {
570 unsigned TotalWeight = 0;
571 unsigned NumUnknownEdges = 0;
572 Edge UnknownEdge, SelfReferentialEdge;
575 // First, visit all predecessor edges.
576 for (auto *Pred : Predecessors[BB]) {
577 Edge E = std::make_pair(Pred, BB);
578 TotalWeight += visitEdge(E, &NumUnknownEdges, &UnknownEdge);
579 if (E.first == E.second)
580 SelfReferentialEdge = E;
583 // On the second round, visit all successor edges.
584 for (auto *Succ : Successors[BB]) {
585 Edge E = std::make_pair(BB, Succ);
586 TotalWeight += visitEdge(E, &NumUnknownEdges, &UnknownEdge);
590 // After visiting all the edges, there are three cases that we
591 // can handle immediately:
593 // - All the edge weights are known (i.e., NumUnknownEdges == 0).
594 // In this case, we simply check that the sum of all the edges
595 // is the same as BB's weight. If not, we change BB's weight
596 // to match. Additionally, if BB had not been visited before,
597 // we mark it visited.
599 // - Only one edge is unknown and BB has already been visited.
600 // In this case, we can compute the weight of the edge by
601 // subtracting the total block weight from all the known
602 // edge weights. If the edges weight more than BB, then the
603 // edge of the last remaining edge is set to zero.
605 // - There exists a self-referential edge and the weight of BB is
606 // known. In this case, this edge can be based on BB's weight.
607 // We add up all the other known edges and set the weight on
608 // the self-referential edge as we did in the previous case.
610 // In any other case, we must continue iterating. Eventually,
611 // all edges will get a weight, or iteration will stop when
612 // it reaches SampleProfileMaxPropagateIterations.
613 if (NumUnknownEdges <= 1) {
614 unsigned &BBWeight = BlockWeights[BB];
615 if (NumUnknownEdges == 0) {
616 // If we already know the weight of all edges, the weight of the
617 // basic block can be computed. It should be no larger than the sum
618 // of all edge weights.
619 if (TotalWeight > BBWeight) {
620 BBWeight = TotalWeight;
622 DEBUG(dbgs() << "All edge weights for " << BB->getName()
623 << " known. Set weight for block: ";
624 printBlockWeight(dbgs(), BB););
626 if (VisitedBlocks.insert(BB).second)
628 } else if (NumUnknownEdges == 1 && VisitedBlocks.count(BB)) {
629 // If there is a single unknown edge and the block has been
630 // visited, then we can compute E's weight.
631 if (BBWeight >= TotalWeight)
632 EdgeWeights[UnknownEdge] = BBWeight - TotalWeight;
634 EdgeWeights[UnknownEdge] = 0;
635 VisitedEdges.insert(UnknownEdge);
637 DEBUG(dbgs() << "Set weight for edge: ";
638 printEdgeWeight(dbgs(), UnknownEdge));
640 } else if (SelfReferentialEdge.first && VisitedBlocks.count(BB)) {
641 unsigned &BBWeight = BlockWeights[BB];
642 // We have a self-referential edge and the weight of BB is known.
643 if (BBWeight >= TotalWeight)
644 EdgeWeights[SelfReferentialEdge] = BBWeight - TotalWeight;
646 EdgeWeights[SelfReferentialEdge] = 0;
647 VisitedEdges.insert(SelfReferentialEdge);
649 DEBUG(dbgs() << "Set self-referential edge weight to: ";
650 printEdgeWeight(dbgs(), SelfReferentialEdge));
658 /// \brief Build in/out edge lists for each basic block in the CFG.
660 /// We are interested in unique edges. If a block B1 has multiple
661 /// edges to another block B2, we only add a single B1->B2 edge.
662 void SampleProfileLoader::buildEdges(Function &F) {
664 BasicBlock *B1 = &BI;
666 // Add predecessors for B1.
667 SmallPtrSet<BasicBlock *, 16> Visited;
668 if (!Predecessors[B1].empty())
669 llvm_unreachable("Found a stale predecessors list in a basic block.");
670 for (pred_iterator PI = pred_begin(B1), PE = pred_end(B1); PI != PE; ++PI) {
671 BasicBlock *B2 = *PI;
672 if (Visited.insert(B2).second)
673 Predecessors[B1].push_back(B2);
676 // Add successors for B1.
678 if (!Successors[B1].empty())
679 llvm_unreachable("Found a stale successors list in a basic block.");
680 for (succ_iterator SI = succ_begin(B1), SE = succ_end(B1); SI != SE; ++SI) {
681 BasicBlock *B2 = *SI;
682 if (Visited.insert(B2).second)
683 Successors[B1].push_back(B2);
688 /// \brief Propagate weights into edges
690 /// The following rules are applied to every block BB in the CFG:
692 /// - If BB has a single predecessor/successor, then the weight
693 /// of that edge is the weight of the block.
695 /// - If all incoming or outgoing edges are known except one, and the
696 /// weight of the block is already known, the weight of the unknown
697 /// edge will be the weight of the block minus the sum of all the known
698 /// edges. If the sum of all the known edges is larger than BB's weight,
699 /// we set the unknown edge weight to zero.
701 /// - If there is a self-referential edge, and the weight of the block is
702 /// known, the weight for that edge is set to the weight of the block
703 /// minus the weight of the other incoming edges to that block (if
705 void SampleProfileLoader::propagateWeights(Function &F) {
709 // Add an entry count to the function using the samples gathered
710 // at the function entry.
711 F.setEntryCount(Samples->getHeadSamples());
713 // Before propagation starts, build, for each block, a list of
714 // unique predecessors and successors. This is necessary to handle
715 // identical edges in multiway branches. Since we visit all blocks and all
716 // edges of the CFG, it is cleaner to build these lists once at the start
720 // Propagate until we converge or we go past the iteration limit.
721 while (Changed && i++ < SampleProfileMaxPropagateIterations) {
722 Changed = propagateThroughEdges(F);
725 // Generate MD_prof metadata for every branch instruction using the
726 // edge weights computed during propagation.
727 DEBUG(dbgs() << "\nPropagation complete. Setting branch weights\n");
728 MDBuilder MDB(F.getContext());
730 BasicBlock *BB = &BI;
731 TerminatorInst *TI = BB->getTerminator();
732 if (TI->getNumSuccessors() == 1)
734 if (!isa<BranchInst>(TI) && !isa<SwitchInst>(TI))
737 DEBUG(dbgs() << "\nGetting weights for branch at line "
738 << TI->getDebugLoc().getLine() << ".\n");
739 SmallVector<unsigned, 4> Weights;
740 bool AllWeightsZero = true;
741 for (unsigned I = 0; I < TI->getNumSuccessors(); ++I) {
742 BasicBlock *Succ = TI->getSuccessor(I);
743 Edge E = std::make_pair(BB, Succ);
744 unsigned Weight = EdgeWeights[E];
745 DEBUG(dbgs() << "\t"; printEdgeWeight(dbgs(), E));
746 Weights.push_back(Weight);
748 AllWeightsZero = false;
751 // Only set weights if there is at least one non-zero weight.
752 // In any other case, let the analyzer set weights.
753 if (!AllWeightsZero) {
754 DEBUG(dbgs() << "SUCCESS. Found non-zero weights.\n");
755 TI->setMetadata(llvm::LLVMContext::MD_prof,
756 MDB.createBranchWeights(Weights));
758 DEBUG(dbgs() << "SKIPPED. All branch weights are zero.\n");
763 /// \brief Get the line number for the function header.
765 /// This looks up function \p F in the current compilation unit and
766 /// retrieves the line number where the function is defined. This is
767 /// line 0 for all the samples read from the profile file. Every line
768 /// number is relative to this line.
770 /// \param F Function object to query.
772 /// \returns the line number where \p F is defined. If it returns 0,
773 /// it means that there is no debug information available for \p F.
774 unsigned SampleProfileLoader::getFunctionLoc(Function &F) {
775 if (DISubprogram *S = getDISubprogram(&F))
778 // If could not find the start of \p F, emit a diagnostic to inform the user
779 // about the missed opportunity.
780 F.getContext().diagnose(DiagnosticInfoSampleProfile(
781 "No debug information found in function " + F.getName() +
782 ": Function profile not used",
787 void SampleProfileLoader::computeDominanceAndLoopInfo(Function &F) {
788 DT.reset(new DominatorTree);
791 PDT.reset(new DominatorTreeBase<BasicBlock>(true));
794 LI.reset(new LoopInfo);
798 /// \brief Generate branch weight metadata for all branches in \p F.
800 /// Branch weights are computed out of instruction samples using a
801 /// propagation heuristic. Propagation proceeds in 3 phases:
803 /// 1- Assignment of block weights. All the basic blocks in the function
804 /// are initial assigned the same weight as their most frequently
805 /// executed instruction.
807 /// 2- Creation of equivalence classes. Since samples may be missing from
808 /// blocks, we can fill in the gaps by setting the weights of all the
809 /// blocks in the same equivalence class to the same weight. To compute
810 /// the concept of equivalence, we use dominance and loop information.
811 /// Two blocks B1 and B2 are in the same equivalence class if B1
812 /// dominates B2, B2 post-dominates B1 and both are in the same loop.
814 /// 3- Propagation of block weights into edges. This uses a simple
815 /// propagation heuristic. The following rules are applied to every
816 /// block BB in the CFG:
818 /// - If BB has a single predecessor/successor, then the weight
819 /// of that edge is the weight of the block.
821 /// - If all the edges are known except one, and the weight of the
822 /// block is already known, the weight of the unknown edge will
823 /// be the weight of the block minus the sum of all the known
824 /// edges. If the sum of all the known edges is larger than BB's weight,
825 /// we set the unknown edge weight to zero.
827 /// - If there is a self-referential edge, and the weight of the block is
828 /// known, the weight for that edge is set to the weight of the block
829 /// minus the weight of the other incoming edges to that block (if
832 /// Since this propagation is not guaranteed to finalize for every CFG, we
833 /// only allow it to proceed for a limited number of iterations (controlled
834 /// by -sample-profile-max-propagate-iterations).
836 /// FIXME: Try to replace this propagation heuristic with a scheme
837 /// that is guaranteed to finalize. A work-list approach similar to
838 /// the standard value propagation algorithm used by SSA-CCP might
841 /// Once all the branch weights are computed, we emit the MD_prof
842 /// metadata on BB using the computed values for each of its branches.
844 /// \param F The function to query.
846 /// \returns true if \p F was modified. Returns false, otherwise.
847 bool SampleProfileLoader::emitAnnotations(Function &F) {
848 bool Changed = false;
850 // Initialize invariants used during computation and propagation.
851 HeaderLineno = getFunctionLoc(F);
852 if (HeaderLineno == 0)
855 DEBUG(dbgs() << "Line number for the first instruction in " << F.getName()
856 << ": " << HeaderLineno << "\n");
858 Changed |= inlineHotFunctions(F);
860 // Compute basic block weights.
861 Changed |= computeBlockWeights(F);
864 // Compute dominance and loop info needed for propagation.
865 computeDominanceAndLoopInfo(F);
867 // Find equivalence classes.
868 findEquivalenceClasses(F);
870 // Propagate weights to all edges.
877 char SampleProfileLoader::ID = 0;
878 INITIALIZE_PASS_BEGIN(SampleProfileLoader, "sample-profile",
879 "Sample Profile loader", false, false)
880 INITIALIZE_PASS_DEPENDENCY(AddDiscriminators)
881 INITIALIZE_PASS_END(SampleProfileLoader, "sample-profile",
882 "Sample Profile loader", false, false)
884 bool SampleProfileLoader::doInitialization(Module &M) {
885 auto &Ctx = M.getContext();
886 auto ReaderOrErr = SampleProfileReader::create(Filename, Ctx);
887 if (std::error_code EC = ReaderOrErr.getError()) {
888 std::string Msg = "Could not open profile: " + EC.message();
889 Ctx.diagnose(DiagnosticInfoSampleProfile(Filename.data(), Msg));
892 Reader = std::move(ReaderOrErr.get());
893 ProfileIsValid = (Reader->read() == sampleprof_error::success);
897 ModulePass *llvm::createSampleProfileLoaderPass() {
898 return new SampleProfileLoader(SampleProfileFile);
901 ModulePass *llvm::createSampleProfileLoaderPass(StringRef Name) {
902 return new SampleProfileLoader(Name);
905 bool SampleProfileLoader::runOnModule(Module &M) {
908 if (!F.isDeclaration())
909 retval |= runOnFunction(F);
913 bool SampleProfileLoader::runOnFunction(Function &F) {
917 Samples = Reader->getSamplesFor(F);
918 if (!Samples->empty())
919 return emitAnnotations(F);