20bfac954a55dcee5ff1a5246805bb8115fed3d1
[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 static cl::opt<unsigned> SampleProfileCoverage(
67     "sample-profile-check-coverage", cl::init(0), cl::value_desc("N"),
68     cl::desc("Emit a warning if less than N% of samples in the input profile "
69              "are matched to the IR."));
70
71 namespace {
72 typedef DenseMap<const BasicBlock *, uint64_t> BlockWeightMap;
73 typedef DenseMap<const BasicBlock *, const BasicBlock *> EquivalenceClassMap;
74 typedef std::pair<const BasicBlock *, const BasicBlock *> Edge;
75 typedef DenseMap<Edge, uint64_t> EdgeWeightMap;
76 typedef DenseMap<const BasicBlock *, SmallVector<const BasicBlock *, 8>>
77     BlockEdgeMap;
78
79 /// \brief Sample profile pass.
80 ///
81 /// This pass reads profile data from the file specified by
82 /// -sample-profile-file and annotates every affected function with the
83 /// profile information found in that file.
84 class SampleProfileLoader : public ModulePass {
85 public:
86   // Class identification, replacement for typeinfo
87   static char ID;
88
89   SampleProfileLoader(StringRef Name = SampleProfileFile)
90       : ModulePass(ID), DT(nullptr), PDT(nullptr), LI(nullptr), Reader(),
91         Samples(nullptr), Filename(Name), ProfileIsValid(false) {
92     initializeSampleProfileLoaderPass(*PassRegistry::getPassRegistry());
93   }
94
95   bool doInitialization(Module &M) override;
96
97   void dump() { Reader->dump(); }
98
99   const char *getPassName() const override { return "Sample profile pass"; }
100
101   bool runOnModule(Module &M) override;
102
103   void getAnalysisUsage(AnalysisUsage &AU) const override {
104     AU.setPreservesCFG();
105   }
106
107 protected:
108   bool runOnFunction(Function &F);
109   unsigned getFunctionLoc(Function &F);
110   bool emitAnnotations(Function &F);
111   ErrorOr<uint64_t> getInstWeight(const Instruction &I) const;
112   ErrorOr<uint64_t> getBlockWeight(const BasicBlock *BB) const;
113   const FunctionSamples *findCalleeFunctionSamples(const CallInst &I) const;
114   const FunctionSamples *findFunctionSamples(const Instruction &I) const;
115   bool inlineHotFunctions(Function &F);
116   void printEdgeWeight(raw_ostream &OS, Edge E);
117   void printBlockWeight(raw_ostream &OS, const BasicBlock *BB) const;
118   void printBlockEquivalence(raw_ostream &OS, const BasicBlock *BB);
119   bool computeBlockWeights(Function &F);
120   void findEquivalenceClasses(Function &F);
121   void findEquivalencesFor(BasicBlock *BB1,
122                            SmallVector<BasicBlock *, 8> Descendants,
123                            DominatorTreeBase<BasicBlock> *DomTree);
124   void propagateWeights(Function &F);
125   uint64_t visitEdge(Edge E, unsigned *NumUnknownEdges, Edge *UnknownEdge);
126   void buildEdges(Function &F);
127   bool propagateThroughEdges(Function &F);
128   void computeDominanceAndLoopInfo(Function &F);
129   unsigned getOffset(unsigned L, unsigned H) const;
130   void clearFunctionData();
131
132   /// \brief Map basic blocks to their computed weights.
133   ///
134   /// The weight of a basic block is defined to be the maximum
135   /// of all the instruction weights in that block.
136   BlockWeightMap BlockWeights;
137
138   /// \brief Map edges to their computed weights.
139   ///
140   /// Edge weights are computed by propagating basic block weights in
141   /// SampleProfile::propagateWeights.
142   EdgeWeightMap EdgeWeights;
143
144   /// \brief Set of visited blocks during propagation.
145   SmallPtrSet<const BasicBlock *, 128> VisitedBlocks;
146
147   /// \brief Set of visited edges during propagation.
148   SmallSet<Edge, 128> VisitedEdges;
149
150   /// \brief Equivalence classes for block weights.
151   ///
152   /// Two blocks BB1 and BB2 are in the same equivalence class if they
153   /// dominate and post-dominate each other, and they are in the same loop
154   /// nest. When this happens, the two blocks are guaranteed to execute
155   /// the same number of times.
156   EquivalenceClassMap EquivalenceClass;
157
158   /// \brief Dominance, post-dominance and loop information.
159   std::unique_ptr<DominatorTree> DT;
160   std::unique_ptr<DominatorTreeBase<BasicBlock>> PDT;
161   std::unique_ptr<LoopInfo> LI;
162
163   /// \brief Predecessors for each basic block in the CFG.
164   BlockEdgeMap Predecessors;
165
166   /// \brief Successors for each basic block in the CFG.
167   BlockEdgeMap Successors;
168
169   /// \brief Profile reader object.
170   std::unique_ptr<SampleProfileReader> Reader;
171
172   /// \brief Samples collected for the body of this function.
173   FunctionSamples *Samples;
174
175   /// \brief Name of the profile file to load.
176   StringRef Filename;
177
178   /// \brief Flag indicating whether the profile input loaded successfully.
179   bool ProfileIsValid;
180 };
181
182 class SampleCoverageTracker {
183 public:
184   SampleCoverageTracker() : SampleCoverage() {}
185
186   bool markSamplesUsed(const FunctionSamples *Samples, uint32_t LineOffset,
187                        uint32_t Discriminator);
188   unsigned computeCoverage(unsigned Used, unsigned Total) const;
189   unsigned countUsedSamples(const FunctionSamples *Samples) const;
190   unsigned countBodySamples(const FunctionSamples *Samples) const;
191
192 private:
193   typedef DenseMap<LineLocation, unsigned> BodySampleCoverageMap;
194   typedef DenseMap<const FunctionSamples *, BodySampleCoverageMap>
195       FunctionSamplesCoverageMap;
196
197   /// Coverage map for sampling records.
198   ///
199   /// This map keeps a record of sampling records that have been matched to
200   /// an IR instruction. This is used to detect some form of staleness in
201   /// profiles (see flag -sample-profile-check-coverage).
202   ///
203   /// Each entry in the map corresponds to a FunctionSamples instance.  This is
204   /// another map that counts how many times the sample record at the
205   /// given location has been used.
206   FunctionSamplesCoverageMap SampleCoverage;
207 };
208
209 SampleCoverageTracker CoverageTracker;
210 }
211
212 /// Mark as used the sample record for the given function samples at
213 /// (LineOffset, Discriminator).
214 ///
215 /// \returns true if this is the first time we mark the given record.
216 bool SampleCoverageTracker::markSamplesUsed(const FunctionSamples *Samples,
217                                             uint32_t LineOffset,
218                                             uint32_t Discriminator) {
219   LineLocation Loc(LineOffset, Discriminator);
220   unsigned &Count = SampleCoverage[Samples][Loc];
221   return ++Count == 1;
222 }
223
224 /// Return the number of sample records that were applied from this profile.
225 unsigned
226 SampleCoverageTracker::countUsedSamples(const FunctionSamples *Samples) const {
227   auto I = SampleCoverage.find(Samples);
228
229   // The size of the coverage map for Samples represents the number of records
230   // that were marked used at least once.
231   unsigned Count = (I != SampleCoverage.end()) ? I->second.size() : 0;
232
233   // If there are inlined callsites in this function, count the samples found
234   // in the respective bodies. However, do not bother counting callees with 0
235   // total samples, these are callees that were never invoked at runtime.
236   for (const auto &I : Samples->getCallsiteSamples()) {
237     const FunctionSamples *CalleeSamples = &I.second;
238     if (CalleeSamples->getTotalSamples() > 0)
239       Count += countUsedSamples(CalleeSamples);
240   }
241
242   return Count;
243 }
244
245 /// Return the number of sample records in the body of this profile.
246 ///
247 /// The count includes all the samples in inlined callees. However, callsites
248 /// with 0 samples indicate inlined function calls that were never actually
249 /// invoked at runtime. Ignore these callsites for coverage purposes.
250 unsigned
251 SampleCoverageTracker::countBodySamples(const FunctionSamples *Samples) const {
252   unsigned Count = Samples->getBodySamples().size();
253
254   // Count all the callsites with non-zero samples.
255   for (const auto &I : Samples->getCallsiteSamples()) {
256     const FunctionSamples *CalleeSamples = &I.second;
257     if (CalleeSamples->getTotalSamples() > 0)
258       Count += countBodySamples(CalleeSamples);
259   }
260
261   return Count;
262 }
263
264 /// Return the fraction of sample records used in this profile.
265 ///
266 /// The returned value is an unsigned integer in the range 0-100 indicating
267 /// the percentage of sample records that were used while applying this
268 /// profile to the associated function.
269 unsigned SampleCoverageTracker::computeCoverage(unsigned Used,
270                                                 unsigned Total) const {
271   assert(Used <= Total &&
272          "number of used records cannot exceed the total number of records");
273   return Total > 0 ? Used * 100 / Total : 100;
274 }
275
276 /// Clear all the per-function data used to load samples and propagate weights.
277 void SampleProfileLoader::clearFunctionData() {
278   BlockWeights.clear();
279   EdgeWeights.clear();
280   VisitedBlocks.clear();
281   VisitedEdges.clear();
282   EquivalenceClass.clear();
283   DT = nullptr;
284   PDT = nullptr;
285   LI = nullptr;
286   Predecessors.clear();
287   Successors.clear();
288 }
289
290 /// \brief Returns the offset of lineno \p L to head_lineno \p H
291 ///
292 /// \param L  Lineno
293 /// \param H  Header lineno of the function
294 ///
295 /// \returns offset to the header lineno. 16 bits are used to represent offset.
296 /// We assume that a single function will not exceed 65535 LOC.
297 unsigned SampleProfileLoader::getOffset(unsigned L, unsigned H) const {
298   return (L - H) & 0xffff;
299 }
300
301 /// \brief Print the weight of edge \p E on stream \p OS.
302 ///
303 /// \param OS  Stream to emit the output to.
304 /// \param E  Edge to print.
305 void SampleProfileLoader::printEdgeWeight(raw_ostream &OS, Edge E) {
306   OS << "weight[" << E.first->getName() << "->" << E.second->getName()
307      << "]: " << EdgeWeights[E] << "\n";
308 }
309
310 /// \brief Print the equivalence class of block \p BB on stream \p OS.
311 ///
312 /// \param OS  Stream to emit the output to.
313 /// \param BB  Block to print.
314 void SampleProfileLoader::printBlockEquivalence(raw_ostream &OS,
315                                                 const BasicBlock *BB) {
316   const BasicBlock *Equiv = EquivalenceClass[BB];
317   OS << "equivalence[" << BB->getName()
318      << "]: " << ((Equiv) ? EquivalenceClass[BB]->getName() : "NONE") << "\n";
319 }
320
321 /// \brief Print the weight of block \p BB on stream \p OS.
322 ///
323 /// \param OS  Stream to emit the output to.
324 /// \param BB  Block to print.
325 void SampleProfileLoader::printBlockWeight(raw_ostream &OS,
326                                            const BasicBlock *BB) const {
327   const auto &I = BlockWeights.find(BB);
328   uint64_t W = (I == BlockWeights.end() ? 0 : I->second);
329   OS << "weight[" << BB->getName() << "]: " << W << "\n";
330 }
331
332 /// \brief Get the weight for an instruction.
333 ///
334 /// The "weight" of an instruction \p Inst is the number of samples
335 /// collected on that instruction at runtime. To retrieve it, we
336 /// need to compute the line number of \p Inst relative to the start of its
337 /// function. We use HeaderLineno to compute the offset. We then
338 /// look up the samples collected for \p Inst using BodySamples.
339 ///
340 /// \param Inst Instruction to query.
341 ///
342 /// \returns the weight of \p Inst.
343 ErrorOr<uint64_t>
344 SampleProfileLoader::getInstWeight(const Instruction &Inst) const {
345   DebugLoc DLoc = Inst.getDebugLoc();
346   if (!DLoc)
347     return std::error_code();
348
349   const FunctionSamples *FS = findFunctionSamples(Inst);
350   if (!FS)
351     return std::error_code();
352
353   const DILocation *DIL = DLoc;
354   unsigned Lineno = DLoc.getLine();
355   unsigned HeaderLineno = DIL->getScope()->getSubprogram()->getLine();
356
357   uint32_t LineOffset = getOffset(Lineno, HeaderLineno);
358   uint32_t Discriminator = DIL->getDiscriminator();
359   ErrorOr<uint64_t> R = FS->findSamplesAt(LineOffset, Discriminator);
360   if (R) {
361     bool FirstMark =
362         CoverageTracker.markSamplesUsed(FS, LineOffset, Discriminator);
363     if (FirstMark) {
364       const Function *F = Inst.getParent()->getParent();
365       LLVMContext &Ctx = F->getContext();
366       emitOptimizationRemark(
367           Ctx, DEBUG_TYPE, *F, DLoc,
368           Twine("Applied ") + Twine(*R) + " samples from profile (offset: " +
369               Twine(LineOffset) +
370               ((Discriminator) ? Twine(".") + Twine(Discriminator) : "") + ")");
371     }
372     DEBUG(dbgs() << "    " << Lineno << "." << DIL->getDiscriminator() << ":"
373                  << Inst << " (line offset: " << Lineno - HeaderLineno << "."
374                  << DIL->getDiscriminator() << " - weight: " << R.get()
375                  << ")\n");
376   }
377   return R;
378 }
379
380 /// \brief Compute the weight of a basic block.
381 ///
382 /// The weight of basic block \p BB is the maximum weight of all the
383 /// instructions in BB.
384 ///
385 /// \param BB The basic block to query.
386 ///
387 /// \returns the weight for \p BB.
388 ErrorOr<uint64_t>
389 SampleProfileLoader::getBlockWeight(const BasicBlock *BB) const {
390   bool Found = false;
391   uint64_t Weight = 0;
392   for (auto &I : BB->getInstList()) {
393     const ErrorOr<uint64_t> &R = getInstWeight(I);
394     if (R && R.get() >= Weight) {
395       Weight = R.get();
396       Found = true;
397     }
398   }
399   if (Found)
400     return Weight;
401   else
402     return std::error_code();
403 }
404
405 /// \brief Compute and store the weights of every basic block.
406 ///
407 /// This populates the BlockWeights map by computing
408 /// the weights of every basic block in the CFG.
409 ///
410 /// \param F The function to query.
411 bool SampleProfileLoader::computeBlockWeights(Function &F) {
412   bool Changed = false;
413   DEBUG(dbgs() << "Block weights\n");
414   for (const auto &BB : F) {
415     ErrorOr<uint64_t> Weight = getBlockWeight(&BB);
416     if (Weight) {
417       BlockWeights[&BB] = Weight.get();
418       VisitedBlocks.insert(&BB);
419       Changed = true;
420     }
421     DEBUG(printBlockWeight(dbgs(), &BB));
422   }
423
424   return Changed;
425 }
426
427 /// \brief Get the FunctionSamples for a call instruction.
428 ///
429 /// The FunctionSamples of a call instruction \p Inst is the inlined
430 /// instance in which that call instruction is calling to. It contains
431 /// all samples that resides in the inlined instance. We first find the
432 /// inlined instance in which the call instruction is from, then we
433 /// traverse its children to find the callsite with the matching
434 /// location and callee function name.
435 ///
436 /// \param Inst Call instruction to query.
437 ///
438 /// \returns The FunctionSamples pointer to the inlined instance.
439 const FunctionSamples *
440 SampleProfileLoader::findCalleeFunctionSamples(const CallInst &Inst) const {
441   const DILocation *DIL = Inst.getDebugLoc();
442   if (!DIL) {
443     return nullptr;
444   }
445   DISubprogram *SP = DIL->getScope()->getSubprogram();
446   if (!SP)
447     return nullptr;
448
449   Function *CalleeFunc = Inst.getCalledFunction();
450   if (!CalleeFunc) {
451     return nullptr;
452   }
453
454   StringRef CalleeName = CalleeFunc->getName();
455   const FunctionSamples *FS = findFunctionSamples(Inst);
456   if (FS == nullptr)
457     return nullptr;
458
459   return FS->findFunctionSamplesAt(
460       CallsiteLocation(getOffset(DIL->getLine(), SP->getLine()),
461                        DIL->getDiscriminator(), CalleeName));
462 }
463
464 /// \brief Get the FunctionSamples for an instruction.
465 ///
466 /// The FunctionSamples of an instruction \p Inst is the inlined instance
467 /// in which that instruction is coming from. We traverse the inline stack
468 /// of that instruction, and match it with the tree nodes in the profile.
469 ///
470 /// \param Inst Instruction to query.
471 ///
472 /// \returns the FunctionSamples pointer to the inlined instance.
473 const FunctionSamples *
474 SampleProfileLoader::findFunctionSamples(const Instruction &Inst) const {
475   SmallVector<CallsiteLocation, 10> S;
476   const DILocation *DIL = Inst.getDebugLoc();
477   if (!DIL) {
478     return Samples;
479   }
480   StringRef CalleeName;
481   for (const DILocation *DIL = Inst.getDebugLoc(); DIL;
482        DIL = DIL->getInlinedAt()) {
483     DISubprogram *SP = DIL->getScope()->getSubprogram();
484     if (!SP)
485       return nullptr;
486     if (!CalleeName.empty()) {
487       S.push_back(CallsiteLocation(getOffset(DIL->getLine(), SP->getLine()),
488                                    DIL->getDiscriminator(), CalleeName));
489     }
490     CalleeName = SP->getLinkageName();
491   }
492   if (S.size() == 0)
493     return Samples;
494   const FunctionSamples *FS = Samples;
495   for (int i = S.size() - 1; i >= 0 && FS != nullptr; i--) {
496     FS = FS->findFunctionSamplesAt(S[i]);
497   }
498   return FS;
499 }
500
501 /// \brief Iteratively inline hot callsites of a function.
502 ///
503 /// Iteratively traverse all callsites of the function \p F, and find if
504 /// the corresponding inlined instance exists and is hot in profile. If
505 /// it is hot enough, inline the callsites and adds new callsites of the
506 /// callee into the caller.
507 ///
508 /// TODO: investigate the possibility of not invoking InlineFunction directly.
509 ///
510 /// \param F function to perform iterative inlining.
511 ///
512 /// \returns True if there is any inline happened.
513 bool SampleProfileLoader::inlineHotFunctions(Function &F) {
514   bool Changed = false;
515   LLVMContext &Ctx = F.getContext();
516   while (true) {
517     bool LocalChanged = false;
518     SmallVector<CallInst *, 10> CIS;
519     for (auto &BB : F) {
520       for (auto &I : BB.getInstList()) {
521         CallInst *CI = dyn_cast<CallInst>(&I);
522         if (CI) {
523           const FunctionSamples *FS = findCalleeFunctionSamples(*CI);
524           if (FS && FS->getTotalSamples() > 0) {
525             CIS.push_back(CI);
526           }
527         }
528       }
529     }
530     for (auto CI : CIS) {
531       InlineFunctionInfo IFI;
532       Function *CalledFunction = CI->getCalledFunction();
533       DebugLoc DLoc = CI->getDebugLoc();
534       uint64_t NumSamples = findCalleeFunctionSamples(*CI)->getTotalSamples();
535       if (InlineFunction(CI, IFI)) {
536         LocalChanged = true;
537         emitOptimizationRemark(Ctx, DEBUG_TYPE, F, DLoc,
538                                Twine("inlined hot callee '") +
539                                    CalledFunction->getName() + "' with " +
540                                    Twine(NumSamples) + " samples into '" +
541                                    F.getName() + "'");
542       }
543     }
544     if (LocalChanged) {
545       Changed = true;
546     } else {
547       break;
548     }
549   }
550   return Changed;
551 }
552
553 /// \brief Find equivalence classes for the given block.
554 ///
555 /// This finds all the blocks that are guaranteed to execute the same
556 /// number of times as \p BB1. To do this, it traverses all the
557 /// descendants of \p BB1 in the dominator or post-dominator tree.
558 ///
559 /// A block BB2 will be in the same equivalence class as \p BB1 if
560 /// the following holds:
561 ///
562 /// 1- \p BB1 is a descendant of BB2 in the opposite tree. So, if BB2
563 ///    is a descendant of \p BB1 in the dominator tree, then BB2 should
564 ///    dominate BB1 in the post-dominator tree.
565 ///
566 /// 2- Both BB2 and \p BB1 must be in the same loop.
567 ///
568 /// For every block BB2 that meets those two requirements, we set BB2's
569 /// equivalence class to \p BB1.
570 ///
571 /// \param BB1  Block to check.
572 /// \param Descendants  Descendants of \p BB1 in either the dom or pdom tree.
573 /// \param DomTree  Opposite dominator tree. If \p Descendants is filled
574 ///                 with blocks from \p BB1's dominator tree, then
575 ///                 this is the post-dominator tree, and vice versa.
576 void SampleProfileLoader::findEquivalencesFor(
577     BasicBlock *BB1, SmallVector<BasicBlock *, 8> Descendants,
578     DominatorTreeBase<BasicBlock> *DomTree) {
579   const BasicBlock *EC = EquivalenceClass[BB1];
580   uint64_t Weight = BlockWeights[EC];
581   for (const auto *BB2 : Descendants) {
582     bool IsDomParent = DomTree->dominates(BB2, BB1);
583     bool IsInSameLoop = LI->getLoopFor(BB1) == LI->getLoopFor(BB2);
584     if (BB1 != BB2 && IsDomParent && IsInSameLoop) {
585       EquivalenceClass[BB2] = EC;
586
587       // If BB2 is heavier than BB1, make BB2 have the same weight
588       // as BB1.
589       //
590       // Note that we don't worry about the opposite situation here
591       // (when BB2 is lighter than BB1). We will deal with this
592       // during the propagation phase. Right now, we just want to
593       // make sure that BB1 has the largest weight of all the
594       // members of its equivalence set.
595       Weight = std::max(Weight, BlockWeights[BB2]);
596     }
597   }
598   BlockWeights[EC] = Weight;
599 }
600
601 /// \brief Find equivalence classes.
602 ///
603 /// Since samples may be missing from blocks, we can fill in the gaps by setting
604 /// the weights of all the blocks in the same equivalence class to the same
605 /// weight. To compute the concept of equivalence, we use dominance and loop
606 /// information. Two blocks B1 and B2 are in the same equivalence class if B1
607 /// dominates B2, B2 post-dominates B1 and both are in the same loop.
608 ///
609 /// \param F The function to query.
610 void SampleProfileLoader::findEquivalenceClasses(Function &F) {
611   SmallVector<BasicBlock *, 8> DominatedBBs;
612   DEBUG(dbgs() << "\nBlock equivalence classes\n");
613   // Find equivalence sets based on dominance and post-dominance information.
614   for (auto &BB : F) {
615     BasicBlock *BB1 = &BB;
616
617     // Compute BB1's equivalence class once.
618     if (EquivalenceClass.count(BB1)) {
619       DEBUG(printBlockEquivalence(dbgs(), BB1));
620       continue;
621     }
622
623     // By default, blocks are in their own equivalence class.
624     EquivalenceClass[BB1] = BB1;
625
626     // Traverse all the blocks dominated by BB1. We are looking for
627     // every basic block BB2 such that:
628     //
629     // 1- BB1 dominates BB2.
630     // 2- BB2 post-dominates BB1.
631     // 3- BB1 and BB2 are in the same loop nest.
632     //
633     // If all those conditions hold, it means that BB2 is executed
634     // as many times as BB1, so they are placed in the same equivalence
635     // class by making BB2's equivalence class be BB1.
636     DominatedBBs.clear();
637     DT->getDescendants(BB1, DominatedBBs);
638     findEquivalencesFor(BB1, DominatedBBs, PDT.get());
639
640     DEBUG(printBlockEquivalence(dbgs(), BB1));
641   }
642
643   // Assign weights to equivalence classes.
644   //
645   // All the basic blocks in the same equivalence class will execute
646   // the same number of times. Since we know that the head block in
647   // each equivalence class has the largest weight, assign that weight
648   // to all the blocks in that equivalence class.
649   DEBUG(dbgs() << "\nAssign the same weight to all blocks in the same class\n");
650   for (auto &BI : F) {
651     const BasicBlock *BB = &BI;
652     const BasicBlock *EquivBB = EquivalenceClass[BB];
653     if (BB != EquivBB)
654       BlockWeights[BB] = BlockWeights[EquivBB];
655     DEBUG(printBlockWeight(dbgs(), BB));
656   }
657 }
658
659 /// \brief Visit the given edge to decide if it has a valid weight.
660 ///
661 /// If \p E has not been visited before, we copy to \p UnknownEdge
662 /// and increment the count of unknown edges.
663 ///
664 /// \param E  Edge to visit.
665 /// \param NumUnknownEdges  Current number of unknown edges.
666 /// \param UnknownEdge  Set if E has not been visited before.
667 ///
668 /// \returns E's weight, if known. Otherwise, return 0.
669 uint64_t SampleProfileLoader::visitEdge(Edge E, unsigned *NumUnknownEdges,
670                                         Edge *UnknownEdge) {
671   if (!VisitedEdges.count(E)) {
672     (*NumUnknownEdges)++;
673     *UnknownEdge = E;
674     return 0;
675   }
676
677   return EdgeWeights[E];
678 }
679
680 /// \brief Propagate weights through incoming/outgoing edges.
681 ///
682 /// If the weight of a basic block is known, and there is only one edge
683 /// with an unknown weight, we can calculate the weight of that edge.
684 ///
685 /// Similarly, if all the edges have a known count, we can calculate the
686 /// count of the basic block, if needed.
687 ///
688 /// \param F  Function to process.
689 ///
690 /// \returns  True if new weights were assigned to edges or blocks.
691 bool SampleProfileLoader::propagateThroughEdges(Function &F) {
692   bool Changed = false;
693   DEBUG(dbgs() << "\nPropagation through edges\n");
694   for (const auto &BI : F) {
695     const BasicBlock *BB = &BI;
696     const BasicBlock *EC = EquivalenceClass[BB];
697
698     // Visit all the predecessor and successor edges to determine
699     // which ones have a weight assigned already. Note that it doesn't
700     // matter that we only keep track of a single unknown edge. The
701     // only case we are interested in handling is when only a single
702     // edge is unknown (see setEdgeOrBlockWeight).
703     for (unsigned i = 0; i < 2; i++) {
704       uint64_t TotalWeight = 0;
705       unsigned NumUnknownEdges = 0;
706       Edge UnknownEdge, SelfReferentialEdge;
707
708       if (i == 0) {
709         // First, visit all predecessor edges.
710         for (auto *Pred : Predecessors[BB]) {
711           Edge E = std::make_pair(Pred, BB);
712           TotalWeight += visitEdge(E, &NumUnknownEdges, &UnknownEdge);
713           if (E.first == E.second)
714             SelfReferentialEdge = E;
715         }
716       } else {
717         // On the second round, visit all successor edges.
718         for (auto *Succ : Successors[BB]) {
719           Edge E = std::make_pair(BB, Succ);
720           TotalWeight += visitEdge(E, &NumUnknownEdges, &UnknownEdge);
721         }
722       }
723
724       // After visiting all the edges, there are three cases that we
725       // can handle immediately:
726       //
727       // - All the edge weights are known (i.e., NumUnknownEdges == 0).
728       //   In this case, we simply check that the sum of all the edges
729       //   is the same as BB's weight. If not, we change BB's weight
730       //   to match. Additionally, if BB had not been visited before,
731       //   we mark it visited.
732       //
733       // - Only one edge is unknown and BB has already been visited.
734       //   In this case, we can compute the weight of the edge by
735       //   subtracting the total block weight from all the known
736       //   edge weights. If the edges weight more than BB, then the
737       //   edge of the last remaining edge is set to zero.
738       //
739       // - There exists a self-referential edge and the weight of BB is
740       //   known. In this case, this edge can be based on BB's weight.
741       //   We add up all the other known edges and set the weight on
742       //   the self-referential edge as we did in the previous case.
743       //
744       // In any other case, we must continue iterating. Eventually,
745       // all edges will get a weight, or iteration will stop when
746       // it reaches SampleProfileMaxPropagateIterations.
747       if (NumUnknownEdges <= 1) {
748         uint64_t &BBWeight = BlockWeights[EC];
749         if (NumUnknownEdges == 0) {
750           // If we already know the weight of all edges, the weight of the
751           // basic block can be computed. It should be no larger than the sum
752           // of all edge weights.
753           if (TotalWeight > BBWeight) {
754             BBWeight = TotalWeight;
755             Changed = true;
756             DEBUG(dbgs() << "All edge weights for " << BB->getName()
757                          << " known. Set weight for block: ";
758                   printBlockWeight(dbgs(), BB););
759           }
760           if (VisitedBlocks.insert(EC).second)
761             Changed = true;
762         } else if (NumUnknownEdges == 1 && VisitedBlocks.count(EC)) {
763           // If there is a single unknown edge and the block has been
764           // visited, then we can compute E's weight.
765           if (BBWeight >= TotalWeight)
766             EdgeWeights[UnknownEdge] = BBWeight - TotalWeight;
767           else
768             EdgeWeights[UnknownEdge] = 0;
769           VisitedEdges.insert(UnknownEdge);
770           Changed = true;
771           DEBUG(dbgs() << "Set weight for edge: ";
772                 printEdgeWeight(dbgs(), UnknownEdge));
773         }
774       } else if (SelfReferentialEdge.first && VisitedBlocks.count(EC)) {
775         uint64_t &BBWeight = BlockWeights[BB];
776         // We have a self-referential edge and the weight of BB is known.
777         if (BBWeight >= TotalWeight)
778           EdgeWeights[SelfReferentialEdge] = BBWeight - TotalWeight;
779         else
780           EdgeWeights[SelfReferentialEdge] = 0;
781         VisitedEdges.insert(SelfReferentialEdge);
782         Changed = true;
783         DEBUG(dbgs() << "Set self-referential edge weight to: ";
784               printEdgeWeight(dbgs(), SelfReferentialEdge));
785       }
786     }
787   }
788
789   return Changed;
790 }
791
792 /// \brief Build in/out edge lists for each basic block in the CFG.
793 ///
794 /// We are interested in unique edges. If a block B1 has multiple
795 /// edges to another block B2, we only add a single B1->B2 edge.
796 void SampleProfileLoader::buildEdges(Function &F) {
797   for (auto &BI : F) {
798     BasicBlock *B1 = &BI;
799
800     // Add predecessors for B1.
801     SmallPtrSet<BasicBlock *, 16> Visited;
802     if (!Predecessors[B1].empty())
803       llvm_unreachable("Found a stale predecessors list in a basic block.");
804     for (pred_iterator PI = pred_begin(B1), PE = pred_end(B1); PI != PE; ++PI) {
805       BasicBlock *B2 = *PI;
806       if (Visited.insert(B2).second)
807         Predecessors[B1].push_back(B2);
808     }
809
810     // Add successors for B1.
811     Visited.clear();
812     if (!Successors[B1].empty())
813       llvm_unreachable("Found a stale successors list in a basic block.");
814     for (succ_iterator SI = succ_begin(B1), SE = succ_end(B1); SI != SE; ++SI) {
815       BasicBlock *B2 = *SI;
816       if (Visited.insert(B2).second)
817         Successors[B1].push_back(B2);
818     }
819   }
820 }
821
822 /// \brief Propagate weights into edges
823 ///
824 /// The following rules are applied to every block BB in the CFG:
825 ///
826 /// - If BB has a single predecessor/successor, then the weight
827 ///   of that edge is the weight of the block.
828 ///
829 /// - If all incoming or outgoing edges are known except one, and the
830 ///   weight of the block is already known, the weight of the unknown
831 ///   edge will be the weight of the block minus the sum of all the known
832 ///   edges. If the sum of all the known edges is larger than BB's weight,
833 ///   we set the unknown edge weight to zero.
834 ///
835 /// - If there is a self-referential edge, and the weight of the block is
836 ///   known, the weight for that edge is set to the weight of the block
837 ///   minus the weight of the other incoming edges to that block (if
838 ///   known).
839 void SampleProfileLoader::propagateWeights(Function &F) {
840   bool Changed = true;
841   unsigned I = 0;
842
843   // Add an entry count to the function using the samples gathered
844   // at the function entry.
845   F.setEntryCount(Samples->getHeadSamples());
846
847   // Before propagation starts, build, for each block, a list of
848   // unique predecessors and successors. This is necessary to handle
849   // identical edges in multiway branches. Since we visit all blocks and all
850   // edges of the CFG, it is cleaner to build these lists once at the start
851   // of the pass.
852   buildEdges(F);
853
854   // Propagate until we converge or we go past the iteration limit.
855   while (Changed && I++ < SampleProfileMaxPropagateIterations) {
856     Changed = propagateThroughEdges(F);
857   }
858
859   // Generate MD_prof metadata for every branch instruction using the
860   // edge weights computed during propagation.
861   DEBUG(dbgs() << "\nPropagation complete. Setting branch weights\n");
862   LLVMContext &Ctx = F.getContext();
863   MDBuilder MDB(Ctx);
864   for (auto &BI : F) {
865     BasicBlock *BB = &BI;
866     TerminatorInst *TI = BB->getTerminator();
867     if (TI->getNumSuccessors() == 1)
868       continue;
869     if (!isa<BranchInst>(TI) && !isa<SwitchInst>(TI))
870       continue;
871
872     DEBUG(dbgs() << "\nGetting weights for branch at line "
873                  << TI->getDebugLoc().getLine() << ".\n");
874     SmallVector<uint32_t, 4> Weights;
875     uint32_t MaxWeight = 0;
876     DebugLoc MaxDestLoc;
877     for (unsigned I = 0; I < TI->getNumSuccessors(); ++I) {
878       BasicBlock *Succ = TI->getSuccessor(I);
879       Edge E = std::make_pair(BB, Succ);
880       uint64_t Weight = EdgeWeights[E];
881       DEBUG(dbgs() << "\t"; printEdgeWeight(dbgs(), E));
882       // Use uint32_t saturated arithmetic to adjust the incoming weights,
883       // if needed. Sample counts in profiles are 64-bit unsigned values,
884       // but internally branch weights are expressed as 32-bit values.
885       if (Weight > std::numeric_limits<uint32_t>::max()) {
886         DEBUG(dbgs() << " (saturated due to uint32_t overflow)");
887         Weight = std::numeric_limits<uint32_t>::max();
888       }
889       Weights.push_back(static_cast<uint32_t>(Weight));
890       if (Weight != 0) {
891         if (Weight > MaxWeight) {
892           MaxWeight = Weight;
893           MaxDestLoc = Succ->getFirstNonPHIOrDbgOrLifetime()->getDebugLoc();
894         }
895       }
896     }
897
898     // Only set weights if there is at least one non-zero weight.
899     // In any other case, let the analyzer set weights.
900     if (MaxWeight > 0) {
901       DEBUG(dbgs() << "SUCCESS. Found non-zero weights.\n");
902       TI->setMetadata(llvm::LLVMContext::MD_prof,
903                       MDB.createBranchWeights(Weights));
904       DebugLoc BranchLoc = TI->getDebugLoc();
905       emitOptimizationRemark(
906           Ctx, DEBUG_TYPE, F, MaxDestLoc,
907           Twine("most popular destination for conditional branches at ") +
908               ((BranchLoc) ? Twine(BranchLoc->getFilename() + ":" +
909                                    Twine(BranchLoc.getLine()) + ":" +
910                                    Twine(BranchLoc.getCol()))
911                            : Twine("<UNKNOWN LOCATION>")));
912     } else {
913       DEBUG(dbgs() << "SKIPPED. All branch weights are zero.\n");
914     }
915   }
916 }
917
918 /// \brief Get the line number for the function header.
919 ///
920 /// This looks up function \p F in the current compilation unit and
921 /// retrieves the line number where the function is defined. This is
922 /// line 0 for all the samples read from the profile file. Every line
923 /// number is relative to this line.
924 ///
925 /// \param F  Function object to query.
926 ///
927 /// \returns the line number where \p F is defined. If it returns 0,
928 ///          it means that there is no debug information available for \p F.
929 unsigned SampleProfileLoader::getFunctionLoc(Function &F) {
930   if (DISubprogram *S = getDISubprogram(&F))
931     return S->getLine();
932
933   // If the start of \p F is missing, emit a diagnostic to inform the user
934   // about the missed opportunity.
935   F.getContext().diagnose(DiagnosticInfoSampleProfile(
936       "No debug information found in function " + F.getName() +
937           ": Function profile not used",
938       DS_Warning));
939   return 0;
940 }
941
942 void SampleProfileLoader::computeDominanceAndLoopInfo(Function &F) {
943   DT.reset(new DominatorTree);
944   DT->recalculate(F);
945
946   PDT.reset(new DominatorTreeBase<BasicBlock>(true));
947   PDT->recalculate(F);
948
949   LI.reset(new LoopInfo);
950   LI->analyze(*DT);
951 }
952
953 /// \brief Generate branch weight metadata for all branches in \p F.
954 ///
955 /// Branch weights are computed out of instruction samples using a
956 /// propagation heuristic. Propagation proceeds in 3 phases:
957 ///
958 /// 1- Assignment of block weights. All the basic blocks in the function
959 ///    are initial assigned the same weight as their most frequently
960 ///    executed instruction.
961 ///
962 /// 2- Creation of equivalence classes. Since samples may be missing from
963 ///    blocks, we can fill in the gaps by setting the weights of all the
964 ///    blocks in the same equivalence class to the same weight. To compute
965 ///    the concept of equivalence, we use dominance and loop information.
966 ///    Two blocks B1 and B2 are in the same equivalence class if B1
967 ///    dominates B2, B2 post-dominates B1 and both are in the same loop.
968 ///
969 /// 3- Propagation of block weights into edges. This uses a simple
970 ///    propagation heuristic. The following rules are applied to every
971 ///    block BB in the CFG:
972 ///
973 ///    - If BB has a single predecessor/successor, then the weight
974 ///      of that edge is the weight of the block.
975 ///
976 ///    - If all the edges are known except one, and the weight of the
977 ///      block is already known, the weight of the unknown edge will
978 ///      be the weight of the block minus the sum of all the known
979 ///      edges. If the sum of all the known edges is larger than BB's weight,
980 ///      we set the unknown edge weight to zero.
981 ///
982 ///    - If there is a self-referential edge, and the weight of the block is
983 ///      known, the weight for that edge is set to the weight of the block
984 ///      minus the weight of the other incoming edges to that block (if
985 ///      known).
986 ///
987 /// Since this propagation is not guaranteed to finalize for every CFG, we
988 /// only allow it to proceed for a limited number of iterations (controlled
989 /// by -sample-profile-max-propagate-iterations).
990 ///
991 /// FIXME: Try to replace this propagation heuristic with a scheme
992 /// that is guaranteed to finalize. A work-list approach similar to
993 /// the standard value propagation algorithm used by SSA-CCP might
994 /// work here.
995 ///
996 /// Once all the branch weights are computed, we emit the MD_prof
997 /// metadata on BB using the computed values for each of its branches.
998 ///
999 /// \param F The function to query.
1000 ///
1001 /// \returns true if \p F was modified. Returns false, otherwise.
1002 bool SampleProfileLoader::emitAnnotations(Function &F) {
1003   bool Changed = false;
1004
1005   if (getFunctionLoc(F) == 0)
1006     return false;
1007
1008   DEBUG(dbgs() << "Line number for the first instruction in " << F.getName()
1009                << ": " << getFunctionLoc(F) << "\n");
1010
1011   Changed |= inlineHotFunctions(F);
1012
1013   // Compute basic block weights.
1014   Changed |= computeBlockWeights(F);
1015
1016   if (Changed) {
1017     // Compute dominance and loop info needed for propagation.
1018     computeDominanceAndLoopInfo(F);
1019
1020     // Find equivalence classes.
1021     findEquivalenceClasses(F);
1022
1023     // Propagate weights to all edges.
1024     propagateWeights(F);
1025   }
1026
1027   // If coverage checking was requested, compute it now.
1028   if (SampleProfileCoverage) {
1029     unsigned Used = CoverageTracker.countUsedSamples(Samples);
1030     unsigned Total = CoverageTracker.countBodySamples(Samples);
1031     unsigned Coverage = CoverageTracker.computeCoverage(Used, Total);
1032     if (Coverage < SampleProfileCoverage) {
1033       F.getContext().diagnose(DiagnosticInfoSampleProfile(
1034           getDISubprogram(&F)->getFilename(), getFunctionLoc(F),
1035           Twine(Used) + " of " + Twine(Total) + " available profile records (" +
1036               Twine(Coverage) + "%) were applied",
1037           DS_Warning));
1038     }
1039   }
1040
1041   return Changed;
1042 }
1043
1044 char SampleProfileLoader::ID = 0;
1045 INITIALIZE_PASS_BEGIN(SampleProfileLoader, "sample-profile",
1046                       "Sample Profile loader", false, false)
1047 INITIALIZE_PASS_DEPENDENCY(AddDiscriminators)
1048 INITIALIZE_PASS_END(SampleProfileLoader, "sample-profile",
1049                     "Sample Profile loader", false, false)
1050
1051 bool SampleProfileLoader::doInitialization(Module &M) {
1052   auto &Ctx = M.getContext();
1053   auto ReaderOrErr = SampleProfileReader::create(Filename, Ctx);
1054   if (std::error_code EC = ReaderOrErr.getError()) {
1055     std::string Msg = "Could not open profile: " + EC.message();
1056     Ctx.diagnose(DiagnosticInfoSampleProfile(Filename, Msg));
1057     return false;
1058   }
1059   Reader = std::move(ReaderOrErr.get());
1060   ProfileIsValid = (Reader->read() == sampleprof_error::success);
1061   return true;
1062 }
1063
1064 ModulePass *llvm::createSampleProfileLoaderPass() {
1065   return new SampleProfileLoader(SampleProfileFile);
1066 }
1067
1068 ModulePass *llvm::createSampleProfileLoaderPass(StringRef Name) {
1069   return new SampleProfileLoader(Name);
1070 }
1071
1072 bool SampleProfileLoader::runOnModule(Module &M) {
1073   if (!ProfileIsValid)
1074     return false;
1075
1076   bool retval = false;
1077   for (auto &F : M)
1078     if (!F.isDeclaration()) {
1079       clearFunctionData();
1080       retval |= runOnFunction(F);
1081     }
1082   return retval;
1083 }
1084
1085 bool SampleProfileLoader::runOnFunction(Function &F) {
1086   Samples = Reader->getSamplesFor(F);
1087   if (!Samples->empty())
1088     return emitAnnotations(F);
1089   return false;
1090 }