blob: 3e931f771128c6f8c7e9c09f58ad46e12f373316 [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"
Logan Chien61c6df02014-02-22 06:34:10 +000049#include <cctype>
Diego Novillo8d6568b2013-11-13 12:22:21 +000050
51using namespace llvm;
Diego Novillode1ab262014-09-09 12:40:50 +000052using namespace sampleprof;
Diego Novillo8d6568b2013-11-13 12:22:21 +000053
Chandler Carruth964daaa2014-04-22 02:55:47 +000054#define DEBUG_TYPE "sample-profile"
55
Diego Novillo8d6568b2013-11-13 12:22:21 +000056// 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 {
Dehao Chen8e7df832015-09-29 18:28:15 +000067typedef DenseMap<const BasicBlock *, unsigned> BlockWeightMap;
68typedef DenseMap<const BasicBlock *, const BasicBlock *> EquivalenceClassMap;
69typedef std::pair<const BasicBlock *, const BasicBlock *> Edge;
Diego Novillo92aa8c22014-03-10 22:41:28 +000070typedef DenseMap<Edge, unsigned> EdgeWeightMap;
Dehao Chen8e7df832015-09-29 18:28:15 +000071typedef DenseMap<const BasicBlock *, SmallVector<const BasicBlock *, 8>>
72 BlockEdgeMap;
Diego Novilloc0dd1032013-11-26 20:37:33 +000073
Diego Novillode1ab262014-09-09 12:40:50 +000074/// \brief Sample profile pass.
Diego Novilloc0dd1032013-11-26 20:37:33 +000075///
Diego Novillode1ab262014-09-09 12:40:50 +000076/// This pass reads profile data from the file specified by
77/// -sample-profile-file and annotates every affected function with the
78/// profile information found in that file.
Diego Novillo4d711132015-08-25 15:25:11 +000079class SampleProfileLoader : public ModulePass {
Diego Novilloc0dd1032013-11-26 20:37:33 +000080public:
Diego Novillode1ab262014-09-09 12:40:50 +000081 // Class identification, replacement for typeinfo
82 static char ID;
Diego Novilloc0dd1032013-11-26 20:37:33 +000083
Diego Novillode1ab262014-09-09 12:40:50 +000084 SampleProfileLoader(StringRef Name = SampleProfileFile)
Diego Novillo7732ae42015-08-26 20:00:27 +000085 : ModulePass(ID), DT(nullptr), PDT(nullptr), LI(nullptr), Reader(),
86 Samples(nullptr), Filename(Name), ProfileIsValid(false) {
Diego Novillode1ab262014-09-09 12:40:50 +000087 initializeSampleProfileLoaderPass(*PassRegistry::getPassRegistry());
88 }
89
90 bool doInitialization(Module &M) override;
91
92 void dump() { Reader->dump(); }
93
94 const char *getPassName() const override { return "Sample profile pass"; }
95
Diego Novillo4d711132015-08-25 15:25:11 +000096 bool runOnModule(Module &M) override;
Diego Novillode1ab262014-09-09 12:40:50 +000097
98 void getAnalysisUsage(AnalysisUsage &AU) const override {
99 AU.setPreservesCFG();
Diego Novillode1ab262014-09-09 12:40:50 +0000100 }
101
102protected:
Diego Novillo4d711132015-08-25 15:25:11 +0000103 bool runOnFunction(Function &F);
Diego Novillo0accb3d2014-01-10 23:23:46 +0000104 unsigned getFunctionLoc(Function &F);
Diego Novillode1ab262014-09-09 12:40:50 +0000105 bool emitAnnotations(Function &F);
Dehao Chen8e7df832015-09-29 18:28:15 +0000106 ErrorOr<unsigned> getInstWeight(const Instruction &I) const;
107 ErrorOr<unsigned> getBlockWeight(const BasicBlock *BB) const;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000108 void printEdgeWeight(raw_ostream &OS, Edge E);
Dehao Chen8e7df832015-09-29 18:28:15 +0000109 void printBlockWeight(raw_ostream &OS, const BasicBlock *BB) const;
110 void printBlockEquivalence(raw_ostream &OS, const BasicBlock *BB);
Diego Novillo0accb3d2014-01-10 23:23:46 +0000111 bool computeBlockWeights(Function &F);
112 void findEquivalenceClasses(Function &F);
113 void findEquivalencesFor(BasicBlock *BB1,
114 SmallVector<BasicBlock *, 8> Descendants,
115 DominatorTreeBase<BasicBlock> *DomTree);
116 void propagateWeights(Function &F);
Diego Novillo92aa8c22014-03-10 22:41:28 +0000117 unsigned visitEdge(Edge E, unsigned *NumUnknownEdges, Edge *UnknownEdge);
Diego Novillo0accb3d2014-01-10 23:23:46 +0000118 void buildEdges(Function &F);
119 bool propagateThroughEdges(Function &F);
Diego Novillo7732ae42015-08-26 20:00:27 +0000120 void computeDominanceAndLoopInfo(Function &F);
Diego Novilloc0dd1032013-11-26 20:37:33 +0000121
Diego Novillode1ab262014-09-09 12:40:50 +0000122 /// \brief Line number for the function header. Used to compute absolute
123 /// line numbers from the relative line numbers found in the profile.
Diego Novillo0accb3d2014-01-10 23:23:46 +0000124 unsigned HeaderLineno;
125
Diego Novilloc0dd1032013-11-26 20:37:33 +0000126 /// \brief Map basic blocks to their computed weights.
127 ///
128 /// The weight of a basic block is defined to be the maximum
129 /// of all the instruction weights in that block.
130 BlockWeightMap BlockWeights;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000131
132 /// \brief Map edges to their computed weights.
133 ///
134 /// Edge weights are computed by propagating basic block weights in
135 /// SampleProfile::propagateWeights.
136 EdgeWeightMap EdgeWeights;
137
138 /// \brief Set of visited blocks during propagation.
Dehao Chen8e7df832015-09-29 18:28:15 +0000139 SmallPtrSet<const BasicBlock *, 128> VisitedBlocks;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000140
141 /// \brief Set of visited edges during propagation.
142 SmallSet<Edge, 128> VisitedEdges;
143
144 /// \brief Equivalence classes for block weights.
145 ///
146 /// Two blocks BB1 and BB2 are in the same equivalence class if they
147 /// dominate and post-dominate each other, and they are in the same loop
148 /// nest. When this happens, the two blocks are guaranteed to execute
149 /// the same number of times.
150 EquivalenceClassMap EquivalenceClass;
151
152 /// \brief Dominance, post-dominance and loop information.
Diego Novillo7732ae42015-08-26 20:00:27 +0000153 std::unique_ptr<DominatorTree> DT;
154 std::unique_ptr<DominatorTreeBase<BasicBlock>> PDT;
155 std::unique_ptr<LoopInfo> LI;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000156
157 /// \brief Predecessors for each basic block in the CFG.
158 BlockEdgeMap Predecessors;
159
160 /// \brief Successors for each basic block in the CFG.
161 BlockEdgeMap Successors;
Diego Novillo92aa8c22014-03-10 22:41:28 +0000162
Diego Novillo8d6568b2013-11-13 12:22:21 +0000163 /// \brief Profile reader object.
Diego Novillode1ab262014-09-09 12:40:50 +0000164 std::unique_ptr<SampleProfileReader> Reader;
165
166 /// \brief Samples collected for the body of this function.
167 FunctionSamples *Samples;
Diego Novillo8d6568b2013-11-13 12:22:21 +0000168
169 /// \brief Name of the profile file to load.
170 StringRef Filename;
Diego Novilloa32aa322014-03-14 21:58:59 +0000171
Alp Toker16f98b22014-04-09 14:47:27 +0000172 /// \brief Flag indicating whether the profile input loaded successfully.
Diego Novilloa32aa322014-03-14 21:58:59 +0000173 bool ProfileIsValid;
Diego Novillo8d6568b2013-11-13 12:22:21 +0000174};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000175}
Diego Novillo8d6568b2013-11-13 12:22:21 +0000176
Diego Novillo0accb3d2014-01-10 23:23:46 +0000177/// \brief Print the weight of edge \p E on stream \p OS.
178///
179/// \param OS Stream to emit the output to.
180/// \param E Edge to print.
Diego Novillode1ab262014-09-09 12:40:50 +0000181void SampleProfileLoader::printEdgeWeight(raw_ostream &OS, Edge E) {
Diego Novillo0accb3d2014-01-10 23:23:46 +0000182 OS << "weight[" << E.first->getName() << "->" << E.second->getName()
183 << "]: " << EdgeWeights[E] << "\n";
184}
185
186/// \brief Print the equivalence class of block \p BB on stream \p OS.
187///
188/// \param OS Stream to emit the output to.
189/// \param BB Block to print.
Diego Novillode1ab262014-09-09 12:40:50 +0000190void SampleProfileLoader::printBlockEquivalence(raw_ostream &OS,
Dehao Chen8e7df832015-09-29 18:28:15 +0000191 const BasicBlock *BB) {
192 const BasicBlock *Equiv = EquivalenceClass[BB];
Diego Novillo0accb3d2014-01-10 23:23:46 +0000193 OS << "equivalence[" << BB->getName()
194 << "]: " << ((Equiv) ? EquivalenceClass[BB]->getName() : "NONE") << "\n";
195}
196
197/// \brief Print the weight of block \p BB on stream \p OS.
198///
199/// \param OS Stream to emit the output to.
200/// \param BB Block to print.
Dehao Chen8e7df832015-09-29 18:28:15 +0000201void SampleProfileLoader::printBlockWeight(raw_ostream &OS,
202 const BasicBlock *BB) const {
203 const auto &I = BlockWeights.find(BB);
204 unsigned W = (I == BlockWeights.end() ? 0 : I->second);
205 OS << "weight[" << BB->getName() << "]: " << W << "\n";
Diego Novillo0accb3d2014-01-10 23:23:46 +0000206}
207
Diego Novillo0accb3d2014-01-10 23:23:46 +0000208/// \brief Get the weight for an instruction.
209///
210/// The "weight" of an instruction \p Inst is the number of samples
211/// collected on that instruction at runtime. To retrieve it, we
212/// need to compute the line number of \p Inst relative to the start of its
213/// function. We use HeaderLineno to compute the offset. We then
214/// look up the samples collected for \p Inst using BodySamples.
215///
216/// \param Inst Instruction to query.
217///
Dehao Chen8e7df832015-09-29 18:28:15 +0000218/// \returns the weight of \p Inst.
219ErrorOr<unsigned>
220SampleProfileLoader::getInstWeight(const Instruction &Inst) const {
Diego Novillo92aa8c22014-03-10 22:41:28 +0000221 DebugLoc DLoc = Inst.getDebugLoc();
Duncan P. N. Exon Smithec819c02015-03-30 19:49:49 +0000222 if (!DLoc)
Dehao Chen8e7df832015-09-29 18:28:15 +0000223 return std::error_code();
Duncan P. N. Exon Smith41a15462015-03-20 00:56:55 +0000224
Diego Novillo92aa8c22014-03-10 22:41:28 +0000225 unsigned Lineno = DLoc.getLine();
Diego Novillo0accb3d2014-01-10 23:23:46 +0000226 if (Lineno < HeaderLineno)
Dehao Chen8e7df832015-09-29 18:28:15 +0000227 return std::error_code();
Diego Novillo92aa8c22014-03-10 22:41:28 +0000228
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000229 const DILocation *DIL = DLoc;
Dehao Chen8e7df832015-09-29 18:28:15 +0000230 ErrorOr<unsigned> R =
231 Samples->findSamplesAt(Lineno - HeaderLineno, DIL->getDiscriminator());
232 if (R)
233 DEBUG(dbgs() << " " << Lineno << "." << DIL->getDiscriminator() << ":"
234 << Inst << " (line offset: " << Lineno - HeaderLineno << "."
235 << DIL->getDiscriminator() << " - weight: " << R.get()
236 << ")\n");
237 return R;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000238}
239
240/// \brief Compute the weight of a basic block.
241///
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000242/// The weight of basic block \p BB is the maximum weight of all the
Dehao Chen8e7df832015-09-29 18:28:15 +0000243/// instructions in BB.
Diego Novillo0accb3d2014-01-10 23:23:46 +0000244///
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000245/// \param BB The basic block to query.
Diego Novillo0accb3d2014-01-10 23:23:46 +0000246///
Dehao Chen8e7df832015-09-29 18:28:15 +0000247/// \returns the weight for \p BB.
248ErrorOr<unsigned>
249SampleProfileLoader::getBlockWeight(const BasicBlock *BB) const {
250 bool Found = false;
Diego Novillo92aa8c22014-03-10 22:41:28 +0000251 unsigned Weight = 0;
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000252 for (auto &I : BB->getInstList()) {
Dehao Chen8e7df832015-09-29 18:28:15 +0000253 const ErrorOr<unsigned> &R = getInstWeight(I);
254 if (R && R.get() >= Weight) {
255 Weight = R.get();
256 Found = true;
257 }
Diego Novillo0accb3d2014-01-10 23:23:46 +0000258 }
Dehao Chen8e7df832015-09-29 18:28:15 +0000259 if (Found)
260 return Weight;
261 else
262 return std::error_code();
Diego Novillo0accb3d2014-01-10 23:23:46 +0000263}
264
265/// \brief Compute and store the weights of every basic block.
266///
267/// This populates the BlockWeights map by computing
268/// the weights of every basic block in the CFG.
269///
270/// \param F The function to query.
Diego Novillode1ab262014-09-09 12:40:50 +0000271bool SampleProfileLoader::computeBlockWeights(Function &F) {
Diego Novillo0accb3d2014-01-10 23:23:46 +0000272 bool Changed = false;
273 DEBUG(dbgs() << "Block weights\n");
Dehao Chen8e7df832015-09-29 18:28:15 +0000274 for (const auto &BB : F) {
275 ErrorOr<unsigned> Weight = getBlockWeight(&BB);
276 if (Weight) {
277 BlockWeights[&BB] = Weight.get();
278 Changed = true;
279 }
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000280 DEBUG(printBlockWeight(dbgs(), &BB));
Diego Novillo0accb3d2014-01-10 23:23:46 +0000281 }
282
283 return Changed;
284}
285
286/// \brief Find equivalence classes for the given block.
287///
288/// This finds all the blocks that are guaranteed to execute the same
Eric Christopher572e03a2015-06-19 01:53:21 +0000289/// number of times as \p BB1. To do this, it traverses all the
Diego Novillo0accb3d2014-01-10 23:23:46 +0000290/// descendants of \p BB1 in the dominator or post-dominator tree.
291///
292/// A block BB2 will be in the same equivalence class as \p BB1 if
293/// the following holds:
294///
295/// 1- \p BB1 is a descendant of BB2 in the opposite tree. So, if BB2
296/// is a descendant of \p BB1 in the dominator tree, then BB2 should
297/// dominate BB1 in the post-dominator tree.
298///
299/// 2- Both BB2 and \p BB1 must be in the same loop.
300///
301/// For every block BB2 that meets those two requirements, we set BB2's
302/// equivalence class to \p BB1.
303///
304/// \param BB1 Block to check.
305/// \param Descendants Descendants of \p BB1 in either the dom or pdom tree.
306/// \param DomTree Opposite dominator tree. If \p Descendants is filled
307/// with blocks from \p BB1's dominator tree, then
308/// this is the post-dominator tree, and vice versa.
Diego Novillode1ab262014-09-09 12:40:50 +0000309void SampleProfileLoader::findEquivalencesFor(
Diego Novillo0accb3d2014-01-10 23:23:46 +0000310 BasicBlock *BB1, SmallVector<BasicBlock *, 8> Descendants,
311 DominatorTreeBase<BasicBlock> *DomTree) {
Dehao Chen8e7df832015-09-29 18:28:15 +0000312 for (const auto *BB2 : Descendants) {
Diego Novillo0accb3d2014-01-10 23:23:46 +0000313 bool IsDomParent = DomTree->dominates(BB2, BB1);
314 bool IsInSameLoop = LI->getLoopFor(BB1) == LI->getLoopFor(BB2);
Dehao Chen028e1222015-09-29 18:18:49 +0000315 if (BB1 != BB2 && VisitedBlocks.insert(BB2).second && IsDomParent &&
316 IsInSameLoop) {
Diego Novillo0accb3d2014-01-10 23:23:46 +0000317 EquivalenceClass[BB2] = BB1;
318
319 // If BB2 is heavier than BB1, make BB2 have the same weight
320 // as BB1.
321 //
322 // Note that we don't worry about the opposite situation here
323 // (when BB2 is lighter than BB1). We will deal with this
324 // during the propagation phase. Right now, we just want to
325 // make sure that BB1 has the largest weight of all the
326 // members of its equivalence set.
Diego Novillo92aa8c22014-03-10 22:41:28 +0000327 unsigned &BB1Weight = BlockWeights[BB1];
328 unsigned &BB2Weight = BlockWeights[BB2];
Diego Novillo0accb3d2014-01-10 23:23:46 +0000329 BB1Weight = std::max(BB1Weight, BB2Weight);
330 }
331 }
332}
333
334/// \brief Find equivalence classes.
335///
336/// Since samples may be missing from blocks, we can fill in the gaps by setting
337/// the weights of all the blocks in the same equivalence class to the same
338/// weight. To compute the concept of equivalence, we use dominance and loop
339/// information. Two blocks B1 and B2 are in the same equivalence class if B1
340/// dominates B2, B2 post-dominates B1 and both are in the same loop.
341///
342/// \param F The function to query.
Diego Novillode1ab262014-09-09 12:40:50 +0000343void SampleProfileLoader::findEquivalenceClasses(Function &F) {
Diego Novillo0accb3d2014-01-10 23:23:46 +0000344 SmallVector<BasicBlock *, 8> DominatedBBs;
345 DEBUG(dbgs() << "\nBlock equivalence classes\n");
346 // Find equivalence sets based on dominance and post-dominance information.
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000347 for (auto &BB : F) {
348 BasicBlock *BB1 = &BB;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000349
350 // Compute BB1's equivalence class once.
351 if (EquivalenceClass.count(BB1)) {
352 DEBUG(printBlockEquivalence(dbgs(), BB1));
353 continue;
354 }
355
356 // By default, blocks are in their own equivalence class.
357 EquivalenceClass[BB1] = BB1;
358
359 // Traverse all the blocks dominated by BB1. We are looking for
360 // every basic block BB2 such that:
361 //
362 // 1- BB1 dominates BB2.
363 // 2- BB2 post-dominates BB1.
364 // 3- BB1 and BB2 are in the same loop nest.
365 //
366 // If all those conditions hold, it means that BB2 is executed
367 // as many times as BB1, so they are placed in the same equivalence
368 // class by making BB2's equivalence class be BB1.
369 DominatedBBs.clear();
370 DT->getDescendants(BB1, DominatedBBs);
Diego Novillo7732ae42015-08-26 20:00:27 +0000371 findEquivalencesFor(BB1, DominatedBBs, PDT.get());
Diego Novillo0accb3d2014-01-10 23:23:46 +0000372
373 // Repeat the same logic for all the blocks post-dominated by BB1.
374 // We are looking for every basic block BB2 such that:
375 //
376 // 1- BB1 post-dominates BB2.
377 // 2- BB2 dominates BB1.
378 // 3- BB1 and BB2 are in the same loop nest.
379 //
380 // If all those conditions hold, BB2's equivalence class is BB1.
381 DominatedBBs.clear();
382 PDT->getDescendants(BB1, DominatedBBs);
Diego Novillo7732ae42015-08-26 20:00:27 +0000383 findEquivalencesFor(BB1, DominatedBBs, DT.get());
Diego Novillo0accb3d2014-01-10 23:23:46 +0000384
385 DEBUG(printBlockEquivalence(dbgs(), BB1));
386 }
387
388 // Assign weights to equivalence classes.
389 //
390 // All the basic blocks in the same equivalence class will execute
391 // the same number of times. Since we know that the head block in
392 // each equivalence class has the largest weight, assign that weight
393 // to all the blocks in that equivalence class.
394 DEBUG(dbgs() << "\nAssign the same weight to all blocks in the same class\n");
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000395 for (auto &BI : F) {
Dehao Chen8e7df832015-09-29 18:28:15 +0000396 const BasicBlock *BB = &BI;
397 const BasicBlock *EquivBB = EquivalenceClass[BB];
Diego Novillo0accb3d2014-01-10 23:23:46 +0000398 if (BB != EquivBB)
399 BlockWeights[BB] = BlockWeights[EquivBB];
400 DEBUG(printBlockWeight(dbgs(), BB));
401 }
402}
403
404/// \brief Visit the given edge to decide if it has a valid weight.
405///
406/// If \p E has not been visited before, we copy to \p UnknownEdge
407/// and increment the count of unknown edges.
408///
409/// \param E Edge to visit.
410/// \param NumUnknownEdges Current number of unknown edges.
411/// \param UnknownEdge Set if E has not been visited before.
412///
413/// \returns E's weight, if known. Otherwise, return 0.
Diego Novillode1ab262014-09-09 12:40:50 +0000414unsigned SampleProfileLoader::visitEdge(Edge E, unsigned *NumUnknownEdges,
415 Edge *UnknownEdge) {
Diego Novillo0accb3d2014-01-10 23:23:46 +0000416 if (!VisitedEdges.count(E)) {
417 (*NumUnknownEdges)++;
418 *UnknownEdge = E;
419 return 0;
420 }
421
422 return EdgeWeights[E];
423}
424
425/// \brief Propagate weights through incoming/outgoing edges.
426///
427/// If the weight of a basic block is known, and there is only one edge
428/// with an unknown weight, we can calculate the weight of that edge.
429///
430/// Similarly, if all the edges have a known count, we can calculate the
431/// count of the basic block, if needed.
432///
433/// \param F Function to process.
434///
435/// \returns True if new weights were assigned to edges or blocks.
Diego Novillode1ab262014-09-09 12:40:50 +0000436bool SampleProfileLoader::propagateThroughEdges(Function &F) {
Diego Novillo0accb3d2014-01-10 23:23:46 +0000437 bool Changed = false;
438 DEBUG(dbgs() << "\nPropagation through edges\n");
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000439 for (auto &BI : F) {
440 BasicBlock *BB = &BI;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000441
442 // Visit all the predecessor and successor edges to determine
443 // which ones have a weight assigned already. Note that it doesn't
444 // matter that we only keep track of a single unknown edge. The
445 // only case we are interested in handling is when only a single
446 // edge is unknown (see setEdgeOrBlockWeight).
447 for (unsigned i = 0; i < 2; i++) {
Diego Novillo92aa8c22014-03-10 22:41:28 +0000448 unsigned TotalWeight = 0;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000449 unsigned NumUnknownEdges = 0;
450 Edge UnknownEdge, SelfReferentialEdge;
451
452 if (i == 0) {
453 // First, visit all predecessor edges.
Diego Novillob368b7d2014-10-22 16:51:50 +0000454 for (auto *Pred : Predecessors[BB]) {
455 Edge E = std::make_pair(Pred, BB);
Diego Novillo0accb3d2014-01-10 23:23:46 +0000456 TotalWeight += visitEdge(E, &NumUnknownEdges, &UnknownEdge);
457 if (E.first == E.second)
458 SelfReferentialEdge = E;
459 }
460 } else {
461 // On the second round, visit all successor edges.
Diego Novillob368b7d2014-10-22 16:51:50 +0000462 for (auto *Succ : Successors[BB]) {
463 Edge E = std::make_pair(BB, Succ);
Diego Novillo0accb3d2014-01-10 23:23:46 +0000464 TotalWeight += visitEdge(E, &NumUnknownEdges, &UnknownEdge);
465 }
466 }
467
468 // After visiting all the edges, there are three cases that we
469 // can handle immediately:
470 //
471 // - All the edge weights are known (i.e., NumUnknownEdges == 0).
472 // In this case, we simply check that the sum of all the edges
473 // is the same as BB's weight. If not, we change BB's weight
474 // to match. Additionally, if BB had not been visited before,
475 // we mark it visited.
476 //
477 // - Only one edge is unknown and BB has already been visited.
478 // In this case, we can compute the weight of the edge by
479 // subtracting the total block weight from all the known
480 // edge weights. If the edges weight more than BB, then the
481 // edge of the last remaining edge is set to zero.
482 //
483 // - There exists a self-referential edge and the weight of BB is
484 // known. In this case, this edge can be based on BB's weight.
485 // We add up all the other known edges and set the weight on
486 // the self-referential edge as we did in the previous case.
487 //
488 // In any other case, we must continue iterating. Eventually,
489 // all edges will get a weight, or iteration will stop when
490 // it reaches SampleProfileMaxPropagateIterations.
491 if (NumUnknownEdges <= 1) {
Diego Novillo92aa8c22014-03-10 22:41:28 +0000492 unsigned &BBWeight = BlockWeights[BB];
Diego Novillo0accb3d2014-01-10 23:23:46 +0000493 if (NumUnknownEdges == 0) {
494 // If we already know the weight of all edges, the weight of the
495 // basic block can be computed. It should be no larger than the sum
496 // of all edge weights.
497 if (TotalWeight > BBWeight) {
498 BBWeight = TotalWeight;
499 Changed = true;
500 DEBUG(dbgs() << "All edge weights for " << BB->getName()
501 << " known. Set weight for block: ";
502 printBlockWeight(dbgs(), BB););
503 }
David Blaikie70573dc2014-11-19 07:49:26 +0000504 if (VisitedBlocks.insert(BB).second)
Diego Novillo0accb3d2014-01-10 23:23:46 +0000505 Changed = true;
506 } else if (NumUnknownEdges == 1 && VisitedBlocks.count(BB)) {
507 // If there is a single unknown edge and the block has been
508 // visited, then we can compute E's weight.
509 if (BBWeight >= TotalWeight)
510 EdgeWeights[UnknownEdge] = BBWeight - TotalWeight;
511 else
512 EdgeWeights[UnknownEdge] = 0;
513 VisitedEdges.insert(UnknownEdge);
514 Changed = true;
515 DEBUG(dbgs() << "Set weight for edge: ";
516 printEdgeWeight(dbgs(), UnknownEdge));
517 }
518 } else if (SelfReferentialEdge.first && VisitedBlocks.count(BB)) {
Diego Novillo92aa8c22014-03-10 22:41:28 +0000519 unsigned &BBWeight = BlockWeights[BB];
Diego Novillo0accb3d2014-01-10 23:23:46 +0000520 // We have a self-referential edge and the weight of BB is known.
521 if (BBWeight >= TotalWeight)
522 EdgeWeights[SelfReferentialEdge] = BBWeight - TotalWeight;
523 else
524 EdgeWeights[SelfReferentialEdge] = 0;
525 VisitedEdges.insert(SelfReferentialEdge);
526 Changed = true;
527 DEBUG(dbgs() << "Set self-referential edge weight to: ";
528 printEdgeWeight(dbgs(), SelfReferentialEdge));
529 }
530 }
531 }
532
533 return Changed;
534}
535
536/// \brief Build in/out edge lists for each basic block in the CFG.
537///
538/// We are interested in unique edges. If a block B1 has multiple
539/// edges to another block B2, we only add a single B1->B2 edge.
Diego Novillode1ab262014-09-09 12:40:50 +0000540void SampleProfileLoader::buildEdges(Function &F) {
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000541 for (auto &BI : F) {
542 BasicBlock *B1 = &BI;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000543
544 // Add predecessors for B1.
545 SmallPtrSet<BasicBlock *, 16> Visited;
546 if (!Predecessors[B1].empty())
547 llvm_unreachable("Found a stale predecessors list in a basic block.");
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000548 for (pred_iterator PI = pred_begin(B1), PE = pred_end(B1); PI != PE; ++PI) {
549 BasicBlock *B2 = *PI;
David Blaikie70573dc2014-11-19 07:49:26 +0000550 if (Visited.insert(B2).second)
Diego Novillo0accb3d2014-01-10 23:23:46 +0000551 Predecessors[B1].push_back(B2);
552 }
553
554 // Add successors for B1.
555 Visited.clear();
556 if (!Successors[B1].empty())
557 llvm_unreachable("Found a stale successors list in a basic block.");
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000558 for (succ_iterator SI = succ_begin(B1), SE = succ_end(B1); SI != SE; ++SI) {
559 BasicBlock *B2 = *SI;
David Blaikie70573dc2014-11-19 07:49:26 +0000560 if (Visited.insert(B2).second)
Diego Novillo0accb3d2014-01-10 23:23:46 +0000561 Successors[B1].push_back(B2);
562 }
563 }
564}
565
566/// \brief Propagate weights into edges
567///
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000568/// The following rules are applied to every block BB in the CFG:
Diego Novillo0accb3d2014-01-10 23:23:46 +0000569///
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000570/// - If BB has a single predecessor/successor, then the weight
Diego Novillo0accb3d2014-01-10 23:23:46 +0000571/// of that edge is the weight of the block.
572///
573/// - If all incoming or outgoing edges are known except one, and the
574/// weight of the block is already known, the weight of the unknown
575/// edge will be the weight of the block minus the sum of all the known
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000576/// edges. If the sum of all the known edges is larger than BB's weight,
Diego Novillo0accb3d2014-01-10 23:23:46 +0000577/// we set the unknown edge weight to zero.
578///
579/// - If there is a self-referential edge, and the weight of the block is
580/// known, the weight for that edge is set to the weight of the block
581/// minus the weight of the other incoming edges to that block (if
582/// known).
Diego Novillode1ab262014-09-09 12:40:50 +0000583void SampleProfileLoader::propagateWeights(Function &F) {
Diego Novillo0accb3d2014-01-10 23:23:46 +0000584 bool Changed = true;
585 unsigned i = 0;
586
Diego Novilloffc84e32015-05-13 17:04:29 +0000587 // Add an entry count to the function using the samples gathered
588 // at the function entry.
589 F.setEntryCount(Samples->getHeadSamples());
590
Diego Novillo0accb3d2014-01-10 23:23:46 +0000591 // Before propagation starts, build, for each block, a list of
592 // unique predecessors and successors. This is necessary to handle
593 // identical edges in multiway branches. Since we visit all blocks and all
594 // edges of the CFG, it is cleaner to build these lists once at the start
595 // of the pass.
596 buildEdges(F);
597
598 // Propagate until we converge or we go past the iteration limit.
599 while (Changed && i++ < SampleProfileMaxPropagateIterations) {
600 Changed = propagateThroughEdges(F);
601 }
602
603 // Generate MD_prof metadata for every branch instruction using the
604 // edge weights computed during propagation.
605 DEBUG(dbgs() << "\nPropagation complete. Setting branch weights\n");
606 MDBuilder MDB(F.getContext());
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000607 for (auto &BI : F) {
608 BasicBlock *BB = &BI;
609 TerminatorInst *TI = BB->getTerminator();
Diego Novillo0accb3d2014-01-10 23:23:46 +0000610 if (TI->getNumSuccessors() == 1)
611 continue;
612 if (!isa<BranchInst>(TI) && !isa<SwitchInst>(TI))
613 continue;
614
615 DEBUG(dbgs() << "\nGetting weights for branch at line "
Diego Novillo92aa8c22014-03-10 22:41:28 +0000616 << TI->getDebugLoc().getLine() << ".\n");
617 SmallVector<unsigned, 4> Weights;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000618 bool AllWeightsZero = true;
619 for (unsigned I = 0; I < TI->getNumSuccessors(); ++I) {
620 BasicBlock *Succ = TI->getSuccessor(I);
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000621 Edge E = std::make_pair(BB, Succ);
Diego Novillo92aa8c22014-03-10 22:41:28 +0000622 unsigned Weight = EdgeWeights[E];
Diego Novillo0accb3d2014-01-10 23:23:46 +0000623 DEBUG(dbgs() << "\t"; printEdgeWeight(dbgs(), E));
624 Weights.push_back(Weight);
625 if (Weight != 0)
626 AllWeightsZero = false;
627 }
628
629 // Only set weights if there is at least one non-zero weight.
630 // In any other case, let the analyzer set weights.
631 if (!AllWeightsZero) {
632 DEBUG(dbgs() << "SUCCESS. Found non-zero weights.\n");
633 TI->setMetadata(llvm::LLVMContext::MD_prof,
634 MDB.createBranchWeights(Weights));
635 } else {
636 DEBUG(dbgs() << "SKIPPED. All branch weights are zero.\n");
637 }
638 }
639}
640
641/// \brief Get the line number for the function header.
642///
643/// This looks up function \p F in the current compilation unit and
644/// retrieves the line number where the function is defined. This is
645/// line 0 for all the samples read from the profile file. Every line
646/// number is relative to this line.
647///
648/// \param F Function object to query.
649///
Diego Novilloa32aa322014-03-14 21:58:59 +0000650/// \returns the line number where \p F is defined. If it returns 0,
651/// it means that there is no debug information available for \p F.
Diego Novillode1ab262014-09-09 12:40:50 +0000652unsigned SampleProfileLoader::getFunctionLoc(Function &F) {
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000653 if (DISubprogram *S = getDISubprogram(&F))
Duncan P. N. Exon Smith537b4a82015-04-14 03:40:37 +0000654 return S->getLine();
Diego Novillo0accb3d2014-01-10 23:23:46 +0000655
Diego Novillo8027b802014-10-22 12:59:00 +0000656 // If could not find the start of \p F, emit a diagnostic to inform the user
657 // about the missed opportunity.
David Blaikie61079682014-03-16 01:36:18 +0000658 F.getContext().diagnose(DiagnosticInfoSampleProfile(
Diego Novilloa67c0b42014-10-22 13:36:35 +0000659 "No debug information found in function " + F.getName() +
660 ": Function profile not used",
661 DS_Warning));
Diego Novilloa32aa322014-03-14 21:58:59 +0000662 return 0;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000663}
664
Diego Novillo7732ae42015-08-26 20:00:27 +0000665void SampleProfileLoader::computeDominanceAndLoopInfo(Function &F) {
666 DT.reset(new DominatorTree);
667 DT->recalculate(F);
668
669 PDT.reset(new DominatorTreeBase<BasicBlock>(true));
670 PDT->recalculate(F);
671
672 LI.reset(new LoopInfo);
673 LI->analyze(*DT);
674}
675
Diego Novillo0accb3d2014-01-10 23:23:46 +0000676/// \brief Generate branch weight metadata for all branches in \p F.
677///
678/// Branch weights are computed out of instruction samples using a
679/// propagation heuristic. Propagation proceeds in 3 phases:
680///
681/// 1- Assignment of block weights. All the basic blocks in the function
682/// are initial assigned the same weight as their most frequently
683/// executed instruction.
684///
685/// 2- Creation of equivalence classes. Since samples may be missing from
686/// blocks, we can fill in the gaps by setting the weights of all the
687/// blocks in the same equivalence class to the same weight. To compute
688/// the concept of equivalence, we use dominance and loop information.
689/// Two blocks B1 and B2 are in the same equivalence class if B1
690/// dominates B2, B2 post-dominates B1 and both are in the same loop.
691///
692/// 3- Propagation of block weights into edges. This uses a simple
693/// propagation heuristic. The following rules are applied to every
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000694/// block BB in the CFG:
Diego Novillo0accb3d2014-01-10 23:23:46 +0000695///
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000696/// - If BB has a single predecessor/successor, then the weight
Diego Novillo0accb3d2014-01-10 23:23:46 +0000697/// of that edge is the weight of the block.
698///
699/// - If all the edges are known except one, and the weight of the
700/// block is already known, the weight of the unknown edge will
701/// be the weight of the block minus the sum of all the known
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000702/// edges. If the sum of all the known edges is larger than BB's weight,
Diego Novillo0accb3d2014-01-10 23:23:46 +0000703/// we set the unknown edge weight to zero.
704///
705/// - If there is a self-referential edge, and the weight of the block is
706/// known, the weight for that edge is set to the weight of the block
707/// minus the weight of the other incoming edges to that block (if
708/// known).
709///
710/// Since this propagation is not guaranteed to finalize for every CFG, we
711/// only allow it to proceed for a limited number of iterations (controlled
712/// by -sample-profile-max-propagate-iterations).
713///
714/// FIXME: Try to replace this propagation heuristic with a scheme
715/// that is guaranteed to finalize. A work-list approach similar to
716/// the standard value propagation algorithm used by SSA-CCP might
717/// work here.
718///
719/// Once all the branch weights are computed, we emit the MD_prof
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000720/// metadata on BB using the computed values for each of its branches.
Diego Novillo0accb3d2014-01-10 23:23:46 +0000721///
722/// \param F The function to query.
Diego Novilloa32aa322014-03-14 21:58:59 +0000723///
724/// \returns true if \p F was modified. Returns false, otherwise.
Diego Novillode1ab262014-09-09 12:40:50 +0000725bool SampleProfileLoader::emitAnnotations(Function &F) {
Diego Novillo0accb3d2014-01-10 23:23:46 +0000726 bool Changed = false;
727
728 // Initialize invariants used during computation and propagation.
729 HeaderLineno = getFunctionLoc(F);
Diego Novilloa32aa322014-03-14 21:58:59 +0000730 if (HeaderLineno == 0)
731 return false;
732
Diego Novillo0accb3d2014-01-10 23:23:46 +0000733 DEBUG(dbgs() << "Line number for the first instruction in " << F.getName()
734 << ": " << HeaderLineno << "\n");
Diego Novillo0accb3d2014-01-10 23:23:46 +0000735
736 // Compute basic block weights.
737 Changed |= computeBlockWeights(F);
738
739 if (Changed) {
Diego Novillo7732ae42015-08-26 20:00:27 +0000740 // Compute dominance and loop info needed for propagation.
741 computeDominanceAndLoopInfo(F);
742
Diego Novillo0accb3d2014-01-10 23:23:46 +0000743 // Find equivalence classes.
744 findEquivalenceClasses(F);
745
746 // Propagate weights to all edges.
747 propagateWeights(F);
748 }
749
750 return Changed;
751}
752
Diego Novilloc0dd1032013-11-26 20:37:33 +0000753char SampleProfileLoader::ID = 0;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000754INITIALIZE_PASS_BEGIN(SampleProfileLoader, "sample-profile",
755 "Sample Profile loader", false, false)
Diego Novillo92aa8c22014-03-10 22:41:28 +0000756INITIALIZE_PASS_DEPENDENCY(AddDiscriminators)
Diego Novillo0accb3d2014-01-10 23:23:46 +0000757INITIALIZE_PASS_END(SampleProfileLoader, "sample-profile",
758 "Sample Profile loader", false, false)
Diego Novilloc0dd1032013-11-26 20:37:33 +0000759
760bool SampleProfileLoader::doInitialization(Module &M) {
Diego Novillo7732ae42015-08-26 20:00:27 +0000761 auto &Ctx = M.getContext();
Diego Novillo4d711132015-08-25 15:25:11 +0000762 auto ReaderOrErr = SampleProfileReader::create(Filename, Ctx);
Diego Novillofcd55602014-11-03 00:51:45 +0000763 if (std::error_code EC = ReaderOrErr.getError()) {
Diego Novilloc572e922014-10-30 18:00:06 +0000764 std::string Msg = "Could not open profile: " + EC.message();
Diego Novillo4d711132015-08-25 15:25:11 +0000765 Ctx.diagnose(DiagnosticInfoSampleProfile(Filename.data(), Msg));
Diego Novilloc572e922014-10-30 18:00:06 +0000766 return false;
767 }
Diego Novillofcd55602014-11-03 00:51:45 +0000768 Reader = std::move(ReaderOrErr.get());
Diego Novilloc572e922014-10-30 18:00:06 +0000769 ProfileIsValid = (Reader->read() == sampleprof_error::success);
Diego Novilloc0dd1032013-11-26 20:37:33 +0000770 return true;
771}
772
Diego Novillo4d711132015-08-25 15:25:11 +0000773ModulePass *llvm::createSampleProfileLoaderPass() {
Diego Novilloc0dd1032013-11-26 20:37:33 +0000774 return new SampleProfileLoader(SampleProfileFile);
775}
776
Diego Novillo4d711132015-08-25 15:25:11 +0000777ModulePass *llvm::createSampleProfileLoaderPass(StringRef Name) {
Diego Novilloc0dd1032013-11-26 20:37:33 +0000778 return new SampleProfileLoader(Name);
779}
780
Diego Novillo4d711132015-08-25 15:25:11 +0000781bool SampleProfileLoader::runOnModule(Module &M) {
782 bool retval = false;
783 for (auto &F : M)
784 if (!F.isDeclaration())
785 retval |= runOnFunction(F);
786 return retval;
787}
788
Diego Novillo8d6568b2013-11-13 12:22:21 +0000789bool SampleProfileLoader::runOnFunction(Function &F) {
Diego Novilloa32aa322014-03-14 21:58:59 +0000790 if (!ProfileIsValid)
791 return false;
Diego Novillode1ab262014-09-09 12:40:50 +0000792
Diego Novillode1ab262014-09-09 12:40:50 +0000793 Samples = Reader->getSamplesFor(F);
794 if (!Samples->empty())
795 return emitAnnotations(F);
Diego Novillo0accb3d2014-01-10 23:23:46 +0000796 return false;
Diego Novillo8d6568b2013-11-13 12:22:21 +0000797}