blob: 68310687f8289c1f38713bd00761e87dbd3de714 [file] [log] [blame]
Diego Novillo8d6568b2013-11-13 12:22:21 +00001//===- 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
Xinliang David Lid38392e2016-05-27 23:20:16 +000025#include "llvm/Transforms/SampleProfile.h"
Diego Novillo8d6568b2013-11-13 12:22:21 +000026#include "llvm/ADT/DenseMap.h"
Diego Novillo0accb3d2014-01-10 23:23:46 +000027#include "llvm/ADT/SmallPtrSet.h"
Chandler Carruth07baed52014-01-13 08:04:33 +000028#include "llvm/ADT/SmallSet.h"
Diego Novillo8d6568b2013-11-13 12:22:21 +000029#include "llvm/ADT/StringRef.h"
Diego Novillo0accb3d2014-01-10 23:23:46 +000030#include "llvm/Analysis/LoopInfo.h"
Chandler Carruth07baed52014-01-13 08:04:33 +000031#include "llvm/Analysis/PostDominators.h"
Diego Novillo8d6568b2013-11-13 12:22:21 +000032#include "llvm/IR/Constants.h"
Chandler Carruth9a4c9e52014-03-06 00:46:21 +000033#include "llvm/IR/DebugInfo.h"
Diego Novilloa32aa322014-03-14 21:58:59 +000034#include "llvm/IR/DiagnosticInfo.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000035#include "llvm/IR/Dominators.h"
Diego Novillo8d6568b2013-11-13 12:22:21 +000036#include "llvm/IR/Function.h"
Chandler Carruth83948572014-03-04 10:30:26 +000037#include "llvm/IR/InstIterator.h"
Diego Novillo8d6568b2013-11-13 12:22:21 +000038#include "llvm/IR/Instructions.h"
Xinliang David Lid38392e2016-05-27 23:20:16 +000039#include "llvm/IR/IntrinsicInst.h"
Diego Novillo8d6568b2013-11-13 12:22:21 +000040#include "llvm/IR/LLVMContext.h"
Diego Novillo8d6568b2013-11-13 12:22:21 +000041#include "llvm/IR/MDBuilder.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000042#include "llvm/IR/Metadata.h"
Diego Novillo8d6568b2013-11-13 12:22:21 +000043#include "llvm/IR/Module.h"
44#include "llvm/Pass.h"
Diego Novillode1ab262014-09-09 12:40:50 +000045#include "llvm/ProfileData/SampleProfReader.h"
Diego Novillo8d6568b2013-11-13 12:22:21 +000046#include "llvm/Support/CommandLine.h"
47#include "llvm/Support/Debug.h"
Dehao Chen8e7df832015-09-29 18:28:15 +000048#include "llvm/Support/ErrorOr.h"
Diego Novillo7ff0a172015-11-29 18:23:26 +000049#include "llvm/Support/Format.h"
Diego Novillo8d6568b2013-11-13 12:22:21 +000050#include "llvm/Support/raw_ostream.h"
Diego Novillo4d711132015-08-25 15:25:11 +000051#include "llvm/Transforms/IPO.h"
Dehao Chen57d1dda2016-03-03 18:09:32 +000052#include "llvm/Transforms/Utils/Cloning.h"
Logan Chien61c6df02014-02-22 06:34:10 +000053#include <cctype>
Diego Novillo8d6568b2013-11-13 12:22:21 +000054
55using namespace llvm;
Diego Novillode1ab262014-09-09 12:40:50 +000056using namespace sampleprof;
Diego Novillo8d6568b2013-11-13 12:22:21 +000057
Chandler Carruth964daaa2014-04-22 02:55:47 +000058#define DEBUG_TYPE "sample-profile"
59
Diego Novillo8d6568b2013-11-13 12:22:21 +000060// Command line option to specify the file to read samples from. This is
61// mainly used for debugging.
62static cl::opt<std::string> SampleProfileFile(
63 "sample-profile-file", cl::init(""), cl::value_desc("filename"),
64 cl::desc("Profile file loaded by -sample-profile"), cl::Hidden);
Diego Novillo0accb3d2014-01-10 23:23:46 +000065static cl::opt<unsigned> SampleProfileMaxPropagateIterations(
66 "sample-profile-max-propagate-iterations", cl::init(100),
67 cl::desc("Maximum number of iterations to go through when propagating "
68 "sample block/edge weights through the CFG."));
Diego Novillo243ea6a2015-11-23 20:12:21 +000069static cl::opt<unsigned> SampleProfileRecordCoverage(
70 "sample-profile-check-record-coverage", cl::init(0), cl::value_desc("N"),
71 cl::desc("Emit a warning if less than N% of records in the input profile "
72 "are matched to the IR."));
73static cl::opt<unsigned> SampleProfileSampleCoverage(
74 "sample-profile-check-sample-coverage", cl::init(0), cl::value_desc("N"),
Diego Novillo748b3ffe2015-10-28 22:30:25 +000075 cl::desc("Emit a warning if less than N% of samples in the input profile "
76 "are matched to the IR."));
Diego Novillob5792402015-11-27 23:14:49 +000077static cl::opt<double> SampleProfileHotThreshold(
78 "sample-profile-inline-hot-threshold", cl::init(0.1), cl::value_desc("N"),
Diego Novillo0b6985a2015-11-24 22:38:37 +000079 cl::desc("Inlined functions that account for more than N% of all samples "
80 "collected in the parent function, will be inlined again."));
Diego Novillo84f06cc2015-11-27 23:14:51 +000081static cl::opt<double> SampleProfileGlobalHotThreshold(
82 "sample-profile-global-hot-threshold", cl::init(30), cl::value_desc("N"),
83 cl::desc("Top-level functions that account for more than N% of all samples "
84 "collected in the profile, will be marked as hot for the inliner "
85 "to consider."));
86static cl::opt<double> SampleProfileGlobalColdThreshold(
87 "sample-profile-global-cold-threshold", cl::init(0.5), cl::value_desc("N"),
88 cl::desc("Top-level functions that account for less than N% of all samples "
89 "collected in the profile, will be marked as cold for the inliner "
90 "to consider."));
Diego Novillo8d6568b2013-11-13 12:22:21 +000091
92namespace {
Diego Novillo38be3332015-10-15 16:36:21 +000093typedef DenseMap<const BasicBlock *, uint64_t> BlockWeightMap;
Dehao Chen8e7df832015-09-29 18:28:15 +000094typedef DenseMap<const BasicBlock *, const BasicBlock *> EquivalenceClassMap;
95typedef std::pair<const BasicBlock *, const BasicBlock *> Edge;
Diego Novillo38be3332015-10-15 16:36:21 +000096typedef DenseMap<Edge, uint64_t> EdgeWeightMap;
Dehao Chen8e7df832015-09-29 18:28:15 +000097typedef DenseMap<const BasicBlock *, SmallVector<const BasicBlock *, 8>>
98 BlockEdgeMap;
Diego Novilloc0dd1032013-11-26 20:37:33 +000099
Diego Novillode1ab262014-09-09 12:40:50 +0000100/// \brief Sample profile pass.
Diego Novilloc0dd1032013-11-26 20:37:33 +0000101///
Diego Novillode1ab262014-09-09 12:40:50 +0000102/// This pass reads profile data from the file specified by
103/// -sample-profile-file and annotates every affected function with the
104/// profile information found in that file.
Xinliang David Lie897edb2016-05-27 22:30:44 +0000105class SampleProfileLoader {
Diego Novilloc0dd1032013-11-26 20:37:33 +0000106public:
Diego Novillode1ab262014-09-09 12:40:50 +0000107 SampleProfileLoader(StringRef Name = SampleProfileFile)
Xinliang David Lie897edb2016-05-27 22:30:44 +0000108 : DT(nullptr), PDT(nullptr), LI(nullptr), Reader(), Samples(nullptr),
109 Filename(Name), ProfileIsValid(false), TotalCollectedSamples(0) {}
Diego Novillode1ab262014-09-09 12:40:50 +0000110
Xinliang David Lie897edb2016-05-27 22:30:44 +0000111 bool doInitialization(Module &M);
112 bool runOnModule(Module &M);
Diego Novillode1ab262014-09-09 12:40:50 +0000113
114 void dump() { Reader->dump(); }
115
Diego Novillode1ab262014-09-09 12:40:50 +0000116protected:
Diego Novillo4d711132015-08-25 15:25:11 +0000117 bool runOnFunction(Function &F);
Diego Novillo0accb3d2014-01-10 23:23:46 +0000118 unsigned getFunctionLoc(Function &F);
Diego Novillode1ab262014-09-09 12:40:50 +0000119 bool emitAnnotations(Function &F);
Diego Novillo38be3332015-10-15 16:36:21 +0000120 ErrorOr<uint64_t> getInstWeight(const Instruction &I) const;
121 ErrorOr<uint64_t> getBlockWeight(const BasicBlock *BB) const;
Dehao Chen67226882015-09-30 00:42:46 +0000122 const FunctionSamples *findCalleeFunctionSamples(const CallInst &I) const;
123 const FunctionSamples *findFunctionSamples(const Instruction &I) const;
124 bool inlineHotFunctions(Function &F);
Diego Novillo84f06cc2015-11-27 23:14:51 +0000125 bool emitInlineHints(Function &F);
Diego Novillo0accb3d2014-01-10 23:23:46 +0000126 void printEdgeWeight(raw_ostream &OS, Edge E);
Dehao Chen8e7df832015-09-29 18:28:15 +0000127 void printBlockWeight(raw_ostream &OS, const BasicBlock *BB) const;
128 void printBlockEquivalence(raw_ostream &OS, const BasicBlock *BB);
Diego Novillo0accb3d2014-01-10 23:23:46 +0000129 bool computeBlockWeights(Function &F);
130 void findEquivalenceClasses(Function &F);
Benjamin Kramer8a752e32016-02-13 16:01:12 +0000131 void findEquivalencesFor(BasicBlock *BB1, ArrayRef<BasicBlock *> Descendants,
Diego Novillo0accb3d2014-01-10 23:23:46 +0000132 DominatorTreeBase<BasicBlock> *DomTree);
133 void propagateWeights(Function &F);
Diego Novillo38be3332015-10-15 16:36:21 +0000134 uint64_t visitEdge(Edge E, unsigned *NumUnknownEdges, Edge *UnknownEdge);
Diego Novillo0accb3d2014-01-10 23:23:46 +0000135 void buildEdges(Function &F);
136 bool propagateThroughEdges(Function &F);
Diego Novillo7732ae42015-08-26 20:00:27 +0000137 void computeDominanceAndLoopInfo(Function &F);
Dehao Chen10042412015-10-21 01:22:27 +0000138 unsigned getOffset(unsigned L, unsigned H) const;
Diego Novilloa8a3bd22015-10-28 17:40:22 +0000139 void clearFunctionData();
Diego Novilloc0dd1032013-11-26 20:37:33 +0000140
Diego Novilloc0dd1032013-11-26 20:37:33 +0000141 /// \brief Map basic blocks to their computed weights.
142 ///
143 /// The weight of a basic block is defined to be the maximum
144 /// of all the instruction weights in that block.
145 BlockWeightMap BlockWeights;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000146
147 /// \brief Map edges to their computed weights.
148 ///
149 /// Edge weights are computed by propagating basic block weights in
150 /// SampleProfile::propagateWeights.
151 EdgeWeightMap EdgeWeights;
152
153 /// \brief Set of visited blocks during propagation.
Matthias Braunb30f2f512016-01-30 01:24:31 +0000154 SmallPtrSet<const BasicBlock *, 32> VisitedBlocks;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000155
156 /// \brief Set of visited edges during propagation.
Matthias Braunb30f2f512016-01-30 01:24:31 +0000157 SmallSet<Edge, 32> VisitedEdges;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000158
159 /// \brief Equivalence classes for block weights.
160 ///
161 /// Two blocks BB1 and BB2 are in the same equivalence class if they
162 /// dominate and post-dominate each other, and they are in the same loop
163 /// nest. When this happens, the two blocks are guaranteed to execute
164 /// the same number of times.
165 EquivalenceClassMap EquivalenceClass;
166
167 /// \brief Dominance, post-dominance and loop information.
Diego Novillo7732ae42015-08-26 20:00:27 +0000168 std::unique_ptr<DominatorTree> DT;
169 std::unique_ptr<DominatorTreeBase<BasicBlock>> PDT;
170 std::unique_ptr<LoopInfo> LI;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000171
172 /// \brief Predecessors for each basic block in the CFG.
173 BlockEdgeMap Predecessors;
174
175 /// \brief Successors for each basic block in the CFG.
176 BlockEdgeMap Successors;
Diego Novillo92aa8c22014-03-10 22:41:28 +0000177
Diego Novillo8d6568b2013-11-13 12:22:21 +0000178 /// \brief Profile reader object.
Diego Novillode1ab262014-09-09 12:40:50 +0000179 std::unique_ptr<SampleProfileReader> Reader;
180
181 /// \brief Samples collected for the body of this function.
182 FunctionSamples *Samples;
Diego Novillo8d6568b2013-11-13 12:22:21 +0000183
184 /// \brief Name of the profile file to load.
185 StringRef Filename;
Diego Novilloa32aa322014-03-14 21:58:59 +0000186
Alp Toker16f98b22014-04-09 14:47:27 +0000187 /// \brief Flag indicating whether the profile input loaded successfully.
Diego Novilloa32aa322014-03-14 21:58:59 +0000188 bool ProfileIsValid;
Diego Novillo84f06cc2015-11-27 23:14:51 +0000189
190 /// \brief Total number of samples collected in this profile.
191 ///
192 /// This is the sum of all the samples collected in all the functions executed
193 /// at runtime.
194 uint64_t TotalCollectedSamples;
Diego Novillo8d6568b2013-11-13 12:22:21 +0000195};
Diego Novillo748b3ffe2015-10-28 22:30:25 +0000196
Xinliang David Lie897edb2016-05-27 22:30:44 +0000197class SampleProfileLoaderLegacyPass : public ModulePass {
198public:
199 // Class identification, replacement for typeinfo
200 static char ID;
201
202 SampleProfileLoaderLegacyPass(StringRef Name = SampleProfileFile)
203 : ModulePass(ID), SampleLoader(Name) {
204 initializeSampleProfileLoaderLegacyPassPass(
205 *PassRegistry::getPassRegistry());
206 }
207
208 void dump() { SampleLoader.dump(); }
209
210 bool doInitialization(Module &M) override {
211 return SampleLoader.doInitialization(M);
212 }
213 const char *getPassName() const override { return "Sample profile pass"; }
214 bool runOnModule(Module &M) override;
215
216private:
217 SampleProfileLoader SampleLoader;
218};
219
Diego Novillo748b3ffe2015-10-28 22:30:25 +0000220class SampleCoverageTracker {
221public:
Diego Novillo243ea6a2015-11-23 20:12:21 +0000222 SampleCoverageTracker() : SampleCoverage(), TotalUsedSamples(0) {}
Diego Novillo748b3ffe2015-10-28 22:30:25 +0000223
Diego Novillo243ea6a2015-11-23 20:12:21 +0000224 bool markSamplesUsed(const FunctionSamples *FS, uint32_t LineOffset,
225 uint32_t Discriminator, uint64_t Samples);
Diego Novillof9ed08e2015-10-31 21:53:58 +0000226 unsigned computeCoverage(unsigned Used, unsigned Total) const;
Diego Novillo243ea6a2015-11-23 20:12:21 +0000227 unsigned countUsedRecords(const FunctionSamples *FS) const;
228 unsigned countBodyRecords(const FunctionSamples *FS) const;
229 uint64_t getTotalUsedSamples() const { return TotalUsedSamples; }
230 uint64_t countBodySamples(const FunctionSamples *FS) const;
231 void clear() {
232 SampleCoverage.clear();
233 TotalUsedSamples = 0;
234 }
Diego Novillo748b3ffe2015-10-28 22:30:25 +0000235
236private:
Diego Novillo10cf1242015-12-11 23:21:38 +0000237 typedef std::map<LineLocation, unsigned> BodySampleCoverageMap;
Diego Novillo748b3ffe2015-10-28 22:30:25 +0000238 typedef DenseMap<const FunctionSamples *, BodySampleCoverageMap>
239 FunctionSamplesCoverageMap;
240
241 /// Coverage map for sampling records.
242 ///
243 /// This map keeps a record of sampling records that have been matched to
244 /// an IR instruction. This is used to detect some form of staleness in
245 /// profiles (see flag -sample-profile-check-coverage).
246 ///
247 /// Each entry in the map corresponds to a FunctionSamples instance. This is
248 /// another map that counts how many times the sample record at the
249 /// given location has been used.
250 FunctionSamplesCoverageMap SampleCoverage;
Diego Novillo243ea6a2015-11-23 20:12:21 +0000251
252 /// Number of samples used from the profile.
253 ///
254 /// When a sampling record is used for the first time, the samples from
255 /// that record are added to this accumulator. Coverage is later computed
256 /// based on the total number of samples available in this function and
257 /// its callsites.
258 ///
259 /// Note that this accumulator tracks samples used from a single function
260 /// and all the inlined callsites. Strictly, we should have a map of counters
261 /// keyed by FunctionSamples pointers, but these stats are cleared after
262 /// every function, so we just need to keep a single counter.
263 uint64_t TotalUsedSamples;
Diego Novillo748b3ffe2015-10-28 22:30:25 +0000264};
265
266SampleCoverageTracker CoverageTracker;
Diego Novillo0b6985a2015-11-24 22:38:37 +0000267
268/// Return true if the given callsite is hot wrt to its caller.
269///
270/// Functions that were inlined in the original binary will be represented
271/// in the inline stack in the sample profile. If the profile shows that
272/// the original inline decision was "good" (i.e., the callsite is executed
273/// frequently), then we will recreate the inline decision and apply the
274/// profile from the inlined callsite.
275///
276/// To decide whether an inlined callsite is hot, we compute the fraction
277/// of samples used by the callsite with respect to the total number of samples
278/// collected in the caller.
279///
280/// If that fraction is larger than the default given by
281/// SampleProfileHotThreshold, the callsite will be inlined again.
282bool callsiteIsHot(const FunctionSamples *CallerFS,
283 const FunctionSamples *CallsiteFS) {
284 if (!CallsiteFS)
285 return false; // The callsite was not inlined in the original binary.
286
287 uint64_t ParentTotalSamples = CallerFS->getTotalSamples();
288 if (ParentTotalSamples == 0)
289 return false; // Avoid division by zero.
290
291 uint64_t CallsiteTotalSamples = CallsiteFS->getTotalSamples();
292 if (CallsiteTotalSamples == 0)
293 return false; // Callsite is trivially cold.
294
Diego Novillob5792402015-11-27 23:14:49 +0000295 double PercentSamples =
296 (double)CallsiteTotalSamples / (double)ParentTotalSamples * 100.0;
Diego Novillo0b6985a2015-11-24 22:38:37 +0000297 return PercentSamples >= SampleProfileHotThreshold;
298}
Diego Novillo748b3ffe2015-10-28 22:30:25 +0000299}
300
301/// Mark as used the sample record for the given function samples at
302/// (LineOffset, Discriminator).
Diego Novillof9ed08e2015-10-31 21:53:58 +0000303///
304/// \returns true if this is the first time we mark the given record.
Diego Novillo243ea6a2015-11-23 20:12:21 +0000305bool SampleCoverageTracker::markSamplesUsed(const FunctionSamples *FS,
Diego Novillo748b3ffe2015-10-28 22:30:25 +0000306 uint32_t LineOffset,
Diego Novillo243ea6a2015-11-23 20:12:21 +0000307 uint32_t Discriminator,
308 uint64_t Samples) {
Diego Novillof9ed08e2015-10-31 21:53:58 +0000309 LineLocation Loc(LineOffset, Discriminator);
Diego Novillo243ea6a2015-11-23 20:12:21 +0000310 unsigned &Count = SampleCoverage[FS][Loc];
311 bool FirstTime = (++Count == 1);
312 if (FirstTime)
313 TotalUsedSamples += Samples;
314 return FirstTime;
Diego Novillo748b3ffe2015-10-28 22:30:25 +0000315}
316
317/// Return the number of sample records that were applied from this profile.
Diego Novillo0b6985a2015-11-24 22:38:37 +0000318///
319/// This count does not include records from cold inlined callsites.
Diego Novillo748b3ffe2015-10-28 22:30:25 +0000320unsigned
Diego Novillo243ea6a2015-11-23 20:12:21 +0000321SampleCoverageTracker::countUsedRecords(const FunctionSamples *FS) const {
322 auto I = SampleCoverage.find(FS);
Diego Novillo5fb49e52015-11-20 21:46:38 +0000323
Diego Novillo243ea6a2015-11-23 20:12:21 +0000324 // The size of the coverage map for FS represents the number of records
Diego Novillo5fb49e52015-11-20 21:46:38 +0000325 // that were marked used at least once.
Diego Novillof9ed08e2015-10-31 21:53:58 +0000326 unsigned Count = (I != SampleCoverage.end()) ? I->second.size() : 0;
Diego Novillo5fb49e52015-11-20 21:46:38 +0000327
328 // If there are inlined callsites in this function, count the samples found
329 // in the respective bodies. However, do not bother counting callees with 0
330 // total samples, these are callees that were never invoked at runtime.
Diego Novillo243ea6a2015-11-23 20:12:21 +0000331 for (const auto &I : FS->getCallsiteSamples()) {
Diego Novillo5fb49e52015-11-20 21:46:38 +0000332 const FunctionSamples *CalleeSamples = &I.second;
Diego Novillo0b6985a2015-11-24 22:38:37 +0000333 if (callsiteIsHot(FS, CalleeSamples))
Diego Novillo243ea6a2015-11-23 20:12:21 +0000334 Count += countUsedRecords(CalleeSamples);
Diego Novillo5fb49e52015-11-20 21:46:38 +0000335 }
336
Diego Novillof9ed08e2015-10-31 21:53:58 +0000337 return Count;
338}
339
340/// Return the number of sample records in the body of this profile.
341///
Diego Novillo0b6985a2015-11-24 22:38:37 +0000342/// This count does not include records from cold inlined callsites.
Diego Novillof9ed08e2015-10-31 21:53:58 +0000343unsigned
Diego Novillo243ea6a2015-11-23 20:12:21 +0000344SampleCoverageTracker::countBodyRecords(const FunctionSamples *FS) const {
345 unsigned Count = FS->getBodySamples().size();
Diego Novillo5fb49e52015-11-20 21:46:38 +0000346
Diego Novillo0b6985a2015-11-24 22:38:37 +0000347 // Only count records in hot callsites.
Diego Novillo243ea6a2015-11-23 20:12:21 +0000348 for (const auto &I : FS->getCallsiteSamples()) {
Diego Novillo5fb49e52015-11-20 21:46:38 +0000349 const FunctionSamples *CalleeSamples = &I.second;
Diego Novillo0b6985a2015-11-24 22:38:37 +0000350 if (callsiteIsHot(FS, CalleeSamples))
Diego Novillo243ea6a2015-11-23 20:12:21 +0000351 Count += countBodyRecords(CalleeSamples);
Diego Novillo5fb49e52015-11-20 21:46:38 +0000352 }
353
Diego Novillof9ed08e2015-10-31 21:53:58 +0000354 return Count;
Diego Novillo748b3ffe2015-10-28 22:30:25 +0000355}
356
Diego Novillo243ea6a2015-11-23 20:12:21 +0000357/// Return the number of samples collected in the body of this profile.
358///
Diego Novillo0b6985a2015-11-24 22:38:37 +0000359/// This count does not include samples from cold inlined callsites.
Diego Novillo243ea6a2015-11-23 20:12:21 +0000360uint64_t
361SampleCoverageTracker::countBodySamples(const FunctionSamples *FS) const {
362 uint64_t Total = 0;
363 for (const auto &I : FS->getBodySamples())
364 Total += I.second.getSamples();
365
Diego Novillo0b6985a2015-11-24 22:38:37 +0000366 // Only count samples in hot callsites.
Diego Novillo243ea6a2015-11-23 20:12:21 +0000367 for (const auto &I : FS->getCallsiteSamples()) {
368 const FunctionSamples *CalleeSamples = &I.second;
Diego Novillo0b6985a2015-11-24 22:38:37 +0000369 if (callsiteIsHot(FS, CalleeSamples))
Diego Novillo243ea6a2015-11-23 20:12:21 +0000370 Total += countBodySamples(CalleeSamples);
371 }
372
373 return Total;
374}
375
Diego Novillo748b3ffe2015-10-28 22:30:25 +0000376/// Return the fraction of sample records used in this profile.
377///
378/// The returned value is an unsigned integer in the range 0-100 indicating
379/// the percentage of sample records that were used while applying this
380/// profile to the associated function.
Diego Novillof9ed08e2015-10-31 21:53:58 +0000381unsigned SampleCoverageTracker::computeCoverage(unsigned Used,
382 unsigned Total) const {
383 assert(Used <= Total &&
Diego Novillo748b3ffe2015-10-28 22:30:25 +0000384 "number of used records cannot exceed the total number of records");
Diego Novillof9ed08e2015-10-31 21:53:58 +0000385 return Total > 0 ? Used * 100 / Total : 100;
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000386}
Diego Novillo8d6568b2013-11-13 12:22:21 +0000387
Diego Novilloa8a3bd22015-10-28 17:40:22 +0000388/// Clear all the per-function data used to load samples and propagate weights.
389void SampleProfileLoader::clearFunctionData() {
390 BlockWeights.clear();
391 EdgeWeights.clear();
392 VisitedBlocks.clear();
393 VisitedEdges.clear();
394 EquivalenceClass.clear();
395 DT = nullptr;
396 PDT = nullptr;
397 LI = nullptr;
398 Predecessors.clear();
399 Successors.clear();
Diego Novillo1ca881c2015-11-23 16:30:17 +0000400 CoverageTracker.clear();
Diego Novilloa8a3bd22015-10-28 17:40:22 +0000401}
402
Dehao Chen10042412015-10-21 01:22:27 +0000403/// \brief Returns the offset of lineno \p L to head_lineno \p H
404///
405/// \param L Lineno
406/// \param H Header lineno of the function
407///
408/// \returns offset to the header lineno. 16 bits are used to represent offset.
409/// We assume that a single function will not exceed 65535 LOC.
410unsigned SampleProfileLoader::getOffset(unsigned L, unsigned H) const {
411 return (L - H) & 0xffff;
412}
413
Diego Novillo0accb3d2014-01-10 23:23:46 +0000414/// \brief Print the weight of edge \p E on stream \p OS.
415///
416/// \param OS Stream to emit the output to.
417/// \param E Edge to print.
Diego Novillode1ab262014-09-09 12:40:50 +0000418void SampleProfileLoader::printEdgeWeight(raw_ostream &OS, Edge E) {
Diego Novillo0accb3d2014-01-10 23:23:46 +0000419 OS << "weight[" << E.first->getName() << "->" << E.second->getName()
420 << "]: " << EdgeWeights[E] << "\n";
421}
422
423/// \brief Print the equivalence class of block \p BB on stream \p OS.
424///
425/// \param OS Stream to emit the output to.
426/// \param BB Block to print.
Diego Novillode1ab262014-09-09 12:40:50 +0000427void SampleProfileLoader::printBlockEquivalence(raw_ostream &OS,
Dehao Chen8e7df832015-09-29 18:28:15 +0000428 const BasicBlock *BB) {
429 const BasicBlock *Equiv = EquivalenceClass[BB];
Diego Novillo0accb3d2014-01-10 23:23:46 +0000430 OS << "equivalence[" << BB->getName()
431 << "]: " << ((Equiv) ? EquivalenceClass[BB]->getName() : "NONE") << "\n";
432}
433
434/// \brief Print the weight of block \p BB on stream \p OS.
435///
436/// \param OS Stream to emit the output to.
437/// \param BB Block to print.
Dehao Chen8e7df832015-09-29 18:28:15 +0000438void SampleProfileLoader::printBlockWeight(raw_ostream &OS,
439 const BasicBlock *BB) const {
440 const auto &I = BlockWeights.find(BB);
Diego Novillo38be3332015-10-15 16:36:21 +0000441 uint64_t W = (I == BlockWeights.end() ? 0 : I->second);
Dehao Chen8e7df832015-09-29 18:28:15 +0000442 OS << "weight[" << BB->getName() << "]: " << W << "\n";
Diego Novillo0accb3d2014-01-10 23:23:46 +0000443}
444
Diego Novillo0accb3d2014-01-10 23:23:46 +0000445/// \brief Get the weight for an instruction.
446///
447/// The "weight" of an instruction \p Inst is the number of samples
448/// collected on that instruction at runtime. To retrieve it, we
449/// need to compute the line number of \p Inst relative to the start of its
450/// function. We use HeaderLineno to compute the offset. We then
451/// look up the samples collected for \p Inst using BodySamples.
452///
453/// \param Inst Instruction to query.
454///
Dehao Chen8e7df832015-09-29 18:28:15 +0000455/// \returns the weight of \p Inst.
Diego Novillo38be3332015-10-15 16:36:21 +0000456ErrorOr<uint64_t>
Dehao Chen8e7df832015-09-29 18:28:15 +0000457SampleProfileLoader::getInstWeight(const Instruction &Inst) const {
Benjamin Kramer4fed9282016-05-27 12:30:51 +0000458 const DebugLoc &DLoc = Inst.getDebugLoc();
Duncan P. N. Exon Smithec819c02015-03-30 19:49:49 +0000459 if (!DLoc)
Dehao Chen8e7df832015-09-29 18:28:15 +0000460 return std::error_code();
Duncan P. N. Exon Smith41a15462015-03-20 00:56:55 +0000461
Dehao Chen67226882015-09-30 00:42:46 +0000462 const FunctionSamples *FS = findFunctionSamples(Inst);
463 if (!FS)
464 return std::error_code();
Dehao Chen41dc5a62015-10-09 16:50:16 +0000465
Dehao Chena8bae822016-04-20 23:36:23 +0000466 // Ignore all dbg_value intrinsics.
467 const IntrinsicInst *II = dyn_cast<IntrinsicInst>(&Inst);
468 if (II && II->getIntrinsicID() == Intrinsic::dbg_value)
469 return std::error_code();
470
Dehao Chen41dc5a62015-10-09 16:50:16 +0000471 const DILocation *DIL = DLoc;
472 unsigned Lineno = DLoc.getLine();
473 unsigned HeaderLineno = DIL->getScope()->getSubprogram()->getLine();
Dehao Chen41dc5a62015-10-09 16:50:16 +0000474
Diego Novillo748b3ffe2015-10-28 22:30:25 +0000475 uint32_t LineOffset = getOffset(Lineno, HeaderLineno);
476 uint32_t Discriminator = DIL->getDiscriminator();
477 ErrorOr<uint64_t> R = FS->findSamplesAt(LineOffset, Discriminator);
478 if (R) {
Diego Novillof9ed08e2015-10-31 21:53:58 +0000479 bool FirstMark =
Diego Novillo243ea6a2015-11-23 20:12:21 +0000480 CoverageTracker.markSamplesUsed(FS, LineOffset, Discriminator, R.get());
Diego Novillof9ed08e2015-10-31 21:53:58 +0000481 if (FirstMark) {
482 const Function *F = Inst.getParent()->getParent();
483 LLVMContext &Ctx = F->getContext();
Diego Novillodf544a02015-11-20 15:39:42 +0000484 emitOptimizationRemark(
485 Ctx, DEBUG_TYPE, *F, DLoc,
486 Twine("Applied ") + Twine(*R) + " samples from profile (offset: " +
487 Twine(LineOffset) +
488 ((Discriminator) ? Twine(".") + Twine(Discriminator) : "") + ")");
Diego Novillof9ed08e2015-10-31 21:53:58 +0000489 }
Dehao Chen8e7df832015-09-29 18:28:15 +0000490 DEBUG(dbgs() << " " << Lineno << "." << DIL->getDiscriminator() << ":"
491 << Inst << " (line offset: " << Lineno - HeaderLineno << "."
492 << DIL->getDiscriminator() << " - weight: " << R.get()
493 << ")\n");
Dehao Chena8bae822016-04-20 23:36:23 +0000494 } else {
495 // If a call instruction is inlined in profile, but not inlined here,
496 // it means that the inlined callsite has no sample, thus the call
497 // instruction should have 0 count.
498 const CallInst *CI = dyn_cast<CallInst>(&Inst);
499 if (CI && findCalleeFunctionSamples(*CI))
500 R = 0;
Diego Novillo748b3ffe2015-10-28 22:30:25 +0000501 }
Dehao Chen8e7df832015-09-29 18:28:15 +0000502 return R;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000503}
504
505/// \brief Compute the weight of a basic block.
506///
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000507/// The weight of basic block \p BB is the maximum weight of all the
Dehao Chen8e7df832015-09-29 18:28:15 +0000508/// instructions in BB.
Diego Novillo0accb3d2014-01-10 23:23:46 +0000509///
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000510/// \param BB The basic block to query.
Diego Novillo0accb3d2014-01-10 23:23:46 +0000511///
Dehao Chen8e7df832015-09-29 18:28:15 +0000512/// \returns the weight for \p BB.
Diego Novillo38be3332015-10-15 16:36:21 +0000513ErrorOr<uint64_t>
Dehao Chen8e7df832015-09-29 18:28:15 +0000514SampleProfileLoader::getBlockWeight(const BasicBlock *BB) const {
Dehao Chen5d6d4842016-04-26 04:59:11 +0000515 DenseMap<uint64_t, uint64_t> CM;
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000516 for (auto &I : BB->getInstList()) {
Diego Novillo38be3332015-10-15 16:36:21 +0000517 const ErrorOr<uint64_t> &R = getInstWeight(I);
Dehao Chen5d6d4842016-04-26 04:59:11 +0000518 if (R) CM[R.get()]++;
519 }
520 if (CM.size() == 0) return std::error_code();
521 uint64_t W = 0, C = 0;
522 for (const auto &C_W : CM) {
523 if (C_W.second == W) {
524 C = std::max(C, C_W.first);
525 } else if (C_W.second > W) {
526 C = C_W.first;
527 W = C_W.second;
Dehao Chen8e7df832015-09-29 18:28:15 +0000528 }
Diego Novillo0accb3d2014-01-10 23:23:46 +0000529 }
Dehao Chen5d6d4842016-04-26 04:59:11 +0000530 return C;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000531}
532
533/// \brief Compute and store the weights of every basic block.
534///
535/// This populates the BlockWeights map by computing
536/// the weights of every basic block in the CFG.
537///
538/// \param F The function to query.
Diego Novillode1ab262014-09-09 12:40:50 +0000539bool SampleProfileLoader::computeBlockWeights(Function &F) {
Diego Novillo0accb3d2014-01-10 23:23:46 +0000540 bool Changed = false;
541 DEBUG(dbgs() << "Block weights\n");
Dehao Chen8e7df832015-09-29 18:28:15 +0000542 for (const auto &BB : F) {
Diego Novillo38be3332015-10-15 16:36:21 +0000543 ErrorOr<uint64_t> Weight = getBlockWeight(&BB);
Dehao Chen8e7df832015-09-29 18:28:15 +0000544 if (Weight) {
545 BlockWeights[&BB] = Weight.get();
Dehao Chen7c41dd62015-10-01 00:26:56 +0000546 VisitedBlocks.insert(&BB);
Dehao Chen8e7df832015-09-29 18:28:15 +0000547 Changed = true;
548 }
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000549 DEBUG(printBlockWeight(dbgs(), &BB));
Diego Novillo0accb3d2014-01-10 23:23:46 +0000550 }
551
552 return Changed;
553}
554
Dehao Chen67226882015-09-30 00:42:46 +0000555/// \brief Get the FunctionSamples for a call instruction.
556///
557/// The FunctionSamples of a call instruction \p Inst is the inlined
558/// instance in which that call instruction is calling to. It contains
559/// all samples that resides in the inlined instance. We first find the
560/// inlined instance in which the call instruction is from, then we
561/// traverse its children to find the callsite with the matching
562/// location and callee function name.
563///
564/// \param Inst Call instruction to query.
565///
566/// \returns The FunctionSamples pointer to the inlined instance.
567const FunctionSamples *
568SampleProfileLoader::findCalleeFunctionSamples(const CallInst &Inst) const {
569 const DILocation *DIL = Inst.getDebugLoc();
570 if (!DIL) {
571 return nullptr;
572 }
573 DISubprogram *SP = DIL->getScope()->getSubprogram();
Dehao Chen10042412015-10-21 01:22:27 +0000574 if (!SP)
Dehao Chen67226882015-09-30 00:42:46 +0000575 return nullptr;
576
Dehao Chen67226882015-09-30 00:42:46 +0000577 const FunctionSamples *FS = findFunctionSamples(Inst);
578 if (FS == nullptr)
579 return nullptr;
580
Dehao Chen57d1dda2016-03-03 18:09:32 +0000581 return FS->findFunctionSamplesAt(LineLocation(
582 getOffset(DIL->getLine(), SP->getLine()), DIL->getDiscriminator()));
Dehao Chen67226882015-09-30 00:42:46 +0000583}
584
585/// \brief Get the FunctionSamples for an instruction.
586///
587/// The FunctionSamples of an instruction \p Inst is the inlined instance
588/// in which that instruction is coming from. We traverse the inline stack
589/// of that instruction, and match it with the tree nodes in the profile.
590///
591/// \param Inst Instruction to query.
592///
593/// \returns the FunctionSamples pointer to the inlined instance.
594const FunctionSamples *
595SampleProfileLoader::findFunctionSamples(const Instruction &Inst) const {
Dehao Chen57d1dda2016-03-03 18:09:32 +0000596 SmallVector<LineLocation, 10> S;
Dehao Chen67226882015-09-30 00:42:46 +0000597 const DILocation *DIL = Inst.getDebugLoc();
598 if (!DIL) {
599 return Samples;
600 }
Dehao Chen21aefae2016-04-29 17:19:10 +0000601 for (DIL = DIL->getInlinedAt(); DIL; DIL = DIL->getInlinedAt()) {
Dehao Chen67226882015-09-30 00:42:46 +0000602 DISubprogram *SP = DIL->getScope()->getSubprogram();
Dehao Chen10042412015-10-21 01:22:27 +0000603 if (!SP)
Dehao Chen67226882015-09-30 00:42:46 +0000604 return nullptr;
Dehao Chen21aefae2016-04-29 17:19:10 +0000605 S.push_back(LineLocation(getOffset(DIL->getLine(), SP->getLine()),
606 DIL->getDiscriminator()));
Dehao Chen67226882015-09-30 00:42:46 +0000607 }
608 if (S.size() == 0)
609 return Samples;
610 const FunctionSamples *FS = Samples;
611 for (int i = S.size() - 1; i >= 0 && FS != nullptr; i--) {
612 FS = FS->findFunctionSamplesAt(S[i]);
613 }
614 return FS;
615}
616
Diego Novillo84f06cc2015-11-27 23:14:51 +0000617/// \brief Emit an inline hint if \p F is globally hot or cold.
618///
619/// If \p F consumes a significant fraction of samples (indicated by
620/// SampleProfileGlobalHotThreshold), apply the InlineHint attribute for the
621/// inliner to consider the function hot.
622///
623/// If \p F consumes a small fraction of samples (indicated by
624/// SampleProfileGlobalColdThreshold), apply the Cold attribute for the inliner
625/// to consider the function cold.
626///
627/// FIXME - This setting of inline hints is sub-optimal. Instead of marking a
628/// function globally hot or cold, we should be annotating individual callsites.
629/// This is not currently possible, but work on the inliner will eventually
630/// provide this ability. See http://reviews.llvm.org/D15003 for details and
631/// discussion.
632///
633/// \returns True if either attribute was applied to \p F.
634bool SampleProfileLoader::emitInlineHints(Function &F) {
635 if (TotalCollectedSamples == 0)
636 return false;
637
638 uint64_t FunctionSamples = Samples->getTotalSamples();
639 double SamplesPercent =
640 (double)FunctionSamples / (double)TotalCollectedSamples * 100.0;
641
642 // If the function collected more samples than the hot threshold, mark
643 // it globally hot.
644 if (SamplesPercent >= SampleProfileGlobalHotThreshold) {
645 F.addFnAttr(llvm::Attribute::InlineHint);
Diego Novillo7ff0a172015-11-29 18:23:26 +0000646 std::string Msg;
647 raw_string_ostream S(Msg);
648 S << "Applied inline hint to globally hot function '" << F.getName()
649 << "' with " << format("%.2f", SamplesPercent)
650 << "% of samples (threshold: "
651 << format("%.2f", SampleProfileGlobalHotThreshold.getValue()) << "%)";
652 S.flush();
653 emitOptimizationRemark(F.getContext(), DEBUG_TYPE, F, DebugLoc(), Msg);
Diego Novillo84f06cc2015-11-27 23:14:51 +0000654 return true;
655 }
656
657 // If the function collected fewer samples than the cold threshold, mark
658 // it globally cold.
659 if (SamplesPercent <= SampleProfileGlobalColdThreshold) {
660 F.addFnAttr(llvm::Attribute::Cold);
Diego Novillo7ff0a172015-11-29 18:23:26 +0000661 std::string Msg;
662 raw_string_ostream S(Msg);
663 S << "Applied cold hint to globally cold function '" << F.getName()
664 << "' with " << format("%.2f", SamplesPercent)
665 << "% of samples (threshold: "
666 << format("%.2f", SampleProfileGlobalColdThreshold.getValue()) << "%)";
667 S.flush();
668 emitOptimizationRemark(F.getContext(), DEBUG_TYPE, F, DebugLoc(), Msg);
Diego Novillo84f06cc2015-11-27 23:14:51 +0000669 return true;
670 }
671
672 return false;
673}
674
Dehao Chen67226882015-09-30 00:42:46 +0000675/// \brief Iteratively inline hot callsites of a function.
676///
677/// Iteratively traverse all callsites of the function \p F, and find if
678/// the corresponding inlined instance exists and is hot in profile. If
679/// it is hot enough, inline the callsites and adds new callsites of the
680/// callee into the caller.
681///
682/// TODO: investigate the possibility of not invoking InlineFunction directly.
683///
684/// \param F function to perform iterative inlining.
685///
686/// \returns True if there is any inline happened.
687bool SampleProfileLoader::inlineHotFunctions(Function &F) {
688 bool Changed = false;
Diego Novillo7963ea12015-10-26 18:52:53 +0000689 LLVMContext &Ctx = F.getContext();
Dehao Chen67226882015-09-30 00:42:46 +0000690 while (true) {
691 bool LocalChanged = false;
692 SmallVector<CallInst *, 10> CIS;
693 for (auto &BB : F) {
694 for (auto &I : BB.getInstList()) {
695 CallInst *CI = dyn_cast<CallInst>(&I);
Diego Novillo0b6985a2015-11-24 22:38:37 +0000696 if (CI && callsiteIsHot(Samples, findCalleeFunctionSamples(*CI)))
697 CIS.push_back(CI);
Dehao Chen67226882015-09-30 00:42:46 +0000698 }
699 }
700 for (auto CI : CIS) {
701 InlineFunctionInfo IFI;
Diego Novillo7963ea12015-10-26 18:52:53 +0000702 Function *CalledFunction = CI->getCalledFunction();
703 DebugLoc DLoc = CI->getDebugLoc();
704 uint64_t NumSamples = findCalleeFunctionSamples(*CI)->getTotalSamples();
705 if (InlineFunction(CI, IFI)) {
Dehao Chen67226882015-09-30 00:42:46 +0000706 LocalChanged = true;
Diego Novillo7963ea12015-10-26 18:52:53 +0000707 emitOptimizationRemark(Ctx, DEBUG_TYPE, F, DLoc,
708 Twine("inlined hot callee '") +
709 CalledFunction->getName() + "' with " +
710 Twine(NumSamples) + " samples into '" +
711 F.getName() + "'");
712 }
Dehao Chen67226882015-09-30 00:42:46 +0000713 }
714 if (LocalChanged) {
715 Changed = true;
716 } else {
717 break;
718 }
719 }
720 return Changed;
721}
722
Diego Novillo0accb3d2014-01-10 23:23:46 +0000723/// \brief Find equivalence classes for the given block.
724///
725/// This finds all the blocks that are guaranteed to execute the same
Eric Christopher572e03a2015-06-19 01:53:21 +0000726/// number of times as \p BB1. To do this, it traverses all the
Diego Novillo0accb3d2014-01-10 23:23:46 +0000727/// descendants of \p BB1 in the dominator or post-dominator tree.
728///
729/// A block BB2 will be in the same equivalence class as \p BB1 if
730/// the following holds:
731///
732/// 1- \p BB1 is a descendant of BB2 in the opposite tree. So, if BB2
733/// is a descendant of \p BB1 in the dominator tree, then BB2 should
734/// dominate BB1 in the post-dominator tree.
735///
736/// 2- Both BB2 and \p BB1 must be in the same loop.
737///
738/// For every block BB2 that meets those two requirements, we set BB2's
739/// equivalence class to \p BB1.
740///
741/// \param BB1 Block to check.
742/// \param Descendants Descendants of \p BB1 in either the dom or pdom tree.
743/// \param DomTree Opposite dominator tree. If \p Descendants is filled
744/// with blocks from \p BB1's dominator tree, then
745/// this is the post-dominator tree, and vice versa.
Diego Novillode1ab262014-09-09 12:40:50 +0000746void SampleProfileLoader::findEquivalencesFor(
Benjamin Kramer8a752e32016-02-13 16:01:12 +0000747 BasicBlock *BB1, ArrayRef<BasicBlock *> Descendants,
Diego Novillo0accb3d2014-01-10 23:23:46 +0000748 DominatorTreeBase<BasicBlock> *DomTree) {
Dehao Chen7c41dd62015-10-01 00:26:56 +0000749 const BasicBlock *EC = EquivalenceClass[BB1];
Diego Novillo38be3332015-10-15 16:36:21 +0000750 uint64_t Weight = BlockWeights[EC];
Dehao Chen8e7df832015-09-29 18:28:15 +0000751 for (const auto *BB2 : Descendants) {
Diego Novillo0accb3d2014-01-10 23:23:46 +0000752 bool IsDomParent = DomTree->dominates(BB2, BB1);
753 bool IsInSameLoop = LI->getLoopFor(BB1) == LI->getLoopFor(BB2);
Dehao Chen7c41dd62015-10-01 00:26:56 +0000754 if (BB1 != BB2 && IsDomParent && IsInSameLoop) {
755 EquivalenceClass[BB2] = EC;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000756
757 // If BB2 is heavier than BB1, make BB2 have the same weight
758 // as BB1.
759 //
760 // Note that we don't worry about the opposite situation here
761 // (when BB2 is lighter than BB1). We will deal with this
762 // during the propagation phase. Right now, we just want to
763 // make sure that BB1 has the largest weight of all the
764 // members of its equivalence set.
Dehao Chen7c41dd62015-10-01 00:26:56 +0000765 Weight = std::max(Weight, BlockWeights[BB2]);
Diego Novillo0accb3d2014-01-10 23:23:46 +0000766 }
767 }
Dehao Chen7c41dd62015-10-01 00:26:56 +0000768 BlockWeights[EC] = Weight;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000769}
770
771/// \brief Find equivalence classes.
772///
773/// Since samples may be missing from blocks, we can fill in the gaps by setting
774/// the weights of all the blocks in the same equivalence class to the same
775/// weight. To compute the concept of equivalence, we use dominance and loop
776/// information. Two blocks B1 and B2 are in the same equivalence class if B1
777/// dominates B2, B2 post-dominates B1 and both are in the same loop.
778///
779/// \param F The function to query.
Diego Novillode1ab262014-09-09 12:40:50 +0000780void SampleProfileLoader::findEquivalenceClasses(Function &F) {
Diego Novillo0accb3d2014-01-10 23:23:46 +0000781 SmallVector<BasicBlock *, 8> DominatedBBs;
782 DEBUG(dbgs() << "\nBlock equivalence classes\n");
783 // Find equivalence sets based on dominance and post-dominance information.
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000784 for (auto &BB : F) {
785 BasicBlock *BB1 = &BB;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000786
787 // Compute BB1's equivalence class once.
788 if (EquivalenceClass.count(BB1)) {
789 DEBUG(printBlockEquivalence(dbgs(), BB1));
790 continue;
791 }
792
793 // By default, blocks are in their own equivalence class.
794 EquivalenceClass[BB1] = BB1;
795
796 // Traverse all the blocks dominated by BB1. We are looking for
797 // every basic block BB2 such that:
798 //
799 // 1- BB1 dominates BB2.
800 // 2- BB2 post-dominates BB1.
801 // 3- BB1 and BB2 are in the same loop nest.
802 //
803 // If all those conditions hold, it means that BB2 is executed
804 // as many times as BB1, so they are placed in the same equivalence
805 // class by making BB2's equivalence class be BB1.
806 DominatedBBs.clear();
807 DT->getDescendants(BB1, DominatedBBs);
Diego Novillo7732ae42015-08-26 20:00:27 +0000808 findEquivalencesFor(BB1, DominatedBBs, PDT.get());
Diego Novillo0accb3d2014-01-10 23:23:46 +0000809
Diego Novillo0accb3d2014-01-10 23:23:46 +0000810 DEBUG(printBlockEquivalence(dbgs(), BB1));
811 }
812
813 // Assign weights to equivalence classes.
814 //
815 // All the basic blocks in the same equivalence class will execute
816 // the same number of times. Since we know that the head block in
817 // each equivalence class has the largest weight, assign that weight
818 // to all the blocks in that equivalence class.
819 DEBUG(dbgs() << "\nAssign the same weight to all blocks in the same class\n");
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000820 for (auto &BI : F) {
Dehao Chen8e7df832015-09-29 18:28:15 +0000821 const BasicBlock *BB = &BI;
822 const BasicBlock *EquivBB = EquivalenceClass[BB];
Diego Novillo0accb3d2014-01-10 23:23:46 +0000823 if (BB != EquivBB)
824 BlockWeights[BB] = BlockWeights[EquivBB];
825 DEBUG(printBlockWeight(dbgs(), BB));
826 }
827}
828
829/// \brief Visit the given edge to decide if it has a valid weight.
830///
831/// If \p E has not been visited before, we copy to \p UnknownEdge
832/// and increment the count of unknown edges.
833///
834/// \param E Edge to visit.
835/// \param NumUnknownEdges Current number of unknown edges.
836/// \param UnknownEdge Set if E has not been visited before.
837///
838/// \returns E's weight, if known. Otherwise, return 0.
Diego Novillo38be3332015-10-15 16:36:21 +0000839uint64_t SampleProfileLoader::visitEdge(Edge E, unsigned *NumUnknownEdges,
Diego Novillode1ab262014-09-09 12:40:50 +0000840 Edge *UnknownEdge) {
Diego Novillo0accb3d2014-01-10 23:23:46 +0000841 if (!VisitedEdges.count(E)) {
842 (*NumUnknownEdges)++;
843 *UnknownEdge = E;
844 return 0;
845 }
846
847 return EdgeWeights[E];
848}
849
850/// \brief Propagate weights through incoming/outgoing edges.
851///
852/// If the weight of a basic block is known, and there is only one edge
853/// with an unknown weight, we can calculate the weight of that edge.
854///
855/// Similarly, if all the edges have a known count, we can calculate the
856/// count of the basic block, if needed.
857///
858/// \param F Function to process.
859///
860/// \returns True if new weights were assigned to edges or blocks.
Diego Novillode1ab262014-09-09 12:40:50 +0000861bool SampleProfileLoader::propagateThroughEdges(Function &F) {
Diego Novillo0accb3d2014-01-10 23:23:46 +0000862 bool Changed = false;
863 DEBUG(dbgs() << "\nPropagation through edges\n");
Dehao Chen7c41dd62015-10-01 00:26:56 +0000864 for (const auto &BI : F) {
865 const BasicBlock *BB = &BI;
866 const BasicBlock *EC = EquivalenceClass[BB];
Diego Novillo0accb3d2014-01-10 23:23:46 +0000867
868 // Visit all the predecessor and successor edges to determine
869 // which ones have a weight assigned already. Note that it doesn't
870 // matter that we only keep track of a single unknown edge. The
871 // only case we are interested in handling is when only a single
872 // edge is unknown (see setEdgeOrBlockWeight).
873 for (unsigned i = 0; i < 2; i++) {
Diego Novillo38be3332015-10-15 16:36:21 +0000874 uint64_t TotalWeight = 0;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000875 unsigned NumUnknownEdges = 0;
876 Edge UnknownEdge, SelfReferentialEdge;
877
878 if (i == 0) {
879 // First, visit all predecessor edges.
Diego Novillob368b7d2014-10-22 16:51:50 +0000880 for (auto *Pred : Predecessors[BB]) {
881 Edge E = std::make_pair(Pred, BB);
Diego Novillo0accb3d2014-01-10 23:23:46 +0000882 TotalWeight += visitEdge(E, &NumUnknownEdges, &UnknownEdge);
883 if (E.first == E.second)
884 SelfReferentialEdge = E;
885 }
886 } else {
887 // On the second round, visit all successor edges.
Diego Novillob368b7d2014-10-22 16:51:50 +0000888 for (auto *Succ : Successors[BB]) {
889 Edge E = std::make_pair(BB, Succ);
Diego Novillo0accb3d2014-01-10 23:23:46 +0000890 TotalWeight += visitEdge(E, &NumUnknownEdges, &UnknownEdge);
891 }
892 }
893
894 // After visiting all the edges, there are three cases that we
895 // can handle immediately:
896 //
897 // - All the edge weights are known (i.e., NumUnknownEdges == 0).
898 // In this case, we simply check that the sum of all the edges
899 // is the same as BB's weight. If not, we change BB's weight
900 // to match. Additionally, if BB had not been visited before,
901 // we mark it visited.
902 //
903 // - Only one edge is unknown and BB has already been visited.
904 // In this case, we can compute the weight of the edge by
905 // subtracting the total block weight from all the known
906 // edge weights. If the edges weight more than BB, then the
907 // edge of the last remaining edge is set to zero.
908 //
909 // - There exists a self-referential edge and the weight of BB is
910 // known. In this case, this edge can be based on BB's weight.
911 // We add up all the other known edges and set the weight on
912 // the self-referential edge as we did in the previous case.
913 //
914 // In any other case, we must continue iterating. Eventually,
915 // all edges will get a weight, or iteration will stop when
916 // it reaches SampleProfileMaxPropagateIterations.
917 if (NumUnknownEdges <= 1) {
Diego Novillo38be3332015-10-15 16:36:21 +0000918 uint64_t &BBWeight = BlockWeights[EC];
Diego Novillo0accb3d2014-01-10 23:23:46 +0000919 if (NumUnknownEdges == 0) {
920 // If we already know the weight of all edges, the weight of the
921 // basic block can be computed. It should be no larger than the sum
922 // of all edge weights.
923 if (TotalWeight > BBWeight) {
924 BBWeight = TotalWeight;
925 Changed = true;
926 DEBUG(dbgs() << "All edge weights for " << BB->getName()
927 << " known. Set weight for block: ";
928 printBlockWeight(dbgs(), BB););
929 }
Dehao Chen7c41dd62015-10-01 00:26:56 +0000930 if (VisitedBlocks.insert(EC).second)
Diego Novillo0accb3d2014-01-10 23:23:46 +0000931 Changed = true;
Dehao Chen7c41dd62015-10-01 00:26:56 +0000932 } else if (NumUnknownEdges == 1 && VisitedBlocks.count(EC)) {
Diego Novillo0accb3d2014-01-10 23:23:46 +0000933 // If there is a single unknown edge and the block has been
934 // visited, then we can compute E's weight.
935 if (BBWeight >= TotalWeight)
936 EdgeWeights[UnknownEdge] = BBWeight - TotalWeight;
937 else
938 EdgeWeights[UnknownEdge] = 0;
939 VisitedEdges.insert(UnknownEdge);
940 Changed = true;
941 DEBUG(dbgs() << "Set weight for edge: ";
942 printEdgeWeight(dbgs(), UnknownEdge));
943 }
Dehao Chen7c41dd62015-10-01 00:26:56 +0000944 } else if (SelfReferentialEdge.first && VisitedBlocks.count(EC)) {
Diego Novillo38be3332015-10-15 16:36:21 +0000945 uint64_t &BBWeight = BlockWeights[BB];
Diego Novillo0accb3d2014-01-10 23:23:46 +0000946 // We have a self-referential edge and the weight of BB is known.
947 if (BBWeight >= TotalWeight)
948 EdgeWeights[SelfReferentialEdge] = BBWeight - TotalWeight;
949 else
950 EdgeWeights[SelfReferentialEdge] = 0;
951 VisitedEdges.insert(SelfReferentialEdge);
952 Changed = true;
953 DEBUG(dbgs() << "Set self-referential edge weight to: ";
954 printEdgeWeight(dbgs(), SelfReferentialEdge));
955 }
956 }
957 }
958
959 return Changed;
960}
961
962/// \brief Build in/out edge lists for each basic block in the CFG.
963///
964/// We are interested in unique edges. If a block B1 has multiple
965/// edges to another block B2, we only add a single B1->B2 edge.
Diego Novillode1ab262014-09-09 12:40:50 +0000966void SampleProfileLoader::buildEdges(Function &F) {
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000967 for (auto &BI : F) {
968 BasicBlock *B1 = &BI;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000969
970 // Add predecessors for B1.
971 SmallPtrSet<BasicBlock *, 16> Visited;
972 if (!Predecessors[B1].empty())
973 llvm_unreachable("Found a stale predecessors list in a basic block.");
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000974 for (pred_iterator PI = pred_begin(B1), PE = pred_end(B1); PI != PE; ++PI) {
975 BasicBlock *B2 = *PI;
David Blaikie70573dc2014-11-19 07:49:26 +0000976 if (Visited.insert(B2).second)
Diego Novillo0accb3d2014-01-10 23:23:46 +0000977 Predecessors[B1].push_back(B2);
978 }
979
980 // Add successors for B1.
981 Visited.clear();
982 if (!Successors[B1].empty())
983 llvm_unreachable("Found a stale successors list in a basic block.");
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000984 for (succ_iterator SI = succ_begin(B1), SE = succ_end(B1); SI != SE; ++SI) {
985 BasicBlock *B2 = *SI;
David Blaikie70573dc2014-11-19 07:49:26 +0000986 if (Visited.insert(B2).second)
Diego Novillo0accb3d2014-01-10 23:23:46 +0000987 Successors[B1].push_back(B2);
988 }
989 }
990}
991
992/// \brief Propagate weights into edges
993///
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000994/// The following rules are applied to every block BB in the CFG:
Diego Novillo0accb3d2014-01-10 23:23:46 +0000995///
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000996/// - If BB has a single predecessor/successor, then the weight
Diego Novillo0accb3d2014-01-10 23:23:46 +0000997/// of that edge is the weight of the block.
998///
999/// - If all incoming or outgoing edges are known except one, and the
1000/// weight of the block is already known, the weight of the unknown
1001/// edge will be the weight of the block minus the sum of all the known
Diego Novillo19e7b7e2014-10-22 18:39:50 +00001002/// edges. If the sum of all the known edges is larger than BB's weight,
Diego Novillo0accb3d2014-01-10 23:23:46 +00001003/// we set the unknown edge weight to zero.
1004///
1005/// - If there is a self-referential edge, and the weight of the block is
1006/// known, the weight for that edge is set to the weight of the block
1007/// minus the weight of the other incoming edges to that block (if
1008/// known).
Diego Novillode1ab262014-09-09 12:40:50 +00001009void SampleProfileLoader::propagateWeights(Function &F) {
Diego Novillo0accb3d2014-01-10 23:23:46 +00001010 bool Changed = true;
Diego Novillo38be3332015-10-15 16:36:21 +00001011 unsigned I = 0;
Diego Novillo0accb3d2014-01-10 23:23:46 +00001012
Diego Novilloffc84e32015-05-13 17:04:29 +00001013 // Add an entry count to the function using the samples gathered
1014 // at the function entry.
1015 F.setEntryCount(Samples->getHeadSamples());
1016
Diego Novillo0accb3d2014-01-10 23:23:46 +00001017 // Before propagation starts, build, for each block, a list of
1018 // unique predecessors and successors. This is necessary to handle
1019 // identical edges in multiway branches. Since we visit all blocks and all
1020 // edges of the CFG, it is cleaner to build these lists once at the start
1021 // of the pass.
1022 buildEdges(F);
1023
1024 // Propagate until we converge or we go past the iteration limit.
Diego Novillo38be3332015-10-15 16:36:21 +00001025 while (Changed && I++ < SampleProfileMaxPropagateIterations) {
Diego Novillo0accb3d2014-01-10 23:23:46 +00001026 Changed = propagateThroughEdges(F);
1027 }
1028
1029 // Generate MD_prof metadata for every branch instruction using the
1030 // edge weights computed during propagation.
1031 DEBUG(dbgs() << "\nPropagation complete. Setting branch weights\n");
Diego Novillo7963ea12015-10-26 18:52:53 +00001032 LLVMContext &Ctx = F.getContext();
1033 MDBuilder MDB(Ctx);
Diego Novillo19e7b7e2014-10-22 18:39:50 +00001034 for (auto &BI : F) {
1035 BasicBlock *BB = &BI;
1036 TerminatorInst *TI = BB->getTerminator();
Diego Novillo0accb3d2014-01-10 23:23:46 +00001037 if (TI->getNumSuccessors() == 1)
1038 continue;
1039 if (!isa<BranchInst>(TI) && !isa<SwitchInst>(TI))
1040 continue;
1041
1042 DEBUG(dbgs() << "\nGetting weights for branch at line "
Diego Novillo92aa8c22014-03-10 22:41:28 +00001043 << TI->getDebugLoc().getLine() << ".\n");
Diego Novillo38be3332015-10-15 16:36:21 +00001044 SmallVector<uint32_t, 4> Weights;
Diego Novillo7963ea12015-10-26 18:52:53 +00001045 uint32_t MaxWeight = 0;
Diego Novillo7963ea12015-10-26 18:52:53 +00001046 DebugLoc MaxDestLoc;
Diego Novillo0accb3d2014-01-10 23:23:46 +00001047 for (unsigned I = 0; I < TI->getNumSuccessors(); ++I) {
1048 BasicBlock *Succ = TI->getSuccessor(I);
Diego Novillo19e7b7e2014-10-22 18:39:50 +00001049 Edge E = std::make_pair(BB, Succ);
Diego Novillo38be3332015-10-15 16:36:21 +00001050 uint64_t Weight = EdgeWeights[E];
Diego Novillo0accb3d2014-01-10 23:23:46 +00001051 DEBUG(dbgs() << "\t"; printEdgeWeight(dbgs(), E));
Diego Novillo38be3332015-10-15 16:36:21 +00001052 // Use uint32_t saturated arithmetic to adjust the incoming weights,
1053 // if needed. Sample counts in profiles are 64-bit unsigned values,
1054 // but internally branch weights are expressed as 32-bit values.
1055 if (Weight > std::numeric_limits<uint32_t>::max()) {
1056 DEBUG(dbgs() << " (saturated due to uint32_t overflow)");
1057 Weight = std::numeric_limits<uint32_t>::max();
1058 }
1059 Weights.push_back(static_cast<uint32_t>(Weight));
Diego Novillo7963ea12015-10-26 18:52:53 +00001060 if (Weight != 0) {
1061 if (Weight > MaxWeight) {
1062 MaxWeight = Weight;
Diego Novillo7963ea12015-10-26 18:52:53 +00001063 MaxDestLoc = Succ->getFirstNonPHIOrDbgOrLifetime()->getDebugLoc();
1064 }
1065 }
Diego Novillo0accb3d2014-01-10 23:23:46 +00001066 }
1067
1068 // Only set weights if there is at least one non-zero weight.
1069 // In any other case, let the analyzer set weights.
Diego Novillo7963ea12015-10-26 18:52:53 +00001070 if (MaxWeight > 0) {
Diego Novillo0accb3d2014-01-10 23:23:46 +00001071 DEBUG(dbgs() << "SUCCESS. Found non-zero weights.\n");
1072 TI->setMetadata(llvm::LLVMContext::MD_prof,
1073 MDB.createBranchWeights(Weights));
Diego Novillo7963ea12015-10-26 18:52:53 +00001074 DebugLoc BranchLoc = TI->getDebugLoc();
1075 emitOptimizationRemark(
1076 Ctx, DEBUG_TYPE, F, MaxDestLoc,
1077 Twine("most popular destination for conditional branches at ") +
Diego Novilloc04270d2015-10-27 17:37:00 +00001078 ((BranchLoc) ? Twine(BranchLoc->getFilename() + ":" +
1079 Twine(BranchLoc.getLine()) + ":" +
1080 Twine(BranchLoc.getCol()))
1081 : Twine("<UNKNOWN LOCATION>")));
Diego Novillo0accb3d2014-01-10 23:23:46 +00001082 } else {
1083 DEBUG(dbgs() << "SKIPPED. All branch weights are zero.\n");
1084 }
1085 }
1086}
1087
1088/// \brief Get the line number for the function header.
1089///
1090/// This looks up function \p F in the current compilation unit and
1091/// retrieves the line number where the function is defined. This is
1092/// line 0 for all the samples read from the profile file. Every line
1093/// number is relative to this line.
1094///
1095/// \param F Function object to query.
1096///
Diego Novilloa32aa322014-03-14 21:58:59 +00001097/// \returns the line number where \p F is defined. If it returns 0,
1098/// it means that there is no debug information available for \p F.
Diego Novillode1ab262014-09-09 12:40:50 +00001099unsigned SampleProfileLoader::getFunctionLoc(Function &F) {
Pete Cooperadebb932016-03-11 02:14:16 +00001100 if (DISubprogram *S = F.getSubprogram())
Duncan P. N. Exon Smith537b4a82015-04-14 03:40:37 +00001101 return S->getLine();
Diego Novillo0accb3d2014-01-10 23:23:46 +00001102
Diego Novilloaa555072015-10-27 18:41:46 +00001103 // If the start of \p F is missing, emit a diagnostic to inform the user
Diego Novillo8027b802014-10-22 12:59:00 +00001104 // about the missed opportunity.
David Blaikie61079682014-03-16 01:36:18 +00001105 F.getContext().diagnose(DiagnosticInfoSampleProfile(
Diego Novilloa67c0b42014-10-22 13:36:35 +00001106 "No debug information found in function " + F.getName() +
1107 ": Function profile not used",
1108 DS_Warning));
Diego Novilloa32aa322014-03-14 21:58:59 +00001109 return 0;
Diego Novillo0accb3d2014-01-10 23:23:46 +00001110}
1111
Diego Novillo7732ae42015-08-26 20:00:27 +00001112void SampleProfileLoader::computeDominanceAndLoopInfo(Function &F) {
1113 DT.reset(new DominatorTree);
1114 DT->recalculate(F);
1115
1116 PDT.reset(new DominatorTreeBase<BasicBlock>(true));
1117 PDT->recalculate(F);
1118
1119 LI.reset(new LoopInfo);
1120 LI->analyze(*DT);
1121}
1122
Diego Novillo0accb3d2014-01-10 23:23:46 +00001123/// \brief Generate branch weight metadata for all branches in \p F.
1124///
1125/// Branch weights are computed out of instruction samples using a
1126/// propagation heuristic. Propagation proceeds in 3 phases:
1127///
1128/// 1- Assignment of block weights. All the basic blocks in the function
1129/// are initial assigned the same weight as their most frequently
1130/// executed instruction.
1131///
1132/// 2- Creation of equivalence classes. Since samples may be missing from
1133/// blocks, we can fill in the gaps by setting the weights of all the
1134/// blocks in the same equivalence class to the same weight. To compute
1135/// the concept of equivalence, we use dominance and loop information.
1136/// Two blocks B1 and B2 are in the same equivalence class if B1
1137/// dominates B2, B2 post-dominates B1 and both are in the same loop.
1138///
1139/// 3- Propagation of block weights into edges. This uses a simple
1140/// propagation heuristic. The following rules are applied to every
Diego Novillo19e7b7e2014-10-22 18:39:50 +00001141/// block BB in the CFG:
Diego Novillo0accb3d2014-01-10 23:23:46 +00001142///
Diego Novillo19e7b7e2014-10-22 18:39:50 +00001143/// - If BB has a single predecessor/successor, then the weight
Diego Novillo0accb3d2014-01-10 23:23:46 +00001144/// of that edge is the weight of the block.
1145///
1146/// - If all the edges are known except one, and the weight of the
1147/// block is already known, the weight of the unknown edge will
1148/// be the weight of the block minus the sum of all the known
Diego Novillo19e7b7e2014-10-22 18:39:50 +00001149/// edges. If the sum of all the known edges is larger than BB's weight,
Diego Novillo0accb3d2014-01-10 23:23:46 +00001150/// we set the unknown edge weight to zero.
1151///
1152/// - If there is a self-referential edge, and the weight of the block is
1153/// known, the weight for that edge is set to the weight of the block
1154/// minus the weight of the other incoming edges to that block (if
1155/// known).
1156///
1157/// Since this propagation is not guaranteed to finalize for every CFG, we
1158/// only allow it to proceed for a limited number of iterations (controlled
1159/// by -sample-profile-max-propagate-iterations).
1160///
1161/// FIXME: Try to replace this propagation heuristic with a scheme
1162/// that is guaranteed to finalize. A work-list approach similar to
1163/// the standard value propagation algorithm used by SSA-CCP might
1164/// work here.
1165///
1166/// Once all the branch weights are computed, we emit the MD_prof
Diego Novillo19e7b7e2014-10-22 18:39:50 +00001167/// metadata on BB using the computed values for each of its branches.
Diego Novillo0accb3d2014-01-10 23:23:46 +00001168///
1169/// \param F The function to query.
Diego Novilloa32aa322014-03-14 21:58:59 +00001170///
1171/// \returns true if \p F was modified. Returns false, otherwise.
Diego Novillode1ab262014-09-09 12:40:50 +00001172bool SampleProfileLoader::emitAnnotations(Function &F) {
Diego Novillo0accb3d2014-01-10 23:23:46 +00001173 bool Changed = false;
1174
Dehao Chen41dc5a62015-10-09 16:50:16 +00001175 if (getFunctionLoc(F) == 0)
Diego Novilloa32aa322014-03-14 21:58:59 +00001176 return false;
1177
Diego Novillo0accb3d2014-01-10 23:23:46 +00001178 DEBUG(dbgs() << "Line number for the first instruction in " << F.getName()
Dehao Chen41dc5a62015-10-09 16:50:16 +00001179 << ": " << getFunctionLoc(F) << "\n");
Diego Novillo0accb3d2014-01-10 23:23:46 +00001180
Diego Novillo84f06cc2015-11-27 23:14:51 +00001181 Changed |= emitInlineHints(F);
1182
Dehao Chen67226882015-09-30 00:42:46 +00001183 Changed |= inlineHotFunctions(F);
1184
Diego Novillo0accb3d2014-01-10 23:23:46 +00001185 // Compute basic block weights.
1186 Changed |= computeBlockWeights(F);
1187
1188 if (Changed) {
Diego Novillo7732ae42015-08-26 20:00:27 +00001189 // Compute dominance and loop info needed for propagation.
1190 computeDominanceAndLoopInfo(F);
1191
Diego Novillo0accb3d2014-01-10 23:23:46 +00001192 // Find equivalence classes.
1193 findEquivalenceClasses(F);
1194
1195 // Propagate weights to all edges.
1196 propagateWeights(F);
1197 }
1198
Diego Novillof9ed08e2015-10-31 21:53:58 +00001199 // If coverage checking was requested, compute it now.
Diego Novillo243ea6a2015-11-23 20:12:21 +00001200 if (SampleProfileRecordCoverage) {
1201 unsigned Used = CoverageTracker.countUsedRecords(Samples);
1202 unsigned Total = CoverageTracker.countBodyRecords(Samples);
Diego Novillof9ed08e2015-10-31 21:53:58 +00001203 unsigned Coverage = CoverageTracker.computeCoverage(Used, Total);
Diego Novillo243ea6a2015-11-23 20:12:21 +00001204 if (Coverage < SampleProfileRecordCoverage) {
Diego Novillof9ed08e2015-10-31 21:53:58 +00001205 F.getContext().diagnose(DiagnosticInfoSampleProfile(
Pete Cooperadebb932016-03-11 02:14:16 +00001206 F.getSubprogram()->getFilename(), getFunctionLoc(F),
Diego Novillof9ed08e2015-10-31 21:53:58 +00001207 Twine(Used) + " of " + Twine(Total) + " available profile records (" +
1208 Twine(Coverage) + "%) were applied",
1209 DS_Warning));
1210 }
1211 }
1212
Diego Novillo243ea6a2015-11-23 20:12:21 +00001213 if (SampleProfileSampleCoverage) {
1214 uint64_t Used = CoverageTracker.getTotalUsedSamples();
1215 uint64_t Total = CoverageTracker.countBodySamples(Samples);
1216 unsigned Coverage = CoverageTracker.computeCoverage(Used, Total);
1217 if (Coverage < SampleProfileSampleCoverage) {
1218 F.getContext().diagnose(DiagnosticInfoSampleProfile(
Pete Cooperadebb932016-03-11 02:14:16 +00001219 F.getSubprogram()->getFilename(), getFunctionLoc(F),
Diego Novillo243ea6a2015-11-23 20:12:21 +00001220 Twine(Used) + " of " + Twine(Total) + " available profile samples (" +
1221 Twine(Coverage) + "%) were applied",
1222 DS_Warning));
1223 }
1224 }
Diego Novillo0accb3d2014-01-10 23:23:46 +00001225 return Changed;
1226}
1227
Xinliang David Lie897edb2016-05-27 22:30:44 +00001228char SampleProfileLoaderLegacyPass::ID = 0;
Xinliang David Lid38392e2016-05-27 23:20:16 +00001229INITIALIZE_PASS(SampleProfileLoaderLegacyPass, "sample-profile",
1230 "Sample Profile loader", false, false)
Diego Novilloc0dd1032013-11-26 20:37:33 +00001231
1232bool SampleProfileLoader::doInitialization(Module &M) {
Diego Novillo7732ae42015-08-26 20:00:27 +00001233 auto &Ctx = M.getContext();
Diego Novillo4d711132015-08-25 15:25:11 +00001234 auto ReaderOrErr = SampleProfileReader::create(Filename, Ctx);
Diego Novillofcd55602014-11-03 00:51:45 +00001235 if (std::error_code EC = ReaderOrErr.getError()) {
Diego Novilloc572e922014-10-30 18:00:06 +00001236 std::string Msg = "Could not open profile: " + EC.message();
David Blaikie2297a912015-11-02 20:01:13 +00001237 Ctx.diagnose(DiagnosticInfoSampleProfile(Filename, Msg));
Diego Novilloc572e922014-10-30 18:00:06 +00001238 return false;
1239 }
Diego Novillofcd55602014-11-03 00:51:45 +00001240 Reader = std::move(ReaderOrErr.get());
Diego Novilloc572e922014-10-30 18:00:06 +00001241 ProfileIsValid = (Reader->read() == sampleprof_error::success);
Diego Novilloc0dd1032013-11-26 20:37:33 +00001242 return true;
1243}
1244
Diego Novillo4d711132015-08-25 15:25:11 +00001245ModulePass *llvm::createSampleProfileLoaderPass() {
Xinliang David Lie897edb2016-05-27 22:30:44 +00001246 return new SampleProfileLoaderLegacyPass(SampleProfileFile);
Diego Novilloc0dd1032013-11-26 20:37:33 +00001247}
1248
Diego Novillo4d711132015-08-25 15:25:11 +00001249ModulePass *llvm::createSampleProfileLoaderPass(StringRef Name) {
Xinliang David Lie897edb2016-05-27 22:30:44 +00001250 return new SampleProfileLoaderLegacyPass(Name);
Diego Novilloc0dd1032013-11-26 20:37:33 +00001251}
1252
Diego Novillo4d711132015-08-25 15:25:11 +00001253bool SampleProfileLoader::runOnModule(Module &M) {
Diego Novilloa8a3bd22015-10-28 17:40:22 +00001254 if (!ProfileIsValid)
1255 return false;
1256
Diego Novillo84f06cc2015-11-27 23:14:51 +00001257 // Compute the total number of samples collected in this profile.
1258 for (const auto &I : Reader->getProfiles())
1259 TotalCollectedSamples += I.second.getTotalSamples();
1260
Diego Novillo4d711132015-08-25 15:25:11 +00001261 bool retval = false;
1262 for (auto &F : M)
Diego Novilloa8a3bd22015-10-28 17:40:22 +00001263 if (!F.isDeclaration()) {
1264 clearFunctionData();
Diego Novillo4d711132015-08-25 15:25:11 +00001265 retval |= runOnFunction(F);
Diego Novilloa8a3bd22015-10-28 17:40:22 +00001266 }
Diego Novillo4d711132015-08-25 15:25:11 +00001267 return retval;
1268}
1269
Xinliang David Lie897edb2016-05-27 22:30:44 +00001270bool SampleProfileLoaderLegacyPass::runOnModule(Module &M) {
1271 return SampleLoader.runOnModule(M);
1272}
1273
Diego Novillo8d6568b2013-11-13 12:22:21 +00001274bool SampleProfileLoader::runOnFunction(Function &F) {
Dehao Chen6c73b492016-02-22 22:46:21 +00001275 F.setEntryCount(0);
Diego Novillode1ab262014-09-09 12:40:50 +00001276 Samples = Reader->getSamplesFor(F);
1277 if (!Samples->empty())
1278 return emitAnnotations(F);
Diego Novillo0accb3d2014-01-10 23:23:46 +00001279 return false;
Diego Novillo8d6568b2013-11-13 12:22:21 +00001280}
Xinliang David Lid38392e2016-05-27 23:20:16 +00001281
1282PreservedAnalyses SampleProfileLoaderPass::run(Module &M,
1283 AnalysisManager<Module> &AM) {
1284
1285 SampleProfileLoader SampleLoader(SampleProfileFile);
1286
1287 SampleLoader.doInitialization(M);
1288
1289 if (!SampleLoader.runOnModule(M))
1290 return PreservedAnalyses::all();
1291
1292 return PreservedAnalyses::none();
1293}