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/AssumptionCache.h"
31 #include "llvm/Analysis/InlineCost.h"
32 #include "llvm/Analysis/LoopInfo.h"
33 #include "llvm/Analysis/OptimizationDiagnosticInfo.h"
34 #include "llvm/Analysis/PostDominators.h"
35 #include "llvm/Analysis/TargetTransformInfo.h"
36 #include "llvm/IR/Constants.h"
37 #include "llvm/IR/DebugInfo.h"
38 #include "llvm/IR/DiagnosticInfo.h"
39 #include "llvm/IR/Dominators.h"
40 #include "llvm/IR/Function.h"
41 #include "llvm/IR/GlobalValue.h"
42 #include "llvm/IR/InstIterator.h"
43 #include "llvm/IR/Instructions.h"
44 #include "llvm/IR/IntrinsicInst.h"
45 #include "llvm/IR/LLVMContext.h"
46 #include "llvm/IR/MDBuilder.h"
47 #include "llvm/IR/Metadata.h"
48 #include "llvm/IR/Module.h"
49 #include "llvm/IR/ValueSymbolTable.h"
50 #include "llvm/Pass.h"
51 #include "llvm/ProfileData/InstrProf.h"
52 #include "llvm/ProfileData/SampleProfReader.h"
53 #include "llvm/Support/CommandLine.h"
54 #include "llvm/Support/Debug.h"
55 #include "llvm/Support/ErrorOr.h"
56 #include "llvm/Support/Format.h"
57 #include "llvm/Support/raw_ostream.h"
58 #include "llvm/Transforms/IPO.h"
59 #include "llvm/Transforms/Instrumentation.h"
60 #include "llvm/Transforms/Utils/Cloning.h"
61 #include <cctype>
62 
63 using namespace llvm;
64 using namespace sampleprof;
65 
66 #define DEBUG_TYPE "sample-profile"
67 
68 // Command line option to specify the file to read samples from. This is
69 // mainly used for debugging.
70 static cl::opt<std::string> SampleProfileFile(
71     "sample-profile-file", cl::init(""), cl::value_desc("filename"),
72     cl::desc("Profile file loaded by -sample-profile"), cl::Hidden);
73 static cl::opt<unsigned> SampleProfileMaxPropagateIterations(
74     "sample-profile-max-propagate-iterations", cl::init(100),
75     cl::desc("Maximum number of iterations to go through when propagating "
76              "sample block/edge weights through the CFG."));
77 static cl::opt<unsigned> SampleProfileRecordCoverage(
78     "sample-profile-check-record-coverage", cl::init(0), cl::value_desc("N"),
79     cl::desc("Emit a warning if less than N% of records in the input profile "
80              "are matched to the IR."));
81 static cl::opt<unsigned> SampleProfileSampleCoverage(
82     "sample-profile-check-sample-coverage", cl::init(0), cl::value_desc("N"),
83     cl::desc("Emit a warning if less than N% of samples in the input profile "
84              "are matched to the IR."));
85 static cl::opt<double> SampleProfileHotThreshold(
86     "sample-profile-inline-hot-threshold", cl::init(0.1), cl::value_desc("N"),
87     cl::desc("Inlined functions that account for more than N% of all samples "
88              "collected in the parent function, will be inlined again."));
89 
90 namespace {
91 typedef DenseMap<const BasicBlock *, uint64_t> BlockWeightMap;
92 typedef DenseMap<const BasicBlock *, const BasicBlock *> EquivalenceClassMap;
93 typedef std::pair<const BasicBlock *, const BasicBlock *> Edge;
94 typedef DenseMap<Edge, uint64_t> EdgeWeightMap;
95 typedef DenseMap<const BasicBlock *, SmallVector<const BasicBlock *, 8>>
96     BlockEdgeMap;
97 
98 class SampleCoverageTracker {
99 public:
100   SampleCoverageTracker() : SampleCoverage(), TotalUsedSamples(0) {}
101 
102   bool markSamplesUsed(const FunctionSamples *FS, uint32_t LineOffset,
103                        uint32_t Discriminator, uint64_t Samples);
104   unsigned computeCoverage(unsigned Used, unsigned Total) const;
105   unsigned countUsedRecords(const FunctionSamples *FS) const;
106   unsigned countBodyRecords(const FunctionSamples *FS) const;
107   uint64_t getTotalUsedSamples() const { return TotalUsedSamples; }
108   uint64_t countBodySamples(const FunctionSamples *FS) const;
109   void clear() {
110     SampleCoverage.clear();
111     TotalUsedSamples = 0;
112   }
113 
114 private:
115   typedef std::map<LineLocation, unsigned> BodySampleCoverageMap;
116   typedef DenseMap<const FunctionSamples *, BodySampleCoverageMap>
117       FunctionSamplesCoverageMap;
118 
119   /// Coverage map for sampling records.
120   ///
121   /// This map keeps a record of sampling records that have been matched to
122   /// an IR instruction. This is used to detect some form of staleness in
123   /// profiles (see flag -sample-profile-check-coverage).
124   ///
125   /// Each entry in the map corresponds to a FunctionSamples instance.  This is
126   /// another map that counts how many times the sample record at the
127   /// given location has been used.
128   FunctionSamplesCoverageMap SampleCoverage;
129 
130   /// Number of samples used from the profile.
131   ///
132   /// When a sampling record is used for the first time, the samples from
133   /// that record are added to this accumulator.  Coverage is later computed
134   /// based on the total number of samples available in this function and
135   /// its callsites.
136   ///
137   /// Note that this accumulator tracks samples used from a single function
138   /// and all the inlined callsites. Strictly, we should have a map of counters
139   /// keyed by FunctionSamples pointers, but these stats are cleared after
140   /// every function, so we just need to keep a single counter.
141   uint64_t TotalUsedSamples;
142 };
143 
144 /// \brief Sample profile pass.
145 ///
146 /// This pass reads profile data from the file specified by
147 /// -sample-profile-file and annotates every affected function with the
148 /// profile information found in that file.
149 class SampleProfileLoader {
150 public:
151   SampleProfileLoader(
152       StringRef Name,
153       std::function<AssumptionCache &(Function &)> GetAssumptionCache,
154       std::function<TargetTransformInfo &(Function &)> GetTargetTransformInfo)
155       : DT(nullptr), PDT(nullptr), LI(nullptr), GetAC(GetAssumptionCache),
156         GetTTI(GetTargetTransformInfo), Reader(), Samples(nullptr),
157         Filename(Name), ProfileIsValid(false), TotalCollectedSamples(0),
158         ORE(nullptr) {}
159 
160   bool doInitialization(Module &M);
161   bool runOnModule(Module &M, ModuleAnalysisManager *AM);
162 
163   void dump() { Reader->dump(); }
164 
165 protected:
166   bool runOnFunction(Function &F, ModuleAnalysisManager *AM);
167   unsigned getFunctionLoc(Function &F);
168   bool emitAnnotations(Function &F);
169   ErrorOr<uint64_t> getInstWeight(const Instruction &I);
170   ErrorOr<uint64_t> getBlockWeight(const BasicBlock *BB);
171   const FunctionSamples *findCalleeFunctionSamples(const Instruction &I) const;
172   std::vector<const FunctionSamples *>
173   findIndirectCallFunctionSamples(const Instruction &I) const;
174   const FunctionSamples *findFunctionSamples(const Instruction &I) const;
175   bool inlineHotFunctions(Function &F,
176                           DenseSet<GlobalValue::GUID> &ImportGUIDs);
177   void printEdgeWeight(raw_ostream &OS, Edge E);
178   void printBlockWeight(raw_ostream &OS, const BasicBlock *BB) const;
179   void printBlockEquivalence(raw_ostream &OS, const BasicBlock *BB);
180   bool computeBlockWeights(Function &F);
181   void findEquivalenceClasses(Function &F);
182   template <bool IsPostDom>
183   void findEquivalencesFor(BasicBlock *BB1, ArrayRef<BasicBlock *> Descendants,
184                            DominatorTreeBase<BasicBlock, IsPostDom> *DomTree);
185 
186   void propagateWeights(Function &F);
187   uint64_t visitEdge(Edge E, unsigned *NumUnknownEdges, Edge *UnknownEdge);
188   void buildEdges(Function &F);
189   bool propagateThroughEdges(Function &F, bool UpdateBlockCount);
190   void computeDominanceAndLoopInfo(Function &F);
191   unsigned getOffset(const DILocation *DIL) const;
192   void clearFunctionData();
193 
194   /// \brief Map basic blocks to their computed weights.
195   ///
196   /// The weight of a basic block is defined to be the maximum
197   /// of all the instruction weights in that block.
198   BlockWeightMap BlockWeights;
199 
200   /// \brief Map edges to their computed weights.
201   ///
202   /// Edge weights are computed by propagating basic block weights in
203   /// SampleProfile::propagateWeights.
204   EdgeWeightMap EdgeWeights;
205 
206   /// \brief Set of visited blocks during propagation.
207   SmallPtrSet<const BasicBlock *, 32> VisitedBlocks;
208 
209   /// \brief Set of visited edges during propagation.
210   SmallSet<Edge, 32> VisitedEdges;
211 
212   /// \brief Equivalence classes for block weights.
213   ///
214   /// Two blocks BB1 and BB2 are in the same equivalence class if they
215   /// dominate and post-dominate each other, and they are in the same loop
216   /// nest. When this happens, the two blocks are guaranteed to execute
217   /// the same number of times.
218   EquivalenceClassMap EquivalenceClass;
219 
220   /// Map from function name to Function *. Used to find the function from
221   /// the function name. If the function name contains suffix, additional
222   /// entry is added to map from the stripped name to the function if there
223   /// is one-to-one mapping.
224   StringMap<Function *> SymbolMap;
225 
226   /// \brief Dominance, post-dominance and loop information.
227   std::unique_ptr<DominatorTree> DT;
228   std::unique_ptr<PostDomTreeBase<BasicBlock>> PDT;
229   std::unique_ptr<LoopInfo> LI;
230 
231   std::function<AssumptionCache &(Function &)> GetAC;
232   std::function<TargetTransformInfo &(Function &)> GetTTI;
233 
234   /// \brief Predecessors for each basic block in the CFG.
235   BlockEdgeMap Predecessors;
236 
237   /// \brief Successors for each basic block in the CFG.
238   BlockEdgeMap Successors;
239 
240   SampleCoverageTracker CoverageTracker;
241 
242   /// \brief Profile reader object.
243   std::unique_ptr<SampleProfileReader> Reader;
244 
245   /// \brief Samples collected for the body of this function.
246   FunctionSamples *Samples;
247 
248   /// \brief Name of the profile file to load.
249   std::string Filename;
250 
251   /// \brief Flag indicating whether the profile input loaded successfully.
252   bool ProfileIsValid;
253 
254   /// \brief Total number of samples collected in this profile.
255   ///
256   /// This is the sum of all the samples collected in all the functions executed
257   /// at runtime.
258   uint64_t TotalCollectedSamples;
259 
260   /// \brief Optimization Remark Emitter used to emit diagnostic remarks.
261   OptimizationRemarkEmitter *ORE;
262 };
263 
264 class SampleProfileLoaderLegacyPass : public ModulePass {
265 public:
266   // Class identification, replacement for typeinfo
267   static char ID;
268 
269   SampleProfileLoaderLegacyPass(StringRef Name = SampleProfileFile)
270       : ModulePass(ID), SampleLoader(Name,
271                                      [&](Function &F) -> AssumptionCache & {
272                                        return ACT->getAssumptionCache(F);
273                                      },
274                                      [&](Function &F) -> TargetTransformInfo & {
275                                        return TTIWP->getTTI(F);
276                                      }),
277         ACT(nullptr), TTIWP(nullptr) {
278     initializeSampleProfileLoaderLegacyPassPass(
279         *PassRegistry::getPassRegistry());
280   }
281 
282   void dump() { SampleLoader.dump(); }
283 
284   bool doInitialization(Module &M) override {
285     return SampleLoader.doInitialization(M);
286   }
287   StringRef getPassName() const override { return "Sample profile pass"; }
288   bool runOnModule(Module &M) override;
289 
290   void getAnalysisUsage(AnalysisUsage &AU) const override {
291     AU.addRequired<AssumptionCacheTracker>();
292     AU.addRequired<TargetTransformInfoWrapperPass>();
293   }
294 
295 private:
296   SampleProfileLoader SampleLoader;
297   AssumptionCacheTracker *ACT;
298   TargetTransformInfoWrapperPass *TTIWP;
299 };
300 
301 /// Return true if the given callsite is hot wrt to its caller.
302 ///
303 /// Functions that were inlined in the original binary will be represented
304 /// in the inline stack in the sample profile. If the profile shows that
305 /// the original inline decision was "good" (i.e., the callsite is executed
306 /// frequently), then we will recreate the inline decision and apply the
307 /// profile from the inlined callsite.
308 ///
309 /// To decide whether an inlined callsite is hot, we compute the fraction
310 /// of samples used by the callsite with respect to the total number of samples
311 /// collected in the caller.
312 ///
313 /// If that fraction is larger than the default given by
314 /// SampleProfileHotThreshold, the callsite will be inlined again.
315 bool callsiteIsHot(const FunctionSamples *CallerFS,
316                    const FunctionSamples *CallsiteFS) {
317   if (!CallsiteFS)
318     return false; // The callsite was not inlined in the original binary.
319 
320   uint64_t ParentTotalSamples = CallerFS->getTotalSamples();
321   if (ParentTotalSamples == 0)
322     return false; // Avoid division by zero.
323 
324   uint64_t CallsiteTotalSamples = CallsiteFS->getTotalSamples();
325   if (CallsiteTotalSamples == 0)
326     return false; // Callsite is trivially cold.
327 
328   double PercentSamples =
329       (double)CallsiteTotalSamples / (double)ParentTotalSamples * 100.0;
330   return PercentSamples >= SampleProfileHotThreshold;
331 }
332 }
333 
334 /// Mark as used the sample record for the given function samples at
335 /// (LineOffset, Discriminator).
336 ///
337 /// \returns true if this is the first time we mark the given record.
338 bool SampleCoverageTracker::markSamplesUsed(const FunctionSamples *FS,
339                                             uint32_t LineOffset,
340                                             uint32_t Discriminator,
341                                             uint64_t Samples) {
342   LineLocation Loc(LineOffset, Discriminator);
343   unsigned &Count = SampleCoverage[FS][Loc];
344   bool FirstTime = (++Count == 1);
345   if (FirstTime)
346     TotalUsedSamples += Samples;
347   return FirstTime;
348 }
349 
350 /// Return the number of sample records that were applied from this profile.
351 ///
352 /// This count does not include records from cold inlined callsites.
353 unsigned
354 SampleCoverageTracker::countUsedRecords(const FunctionSamples *FS) const {
355   auto I = SampleCoverage.find(FS);
356 
357   // The size of the coverage map for FS represents the number of records
358   // that were marked used at least once.
359   unsigned Count = (I != SampleCoverage.end()) ? I->second.size() : 0;
360 
361   // If there are inlined callsites in this function, count the samples found
362   // in the respective bodies. However, do not bother counting callees with 0
363   // total samples, these are callees that were never invoked at runtime.
364   for (const auto &I : FS->getCallsiteSamples())
365     for (const auto &J : I.second) {
366       const FunctionSamples *CalleeSamples = &J.second;
367       if (callsiteIsHot(FS, CalleeSamples))
368         Count += countUsedRecords(CalleeSamples);
369     }
370 
371   return Count;
372 }
373 
374 /// Return the number of sample records in the body of this profile.
375 ///
376 /// This count does not include records from cold inlined callsites.
377 unsigned
378 SampleCoverageTracker::countBodyRecords(const FunctionSamples *FS) const {
379   unsigned Count = FS->getBodySamples().size();
380 
381   // Only count records in hot callsites.
382   for (const auto &I : FS->getCallsiteSamples())
383     for (const auto &J : I.second) {
384       const FunctionSamples *CalleeSamples = &J.second;
385       if (callsiteIsHot(FS, CalleeSamples))
386         Count += countBodyRecords(CalleeSamples);
387     }
388 
389   return Count;
390 }
391 
392 /// Return the number of samples collected in the body of this profile.
393 ///
394 /// This count does not include samples from cold inlined callsites.
395 uint64_t
396 SampleCoverageTracker::countBodySamples(const FunctionSamples *FS) const {
397   uint64_t Total = 0;
398   for (const auto &I : FS->getBodySamples())
399     Total += I.second.getSamples();
400 
401   // Only count samples in hot callsites.
402   for (const auto &I : FS->getCallsiteSamples())
403     for (const auto &J : I.second) {
404       const FunctionSamples *CalleeSamples = &J.second;
405       if (callsiteIsHot(FS, CalleeSamples))
406         Total += countBodySamples(CalleeSamples);
407     }
408 
409   return Total;
410 }
411 
412 /// Return the fraction of sample records used in this profile.
413 ///
414 /// The returned value is an unsigned integer in the range 0-100 indicating
415 /// the percentage of sample records that were used while applying this
416 /// profile to the associated function.
417 unsigned SampleCoverageTracker::computeCoverage(unsigned Used,
418                                                 unsigned Total) const {
419   assert(Used <= Total &&
420          "number of used records cannot exceed the total number of records");
421   return Total > 0 ? Used * 100 / Total : 100;
422 }
423 
424 /// Clear all the per-function data used to load samples and propagate weights.
425 void SampleProfileLoader::clearFunctionData() {
426   BlockWeights.clear();
427   EdgeWeights.clear();
428   VisitedBlocks.clear();
429   VisitedEdges.clear();
430   EquivalenceClass.clear();
431   DT = nullptr;
432   PDT = nullptr;
433   LI = nullptr;
434   Predecessors.clear();
435   Successors.clear();
436   CoverageTracker.clear();
437 }
438 
439 /// Returns the line offset to the start line of the subprogram.
440 /// We assume that a single function will not exceed 65535 LOC.
441 unsigned SampleProfileLoader::getOffset(const DILocation *DIL) const {
442   return (DIL->getLine() - DIL->getScope()->getSubprogram()->getLine()) &
443          0xffff;
444 }
445 
446 #ifndef NDEBUG
447 /// \brief Print the weight of edge \p E on stream \p OS.
448 ///
449 /// \param OS  Stream to emit the output to.
450 /// \param E  Edge to print.
451 void SampleProfileLoader::printEdgeWeight(raw_ostream &OS, Edge E) {
452   OS << "weight[" << E.first->getName() << "->" << E.second->getName()
453      << "]: " << EdgeWeights[E] << "\n";
454 }
455 
456 /// \brief Print the equivalence class of block \p BB on stream \p OS.
457 ///
458 /// \param OS  Stream to emit the output to.
459 /// \param BB  Block to print.
460 void SampleProfileLoader::printBlockEquivalence(raw_ostream &OS,
461                                                 const BasicBlock *BB) {
462   const BasicBlock *Equiv = EquivalenceClass[BB];
463   OS << "equivalence[" << BB->getName()
464      << "]: " << ((Equiv) ? EquivalenceClass[BB]->getName() : "NONE") << "\n";
465 }
466 
467 /// \brief Print the weight of block \p BB on stream \p OS.
468 ///
469 /// \param OS  Stream to emit the output to.
470 /// \param BB  Block to print.
471 void SampleProfileLoader::printBlockWeight(raw_ostream &OS,
472                                            const BasicBlock *BB) const {
473   const auto &I = BlockWeights.find(BB);
474   uint64_t W = (I == BlockWeights.end() ? 0 : I->second);
475   OS << "weight[" << BB->getName() << "]: " << W << "\n";
476 }
477 #endif
478 
479 /// \brief Get the weight for an instruction.
480 ///
481 /// The "weight" of an instruction \p Inst is the number of samples
482 /// collected on that instruction at runtime. To retrieve it, we
483 /// need to compute the line number of \p Inst relative to the start of its
484 /// function. We use HeaderLineno to compute the offset. We then
485 /// look up the samples collected for \p Inst using BodySamples.
486 ///
487 /// \param Inst Instruction to query.
488 ///
489 /// \returns the weight of \p Inst.
490 ErrorOr<uint64_t> SampleProfileLoader::getInstWeight(const Instruction &Inst) {
491   const DebugLoc &DLoc = Inst.getDebugLoc();
492   if (!DLoc)
493     return std::error_code();
494 
495   const FunctionSamples *FS = findFunctionSamples(Inst);
496   if (!FS)
497     return std::error_code();
498 
499   // Ignore all intrinsics and branch instructions.
500   // Branch instruction usually contains debug info from sources outside of
501   // the residing basic block, thus we ignore them during annotation.
502   if (isa<BranchInst>(Inst) || isa<IntrinsicInst>(Inst))
503     return std::error_code();
504 
505   // If a call/invoke instruction is inlined in profile, but not inlined here,
506   // it means that the inlined callsite has no sample, thus the call
507   // instruction should have 0 count.
508   if ((isa<CallInst>(Inst) || isa<InvokeInst>(Inst)) &&
509       findCalleeFunctionSamples(Inst))
510     return 0;
511 
512   const DILocation *DIL = DLoc;
513   uint32_t LineOffset = getOffset(DIL);
514   uint32_t Discriminator = DIL->getBaseDiscriminator();
515   ErrorOr<uint64_t> R = FS->findSamplesAt(LineOffset, Discriminator);
516   if (R) {
517     bool FirstMark =
518         CoverageTracker.markSamplesUsed(FS, LineOffset, Discriminator, R.get());
519     if (FirstMark) {
520       if (Discriminator)
521         ORE->emit(OptimizationRemarkAnalysis(DEBUG_TYPE, "AppliedSamples", &Inst)
522                   << "Applied " << ore::NV("NumSamples", *R)
523                   << " samples from profile (offset: "
524                   << ore::NV("LineOffset", LineOffset) << "."
525                   << ore::NV("Discriminator", Discriminator) << ")");
526       else
527         ORE->emit(OptimizationRemarkAnalysis(DEBUG_TYPE, "AppliedSamples", &Inst)
528                   << "Applied " << ore::NV("NumSamples", *R)
529                   << " samples from profile (offset: "
530                   << ore::NV("LineOffset", LineOffset) << ")");
531     }
532     DEBUG(dbgs() << "    " << DLoc.getLine() << "."
533                  << DIL->getBaseDiscriminator() << ":" << Inst
534                  << " (line offset: " << LineOffset << "."
535                  << DIL->getBaseDiscriminator() << " - weight: " << R.get()
536                  << ")\n");
537   }
538   return R;
539 }
540 
541 /// \brief Compute the weight of a basic block.
542 ///
543 /// The weight of basic block \p BB is the maximum weight of all the
544 /// instructions in BB.
545 ///
546 /// \param BB The basic block to query.
547 ///
548 /// \returns the weight for \p BB.
549 ErrorOr<uint64_t> SampleProfileLoader::getBlockWeight(const BasicBlock *BB) {
550   uint64_t Max = 0;
551   bool HasWeight = false;
552   for (auto &I : BB->getInstList()) {
553     const ErrorOr<uint64_t> &R = getInstWeight(I);
554     if (R) {
555       Max = std::max(Max, R.get());
556       HasWeight = true;
557     }
558   }
559   return HasWeight ? ErrorOr<uint64_t>(Max) : std::error_code();
560 }
561 
562 /// \brief Compute and store the weights of every basic block.
563 ///
564 /// This populates the BlockWeights map by computing
565 /// the weights of every basic block in the CFG.
566 ///
567 /// \param F The function to query.
568 bool SampleProfileLoader::computeBlockWeights(Function &F) {
569   bool Changed = false;
570   DEBUG(dbgs() << "Block weights\n");
571   for (const auto &BB : F) {
572     ErrorOr<uint64_t> Weight = getBlockWeight(&BB);
573     if (Weight) {
574       BlockWeights[&BB] = Weight.get();
575       VisitedBlocks.insert(&BB);
576       Changed = true;
577     }
578     DEBUG(printBlockWeight(dbgs(), &BB));
579   }
580 
581   return Changed;
582 }
583 
584 /// \brief Get the FunctionSamples for a call instruction.
585 ///
586 /// The FunctionSamples of a call/invoke instruction \p Inst is the inlined
587 /// instance in which that call instruction is calling to. It contains
588 /// all samples that resides in the inlined instance. We first find the
589 /// inlined instance in which the call instruction is from, then we
590 /// traverse its children to find the callsite with the matching
591 /// location.
592 ///
593 /// \param Inst Call/Invoke instruction to query.
594 ///
595 /// \returns The FunctionSamples pointer to the inlined instance.
596 const FunctionSamples *
597 SampleProfileLoader::findCalleeFunctionSamples(const Instruction &Inst) const {
598   const DILocation *DIL = Inst.getDebugLoc();
599   if (!DIL) {
600     return nullptr;
601   }
602 
603   StringRef CalleeName;
604   if (const CallInst *CI = dyn_cast<CallInst>(&Inst))
605     if (Function *Callee = CI->getCalledFunction())
606       CalleeName = Callee->getName();
607 
608   const FunctionSamples *FS = findFunctionSamples(Inst);
609   if (FS == nullptr)
610     return nullptr;
611 
612   return FS->findFunctionSamplesAt(
613       LineLocation(getOffset(DIL), DIL->getBaseDiscriminator()), CalleeName);
614 }
615 
616 /// Returns a vector of FunctionSamples that are the indirect call targets
617 /// of \p Inst. The vector is sorted by the total number of samples.
618 std::vector<const FunctionSamples *>
619 SampleProfileLoader::findIndirectCallFunctionSamples(
620     const Instruction &Inst) const {
621   const DILocation *DIL = Inst.getDebugLoc();
622   std::vector<const FunctionSamples *> R;
623 
624   if (!DIL) {
625     return R;
626   }
627 
628   const FunctionSamples *FS = findFunctionSamples(Inst);
629   if (FS == nullptr)
630     return R;
631 
632   if (const FunctionSamplesMap *M = FS->findFunctionSamplesMapAt(
633           LineLocation(getOffset(DIL), DIL->getBaseDiscriminator()))) {
634     if (M->size() == 0)
635       return R;
636     for (const auto &NameFS : *M) {
637       R.push_back(&NameFS.second);
638     }
639     std::sort(R.begin(), R.end(),
640               [](const FunctionSamples *L, const FunctionSamples *R) {
641                 return L->getTotalSamples() > R->getTotalSamples();
642               });
643   }
644   return R;
645 }
646 
647 /// \brief Get the FunctionSamples for an instruction.
648 ///
649 /// The FunctionSamples of an instruction \p Inst is the inlined instance
650 /// in which that instruction is coming from. We traverse the inline stack
651 /// of that instruction, and match it with the tree nodes in the profile.
652 ///
653 /// \param Inst Instruction to query.
654 ///
655 /// \returns the FunctionSamples pointer to the inlined instance.
656 const FunctionSamples *
657 SampleProfileLoader::findFunctionSamples(const Instruction &Inst) const {
658   SmallVector<std::pair<LineLocation, StringRef>, 10> S;
659   const DILocation *DIL = Inst.getDebugLoc();
660   if (!DIL)
661     return Samples;
662 
663   const DILocation *PrevDIL = DIL;
664   for (DIL = DIL->getInlinedAt(); DIL; DIL = DIL->getInlinedAt()) {
665     S.push_back(std::make_pair(
666         LineLocation(getOffset(DIL), DIL->getBaseDiscriminator()),
667         PrevDIL->getScope()->getSubprogram()->getLinkageName()));
668     PrevDIL = DIL;
669   }
670   if (S.size() == 0)
671     return Samples;
672   const FunctionSamples *FS = Samples;
673   for (int i = S.size() - 1; i >= 0 && FS != nullptr; i--) {
674     FS = FS->findFunctionSamplesAt(S[i].first, S[i].second);
675   }
676   return FS;
677 }
678 
679 /// \brief Iteratively inline hot callsites of a function.
680 ///
681 /// Iteratively traverse all callsites of the function \p F, and find if
682 /// the corresponding inlined instance exists and is hot in profile. If
683 /// it is hot enough, inline the callsites and adds new callsites of the
684 /// callee into the caller. If the call is an indirect call, first promote
685 /// it to direct call. Each indirect call is limited with a single target.
686 ///
687 /// \param F function to perform iterative inlining.
688 /// \param ImportGUIDs a set to be updated to include all GUIDs that come
689 ///     from a different module but inlined in the profiled binary.
690 ///
691 /// \returns True if there is any inline happened.
692 bool SampleProfileLoader::inlineHotFunctions(
693     Function &F, DenseSet<GlobalValue::GUID> &ImportGUIDs) {
694   DenseSet<Instruction *> PromotedInsns;
695   bool Changed = false;
696   while (true) {
697     bool LocalChanged = false;
698     SmallVector<Instruction *, 10> CIS;
699     for (auto &BB : F) {
700       bool Hot = false;
701       SmallVector<Instruction *, 10> Candidates;
702       for (auto &I : BB.getInstList()) {
703         const FunctionSamples *FS = nullptr;
704         if ((isa<CallInst>(I) || isa<InvokeInst>(I)) &&
705             !isa<IntrinsicInst>(I) && (FS = findCalleeFunctionSamples(I))) {
706           Candidates.push_back(&I);
707           if (callsiteIsHot(Samples, FS))
708             Hot = true;
709         }
710       }
711       if (Hot) {
712         CIS.insert(CIS.begin(), Candidates.begin(), Candidates.end());
713       }
714     }
715     for (auto I : CIS) {
716       InlineFunctionInfo IFI(nullptr, &GetAC);
717       Function *CalledFunction = CallSite(I).getCalledFunction();
718       // Do not inline recursive calls.
719       if (CalledFunction == &F)
720         continue;
721       Instruction *DI = I;
722       if (!CalledFunction && !PromotedInsns.count(I) &&
723           CallSite(I).isIndirectCall())
724         for (const auto *FS : findIndirectCallFunctionSamples(*I)) {
725           auto CalleeFunctionName = FS->getName();
726           // If it is a recursive call, we do not inline it as it could bloat
727           // the code exponentially. There is way to better handle this, e.g.
728           // clone the caller first, and inline the cloned caller if it is
729           // recursive. As llvm does not inline recursive calls, we will simply
730           // ignore it instead of handling it explicitly.
731           if (CalleeFunctionName == F.getName())
732             continue;
733           const char *Reason = "Callee function not available";
734           auto R = SymbolMap.find(CalleeFunctionName);
735           if (R == SymbolMap.end())
736             continue;
737           CalledFunction = R->getValue();
738           if (CalledFunction && isLegalToPromote(I, CalledFunction, &Reason)) {
739             // The indirect target was promoted and inlined in the profile, as a
740             // result, we do not have profile info for the branch probability.
741             // We set the probability to 80% taken to indicate that the static
742             // call is likely taken.
743             DI = dyn_cast<Instruction>(
744                 promoteIndirectCall(I, CalledFunction, 80, 100, false, ORE)
745                     ->stripPointerCasts());
746             PromotedInsns.insert(I);
747           } else {
748             DEBUG(dbgs() << "\nFailed to promote indirect call to "
749                          << CalleeFunctionName << " because " << Reason
750                          << "\n");
751             continue;
752           }
753         }
754       if (!CalledFunction || !CalledFunction->getSubprogram()) {
755         findCalleeFunctionSamples(*I)->findImportedFunctions(
756             ImportGUIDs, F.getParent(),
757             Samples->getTotalSamples() * SampleProfileHotThreshold / 100);
758         continue;
759       }
760       CallSite CS(DI);
761       DebugLoc DLoc = I->getDebugLoc();
762       BasicBlock *BB = I->getParent();
763       InlineParams Params = getInlineParams();
764       Params.ComputeFullInlineCost = true;
765       // Checks if there is anything in the reachable portion of the callee at
766       // this callsite that makes this inlining potentially illegal. Need to
767       // set ComputeFullInlineCost, otherwise getInlineCost may return early
768       // when cost exceeds threshold without checking all IRs in the callee.
769       // The acutal cost does not matter because we only checks isNever() to
770       // see if it is legal to inline the callsite.
771       InlineCost Cost = getInlineCost(CS, Params, GetTTI(*CalledFunction), GetAC,
772                                       None, nullptr, nullptr);
773       if (Cost.isNever()) {
774         ORE->emit(OptimizationRemark(DEBUG_TYPE, "Not inline", DLoc, BB)
775                   << "incompatible inlining");
776         continue;
777       }
778       if (InlineFunction(CS, IFI)) {
779         LocalChanged = true;
780         // The call to InlineFunction erases DI, so we can't pass it here.
781         ORE->emit(OptimizationRemark(DEBUG_TYPE, "HotInline", DLoc, BB)
782                   << "inlined hot callee '"
783                   << ore::NV("Callee", CalledFunction) << "' into '"
784                   << ore::NV("Caller", &F) << "'");
785       }
786     }
787     if (LocalChanged) {
788       Changed = true;
789     } else {
790       break;
791     }
792   }
793   return Changed;
794 }
795 
796 /// \brief Find equivalence classes for the given block.
797 ///
798 /// This finds all the blocks that are guaranteed to execute the same
799 /// number of times as \p BB1. To do this, it traverses all the
800 /// descendants of \p BB1 in the dominator or post-dominator tree.
801 ///
802 /// A block BB2 will be in the same equivalence class as \p BB1 if
803 /// the following holds:
804 ///
805 /// 1- \p BB1 is a descendant of BB2 in the opposite tree. So, if BB2
806 ///    is a descendant of \p BB1 in the dominator tree, then BB2 should
807 ///    dominate BB1 in the post-dominator tree.
808 ///
809 /// 2- Both BB2 and \p BB1 must be in the same loop.
810 ///
811 /// For every block BB2 that meets those two requirements, we set BB2's
812 /// equivalence class to \p BB1.
813 ///
814 /// \param BB1  Block to check.
815 /// \param Descendants  Descendants of \p BB1 in either the dom or pdom tree.
816 /// \param DomTree  Opposite dominator tree. If \p Descendants is filled
817 ///                 with blocks from \p BB1's dominator tree, then
818 ///                 this is the post-dominator tree, and vice versa.
819 template <bool IsPostDom>
820 void SampleProfileLoader::findEquivalencesFor(
821     BasicBlock *BB1, ArrayRef<BasicBlock *> Descendants,
822     DominatorTreeBase<BasicBlock, IsPostDom> *DomTree) {
823   const BasicBlock *EC = EquivalenceClass[BB1];
824   uint64_t Weight = BlockWeights[EC];
825   for (const auto *BB2 : Descendants) {
826     bool IsDomParent = DomTree->dominates(BB2, BB1);
827     bool IsInSameLoop = LI->getLoopFor(BB1) == LI->getLoopFor(BB2);
828     if (BB1 != BB2 && IsDomParent && IsInSameLoop) {
829       EquivalenceClass[BB2] = EC;
830       // If BB2 is visited, then the entire EC should be marked as visited.
831       if (VisitedBlocks.count(BB2)) {
832         VisitedBlocks.insert(EC);
833       }
834 
835       // If BB2 is heavier than BB1, make BB2 have the same weight
836       // as BB1.
837       //
838       // Note that we don't worry about the opposite situation here
839       // (when BB2 is lighter than BB1). We will deal with this
840       // during the propagation phase. Right now, we just want to
841       // make sure that BB1 has the largest weight of all the
842       // members of its equivalence set.
843       Weight = std::max(Weight, BlockWeights[BB2]);
844     }
845   }
846   if (EC == &EC->getParent()->getEntryBlock()) {
847     BlockWeights[EC] = Samples->getHeadSamples() + 1;
848   } else {
849     BlockWeights[EC] = Weight;
850   }
851 }
852 
853 /// \brief Find equivalence classes.
854 ///
855 /// Since samples may be missing from blocks, we can fill in the gaps by setting
856 /// the weights of all the blocks in the same equivalence class to the same
857 /// weight. To compute the concept of equivalence, we use dominance and loop
858 /// information. Two blocks B1 and B2 are in the same equivalence class if B1
859 /// dominates B2, B2 post-dominates B1 and both are in the same loop.
860 ///
861 /// \param F The function to query.
862 void SampleProfileLoader::findEquivalenceClasses(Function &F) {
863   SmallVector<BasicBlock *, 8> DominatedBBs;
864   DEBUG(dbgs() << "\nBlock equivalence classes\n");
865   // Find equivalence sets based on dominance and post-dominance information.
866   for (auto &BB : F) {
867     BasicBlock *BB1 = &BB;
868 
869     // Compute BB1's equivalence class once.
870     if (EquivalenceClass.count(BB1)) {
871       DEBUG(printBlockEquivalence(dbgs(), BB1));
872       continue;
873     }
874 
875     // By default, blocks are in their own equivalence class.
876     EquivalenceClass[BB1] = BB1;
877 
878     // Traverse all the blocks dominated by BB1. We are looking for
879     // every basic block BB2 such that:
880     //
881     // 1- BB1 dominates BB2.
882     // 2- BB2 post-dominates BB1.
883     // 3- BB1 and BB2 are in the same loop nest.
884     //
885     // If all those conditions hold, it means that BB2 is executed
886     // as many times as BB1, so they are placed in the same equivalence
887     // class by making BB2's equivalence class be BB1.
888     DominatedBBs.clear();
889     DT->getDescendants(BB1, DominatedBBs);
890     findEquivalencesFor(BB1, DominatedBBs, PDT.get());
891 
892     DEBUG(printBlockEquivalence(dbgs(), BB1));
893   }
894 
895   // Assign weights to equivalence classes.
896   //
897   // All the basic blocks in the same equivalence class will execute
898   // the same number of times. Since we know that the head block in
899   // each equivalence class has the largest weight, assign that weight
900   // to all the blocks in that equivalence class.
901   DEBUG(dbgs() << "\nAssign the same weight to all blocks in the same class\n");
902   for (auto &BI : F) {
903     const BasicBlock *BB = &BI;
904     const BasicBlock *EquivBB = EquivalenceClass[BB];
905     if (BB != EquivBB)
906       BlockWeights[BB] = BlockWeights[EquivBB];
907     DEBUG(printBlockWeight(dbgs(), BB));
908   }
909 }
910 
911 /// \brief Visit the given edge to decide if it has a valid weight.
912 ///
913 /// If \p E has not been visited before, we copy to \p UnknownEdge
914 /// and increment the count of unknown edges.
915 ///
916 /// \param E  Edge to visit.
917 /// \param NumUnknownEdges  Current number of unknown edges.
918 /// \param UnknownEdge  Set if E has not been visited before.
919 ///
920 /// \returns E's weight, if known. Otherwise, return 0.
921 uint64_t SampleProfileLoader::visitEdge(Edge E, unsigned *NumUnknownEdges,
922                                         Edge *UnknownEdge) {
923   if (!VisitedEdges.count(E)) {
924     (*NumUnknownEdges)++;
925     *UnknownEdge = E;
926     return 0;
927   }
928 
929   return EdgeWeights[E];
930 }
931 
932 /// \brief Propagate weights through incoming/outgoing edges.
933 ///
934 /// If the weight of a basic block is known, and there is only one edge
935 /// with an unknown weight, we can calculate the weight of that edge.
936 ///
937 /// Similarly, if all the edges have a known count, we can calculate the
938 /// count of the basic block, if needed.
939 ///
940 /// \param F  Function to process.
941 /// \param UpdateBlockCount  Whether we should update basic block counts that
942 ///                          has already been annotated.
943 ///
944 /// \returns  True if new weights were assigned to edges or blocks.
945 bool SampleProfileLoader::propagateThroughEdges(Function &F,
946                                                 bool UpdateBlockCount) {
947   bool Changed = false;
948   DEBUG(dbgs() << "\nPropagation through edges\n");
949   for (const auto &BI : F) {
950     const BasicBlock *BB = &BI;
951     const BasicBlock *EC = EquivalenceClass[BB];
952 
953     // Visit all the predecessor and successor edges to determine
954     // which ones have a weight assigned already. Note that it doesn't
955     // matter that we only keep track of a single unknown edge. The
956     // only case we are interested in handling is when only a single
957     // edge is unknown (see setEdgeOrBlockWeight).
958     for (unsigned i = 0; i < 2; i++) {
959       uint64_t TotalWeight = 0;
960       unsigned NumUnknownEdges = 0, NumTotalEdges = 0;
961       Edge UnknownEdge, SelfReferentialEdge, SingleEdge;
962 
963       if (i == 0) {
964         // First, visit all predecessor edges.
965         NumTotalEdges = Predecessors[BB].size();
966         for (auto *Pred : Predecessors[BB]) {
967           Edge E = std::make_pair(Pred, BB);
968           TotalWeight += visitEdge(E, &NumUnknownEdges, &UnknownEdge);
969           if (E.first == E.second)
970             SelfReferentialEdge = E;
971         }
972         if (NumTotalEdges == 1) {
973           SingleEdge = std::make_pair(Predecessors[BB][0], BB);
974         }
975       } else {
976         // On the second round, visit all successor edges.
977         NumTotalEdges = Successors[BB].size();
978         for (auto *Succ : Successors[BB]) {
979           Edge E = std::make_pair(BB, Succ);
980           TotalWeight += visitEdge(E, &NumUnknownEdges, &UnknownEdge);
981         }
982         if (NumTotalEdges == 1) {
983           SingleEdge = std::make_pair(BB, Successors[BB][0]);
984         }
985       }
986 
987       // After visiting all the edges, there are three cases that we
988       // can handle immediately:
989       //
990       // - All the edge weights are known (i.e., NumUnknownEdges == 0).
991       //   In this case, we simply check that the sum of all the edges
992       //   is the same as BB's weight. If not, we change BB's weight
993       //   to match. Additionally, if BB had not been visited before,
994       //   we mark it visited.
995       //
996       // - Only one edge is unknown and BB has already been visited.
997       //   In this case, we can compute the weight of the edge by
998       //   subtracting the total block weight from all the known
999       //   edge weights. If the edges weight more than BB, then the
1000       //   edge of the last remaining edge is set to zero.
1001       //
1002       // - There exists a self-referential edge and the weight of BB is
1003       //   known. In this case, this edge can be based on BB's weight.
1004       //   We add up all the other known edges and set the weight on
1005       //   the self-referential edge as we did in the previous case.
1006       //
1007       // In any other case, we must continue iterating. Eventually,
1008       // all edges will get a weight, or iteration will stop when
1009       // it reaches SampleProfileMaxPropagateIterations.
1010       if (NumUnknownEdges <= 1) {
1011         uint64_t &BBWeight = BlockWeights[EC];
1012         if (NumUnknownEdges == 0) {
1013           if (!VisitedBlocks.count(EC)) {
1014             // If we already know the weight of all edges, the weight of the
1015             // basic block can be computed. It should be no larger than the sum
1016             // of all edge weights.
1017             if (TotalWeight > BBWeight) {
1018               BBWeight = TotalWeight;
1019               Changed = true;
1020               DEBUG(dbgs() << "All edge weights for " << BB->getName()
1021                            << " known. Set weight for block: ";
1022                     printBlockWeight(dbgs(), BB););
1023             }
1024           } else if (NumTotalEdges == 1 &&
1025                      EdgeWeights[SingleEdge] < BlockWeights[EC]) {
1026             // If there is only one edge for the visited basic block, use the
1027             // block weight to adjust edge weight if edge weight is smaller.
1028             EdgeWeights[SingleEdge] = BlockWeights[EC];
1029             Changed = true;
1030           }
1031         } else if (NumUnknownEdges == 1 && VisitedBlocks.count(EC)) {
1032           // If there is a single unknown edge and the block has been
1033           // visited, then we can compute E's weight.
1034           if (BBWeight >= TotalWeight)
1035             EdgeWeights[UnknownEdge] = BBWeight - TotalWeight;
1036           else
1037             EdgeWeights[UnknownEdge] = 0;
1038           const BasicBlock *OtherEC;
1039           if (i == 0)
1040             OtherEC = EquivalenceClass[UnknownEdge.first];
1041           else
1042             OtherEC = EquivalenceClass[UnknownEdge.second];
1043           // Edge weights should never exceed the BB weights it connects.
1044           if (VisitedBlocks.count(OtherEC) &&
1045               EdgeWeights[UnknownEdge] > BlockWeights[OtherEC])
1046             EdgeWeights[UnknownEdge] = BlockWeights[OtherEC];
1047           VisitedEdges.insert(UnknownEdge);
1048           Changed = true;
1049           DEBUG(dbgs() << "Set weight for edge: ";
1050                 printEdgeWeight(dbgs(), UnknownEdge));
1051         }
1052       } else if (VisitedBlocks.count(EC) && BlockWeights[EC] == 0) {
1053         // If a block Weights 0, all its in/out edges should weight 0.
1054         if (i == 0) {
1055           for (auto *Pred : Predecessors[BB]) {
1056             Edge E = std::make_pair(Pred, BB);
1057             EdgeWeights[E] = 0;
1058             VisitedEdges.insert(E);
1059           }
1060         } else {
1061           for (auto *Succ : Successors[BB]) {
1062             Edge E = std::make_pair(BB, Succ);
1063             EdgeWeights[E] = 0;
1064             VisitedEdges.insert(E);
1065           }
1066         }
1067       } else if (SelfReferentialEdge.first && VisitedBlocks.count(EC)) {
1068         uint64_t &BBWeight = BlockWeights[BB];
1069         // We have a self-referential edge and the weight of BB is known.
1070         if (BBWeight >= TotalWeight)
1071           EdgeWeights[SelfReferentialEdge] = BBWeight - TotalWeight;
1072         else
1073           EdgeWeights[SelfReferentialEdge] = 0;
1074         VisitedEdges.insert(SelfReferentialEdge);
1075         Changed = true;
1076         DEBUG(dbgs() << "Set self-referential edge weight to: ";
1077               printEdgeWeight(dbgs(), SelfReferentialEdge));
1078       }
1079       if (UpdateBlockCount && !VisitedBlocks.count(EC) && TotalWeight > 0) {
1080         BlockWeights[EC] = TotalWeight;
1081         VisitedBlocks.insert(EC);
1082         Changed = true;
1083       }
1084     }
1085   }
1086 
1087   return Changed;
1088 }
1089 
1090 /// \brief Build in/out edge lists for each basic block in the CFG.
1091 ///
1092 /// We are interested in unique edges. If a block B1 has multiple
1093 /// edges to another block B2, we only add a single B1->B2 edge.
1094 void SampleProfileLoader::buildEdges(Function &F) {
1095   for (auto &BI : F) {
1096     BasicBlock *B1 = &BI;
1097 
1098     // Add predecessors for B1.
1099     SmallPtrSet<BasicBlock *, 16> Visited;
1100     if (!Predecessors[B1].empty())
1101       llvm_unreachable("Found a stale predecessors list in a basic block.");
1102     for (pred_iterator PI = pred_begin(B1), PE = pred_end(B1); PI != PE; ++PI) {
1103       BasicBlock *B2 = *PI;
1104       if (Visited.insert(B2).second)
1105         Predecessors[B1].push_back(B2);
1106     }
1107 
1108     // Add successors for B1.
1109     Visited.clear();
1110     if (!Successors[B1].empty())
1111       llvm_unreachable("Found a stale successors list in a basic block.");
1112     for (succ_iterator SI = succ_begin(B1), SE = succ_end(B1); SI != SE; ++SI) {
1113       BasicBlock *B2 = *SI;
1114       if (Visited.insert(B2).second)
1115         Successors[B1].push_back(B2);
1116     }
1117   }
1118 }
1119 
1120 /// Sorts the CallTargetMap \p M by count in descending order and stores the
1121 /// sorted result in \p Sorted. Returns the total counts.
1122 static uint64_t SortCallTargets(SmallVector<InstrProfValueData, 2> &Sorted,
1123                                 const SampleRecord::CallTargetMap &M) {
1124   Sorted.clear();
1125   uint64_t Sum = 0;
1126   for (auto I = M.begin(); I != M.end(); ++I) {
1127     Sum += I->getValue();
1128     Sorted.push_back({Function::getGUID(I->getKey()), I->getValue()});
1129   }
1130   std::sort(Sorted.begin(), Sorted.end(),
1131             [](const InstrProfValueData &L, const InstrProfValueData &R) {
1132               if (L.Count == R.Count)
1133                 return L.Value > R.Value;
1134               else
1135                 return L.Count > R.Count;
1136             });
1137   return Sum;
1138 }
1139 
1140 /// \brief Propagate weights into edges
1141 ///
1142 /// The following rules are applied to every block BB in the CFG:
1143 ///
1144 /// - If BB has a single predecessor/successor, then the weight
1145 ///   of that edge is the weight of the block.
1146 ///
1147 /// - If all incoming or outgoing edges are known except one, and the
1148 ///   weight of the block is already known, the weight of the unknown
1149 ///   edge will be the weight of the block minus the sum of all the known
1150 ///   edges. If the sum of all the known edges is larger than BB's weight,
1151 ///   we set the unknown edge weight to zero.
1152 ///
1153 /// - If there is a self-referential edge, and the weight of the block is
1154 ///   known, the weight for that edge is set to the weight of the block
1155 ///   minus the weight of the other incoming edges to that block (if
1156 ///   known).
1157 void SampleProfileLoader::propagateWeights(Function &F) {
1158   bool Changed = true;
1159   unsigned I = 0;
1160 
1161   // If BB weight is larger than its corresponding loop's header BB weight,
1162   // use the BB weight to replace the loop header BB weight.
1163   for (auto &BI : F) {
1164     BasicBlock *BB = &BI;
1165     Loop *L = LI->getLoopFor(BB);
1166     if (!L) {
1167       continue;
1168     }
1169     BasicBlock *Header = L->getHeader();
1170     if (Header && BlockWeights[BB] > BlockWeights[Header]) {
1171       BlockWeights[Header] = BlockWeights[BB];
1172     }
1173   }
1174 
1175   // Before propagation starts, build, for each block, a list of
1176   // unique predecessors and successors. This is necessary to handle
1177   // identical edges in multiway branches. Since we visit all blocks and all
1178   // edges of the CFG, it is cleaner to build these lists once at the start
1179   // of the pass.
1180   buildEdges(F);
1181 
1182   // Propagate until we converge or we go past the iteration limit.
1183   while (Changed && I++ < SampleProfileMaxPropagateIterations) {
1184     Changed = propagateThroughEdges(F, false);
1185   }
1186 
1187   // The first propagation propagates BB counts from annotated BBs to unknown
1188   // BBs. The 2nd propagation pass resets edges weights, and use all BB weights
1189   // to propagate edge weights.
1190   VisitedEdges.clear();
1191   Changed = true;
1192   while (Changed && I++ < SampleProfileMaxPropagateIterations) {
1193     Changed = propagateThroughEdges(F, false);
1194   }
1195 
1196   // The 3rd propagation pass allows adjust annotated BB weights that are
1197   // obviously wrong.
1198   Changed = true;
1199   while (Changed && I++ < SampleProfileMaxPropagateIterations) {
1200     Changed = propagateThroughEdges(F, true);
1201   }
1202 
1203   // Generate MD_prof metadata for every branch instruction using the
1204   // edge weights computed during propagation.
1205   DEBUG(dbgs() << "\nPropagation complete. Setting branch weights\n");
1206   LLVMContext &Ctx = F.getContext();
1207   MDBuilder MDB(Ctx);
1208   for (auto &BI : F) {
1209     BasicBlock *BB = &BI;
1210 
1211     if (BlockWeights[BB]) {
1212       for (auto &I : BB->getInstList()) {
1213         if (!isa<CallInst>(I) && !isa<InvokeInst>(I))
1214           continue;
1215         CallSite CS(&I);
1216         if (!CS.getCalledFunction()) {
1217           const DebugLoc &DLoc = I.getDebugLoc();
1218           if (!DLoc)
1219             continue;
1220           const DILocation *DIL = DLoc;
1221           uint32_t LineOffset = getOffset(DIL);
1222           uint32_t Discriminator = DIL->getBaseDiscriminator();
1223 
1224           const FunctionSamples *FS = findFunctionSamples(I);
1225           if (!FS)
1226             continue;
1227           auto T = FS->findCallTargetMapAt(LineOffset, Discriminator);
1228           if (!T || T.get().size() == 0)
1229             continue;
1230           SmallVector<InstrProfValueData, 2> SortedCallTargets;
1231           uint64_t Sum = SortCallTargets(SortedCallTargets, T.get());
1232           annotateValueSite(*I.getParent()->getParent()->getParent(), I,
1233                             SortedCallTargets, Sum, IPVK_IndirectCallTarget,
1234                             SortedCallTargets.size());
1235         } else if (!dyn_cast<IntrinsicInst>(&I)) {
1236           SmallVector<uint32_t, 1> Weights;
1237           Weights.push_back(BlockWeights[BB]);
1238           I.setMetadata(LLVMContext::MD_prof, MDB.createBranchWeights(Weights));
1239         }
1240       }
1241     }
1242     TerminatorInst *TI = BB->getTerminator();
1243     if (TI->getNumSuccessors() == 1)
1244       continue;
1245     if (!isa<BranchInst>(TI) && !isa<SwitchInst>(TI))
1246       continue;
1247 
1248     DebugLoc BranchLoc = TI->getDebugLoc();
1249     DEBUG(dbgs() << "\nGetting weights for branch at line "
1250                  << ((BranchLoc) ? Twine(BranchLoc.getLine())
1251                                  : Twine("<UNKNOWN LOCATION>"))
1252                  << ".\n");
1253     SmallVector<uint32_t, 4> Weights;
1254     uint32_t MaxWeight = 0;
1255     Instruction *MaxDestInst;
1256     for (unsigned I = 0; I < TI->getNumSuccessors(); ++I) {
1257       BasicBlock *Succ = TI->getSuccessor(I);
1258       Edge E = std::make_pair(BB, Succ);
1259       uint64_t Weight = EdgeWeights[E];
1260       DEBUG(dbgs() << "\t"; printEdgeWeight(dbgs(), E));
1261       // Use uint32_t saturated arithmetic to adjust the incoming weights,
1262       // if needed. Sample counts in profiles are 64-bit unsigned values,
1263       // but internally branch weights are expressed as 32-bit values.
1264       if (Weight > std::numeric_limits<uint32_t>::max()) {
1265         DEBUG(dbgs() << " (saturated due to uint32_t overflow)");
1266         Weight = std::numeric_limits<uint32_t>::max();
1267       }
1268       // Weight is added by one to avoid propagation errors introduced by
1269       // 0 weights.
1270       Weights.push_back(static_cast<uint32_t>(Weight + 1));
1271       if (Weight != 0) {
1272         if (Weight > MaxWeight) {
1273           MaxWeight = Weight;
1274           MaxDestInst = Succ->getFirstNonPHIOrDbgOrLifetime();
1275         }
1276       }
1277     }
1278 
1279     uint64_t TempWeight;
1280     // Only set weights if there is at least one non-zero weight.
1281     // In any other case, let the analyzer set weights.
1282     // Do not set weights if the weights are present. In ThinLTO, the profile
1283     // annotation is done twice. If the first annotation already set the
1284     // weights, the second pass does not need to set it.
1285     if (MaxWeight > 0 && !TI->extractProfTotalWeight(TempWeight)) {
1286       DEBUG(dbgs() << "SUCCESS. Found non-zero weights.\n");
1287       TI->setMetadata(llvm::LLVMContext::MD_prof,
1288                       MDB.createBranchWeights(Weights));
1289       ORE->emit(OptimizationRemark(DEBUG_TYPE, "PopularDest", MaxDestInst)
1290                 << "most popular destination for conditional branches at "
1291                 << ore::NV("CondBranchesLoc", BranchLoc));
1292     } else {
1293       DEBUG(dbgs() << "SKIPPED. All branch weights are zero.\n");
1294     }
1295   }
1296 }
1297 
1298 /// \brief Get the line number for the function header.
1299 ///
1300 /// This looks up function \p F in the current compilation unit and
1301 /// retrieves the line number where the function is defined. This is
1302 /// line 0 for all the samples read from the profile file. Every line
1303 /// number is relative to this line.
1304 ///
1305 /// \param F  Function object to query.
1306 ///
1307 /// \returns the line number where \p F is defined. If it returns 0,
1308 ///          it means that there is no debug information available for \p F.
1309 unsigned SampleProfileLoader::getFunctionLoc(Function &F) {
1310   if (DISubprogram *S = F.getSubprogram())
1311     return S->getLine();
1312 
1313   // If the start of \p F is missing, emit a diagnostic to inform the user
1314   // about the missed opportunity.
1315   F.getContext().diagnose(DiagnosticInfoSampleProfile(
1316       "No debug information found in function " + F.getName() +
1317           ": Function profile not used",
1318       DS_Warning));
1319   return 0;
1320 }
1321 
1322 void SampleProfileLoader::computeDominanceAndLoopInfo(Function &F) {
1323   DT.reset(new DominatorTree);
1324   DT->recalculate(F);
1325 
1326   PDT.reset(new PostDomTreeBase<BasicBlock>());
1327   PDT->recalculate(F);
1328 
1329   LI.reset(new LoopInfo);
1330   LI->analyze(*DT);
1331 }
1332 
1333 /// \brief Generate branch weight metadata for all branches in \p F.
1334 ///
1335 /// Branch weights are computed out of instruction samples using a
1336 /// propagation heuristic. Propagation proceeds in 3 phases:
1337 ///
1338 /// 1- Assignment of block weights. All the basic blocks in the function
1339 ///    are initial assigned the same weight as their most frequently
1340 ///    executed instruction.
1341 ///
1342 /// 2- Creation of equivalence classes. Since samples may be missing from
1343 ///    blocks, we can fill in the gaps by setting the weights of all the
1344 ///    blocks in the same equivalence class to the same weight. To compute
1345 ///    the concept of equivalence, we use dominance and loop information.
1346 ///    Two blocks B1 and B2 are in the same equivalence class if B1
1347 ///    dominates B2, B2 post-dominates B1 and both are in the same loop.
1348 ///
1349 /// 3- Propagation of block weights into edges. This uses a simple
1350 ///    propagation heuristic. The following rules are applied to every
1351 ///    block BB in the CFG:
1352 ///
1353 ///    - If BB has a single predecessor/successor, then the weight
1354 ///      of that edge is the weight of the block.
1355 ///
1356 ///    - If all the edges are known except one, and the weight of the
1357 ///      block is already known, the weight of the unknown edge will
1358 ///      be the weight of the block minus the sum of all the known
1359 ///      edges. If the sum of all the known edges is larger than BB's weight,
1360 ///      we set the unknown edge weight to zero.
1361 ///
1362 ///    - If there is a self-referential edge, and the weight of the block is
1363 ///      known, the weight for that edge is set to the weight of the block
1364 ///      minus the weight of the other incoming edges to that block (if
1365 ///      known).
1366 ///
1367 /// Since this propagation is not guaranteed to finalize for every CFG, we
1368 /// only allow it to proceed for a limited number of iterations (controlled
1369 /// by -sample-profile-max-propagate-iterations).
1370 ///
1371 /// FIXME: Try to replace this propagation heuristic with a scheme
1372 /// that is guaranteed to finalize. A work-list approach similar to
1373 /// the standard value propagation algorithm used by SSA-CCP might
1374 /// work here.
1375 ///
1376 /// Once all the branch weights are computed, we emit the MD_prof
1377 /// metadata on BB using the computed values for each of its branches.
1378 ///
1379 /// \param F The function to query.
1380 ///
1381 /// \returns true if \p F was modified. Returns false, otherwise.
1382 bool SampleProfileLoader::emitAnnotations(Function &F) {
1383   bool Changed = false;
1384 
1385   if (getFunctionLoc(F) == 0)
1386     return false;
1387 
1388   DEBUG(dbgs() << "Line number for the first instruction in " << F.getName()
1389                << ": " << getFunctionLoc(F) << "\n");
1390 
1391   DenseSet<GlobalValue::GUID> ImportGUIDs;
1392   Changed |= inlineHotFunctions(F, ImportGUIDs);
1393 
1394   // Compute basic block weights.
1395   Changed |= computeBlockWeights(F);
1396 
1397   if (Changed) {
1398     // Add an entry count to the function using the samples gathered at the
1399     // function entry. Also sets the GUIDs that comes from a different
1400     // module but inlined in the profiled binary. This is aiming at making
1401     // the IR match the profiled binary before annotation.
1402     F.setEntryCount(Samples->getHeadSamples() + 1, &ImportGUIDs);
1403 
1404     // Compute dominance and loop info needed for propagation.
1405     computeDominanceAndLoopInfo(F);
1406 
1407     // Find equivalence classes.
1408     findEquivalenceClasses(F);
1409 
1410     // Propagate weights to all edges.
1411     propagateWeights(F);
1412   }
1413 
1414   // If coverage checking was requested, compute it now.
1415   if (SampleProfileRecordCoverage) {
1416     unsigned Used = CoverageTracker.countUsedRecords(Samples);
1417     unsigned Total = CoverageTracker.countBodyRecords(Samples);
1418     unsigned Coverage = CoverageTracker.computeCoverage(Used, Total);
1419     if (Coverage < SampleProfileRecordCoverage) {
1420       F.getContext().diagnose(DiagnosticInfoSampleProfile(
1421           F.getSubprogram()->getFilename(), getFunctionLoc(F),
1422           Twine(Used) + " of " + Twine(Total) + " available profile records (" +
1423               Twine(Coverage) + "%) were applied",
1424           DS_Warning));
1425     }
1426   }
1427 
1428   if (SampleProfileSampleCoverage) {
1429     uint64_t Used = CoverageTracker.getTotalUsedSamples();
1430     uint64_t Total = CoverageTracker.countBodySamples(Samples);
1431     unsigned Coverage = CoverageTracker.computeCoverage(Used, Total);
1432     if (Coverage < SampleProfileSampleCoverage) {
1433       F.getContext().diagnose(DiagnosticInfoSampleProfile(
1434           F.getSubprogram()->getFilename(), getFunctionLoc(F),
1435           Twine(Used) + " of " + Twine(Total) + " available profile samples (" +
1436               Twine(Coverage) + "%) were applied",
1437           DS_Warning));
1438     }
1439   }
1440   return Changed;
1441 }
1442 
1443 char SampleProfileLoaderLegacyPass::ID = 0;
1444 INITIALIZE_PASS_BEGIN(SampleProfileLoaderLegacyPass, "sample-profile",
1445                       "Sample Profile loader", false, false)
1446 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
1447 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
1448 INITIALIZE_PASS_END(SampleProfileLoaderLegacyPass, "sample-profile",
1449                     "Sample Profile loader", false, false)
1450 
1451 bool SampleProfileLoader::doInitialization(Module &M) {
1452   auto &Ctx = M.getContext();
1453   auto ReaderOrErr = SampleProfileReader::create(Filename, Ctx);
1454   if (std::error_code EC = ReaderOrErr.getError()) {
1455     std::string Msg = "Could not open profile: " + EC.message();
1456     Ctx.diagnose(DiagnosticInfoSampleProfile(Filename, Msg));
1457     return false;
1458   }
1459   Reader = std::move(ReaderOrErr.get());
1460   ProfileIsValid = (Reader->read() == sampleprof_error::success);
1461   return true;
1462 }
1463 
1464 ModulePass *llvm::createSampleProfileLoaderPass() {
1465   return new SampleProfileLoaderLegacyPass(SampleProfileFile);
1466 }
1467 
1468 ModulePass *llvm::createSampleProfileLoaderPass(StringRef Name) {
1469   return new SampleProfileLoaderLegacyPass(Name);
1470 }
1471 
1472 bool SampleProfileLoader::runOnModule(Module &M, ModuleAnalysisManager *AM) {
1473   if (!ProfileIsValid)
1474     return false;
1475 
1476   // Compute the total number of samples collected in this profile.
1477   for (const auto &I : Reader->getProfiles())
1478     TotalCollectedSamples += I.second.getTotalSamples();
1479 
1480   // Populate the symbol map.
1481   for (const auto &N_F : M.getValueSymbolTable()) {
1482     std::string OrigName = N_F.getKey();
1483     Function *F = dyn_cast<Function>(N_F.getValue());
1484     if (F == nullptr)
1485       continue;
1486     SymbolMap[OrigName] = F;
1487     auto pos = OrigName.find('.');
1488     if (pos != std::string::npos) {
1489       std::string NewName = OrigName.substr(0, pos);
1490       auto r = SymbolMap.insert(std::make_pair(NewName, F));
1491       // Failiing to insert means there is already an entry in SymbolMap,
1492       // thus there are multiple functions that are mapped to the same
1493       // stripped name. In this case of name conflicting, set the value
1494       // to nullptr to avoid confusion.
1495       if (!r.second)
1496         r.first->second = nullptr;
1497     }
1498   }
1499 
1500   bool retval = false;
1501   for (auto &F : M)
1502     if (!F.isDeclaration()) {
1503       clearFunctionData();
1504       retval |= runOnFunction(F, AM);
1505     }
1506   if (M.getProfileSummary() == nullptr)
1507     M.setProfileSummary(Reader->getSummary().getMD(M.getContext()));
1508   return retval;
1509 }
1510 
1511 bool SampleProfileLoaderLegacyPass::runOnModule(Module &M) {
1512   ACT = &getAnalysis<AssumptionCacheTracker>();
1513   TTIWP = &getAnalysis<TargetTransformInfoWrapperPass>();
1514   return SampleLoader.runOnModule(M, nullptr);
1515 }
1516 
1517 bool SampleProfileLoader::runOnFunction(Function &F, ModuleAnalysisManager *AM) {
1518   F.setEntryCount(0);
1519   std::unique_ptr<OptimizationRemarkEmitter> OwnedORE;
1520   if (AM) {
1521     auto &FAM =
1522         AM->getResult<FunctionAnalysisManagerModuleProxy>(*F.getParent())
1523             .getManager();
1524     ORE = &FAM.getResult<OptimizationRemarkEmitterAnalysis>(F);
1525   } else {
1526     OwnedORE = make_unique<OptimizationRemarkEmitter>(&F);
1527     ORE = OwnedORE.get();
1528   }
1529   Samples = Reader->getSamplesFor(F);
1530   if (Samples && !Samples->empty())
1531     return emitAnnotations(F);
1532   return false;
1533 }
1534 
1535 PreservedAnalyses SampleProfileLoaderPass::run(Module &M,
1536                                                ModuleAnalysisManager &AM) {
1537   FunctionAnalysisManager &FAM =
1538       AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
1539 
1540   auto GetAssumptionCache = [&](Function &F) -> AssumptionCache & {
1541     return FAM.getResult<AssumptionAnalysis>(F);
1542   };
1543   auto GetTTI = [&](Function &F) -> TargetTransformInfo & {
1544     return FAM.getResult<TargetIRAnalysis>(F);
1545   };
1546 
1547   SampleProfileLoader SampleLoader(ProfileFileName.empty() ? SampleProfileFile
1548                                                            : ProfileFileName,
1549                                    GetAssumptionCache, GetTTI);
1550 
1551   SampleLoader.doInitialization(M);
1552 
1553   if (!SampleLoader.runOnModule(M, &AM))
1554     return PreservedAnalyses::all();
1555 
1556   return PreservedAnalyses::none();
1557 }
1558