http://reviews.llvm.org/D13145
[oota-llvm.git] / lib / Transforms / IPO / SampleProfile.cpp
1 //===- SampleProfile.cpp - Incorporate sample profiles into the IR --------===//
2 //
3 //                      The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the SampleProfileLoader transformation. This pass
11 // reads a profile file generated by a sampling profiler (e.g. Linux Perf -
12 // http://perf.wiki.kernel.org/) and generates IR metadata to reflect the
13 // profile information in the given profile.
14 //
15 // This pass generates branch weight annotations on the IR:
16 //
17 // - prof: Represents branch weights. This annotation is added to branches
18 //      to indicate the weights of each edge coming out of the branch.
19 //      The weight of each edge is the weight of the target block for
20 //      that edge. The weight of a block B is computed as the maximum
21 //      number of samples found in B.
22 //
23 //===----------------------------------------------------------------------===//
24
25 #include "llvm/ADT/DenseMap.h"
26 #include "llvm/ADT/SmallPtrSet.h"
27 #include "llvm/ADT/SmallSet.h"
28 #include "llvm/ADT/StringRef.h"
29 #include "llvm/Analysis/LoopInfo.h"
30 #include "llvm/Analysis/PostDominators.h"
31 #include "llvm/IR/Constants.h"
32 #include "llvm/IR/DebugInfo.h"
33 #include "llvm/IR/DiagnosticInfo.h"
34 #include "llvm/IR/Dominators.h"
35 #include "llvm/IR/Function.h"
36 #include "llvm/IR/InstIterator.h"
37 #include "llvm/IR/Instructions.h"
38 #include "llvm/IR/LLVMContext.h"
39 #include "llvm/IR/MDBuilder.h"
40 #include "llvm/IR/Metadata.h"
41 #include "llvm/IR/Module.h"
42 #include "llvm/Pass.h"
43 #include "llvm/ProfileData/SampleProfReader.h"
44 #include "llvm/Support/CommandLine.h"
45 #include "llvm/Support/Debug.h"
46 #include "llvm/Support/ErrorOr.h"
47 #include "llvm/Support/raw_ostream.h"
48 #include "llvm/Transforms/IPO.h"
49 #include "llvm/Transforms/Utils/Cloning.h"
50 #include <cctype>
51
52 using namespace llvm;
53 using namespace sampleprof;
54
55 #define DEBUG_TYPE "sample-profile"
56
57 // Command line option to specify the file to read samples from. This is
58 // mainly used for debugging.
59 static 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);
62 static 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."));
66
67 namespace {
68 typedef DenseMap<const BasicBlock *, unsigned> BlockWeightMap;
69 typedef DenseMap<const BasicBlock *, const BasicBlock *> EquivalenceClassMap;
70 typedef std::pair<const BasicBlock *, const BasicBlock *> Edge;
71 typedef DenseMap<Edge, unsigned> EdgeWeightMap;
72 typedef DenseMap<const BasicBlock *, SmallVector<const BasicBlock *, 8>>
73     BlockEdgeMap;
74
75 /// \brief Sample profile pass.
76 ///
77 /// 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.
80 class SampleProfileLoader : public ModulePass {
81 public:
82   // Class identification, replacement for typeinfo
83   static char ID;
84
85   SampleProfileLoader(StringRef Name = SampleProfileFile)
86       : ModulePass(ID), DT(nullptr), PDT(nullptr), LI(nullptr), Reader(),
87         Samples(nullptr), Filename(Name), ProfileIsValid(false) {
88     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
97   bool runOnModule(Module &M) override;
98
99   void getAnalysisUsage(AnalysisUsage &AU) const override {
100     AU.setPreservesCFG();
101   }
102
103 protected:
104   bool runOnFunction(Function &F);
105   unsigned getFunctionLoc(Function &F);
106   bool emitAnnotations(Function &F);
107   ErrorOr<unsigned> getInstWeight(const Instruction &I) const;
108   ErrorOr<unsigned> getBlockWeight(const BasicBlock *BB) const;
109   const FunctionSamples *findCalleeFunctionSamples(const CallInst &I) const;
110   const FunctionSamples *findFunctionSamples(const Instruction &I) const;
111   bool inlineHotFunctions(Function &F);
112   void printEdgeWeight(raw_ostream &OS, Edge E);
113   void printBlockWeight(raw_ostream &OS, const BasicBlock *BB) const;
114   void printBlockEquivalence(raw_ostream &OS, const BasicBlock *BB);
115   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);
121   unsigned visitEdge(Edge E, unsigned *NumUnknownEdges, Edge *UnknownEdge);
122   void buildEdges(Function &F);
123   bool propagateThroughEdges(Function &F);
124   void computeDominanceAndLoopInfo(Function &F);
125
126   /// \brief Line number for the function header. Used to compute absolute
127   /// line numbers from the relative line numbers found in the profile.
128   unsigned HeaderLineno;
129
130   /// \brief Map basic blocks to their computed weights.
131   ///
132   /// The weight of a basic block is defined to be the maximum
133   /// of all the instruction weights in that block.
134   BlockWeightMap BlockWeights;
135
136   /// \brief Map edges to their computed weights.
137   ///
138   /// Edge weights are computed by propagating basic block weights in
139   /// SampleProfile::propagateWeights.
140   EdgeWeightMap EdgeWeights;
141
142   /// \brief Set of visited blocks during propagation.
143   SmallPtrSet<const BasicBlock *, 128> VisitedBlocks;
144
145   /// \brief Set of visited edges during propagation.
146   SmallSet<Edge, 128> VisitedEdges;
147
148   /// \brief Equivalence classes for block weights.
149   ///
150   /// Two blocks BB1 and BB2 are in the same equivalence class if they
151   /// dominate and post-dominate each other, and they are in the same loop
152   /// nest. When this happens, the two blocks are guaranteed to execute
153   /// the same number of times.
154   EquivalenceClassMap EquivalenceClass;
155
156   /// \brief Dominance, post-dominance and loop information.
157   std::unique_ptr<DominatorTree> DT;
158   std::unique_ptr<DominatorTreeBase<BasicBlock>> PDT;
159   std::unique_ptr<LoopInfo> LI;
160
161   /// \brief Predecessors for each basic block in the CFG.
162   BlockEdgeMap Predecessors;
163
164   /// \brief Successors for each basic block in the CFG.
165   BlockEdgeMap Successors;
166
167   /// \brief Profile reader object.
168   std::unique_ptr<SampleProfileReader> Reader;
169
170   /// \brief Samples collected for the body of this function.
171   FunctionSamples *Samples;
172
173   /// \brief Name of the profile file to load.
174   StringRef Filename;
175
176   /// \brief Flag indicating whether the profile input loaded successfully.
177   bool ProfileIsValid;
178 };
179 }
180
181 /// \brief Print the weight of edge \p E on stream \p OS.
182 ///
183 /// \param OS  Stream to emit the output to.
184 /// \param E  Edge to print.
185 void SampleProfileLoader::printEdgeWeight(raw_ostream &OS, Edge E) {
186   OS << "weight[" << E.first->getName() << "->" << E.second->getName()
187      << "]: " << EdgeWeights[E] << "\n";
188 }
189
190 /// \brief Print the equivalence class of block \p BB on stream \p OS.
191 ///
192 /// \param OS  Stream to emit the output to.
193 /// \param BB  Block to print.
194 void SampleProfileLoader::printBlockEquivalence(raw_ostream &OS,
195                                                 const BasicBlock *BB) {
196   const BasicBlock *Equiv = EquivalenceClass[BB];
197   OS << "equivalence[" << BB->getName()
198      << "]: " << ((Equiv) ? EquivalenceClass[BB]->getName() : "NONE") << "\n";
199 }
200
201 /// \brief Print the weight of block \p BB on stream \p OS.
202 ///
203 /// \param OS  Stream to emit the output to.
204 /// \param BB  Block to print.
205 void SampleProfileLoader::printBlockWeight(raw_ostream &OS,
206                                            const BasicBlock *BB) const {
207   const auto &I = BlockWeights.find(BB);
208   unsigned W = (I == BlockWeights.end() ? 0 : I->second);
209   OS << "weight[" << BB->getName() << "]: " << W << "\n";
210 }
211
212 /// \brief Get the weight for an instruction.
213 ///
214 /// The "weight" of an instruction \p Inst is the number of samples
215 /// collected on that instruction at runtime. To retrieve it, we
216 /// need to compute the line number of \p Inst relative to the start of its
217 /// function. We use HeaderLineno to compute the offset. We then
218 /// look up the samples collected for \p Inst using BodySamples.
219 ///
220 /// \param Inst Instruction to query.
221 ///
222 /// \returns the weight of \p Inst.
223 ErrorOr<unsigned>
224 SampleProfileLoader::getInstWeight(const Instruction &Inst) const {
225   DebugLoc DLoc = Inst.getDebugLoc();
226   if (!DLoc)
227     return std::error_code();
228
229   unsigned Lineno = DLoc.getLine();
230   if (Lineno < HeaderLineno)
231     return std::error_code();
232
233   const DILocation *DIL = DLoc;
234   const FunctionSamples *FS = findFunctionSamples(Inst);
235   if (!FS)
236     return std::error_code();
237   ErrorOr<unsigned> R =
238       FS->findSamplesAt(Lineno - HeaderLineno, DIL->getDiscriminator());
239   if (R)
240     DEBUG(dbgs() << "    " << Lineno << "." << DIL->getDiscriminator() << ":"
241                  << Inst << " (line offset: " << Lineno - HeaderLineno << "."
242                  << DIL->getDiscriminator() << " - weight: " << R.get()
243                  << ")\n");
244   return R;
245 }
246
247 /// \brief Compute the weight of a basic block.
248 ///
249 /// The weight of basic block \p BB is the maximum weight of all the
250 /// instructions in BB.
251 ///
252 /// \param BB The basic block to query.
253 ///
254 /// \returns the weight for \p BB.
255 ErrorOr<unsigned>
256 SampleProfileLoader::getBlockWeight(const BasicBlock *BB) const {
257   bool Found = false;
258   unsigned Weight = 0;
259   for (auto &I : BB->getInstList()) {
260     const ErrorOr<unsigned> &R = getInstWeight(I);
261     if (R && R.get() >= Weight) {
262       Weight = R.get();
263       Found = true;
264     }
265   }
266   if (Found)
267     return Weight;
268   else
269     return std::error_code();
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.
278 bool SampleProfileLoader::computeBlockWeights(Function &F) {
279   bool Changed = false;
280   DEBUG(dbgs() << "Block weights\n");
281   for (const auto &BB : F) {
282     ErrorOr<unsigned> Weight = getBlockWeight(&BB);
283     if (Weight) {
284       BlockWeights[&BB] = Weight.get();
285       Changed = true;
286     }
287     DEBUG(printBlockWeight(dbgs(), &BB));
288   }
289
290   return Changed;
291 }
292
293 /// \brief Get the FunctionSamples for a call instruction.
294 ///
295 /// The FunctionSamples of a call instruction \p Inst is the inlined
296 /// instance in which that call instruction is calling to. It contains
297 /// all samples that resides in the inlined instance. We first find the
298 /// inlined instance in which the call instruction is from, then we
299 /// traverse its children to find the callsite with the matching
300 /// location and callee function name.
301 ///
302 /// \param Inst Call instruction to query.
303 ///
304 /// \returns The FunctionSamples pointer to the inlined instance.
305 const FunctionSamples *
306 SampleProfileLoader::findCalleeFunctionSamples(const CallInst &Inst) const {
307   const DILocation *DIL = Inst.getDebugLoc();
308   if (!DIL) {
309     return nullptr;
310   }
311   DISubprogram *SP = DIL->getScope()->getSubprogram();
312   if (!SP || DIL->getLine() < SP->getLine())
313     return nullptr;
314
315   Function *CalleeFunc = Inst.getCalledFunction();
316   if (!CalleeFunc) {
317     return nullptr;
318   }
319
320   StringRef CalleeName = CalleeFunc->getName();
321   const FunctionSamples *FS = findFunctionSamples(Inst);
322   if (FS == nullptr)
323     return nullptr;
324
325   return FS->findFunctionSamplesAt(CallsiteLocation(
326       DIL->getLine() - SP->getLine(), DIL->getDiscriminator(), CalleeName));
327 }
328
329 /// \brief Get the FunctionSamples for an instruction.
330 ///
331 /// The FunctionSamples of an instruction \p Inst is the inlined instance
332 /// in which that instruction is coming from. We traverse the inline stack
333 /// of that instruction, and match it with the tree nodes in the profile.
334 ///
335 /// \param Inst Instruction to query.
336 ///
337 /// \returns the FunctionSamples pointer to the inlined instance.
338 const FunctionSamples *
339 SampleProfileLoader::findFunctionSamples(const Instruction &Inst) const {
340   SmallVector<CallsiteLocation, 10> S;
341   const DILocation *DIL = Inst.getDebugLoc();
342   if (!DIL) {
343     return Samples;
344   }
345   StringRef CalleeName;
346   for (const DILocation *DIL = Inst.getDebugLoc(); DIL;
347        DIL = DIL->getInlinedAt()) {
348     DISubprogram *SP = DIL->getScope()->getSubprogram();
349     if (!SP || DIL->getLine() < SP->getLine())
350       return nullptr;
351     if (!CalleeName.empty()) {
352       S.push_back(CallsiteLocation(DIL->getLine() - SP->getLine(),
353                                    DIL->getDiscriminator(), CalleeName));
354     }
355     CalleeName = SP->getLinkageName();
356   }
357   if (S.size() == 0)
358     return Samples;
359   const FunctionSamples *FS = Samples;
360   for (int i = S.size() - 1; i >= 0 && FS != nullptr; i--) {
361     FS = FS->findFunctionSamplesAt(S[i]);
362   }
363   return FS;
364 }
365
366 /// \brief Iteratively inline hot callsites of a function.
367 ///
368 /// Iteratively traverse all callsites of the function \p F, and find if
369 /// the corresponding inlined instance exists and is hot in profile. If
370 /// it is hot enough, inline the callsites and adds new callsites of the
371 /// callee into the caller.
372 ///
373 /// TODO: investigate the possibility of not invoking InlineFunction directly.
374 ///
375 /// \param F function to perform iterative inlining.
376 ///
377 /// \returns True if there is any inline happened.
378 bool SampleProfileLoader::inlineHotFunctions(Function &F) {
379   bool Changed = false;
380   while (true) {
381     bool LocalChanged = false;
382     SmallVector<CallInst *, 10> CIS;
383     for (auto &BB : F) {
384       for (auto &I : BB.getInstList()) {
385         CallInst *CI = dyn_cast<CallInst>(&I);
386         if (CI) {
387           const FunctionSamples *FS = findCalleeFunctionSamples(*CI);
388           if (FS && FS->getTotalSamples() > 0) {
389             CIS.push_back(CI);
390           }
391         }
392       }
393     }
394     for (auto CI : CIS) {
395       InlineFunctionInfo IFI;
396       if (InlineFunction(CI, IFI))
397         LocalChanged = true;
398     }
399     if (LocalChanged) {
400       Changed = true;
401     } else {
402       break;
403     }
404   }
405   return Changed;
406 }
407
408 /// \brief Find equivalence classes for the given block.
409 ///
410 /// This finds all the blocks that are guaranteed to execute the same
411 /// number of times as \p BB1. To do this, it traverses all the
412 /// descendants of \p BB1 in the dominator or post-dominator tree.
413 ///
414 /// A block BB2 will be in the same equivalence class as \p BB1 if
415 /// the following holds:
416 ///
417 /// 1- \p BB1 is a descendant of BB2 in the opposite tree. So, if BB2
418 ///    is a descendant of \p BB1 in the dominator tree, then BB2 should
419 ///    dominate BB1 in the post-dominator tree.
420 ///
421 /// 2- Both BB2 and \p BB1 must be in the same loop.
422 ///
423 /// For every block BB2 that meets those two requirements, we set BB2's
424 /// equivalence class to \p BB1.
425 ///
426 /// \param BB1  Block to check.
427 /// \param Descendants  Descendants of \p BB1 in either the dom or pdom tree.
428 /// \param DomTree  Opposite dominator tree. If \p Descendants is filled
429 ///                 with blocks from \p BB1's dominator tree, then
430 ///                 this is the post-dominator tree, and vice versa.
431 void SampleProfileLoader::findEquivalencesFor(
432     BasicBlock *BB1, SmallVector<BasicBlock *, 8> Descendants,
433     DominatorTreeBase<BasicBlock> *DomTree) {
434   for (const auto *BB2 : Descendants) {
435     bool IsDomParent = DomTree->dominates(BB2, BB1);
436     bool IsInSameLoop = LI->getLoopFor(BB1) == LI->getLoopFor(BB2);
437     if (BB1 != BB2 && VisitedBlocks.insert(BB2).second && IsDomParent &&
438         IsInSameLoop) {
439       EquivalenceClass[BB2] = BB1;
440
441       // If BB2 is heavier than BB1, make BB2 have the same weight
442       // as BB1.
443       //
444       // Note that we don't worry about the opposite situation here
445       // (when BB2 is lighter than BB1). We will deal with this
446       // during the propagation phase. Right now, we just want to
447       // make sure that BB1 has the largest weight of all the
448       // members of its equivalence set.
449       unsigned &BB1Weight = BlockWeights[BB1];
450       unsigned &BB2Weight = BlockWeights[BB2];
451       BB1Weight = std::max(BB1Weight, BB2Weight);
452     }
453   }
454 }
455
456 /// \brief Find equivalence classes.
457 ///
458 /// Since samples may be missing from blocks, we can fill in the gaps by setting
459 /// the weights of all the blocks in the same equivalence class to the same
460 /// weight. To compute the concept of equivalence, we use dominance and loop
461 /// information. Two blocks B1 and B2 are in the same equivalence class if B1
462 /// dominates B2, B2 post-dominates B1 and both are in the same loop.
463 ///
464 /// \param F The function to query.
465 void SampleProfileLoader::findEquivalenceClasses(Function &F) {
466   SmallVector<BasicBlock *, 8> DominatedBBs;
467   DEBUG(dbgs() << "\nBlock equivalence classes\n");
468   // Find equivalence sets based on dominance and post-dominance information.
469   for (auto &BB : F) {
470     BasicBlock *BB1 = &BB;
471
472     // Compute BB1's equivalence class once.
473     if (EquivalenceClass.count(BB1)) {
474       DEBUG(printBlockEquivalence(dbgs(), BB1));
475       continue;
476     }
477
478     // By default, blocks are in their own equivalence class.
479     EquivalenceClass[BB1] = BB1;
480
481     // Traverse all the blocks dominated by BB1. We are looking for
482     // every basic block BB2 such that:
483     //
484     // 1- BB1 dominates BB2.
485     // 2- BB2 post-dominates BB1.
486     // 3- BB1 and BB2 are in the same loop nest.
487     //
488     // If all those conditions hold, it means that BB2 is executed
489     // as many times as BB1, so they are placed in the same equivalence
490     // class by making BB2's equivalence class be BB1.
491     DominatedBBs.clear();
492     DT->getDescendants(BB1, DominatedBBs);
493     findEquivalencesFor(BB1, DominatedBBs, PDT.get());
494
495     // Repeat the same logic for all the blocks post-dominated by BB1.
496     // We are looking for every basic block BB2 such that:
497     //
498     // 1- BB1 post-dominates BB2.
499     // 2- BB2 dominates BB1.
500     // 3- BB1 and BB2 are in the same loop nest.
501     //
502     // If all those conditions hold, BB2's equivalence class is BB1.
503     DominatedBBs.clear();
504     PDT->getDescendants(BB1, DominatedBBs);
505     findEquivalencesFor(BB1, DominatedBBs, DT.get());
506
507     DEBUG(printBlockEquivalence(dbgs(), BB1));
508   }
509
510   // Assign weights to equivalence classes.
511   //
512   // All the basic blocks in the same equivalence class will execute
513   // the same number of times. Since we know that the head block in
514   // each equivalence class has the largest weight, assign that weight
515   // to all the blocks in that equivalence class.
516   DEBUG(dbgs() << "\nAssign the same weight to all blocks in the same class\n");
517   for (auto &BI : F) {
518     const BasicBlock *BB = &BI;
519     const BasicBlock *EquivBB = EquivalenceClass[BB];
520     if (BB != EquivBB)
521       BlockWeights[BB] = BlockWeights[EquivBB];
522     DEBUG(printBlockWeight(dbgs(), BB));
523   }
524 }
525
526 /// \brief Visit the given edge to decide if it has a valid weight.
527 ///
528 /// If \p E has not been visited before, we copy to \p UnknownEdge
529 /// and increment the count of unknown edges.
530 ///
531 /// \param E  Edge to visit.
532 /// \param NumUnknownEdges  Current number of unknown edges.
533 /// \param UnknownEdge  Set if E has not been visited before.
534 ///
535 /// \returns E's weight, if known. Otherwise, return 0.
536 unsigned SampleProfileLoader::visitEdge(Edge E, unsigned *NumUnknownEdges,
537                                         Edge *UnknownEdge) {
538   if (!VisitedEdges.count(E)) {
539     (*NumUnknownEdges)++;
540     *UnknownEdge = E;
541     return 0;
542   }
543
544   return EdgeWeights[E];
545 }
546
547 /// \brief Propagate weights through incoming/outgoing edges.
548 ///
549 /// If the weight of a basic block is known, and there is only one edge
550 /// with an unknown weight, we can calculate the weight of that edge.
551 ///
552 /// Similarly, if all the edges have a known count, we can calculate the
553 /// count of the basic block, if needed.
554 ///
555 /// \param F  Function to process.
556 ///
557 /// \returns  True if new weights were assigned to edges or blocks.
558 bool SampleProfileLoader::propagateThroughEdges(Function &F) {
559   bool Changed = false;
560   DEBUG(dbgs() << "\nPropagation through edges\n");
561   for (auto &BI : F) {
562     BasicBlock *BB = &BI;
563
564     // Visit all the predecessor and successor edges to determine
565     // which ones have a weight assigned already. Note that it doesn't
566     // matter that we only keep track of a single unknown edge. The
567     // only case we are interested in handling is when only a single
568     // edge is unknown (see setEdgeOrBlockWeight).
569     for (unsigned i = 0; i < 2; i++) {
570       unsigned TotalWeight = 0;
571       unsigned NumUnknownEdges = 0;
572       Edge UnknownEdge, SelfReferentialEdge;
573
574       if (i == 0) {
575         // First, visit all predecessor edges.
576         for (auto *Pred : Predecessors[BB]) {
577           Edge E = std::make_pair(Pred, BB);
578           TotalWeight += visitEdge(E, &NumUnknownEdges, &UnknownEdge);
579           if (E.first == E.second)
580             SelfReferentialEdge = E;
581         }
582       } else {
583         // On the second round, visit all successor edges.
584         for (auto *Succ : Successors[BB]) {
585           Edge E = std::make_pair(BB, Succ);
586           TotalWeight += visitEdge(E, &NumUnknownEdges, &UnknownEdge);
587         }
588       }
589
590       // After visiting all the edges, there are three cases that we
591       // can handle immediately:
592       //
593       // - All the edge weights are known (i.e., NumUnknownEdges == 0).
594       //   In this case, we simply check that the sum of all the edges
595       //   is the same as BB's weight. If not, we change BB's weight
596       //   to match. Additionally, if BB had not been visited before,
597       //   we mark it visited.
598       //
599       // - Only one edge is unknown and BB has already been visited.
600       //   In this case, we can compute the weight of the edge by
601       //   subtracting the total block weight from all the known
602       //   edge weights. If the edges weight more than BB, then the
603       //   edge of the last remaining edge is set to zero.
604       //
605       // - There exists a self-referential edge and the weight of BB is
606       //   known. In this case, this edge can be based on BB's weight.
607       //   We add up all the other known edges and set the weight on
608       //   the self-referential edge as we did in the previous case.
609       //
610       // In any other case, we must continue iterating. Eventually,
611       // all edges will get a weight, or iteration will stop when
612       // it reaches SampleProfileMaxPropagateIterations.
613       if (NumUnknownEdges <= 1) {
614         unsigned &BBWeight = BlockWeights[BB];
615         if (NumUnknownEdges == 0) {
616           // If we already know the weight of all edges, the weight of the
617           // basic block can be computed. It should be no larger than the sum
618           // of all edge weights.
619           if (TotalWeight > BBWeight) {
620             BBWeight = TotalWeight;
621             Changed = true;
622             DEBUG(dbgs() << "All edge weights for " << BB->getName()
623                          << " known. Set weight for block: ";
624                   printBlockWeight(dbgs(), BB););
625           }
626           if (VisitedBlocks.insert(BB).second)
627             Changed = true;
628         } else if (NumUnknownEdges == 1 && VisitedBlocks.count(BB)) {
629           // If there is a single unknown edge and the block has been
630           // visited, then we can compute E's weight.
631           if (BBWeight >= TotalWeight)
632             EdgeWeights[UnknownEdge] = BBWeight - TotalWeight;
633           else
634             EdgeWeights[UnknownEdge] = 0;
635           VisitedEdges.insert(UnknownEdge);
636           Changed = true;
637           DEBUG(dbgs() << "Set weight for edge: ";
638                 printEdgeWeight(dbgs(), UnknownEdge));
639         }
640       } else if (SelfReferentialEdge.first && VisitedBlocks.count(BB)) {
641         unsigned &BBWeight = BlockWeights[BB];
642         // We have a self-referential edge and the weight of BB is known.
643         if (BBWeight >= TotalWeight)
644           EdgeWeights[SelfReferentialEdge] = BBWeight - TotalWeight;
645         else
646           EdgeWeights[SelfReferentialEdge] = 0;
647         VisitedEdges.insert(SelfReferentialEdge);
648         Changed = true;
649         DEBUG(dbgs() << "Set self-referential edge weight to: ";
650               printEdgeWeight(dbgs(), SelfReferentialEdge));
651       }
652     }
653   }
654
655   return Changed;
656 }
657
658 /// \brief Build in/out edge lists for each basic block in the CFG.
659 ///
660 /// We are interested in unique edges. If a block B1 has multiple
661 /// edges to another block B2, we only add a single B1->B2 edge.
662 void SampleProfileLoader::buildEdges(Function &F) {
663   for (auto &BI : F) {
664     BasicBlock *B1 = &BI;
665
666     // Add predecessors for B1.
667     SmallPtrSet<BasicBlock *, 16> Visited;
668     if (!Predecessors[B1].empty())
669       llvm_unreachable("Found a stale predecessors list in a basic block.");
670     for (pred_iterator PI = pred_begin(B1), PE = pred_end(B1); PI != PE; ++PI) {
671       BasicBlock *B2 = *PI;
672       if (Visited.insert(B2).second)
673         Predecessors[B1].push_back(B2);
674     }
675
676     // Add successors for B1.
677     Visited.clear();
678     if (!Successors[B1].empty())
679       llvm_unreachable("Found a stale successors list in a basic block.");
680     for (succ_iterator SI = succ_begin(B1), SE = succ_end(B1); SI != SE; ++SI) {
681       BasicBlock *B2 = *SI;
682       if (Visited.insert(B2).second)
683         Successors[B1].push_back(B2);
684     }
685   }
686 }
687
688 /// \brief Propagate weights into edges
689 ///
690 /// The following rules are applied to every block BB in the CFG:
691 ///
692 /// - If BB has a single predecessor/successor, then the weight
693 ///   of that edge is the weight of the block.
694 ///
695 /// - If all incoming or outgoing edges are known except one, and the
696 ///   weight of the block is already known, the weight of the unknown
697 ///   edge will be the weight of the block minus the sum of all the known
698 ///   edges. If the sum of all the known edges is larger than BB's weight,
699 ///   we set the unknown edge weight to zero.
700 ///
701 /// - If there is a self-referential edge, and the weight of the block is
702 ///   known, the weight for that edge is set to the weight of the block
703 ///   minus the weight of the other incoming edges to that block (if
704 ///   known).
705 void SampleProfileLoader::propagateWeights(Function &F) {
706   bool Changed = true;
707   unsigned i = 0;
708
709   // Add an entry count to the function using the samples gathered
710   // at the function entry.
711   F.setEntryCount(Samples->getHeadSamples());
712
713   // Before propagation starts, build, for each block, a list of
714   // unique predecessors and successors. This is necessary to handle
715   // identical edges in multiway branches. Since we visit all blocks and all
716   // edges of the CFG, it is cleaner to build these lists once at the start
717   // of the pass.
718   buildEdges(F);
719
720   // Propagate until we converge or we go past the iteration limit.
721   while (Changed && i++ < SampleProfileMaxPropagateIterations) {
722     Changed = propagateThroughEdges(F);
723   }
724
725   // Generate MD_prof metadata for every branch instruction using the
726   // edge weights computed during propagation.
727   DEBUG(dbgs() << "\nPropagation complete. Setting branch weights\n");
728   MDBuilder MDB(F.getContext());
729   for (auto &BI : F) {
730     BasicBlock *BB = &BI;
731     TerminatorInst *TI = BB->getTerminator();
732     if (TI->getNumSuccessors() == 1)
733       continue;
734     if (!isa<BranchInst>(TI) && !isa<SwitchInst>(TI))
735       continue;
736
737     DEBUG(dbgs() << "\nGetting weights for branch at line "
738                  << TI->getDebugLoc().getLine() << ".\n");
739     SmallVector<unsigned, 4> Weights;
740     bool AllWeightsZero = true;
741     for (unsigned I = 0; I < TI->getNumSuccessors(); ++I) {
742       BasicBlock *Succ = TI->getSuccessor(I);
743       Edge E = std::make_pair(BB, Succ);
744       unsigned Weight = EdgeWeights[E];
745       DEBUG(dbgs() << "\t"; printEdgeWeight(dbgs(), E));
746       Weights.push_back(Weight);
747       if (Weight != 0)
748         AllWeightsZero = false;
749     }
750
751     // Only set weights if there is at least one non-zero weight.
752     // In any other case, let the analyzer set weights.
753     if (!AllWeightsZero) {
754       DEBUG(dbgs() << "SUCCESS. Found non-zero weights.\n");
755       TI->setMetadata(llvm::LLVMContext::MD_prof,
756                       MDB.createBranchWeights(Weights));
757     } else {
758       DEBUG(dbgs() << "SKIPPED. All branch weights are zero.\n");
759     }
760   }
761 }
762
763 /// \brief Get the line number for the function header.
764 ///
765 /// This looks up function \p F in the current compilation unit and
766 /// retrieves the line number where the function is defined. This is
767 /// line 0 for all the samples read from the profile file. Every line
768 /// number is relative to this line.
769 ///
770 /// \param F  Function object to query.
771 ///
772 /// \returns the line number where \p F is defined. If it returns 0,
773 ///          it means that there is no debug information available for \p F.
774 unsigned SampleProfileLoader::getFunctionLoc(Function &F) {
775   if (DISubprogram *S = getDISubprogram(&F))
776     return S->getLine();
777
778   // If could not find the start of \p F, emit a diagnostic to inform the user
779   // about the missed opportunity.
780   F.getContext().diagnose(DiagnosticInfoSampleProfile(
781       "No debug information found in function " + F.getName() +
782           ": Function profile not used",
783       DS_Warning));
784   return 0;
785 }
786
787 void SampleProfileLoader::computeDominanceAndLoopInfo(Function &F) {
788   DT.reset(new DominatorTree);
789   DT->recalculate(F);
790
791   PDT.reset(new DominatorTreeBase<BasicBlock>(true));
792   PDT->recalculate(F);
793
794   LI.reset(new LoopInfo);
795   LI->analyze(*DT);
796 }
797
798 /// \brief Generate branch weight metadata for all branches in \p F.
799 ///
800 /// Branch weights are computed out of instruction samples using a
801 /// propagation heuristic. Propagation proceeds in 3 phases:
802 ///
803 /// 1- Assignment of block weights. All the basic blocks in the function
804 ///    are initial assigned the same weight as their most frequently
805 ///    executed instruction.
806 ///
807 /// 2- Creation of equivalence classes. Since samples may be missing from
808 ///    blocks, we can fill in the gaps by setting the weights of all the
809 ///    blocks in the same equivalence class to the same weight. To compute
810 ///    the concept of equivalence, we use dominance and loop information.
811 ///    Two blocks B1 and B2 are in the same equivalence class if B1
812 ///    dominates B2, B2 post-dominates B1 and both are in the same loop.
813 ///
814 /// 3- Propagation of block weights into edges. This uses a simple
815 ///    propagation heuristic. The following rules are applied to every
816 ///    block BB in the CFG:
817 ///
818 ///    - If BB has a single predecessor/successor, then the weight
819 ///      of that edge is the weight of the block.
820 ///
821 ///    - If all the edges are known except one, and the weight of the
822 ///      block is already known, the weight of the unknown edge will
823 ///      be the weight of the block minus the sum of all the known
824 ///      edges. If the sum of all the known edges is larger than BB's weight,
825 ///      we set the unknown edge weight to zero.
826 ///
827 ///    - If there is a self-referential edge, and the weight of the block is
828 ///      known, the weight for that edge is set to the weight of the block
829 ///      minus the weight of the other incoming edges to that block (if
830 ///      known).
831 ///
832 /// Since this propagation is not guaranteed to finalize for every CFG, we
833 /// only allow it to proceed for a limited number of iterations (controlled
834 /// by -sample-profile-max-propagate-iterations).
835 ///
836 /// FIXME: Try to replace this propagation heuristic with a scheme
837 /// that is guaranteed to finalize. A work-list approach similar to
838 /// the standard value propagation algorithm used by SSA-CCP might
839 /// work here.
840 ///
841 /// Once all the branch weights are computed, we emit the MD_prof
842 /// metadata on BB using the computed values for each of its branches.
843 ///
844 /// \param F The function to query.
845 ///
846 /// \returns true if \p F was modified. Returns false, otherwise.
847 bool SampleProfileLoader::emitAnnotations(Function &F) {
848   bool Changed = false;
849
850   // Initialize invariants used during computation and propagation.
851   HeaderLineno = getFunctionLoc(F);
852   if (HeaderLineno == 0)
853     return false;
854
855   DEBUG(dbgs() << "Line number for the first instruction in " << F.getName()
856                << ": " << HeaderLineno << "\n");
857
858   Changed |= inlineHotFunctions(F);
859
860   // Compute basic block weights.
861   Changed |= computeBlockWeights(F);
862
863   if (Changed) {
864     // Compute dominance and loop info needed for propagation.
865     computeDominanceAndLoopInfo(F);
866
867     // Find equivalence classes.
868     findEquivalenceClasses(F);
869
870     // Propagate weights to all edges.
871     propagateWeights(F);
872   }
873
874   return Changed;
875 }
876
877 char SampleProfileLoader::ID = 0;
878 INITIALIZE_PASS_BEGIN(SampleProfileLoader, "sample-profile",
879                       "Sample Profile loader", false, false)
880 INITIALIZE_PASS_DEPENDENCY(AddDiscriminators)
881 INITIALIZE_PASS_END(SampleProfileLoader, "sample-profile",
882                     "Sample Profile loader", false, false)
883
884 bool SampleProfileLoader::doInitialization(Module &M) {
885   auto &Ctx = M.getContext();
886   auto ReaderOrErr = SampleProfileReader::create(Filename, Ctx);
887   if (std::error_code EC = ReaderOrErr.getError()) {
888     std::string Msg = "Could not open profile: " + EC.message();
889     Ctx.diagnose(DiagnosticInfoSampleProfile(Filename.data(), Msg));
890     return false;
891   }
892   Reader = std::move(ReaderOrErr.get());
893   ProfileIsValid = (Reader->read() == sampleprof_error::success);
894   return true;
895 }
896
897 ModulePass *llvm::createSampleProfileLoaderPass() {
898   return new SampleProfileLoader(SampleProfileFile);
899 }
900
901 ModulePass *llvm::createSampleProfileLoaderPass(StringRef Name) {
902   return new SampleProfileLoader(Name);
903 }
904
905 bool SampleProfileLoader::runOnModule(Module &M) {
906   bool retval = false;
907   for (auto &F : M)
908     if (!F.isDeclaration())
909       retval |= runOnFunction(F);
910   return retval;
911 }
912
913 bool SampleProfileLoader::runOnFunction(Function &F) {
914   if (!ProfileIsValid)
915     return false;
916
917   Samples = Reader->getSamplesFor(F);
918   if (!Samples->empty())
919     return emitAnnotations(F);
920   return false;
921 }