3e931f771128c6f8c7e9c09f58ad46e12f373316
[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 <cctype>
50
51 using namespace llvm;
52 using namespace sampleprof;
53
54 #define DEBUG_TYPE "sample-profile"
55
56 // Command line option to specify the file to read samples from. This is
57 // mainly used for debugging.
58 static 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);
61 static 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."));
65
66 namespace {
67 typedef DenseMap<const BasicBlock *, unsigned> BlockWeightMap;
68 typedef DenseMap<const BasicBlock *, const BasicBlock *> EquivalenceClassMap;
69 typedef std::pair<const BasicBlock *, const BasicBlock *> Edge;
70 typedef DenseMap<Edge, unsigned> EdgeWeightMap;
71 typedef DenseMap<const BasicBlock *, SmallVector<const BasicBlock *, 8>>
72     BlockEdgeMap;
73
74 /// \brief Sample profile pass.
75 ///
76 /// 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.
79 class SampleProfileLoader : public ModulePass {
80 public:
81   // Class identification, replacement for typeinfo
82   static char ID;
83
84   SampleProfileLoader(StringRef Name = SampleProfileFile)
85       : ModulePass(ID), DT(nullptr), PDT(nullptr), LI(nullptr), Reader(),
86         Samples(nullptr), Filename(Name), ProfileIsValid(false) {
87     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
96   bool runOnModule(Module &M) override;
97
98   void getAnalysisUsage(AnalysisUsage &AU) const override {
99     AU.setPreservesCFG();
100   }
101
102 protected:
103   bool runOnFunction(Function &F);
104   unsigned getFunctionLoc(Function &F);
105   bool emitAnnotations(Function &F);
106   ErrorOr<unsigned> getInstWeight(const Instruction &I) const;
107   ErrorOr<unsigned> getBlockWeight(const BasicBlock *BB) const;
108   void printEdgeWeight(raw_ostream &OS, Edge E);
109   void printBlockWeight(raw_ostream &OS, const BasicBlock *BB) const;
110   void printBlockEquivalence(raw_ostream &OS, const BasicBlock *BB);
111   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);
117   unsigned visitEdge(Edge E, unsigned *NumUnknownEdges, Edge *UnknownEdge);
118   void buildEdges(Function &F);
119   bool propagateThroughEdges(Function &F);
120   void computeDominanceAndLoopInfo(Function &F);
121
122   /// \brief Line number for the function header. Used to compute absolute
123   /// line numbers from the relative line numbers found in the profile.
124   unsigned HeaderLineno;
125
126   /// \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;
131
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.
139   SmallPtrSet<const BasicBlock *, 128> VisitedBlocks;
140
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.
153   std::unique_ptr<DominatorTree> DT;
154   std::unique_ptr<DominatorTreeBase<BasicBlock>> PDT;
155   std::unique_ptr<LoopInfo> LI;
156
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;
162
163   /// \brief Profile reader object.
164   std::unique_ptr<SampleProfileReader> Reader;
165
166   /// \brief Samples collected for the body of this function.
167   FunctionSamples *Samples;
168
169   /// \brief Name of the profile file to load.
170   StringRef Filename;
171
172   /// \brief Flag indicating whether the profile input loaded successfully.
173   bool ProfileIsValid;
174 };
175 }
176
177 /// \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.
181 void SampleProfileLoader::printEdgeWeight(raw_ostream &OS, Edge E) {
182   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.
190 void SampleProfileLoader::printBlockEquivalence(raw_ostream &OS,
191                                                 const BasicBlock *BB) {
192   const BasicBlock *Equiv = EquivalenceClass[BB];
193   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.
201 void 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";
206 }
207
208 /// \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 ///
218 /// \returns the weight of \p Inst.
219 ErrorOr<unsigned>
220 SampleProfileLoader::getInstWeight(const Instruction &Inst) const {
221   DebugLoc DLoc = Inst.getDebugLoc();
222   if (!DLoc)
223     return std::error_code();
224
225   unsigned Lineno = DLoc.getLine();
226   if (Lineno < HeaderLineno)
227     return std::error_code();
228
229   const DILocation *DIL = DLoc;
230   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;
238 }
239
240 /// \brief Compute the weight of a basic block.
241 ///
242 /// The weight of basic block \p BB is the maximum weight of all the
243 /// instructions in BB.
244 ///
245 /// \param BB The basic block to query.
246 ///
247 /// \returns the weight for \p BB.
248 ErrorOr<unsigned>
249 SampleProfileLoader::getBlockWeight(const BasicBlock *BB) const {
250   bool Found = false;
251   unsigned Weight = 0;
252   for (auto &I : BB->getInstList()) {
253     const ErrorOr<unsigned> &R = getInstWeight(I);
254     if (R && R.get() >= Weight) {
255       Weight = R.get();
256       Found = true;
257     }
258   }
259   if (Found)
260     return Weight;
261   else
262     return std::error_code();
263 }
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.
271 bool SampleProfileLoader::computeBlockWeights(Function &F) {
272   bool Changed = false;
273   DEBUG(dbgs() << "Block weights\n");
274   for (const auto &BB : F) {
275     ErrorOr<unsigned> Weight = getBlockWeight(&BB);
276     if (Weight) {
277       BlockWeights[&BB] = Weight.get();
278       Changed = true;
279     }
280     DEBUG(printBlockWeight(dbgs(), &BB));
281   }
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
289 /// number of times as \p BB1. To do this, it traverses all the
290 /// 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.
309 void SampleProfileLoader::findEquivalencesFor(
310     BasicBlock *BB1, SmallVector<BasicBlock *, 8> Descendants,
311     DominatorTreeBase<BasicBlock> *DomTree) {
312   for (const auto *BB2 : Descendants) {
313     bool IsDomParent = DomTree->dominates(BB2, BB1);
314     bool IsInSameLoop = LI->getLoopFor(BB1) == LI->getLoopFor(BB2);
315     if (BB1 != BB2 && VisitedBlocks.insert(BB2).second && IsDomParent &&
316         IsInSameLoop) {
317       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.
327       unsigned &BB1Weight = BlockWeights[BB1];
328       unsigned &BB2Weight = BlockWeights[BB2];
329       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.
343 void SampleProfileLoader::findEquivalenceClasses(Function &F) {
344   SmallVector<BasicBlock *, 8> DominatedBBs;
345   DEBUG(dbgs() << "\nBlock equivalence classes\n");
346   // Find equivalence sets based on dominance and post-dominance information.
347   for (auto &BB : F) {
348     BasicBlock *BB1 = &BB;
349
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);
371     findEquivalencesFor(BB1, DominatedBBs, PDT.get());
372
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);
383     findEquivalencesFor(BB1, DominatedBBs, DT.get());
384
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");
395   for (auto &BI : F) {
396     const BasicBlock *BB = &BI;
397     const BasicBlock *EquivBB = EquivalenceClass[BB];
398     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.
414 unsigned SampleProfileLoader::visitEdge(Edge E, unsigned *NumUnknownEdges,
415                                         Edge *UnknownEdge) {
416   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.
436 bool SampleProfileLoader::propagateThroughEdges(Function &F) {
437   bool Changed = false;
438   DEBUG(dbgs() << "\nPropagation through edges\n");
439   for (auto &BI : F) {
440     BasicBlock *BB = &BI;
441
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++) {
448       unsigned TotalWeight = 0;
449       unsigned NumUnknownEdges = 0;
450       Edge UnknownEdge, SelfReferentialEdge;
451
452       if (i == 0) {
453         // First, visit all predecessor edges.
454         for (auto *Pred : Predecessors[BB]) {
455           Edge E = std::make_pair(Pred, BB);
456           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.
462         for (auto *Succ : Successors[BB]) {
463           Edge E = std::make_pair(BB, Succ);
464           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) {
492         unsigned &BBWeight = BlockWeights[BB];
493         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           }
504           if (VisitedBlocks.insert(BB).second)
505             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)) {
519         unsigned &BBWeight = BlockWeights[BB];
520         // 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.
540 void SampleProfileLoader::buildEdges(Function &F) {
541   for (auto &BI : F) {
542     BasicBlock *B1 = &BI;
543
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.");
548     for (pred_iterator PI = pred_begin(B1), PE = pred_end(B1); PI != PE; ++PI) {
549       BasicBlock *B2 = *PI;
550       if (Visited.insert(B2).second)
551         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.");
558     for (succ_iterator SI = succ_begin(B1), SE = succ_end(B1); SI != SE; ++SI) {
559       BasicBlock *B2 = *SI;
560       if (Visited.insert(B2).second)
561         Successors[B1].push_back(B2);
562     }
563   }
564 }
565
566 /// \brief Propagate weights into edges
567 ///
568 /// The following rules are applied to every block BB in the CFG:
569 ///
570 /// - If BB has a single predecessor/successor, then the weight
571 ///   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
576 ///   edges. If the sum of all the known edges is larger than BB's weight,
577 ///   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).
583 void SampleProfileLoader::propagateWeights(Function &F) {
584   bool Changed = true;
585   unsigned i = 0;
586
587   // Add an entry count to the function using the samples gathered
588   // at the function entry.
589   F.setEntryCount(Samples->getHeadSamples());
590
591   // 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());
607   for (auto &BI : F) {
608     BasicBlock *BB = &BI;
609     TerminatorInst *TI = BB->getTerminator();
610     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 "
616                  << TI->getDebugLoc().getLine() << ".\n");
617     SmallVector<unsigned, 4> Weights;
618     bool AllWeightsZero = true;
619     for (unsigned I = 0; I < TI->getNumSuccessors(); ++I) {
620       BasicBlock *Succ = TI->getSuccessor(I);
621       Edge E = std::make_pair(BB, Succ);
622       unsigned Weight = EdgeWeights[E];
623       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 ///
650 /// \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.
652 unsigned SampleProfileLoader::getFunctionLoc(Function &F) {
653   if (DISubprogram *S = getDISubprogram(&F))
654     return S->getLine();
655
656   // If could not find the start of \p F, emit a diagnostic to inform the user
657   // about the missed opportunity.
658   F.getContext().diagnose(DiagnosticInfoSampleProfile(
659       "No debug information found in function " + F.getName() +
660           ": Function profile not used",
661       DS_Warning));
662   return 0;
663 }
664
665 void 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
676 /// \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
694 ///    block BB in the CFG:
695 ///
696 ///    - If BB has a single predecessor/successor, then the weight
697 ///      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
702 ///      edges. If the sum of all the known edges is larger than BB's weight,
703 ///      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
720 /// metadata on BB using the computed values for each of its branches.
721 ///
722 /// \param F The function to query.
723 ///
724 /// \returns true if \p F was modified. Returns false, otherwise.
725 bool SampleProfileLoader::emitAnnotations(Function &F) {
726   bool Changed = false;
727
728   // Initialize invariants used during computation and propagation.
729   HeaderLineno = getFunctionLoc(F);
730   if (HeaderLineno == 0)
731     return false;
732
733   DEBUG(dbgs() << "Line number for the first instruction in " << F.getName()
734                << ": " << HeaderLineno << "\n");
735
736   // Compute basic block weights.
737   Changed |= computeBlockWeights(F);
738
739   if (Changed) {
740     // Compute dominance and loop info needed for propagation.
741     computeDominanceAndLoopInfo(F);
742
743     // Find equivalence classes.
744     findEquivalenceClasses(F);
745
746     // Propagate weights to all edges.
747     propagateWeights(F);
748   }
749
750   return Changed;
751 }
752
753 char SampleProfileLoader::ID = 0;
754 INITIALIZE_PASS_BEGIN(SampleProfileLoader, "sample-profile",
755                       "Sample Profile loader", false, false)
756 INITIALIZE_PASS_DEPENDENCY(AddDiscriminators)
757 INITIALIZE_PASS_END(SampleProfileLoader, "sample-profile",
758                     "Sample Profile loader", false, false)
759
760 bool SampleProfileLoader::doInitialization(Module &M) {
761   auto &Ctx = M.getContext();
762   auto ReaderOrErr = SampleProfileReader::create(Filename, Ctx);
763   if (std::error_code EC = ReaderOrErr.getError()) {
764     std::string Msg = "Could not open profile: " + EC.message();
765     Ctx.diagnose(DiagnosticInfoSampleProfile(Filename.data(), Msg));
766     return false;
767   }
768   Reader = std::move(ReaderOrErr.get());
769   ProfileIsValid = (Reader->read() == sampleprof_error::success);
770   return true;
771 }
772
773 ModulePass *llvm::createSampleProfileLoaderPass() {
774   return new SampleProfileLoader(SampleProfileFile);
775 }
776
777 ModulePass *llvm::createSampleProfileLoaderPass(StringRef Name) {
778   return new SampleProfileLoader(Name);
779 }
780
781 bool 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
789 bool SampleProfileLoader::runOnFunction(Function &F) {
790   if (!ProfileIsValid)
791     return false;
792
793   Samples = Reader->getSamplesFor(F);
794   if (!Samples->empty())
795     return emitAnnotations(F);
796   return false;
797 }