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