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 #define DEBUG_TYPE "sample-profile"
27 #include "llvm/ADT/DenseMap.h"
28 #include "llvm/ADT/OwningPtr.h"
29 #include "llvm/ADT/SmallSet.h"
30 #include "llvm/ADT/SmallPtrSet.h"
31 #include "llvm/ADT/StringMap.h"
32 #include "llvm/ADT/StringRef.h"
33 #include "llvm/Analysis/Dominators.h"
34 #include "llvm/Analysis/PostDominators.h"
35 #include "llvm/Analysis/LoopInfo.h"
36 #include "llvm/DebugInfo.h"
37 #include "llvm/IR/Constants.h"
38 #include "llvm/IR/Function.h"
39 #include "llvm/IR/Instructions.h"
40 #include "llvm/IR/LLVMContext.h"
41 #include "llvm/IR/MDBuilder.h"
42 #include "llvm/IR/Metadata.h"
43 #include "llvm/IR/Module.h"
44 #include "llvm/Pass.h"
45 #include "llvm/Support/CommandLine.h"
46 #include "llvm/Support/Debug.h"
47 #include "llvm/Support/InstIterator.h"
48 #include "llvm/Support/MemoryBuffer.h"
49 #include "llvm/Support/Regex.h"
50 #include "llvm/Support/raw_ostream.h"
51 #include "llvm/Transforms/Scalar.h"
55 // Command line option to specify the file to read samples from. This is
56 // mainly used for debugging.
57 static cl::opt<std::string> SampleProfileFile(
58 "sample-profile-file", cl::init(""), cl::value_desc("filename"),
59 cl::desc("Profile file loaded by -sample-profile"), cl::Hidden);
60 static cl::opt<unsigned> SampleProfileMaxPropagateIterations(
61 "sample-profile-max-propagate-iterations", cl::init(100),
62 cl::desc("Maximum number of iterations to go through when propagating "
63 "sample block/edge weights through the CFG."));
67 typedef DenseMap<uint32_t, uint32_t> BodySampleMap;
68 typedef DenseMap<BasicBlock *, uint32_t> BlockWeightMap;
69 typedef DenseMap<BasicBlock *, BasicBlock *> EquivalenceClassMap;
70 typedef std::pair<BasicBlock *, BasicBlock *> Edge;
71 typedef DenseMap<Edge, uint32_t> EdgeWeightMap;
72 typedef DenseMap<BasicBlock *, SmallVector<BasicBlock *, 8> > BlockEdgeMap;
74 /// \brief Representation of the runtime profile for a function.
76 /// This data structure contains the runtime profile for a given
77 /// function. It contains the total number of samples collected
78 /// in the function and a map of samples collected in every statement.
79 class SampleFunctionProfile {
81 SampleFunctionProfile()
82 : TotalSamples(0), TotalHeadSamples(0), HeaderLineno(0), DT(0), PDT(0),
85 unsigned getFunctionLoc(Function &F);
86 bool emitAnnotations(Function &F, DominatorTree *DomTree,
87 PostDominatorTree *PostDomTree, LoopInfo *Loops);
88 uint32_t getInstWeight(Instruction &I);
89 uint32_t getBlockWeight(BasicBlock *B);
90 void addTotalSamples(unsigned Num) { TotalSamples += Num; }
91 void addHeadSamples(unsigned Num) { TotalHeadSamples += Num; }
92 void addBodySamples(unsigned LineOffset, unsigned Num) {
93 BodySamples[LineOffset] += Num;
95 void print(raw_ostream &OS);
96 void printEdgeWeight(raw_ostream &OS, Edge E);
97 void printBlockWeight(raw_ostream &OS, BasicBlock *BB);
98 void printBlockEquivalence(raw_ostream &OS, BasicBlock *BB);
99 bool computeBlockWeights(Function &F);
100 void findEquivalenceClasses(Function &F);
101 void findEquivalencesFor(BasicBlock *BB1,
102 SmallVector<BasicBlock *, 8> Descendants,
103 DominatorTreeBase<BasicBlock> *DomTree);
104 void propagateWeights(Function &F);
105 uint32_t visitEdge(Edge E, unsigned *NumUnknownEdges, Edge *UnknownEdge);
106 void buildEdges(Function &F);
107 bool propagateThroughEdges(Function &F);
108 bool empty() { return BodySamples.empty(); }
111 /// \brief Total number of samples collected inside this function.
113 /// Samples are cumulative, they include all the samples collected
114 /// inside this function and all its inlined callees.
115 unsigned TotalSamples;
117 /// \brief Total number of samples collected at the head of the function.
118 unsigned TotalHeadSamples;
120 /// \brief Line number for the function header. Used to compute relative
121 /// line numbers from the absolute line LOCs found in instruction locations.
122 /// The relative line numbers are needed to address the samples from the
124 unsigned HeaderLineno;
126 /// \brief Map line offsets to collected samples.
128 /// Each entry in this map contains the number of samples
129 /// collected at the corresponding line offset. All line locations
130 /// are an offset from the start of the function.
131 BodySampleMap BodySamples;
133 /// \brief Map basic blocks to their computed weights.
135 /// The weight of a basic block is defined to be the maximum
136 /// of all the instruction weights in that block.
137 BlockWeightMap BlockWeights;
139 /// \brief Map edges to their computed weights.
141 /// Edge weights are computed by propagating basic block weights in
142 /// SampleProfile::propagateWeights.
143 EdgeWeightMap EdgeWeights;
145 /// \brief Set of visited blocks during propagation.
146 SmallPtrSet<BasicBlock *, 128> VisitedBlocks;
148 /// \brief Set of visited edges during propagation.
149 SmallSet<Edge, 128> VisitedEdges;
151 /// \brief Equivalence classes for block weights.
153 /// Two blocks BB1 and BB2 are in the same equivalence class if they
154 /// dominate and post-dominate each other, and they are in the same loop
155 /// nest. When this happens, the two blocks are guaranteed to execute
156 /// the same number of times.
157 EquivalenceClassMap EquivalenceClass;
159 /// \brief Dominance, post-dominance and loop information.
161 PostDominatorTree *PDT;
164 /// \brief Predecessors for each basic block in the CFG.
165 BlockEdgeMap Predecessors;
167 /// \brief Successors for each basic block in the CFG.
168 BlockEdgeMap Successors;
171 /// \brief Sample-based profile reader.
173 /// Each profile contains sample counts for all the functions
174 /// executed. Inside each function, statements are annotated with the
175 /// collected samples on all the instructions associated with that
178 /// For this to produce meaningful data, the program needs to be
179 /// compiled with some debug information (at minimum, line numbers:
180 /// -gline-tables-only). Otherwise, it will be impossible to match IR
181 /// instructions to the line numbers collected by the profiler.
183 /// From the profile file, we are interested in collecting the
184 /// following information:
186 /// * A list of functions included in the profile (mangled names).
188 /// * For each function F:
189 /// 1. The total number of samples collected in F.
191 /// 2. The samples collected at each line in F. To provide some
192 /// protection against source code shuffling, line numbers should
193 /// be relative to the start of the function.
194 class SampleModuleProfile {
196 SampleModuleProfile(StringRef F) : Profiles(0), Filename(F) {}
200 void loadNative() { llvm_unreachable("not implemented"); }
201 void printFunctionProfile(raw_ostream &OS, StringRef FName);
202 void dumpFunctionProfile(StringRef FName);
203 SampleFunctionProfile &getProfile(const Function &F) {
204 return Profiles[F.getName()];
208 /// \brief Map every function to its associated profile.
210 /// The profile of every function executed at runtime is collected
211 /// in the structure SampleFunctionProfile. This maps function objects
212 /// to their corresponding profiles.
213 StringMap<SampleFunctionProfile> Profiles;
215 /// \brief Path name to the file holding the profile data.
217 /// The format of this file is defined by each profiler
218 /// independently. If possible, the profiler should have a text
219 /// version of the profile format to be used in constructing test
220 /// cases and debugging.
224 /// \brief Loader class for text-based profiles.
226 /// This class defines a simple interface to read text files containing
227 /// profiles. It keeps track of line number information and location of
228 /// the file pointer. Users of this class are responsible for actually
229 /// parsing the lines returned by the readLine function.
231 /// TODO - This does not really belong here. It is a generic text file
232 /// reader. It should be moved to the Support library and made more general.
233 class ExternalProfileTextLoader {
235 ExternalProfileTextLoader(StringRef F) : Filename(F) {
237 EC = MemoryBuffer::getFile(Filename, Buffer);
239 report_fatal_error("Could not open profile file " + Filename + ": " +
241 FP = Buffer->getBufferStart();
245 /// \brief Read a line from the mapped file.
246 StringRef readLine() {
248 const char *start = FP;
249 while (FP != Buffer->getBufferEnd() && *FP != '\n') {
253 if (FP != Buffer->getBufferEnd())
256 return StringRef(start, Length);
259 /// \brief Return true, if we've reached EOF.
260 bool atEOF() const { return FP == Buffer->getBufferEnd(); }
262 /// \brief Report a parse error message and stop compilation.
263 void reportParseError(Twine Msg) const {
264 report_fatal_error(Filename + ":" + Twine(Lineno) + ": " + Msg + "\n");
268 /// \brief Memory buffer holding the text file.
269 OwningPtr<MemoryBuffer> Buffer;
271 /// \brief Current position into the memory buffer.
274 /// \brief Current line number.
277 /// \brief Path name where to the profile file.
281 /// \brief Sample profile pass.
283 /// This pass reads profile data from the file specified by
284 /// -sample-profile-file and annotates every affected function with the
285 /// profile information found in that file.
286 class SampleProfileLoader : public FunctionPass {
288 // Class identification, replacement for typeinfo
291 SampleProfileLoader(StringRef Name = SampleProfileFile)
292 : FunctionPass(ID), Profiler(0), Filename(Name) {
293 initializeSampleProfileLoaderPass(*PassRegistry::getPassRegistry());
296 virtual bool doInitialization(Module &M);
298 void dump() { Profiler->dump(); }
300 virtual const char *getPassName() const { return "Sample profile pass"; }
302 virtual bool runOnFunction(Function &F);
304 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
305 AU.setPreservesCFG();
306 AU.addRequired<LoopInfo>();
307 AU.addRequired<DominatorTree>();
308 AU.addRequired<PostDominatorTree>();
312 /// \brief Profile reader object.
313 OwningPtr<SampleModuleProfile> Profiler;
315 /// \brief Name of the profile file to load.
320 /// \brief Print this function profile on stream \p OS.
322 /// \param OS Stream to emit the output to.
323 void SampleFunctionProfile::print(raw_ostream &OS) {
324 OS << TotalSamples << ", " << TotalHeadSamples << ", " << BodySamples.size()
325 << " sampled lines\n";
326 for (BodySampleMap::const_iterator SI = BodySamples.begin(),
327 SE = BodySamples.end();
329 OS << "\tline offset: " << SI->first
330 << ", number of samples: " << SI->second << "\n";
334 /// \brief Print the weight of edge \p E on stream \p OS.
336 /// \param OS Stream to emit the output to.
337 /// \param E Edge to print.
338 void SampleFunctionProfile::printEdgeWeight(raw_ostream &OS, Edge E) {
339 OS << "weight[" << E.first->getName() << "->" << E.second->getName()
340 << "]: " << EdgeWeights[E] << "\n";
343 /// \brief Print the equivalence class of block \p BB on stream \p OS.
345 /// \param OS Stream to emit the output to.
346 /// \param BB Block to print.
347 void SampleFunctionProfile::printBlockEquivalence(raw_ostream &OS,
349 BasicBlock *Equiv = EquivalenceClass[BB];
350 OS << "equivalence[" << BB->getName()
351 << "]: " << ((Equiv) ? EquivalenceClass[BB]->getName() : "NONE") << "\n";
354 /// \brief Print the weight of block \p BB on stream \p OS.
356 /// \param OS Stream to emit the output to.
357 /// \param BB Block to print.
358 void SampleFunctionProfile::printBlockWeight(raw_ostream &OS, BasicBlock *BB) {
359 OS << "weight[" << BB->getName() << "]: " << BlockWeights[BB] << "\n";
362 /// \brief Print the function profile for \p FName on stream \p OS.
364 /// \param OS Stream to emit the output to.
365 /// \param FName Name of the function to print.
366 void SampleModuleProfile::printFunctionProfile(raw_ostream &OS,
368 OS << "Function: " << FName << ":\n";
369 Profiles[FName].print(OS);
372 /// \brief Dump the function profile for \p FName.
374 /// \param FName Name of the function to print.
375 void SampleModuleProfile::dumpFunctionProfile(StringRef FName) {
376 printFunctionProfile(dbgs(), FName);
379 /// \brief Dump all the function profiles found.
380 void SampleModuleProfile::dump() {
381 for (StringMap<SampleFunctionProfile>::const_iterator I = Profiles.begin(),
384 dumpFunctionProfile(I->getKey());
387 /// \brief Load samples from a text file.
389 /// The file is divided in two segments:
391 /// Symbol table (represented with the string "symbol table")
392 /// Number of symbols in the table
398 /// Function body profiles
399 /// function1:total_samples:total_head_samples:number_of_locations
400 /// location_offset_1: number_of_samples
401 /// location_offset_2: number_of_samples
403 /// location_offset_N: number_of_samples
405 /// Function names must be mangled in order for the profile loader to
406 /// match them in the current translation unit.
408 /// Since this is a flat profile, a function that shows up more than
409 /// once gets all its samples aggregated across all its instances.
410 /// TODO - flat profiles are too imprecise to provide good optimization
411 /// opportunities. Convert them to context-sensitive profile.
413 /// This textual representation is useful to generate unit tests and
414 /// for debugging purposes, but it should not be used to generate
415 /// profiles for large programs, as the representation is extremely
417 void SampleModuleProfile::loadText() {
418 ExternalProfileTextLoader Loader(Filename);
420 // Read the symbol table.
421 StringRef Line = Loader.readLine();
422 if (Line != "symbol table")
423 Loader.reportParseError("Expected 'symbol table', found " + Line);
425 Line = Loader.readLine();
426 if (Line.getAsInteger(10, NumSymbols))
427 Loader.reportParseError("Expected a number, found " + Line);
428 for (int I = 0; I < NumSymbols; I++)
429 Profiles[Loader.readLine()] = SampleFunctionProfile();
431 // Read the profile of each function. Since each function may be
432 // mentioned more than once, and we are collecting flat profiles,
433 // accumulate samples as we parse them.
434 Regex HeadRE("^([^:]+):([0-9]+):([0-9]+):([0-9]+)$");
435 Regex LineSample("^([0-9]+): ([0-9]+)$");
436 while (!Loader.atEOF()) {
437 SmallVector<StringRef, 4> Matches;
438 Line = Loader.readLine();
439 if (!HeadRE.match(Line, &Matches))
440 Loader.reportParseError("Expected 'mangled_name:NUM:NUM:NUM', found " +
442 assert(Matches.size() == 5);
443 StringRef FName = Matches[1];
444 unsigned NumSamples, NumHeadSamples, NumSampledLines;
445 Matches[2].getAsInteger(10, NumSamples);
446 Matches[3].getAsInteger(10, NumHeadSamples);
447 Matches[4].getAsInteger(10, NumSampledLines);
448 SampleFunctionProfile &FProfile = Profiles[FName];
449 FProfile.addTotalSamples(NumSamples);
450 FProfile.addHeadSamples(NumHeadSamples);
452 for (I = 0; I < NumSampledLines && !Loader.atEOF(); I++) {
453 Line = Loader.readLine();
454 if (!LineSample.match(Line, &Matches))
455 Loader.reportParseError("Expected 'NUM: NUM', found " + Line);
456 assert(Matches.size() == 3);
457 unsigned LineOffset, NumSamples;
458 Matches[1].getAsInteger(10, LineOffset);
459 Matches[2].getAsInteger(10, NumSamples);
460 // When dealing with instruction weights, we use the value
461 // zero to indicate the absence of a sample. If we read an
462 // actual zero from the profile file, return it as 1 to
463 // avoid the confusion later on.
466 FProfile.addBodySamples(LineOffset, NumSamples);
469 if (I < NumSampledLines)
470 Loader.reportParseError("Unexpected end of file");
474 /// \brief Get the weight for an instruction.
476 /// The "weight" of an instruction \p Inst is the number of samples
477 /// collected on that instruction at runtime. To retrieve it, we
478 /// need to compute the line number of \p Inst relative to the start of its
479 /// function. We use HeaderLineno to compute the offset. We then
480 /// look up the samples collected for \p Inst using BodySamples.
482 /// \param Inst Instruction to query.
484 /// \returns The profiled weight of I.
485 uint32_t SampleFunctionProfile::getInstWeight(Instruction &Inst) {
486 unsigned Lineno = Inst.getDebugLoc().getLine();
487 if (Lineno < HeaderLineno)
489 unsigned LOffset = Lineno - HeaderLineno;
490 uint32_t Weight = BodySamples.lookup(LOffset);
491 DEBUG(dbgs() << " " << Lineno << ":" << Inst.getDebugLoc().getCol() << ":"
492 << Inst << " (line offset: " << LOffset
493 << " - weight: " << Weight << ")\n");
497 /// \brief Compute the weight of a basic block.
499 /// The weight of basic block \p B is the maximum weight of all the
500 /// instructions in B. The weight of \p B is computed and cached in
501 /// the BlockWeights map.
503 /// \param B The basic block to query.
505 /// \returns The computed weight of B.
506 uint32_t SampleFunctionProfile::getBlockWeight(BasicBlock *B) {
507 // If we've computed B's weight before, return it.
508 std::pair<BlockWeightMap::iterator, bool> Entry =
509 BlockWeights.insert(std::make_pair(B, 0));
511 return Entry.first->second;
513 // Otherwise, compute and cache B's weight.
515 for (BasicBlock::iterator I = B->begin(), E = B->end(); I != E; ++I) {
516 uint32_t InstWeight = getInstWeight(*I);
517 if (InstWeight > Weight)
520 Entry.first->second = Weight;
524 /// \brief Compute and store the weights of every basic block.
526 /// This populates the BlockWeights map by computing
527 /// the weights of every basic block in the CFG.
529 /// \param F The function to query.
530 bool SampleFunctionProfile::computeBlockWeights(Function &F) {
531 bool Changed = false;
532 DEBUG(dbgs() << "Block weights\n");
533 for (Function::iterator B = F.begin(), E = F.end(); B != E; ++B) {
534 uint32_t Weight = getBlockWeight(B);
535 Changed |= (Weight > 0);
536 DEBUG(printBlockWeight(dbgs(), B));
542 /// \brief Find equivalence classes for the given block.
544 /// This finds all the blocks that are guaranteed to execute the same
545 /// number of times as \p BB1. To do this, it traverses all the the
546 /// descendants of \p BB1 in the dominator or post-dominator tree.
548 /// A block BB2 will be in the same equivalence class as \p BB1 if
549 /// the following holds:
551 /// 1- \p BB1 is a descendant of BB2 in the opposite tree. So, if BB2
552 /// is a descendant of \p BB1 in the dominator tree, then BB2 should
553 /// dominate BB1 in the post-dominator tree.
555 /// 2- Both BB2 and \p BB1 must be in the same loop.
557 /// For every block BB2 that meets those two requirements, we set BB2's
558 /// equivalence class to \p BB1.
560 /// \param BB1 Block to check.
561 /// \param Descendants Descendants of \p BB1 in either the dom or pdom tree.
562 /// \param DomTree Opposite dominator tree. If \p Descendants is filled
563 /// with blocks from \p BB1's dominator tree, then
564 /// this is the post-dominator tree, and vice versa.
565 void SampleFunctionProfile::findEquivalencesFor(
566 BasicBlock *BB1, SmallVector<BasicBlock *, 8> Descendants,
567 DominatorTreeBase<BasicBlock> *DomTree) {
568 for (SmallVectorImpl<BasicBlock *>::iterator I = Descendants.begin(),
569 E = Descendants.end();
571 BasicBlock *BB2 = *I;
572 bool IsDomParent = DomTree->dominates(BB2, BB1);
573 bool IsInSameLoop = LI->getLoopFor(BB1) == LI->getLoopFor(BB2);
574 if (BB1 != BB2 && VisitedBlocks.insert(BB2) && IsDomParent &&
576 EquivalenceClass[BB2] = BB1;
578 // If BB2 is heavier than BB1, make BB2 have the same weight
581 // Note that we don't worry about the opposite situation here
582 // (when BB2 is lighter than BB1). We will deal with this
583 // during the propagation phase. Right now, we just want to
584 // make sure that BB1 has the largest weight of all the
585 // members of its equivalence set.
586 uint32_t &BB1Weight = BlockWeights[BB1];
587 uint32_t &BB2Weight = BlockWeights[BB2];
588 BB1Weight = std::max(BB1Weight, BB2Weight);
593 /// \brief Find equivalence classes.
595 /// Since samples may be missing from blocks, we can fill in the gaps by setting
596 /// the weights of all the blocks in the same equivalence class to the same
597 /// weight. To compute the concept of equivalence, we use dominance and loop
598 /// information. Two blocks B1 and B2 are in the same equivalence class if B1
599 /// dominates B2, B2 post-dominates B1 and both are in the same loop.
601 /// \param F The function to query.
602 void SampleFunctionProfile::findEquivalenceClasses(Function &F) {
603 SmallVector<BasicBlock *, 8> DominatedBBs;
604 DEBUG(dbgs() << "\nBlock equivalence classes\n");
605 // Find equivalence sets based on dominance and post-dominance information.
606 for (Function::iterator B = F.begin(), E = F.end(); B != E; ++B) {
609 // Compute BB1's equivalence class once.
610 if (EquivalenceClass.count(BB1)) {
611 DEBUG(printBlockEquivalence(dbgs(), BB1));
615 // By default, blocks are in their own equivalence class.
616 EquivalenceClass[BB1] = BB1;
618 // Traverse all the blocks dominated by BB1. We are looking for
619 // every basic block BB2 such that:
621 // 1- BB1 dominates BB2.
622 // 2- BB2 post-dominates BB1.
623 // 3- BB1 and BB2 are in the same loop nest.
625 // If all those conditions hold, it means that BB2 is executed
626 // as many times as BB1, so they are placed in the same equivalence
627 // class by making BB2's equivalence class be BB1.
628 DominatedBBs.clear();
629 DT->getDescendants(BB1, DominatedBBs);
630 findEquivalencesFor(BB1, DominatedBBs, PDT->DT);
632 // Repeat the same logic for all the blocks post-dominated by BB1.
633 // We are looking for every basic block BB2 such that:
635 // 1- BB1 post-dominates BB2.
636 // 2- BB2 dominates BB1.
637 // 3- BB1 and BB2 are in the same loop nest.
639 // If all those conditions hold, BB2's equivalence class is BB1.
640 DominatedBBs.clear();
641 PDT->getDescendants(BB1, DominatedBBs);
642 findEquivalencesFor(BB1, DominatedBBs, DT->DT);
644 DEBUG(printBlockEquivalence(dbgs(), BB1));
647 // Assign weights to equivalence classes.
649 // All the basic blocks in the same equivalence class will execute
650 // the same number of times. Since we know that the head block in
651 // each equivalence class has the largest weight, assign that weight
652 // to all the blocks in that equivalence class.
653 DEBUG(dbgs() << "\nAssign the same weight to all blocks in the same class\n");
654 for (Function::iterator B = F.begin(), E = F.end(); B != E; ++B) {
656 BasicBlock *EquivBB = EquivalenceClass[BB];
658 BlockWeights[BB] = BlockWeights[EquivBB];
659 DEBUG(printBlockWeight(dbgs(), BB));
663 /// \brief Visit the given edge to decide if it has a valid weight.
665 /// If \p E has not been visited before, we copy to \p UnknownEdge
666 /// and increment the count of unknown edges.
668 /// \param E Edge to visit.
669 /// \param NumUnknownEdges Current number of unknown edges.
670 /// \param UnknownEdge Set if E has not been visited before.
672 /// \returns E's weight, if known. Otherwise, return 0.
673 uint32_t SampleFunctionProfile::visitEdge(Edge E, unsigned *NumUnknownEdges,
675 if (!VisitedEdges.count(E)) {
676 (*NumUnknownEdges)++;
681 return EdgeWeights[E];
684 /// \brief Propagate weights through incoming/outgoing edges.
686 /// If the weight of a basic block is known, and there is only one edge
687 /// with an unknown weight, we can calculate the weight of that edge.
689 /// Similarly, if all the edges have a known count, we can calculate the
690 /// count of the basic block, if needed.
692 /// \param F Function to process.
694 /// \returns True if new weights were assigned to edges or blocks.
695 bool SampleFunctionProfile::propagateThroughEdges(Function &F) {
696 bool Changed = false;
697 DEBUG(dbgs() << "\nPropagation through edges\n");
698 for (Function::iterator BI = F.begin(), EI = F.end(); BI != EI; ++BI) {
701 // Visit all the predecessor and successor edges to determine
702 // which ones have a weight assigned already. Note that it doesn't
703 // matter that we only keep track of a single unknown edge. The
704 // only case we are interested in handling is when only a single
705 // edge is unknown (see setEdgeOrBlockWeight).
706 for (unsigned i = 0; i < 2; i++) {
707 uint32_t TotalWeight = 0;
708 unsigned NumUnknownEdges = 0;
709 Edge UnknownEdge, SelfReferentialEdge;
712 // First, visit all predecessor edges.
713 for (size_t I = 0; I < Predecessors[BB].size(); I++) {
714 Edge E = std::make_pair(Predecessors[BB][I], BB);
715 TotalWeight += visitEdge(E, &NumUnknownEdges, &UnknownEdge);
716 if (E.first == E.second)
717 SelfReferentialEdge = E;
720 // On the second round, visit all successor edges.
721 for (size_t I = 0; I < Successors[BB].size(); I++) {
722 Edge E = std::make_pair(BB, Successors[BB][I]);
723 TotalWeight += visitEdge(E, &NumUnknownEdges, &UnknownEdge);
727 // After visiting all the edges, there are three cases that we
728 // can handle immediately:
730 // - All the edge weights are known (i.e., NumUnknownEdges == 0).
731 // In this case, we simply check that the sum of all the edges
732 // is the same as BB's weight. If not, we change BB's weight
733 // to match. Additionally, if BB had not been visited before,
734 // we mark it visited.
736 // - Only one edge is unknown and BB has already been visited.
737 // In this case, we can compute the weight of the edge by
738 // subtracting the total block weight from all the known
739 // edge weights. If the edges weight more than BB, then the
740 // edge of the last remaining edge is set to zero.
742 // - There exists a self-referential edge and the weight of BB is
743 // known. In this case, this edge can be based on BB's weight.
744 // We add up all the other known edges and set the weight on
745 // the self-referential edge as we did in the previous case.
747 // In any other case, we must continue iterating. Eventually,
748 // all edges will get a weight, or iteration will stop when
749 // it reaches SampleProfileMaxPropagateIterations.
750 if (NumUnknownEdges <= 1) {
751 uint32_t &BBWeight = BlockWeights[BB];
752 if (NumUnknownEdges == 0) {
753 // If we already know the weight of all edges, the weight of the
754 // basic block can be computed. It should be no larger than the sum
755 // of all edge weights.
756 if (TotalWeight > BBWeight) {
757 BBWeight = TotalWeight;
759 DEBUG(dbgs() << "All edge weights for " << BB->getName()
760 << " known. Set weight for block: ";
761 printBlockWeight(dbgs(), BB););
763 if (VisitedBlocks.insert(BB))
765 } else if (NumUnknownEdges == 1 && VisitedBlocks.count(BB)) {
766 // If there is a single unknown edge and the block has been
767 // visited, then we can compute E's weight.
768 if (BBWeight >= TotalWeight)
769 EdgeWeights[UnknownEdge] = BBWeight - TotalWeight;
771 EdgeWeights[UnknownEdge] = 0;
772 VisitedEdges.insert(UnknownEdge);
774 DEBUG(dbgs() << "Set weight for edge: ";
775 printEdgeWeight(dbgs(), UnknownEdge));
777 } else if (SelfReferentialEdge.first && VisitedBlocks.count(BB)) {
778 uint32_t &BBWeight = BlockWeights[BB];
779 // We have a self-referential edge and the weight of BB is known.
780 if (BBWeight >= TotalWeight)
781 EdgeWeights[SelfReferentialEdge] = BBWeight - TotalWeight;
783 EdgeWeights[SelfReferentialEdge] = 0;
784 VisitedEdges.insert(SelfReferentialEdge);
786 DEBUG(dbgs() << "Set self-referential edge weight to: ";
787 printEdgeWeight(dbgs(), SelfReferentialEdge));
795 /// \brief Build in/out edge lists for each basic block in the CFG.
797 /// We are interested in unique edges. If a block B1 has multiple
798 /// edges to another block B2, we only add a single B1->B2 edge.
799 void SampleFunctionProfile::buildEdges(Function &F) {
800 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
803 // Add predecessors for B1.
804 SmallPtrSet<BasicBlock *, 16> Visited;
805 if (!Predecessors[B1].empty())
806 llvm_unreachable("Found a stale predecessors list in a basic block.");
807 for (pred_iterator PI = pred_begin(B1), PE = pred_end(B1); PI != PE; ++PI) {
808 BasicBlock *B2 = *PI;
809 if (Visited.insert(B2))
810 Predecessors[B1].push_back(B2);
813 // Add successors for B1.
815 if (!Successors[B1].empty())
816 llvm_unreachable("Found a stale successors list in a basic block.");
817 for (succ_iterator SI = succ_begin(B1), SE = succ_end(B1); SI != SE; ++SI) {
818 BasicBlock *B2 = *SI;
819 if (Visited.insert(B2))
820 Successors[B1].push_back(B2);
825 /// \brief Propagate weights into edges
827 /// The following rules are applied to every block B in the CFG:
829 /// - If B has a single predecessor/successor, then the weight
830 /// of that edge is the weight of the block.
832 /// - If all incoming or outgoing edges are known except one, and the
833 /// weight of the block is already known, the weight of the unknown
834 /// edge will be the weight of the block minus the sum of all the known
835 /// edges. If the sum of all the known edges is larger than B's weight,
836 /// we set the unknown edge weight to zero.
838 /// - If there is a self-referential edge, and the weight of the block is
839 /// known, the weight for that edge is set to the weight of the block
840 /// minus the weight of the other incoming edges to that block (if
842 void SampleFunctionProfile::propagateWeights(Function &F) {
846 // Before propagation starts, build, for each block, a list of
847 // unique predecessors and successors. This is necessary to handle
848 // identical edges in multiway branches. Since we visit all blocks and all
849 // edges of the CFG, it is cleaner to build these lists once at the start
853 // Propagate until we converge or we go past the iteration limit.
854 while (Changed && i++ < SampleProfileMaxPropagateIterations) {
855 Changed = propagateThroughEdges(F);
858 // Generate MD_prof metadata for every branch instruction using the
859 // edge weights computed during propagation.
860 DEBUG(dbgs() << "\nPropagation complete. Setting branch weights\n");
861 MDBuilder MDB(F.getContext());
862 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
864 TerminatorInst *TI = B->getTerminator();
865 if (TI->getNumSuccessors() == 1)
867 if (!isa<BranchInst>(TI) && !isa<SwitchInst>(TI))
870 DEBUG(dbgs() << "\nGetting weights for branch at line "
871 << TI->getDebugLoc().getLine() << ":"
872 << TI->getDebugLoc().getCol() << ".\n");
873 SmallVector<uint32_t, 4> Weights;
874 bool AllWeightsZero = true;
875 for (unsigned I = 0; I < TI->getNumSuccessors(); ++I) {
876 BasicBlock *Succ = TI->getSuccessor(I);
877 Edge E = std::make_pair(B, Succ);
878 uint32_t Weight = EdgeWeights[E];
879 DEBUG(dbgs() << "\t"; printEdgeWeight(dbgs(), E));
880 Weights.push_back(Weight);
882 AllWeightsZero = false;
885 // Only set weights if there is at least one non-zero weight.
886 // In any other case, let the analyzer set weights.
887 if (!AllWeightsZero) {
888 DEBUG(dbgs() << "SUCCESS. Found non-zero weights.\n");
889 TI->setMetadata(llvm::LLVMContext::MD_prof,
890 MDB.createBranchWeights(Weights));
892 DEBUG(dbgs() << "SKIPPED. All branch weights are zero.\n");
897 /// \brief Get the line number for the function header.
899 /// This looks up function \p F in the current compilation unit and
900 /// retrieves the line number where the function is defined. This is
901 /// line 0 for all the samples read from the profile file. Every line
902 /// number is relative to this line.
904 /// \param F Function object to query.
906 /// \returns the line number where \p F is defined.
907 unsigned SampleFunctionProfile::getFunctionLoc(Function &F) {
908 NamedMDNode *CUNodes = F.getParent()->getNamedMetadata("llvm.dbg.cu");
910 for (unsigned I = 0, E1 = CUNodes->getNumOperands(); I != E1; ++I) {
911 DICompileUnit CU(CUNodes->getOperand(I));
912 DIArray Subprograms = CU.getSubprograms();
913 for (unsigned J = 0, E2 = Subprograms.getNumElements(); J != E2; ++J) {
914 DISubprogram Subprogram(Subprograms.getElement(J));
915 if (Subprogram.describes(&F))
916 return Subprogram.getLineNumber();
921 report_fatal_error("No debug information found in function " + F.getName() +
925 /// \brief Generate branch weight metadata for all branches in \p F.
927 /// Branch weights are computed out of instruction samples using a
928 /// propagation heuristic. Propagation proceeds in 3 phases:
930 /// 1- Assignment of block weights. All the basic blocks in the function
931 /// are initial assigned the same weight as their most frequently
932 /// executed instruction.
934 /// 2- Creation of equivalence classes. Since samples may be missing from
935 /// blocks, we can fill in the gaps by setting the weights of all the
936 /// blocks in the same equivalence class to the same weight. To compute
937 /// the concept of equivalence, we use dominance and loop information.
938 /// Two blocks B1 and B2 are in the same equivalence class if B1
939 /// dominates B2, B2 post-dominates B1 and both are in the same loop.
941 /// 3- Propagation of block weights into edges. This uses a simple
942 /// propagation heuristic. The following rules are applied to every
943 /// block B in the CFG:
945 /// - If B has a single predecessor/successor, then the weight
946 /// of that edge is the weight of the block.
948 /// - If all the edges are known except one, and the weight of the
949 /// block is already known, the weight of the unknown edge will
950 /// be the weight of the block minus the sum of all the known
951 /// edges. If the sum of all the known edges is larger than B's weight,
952 /// we set the unknown edge weight to zero.
954 /// - If there is a self-referential edge, and the weight of the block is
955 /// known, the weight for that edge is set to the weight of the block
956 /// minus the weight of the other incoming edges to that block (if
959 /// Since this propagation is not guaranteed to finalize for every CFG, we
960 /// only allow it to proceed for a limited number of iterations (controlled
961 /// by -sample-profile-max-propagate-iterations).
963 /// FIXME: Try to replace this propagation heuristic with a scheme
964 /// that is guaranteed to finalize. A work-list approach similar to
965 /// the standard value propagation algorithm used by SSA-CCP might
968 /// Once all the branch weights are computed, we emit the MD_prof
969 /// metadata on B using the computed values for each of its branches.
971 /// \param F The function to query.
972 bool SampleFunctionProfile::emitAnnotations(Function &F, DominatorTree *DomTree,
973 PostDominatorTree *PostDomTree,
975 bool Changed = false;
977 // Initialize invariants used during computation and propagation.
978 HeaderLineno = getFunctionLoc(F);
979 DEBUG(dbgs() << "Line number for the first instruction in " << F.getName()
980 << ": " << HeaderLineno << "\n");
985 // Compute basic block weights.
986 Changed |= computeBlockWeights(F);
989 // Find equivalence classes.
990 findEquivalenceClasses(F);
992 // Propagate weights to all edges.
999 char SampleProfileLoader::ID = 0;
1000 INITIALIZE_PASS_BEGIN(SampleProfileLoader, "sample-profile",
1001 "Sample Profile loader", false, false)
1002 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
1003 INITIALIZE_PASS_DEPENDENCY(PostDominatorTree)
1004 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
1005 INITIALIZE_PASS_END(SampleProfileLoader, "sample-profile",
1006 "Sample Profile loader", false, false)
1008 bool SampleProfileLoader::doInitialization(Module &M) {
1009 Profiler.reset(new SampleModuleProfile(Filename));
1010 Profiler->loadText();
1014 FunctionPass *llvm::createSampleProfileLoaderPass() {
1015 return new SampleProfileLoader(SampleProfileFile);
1018 FunctionPass *llvm::createSampleProfileLoaderPass(StringRef Name) {
1019 return new SampleProfileLoader(Name);
1022 bool SampleProfileLoader::runOnFunction(Function &F) {
1023 DominatorTree *DT = &getAnalysis<DominatorTree>();
1024 PostDominatorTree *PDT = &getAnalysis<PostDominatorTree>();
1025 LoopInfo *LI = &getAnalysis<LoopInfo>();
1026 SampleFunctionProfile &FunctionProfile = Profiler->getProfile(F);
1027 if (!FunctionProfile.empty())
1028 return FunctionProfile.emitAnnotations(F, DT, PDT, LI);