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/Transforms/Scalar.h"
28 #include "llvm/ADT/DenseMap.h"
29 #include "llvm/ADT/OwningPtr.h"
30 #include "llvm/ADT/SmallPtrSet.h"
31 #include "llvm/ADT/SmallSet.h"
32 #include "llvm/ADT/StringMap.h"
33 #include "llvm/ADT/StringRef.h"
34 #include "llvm/Analysis/LoopInfo.h"
35 #include "llvm/Analysis/PostDominators.h"
36 #include "llvm/DebugInfo.h"
37 #include "llvm/IR/Constants.h"
38 #include "llvm/IR/Dominators.h"
39 #include "llvm/IR/Function.h"
40 #include "llvm/IR/Instructions.h"
41 #include "llvm/IR/LLVMContext.h"
42 #include "llvm/IR/MDBuilder.h"
43 #include "llvm/IR/Metadata.h"
44 #include "llvm/IR/Module.h"
45 #include "llvm/Pass.h"
46 #include "llvm/Support/CommandLine.h"
47 #include "llvm/Support/Debug.h"
48 #include "llvm/Support/InstIterator.h"
49 #include "llvm/Support/LineIterator.h"
50 #include "llvm/Support/MemoryBuffer.h"
51 #include "llvm/Support/Regex.h"
52 #include "llvm/Support/raw_ostream.h"
56 // Command line option to specify the file to read samples from. This is
57 // mainly used for debugging.
58 static cl::opt<std::string> SampleProfileFile(
59 "sample-profile-file", cl::init(""), cl::value_desc("filename"),
60 cl::desc("Profile file loaded by -sample-profile"), cl::Hidden);
61 static cl::opt<unsigned> SampleProfileMaxPropagateIterations(
62 "sample-profile-max-propagate-iterations", cl::init(100),
63 cl::desc("Maximum number of iterations to go through when propagating "
64 "sample block/edge weights through the CFG."));
68 typedef DenseMap<uint32_t, uint32_t> BodySampleMap;
69 typedef DenseMap<BasicBlock *, uint32_t> BlockWeightMap;
70 typedef DenseMap<BasicBlock *, BasicBlock *> EquivalenceClassMap;
71 typedef std::pair<BasicBlock *, BasicBlock *> Edge;
72 typedef DenseMap<Edge, uint32_t> EdgeWeightMap;
73 typedef DenseMap<BasicBlock *, SmallVector<BasicBlock *, 8> > BlockEdgeMap;
75 /// \brief Representation of the runtime profile for a function.
77 /// This data structure contains the runtime profile for a given
78 /// function. It contains the total number of samples collected
79 /// in the function and a map of samples collected in every statement.
80 class SampleFunctionProfile {
82 SampleFunctionProfile()
83 : TotalSamples(0), TotalHeadSamples(0), HeaderLineno(0), DT(0), PDT(0),
86 unsigned getFunctionLoc(Function &F);
87 bool emitAnnotations(Function &F, DominatorTree *DomTree,
88 PostDominatorTree *PostDomTree, LoopInfo *Loops);
89 uint32_t getInstWeight(Instruction &I);
90 uint32_t getBlockWeight(BasicBlock *B);
91 void addTotalSamples(unsigned Num) { TotalSamples += Num; }
92 void addHeadSamples(unsigned Num) { TotalHeadSamples += Num; }
93 void addBodySamples(unsigned LineOffset, unsigned Num) {
94 BodySamples[LineOffset] += Num;
96 void print(raw_ostream &OS);
97 void printEdgeWeight(raw_ostream &OS, Edge E);
98 void printBlockWeight(raw_ostream &OS, BasicBlock *BB);
99 void printBlockEquivalence(raw_ostream &OS, BasicBlock *BB);
100 bool computeBlockWeights(Function &F);
101 void findEquivalenceClasses(Function &F);
102 void findEquivalencesFor(BasicBlock *BB1,
103 SmallVector<BasicBlock *, 8> Descendants,
104 DominatorTreeBase<BasicBlock> *DomTree);
105 void propagateWeights(Function &F);
106 uint32_t visitEdge(Edge E, unsigned *NumUnknownEdges, Edge *UnknownEdge);
107 void buildEdges(Function &F);
108 bool propagateThroughEdges(Function &F);
109 bool empty() { return BodySamples.empty(); }
112 /// \brief Total number of samples collected inside this function.
114 /// Samples are cumulative, they include all the samples collected
115 /// inside this function and all its inlined callees.
116 unsigned TotalSamples;
118 /// \brief Total number of samples collected at the head of the function.
119 /// FIXME: Use head samples to estimate a cold/hot attribute for the function.
120 unsigned TotalHeadSamples;
122 /// \brief Line number for the function header. Used to compute relative
123 /// line numbers from the absolute line LOCs found in instruction locations.
124 /// The relative line numbers are needed to address the samples from the
126 unsigned HeaderLineno;
128 /// \brief Map line offsets to collected samples.
130 /// Each entry in this map contains the number of samples
131 /// collected at the corresponding line offset. All line locations
132 /// are an offset from the start of the function.
133 BodySampleMap BodySamples;
135 /// \brief Map basic blocks to their computed weights.
137 /// The weight of a basic block is defined to be the maximum
138 /// of all the instruction weights in that block.
139 BlockWeightMap BlockWeights;
141 /// \brief Map edges to their computed weights.
143 /// Edge weights are computed by propagating basic block weights in
144 /// SampleProfile::propagateWeights.
145 EdgeWeightMap EdgeWeights;
147 /// \brief Set of visited blocks during propagation.
148 SmallPtrSet<BasicBlock *, 128> VisitedBlocks;
150 /// \brief Set of visited edges during propagation.
151 SmallSet<Edge, 128> VisitedEdges;
153 /// \brief Equivalence classes for block weights.
155 /// Two blocks BB1 and BB2 are in the same equivalence class if they
156 /// dominate and post-dominate each other, and they are in the same loop
157 /// nest. When this happens, the two blocks are guaranteed to execute
158 /// the same number of times.
159 EquivalenceClassMap EquivalenceClass;
161 /// \brief Dominance, post-dominance and loop information.
163 PostDominatorTree *PDT;
166 /// \brief Predecessors for each basic block in the CFG.
167 BlockEdgeMap Predecessors;
169 /// \brief Successors for each basic block in the CFG.
170 BlockEdgeMap Successors;
173 /// \brief Sample-based profile reader.
175 /// Each profile contains sample counts for all the functions
176 /// executed. Inside each function, statements are annotated with the
177 /// collected samples on all the instructions associated with that
180 /// For this to produce meaningful data, the program needs to be
181 /// compiled with some debug information (at minimum, line numbers:
182 /// -gline-tables-only). Otherwise, it will be impossible to match IR
183 /// instructions to the line numbers collected by the profiler.
185 /// From the profile file, we are interested in collecting the
186 /// following information:
188 /// * A list of functions included in the profile (mangled names).
190 /// * For each function F:
191 /// 1. The total number of samples collected in F.
193 /// 2. The samples collected at each line in F. To provide some
194 /// protection against source code shuffling, line numbers should
195 /// be relative to the start of the function.
196 class SampleModuleProfile {
198 SampleModuleProfile(StringRef F) : Profiles(0), Filename(F) {}
202 void loadNative() { llvm_unreachable("not implemented"); }
203 void printFunctionProfile(raw_ostream &OS, StringRef FName);
204 void dumpFunctionProfile(StringRef FName);
205 SampleFunctionProfile &getProfile(const Function &F) {
206 return Profiles[F.getName()];
209 /// \brief Report a parse error message and stop compilation.
210 void reportParseError(int64_t LineNumber, Twine Msg) const {
211 report_fatal_error(Filename + ":" + Twine(LineNumber) + ": " + Msg + "\n");
215 /// \brief Map every function to its associated profile.
217 /// The profile of every function executed at runtime is collected
218 /// in the structure SampleFunctionProfile. This maps function objects
219 /// to their corresponding profiles.
220 StringMap<SampleFunctionProfile> Profiles;
222 /// \brief Path name to the file holding the profile data.
224 /// The format of this file is defined by each profiler
225 /// independently. If possible, the profiler should have a text
226 /// version of the profile format to be used in constructing test
227 /// cases and debugging.
231 /// \brief Sample profile pass.
233 /// This pass reads profile data from the file specified by
234 /// -sample-profile-file and annotates every affected function with the
235 /// profile information found in that file.
236 class SampleProfileLoader : public FunctionPass {
238 // Class identification, replacement for typeinfo
241 SampleProfileLoader(StringRef Name = SampleProfileFile)
242 : FunctionPass(ID), Profiler(0), Filename(Name) {
243 initializeSampleProfileLoaderPass(*PassRegistry::getPassRegistry());
246 virtual bool doInitialization(Module &M);
248 void dump() { Profiler->dump(); }
250 virtual const char *getPassName() const { return "Sample profile pass"; }
252 virtual bool runOnFunction(Function &F);
254 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
255 AU.setPreservesCFG();
256 AU.addRequired<LoopInfo>();
257 AU.addRequired<DominatorTree>();
258 AU.addRequired<PostDominatorTree>();
262 /// \brief Profile reader object.
263 OwningPtr<SampleModuleProfile> Profiler;
265 /// \brief Name of the profile file to load.
270 /// \brief Print this function profile on stream \p OS.
272 /// \param OS Stream to emit the output to.
273 void SampleFunctionProfile::print(raw_ostream &OS) {
274 OS << TotalSamples << ", " << TotalHeadSamples << ", " << BodySamples.size()
275 << " sampled lines\n";
276 for (BodySampleMap::const_iterator SI = BodySamples.begin(),
277 SE = BodySamples.end();
279 OS << "\tline offset: " << SI->first
280 << ", number of samples: " << SI->second << "\n";
284 /// \brief Print the weight of edge \p E on stream \p OS.
286 /// \param OS Stream to emit the output to.
287 /// \param E Edge to print.
288 void SampleFunctionProfile::printEdgeWeight(raw_ostream &OS, Edge E) {
289 OS << "weight[" << E.first->getName() << "->" << E.second->getName()
290 << "]: " << EdgeWeights[E] << "\n";
293 /// \brief Print the equivalence class of block \p BB on stream \p OS.
295 /// \param OS Stream to emit the output to.
296 /// \param BB Block to print.
297 void SampleFunctionProfile::printBlockEquivalence(raw_ostream &OS,
299 BasicBlock *Equiv = EquivalenceClass[BB];
300 OS << "equivalence[" << BB->getName()
301 << "]: " << ((Equiv) ? EquivalenceClass[BB]->getName() : "NONE") << "\n";
304 /// \brief Print the weight of block \p BB on stream \p OS.
306 /// \param OS Stream to emit the output to.
307 /// \param BB Block to print.
308 void SampleFunctionProfile::printBlockWeight(raw_ostream &OS, BasicBlock *BB) {
309 OS << "weight[" << BB->getName() << "]: " << BlockWeights[BB] << "\n";
312 /// \brief Print the function profile for \p FName on stream \p OS.
314 /// \param OS Stream to emit the output to.
315 /// \param FName Name of the function to print.
316 void SampleModuleProfile::printFunctionProfile(raw_ostream &OS,
318 OS << "Function: " << FName << ":\n";
319 Profiles[FName].print(OS);
322 /// \brief Dump the function profile for \p FName.
324 /// \param FName Name of the function to print.
325 void SampleModuleProfile::dumpFunctionProfile(StringRef FName) {
326 printFunctionProfile(dbgs(), FName);
329 /// \brief Dump all the function profiles found.
330 void SampleModuleProfile::dump() {
331 for (StringMap<SampleFunctionProfile>::const_iterator I = Profiles.begin(),
334 dumpFunctionProfile(I->getKey());
337 /// \brief Load samples from a text file.
339 /// The file contains a list of samples for every function executed at
340 /// runtime. Each function profile has the following format:
342 /// function1:total_samples:total_head_samples
343 /// offset1[.discriminator]: number_of_samples [fn1:num fn2:num ... ]
344 /// offset2[.discriminator]: number_of_samples [fn3:num fn4:num ... ]
346 /// offsetN[.discriminator]: number_of_samples [fn5:num fn6:num ... ]
348 /// Function names must be mangled in order for the profile loader to
349 /// match them in the current translation unit. The two numbers in the
350 /// function header specify how many total samples were accumulated in
351 /// the function (first number), and the total number of samples accumulated
352 /// at the prologue of the function (second number). This head sample
353 /// count provides an indicator of how frequent is the function invoked.
355 /// Each sampled line may contain several items. Some are optional
358 /// a- Source line offset. This number represents the line number
359 /// in the function where the sample was collected. The line number
360 /// is always relative to the line where symbol of the function
361 /// is defined. So, if the function has its header at line 280,
362 /// the offset 13 is at line 293 in the file.
364 /// b- [OPTIONAL] Discriminator. This is used if the sampled program
365 /// was compiled with DWARF discriminator support
366 /// (http://wiki.dwarfstd.org/index.php?title=Path_Discriminators)
367 /// This is currently only emitted by GCC and we just ignore it.
369 /// FIXME: Handle discriminators, since they are needed to distinguish
370 /// multiple control flow within a single source LOC.
372 /// c- Number of samples. This is the number of samples collected by
373 /// the profiler at this source location.
375 /// d- [OPTIONAL] Potential call targets and samples. If present, this
376 /// line contains a call instruction. This models both direct and
377 /// indirect calls. Each called target is listed together with the
378 /// number of samples. For example,
380 /// 130: 7 foo:3 bar:2 baz:7
382 /// The above means that at relative line offset 130 there is a
383 /// call instruction that calls one of foo(), bar() and baz(). With
384 /// baz() being the relatively more frequent call target.
386 /// FIXME: This is currently unhandled, but it has a lot of
387 /// potential for aiding the inliner.
390 /// Since this is a flat profile, a function that shows up more than
391 /// once gets all its samples aggregated across all its instances.
393 /// FIXME: flat profiles are too imprecise to provide good optimization
394 /// opportunities. Convert them to context-sensitive profile.
396 /// This textual representation is useful to generate unit tests and
397 /// for debugging purposes, but it should not be used to generate
398 /// profiles for large programs, as the representation is extremely
400 void SampleModuleProfile::loadText() {
401 OwningPtr<MemoryBuffer> Buffer;
402 error_code EC = MemoryBuffer::getFile(Filename, Buffer);
404 report_fatal_error("Could not open file " + Filename + ": " + EC.message());
405 line_iterator LineIt(*Buffer, '#');
407 // Read the profile of each function. Since each function may be
408 // mentioned more than once, and we are collecting flat profiles,
409 // accumulate samples as we parse them.
410 Regex HeadRE("^([^:]+):([0-9]+):([0-9]+)$");
411 Regex LineSample("^([0-9]+)(\\.[0-9]+)?: ([0-9]+)(.*)$");
412 while (!LineIt.is_at_eof()) {
413 // Read the header of each function. The function header should
416 // function_name:total_samples:total_head_samples
418 // See above for an explanation of each field.
419 SmallVector<StringRef, 3> Matches;
420 if (!HeadRE.match(*LineIt, &Matches))
421 reportParseError(LineIt.line_number(),
422 "Expected 'mangled_name:NUM:NUM', found " + *LineIt);
423 assert(Matches.size() == 4);
424 StringRef FName = Matches[1];
425 unsigned NumSamples, NumHeadSamples;
426 Matches[2].getAsInteger(10, NumSamples);
427 Matches[3].getAsInteger(10, NumHeadSamples);
428 Profiles[FName] = SampleFunctionProfile();
429 SampleFunctionProfile &FProfile = Profiles[FName];
430 FProfile.addTotalSamples(NumSamples);
431 FProfile.addHeadSamples(NumHeadSamples);
434 // Now read the body. The body of the function ends when we reach
435 // EOF or when we see the start of the next function.
436 while (!LineIt.is_at_eof() && isdigit((*LineIt)[0])) {
437 if (!LineSample.match(*LineIt, &Matches))
439 LineIt.line_number(),
440 "Expected 'NUM[.NUM]: NUM[ mangled_name:NUM]*', found " + *LineIt);
441 assert(Matches.size() == 5);
442 unsigned LineOffset, NumSamples;
443 Matches[1].getAsInteger(10, LineOffset);
445 // FIXME: Handle discriminator information (in Matches[2]).
447 Matches[3].getAsInteger(10, NumSamples);
449 // FIXME: Handle called targets (in Matches[4]).
451 // When dealing with instruction weights, we use the value
452 // zero to indicate the absence of a sample. If we read an
453 // actual zero from the profile file, return it as 1 to
454 // avoid the confusion later on.
457 FProfile.addBodySamples(LineOffset, NumSamples);
463 /// \brief Get the weight for an instruction.
465 /// The "weight" of an instruction \p Inst is the number of samples
466 /// collected on that instruction at runtime. To retrieve it, we
467 /// need to compute the line number of \p Inst relative to the start of its
468 /// function. We use HeaderLineno to compute the offset. We then
469 /// look up the samples collected for \p Inst using BodySamples.
471 /// \param Inst Instruction to query.
473 /// \returns The profiled weight of I.
474 uint32_t SampleFunctionProfile::getInstWeight(Instruction &Inst) {
475 unsigned Lineno = Inst.getDebugLoc().getLine();
476 if (Lineno < HeaderLineno)
478 unsigned LOffset = Lineno - HeaderLineno;
479 uint32_t Weight = BodySamples.lookup(LOffset);
480 DEBUG(dbgs() << " " << Lineno << ":" << Inst.getDebugLoc().getCol() << ":"
481 << Inst << " (line offset: " << LOffset
482 << " - weight: " << Weight << ")\n");
486 /// \brief Compute the weight of a basic block.
488 /// The weight of basic block \p B is the maximum weight of all the
489 /// instructions in B. The weight of \p B is computed and cached in
490 /// the BlockWeights map.
492 /// \param B The basic block to query.
494 /// \returns The computed weight of B.
495 uint32_t SampleFunctionProfile::getBlockWeight(BasicBlock *B) {
496 // If we've computed B's weight before, return it.
497 std::pair<BlockWeightMap::iterator, bool> Entry =
498 BlockWeights.insert(std::make_pair(B, 0));
500 return Entry.first->second;
502 // Otherwise, compute and cache B's weight.
504 for (BasicBlock::iterator I = B->begin(), E = B->end(); I != E; ++I) {
505 uint32_t InstWeight = getInstWeight(*I);
506 if (InstWeight > Weight)
509 Entry.first->second = Weight;
513 /// \brief Compute and store the weights of every basic block.
515 /// This populates the BlockWeights map by computing
516 /// the weights of every basic block in the CFG.
518 /// \param F The function to query.
519 bool SampleFunctionProfile::computeBlockWeights(Function &F) {
520 bool Changed = false;
521 DEBUG(dbgs() << "Block weights\n");
522 for (Function::iterator B = F.begin(), E = F.end(); B != E; ++B) {
523 uint32_t Weight = getBlockWeight(B);
524 Changed |= (Weight > 0);
525 DEBUG(printBlockWeight(dbgs(), B));
531 /// \brief Find equivalence classes for the given block.
533 /// This finds all the blocks that are guaranteed to execute the same
534 /// number of times as \p BB1. To do this, it traverses all the the
535 /// descendants of \p BB1 in the dominator or post-dominator tree.
537 /// A block BB2 will be in the same equivalence class as \p BB1 if
538 /// the following holds:
540 /// 1- \p BB1 is a descendant of BB2 in the opposite tree. So, if BB2
541 /// is a descendant of \p BB1 in the dominator tree, then BB2 should
542 /// dominate BB1 in the post-dominator tree.
544 /// 2- Both BB2 and \p BB1 must be in the same loop.
546 /// For every block BB2 that meets those two requirements, we set BB2's
547 /// equivalence class to \p BB1.
549 /// \param BB1 Block to check.
550 /// \param Descendants Descendants of \p BB1 in either the dom or pdom tree.
551 /// \param DomTree Opposite dominator tree. If \p Descendants is filled
552 /// with blocks from \p BB1's dominator tree, then
553 /// this is the post-dominator tree, and vice versa.
554 void SampleFunctionProfile::findEquivalencesFor(
555 BasicBlock *BB1, SmallVector<BasicBlock *, 8> Descendants,
556 DominatorTreeBase<BasicBlock> *DomTree) {
557 for (SmallVectorImpl<BasicBlock *>::iterator I = Descendants.begin(),
558 E = Descendants.end();
560 BasicBlock *BB2 = *I;
561 bool IsDomParent = DomTree->dominates(BB2, BB1);
562 bool IsInSameLoop = LI->getLoopFor(BB1) == LI->getLoopFor(BB2);
563 if (BB1 != BB2 && VisitedBlocks.insert(BB2) && IsDomParent &&
565 EquivalenceClass[BB2] = BB1;
567 // If BB2 is heavier than BB1, make BB2 have the same weight
570 // Note that we don't worry about the opposite situation here
571 // (when BB2 is lighter than BB1). We will deal with this
572 // during the propagation phase. Right now, we just want to
573 // make sure that BB1 has the largest weight of all the
574 // members of its equivalence set.
575 uint32_t &BB1Weight = BlockWeights[BB1];
576 uint32_t &BB2Weight = BlockWeights[BB2];
577 BB1Weight = std::max(BB1Weight, BB2Weight);
582 /// \brief Find equivalence classes.
584 /// Since samples may be missing from blocks, we can fill in the gaps by setting
585 /// the weights of all the blocks in the same equivalence class to the same
586 /// weight. To compute the concept of equivalence, we use dominance and loop
587 /// information. Two blocks B1 and B2 are in the same equivalence class if B1
588 /// dominates B2, B2 post-dominates B1 and both are in the same loop.
590 /// \param F The function to query.
591 void SampleFunctionProfile::findEquivalenceClasses(Function &F) {
592 SmallVector<BasicBlock *, 8> DominatedBBs;
593 DEBUG(dbgs() << "\nBlock equivalence classes\n");
594 // Find equivalence sets based on dominance and post-dominance information.
595 for (Function::iterator B = F.begin(), E = F.end(); B != E; ++B) {
598 // Compute BB1's equivalence class once.
599 if (EquivalenceClass.count(BB1)) {
600 DEBUG(printBlockEquivalence(dbgs(), BB1));
604 // By default, blocks are in their own equivalence class.
605 EquivalenceClass[BB1] = BB1;
607 // Traverse all the blocks dominated by BB1. We are looking for
608 // every basic block BB2 such that:
610 // 1- BB1 dominates BB2.
611 // 2- BB2 post-dominates BB1.
612 // 3- BB1 and BB2 are in the same loop nest.
614 // If all those conditions hold, it means that BB2 is executed
615 // as many times as BB1, so they are placed in the same equivalence
616 // class by making BB2's equivalence class be BB1.
617 DominatedBBs.clear();
618 DT->getDescendants(BB1, DominatedBBs);
619 findEquivalencesFor(BB1, DominatedBBs, PDT->DT);
621 // Repeat the same logic for all the blocks post-dominated by BB1.
622 // We are looking for every basic block BB2 such that:
624 // 1- BB1 post-dominates BB2.
625 // 2- BB2 dominates BB1.
626 // 3- BB1 and BB2 are in the same loop nest.
628 // If all those conditions hold, BB2's equivalence class is BB1.
629 DominatedBBs.clear();
630 PDT->getDescendants(BB1, DominatedBBs);
631 findEquivalencesFor(BB1, DominatedBBs, DT->DT);
633 DEBUG(printBlockEquivalence(dbgs(), BB1));
636 // Assign weights to equivalence classes.
638 // All the basic blocks in the same equivalence class will execute
639 // the same number of times. Since we know that the head block in
640 // each equivalence class has the largest weight, assign that weight
641 // to all the blocks in that equivalence class.
642 DEBUG(dbgs() << "\nAssign the same weight to all blocks in the same class\n");
643 for (Function::iterator B = F.begin(), E = F.end(); B != E; ++B) {
645 BasicBlock *EquivBB = EquivalenceClass[BB];
647 BlockWeights[BB] = BlockWeights[EquivBB];
648 DEBUG(printBlockWeight(dbgs(), BB));
652 /// \brief Visit the given edge to decide if it has a valid weight.
654 /// If \p E has not been visited before, we copy to \p UnknownEdge
655 /// and increment the count of unknown edges.
657 /// \param E Edge to visit.
658 /// \param NumUnknownEdges Current number of unknown edges.
659 /// \param UnknownEdge Set if E has not been visited before.
661 /// \returns E's weight, if known. Otherwise, return 0.
662 uint32_t SampleFunctionProfile::visitEdge(Edge E, unsigned *NumUnknownEdges,
664 if (!VisitedEdges.count(E)) {
665 (*NumUnknownEdges)++;
670 return EdgeWeights[E];
673 /// \brief Propagate weights through incoming/outgoing edges.
675 /// If the weight of a basic block is known, and there is only one edge
676 /// with an unknown weight, we can calculate the weight of that edge.
678 /// Similarly, if all the edges have a known count, we can calculate the
679 /// count of the basic block, if needed.
681 /// \param F Function to process.
683 /// \returns True if new weights were assigned to edges or blocks.
684 bool SampleFunctionProfile::propagateThroughEdges(Function &F) {
685 bool Changed = false;
686 DEBUG(dbgs() << "\nPropagation through edges\n");
687 for (Function::iterator BI = F.begin(), EI = F.end(); BI != EI; ++BI) {
690 // Visit all the predecessor and successor edges to determine
691 // which ones have a weight assigned already. Note that it doesn't
692 // matter that we only keep track of a single unknown edge. The
693 // only case we are interested in handling is when only a single
694 // edge is unknown (see setEdgeOrBlockWeight).
695 for (unsigned i = 0; i < 2; i++) {
696 uint32_t TotalWeight = 0;
697 unsigned NumUnknownEdges = 0;
698 Edge UnknownEdge, SelfReferentialEdge;
701 // First, visit all predecessor edges.
702 for (size_t I = 0; I < Predecessors[BB].size(); I++) {
703 Edge E = std::make_pair(Predecessors[BB][I], BB);
704 TotalWeight += visitEdge(E, &NumUnknownEdges, &UnknownEdge);
705 if (E.first == E.second)
706 SelfReferentialEdge = E;
709 // On the second round, visit all successor edges.
710 for (size_t I = 0; I < Successors[BB].size(); I++) {
711 Edge E = std::make_pair(BB, Successors[BB][I]);
712 TotalWeight += visitEdge(E, &NumUnknownEdges, &UnknownEdge);
716 // After visiting all the edges, there are three cases that we
717 // can handle immediately:
719 // - All the edge weights are known (i.e., NumUnknownEdges == 0).
720 // In this case, we simply check that the sum of all the edges
721 // is the same as BB's weight. If not, we change BB's weight
722 // to match. Additionally, if BB had not been visited before,
723 // we mark it visited.
725 // - Only one edge is unknown and BB has already been visited.
726 // In this case, we can compute the weight of the edge by
727 // subtracting the total block weight from all the known
728 // edge weights. If the edges weight more than BB, then the
729 // edge of the last remaining edge is set to zero.
731 // - There exists a self-referential edge and the weight of BB is
732 // known. In this case, this edge can be based on BB's weight.
733 // We add up all the other known edges and set the weight on
734 // the self-referential edge as we did in the previous case.
736 // In any other case, we must continue iterating. Eventually,
737 // all edges will get a weight, or iteration will stop when
738 // it reaches SampleProfileMaxPropagateIterations.
739 if (NumUnknownEdges <= 1) {
740 uint32_t &BBWeight = BlockWeights[BB];
741 if (NumUnknownEdges == 0) {
742 // If we already know the weight of all edges, the weight of the
743 // basic block can be computed. It should be no larger than the sum
744 // of all edge weights.
745 if (TotalWeight > BBWeight) {
746 BBWeight = TotalWeight;
748 DEBUG(dbgs() << "All edge weights for " << BB->getName()
749 << " known. Set weight for block: ";
750 printBlockWeight(dbgs(), BB););
752 if (VisitedBlocks.insert(BB))
754 } else if (NumUnknownEdges == 1 && VisitedBlocks.count(BB)) {
755 // If there is a single unknown edge and the block has been
756 // visited, then we can compute E's weight.
757 if (BBWeight >= TotalWeight)
758 EdgeWeights[UnknownEdge] = BBWeight - TotalWeight;
760 EdgeWeights[UnknownEdge] = 0;
761 VisitedEdges.insert(UnknownEdge);
763 DEBUG(dbgs() << "Set weight for edge: ";
764 printEdgeWeight(dbgs(), UnknownEdge));
766 } else if (SelfReferentialEdge.first && VisitedBlocks.count(BB)) {
767 uint32_t &BBWeight = BlockWeights[BB];
768 // We have a self-referential edge and the weight of BB is known.
769 if (BBWeight >= TotalWeight)
770 EdgeWeights[SelfReferentialEdge] = BBWeight - TotalWeight;
772 EdgeWeights[SelfReferentialEdge] = 0;
773 VisitedEdges.insert(SelfReferentialEdge);
775 DEBUG(dbgs() << "Set self-referential edge weight to: ";
776 printEdgeWeight(dbgs(), SelfReferentialEdge));
784 /// \brief Build in/out edge lists for each basic block in the CFG.
786 /// We are interested in unique edges. If a block B1 has multiple
787 /// edges to another block B2, we only add a single B1->B2 edge.
788 void SampleFunctionProfile::buildEdges(Function &F) {
789 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
792 // Add predecessors for B1.
793 SmallPtrSet<BasicBlock *, 16> Visited;
794 if (!Predecessors[B1].empty())
795 llvm_unreachable("Found a stale predecessors list in a basic block.");
796 for (pred_iterator PI = pred_begin(B1), PE = pred_end(B1); PI != PE; ++PI) {
797 BasicBlock *B2 = *PI;
798 if (Visited.insert(B2))
799 Predecessors[B1].push_back(B2);
802 // Add successors for B1.
804 if (!Successors[B1].empty())
805 llvm_unreachable("Found a stale successors list in a basic block.");
806 for (succ_iterator SI = succ_begin(B1), SE = succ_end(B1); SI != SE; ++SI) {
807 BasicBlock *B2 = *SI;
808 if (Visited.insert(B2))
809 Successors[B1].push_back(B2);
814 /// \brief Propagate weights into edges
816 /// The following rules are applied to every block B in the CFG:
818 /// - If B has a single predecessor/successor, then the weight
819 /// of that edge is the weight of the block.
821 /// - If all incoming or outgoing edges are known except one, and the
822 /// weight of the block is already known, the weight of the unknown
823 /// edge will 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 B'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
831 void SampleFunctionProfile::propagateWeights(Function &F) {
835 // Before propagation starts, build, for each block, a list of
836 // unique predecessors and successors. This is necessary to handle
837 // identical edges in multiway branches. Since we visit all blocks and all
838 // edges of the CFG, it is cleaner to build these lists once at the start
842 // Propagate until we converge or we go past the iteration limit.
843 while (Changed && i++ < SampleProfileMaxPropagateIterations) {
844 Changed = propagateThroughEdges(F);
847 // Generate MD_prof metadata for every branch instruction using the
848 // edge weights computed during propagation.
849 DEBUG(dbgs() << "\nPropagation complete. Setting branch weights\n");
850 MDBuilder MDB(F.getContext());
851 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
853 TerminatorInst *TI = B->getTerminator();
854 if (TI->getNumSuccessors() == 1)
856 if (!isa<BranchInst>(TI) && !isa<SwitchInst>(TI))
859 DEBUG(dbgs() << "\nGetting weights for branch at line "
860 << TI->getDebugLoc().getLine() << ":"
861 << TI->getDebugLoc().getCol() << ".\n");
862 SmallVector<uint32_t, 4> Weights;
863 bool AllWeightsZero = true;
864 for (unsigned I = 0; I < TI->getNumSuccessors(); ++I) {
865 BasicBlock *Succ = TI->getSuccessor(I);
866 Edge E = std::make_pair(B, Succ);
867 uint32_t Weight = EdgeWeights[E];
868 DEBUG(dbgs() << "\t"; printEdgeWeight(dbgs(), E));
869 Weights.push_back(Weight);
871 AllWeightsZero = false;
874 // Only set weights if there is at least one non-zero weight.
875 // In any other case, let the analyzer set weights.
876 if (!AllWeightsZero) {
877 DEBUG(dbgs() << "SUCCESS. Found non-zero weights.\n");
878 TI->setMetadata(llvm::LLVMContext::MD_prof,
879 MDB.createBranchWeights(Weights));
881 DEBUG(dbgs() << "SKIPPED. All branch weights are zero.\n");
886 /// \brief Get the line number for the function header.
888 /// This looks up function \p F in the current compilation unit and
889 /// retrieves the line number where the function is defined. This is
890 /// line 0 for all the samples read from the profile file. Every line
891 /// number is relative to this line.
893 /// \param F Function object to query.
895 /// \returns the line number where \p F is defined.
896 unsigned SampleFunctionProfile::getFunctionLoc(Function &F) {
897 NamedMDNode *CUNodes = F.getParent()->getNamedMetadata("llvm.dbg.cu");
899 for (unsigned I = 0, E1 = CUNodes->getNumOperands(); I != E1; ++I) {
900 DICompileUnit CU(CUNodes->getOperand(I));
901 DIArray Subprograms = CU.getSubprograms();
902 for (unsigned J = 0, E2 = Subprograms.getNumElements(); J != E2; ++J) {
903 DISubprogram Subprogram(Subprograms.getElement(J));
904 if (Subprogram.describes(&F))
905 return Subprogram.getLineNumber();
910 report_fatal_error("No debug information found in function " + F.getName() +
914 /// \brief Generate branch weight metadata for all branches in \p F.
916 /// Branch weights are computed out of instruction samples using a
917 /// propagation heuristic. Propagation proceeds in 3 phases:
919 /// 1- Assignment of block weights. All the basic blocks in the function
920 /// are initial assigned the same weight as their most frequently
921 /// executed instruction.
923 /// 2- Creation of equivalence classes. Since samples may be missing from
924 /// blocks, we can fill in the gaps by setting the weights of all the
925 /// blocks in the same equivalence class to the same weight. To compute
926 /// the concept of equivalence, we use dominance and loop information.
927 /// Two blocks B1 and B2 are in the same equivalence class if B1
928 /// dominates B2, B2 post-dominates B1 and both are in the same loop.
930 /// 3- Propagation of block weights into edges. This uses a simple
931 /// propagation heuristic. The following rules are applied to every
932 /// block B in the CFG:
934 /// - If B has a single predecessor/successor, then the weight
935 /// of that edge is the weight of the block.
937 /// - If all the edges are known except one, and the weight of the
938 /// block is already known, the weight of the unknown edge will
939 /// be the weight of the block minus the sum of all the known
940 /// edges. If the sum of all the known edges is larger than B's weight,
941 /// we set the unknown edge weight to zero.
943 /// - If there is a self-referential edge, and the weight of the block is
944 /// known, the weight for that edge is set to the weight of the block
945 /// minus the weight of the other incoming edges to that block (if
948 /// Since this propagation is not guaranteed to finalize for every CFG, we
949 /// only allow it to proceed for a limited number of iterations (controlled
950 /// by -sample-profile-max-propagate-iterations).
952 /// FIXME: Try to replace this propagation heuristic with a scheme
953 /// that is guaranteed to finalize. A work-list approach similar to
954 /// the standard value propagation algorithm used by SSA-CCP might
957 /// Once all the branch weights are computed, we emit the MD_prof
958 /// metadata on B using the computed values for each of its branches.
960 /// \param F The function to query.
961 bool SampleFunctionProfile::emitAnnotations(Function &F, DominatorTree *DomTree,
962 PostDominatorTree *PostDomTree,
964 bool Changed = false;
966 // Initialize invariants used during computation and propagation.
967 HeaderLineno = getFunctionLoc(F);
968 DEBUG(dbgs() << "Line number for the first instruction in " << F.getName()
969 << ": " << HeaderLineno << "\n");
974 // Compute basic block weights.
975 Changed |= computeBlockWeights(F);
978 // Find equivalence classes.
979 findEquivalenceClasses(F);
981 // Propagate weights to all edges.
988 char SampleProfileLoader::ID = 0;
989 INITIALIZE_PASS_BEGIN(SampleProfileLoader, "sample-profile",
990 "Sample Profile loader", false, false)
991 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
992 INITIALIZE_PASS_DEPENDENCY(PostDominatorTree)
993 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
994 INITIALIZE_PASS_END(SampleProfileLoader, "sample-profile",
995 "Sample Profile loader", false, false)
997 bool SampleProfileLoader::doInitialization(Module &M) {
998 Profiler.reset(new SampleModuleProfile(Filename));
999 Profiler->loadText();
1003 FunctionPass *llvm::createSampleProfileLoaderPass() {
1004 return new SampleProfileLoader(SampleProfileFile);
1007 FunctionPass *llvm::createSampleProfileLoaderPass(StringRef Name) {
1008 return new SampleProfileLoader(Name);
1011 bool SampleProfileLoader::runOnFunction(Function &F) {
1012 DominatorTree *DT = &getAnalysis<DominatorTree>();
1013 PostDominatorTree *PDT = &getAnalysis<PostDominatorTree>();
1014 LoopInfo *LI = &getAnalysis<LoopInfo>();
1015 SampleFunctionProfile &FunctionProfile = Profiler->getProfile(F);
1016 if (!FunctionProfile.empty())
1017 return FunctionProfile.emitAnnotations(F, DT, PDT, LI);