Sample Profiles - Adjust integer types. Mostly NFC.
[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 *, uint64_t> BlockWeightMap;
69 typedef DenseMap<const BasicBlock *, const BasicBlock *> EquivalenceClassMap;
70 typedef std::pair<const BasicBlock *, const BasicBlock *> Edge;
71 typedef DenseMap<Edge, uint64_t> 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<uint64_t> getInstWeight(const Instruction &I) const;
108   ErrorOr<uint64_t> 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   uint64_t 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 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   uint64_t 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<uint64_t>
220 SampleProfileLoader::getInstWeight(const Instruction &Inst) const {
221   DebugLoc DLoc = Inst.getDebugLoc();
222   if (!DLoc)
223     return std::error_code();
224
225   const FunctionSamples *FS = findFunctionSamples(Inst);
226   if (!FS)
227     return std::error_code();
228
229   const DILocation *DIL = DLoc;
230   unsigned Lineno = DLoc.getLine();
231   unsigned HeaderLineno = DIL->getScope()->getSubprogram()->getLine();
232   if (Lineno < HeaderLineno)
233     return std::error_code();
234
235   ErrorOr<uint64_t> R =
236       FS->findSamplesAt(Lineno - HeaderLineno, DIL->getDiscriminator());
237   if (R)
238     DEBUG(dbgs() << "    " << Lineno << "." << DIL->getDiscriminator() << ":"
239                  << Inst << " (line offset: " << Lineno - HeaderLineno << "."
240                  << DIL->getDiscriminator() << " - weight: " << R.get()
241                  << ")\n");
242   return R;
243 }
244
245 /// \brief Compute the weight of a basic block.
246 ///
247 /// The weight of basic block \p BB is the maximum weight of all the
248 /// instructions in BB.
249 ///
250 /// \param BB The basic block to query.
251 ///
252 /// \returns the weight for \p BB.
253 ErrorOr<uint64_t>
254 SampleProfileLoader::getBlockWeight(const BasicBlock *BB) const {
255   bool Found = false;
256   uint64_t Weight = 0;
257   for (auto &I : BB->getInstList()) {
258     const ErrorOr<uint64_t> &R = getInstWeight(I);
259     if (R && R.get() >= Weight) {
260       Weight = R.get();
261       Found = true;
262     }
263   }
264   if (Found)
265     return Weight;
266   else
267     return std::error_code();
268 }
269
270 /// \brief Compute and store the weights of every basic block.
271 ///
272 /// This populates the BlockWeights map by computing
273 /// the weights of every basic block in the CFG.
274 ///
275 /// \param F The function to query.
276 bool SampleProfileLoader::computeBlockWeights(Function &F) {
277   bool Changed = false;
278   DEBUG(dbgs() << "Block weights\n");
279   for (const auto &BB : F) {
280     ErrorOr<uint64_t> Weight = getBlockWeight(&BB);
281     if (Weight) {
282       BlockWeights[&BB] = Weight.get();
283       VisitedBlocks.insert(&BB);
284       Changed = true;
285     }
286     DEBUG(printBlockWeight(dbgs(), &BB));
287   }
288
289   return Changed;
290 }
291
292 /// \brief Get the FunctionSamples for a call instruction.
293 ///
294 /// The FunctionSamples of a call instruction \p Inst is the inlined
295 /// instance in which that call instruction is calling to. It contains
296 /// all samples that resides in the inlined instance. We first find the
297 /// inlined instance in which the call instruction is from, then we
298 /// traverse its children to find the callsite with the matching
299 /// location and callee function name.
300 ///
301 /// \param Inst Call instruction to query.
302 ///
303 /// \returns The FunctionSamples pointer to the inlined instance.
304 const FunctionSamples *
305 SampleProfileLoader::findCalleeFunctionSamples(const CallInst &Inst) const {
306   const DILocation *DIL = Inst.getDebugLoc();
307   if (!DIL) {
308     return nullptr;
309   }
310   DISubprogram *SP = DIL->getScope()->getSubprogram();
311   if (!SP || DIL->getLine() < SP->getLine())
312     return nullptr;
313
314   Function *CalleeFunc = Inst.getCalledFunction();
315   if (!CalleeFunc) {
316     return nullptr;
317   }
318
319   StringRef CalleeName = CalleeFunc->getName();
320   const FunctionSamples *FS = findFunctionSamples(Inst);
321   if (FS == nullptr)
322     return nullptr;
323
324   return FS->findFunctionSamplesAt(CallsiteLocation(
325       DIL->getLine() - SP->getLine(), DIL->getDiscriminator(), CalleeName));
326 }
327
328 /// \brief Get the FunctionSamples for an instruction.
329 ///
330 /// The FunctionSamples of an instruction \p Inst is the inlined instance
331 /// in which that instruction is coming from. We traverse the inline stack
332 /// of that instruction, and match it with the tree nodes in the profile.
333 ///
334 /// \param Inst Instruction to query.
335 ///
336 /// \returns the FunctionSamples pointer to the inlined instance.
337 const FunctionSamples *
338 SampleProfileLoader::findFunctionSamples(const Instruction &Inst) const {
339   SmallVector<CallsiteLocation, 10> S;
340   const DILocation *DIL = Inst.getDebugLoc();
341   if (!DIL) {
342     return Samples;
343   }
344   StringRef CalleeName;
345   for (const DILocation *DIL = Inst.getDebugLoc(); DIL;
346        DIL = DIL->getInlinedAt()) {
347     DISubprogram *SP = DIL->getScope()->getSubprogram();
348     if (!SP || DIL->getLine() < SP->getLine())
349       return nullptr;
350     if (!CalleeName.empty()) {
351       S.push_back(CallsiteLocation(DIL->getLine() - SP->getLine(),
352                                    DIL->getDiscriminator(), CalleeName));
353     }
354     CalleeName = SP->getLinkageName();
355   }
356   if (S.size() == 0)
357     return Samples;
358   const FunctionSamples *FS = Samples;
359   for (int i = S.size() - 1; i >= 0 && FS != nullptr; i--) {
360     FS = FS->findFunctionSamplesAt(S[i]);
361   }
362   return FS;
363 }
364
365 /// \brief Iteratively inline hot callsites of a function.
366 ///
367 /// Iteratively traverse all callsites of the function \p F, and find if
368 /// the corresponding inlined instance exists and is hot in profile. If
369 /// it is hot enough, inline the callsites and adds new callsites of the
370 /// callee into the caller.
371 ///
372 /// TODO: investigate the possibility of not invoking InlineFunction directly.
373 ///
374 /// \param F function to perform iterative inlining.
375 ///
376 /// \returns True if there is any inline happened.
377 bool SampleProfileLoader::inlineHotFunctions(Function &F) {
378   bool Changed = false;
379   while (true) {
380     bool LocalChanged = false;
381     SmallVector<CallInst *, 10> CIS;
382     for (auto &BB : F) {
383       for (auto &I : BB.getInstList()) {
384         CallInst *CI = dyn_cast<CallInst>(&I);
385         if (CI) {
386           const FunctionSamples *FS = findCalleeFunctionSamples(*CI);
387           if (FS && FS->getTotalSamples() > 0) {
388             CIS.push_back(CI);
389           }
390         }
391       }
392     }
393     for (auto CI : CIS) {
394       InlineFunctionInfo IFI;
395       if (InlineFunction(CI, IFI))
396         LocalChanged = true;
397     }
398     if (LocalChanged) {
399       Changed = true;
400     } else {
401       break;
402     }
403   }
404   return Changed;
405 }
406
407 /// \brief Find equivalence classes for the given block.
408 ///
409 /// This finds all the blocks that are guaranteed to execute the same
410 /// number of times as \p BB1. To do this, it traverses all the
411 /// descendants of \p BB1 in the dominator or post-dominator tree.
412 ///
413 /// A block BB2 will be in the same equivalence class as \p BB1 if
414 /// the following holds:
415 ///
416 /// 1- \p BB1 is a descendant of BB2 in the opposite tree. So, if BB2
417 ///    is a descendant of \p BB1 in the dominator tree, then BB2 should
418 ///    dominate BB1 in the post-dominator tree.
419 ///
420 /// 2- Both BB2 and \p BB1 must be in the same loop.
421 ///
422 /// For every block BB2 that meets those two requirements, we set BB2's
423 /// equivalence class to \p BB1.
424 ///
425 /// \param BB1  Block to check.
426 /// \param Descendants  Descendants of \p BB1 in either the dom or pdom tree.
427 /// \param DomTree  Opposite dominator tree. If \p Descendants is filled
428 ///                 with blocks from \p BB1's dominator tree, then
429 ///                 this is the post-dominator tree, and vice versa.
430 void SampleProfileLoader::findEquivalencesFor(
431     BasicBlock *BB1, SmallVector<BasicBlock *, 8> Descendants,
432     DominatorTreeBase<BasicBlock> *DomTree) {
433   const BasicBlock *EC = EquivalenceClass[BB1];
434   uint64_t Weight = BlockWeights[EC];
435   for (const auto *BB2 : Descendants) {
436     bool IsDomParent = DomTree->dominates(BB2, BB1);
437     bool IsInSameLoop = LI->getLoopFor(BB1) == LI->getLoopFor(BB2);
438     if (BB1 != BB2 && IsDomParent && IsInSameLoop) {
439       EquivalenceClass[BB2] = EC;
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       Weight = std::max(Weight, BlockWeights[BB2]);
450     }
451   }
452   BlockWeights[EC] = Weight;
453 }
454
455 /// \brief Find equivalence classes.
456 ///
457 /// Since samples may be missing from blocks, we can fill in the gaps by setting
458 /// the weights of all the blocks in the same equivalence class to the same
459 /// weight. To compute the concept of equivalence, we use dominance and loop
460 /// information. Two blocks B1 and B2 are in the same equivalence class if B1
461 /// dominates B2, B2 post-dominates B1 and both are in the same loop.
462 ///
463 /// \param F The function to query.
464 void SampleProfileLoader::findEquivalenceClasses(Function &F) {
465   SmallVector<BasicBlock *, 8> DominatedBBs;
466   DEBUG(dbgs() << "\nBlock equivalence classes\n");
467   // Find equivalence sets based on dominance and post-dominance information.
468   for (auto &BB : F) {
469     BasicBlock *BB1 = &BB;
470
471     // Compute BB1's equivalence class once.
472     if (EquivalenceClass.count(BB1)) {
473       DEBUG(printBlockEquivalence(dbgs(), BB1));
474       continue;
475     }
476
477     // By default, blocks are in their own equivalence class.
478     EquivalenceClass[BB1] = BB1;
479
480     // Traverse all the blocks dominated by BB1. We are looking for
481     // every basic block BB2 such that:
482     //
483     // 1- BB1 dominates BB2.
484     // 2- BB2 post-dominates BB1.
485     // 3- BB1 and BB2 are in the same loop nest.
486     //
487     // If all those conditions hold, it means that BB2 is executed
488     // as many times as BB1, so they are placed in the same equivalence
489     // class by making BB2's equivalence class be BB1.
490     DominatedBBs.clear();
491     DT->getDescendants(BB1, DominatedBBs);
492     findEquivalencesFor(BB1, DominatedBBs, PDT.get());
493
494     DEBUG(printBlockEquivalence(dbgs(), BB1));
495   }
496
497   // Assign weights to equivalence classes.
498   //
499   // All the basic blocks in the same equivalence class will execute
500   // the same number of times. Since we know that the head block in
501   // each equivalence class has the largest weight, assign that weight
502   // to all the blocks in that equivalence class.
503   DEBUG(dbgs() << "\nAssign the same weight to all blocks in the same class\n");
504   for (auto &BI : F) {
505     const BasicBlock *BB = &BI;
506     const BasicBlock *EquivBB = EquivalenceClass[BB];
507     if (BB != EquivBB)
508       BlockWeights[BB] = BlockWeights[EquivBB];
509     DEBUG(printBlockWeight(dbgs(), BB));
510   }
511 }
512
513 /// \brief Visit the given edge to decide if it has a valid weight.
514 ///
515 /// If \p E has not been visited before, we copy to \p UnknownEdge
516 /// and increment the count of unknown edges.
517 ///
518 /// \param E  Edge to visit.
519 /// \param NumUnknownEdges  Current number of unknown edges.
520 /// \param UnknownEdge  Set if E has not been visited before.
521 ///
522 /// \returns E's weight, if known. Otherwise, return 0.
523 uint64_t SampleProfileLoader::visitEdge(Edge E, unsigned *NumUnknownEdges,
524                                         Edge *UnknownEdge) {
525   if (!VisitedEdges.count(E)) {
526     (*NumUnknownEdges)++;
527     *UnknownEdge = E;
528     return 0;
529   }
530
531   return EdgeWeights[E];
532 }
533
534 /// \brief Propagate weights through incoming/outgoing edges.
535 ///
536 /// If the weight of a basic block is known, and there is only one edge
537 /// with an unknown weight, we can calculate the weight of that edge.
538 ///
539 /// Similarly, if all the edges have a known count, we can calculate the
540 /// count of the basic block, if needed.
541 ///
542 /// \param F  Function to process.
543 ///
544 /// \returns  True if new weights were assigned to edges or blocks.
545 bool SampleProfileLoader::propagateThroughEdges(Function &F) {
546   bool Changed = false;
547   DEBUG(dbgs() << "\nPropagation through edges\n");
548   for (const auto &BI : F) {
549     const BasicBlock *BB = &BI;
550     const BasicBlock *EC = EquivalenceClass[BB];
551
552     // Visit all the predecessor and successor edges to determine
553     // which ones have a weight assigned already. Note that it doesn't
554     // matter that we only keep track of a single unknown edge. The
555     // only case we are interested in handling is when only a single
556     // edge is unknown (see setEdgeOrBlockWeight).
557     for (unsigned i = 0; i < 2; i++) {
558       uint64_t TotalWeight = 0;
559       unsigned NumUnknownEdges = 0;
560       Edge UnknownEdge, SelfReferentialEdge;
561
562       if (i == 0) {
563         // First, visit all predecessor edges.
564         for (auto *Pred : Predecessors[BB]) {
565           Edge E = std::make_pair(Pred, BB);
566           TotalWeight += visitEdge(E, &NumUnknownEdges, &UnknownEdge);
567           if (E.first == E.second)
568             SelfReferentialEdge = E;
569         }
570       } else {
571         // On the second round, visit all successor edges.
572         for (auto *Succ : Successors[BB]) {
573           Edge E = std::make_pair(BB, Succ);
574           TotalWeight += visitEdge(E, &NumUnknownEdges, &UnknownEdge);
575         }
576       }
577
578       // After visiting all the edges, there are three cases that we
579       // can handle immediately:
580       //
581       // - All the edge weights are known (i.e., NumUnknownEdges == 0).
582       //   In this case, we simply check that the sum of all the edges
583       //   is the same as BB's weight. If not, we change BB's weight
584       //   to match. Additionally, if BB had not been visited before,
585       //   we mark it visited.
586       //
587       // - Only one edge is unknown and BB has already been visited.
588       //   In this case, we can compute the weight of the edge by
589       //   subtracting the total block weight from all the known
590       //   edge weights. If the edges weight more than BB, then the
591       //   edge of the last remaining edge is set to zero.
592       //
593       // - There exists a self-referential edge and the weight of BB is
594       //   known. In this case, this edge can be based on BB's weight.
595       //   We add up all the other known edges and set the weight on
596       //   the self-referential edge as we did in the previous case.
597       //
598       // In any other case, we must continue iterating. Eventually,
599       // all edges will get a weight, or iteration will stop when
600       // it reaches SampleProfileMaxPropagateIterations.
601       if (NumUnknownEdges <= 1) {
602         uint64_t &BBWeight = BlockWeights[EC];
603         if (NumUnknownEdges == 0) {
604           // If we already know the weight of all edges, the weight of the
605           // basic block can be computed. It should be no larger than the sum
606           // of all edge weights.
607           if (TotalWeight > BBWeight) {
608             BBWeight = TotalWeight;
609             Changed = true;
610             DEBUG(dbgs() << "All edge weights for " << BB->getName()
611                          << " known. Set weight for block: ";
612                   printBlockWeight(dbgs(), BB););
613           }
614           if (VisitedBlocks.insert(EC).second)
615             Changed = true;
616         } else if (NumUnknownEdges == 1 && VisitedBlocks.count(EC)) {
617           // If there is a single unknown edge and the block has been
618           // visited, then we can compute E's weight.
619           if (BBWeight >= TotalWeight)
620             EdgeWeights[UnknownEdge] = BBWeight - TotalWeight;
621           else
622             EdgeWeights[UnknownEdge] = 0;
623           VisitedEdges.insert(UnknownEdge);
624           Changed = true;
625           DEBUG(dbgs() << "Set weight for edge: ";
626                 printEdgeWeight(dbgs(), UnknownEdge));
627         }
628       } else if (SelfReferentialEdge.first && VisitedBlocks.count(EC)) {
629         uint64_t &BBWeight = BlockWeights[BB];
630         // We have a self-referential edge and the weight of BB is known.
631         if (BBWeight >= TotalWeight)
632           EdgeWeights[SelfReferentialEdge] = BBWeight - TotalWeight;
633         else
634           EdgeWeights[SelfReferentialEdge] = 0;
635         VisitedEdges.insert(SelfReferentialEdge);
636         Changed = true;
637         DEBUG(dbgs() << "Set self-referential edge weight to: ";
638               printEdgeWeight(dbgs(), SelfReferentialEdge));
639       }
640     }
641   }
642
643   return Changed;
644 }
645
646 /// \brief Build in/out edge lists for each basic block in the CFG.
647 ///
648 /// We are interested in unique edges. If a block B1 has multiple
649 /// edges to another block B2, we only add a single B1->B2 edge.
650 void SampleProfileLoader::buildEdges(Function &F) {
651   for (auto &BI : F) {
652     BasicBlock *B1 = &BI;
653
654     // Add predecessors for B1.
655     SmallPtrSet<BasicBlock *, 16> Visited;
656     if (!Predecessors[B1].empty())
657       llvm_unreachable("Found a stale predecessors list in a basic block.");
658     for (pred_iterator PI = pred_begin(B1), PE = pred_end(B1); PI != PE; ++PI) {
659       BasicBlock *B2 = *PI;
660       if (Visited.insert(B2).second)
661         Predecessors[B1].push_back(B2);
662     }
663
664     // Add successors for B1.
665     Visited.clear();
666     if (!Successors[B1].empty())
667       llvm_unreachable("Found a stale successors list in a basic block.");
668     for (succ_iterator SI = succ_begin(B1), SE = succ_end(B1); SI != SE; ++SI) {
669       BasicBlock *B2 = *SI;
670       if (Visited.insert(B2).second)
671         Successors[B1].push_back(B2);
672     }
673   }
674 }
675
676 /// \brief Propagate weights into edges
677 ///
678 /// The following rules are applied to every block BB in the CFG:
679 ///
680 /// - If BB has a single predecessor/successor, then the weight
681 ///   of that edge is the weight of the block.
682 ///
683 /// - If all incoming or outgoing edges are known except one, and the
684 ///   weight of the block is already known, the weight of the unknown
685 ///   edge will be the weight of the block minus the sum of all the known
686 ///   edges. If the sum of all the known edges is larger than BB's weight,
687 ///   we set the unknown edge weight to zero.
688 ///
689 /// - If there is a self-referential edge, and the weight of the block is
690 ///   known, the weight for that edge is set to the weight of the block
691 ///   minus the weight of the other incoming edges to that block (if
692 ///   known).
693 void SampleProfileLoader::propagateWeights(Function &F) {
694   bool Changed = true;
695   unsigned I = 0;
696
697   // Add an entry count to the function using the samples gathered
698   // at the function entry.
699   F.setEntryCount(Samples->getHeadSamples());
700
701   // Before propagation starts, build, for each block, a list of
702   // unique predecessors and successors. This is necessary to handle
703   // identical edges in multiway branches. Since we visit all blocks and all
704   // edges of the CFG, it is cleaner to build these lists once at the start
705   // of the pass.
706   buildEdges(F);
707
708   // Propagate until we converge or we go past the iteration limit.
709   while (Changed && I++ < SampleProfileMaxPropagateIterations) {
710     Changed = propagateThroughEdges(F);
711   }
712
713   // Generate MD_prof metadata for every branch instruction using the
714   // edge weights computed during propagation.
715   DEBUG(dbgs() << "\nPropagation complete. Setting branch weights\n");
716   MDBuilder MDB(F.getContext());
717   for (auto &BI : F) {
718     BasicBlock *BB = &BI;
719     TerminatorInst *TI = BB->getTerminator();
720     if (TI->getNumSuccessors() == 1)
721       continue;
722     if (!isa<BranchInst>(TI) && !isa<SwitchInst>(TI))
723       continue;
724
725     DEBUG(dbgs() << "\nGetting weights for branch at line "
726                  << TI->getDebugLoc().getLine() << ".\n");
727     SmallVector<uint32_t, 4> Weights;
728     bool AllWeightsZero = true;
729     for (unsigned I = 0; I < TI->getNumSuccessors(); ++I) {
730       BasicBlock *Succ = TI->getSuccessor(I);
731       Edge E = std::make_pair(BB, Succ);
732       uint64_t Weight = EdgeWeights[E];
733       DEBUG(dbgs() << "\t"; printEdgeWeight(dbgs(), E));
734       // Use uint32_t saturated arithmetic to adjust the incoming weights,
735       // if needed. Sample counts in profiles are 64-bit unsigned values,
736       // but internally branch weights are expressed as 32-bit values.
737       if (Weight > std::numeric_limits<uint32_t>::max()) {
738         DEBUG(dbgs() << " (saturated due to uint32_t overflow)");
739         Weight = std::numeric_limits<uint32_t>::max();
740       }
741       Weights.push_back(static_cast<uint32_t>(Weight));
742       if (Weight != 0)
743         AllWeightsZero = false;
744     }
745
746     // Only set weights if there is at least one non-zero weight.
747     // In any other case, let the analyzer set weights.
748     if (!AllWeightsZero) {
749       DEBUG(dbgs() << "SUCCESS. Found non-zero weights.\n");
750       TI->setMetadata(llvm::LLVMContext::MD_prof,
751                       MDB.createBranchWeights(Weights));
752     } else {
753       DEBUG(dbgs() << "SKIPPED. All branch weights are zero.\n");
754     }
755   }
756 }
757
758 /// \brief Get the line number for the function header.
759 ///
760 /// This looks up function \p F in the current compilation unit and
761 /// retrieves the line number where the function is defined. This is
762 /// line 0 for all the samples read from the profile file. Every line
763 /// number is relative to this line.
764 ///
765 /// \param F  Function object to query.
766 ///
767 /// \returns the line number where \p F is defined. If it returns 0,
768 ///          it means that there is no debug information available for \p F.
769 unsigned SampleProfileLoader::getFunctionLoc(Function &F) {
770   if (DISubprogram *S = getDISubprogram(&F))
771     return S->getLine();
772
773   // If could not find the start of \p F, emit a diagnostic to inform the user
774   // about the missed opportunity.
775   F.getContext().diagnose(DiagnosticInfoSampleProfile(
776       "No debug information found in function " + F.getName() +
777           ": Function profile not used",
778       DS_Warning));
779   return 0;
780 }
781
782 void SampleProfileLoader::computeDominanceAndLoopInfo(Function &F) {
783   DT.reset(new DominatorTree);
784   DT->recalculate(F);
785
786   PDT.reset(new DominatorTreeBase<BasicBlock>(true));
787   PDT->recalculate(F);
788
789   LI.reset(new LoopInfo);
790   LI->analyze(*DT);
791 }
792
793 /// \brief Generate branch weight metadata for all branches in \p F.
794 ///
795 /// Branch weights are computed out of instruction samples using a
796 /// propagation heuristic. Propagation proceeds in 3 phases:
797 ///
798 /// 1- Assignment of block weights. All the basic blocks in the function
799 ///    are initial assigned the same weight as their most frequently
800 ///    executed instruction.
801 ///
802 /// 2- Creation of equivalence classes. Since samples may be missing from
803 ///    blocks, we can fill in the gaps by setting the weights of all the
804 ///    blocks in the same equivalence class to the same weight. To compute
805 ///    the concept of equivalence, we use dominance and loop information.
806 ///    Two blocks B1 and B2 are in the same equivalence class if B1
807 ///    dominates B2, B2 post-dominates B1 and both are in the same loop.
808 ///
809 /// 3- Propagation of block weights into edges. This uses a simple
810 ///    propagation heuristic. The following rules are applied to every
811 ///    block BB in the CFG:
812 ///
813 ///    - If BB has a single predecessor/successor, then the weight
814 ///      of that edge is the weight of the block.
815 ///
816 ///    - If all the edges are known except one, and the weight of the
817 ///      block is already known, the weight of the unknown edge will
818 ///      be the weight of the block minus the sum of all the known
819 ///      edges. If the sum of all the known edges is larger than BB's weight,
820 ///      we set the unknown edge weight to zero.
821 ///
822 ///    - If there is a self-referential edge, and the weight of the block is
823 ///      known, the weight for that edge is set to the weight of the block
824 ///      minus the weight of the other incoming edges to that block (if
825 ///      known).
826 ///
827 /// Since this propagation is not guaranteed to finalize for every CFG, we
828 /// only allow it to proceed for a limited number of iterations (controlled
829 /// by -sample-profile-max-propagate-iterations).
830 ///
831 /// FIXME: Try to replace this propagation heuristic with a scheme
832 /// that is guaranteed to finalize. A work-list approach similar to
833 /// the standard value propagation algorithm used by SSA-CCP might
834 /// work here.
835 ///
836 /// Once all the branch weights are computed, we emit the MD_prof
837 /// metadata on BB using the computed values for each of its branches.
838 ///
839 /// \param F The function to query.
840 ///
841 /// \returns true if \p F was modified. Returns false, otherwise.
842 bool SampleProfileLoader::emitAnnotations(Function &F) {
843   bool Changed = false;
844
845   if (getFunctionLoc(F) == 0)
846     return false;
847
848   DEBUG(dbgs() << "Line number for the first instruction in " << F.getName()
849                << ": " << getFunctionLoc(F) << "\n");
850
851   Changed |= inlineHotFunctions(F);
852
853   // Compute basic block weights.
854   Changed |= computeBlockWeights(F);
855
856   if (Changed) {
857     // Compute dominance and loop info needed for propagation.
858     computeDominanceAndLoopInfo(F);
859
860     // Find equivalence classes.
861     findEquivalenceClasses(F);
862
863     // Propagate weights to all edges.
864     propagateWeights(F);
865   }
866
867   return Changed;
868 }
869
870 char SampleProfileLoader::ID = 0;
871 INITIALIZE_PASS_BEGIN(SampleProfileLoader, "sample-profile",
872                       "Sample Profile loader", false, false)
873 INITIALIZE_PASS_DEPENDENCY(AddDiscriminators)
874 INITIALIZE_PASS_END(SampleProfileLoader, "sample-profile",
875                     "Sample Profile loader", false, false)
876
877 bool SampleProfileLoader::doInitialization(Module &M) {
878   auto &Ctx = M.getContext();
879   auto ReaderOrErr = SampleProfileReader::create(Filename, Ctx);
880   if (std::error_code EC = ReaderOrErr.getError()) {
881     std::string Msg = "Could not open profile: " + EC.message();
882     Ctx.diagnose(DiagnosticInfoSampleProfile(Filename.data(), Msg));
883     return false;
884   }
885   Reader = std::move(ReaderOrErr.get());
886   ProfileIsValid = (Reader->read() == sampleprof_error::success);
887   return true;
888 }
889
890 ModulePass *llvm::createSampleProfileLoaderPass() {
891   return new SampleProfileLoader(SampleProfileFile);
892 }
893
894 ModulePass *llvm::createSampleProfileLoaderPass(StringRef Name) {
895   return new SampleProfileLoader(Name);
896 }
897
898 bool SampleProfileLoader::runOnModule(Module &M) {
899   bool retval = false;
900   for (auto &F : M)
901     if (!F.isDeclaration())
902       retval |= runOnFunction(F);
903   return retval;
904 }
905
906 bool SampleProfileLoader::runOnFunction(Function &F) {
907   if (!ProfileIsValid)
908     return false;
909
910   Samples = Reader->getSamplesFor(F);
911   if (!Samples->empty())
912     return emitAnnotations(F);
913   return false;
914 }