blob: d48e43d47c5d29ba3418eea5ff3f4089f6e025c1 [file] [log] [blame]
Diego Novillo8d6568b2013-11-13 12:22:21 +00001//===- SampleProfile.cpp - Incorporate sample profiles into the IR --------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
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.
14//
15// This pass generates branch weight annotations on the IR:
16//
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.
22//
23//===----------------------------------------------------------------------===//
24
25#define DEBUG_TYPE "sample-profile"
26
Chandler Carruth07baed52014-01-13 08:04:33 +000027#include "llvm/Transforms/Scalar.h"
Diego Novillo8d6568b2013-11-13 12:22:21 +000028#include "llvm/ADT/DenseMap.h"
Diego Novillo0accb3d2014-01-10 23:23:46 +000029#include "llvm/ADT/SmallPtrSet.h"
Chandler Carruth07baed52014-01-13 08:04:33 +000030#include "llvm/ADT/SmallSet.h"
Diego Novillo8d6568b2013-11-13 12:22:21 +000031#include "llvm/ADT/StringMap.h"
32#include "llvm/ADT/StringRef.h"
Diego Novillo0accb3d2014-01-10 23:23:46 +000033#include "llvm/Analysis/LoopInfo.h"
Chandler Carruth07baed52014-01-13 08:04:33 +000034#include "llvm/Analysis/PostDominators.h"
Diego Novillo8d6568b2013-11-13 12:22:21 +000035#include "llvm/IR/Constants.h"
Chandler Carruth9a4c9e52014-03-06 00:46:21 +000036#include "llvm/IR/DebugInfo.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000037#include "llvm/IR/Dominators.h"
Diego Novillo8d6568b2013-11-13 12:22:21 +000038#include "llvm/IR/Function.h"
Chandler Carruth83948572014-03-04 10:30:26 +000039#include "llvm/IR/InstIterator.h"
Diego Novillo8d6568b2013-11-13 12:22:21 +000040#include "llvm/IR/Instructions.h"
41#include "llvm/IR/LLVMContext.h"
Diego Novillo8d6568b2013-11-13 12:22:21 +000042#include "llvm/IR/MDBuilder.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000043#include "llvm/IR/Metadata.h"
Diego Novillo8d6568b2013-11-13 12:22:21 +000044#include "llvm/IR/Module.h"
45#include "llvm/Pass.h"
46#include "llvm/Support/CommandLine.h"
47#include "llvm/Support/Debug.h"
Diego Novillo9518b632014-01-10 23:23:51 +000048#include "llvm/Support/LineIterator.h"
Diego Novillo8d6568b2013-11-13 12:22:21 +000049#include "llvm/Support/MemoryBuffer.h"
50#include "llvm/Support/Regex.h"
51#include "llvm/Support/raw_ostream.h"
Logan Chien61c6df02014-02-22 06:34:10 +000052#include <cctype>
Diego Novillo8d6568b2013-11-13 12:22:21 +000053
54using namespace llvm;
55
56// Command line option to specify the file to read samples from. This is
57// mainly used for debugging.
58static 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);
Diego Novillo0accb3d2014-01-10 23:23:46 +000061static 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."));
Diego Novillo8d6568b2013-11-13 12:22:21 +000065
66namespace {
Diego Novilloc0dd1032013-11-26 20:37:33 +000067
68typedef DenseMap<uint32_t, uint32_t> BodySampleMap;
69typedef DenseMap<BasicBlock *, uint32_t> BlockWeightMap;
Diego Novillo0accb3d2014-01-10 23:23:46 +000070typedef DenseMap<BasicBlock *, BasicBlock *> EquivalenceClassMap;
71typedef std::pair<BasicBlock *, BasicBlock *> Edge;
72typedef DenseMap<Edge, uint32_t> EdgeWeightMap;
73typedef DenseMap<BasicBlock *, SmallVector<BasicBlock *, 8> > BlockEdgeMap;
Diego Novilloc0dd1032013-11-26 20:37:33 +000074
75/// \brief Representation of the runtime profile for a function.
76///
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.
80class SampleFunctionProfile {
81public:
Diego Novillo0accb3d2014-01-10 23:23:46 +000082 SampleFunctionProfile()
83 : TotalSamples(0), TotalHeadSamples(0), HeaderLineno(0), DT(0), PDT(0),
84 LI(0) {}
Diego Novilloc0dd1032013-11-26 20:37:33 +000085
Diego Novillo0accb3d2014-01-10 23:23:46 +000086 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);
Diego Novilloc0dd1032013-11-26 20:37:33 +000091 void addTotalSamples(unsigned Num) { TotalSamples += Num; }
92 void addHeadSamples(unsigned Num) { TotalHeadSamples += Num; }
93 void addBodySamples(unsigned LineOffset, unsigned Num) {
94 BodySamples[LineOffset] += Num;
95 }
96 void print(raw_ostream &OS);
Diego Novillo0accb3d2014-01-10 23:23:46 +000097 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(); }
Diego Novilloc0dd1032013-11-26 20:37:33 +0000110
111protected:
112 /// \brief Total number of samples collected inside this function.
113 ///
114 /// Samples are cumulative, they include all the samples collected
115 /// inside this function and all its inlined callees.
116 unsigned TotalSamples;
117
Diego Novillo0accb3d2014-01-10 23:23:46 +0000118 /// \brief Total number of samples collected at the head of the function.
Diego Novillo9518b632014-01-10 23:23:51 +0000119 /// FIXME: Use head samples to estimate a cold/hot attribute for the function.
Diego Novilloc0dd1032013-11-26 20:37:33 +0000120 unsigned TotalHeadSamples;
121
Diego Novillo0accb3d2014-01-10 23:23:46 +0000122 /// \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
125 /// profile file.
126 unsigned HeaderLineno;
127
Diego Novilloc0dd1032013-11-26 20:37:33 +0000128 /// \brief Map line offsets to collected samples.
129 ///
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;
134
135 /// \brief Map basic blocks to their computed weights.
136 ///
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;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000140
141 /// \brief Map edges to their computed weights.
142 ///
143 /// Edge weights are computed by propagating basic block weights in
144 /// SampleProfile::propagateWeights.
145 EdgeWeightMap EdgeWeights;
146
147 /// \brief Set of visited blocks during propagation.
148 SmallPtrSet<BasicBlock *, 128> VisitedBlocks;
149
150 /// \brief Set of visited edges during propagation.
151 SmallSet<Edge, 128> VisitedEdges;
152
153 /// \brief Equivalence classes for block weights.
154 ///
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;
160
161 /// \brief Dominance, post-dominance and loop information.
162 DominatorTree *DT;
163 PostDominatorTree *PDT;
164 LoopInfo *LI;
165
166 /// \brief Predecessors for each basic block in the CFG.
167 BlockEdgeMap Predecessors;
168
169 /// \brief Successors for each basic block in the CFG.
170 BlockEdgeMap Successors;
Diego Novilloc0dd1032013-11-26 20:37:33 +0000171};
172
Diego Novillo8d6568b2013-11-13 12:22:21 +0000173/// \brief Sample-based profile reader.
174///
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
178/// statement.
179///
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.
184///
185/// From the profile file, we are interested in collecting the
186/// following information:
187///
188/// * A list of functions included in the profile (mangled names).
189///
190/// * For each function F:
191/// 1. The total number of samples collected in F.
192///
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.
Diego Novilloc0dd1032013-11-26 20:37:33 +0000196class SampleModuleProfile {
Diego Novillo8d6568b2013-11-13 12:22:21 +0000197public:
Diego Novilloc0dd1032013-11-26 20:37:33 +0000198 SampleModuleProfile(StringRef F) : Profiles(0), Filename(F) {}
Diego Novillo8d6568b2013-11-13 12:22:21 +0000199
Alexey Samsonovaa19c0a2013-11-13 13:09:39 +0000200 void dump();
201 void loadText();
202 void loadNative() { llvm_unreachable("not implemented"); }
Diego Novillo8d6568b2013-11-13 12:22:21 +0000203 void printFunctionProfile(raw_ostream &OS, StringRef FName);
204 void dumpFunctionProfile(StringRef FName);
Diego Novilloc0dd1032013-11-26 20:37:33 +0000205 SampleFunctionProfile &getProfile(const Function &F) {
206 return Profiles[F.getName()];
207 }
Diego Novillo8d6568b2013-11-13 12:22:21 +0000208
Diego Novillo9518b632014-01-10 23:23:51 +0000209 /// \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");
212 }
213
Diego Novillo8d6568b2013-11-13 12:22:21 +0000214protected:
Diego Novillo8d6568b2013-11-13 12:22:21 +0000215 /// \brief Map every function to its associated profile.
216 ///
217 /// The profile of every function executed at runtime is collected
Diego Novilloc0dd1032013-11-26 20:37:33 +0000218 /// in the structure SampleFunctionProfile. This maps function objects
Diego Novillo8d6568b2013-11-13 12:22:21 +0000219 /// to their corresponding profiles.
Diego Novilloc0dd1032013-11-26 20:37:33 +0000220 StringMap<SampleFunctionProfile> Profiles;
Diego Novillo8d6568b2013-11-13 12:22:21 +0000221
222 /// \brief Path name to the file holding the profile data.
223 ///
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.
228 StringRef Filename;
229};
230
Diego Novillo8d6568b2013-11-13 12:22:21 +0000231/// \brief Sample profile pass.
232///
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.
236class SampleProfileLoader : public FunctionPass {
237public:
238 // Class identification, replacement for typeinfo
239 static char ID;
240
241 SampleProfileLoader(StringRef Name = SampleProfileFile)
Ahmed Charles56440fd2014-03-06 05:51:42 +0000242 : FunctionPass(ID), Profiler(), Filename(Name) {
Diego Novillo8d6568b2013-11-13 12:22:21 +0000243 initializeSampleProfileLoaderPass(*PassRegistry::getPassRegistry());
244 }
245
Craig Topper3e4c6972014-03-05 09:10:37 +0000246 bool doInitialization(Module &M) override;
Diego Novillo8d6568b2013-11-13 12:22:21 +0000247
248 void dump() { Profiler->dump(); }
249
Craig Topper3e4c6972014-03-05 09:10:37 +0000250 const char *getPassName() const override { return "Sample profile pass"; }
Diego Novillo8d6568b2013-11-13 12:22:21 +0000251
Craig Topper3e4c6972014-03-05 09:10:37 +0000252 bool runOnFunction(Function &F) override;
Diego Novillo8d6568b2013-11-13 12:22:21 +0000253
Craig Topper3e4c6972014-03-05 09:10:37 +0000254 void getAnalysisUsage(AnalysisUsage &AU) const override {
Diego Novillo8d6568b2013-11-13 12:22:21 +0000255 AU.setPreservesCFG();
Diego Novillo0accb3d2014-01-10 23:23:46 +0000256 AU.addRequired<LoopInfo>();
Chandler Carruth73523022014-01-13 13:07:17 +0000257 AU.addRequired<DominatorTreeWrapperPass>();
Diego Novillo0accb3d2014-01-10 23:23:46 +0000258 AU.addRequired<PostDominatorTree>();
Diego Novillo8d6568b2013-11-13 12:22:21 +0000259 }
260
261protected:
262 /// \brief Profile reader object.
Ahmed Charles56440fd2014-03-06 05:51:42 +0000263 std::unique_ptr<SampleModuleProfile> Profiler;
Diego Novillo8d6568b2013-11-13 12:22:21 +0000264
265 /// \brief Name of the profile file to load.
266 StringRef Filename;
267};
268}
269
Diego Novilloc0dd1032013-11-26 20:37:33 +0000270/// \brief Print this function profile on stream \p OS.
Diego Novillo8d6568b2013-11-13 12:22:21 +0000271///
272/// \param OS Stream to emit the output to.
Diego Novilloc0dd1032013-11-26 20:37:33 +0000273void SampleFunctionProfile::print(raw_ostream &OS) {
274 OS << TotalSamples << ", " << TotalHeadSamples << ", " << BodySamples.size()
Diego Novillo8d6568b2013-11-13 12:22:21 +0000275 << " sampled lines\n";
Diego Novilloc0dd1032013-11-26 20:37:33 +0000276 for (BodySampleMap::const_iterator SI = BodySamples.begin(),
277 SE = BodySamples.end();
Diego Novillo8d6568b2013-11-13 12:22:21 +0000278 SI != SE; ++SI)
279 OS << "\tline offset: " << SI->first
280 << ", number of samples: " << SI->second << "\n";
281 OS << "\n";
282}
283
Diego Novillo0accb3d2014-01-10 23:23:46 +0000284/// \brief Print the weight of edge \p E on stream \p OS.
285///
286/// \param OS Stream to emit the output to.
287/// \param E Edge to print.
288void SampleFunctionProfile::printEdgeWeight(raw_ostream &OS, Edge E) {
289 OS << "weight[" << E.first->getName() << "->" << E.second->getName()
290 << "]: " << EdgeWeights[E] << "\n";
291}
292
293/// \brief Print the equivalence class of block \p BB on stream \p OS.
294///
295/// \param OS Stream to emit the output to.
296/// \param BB Block to print.
297void SampleFunctionProfile::printBlockEquivalence(raw_ostream &OS,
298 BasicBlock *BB) {
299 BasicBlock *Equiv = EquivalenceClass[BB];
300 OS << "equivalence[" << BB->getName()
301 << "]: " << ((Equiv) ? EquivalenceClass[BB]->getName() : "NONE") << "\n";
302}
303
304/// \brief Print the weight of block \p BB on stream \p OS.
305///
306/// \param OS Stream to emit the output to.
307/// \param BB Block to print.
308void SampleFunctionProfile::printBlockWeight(raw_ostream &OS, BasicBlock *BB) {
309 OS << "weight[" << BB->getName() << "]: " << BlockWeights[BB] << "\n";
310}
311
Diego Novilloc0dd1032013-11-26 20:37:33 +0000312/// \brief Print the function profile for \p FName on stream \p OS.
313///
314/// \param OS Stream to emit the output to.
315/// \param FName Name of the function to print.
316void SampleModuleProfile::printFunctionProfile(raw_ostream &OS,
317 StringRef FName) {
318 OS << "Function: " << FName << ":\n";
319 Profiles[FName].print(OS);
320}
321
Diego Novillo8d6568b2013-11-13 12:22:21 +0000322/// \brief Dump the function profile for \p FName.
323///
324/// \param FName Name of the function to print.
Diego Novilloc0dd1032013-11-26 20:37:33 +0000325void SampleModuleProfile::dumpFunctionProfile(StringRef FName) {
Diego Novillo8d6568b2013-11-13 12:22:21 +0000326 printFunctionProfile(dbgs(), FName);
327}
328
329/// \brief Dump all the function profiles found.
Diego Novilloc0dd1032013-11-26 20:37:33 +0000330void SampleModuleProfile::dump() {
331 for (StringMap<SampleFunctionProfile>::const_iterator I = Profiles.begin(),
332 E = Profiles.end();
Diego Novillo8d6568b2013-11-13 12:22:21 +0000333 I != E; ++I)
334 dumpFunctionProfile(I->getKey());
335}
336
337/// \brief Load samples from a text file.
338///
Diego Novillo9518b632014-01-10 23:23:51 +0000339/// The file contains a list of samples for every function executed at
340/// runtime. Each function profile has the following format:
Diego Novillo8d6568b2013-11-13 12:22:21 +0000341///
Diego Novillo9518b632014-01-10 23:23:51 +0000342/// 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 ... ]
Diego Novillo8d6568b2013-11-13 12:22:21 +0000345/// ...
Diego Novillo9518b632014-01-10 23:23:51 +0000346/// offsetN[.discriminator]: number_of_samples [fn5:num fn6:num ... ]
Diego Novillo8d6568b2013-11-13 12:22:21 +0000347///
348/// Function names must be mangled in order for the profile loader to
Diego Novillo9518b632014-01-10 23:23:51 +0000349/// 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.
354///
355/// Each sampled line may contain several items. Some are optional
356/// (marked below):
357///
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.
363///
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.
368///
369/// FIXME: Handle discriminators, since they are needed to distinguish
370/// multiple control flow within a single source LOC.
371///
372/// c- Number of samples. This is the number of samples collected by
373/// the profiler at this source location.
374///
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,
379///
380/// 130: 7 foo:3 bar:2 baz:7
381///
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.
385///
386/// FIXME: This is currently unhandled, but it has a lot of
387/// potential for aiding the inliner.
388///
Diego Novillo8d6568b2013-11-13 12:22:21 +0000389///
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.
Diego Novillo9518b632014-01-10 23:23:51 +0000392///
393/// FIXME: flat profiles are too imprecise to provide good optimization
394/// opportunities. Convert them to context-sensitive profile.
Diego Novillo8d6568b2013-11-13 12:22:21 +0000395///
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
399/// inefficient.
Diego Novilloc0dd1032013-11-26 20:37:33 +0000400void SampleModuleProfile::loadText() {
Ahmed Charles56440fd2014-03-06 05:51:42 +0000401 std::unique_ptr<MemoryBuffer> Buffer;
Diego Novillo9518b632014-01-10 23:23:51 +0000402 error_code EC = MemoryBuffer::getFile(Filename, Buffer);
403 if (EC)
404 report_fatal_error("Could not open file " + Filename + ": " + EC.message());
405 line_iterator LineIt(*Buffer, '#');
Diego Novillo8d6568b2013-11-13 12:22:21 +0000406
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.
Diego Novillo9518b632014-01-10 23:23:51 +0000410 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
414 // have this format:
415 //
416 // function_name:total_samples:total_head_samples
417 //
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);
Diego Novillo8d6568b2013-11-13 12:22:21 +0000424 StringRef FName = Matches[1];
Diego Novillo9518b632014-01-10 23:23:51 +0000425 unsigned NumSamples, NumHeadSamples;
Diego Novillo8d6568b2013-11-13 12:22:21 +0000426 Matches[2].getAsInteger(10, NumSamples);
427 Matches[3].getAsInteger(10, NumHeadSamples);
Diego Novillo9518b632014-01-10 23:23:51 +0000428 Profiles[FName] = SampleFunctionProfile();
Diego Novilloc0dd1032013-11-26 20:37:33 +0000429 SampleFunctionProfile &FProfile = Profiles[FName];
430 FProfile.addTotalSamples(NumSamples);
431 FProfile.addHeadSamples(NumHeadSamples);
Diego Novillo9518b632014-01-10 23:23:51 +0000432 ++LineIt;
433
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))
438 reportParseError(
439 LineIt.line_number(),
440 "Expected 'NUM[.NUM]: NUM[ mangled_name:NUM]*', found " + *LineIt);
441 assert(Matches.size() == 5);
Diego Novillo8d6568b2013-11-13 12:22:21 +0000442 unsigned LineOffset, NumSamples;
443 Matches[1].getAsInteger(10, LineOffset);
Diego Novillo9518b632014-01-10 23:23:51 +0000444
445 // FIXME: Handle discriminator information (in Matches[2]).
446
447 Matches[3].getAsInteger(10, NumSamples);
448
449 // FIXME: Handle called targets (in Matches[4]).
450
Diego Novillo0accb3d2014-01-10 23:23:46 +0000451 // 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.
455 if (NumSamples == 0)
456 NumSamples = 1;
Diego Novilloc0dd1032013-11-26 20:37:33 +0000457 FProfile.addBodySamples(LineOffset, NumSamples);
Diego Novillo9518b632014-01-10 23:23:51 +0000458 ++LineIt;
Diego Novillo8d6568b2013-11-13 12:22:21 +0000459 }
Diego Novillo8d6568b2013-11-13 12:22:21 +0000460 }
461}
462
Diego Novillo0accb3d2014-01-10 23:23:46 +0000463/// \brief Get the weight for an instruction.
464///
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.
470///
471/// \param Inst Instruction to query.
472///
473/// \returns The profiled weight of I.
474uint32_t SampleFunctionProfile::getInstWeight(Instruction &Inst) {
475 unsigned Lineno = Inst.getDebugLoc().getLine();
476 if (Lineno < HeaderLineno)
477 return 0;
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");
483 return Weight;
484}
485
486/// \brief Compute the weight of a basic block.
487///
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.
491///
492/// \param B The basic block to query.
493///
494/// \returns The computed weight of B.
495uint32_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));
499 if (!Entry.second)
500 return Entry.first->second;
501
502 // Otherwise, compute and cache B's weight.
503 uint32_t Weight = 0;
504 for (BasicBlock::iterator I = B->begin(), E = B->end(); I != E; ++I) {
505 uint32_t InstWeight = getInstWeight(*I);
506 if (InstWeight > Weight)
507 Weight = InstWeight;
508 }
509 Entry.first->second = Weight;
510 return Weight;
511}
512
513/// \brief Compute and store the weights of every basic block.
514///
515/// This populates the BlockWeights map by computing
516/// the weights of every basic block in the CFG.
517///
518/// \param F The function to query.
519bool 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));
526 }
527
528 return Changed;
529}
530
531/// \brief Find equivalence classes for the given block.
532///
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.
536///
537/// A block BB2 will be in the same equivalence class as \p BB1 if
538/// the following holds:
539///
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.
543///
544/// 2- Both BB2 and \p BB1 must be in the same loop.
545///
546/// For every block BB2 that meets those two requirements, we set BB2's
547/// equivalence class to \p BB1.
548///
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.
554void 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();
559 I != E; ++I) {
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 &&
564 IsInSameLoop) {
565 EquivalenceClass[BB2] = BB1;
566
567 // If BB2 is heavier than BB1, make BB2 have the same weight
568 // as BB1.
569 //
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);
578 }
579 }
580}
581
582/// \brief Find equivalence classes.
583///
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.
589///
590/// \param F The function to query.
591void 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) {
596 BasicBlock *BB1 = B;
597
598 // Compute BB1's equivalence class once.
599 if (EquivalenceClass.count(BB1)) {
600 DEBUG(printBlockEquivalence(dbgs(), BB1));
601 continue;
602 }
603
604 // By default, blocks are in their own equivalence class.
605 EquivalenceClass[BB1] = BB1;
606
607 // Traverse all the blocks dominated by BB1. We are looking for
608 // every basic block BB2 such that:
609 //
610 // 1- BB1 dominates BB2.
611 // 2- BB2 post-dominates BB1.
612 // 3- BB1 and BB2 are in the same loop nest.
613 //
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);
620
621 // Repeat the same logic for all the blocks post-dominated by BB1.
622 // We are looking for every basic block BB2 such that:
623 //
624 // 1- BB1 post-dominates BB2.
625 // 2- BB2 dominates BB1.
626 // 3- BB1 and BB2 are in the same loop nest.
627 //
628 // If all those conditions hold, BB2's equivalence class is BB1.
629 DominatedBBs.clear();
630 PDT->getDescendants(BB1, DominatedBBs);
Chandler Carruth73523022014-01-13 13:07:17 +0000631 findEquivalencesFor(BB1, DominatedBBs, DT);
Diego Novillo0accb3d2014-01-10 23:23:46 +0000632
633 DEBUG(printBlockEquivalence(dbgs(), BB1));
634 }
635
636 // Assign weights to equivalence classes.
637 //
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) {
644 BasicBlock *BB = B;
645 BasicBlock *EquivBB = EquivalenceClass[BB];
646 if (BB != EquivBB)
647 BlockWeights[BB] = BlockWeights[EquivBB];
648 DEBUG(printBlockWeight(dbgs(), BB));
649 }
650}
651
652/// \brief Visit the given edge to decide if it has a valid weight.
653///
654/// If \p E has not been visited before, we copy to \p UnknownEdge
655/// and increment the count of unknown edges.
656///
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.
660///
661/// \returns E's weight, if known. Otherwise, return 0.
662uint32_t SampleFunctionProfile::visitEdge(Edge E, unsigned *NumUnknownEdges,
663 Edge *UnknownEdge) {
664 if (!VisitedEdges.count(E)) {
665 (*NumUnknownEdges)++;
666 *UnknownEdge = E;
667 return 0;
668 }
669
670 return EdgeWeights[E];
671}
672
673/// \brief Propagate weights through incoming/outgoing edges.
674///
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.
677///
678/// Similarly, if all the edges have a known count, we can calculate the
679/// count of the basic block, if needed.
680///
681/// \param F Function to process.
682///
683/// \returns True if new weights were assigned to edges or blocks.
684bool 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) {
688 BasicBlock *BB = BI;
689
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;
699
700 if (i == 0) {
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;
707 }
708 } else {
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);
713 }
714 }
715
716 // After visiting all the edges, there are three cases that we
717 // can handle immediately:
718 //
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.
724 //
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.
730 //
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.
735 //
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;
747 Changed = true;
748 DEBUG(dbgs() << "All edge weights for " << BB->getName()
749 << " known. Set weight for block: ";
750 printBlockWeight(dbgs(), BB););
751 }
752 if (VisitedBlocks.insert(BB))
753 Changed = true;
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;
759 else
760 EdgeWeights[UnknownEdge] = 0;
761 VisitedEdges.insert(UnknownEdge);
762 Changed = true;
763 DEBUG(dbgs() << "Set weight for edge: ";
764 printEdgeWeight(dbgs(), UnknownEdge));
765 }
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;
771 else
772 EdgeWeights[SelfReferentialEdge] = 0;
773 VisitedEdges.insert(SelfReferentialEdge);
774 Changed = true;
775 DEBUG(dbgs() << "Set self-referential edge weight to: ";
776 printEdgeWeight(dbgs(), SelfReferentialEdge));
777 }
778 }
779 }
780
781 return Changed;
782}
783
784/// \brief Build in/out edge lists for each basic block in the CFG.
785///
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.
788void SampleFunctionProfile::buildEdges(Function &F) {
789 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
790 BasicBlock *B1 = I;
791
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);
800 }
801
802 // Add successors for B1.
803 Visited.clear();
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);
810 }
811 }
812}
813
814/// \brief Propagate weights into edges
815///
816/// The following rules are applied to every block B in the CFG:
817///
818/// - If B has a single predecessor/successor, then the weight
819/// of that edge is the weight of the block.
820///
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.
826///
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
830/// known).
831void SampleFunctionProfile::propagateWeights(Function &F) {
832 bool Changed = true;
833 unsigned i = 0;
834
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
839 // of the pass.
840 buildEdges(F);
841
842 // Propagate until we converge or we go past the iteration limit.
843 while (Changed && i++ < SampleProfileMaxPropagateIterations) {
844 Changed = propagateThroughEdges(F);
845 }
846
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) {
852 BasicBlock *B = I;
853 TerminatorInst *TI = B->getTerminator();
854 if (TI->getNumSuccessors() == 1)
855 continue;
856 if (!isa<BranchInst>(TI) && !isa<SwitchInst>(TI))
857 continue;
858
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);
870 if (Weight != 0)
871 AllWeightsZero = false;
872 }
873
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));
880 } else {
881 DEBUG(dbgs() << "SKIPPED. All branch weights are zero.\n");
882 }
883 }
884}
885
886/// \brief Get the line number for the function header.
887///
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.
892///
893/// \param F Function object to query.
894///
895/// \returns the line number where \p F is defined.
896unsigned SampleFunctionProfile::getFunctionLoc(Function &F) {
897 NamedMDNode *CUNodes = F.getParent()->getNamedMetadata("llvm.dbg.cu");
898 if (CUNodes) {
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();
906 }
907 }
908 }
909
910 report_fatal_error("No debug information found in function " + F.getName() +
911 "\n");
912}
913
914/// \brief Generate branch weight metadata for all branches in \p F.
915///
916/// Branch weights are computed out of instruction samples using a
917/// propagation heuristic. Propagation proceeds in 3 phases:
918///
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.
922///
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.
929///
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:
933///
934/// - If B has a single predecessor/successor, then the weight
935/// of that edge is the weight of the block.
936///
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.
942///
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
946/// known).
947///
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).
951///
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
955/// work here.
956///
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.
959///
960/// \param F The function to query.
961bool SampleFunctionProfile::emitAnnotations(Function &F, DominatorTree *DomTree,
962 PostDominatorTree *PostDomTree,
963 LoopInfo *Loops) {
964 bool Changed = false;
965
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");
970 DT = DomTree;
971 PDT = PostDomTree;
972 LI = Loops;
973
974 // Compute basic block weights.
975 Changed |= computeBlockWeights(F);
976
977 if (Changed) {
978 // Find equivalence classes.
979 findEquivalenceClasses(F);
980
981 // Propagate weights to all edges.
982 propagateWeights(F);
983 }
984
985 return Changed;
986}
987
Diego Novilloc0dd1032013-11-26 20:37:33 +0000988char SampleProfileLoader::ID = 0;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000989INITIALIZE_PASS_BEGIN(SampleProfileLoader, "sample-profile",
990 "Sample Profile loader", false, false)
Chandler Carruth73523022014-01-13 13:07:17 +0000991INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Diego Novillo0accb3d2014-01-10 23:23:46 +0000992INITIALIZE_PASS_DEPENDENCY(PostDominatorTree)
993INITIALIZE_PASS_DEPENDENCY(LoopInfo)
994INITIALIZE_PASS_END(SampleProfileLoader, "sample-profile",
995 "Sample Profile loader", false, false)
Diego Novilloc0dd1032013-11-26 20:37:33 +0000996
997bool SampleProfileLoader::doInitialization(Module &M) {
998 Profiler.reset(new SampleModuleProfile(Filename));
999 Profiler->loadText();
1000 return true;
1001}
1002
1003FunctionPass *llvm::createSampleProfileLoaderPass() {
1004 return new SampleProfileLoader(SampleProfileFile);
1005}
1006
1007FunctionPass *llvm::createSampleProfileLoaderPass(StringRef Name) {
1008 return new SampleProfileLoader(Name);
1009}
1010
Diego Novillo8d6568b2013-11-13 12:22:21 +00001011bool SampleProfileLoader::runOnFunction(Function &F) {
Chandler Carruth73523022014-01-13 13:07:17 +00001012 DominatorTree *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Diego Novillo0accb3d2014-01-10 23:23:46 +00001013 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);
1018 return false;
Diego Novillo8d6568b2013-11-13 12:22:21 +00001019}