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