Use auto iteration in lib/Transforms/Scalar/SampleProfile.cpp. No functional changes.
[oota-llvm.git] / lib / Transforms / Scalar / 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/Transforms/Scalar.h"
26 #include "llvm/ADT/DenseMap.h"
27 #include "llvm/ADT/SmallPtrSet.h"
28 #include "llvm/ADT/SmallSet.h"
29 #include "llvm/ADT/StringRef.h"
30 #include "llvm/Analysis/LoopInfo.h"
31 #include "llvm/Analysis/PostDominators.h"
32 #include "llvm/IR/Constants.h"
33 #include "llvm/IR/DebugInfo.h"
34 #include "llvm/IR/DiagnosticInfo.h"
35 #include "llvm/IR/Dominators.h"
36 #include "llvm/IR/Function.h"
37 #include "llvm/IR/InstIterator.h"
38 #include "llvm/IR/Instructions.h"
39 #include "llvm/IR/LLVMContext.h"
40 #include "llvm/IR/MDBuilder.h"
41 #include "llvm/IR/Metadata.h"
42 #include "llvm/IR/Module.h"
43 #include "llvm/Pass.h"
44 #include "llvm/ProfileData/SampleProfReader.h"
45 #include "llvm/Support/CommandLine.h"
46 #include "llvm/Support/Debug.h"
47 #include "llvm/Support/raw_ostream.h"
48 #include <cctype>
49
50 using namespace llvm;
51 using namespace sampleprof;
52
53 #define DEBUG_TYPE "sample-profile"
54
55 // Command line option to specify the file to read samples from. This is
56 // mainly used for debugging.
57 static 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);
60 static 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."));
64
65 namespace {
66 typedef DenseMap<BasicBlock *, unsigned> BlockWeightMap;
67 typedef DenseMap<BasicBlock *, BasicBlock *> EquivalenceClassMap;
68 typedef std::pair<BasicBlock *, BasicBlock *> Edge;
69 typedef DenseMap<Edge, unsigned> EdgeWeightMap;
70 typedef DenseMap<BasicBlock *, SmallVector<BasicBlock *, 8>> BlockEdgeMap;
71
72 /// \brief Sample profile pass.
73 ///
74 /// 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.
77 class SampleProfileLoader : public FunctionPass {
78 public:
79   // Class identification, replacement for typeinfo
80   static char ID;
81
82   SampleProfileLoader(StringRef Name = SampleProfileFile)
83       : FunctionPass(ID), DT(nullptr), PDT(nullptr), LI(nullptr), Ctx(nullptr),
84         Reader(), Samples(nullptr), Filename(Name), ProfileIsValid(false) {
85     initializeSampleProfileLoaderPass(*PassRegistry::getPassRegistry());
86   }
87
88   bool doInitialization(Module &M) override;
89
90   void dump() { Reader->dump(); }
91
92   const char *getPassName() const override { return "Sample profile pass"; }
93
94   bool runOnFunction(Function &F) override;
95
96   void getAnalysisUsage(AnalysisUsage &AU) const override {
97     AU.setPreservesCFG();
98     AU.addRequired<LoopInfo>();
99     AU.addRequired<DominatorTreeWrapperPass>();
100     AU.addRequired<PostDominatorTree>();
101   }
102
103 protected:
104   unsigned getFunctionLoc(Function &F);
105   bool emitAnnotations(Function &F);
106   unsigned getInstWeight(Instruction &I);
107   unsigned getBlockWeight(BasicBlock *B);
108   void printEdgeWeight(raw_ostream &OS, Edge E);
109   void printBlockWeight(raw_ostream &OS, BasicBlock *BB);
110   void printBlockEquivalence(raw_ostream &OS, 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
121   /// \brief Line number for the function header. Used to compute absolute
122   /// line numbers from the relative line numbers found in the profile.
123   unsigned HeaderLineno;
124
125   /// \brief Map basic blocks to their computed weights.
126   ///
127   /// The weight of a basic block is defined to be the maximum
128   /// of all the instruction weights in that block.
129   BlockWeightMap BlockWeights;
130
131   /// \brief Map edges to their computed weights.
132   ///
133   /// Edge weights are computed by propagating basic block weights in
134   /// SampleProfile::propagateWeights.
135   EdgeWeightMap EdgeWeights;
136
137   /// \brief Set of visited blocks during propagation.
138   SmallPtrSet<BasicBlock *, 128> VisitedBlocks;
139
140   /// \brief Set of visited edges during propagation.
141   SmallSet<Edge, 128> VisitedEdges;
142
143   /// \brief Equivalence classes for block weights.
144   ///
145   /// Two blocks BB1 and BB2 are in the same equivalence class if they
146   /// dominate and post-dominate each other, and they are in the same loop
147   /// nest. When this happens, the two blocks are guaranteed to execute
148   /// the same number of times.
149   EquivalenceClassMap EquivalenceClass;
150
151   /// \brief Dominance, post-dominance and loop information.
152   DominatorTree *DT;
153   PostDominatorTree *PDT;
154   LoopInfo *LI;
155
156   /// \brief Predecessors for each basic block in the CFG.
157   BlockEdgeMap Predecessors;
158
159   /// \brief Successors for each basic block in the CFG.
160   BlockEdgeMap Successors;
161
162   /// \brief LLVM context holding the debug data we need.
163   LLVMContext *Ctx;
164
165   /// \brief Profile reader object.
166   std::unique_ptr<SampleProfileReader> Reader;
167
168   /// \brief Samples collected for the body of this function.
169   FunctionSamples *Samples;
170
171   /// \brief Name of the profile file to load.
172   StringRef Filename;
173
174   /// \brief Flag indicating whether the profile input loaded successfully.
175   bool ProfileIsValid;
176 };
177 }
178
179 /// \brief Print the weight of edge \p E on stream \p OS.
180 ///
181 /// \param OS  Stream to emit the output to.
182 /// \param E  Edge to print.
183 void SampleProfileLoader::printEdgeWeight(raw_ostream &OS, Edge E) {
184   OS << "weight[" << E.first->getName() << "->" << E.second->getName()
185      << "]: " << EdgeWeights[E] << "\n";
186 }
187
188 /// \brief Print the equivalence class of block \p BB on stream \p OS.
189 ///
190 /// \param OS  Stream to emit the output to.
191 /// \param BB  Block to print.
192 void SampleProfileLoader::printBlockEquivalence(raw_ostream &OS,
193                                                 BasicBlock *BB) {
194   BasicBlock *Equiv = EquivalenceClass[BB];
195   OS << "equivalence[" << BB->getName()
196      << "]: " << ((Equiv) ? EquivalenceClass[BB]->getName() : "NONE") << "\n";
197 }
198
199 /// \brief Print the weight of block \p BB on stream \p OS.
200 ///
201 /// \param OS  Stream to emit the output to.
202 /// \param BB  Block to print.
203 void SampleProfileLoader::printBlockWeight(raw_ostream &OS, BasicBlock *BB) {
204   OS << "weight[" << BB->getName() << "]: " << BlockWeights[BB] << "\n";
205 }
206
207 /// \brief Get the weight for an instruction.
208 ///
209 /// The "weight" of an instruction \p Inst is the number of samples
210 /// collected on that instruction at runtime. To retrieve it, we
211 /// need to compute the line number of \p Inst relative to the start of its
212 /// function. We use HeaderLineno to compute the offset. We then
213 /// look up the samples collected for \p Inst using BodySamples.
214 ///
215 /// \param Inst Instruction to query.
216 ///
217 /// \returns The profiled weight of I.
218 unsigned SampleProfileLoader::getInstWeight(Instruction &Inst) {
219   DebugLoc DLoc = Inst.getDebugLoc();
220   unsigned Lineno = DLoc.getLine();
221   if (Lineno < HeaderLineno)
222     return 0;
223
224   DILocation DIL(DLoc.getAsMDNode(*Ctx));
225   int LOffset = Lineno - HeaderLineno;
226   unsigned Discriminator = DIL.getDiscriminator();
227   unsigned Weight = Samples->samplesAt(LOffset, Discriminator);
228   DEBUG(dbgs() << "    " << Lineno << "." << Discriminator << ":" << Inst
229                << " (line offset: " << LOffset << "." << Discriminator
230                << " - weight: " << Weight << ")\n");
231   return Weight;
232 }
233
234 /// \brief Compute the weight of a basic block.
235 ///
236 /// The weight of basic block \p B is the maximum weight of all the
237 /// instructions in B. The weight of \p B is computed and cached in
238 /// the BlockWeights map.
239 ///
240 /// \param B The basic block to query.
241 ///
242 /// \returns The computed weight of B.
243 unsigned SampleProfileLoader::getBlockWeight(BasicBlock *B) {
244   // If we've computed B's weight before, return it.
245   std::pair<BlockWeightMap::iterator, bool> Entry =
246       BlockWeights.insert(std::make_pair(B, 0));
247   if (!Entry.second)
248     return Entry.first->second;
249
250   // Otherwise, compute and cache B's weight.
251   unsigned Weight = 0;
252   for (auto &I : B->getInstList()) {
253     unsigned InstWeight = getInstWeight(I);
254     if (InstWeight > Weight)
255       Weight = InstWeight;
256   }
257   Entry.first->second = Weight;
258   return Weight;
259 }
260
261 /// \brief Compute and store the weights of every basic block.
262 ///
263 /// This populates the BlockWeights map by computing
264 /// the weights of every basic block in the CFG.
265 ///
266 /// \param F The function to query.
267 bool SampleProfileLoader::computeBlockWeights(Function &F) {
268   bool Changed = false;
269   DEBUG(dbgs() << "Block weights\n");
270   for (auto B = F.begin(), E = F.end(); B != E; ++B) {
271     unsigned Weight = getBlockWeight(B);
272     Changed |= (Weight > 0);
273     DEBUG(printBlockWeight(dbgs(), B));
274   }
275
276   return Changed;
277 }
278
279 /// \brief Find equivalence classes for the given block.
280 ///
281 /// This finds all the blocks that are guaranteed to execute the same
282 /// number of times as \p BB1. To do this, it traverses all the the
283 /// descendants of \p BB1 in the dominator or post-dominator tree.
284 ///
285 /// A block BB2 will be in the same equivalence class as \p BB1 if
286 /// the following holds:
287 ///
288 /// 1- \p BB1 is a descendant of BB2 in the opposite tree. So, if BB2
289 ///    is a descendant of \p BB1 in the dominator tree, then BB2 should
290 ///    dominate BB1 in the post-dominator tree.
291 ///
292 /// 2- Both BB2 and \p BB1 must be in the same loop.
293 ///
294 /// For every block BB2 that meets those two requirements, we set BB2's
295 /// equivalence class to \p BB1.
296 ///
297 /// \param BB1  Block to check.
298 /// \param Descendants  Descendants of \p BB1 in either the dom or pdom tree.
299 /// \param DomTree  Opposite dominator tree. If \p Descendants is filled
300 ///                 with blocks from \p BB1's dominator tree, then
301 ///                 this is the post-dominator tree, and vice versa.
302 void SampleProfileLoader::findEquivalencesFor(
303     BasicBlock *BB1, SmallVector<BasicBlock *, 8> Descendants,
304     DominatorTreeBase<BasicBlock> *DomTree) {
305   for (auto I = Descendants.begin(), E = Descendants.end(); I != E; ++I) {
306     BasicBlock *BB2 = *I;
307     bool IsDomParent = DomTree->dominates(BB2, BB1);
308     bool IsInSameLoop = LI->getLoopFor(BB1) == LI->getLoopFor(BB2);
309     if (BB1 != BB2 && VisitedBlocks.insert(BB2) && IsDomParent &&
310         IsInSameLoop) {
311       EquivalenceClass[BB2] = BB1;
312
313       // If BB2 is heavier than BB1, make BB2 have the same weight
314       // as BB1.
315       //
316       // Note that we don't worry about the opposite situation here
317       // (when BB2 is lighter than BB1). We will deal with this
318       // during the propagation phase. Right now, we just want to
319       // make sure that BB1 has the largest weight of all the
320       // members of its equivalence set.
321       unsigned &BB1Weight = BlockWeights[BB1];
322       unsigned &BB2Weight = BlockWeights[BB2];
323       BB1Weight = std::max(BB1Weight, BB2Weight);
324     }
325   }
326 }
327
328 /// \brief Find equivalence classes.
329 ///
330 /// Since samples may be missing from blocks, we can fill in the gaps by setting
331 /// the weights of all the blocks in the same equivalence class to the same
332 /// weight. To compute the concept of equivalence, we use dominance and loop
333 /// information. Two blocks B1 and B2 are in the same equivalence class if B1
334 /// dominates B2, B2 post-dominates B1 and both are in the same loop.
335 ///
336 /// \param F The function to query.
337 void SampleProfileLoader::findEquivalenceClasses(Function &F) {
338   SmallVector<BasicBlock *, 8> DominatedBBs;
339   DEBUG(dbgs() << "\nBlock equivalence classes\n");
340   // Find equivalence sets based on dominance and post-dominance information.
341   for (auto B = F.begin(), E = F.end(); B != E; ++B) {
342     BasicBlock *BB1 = B;
343
344     // Compute BB1's equivalence class once.
345     if (EquivalenceClass.count(BB1)) {
346       DEBUG(printBlockEquivalence(dbgs(), BB1));
347       continue;
348     }
349
350     // By default, blocks are in their own equivalence class.
351     EquivalenceClass[BB1] = BB1;
352
353     // Traverse all the blocks dominated by BB1. We are looking for
354     // every basic block BB2 such that:
355     //
356     // 1- BB1 dominates BB2.
357     // 2- BB2 post-dominates BB1.
358     // 3- BB1 and BB2 are in the same loop nest.
359     //
360     // If all those conditions hold, it means that BB2 is executed
361     // as many times as BB1, so they are placed in the same equivalence
362     // class by making BB2's equivalence class be BB1.
363     DominatedBBs.clear();
364     DT->getDescendants(BB1, DominatedBBs);
365     findEquivalencesFor(BB1, DominatedBBs, PDT->DT);
366
367     // Repeat the same logic for all the blocks post-dominated by BB1.
368     // We are looking for every basic block BB2 such that:
369     //
370     // 1- BB1 post-dominates BB2.
371     // 2- BB2 dominates BB1.
372     // 3- BB1 and BB2 are in the same loop nest.
373     //
374     // If all those conditions hold, BB2's equivalence class is BB1.
375     DominatedBBs.clear();
376     PDT->getDescendants(BB1, DominatedBBs);
377     findEquivalencesFor(BB1, DominatedBBs, DT);
378
379     DEBUG(printBlockEquivalence(dbgs(), BB1));
380   }
381
382   // Assign weights to equivalence classes.
383   //
384   // All the basic blocks in the same equivalence class will execute
385   // the same number of times. Since we know that the head block in
386   // each equivalence class has the largest weight, assign that weight
387   // to all the blocks in that equivalence class.
388   DEBUG(dbgs() << "\nAssign the same weight to all blocks in the same class\n");
389   for (auto B = F.begin(), E = F.end(); B != E; ++B) {
390     BasicBlock *BB = B;
391     BasicBlock *EquivBB = EquivalenceClass[BB];
392     if (BB != EquivBB)
393       BlockWeights[BB] = BlockWeights[EquivBB];
394     DEBUG(printBlockWeight(dbgs(), BB));
395   }
396 }
397
398 /// \brief Visit the given edge to decide if it has a valid weight.
399 ///
400 /// If \p E has not been visited before, we copy to \p UnknownEdge
401 /// and increment the count of unknown edges.
402 ///
403 /// \param E  Edge to visit.
404 /// \param NumUnknownEdges  Current number of unknown edges.
405 /// \param UnknownEdge  Set if E has not been visited before.
406 ///
407 /// \returns E's weight, if known. Otherwise, return 0.
408 unsigned SampleProfileLoader::visitEdge(Edge E, unsigned *NumUnknownEdges,
409                                         Edge *UnknownEdge) {
410   if (!VisitedEdges.count(E)) {
411     (*NumUnknownEdges)++;
412     *UnknownEdge = E;
413     return 0;
414   }
415
416   return EdgeWeights[E];
417 }
418
419 /// \brief Propagate weights through incoming/outgoing edges.
420 ///
421 /// If the weight of a basic block is known, and there is only one edge
422 /// with an unknown weight, we can calculate the weight of that edge.
423 ///
424 /// Similarly, if all the edges have a known count, we can calculate the
425 /// count of the basic block, if needed.
426 ///
427 /// \param F  Function to process.
428 ///
429 /// \returns  True if new weights were assigned to edges or blocks.
430 bool SampleProfileLoader::propagateThroughEdges(Function &F) {
431   bool Changed = false;
432   DEBUG(dbgs() << "\nPropagation through edges\n");
433   for (auto BI = F.begin(), EI = F.end(); BI != EI; ++BI) {
434     BasicBlock *BB = BI;
435
436     // Visit all the predecessor and successor edges to determine
437     // which ones have a weight assigned already. Note that it doesn't
438     // matter that we only keep track of a single unknown edge. The
439     // only case we are interested in handling is when only a single
440     // edge is unknown (see setEdgeOrBlockWeight).
441     for (unsigned i = 0; i < 2; i++) {
442       unsigned TotalWeight = 0;
443       unsigned NumUnknownEdges = 0;
444       Edge UnknownEdge, SelfReferentialEdge;
445
446       if (i == 0) {
447         // First, visit all predecessor edges.
448         for (auto *Pred : Predecessors[BB]) {
449           Edge E = std::make_pair(Pred, BB);
450           TotalWeight += visitEdge(E, &NumUnknownEdges, &UnknownEdge);
451           if (E.first == E.second)
452             SelfReferentialEdge = E;
453         }
454       } else {
455         // On the second round, visit all successor edges.
456         for (auto *Succ : Successors[BB]) {
457           Edge E = std::make_pair(BB, Succ);
458           TotalWeight += visitEdge(E, &NumUnknownEdges, &UnknownEdge);
459         }
460       }
461
462       // After visiting all the edges, there are three cases that we
463       // can handle immediately:
464       //
465       // - All the edge weights are known (i.e., NumUnknownEdges == 0).
466       //   In this case, we simply check that the sum of all the edges
467       //   is the same as BB's weight. If not, we change BB's weight
468       //   to match. Additionally, if BB had not been visited before,
469       //   we mark it visited.
470       //
471       // - Only one edge is unknown and BB has already been visited.
472       //   In this case, we can compute the weight of the edge by
473       //   subtracting the total block weight from all the known
474       //   edge weights. If the edges weight more than BB, then the
475       //   edge of the last remaining edge is set to zero.
476       //
477       // - There exists a self-referential edge and the weight of BB is
478       //   known. In this case, this edge can be based on BB's weight.
479       //   We add up all the other known edges and set the weight on
480       //   the self-referential edge as we did in the previous case.
481       //
482       // In any other case, we must continue iterating. Eventually,
483       // all edges will get a weight, or iteration will stop when
484       // it reaches SampleProfileMaxPropagateIterations.
485       if (NumUnknownEdges <= 1) {
486         unsigned &BBWeight = BlockWeights[BB];
487         if (NumUnknownEdges == 0) {
488           // If we already know the weight of all edges, the weight of the
489           // basic block can be computed. It should be no larger than the sum
490           // of all edge weights.
491           if (TotalWeight > BBWeight) {
492             BBWeight = TotalWeight;
493             Changed = true;
494             DEBUG(dbgs() << "All edge weights for " << BB->getName()
495                          << " known. Set weight for block: ";
496                   printBlockWeight(dbgs(), BB););
497           }
498           if (VisitedBlocks.insert(BB))
499             Changed = true;
500         } else if (NumUnknownEdges == 1 && VisitedBlocks.count(BB)) {
501           // If there is a single unknown edge and the block has been
502           // visited, then we can compute E's weight.
503           if (BBWeight >= TotalWeight)
504             EdgeWeights[UnknownEdge] = BBWeight - TotalWeight;
505           else
506             EdgeWeights[UnknownEdge] = 0;
507           VisitedEdges.insert(UnknownEdge);
508           Changed = true;
509           DEBUG(dbgs() << "Set weight for edge: ";
510                 printEdgeWeight(dbgs(), UnknownEdge));
511         }
512       } else if (SelfReferentialEdge.first && VisitedBlocks.count(BB)) {
513         unsigned &BBWeight = BlockWeights[BB];
514         // We have a self-referential edge and the weight of BB is known.
515         if (BBWeight >= TotalWeight)
516           EdgeWeights[SelfReferentialEdge] = BBWeight - TotalWeight;
517         else
518           EdgeWeights[SelfReferentialEdge] = 0;
519         VisitedEdges.insert(SelfReferentialEdge);
520         Changed = true;
521         DEBUG(dbgs() << "Set self-referential edge weight to: ";
522               printEdgeWeight(dbgs(), SelfReferentialEdge));
523       }
524     }
525   }
526
527   return Changed;
528 }
529
530 /// \brief Build in/out edge lists for each basic block in the CFG.
531 ///
532 /// We are interested in unique edges. If a block B1 has multiple
533 /// edges to another block B2, we only add a single B1->B2 edge.
534 void SampleProfileLoader::buildEdges(Function &F) {
535   for (auto I = F.begin(), E = F.end(); I != E; ++I) {
536     BasicBlock *B1 = I;
537
538     // Add predecessors for B1.
539     SmallPtrSet<BasicBlock *, 16> Visited;
540     if (!Predecessors[B1].empty())
541       llvm_unreachable("Found a stale predecessors list in a basic block.");
542     for (pred_iterator PI = pred_begin(B1), PE = pred_end(B1); PI != PE; ++PI) {
543       BasicBlock *B2 = *PI;
544       if (Visited.insert(B2))
545         Predecessors[B1].push_back(B2);
546     }
547
548     // Add successors for B1.
549     Visited.clear();
550     if (!Successors[B1].empty())
551       llvm_unreachable("Found a stale successors list in a basic block.");
552     for (succ_iterator SI = succ_begin(B1), SE = succ_end(B1); SI != SE; ++SI) {
553       BasicBlock *B2 = *SI;
554       if (Visited.insert(B2))
555         Successors[B1].push_back(B2);
556     }
557   }
558 }
559
560 /// \brief Propagate weights into edges
561 ///
562 /// The following rules are applied to every block B in the CFG:
563 ///
564 /// - If B has a single predecessor/successor, then the weight
565 ///   of that edge is the weight of the block.
566 ///
567 /// - If all incoming or outgoing edges are known except one, and the
568 ///   weight of the block is already known, the weight of the unknown
569 ///   edge will be the weight of the block minus the sum of all the known
570 ///   edges. If the sum of all the known edges is larger than B's weight,
571 ///   we set the unknown edge weight to zero.
572 ///
573 /// - If there is a self-referential edge, and the weight of the block is
574 ///   known, the weight for that edge is set to the weight of the block
575 ///   minus the weight of the other incoming edges to that block (if
576 ///   known).
577 void SampleProfileLoader::propagateWeights(Function &F) {
578   bool Changed = true;
579   unsigned i = 0;
580
581   // Before propagation starts, build, for each block, a list of
582   // unique predecessors and successors. This is necessary to handle
583   // identical edges in multiway branches. Since we visit all blocks and all
584   // edges of the CFG, it is cleaner to build these lists once at the start
585   // of the pass.
586   buildEdges(F);
587
588   // Propagate until we converge or we go past the iteration limit.
589   while (Changed && i++ < SampleProfileMaxPropagateIterations) {
590     Changed = propagateThroughEdges(F);
591   }
592
593   // Generate MD_prof metadata for every branch instruction using the
594   // edge weights computed during propagation.
595   DEBUG(dbgs() << "\nPropagation complete. Setting branch weights\n");
596   MDBuilder MDB(F.getContext());
597   for (auto I = F.begin(), E = F.end(); I != E; ++I) {
598     BasicBlock *B = I;
599     TerminatorInst *TI = B->getTerminator();
600     if (TI->getNumSuccessors() == 1)
601       continue;
602     if (!isa<BranchInst>(TI) && !isa<SwitchInst>(TI))
603       continue;
604
605     DEBUG(dbgs() << "\nGetting weights for branch at line "
606                  << TI->getDebugLoc().getLine() << ".\n");
607     SmallVector<unsigned, 4> Weights;
608     bool AllWeightsZero = true;
609     for (unsigned I = 0; I < TI->getNumSuccessors(); ++I) {
610       BasicBlock *Succ = TI->getSuccessor(I);
611       Edge E = std::make_pair(B, Succ);
612       unsigned Weight = EdgeWeights[E];
613       DEBUG(dbgs() << "\t"; printEdgeWeight(dbgs(), E));
614       Weights.push_back(Weight);
615       if (Weight != 0)
616         AllWeightsZero = false;
617     }
618
619     // Only set weights if there is at least one non-zero weight.
620     // In any other case, let the analyzer set weights.
621     if (!AllWeightsZero) {
622       DEBUG(dbgs() << "SUCCESS. Found non-zero weights.\n");
623       TI->setMetadata(llvm::LLVMContext::MD_prof,
624                       MDB.createBranchWeights(Weights));
625     } else {
626       DEBUG(dbgs() << "SKIPPED. All branch weights are zero.\n");
627     }
628   }
629 }
630
631 /// \brief Locate the DISubprogram for F.
632 ///
633 /// We look for the first instruction that has a debug annotation
634 /// leading back to \p F.
635 ///
636 /// \returns a valid DISubprogram, if found. Otherwise, it returns an empty
637 /// DISubprogram.
638 static const DISubprogram getDISubprogram(Function &F, const LLVMContext &Ctx) {
639   for (auto I = F.begin(), E = F.end(); I != E; ++I) {
640     BasicBlock *B = I;
641     for (auto &Inst : B->getInstList()) {
642       DebugLoc DLoc = Inst.getDebugLoc();
643       if (DLoc.isUnknown())
644         continue;
645       const MDNode *Scope = DLoc.getScopeNode(Ctx);
646       DISubprogram Subprogram = getDISubprogram(Scope);
647       return Subprogram.describes(&F) ? Subprogram : DISubprogram();
648     }
649   }
650
651   return DISubprogram();
652 }
653
654 /// \brief Get the line number for the function header.
655 ///
656 /// This looks up function \p F in the current compilation unit and
657 /// retrieves the line number where the function is defined. This is
658 /// line 0 for all the samples read from the profile file. Every line
659 /// number is relative to this line.
660 ///
661 /// \param F  Function object to query.
662 ///
663 /// \returns the line number where \p F is defined. If it returns 0,
664 ///          it means that there is no debug information available for \p F.
665 unsigned SampleProfileLoader::getFunctionLoc(Function &F) {
666   const DISubprogram &S = getDISubprogram(F, *Ctx);
667   if (S.isSubprogram())
668     return S.getLineNumber();
669
670   // If could not find the start of \p F, emit a diagnostic to inform the user
671   // about the missed opportunity.
672   F.getContext().diagnose(DiagnosticInfoSampleProfile(
673       "No debug information found in function " + F.getName() +
674           ": Function profile not used",
675       DS_Warning));
676   return 0;
677 }
678
679 /// \brief Generate branch weight metadata for all branches in \p F.
680 ///
681 /// Branch weights are computed out of instruction samples using a
682 /// propagation heuristic. Propagation proceeds in 3 phases:
683 ///
684 /// 1- Assignment of block weights. All the basic blocks in the function
685 ///    are initial assigned the same weight as their most frequently
686 ///    executed instruction.
687 ///
688 /// 2- Creation of equivalence classes. Since samples may be missing from
689 ///    blocks, we can fill in the gaps by setting the weights of all the
690 ///    blocks in the same equivalence class to the same weight. To compute
691 ///    the concept of equivalence, we use dominance and loop information.
692 ///    Two blocks B1 and B2 are in the same equivalence class if B1
693 ///    dominates B2, B2 post-dominates B1 and both are in the same loop.
694 ///
695 /// 3- Propagation of block weights into edges. This uses a simple
696 ///    propagation heuristic. The following rules are applied to every
697 ///    block B in the CFG:
698 ///
699 ///    - If B has a single predecessor/successor, then the weight
700 ///      of that edge is the weight of the block.
701 ///
702 ///    - If all the edges are known except one, and the weight of the
703 ///      block is already known, the weight of the unknown edge will
704 ///      be the weight of the block minus the sum of all the known
705 ///      edges. If the sum of all the known edges is larger than B's weight,
706 ///      we set the unknown edge weight to zero.
707 ///
708 ///    - If there is a self-referential edge, and the weight of the block is
709 ///      known, the weight for that edge is set to the weight of the block
710 ///      minus the weight of the other incoming edges to that block (if
711 ///      known).
712 ///
713 /// Since this propagation is not guaranteed to finalize for every CFG, we
714 /// only allow it to proceed for a limited number of iterations (controlled
715 /// by -sample-profile-max-propagate-iterations).
716 ///
717 /// FIXME: Try to replace this propagation heuristic with a scheme
718 /// that is guaranteed to finalize. A work-list approach similar to
719 /// the standard value propagation algorithm used by SSA-CCP might
720 /// work here.
721 ///
722 /// Once all the branch weights are computed, we emit the MD_prof
723 /// metadata on B using the computed values for each of its branches.
724 ///
725 /// \param F The function to query.
726 ///
727 /// \returns true if \p F was modified. Returns false, otherwise.
728 bool SampleProfileLoader::emitAnnotations(Function &F) {
729   bool Changed = false;
730
731   // Initialize invariants used during computation and propagation.
732   HeaderLineno = getFunctionLoc(F);
733   if (HeaderLineno == 0)
734     return false;
735
736   DEBUG(dbgs() << "Line number for the first instruction in " << F.getName()
737                << ": " << HeaderLineno << "\n");
738
739   // Compute basic block weights.
740   Changed |= computeBlockWeights(F);
741
742   if (Changed) {
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(DominatorTreeWrapperPass)
757 INITIALIZE_PASS_DEPENDENCY(PostDominatorTree)
758 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
759 INITIALIZE_PASS_DEPENDENCY(AddDiscriminators)
760 INITIALIZE_PASS_END(SampleProfileLoader, "sample-profile",
761                     "Sample Profile loader", false, false)
762
763 bool SampleProfileLoader::doInitialization(Module &M) {
764   Reader.reset(new SampleProfileReader(M, Filename));
765   ProfileIsValid = Reader->load();
766   return true;
767 }
768
769 FunctionPass *llvm::createSampleProfileLoaderPass() {
770   return new SampleProfileLoader(SampleProfileFile);
771 }
772
773 FunctionPass *llvm::createSampleProfileLoaderPass(StringRef Name) {
774   return new SampleProfileLoader(Name);
775 }
776
777 bool SampleProfileLoader::runOnFunction(Function &F) {
778   if (!ProfileIsValid)
779     return false;
780
781   DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
782   PDT = &getAnalysis<PostDominatorTree>();
783   LI = &getAnalysis<LoopInfo>();
784   Ctx = &F.getParent()->getContext();
785   Samples = Reader->getSamplesFor(F);
786   if (!Samples->empty())
787     return emitAnnotations(F);
788   return false;
789 }