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