blob: 0222d249a85f8e9e452ff70f1f65b958e53b7bc4 [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
David Blaikie301627f2018-03-22 22:42:44 +000025#include "llvm/Transforms/IPO/SampleProfile.h"
Eugene Zelenkof27d1612017-10-19 21:21:30 +000026#include "llvm/ADT/ArrayRef.h"
Diego Novillo8d6568b2013-11-13 12:22:21 +000027#include "llvm/ADT/DenseMap.h"
Eugene Zelenkof27d1612017-10-19 21:21:30 +000028#include "llvm/ADT/DenseSet.h"
29#include "llvm/ADT/None.h"
Diego Novillo0accb3d2014-01-10 23:23:46 +000030#include "llvm/ADT/SmallPtrSet.h"
Chandler Carruth07baed52014-01-13 08:04:33 +000031#include "llvm/ADT/SmallSet.h"
Eugene Zelenkof27d1612017-10-19 21:21:30 +000032#include "llvm/ADT/SmallVector.h"
33#include "llvm/ADT/StringMap.h"
Diego Novillo8d6568b2013-11-13 12:22:21 +000034#include "llvm/ADT/StringRef.h"
Eugene Zelenkof27d1612017-10-19 21:21:30 +000035#include "llvm/ADT/Twine.h"
Daniel Jasperaec2fa32016-12-19 08:22:17 +000036#include "llvm/Analysis/AssumptionCache.h"
Dehao Chen3a81f842017-09-14 17:29:56 +000037#include "llvm/Analysis/InlineCost.h"
Diego Novillo0accb3d2014-01-10 23:23:46 +000038#include "llvm/Analysis/LoopInfo.h"
Adam Nemet0965da22017-10-09 23:19:02 +000039#include "llvm/Analysis/OptimizationRemarkEmitter.h"
Wei Mi0c2f6be2018-05-10 23:02:27 +000040#include "llvm/Analysis/ProfileSummaryInfo.h"
Dehao Chen3a81f842017-09-14 17:29:56 +000041#include "llvm/Analysis/TargetTransformInfo.h"
Eugene Zelenkof27d1612017-10-19 21:21:30 +000042#include "llvm/IR/BasicBlock.h"
43#include "llvm/IR/CFG.h"
44#include "llvm/IR/CallSite.h"
45#include "llvm/IR/DebugInfoMetadata.h"
46#include "llvm/IR/DebugLoc.h"
Diego Novilloa32aa322014-03-14 21:58:59 +000047#include "llvm/IR/DiagnosticInfo.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000048#include "llvm/IR/Dominators.h"
Diego Novillo8d6568b2013-11-13 12:22:21 +000049#include "llvm/IR/Function.h"
Dehao Chen77079002017-01-20 22:56:07 +000050#include "llvm/IR/GlobalValue.h"
Eugene Zelenkof27d1612017-10-19 21:21:30 +000051#include "llvm/IR/InstrTypes.h"
52#include "llvm/IR/Instruction.h"
Diego Novillo8d6568b2013-11-13 12:22:21 +000053#include "llvm/IR/Instructions.h"
Xinliang David Lid38392e2016-05-27 23:20:16 +000054#include "llvm/IR/IntrinsicInst.h"
Diego Novillo8d6568b2013-11-13 12:22:21 +000055#include "llvm/IR/LLVMContext.h"
Diego Novillo8d6568b2013-11-13 12:22:21 +000056#include "llvm/IR/MDBuilder.h"
57#include "llvm/IR/Module.h"
Eugene Zelenkof27d1612017-10-19 21:21:30 +000058#include "llvm/IR/PassManager.h"
Dehao Chen1ea8bd82017-04-17 22:23:05 +000059#include "llvm/IR/ValueSymbolTable.h"
Diego Novillo8d6568b2013-11-13 12:22:21 +000060#include "llvm/Pass.h"
Dehao Chen77079002017-01-20 22:56:07 +000061#include "llvm/ProfileData/InstrProf.h"
Eugene Zelenkof27d1612017-10-19 21:21:30 +000062#include "llvm/ProfileData/SampleProf.h"
Diego Novillode1ab262014-09-09 12:40:50 +000063#include "llvm/ProfileData/SampleProfReader.h"
Eugene Zelenkof27d1612017-10-19 21:21:30 +000064#include "llvm/Support/Casting.h"
Diego Novillo8d6568b2013-11-13 12:22:21 +000065#include "llvm/Support/CommandLine.h"
66#include "llvm/Support/Debug.h"
Eugene Zelenkof27d1612017-10-19 21:21:30 +000067#include "llvm/Support/ErrorHandling.h"
Dehao Chen8e7df832015-09-29 18:28:15 +000068#include "llvm/Support/ErrorOr.h"
Eugene Zelenkof27d1612017-10-19 21:21:30 +000069#include "llvm/Support/GenericDomTree.h"
Diego Novillo8d6568b2013-11-13 12:22:21 +000070#include "llvm/Support/raw_ostream.h"
Diego Novillo4d711132015-08-25 15:25:11 +000071#include "llvm/Transforms/IPO.h"
Dehao Chen274df5e2017-01-31 17:49:37 +000072#include "llvm/Transforms/Instrumentation.h"
Matthew Simpsone363d2c2017-12-06 21:22:54 +000073#include "llvm/Transforms/Utils/CallPromotionUtils.h"
Dehao Chen57d1dda2016-03-03 18:09:32 +000074#include "llvm/Transforms/Utils/Cloning.h"
Eugene Zelenkof27d1612017-10-19 21:21:30 +000075#include <algorithm>
76#include <cassert>
77#include <cstdint>
78#include <functional>
79#include <limits>
80#include <map>
81#include <memory>
82#include <string>
83#include <system_error>
84#include <utility>
85#include <vector>
Diego Novillo8d6568b2013-11-13 12:22:21 +000086
87using namespace llvm;
Diego Novillode1ab262014-09-09 12:40:50 +000088using namespace sampleprof;
Easwaran Ramane5b8de22018-01-17 22:24:23 +000089using ProfileCount = Function::ProfileCount;
Chandler Carruth964daaa2014-04-22 02:55:47 +000090#define DEBUG_TYPE "sample-profile"
91
Diego Novillo8d6568b2013-11-13 12:22:21 +000092// Command line option to specify the file to read samples from. This is
93// mainly used for debugging.
94static cl::opt<std::string> SampleProfileFile(
95 "sample-profile-file", cl::init(""), cl::value_desc("filename"),
96 cl::desc("Profile file loaded by -sample-profile"), cl::Hidden);
Eugene Zelenkof27d1612017-10-19 21:21:30 +000097
Diego Novillo0accb3d2014-01-10 23:23:46 +000098static cl::opt<unsigned> SampleProfileMaxPropagateIterations(
99 "sample-profile-max-propagate-iterations", cl::init(100),
100 cl::desc("Maximum number of iterations to go through when propagating "
101 "sample block/edge weights through the CFG."));
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000102
Diego Novillo243ea6a2015-11-23 20:12:21 +0000103static cl::opt<unsigned> SampleProfileRecordCoverage(
104 "sample-profile-check-record-coverage", cl::init(0), cl::value_desc("N"),
105 cl::desc("Emit a warning if less than N% of records in the input profile "
106 "are matched to the IR."));
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000107
Diego Novillo243ea6a2015-11-23 20:12:21 +0000108static cl::opt<unsigned> SampleProfileSampleCoverage(
109 "sample-profile-check-sample-coverage", cl::init(0), cl::value_desc("N"),
Diego Novillo748b3ffe2015-10-28 22:30:25 +0000110 cl::desc("Emit a warning if less than N% of samples in the input profile "
111 "are matched to the IR."));
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000112
Diego Novillo8d6568b2013-11-13 12:22:21 +0000113namespace {
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000114
115using BlockWeightMap = DenseMap<const BasicBlock *, uint64_t>;
116using EquivalenceClassMap = DenseMap<const BasicBlock *, const BasicBlock *>;
117using Edge = std::pair<const BasicBlock *, const BasicBlock *>;
118using EdgeWeightMap = DenseMap<Edge, uint64_t>;
119using BlockEdgeMap =
120 DenseMap<const BasicBlock *, SmallVector<const BasicBlock *, 8>>;
Diego Novilloc0dd1032013-11-26 20:37:33 +0000121
Dehao Chen0f35fa92016-12-13 22:13:18 +0000122class SampleCoverageTracker {
123public:
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000124 SampleCoverageTracker() = default;
Dehao Chen0f35fa92016-12-13 22:13:18 +0000125
126 bool markSamplesUsed(const FunctionSamples *FS, uint32_t LineOffset,
127 uint32_t Discriminator, uint64_t Samples);
128 unsigned computeCoverage(unsigned Used, unsigned Total) const;
Wei Mi0c2f6be2018-05-10 23:02:27 +0000129 unsigned countUsedRecords(const FunctionSamples *FS,
130 ProfileSummaryInfo *PSI) const;
131 unsigned countBodyRecords(const FunctionSamples *FS,
132 ProfileSummaryInfo *PSI) const;
Dehao Chen0f35fa92016-12-13 22:13:18 +0000133 uint64_t getTotalUsedSamples() const { return TotalUsedSamples; }
Wei Mi0c2f6be2018-05-10 23:02:27 +0000134 uint64_t countBodySamples(const FunctionSamples *FS,
135 ProfileSummaryInfo *PSI) const;
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000136
Dehao Chen0f35fa92016-12-13 22:13:18 +0000137 void clear() {
138 SampleCoverage.clear();
139 TotalUsedSamples = 0;
140 }
141
142private:
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000143 using BodySampleCoverageMap = std::map<LineLocation, unsigned>;
144 using FunctionSamplesCoverageMap =
145 DenseMap<const FunctionSamples *, BodySampleCoverageMap>;
Dehao Chen0f35fa92016-12-13 22:13:18 +0000146
147 /// Coverage map for sampling records.
148 ///
149 /// This map keeps a record of sampling records that have been matched to
150 /// an IR instruction. This is used to detect some form of staleness in
151 /// profiles (see flag -sample-profile-check-coverage).
152 ///
153 /// Each entry in the map corresponds to a FunctionSamples instance. This is
154 /// another map that counts how many times the sample record at the
155 /// given location has been used.
156 FunctionSamplesCoverageMap SampleCoverage;
157
158 /// Number of samples used from the profile.
159 ///
160 /// When a sampling record is used for the first time, the samples from
161 /// that record are added to this accumulator. Coverage is later computed
162 /// based on the total number of samples available in this function and
163 /// its callsites.
164 ///
165 /// Note that this accumulator tracks samples used from a single function
166 /// and all the inlined callsites. Strictly, we should have a map of counters
167 /// keyed by FunctionSamples pointers, but these stats are cleared after
168 /// every function, so we just need to keep a single counter.
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000169 uint64_t TotalUsedSamples = 0;
Dehao Chen0f35fa92016-12-13 22:13:18 +0000170};
171
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000172/// Sample profile pass.
Diego Novilloc0dd1032013-11-26 20:37:33 +0000173///
Diego Novillode1ab262014-09-09 12:40:50 +0000174/// This pass reads profile data from the file specified by
175/// -sample-profile-file and annotates every affected function with the
176/// profile information found in that file.
Xinliang David Lie897edb2016-05-27 22:30:44 +0000177class SampleProfileLoader {
Diego Novilloc0dd1032013-11-26 20:37:33 +0000178public:
Dehao Chenf3ed14d2017-09-12 21:55:55 +0000179 SampleProfileLoader(
Dehao Chend26dae02017-10-01 05:24:51 +0000180 StringRef Name, bool IsThinLTOPreLink,
Dehao Chen3a81f842017-09-14 17:29:56 +0000181 std::function<AssumptionCache &(Function &)> GetAssumptionCache,
182 std::function<TargetTransformInfo &(Function &)> GetTargetTransformInfo)
Benjamin Kramer24cb28b2017-12-28 18:10:41 +0000183 : GetAC(std::move(GetAssumptionCache)),
184 GetTTI(std::move(GetTargetTransformInfo)), Filename(Name),
185 IsThinLTOPreLink(IsThinLTOPreLink) {}
Diego Novillode1ab262014-09-09 12:40:50 +0000186
Xinliang David Lie897edb2016-05-27 22:30:44 +0000187 bool doInitialization(Module &M);
Wei Mi0c2f6be2018-05-10 23:02:27 +0000188 bool runOnModule(Module &M, ModuleAnalysisManager *AM,
189 ProfileSummaryInfo *_PSI);
Diego Novillode1ab262014-09-09 12:40:50 +0000190
191 void dump() { Reader->dump(); }
192
Diego Novillode1ab262014-09-09 12:40:50 +0000193protected:
Eli Friedman51cf2602017-08-11 21:12:04 +0000194 bool runOnFunction(Function &F, ModuleAnalysisManager *AM);
Diego Novillo0accb3d2014-01-10 23:23:46 +0000195 unsigned getFunctionLoc(Function &F);
Diego Novillode1ab262014-09-09 12:40:50 +0000196 bool emitAnnotations(Function &F);
Dehao Chen0f35fa92016-12-13 22:13:18 +0000197 ErrorOr<uint64_t> getInstWeight(const Instruction &I);
198 ErrorOr<uint64_t> getBlockWeight(const BasicBlock *BB);
Dehao Chen41cde0b2016-09-18 23:11:37 +0000199 const FunctionSamples *findCalleeFunctionSamples(const Instruction &I) const;
Dehao Chen2c7ca9b2017-04-13 19:52:10 +0000200 std::vector<const FunctionSamples *>
Dehao Chen3f56a052017-10-10 21:13:50 +0000201 findIndirectCallFunctionSamples(const Instruction &I, uint64_t &Sum) const;
Dehao Chen67226882015-09-30 00:42:46 +0000202 const FunctionSamples *findFunctionSamples(const Instruction &I) const;
Dehao Chen4f5d8302017-09-30 20:46:15 +0000203 bool inlineCallInstruction(Instruction *I);
Dehao Chena60cdd32017-02-28 18:09:44 +0000204 bool inlineHotFunctions(Function &F,
Dehao Chenc6c051f2017-11-01 20:26:47 +0000205 DenseSet<GlobalValue::GUID> &InlinedGUIDs);
Diego Novillo0accb3d2014-01-10 23:23:46 +0000206 void printEdgeWeight(raw_ostream &OS, Edge E);
Dehao Chen8e7df832015-09-29 18:28:15 +0000207 void printBlockWeight(raw_ostream &OS, const BasicBlock *BB) const;
208 void printBlockEquivalence(raw_ostream &OS, const BasicBlock *BB);
Diego Novillo0accb3d2014-01-10 23:23:46 +0000209 bool computeBlockWeights(Function &F);
210 void findEquivalenceClasses(Function &F);
Jakub Kuderskib292c222017-07-14 18:26:09 +0000211 template <bool IsPostDom>
Benjamin Kramer8a752e32016-02-13 16:01:12 +0000212 void findEquivalencesFor(BasicBlock *BB1, ArrayRef<BasicBlock *> Descendants,
Jakub Kuderskib292c222017-07-14 18:26:09 +0000213 DominatorTreeBase<BasicBlock, IsPostDom> *DomTree);
214
Diego Novillo0accb3d2014-01-10 23:23:46 +0000215 void propagateWeights(Function &F);
Diego Novillo38be3332015-10-15 16:36:21 +0000216 uint64_t visitEdge(Edge E, unsigned *NumUnknownEdges, Edge *UnknownEdge);
Diego Novillo0accb3d2014-01-10 23:23:46 +0000217 void buildEdges(Function &F);
Dehao Chenc0a1e432016-08-12 16:22:12 +0000218 bool propagateThroughEdges(Function &F, bool UpdateBlockCount);
Diego Novillo7732ae42015-08-26 20:00:27 +0000219 void computeDominanceAndLoopInfo(Function &F);
Diego Novilloa8a3bd22015-10-28 17:40:22 +0000220 void clearFunctionData();
Diego Novilloc0dd1032013-11-26 20:37:33 +0000221
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000222 /// Map basic blocks to their computed weights.
Diego Novilloc0dd1032013-11-26 20:37:33 +0000223 ///
224 /// The weight of a basic block is defined to be the maximum
225 /// of all the instruction weights in that block.
226 BlockWeightMap BlockWeights;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000227
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000228 /// Map edges to their computed weights.
Diego Novillo0accb3d2014-01-10 23:23:46 +0000229 ///
230 /// Edge weights are computed by propagating basic block weights in
231 /// SampleProfile::propagateWeights.
232 EdgeWeightMap EdgeWeights;
233
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000234 /// Set of visited blocks during propagation.
Matthias Braunb30f2f512016-01-30 01:24:31 +0000235 SmallPtrSet<const BasicBlock *, 32> VisitedBlocks;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000236
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000237 /// Set of visited edges during propagation.
Matthias Braunb30f2f512016-01-30 01:24:31 +0000238 SmallSet<Edge, 32> VisitedEdges;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000239
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000240 /// Equivalence classes for block weights.
Diego Novillo0accb3d2014-01-10 23:23:46 +0000241 ///
242 /// Two blocks BB1 and BB2 are in the same equivalence class if they
243 /// dominate and post-dominate each other, and they are in the same loop
244 /// nest. When this happens, the two blocks are guaranteed to execute
245 /// the same number of times.
246 EquivalenceClassMap EquivalenceClass;
247
Dehao Chen1ea8bd82017-04-17 22:23:05 +0000248 /// Map from function name to Function *. Used to find the function from
249 /// the function name. If the function name contains suffix, additional
250 /// entry is added to map from the stripped name to the function if there
251 /// is one-to-one mapping.
252 StringMap<Function *> SymbolMap;
253
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000254 /// Dominance, post-dominance and loop information.
Diego Novillo7732ae42015-08-26 20:00:27 +0000255 std::unique_ptr<DominatorTree> DT;
Jakub Kuderskib292c222017-07-14 18:26:09 +0000256 std::unique_ptr<PostDomTreeBase<BasicBlock>> PDT;
Diego Novillo7732ae42015-08-26 20:00:27 +0000257 std::unique_ptr<LoopInfo> LI;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000258
Dehao Chenf3ed14d2017-09-12 21:55:55 +0000259 std::function<AssumptionCache &(Function &)> GetAC;
Dehao Chen3a81f842017-09-14 17:29:56 +0000260 std::function<TargetTransformInfo &(Function &)> GetTTI;
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000261
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000262 /// Predecessors for each basic block in the CFG.
Diego Novillo0accb3d2014-01-10 23:23:46 +0000263 BlockEdgeMap Predecessors;
264
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000265 /// Successors for each basic block in the CFG.
Diego Novillo0accb3d2014-01-10 23:23:46 +0000266 BlockEdgeMap Successors;
Diego Novillo92aa8c22014-03-10 22:41:28 +0000267
Dehao Chen0f35fa92016-12-13 22:13:18 +0000268 SampleCoverageTracker CoverageTracker;
269
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000270 /// Profile reader object.
Diego Novillode1ab262014-09-09 12:40:50 +0000271 std::unique_ptr<SampleProfileReader> Reader;
272
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000273 /// Samples collected for the body of this function.
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000274 FunctionSamples *Samples = nullptr;
Diego Novillo8d6568b2013-11-13 12:22:21 +0000275
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000276 /// Name of the profile file to load.
Dehao Chenfb699612016-12-14 22:03:08 +0000277 std::string Filename;
Diego Novilloa32aa322014-03-14 21:58:59 +0000278
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000279 /// Flag indicating whether the profile input loaded successfully.
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000280 bool ProfileIsValid = false;
Diego Novillo84f06cc2015-11-27 23:14:51 +0000281
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000282 /// Flag indicating if the pass is invoked in ThinLTO compile phase.
Dehao Chend26dae02017-10-01 05:24:51 +0000283 ///
284 /// In this phase, in annotation, we should not promote indirect calls.
285 /// Instead, we will mark GUIDs that needs to be annotated to the function.
286 bool IsThinLTOPreLink;
287
Wei Mi0c2f6be2018-05-10 23:02:27 +0000288 /// Profile Summary Info computed from sample profile.
289 ProfileSummaryInfo *PSI = nullptr;
290
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000291 /// Total number of samples collected in this profile.
Diego Novillo84f06cc2015-11-27 23:14:51 +0000292 ///
293 /// This is the sum of all the samples collected in all the functions executed
294 /// at runtime.
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000295 uint64_t TotalCollectedSamples = 0;
Eli Friedman51cf2602017-08-11 21:12:04 +0000296
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000297 /// Optimization Remark Emitter used to emit diagnostic remarks.
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000298 OptimizationRemarkEmitter *ORE = nullptr;
Diego Novillo8d6568b2013-11-13 12:22:21 +0000299};
Diego Novillo748b3ffe2015-10-28 22:30:25 +0000300
Xinliang David Lie897edb2016-05-27 22:30:44 +0000301class SampleProfileLoaderLegacyPass : public ModulePass {
302public:
303 // Class identification, replacement for typeinfo
304 static char ID;
305
Dehao Chend26dae02017-10-01 05:24:51 +0000306 SampleProfileLoaderLegacyPass(StringRef Name = SampleProfileFile,
307 bool IsThinLTOPreLink = false)
308 : ModulePass(ID), SampleLoader(Name, IsThinLTOPreLink,
Dehao Chenf3ed14d2017-09-12 21:55:55 +0000309 [&](Function &F) -> AssumptionCache & {
310 return ACT->getAssumptionCache(F);
Dehao Chen3a81f842017-09-14 17:29:56 +0000311 },
312 [&](Function &F) -> TargetTransformInfo & {
313 return TTIWP->getTTI(F);
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000314 }) {
Xinliang David Lie897edb2016-05-27 22:30:44 +0000315 initializeSampleProfileLoaderLegacyPassPass(
316 *PassRegistry::getPassRegistry());
317 }
318
319 void dump() { SampleLoader.dump(); }
320
321 bool doInitialization(Module &M) override {
322 return SampleLoader.doInitialization(M);
323 }
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000324
Mehdi Amini117296c2016-10-01 02:56:57 +0000325 StringRef getPassName() const override { return "Sample profile pass"; }
Xinliang David Lie897edb2016-05-27 22:30:44 +0000326 bool runOnModule(Module &M) override;
327
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000328 void getAnalysisUsage(AnalysisUsage &AU) const override {
329 AU.addRequired<AssumptionCacheTracker>();
Dehao Chen3a81f842017-09-14 17:29:56 +0000330 AU.addRequired<TargetTransformInfoWrapperPass>();
Wei Mi0c2f6be2018-05-10 23:02:27 +0000331 AU.addRequired<ProfileSummaryInfoWrapperPass>();
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000332 }
333
Xinliang David Lie897edb2016-05-27 22:30:44 +0000334private:
335 SampleProfileLoader SampleLoader;
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000336 AssumptionCacheTracker *ACT = nullptr;
337 TargetTransformInfoWrapperPass *TTIWP = nullptr;
Xinliang David Lie897edb2016-05-27 22:30:44 +0000338};
339
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000340} // end anonymous namespace
341
Wei Mi0c2f6be2018-05-10 23:02:27 +0000342/// Return true if the given callsite is hot wrt to hot cutoff threshold.
Diego Novillo0b6985a2015-11-24 22:38:37 +0000343///
344/// Functions that were inlined in the original binary will be represented
345/// in the inline stack in the sample profile. If the profile shows that
346/// the original inline decision was "good" (i.e., the callsite is executed
347/// frequently), then we will recreate the inline decision and apply the
348/// profile from the inlined callsite.
349///
Wei Mi0c2f6be2018-05-10 23:02:27 +0000350/// To decide whether an inlined callsite is hot, we compare the callsite
351/// sample count with the hot cutoff computed by ProfileSummaryInfo, it is
352/// regarded as hot if the count is above the cutoff value.
353static bool callsiteIsHot(const FunctionSamples *CallsiteFS,
354 ProfileSummaryInfo *PSI) {
Diego Novillo0b6985a2015-11-24 22:38:37 +0000355 if (!CallsiteFS)
356 return false; // The callsite was not inlined in the original binary.
357
Wei Mi0c2f6be2018-05-10 23:02:27 +0000358 assert(PSI && "PSI is expected to be non null");
Diego Novillo0b6985a2015-11-24 22:38:37 +0000359 uint64_t CallsiteTotalSamples = CallsiteFS->getTotalSamples();
Wei Mi0c2f6be2018-05-10 23:02:27 +0000360 return PSI->isHotCount(CallsiteTotalSamples);
Diego Novillo0b6985a2015-11-24 22:38:37 +0000361}
Diego Novillo748b3ffe2015-10-28 22:30:25 +0000362
363/// Mark as used the sample record for the given function samples at
364/// (LineOffset, Discriminator).
Diego Novillof9ed08e2015-10-31 21:53:58 +0000365///
366/// \returns true if this is the first time we mark the given record.
Diego Novillo243ea6a2015-11-23 20:12:21 +0000367bool SampleCoverageTracker::markSamplesUsed(const FunctionSamples *FS,
Diego Novillo748b3ffe2015-10-28 22:30:25 +0000368 uint32_t LineOffset,
Diego Novillo243ea6a2015-11-23 20:12:21 +0000369 uint32_t Discriminator,
370 uint64_t Samples) {
Diego Novillof9ed08e2015-10-31 21:53:58 +0000371 LineLocation Loc(LineOffset, Discriminator);
Diego Novillo243ea6a2015-11-23 20:12:21 +0000372 unsigned &Count = SampleCoverage[FS][Loc];
373 bool FirstTime = (++Count == 1);
374 if (FirstTime)
375 TotalUsedSamples += Samples;
376 return FirstTime;
Diego Novillo748b3ffe2015-10-28 22:30:25 +0000377}
378
379/// Return the number of sample records that were applied from this profile.
Diego Novillo0b6985a2015-11-24 22:38:37 +0000380///
381/// This count does not include records from cold inlined callsites.
Diego Novillo748b3ffe2015-10-28 22:30:25 +0000382unsigned
Wei Mi0c2f6be2018-05-10 23:02:27 +0000383SampleCoverageTracker::countUsedRecords(const FunctionSamples *FS,
384 ProfileSummaryInfo *PSI) const {
Diego Novillo243ea6a2015-11-23 20:12:21 +0000385 auto I = SampleCoverage.find(FS);
Diego Novillo5fb49e52015-11-20 21:46:38 +0000386
Diego Novillo243ea6a2015-11-23 20:12:21 +0000387 // The size of the coverage map for FS represents the number of records
Diego Novillo5fb49e52015-11-20 21:46:38 +0000388 // that were marked used at least once.
Diego Novillof9ed08e2015-10-31 21:53:58 +0000389 unsigned Count = (I != SampleCoverage.end()) ? I->second.size() : 0;
Diego Novillo5fb49e52015-11-20 21:46:38 +0000390
391 // If there are inlined callsites in this function, count the samples found
392 // in the respective bodies. However, do not bother counting callees with 0
393 // total samples, these are callees that were never invoked at runtime.
Dehao Chen2c7ca9b2017-04-13 19:52:10 +0000394 for (const auto &I : FS->getCallsiteSamples())
395 for (const auto &J : I.second) {
396 const FunctionSamples *CalleeSamples = &J.second;
Wei Mi0c2f6be2018-05-10 23:02:27 +0000397 if (callsiteIsHot(CalleeSamples, PSI))
398 Count += countUsedRecords(CalleeSamples, PSI);
Dehao Chen2c7ca9b2017-04-13 19:52:10 +0000399 }
Diego Novillo5fb49e52015-11-20 21:46:38 +0000400
Diego Novillof9ed08e2015-10-31 21:53:58 +0000401 return Count;
402}
403
404/// Return the number of sample records in the body of this profile.
405///
Diego Novillo0b6985a2015-11-24 22:38:37 +0000406/// This count does not include records from cold inlined callsites.
Diego Novillof9ed08e2015-10-31 21:53:58 +0000407unsigned
Wei Mi0c2f6be2018-05-10 23:02:27 +0000408SampleCoverageTracker::countBodyRecords(const FunctionSamples *FS,
409 ProfileSummaryInfo *PSI) const {
Diego Novillo243ea6a2015-11-23 20:12:21 +0000410 unsigned Count = FS->getBodySamples().size();
Diego Novillo5fb49e52015-11-20 21:46:38 +0000411
Diego Novillo0b6985a2015-11-24 22:38:37 +0000412 // Only count records in hot callsites.
Dehao Chen2c7ca9b2017-04-13 19:52:10 +0000413 for (const auto &I : FS->getCallsiteSamples())
414 for (const auto &J : I.second) {
415 const FunctionSamples *CalleeSamples = &J.second;
Wei Mi0c2f6be2018-05-10 23:02:27 +0000416 if (callsiteIsHot(CalleeSamples, PSI))
417 Count += countBodyRecords(CalleeSamples, PSI);
Dehao Chen2c7ca9b2017-04-13 19:52:10 +0000418 }
Diego Novillo5fb49e52015-11-20 21:46:38 +0000419
Diego Novillof9ed08e2015-10-31 21:53:58 +0000420 return Count;
Diego Novillo748b3ffe2015-10-28 22:30:25 +0000421}
422
Diego Novillo243ea6a2015-11-23 20:12:21 +0000423/// Return the number of samples collected in the body of this profile.
424///
Diego Novillo0b6985a2015-11-24 22:38:37 +0000425/// This count does not include samples from cold inlined callsites.
Diego Novillo243ea6a2015-11-23 20:12:21 +0000426uint64_t
Wei Mi0c2f6be2018-05-10 23:02:27 +0000427SampleCoverageTracker::countBodySamples(const FunctionSamples *FS,
428 ProfileSummaryInfo *PSI) const {
Diego Novillo243ea6a2015-11-23 20:12:21 +0000429 uint64_t Total = 0;
430 for (const auto &I : FS->getBodySamples())
431 Total += I.second.getSamples();
432
Diego Novillo0b6985a2015-11-24 22:38:37 +0000433 // Only count samples in hot callsites.
Dehao Chen2c7ca9b2017-04-13 19:52:10 +0000434 for (const auto &I : FS->getCallsiteSamples())
435 for (const auto &J : I.second) {
436 const FunctionSamples *CalleeSamples = &J.second;
Wei Mi0c2f6be2018-05-10 23:02:27 +0000437 if (callsiteIsHot(CalleeSamples, PSI))
438 Total += countBodySamples(CalleeSamples, PSI);
Dehao Chen2c7ca9b2017-04-13 19:52:10 +0000439 }
Diego Novillo243ea6a2015-11-23 20:12:21 +0000440
441 return Total;
442}
443
Diego Novillo748b3ffe2015-10-28 22:30:25 +0000444/// Return the fraction of sample records used in this profile.
445///
446/// The returned value is an unsigned integer in the range 0-100 indicating
447/// the percentage of sample records that were used while applying this
448/// profile to the associated function.
Diego Novillof9ed08e2015-10-31 21:53:58 +0000449unsigned SampleCoverageTracker::computeCoverage(unsigned Used,
450 unsigned Total) const {
451 assert(Used <= Total &&
Diego Novillo748b3ffe2015-10-28 22:30:25 +0000452 "number of used records cannot exceed the total number of records");
Diego Novillof9ed08e2015-10-31 21:53:58 +0000453 return Total > 0 ? Used * 100 / Total : 100;
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000454}
Diego Novillo8d6568b2013-11-13 12:22:21 +0000455
Diego Novilloa8a3bd22015-10-28 17:40:22 +0000456/// Clear all the per-function data used to load samples and propagate weights.
457void SampleProfileLoader::clearFunctionData() {
458 BlockWeights.clear();
459 EdgeWeights.clear();
460 VisitedBlocks.clear();
461 VisitedEdges.clear();
462 EquivalenceClass.clear();
463 DT = nullptr;
464 PDT = nullptr;
465 LI = nullptr;
466 Predecessors.clear();
467 Successors.clear();
Diego Novillo1ca881c2015-11-23 16:30:17 +0000468 CoverageTracker.clear();
Diego Novilloa8a3bd22015-10-28 17:40:22 +0000469}
470
Florian Hahn6b3216a2017-07-31 10:07:49 +0000471#ifndef NDEBUG
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000472/// Print the weight of edge \p E on stream \p OS.
Diego Novillo0accb3d2014-01-10 23:23:46 +0000473///
474/// \param OS Stream to emit the output to.
475/// \param E Edge to print.
Diego Novillode1ab262014-09-09 12:40:50 +0000476void SampleProfileLoader::printEdgeWeight(raw_ostream &OS, Edge E) {
Diego Novillo0accb3d2014-01-10 23:23:46 +0000477 OS << "weight[" << E.first->getName() << "->" << E.second->getName()
478 << "]: " << EdgeWeights[E] << "\n";
479}
480
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000481/// Print the equivalence class of block \p BB on stream \p OS.
Diego Novillo0accb3d2014-01-10 23:23:46 +0000482///
483/// \param OS Stream to emit the output to.
484/// \param BB Block to print.
Diego Novillode1ab262014-09-09 12:40:50 +0000485void SampleProfileLoader::printBlockEquivalence(raw_ostream &OS,
Dehao Chen8e7df832015-09-29 18:28:15 +0000486 const BasicBlock *BB) {
487 const BasicBlock *Equiv = EquivalenceClass[BB];
Diego Novillo0accb3d2014-01-10 23:23:46 +0000488 OS << "equivalence[" << BB->getName()
489 << "]: " << ((Equiv) ? EquivalenceClass[BB]->getName() : "NONE") << "\n";
490}
491
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000492/// Print the weight of block \p BB on stream \p OS.
Diego Novillo0accb3d2014-01-10 23:23:46 +0000493///
494/// \param OS Stream to emit the output to.
495/// \param BB Block to print.
Dehao Chen8e7df832015-09-29 18:28:15 +0000496void SampleProfileLoader::printBlockWeight(raw_ostream &OS,
497 const BasicBlock *BB) const {
498 const auto &I = BlockWeights.find(BB);
Diego Novillo38be3332015-10-15 16:36:21 +0000499 uint64_t W = (I == BlockWeights.end() ? 0 : I->second);
Dehao Chen8e7df832015-09-29 18:28:15 +0000500 OS << "weight[" << BB->getName() << "]: " << W << "\n";
Diego Novillo0accb3d2014-01-10 23:23:46 +0000501}
Florian Hahn6b3216a2017-07-31 10:07:49 +0000502#endif
Diego Novillo0accb3d2014-01-10 23:23:46 +0000503
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000504/// Get the weight for an instruction.
Diego Novillo0accb3d2014-01-10 23:23:46 +0000505///
506/// The "weight" of an instruction \p Inst is the number of samples
507/// collected on that instruction at runtime. To retrieve it, we
508/// need to compute the line number of \p Inst relative to the start of its
509/// function. We use HeaderLineno to compute the offset. We then
510/// look up the samples collected for \p Inst using BodySamples.
511///
512/// \param Inst Instruction to query.
513///
Dehao Chen8e7df832015-09-29 18:28:15 +0000514/// \returns the weight of \p Inst.
Dehao Chen94f369f2017-01-19 23:20:31 +0000515ErrorOr<uint64_t> SampleProfileLoader::getInstWeight(const Instruction &Inst) {
Benjamin Kramer4fed9282016-05-27 12:30:51 +0000516 const DebugLoc &DLoc = Inst.getDebugLoc();
Duncan P. N. Exon Smithec819c02015-03-30 19:49:49 +0000517 if (!DLoc)
Dehao Chen8e7df832015-09-29 18:28:15 +0000518 return std::error_code();
Duncan P. N. Exon Smith41a15462015-03-20 00:56:55 +0000519
Dehao Chen67226882015-09-30 00:42:46 +0000520 const FunctionSamples *FS = findFunctionSamples(Inst);
521 if (!FS)
522 return std::error_code();
Dehao Chen41dc5a62015-10-09 16:50:16 +0000523
Dehao Chenc0a1e432016-08-12 16:22:12 +0000524 // Ignore all intrinsics and branch instructions.
525 // Branch instruction usually contains debug info from sources outside of
526 // the residing basic block, thus we ignore them during annotation.
527 if (isa<BranchInst>(Inst) || isa<IntrinsicInst>(Inst))
Dehao Chena8bae822016-04-20 23:36:23 +0000528 return std::error_code();
529
Dehao Chen16f01fb2017-10-05 20:15:29 +0000530 // If a direct call/invoke instruction is inlined in profile
531 // (findCalleeFunctionSamples returns non-empty result), but not inlined here,
Dehao Chenc0a1e432016-08-12 16:22:12 +0000532 // it means that the inlined callsite has no sample, thus the call
533 // instruction should have 0 count.
Dehao Chenc632a392017-03-06 17:49:59 +0000534 if ((isa<CallInst>(Inst) || isa<InvokeInst>(Inst)) &&
Dehao Chen16f01fb2017-10-05 20:15:29 +0000535 !ImmutableCallSite(&Inst).isIndirectCall() &&
Dehao Chenc632a392017-03-06 17:49:59 +0000536 findCalleeFunctionSamples(Inst))
Dehao Chen41cde0b2016-09-18 23:11:37 +0000537 return 0;
Dehao Chenc0a1e432016-08-12 16:22:12 +0000538
Dehao Chen41dc5a62015-10-09 16:50:16 +0000539 const DILocation *DIL = DLoc;
Mircea Trofin56950972018-02-22 06:42:57 +0000540 uint32_t LineOffset = FunctionSamples::getOffset(DIL);
Dehao Chen533bc6e2017-02-23 18:27:45 +0000541 uint32_t Discriminator = DIL->getBaseDiscriminator();
Dehao Chenc632a392017-03-06 17:49:59 +0000542 ErrorOr<uint64_t> R = FS->findSamplesAt(LineOffset, Discriminator);
Diego Novillo748b3ffe2015-10-28 22:30:25 +0000543 if (R) {
Diego Novillof9ed08e2015-10-31 21:53:58 +0000544 bool FirstMark =
Diego Novillo243ea6a2015-11-23 20:12:21 +0000545 CoverageTracker.markSamplesUsed(FS, LineOffset, Discriminator, R.get());
Diego Novillof9ed08e2015-10-31 21:53:58 +0000546 if (FirstMark) {
Vivek Pandya95906582017-10-11 17:12:59 +0000547 ORE->emit([&]() {
548 OptimizationRemarkAnalysis Remark(DEBUG_TYPE, "AppliedSamples", &Inst);
549 Remark << "Applied " << ore::NV("NumSamples", *R);
550 Remark << " samples from profile (offset: ";
551 Remark << ore::NV("LineOffset", LineOffset);
552 if (Discriminator) {
553 Remark << ".";
554 Remark << ore::NV("Discriminator", Discriminator);
555 }
556 Remark << ")";
557 return Remark;
558 });
Diego Novillof9ed08e2015-10-31 21:53:58 +0000559 }
Dehao Chen533bc6e2017-02-23 18:27:45 +0000560 DEBUG(dbgs() << " " << DLoc.getLine() << "."
561 << DIL->getBaseDiscriminator() << ":" << Inst
562 << " (line offset: " << LineOffset << "."
563 << DIL->getBaseDiscriminator() << " - weight: " << R.get()
Dehao Chen8e7df832015-09-29 18:28:15 +0000564 << ")\n");
Diego Novillo748b3ffe2015-10-28 22:30:25 +0000565 }
Dehao Chen8e7df832015-09-29 18:28:15 +0000566 return R;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000567}
568
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000569/// Compute the weight of a basic block.
Diego Novillo0accb3d2014-01-10 23:23:46 +0000570///
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000571/// The weight of basic block \p BB is the maximum weight of all the
Dehao Chen8e7df832015-09-29 18:28:15 +0000572/// instructions in BB.
Diego Novillo0accb3d2014-01-10 23:23:46 +0000573///
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000574/// \param BB The basic block to query.
Diego Novillo0accb3d2014-01-10 23:23:46 +0000575///
Dehao Chen8e7df832015-09-29 18:28:15 +0000576/// \returns the weight for \p BB.
Dehao Chen94f369f2017-01-19 23:20:31 +0000577ErrorOr<uint64_t> SampleProfileLoader::getBlockWeight(const BasicBlock *BB) {
Dehao Chen160fbc32016-09-21 16:26:51 +0000578 uint64_t Max = 0;
579 bool HasWeight = false;
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000580 for (auto &I : BB->getInstList()) {
Diego Novillo38be3332015-10-15 16:36:21 +0000581 const ErrorOr<uint64_t> &R = getInstWeight(I);
Dehao Chen160fbc32016-09-21 16:26:51 +0000582 if (R) {
583 Max = std::max(Max, R.get());
584 HasWeight = true;
Dehao Chen8e7df832015-09-29 18:28:15 +0000585 }
Diego Novillo0accb3d2014-01-10 23:23:46 +0000586 }
Dehao Chen160fbc32016-09-21 16:26:51 +0000587 return HasWeight ? ErrorOr<uint64_t>(Max) : std::error_code();
Diego Novillo0accb3d2014-01-10 23:23:46 +0000588}
589
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000590/// Compute and store the weights of every basic block.
Diego Novillo0accb3d2014-01-10 23:23:46 +0000591///
592/// This populates the BlockWeights map by computing
593/// the weights of every basic block in the CFG.
594///
595/// \param F The function to query.
Diego Novillode1ab262014-09-09 12:40:50 +0000596bool SampleProfileLoader::computeBlockWeights(Function &F) {
Diego Novillo0accb3d2014-01-10 23:23:46 +0000597 bool Changed = false;
598 DEBUG(dbgs() << "Block weights\n");
Dehao Chen8e7df832015-09-29 18:28:15 +0000599 for (const auto &BB : F) {
Diego Novillo38be3332015-10-15 16:36:21 +0000600 ErrorOr<uint64_t> Weight = getBlockWeight(&BB);
Dehao Chen8e7df832015-09-29 18:28:15 +0000601 if (Weight) {
602 BlockWeights[&BB] = Weight.get();
Dehao Chen7c41dd62015-10-01 00:26:56 +0000603 VisitedBlocks.insert(&BB);
Dehao Chen8e7df832015-09-29 18:28:15 +0000604 Changed = true;
605 }
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000606 DEBUG(printBlockWeight(dbgs(), &BB));
Diego Novillo0accb3d2014-01-10 23:23:46 +0000607 }
608
609 return Changed;
610}
611
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000612/// Get the FunctionSamples for a call instruction.
Dehao Chen67226882015-09-30 00:42:46 +0000613///
Dehao Chen41cde0b2016-09-18 23:11:37 +0000614/// The FunctionSamples of a call/invoke instruction \p Inst is the inlined
Dehao Chen67226882015-09-30 00:42:46 +0000615/// instance in which that call instruction is calling to. It contains
616/// all samples that resides in the inlined instance. We first find the
617/// inlined instance in which the call instruction is from, then we
618/// traverse its children to find the callsite with the matching
Dehao Chen41cde0b2016-09-18 23:11:37 +0000619/// location.
Dehao Chen67226882015-09-30 00:42:46 +0000620///
Dehao Chen41cde0b2016-09-18 23:11:37 +0000621/// \param Inst Call/Invoke instruction to query.
Dehao Chen67226882015-09-30 00:42:46 +0000622///
623/// \returns The FunctionSamples pointer to the inlined instance.
624const FunctionSamples *
Dehao Chen41cde0b2016-09-18 23:11:37 +0000625SampleProfileLoader::findCalleeFunctionSamples(const Instruction &Inst) const {
Dehao Chen67226882015-09-30 00:42:46 +0000626 const DILocation *DIL = Inst.getDebugLoc();
627 if (!DIL) {
628 return nullptr;
629 }
Dehao Chen2c7ca9b2017-04-13 19:52:10 +0000630
631 StringRef CalleeName;
632 if (const CallInst *CI = dyn_cast<CallInst>(&Inst))
633 if (Function *Callee = CI->getCalledFunction())
634 CalleeName = Callee->getName();
635
Dehao Chen67226882015-09-30 00:42:46 +0000636 const FunctionSamples *FS = findFunctionSamples(Inst);
637 if (FS == nullptr)
638 return nullptr;
639
Mircea Trofin56950972018-02-22 06:42:57 +0000640 return FS->findFunctionSamplesAt(LineLocation(FunctionSamples::getOffset(DIL),
641 DIL->getBaseDiscriminator()),
642 CalleeName);
Dehao Chen2c7ca9b2017-04-13 19:52:10 +0000643}
644
645/// Returns a vector of FunctionSamples that are the indirect call targets
Dehao Chen3f56a052017-10-10 21:13:50 +0000646/// of \p Inst. The vector is sorted by the total number of samples. Stores
647/// the total call count of the indirect call in \p Sum.
Dehao Chen2c7ca9b2017-04-13 19:52:10 +0000648std::vector<const FunctionSamples *>
649SampleProfileLoader::findIndirectCallFunctionSamples(
Dehao Chen3f56a052017-10-10 21:13:50 +0000650 const Instruction &Inst, uint64_t &Sum) const {
Dehao Chen2c7ca9b2017-04-13 19:52:10 +0000651 const DILocation *DIL = Inst.getDebugLoc();
652 std::vector<const FunctionSamples *> R;
653
654 if (!DIL) {
655 return R;
656 }
657
658 const FunctionSamples *FS = findFunctionSamples(Inst);
659 if (FS == nullptr)
660 return R;
661
Mircea Trofin56950972018-02-22 06:42:57 +0000662 uint32_t LineOffset = FunctionSamples::getOffset(DIL);
Dehao Chen3f56a052017-10-10 21:13:50 +0000663 uint32_t Discriminator = DIL->getBaseDiscriminator();
664
665 auto T = FS->findCallTargetMapAt(LineOffset, Discriminator);
666 Sum = 0;
667 if (T)
668 for (const auto &T_C : T.get())
669 Sum += T_C.second;
Mircea Trofin56950972018-02-22 06:42:57 +0000670 if (const FunctionSamplesMap *M = FS->findFunctionSamplesMapAt(LineLocation(
671 FunctionSamples::getOffset(DIL), DIL->getBaseDiscriminator()))) {
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000672 if (M->empty())
Dehao Chen2c7ca9b2017-04-13 19:52:10 +0000673 return R;
674 for (const auto &NameFS : *M) {
Dehao Chen3f56a052017-10-10 21:13:50 +0000675 Sum += NameFS.second.getEntrySamples();
Dehao Chen2c7ca9b2017-04-13 19:52:10 +0000676 R.push_back(&NameFS.second);
677 }
Mandeep Singh Grang636d94d2018-04-13 19:47:57 +0000678 llvm::sort(R.begin(), R.end(),
679 [](const FunctionSamples *L, const FunctionSamples *R) {
680 return L->getEntrySamples() > R->getEntrySamples();
681 });
Dehao Chen2c7ca9b2017-04-13 19:52:10 +0000682 }
683 return R;
Dehao Chen67226882015-09-30 00:42:46 +0000684}
685
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000686/// Get the FunctionSamples for an instruction.
Dehao Chen67226882015-09-30 00:42:46 +0000687///
688/// The FunctionSamples of an instruction \p Inst is the inlined instance
689/// in which that instruction is coming from. We traverse the inline stack
690/// of that instruction, and match it with the tree nodes in the profile.
691///
692/// \param Inst Instruction to query.
693///
694/// \returns the FunctionSamples pointer to the inlined instance.
695const FunctionSamples *
696SampleProfileLoader::findFunctionSamples(const Instruction &Inst) const {
Dehao Chen2c7ca9b2017-04-13 19:52:10 +0000697 SmallVector<std::pair<LineLocation, StringRef>, 10> S;
Dehao Chen67226882015-09-30 00:42:46 +0000698 const DILocation *DIL = Inst.getDebugLoc();
Dehao Chen2c7ca9b2017-04-13 19:52:10 +0000699 if (!DIL)
Dehao Chen67226882015-09-30 00:42:46 +0000700 return Samples;
Dehao Chen2c7ca9b2017-04-13 19:52:10 +0000701
Mircea Trofin56950972018-02-22 06:42:57 +0000702 return Samples->findFunctionSamples(DIL);
Dehao Chen67226882015-09-30 00:42:46 +0000703}
704
Dehao Chen4f5d8302017-09-30 20:46:15 +0000705bool SampleProfileLoader::inlineCallInstruction(Instruction *I) {
706 assert(isa<CallInst>(I) || isa<InvokeInst>(I));
707 CallSite CS(I);
708 Function *CalledFunction = CS.getCalledFunction();
709 assert(CalledFunction);
710 DebugLoc DLoc = I->getDebugLoc();
711 BasicBlock *BB = I->getParent();
712 InlineParams Params = getInlineParams();
713 Params.ComputeFullInlineCost = true;
714 // Checks if there is anything in the reachable portion of the callee at
715 // this callsite that makes this inlining potentially illegal. Need to
716 // set ComputeFullInlineCost, otherwise getInlineCost may return early
717 // when cost exceeds threshold without checking all IRs in the callee.
718 // The acutal cost does not matter because we only checks isNever() to
719 // see if it is legal to inline the callsite.
720 InlineCost Cost = getInlineCost(CS, Params, GetTTI(*CalledFunction), GetAC,
721 None, nullptr, nullptr);
722 if (Cost.isNever()) {
723 ORE->emit(OptimizationRemark(DEBUG_TYPE, "Not inline", DLoc, BB)
724 << "incompatible inlining");
725 return false;
726 }
727 InlineFunctionInfo IFI(nullptr, &GetAC);
728 if (InlineFunction(CS, IFI)) {
729 // The call to InlineFunction erases I, so we can't pass it here.
730 ORE->emit(OptimizationRemark(DEBUG_TYPE, "HotInline", DLoc, BB)
731 << "inlined hot callee '" << ore::NV("Callee", CalledFunction)
732 << "' into '" << ore::NV("Caller", BB->getParent()) << "'");
733 return true;
734 }
735 return false;
736}
737
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000738/// Iteratively inline hot callsites of a function.
Dehao Chen67226882015-09-30 00:42:46 +0000739///
740/// Iteratively traverse all callsites of the function \p F, and find if
741/// the corresponding inlined instance exists and is hot in profile. If
742/// it is hot enough, inline the callsites and adds new callsites of the
Dehao Chen274df5e2017-01-31 17:49:37 +0000743/// callee into the caller. If the call is an indirect call, first promote
744/// it to direct call. Each indirect call is limited with a single target.
Dehao Chen67226882015-09-30 00:42:46 +0000745///
746/// \param F function to perform iterative inlining.
Dehao Chenc6c051f2017-11-01 20:26:47 +0000747/// \param InlinedGUIDs a set to be updated to include all GUIDs that are
748/// inlined in the profiled binary.
Dehao Chen67226882015-09-30 00:42:46 +0000749///
750/// \returns True if there is any inline happened.
Dehao Chena60cdd32017-02-28 18:09:44 +0000751bool SampleProfileLoader::inlineHotFunctions(
Dehao Chenc6c051f2017-11-01 20:26:47 +0000752 Function &F, DenseSet<GlobalValue::GUID> &InlinedGUIDs) {
Dehao Chen274df5e2017-01-31 17:49:37 +0000753 DenseSet<Instruction *> PromotedInsns;
Dehao Chen67226882015-09-30 00:42:46 +0000754 bool Changed = false;
755 while (true) {
756 bool LocalChanged = false;
Dehao Chen41cde0b2016-09-18 23:11:37 +0000757 SmallVector<Instruction *, 10> CIS;
Dehao Chen67226882015-09-30 00:42:46 +0000758 for (auto &BB : F) {
Dehao Chen20866ed2016-09-19 18:38:14 +0000759 bool Hot = false;
760 SmallVector<Instruction *, 10> Candidates;
Dehao Chen67226882015-09-30 00:42:46 +0000761 for (auto &I : BB.getInstList()) {
Dehao Chen41cde0b2016-09-18 23:11:37 +0000762 const FunctionSamples *FS = nullptr;
763 if ((isa<CallInst>(I) || isa<InvokeInst>(I)) &&
Andrea Di Biagioe3edef02017-04-18 10:08:53 +0000764 !isa<IntrinsicInst>(I) && (FS = findCalleeFunctionSamples(I))) {
Dehao Chen20866ed2016-09-19 18:38:14 +0000765 Candidates.push_back(&I);
Wei Mi0c2f6be2018-05-10 23:02:27 +0000766 if (callsiteIsHot(FS, PSI))
Dehao Chen20866ed2016-09-19 18:38:14 +0000767 Hot = true;
Dehao Chen41cde0b2016-09-18 23:11:37 +0000768 }
Dehao Chen67226882015-09-30 00:42:46 +0000769 }
Dehao Chen20866ed2016-09-19 18:38:14 +0000770 if (Hot) {
771 CIS.insert(CIS.begin(), Candidates.begin(), Candidates.end());
772 }
Dehao Chen67226882015-09-30 00:42:46 +0000773 }
Dehao Chen41cde0b2016-09-18 23:11:37 +0000774 for (auto I : CIS) {
Dehao Chen274df5e2017-01-31 17:49:37 +0000775 Function *CalledFunction = CallSite(I).getCalledFunction();
Dehao Chen50f2aa12017-06-21 17:57:43 +0000776 // Do not inline recursive calls.
777 if (CalledFunction == &F)
778 continue;
Dehao Chen4f5d8302017-09-30 20:46:15 +0000779 if (CallSite(I).isIndirectCall()) {
780 if (PromotedInsns.count(I))
781 continue;
Dehao Chen3f56a052017-10-10 21:13:50 +0000782 uint64_t Sum;
783 for (const auto *FS : findIndirectCallFunctionSamples(*I, Sum)) {
Dehao Chend26dae02017-10-01 05:24:51 +0000784 if (IsThinLTOPreLink) {
Dehao Chenc6c051f2017-11-01 20:26:47 +0000785 FS->findInlinedFunctions(InlinedGUIDs, F.getParent(),
Wei Mi0c2f6be2018-05-10 23:02:27 +0000786 PSI->getOrCompHotCountThreshold());
Dehao Chend26dae02017-10-01 05:24:51 +0000787 continue;
788 }
Dehao Chen2c7ca9b2017-04-13 19:52:10 +0000789 auto CalleeFunctionName = FS->getName();
Dehao Chene2a428b2017-06-08 20:11:57 +0000790 // If it is a recursive call, we do not inline it as it could bloat
791 // the code exponentially. There is way to better handle this, e.g.
792 // clone the caller first, and inline the cloned caller if it is
Dehao Chen4f5d8302017-09-30 20:46:15 +0000793 // recursive. As llvm does not inline recursive calls, we will
794 // simply ignore it instead of handling it explicitly.
Dehao Chene2a428b2017-06-08 20:11:57 +0000795 if (CalleeFunctionName == F.getName())
796 continue;
Dehao Chen4f5d8302017-09-30 20:46:15 +0000797
Dehao Chen2c7ca9b2017-04-13 19:52:10 +0000798 const char *Reason = "Callee function not available";
Dehao Chen1ea8bd82017-04-17 22:23:05 +0000799 auto R = SymbolMap.find(CalleeFunctionName);
Dehao Chen4f5d8302017-09-30 20:46:15 +0000800 if (R != SymbolMap.end() && R->getValue() &&
801 !R->getValue()->isDeclaration() &&
802 R->getValue()->getSubprogram() &&
Matthew Simpsone363d2c2017-12-06 21:22:54 +0000803 isLegalToPromote(CallSite(I), R->getValue(), &Reason)) {
Dehao Chen3f56a052017-10-10 21:13:50 +0000804 uint64_t C = FS->getEntrySamples();
Matthew Simpsone363d2c2017-12-06 21:22:54 +0000805 Instruction *DI =
806 pgo::promoteIndirectCall(I, R->getValue(), C, Sum, false, ORE);
Dehao Chen3f56a052017-10-10 21:13:50 +0000807 Sum -= C;
Dehao Chen2c7ca9b2017-04-13 19:52:10 +0000808 PromotedInsns.insert(I);
Dehao Chen4f5d8302017-09-30 20:46:15 +0000809 // If profile mismatches, we should not attempt to inline DI.
810 if ((isa<CallInst>(DI) || isa<InvokeInst>(DI)) &&
811 inlineCallInstruction(DI))
812 LocalChanged = true;
Dehao Chen2c7ca9b2017-04-13 19:52:10 +0000813 } else {
Dehao Chend26dae02017-10-01 05:24:51 +0000814 DEBUG(dbgs()
815 << "\nFailed to promote indirect call to "
816 << CalleeFunctionName << " because " << Reason << "\n");
Dehao Chen2c7ca9b2017-04-13 19:52:10 +0000817 }
Dehao Chen274df5e2017-01-31 17:49:37 +0000818 }
Dehao Chen4f5d8302017-09-30 20:46:15 +0000819 } else if (CalledFunction && CalledFunction->getSubprogram() &&
820 !CalledFunction->isDeclaration()) {
821 if (inlineCallInstruction(I))
822 LocalChanged = true;
Dehao Chend26dae02017-10-01 05:24:51 +0000823 } else if (IsThinLTOPreLink) {
Dehao Chenc6c051f2017-11-01 20:26:47 +0000824 findCalleeFunctionSamples(*I)->findInlinedFunctions(
Wei Mi0c2f6be2018-05-10 23:02:27 +0000825 InlinedGUIDs, F.getParent(), PSI->getOrCompHotCountThreshold());
Diego Novillo7963ea12015-10-26 18:52:53 +0000826 }
Dehao Chen67226882015-09-30 00:42:46 +0000827 }
828 if (LocalChanged) {
829 Changed = true;
830 } else {
831 break;
832 }
833 }
834 return Changed;
835}
836
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000837/// Find equivalence classes for the given block.
Diego Novillo0accb3d2014-01-10 23:23:46 +0000838///
839/// This finds all the blocks that are guaranteed to execute the same
Eric Christopher572e03a2015-06-19 01:53:21 +0000840/// number of times as \p BB1. To do this, it traverses all the
Diego Novillo0accb3d2014-01-10 23:23:46 +0000841/// descendants of \p BB1 in the dominator or post-dominator tree.
842///
843/// A block BB2 will be in the same equivalence class as \p BB1 if
844/// the following holds:
845///
846/// 1- \p BB1 is a descendant of BB2 in the opposite tree. So, if BB2
847/// is a descendant of \p BB1 in the dominator tree, then BB2 should
848/// dominate BB1 in the post-dominator tree.
849///
850/// 2- Both BB2 and \p BB1 must be in the same loop.
851///
852/// For every block BB2 that meets those two requirements, we set BB2's
853/// equivalence class to \p BB1.
854///
855/// \param BB1 Block to check.
856/// \param Descendants Descendants of \p BB1 in either the dom or pdom tree.
857/// \param DomTree Opposite dominator tree. If \p Descendants is filled
858/// with blocks from \p BB1's dominator tree, then
859/// this is the post-dominator tree, and vice versa.
Jakub Kuderskib292c222017-07-14 18:26:09 +0000860template <bool IsPostDom>
Diego Novillode1ab262014-09-09 12:40:50 +0000861void SampleProfileLoader::findEquivalencesFor(
Benjamin Kramer8a752e32016-02-13 16:01:12 +0000862 BasicBlock *BB1, ArrayRef<BasicBlock *> Descendants,
Jakub Kuderskib292c222017-07-14 18:26:09 +0000863 DominatorTreeBase<BasicBlock, IsPostDom> *DomTree) {
Dehao Chen7c41dd62015-10-01 00:26:56 +0000864 const BasicBlock *EC = EquivalenceClass[BB1];
Diego Novillo38be3332015-10-15 16:36:21 +0000865 uint64_t Weight = BlockWeights[EC];
Dehao Chen8e7df832015-09-29 18:28:15 +0000866 for (const auto *BB2 : Descendants) {
Diego Novillo0accb3d2014-01-10 23:23:46 +0000867 bool IsDomParent = DomTree->dominates(BB2, BB1);
868 bool IsInSameLoop = LI->getLoopFor(BB1) == LI->getLoopFor(BB2);
Dehao Chen7c41dd62015-10-01 00:26:56 +0000869 if (BB1 != BB2 && IsDomParent && IsInSameLoop) {
870 EquivalenceClass[BB2] = EC;
Dehao Chenc0a1e432016-08-12 16:22:12 +0000871 // If BB2 is visited, then the entire EC should be marked as visited.
872 if (VisitedBlocks.count(BB2)) {
873 VisitedBlocks.insert(EC);
874 }
Diego Novillo0accb3d2014-01-10 23:23:46 +0000875
876 // If BB2 is heavier than BB1, make BB2 have the same weight
877 // as BB1.
878 //
879 // Note that we don't worry about the opposite situation here
880 // (when BB2 is lighter than BB1). We will deal with this
881 // during the propagation phase. Right now, we just want to
882 // make sure that BB1 has the largest weight of all the
883 // members of its equivalence set.
Dehao Chen7c41dd62015-10-01 00:26:56 +0000884 Weight = std::max(Weight, BlockWeights[BB2]);
Diego Novillo0accb3d2014-01-10 23:23:46 +0000885 }
886 }
Dehao Chenc0a1e432016-08-12 16:22:12 +0000887 if (EC == &EC->getParent()->getEntryBlock()) {
888 BlockWeights[EC] = Samples->getHeadSamples() + 1;
889 } else {
890 BlockWeights[EC] = Weight;
891 }
Diego Novillo0accb3d2014-01-10 23:23:46 +0000892}
893
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000894/// Find equivalence classes.
Diego Novillo0accb3d2014-01-10 23:23:46 +0000895///
896/// Since samples may be missing from blocks, we can fill in the gaps by setting
897/// the weights of all the blocks in the same equivalence class to the same
898/// weight. To compute the concept of equivalence, we use dominance and loop
899/// information. Two blocks B1 and B2 are in the same equivalence class if B1
900/// dominates B2, B2 post-dominates B1 and both are in the same loop.
901///
902/// \param F The function to query.
Diego Novillode1ab262014-09-09 12:40:50 +0000903void SampleProfileLoader::findEquivalenceClasses(Function &F) {
Diego Novillo0accb3d2014-01-10 23:23:46 +0000904 SmallVector<BasicBlock *, 8> DominatedBBs;
905 DEBUG(dbgs() << "\nBlock equivalence classes\n");
906 // Find equivalence sets based on dominance and post-dominance information.
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000907 for (auto &BB : F) {
908 BasicBlock *BB1 = &BB;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000909
910 // Compute BB1's equivalence class once.
911 if (EquivalenceClass.count(BB1)) {
912 DEBUG(printBlockEquivalence(dbgs(), BB1));
913 continue;
914 }
915
916 // By default, blocks are in their own equivalence class.
917 EquivalenceClass[BB1] = BB1;
918
919 // Traverse all the blocks dominated by BB1. We are looking for
920 // every basic block BB2 such that:
921 //
922 // 1- BB1 dominates BB2.
923 // 2- BB2 post-dominates BB1.
924 // 3- BB1 and BB2 are in the same loop nest.
925 //
926 // If all those conditions hold, it means that BB2 is executed
927 // as many times as BB1, so they are placed in the same equivalence
928 // class by making BB2's equivalence class be BB1.
929 DominatedBBs.clear();
930 DT->getDescendants(BB1, DominatedBBs);
Diego Novillo7732ae42015-08-26 20:00:27 +0000931 findEquivalencesFor(BB1, DominatedBBs, PDT.get());
Diego Novillo0accb3d2014-01-10 23:23:46 +0000932
Diego Novillo0accb3d2014-01-10 23:23:46 +0000933 DEBUG(printBlockEquivalence(dbgs(), BB1));
934 }
935
936 // Assign weights to equivalence classes.
937 //
938 // All the basic blocks in the same equivalence class will execute
939 // the same number of times. Since we know that the head block in
940 // each equivalence class has the largest weight, assign that weight
941 // to all the blocks in that equivalence class.
942 DEBUG(dbgs() << "\nAssign the same weight to all blocks in the same class\n");
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000943 for (auto &BI : F) {
Dehao Chen8e7df832015-09-29 18:28:15 +0000944 const BasicBlock *BB = &BI;
945 const BasicBlock *EquivBB = EquivalenceClass[BB];
Diego Novillo0accb3d2014-01-10 23:23:46 +0000946 if (BB != EquivBB)
947 BlockWeights[BB] = BlockWeights[EquivBB];
948 DEBUG(printBlockWeight(dbgs(), BB));
949 }
950}
951
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000952/// Visit the given edge to decide if it has a valid weight.
Diego Novillo0accb3d2014-01-10 23:23:46 +0000953///
954/// If \p E has not been visited before, we copy to \p UnknownEdge
955/// and increment the count of unknown edges.
956///
957/// \param E Edge to visit.
958/// \param NumUnknownEdges Current number of unknown edges.
959/// \param UnknownEdge Set if E has not been visited before.
960///
961/// \returns E's weight, if known. Otherwise, return 0.
Diego Novillo38be3332015-10-15 16:36:21 +0000962uint64_t SampleProfileLoader::visitEdge(Edge E, unsigned *NumUnknownEdges,
Diego Novillode1ab262014-09-09 12:40:50 +0000963 Edge *UnknownEdge) {
Diego Novillo0accb3d2014-01-10 23:23:46 +0000964 if (!VisitedEdges.count(E)) {
965 (*NumUnknownEdges)++;
966 *UnknownEdge = E;
967 return 0;
968 }
969
970 return EdgeWeights[E];
971}
972
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000973/// Propagate weights through incoming/outgoing edges.
Diego Novillo0accb3d2014-01-10 23:23:46 +0000974///
975/// If the weight of a basic block is known, and there is only one edge
976/// with an unknown weight, we can calculate the weight of that edge.
977///
978/// Similarly, if all the edges have a known count, we can calculate the
979/// count of the basic block, if needed.
980///
981/// \param F Function to process.
Dehao Chenc0a1e432016-08-12 16:22:12 +0000982/// \param UpdateBlockCount Whether we should update basic block counts that
983/// has already been annotated.
Diego Novillo0accb3d2014-01-10 23:23:46 +0000984///
985/// \returns True if new weights were assigned to edges or blocks.
Dehao Chenc0a1e432016-08-12 16:22:12 +0000986bool SampleProfileLoader::propagateThroughEdges(Function &F,
987 bool UpdateBlockCount) {
Diego Novillo0accb3d2014-01-10 23:23:46 +0000988 bool Changed = false;
989 DEBUG(dbgs() << "\nPropagation through edges\n");
Dehao Chen7c41dd62015-10-01 00:26:56 +0000990 for (const auto &BI : F) {
991 const BasicBlock *BB = &BI;
992 const BasicBlock *EC = EquivalenceClass[BB];
Diego Novillo0accb3d2014-01-10 23:23:46 +0000993
994 // Visit all the predecessor and successor edges to determine
995 // which ones have a weight assigned already. Note that it doesn't
996 // matter that we only keep track of a single unknown edge. The
997 // only case we are interested in handling is when only a single
998 // edge is unknown (see setEdgeOrBlockWeight).
999 for (unsigned i = 0; i < 2; i++) {
Diego Novillo38be3332015-10-15 16:36:21 +00001000 uint64_t TotalWeight = 0;
Dehao Chen29d26412016-07-11 16:40:17 +00001001 unsigned NumUnknownEdges = 0, NumTotalEdges = 0;
1002 Edge UnknownEdge, SelfReferentialEdge, SingleEdge;
Diego Novillo0accb3d2014-01-10 23:23:46 +00001003
1004 if (i == 0) {
1005 // First, visit all predecessor edges.
Dehao Chen29d26412016-07-11 16:40:17 +00001006 NumTotalEdges = Predecessors[BB].size();
Diego Novillob368b7d2014-10-22 16:51:50 +00001007 for (auto *Pred : Predecessors[BB]) {
1008 Edge E = std::make_pair(Pred, BB);
Diego Novillo0accb3d2014-01-10 23:23:46 +00001009 TotalWeight += visitEdge(E, &NumUnknownEdges, &UnknownEdge);
1010 if (E.first == E.second)
1011 SelfReferentialEdge = E;
1012 }
Dehao Chen29d26412016-07-11 16:40:17 +00001013 if (NumTotalEdges == 1) {
1014 SingleEdge = std::make_pair(Predecessors[BB][0], BB);
1015 }
Diego Novillo0accb3d2014-01-10 23:23:46 +00001016 } else {
1017 // On the second round, visit all successor edges.
Dehao Chen29d26412016-07-11 16:40:17 +00001018 NumTotalEdges = Successors[BB].size();
Diego Novillob368b7d2014-10-22 16:51:50 +00001019 for (auto *Succ : Successors[BB]) {
1020 Edge E = std::make_pair(BB, Succ);
Diego Novillo0accb3d2014-01-10 23:23:46 +00001021 TotalWeight += visitEdge(E, &NumUnknownEdges, &UnknownEdge);
1022 }
Dehao Chen29d26412016-07-11 16:40:17 +00001023 if (NumTotalEdges == 1) {
1024 SingleEdge = std::make_pair(BB, Successors[BB][0]);
1025 }
Diego Novillo0accb3d2014-01-10 23:23:46 +00001026 }
1027
1028 // After visiting all the edges, there are three cases that we
1029 // can handle immediately:
1030 //
1031 // - All the edge weights are known (i.e., NumUnknownEdges == 0).
1032 // In this case, we simply check that the sum of all the edges
1033 // is the same as BB's weight. If not, we change BB's weight
1034 // to match. Additionally, if BB had not been visited before,
1035 // we mark it visited.
1036 //
1037 // - Only one edge is unknown and BB has already been visited.
1038 // In this case, we can compute the weight of the edge by
1039 // subtracting the total block weight from all the known
1040 // edge weights. If the edges weight more than BB, then the
1041 // edge of the last remaining edge is set to zero.
1042 //
1043 // - There exists a self-referential edge and the weight of BB is
1044 // known. In this case, this edge can be based on BB's weight.
1045 // We add up all the other known edges and set the weight on
1046 // the self-referential edge as we did in the previous case.
1047 //
1048 // In any other case, we must continue iterating. Eventually,
1049 // all edges will get a weight, or iteration will stop when
1050 // it reaches SampleProfileMaxPropagateIterations.
1051 if (NumUnknownEdges <= 1) {
Diego Novillo38be3332015-10-15 16:36:21 +00001052 uint64_t &BBWeight = BlockWeights[EC];
Diego Novillo0accb3d2014-01-10 23:23:46 +00001053 if (NumUnknownEdges == 0) {
Dehao Chen29d26412016-07-11 16:40:17 +00001054 if (!VisitedBlocks.count(EC)) {
1055 // If we already know the weight of all edges, the weight of the
1056 // basic block can be computed. It should be no larger than the sum
1057 // of all edge weights.
1058 if (TotalWeight > BBWeight) {
1059 BBWeight = TotalWeight;
1060 Changed = true;
1061 DEBUG(dbgs() << "All edge weights for " << BB->getName()
1062 << " known. Set weight for block: ";
1063 printBlockWeight(dbgs(), BB););
1064 }
1065 } else if (NumTotalEdges == 1 &&
1066 EdgeWeights[SingleEdge] < BlockWeights[EC]) {
1067 // If there is only one edge for the visited basic block, use the
1068 // block weight to adjust edge weight if edge weight is smaller.
1069 EdgeWeights[SingleEdge] = BlockWeights[EC];
Diego Novillo0accb3d2014-01-10 23:23:46 +00001070 Changed = true;
Diego Novillo0accb3d2014-01-10 23:23:46 +00001071 }
Dehao Chen7c41dd62015-10-01 00:26:56 +00001072 } else if (NumUnknownEdges == 1 && VisitedBlocks.count(EC)) {
Diego Novillo0accb3d2014-01-10 23:23:46 +00001073 // If there is a single unknown edge and the block has been
1074 // visited, then we can compute E's weight.
1075 if (BBWeight >= TotalWeight)
1076 EdgeWeights[UnknownEdge] = BBWeight - TotalWeight;
1077 else
1078 EdgeWeights[UnknownEdge] = 0;
Dehao Chenc0a1e432016-08-12 16:22:12 +00001079 const BasicBlock *OtherEC;
1080 if (i == 0)
1081 OtherEC = EquivalenceClass[UnknownEdge.first];
1082 else
1083 OtherEC = EquivalenceClass[UnknownEdge.second];
1084 // Edge weights should never exceed the BB weights it connects.
1085 if (VisitedBlocks.count(OtherEC) &&
1086 EdgeWeights[UnknownEdge] > BlockWeights[OtherEC])
1087 EdgeWeights[UnknownEdge] = BlockWeights[OtherEC];
Diego Novillo0accb3d2014-01-10 23:23:46 +00001088 VisitedEdges.insert(UnknownEdge);
1089 Changed = true;
1090 DEBUG(dbgs() << "Set weight for edge: ";
1091 printEdgeWeight(dbgs(), UnknownEdge));
1092 }
Dehao Chenc0a1e432016-08-12 16:22:12 +00001093 } else if (VisitedBlocks.count(EC) && BlockWeights[EC] == 0) {
1094 // If a block Weights 0, all its in/out edges should weight 0.
1095 if (i == 0) {
1096 for (auto *Pred : Predecessors[BB]) {
1097 Edge E = std::make_pair(Pred, BB);
1098 EdgeWeights[E] = 0;
1099 VisitedEdges.insert(E);
1100 }
1101 } else {
1102 for (auto *Succ : Successors[BB]) {
1103 Edge E = std::make_pair(BB, Succ);
1104 EdgeWeights[E] = 0;
1105 VisitedEdges.insert(E);
1106 }
1107 }
Dehao Chen7c41dd62015-10-01 00:26:56 +00001108 } else if (SelfReferentialEdge.first && VisitedBlocks.count(EC)) {
Diego Novillo38be3332015-10-15 16:36:21 +00001109 uint64_t &BBWeight = BlockWeights[BB];
Diego Novillo0accb3d2014-01-10 23:23:46 +00001110 // We have a self-referential edge and the weight of BB is known.
1111 if (BBWeight >= TotalWeight)
1112 EdgeWeights[SelfReferentialEdge] = BBWeight - TotalWeight;
1113 else
1114 EdgeWeights[SelfReferentialEdge] = 0;
1115 VisitedEdges.insert(SelfReferentialEdge);
1116 Changed = true;
1117 DEBUG(dbgs() << "Set self-referential edge weight to: ";
1118 printEdgeWeight(dbgs(), SelfReferentialEdge));
1119 }
Dehao Chenc0a1e432016-08-12 16:22:12 +00001120 if (UpdateBlockCount && !VisitedBlocks.count(EC) && TotalWeight > 0) {
1121 BlockWeights[EC] = TotalWeight;
1122 VisitedBlocks.insert(EC);
1123 Changed = true;
1124 }
Diego Novillo0accb3d2014-01-10 23:23:46 +00001125 }
1126 }
1127
1128 return Changed;
1129}
1130
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001131/// Build in/out edge lists for each basic block in the CFG.
Diego Novillo0accb3d2014-01-10 23:23:46 +00001132///
1133/// We are interested in unique edges. If a block B1 has multiple
1134/// edges to another block B2, we only add a single B1->B2 edge.
Diego Novillode1ab262014-09-09 12:40:50 +00001135void SampleProfileLoader::buildEdges(Function &F) {
Diego Novillo19e7b7e2014-10-22 18:39:50 +00001136 for (auto &BI : F) {
1137 BasicBlock *B1 = &BI;
Diego Novillo0accb3d2014-01-10 23:23:46 +00001138
1139 // Add predecessors for B1.
1140 SmallPtrSet<BasicBlock *, 16> Visited;
1141 if (!Predecessors[B1].empty())
1142 llvm_unreachable("Found a stale predecessors list in a basic block.");
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001143 for (pred_iterator PI = pred_begin(B1), PE = pred_end(B1); PI != PE; ++PI) {
1144 BasicBlock *B2 = *PI;
David Blaikie70573dc2014-11-19 07:49:26 +00001145 if (Visited.insert(B2).second)
Diego Novillo0accb3d2014-01-10 23:23:46 +00001146 Predecessors[B1].push_back(B2);
1147 }
1148
1149 // Add successors for B1.
1150 Visited.clear();
1151 if (!Successors[B1].empty())
1152 llvm_unreachable("Found a stale successors list in a basic block.");
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001153 for (succ_iterator SI = succ_begin(B1), SE = succ_end(B1); SI != SE; ++SI) {
1154 BasicBlock *B2 = *SI;
David Blaikie70573dc2014-11-19 07:49:26 +00001155 if (Visited.insert(B2).second)
Diego Novillo0accb3d2014-01-10 23:23:46 +00001156 Successors[B1].push_back(B2);
1157 }
1158 }
1159}
1160
Dehao Chen5d2a1a52017-11-06 19:52:49 +00001161/// Returns the sorted CallTargetMap \p M by count in descending order.
1162static SmallVector<InstrProfValueData, 2> SortCallTargets(
1163 const SampleRecord::CallTargetMap &M) {
1164 SmallVector<InstrProfValueData, 2> R;
1165 for (auto I = M.begin(); I != M.end(); ++I)
1166 R.push_back({Function::getGUID(I->getKey()), I->getValue()});
Mandeep Singh Grang636d94d2018-04-13 19:47:57 +00001167 llvm::sort(R.begin(), R.end(),
1168 [](const InstrProfValueData &L, const InstrProfValueData &R) {
1169 if (L.Count == R.Count)
1170 return L.Value > R.Value;
1171 else
1172 return L.Count > R.Count;
1173 });
Dehao Chen5d2a1a52017-11-06 19:52:49 +00001174 return R;
Dehao Chen77079002017-01-20 22:56:07 +00001175}
1176
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001177/// Propagate weights into edges
Diego Novillo0accb3d2014-01-10 23:23:46 +00001178///
Diego Novillo19e7b7e2014-10-22 18:39:50 +00001179/// The following rules are applied to every block BB in the CFG:
Diego Novillo0accb3d2014-01-10 23:23:46 +00001180///
Diego Novillo19e7b7e2014-10-22 18:39:50 +00001181/// - If BB has a single predecessor/successor, then the weight
Diego Novillo0accb3d2014-01-10 23:23:46 +00001182/// of that edge is the weight of the block.
1183///
1184/// - If all incoming or outgoing edges are known except one, and the
1185/// weight of the block is already known, the weight of the unknown
1186/// edge will be the weight of the block minus the sum of all the known
Diego Novillo19e7b7e2014-10-22 18:39:50 +00001187/// edges. If the sum of all the known edges is larger than BB's weight,
Diego Novillo0accb3d2014-01-10 23:23:46 +00001188/// we set the unknown edge weight to zero.
1189///
1190/// - If there is a self-referential edge, and the weight of the block is
1191/// known, the weight for that edge is set to the weight of the block
1192/// minus the weight of the other incoming edges to that block (if
1193/// known).
Diego Novillode1ab262014-09-09 12:40:50 +00001194void SampleProfileLoader::propagateWeights(Function &F) {
Diego Novillo0accb3d2014-01-10 23:23:46 +00001195 bool Changed = true;
Diego Novillo38be3332015-10-15 16:36:21 +00001196 unsigned I = 0;
Diego Novillo0accb3d2014-01-10 23:23:46 +00001197
Dehao Chenc0a1e432016-08-12 16:22:12 +00001198 // If BB weight is larger than its corresponding loop's header BB weight,
1199 // use the BB weight to replace the loop header BB weight.
1200 for (auto &BI : F) {
1201 BasicBlock *BB = &BI;
1202 Loop *L = LI->getLoopFor(BB);
1203 if (!L) {
1204 continue;
1205 }
1206 BasicBlock *Header = L->getHeader();
1207 if (Header && BlockWeights[BB] > BlockWeights[Header]) {
1208 BlockWeights[Header] = BlockWeights[BB];
1209 }
1210 }
Diego Novilloffc84e32015-05-13 17:04:29 +00001211
Diego Novillo0accb3d2014-01-10 23:23:46 +00001212 // Before propagation starts, build, for each block, a list of
1213 // unique predecessors and successors. This is necessary to handle
1214 // identical edges in multiway branches. Since we visit all blocks and all
1215 // edges of the CFG, it is cleaner to build these lists once at the start
1216 // of the pass.
1217 buildEdges(F);
1218
1219 // Propagate until we converge or we go past the iteration limit.
Diego Novillo38be3332015-10-15 16:36:21 +00001220 while (Changed && I++ < SampleProfileMaxPropagateIterations) {
Dehao Chenc0a1e432016-08-12 16:22:12 +00001221 Changed = propagateThroughEdges(F, false);
1222 }
1223
1224 // The first propagation propagates BB counts from annotated BBs to unknown
1225 // BBs. The 2nd propagation pass resets edges weights, and use all BB weights
1226 // to propagate edge weights.
1227 VisitedEdges.clear();
1228 Changed = true;
1229 while (Changed && I++ < SampleProfileMaxPropagateIterations) {
1230 Changed = propagateThroughEdges(F, false);
1231 }
1232
1233 // The 3rd propagation pass allows adjust annotated BB weights that are
1234 // obviously wrong.
1235 Changed = true;
1236 while (Changed && I++ < SampleProfileMaxPropagateIterations) {
1237 Changed = propagateThroughEdges(F, true);
Diego Novillo0accb3d2014-01-10 23:23:46 +00001238 }
1239
1240 // Generate MD_prof metadata for every branch instruction using the
1241 // edge weights computed during propagation.
1242 DEBUG(dbgs() << "\nPropagation complete. Setting branch weights\n");
Diego Novillo7963ea12015-10-26 18:52:53 +00001243 LLVMContext &Ctx = F.getContext();
1244 MDBuilder MDB(Ctx);
Diego Novillo19e7b7e2014-10-22 18:39:50 +00001245 for (auto &BI : F) {
1246 BasicBlock *BB = &BI;
Dehao Chen9232f982016-07-11 16:48:54 +00001247
1248 if (BlockWeights[BB]) {
1249 for (auto &I : BB->getInstList()) {
Dehao Chen77079002017-01-20 22:56:07 +00001250 if (!isa<CallInst>(I) && !isa<InvokeInst>(I))
1251 continue;
1252 CallSite CS(&I);
1253 if (!CS.getCalledFunction()) {
1254 const DebugLoc &DLoc = I.getDebugLoc();
1255 if (!DLoc)
1256 continue;
1257 const DILocation *DIL = DLoc;
Mircea Trofin56950972018-02-22 06:42:57 +00001258 uint32_t LineOffset = FunctionSamples::getOffset(DIL);
Dehao Chen533bc6e2017-02-23 18:27:45 +00001259 uint32_t Discriminator = DIL->getBaseDiscriminator();
Dehao Chen77079002017-01-20 22:56:07 +00001260
1261 const FunctionSamples *FS = findFunctionSamples(I);
1262 if (!FS)
1263 continue;
1264 auto T = FS->findCallTargetMapAt(LineOffset, Discriminator);
Eugene Zelenkof27d1612017-10-19 21:21:30 +00001265 if (!T || T.get().empty())
Dehao Chen77079002017-01-20 22:56:07 +00001266 continue;
Dehao Chen5d2a1a52017-11-06 19:52:49 +00001267 SmallVector<InstrProfValueData, 2> SortedCallTargets =
1268 SortCallTargets(T.get());
1269 uint64_t Sum;
1270 findIndirectCallFunctionSamples(I, Sum);
Dehao Chen77079002017-01-20 22:56:07 +00001271 annotateValueSite(*I.getParent()->getParent()->getParent(), I,
1272 SortedCallTargets, Sum, IPVK_IndirectCallTarget,
1273 SortedCallTargets.size());
1274 } else if (!dyn_cast<IntrinsicInst>(&I)) {
1275 SmallVector<uint32_t, 1> Weights;
1276 Weights.push_back(BlockWeights[BB]);
1277 I.setMetadata(LLVMContext::MD_prof, MDB.createBranchWeights(Weights));
Dehao Chen9232f982016-07-11 16:48:54 +00001278 }
1279 }
1280 }
Diego Novillo19e7b7e2014-10-22 18:39:50 +00001281 TerminatorInst *TI = BB->getTerminator();
Diego Novillo0accb3d2014-01-10 23:23:46 +00001282 if (TI->getNumSuccessors() == 1)
1283 continue;
1284 if (!isa<BranchInst>(TI) && !isa<SwitchInst>(TI))
1285 continue;
1286
Andrea Di Biagio517e3fc2017-04-18 11:27:58 +00001287 DebugLoc BranchLoc = TI->getDebugLoc();
Diego Novillo0accb3d2014-01-10 23:23:46 +00001288 DEBUG(dbgs() << "\nGetting weights for branch at line "
Andrea Di Biagio517e3fc2017-04-18 11:27:58 +00001289 << ((BranchLoc) ? Twine(BranchLoc.getLine())
1290 : Twine("<UNKNOWN LOCATION>"))
1291 << ".\n");
Diego Novillo38be3332015-10-15 16:36:21 +00001292 SmallVector<uint32_t, 4> Weights;
Diego Novillo7963ea12015-10-26 18:52:53 +00001293 uint32_t MaxWeight = 0;
Eli Friedman51cf2602017-08-11 21:12:04 +00001294 Instruction *MaxDestInst;
Diego Novillo0accb3d2014-01-10 23:23:46 +00001295 for (unsigned I = 0; I < TI->getNumSuccessors(); ++I) {
1296 BasicBlock *Succ = TI->getSuccessor(I);
Diego Novillo19e7b7e2014-10-22 18:39:50 +00001297 Edge E = std::make_pair(BB, Succ);
Diego Novillo38be3332015-10-15 16:36:21 +00001298 uint64_t Weight = EdgeWeights[E];
Diego Novillo0accb3d2014-01-10 23:23:46 +00001299 DEBUG(dbgs() << "\t"; printEdgeWeight(dbgs(), E));
Diego Novillo38be3332015-10-15 16:36:21 +00001300 // Use uint32_t saturated arithmetic to adjust the incoming weights,
1301 // if needed. Sample counts in profiles are 64-bit unsigned values,
1302 // but internally branch weights are expressed as 32-bit values.
1303 if (Weight > std::numeric_limits<uint32_t>::max()) {
1304 DEBUG(dbgs() << " (saturated due to uint32_t overflow)");
1305 Weight = std::numeric_limits<uint32_t>::max();
1306 }
Dehao Chenc0a1e432016-08-12 16:22:12 +00001307 // Weight is added by one to avoid propagation errors introduced by
1308 // 0 weights.
1309 Weights.push_back(static_cast<uint32_t>(Weight + 1));
Diego Novillo7963ea12015-10-26 18:52:53 +00001310 if (Weight != 0) {
1311 if (Weight > MaxWeight) {
1312 MaxWeight = Weight;
Eli Friedman51cf2602017-08-11 21:12:04 +00001313 MaxDestInst = Succ->getFirstNonPHIOrDbgOrLifetime();
Diego Novillo7963ea12015-10-26 18:52:53 +00001314 }
1315 }
Diego Novillo0accb3d2014-01-10 23:23:46 +00001316 }
1317
Dehao Chen53a0c082017-03-23 14:43:10 +00001318 uint64_t TempWeight;
Diego Novillo0accb3d2014-01-10 23:23:46 +00001319 // Only set weights if there is at least one non-zero weight.
1320 // In any other case, let the analyzer set weights.
Dehao Chen53a0c082017-03-23 14:43:10 +00001321 // Do not set weights if the weights are present. In ThinLTO, the profile
1322 // annotation is done twice. If the first annotation already set the
1323 // weights, the second pass does not need to set it.
1324 if (MaxWeight > 0 && !TI->extractProfTotalWeight(TempWeight)) {
Dehao Chen82667d02016-09-19 16:33:41 +00001325 DEBUG(dbgs() << "SUCCESS. Found non-zero weights.\n");
Eugene Zelenkof27d1612017-10-19 21:21:30 +00001326 TI->setMetadata(LLVMContext::MD_prof,
Dehao Chen82667d02016-09-19 16:33:41 +00001327 MDB.createBranchWeights(Weights));
Vivek Pandya95906582017-10-11 17:12:59 +00001328 ORE->emit([&]() {
1329 return OptimizationRemark(DEBUG_TYPE, "PopularDest", MaxDestInst)
1330 << "most popular destination for conditional branches at "
1331 << ore::NV("CondBranchesLoc", BranchLoc);
1332 });
Dehao Chen82667d02016-09-19 16:33:41 +00001333 } else {
1334 DEBUG(dbgs() << "SKIPPED. All branch weights are zero.\n");
1335 }
Diego Novillo0accb3d2014-01-10 23:23:46 +00001336 }
1337}
1338
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001339/// Get the line number for the function header.
Diego Novillo0accb3d2014-01-10 23:23:46 +00001340///
1341/// This looks up function \p F in the current compilation unit and
1342/// retrieves the line number where the function is defined. This is
1343/// line 0 for all the samples read from the profile file. Every line
1344/// number is relative to this line.
1345///
1346/// \param F Function object to query.
1347///
Diego Novilloa32aa322014-03-14 21:58:59 +00001348/// \returns the line number where \p F is defined. If it returns 0,
1349/// it means that there is no debug information available for \p F.
Diego Novillode1ab262014-09-09 12:40:50 +00001350unsigned SampleProfileLoader::getFunctionLoc(Function &F) {
Pete Cooperadebb932016-03-11 02:14:16 +00001351 if (DISubprogram *S = F.getSubprogram())
Duncan P. N. Exon Smith537b4a82015-04-14 03:40:37 +00001352 return S->getLine();
Diego Novillo0accb3d2014-01-10 23:23:46 +00001353
Diego Novilloaa555072015-10-27 18:41:46 +00001354 // If the start of \p F is missing, emit a diagnostic to inform the user
Diego Novillo8027b802014-10-22 12:59:00 +00001355 // about the missed opportunity.
David Blaikie61079682014-03-16 01:36:18 +00001356 F.getContext().diagnose(DiagnosticInfoSampleProfile(
Diego Novilloa67c0b42014-10-22 13:36:35 +00001357 "No debug information found in function " + F.getName() +
1358 ": Function profile not used",
1359 DS_Warning));
Diego Novilloa32aa322014-03-14 21:58:59 +00001360 return 0;
Diego Novillo0accb3d2014-01-10 23:23:46 +00001361}
1362
Diego Novillo7732ae42015-08-26 20:00:27 +00001363void SampleProfileLoader::computeDominanceAndLoopInfo(Function &F) {
1364 DT.reset(new DominatorTree);
1365 DT->recalculate(F);
1366
Jakub Kuderskib292c222017-07-14 18:26:09 +00001367 PDT.reset(new PostDomTreeBase<BasicBlock>());
Diego Novillo7732ae42015-08-26 20:00:27 +00001368 PDT->recalculate(F);
1369
1370 LI.reset(new LoopInfo);
1371 LI->analyze(*DT);
1372}
1373
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001374/// Generate branch weight metadata for all branches in \p F.
Diego Novillo0accb3d2014-01-10 23:23:46 +00001375///
1376/// Branch weights are computed out of instruction samples using a
1377/// propagation heuristic. Propagation proceeds in 3 phases:
1378///
1379/// 1- Assignment of block weights. All the basic blocks in the function
1380/// are initial assigned the same weight as their most frequently
1381/// executed instruction.
1382///
1383/// 2- Creation of equivalence classes. Since samples may be missing from
1384/// blocks, we can fill in the gaps by setting the weights of all the
1385/// blocks in the same equivalence class to the same weight. To compute
1386/// the concept of equivalence, we use dominance and loop information.
1387/// Two blocks B1 and B2 are in the same equivalence class if B1
1388/// dominates B2, B2 post-dominates B1 and both are in the same loop.
1389///
1390/// 3- Propagation of block weights into edges. This uses a simple
1391/// propagation heuristic. The following rules are applied to every
Diego Novillo19e7b7e2014-10-22 18:39:50 +00001392/// block BB in the CFG:
Diego Novillo0accb3d2014-01-10 23:23:46 +00001393///
Diego Novillo19e7b7e2014-10-22 18:39:50 +00001394/// - If BB has a single predecessor/successor, then the weight
Diego Novillo0accb3d2014-01-10 23:23:46 +00001395/// of that edge is the weight of the block.
1396///
1397/// - If all the edges are known except one, and the weight of the
1398/// block is already known, the weight of the unknown edge will
1399/// be the weight of the block minus the sum of all the known
Diego Novillo19e7b7e2014-10-22 18:39:50 +00001400/// edges. If the sum of all the known edges is larger than BB's weight,
Diego Novillo0accb3d2014-01-10 23:23:46 +00001401/// we set the unknown edge weight to zero.
1402///
1403/// - If there is a self-referential edge, and the weight of the block is
1404/// known, the weight for that edge is set to the weight of the block
1405/// minus the weight of the other incoming edges to that block (if
1406/// known).
1407///
1408/// Since this propagation is not guaranteed to finalize for every CFG, we
1409/// only allow it to proceed for a limited number of iterations (controlled
1410/// by -sample-profile-max-propagate-iterations).
1411///
1412/// FIXME: Try to replace this propagation heuristic with a scheme
1413/// that is guaranteed to finalize. A work-list approach similar to
1414/// the standard value propagation algorithm used by SSA-CCP might
1415/// work here.
1416///
1417/// Once all the branch weights are computed, we emit the MD_prof
Diego Novillo19e7b7e2014-10-22 18:39:50 +00001418/// metadata on BB using the computed values for each of its branches.
Diego Novillo0accb3d2014-01-10 23:23:46 +00001419///
1420/// \param F The function to query.
Diego Novilloa32aa322014-03-14 21:58:59 +00001421///
1422/// \returns true if \p F was modified. Returns false, otherwise.
Diego Novillode1ab262014-09-09 12:40:50 +00001423bool SampleProfileLoader::emitAnnotations(Function &F) {
Diego Novillo0accb3d2014-01-10 23:23:46 +00001424 bool Changed = false;
1425
Dehao Chen41dc5a62015-10-09 16:50:16 +00001426 if (getFunctionLoc(F) == 0)
Diego Novilloa32aa322014-03-14 21:58:59 +00001427 return false;
1428
Diego Novillo0accb3d2014-01-10 23:23:46 +00001429 DEBUG(dbgs() << "Line number for the first instruction in " << F.getName()
Dehao Chen41dc5a62015-10-09 16:50:16 +00001430 << ": " << getFunctionLoc(F) << "\n");
Diego Novillo0accb3d2014-01-10 23:23:46 +00001431
Dehao Chenc6c051f2017-11-01 20:26:47 +00001432 DenseSet<GlobalValue::GUID> InlinedGUIDs;
1433 Changed |= inlineHotFunctions(F, InlinedGUIDs);
Dehao Chen67226882015-09-30 00:42:46 +00001434
Diego Novillo0accb3d2014-01-10 23:23:46 +00001435 // Compute basic block weights.
1436 Changed |= computeBlockWeights(F);
1437
1438 if (Changed) {
Dehao Chena60cdd32017-02-28 18:09:44 +00001439 // Add an entry count to the function using the samples gathered at the
Dehao Chenc6c051f2017-11-01 20:26:47 +00001440 // function entry.
1441 // Sets the GUIDs that are inlined in the profiled binary. This is used
1442 // for ThinLink to make correct liveness analysis, and also make the IR
1443 // match the profiled binary before annotation.
Easwaran Ramane5b8de22018-01-17 22:24:23 +00001444 F.setEntryCount(
1445 ProfileCount(Samples->getHeadSamples() + 1, Function::PCT_Real),
1446 &InlinedGUIDs);
Dehao Chena60cdd32017-02-28 18:09:44 +00001447
Diego Novillo7732ae42015-08-26 20:00:27 +00001448 // Compute dominance and loop info needed for propagation.
1449 computeDominanceAndLoopInfo(F);
1450
Diego Novillo0accb3d2014-01-10 23:23:46 +00001451 // Find equivalence classes.
1452 findEquivalenceClasses(F);
1453
1454 // Propagate weights to all edges.
1455 propagateWeights(F);
1456 }
1457
Diego Novillof9ed08e2015-10-31 21:53:58 +00001458 // If coverage checking was requested, compute it now.
Diego Novillo243ea6a2015-11-23 20:12:21 +00001459 if (SampleProfileRecordCoverage) {
Wei Mi0c2f6be2018-05-10 23:02:27 +00001460 unsigned Used = CoverageTracker.countUsedRecords(Samples, PSI);
1461 unsigned Total = CoverageTracker.countBodyRecords(Samples, PSI);
Diego Novillof9ed08e2015-10-31 21:53:58 +00001462 unsigned Coverage = CoverageTracker.computeCoverage(Used, Total);
Diego Novillo243ea6a2015-11-23 20:12:21 +00001463 if (Coverage < SampleProfileRecordCoverage) {
Diego Novillof9ed08e2015-10-31 21:53:58 +00001464 F.getContext().diagnose(DiagnosticInfoSampleProfile(
Pete Cooperadebb932016-03-11 02:14:16 +00001465 F.getSubprogram()->getFilename(), getFunctionLoc(F),
Diego Novillof9ed08e2015-10-31 21:53:58 +00001466 Twine(Used) + " of " + Twine(Total) + " available profile records (" +
1467 Twine(Coverage) + "%) were applied",
1468 DS_Warning));
1469 }
1470 }
1471
Diego Novillo243ea6a2015-11-23 20:12:21 +00001472 if (SampleProfileSampleCoverage) {
1473 uint64_t Used = CoverageTracker.getTotalUsedSamples();
Wei Mi0c2f6be2018-05-10 23:02:27 +00001474 uint64_t Total = CoverageTracker.countBodySamples(Samples, PSI);
Diego Novillo243ea6a2015-11-23 20:12:21 +00001475 unsigned Coverage = CoverageTracker.computeCoverage(Used, Total);
1476 if (Coverage < SampleProfileSampleCoverage) {
1477 F.getContext().diagnose(DiagnosticInfoSampleProfile(
Pete Cooperadebb932016-03-11 02:14:16 +00001478 F.getSubprogram()->getFilename(), getFunctionLoc(F),
Diego Novillo243ea6a2015-11-23 20:12:21 +00001479 Twine(Used) + " of " + Twine(Total) + " available profile samples (" +
1480 Twine(Coverage) + "%) were applied",
1481 DS_Warning));
1482 }
1483 }
Diego Novillo0accb3d2014-01-10 23:23:46 +00001484 return Changed;
1485}
1486
Xinliang David Lie897edb2016-05-27 22:30:44 +00001487char SampleProfileLoaderLegacyPass::ID = 0;
Eugene Zelenkof27d1612017-10-19 21:21:30 +00001488
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001489INITIALIZE_PASS_BEGIN(SampleProfileLoaderLegacyPass, "sample-profile",
1490 "Sample Profile loader", false, false)
1491INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Dehao Chen3a81f842017-09-14 17:29:56 +00001492INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
Wei Mi0c2f6be2018-05-10 23:02:27 +00001493INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001494INITIALIZE_PASS_END(SampleProfileLoaderLegacyPass, "sample-profile",
1495 "Sample Profile loader", false, false)
Diego Novilloc0dd1032013-11-26 20:37:33 +00001496
1497bool SampleProfileLoader::doInitialization(Module &M) {
Diego Novillo7732ae42015-08-26 20:00:27 +00001498 auto &Ctx = M.getContext();
Diego Novillo4d711132015-08-25 15:25:11 +00001499 auto ReaderOrErr = SampleProfileReader::create(Filename, Ctx);
Diego Novillofcd55602014-11-03 00:51:45 +00001500 if (std::error_code EC = ReaderOrErr.getError()) {
Diego Novilloc572e922014-10-30 18:00:06 +00001501 std::string Msg = "Could not open profile: " + EC.message();
David Blaikie2297a912015-11-02 20:01:13 +00001502 Ctx.diagnose(DiagnosticInfoSampleProfile(Filename, Msg));
Diego Novilloc572e922014-10-30 18:00:06 +00001503 return false;
1504 }
Diego Novillofcd55602014-11-03 00:51:45 +00001505 Reader = std::move(ReaderOrErr.get());
Diego Novilloc572e922014-10-30 18:00:06 +00001506 ProfileIsValid = (Reader->read() == sampleprof_error::success);
Diego Novilloc0dd1032013-11-26 20:37:33 +00001507 return true;
1508}
1509
Diego Novillo4d711132015-08-25 15:25:11 +00001510ModulePass *llvm::createSampleProfileLoaderPass() {
Xinliang David Lie897edb2016-05-27 22:30:44 +00001511 return new SampleProfileLoaderLegacyPass(SampleProfileFile);
Diego Novilloc0dd1032013-11-26 20:37:33 +00001512}
1513
Diego Novillo4d711132015-08-25 15:25:11 +00001514ModulePass *llvm::createSampleProfileLoaderPass(StringRef Name) {
Xinliang David Lie897edb2016-05-27 22:30:44 +00001515 return new SampleProfileLoaderLegacyPass(Name);
Diego Novilloc0dd1032013-11-26 20:37:33 +00001516}
1517
Wei Mi0c2f6be2018-05-10 23:02:27 +00001518bool SampleProfileLoader::runOnModule(Module &M, ModuleAnalysisManager *AM,
1519 ProfileSummaryInfo *_PSI) {
Diego Novilloa8a3bd22015-10-28 17:40:22 +00001520 if (!ProfileIsValid)
1521 return false;
1522
Wei Mi0c2f6be2018-05-10 23:02:27 +00001523 PSI = _PSI;
1524 if (M.getProfileSummary() == nullptr)
1525 M.setProfileSummary(Reader->getSummary().getMD(M.getContext()));
1526
Diego Novillo84f06cc2015-11-27 23:14:51 +00001527 // Compute the total number of samples collected in this profile.
1528 for (const auto &I : Reader->getProfiles())
1529 TotalCollectedSamples += I.second.getTotalSamples();
1530
Dehao Chen1ea8bd82017-04-17 22:23:05 +00001531 // Populate the symbol map.
1532 for (const auto &N_F : M.getValueSymbolTable()) {
Benjamin Kramer24cb28b2017-12-28 18:10:41 +00001533 StringRef OrigName = N_F.getKey();
Dehao Chen1ea8bd82017-04-17 22:23:05 +00001534 Function *F = dyn_cast<Function>(N_F.getValue());
1535 if (F == nullptr)
1536 continue;
1537 SymbolMap[OrigName] = F;
1538 auto pos = OrigName.find('.');
Benjamin Kramer24cb28b2017-12-28 18:10:41 +00001539 if (pos != StringRef::npos) {
1540 StringRef NewName = OrigName.substr(0, pos);
Dehao Chen1ea8bd82017-04-17 22:23:05 +00001541 auto r = SymbolMap.insert(std::make_pair(NewName, F));
1542 // Failiing to insert means there is already an entry in SymbolMap,
1543 // thus there are multiple functions that are mapped to the same
1544 // stripped name. In this case of name conflicting, set the value
1545 // to nullptr to avoid confusion.
1546 if (!r.second)
1547 r.first->second = nullptr;
1548 }
1549 }
1550
Diego Novillo4d711132015-08-25 15:25:11 +00001551 bool retval = false;
1552 for (auto &F : M)
Diego Novilloa8a3bd22015-10-28 17:40:22 +00001553 if (!F.isDeclaration()) {
1554 clearFunctionData();
Eli Friedman51cf2602017-08-11 21:12:04 +00001555 retval |= runOnFunction(F, AM);
Diego Novilloa8a3bd22015-10-28 17:40:22 +00001556 }
Diego Novillo4d711132015-08-25 15:25:11 +00001557 return retval;
1558}
1559
Xinliang David Lie897edb2016-05-27 22:30:44 +00001560bool SampleProfileLoaderLegacyPass::runOnModule(Module &M) {
Dehao Chenf3ed14d2017-09-12 21:55:55 +00001561 ACT = &getAnalysis<AssumptionCacheTracker>();
Dehao Chen3a81f842017-09-14 17:29:56 +00001562 TTIWP = &getAnalysis<TargetTransformInfoWrapperPass>();
Wei Mi0c2f6be2018-05-10 23:02:27 +00001563 ProfileSummaryInfo *PSI =
1564 getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
1565 return SampleLoader.runOnModule(M, nullptr, PSI);
Xinliang David Lie897edb2016-05-27 22:30:44 +00001566}
1567
Eli Friedman51cf2602017-08-11 21:12:04 +00001568bool SampleProfileLoader::runOnFunction(Function &F, ModuleAnalysisManager *AM) {
Teresa Johnson915897e2017-12-18 20:02:43 +00001569 // Initialize the entry count to -1, which will be treated conservatively
1570 // by getEntryCount as the same as unknown (None). If we have samples this
1571 // will be overwritten in emitAnnotations.
Easwaran Ramane5b8de22018-01-17 22:24:23 +00001572 F.setEntryCount(ProfileCount(-1, Function::PCT_Real));
Eli Friedman51cf2602017-08-11 21:12:04 +00001573 std::unique_ptr<OptimizationRemarkEmitter> OwnedORE;
1574 if (AM) {
1575 auto &FAM =
1576 AM->getResult<FunctionAnalysisManagerModuleProxy>(*F.getParent())
1577 .getManager();
1578 ORE = &FAM.getResult<OptimizationRemarkEmitterAnalysis>(F);
1579 } else {
1580 OwnedORE = make_unique<OptimizationRemarkEmitter>(&F);
1581 ORE = OwnedORE.get();
1582 }
Diego Novillode1ab262014-09-09 12:40:50 +00001583 Samples = Reader->getSamplesFor(F);
Dehao Chen4a435e02017-03-14 17:33:01 +00001584 if (Samples && !Samples->empty())
Diego Novillode1ab262014-09-09 12:40:50 +00001585 return emitAnnotations(F);
Diego Novillo0accb3d2014-01-10 23:23:46 +00001586 return false;
Diego Novillo8d6568b2013-11-13 12:22:21 +00001587}
Xinliang David Lid38392e2016-05-27 23:20:16 +00001588
1589PreservedAnalyses SampleProfileLoaderPass::run(Module &M,
Sean Silvafd03ac62016-08-09 00:28:38 +00001590 ModuleAnalysisManager &AM) {
Dehao Chenf3ed14d2017-09-12 21:55:55 +00001591 FunctionAnalysisManager &FAM =
1592 AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
Xinliang David Lid38392e2016-05-27 23:20:16 +00001593
Dehao Chenf3ed14d2017-09-12 21:55:55 +00001594 auto GetAssumptionCache = [&](Function &F) -> AssumptionCache & {
1595 return FAM.getResult<AssumptionAnalysis>(F);
1596 };
Dehao Chen3a81f842017-09-14 17:29:56 +00001597 auto GetTTI = [&](Function &F) -> TargetTransformInfo & {
1598 return FAM.getResult<TargetIRAnalysis>(F);
1599 };
Dehao Chenf3ed14d2017-09-12 21:55:55 +00001600
Dehao Chend26dae02017-10-01 05:24:51 +00001601 SampleProfileLoader SampleLoader(
1602 ProfileFileName.empty() ? SampleProfileFile : ProfileFileName,
1603 IsThinLTOPreLink, GetAssumptionCache, GetTTI);
Xinliang David Lid38392e2016-05-27 23:20:16 +00001604
1605 SampleLoader.doInitialization(M);
1606
Wei Mi0c2f6be2018-05-10 23:02:27 +00001607 ProfileSummaryInfo *PSI = &AM.getResult<ProfileSummaryAnalysis>(M);
1608 if (!SampleLoader.runOnModule(M, &AM, PSI))
Xinliang David Lid38392e2016-05-27 23:20:16 +00001609 return PreservedAnalyses::all();
1610
1611 return PreservedAnalyses::none();
1612}