blob: b6a112d530ec1cd66a7447caaf65996718bbfe65 [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"
Dehao Chen071bb9d2016-06-20 20:53:40 +000030#include "llvm/Analysis/AssumptionCache.h"
Diego Novillo0accb3d2014-01-10 23:23:46 +000031#include "llvm/Analysis/LoopInfo.h"
Chandler Carruth07baed52014-01-13 08:04:33 +000032#include "llvm/Analysis/PostDominators.h"
Diego Novillo8d6568b2013-11-13 12:22:21 +000033#include "llvm/IR/Constants.h"
Chandler Carruth9a4c9e52014-03-06 00:46:21 +000034#include "llvm/IR/DebugInfo.h"
Diego Novilloa32aa322014-03-14 21:58:59 +000035#include "llvm/IR/DiagnosticInfo.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000036#include "llvm/IR/Dominators.h"
Diego Novillo8d6568b2013-11-13 12:22:21 +000037#include "llvm/IR/Function.h"
Chandler Carruth83948572014-03-04 10:30:26 +000038#include "llvm/IR/InstIterator.h"
Diego Novillo8d6568b2013-11-13 12:22:21 +000039#include "llvm/IR/Instructions.h"
Xinliang David Lid38392e2016-05-27 23:20:16 +000040#include "llvm/IR/IntrinsicInst.h"
Diego Novillo8d6568b2013-11-13 12:22:21 +000041#include "llvm/IR/LLVMContext.h"
Diego Novillo8d6568b2013-11-13 12:22:21 +000042#include "llvm/IR/MDBuilder.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000043#include "llvm/IR/Metadata.h"
Diego Novillo8d6568b2013-11-13 12:22:21 +000044#include "llvm/IR/Module.h"
45#include "llvm/Pass.h"
Diego Novillode1ab262014-09-09 12:40:50 +000046#include "llvm/ProfileData/SampleProfReader.h"
Diego Novillo8d6568b2013-11-13 12:22:21 +000047#include "llvm/Support/CommandLine.h"
48#include "llvm/Support/Debug.h"
Dehao Chen8e7df832015-09-29 18:28:15 +000049#include "llvm/Support/ErrorOr.h"
Diego Novillo7ff0a172015-11-29 18:23:26 +000050#include "llvm/Support/Format.h"
Diego Novillo8d6568b2013-11-13 12:22:21 +000051#include "llvm/Support/raw_ostream.h"
Diego Novillo4d711132015-08-25 15:25:11 +000052#include "llvm/Transforms/IPO.h"
Dehao Chen57d1dda2016-03-03 18:09:32 +000053#include "llvm/Transforms/Utils/Cloning.h"
Logan Chien61c6df02014-02-22 06:34:10 +000054#include <cctype>
Diego Novillo8d6568b2013-11-13 12:22:21 +000055
56using namespace llvm;
Diego Novillode1ab262014-09-09 12:40:50 +000057using namespace sampleprof;
Diego Novillo8d6568b2013-11-13 12:22:21 +000058
Chandler Carruth964daaa2014-04-22 02:55:47 +000059#define DEBUG_TYPE "sample-profile"
60
Diego Novillo8d6568b2013-11-13 12:22:21 +000061// Command line option to specify the file to read samples from. This is
62// mainly used for debugging.
63static cl::opt<std::string> SampleProfileFile(
64 "sample-profile-file", cl::init(""), cl::value_desc("filename"),
65 cl::desc("Profile file loaded by -sample-profile"), cl::Hidden);
Diego Novillo0accb3d2014-01-10 23:23:46 +000066static cl::opt<unsigned> SampleProfileMaxPropagateIterations(
67 "sample-profile-max-propagate-iterations", cl::init(100),
68 cl::desc("Maximum number of iterations to go through when propagating "
69 "sample block/edge weights through the CFG."));
Diego Novillo243ea6a2015-11-23 20:12:21 +000070static cl::opt<unsigned> SampleProfileRecordCoverage(
71 "sample-profile-check-record-coverage", cl::init(0), cl::value_desc("N"),
72 cl::desc("Emit a warning if less than N% of records in the input profile "
73 "are matched to the IR."));
74static cl::opt<unsigned> SampleProfileSampleCoverage(
75 "sample-profile-check-sample-coverage", cl::init(0), cl::value_desc("N"),
Diego Novillo748b3ffe2015-10-28 22:30:25 +000076 cl::desc("Emit a warning if less than N% of samples in the input profile "
77 "are matched to the IR."));
Diego Novillob5792402015-11-27 23:14:49 +000078static cl::opt<double> SampleProfileHotThreshold(
79 "sample-profile-inline-hot-threshold", cl::init(0.1), cl::value_desc("N"),
Diego Novillo0b6985a2015-11-24 22:38:37 +000080 cl::desc("Inlined functions that account for more than N% of all samples "
81 "collected in the parent function, will be inlined again."));
Diego Novillo84f06cc2015-11-27 23:14:51 +000082static cl::opt<double> SampleProfileGlobalHotThreshold(
83 "sample-profile-global-hot-threshold", cl::init(30), cl::value_desc("N"),
84 cl::desc("Top-level functions that account for more than N% of all samples "
85 "collected in the profile, will be marked as hot for the inliner "
86 "to consider."));
87static cl::opt<double> SampleProfileGlobalColdThreshold(
88 "sample-profile-global-cold-threshold", cl::init(0.5), cl::value_desc("N"),
89 cl::desc("Top-level functions that account for less than N% of all samples "
90 "collected in the profile, will be marked as cold for the inliner "
91 "to consider."));
Diego Novillo8d6568b2013-11-13 12:22:21 +000092
93namespace {
Diego Novillo38be3332015-10-15 16:36:21 +000094typedef DenseMap<const BasicBlock *, uint64_t> BlockWeightMap;
Dehao Chen8e7df832015-09-29 18:28:15 +000095typedef DenseMap<const BasicBlock *, const BasicBlock *> EquivalenceClassMap;
96typedef std::pair<const BasicBlock *, const BasicBlock *> Edge;
Diego Novillo38be3332015-10-15 16:36:21 +000097typedef DenseMap<Edge, uint64_t> EdgeWeightMap;
Dehao Chen8e7df832015-09-29 18:28:15 +000098typedef DenseMap<const BasicBlock *, SmallVector<const BasicBlock *, 8>>
99 BlockEdgeMap;
Diego Novilloc0dd1032013-11-26 20:37:33 +0000100
Diego Novillode1ab262014-09-09 12:40:50 +0000101/// \brief Sample profile pass.
Diego Novilloc0dd1032013-11-26 20:37:33 +0000102///
Diego Novillode1ab262014-09-09 12:40:50 +0000103/// This pass reads profile data from the file specified by
104/// -sample-profile-file and annotates every affected function with the
105/// profile information found in that file.
Xinliang David Lie897edb2016-05-27 22:30:44 +0000106class SampleProfileLoader {
Diego Novilloc0dd1032013-11-26 20:37:33 +0000107public:
Diego Novillode1ab262014-09-09 12:40:50 +0000108 SampleProfileLoader(StringRef Name = SampleProfileFile)
Dehao Chen071bb9d2016-06-20 20:53:40 +0000109 : DT(nullptr), PDT(nullptr), LI(nullptr), ACT(nullptr), Reader(),
110 Samples(nullptr), Filename(Name), ProfileIsValid(false),
111 TotalCollectedSamples(0) {}
Diego Novillode1ab262014-09-09 12:40:50 +0000112
Xinliang David Lie897edb2016-05-27 22:30:44 +0000113 bool doInitialization(Module &M);
114 bool runOnModule(Module &M);
Dehao Chen071bb9d2016-06-20 20:53:40 +0000115 void setACT(AssumptionCacheTracker *A) { ACT = A; }
Diego Novillode1ab262014-09-09 12:40:50 +0000116
117 void dump() { Reader->dump(); }
118
Diego Novillode1ab262014-09-09 12:40:50 +0000119protected:
Diego Novillo4d711132015-08-25 15:25:11 +0000120 bool runOnFunction(Function &F);
Diego Novillo0accb3d2014-01-10 23:23:46 +0000121 unsigned getFunctionLoc(Function &F);
Diego Novillode1ab262014-09-09 12:40:50 +0000122 bool emitAnnotations(Function &F);
Diego Novillo38be3332015-10-15 16:36:21 +0000123 ErrorOr<uint64_t> getInstWeight(const Instruction &I) const;
124 ErrorOr<uint64_t> getBlockWeight(const BasicBlock *BB) const;
Dehao Chen67226882015-09-30 00:42:46 +0000125 const FunctionSamples *findCalleeFunctionSamples(const CallInst &I) const;
126 const FunctionSamples *findFunctionSamples(const Instruction &I) const;
127 bool inlineHotFunctions(Function &F);
Diego Novillo84f06cc2015-11-27 23:14:51 +0000128 bool emitInlineHints(Function &F);
Diego Novillo0accb3d2014-01-10 23:23:46 +0000129 void printEdgeWeight(raw_ostream &OS, Edge E);
Dehao Chen8e7df832015-09-29 18:28:15 +0000130 void printBlockWeight(raw_ostream &OS, const BasicBlock *BB) const;
131 void printBlockEquivalence(raw_ostream &OS, const BasicBlock *BB);
Diego Novillo0accb3d2014-01-10 23:23:46 +0000132 bool computeBlockWeights(Function &F);
133 void findEquivalenceClasses(Function &F);
Benjamin Kramer8a752e32016-02-13 16:01:12 +0000134 void findEquivalencesFor(BasicBlock *BB1, ArrayRef<BasicBlock *> Descendants,
Diego Novillo0accb3d2014-01-10 23:23:46 +0000135 DominatorTreeBase<BasicBlock> *DomTree);
136 void propagateWeights(Function &F);
Diego Novillo38be3332015-10-15 16:36:21 +0000137 uint64_t visitEdge(Edge E, unsigned *NumUnknownEdges, Edge *UnknownEdge);
Diego Novillo0accb3d2014-01-10 23:23:46 +0000138 void buildEdges(Function &F);
139 bool propagateThroughEdges(Function &F);
Diego Novillo7732ae42015-08-26 20:00:27 +0000140 void computeDominanceAndLoopInfo(Function &F);
Dehao Chen10042412015-10-21 01:22:27 +0000141 unsigned getOffset(unsigned L, unsigned H) const;
Diego Novilloa8a3bd22015-10-28 17:40:22 +0000142 void clearFunctionData();
Diego Novilloc0dd1032013-11-26 20:37:33 +0000143
Diego Novilloc0dd1032013-11-26 20:37:33 +0000144 /// \brief Map basic blocks to their computed weights.
145 ///
146 /// The weight of a basic block is defined to be the maximum
147 /// of all the instruction weights in that block.
148 BlockWeightMap BlockWeights;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000149
150 /// \brief Map edges to their computed weights.
151 ///
152 /// Edge weights are computed by propagating basic block weights in
153 /// SampleProfile::propagateWeights.
154 EdgeWeightMap EdgeWeights;
155
156 /// \brief Set of visited blocks during propagation.
Matthias Braunb30f2f512016-01-30 01:24:31 +0000157 SmallPtrSet<const BasicBlock *, 32> VisitedBlocks;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000158
159 /// \brief Set of visited edges during propagation.
Matthias Braunb30f2f512016-01-30 01:24:31 +0000160 SmallSet<Edge, 32> VisitedEdges;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000161
162 /// \brief Equivalence classes for block weights.
163 ///
164 /// Two blocks BB1 and BB2 are in the same equivalence class if they
165 /// dominate and post-dominate each other, and they are in the same loop
166 /// nest. When this happens, the two blocks are guaranteed to execute
167 /// the same number of times.
168 EquivalenceClassMap EquivalenceClass;
169
170 /// \brief Dominance, post-dominance and loop information.
Diego Novillo7732ae42015-08-26 20:00:27 +0000171 std::unique_ptr<DominatorTree> DT;
172 std::unique_ptr<DominatorTreeBase<BasicBlock>> PDT;
173 std::unique_ptr<LoopInfo> LI;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000174
Dehao Chen071bb9d2016-06-20 20:53:40 +0000175 AssumptionCacheTracker *ACT;
176
Diego Novillo0accb3d2014-01-10 23:23:46 +0000177 /// \brief Predecessors for each basic block in the CFG.
178 BlockEdgeMap Predecessors;
179
180 /// \brief Successors for each basic block in the CFG.
181 BlockEdgeMap Successors;
Diego Novillo92aa8c22014-03-10 22:41:28 +0000182
Diego Novillo8d6568b2013-11-13 12:22:21 +0000183 /// \brief Profile reader object.
Diego Novillode1ab262014-09-09 12:40:50 +0000184 std::unique_ptr<SampleProfileReader> Reader;
185
186 /// \brief Samples collected for the body of this function.
187 FunctionSamples *Samples;
Diego Novillo8d6568b2013-11-13 12:22:21 +0000188
189 /// \brief Name of the profile file to load.
190 StringRef Filename;
Diego Novilloa32aa322014-03-14 21:58:59 +0000191
Alp Toker16f98b22014-04-09 14:47:27 +0000192 /// \brief Flag indicating whether the profile input loaded successfully.
Diego Novilloa32aa322014-03-14 21:58:59 +0000193 bool ProfileIsValid;
Diego Novillo84f06cc2015-11-27 23:14:51 +0000194
195 /// \brief Total number of samples collected in this profile.
196 ///
197 /// This is the sum of all the samples collected in all the functions executed
198 /// at runtime.
199 uint64_t TotalCollectedSamples;
Diego Novillo8d6568b2013-11-13 12:22:21 +0000200};
Diego Novillo748b3ffe2015-10-28 22:30:25 +0000201
Xinliang David Lie897edb2016-05-27 22:30:44 +0000202class SampleProfileLoaderLegacyPass : public ModulePass {
203public:
204 // Class identification, replacement for typeinfo
205 static char ID;
206
207 SampleProfileLoaderLegacyPass(StringRef Name = SampleProfileFile)
208 : ModulePass(ID), SampleLoader(Name) {
209 initializeSampleProfileLoaderLegacyPassPass(
210 *PassRegistry::getPassRegistry());
211 }
212
213 void dump() { SampleLoader.dump(); }
214
215 bool doInitialization(Module &M) override {
216 return SampleLoader.doInitialization(M);
217 }
218 const char *getPassName() const override { return "Sample profile pass"; }
219 bool runOnModule(Module &M) override;
220
Dehao Chen071bb9d2016-06-20 20:53:40 +0000221 void getAnalysisUsage(AnalysisUsage &AU) const override {
222 AU.addRequired<AssumptionCacheTracker>();
223 }
Xinliang David Lie897edb2016-05-27 22:30:44 +0000224private:
225 SampleProfileLoader SampleLoader;
226};
227
Diego Novillo748b3ffe2015-10-28 22:30:25 +0000228class SampleCoverageTracker {
229public:
Diego Novillo243ea6a2015-11-23 20:12:21 +0000230 SampleCoverageTracker() : SampleCoverage(), TotalUsedSamples(0) {}
Diego Novillo748b3ffe2015-10-28 22:30:25 +0000231
Diego Novillo243ea6a2015-11-23 20:12:21 +0000232 bool markSamplesUsed(const FunctionSamples *FS, uint32_t LineOffset,
233 uint32_t Discriminator, uint64_t Samples);
Diego Novillof9ed08e2015-10-31 21:53:58 +0000234 unsigned computeCoverage(unsigned Used, unsigned Total) const;
Diego Novillo243ea6a2015-11-23 20:12:21 +0000235 unsigned countUsedRecords(const FunctionSamples *FS) const;
236 unsigned countBodyRecords(const FunctionSamples *FS) const;
237 uint64_t getTotalUsedSamples() const { return TotalUsedSamples; }
238 uint64_t countBodySamples(const FunctionSamples *FS) const;
239 void clear() {
240 SampleCoverage.clear();
241 TotalUsedSamples = 0;
242 }
Diego Novillo748b3ffe2015-10-28 22:30:25 +0000243
244private:
Diego Novillo10cf1242015-12-11 23:21:38 +0000245 typedef std::map<LineLocation, unsigned> BodySampleCoverageMap;
Diego Novillo748b3ffe2015-10-28 22:30:25 +0000246 typedef DenseMap<const FunctionSamples *, BodySampleCoverageMap>
247 FunctionSamplesCoverageMap;
248
249 /// Coverage map for sampling records.
250 ///
251 /// This map keeps a record of sampling records that have been matched to
252 /// an IR instruction. This is used to detect some form of staleness in
253 /// profiles (see flag -sample-profile-check-coverage).
254 ///
255 /// Each entry in the map corresponds to a FunctionSamples instance. This is
256 /// another map that counts how many times the sample record at the
257 /// given location has been used.
258 FunctionSamplesCoverageMap SampleCoverage;
Diego Novillo243ea6a2015-11-23 20:12:21 +0000259
260 /// Number of samples used from the profile.
261 ///
262 /// When a sampling record is used for the first time, the samples from
263 /// that record are added to this accumulator. Coverage is later computed
264 /// based on the total number of samples available in this function and
265 /// its callsites.
266 ///
267 /// Note that this accumulator tracks samples used from a single function
268 /// and all the inlined callsites. Strictly, we should have a map of counters
269 /// keyed by FunctionSamples pointers, but these stats are cleared after
270 /// every function, so we just need to keep a single counter.
271 uint64_t TotalUsedSamples;
Diego Novillo748b3ffe2015-10-28 22:30:25 +0000272};
273
274SampleCoverageTracker CoverageTracker;
Diego Novillo0b6985a2015-11-24 22:38:37 +0000275
276/// Return true if the given callsite is hot wrt to its caller.
277///
278/// Functions that were inlined in the original binary will be represented
279/// in the inline stack in the sample profile. If the profile shows that
280/// the original inline decision was "good" (i.e., the callsite is executed
281/// frequently), then we will recreate the inline decision and apply the
282/// profile from the inlined callsite.
283///
284/// To decide whether an inlined callsite is hot, we compute the fraction
285/// of samples used by the callsite with respect to the total number of samples
286/// collected in the caller.
287///
288/// If that fraction is larger than the default given by
289/// SampleProfileHotThreshold, the callsite will be inlined again.
290bool callsiteIsHot(const FunctionSamples *CallerFS,
291 const FunctionSamples *CallsiteFS) {
292 if (!CallsiteFS)
293 return false; // The callsite was not inlined in the original binary.
294
295 uint64_t ParentTotalSamples = CallerFS->getTotalSamples();
296 if (ParentTotalSamples == 0)
297 return false; // Avoid division by zero.
298
299 uint64_t CallsiteTotalSamples = CallsiteFS->getTotalSamples();
300 if (CallsiteTotalSamples == 0)
301 return false; // Callsite is trivially cold.
302
Diego Novillob5792402015-11-27 23:14:49 +0000303 double PercentSamples =
304 (double)CallsiteTotalSamples / (double)ParentTotalSamples * 100.0;
Diego Novillo0b6985a2015-11-24 22:38:37 +0000305 return PercentSamples >= SampleProfileHotThreshold;
306}
Diego Novillo748b3ffe2015-10-28 22:30:25 +0000307}
308
309/// Mark as used the sample record for the given function samples at
310/// (LineOffset, Discriminator).
Diego Novillof9ed08e2015-10-31 21:53:58 +0000311///
312/// \returns true if this is the first time we mark the given record.
Diego Novillo243ea6a2015-11-23 20:12:21 +0000313bool SampleCoverageTracker::markSamplesUsed(const FunctionSamples *FS,
Diego Novillo748b3ffe2015-10-28 22:30:25 +0000314 uint32_t LineOffset,
Diego Novillo243ea6a2015-11-23 20:12:21 +0000315 uint32_t Discriminator,
316 uint64_t Samples) {
Diego Novillof9ed08e2015-10-31 21:53:58 +0000317 LineLocation Loc(LineOffset, Discriminator);
Diego Novillo243ea6a2015-11-23 20:12:21 +0000318 unsigned &Count = SampleCoverage[FS][Loc];
319 bool FirstTime = (++Count == 1);
320 if (FirstTime)
321 TotalUsedSamples += Samples;
322 return FirstTime;
Diego Novillo748b3ffe2015-10-28 22:30:25 +0000323}
324
325/// Return the number of sample records that were applied from this profile.
Diego Novillo0b6985a2015-11-24 22:38:37 +0000326///
327/// This count does not include records from cold inlined callsites.
Diego Novillo748b3ffe2015-10-28 22:30:25 +0000328unsigned
Diego Novillo243ea6a2015-11-23 20:12:21 +0000329SampleCoverageTracker::countUsedRecords(const FunctionSamples *FS) const {
330 auto I = SampleCoverage.find(FS);
Diego Novillo5fb49e52015-11-20 21:46:38 +0000331
Diego Novillo243ea6a2015-11-23 20:12:21 +0000332 // The size of the coverage map for FS represents the number of records
Diego Novillo5fb49e52015-11-20 21:46:38 +0000333 // that were marked used at least once.
Diego Novillof9ed08e2015-10-31 21:53:58 +0000334 unsigned Count = (I != SampleCoverage.end()) ? I->second.size() : 0;
Diego Novillo5fb49e52015-11-20 21:46:38 +0000335
336 // If there are inlined callsites in this function, count the samples found
337 // in the respective bodies. However, do not bother counting callees with 0
338 // total samples, these are callees that were never invoked at runtime.
Diego Novillo243ea6a2015-11-23 20:12:21 +0000339 for (const auto &I : FS->getCallsiteSamples()) {
Diego Novillo5fb49e52015-11-20 21:46:38 +0000340 const FunctionSamples *CalleeSamples = &I.second;
Diego Novillo0b6985a2015-11-24 22:38:37 +0000341 if (callsiteIsHot(FS, CalleeSamples))
Diego Novillo243ea6a2015-11-23 20:12:21 +0000342 Count += countUsedRecords(CalleeSamples);
Diego Novillo5fb49e52015-11-20 21:46:38 +0000343 }
344
Diego Novillof9ed08e2015-10-31 21:53:58 +0000345 return Count;
346}
347
348/// Return the number of sample records in the body of this profile.
349///
Diego Novillo0b6985a2015-11-24 22:38:37 +0000350/// This count does not include records from cold inlined callsites.
Diego Novillof9ed08e2015-10-31 21:53:58 +0000351unsigned
Diego Novillo243ea6a2015-11-23 20:12:21 +0000352SampleCoverageTracker::countBodyRecords(const FunctionSamples *FS) const {
353 unsigned Count = FS->getBodySamples().size();
Diego Novillo5fb49e52015-11-20 21:46:38 +0000354
Diego Novillo0b6985a2015-11-24 22:38:37 +0000355 // Only count records in hot callsites.
Diego Novillo243ea6a2015-11-23 20:12:21 +0000356 for (const auto &I : FS->getCallsiteSamples()) {
Diego Novillo5fb49e52015-11-20 21:46:38 +0000357 const FunctionSamples *CalleeSamples = &I.second;
Diego Novillo0b6985a2015-11-24 22:38:37 +0000358 if (callsiteIsHot(FS, CalleeSamples))
Diego Novillo243ea6a2015-11-23 20:12:21 +0000359 Count += countBodyRecords(CalleeSamples);
Diego Novillo5fb49e52015-11-20 21:46:38 +0000360 }
361
Diego Novillof9ed08e2015-10-31 21:53:58 +0000362 return Count;
Diego Novillo748b3ffe2015-10-28 22:30:25 +0000363}
364
Diego Novillo243ea6a2015-11-23 20:12:21 +0000365/// Return the number of samples collected in the body of this profile.
366///
Diego Novillo0b6985a2015-11-24 22:38:37 +0000367/// This count does not include samples from cold inlined callsites.
Diego Novillo243ea6a2015-11-23 20:12:21 +0000368uint64_t
369SampleCoverageTracker::countBodySamples(const FunctionSamples *FS) const {
370 uint64_t Total = 0;
371 for (const auto &I : FS->getBodySamples())
372 Total += I.second.getSamples();
373
Diego Novillo0b6985a2015-11-24 22:38:37 +0000374 // Only count samples in hot callsites.
Diego Novillo243ea6a2015-11-23 20:12:21 +0000375 for (const auto &I : FS->getCallsiteSamples()) {
376 const FunctionSamples *CalleeSamples = &I.second;
Diego Novillo0b6985a2015-11-24 22:38:37 +0000377 if (callsiteIsHot(FS, CalleeSamples))
Diego Novillo243ea6a2015-11-23 20:12:21 +0000378 Total += countBodySamples(CalleeSamples);
379 }
380
381 return Total;
382}
383
Diego Novillo748b3ffe2015-10-28 22:30:25 +0000384/// Return the fraction of sample records used in this profile.
385///
386/// The returned value is an unsigned integer in the range 0-100 indicating
387/// the percentage of sample records that were used while applying this
388/// profile to the associated function.
Diego Novillof9ed08e2015-10-31 21:53:58 +0000389unsigned SampleCoverageTracker::computeCoverage(unsigned Used,
390 unsigned Total) const {
391 assert(Used <= Total &&
Diego Novillo748b3ffe2015-10-28 22:30:25 +0000392 "number of used records cannot exceed the total number of records");
Diego Novillof9ed08e2015-10-31 21:53:58 +0000393 return Total > 0 ? Used * 100 / Total : 100;
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000394}
Diego Novillo8d6568b2013-11-13 12:22:21 +0000395
Diego Novilloa8a3bd22015-10-28 17:40:22 +0000396/// Clear all the per-function data used to load samples and propagate weights.
397void SampleProfileLoader::clearFunctionData() {
398 BlockWeights.clear();
399 EdgeWeights.clear();
400 VisitedBlocks.clear();
401 VisitedEdges.clear();
402 EquivalenceClass.clear();
403 DT = nullptr;
404 PDT = nullptr;
405 LI = nullptr;
406 Predecessors.clear();
407 Successors.clear();
Diego Novillo1ca881c2015-11-23 16:30:17 +0000408 CoverageTracker.clear();
Diego Novilloa8a3bd22015-10-28 17:40:22 +0000409}
410
Dehao Chen10042412015-10-21 01:22:27 +0000411/// \brief Returns the offset of lineno \p L to head_lineno \p H
412///
413/// \param L Lineno
414/// \param H Header lineno of the function
415///
416/// \returns offset to the header lineno. 16 bits are used to represent offset.
417/// We assume that a single function will not exceed 65535 LOC.
418unsigned SampleProfileLoader::getOffset(unsigned L, unsigned H) const {
419 return (L - H) & 0xffff;
420}
421
Diego Novillo0accb3d2014-01-10 23:23:46 +0000422/// \brief Print the weight of edge \p E on stream \p OS.
423///
424/// \param OS Stream to emit the output to.
425/// \param E Edge to print.
Diego Novillode1ab262014-09-09 12:40:50 +0000426void SampleProfileLoader::printEdgeWeight(raw_ostream &OS, Edge E) {
Diego Novillo0accb3d2014-01-10 23:23:46 +0000427 OS << "weight[" << E.first->getName() << "->" << E.second->getName()
428 << "]: " << EdgeWeights[E] << "\n";
429}
430
431/// \brief Print the equivalence class of block \p BB on stream \p OS.
432///
433/// \param OS Stream to emit the output to.
434/// \param BB Block to print.
Diego Novillode1ab262014-09-09 12:40:50 +0000435void SampleProfileLoader::printBlockEquivalence(raw_ostream &OS,
Dehao Chen8e7df832015-09-29 18:28:15 +0000436 const BasicBlock *BB) {
437 const BasicBlock *Equiv = EquivalenceClass[BB];
Diego Novillo0accb3d2014-01-10 23:23:46 +0000438 OS << "equivalence[" << BB->getName()
439 << "]: " << ((Equiv) ? EquivalenceClass[BB]->getName() : "NONE") << "\n";
440}
441
442/// \brief Print the weight of block \p BB on stream \p OS.
443///
444/// \param OS Stream to emit the output to.
445/// \param BB Block to print.
Dehao Chen8e7df832015-09-29 18:28:15 +0000446void SampleProfileLoader::printBlockWeight(raw_ostream &OS,
447 const BasicBlock *BB) const {
448 const auto &I = BlockWeights.find(BB);
Diego Novillo38be3332015-10-15 16:36:21 +0000449 uint64_t W = (I == BlockWeights.end() ? 0 : I->second);
Dehao Chen8e7df832015-09-29 18:28:15 +0000450 OS << "weight[" << BB->getName() << "]: " << W << "\n";
Diego Novillo0accb3d2014-01-10 23:23:46 +0000451}
452
Diego Novillo0accb3d2014-01-10 23:23:46 +0000453/// \brief Get the weight for an instruction.
454///
455/// The "weight" of an instruction \p Inst is the number of samples
456/// collected on that instruction at runtime. To retrieve it, we
457/// need to compute the line number of \p Inst relative to the start of its
458/// function. We use HeaderLineno to compute the offset. We then
459/// look up the samples collected for \p Inst using BodySamples.
460///
461/// \param Inst Instruction to query.
462///
Dehao Chen8e7df832015-09-29 18:28:15 +0000463/// \returns the weight of \p Inst.
Diego Novillo38be3332015-10-15 16:36:21 +0000464ErrorOr<uint64_t>
Dehao Chen8e7df832015-09-29 18:28:15 +0000465SampleProfileLoader::getInstWeight(const Instruction &Inst) const {
Benjamin Kramer4fed9282016-05-27 12:30:51 +0000466 const DebugLoc &DLoc = Inst.getDebugLoc();
Duncan P. N. Exon Smithec819c02015-03-30 19:49:49 +0000467 if (!DLoc)
Dehao Chen8e7df832015-09-29 18:28:15 +0000468 return std::error_code();
Duncan P. N. Exon Smith41a15462015-03-20 00:56:55 +0000469
Dehao Chen67226882015-09-30 00:42:46 +0000470 const FunctionSamples *FS = findFunctionSamples(Inst);
471 if (!FS)
472 return std::error_code();
Dehao Chen41dc5a62015-10-09 16:50:16 +0000473
Dehao Chena8bae822016-04-20 23:36:23 +0000474 // Ignore all dbg_value intrinsics.
475 const IntrinsicInst *II = dyn_cast<IntrinsicInst>(&Inst);
476 if (II && II->getIntrinsicID() == Intrinsic::dbg_value)
477 return std::error_code();
478
Dehao Chen41dc5a62015-10-09 16:50:16 +0000479 const DILocation *DIL = DLoc;
480 unsigned Lineno = DLoc.getLine();
481 unsigned HeaderLineno = DIL->getScope()->getSubprogram()->getLine();
Dehao Chen41dc5a62015-10-09 16:50:16 +0000482
Diego Novillo748b3ffe2015-10-28 22:30:25 +0000483 uint32_t LineOffset = getOffset(Lineno, HeaderLineno);
484 uint32_t Discriminator = DIL->getDiscriminator();
485 ErrorOr<uint64_t> R = FS->findSamplesAt(LineOffset, Discriminator);
486 if (R) {
Diego Novillof9ed08e2015-10-31 21:53:58 +0000487 bool FirstMark =
Diego Novillo243ea6a2015-11-23 20:12:21 +0000488 CoverageTracker.markSamplesUsed(FS, LineOffset, Discriminator, R.get());
Diego Novillof9ed08e2015-10-31 21:53:58 +0000489 if (FirstMark) {
490 const Function *F = Inst.getParent()->getParent();
491 LLVMContext &Ctx = F->getContext();
Diego Novillodf544a02015-11-20 15:39:42 +0000492 emitOptimizationRemark(
493 Ctx, DEBUG_TYPE, *F, DLoc,
494 Twine("Applied ") + Twine(*R) + " samples from profile (offset: " +
495 Twine(LineOffset) +
496 ((Discriminator) ? Twine(".") + Twine(Discriminator) : "") + ")");
Diego Novillof9ed08e2015-10-31 21:53:58 +0000497 }
Dehao Chen8e7df832015-09-29 18:28:15 +0000498 DEBUG(dbgs() << " " << Lineno << "." << DIL->getDiscriminator() << ":"
499 << Inst << " (line offset: " << Lineno - HeaderLineno << "."
500 << DIL->getDiscriminator() << " - weight: " << R.get()
501 << ")\n");
Dehao Chena8bae822016-04-20 23:36:23 +0000502 } else {
503 // If a call instruction is inlined in profile, but not inlined here,
504 // it means that the inlined callsite has no sample, thus the call
505 // instruction should have 0 count.
506 const CallInst *CI = dyn_cast<CallInst>(&Inst);
507 if (CI && findCalleeFunctionSamples(*CI))
508 R = 0;
Diego Novillo748b3ffe2015-10-28 22:30:25 +0000509 }
Dehao Chen8e7df832015-09-29 18:28:15 +0000510 return R;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000511}
512
513/// \brief Compute the weight of a basic block.
514///
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000515/// The weight of basic block \p BB is the maximum weight of all the
Dehao Chen8e7df832015-09-29 18:28:15 +0000516/// instructions in BB.
Diego Novillo0accb3d2014-01-10 23:23:46 +0000517///
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000518/// \param BB The basic block to query.
Diego Novillo0accb3d2014-01-10 23:23:46 +0000519///
Dehao Chen8e7df832015-09-29 18:28:15 +0000520/// \returns the weight for \p BB.
Diego Novillo38be3332015-10-15 16:36:21 +0000521ErrorOr<uint64_t>
Dehao Chen8e7df832015-09-29 18:28:15 +0000522SampleProfileLoader::getBlockWeight(const BasicBlock *BB) const {
Dehao Chen5d6d4842016-04-26 04:59:11 +0000523 DenseMap<uint64_t, uint64_t> CM;
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000524 for (auto &I : BB->getInstList()) {
Diego Novillo38be3332015-10-15 16:36:21 +0000525 const ErrorOr<uint64_t> &R = getInstWeight(I);
Dehao Chen5d6d4842016-04-26 04:59:11 +0000526 if (R) CM[R.get()]++;
527 }
528 if (CM.size() == 0) return std::error_code();
529 uint64_t W = 0, C = 0;
530 for (const auto &C_W : CM) {
531 if (C_W.second == W) {
532 C = std::max(C, C_W.first);
533 } else if (C_W.second > W) {
534 C = C_W.first;
535 W = C_W.second;
Dehao Chen8e7df832015-09-29 18:28:15 +0000536 }
Diego Novillo0accb3d2014-01-10 23:23:46 +0000537 }
Dehao Chen5d6d4842016-04-26 04:59:11 +0000538 return C;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000539}
540
541/// \brief Compute and store the weights of every basic block.
542///
543/// This populates the BlockWeights map by computing
544/// the weights of every basic block in the CFG.
545///
546/// \param F The function to query.
Diego Novillode1ab262014-09-09 12:40:50 +0000547bool SampleProfileLoader::computeBlockWeights(Function &F) {
Diego Novillo0accb3d2014-01-10 23:23:46 +0000548 bool Changed = false;
549 DEBUG(dbgs() << "Block weights\n");
Dehao Chen8e7df832015-09-29 18:28:15 +0000550 for (const auto &BB : F) {
Diego Novillo38be3332015-10-15 16:36:21 +0000551 ErrorOr<uint64_t> Weight = getBlockWeight(&BB);
Dehao Chen8e7df832015-09-29 18:28:15 +0000552 if (Weight) {
553 BlockWeights[&BB] = Weight.get();
Dehao Chen7c41dd62015-10-01 00:26:56 +0000554 VisitedBlocks.insert(&BB);
Dehao Chen8e7df832015-09-29 18:28:15 +0000555 Changed = true;
556 }
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000557 DEBUG(printBlockWeight(dbgs(), &BB));
Diego Novillo0accb3d2014-01-10 23:23:46 +0000558 }
559
560 return Changed;
561}
562
Dehao Chen67226882015-09-30 00:42:46 +0000563/// \brief Get the FunctionSamples for a call instruction.
564///
565/// The FunctionSamples of a call instruction \p Inst is the inlined
566/// instance in which that call instruction is calling to. It contains
567/// all samples that resides in the inlined instance. We first find the
568/// inlined instance in which the call instruction is from, then we
569/// traverse its children to find the callsite with the matching
570/// location and callee function name.
571///
572/// \param Inst Call instruction to query.
573///
574/// \returns The FunctionSamples pointer to the inlined instance.
575const FunctionSamples *
576SampleProfileLoader::findCalleeFunctionSamples(const CallInst &Inst) const {
577 const DILocation *DIL = Inst.getDebugLoc();
578 if (!DIL) {
579 return nullptr;
580 }
581 DISubprogram *SP = DIL->getScope()->getSubprogram();
Dehao Chen10042412015-10-21 01:22:27 +0000582 if (!SP)
Dehao Chen67226882015-09-30 00:42:46 +0000583 return nullptr;
584
Dehao Chen67226882015-09-30 00:42:46 +0000585 const FunctionSamples *FS = findFunctionSamples(Inst);
586 if (FS == nullptr)
587 return nullptr;
588
Dehao Chen57d1dda2016-03-03 18:09:32 +0000589 return FS->findFunctionSamplesAt(LineLocation(
590 getOffset(DIL->getLine(), SP->getLine()), DIL->getDiscriminator()));
Dehao Chen67226882015-09-30 00:42:46 +0000591}
592
593/// \brief Get the FunctionSamples for an instruction.
594///
595/// The FunctionSamples of an instruction \p Inst is the inlined instance
596/// in which that instruction is coming from. We traverse the inline stack
597/// of that instruction, and match it with the tree nodes in the profile.
598///
599/// \param Inst Instruction to query.
600///
601/// \returns the FunctionSamples pointer to the inlined instance.
602const FunctionSamples *
603SampleProfileLoader::findFunctionSamples(const Instruction &Inst) const {
Dehao Chen57d1dda2016-03-03 18:09:32 +0000604 SmallVector<LineLocation, 10> S;
Dehao Chen67226882015-09-30 00:42:46 +0000605 const DILocation *DIL = Inst.getDebugLoc();
606 if (!DIL) {
607 return Samples;
608 }
Dehao Chen21aefae2016-04-29 17:19:10 +0000609 for (DIL = DIL->getInlinedAt(); DIL; DIL = DIL->getInlinedAt()) {
Dehao Chen67226882015-09-30 00:42:46 +0000610 DISubprogram *SP = DIL->getScope()->getSubprogram();
Dehao Chen10042412015-10-21 01:22:27 +0000611 if (!SP)
Dehao Chen67226882015-09-30 00:42:46 +0000612 return nullptr;
Dehao Chen21aefae2016-04-29 17:19:10 +0000613 S.push_back(LineLocation(getOffset(DIL->getLine(), SP->getLine()),
614 DIL->getDiscriminator()));
Dehao Chen67226882015-09-30 00:42:46 +0000615 }
616 if (S.size() == 0)
617 return Samples;
618 const FunctionSamples *FS = Samples;
619 for (int i = S.size() - 1; i >= 0 && FS != nullptr; i--) {
620 FS = FS->findFunctionSamplesAt(S[i]);
621 }
622 return FS;
623}
624
Diego Novillo84f06cc2015-11-27 23:14:51 +0000625/// \brief Emit an inline hint if \p F is globally hot or cold.
626///
627/// If \p F consumes a significant fraction of samples (indicated by
628/// SampleProfileGlobalHotThreshold), apply the InlineHint attribute for the
629/// inliner to consider the function hot.
630///
631/// If \p F consumes a small fraction of samples (indicated by
632/// SampleProfileGlobalColdThreshold), apply the Cold attribute for the inliner
633/// to consider the function cold.
634///
635/// FIXME - This setting of inline hints is sub-optimal. Instead of marking a
636/// function globally hot or cold, we should be annotating individual callsites.
637/// This is not currently possible, but work on the inliner will eventually
638/// provide this ability. See http://reviews.llvm.org/D15003 for details and
639/// discussion.
640///
641/// \returns True if either attribute was applied to \p F.
642bool SampleProfileLoader::emitInlineHints(Function &F) {
643 if (TotalCollectedSamples == 0)
644 return false;
645
646 uint64_t FunctionSamples = Samples->getTotalSamples();
647 double SamplesPercent =
648 (double)FunctionSamples / (double)TotalCollectedSamples * 100.0;
649
650 // If the function collected more samples than the hot threshold, mark
651 // it globally hot.
652 if (SamplesPercent >= SampleProfileGlobalHotThreshold) {
653 F.addFnAttr(llvm::Attribute::InlineHint);
Diego Novillo7ff0a172015-11-29 18:23:26 +0000654 std::string Msg;
655 raw_string_ostream S(Msg);
656 S << "Applied inline hint to globally hot function '" << F.getName()
657 << "' with " << format("%.2f", SamplesPercent)
658 << "% of samples (threshold: "
659 << format("%.2f", SampleProfileGlobalHotThreshold.getValue()) << "%)";
660 S.flush();
661 emitOptimizationRemark(F.getContext(), DEBUG_TYPE, F, DebugLoc(), Msg);
Diego Novillo84f06cc2015-11-27 23:14:51 +0000662 return true;
663 }
664
665 // If the function collected fewer samples than the cold threshold, mark
666 // it globally cold.
667 if (SamplesPercent <= SampleProfileGlobalColdThreshold) {
668 F.addFnAttr(llvm::Attribute::Cold);
Diego Novillo7ff0a172015-11-29 18:23:26 +0000669 std::string Msg;
670 raw_string_ostream S(Msg);
671 S << "Applied cold hint to globally cold function '" << F.getName()
672 << "' with " << format("%.2f", SamplesPercent)
673 << "% of samples (threshold: "
674 << format("%.2f", SampleProfileGlobalColdThreshold.getValue()) << "%)";
675 S.flush();
676 emitOptimizationRemark(F.getContext(), DEBUG_TYPE, F, DebugLoc(), Msg);
Diego Novillo84f06cc2015-11-27 23:14:51 +0000677 return true;
678 }
679
680 return false;
681}
682
Dehao Chen67226882015-09-30 00:42:46 +0000683/// \brief Iteratively inline hot callsites of a function.
684///
685/// Iteratively traverse all callsites of the function \p F, and find if
686/// the corresponding inlined instance exists and is hot in profile. If
687/// it is hot enough, inline the callsites and adds new callsites of the
688/// callee into the caller.
689///
690/// TODO: investigate the possibility of not invoking InlineFunction directly.
691///
692/// \param F function to perform iterative inlining.
693///
694/// \returns True if there is any inline happened.
695bool SampleProfileLoader::inlineHotFunctions(Function &F) {
696 bool Changed = false;
Diego Novillo7963ea12015-10-26 18:52:53 +0000697 LLVMContext &Ctx = F.getContext();
Dehao Chen67226882015-09-30 00:42:46 +0000698 while (true) {
699 bool LocalChanged = false;
700 SmallVector<CallInst *, 10> CIS;
701 for (auto &BB : F) {
702 for (auto &I : BB.getInstList()) {
703 CallInst *CI = dyn_cast<CallInst>(&I);
Diego Novillo0b6985a2015-11-24 22:38:37 +0000704 if (CI && callsiteIsHot(Samples, findCalleeFunctionSamples(*CI)))
705 CIS.push_back(CI);
Dehao Chen67226882015-09-30 00:42:46 +0000706 }
707 }
708 for (auto CI : CIS) {
Dehao Chen071bb9d2016-06-20 20:53:40 +0000709 InlineFunctionInfo IFI(nullptr, ACT);
Diego Novillo7963ea12015-10-26 18:52:53 +0000710 Function *CalledFunction = CI->getCalledFunction();
711 DebugLoc DLoc = CI->getDebugLoc();
712 uint64_t NumSamples = findCalleeFunctionSamples(*CI)->getTotalSamples();
713 if (InlineFunction(CI, IFI)) {
Dehao Chen67226882015-09-30 00:42:46 +0000714 LocalChanged = true;
Diego Novillo7963ea12015-10-26 18:52:53 +0000715 emitOptimizationRemark(Ctx, DEBUG_TYPE, F, DLoc,
716 Twine("inlined hot callee '") +
717 CalledFunction->getName() + "' with " +
718 Twine(NumSamples) + " samples into '" +
719 F.getName() + "'");
720 }
Dehao Chen67226882015-09-30 00:42:46 +0000721 }
722 if (LocalChanged) {
723 Changed = true;
724 } else {
725 break;
726 }
727 }
728 return Changed;
729}
730
Diego Novillo0accb3d2014-01-10 23:23:46 +0000731/// \brief Find equivalence classes for the given block.
732///
733/// This finds all the blocks that are guaranteed to execute the same
Eric Christopher572e03a2015-06-19 01:53:21 +0000734/// number of times as \p BB1. To do this, it traverses all the
Diego Novillo0accb3d2014-01-10 23:23:46 +0000735/// descendants of \p BB1 in the dominator or post-dominator tree.
736///
737/// A block BB2 will be in the same equivalence class as \p BB1 if
738/// the following holds:
739///
740/// 1- \p BB1 is a descendant of BB2 in the opposite tree. So, if BB2
741/// is a descendant of \p BB1 in the dominator tree, then BB2 should
742/// dominate BB1 in the post-dominator tree.
743///
744/// 2- Both BB2 and \p BB1 must be in the same loop.
745///
746/// For every block BB2 that meets those two requirements, we set BB2's
747/// equivalence class to \p BB1.
748///
749/// \param BB1 Block to check.
750/// \param Descendants Descendants of \p BB1 in either the dom or pdom tree.
751/// \param DomTree Opposite dominator tree. If \p Descendants is filled
752/// with blocks from \p BB1's dominator tree, then
753/// this is the post-dominator tree, and vice versa.
Diego Novillode1ab262014-09-09 12:40:50 +0000754void SampleProfileLoader::findEquivalencesFor(
Benjamin Kramer8a752e32016-02-13 16:01:12 +0000755 BasicBlock *BB1, ArrayRef<BasicBlock *> Descendants,
Diego Novillo0accb3d2014-01-10 23:23:46 +0000756 DominatorTreeBase<BasicBlock> *DomTree) {
Dehao Chen7c41dd62015-10-01 00:26:56 +0000757 const BasicBlock *EC = EquivalenceClass[BB1];
Diego Novillo38be3332015-10-15 16:36:21 +0000758 uint64_t Weight = BlockWeights[EC];
Dehao Chen8e7df832015-09-29 18:28:15 +0000759 for (const auto *BB2 : Descendants) {
Diego Novillo0accb3d2014-01-10 23:23:46 +0000760 bool IsDomParent = DomTree->dominates(BB2, BB1);
761 bool IsInSameLoop = LI->getLoopFor(BB1) == LI->getLoopFor(BB2);
Dehao Chen7c41dd62015-10-01 00:26:56 +0000762 if (BB1 != BB2 && IsDomParent && IsInSameLoop) {
763 EquivalenceClass[BB2] = EC;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000764
765 // If BB2 is heavier than BB1, make BB2 have the same weight
766 // as BB1.
767 //
768 // Note that we don't worry about the opposite situation here
769 // (when BB2 is lighter than BB1). We will deal with this
770 // during the propagation phase. Right now, we just want to
771 // make sure that BB1 has the largest weight of all the
772 // members of its equivalence set.
Dehao Chen7c41dd62015-10-01 00:26:56 +0000773 Weight = std::max(Weight, BlockWeights[BB2]);
Diego Novillo0accb3d2014-01-10 23:23:46 +0000774 }
775 }
Dehao Chen7c41dd62015-10-01 00:26:56 +0000776 BlockWeights[EC] = Weight;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000777}
778
779/// \brief Find equivalence classes.
780///
781/// Since samples may be missing from blocks, we can fill in the gaps by setting
782/// the weights of all the blocks in the same equivalence class to the same
783/// weight. To compute the concept of equivalence, we use dominance and loop
784/// information. Two blocks B1 and B2 are in the same equivalence class if B1
785/// dominates B2, B2 post-dominates B1 and both are in the same loop.
786///
787/// \param F The function to query.
Diego Novillode1ab262014-09-09 12:40:50 +0000788void SampleProfileLoader::findEquivalenceClasses(Function &F) {
Diego Novillo0accb3d2014-01-10 23:23:46 +0000789 SmallVector<BasicBlock *, 8> DominatedBBs;
790 DEBUG(dbgs() << "\nBlock equivalence classes\n");
791 // Find equivalence sets based on dominance and post-dominance information.
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000792 for (auto &BB : F) {
793 BasicBlock *BB1 = &BB;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000794
795 // Compute BB1's equivalence class once.
796 if (EquivalenceClass.count(BB1)) {
797 DEBUG(printBlockEquivalence(dbgs(), BB1));
798 continue;
799 }
800
801 // By default, blocks are in their own equivalence class.
802 EquivalenceClass[BB1] = BB1;
803
804 // Traverse all the blocks dominated by BB1. We are looking for
805 // every basic block BB2 such that:
806 //
807 // 1- BB1 dominates BB2.
808 // 2- BB2 post-dominates BB1.
809 // 3- BB1 and BB2 are in the same loop nest.
810 //
811 // If all those conditions hold, it means that BB2 is executed
812 // as many times as BB1, so they are placed in the same equivalence
813 // class by making BB2's equivalence class be BB1.
814 DominatedBBs.clear();
815 DT->getDescendants(BB1, DominatedBBs);
Diego Novillo7732ae42015-08-26 20:00:27 +0000816 findEquivalencesFor(BB1, DominatedBBs, PDT.get());
Diego Novillo0accb3d2014-01-10 23:23:46 +0000817
Diego Novillo0accb3d2014-01-10 23:23:46 +0000818 DEBUG(printBlockEquivalence(dbgs(), BB1));
819 }
820
821 // Assign weights to equivalence classes.
822 //
823 // All the basic blocks in the same equivalence class will execute
824 // the same number of times. Since we know that the head block in
825 // each equivalence class has the largest weight, assign that weight
826 // to all the blocks in that equivalence class.
827 DEBUG(dbgs() << "\nAssign the same weight to all blocks in the same class\n");
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000828 for (auto &BI : F) {
Dehao Chen8e7df832015-09-29 18:28:15 +0000829 const BasicBlock *BB = &BI;
830 const BasicBlock *EquivBB = EquivalenceClass[BB];
Diego Novillo0accb3d2014-01-10 23:23:46 +0000831 if (BB != EquivBB)
832 BlockWeights[BB] = BlockWeights[EquivBB];
833 DEBUG(printBlockWeight(dbgs(), BB));
834 }
835}
836
837/// \brief Visit the given edge to decide if it has a valid weight.
838///
839/// If \p E has not been visited before, we copy to \p UnknownEdge
840/// and increment the count of unknown edges.
841///
842/// \param E Edge to visit.
843/// \param NumUnknownEdges Current number of unknown edges.
844/// \param UnknownEdge Set if E has not been visited before.
845///
846/// \returns E's weight, if known. Otherwise, return 0.
Diego Novillo38be3332015-10-15 16:36:21 +0000847uint64_t SampleProfileLoader::visitEdge(Edge E, unsigned *NumUnknownEdges,
Diego Novillode1ab262014-09-09 12:40:50 +0000848 Edge *UnknownEdge) {
Diego Novillo0accb3d2014-01-10 23:23:46 +0000849 if (!VisitedEdges.count(E)) {
850 (*NumUnknownEdges)++;
851 *UnknownEdge = E;
852 return 0;
853 }
854
855 return EdgeWeights[E];
856}
857
858/// \brief Propagate weights through incoming/outgoing edges.
859///
860/// If the weight of a basic block is known, and there is only one edge
861/// with an unknown weight, we can calculate the weight of that edge.
862///
863/// Similarly, if all the edges have a known count, we can calculate the
864/// count of the basic block, if needed.
865///
866/// \param F Function to process.
867///
868/// \returns True if new weights were assigned to edges or blocks.
Diego Novillode1ab262014-09-09 12:40:50 +0000869bool SampleProfileLoader::propagateThroughEdges(Function &F) {
Diego Novillo0accb3d2014-01-10 23:23:46 +0000870 bool Changed = false;
871 DEBUG(dbgs() << "\nPropagation through edges\n");
Dehao Chen7c41dd62015-10-01 00:26:56 +0000872 for (const auto &BI : F) {
873 const BasicBlock *BB = &BI;
874 const BasicBlock *EC = EquivalenceClass[BB];
Diego Novillo0accb3d2014-01-10 23:23:46 +0000875
876 // Visit all the predecessor and successor edges to determine
877 // which ones have a weight assigned already. Note that it doesn't
878 // matter that we only keep track of a single unknown edge. The
879 // only case we are interested in handling is when only a single
880 // edge is unknown (see setEdgeOrBlockWeight).
881 for (unsigned i = 0; i < 2; i++) {
Diego Novillo38be3332015-10-15 16:36:21 +0000882 uint64_t TotalWeight = 0;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000883 unsigned NumUnknownEdges = 0;
884 Edge UnknownEdge, SelfReferentialEdge;
885
886 if (i == 0) {
887 // First, visit all predecessor edges.
Diego Novillob368b7d2014-10-22 16:51:50 +0000888 for (auto *Pred : Predecessors[BB]) {
889 Edge E = std::make_pair(Pred, BB);
Diego Novillo0accb3d2014-01-10 23:23:46 +0000890 TotalWeight += visitEdge(E, &NumUnknownEdges, &UnknownEdge);
891 if (E.first == E.second)
892 SelfReferentialEdge = E;
893 }
894 } else {
895 // On the second round, visit all successor edges.
Diego Novillob368b7d2014-10-22 16:51:50 +0000896 for (auto *Succ : Successors[BB]) {
897 Edge E = std::make_pair(BB, Succ);
Diego Novillo0accb3d2014-01-10 23:23:46 +0000898 TotalWeight += visitEdge(E, &NumUnknownEdges, &UnknownEdge);
899 }
900 }
901
902 // After visiting all the edges, there are three cases that we
903 // can handle immediately:
904 //
905 // - All the edge weights are known (i.e., NumUnknownEdges == 0).
906 // In this case, we simply check that the sum of all the edges
907 // is the same as BB's weight. If not, we change BB's weight
908 // to match. Additionally, if BB had not been visited before,
909 // we mark it visited.
910 //
911 // - Only one edge is unknown and BB has already been visited.
912 // In this case, we can compute the weight of the edge by
913 // subtracting the total block weight from all the known
914 // edge weights. If the edges weight more than BB, then the
915 // edge of the last remaining edge is set to zero.
916 //
917 // - There exists a self-referential edge and the weight of BB is
918 // known. In this case, this edge can be based on BB's weight.
919 // We add up all the other known edges and set the weight on
920 // the self-referential edge as we did in the previous case.
921 //
922 // In any other case, we must continue iterating. Eventually,
923 // all edges will get a weight, or iteration will stop when
924 // it reaches SampleProfileMaxPropagateIterations.
925 if (NumUnknownEdges <= 1) {
Diego Novillo38be3332015-10-15 16:36:21 +0000926 uint64_t &BBWeight = BlockWeights[EC];
Diego Novillo0accb3d2014-01-10 23:23:46 +0000927 if (NumUnknownEdges == 0) {
928 // If we already know the weight of all edges, the weight of the
929 // basic block can be computed. It should be no larger than the sum
930 // of all edge weights.
931 if (TotalWeight > BBWeight) {
932 BBWeight = TotalWeight;
933 Changed = true;
934 DEBUG(dbgs() << "All edge weights for " << BB->getName()
935 << " known. Set weight for block: ";
936 printBlockWeight(dbgs(), BB););
937 }
Dehao Chen7c41dd62015-10-01 00:26:56 +0000938 if (VisitedBlocks.insert(EC).second)
Diego Novillo0accb3d2014-01-10 23:23:46 +0000939 Changed = true;
Dehao Chen7c41dd62015-10-01 00:26:56 +0000940 } else if (NumUnknownEdges == 1 && VisitedBlocks.count(EC)) {
Diego Novillo0accb3d2014-01-10 23:23:46 +0000941 // If there is a single unknown edge and the block has been
942 // visited, then we can compute E's weight.
943 if (BBWeight >= TotalWeight)
944 EdgeWeights[UnknownEdge] = BBWeight - TotalWeight;
945 else
946 EdgeWeights[UnknownEdge] = 0;
947 VisitedEdges.insert(UnknownEdge);
948 Changed = true;
949 DEBUG(dbgs() << "Set weight for edge: ";
950 printEdgeWeight(dbgs(), UnknownEdge));
951 }
Dehao Chen7c41dd62015-10-01 00:26:56 +0000952 } else if (SelfReferentialEdge.first && VisitedBlocks.count(EC)) {
Diego Novillo38be3332015-10-15 16:36:21 +0000953 uint64_t &BBWeight = BlockWeights[BB];
Diego Novillo0accb3d2014-01-10 23:23:46 +0000954 // We have a self-referential edge and the weight of BB is known.
955 if (BBWeight >= TotalWeight)
956 EdgeWeights[SelfReferentialEdge] = BBWeight - TotalWeight;
957 else
958 EdgeWeights[SelfReferentialEdge] = 0;
959 VisitedEdges.insert(SelfReferentialEdge);
960 Changed = true;
961 DEBUG(dbgs() << "Set self-referential edge weight to: ";
962 printEdgeWeight(dbgs(), SelfReferentialEdge));
963 }
964 }
965 }
966
967 return Changed;
968}
969
970/// \brief Build in/out edge lists for each basic block in the CFG.
971///
972/// We are interested in unique edges. If a block B1 has multiple
973/// edges to another block B2, we only add a single B1->B2 edge.
Diego Novillode1ab262014-09-09 12:40:50 +0000974void SampleProfileLoader::buildEdges(Function &F) {
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000975 for (auto &BI : F) {
976 BasicBlock *B1 = &BI;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000977
978 // Add predecessors for B1.
979 SmallPtrSet<BasicBlock *, 16> Visited;
980 if (!Predecessors[B1].empty())
981 llvm_unreachable("Found a stale predecessors list in a basic block.");
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000982 for (pred_iterator PI = pred_begin(B1), PE = pred_end(B1); PI != PE; ++PI) {
983 BasicBlock *B2 = *PI;
David Blaikie70573dc2014-11-19 07:49:26 +0000984 if (Visited.insert(B2).second)
Diego Novillo0accb3d2014-01-10 23:23:46 +0000985 Predecessors[B1].push_back(B2);
986 }
987
988 // Add successors for B1.
989 Visited.clear();
990 if (!Successors[B1].empty())
991 llvm_unreachable("Found a stale successors list in a basic block.");
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000992 for (succ_iterator SI = succ_begin(B1), SE = succ_end(B1); SI != SE; ++SI) {
993 BasicBlock *B2 = *SI;
David Blaikie70573dc2014-11-19 07:49:26 +0000994 if (Visited.insert(B2).second)
Diego Novillo0accb3d2014-01-10 23:23:46 +0000995 Successors[B1].push_back(B2);
996 }
997 }
998}
999
1000/// \brief Propagate weights into edges
1001///
Diego Novillo19e7b7e2014-10-22 18:39:50 +00001002/// The following rules are applied to every block BB in the CFG:
Diego Novillo0accb3d2014-01-10 23:23:46 +00001003///
Diego Novillo19e7b7e2014-10-22 18:39:50 +00001004/// - If BB has a single predecessor/successor, then the weight
Diego Novillo0accb3d2014-01-10 23:23:46 +00001005/// of that edge is the weight of the block.
1006///
1007/// - If all incoming or outgoing edges are known except one, and the
1008/// weight of the block is already known, the weight of the unknown
1009/// edge will be the weight of the block minus the sum of all the known
Diego Novillo19e7b7e2014-10-22 18:39:50 +00001010/// edges. If the sum of all the known edges is larger than BB's weight,
Diego Novillo0accb3d2014-01-10 23:23:46 +00001011/// we set the unknown edge weight to zero.
1012///
1013/// - If there is a self-referential edge, and the weight of the block is
1014/// known, the weight for that edge is set to the weight of the block
1015/// minus the weight of the other incoming edges to that block (if
1016/// known).
Diego Novillode1ab262014-09-09 12:40:50 +00001017void SampleProfileLoader::propagateWeights(Function &F) {
Diego Novillo0accb3d2014-01-10 23:23:46 +00001018 bool Changed = true;
Diego Novillo38be3332015-10-15 16:36:21 +00001019 unsigned I = 0;
Diego Novillo0accb3d2014-01-10 23:23:46 +00001020
Diego Novilloffc84e32015-05-13 17:04:29 +00001021 // Add an entry count to the function using the samples gathered
1022 // at the function entry.
1023 F.setEntryCount(Samples->getHeadSamples());
1024
Diego Novillo0accb3d2014-01-10 23:23:46 +00001025 // Before propagation starts, build, for each block, a list of
1026 // unique predecessors and successors. This is necessary to handle
1027 // identical edges in multiway branches. Since we visit all blocks and all
1028 // edges of the CFG, it is cleaner to build these lists once at the start
1029 // of the pass.
1030 buildEdges(F);
1031
1032 // Propagate until we converge or we go past the iteration limit.
Diego Novillo38be3332015-10-15 16:36:21 +00001033 while (Changed && I++ < SampleProfileMaxPropagateIterations) {
Diego Novillo0accb3d2014-01-10 23:23:46 +00001034 Changed = propagateThroughEdges(F);
1035 }
1036
1037 // Generate MD_prof metadata for every branch instruction using the
1038 // edge weights computed during propagation.
1039 DEBUG(dbgs() << "\nPropagation complete. Setting branch weights\n");
Diego Novillo7963ea12015-10-26 18:52:53 +00001040 LLVMContext &Ctx = F.getContext();
1041 MDBuilder MDB(Ctx);
Diego Novillo19e7b7e2014-10-22 18:39:50 +00001042 for (auto &BI : F) {
1043 BasicBlock *BB = &BI;
1044 TerminatorInst *TI = BB->getTerminator();
Diego Novillo0accb3d2014-01-10 23:23:46 +00001045 if (TI->getNumSuccessors() == 1)
1046 continue;
1047 if (!isa<BranchInst>(TI) && !isa<SwitchInst>(TI))
1048 continue;
1049
1050 DEBUG(dbgs() << "\nGetting weights for branch at line "
Diego Novillo92aa8c22014-03-10 22:41:28 +00001051 << TI->getDebugLoc().getLine() << ".\n");
Diego Novillo38be3332015-10-15 16:36:21 +00001052 SmallVector<uint32_t, 4> Weights;
Diego Novillo7963ea12015-10-26 18:52:53 +00001053 uint32_t MaxWeight = 0;
Diego Novillo7963ea12015-10-26 18:52:53 +00001054 DebugLoc MaxDestLoc;
Diego Novillo0accb3d2014-01-10 23:23:46 +00001055 for (unsigned I = 0; I < TI->getNumSuccessors(); ++I) {
1056 BasicBlock *Succ = TI->getSuccessor(I);
Diego Novillo19e7b7e2014-10-22 18:39:50 +00001057 Edge E = std::make_pair(BB, Succ);
Diego Novillo38be3332015-10-15 16:36:21 +00001058 uint64_t Weight = EdgeWeights[E];
Diego Novillo0accb3d2014-01-10 23:23:46 +00001059 DEBUG(dbgs() << "\t"; printEdgeWeight(dbgs(), E));
Diego Novillo38be3332015-10-15 16:36:21 +00001060 // Use uint32_t saturated arithmetic to adjust the incoming weights,
1061 // if needed. Sample counts in profiles are 64-bit unsigned values,
1062 // but internally branch weights are expressed as 32-bit values.
1063 if (Weight > std::numeric_limits<uint32_t>::max()) {
1064 DEBUG(dbgs() << " (saturated due to uint32_t overflow)");
1065 Weight = std::numeric_limits<uint32_t>::max();
1066 }
1067 Weights.push_back(static_cast<uint32_t>(Weight));
Diego Novillo7963ea12015-10-26 18:52:53 +00001068 if (Weight != 0) {
1069 if (Weight > MaxWeight) {
1070 MaxWeight = Weight;
Diego Novillo7963ea12015-10-26 18:52:53 +00001071 MaxDestLoc = Succ->getFirstNonPHIOrDbgOrLifetime()->getDebugLoc();
1072 }
1073 }
Diego Novillo0accb3d2014-01-10 23:23:46 +00001074 }
1075
1076 // Only set weights if there is at least one non-zero weight.
1077 // In any other case, let the analyzer set weights.
Diego Novillo7963ea12015-10-26 18:52:53 +00001078 if (MaxWeight > 0) {
Diego Novillo0accb3d2014-01-10 23:23:46 +00001079 DEBUG(dbgs() << "SUCCESS. Found non-zero weights.\n");
1080 TI->setMetadata(llvm::LLVMContext::MD_prof,
1081 MDB.createBranchWeights(Weights));
Diego Novillo7963ea12015-10-26 18:52:53 +00001082 DebugLoc BranchLoc = TI->getDebugLoc();
1083 emitOptimizationRemark(
1084 Ctx, DEBUG_TYPE, F, MaxDestLoc,
1085 Twine("most popular destination for conditional branches at ") +
Diego Novilloc04270d2015-10-27 17:37:00 +00001086 ((BranchLoc) ? Twine(BranchLoc->getFilename() + ":" +
1087 Twine(BranchLoc.getLine()) + ":" +
1088 Twine(BranchLoc.getCol()))
1089 : Twine("<UNKNOWN LOCATION>")));
Diego Novillo0accb3d2014-01-10 23:23:46 +00001090 } else {
1091 DEBUG(dbgs() << "SKIPPED. All branch weights are zero.\n");
1092 }
1093 }
1094}
1095
1096/// \brief Get the line number for the function header.
1097///
1098/// This looks up function \p F in the current compilation unit and
1099/// retrieves the line number where the function is defined. This is
1100/// line 0 for all the samples read from the profile file. Every line
1101/// number is relative to this line.
1102///
1103/// \param F Function object to query.
1104///
Diego Novilloa32aa322014-03-14 21:58:59 +00001105/// \returns the line number where \p F is defined. If it returns 0,
1106/// it means that there is no debug information available for \p F.
Diego Novillode1ab262014-09-09 12:40:50 +00001107unsigned SampleProfileLoader::getFunctionLoc(Function &F) {
Pete Cooperadebb932016-03-11 02:14:16 +00001108 if (DISubprogram *S = F.getSubprogram())
Duncan P. N. Exon Smith537b4a82015-04-14 03:40:37 +00001109 return S->getLine();
Diego Novillo0accb3d2014-01-10 23:23:46 +00001110
Diego Novilloaa555072015-10-27 18:41:46 +00001111 // If the start of \p F is missing, emit a diagnostic to inform the user
Diego Novillo8027b802014-10-22 12:59:00 +00001112 // about the missed opportunity.
David Blaikie61079682014-03-16 01:36:18 +00001113 F.getContext().diagnose(DiagnosticInfoSampleProfile(
Diego Novilloa67c0b42014-10-22 13:36:35 +00001114 "No debug information found in function " + F.getName() +
1115 ": Function profile not used",
1116 DS_Warning));
Diego Novilloa32aa322014-03-14 21:58:59 +00001117 return 0;
Diego Novillo0accb3d2014-01-10 23:23:46 +00001118}
1119
Diego Novillo7732ae42015-08-26 20:00:27 +00001120void SampleProfileLoader::computeDominanceAndLoopInfo(Function &F) {
1121 DT.reset(new DominatorTree);
1122 DT->recalculate(F);
1123
1124 PDT.reset(new DominatorTreeBase<BasicBlock>(true));
1125 PDT->recalculate(F);
1126
1127 LI.reset(new LoopInfo);
1128 LI->analyze(*DT);
1129}
1130
Diego Novillo0accb3d2014-01-10 23:23:46 +00001131/// \brief Generate branch weight metadata for all branches in \p F.
1132///
1133/// Branch weights are computed out of instruction samples using a
1134/// propagation heuristic. Propagation proceeds in 3 phases:
1135///
1136/// 1- Assignment of block weights. All the basic blocks in the function
1137/// are initial assigned the same weight as their most frequently
1138/// executed instruction.
1139///
1140/// 2- Creation of equivalence classes. Since samples may be missing from
1141/// blocks, we can fill in the gaps by setting the weights of all the
1142/// blocks in the same equivalence class to the same weight. To compute
1143/// the concept of equivalence, we use dominance and loop information.
1144/// Two blocks B1 and B2 are in the same equivalence class if B1
1145/// dominates B2, B2 post-dominates B1 and both are in the same loop.
1146///
1147/// 3- Propagation of block weights into edges. This uses a simple
1148/// propagation heuristic. The following rules are applied to every
Diego Novillo19e7b7e2014-10-22 18:39:50 +00001149/// block BB in the CFG:
Diego Novillo0accb3d2014-01-10 23:23:46 +00001150///
Diego Novillo19e7b7e2014-10-22 18:39:50 +00001151/// - If BB has a single predecessor/successor, then the weight
Diego Novillo0accb3d2014-01-10 23:23:46 +00001152/// of that edge is the weight of the block.
1153///
1154/// - If all the edges are known except one, and the weight of the
1155/// block is already known, the weight of the unknown edge will
1156/// be the weight of the block minus the sum of all the known
Diego Novillo19e7b7e2014-10-22 18:39:50 +00001157/// edges. If the sum of all the known edges is larger than BB's weight,
Diego Novillo0accb3d2014-01-10 23:23:46 +00001158/// we set the unknown edge weight to zero.
1159///
1160/// - If there is a self-referential edge, and the weight of the block is
1161/// known, the weight for that edge is set to the weight of the block
1162/// minus the weight of the other incoming edges to that block (if
1163/// known).
1164///
1165/// Since this propagation is not guaranteed to finalize for every CFG, we
1166/// only allow it to proceed for a limited number of iterations (controlled
1167/// by -sample-profile-max-propagate-iterations).
1168///
1169/// FIXME: Try to replace this propagation heuristic with a scheme
1170/// that is guaranteed to finalize. A work-list approach similar to
1171/// the standard value propagation algorithm used by SSA-CCP might
1172/// work here.
1173///
1174/// Once all the branch weights are computed, we emit the MD_prof
Diego Novillo19e7b7e2014-10-22 18:39:50 +00001175/// metadata on BB using the computed values for each of its branches.
Diego Novillo0accb3d2014-01-10 23:23:46 +00001176///
1177/// \param F The function to query.
Diego Novilloa32aa322014-03-14 21:58:59 +00001178///
1179/// \returns true if \p F was modified. Returns false, otherwise.
Diego Novillode1ab262014-09-09 12:40:50 +00001180bool SampleProfileLoader::emitAnnotations(Function &F) {
Diego Novillo0accb3d2014-01-10 23:23:46 +00001181 bool Changed = false;
1182
Dehao Chen41dc5a62015-10-09 16:50:16 +00001183 if (getFunctionLoc(F) == 0)
Diego Novilloa32aa322014-03-14 21:58:59 +00001184 return false;
1185
Diego Novillo0accb3d2014-01-10 23:23:46 +00001186 DEBUG(dbgs() << "Line number for the first instruction in " << F.getName()
Dehao Chen41dc5a62015-10-09 16:50:16 +00001187 << ": " << getFunctionLoc(F) << "\n");
Diego Novillo0accb3d2014-01-10 23:23:46 +00001188
Diego Novillo84f06cc2015-11-27 23:14:51 +00001189 Changed |= emitInlineHints(F);
1190
Dehao Chen67226882015-09-30 00:42:46 +00001191 Changed |= inlineHotFunctions(F);
1192
Diego Novillo0accb3d2014-01-10 23:23:46 +00001193 // Compute basic block weights.
1194 Changed |= computeBlockWeights(F);
1195
1196 if (Changed) {
Diego Novillo7732ae42015-08-26 20:00:27 +00001197 // Compute dominance and loop info needed for propagation.
1198 computeDominanceAndLoopInfo(F);
1199
Diego Novillo0accb3d2014-01-10 23:23:46 +00001200 // Find equivalence classes.
1201 findEquivalenceClasses(F);
1202
1203 // Propagate weights to all edges.
1204 propagateWeights(F);
1205 }
1206
Diego Novillof9ed08e2015-10-31 21:53:58 +00001207 // If coverage checking was requested, compute it now.
Diego Novillo243ea6a2015-11-23 20:12:21 +00001208 if (SampleProfileRecordCoverage) {
1209 unsigned Used = CoverageTracker.countUsedRecords(Samples);
1210 unsigned Total = CoverageTracker.countBodyRecords(Samples);
Diego Novillof9ed08e2015-10-31 21:53:58 +00001211 unsigned Coverage = CoverageTracker.computeCoverage(Used, Total);
Diego Novillo243ea6a2015-11-23 20:12:21 +00001212 if (Coverage < SampleProfileRecordCoverage) {
Diego Novillof9ed08e2015-10-31 21:53:58 +00001213 F.getContext().diagnose(DiagnosticInfoSampleProfile(
Pete Cooperadebb932016-03-11 02:14:16 +00001214 F.getSubprogram()->getFilename(), getFunctionLoc(F),
Diego Novillof9ed08e2015-10-31 21:53:58 +00001215 Twine(Used) + " of " + Twine(Total) + " available profile records (" +
1216 Twine(Coverage) + "%) were applied",
1217 DS_Warning));
1218 }
1219 }
1220
Diego Novillo243ea6a2015-11-23 20:12:21 +00001221 if (SampleProfileSampleCoverage) {
1222 uint64_t Used = CoverageTracker.getTotalUsedSamples();
1223 uint64_t Total = CoverageTracker.countBodySamples(Samples);
1224 unsigned Coverage = CoverageTracker.computeCoverage(Used, Total);
1225 if (Coverage < SampleProfileSampleCoverage) {
1226 F.getContext().diagnose(DiagnosticInfoSampleProfile(
Pete Cooperadebb932016-03-11 02:14:16 +00001227 F.getSubprogram()->getFilename(), getFunctionLoc(F),
Diego Novillo243ea6a2015-11-23 20:12:21 +00001228 Twine(Used) + " of " + Twine(Total) + " available profile samples (" +
1229 Twine(Coverage) + "%) were applied",
1230 DS_Warning));
1231 }
1232 }
Diego Novillo0accb3d2014-01-10 23:23:46 +00001233 return Changed;
1234}
1235
Xinliang David Lie897edb2016-05-27 22:30:44 +00001236char SampleProfileLoaderLegacyPass::ID = 0;
Dehao Chen071bb9d2016-06-20 20:53:40 +00001237INITIALIZE_PASS_BEGIN(SampleProfileLoaderLegacyPass, "sample-profile",
1238 "Sample Profile loader", false, false)
1239INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
1240INITIALIZE_PASS_END(SampleProfileLoaderLegacyPass, "sample-profile",
Xinliang David Lid38392e2016-05-27 23:20:16 +00001241 "Sample Profile loader", false, false)
Diego Novilloc0dd1032013-11-26 20:37:33 +00001242
1243bool SampleProfileLoader::doInitialization(Module &M) {
Diego Novillo7732ae42015-08-26 20:00:27 +00001244 auto &Ctx = M.getContext();
Diego Novillo4d711132015-08-25 15:25:11 +00001245 auto ReaderOrErr = SampleProfileReader::create(Filename, Ctx);
Diego Novillofcd55602014-11-03 00:51:45 +00001246 if (std::error_code EC = ReaderOrErr.getError()) {
Diego Novilloc572e922014-10-30 18:00:06 +00001247 std::string Msg = "Could not open profile: " + EC.message();
David Blaikie2297a912015-11-02 20:01:13 +00001248 Ctx.diagnose(DiagnosticInfoSampleProfile(Filename, Msg));
Diego Novilloc572e922014-10-30 18:00:06 +00001249 return false;
1250 }
Diego Novillofcd55602014-11-03 00:51:45 +00001251 Reader = std::move(ReaderOrErr.get());
Diego Novilloc572e922014-10-30 18:00:06 +00001252 ProfileIsValid = (Reader->read() == sampleprof_error::success);
Diego Novilloc0dd1032013-11-26 20:37:33 +00001253 return true;
1254}
1255
Diego Novillo4d711132015-08-25 15:25:11 +00001256ModulePass *llvm::createSampleProfileLoaderPass() {
Xinliang David Lie897edb2016-05-27 22:30:44 +00001257 return new SampleProfileLoaderLegacyPass(SampleProfileFile);
Diego Novilloc0dd1032013-11-26 20:37:33 +00001258}
1259
Diego Novillo4d711132015-08-25 15:25:11 +00001260ModulePass *llvm::createSampleProfileLoaderPass(StringRef Name) {
Xinliang David Lie897edb2016-05-27 22:30:44 +00001261 return new SampleProfileLoaderLegacyPass(Name);
Diego Novilloc0dd1032013-11-26 20:37:33 +00001262}
1263
Diego Novillo4d711132015-08-25 15:25:11 +00001264bool SampleProfileLoader::runOnModule(Module &M) {
Diego Novilloa8a3bd22015-10-28 17:40:22 +00001265 if (!ProfileIsValid)
1266 return false;
1267
Diego Novillo84f06cc2015-11-27 23:14:51 +00001268 // Compute the total number of samples collected in this profile.
1269 for (const auto &I : Reader->getProfiles())
1270 TotalCollectedSamples += I.second.getTotalSamples();
1271
Diego Novillo4d711132015-08-25 15:25:11 +00001272 bool retval = false;
1273 for (auto &F : M)
Diego Novilloa8a3bd22015-10-28 17:40:22 +00001274 if (!F.isDeclaration()) {
1275 clearFunctionData();
Diego Novillo4d711132015-08-25 15:25:11 +00001276 retval |= runOnFunction(F);
Diego Novilloa8a3bd22015-10-28 17:40:22 +00001277 }
Dehao Chenc66a06a2016-06-24 22:57:06 +00001278 M.setProfileSummary(Reader->getSummary().getMD(M.getContext()));
Diego Novillo4d711132015-08-25 15:25:11 +00001279 return retval;
1280}
1281
Xinliang David Lie897edb2016-05-27 22:30:44 +00001282bool SampleProfileLoaderLegacyPass::runOnModule(Module &M) {
Dehao Chen071bb9d2016-06-20 20:53:40 +00001283 // FIXME: pass in AssumptionCache correctly for the new pass manager.
1284 SampleLoader.setACT(&getAnalysis<AssumptionCacheTracker>());
Xinliang David Lie897edb2016-05-27 22:30:44 +00001285 return SampleLoader.runOnModule(M);
1286}
1287
Diego Novillo8d6568b2013-11-13 12:22:21 +00001288bool SampleProfileLoader::runOnFunction(Function &F) {
Dehao Chen6c73b492016-02-22 22:46:21 +00001289 F.setEntryCount(0);
Diego Novillode1ab262014-09-09 12:40:50 +00001290 Samples = Reader->getSamplesFor(F);
1291 if (!Samples->empty())
1292 return emitAnnotations(F);
Diego Novillo0accb3d2014-01-10 23:23:46 +00001293 return false;
Diego Novillo8d6568b2013-11-13 12:22:21 +00001294}
Xinliang David Lid38392e2016-05-27 23:20:16 +00001295
1296PreservedAnalyses SampleProfileLoaderPass::run(Module &M,
1297 AnalysisManager<Module> &AM) {
1298
1299 SampleProfileLoader SampleLoader(SampleProfileFile);
1300
1301 SampleLoader.doInitialization(M);
1302
1303 if (!SampleLoader.runOnModule(M))
1304 return PreservedAnalyses::all();
1305
1306 return PreservedAnalyses::none();
1307}