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