blob: f6602fda4305a3f7d066dabc6e3daf4b318817aa [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"
Diego Novillo8d6568b2013-11-13 12:22:21 +000046#include "llvm/Support/raw_ostream.h"
Diego Novillo4d711132015-08-25 15:25:11 +000047#include "llvm/Transforms/IPO.h"
Logan Chien61c6df02014-02-22 06:34:10 +000048#include <cctype>
Diego Novillo8d6568b2013-11-13 12:22:21 +000049
50using namespace llvm;
Diego Novillode1ab262014-09-09 12:40:50 +000051using namespace sampleprof;
Diego Novillo8d6568b2013-11-13 12:22:21 +000052
Chandler Carruth964daaa2014-04-22 02:55:47 +000053#define DEBUG_TYPE "sample-profile"
54
Diego Novillo8d6568b2013-11-13 12:22:21 +000055// Command line option to specify the file to read samples from. This is
56// mainly used for debugging.
57static cl::opt<std::string> SampleProfileFile(
58 "sample-profile-file", cl::init(""), cl::value_desc("filename"),
59 cl::desc("Profile file loaded by -sample-profile"), cl::Hidden);
Diego Novillo0accb3d2014-01-10 23:23:46 +000060static cl::opt<unsigned> SampleProfileMaxPropagateIterations(
61 "sample-profile-max-propagate-iterations", cl::init(100),
62 cl::desc("Maximum number of iterations to go through when propagating "
63 "sample block/edge weights through the CFG."));
Diego Novillo8d6568b2013-11-13 12:22:21 +000064
65namespace {
Diego Novillo92aa8c22014-03-10 22:41:28 +000066typedef DenseMap<BasicBlock *, unsigned> BlockWeightMap;
Diego Novillo0accb3d2014-01-10 23:23:46 +000067typedef DenseMap<BasicBlock *, BasicBlock *> EquivalenceClassMap;
68typedef std::pair<BasicBlock *, BasicBlock *> Edge;
Diego Novillo92aa8c22014-03-10 22:41:28 +000069typedef DenseMap<Edge, unsigned> EdgeWeightMap;
Diego Novillo70959082014-03-14 22:07:18 +000070typedef DenseMap<BasicBlock *, SmallVector<BasicBlock *, 8>> BlockEdgeMap;
Diego Novilloc0dd1032013-11-26 20:37:33 +000071
Diego Novillode1ab262014-09-09 12:40:50 +000072/// \brief Sample profile pass.
Diego Novilloc0dd1032013-11-26 20:37:33 +000073///
Diego Novillode1ab262014-09-09 12:40:50 +000074/// This pass reads profile data from the file specified by
75/// -sample-profile-file and annotates every affected function with the
76/// profile information found in that file.
Diego Novillo4d711132015-08-25 15:25:11 +000077class SampleProfileLoader : public ModulePass {
Diego Novilloc0dd1032013-11-26 20:37:33 +000078public:
Diego Novillode1ab262014-09-09 12:40:50 +000079 // Class identification, replacement for typeinfo
80 static char ID;
Diego Novilloc0dd1032013-11-26 20:37:33 +000081
Diego Novillode1ab262014-09-09 12:40:50 +000082 SampleProfileLoader(StringRef Name = SampleProfileFile)
Diego Novillo4d711132015-08-25 15:25:11 +000083 : ModulePass(ID), DT(nullptr), PDT(nullptr), LI(nullptr),
84 Ctx(nullptr), Reader(), Samples(nullptr), Filename(Name),
85 ProfileIsValid(false) {
Diego Novillode1ab262014-09-09 12:40:50 +000086 initializeSampleProfileLoaderPass(*PassRegistry::getPassRegistry());
87 }
88
89 bool doInitialization(Module &M) override;
90
91 void dump() { Reader->dump(); }
92
93 const char *getPassName() const override { return "Sample profile pass"; }
94
Diego Novillo4d711132015-08-25 15:25:11 +000095 bool runOnModule(Module &M) override;
Diego Novillode1ab262014-09-09 12:40:50 +000096
97 void getAnalysisUsage(AnalysisUsage &AU) const override {
98 AU.setPreservesCFG();
Diego Novillo4d711132015-08-25 15:25:11 +000099
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000100 AU.addRequired<LoopInfoWrapperPass>();
Diego Novillo4d711132015-08-25 15:25:11 +0000101 AU.addPreserved<LoopInfoWrapperPass>();
102
Diego Novillode1ab262014-09-09 12:40:50 +0000103 AU.addRequired<DominatorTreeWrapperPass>();
Diego Novillo4d711132015-08-25 15:25:11 +0000104 AU.addPreserved<DominatorTreeWrapperPass>();
105
Diego Novillode1ab262014-09-09 12:40:50 +0000106 AU.addRequired<PostDominatorTree>();
Diego Novillo4d711132015-08-25 15:25:11 +0000107 AU.addPreserved<PostDominatorTree>();
Diego Novillode1ab262014-09-09 12:40:50 +0000108 }
109
110protected:
Diego Novillo4d711132015-08-25 15:25:11 +0000111 bool runOnFunction(Function &F);
Diego Novillo0accb3d2014-01-10 23:23:46 +0000112 unsigned getFunctionLoc(Function &F);
Diego Novillode1ab262014-09-09 12:40:50 +0000113 bool emitAnnotations(Function &F);
Diego Novillo92aa8c22014-03-10 22:41:28 +0000114 unsigned getInstWeight(Instruction &I);
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000115 unsigned getBlockWeight(BasicBlock *BB);
Diego Novillo0accb3d2014-01-10 23:23:46 +0000116 void printEdgeWeight(raw_ostream &OS, Edge E);
117 void printBlockWeight(raw_ostream &OS, BasicBlock *BB);
118 void printBlockEquivalence(raw_ostream &OS, BasicBlock *BB);
119 bool computeBlockWeights(Function &F);
120 void findEquivalenceClasses(Function &F);
121 void findEquivalencesFor(BasicBlock *BB1,
122 SmallVector<BasicBlock *, 8> Descendants,
123 DominatorTreeBase<BasicBlock> *DomTree);
124 void propagateWeights(Function &F);
Diego Novillo92aa8c22014-03-10 22:41:28 +0000125 unsigned visitEdge(Edge E, unsigned *NumUnknownEdges, Edge *UnknownEdge);
Diego Novillo0accb3d2014-01-10 23:23:46 +0000126 void buildEdges(Function &F);
127 bool propagateThroughEdges(Function &F);
Diego Novilloc0dd1032013-11-26 20:37:33 +0000128
Diego Novillode1ab262014-09-09 12:40:50 +0000129 /// \brief Line number for the function header. Used to compute absolute
130 /// line numbers from the relative line numbers found in the profile.
Diego Novillo0accb3d2014-01-10 23:23:46 +0000131 unsigned HeaderLineno;
132
Diego Novilloc0dd1032013-11-26 20:37:33 +0000133 /// \brief Map basic blocks to their computed weights.
134 ///
135 /// The weight of a basic block is defined to be the maximum
136 /// of all the instruction weights in that block.
137 BlockWeightMap BlockWeights;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000138
139 /// \brief Map edges to their computed weights.
140 ///
141 /// Edge weights are computed by propagating basic block weights in
142 /// SampleProfile::propagateWeights.
143 EdgeWeightMap EdgeWeights;
144
145 /// \brief Set of visited blocks during propagation.
146 SmallPtrSet<BasicBlock *, 128> VisitedBlocks;
147
148 /// \brief Set of visited edges during propagation.
149 SmallSet<Edge, 128> VisitedEdges;
150
151 /// \brief Equivalence classes for block weights.
152 ///
153 /// Two blocks BB1 and BB2 are in the same equivalence class if they
154 /// dominate and post-dominate each other, and they are in the same loop
155 /// nest. When this happens, the two blocks are guaranteed to execute
156 /// the same number of times.
157 EquivalenceClassMap EquivalenceClass;
158
159 /// \brief Dominance, post-dominance and loop information.
160 DominatorTree *DT;
161 PostDominatorTree *PDT;
162 LoopInfo *LI;
163
164 /// \brief Predecessors for each basic block in the CFG.
165 BlockEdgeMap Predecessors;
166
167 /// \brief Successors for each basic block in the CFG.
168 BlockEdgeMap Successors;
Diego Novillo92aa8c22014-03-10 22:41:28 +0000169
170 /// \brief LLVM context holding the debug data we need.
171 LLVMContext *Ctx;
Diego Novilloc0dd1032013-11-26 20:37:33 +0000172
Diego Novillo8d6568b2013-11-13 12:22:21 +0000173 /// \brief Profile reader object.
Diego Novillode1ab262014-09-09 12:40:50 +0000174 std::unique_ptr<SampleProfileReader> Reader;
175
176 /// \brief Samples collected for the body of this function.
177 FunctionSamples *Samples;
Diego Novillo8d6568b2013-11-13 12:22:21 +0000178
179 /// \brief Name of the profile file to load.
180 StringRef Filename;
Diego Novilloa32aa322014-03-14 21:58:59 +0000181
Alp Toker16f98b22014-04-09 14:47:27 +0000182 /// \brief Flag indicating whether the profile input loaded successfully.
Diego Novilloa32aa322014-03-14 21:58:59 +0000183 bool ProfileIsValid;
Diego Novillo8d6568b2013-11-13 12:22:21 +0000184};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000185}
Diego Novillo8d6568b2013-11-13 12:22:21 +0000186
Diego Novillo0accb3d2014-01-10 23:23:46 +0000187/// \brief Print the weight of edge \p E on stream \p OS.
188///
189/// \param OS Stream to emit the output to.
190/// \param E Edge to print.
Diego Novillode1ab262014-09-09 12:40:50 +0000191void SampleProfileLoader::printEdgeWeight(raw_ostream &OS, Edge E) {
Diego Novillo0accb3d2014-01-10 23:23:46 +0000192 OS << "weight[" << E.first->getName() << "->" << E.second->getName()
193 << "]: " << EdgeWeights[E] << "\n";
194}
195
196/// \brief Print the equivalence class of block \p BB on stream \p OS.
197///
198/// \param OS Stream to emit the output to.
199/// \param BB Block to print.
Diego Novillode1ab262014-09-09 12:40:50 +0000200void SampleProfileLoader::printBlockEquivalence(raw_ostream &OS,
201 BasicBlock *BB) {
Diego Novillo0accb3d2014-01-10 23:23:46 +0000202 BasicBlock *Equiv = EquivalenceClass[BB];
203 OS << "equivalence[" << BB->getName()
204 << "]: " << ((Equiv) ? EquivalenceClass[BB]->getName() : "NONE") << "\n";
205}
206
207/// \brief Print the weight of block \p BB on stream \p OS.
208///
209/// \param OS Stream to emit the output to.
210/// \param BB Block to print.
Diego Novillode1ab262014-09-09 12:40:50 +0000211void SampleProfileLoader::printBlockWeight(raw_ostream &OS, BasicBlock *BB) {
Diego Novillo0accb3d2014-01-10 23:23:46 +0000212 OS << "weight[" << BB->getName() << "]: " << BlockWeights[BB] << "\n";
213}
214
Diego Novillo0accb3d2014-01-10 23:23:46 +0000215/// \brief Get the weight for an instruction.
216///
217/// The "weight" of an instruction \p Inst is the number of samples
218/// collected on that instruction at runtime. To retrieve it, we
219/// need to compute the line number of \p Inst relative to the start of its
220/// function. We use HeaderLineno to compute the offset. We then
221/// look up the samples collected for \p Inst using BodySamples.
222///
223/// \param Inst Instruction to query.
224///
225/// \returns The profiled weight of I.
Diego Novillode1ab262014-09-09 12:40:50 +0000226unsigned SampleProfileLoader::getInstWeight(Instruction &Inst) {
Diego Novillo92aa8c22014-03-10 22:41:28 +0000227 DebugLoc DLoc = Inst.getDebugLoc();
Duncan P. N. Exon Smithec819c02015-03-30 19:49:49 +0000228 if (!DLoc)
Duncan P. N. Exon Smith41a15462015-03-20 00:56:55 +0000229 return 0;
230
Diego Novillo92aa8c22014-03-10 22:41:28 +0000231 unsigned Lineno = DLoc.getLine();
Diego Novillo0accb3d2014-01-10 23:23:46 +0000232 if (Lineno < HeaderLineno)
233 return 0;
Diego Novillo92aa8c22014-03-10 22:41:28 +0000234
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000235 const DILocation *DIL = DLoc;
Diego Novillo92aa8c22014-03-10 22:41:28 +0000236 int LOffset = Lineno - HeaderLineno;
Duncan P. N. Exon Smithb7e221b2015-04-14 01:35:55 +0000237 unsigned Discriminator = DIL->getDiscriminator();
Diego Novillode1ab262014-09-09 12:40:50 +0000238 unsigned Weight = Samples->samplesAt(LOffset, Discriminator);
Diego Novillo92aa8c22014-03-10 22:41:28 +0000239 DEBUG(dbgs() << " " << Lineno << "." << Discriminator << ":" << Inst
240 << " (line offset: " << LOffset << "." << Discriminator
Diego Novillo0accb3d2014-01-10 23:23:46 +0000241 << " - weight: " << Weight << ")\n");
242 return Weight;
243}
244
245/// \brief Compute the weight of a basic block.
246///
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000247/// The weight of basic block \p BB is the maximum weight of all the
248/// instructions in BB. The weight of \p BB is computed and cached in
Diego Novillo0accb3d2014-01-10 23:23:46 +0000249/// the BlockWeights map.
250///
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000251/// \param BB The basic block to query.
Diego Novillo0accb3d2014-01-10 23:23:46 +0000252///
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000253/// \returns The computed weight of BB.
254unsigned SampleProfileLoader::getBlockWeight(BasicBlock *BB) {
255 // If we've computed BB's weight before, return it.
Diego Novillo0accb3d2014-01-10 23:23:46 +0000256 std::pair<BlockWeightMap::iterator, bool> Entry =
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000257 BlockWeights.insert(std::make_pair(BB, 0));
Diego Novillo0accb3d2014-01-10 23:23:46 +0000258 if (!Entry.second)
259 return Entry.first->second;
260
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000261 // Otherwise, compute and cache BB's weight.
Diego Novillo92aa8c22014-03-10 22:41:28 +0000262 unsigned Weight = 0;
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000263 for (auto &I : BB->getInstList()) {
Diego Novillob368b7d2014-10-22 16:51:50 +0000264 unsigned InstWeight = getInstWeight(I);
Diego Novillo0accb3d2014-01-10 23:23:46 +0000265 if (InstWeight > Weight)
266 Weight = InstWeight;
267 }
268 Entry.first->second = Weight;
269 return Weight;
270}
271
272/// \brief Compute and store the weights of every basic block.
273///
274/// This populates the BlockWeights map by computing
275/// the weights of every basic block in the CFG.
276///
277/// \param F The function to query.
Diego Novillode1ab262014-09-09 12:40:50 +0000278bool SampleProfileLoader::computeBlockWeights(Function &F) {
Diego Novillo0accb3d2014-01-10 23:23:46 +0000279 bool Changed = false;
280 DEBUG(dbgs() << "Block weights\n");
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000281 for (auto &BB : F) {
282 unsigned Weight = getBlockWeight(&BB);
Diego Novillo0accb3d2014-01-10 23:23:46 +0000283 Changed |= (Weight > 0);
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000284 DEBUG(printBlockWeight(dbgs(), &BB));
Diego Novillo0accb3d2014-01-10 23:23:46 +0000285 }
286
287 return Changed;
288}
289
290/// \brief Find equivalence classes for the given block.
291///
292/// This finds all the blocks that are guaranteed to execute the same
Eric Christopher572e03a2015-06-19 01:53:21 +0000293/// number of times as \p BB1. To do this, it traverses all the
Diego Novillo0accb3d2014-01-10 23:23:46 +0000294/// descendants of \p BB1 in the dominator or post-dominator tree.
295///
296/// A block BB2 will be in the same equivalence class as \p BB1 if
297/// the following holds:
298///
299/// 1- \p BB1 is a descendant of BB2 in the opposite tree. So, if BB2
300/// is a descendant of \p BB1 in the dominator tree, then BB2 should
301/// dominate BB1 in the post-dominator tree.
302///
303/// 2- Both BB2 and \p BB1 must be in the same loop.
304///
305/// For every block BB2 that meets those two requirements, we set BB2's
306/// equivalence class to \p BB1.
307///
308/// \param BB1 Block to check.
309/// \param Descendants Descendants of \p BB1 in either the dom or pdom tree.
310/// \param DomTree Opposite dominator tree. If \p Descendants is filled
311/// with blocks from \p BB1's dominator tree, then
312/// this is the post-dominator tree, and vice versa.
Diego Novillode1ab262014-09-09 12:40:50 +0000313void SampleProfileLoader::findEquivalencesFor(
Diego Novillo0accb3d2014-01-10 23:23:46 +0000314 BasicBlock *BB1, SmallVector<BasicBlock *, 8> Descendants,
315 DominatorTreeBase<BasicBlock> *DomTree) {
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000316 for (auto *BB2 : Descendants) {
Diego Novillo0accb3d2014-01-10 23:23:46 +0000317 bool IsDomParent = DomTree->dominates(BB2, BB1);
318 bool IsInSameLoop = LI->getLoopFor(BB1) == LI->getLoopFor(BB2);
David Blaikie70573dc2014-11-19 07:49:26 +0000319 if (BB1 != BB2 && VisitedBlocks.insert(BB2).second && IsDomParent &&
Diego Novillo0accb3d2014-01-10 23:23:46 +0000320 IsInSameLoop) {
321 EquivalenceClass[BB2] = BB1;
322
323 // If BB2 is heavier than BB1, make BB2 have the same weight
324 // as BB1.
325 //
326 // Note that we don't worry about the opposite situation here
327 // (when BB2 is lighter than BB1). We will deal with this
328 // during the propagation phase. Right now, we just want to
329 // make sure that BB1 has the largest weight of all the
330 // members of its equivalence set.
Diego Novillo92aa8c22014-03-10 22:41:28 +0000331 unsigned &BB1Weight = BlockWeights[BB1];
332 unsigned &BB2Weight = BlockWeights[BB2];
Diego Novillo0accb3d2014-01-10 23:23:46 +0000333 BB1Weight = std::max(BB1Weight, BB2Weight);
334 }
335 }
336}
337
338/// \brief Find equivalence classes.
339///
340/// Since samples may be missing from blocks, we can fill in the gaps by setting
341/// the weights of all the blocks in the same equivalence class to the same
342/// weight. To compute the concept of equivalence, we use dominance and loop
343/// information. Two blocks B1 and B2 are in the same equivalence class if B1
344/// dominates B2, B2 post-dominates B1 and both are in the same loop.
345///
346/// \param F The function to query.
Diego Novillode1ab262014-09-09 12:40:50 +0000347void SampleProfileLoader::findEquivalenceClasses(Function &F) {
Diego Novillo0accb3d2014-01-10 23:23:46 +0000348 SmallVector<BasicBlock *, 8> DominatedBBs;
349 DEBUG(dbgs() << "\nBlock equivalence classes\n");
350 // Find equivalence sets based on dominance and post-dominance information.
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000351 for (auto &BB : F) {
352 BasicBlock *BB1 = &BB;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000353
354 // Compute BB1's equivalence class once.
355 if (EquivalenceClass.count(BB1)) {
356 DEBUG(printBlockEquivalence(dbgs(), BB1));
357 continue;
358 }
359
360 // By default, blocks are in their own equivalence class.
361 EquivalenceClass[BB1] = BB1;
362
363 // Traverse all the blocks dominated by BB1. We are looking for
364 // every basic block BB2 such that:
365 //
366 // 1- BB1 dominates BB2.
367 // 2- BB2 post-dominates BB1.
368 // 3- BB1 and BB2 are in the same loop nest.
369 //
370 // If all those conditions hold, it means that BB2 is executed
371 // as many times as BB1, so they are placed in the same equivalence
372 // class by making BB2's equivalence class be BB1.
373 DominatedBBs.clear();
374 DT->getDescendants(BB1, DominatedBBs);
375 findEquivalencesFor(BB1, DominatedBBs, PDT->DT);
376
377 // Repeat the same logic for all the blocks post-dominated by BB1.
378 // We are looking for every basic block BB2 such that:
379 //
380 // 1- BB1 post-dominates BB2.
381 // 2- BB2 dominates BB1.
382 // 3- BB1 and BB2 are in the same loop nest.
383 //
384 // If all those conditions hold, BB2's equivalence class is BB1.
385 DominatedBBs.clear();
386 PDT->getDescendants(BB1, DominatedBBs);
Chandler Carruth73523022014-01-13 13:07:17 +0000387 findEquivalencesFor(BB1, DominatedBBs, DT);
Diego Novillo0accb3d2014-01-10 23:23:46 +0000388
389 DEBUG(printBlockEquivalence(dbgs(), BB1));
390 }
391
392 // Assign weights to equivalence classes.
393 //
394 // All the basic blocks in the same equivalence class will execute
395 // the same number of times. Since we know that the head block in
396 // each equivalence class has the largest weight, assign that weight
397 // to all the blocks in that equivalence class.
398 DEBUG(dbgs() << "\nAssign the same weight to all blocks in the same class\n");
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000399 for (auto &BI : F) {
400 BasicBlock *BB = &BI;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000401 BasicBlock *EquivBB = EquivalenceClass[BB];
402 if (BB != EquivBB)
403 BlockWeights[BB] = BlockWeights[EquivBB];
404 DEBUG(printBlockWeight(dbgs(), BB));
405 }
406}
407
408/// \brief Visit the given edge to decide if it has a valid weight.
409///
410/// If \p E has not been visited before, we copy to \p UnknownEdge
411/// and increment the count of unknown edges.
412///
413/// \param E Edge to visit.
414/// \param NumUnknownEdges Current number of unknown edges.
415/// \param UnknownEdge Set if E has not been visited before.
416///
417/// \returns E's weight, if known. Otherwise, return 0.
Diego Novillode1ab262014-09-09 12:40:50 +0000418unsigned SampleProfileLoader::visitEdge(Edge E, unsigned *NumUnknownEdges,
419 Edge *UnknownEdge) {
Diego Novillo0accb3d2014-01-10 23:23:46 +0000420 if (!VisitedEdges.count(E)) {
421 (*NumUnknownEdges)++;
422 *UnknownEdge = E;
423 return 0;
424 }
425
426 return EdgeWeights[E];
427}
428
429/// \brief Propagate weights through incoming/outgoing edges.
430///
431/// If the weight of a basic block is known, and there is only one edge
432/// with an unknown weight, we can calculate the weight of that edge.
433///
434/// Similarly, if all the edges have a known count, we can calculate the
435/// count of the basic block, if needed.
436///
437/// \param F Function to process.
438///
439/// \returns True if new weights were assigned to edges or blocks.
Diego Novillode1ab262014-09-09 12:40:50 +0000440bool SampleProfileLoader::propagateThroughEdges(Function &F) {
Diego Novillo0accb3d2014-01-10 23:23:46 +0000441 bool Changed = false;
442 DEBUG(dbgs() << "\nPropagation through edges\n");
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000443 for (auto &BI : F) {
444 BasicBlock *BB = &BI;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000445
446 // Visit all the predecessor and successor edges to determine
447 // which ones have a weight assigned already. Note that it doesn't
448 // matter that we only keep track of a single unknown edge. The
449 // only case we are interested in handling is when only a single
450 // edge is unknown (see setEdgeOrBlockWeight).
451 for (unsigned i = 0; i < 2; i++) {
Diego Novillo92aa8c22014-03-10 22:41:28 +0000452 unsigned TotalWeight = 0;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000453 unsigned NumUnknownEdges = 0;
454 Edge UnknownEdge, SelfReferentialEdge;
455
456 if (i == 0) {
457 // First, visit all predecessor edges.
Diego Novillob368b7d2014-10-22 16:51:50 +0000458 for (auto *Pred : Predecessors[BB]) {
459 Edge E = std::make_pair(Pred, BB);
Diego Novillo0accb3d2014-01-10 23:23:46 +0000460 TotalWeight += visitEdge(E, &NumUnknownEdges, &UnknownEdge);
461 if (E.first == E.second)
462 SelfReferentialEdge = E;
463 }
464 } else {
465 // On the second round, visit all successor edges.
Diego Novillob368b7d2014-10-22 16:51:50 +0000466 for (auto *Succ : Successors[BB]) {
467 Edge E = std::make_pair(BB, Succ);
Diego Novillo0accb3d2014-01-10 23:23:46 +0000468 TotalWeight += visitEdge(E, &NumUnknownEdges, &UnknownEdge);
469 }
470 }
471
472 // After visiting all the edges, there are three cases that we
473 // can handle immediately:
474 //
475 // - All the edge weights are known (i.e., NumUnknownEdges == 0).
476 // In this case, we simply check that the sum of all the edges
477 // is the same as BB's weight. If not, we change BB's weight
478 // to match. Additionally, if BB had not been visited before,
479 // we mark it visited.
480 //
481 // - Only one edge is unknown and BB has already been visited.
482 // In this case, we can compute the weight of the edge by
483 // subtracting the total block weight from all the known
484 // edge weights. If the edges weight more than BB, then the
485 // edge of the last remaining edge is set to zero.
486 //
487 // - There exists a self-referential edge and the weight of BB is
488 // known. In this case, this edge can be based on BB's weight.
489 // We add up all the other known edges and set the weight on
490 // the self-referential edge as we did in the previous case.
491 //
492 // In any other case, we must continue iterating. Eventually,
493 // all edges will get a weight, or iteration will stop when
494 // it reaches SampleProfileMaxPropagateIterations.
495 if (NumUnknownEdges <= 1) {
Diego Novillo92aa8c22014-03-10 22:41:28 +0000496 unsigned &BBWeight = BlockWeights[BB];
Diego Novillo0accb3d2014-01-10 23:23:46 +0000497 if (NumUnknownEdges == 0) {
498 // If we already know the weight of all edges, the weight of the
499 // basic block can be computed. It should be no larger than the sum
500 // of all edge weights.
501 if (TotalWeight > BBWeight) {
502 BBWeight = TotalWeight;
503 Changed = true;
504 DEBUG(dbgs() << "All edge weights for " << BB->getName()
505 << " known. Set weight for block: ";
506 printBlockWeight(dbgs(), BB););
507 }
David Blaikie70573dc2014-11-19 07:49:26 +0000508 if (VisitedBlocks.insert(BB).second)
Diego Novillo0accb3d2014-01-10 23:23:46 +0000509 Changed = true;
510 } else if (NumUnknownEdges == 1 && VisitedBlocks.count(BB)) {
511 // If there is a single unknown edge and the block has been
512 // visited, then we can compute E's weight.
513 if (BBWeight >= TotalWeight)
514 EdgeWeights[UnknownEdge] = BBWeight - TotalWeight;
515 else
516 EdgeWeights[UnknownEdge] = 0;
517 VisitedEdges.insert(UnknownEdge);
518 Changed = true;
519 DEBUG(dbgs() << "Set weight for edge: ";
520 printEdgeWeight(dbgs(), UnknownEdge));
521 }
522 } else if (SelfReferentialEdge.first && VisitedBlocks.count(BB)) {
Diego Novillo92aa8c22014-03-10 22:41:28 +0000523 unsigned &BBWeight = BlockWeights[BB];
Diego Novillo0accb3d2014-01-10 23:23:46 +0000524 // We have a self-referential edge and the weight of BB is known.
525 if (BBWeight >= TotalWeight)
526 EdgeWeights[SelfReferentialEdge] = BBWeight - TotalWeight;
527 else
528 EdgeWeights[SelfReferentialEdge] = 0;
529 VisitedEdges.insert(SelfReferentialEdge);
530 Changed = true;
531 DEBUG(dbgs() << "Set self-referential edge weight to: ";
532 printEdgeWeight(dbgs(), SelfReferentialEdge));
533 }
534 }
535 }
536
537 return Changed;
538}
539
540/// \brief Build in/out edge lists for each basic block in the CFG.
541///
542/// We are interested in unique edges. If a block B1 has multiple
543/// edges to another block B2, we only add a single B1->B2 edge.
Diego Novillode1ab262014-09-09 12:40:50 +0000544void SampleProfileLoader::buildEdges(Function &F) {
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000545 for (auto &BI : F) {
546 BasicBlock *B1 = &BI;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000547
548 // Add predecessors for B1.
549 SmallPtrSet<BasicBlock *, 16> Visited;
550 if (!Predecessors[B1].empty())
551 llvm_unreachable("Found a stale predecessors list in a basic block.");
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000552 for (pred_iterator PI = pred_begin(B1), PE = pred_end(B1); PI != PE; ++PI) {
553 BasicBlock *B2 = *PI;
David Blaikie70573dc2014-11-19 07:49:26 +0000554 if (Visited.insert(B2).second)
Diego Novillo0accb3d2014-01-10 23:23:46 +0000555 Predecessors[B1].push_back(B2);
556 }
557
558 // Add successors for B1.
559 Visited.clear();
560 if (!Successors[B1].empty())
561 llvm_unreachable("Found a stale successors list in a basic block.");
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000562 for (succ_iterator SI = succ_begin(B1), SE = succ_end(B1); SI != SE; ++SI) {
563 BasicBlock *B2 = *SI;
David Blaikie70573dc2014-11-19 07:49:26 +0000564 if (Visited.insert(B2).second)
Diego Novillo0accb3d2014-01-10 23:23:46 +0000565 Successors[B1].push_back(B2);
566 }
567 }
568}
569
570/// \brief Propagate weights into edges
571///
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000572/// The following rules are applied to every block BB in the CFG:
Diego Novillo0accb3d2014-01-10 23:23:46 +0000573///
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000574/// - If BB has a single predecessor/successor, then the weight
Diego Novillo0accb3d2014-01-10 23:23:46 +0000575/// of that edge is the weight of the block.
576///
577/// - If all incoming or outgoing edges are known except one, and the
578/// weight of the block is already known, the weight of the unknown
579/// edge will be the weight of the block minus the sum of all the known
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000580/// edges. If the sum of all the known edges is larger than BB's weight,
Diego Novillo0accb3d2014-01-10 23:23:46 +0000581/// we set the unknown edge weight to zero.
582///
583/// - If there is a self-referential edge, and the weight of the block is
584/// known, the weight for that edge is set to the weight of the block
585/// minus the weight of the other incoming edges to that block (if
586/// known).
Diego Novillode1ab262014-09-09 12:40:50 +0000587void SampleProfileLoader::propagateWeights(Function &F) {
Diego Novillo0accb3d2014-01-10 23:23:46 +0000588 bool Changed = true;
589 unsigned i = 0;
590
Diego Novilloffc84e32015-05-13 17:04:29 +0000591 // Add an entry count to the function using the samples gathered
592 // at the function entry.
593 F.setEntryCount(Samples->getHeadSamples());
594
Diego Novillo0accb3d2014-01-10 23:23:46 +0000595 // Before propagation starts, build, for each block, a list of
596 // unique predecessors and successors. This is necessary to handle
597 // identical edges in multiway branches. Since we visit all blocks and all
598 // edges of the CFG, it is cleaner to build these lists once at the start
599 // of the pass.
600 buildEdges(F);
601
602 // Propagate until we converge or we go past the iteration limit.
603 while (Changed && i++ < SampleProfileMaxPropagateIterations) {
604 Changed = propagateThroughEdges(F);
605 }
606
607 // Generate MD_prof metadata for every branch instruction using the
608 // edge weights computed during propagation.
609 DEBUG(dbgs() << "\nPropagation complete. Setting branch weights\n");
610 MDBuilder MDB(F.getContext());
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000611 for (auto &BI : F) {
612 BasicBlock *BB = &BI;
613 TerminatorInst *TI = BB->getTerminator();
Diego Novillo0accb3d2014-01-10 23:23:46 +0000614 if (TI->getNumSuccessors() == 1)
615 continue;
616 if (!isa<BranchInst>(TI) && !isa<SwitchInst>(TI))
617 continue;
618
619 DEBUG(dbgs() << "\nGetting weights for branch at line "
Diego Novillo92aa8c22014-03-10 22:41:28 +0000620 << TI->getDebugLoc().getLine() << ".\n");
621 SmallVector<unsigned, 4> Weights;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000622 bool AllWeightsZero = true;
623 for (unsigned I = 0; I < TI->getNumSuccessors(); ++I) {
624 BasicBlock *Succ = TI->getSuccessor(I);
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000625 Edge E = std::make_pair(BB, Succ);
Diego Novillo92aa8c22014-03-10 22:41:28 +0000626 unsigned Weight = EdgeWeights[E];
Diego Novillo0accb3d2014-01-10 23:23:46 +0000627 DEBUG(dbgs() << "\t"; printEdgeWeight(dbgs(), E));
628 Weights.push_back(Weight);
629 if (Weight != 0)
630 AllWeightsZero = false;
631 }
632
633 // Only set weights if there is at least one non-zero weight.
634 // In any other case, let the analyzer set weights.
635 if (!AllWeightsZero) {
636 DEBUG(dbgs() << "SUCCESS. Found non-zero weights.\n");
637 TI->setMetadata(llvm::LLVMContext::MD_prof,
638 MDB.createBranchWeights(Weights));
639 } else {
640 DEBUG(dbgs() << "SKIPPED. All branch weights are zero.\n");
641 }
642 }
643}
644
645/// \brief Get the line number for the function header.
646///
647/// This looks up function \p F in the current compilation unit and
648/// retrieves the line number where the function is defined. This is
649/// line 0 for all the samples read from the profile file. Every line
650/// number is relative to this line.
651///
652/// \param F Function object to query.
653///
Diego Novilloa32aa322014-03-14 21:58:59 +0000654/// \returns the line number where \p F is defined. If it returns 0,
655/// it means that there is no debug information available for \p F.
Diego Novillode1ab262014-09-09 12:40:50 +0000656unsigned SampleProfileLoader::getFunctionLoc(Function &F) {
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000657 if (DISubprogram *S = getDISubprogram(&F))
Duncan P. N. Exon Smith537b4a82015-04-14 03:40:37 +0000658 return S->getLine();
Diego Novillo0accb3d2014-01-10 23:23:46 +0000659
Diego Novillo8027b802014-10-22 12:59:00 +0000660 // If could not find the start of \p F, emit a diagnostic to inform the user
661 // about the missed opportunity.
David Blaikie61079682014-03-16 01:36:18 +0000662 F.getContext().diagnose(DiagnosticInfoSampleProfile(
Diego Novilloa67c0b42014-10-22 13:36:35 +0000663 "No debug information found in function " + F.getName() +
664 ": Function profile not used",
665 DS_Warning));
Diego Novilloa32aa322014-03-14 21:58:59 +0000666 return 0;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000667}
668
669/// \brief Generate branch weight metadata for all branches in \p F.
670///
671/// Branch weights are computed out of instruction samples using a
672/// propagation heuristic. Propagation proceeds in 3 phases:
673///
674/// 1- Assignment of block weights. All the basic blocks in the function
675/// are initial assigned the same weight as their most frequently
676/// executed instruction.
677///
678/// 2- Creation of equivalence classes. Since samples may be missing from
679/// blocks, we can fill in the gaps by setting the weights of all the
680/// blocks in the same equivalence class to the same weight. To compute
681/// the concept of equivalence, we use dominance and loop information.
682/// Two blocks B1 and B2 are in the same equivalence class if B1
683/// dominates B2, B2 post-dominates B1 and both are in the same loop.
684///
685/// 3- Propagation of block weights into edges. This uses a simple
686/// propagation heuristic. The following rules are applied to every
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000687/// block BB in the CFG:
Diego Novillo0accb3d2014-01-10 23:23:46 +0000688///
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000689/// - If BB has a single predecessor/successor, then the weight
Diego Novillo0accb3d2014-01-10 23:23:46 +0000690/// of that edge is the weight of the block.
691///
692/// - If all the edges are known except one, and the weight of the
693/// block is already known, the weight of the unknown edge will
694/// be the weight of the block minus the sum of all the known
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000695/// edges. If the sum of all the known edges is larger than BB's weight,
Diego Novillo0accb3d2014-01-10 23:23:46 +0000696/// we set the unknown edge weight to zero.
697///
698/// - If there is a self-referential edge, and the weight of the block is
699/// known, the weight for that edge is set to the weight of the block
700/// minus the weight of the other incoming edges to that block (if
701/// known).
702///
703/// Since this propagation is not guaranteed to finalize for every CFG, we
704/// only allow it to proceed for a limited number of iterations (controlled
705/// by -sample-profile-max-propagate-iterations).
706///
707/// FIXME: Try to replace this propagation heuristic with a scheme
708/// that is guaranteed to finalize. A work-list approach similar to
709/// the standard value propagation algorithm used by SSA-CCP might
710/// work here.
711///
712/// Once all the branch weights are computed, we emit the MD_prof
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000713/// metadata on BB using the computed values for each of its branches.
Diego Novillo0accb3d2014-01-10 23:23:46 +0000714///
715/// \param F The function to query.
Diego Novilloa32aa322014-03-14 21:58:59 +0000716///
717/// \returns true if \p F was modified. Returns false, otherwise.
Diego Novillode1ab262014-09-09 12:40:50 +0000718bool SampleProfileLoader::emitAnnotations(Function &F) {
Diego Novillo0accb3d2014-01-10 23:23:46 +0000719 bool Changed = false;
720
721 // Initialize invariants used during computation and propagation.
722 HeaderLineno = getFunctionLoc(F);
Diego Novilloa32aa322014-03-14 21:58:59 +0000723 if (HeaderLineno == 0)
724 return false;
725
Diego Novillo0accb3d2014-01-10 23:23:46 +0000726 DEBUG(dbgs() << "Line number for the first instruction in " << F.getName()
727 << ": " << HeaderLineno << "\n");
Diego Novillo0accb3d2014-01-10 23:23:46 +0000728
729 // Compute basic block weights.
730 Changed |= computeBlockWeights(F);
731
732 if (Changed) {
733 // Find equivalence classes.
734 findEquivalenceClasses(F);
735
736 // Propagate weights to all edges.
737 propagateWeights(F);
738 }
739
740 return Changed;
741}
742
Diego Novilloc0dd1032013-11-26 20:37:33 +0000743char SampleProfileLoader::ID = 0;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000744INITIALIZE_PASS_BEGIN(SampleProfileLoader, "sample-profile",
745 "Sample Profile loader", false, false)
Chandler Carruth73523022014-01-13 13:07:17 +0000746INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Diego Novillo0accb3d2014-01-10 23:23:46 +0000747INITIALIZE_PASS_DEPENDENCY(PostDominatorTree)
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000748INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
Diego Novillo92aa8c22014-03-10 22:41:28 +0000749INITIALIZE_PASS_DEPENDENCY(AddDiscriminators)
Diego Novillo0accb3d2014-01-10 23:23:46 +0000750INITIALIZE_PASS_END(SampleProfileLoader, "sample-profile",
751 "Sample Profile loader", false, false)
Diego Novilloc0dd1032013-11-26 20:37:33 +0000752
753bool SampleProfileLoader::doInitialization(Module &M) {
Diego Novillo4d711132015-08-25 15:25:11 +0000754 auto& Ctx = M.getContext();
755 auto ReaderOrErr = SampleProfileReader::create(Filename, Ctx);
Diego Novillofcd55602014-11-03 00:51:45 +0000756 if (std::error_code EC = ReaderOrErr.getError()) {
Diego Novilloc572e922014-10-30 18:00:06 +0000757 std::string Msg = "Could not open profile: " + EC.message();
Diego Novillo4d711132015-08-25 15:25:11 +0000758 Ctx.diagnose(DiagnosticInfoSampleProfile(Filename.data(), Msg));
Diego Novilloc572e922014-10-30 18:00:06 +0000759 return false;
760 }
Diego Novillofcd55602014-11-03 00:51:45 +0000761 Reader = std::move(ReaderOrErr.get());
Diego Novilloc572e922014-10-30 18:00:06 +0000762 ProfileIsValid = (Reader->read() == sampleprof_error::success);
Diego Novilloc0dd1032013-11-26 20:37:33 +0000763 return true;
764}
765
Diego Novillo4d711132015-08-25 15:25:11 +0000766ModulePass *llvm::createSampleProfileLoaderPass() {
Diego Novilloc0dd1032013-11-26 20:37:33 +0000767 return new SampleProfileLoader(SampleProfileFile);
768}
769
Diego Novillo4d711132015-08-25 15:25:11 +0000770ModulePass *llvm::createSampleProfileLoaderPass(StringRef Name) {
Diego Novilloc0dd1032013-11-26 20:37:33 +0000771 return new SampleProfileLoader(Name);
772}
773
Diego Novillo4d711132015-08-25 15:25:11 +0000774bool SampleProfileLoader::runOnModule(Module &M) {
775 bool retval = false;
776 for (auto &F : M)
777 if (!F.isDeclaration())
778 retval |= runOnFunction(F);
779 return retval;
780}
781
Diego Novillo8d6568b2013-11-13 12:22:21 +0000782bool SampleProfileLoader::runOnFunction(Function &F) {
Diego Novilloa32aa322014-03-14 21:58:59 +0000783 if (!ProfileIsValid)
784 return false;
Diego Novillode1ab262014-09-09 12:40:50 +0000785
Diego Novillo4d711132015-08-25 15:25:11 +0000786 DT = &getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
787 PDT = &getAnalysis<PostDominatorTree>(F);
788 LI = &getAnalysis<LoopInfoWrapperPass>(F).getLoopInfo();
Diego Novillode1ab262014-09-09 12:40:50 +0000789 Ctx = &F.getParent()->getContext();
790 Samples = Reader->getSamplesFor(F);
791 if (!Samples->empty())
792 return emitAnnotations(F);
Diego Novillo0accb3d2014-01-10 23:23:46 +0000793 return false;
Diego Novillo8d6568b2013-11-13 12:22:21 +0000794}