blob: b797321b2f87f25d8ce30ae282cf5ff8e6255101 [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
Diego Novillo8d6568b2013-11-13 12:22:21 +000025#include "llvm/ADT/DenseMap.h"
Diego Novillo0accb3d2014-01-10 23:23:46 +000026#include "llvm/ADT/SmallPtrSet.h"
Chandler Carruth07baed52014-01-13 08:04:33 +000027#include "llvm/ADT/SmallSet.h"
Diego Novillo8d6568b2013-11-13 12:22:21 +000028#include "llvm/ADT/StringRef.h"
Diego Novillo0accb3d2014-01-10 23:23:46 +000029#include "llvm/Analysis/LoopInfo.h"
Chandler Carruth07baed52014-01-13 08:04:33 +000030#include "llvm/Analysis/PostDominators.h"
Diego Novillo8d6568b2013-11-13 12:22:21 +000031#include "llvm/IR/Constants.h"
Chandler Carruth9a4c9e52014-03-06 00:46:21 +000032#include "llvm/IR/DebugInfo.h"
Diego Novilloa32aa322014-03-14 21:58:59 +000033#include "llvm/IR/DiagnosticInfo.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000034#include "llvm/IR/Dominators.h"
Diego Novillo8d6568b2013-11-13 12:22:21 +000035#include "llvm/IR/Function.h"
Chandler Carruth83948572014-03-04 10:30:26 +000036#include "llvm/IR/InstIterator.h"
Diego Novillo8d6568b2013-11-13 12:22:21 +000037#include "llvm/IR/Instructions.h"
38#include "llvm/IR/LLVMContext.h"
Diego Novillo8d6568b2013-11-13 12:22:21 +000039#include "llvm/IR/MDBuilder.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000040#include "llvm/IR/Metadata.h"
Diego Novillo8d6568b2013-11-13 12:22:21 +000041#include "llvm/IR/Module.h"
42#include "llvm/Pass.h"
Diego Novillode1ab262014-09-09 12:40:50 +000043#include "llvm/ProfileData/SampleProfReader.h"
Diego Novillo8d6568b2013-11-13 12:22:21 +000044#include "llvm/Support/CommandLine.h"
45#include "llvm/Support/Debug.h"
Dehao Chen8e7df832015-09-29 18:28:15 +000046#include "llvm/Support/ErrorOr.h"
Diego Novillo8d6568b2013-11-13 12:22:21 +000047#include "llvm/Support/raw_ostream.h"
Diego Novillo4d711132015-08-25 15:25:11 +000048#include "llvm/Transforms/IPO.h"
Dehao Chen67226882015-09-30 00:42:46 +000049#include "llvm/Transforms/Utils/Cloning.h"
Logan Chien61c6df02014-02-22 06:34:10 +000050#include <cctype>
Diego Novillo8d6568b2013-11-13 12:22:21 +000051
52using namespace llvm;
Diego Novillode1ab262014-09-09 12:40:50 +000053using namespace sampleprof;
Diego Novillo8d6568b2013-11-13 12:22:21 +000054
Chandler Carruth964daaa2014-04-22 02:55:47 +000055#define DEBUG_TYPE "sample-profile"
56
Diego Novillo8d6568b2013-11-13 12:22:21 +000057// Command line option to specify the file to read samples from. This is
58// mainly used for debugging.
59static cl::opt<std::string> SampleProfileFile(
60 "sample-profile-file", cl::init(""), cl::value_desc("filename"),
61 cl::desc("Profile file loaded by -sample-profile"), cl::Hidden);
Diego Novillo0accb3d2014-01-10 23:23:46 +000062static cl::opt<unsigned> SampleProfileMaxPropagateIterations(
63 "sample-profile-max-propagate-iterations", cl::init(100),
64 cl::desc("Maximum number of iterations to go through when propagating "
65 "sample block/edge weights through the CFG."));
Diego Novillo8d6568b2013-11-13 12:22:21 +000066
67namespace {
Diego Novillo38be3332015-10-15 16:36:21 +000068typedef DenseMap<const BasicBlock *, uint64_t> BlockWeightMap;
Dehao Chen8e7df832015-09-29 18:28:15 +000069typedef DenseMap<const BasicBlock *, const BasicBlock *> EquivalenceClassMap;
70typedef std::pair<const BasicBlock *, const BasicBlock *> Edge;
Diego Novillo38be3332015-10-15 16:36:21 +000071typedef DenseMap<Edge, uint64_t> EdgeWeightMap;
Dehao Chen8e7df832015-09-29 18:28:15 +000072typedef DenseMap<const BasicBlock *, SmallVector<const BasicBlock *, 8>>
73 BlockEdgeMap;
Diego Novilloc0dd1032013-11-26 20:37:33 +000074
Diego Novillode1ab262014-09-09 12:40:50 +000075/// \brief Sample profile pass.
Diego Novilloc0dd1032013-11-26 20:37:33 +000076///
Diego Novillode1ab262014-09-09 12:40:50 +000077/// This pass reads profile data from the file specified by
78/// -sample-profile-file and annotates every affected function with the
79/// profile information found in that file.
Diego Novillo4d711132015-08-25 15:25:11 +000080class SampleProfileLoader : public ModulePass {
Diego Novilloc0dd1032013-11-26 20:37:33 +000081public:
Diego Novillode1ab262014-09-09 12:40:50 +000082 // Class identification, replacement for typeinfo
83 static char ID;
Diego Novilloc0dd1032013-11-26 20:37:33 +000084
Diego Novillode1ab262014-09-09 12:40:50 +000085 SampleProfileLoader(StringRef Name = SampleProfileFile)
Diego Novillo7732ae42015-08-26 20:00:27 +000086 : ModulePass(ID), DT(nullptr), PDT(nullptr), LI(nullptr), Reader(),
87 Samples(nullptr), Filename(Name), ProfileIsValid(false) {
Diego Novillode1ab262014-09-09 12:40:50 +000088 initializeSampleProfileLoaderPass(*PassRegistry::getPassRegistry());
89 }
90
91 bool doInitialization(Module &M) override;
92
93 void dump() { Reader->dump(); }
94
95 const char *getPassName() const override { return "Sample profile pass"; }
96
Diego Novillo4d711132015-08-25 15:25:11 +000097 bool runOnModule(Module &M) override;
Diego Novillode1ab262014-09-09 12:40:50 +000098
99 void getAnalysisUsage(AnalysisUsage &AU) const override {
100 AU.setPreservesCFG();
Diego Novillode1ab262014-09-09 12:40:50 +0000101 }
102
103protected:
Diego Novillo4d711132015-08-25 15:25:11 +0000104 bool runOnFunction(Function &F);
Diego Novillo0accb3d2014-01-10 23:23:46 +0000105 unsigned getFunctionLoc(Function &F);
Diego Novillode1ab262014-09-09 12:40:50 +0000106 bool emitAnnotations(Function &F);
Diego Novillo38be3332015-10-15 16:36:21 +0000107 ErrorOr<uint64_t> getInstWeight(const Instruction &I) const;
108 ErrorOr<uint64_t> getBlockWeight(const BasicBlock *BB) const;
Dehao Chen67226882015-09-30 00:42:46 +0000109 const FunctionSamples *findCalleeFunctionSamples(const CallInst &I) const;
110 const FunctionSamples *findFunctionSamples(const Instruction &I) const;
111 bool inlineHotFunctions(Function &F);
Diego Novillo0accb3d2014-01-10 23:23:46 +0000112 void printEdgeWeight(raw_ostream &OS, Edge E);
Dehao Chen8e7df832015-09-29 18:28:15 +0000113 void printBlockWeight(raw_ostream &OS, const BasicBlock *BB) const;
114 void printBlockEquivalence(raw_ostream &OS, const BasicBlock *BB);
Diego Novillo0accb3d2014-01-10 23:23:46 +0000115 bool computeBlockWeights(Function &F);
116 void findEquivalenceClasses(Function &F);
117 void findEquivalencesFor(BasicBlock *BB1,
118 SmallVector<BasicBlock *, 8> Descendants,
119 DominatorTreeBase<BasicBlock> *DomTree);
120 void propagateWeights(Function &F);
Diego Novillo38be3332015-10-15 16:36:21 +0000121 uint64_t visitEdge(Edge E, unsigned *NumUnknownEdges, Edge *UnknownEdge);
Diego Novillo0accb3d2014-01-10 23:23:46 +0000122 void buildEdges(Function &F);
123 bool propagateThroughEdges(Function &F);
Diego Novillo7732ae42015-08-26 20:00:27 +0000124 void computeDominanceAndLoopInfo(Function &F);
Dehao Chen10042412015-10-21 01:22:27 +0000125 unsigned getOffset(unsigned L, unsigned H) const;
Diego Novilloc0dd1032013-11-26 20:37:33 +0000126
Diego Novilloc0dd1032013-11-26 20:37:33 +0000127 /// \brief Map basic blocks to their computed weights.
128 ///
129 /// The weight of a basic block is defined to be the maximum
130 /// of all the instruction weights in that block.
131 BlockWeightMap BlockWeights;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000132
133 /// \brief Map edges to their computed weights.
134 ///
135 /// Edge weights are computed by propagating basic block weights in
136 /// SampleProfile::propagateWeights.
137 EdgeWeightMap EdgeWeights;
138
139 /// \brief Set of visited blocks during propagation.
Dehao Chen8e7df832015-09-29 18:28:15 +0000140 SmallPtrSet<const BasicBlock *, 128> VisitedBlocks;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000141
142 /// \brief Set of visited edges during propagation.
143 SmallSet<Edge, 128> VisitedEdges;
144
145 /// \brief Equivalence classes for block weights.
146 ///
147 /// Two blocks BB1 and BB2 are in the same equivalence class if they
148 /// dominate and post-dominate each other, and they are in the same loop
149 /// nest. When this happens, the two blocks are guaranteed to execute
150 /// the same number of times.
151 EquivalenceClassMap EquivalenceClass;
152
153 /// \brief Dominance, post-dominance and loop information.
Diego Novillo7732ae42015-08-26 20:00:27 +0000154 std::unique_ptr<DominatorTree> DT;
155 std::unique_ptr<DominatorTreeBase<BasicBlock>> PDT;
156 std::unique_ptr<LoopInfo> LI;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000157
158 /// \brief Predecessors for each basic block in the CFG.
159 BlockEdgeMap Predecessors;
160
161 /// \brief Successors for each basic block in the CFG.
162 BlockEdgeMap Successors;
Diego Novillo92aa8c22014-03-10 22:41:28 +0000163
Diego Novillo8d6568b2013-11-13 12:22:21 +0000164 /// \brief Profile reader object.
Diego Novillode1ab262014-09-09 12:40:50 +0000165 std::unique_ptr<SampleProfileReader> Reader;
166
167 /// \brief Samples collected for the body of this function.
168 FunctionSamples *Samples;
Diego Novillo8d6568b2013-11-13 12:22:21 +0000169
170 /// \brief Name of the profile file to load.
171 StringRef Filename;
Diego Novilloa32aa322014-03-14 21:58:59 +0000172
Alp Toker16f98b22014-04-09 14:47:27 +0000173 /// \brief Flag indicating whether the profile input loaded successfully.
Diego Novilloa32aa322014-03-14 21:58:59 +0000174 bool ProfileIsValid;
Diego Novillo8d6568b2013-11-13 12:22:21 +0000175};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000176}
Diego Novillo8d6568b2013-11-13 12:22:21 +0000177
Dehao Chen10042412015-10-21 01:22:27 +0000178/// \brief Returns the offset of lineno \p L to head_lineno \p H
179///
180/// \param L Lineno
181/// \param H Header lineno of the function
182///
183/// \returns offset to the header lineno. 16 bits are used to represent offset.
184/// We assume that a single function will not exceed 65535 LOC.
185unsigned SampleProfileLoader::getOffset(unsigned L, unsigned H) const {
186 return (L - H) & 0xffff;
187}
188
Diego Novillo0accb3d2014-01-10 23:23:46 +0000189/// \brief Print the weight of edge \p E on stream \p OS.
190///
191/// \param OS Stream to emit the output to.
192/// \param E Edge to print.
Diego Novillode1ab262014-09-09 12:40:50 +0000193void SampleProfileLoader::printEdgeWeight(raw_ostream &OS, Edge E) {
Diego Novillo0accb3d2014-01-10 23:23:46 +0000194 OS << "weight[" << E.first->getName() << "->" << E.second->getName()
195 << "]: " << EdgeWeights[E] << "\n";
196}
197
198/// \brief Print the equivalence class of block \p BB on stream \p OS.
199///
200/// \param OS Stream to emit the output to.
201/// \param BB Block to print.
Diego Novillode1ab262014-09-09 12:40:50 +0000202void SampleProfileLoader::printBlockEquivalence(raw_ostream &OS,
Dehao Chen8e7df832015-09-29 18:28:15 +0000203 const BasicBlock *BB) {
204 const BasicBlock *Equiv = EquivalenceClass[BB];
Diego Novillo0accb3d2014-01-10 23:23:46 +0000205 OS << "equivalence[" << BB->getName()
206 << "]: " << ((Equiv) ? EquivalenceClass[BB]->getName() : "NONE") << "\n";
207}
208
209/// \brief Print the weight of block \p BB on stream \p OS.
210///
211/// \param OS Stream to emit the output to.
212/// \param BB Block to print.
Dehao Chen8e7df832015-09-29 18:28:15 +0000213void SampleProfileLoader::printBlockWeight(raw_ostream &OS,
214 const BasicBlock *BB) const {
215 const auto &I = BlockWeights.find(BB);
Diego Novillo38be3332015-10-15 16:36:21 +0000216 uint64_t W = (I == BlockWeights.end() ? 0 : I->second);
Dehao Chen8e7df832015-09-29 18:28:15 +0000217 OS << "weight[" << BB->getName() << "]: " << W << "\n";
Diego Novillo0accb3d2014-01-10 23:23:46 +0000218}
219
Diego Novillo0accb3d2014-01-10 23:23:46 +0000220/// \brief Get the weight for an instruction.
221///
222/// The "weight" of an instruction \p Inst is the number of samples
223/// collected on that instruction at runtime. To retrieve it, we
224/// need to compute the line number of \p Inst relative to the start of its
225/// function. We use HeaderLineno to compute the offset. We then
226/// look up the samples collected for \p Inst using BodySamples.
227///
228/// \param Inst Instruction to query.
229///
Dehao Chen8e7df832015-09-29 18:28:15 +0000230/// \returns the weight of \p Inst.
Diego Novillo38be3332015-10-15 16:36:21 +0000231ErrorOr<uint64_t>
Dehao Chen8e7df832015-09-29 18:28:15 +0000232SampleProfileLoader::getInstWeight(const Instruction &Inst) const {
Diego Novillo92aa8c22014-03-10 22:41:28 +0000233 DebugLoc DLoc = Inst.getDebugLoc();
Duncan P. N. Exon Smithec819c02015-03-30 19:49:49 +0000234 if (!DLoc)
Dehao Chen8e7df832015-09-29 18:28:15 +0000235 return std::error_code();
Duncan P. N. Exon Smith41a15462015-03-20 00:56:55 +0000236
Dehao Chen67226882015-09-30 00:42:46 +0000237 const FunctionSamples *FS = findFunctionSamples(Inst);
238 if (!FS)
239 return std::error_code();
Dehao Chen41dc5a62015-10-09 16:50:16 +0000240
241 const DILocation *DIL = DLoc;
242 unsigned Lineno = DLoc.getLine();
243 unsigned HeaderLineno = DIL->getScope()->getSubprogram()->getLine();
Dehao Chen41dc5a62015-10-09 16:50:16 +0000244
Dehao Chen10042412015-10-21 01:22:27 +0000245 ErrorOr<uint64_t> R = FS->findSamplesAt(getOffset(Lineno, HeaderLineno),
246 DIL->getDiscriminator());
Dehao Chen8e7df832015-09-29 18:28:15 +0000247 if (R)
248 DEBUG(dbgs() << " " << Lineno << "." << DIL->getDiscriminator() << ":"
249 << Inst << " (line offset: " << Lineno - HeaderLineno << "."
250 << DIL->getDiscriminator() << " - weight: " << R.get()
251 << ")\n");
252 return R;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000253}
254
255/// \brief Compute the weight of a basic block.
256///
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000257/// The weight of basic block \p BB is the maximum weight of all the
Dehao Chen8e7df832015-09-29 18:28:15 +0000258/// instructions in BB.
Diego Novillo0accb3d2014-01-10 23:23:46 +0000259///
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000260/// \param BB The basic block to query.
Diego Novillo0accb3d2014-01-10 23:23:46 +0000261///
Dehao Chen8e7df832015-09-29 18:28:15 +0000262/// \returns the weight for \p BB.
Diego Novillo38be3332015-10-15 16:36:21 +0000263ErrorOr<uint64_t>
Dehao Chen8e7df832015-09-29 18:28:15 +0000264SampleProfileLoader::getBlockWeight(const BasicBlock *BB) const {
265 bool Found = false;
Diego Novillo38be3332015-10-15 16:36:21 +0000266 uint64_t Weight = 0;
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000267 for (auto &I : BB->getInstList()) {
Diego Novillo38be3332015-10-15 16:36:21 +0000268 const ErrorOr<uint64_t> &R = getInstWeight(I);
Dehao Chen8e7df832015-09-29 18:28:15 +0000269 if (R && R.get() >= Weight) {
270 Weight = R.get();
271 Found = true;
272 }
Diego Novillo0accb3d2014-01-10 23:23:46 +0000273 }
Dehao Chen8e7df832015-09-29 18:28:15 +0000274 if (Found)
275 return Weight;
276 else
277 return std::error_code();
Diego Novillo0accb3d2014-01-10 23:23:46 +0000278}
279
280/// \brief Compute and store the weights of every basic block.
281///
282/// This populates the BlockWeights map by computing
283/// the weights of every basic block in the CFG.
284///
285/// \param F The function to query.
Diego Novillode1ab262014-09-09 12:40:50 +0000286bool SampleProfileLoader::computeBlockWeights(Function &F) {
Diego Novillo0accb3d2014-01-10 23:23:46 +0000287 bool Changed = false;
288 DEBUG(dbgs() << "Block weights\n");
Dehao Chen8e7df832015-09-29 18:28:15 +0000289 for (const auto &BB : F) {
Diego Novillo38be3332015-10-15 16:36:21 +0000290 ErrorOr<uint64_t> Weight = getBlockWeight(&BB);
Dehao Chen8e7df832015-09-29 18:28:15 +0000291 if (Weight) {
292 BlockWeights[&BB] = Weight.get();
Dehao Chen7c41dd62015-10-01 00:26:56 +0000293 VisitedBlocks.insert(&BB);
Dehao Chen8e7df832015-09-29 18:28:15 +0000294 Changed = true;
295 }
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000296 DEBUG(printBlockWeight(dbgs(), &BB));
Diego Novillo0accb3d2014-01-10 23:23:46 +0000297 }
298
299 return Changed;
300}
301
Dehao Chen67226882015-09-30 00:42:46 +0000302/// \brief Get the FunctionSamples for a call instruction.
303///
304/// The FunctionSamples of a call instruction \p Inst is the inlined
305/// instance in which that call instruction is calling to. It contains
306/// all samples that resides in the inlined instance. We first find the
307/// inlined instance in which the call instruction is from, then we
308/// traverse its children to find the callsite with the matching
309/// location and callee function name.
310///
311/// \param Inst Call instruction to query.
312///
313/// \returns The FunctionSamples pointer to the inlined instance.
314const FunctionSamples *
315SampleProfileLoader::findCalleeFunctionSamples(const CallInst &Inst) const {
316 const DILocation *DIL = Inst.getDebugLoc();
317 if (!DIL) {
318 return nullptr;
319 }
320 DISubprogram *SP = DIL->getScope()->getSubprogram();
Dehao Chen10042412015-10-21 01:22:27 +0000321 if (!SP)
Dehao Chen67226882015-09-30 00:42:46 +0000322 return nullptr;
323
324 Function *CalleeFunc = Inst.getCalledFunction();
325 if (!CalleeFunc) {
326 return nullptr;
327 }
328
329 StringRef CalleeName = CalleeFunc->getName();
330 const FunctionSamples *FS = findFunctionSamples(Inst);
331 if (FS == nullptr)
332 return nullptr;
333
Dehao Chen10042412015-10-21 01:22:27 +0000334 return FS->findFunctionSamplesAt(
335 CallsiteLocation(getOffset(DIL->getLine(), SP->getLine()),
336 DIL->getDiscriminator(), CalleeName));
Dehao Chen67226882015-09-30 00:42:46 +0000337}
338
339/// \brief Get the FunctionSamples for an instruction.
340///
341/// The FunctionSamples of an instruction \p Inst is the inlined instance
342/// in which that instruction is coming from. We traverse the inline stack
343/// of that instruction, and match it with the tree nodes in the profile.
344///
345/// \param Inst Instruction to query.
346///
347/// \returns the FunctionSamples pointer to the inlined instance.
348const FunctionSamples *
349SampleProfileLoader::findFunctionSamples(const Instruction &Inst) const {
350 SmallVector<CallsiteLocation, 10> S;
351 const DILocation *DIL = Inst.getDebugLoc();
352 if (!DIL) {
353 return Samples;
354 }
355 StringRef CalleeName;
356 for (const DILocation *DIL = Inst.getDebugLoc(); DIL;
357 DIL = DIL->getInlinedAt()) {
358 DISubprogram *SP = DIL->getScope()->getSubprogram();
Dehao Chen10042412015-10-21 01:22:27 +0000359 if (!SP)
Dehao Chen67226882015-09-30 00:42:46 +0000360 return nullptr;
361 if (!CalleeName.empty()) {
Dehao Chen10042412015-10-21 01:22:27 +0000362 S.push_back(CallsiteLocation(getOffset(DIL->getLine(), SP->getLine()),
Dehao Chen67226882015-09-30 00:42:46 +0000363 DIL->getDiscriminator(), CalleeName));
364 }
365 CalleeName = SP->getLinkageName();
366 }
367 if (S.size() == 0)
368 return Samples;
369 const FunctionSamples *FS = Samples;
370 for (int i = S.size() - 1; i >= 0 && FS != nullptr; i--) {
371 FS = FS->findFunctionSamplesAt(S[i]);
372 }
373 return FS;
374}
375
376/// \brief Iteratively inline hot callsites of a function.
377///
378/// Iteratively traverse all callsites of the function \p F, and find if
379/// the corresponding inlined instance exists and is hot in profile. If
380/// it is hot enough, inline the callsites and adds new callsites of the
381/// callee into the caller.
382///
383/// TODO: investigate the possibility of not invoking InlineFunction directly.
384///
385/// \param F function to perform iterative inlining.
386///
387/// \returns True if there is any inline happened.
388bool SampleProfileLoader::inlineHotFunctions(Function &F) {
389 bool Changed = false;
390 while (true) {
391 bool LocalChanged = false;
392 SmallVector<CallInst *, 10> CIS;
393 for (auto &BB : F) {
394 for (auto &I : BB.getInstList()) {
395 CallInst *CI = dyn_cast<CallInst>(&I);
396 if (CI) {
397 const FunctionSamples *FS = findCalleeFunctionSamples(*CI);
398 if (FS && FS->getTotalSamples() > 0) {
399 CIS.push_back(CI);
400 }
401 }
402 }
403 }
404 for (auto CI : CIS) {
405 InlineFunctionInfo IFI;
406 if (InlineFunction(CI, IFI))
407 LocalChanged = true;
408 }
409 if (LocalChanged) {
410 Changed = true;
411 } else {
412 break;
413 }
414 }
415 return Changed;
416}
417
Diego Novillo0accb3d2014-01-10 23:23:46 +0000418/// \brief Find equivalence classes for the given block.
419///
420/// This finds all the blocks that are guaranteed to execute the same
Eric Christopher572e03a2015-06-19 01:53:21 +0000421/// number of times as \p BB1. To do this, it traverses all the
Diego Novillo0accb3d2014-01-10 23:23:46 +0000422/// descendants of \p BB1 in the dominator or post-dominator tree.
423///
424/// A block BB2 will be in the same equivalence class as \p BB1 if
425/// the following holds:
426///
427/// 1- \p BB1 is a descendant of BB2 in the opposite tree. So, if BB2
428/// is a descendant of \p BB1 in the dominator tree, then BB2 should
429/// dominate BB1 in the post-dominator tree.
430///
431/// 2- Both BB2 and \p BB1 must be in the same loop.
432///
433/// For every block BB2 that meets those two requirements, we set BB2's
434/// equivalence class to \p BB1.
435///
436/// \param BB1 Block to check.
437/// \param Descendants Descendants of \p BB1 in either the dom or pdom tree.
438/// \param DomTree Opposite dominator tree. If \p Descendants is filled
439/// with blocks from \p BB1's dominator tree, then
440/// this is the post-dominator tree, and vice versa.
Diego Novillode1ab262014-09-09 12:40:50 +0000441void SampleProfileLoader::findEquivalencesFor(
Diego Novillo0accb3d2014-01-10 23:23:46 +0000442 BasicBlock *BB1, SmallVector<BasicBlock *, 8> Descendants,
443 DominatorTreeBase<BasicBlock> *DomTree) {
Dehao Chen7c41dd62015-10-01 00:26:56 +0000444 const BasicBlock *EC = EquivalenceClass[BB1];
Diego Novillo38be3332015-10-15 16:36:21 +0000445 uint64_t Weight = BlockWeights[EC];
Dehao Chen8e7df832015-09-29 18:28:15 +0000446 for (const auto *BB2 : Descendants) {
Diego Novillo0accb3d2014-01-10 23:23:46 +0000447 bool IsDomParent = DomTree->dominates(BB2, BB1);
448 bool IsInSameLoop = LI->getLoopFor(BB1) == LI->getLoopFor(BB2);
Dehao Chen7c41dd62015-10-01 00:26:56 +0000449 if (BB1 != BB2 && IsDomParent && IsInSameLoop) {
450 EquivalenceClass[BB2] = EC;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000451
452 // If BB2 is heavier than BB1, make BB2 have the same weight
453 // as BB1.
454 //
455 // Note that we don't worry about the opposite situation here
456 // (when BB2 is lighter than BB1). We will deal with this
457 // during the propagation phase. Right now, we just want to
458 // make sure that BB1 has the largest weight of all the
459 // members of its equivalence set.
Dehao Chen7c41dd62015-10-01 00:26:56 +0000460 Weight = std::max(Weight, BlockWeights[BB2]);
Diego Novillo0accb3d2014-01-10 23:23:46 +0000461 }
462 }
Dehao Chen7c41dd62015-10-01 00:26:56 +0000463 BlockWeights[EC] = Weight;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000464}
465
466/// \brief Find equivalence classes.
467///
468/// Since samples may be missing from blocks, we can fill in the gaps by setting
469/// the weights of all the blocks in the same equivalence class to the same
470/// weight. To compute the concept of equivalence, we use dominance and loop
471/// information. Two blocks B1 and B2 are in the same equivalence class if B1
472/// dominates B2, B2 post-dominates B1 and both are in the same loop.
473///
474/// \param F The function to query.
Diego Novillode1ab262014-09-09 12:40:50 +0000475void SampleProfileLoader::findEquivalenceClasses(Function &F) {
Diego Novillo0accb3d2014-01-10 23:23:46 +0000476 SmallVector<BasicBlock *, 8> DominatedBBs;
477 DEBUG(dbgs() << "\nBlock equivalence classes\n");
478 // Find equivalence sets based on dominance and post-dominance information.
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000479 for (auto &BB : F) {
480 BasicBlock *BB1 = &BB;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000481
482 // Compute BB1's equivalence class once.
483 if (EquivalenceClass.count(BB1)) {
484 DEBUG(printBlockEquivalence(dbgs(), BB1));
485 continue;
486 }
487
488 // By default, blocks are in their own equivalence class.
489 EquivalenceClass[BB1] = BB1;
490
491 // Traverse all the blocks dominated by BB1. We are looking for
492 // every basic block BB2 such that:
493 //
494 // 1- BB1 dominates BB2.
495 // 2- BB2 post-dominates BB1.
496 // 3- BB1 and BB2 are in the same loop nest.
497 //
498 // If all those conditions hold, it means that BB2 is executed
499 // as many times as BB1, so they are placed in the same equivalence
500 // class by making BB2's equivalence class be BB1.
501 DominatedBBs.clear();
502 DT->getDescendants(BB1, DominatedBBs);
Diego Novillo7732ae42015-08-26 20:00:27 +0000503 findEquivalencesFor(BB1, DominatedBBs, PDT.get());
Diego Novillo0accb3d2014-01-10 23:23:46 +0000504
Diego Novillo0accb3d2014-01-10 23:23:46 +0000505 DEBUG(printBlockEquivalence(dbgs(), BB1));
506 }
507
508 // Assign weights to equivalence classes.
509 //
510 // All the basic blocks in the same equivalence class will execute
511 // the same number of times. Since we know that the head block in
512 // each equivalence class has the largest weight, assign that weight
513 // to all the blocks in that equivalence class.
514 DEBUG(dbgs() << "\nAssign the same weight to all blocks in the same class\n");
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000515 for (auto &BI : F) {
Dehao Chen8e7df832015-09-29 18:28:15 +0000516 const BasicBlock *BB = &BI;
517 const BasicBlock *EquivBB = EquivalenceClass[BB];
Diego Novillo0accb3d2014-01-10 23:23:46 +0000518 if (BB != EquivBB)
519 BlockWeights[BB] = BlockWeights[EquivBB];
520 DEBUG(printBlockWeight(dbgs(), BB));
521 }
522}
523
524/// \brief Visit the given edge to decide if it has a valid weight.
525///
526/// If \p E has not been visited before, we copy to \p UnknownEdge
527/// and increment the count of unknown edges.
528///
529/// \param E Edge to visit.
530/// \param NumUnknownEdges Current number of unknown edges.
531/// \param UnknownEdge Set if E has not been visited before.
532///
533/// \returns E's weight, if known. Otherwise, return 0.
Diego Novillo38be3332015-10-15 16:36:21 +0000534uint64_t SampleProfileLoader::visitEdge(Edge E, unsigned *NumUnknownEdges,
Diego Novillode1ab262014-09-09 12:40:50 +0000535 Edge *UnknownEdge) {
Diego Novillo0accb3d2014-01-10 23:23:46 +0000536 if (!VisitedEdges.count(E)) {
537 (*NumUnknownEdges)++;
538 *UnknownEdge = E;
539 return 0;
540 }
541
542 return EdgeWeights[E];
543}
544
545/// \brief Propagate weights through incoming/outgoing edges.
546///
547/// If the weight of a basic block is known, and there is only one edge
548/// with an unknown weight, we can calculate the weight of that edge.
549///
550/// Similarly, if all the edges have a known count, we can calculate the
551/// count of the basic block, if needed.
552///
553/// \param F Function to process.
554///
555/// \returns True if new weights were assigned to edges or blocks.
Diego Novillode1ab262014-09-09 12:40:50 +0000556bool SampleProfileLoader::propagateThroughEdges(Function &F) {
Diego Novillo0accb3d2014-01-10 23:23:46 +0000557 bool Changed = false;
558 DEBUG(dbgs() << "\nPropagation through edges\n");
Dehao Chen7c41dd62015-10-01 00:26:56 +0000559 for (const auto &BI : F) {
560 const BasicBlock *BB = &BI;
561 const BasicBlock *EC = EquivalenceClass[BB];
Diego Novillo0accb3d2014-01-10 23:23:46 +0000562
563 // Visit all the predecessor and successor edges to determine
564 // which ones have a weight assigned already. Note that it doesn't
565 // matter that we only keep track of a single unknown edge. The
566 // only case we are interested in handling is when only a single
567 // edge is unknown (see setEdgeOrBlockWeight).
568 for (unsigned i = 0; i < 2; i++) {
Diego Novillo38be3332015-10-15 16:36:21 +0000569 uint64_t TotalWeight = 0;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000570 unsigned NumUnknownEdges = 0;
571 Edge UnknownEdge, SelfReferentialEdge;
572
573 if (i == 0) {
574 // First, visit all predecessor edges.
Diego Novillob368b7d2014-10-22 16:51:50 +0000575 for (auto *Pred : Predecessors[BB]) {
576 Edge E = std::make_pair(Pred, BB);
Diego Novillo0accb3d2014-01-10 23:23:46 +0000577 TotalWeight += visitEdge(E, &NumUnknownEdges, &UnknownEdge);
578 if (E.first == E.second)
579 SelfReferentialEdge = E;
580 }
581 } else {
582 // On the second round, visit all successor edges.
Diego Novillob368b7d2014-10-22 16:51:50 +0000583 for (auto *Succ : Successors[BB]) {
584 Edge E = std::make_pair(BB, Succ);
Diego Novillo0accb3d2014-01-10 23:23:46 +0000585 TotalWeight += visitEdge(E, &NumUnknownEdges, &UnknownEdge);
586 }
587 }
588
589 // After visiting all the edges, there are three cases that we
590 // can handle immediately:
591 //
592 // - All the edge weights are known (i.e., NumUnknownEdges == 0).
593 // In this case, we simply check that the sum of all the edges
594 // is the same as BB's weight. If not, we change BB's weight
595 // to match. Additionally, if BB had not been visited before,
596 // we mark it visited.
597 //
598 // - Only one edge is unknown and BB has already been visited.
599 // In this case, we can compute the weight of the edge by
600 // subtracting the total block weight from all the known
601 // edge weights. If the edges weight more than BB, then the
602 // edge of the last remaining edge is set to zero.
603 //
604 // - There exists a self-referential edge and the weight of BB is
605 // known. In this case, this edge can be based on BB's weight.
606 // We add up all the other known edges and set the weight on
607 // the self-referential edge as we did in the previous case.
608 //
609 // In any other case, we must continue iterating. Eventually,
610 // all edges will get a weight, or iteration will stop when
611 // it reaches SampleProfileMaxPropagateIterations.
612 if (NumUnknownEdges <= 1) {
Diego Novillo38be3332015-10-15 16:36:21 +0000613 uint64_t &BBWeight = BlockWeights[EC];
Diego Novillo0accb3d2014-01-10 23:23:46 +0000614 if (NumUnknownEdges == 0) {
615 // If we already know the weight of all edges, the weight of the
616 // basic block can be computed. It should be no larger than the sum
617 // of all edge weights.
618 if (TotalWeight > BBWeight) {
619 BBWeight = TotalWeight;
620 Changed = true;
621 DEBUG(dbgs() << "All edge weights for " << BB->getName()
622 << " known. Set weight for block: ";
623 printBlockWeight(dbgs(), BB););
624 }
Dehao Chen7c41dd62015-10-01 00:26:56 +0000625 if (VisitedBlocks.insert(EC).second)
Diego Novillo0accb3d2014-01-10 23:23:46 +0000626 Changed = true;
Dehao Chen7c41dd62015-10-01 00:26:56 +0000627 } else if (NumUnknownEdges == 1 && VisitedBlocks.count(EC)) {
Diego Novillo0accb3d2014-01-10 23:23:46 +0000628 // If there is a single unknown edge and the block has been
629 // visited, then we can compute E's weight.
630 if (BBWeight >= TotalWeight)
631 EdgeWeights[UnknownEdge] = BBWeight - TotalWeight;
632 else
633 EdgeWeights[UnknownEdge] = 0;
634 VisitedEdges.insert(UnknownEdge);
635 Changed = true;
636 DEBUG(dbgs() << "Set weight for edge: ";
637 printEdgeWeight(dbgs(), UnknownEdge));
638 }
Dehao Chen7c41dd62015-10-01 00:26:56 +0000639 } else if (SelfReferentialEdge.first && VisitedBlocks.count(EC)) {
Diego Novillo38be3332015-10-15 16:36:21 +0000640 uint64_t &BBWeight = BlockWeights[BB];
Diego Novillo0accb3d2014-01-10 23:23:46 +0000641 // We have a self-referential edge and the weight of BB is known.
642 if (BBWeight >= TotalWeight)
643 EdgeWeights[SelfReferentialEdge] = BBWeight - TotalWeight;
644 else
645 EdgeWeights[SelfReferentialEdge] = 0;
646 VisitedEdges.insert(SelfReferentialEdge);
647 Changed = true;
648 DEBUG(dbgs() << "Set self-referential edge weight to: ";
649 printEdgeWeight(dbgs(), SelfReferentialEdge));
650 }
651 }
652 }
653
654 return Changed;
655}
656
657/// \brief Build in/out edge lists for each basic block in the CFG.
658///
659/// We are interested in unique edges. If a block B1 has multiple
660/// edges to another block B2, we only add a single B1->B2 edge.
Diego Novillode1ab262014-09-09 12:40:50 +0000661void SampleProfileLoader::buildEdges(Function &F) {
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000662 for (auto &BI : F) {
663 BasicBlock *B1 = &BI;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000664
665 // Add predecessors for B1.
666 SmallPtrSet<BasicBlock *, 16> Visited;
667 if (!Predecessors[B1].empty())
668 llvm_unreachable("Found a stale predecessors list in a basic block.");
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000669 for (pred_iterator PI = pred_begin(B1), PE = pred_end(B1); PI != PE; ++PI) {
670 BasicBlock *B2 = *PI;
David Blaikie70573dc2014-11-19 07:49:26 +0000671 if (Visited.insert(B2).second)
Diego Novillo0accb3d2014-01-10 23:23:46 +0000672 Predecessors[B1].push_back(B2);
673 }
674
675 // Add successors for B1.
676 Visited.clear();
677 if (!Successors[B1].empty())
678 llvm_unreachable("Found a stale successors list in a basic block.");
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000679 for (succ_iterator SI = succ_begin(B1), SE = succ_end(B1); SI != SE; ++SI) {
680 BasicBlock *B2 = *SI;
David Blaikie70573dc2014-11-19 07:49:26 +0000681 if (Visited.insert(B2).second)
Diego Novillo0accb3d2014-01-10 23:23:46 +0000682 Successors[B1].push_back(B2);
683 }
684 }
685}
686
687/// \brief Propagate weights into edges
688///
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000689/// The following rules are applied to every block BB in the CFG:
Diego Novillo0accb3d2014-01-10 23:23:46 +0000690///
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000691/// - If BB has a single predecessor/successor, then the weight
Diego Novillo0accb3d2014-01-10 23:23:46 +0000692/// of that edge is the weight of the block.
693///
694/// - If all incoming or outgoing edges are known except one, and the
695/// weight of the block is already known, the weight of the unknown
696/// edge will be the weight of the block minus the sum of all the known
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000697/// edges. If the sum of all the known edges is larger than BB's weight,
Diego Novillo0accb3d2014-01-10 23:23:46 +0000698/// we set the unknown edge weight to zero.
699///
700/// - If there is a self-referential edge, and the weight of the block is
701/// known, the weight for that edge is set to the weight of the block
702/// minus the weight of the other incoming edges to that block (if
703/// known).
Diego Novillode1ab262014-09-09 12:40:50 +0000704void SampleProfileLoader::propagateWeights(Function &F) {
Diego Novillo0accb3d2014-01-10 23:23:46 +0000705 bool Changed = true;
Diego Novillo38be3332015-10-15 16:36:21 +0000706 unsigned I = 0;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000707
Diego Novilloffc84e32015-05-13 17:04:29 +0000708 // Add an entry count to the function using the samples gathered
709 // at the function entry.
710 F.setEntryCount(Samples->getHeadSamples());
711
Diego Novillo0accb3d2014-01-10 23:23:46 +0000712 // Before propagation starts, build, for each block, a list of
713 // unique predecessors and successors. This is necessary to handle
714 // identical edges in multiway branches. Since we visit all blocks and all
715 // edges of the CFG, it is cleaner to build these lists once at the start
716 // of the pass.
717 buildEdges(F);
718
719 // Propagate until we converge or we go past the iteration limit.
Diego Novillo38be3332015-10-15 16:36:21 +0000720 while (Changed && I++ < SampleProfileMaxPropagateIterations) {
Diego Novillo0accb3d2014-01-10 23:23:46 +0000721 Changed = propagateThroughEdges(F);
722 }
723
724 // Generate MD_prof metadata for every branch instruction using the
725 // edge weights computed during propagation.
726 DEBUG(dbgs() << "\nPropagation complete. Setting branch weights\n");
727 MDBuilder MDB(F.getContext());
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000728 for (auto &BI : F) {
729 BasicBlock *BB = &BI;
730 TerminatorInst *TI = BB->getTerminator();
Diego Novillo0accb3d2014-01-10 23:23:46 +0000731 if (TI->getNumSuccessors() == 1)
732 continue;
733 if (!isa<BranchInst>(TI) && !isa<SwitchInst>(TI))
734 continue;
735
736 DEBUG(dbgs() << "\nGetting weights for branch at line "
Diego Novillo92aa8c22014-03-10 22:41:28 +0000737 << TI->getDebugLoc().getLine() << ".\n");
Diego Novillo38be3332015-10-15 16:36:21 +0000738 SmallVector<uint32_t, 4> Weights;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000739 bool AllWeightsZero = true;
740 for (unsigned I = 0; I < TI->getNumSuccessors(); ++I) {
741 BasicBlock *Succ = TI->getSuccessor(I);
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000742 Edge E = std::make_pair(BB, Succ);
Diego Novillo38be3332015-10-15 16:36:21 +0000743 uint64_t Weight = EdgeWeights[E];
Diego Novillo0accb3d2014-01-10 23:23:46 +0000744 DEBUG(dbgs() << "\t"; printEdgeWeight(dbgs(), E));
Diego Novillo38be3332015-10-15 16:36:21 +0000745 // Use uint32_t saturated arithmetic to adjust the incoming weights,
746 // if needed. Sample counts in profiles are 64-bit unsigned values,
747 // but internally branch weights are expressed as 32-bit values.
748 if (Weight > std::numeric_limits<uint32_t>::max()) {
749 DEBUG(dbgs() << " (saturated due to uint32_t overflow)");
750 Weight = std::numeric_limits<uint32_t>::max();
751 }
752 Weights.push_back(static_cast<uint32_t>(Weight));
Diego Novillo0accb3d2014-01-10 23:23:46 +0000753 if (Weight != 0)
754 AllWeightsZero = false;
755 }
756
757 // Only set weights if there is at least one non-zero weight.
758 // In any other case, let the analyzer set weights.
759 if (!AllWeightsZero) {
760 DEBUG(dbgs() << "SUCCESS. Found non-zero weights.\n");
761 TI->setMetadata(llvm::LLVMContext::MD_prof,
762 MDB.createBranchWeights(Weights));
763 } else {
764 DEBUG(dbgs() << "SKIPPED. All branch weights are zero.\n");
765 }
766 }
767}
768
769/// \brief Get the line number for the function header.
770///
771/// This looks up function \p F in the current compilation unit and
772/// retrieves the line number where the function is defined. This is
773/// line 0 for all the samples read from the profile file. Every line
774/// number is relative to this line.
775///
776/// \param F Function object to query.
777///
Diego Novilloa32aa322014-03-14 21:58:59 +0000778/// \returns the line number where \p F is defined. If it returns 0,
779/// it means that there is no debug information available for \p F.
Diego Novillode1ab262014-09-09 12:40:50 +0000780unsigned SampleProfileLoader::getFunctionLoc(Function &F) {
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000781 if (DISubprogram *S = getDISubprogram(&F))
Duncan P. N. Exon Smith537b4a82015-04-14 03:40:37 +0000782 return S->getLine();
Diego Novillo0accb3d2014-01-10 23:23:46 +0000783
Diego Novillo8027b802014-10-22 12:59:00 +0000784 // If could not find the start of \p F, emit a diagnostic to inform the user
785 // about the missed opportunity.
David Blaikie61079682014-03-16 01:36:18 +0000786 F.getContext().diagnose(DiagnosticInfoSampleProfile(
Diego Novilloa67c0b42014-10-22 13:36:35 +0000787 "No debug information found in function " + F.getName() +
788 ": Function profile not used",
789 DS_Warning));
Diego Novilloa32aa322014-03-14 21:58:59 +0000790 return 0;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000791}
792
Diego Novillo7732ae42015-08-26 20:00:27 +0000793void SampleProfileLoader::computeDominanceAndLoopInfo(Function &F) {
794 DT.reset(new DominatorTree);
795 DT->recalculate(F);
796
797 PDT.reset(new DominatorTreeBase<BasicBlock>(true));
798 PDT->recalculate(F);
799
800 LI.reset(new LoopInfo);
801 LI->analyze(*DT);
802}
803
Diego Novillo0accb3d2014-01-10 23:23:46 +0000804/// \brief Generate branch weight metadata for all branches in \p F.
805///
806/// Branch weights are computed out of instruction samples using a
807/// propagation heuristic. Propagation proceeds in 3 phases:
808///
809/// 1- Assignment of block weights. All the basic blocks in the function
810/// are initial assigned the same weight as their most frequently
811/// executed instruction.
812///
813/// 2- Creation of equivalence classes. Since samples may be missing from
814/// blocks, we can fill in the gaps by setting the weights of all the
815/// blocks in the same equivalence class to the same weight. To compute
816/// the concept of equivalence, we use dominance and loop information.
817/// Two blocks B1 and B2 are in the same equivalence class if B1
818/// dominates B2, B2 post-dominates B1 and both are in the same loop.
819///
820/// 3- Propagation of block weights into edges. This uses a simple
821/// propagation heuristic. The following rules are applied to every
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000822/// block BB in the CFG:
Diego Novillo0accb3d2014-01-10 23:23:46 +0000823///
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000824/// - If BB has a single predecessor/successor, then the weight
Diego Novillo0accb3d2014-01-10 23:23:46 +0000825/// of that edge is the weight of the block.
826///
827/// - If all the edges are known except one, and the weight of the
828/// block is already known, the weight of the unknown edge will
829/// be the weight of the block minus the sum of all the known
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000830/// edges. If the sum of all the known edges is larger than BB's weight,
Diego Novillo0accb3d2014-01-10 23:23:46 +0000831/// we set the unknown edge weight to zero.
832///
833/// - If there is a self-referential edge, and the weight of the block is
834/// known, the weight for that edge is set to the weight of the block
835/// minus the weight of the other incoming edges to that block (if
836/// known).
837///
838/// Since this propagation is not guaranteed to finalize for every CFG, we
839/// only allow it to proceed for a limited number of iterations (controlled
840/// by -sample-profile-max-propagate-iterations).
841///
842/// FIXME: Try to replace this propagation heuristic with a scheme
843/// that is guaranteed to finalize. A work-list approach similar to
844/// the standard value propagation algorithm used by SSA-CCP might
845/// work here.
846///
847/// Once all the branch weights are computed, we emit the MD_prof
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000848/// metadata on BB using the computed values for each of its branches.
Diego Novillo0accb3d2014-01-10 23:23:46 +0000849///
850/// \param F The function to query.
Diego Novilloa32aa322014-03-14 21:58:59 +0000851///
852/// \returns true if \p F was modified. Returns false, otherwise.
Diego Novillode1ab262014-09-09 12:40:50 +0000853bool SampleProfileLoader::emitAnnotations(Function &F) {
Diego Novillo0accb3d2014-01-10 23:23:46 +0000854 bool Changed = false;
855
Dehao Chen41dc5a62015-10-09 16:50:16 +0000856 if (getFunctionLoc(F) == 0)
Diego Novilloa32aa322014-03-14 21:58:59 +0000857 return false;
858
Diego Novillo0accb3d2014-01-10 23:23:46 +0000859 DEBUG(dbgs() << "Line number for the first instruction in " << F.getName()
Dehao Chen41dc5a62015-10-09 16:50:16 +0000860 << ": " << getFunctionLoc(F) << "\n");
Diego Novillo0accb3d2014-01-10 23:23:46 +0000861
Dehao Chen67226882015-09-30 00:42:46 +0000862 Changed |= inlineHotFunctions(F);
863
Diego Novillo0accb3d2014-01-10 23:23:46 +0000864 // Compute basic block weights.
865 Changed |= computeBlockWeights(F);
866
867 if (Changed) {
Diego Novillo7732ae42015-08-26 20:00:27 +0000868 // Compute dominance and loop info needed for propagation.
869 computeDominanceAndLoopInfo(F);
870
Diego Novillo0accb3d2014-01-10 23:23:46 +0000871 // Find equivalence classes.
872 findEquivalenceClasses(F);
873
874 // Propagate weights to all edges.
875 propagateWeights(F);
876 }
877
878 return Changed;
879}
880
Diego Novilloc0dd1032013-11-26 20:37:33 +0000881char SampleProfileLoader::ID = 0;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000882INITIALIZE_PASS_BEGIN(SampleProfileLoader, "sample-profile",
883 "Sample Profile loader", false, false)
Diego Novillo92aa8c22014-03-10 22:41:28 +0000884INITIALIZE_PASS_DEPENDENCY(AddDiscriminators)
Diego Novillo0accb3d2014-01-10 23:23:46 +0000885INITIALIZE_PASS_END(SampleProfileLoader, "sample-profile",
886 "Sample Profile loader", false, false)
Diego Novilloc0dd1032013-11-26 20:37:33 +0000887
888bool SampleProfileLoader::doInitialization(Module &M) {
Diego Novillo7732ae42015-08-26 20:00:27 +0000889 auto &Ctx = M.getContext();
Diego Novillo4d711132015-08-25 15:25:11 +0000890 auto ReaderOrErr = SampleProfileReader::create(Filename, Ctx);
Diego Novillofcd55602014-11-03 00:51:45 +0000891 if (std::error_code EC = ReaderOrErr.getError()) {
Diego Novilloc572e922014-10-30 18:00:06 +0000892 std::string Msg = "Could not open profile: " + EC.message();
Diego Novillo4d711132015-08-25 15:25:11 +0000893 Ctx.diagnose(DiagnosticInfoSampleProfile(Filename.data(), Msg));
Diego Novilloc572e922014-10-30 18:00:06 +0000894 return false;
895 }
Diego Novillofcd55602014-11-03 00:51:45 +0000896 Reader = std::move(ReaderOrErr.get());
Diego Novilloc572e922014-10-30 18:00:06 +0000897 ProfileIsValid = (Reader->read() == sampleprof_error::success);
Diego Novilloc0dd1032013-11-26 20:37:33 +0000898 return true;
899}
900
Diego Novillo4d711132015-08-25 15:25:11 +0000901ModulePass *llvm::createSampleProfileLoaderPass() {
Diego Novilloc0dd1032013-11-26 20:37:33 +0000902 return new SampleProfileLoader(SampleProfileFile);
903}
904
Diego Novillo4d711132015-08-25 15:25:11 +0000905ModulePass *llvm::createSampleProfileLoaderPass(StringRef Name) {
Diego Novilloc0dd1032013-11-26 20:37:33 +0000906 return new SampleProfileLoader(Name);
907}
908
Diego Novillo4d711132015-08-25 15:25:11 +0000909bool SampleProfileLoader::runOnModule(Module &M) {
910 bool retval = false;
911 for (auto &F : M)
912 if (!F.isDeclaration())
913 retval |= runOnFunction(F);
914 return retval;
915}
916
Diego Novillo8d6568b2013-11-13 12:22:21 +0000917bool SampleProfileLoader::runOnFunction(Function &F) {
Diego Novilloa32aa322014-03-14 21:58:59 +0000918 if (!ProfileIsValid)
919 return false;
Diego Novillode1ab262014-09-09 12:40:50 +0000920
Diego Novillode1ab262014-09-09 12:40:50 +0000921 Samples = Reader->getSamplesFor(F);
922 if (!Samples->empty())
923 return emitAnnotations(F);
Diego Novillo0accb3d2014-01-10 23:23:46 +0000924 return false;
Diego Novillo8d6568b2013-11-13 12:22:21 +0000925}