blob: d9c25f2e9815c7d276848fe38f4b92444a470d74 [file] [log] [blame]
Rong Xuf430ae42015-12-09 18:08:16 +00001//===-- PGOInstrumentation.cpp - MST-based PGO Instrumentation ------------===//
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 PGO instrumentation using a minimum spanning tree based
11// on the following paper:
12// [1] Donald E. Knuth, Francis R. Stevenson. Optimal measurement of points
13// for program frequency counts. BIT Numerical Mathematics 1973, Volume 13,
14// Issue 3, pp 313-322
15// The idea of the algorithm based on the fact that for each node (except for
16// the entry and exit), the sum of incoming edge counts equals the sum of
17// outgoing edge counts. The count of edge on spanning tree can be derived from
18// those edges not on the spanning tree. Knuth proves this method instruments
19// the minimum number of edges.
20//
21// The minimal spanning tree here is actually a maximum weight tree -- on-tree
22// edges have higher frequencies (more likely to execute). The idea is to
23// instrument those less frequently executed edges to reduce the runtime
24// overhead of instrumented binaries.
25//
26// This file contains two passes:
27// (1) Pass PGOInstrumentationGen which instruments the IR to generate edge
Rong Xu13b01dc2016-02-10 18:24:45 +000028// count profile, and generates the instrumentation for indirect call
29// profiling.
Rong Xuf430ae42015-12-09 18:08:16 +000030// (2) Pass PGOInstrumentationUse which reads the edge count profile and
Rong Xu13b01dc2016-02-10 18:24:45 +000031// annotates the branch weights. It also reads the indirect call value
32// profiling records and annotate the indirect call instructions.
33//
Rong Xuf430ae42015-12-09 18:08:16 +000034// To get the precise counter information, These two passes need to invoke at
35// the same compilation point (so they see the same IR). For pass
36// PGOInstrumentationGen, the real work is done in instrumentOneFunc(). For
37// pass PGOInstrumentationUse, the real work in done in class PGOUseFunc and
38// the profile is opened in module level and passed to each PGOUseFunc instance.
39// The shared code for PGOInstrumentationGen and PGOInstrumentationUse is put
40// in class FuncPGOInstrumentation.
41//
42// Class PGOEdge represents a CFG edge and some auxiliary information. Class
43// BBInfo contains auxiliary information for each BB. These two classes are used
44// in pass PGOInstrumentationGen. Class PGOUseEdge and UseBBInfo are the derived
45// class of PGOEdge and BBInfo, respectively. They contains extra data structure
46// used in populating profile counters.
47// The MST implementation is in Class CFGMST (CFGMST.h).
48//
49//===----------------------------------------------------------------------===//
50
Xinliang David Li8aebf442016-05-06 05:49:19 +000051#include "llvm/Transforms/PGOInstrumentation.h"
Rong Xuf430ae42015-12-09 18:08:16 +000052#include "CFGMST.h"
Rong Xuf430ae42015-12-09 18:08:16 +000053#include "llvm/ADT/STLExtras.h"
Rong Xu705f7772016-07-25 18:45:37 +000054#include "llvm/ADT/SmallVector.h"
Rong Xuf430ae42015-12-09 18:08:16 +000055#include "llvm/ADT/Statistic.h"
Rong Xu33c76c02016-02-10 17:18:30 +000056#include "llvm/ADT/Triple.h"
Rong Xuf430ae42015-12-09 18:08:16 +000057#include "llvm/Analysis/BlockFrequencyInfo.h"
58#include "llvm/Analysis/BranchProbabilityInfo.h"
59#include "llvm/Analysis/CFG.h"
Teresa Johnson1e44b5d2016-07-12 21:13:44 +000060#include "llvm/Analysis/IndirectCallSiteVisitor.h"
Xinliang David Licb253ce2017-01-23 18:58:24 +000061#include "llvm/Analysis/LoopInfo.h"
Rong Xued9fec72016-01-21 18:11:44 +000062#include "llvm/IR/CallSite.h"
Rong Xuf430ae42015-12-09 18:08:16 +000063#include "llvm/IR/DiagnosticInfo.h"
Xinliang David Lid289e452017-01-27 19:06:25 +000064#include "llvm/IR/Dominators.h"
Rong Xu705f7772016-07-25 18:45:37 +000065#include "llvm/IR/GlobalValue.h"
Rong Xuf430ae42015-12-09 18:08:16 +000066#include "llvm/IR/IRBuilder.h"
67#include "llvm/IR/InstIterator.h"
68#include "llvm/IR/Instructions.h"
69#include "llvm/IR/IntrinsicInst.h"
70#include "llvm/IR/MDBuilder.h"
71#include "llvm/IR/Module.h"
72#include "llvm/Pass.h"
73#include "llvm/ProfileData/InstrProfReader.h"
Easwaran Raman5fe04a12016-05-26 22:57:11 +000074#include "llvm/ProfileData/ProfileCommon.h"
Rong Xuf430ae42015-12-09 18:08:16 +000075#include "llvm/Support/BranchProbability.h"
Xinliang David Lid289e452017-01-27 19:06:25 +000076#include "llvm/Support/DOTGraphTraits.h"
Rong Xuf430ae42015-12-09 18:08:16 +000077#include "llvm/Support/Debug.h"
Xinliang David Lid289e452017-01-27 19:06:25 +000078#include "llvm/Support/GraphWriter.h"
Rong Xuf430ae42015-12-09 18:08:16 +000079#include "llvm/Support/JamCRC.h"
Rong Xued9fec72016-01-21 18:11:44 +000080#include "llvm/Transforms/Instrumentation.h"
Rong Xuf430ae42015-12-09 18:08:16 +000081#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Xinliang David Li8aebf442016-05-06 05:49:19 +000082#include <algorithm>
Rong Xuf430ae42015-12-09 18:08:16 +000083#include <string>
Rong Xu705f7772016-07-25 18:45:37 +000084#include <unordered_map>
Rong Xuf430ae42015-12-09 18:08:16 +000085#include <utility>
86#include <vector>
87
88using namespace llvm;
89
90#define DEBUG_TYPE "pgo-instrumentation"
91
92STATISTIC(NumOfPGOInstrument, "Number of edges instrumented.");
Xinliang David Li4ca17332016-09-18 18:34:07 +000093STATISTIC(NumOfPGOSelectInsts, "Number of select instruction instrumented.");
Rong Xu4ed52792017-03-15 21:47:27 +000094STATISTIC(NumOfPGOMemIntrinsics, "Number of mem intrinsics instrumented.");
Rong Xuf430ae42015-12-09 18:08:16 +000095STATISTIC(NumOfPGOEdge, "Number of edges.");
96STATISTIC(NumOfPGOBB, "Number of basic-blocks.");
97STATISTIC(NumOfPGOSplit, "Number of critical edge splits.");
98STATISTIC(NumOfPGOFunc, "Number of functions having valid profile counts.");
99STATISTIC(NumOfPGOMismatch, "Number of functions having mismatch profile.");
100STATISTIC(NumOfPGOMissing, "Number of functions without profile.");
Rong Xu13b01dc2016-02-10 18:24:45 +0000101STATISTIC(NumOfPGOICall, "Number of indirect call value instrumentations.");
Rong Xuf430ae42015-12-09 18:08:16 +0000102
103// Command line option to specify the file to read profile from. This is
104// mainly used for testing.
105static cl::opt<std::string>
106 PGOTestProfileFile("pgo-test-profile-file", cl::init(""), cl::Hidden,
107 cl::value_desc("filename"),
108 cl::desc("Specify the path of profile data file. This is"
109 "mainly for test purpose."));
110
Rong Xuecdc98f2016-03-04 22:08:44 +0000111// Command line option to disable value profiling. The default is false:
Rong Xu13b01dc2016-02-10 18:24:45 +0000112// i.e. value profiling is enabled by default. This is for debug purpose.
Rong Xu9e926e82016-02-29 19:16:04 +0000113static cl::opt<bool> DisableValueProfiling("disable-vp", cl::init(false),
114 cl::Hidden,
115 cl::desc("Disable Value Profiling"));
Rong Xued9fec72016-01-21 18:11:44 +0000116
Rong Xuecdc98f2016-03-04 22:08:44 +0000117// Command line option to set the maximum number of VP annotations to write to
Rong Xu08afb052016-04-28 17:31:22 +0000118// the metadata for a single indirect call callsite.
119static cl::opt<unsigned> MaxNumAnnotations(
120 "icp-max-annotations", cl::init(3), cl::Hidden, cl::ZeroOrMore,
121 cl::desc("Max number of annotations for a single indirect "
122 "call callsite"));
Rong Xuecdc98f2016-03-04 22:08:44 +0000123
Rong Xu705f7772016-07-25 18:45:37 +0000124// Command line option to control appending FunctionHash to the name of a COMDAT
125// function. This is to avoid the hash mismatch caused by the preinliner.
126static cl::opt<bool> DoComdatRenaming(
Rong Xu20f5df12017-01-11 20:19:41 +0000127 "do-comdat-renaming", cl::init(false), cl::Hidden,
Rong Xu705f7772016-07-25 18:45:37 +0000128 cl::desc("Append function hash to the name of COMDAT function to avoid "
129 "function hash mismatch due to the preinliner"));
130
Rong Xu0698de92016-05-13 17:26:06 +0000131// Command line option to enable/disable the warning about missing profile
132// information.
Xinliang David Li58fcc9b2017-02-02 21:29:17 +0000133static cl::opt<bool>
134 PGOWarnMissing("pgo-warn-missing-function", cl::init(false), cl::Hidden,
135 cl::desc("Use this option to turn on/off "
136 "warnings about missing profile data for "
137 "functions."));
Rong Xu0698de92016-05-13 17:26:06 +0000138
139// Command line option to enable/disable the warning about a hash mismatch in
140// the profile data.
Xinliang David Li58fcc9b2017-02-02 21:29:17 +0000141static cl::opt<bool>
142 NoPGOWarnMismatch("no-pgo-warn-mismatch", cl::init(false), cl::Hidden,
143 cl::desc("Use this option to turn off/on "
144 "warnings about profile cfg mismatch."));
Rong Xu0698de92016-05-13 17:26:06 +0000145
Rong Xu20f5df12017-01-11 20:19:41 +0000146// Command line option to enable/disable the warning about a hash mismatch in
147// the profile data for Comdat functions, which often turns out to be false
148// positive due to the pre-instrumentation inline.
Xinliang David Li58fcc9b2017-02-02 21:29:17 +0000149static cl::opt<bool>
150 NoPGOWarnMismatchComdat("no-pgo-warn-mismatch-comdat", cl::init(true),
151 cl::Hidden,
152 cl::desc("The option is used to turn on/off "
153 "warnings about hash mismatch for comdat "
154 "functions."));
Rong Xu20f5df12017-01-11 20:19:41 +0000155
Xinliang David Li4ca17332016-09-18 18:34:07 +0000156// Command line option to enable/disable select instruction instrumentation.
Xinliang David Li58fcc9b2017-02-02 21:29:17 +0000157static cl::opt<bool>
158 PGOInstrSelect("pgo-instr-select", cl::init(true), cl::Hidden,
159 cl::desc("Use this option to turn on/off SELECT "
160 "instruction instrumentation. "));
Xinliang David Licb253ce2017-01-23 18:58:24 +0000161
Xinliang David Lid289e452017-01-27 19:06:25 +0000162// Command line option to turn on CFG dot dump of raw profile counts
Xinliang David Li58fcc9b2017-02-02 21:29:17 +0000163static cl::opt<bool>
164 PGOViewRawCounts("pgo-view-raw-counts", cl::init(false), cl::Hidden,
165 cl::desc("A boolean option to show CFG dag "
166 "with raw profile counts from "
167 "profile data. See also option "
168 "-pgo-view-counts. To limit graph "
169 "display to only one function, use "
170 "filtering option -view-bfi-func-name."));
Xinliang David Lid289e452017-01-27 19:06:25 +0000171
Rong Xu4ed52792017-03-15 21:47:27 +0000172// Command line option to enable/disable memop intrinsic calls..
173static cl::opt<bool> PGOInstrMemOP("pgo-instr-memop", cl::init(true),
174 cl::Hidden);
175
Xinliang David Licb253ce2017-01-23 18:58:24 +0000176// Command line option to turn on CFG dot dump after profile annotation.
Xinliang David Li58fcc9b2017-02-02 21:29:17 +0000177// Defined in Analysis/BlockFrequencyInfo.cpp: -pgo-view-counts
Xinliang David Licb253ce2017-01-23 18:58:24 +0000178extern cl::opt<bool> PGOViewCounts;
179
Xinliang David Li58fcc9b2017-02-02 21:29:17 +0000180// Command line option to specify the name of the function for CFG dump
181// Defined in Analysis/BlockFrequencyInfo.cpp: -view-bfi-func-name=
182extern cl::opt<std::string> ViewBlockFreqFuncName;
183
Rong Xuf430ae42015-12-09 18:08:16 +0000184namespace {
Xinliang David Li4ca17332016-09-18 18:34:07 +0000185
186/// The select instruction visitor plays three roles specified
187/// by the mode. In \c VM_counting mode, it simply counts the number of
188/// select instructions. In \c VM_instrument mode, it inserts code to count
189/// the number times TrueValue of select is taken. In \c VM_annotate mode,
190/// it reads the profile data and annotate the select instruction with metadata.
191enum VisitMode { VM_counting, VM_instrument, VM_annotate };
192class PGOUseFunc;
193
194/// Instruction Visitor class to visit select instructions.
195struct SelectInstVisitor : public InstVisitor<SelectInstVisitor> {
196 Function &F;
197 unsigned NSIs = 0; // Number of select instructions instrumented.
198 VisitMode Mode = VM_counting; // Visiting mode.
199 unsigned *CurCtrIdx = nullptr; // Pointer to current counter index.
200 unsigned TotalNumCtrs = 0; // Total number of counters
201 GlobalVariable *FuncNameVar = nullptr;
202 uint64_t FuncHash = 0;
203 PGOUseFunc *UseFunc = nullptr;
204
205 SelectInstVisitor(Function &Func) : F(Func) {}
206
207 void countSelects(Function &Func) {
Vitaly Bukaca6ecd22017-03-15 23:07:41 +0000208 NSIs = 0;
Xinliang David Li4ca17332016-09-18 18:34:07 +0000209 Mode = VM_counting;
210 visit(Func);
211 }
212 // Visit the IR stream and instrument all select instructions. \p
213 // Ind is a pointer to the counter index variable; \p TotalNC
214 // is the total number of counters; \p FNV is the pointer to the
215 // PGO function name var; \p FHash is the function hash.
216 void instrumentSelects(Function &Func, unsigned *Ind, unsigned TotalNC,
217 GlobalVariable *FNV, uint64_t FHash) {
218 Mode = VM_instrument;
219 CurCtrIdx = Ind;
220 TotalNumCtrs = TotalNC;
221 FuncHash = FHash;
222 FuncNameVar = FNV;
223 visit(Func);
224 }
225
226 // Visit the IR stream and annotate all select instructions.
227 void annotateSelects(Function &Func, PGOUseFunc *UF, unsigned *Ind) {
228 Mode = VM_annotate;
229 UseFunc = UF;
230 CurCtrIdx = Ind;
231 visit(Func);
232 }
233
234 void instrumentOneSelectInst(SelectInst &SI);
235 void annotateOneSelectInst(SelectInst &SI);
236 // Visit \p SI instruction and perform tasks according to visit mode.
237 void visitSelectInst(SelectInst &SI);
Vitaly Bukaca6ecd22017-03-15 23:07:41 +0000238 // Return the number of select instructions. This needs be called after
239 // countSelects().
Xinliang David Li4ca17332016-09-18 18:34:07 +0000240 unsigned getNumOfSelectInsts() const { return NSIs; }
241};
242
Rong Xu4ed52792017-03-15 21:47:27 +0000243/// Instruction Visitor class to visit memory intrinsic calls.
244struct MemIntrinsicVisitor : public InstVisitor<MemIntrinsicVisitor> {
245 Function &F;
246 unsigned NMemIs = 0; // Number of memIntrinsics instrumented.
247 VisitMode Mode = VM_counting; // Visiting mode.
248 unsigned CurCtrId = 0; // Current counter index.
249 unsigned TotalNumCtrs = 0; // Total number of counters
250 GlobalVariable *FuncNameVar = nullptr;
251 uint64_t FuncHash = 0;
252 PGOUseFunc *UseFunc = nullptr;
253
254 MemIntrinsicVisitor(Function &Func) : F(Func) {}
255
256 void countMemIntrinsics(Function &Func) {
257 NMemIs = 0;
258 Mode = VM_counting;
259 visit(Func);
260 }
261 void instrumentMemIntrinsics(Function &Func, unsigned TotalNC,
262 GlobalVariable *FNV, uint64_t FHash) {
263 Mode = VM_instrument;
264 TotalNumCtrs = TotalNC;
265 FuncHash = FHash;
266 FuncNameVar = FNV;
267 visit(Func);
268 }
269
270 // Visit the IR stream and annotate all mem intrinsic call instructions.
271 void instrumentOneMemIntrinsic(MemIntrinsic &MI);
272 // Visit \p MI instruction and perform tasks according to visit mode.
273 void visitMemIntrinsic(MemIntrinsic &SI);
274 unsigned getNumOfMemIntrinsics() const { return NMemIs; }
275};
276
Xinliang David Li8aebf442016-05-06 05:49:19 +0000277class PGOInstrumentationGenLegacyPass : public ModulePass {
Rong Xuf430ae42015-12-09 18:08:16 +0000278public:
279 static char ID;
280
Xinliang David Lidfa21c32016-05-09 21:37:12 +0000281 PGOInstrumentationGenLegacyPass() : ModulePass(ID) {
Xinliang David Li8aebf442016-05-06 05:49:19 +0000282 initializePGOInstrumentationGenLegacyPassPass(
283 *PassRegistry::getPassRegistry());
Rong Xuf430ae42015-12-09 18:08:16 +0000284 }
285
Mehdi Amini117296c2016-10-01 02:56:57 +0000286 StringRef getPassName() const override { return "PGOInstrumentationGenPass"; }
Rong Xuf430ae42015-12-09 18:08:16 +0000287
288private:
289 bool runOnModule(Module &M) override;
290
291 void getAnalysisUsage(AnalysisUsage &AU) const override {
292 AU.addRequired<BlockFrequencyInfoWrapperPass>();
293 }
294};
295
Xinliang David Lid55827f2016-05-07 05:39:12 +0000296class PGOInstrumentationUseLegacyPass : public ModulePass {
Rong Xuf430ae42015-12-09 18:08:16 +0000297public:
298 static char ID;
299
300 // Provide the profile filename as the parameter.
Xinliang David Lid55827f2016-05-07 05:39:12 +0000301 PGOInstrumentationUseLegacyPass(std::string Filename = "")
Benjamin Kramer82de7d32016-05-27 14:27:24 +0000302 : ModulePass(ID), ProfileFileName(std::move(Filename)) {
Rong Xuf430ae42015-12-09 18:08:16 +0000303 if (!PGOTestProfileFile.empty())
304 ProfileFileName = PGOTestProfileFile;
Xinliang David Lid55827f2016-05-07 05:39:12 +0000305 initializePGOInstrumentationUseLegacyPassPass(
306 *PassRegistry::getPassRegistry());
Rong Xuf430ae42015-12-09 18:08:16 +0000307 }
308
Mehdi Amini117296c2016-10-01 02:56:57 +0000309 StringRef getPassName() const override { return "PGOInstrumentationUsePass"; }
Rong Xuf430ae42015-12-09 18:08:16 +0000310
311private:
312 std::string ProfileFileName;
Rong Xuf430ae42015-12-09 18:08:16 +0000313
Xinliang David Lida195582016-05-10 21:59:52 +0000314 bool runOnModule(Module &M) override;
Rong Xuf430ae42015-12-09 18:08:16 +0000315 void getAnalysisUsage(AnalysisUsage &AU) const override {
316 AU.addRequired<BlockFrequencyInfoWrapperPass>();
317 }
318};
Xinliang David Li4ca17332016-09-18 18:34:07 +0000319
Rong Xuf430ae42015-12-09 18:08:16 +0000320} // end anonymous namespace
321
Xinliang David Li8aebf442016-05-06 05:49:19 +0000322char PGOInstrumentationGenLegacyPass::ID = 0;
323INITIALIZE_PASS_BEGIN(PGOInstrumentationGenLegacyPass, "pgo-instr-gen",
Rong Xuf430ae42015-12-09 18:08:16 +0000324 "PGO instrumentation.", false, false)
325INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
326INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
Xinliang David Li8aebf442016-05-06 05:49:19 +0000327INITIALIZE_PASS_END(PGOInstrumentationGenLegacyPass, "pgo-instr-gen",
Rong Xuf430ae42015-12-09 18:08:16 +0000328 "PGO instrumentation.", false, false)
329
Xinliang David Li8aebf442016-05-06 05:49:19 +0000330ModulePass *llvm::createPGOInstrumentationGenLegacyPass() {
331 return new PGOInstrumentationGenLegacyPass();
Rong Xuf430ae42015-12-09 18:08:16 +0000332}
333
Xinliang David Lid55827f2016-05-07 05:39:12 +0000334char PGOInstrumentationUseLegacyPass::ID = 0;
335INITIALIZE_PASS_BEGIN(PGOInstrumentationUseLegacyPass, "pgo-instr-use",
Rong Xuf430ae42015-12-09 18:08:16 +0000336 "Read PGO instrumentation profile.", false, false)
337INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
338INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
Xinliang David Lid55827f2016-05-07 05:39:12 +0000339INITIALIZE_PASS_END(PGOInstrumentationUseLegacyPass, "pgo-instr-use",
Rong Xuf430ae42015-12-09 18:08:16 +0000340 "Read PGO instrumentation profile.", false, false)
341
Xinliang David Lid55827f2016-05-07 05:39:12 +0000342ModulePass *llvm::createPGOInstrumentationUseLegacyPass(StringRef Filename) {
343 return new PGOInstrumentationUseLegacyPass(Filename.str());
Rong Xuf430ae42015-12-09 18:08:16 +0000344}
345
346namespace {
347/// \brief An MST based instrumentation for PGO
348///
349/// Implements a Minimum Spanning Tree (MST) based instrumentation for PGO
350/// in the function level.
351struct PGOEdge {
352 // This class implements the CFG edges. Note the CFG can be a multi-graph.
353 // So there might be multiple edges with same SrcBB and DestBB.
354 const BasicBlock *SrcBB;
355 const BasicBlock *DestBB;
356 uint64_t Weight;
357 bool InMST;
358 bool Removed;
359 bool IsCritical;
360 PGOEdge(const BasicBlock *Src, const BasicBlock *Dest, unsigned W = 1)
361 : SrcBB(Src), DestBB(Dest), Weight(W), InMST(false), Removed(false),
362 IsCritical(false) {}
363 // Return the information string of an edge.
364 const std::string infoString() const {
365 return (Twine(Removed ? "-" : " ") + (InMST ? " " : "*") +
366 (IsCritical ? "c" : " ") + " W=" + Twine(Weight)).str();
367 }
368};
369
370// This class stores the auxiliary information for each BB.
371struct BBInfo {
372 BBInfo *Group;
373 uint32_t Index;
374 uint32_t Rank;
375
376 BBInfo(unsigned IX) : Group(this), Index(IX), Rank(0) {}
377
378 // Return the information string of this object.
379 const std::string infoString() const {
380 return (Twine("Index=") + Twine(Index)).str();
381 }
382};
383
384// This class implements the CFG edges. Note the CFG can be a multi-graph.
385template <class Edge, class BBInfo> class FuncPGOInstrumentation {
386private:
387 Function &F;
388 void computeCFGHash();
Rong Xu705f7772016-07-25 18:45:37 +0000389 void renameComdatFunction();
390 // A map that stores the Comdat group in function F.
391 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers;
Rong Xuf430ae42015-12-09 18:08:16 +0000392
393public:
Rong Xua3bbf962017-03-15 18:23:39 +0000394 std::vector<std::vector<Instruction *>> ValueSites;
Xinliang David Li4ca17332016-09-18 18:34:07 +0000395 SelectInstVisitor SIVisitor;
Rong Xu4ed52792017-03-15 21:47:27 +0000396 MemIntrinsicVisitor MIVisitor;
Rong Xuf430ae42015-12-09 18:08:16 +0000397 std::string FuncName;
398 GlobalVariable *FuncNameVar;
399 // CFG hash value for this function.
400 uint64_t FunctionHash;
401
402 // The Minimum Spanning Tree of function CFG.
403 CFGMST<Edge, BBInfo> MST;
404
405 // Give an edge, find the BB that will be instrumented.
406 // Return nullptr if there is no BB to be instrumented.
407 BasicBlock *getInstrBB(Edge *E);
408
409 // Return the auxiliary BB information.
410 BBInfo &getBBInfo(const BasicBlock *BB) const { return MST.getBBInfo(BB); }
411
Rong Xua5b57452016-12-02 19:10:29 +0000412 // Return the auxiliary BB information if available.
413 BBInfo *findBBInfo(const BasicBlock *BB) const { return MST.findBBInfo(BB); }
414
Rong Xuf430ae42015-12-09 18:08:16 +0000415 // Dump edges and BB information.
416 void dumpInfo(std::string Str = "") const {
417 MST.dumpEdges(dbgs(), Twine("Dump Function ") + FuncName + " Hash: " +
Rong Xued9fec72016-01-21 18:11:44 +0000418 Twine(FunctionHash) + "\t" + Str);
Rong Xuf430ae42015-12-09 18:08:16 +0000419 }
420
Rong Xu705f7772016-07-25 18:45:37 +0000421 FuncPGOInstrumentation(
422 Function &Func,
423 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers,
424 bool CreateGlobalVar = false, BranchProbabilityInfo *BPI = nullptr,
425 BlockFrequencyInfo *BFI = nullptr)
Rong Xua3bbf962017-03-15 18:23:39 +0000426 : F(Func), ComdatMembers(ComdatMembers), ValueSites(IPVK_Last + 1),
Rong Xu4ed52792017-03-15 21:47:27 +0000427 SIVisitor(Func), MIVisitor(Func), FunctionHash(0), MST(F, BPI, BFI) {
Xinliang David Li4ca17332016-09-18 18:34:07 +0000428
429 // This should be done before CFG hash computation.
430 SIVisitor.countSelects(Func);
Rong Xu4ed52792017-03-15 21:47:27 +0000431 MIVisitor.countMemIntrinsics(Func);
Xinliang David Li4ca17332016-09-18 18:34:07 +0000432 NumOfPGOSelectInsts += SIVisitor.getNumOfSelectInsts();
Rong Xu4ed52792017-03-15 21:47:27 +0000433 NumOfPGOMemIntrinsics += MIVisitor.getNumOfMemIntrinsics();
Rong Xua3bbf962017-03-15 18:23:39 +0000434 ValueSites[IPVK_IndirectCallTarget] = findIndirectCallSites(Func);
Xinliang David Li4ca17332016-09-18 18:34:07 +0000435
Rong Xuf430ae42015-12-09 18:08:16 +0000436 FuncName = getPGOFuncName(F);
437 computeCFGHash();
Rong Xu705f7772016-07-25 18:45:37 +0000438 if (ComdatMembers.size())
439 renameComdatFunction();
Rong Xuf430ae42015-12-09 18:08:16 +0000440 DEBUG(dumpInfo("after CFGMST"));
441
442 NumOfPGOBB += MST.BBInfos.size();
443 for (auto &E : MST.AllEdges) {
444 if (E->Removed)
445 continue;
446 NumOfPGOEdge++;
447 if (!E->InMST)
448 NumOfPGOInstrument++;
449 }
450
451 if (CreateGlobalVar)
452 FuncNameVar = createPGOFuncNameVar(F, FuncName);
Eugene Zelenko6ac3f732016-01-26 18:48:36 +0000453 }
Xinliang David Lid1197612016-08-01 20:25:06 +0000454
455 // Return the number of profile counters needed for the function.
456 unsigned getNumCounters() {
457 unsigned NumCounters = 0;
458 for (auto &E : this->MST.AllEdges) {
459 if (!E->InMST && !E->Removed)
460 NumCounters++;
461 }
Xinliang David Li4ca17332016-09-18 18:34:07 +0000462 return NumCounters + SIVisitor.getNumOfSelectInsts();
Xinliang David Lid1197612016-08-01 20:25:06 +0000463 }
Rong Xuf430ae42015-12-09 18:08:16 +0000464};
465
466// Compute Hash value for the CFG: the lower 32 bits are CRC32 of the index
467// value of each BB in the CFG. The higher 32 bits record the number of edges.
468template <class Edge, class BBInfo>
469void FuncPGOInstrumentation<Edge, BBInfo>::computeCFGHash() {
470 std::vector<char> Indexes;
471 JamCRC JC;
472 for (auto &BB : F) {
473 const TerminatorInst *TI = BB.getTerminator();
474 for (unsigned I = 0, E = TI->getNumSuccessors(); I != E; ++I) {
475 BasicBlock *Succ = TI->getSuccessor(I);
Rong Xua5b57452016-12-02 19:10:29 +0000476 auto BI = findBBInfo(Succ);
477 if (BI == nullptr)
478 continue;
479 uint32_t Index = BI->Index;
Rong Xuf430ae42015-12-09 18:08:16 +0000480 for (int J = 0; J < 4; J++)
481 Indexes.push_back((char)(Index >> (J * 8)));
482 }
483 }
484 JC.update(Indexes);
Xinliang David Li4ca17332016-09-18 18:34:07 +0000485 FunctionHash = (uint64_t)SIVisitor.getNumOfSelectInsts() << 56 |
Rong Xua3bbf962017-03-15 18:23:39 +0000486 (uint64_t)ValueSites[IPVK_IndirectCallTarget].size() << 48 |
Rong Xu705f7772016-07-25 18:45:37 +0000487 (uint64_t)MST.AllEdges.size() << 32 | JC.getCRC();
488}
489
490// Check if we can safely rename this Comdat function.
491static bool canRenameComdat(
492 Function &F,
493 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers) {
Rong Xu20f5df12017-01-11 20:19:41 +0000494 if (!DoComdatRenaming || !canRenameComdatFunc(F, true))
Rong Xu705f7772016-07-25 18:45:37 +0000495 return false;
Rong Xu705f7772016-07-25 18:45:37 +0000496
497 // FIXME: Current only handle those Comdat groups that only containing one
498 // function and function aliases.
499 // (1) For a Comdat group containing multiple functions, we need to have a
500 // unique postfix based on the hashes for each function. There is a
501 // non-trivial code refactoring to do this efficiently.
502 // (2) Variables can not be renamed, so we can not rename Comdat function in a
503 // group including global vars.
504 Comdat *C = F.getComdat();
505 for (auto &&CM : make_range(ComdatMembers.equal_range(C))) {
506 if (dyn_cast<GlobalAlias>(CM.second))
507 continue;
508 Function *FM = dyn_cast<Function>(CM.second);
509 if (FM != &F)
510 return false;
511 }
512 return true;
513}
514
515// Append the CFGHash to the Comdat function name.
516template <class Edge, class BBInfo>
517void FuncPGOInstrumentation<Edge, BBInfo>::renameComdatFunction() {
518 if (!canRenameComdat(F, ComdatMembers))
519 return;
Rong Xu0e79f7d2016-10-06 20:38:13 +0000520 std::string OrigName = F.getName().str();
Rong Xu705f7772016-07-25 18:45:37 +0000521 std::string NewFuncName =
522 Twine(F.getName() + "." + Twine(FunctionHash)).str();
523 F.setName(Twine(NewFuncName));
Rong Xu0e79f7d2016-10-06 20:38:13 +0000524 GlobalAlias::create(GlobalValue::WeakAnyLinkage, OrigName, &F);
Rong Xu705f7772016-07-25 18:45:37 +0000525 FuncName = Twine(FuncName + "." + Twine(FunctionHash)).str();
526 Comdat *NewComdat;
527 Module *M = F.getParent();
528 // For AvailableExternallyLinkage functions, change the linkage to
529 // LinkOnceODR and put them into comdat. This is because after renaming, there
530 // is no backup external copy available for the function.
531 if (!F.hasComdat()) {
532 assert(F.getLinkage() == GlobalValue::AvailableExternallyLinkage);
533 NewComdat = M->getOrInsertComdat(StringRef(NewFuncName));
534 F.setLinkage(GlobalValue::LinkOnceODRLinkage);
535 F.setComdat(NewComdat);
536 return;
537 }
538
539 // This function belongs to a single function Comdat group.
540 Comdat *OrigComdat = F.getComdat();
541 std::string NewComdatName =
542 Twine(OrigComdat->getName() + "." + Twine(FunctionHash)).str();
543 NewComdat = M->getOrInsertComdat(StringRef(NewComdatName));
544 NewComdat->setSelectionKind(OrigComdat->getSelectionKind());
545
546 for (auto &&CM : make_range(ComdatMembers.equal_range(OrigComdat))) {
547 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(CM.second)) {
548 // For aliases, change the name directly.
549 assert(dyn_cast<Function>(GA->getAliasee()->stripPointerCasts()) == &F);
Rong Xu0e79f7d2016-10-06 20:38:13 +0000550 std::string OrigGAName = GA->getName().str();
Rong Xu705f7772016-07-25 18:45:37 +0000551 GA->setName(Twine(GA->getName() + "." + Twine(FunctionHash)));
Rong Xu0e79f7d2016-10-06 20:38:13 +0000552 GlobalAlias::create(GlobalValue::WeakAnyLinkage, OrigGAName, GA);
Rong Xu705f7772016-07-25 18:45:37 +0000553 continue;
554 }
555 // Must be a function.
556 Function *CF = dyn_cast<Function>(CM.second);
557 assert(CF);
558 CF->setComdat(NewComdat);
559 }
Rong Xuf430ae42015-12-09 18:08:16 +0000560}
561
562// Given a CFG E to be instrumented, find which BB to place the instrumented
563// code. The function will split the critical edge if necessary.
564template <class Edge, class BBInfo>
565BasicBlock *FuncPGOInstrumentation<Edge, BBInfo>::getInstrBB(Edge *E) {
566 if (E->InMST || E->Removed)
567 return nullptr;
568
569 BasicBlock *SrcBB = const_cast<BasicBlock *>(E->SrcBB);
570 BasicBlock *DestBB = const_cast<BasicBlock *>(E->DestBB);
571 // For a fake edge, instrument the real BB.
572 if (SrcBB == nullptr)
573 return DestBB;
574 if (DestBB == nullptr)
575 return SrcBB;
576
577 // Instrument the SrcBB if it has a single successor,
578 // otherwise, the DestBB if this is not a critical edge.
579 TerminatorInst *TI = SrcBB->getTerminator();
580 if (TI->getNumSuccessors() <= 1)
581 return SrcBB;
582 if (!E->IsCritical)
583 return DestBB;
584
585 // For a critical edge, we have to split. Instrument the newly
586 // created BB.
587 NumOfPGOSplit++;
588 DEBUG(dbgs() << "Split critical edge: " << getBBInfo(SrcBB).Index << " --> "
589 << getBBInfo(DestBB).Index << "\n");
590 unsigned SuccNum = GetSuccessorNumber(SrcBB, DestBB);
591 BasicBlock *InstrBB = SplitCriticalEdge(TI, SuccNum);
592 assert(InstrBB && "Critical edge is not split");
593
594 E->Removed = true;
595 return InstrBB;
596}
597
Rong Xued9fec72016-01-21 18:11:44 +0000598// Visit all edge and instrument the edges not in MST, and do value profiling.
Rong Xuf430ae42015-12-09 18:08:16 +0000599// Critical edges will be split.
Rong Xu705f7772016-07-25 18:45:37 +0000600static void instrumentOneFunc(
601 Function &F, Module *M, BranchProbabilityInfo *BPI, BlockFrequencyInfo *BFI,
602 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers) {
Rong Xu705f7772016-07-25 18:45:37 +0000603 FuncPGOInstrumentation<PGOEdge, BBInfo> FuncInfo(F, ComdatMembers, true, BPI,
604 BFI);
Xinliang David Lid1197612016-08-01 20:25:06 +0000605 unsigned NumCounters = FuncInfo.getNumCounters();
606
Rong Xuf430ae42015-12-09 18:08:16 +0000607 uint32_t I = 0;
Rong Xued9fec72016-01-21 18:11:44 +0000608 Type *I8PtrTy = Type::getInt8PtrTy(M->getContext());
Rong Xuf430ae42015-12-09 18:08:16 +0000609 for (auto &E : FuncInfo.MST.AllEdges) {
610 BasicBlock *InstrBB = FuncInfo.getInstrBB(E.get());
611 if (!InstrBB)
612 continue;
613
614 IRBuilder<> Builder(InstrBB, InstrBB->getFirstInsertionPt());
615 assert(Builder.GetInsertPoint() != InstrBB->end() &&
616 "Cannot get the Instrumentation point");
Rong Xuf430ae42015-12-09 18:08:16 +0000617 Builder.CreateCall(
618 Intrinsic::getDeclaration(M, Intrinsic::instrprof_increment),
619 {llvm::ConstantExpr::getBitCast(FuncInfo.FuncNameVar, I8PtrTy),
620 Builder.getInt64(FuncInfo.FunctionHash), Builder.getInt32(NumCounters),
621 Builder.getInt32(I++)});
622 }
Xinliang David Li4ca17332016-09-18 18:34:07 +0000623
624 // Now instrument select instructions:
625 FuncInfo.SIVisitor.instrumentSelects(F, &I, NumCounters, FuncInfo.FuncNameVar,
626 FuncInfo.FunctionHash);
Xinliang David Lid1197612016-08-01 20:25:06 +0000627 assert(I == NumCounters);
Rong Xued9fec72016-01-21 18:11:44 +0000628
629 if (DisableValueProfiling)
630 return;
631
632 unsigned NumIndirectCallSites = 0;
Rong Xua3bbf962017-03-15 18:23:39 +0000633 for (auto &I : FuncInfo.ValueSites[IPVK_IndirectCallTarget]) {
Rong Xued9fec72016-01-21 18:11:44 +0000634 CallSite CS(I);
635 Value *Callee = CS.getCalledValue();
636 DEBUG(dbgs() << "Instrument one indirect call: CallSite Index = "
637 << NumIndirectCallSites << "\n");
638 IRBuilder<> Builder(I);
639 assert(Builder.GetInsertPoint() != I->getParent()->end() &&
640 "Cannot get the Instrumentation point");
641 Builder.CreateCall(
642 Intrinsic::getDeclaration(M, Intrinsic::instrprof_value_profile),
643 {llvm::ConstantExpr::getBitCast(FuncInfo.FuncNameVar, I8PtrTy),
644 Builder.getInt64(FuncInfo.FunctionHash),
645 Builder.CreatePtrToInt(Callee, Builder.getInt64Ty()),
Rong Xua3bbf962017-03-15 18:23:39 +0000646 Builder.getInt32(IPVK_IndirectCallTarget),
Rong Xued9fec72016-01-21 18:11:44 +0000647 Builder.getInt32(NumIndirectCallSites++)});
648 }
649 NumOfPGOICall += NumIndirectCallSites;
Rong Xu4ed52792017-03-15 21:47:27 +0000650
651 // Now instrument memop intrinsic calls.
652 FuncInfo.MIVisitor.instrumentMemIntrinsics(
653 F, NumCounters, FuncInfo.FuncNameVar, FuncInfo.FunctionHash);
Rong Xuf430ae42015-12-09 18:08:16 +0000654}
655
656// This class represents a CFG edge in profile use compilation.
657struct PGOUseEdge : public PGOEdge {
658 bool CountValid;
659 uint64_t CountValue;
660 PGOUseEdge(const BasicBlock *Src, const BasicBlock *Dest, unsigned W = 1)
661 : PGOEdge(Src, Dest, W), CountValid(false), CountValue(0) {}
662
663 // Set edge count value
664 void setEdgeCount(uint64_t Value) {
665 CountValue = Value;
666 CountValid = true;
667 }
668
669 // Return the information string for this object.
670 const std::string infoString() const {
671 if (!CountValid)
672 return PGOEdge::infoString();
Rong Xu9e926e82016-02-29 19:16:04 +0000673 return (Twine(PGOEdge::infoString()) + " Count=" + Twine(CountValue))
674 .str();
Rong Xuf430ae42015-12-09 18:08:16 +0000675 }
676};
677
678typedef SmallVector<PGOUseEdge *, 2> DirectEdges;
679
680// This class stores the auxiliary information for each BB.
681struct UseBBInfo : public BBInfo {
682 uint64_t CountValue;
683 bool CountValid;
684 int32_t UnknownCountInEdge;
685 int32_t UnknownCountOutEdge;
686 DirectEdges InEdges;
687 DirectEdges OutEdges;
688 UseBBInfo(unsigned IX)
689 : BBInfo(IX), CountValue(0), CountValid(false), UnknownCountInEdge(0),
690 UnknownCountOutEdge(0) {}
691 UseBBInfo(unsigned IX, uint64_t C)
692 : BBInfo(IX), CountValue(C), CountValid(true), UnknownCountInEdge(0),
693 UnknownCountOutEdge(0) {}
694
695 // Set the profile count value for this BB.
696 void setBBInfoCount(uint64_t Value) {
697 CountValue = Value;
698 CountValid = true;
699 }
700
701 // Return the information string of this object.
702 const std::string infoString() const {
703 if (!CountValid)
704 return BBInfo::infoString();
705 return (Twine(BBInfo::infoString()) + " Count=" + Twine(CountValue)).str();
706 }
707};
708
709// Sum up the count values for all the edges.
710static uint64_t sumEdgeCount(const ArrayRef<PGOUseEdge *> Edges) {
711 uint64_t Total = 0;
712 for (auto &E : Edges) {
713 if (E->Removed)
714 continue;
715 Total += E->CountValue;
716 }
717 return Total;
718}
719
720class PGOUseFunc {
Rong Xu6090afd2016-03-28 17:08:56 +0000721public:
Rong Xu705f7772016-07-25 18:45:37 +0000722 PGOUseFunc(Function &Func, Module *Modu,
723 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers,
724 BranchProbabilityInfo *BPI = nullptr,
Rong Xu6090afd2016-03-28 17:08:56 +0000725 BlockFrequencyInfo *BFI = nullptr)
Rong Xu705f7772016-07-25 18:45:37 +0000726 : F(Func), M(Modu), FuncInfo(Func, ComdatMembers, false, BPI, BFI),
Rong Xu33308f92016-10-25 21:47:24 +0000727 CountPosition(0), ProfileCountSize(0), FreqAttr(FFA_Normal) {}
Rong Xu6090afd2016-03-28 17:08:56 +0000728
729 // Read counts for the instrumented BB from profile.
730 bool readCounters(IndexedInstrProfReader *PGOReader);
731
732 // Populate the counts for all BBs.
733 void populateCounters();
734
735 // Set the branch weights based on the count values.
736 void setBranchWeights();
737
Rong Xua3bbf962017-03-15 18:23:39 +0000738 // Annotate the value profile call sites all all value kind.
739 void annotateValueSites();
740
741 // Annotate the value profile call sites for one value kind.
742 void annotateValueSites(uint32_t Kind);
Rong Xu6090afd2016-03-28 17:08:56 +0000743
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000744 // The hotness of the function from the profile count.
745 enum FuncFreqAttr { FFA_Normal, FFA_Cold, FFA_Hot };
746
747 // Return the function hotness from the profile.
748 FuncFreqAttr getFuncFreqAttr() const { return FreqAttr; }
749
Rong Xu705f7772016-07-25 18:45:37 +0000750 // Return the function hash.
751 uint64_t getFuncHash() const { return FuncInfo.FunctionHash; }
Easwaran Raman5fe04a12016-05-26 22:57:11 +0000752 // Return the profile record for this function;
753 InstrProfRecord &getProfileRecord() { return ProfileRecord; }
754
Xinliang David Li4ca17332016-09-18 18:34:07 +0000755 // Return the auxiliary BB information.
756 UseBBInfo &getBBInfo(const BasicBlock *BB) const {
757 return FuncInfo.getBBInfo(BB);
758 }
759
Rong Xua5b57452016-12-02 19:10:29 +0000760 // Return the auxiliary BB information if available.
761 UseBBInfo *findBBInfo(const BasicBlock *BB) const {
762 return FuncInfo.findBBInfo(BB);
763 }
764
Xinliang David Lid289e452017-01-27 19:06:25 +0000765 Function &getFunc() const { return F; }
766
Rong Xuf430ae42015-12-09 18:08:16 +0000767private:
768 Function &F;
769 Module *M;
770 // This member stores the shared information with class PGOGenFunc.
771 FuncPGOInstrumentation<PGOUseEdge, UseBBInfo> FuncInfo;
772
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000773 // The maximum count value in the profile. This is only used in PGO use
774 // compilation.
775 uint64_t ProgramMaxCount;
776
Rong Xu33308f92016-10-25 21:47:24 +0000777 // Position of counter that remains to be read.
778 uint32_t CountPosition;
779
780 // Total size of the profile count for this function.
781 uint32_t ProfileCountSize;
782
Rong Xu13b01dc2016-02-10 18:24:45 +0000783 // ProfileRecord for this function.
784 InstrProfRecord ProfileRecord;
785
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000786 // Function hotness info derived from profile.
787 FuncFreqAttr FreqAttr;
788
Rong Xuf430ae42015-12-09 18:08:16 +0000789 // Find the Instrumented BB and set the value.
790 void setInstrumentedCounts(const std::vector<uint64_t> &CountFromProfile);
791
792 // Set the edge counter value for the unknown edge -- there should be only
793 // one unknown edge.
794 void setEdgeCount(DirectEdges &Edges, uint64_t Value);
795
796 // Return FuncName string;
797 const std::string getFuncName() const { return FuncInfo.FuncName; }
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000798
799 // Set the hot/cold inline hints based on the count values.
800 // FIXME: This function should be removed once the functionality in
801 // the inliner is implemented.
802 void markFunctionAttributes(uint64_t EntryCount, uint64_t MaxCount) {
803 if (ProgramMaxCount == 0)
804 return;
805 // Threshold of the hot functions.
806 const BranchProbability HotFunctionThreshold(1, 100);
807 // Threshold of the cold functions.
808 const BranchProbability ColdFunctionThreshold(2, 10000);
809 if (EntryCount >= HotFunctionThreshold.scale(ProgramMaxCount))
810 FreqAttr = FFA_Hot;
811 else if (MaxCount <= ColdFunctionThreshold.scale(ProgramMaxCount))
812 FreqAttr = FFA_Cold;
813 }
Rong Xuf430ae42015-12-09 18:08:16 +0000814};
815
816// Visit all the edges and assign the count value for the instrumented
817// edges and the BB.
818void PGOUseFunc::setInstrumentedCounts(
819 const std::vector<uint64_t> &CountFromProfile) {
820
Xinliang David Lid1197612016-08-01 20:25:06 +0000821 assert(FuncInfo.getNumCounters() == CountFromProfile.size());
Rong Xuf430ae42015-12-09 18:08:16 +0000822 // Use a worklist as we will update the vector during the iteration.
823 std::vector<PGOUseEdge *> WorkList;
824 for (auto &E : FuncInfo.MST.AllEdges)
825 WorkList.push_back(E.get());
826
827 uint32_t I = 0;
828 for (auto &E : WorkList) {
829 BasicBlock *InstrBB = FuncInfo.getInstrBB(E);
830 if (!InstrBB)
831 continue;
832 uint64_t CountValue = CountFromProfile[I++];
833 if (!E->Removed) {
834 getBBInfo(InstrBB).setBBInfoCount(CountValue);
835 E->setEdgeCount(CountValue);
836 continue;
837 }
838
839 // Need to add two new edges.
840 BasicBlock *SrcBB = const_cast<BasicBlock *>(E->SrcBB);
841 BasicBlock *DestBB = const_cast<BasicBlock *>(E->DestBB);
842 // Add new edge of SrcBB->InstrBB.
843 PGOUseEdge &NewEdge = FuncInfo.MST.addEdge(SrcBB, InstrBB, 0);
844 NewEdge.setEdgeCount(CountValue);
845 // Add new edge of InstrBB->DestBB.
846 PGOUseEdge &NewEdge1 = FuncInfo.MST.addEdge(InstrBB, DestBB, 0);
847 NewEdge1.setEdgeCount(CountValue);
848 NewEdge1.InMST = true;
849 getBBInfo(InstrBB).setBBInfoCount(CountValue);
850 }
Rong Xu0a2a1312017-03-09 19:08:55 +0000851 ProfileCountSize = CountFromProfile.size();
Rong Xu33308f92016-10-25 21:47:24 +0000852 CountPosition = I;
Rong Xuf430ae42015-12-09 18:08:16 +0000853}
854
855// Set the count value for the unknown edge. There should be one and only one
856// unknown edge in Edges vector.
857void PGOUseFunc::setEdgeCount(DirectEdges &Edges, uint64_t Value) {
858 for (auto &E : Edges) {
859 if (E->CountValid)
860 continue;
861 E->setEdgeCount(Value);
862
863 getBBInfo(E->SrcBB).UnknownCountOutEdge--;
864 getBBInfo(E->DestBB).UnknownCountInEdge--;
865 return;
866 }
867 llvm_unreachable("Cannot find the unknown count edge");
868}
869
870// Read the profile from ProfileFileName and assign the value to the
871// instrumented BB and the edges. This function also updates ProgramMaxCount.
872// Return true if the profile are successfully read, and false on errors.
873bool PGOUseFunc::readCounters(IndexedInstrProfReader *PGOReader) {
874 auto &Ctx = M->getContext();
Vedant Kumar9152fd12016-05-19 03:54:45 +0000875 Expected<InstrProfRecord> Result =
Rong Xuf430ae42015-12-09 18:08:16 +0000876 PGOReader->getInstrProfRecord(FuncInfo.FuncName, FuncInfo.FunctionHash);
Vedant Kumar9152fd12016-05-19 03:54:45 +0000877 if (Error E = Result.takeError()) {
878 handleAllErrors(std::move(E), [&](const InstrProfError &IPE) {
879 auto Err = IPE.get();
880 bool SkipWarning = false;
881 if (Err == instrprof_error::unknown_function) {
882 NumOfPGOMissing++;
Xinliang David Li76a01082016-08-11 05:09:30 +0000883 SkipWarning = !PGOWarnMissing;
Vedant Kumar9152fd12016-05-19 03:54:45 +0000884 } else if (Err == instrprof_error::hash_mismatch ||
885 Err == instrprof_error::malformed) {
886 NumOfPGOMismatch++;
Rong Xu20f5df12017-01-11 20:19:41 +0000887 SkipWarning =
888 NoPGOWarnMismatch ||
889 (NoPGOWarnMismatchComdat &&
890 (F.hasComdat() ||
891 F.getLinkage() == GlobalValue::AvailableExternallyLinkage));
Vedant Kumar9152fd12016-05-19 03:54:45 +0000892 }
Rong Xuf430ae42015-12-09 18:08:16 +0000893
Vedant Kumar9152fd12016-05-19 03:54:45 +0000894 if (SkipWarning)
895 return;
896
897 std::string Msg = IPE.message() + std::string(" ") + F.getName().str();
898 Ctx.diagnose(
899 DiagnosticInfoPGOProfile(M->getName().data(), Msg, DS_Warning));
900 });
Rong Xuf430ae42015-12-09 18:08:16 +0000901 return false;
902 }
Rong Xu13b01dc2016-02-10 18:24:45 +0000903 ProfileRecord = std::move(Result.get());
904 std::vector<uint64_t> &CountFromProfile = ProfileRecord.Counts;
Rong Xuf430ae42015-12-09 18:08:16 +0000905
906 NumOfPGOFunc++;
907 DEBUG(dbgs() << CountFromProfile.size() << " counts\n");
908 uint64_t ValueSum = 0;
909 for (unsigned I = 0, S = CountFromProfile.size(); I < S; I++) {
910 DEBUG(dbgs() << " " << I << ": " << CountFromProfile[I] << "\n");
911 ValueSum += CountFromProfile[I];
912 }
913
914 DEBUG(dbgs() << "SUM = " << ValueSum << "\n");
915
916 getBBInfo(nullptr).UnknownCountOutEdge = 2;
917 getBBInfo(nullptr).UnknownCountInEdge = 2;
918
919 setInstrumentedCounts(CountFromProfile);
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000920 ProgramMaxCount = PGOReader->getMaximumFunctionCount();
Rong Xuf430ae42015-12-09 18:08:16 +0000921 return true;
922}
923
924// Populate the counters from instrumented BBs to all BBs.
925// In the end of this operation, all BBs should have a valid count value.
926void PGOUseFunc::populateCounters() {
927 // First set up Count variable for all BBs.
928 for (auto &E : FuncInfo.MST.AllEdges) {
929 if (E->Removed)
930 continue;
931
932 const BasicBlock *SrcBB = E->SrcBB;
933 const BasicBlock *DestBB = E->DestBB;
934 UseBBInfo &SrcInfo = getBBInfo(SrcBB);
935 UseBBInfo &DestInfo = getBBInfo(DestBB);
936 SrcInfo.OutEdges.push_back(E.get());
937 DestInfo.InEdges.push_back(E.get());
938 SrcInfo.UnknownCountOutEdge++;
939 DestInfo.UnknownCountInEdge++;
940
941 if (!E->CountValid)
942 continue;
943 DestInfo.UnknownCountInEdge--;
944 SrcInfo.UnknownCountOutEdge--;
945 }
946
947 bool Changes = true;
948 unsigned NumPasses = 0;
949 while (Changes) {
950 NumPasses++;
951 Changes = false;
952
953 // For efficient traversal, it's better to start from the end as most
954 // of the instrumented edges are at the end.
955 for (auto &BB : reverse(F)) {
Rong Xua5b57452016-12-02 19:10:29 +0000956 UseBBInfo *Count = findBBInfo(&BB);
957 if (Count == nullptr)
958 continue;
959 if (!Count->CountValid) {
960 if (Count->UnknownCountOutEdge == 0) {
961 Count->CountValue = sumEdgeCount(Count->OutEdges);
962 Count->CountValid = true;
Rong Xuf430ae42015-12-09 18:08:16 +0000963 Changes = true;
Rong Xua5b57452016-12-02 19:10:29 +0000964 } else if (Count->UnknownCountInEdge == 0) {
965 Count->CountValue = sumEdgeCount(Count->InEdges);
966 Count->CountValid = true;
Rong Xuf430ae42015-12-09 18:08:16 +0000967 Changes = true;
968 }
969 }
Rong Xua5b57452016-12-02 19:10:29 +0000970 if (Count->CountValid) {
971 if (Count->UnknownCountOutEdge == 1) {
Rong Xu51a1e3c2016-12-13 06:41:14 +0000972 uint64_t Total = 0;
973 uint64_t OutSum = sumEdgeCount(Count->OutEdges);
974 // If the one of the successor block can early terminate (no-return),
975 // we can end up with situation where out edge sum count is larger as
976 // the source BB's count is collected by a post-dominated block.
977 if (Count->CountValue > OutSum)
978 Total = Count->CountValue - OutSum;
Rong Xua5b57452016-12-02 19:10:29 +0000979 setEdgeCount(Count->OutEdges, Total);
Rong Xuf430ae42015-12-09 18:08:16 +0000980 Changes = true;
981 }
Rong Xua5b57452016-12-02 19:10:29 +0000982 if (Count->UnknownCountInEdge == 1) {
Rong Xu51a1e3c2016-12-13 06:41:14 +0000983 uint64_t Total = 0;
984 uint64_t InSum = sumEdgeCount(Count->InEdges);
985 if (Count->CountValue > InSum)
986 Total = Count->CountValue - InSum;
Rong Xua5b57452016-12-02 19:10:29 +0000987 setEdgeCount(Count->InEdges, Total);
Rong Xuf430ae42015-12-09 18:08:16 +0000988 Changes = true;
989 }
990 }
991 }
992 }
993
994 DEBUG(dbgs() << "Populate counts in " << NumPasses << " passes.\n");
Sean Silva8c7e1212016-05-28 04:19:45 +0000995#ifndef NDEBUG
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000996 // Assert every BB has a valid counter.
Rong Xua5b57452016-12-02 19:10:29 +0000997 for (auto &BB : F) {
998 auto BI = findBBInfo(&BB);
999 if (BI == nullptr)
1000 continue;
1001 assert(BI->CountValid && "BB count is not valid");
1002 }
Sean Silva8c7e1212016-05-28 04:19:45 +00001003#endif
Sean Silva9dd4b5c2016-05-28 03:56:25 +00001004 uint64_t FuncEntryCount = getBBInfo(&*F.begin()).CountValue;
Sean Silva02b9d892016-05-28 04:05:36 +00001005 F.setEntryCount(FuncEntryCount);
Sean Silva9dd4b5c2016-05-28 03:56:25 +00001006 uint64_t FuncMaxCount = FuncEntryCount;
Rong Xua5b57452016-12-02 19:10:29 +00001007 for (auto &BB : F) {
1008 auto BI = findBBInfo(&BB);
1009 if (BI == nullptr)
1010 continue;
1011 FuncMaxCount = std::max(FuncMaxCount, BI->CountValue);
1012 }
Sean Silva9dd4b5c2016-05-28 03:56:25 +00001013 markFunctionAttributes(FuncEntryCount, FuncMaxCount);
Rong Xuf430ae42015-12-09 18:08:16 +00001014
Rong Xu33308f92016-10-25 21:47:24 +00001015 // Now annotate select instructions
1016 FuncInfo.SIVisitor.annotateSelects(F, this, &CountPosition);
1017 assert(CountPosition == ProfileCountSize);
1018
Rong Xuf430ae42015-12-09 18:08:16 +00001019 DEBUG(FuncInfo.dumpInfo("after reading profile."));
1020}
1021
Xinliang David Li4ca17332016-09-18 18:34:07 +00001022static void setProfMetadata(Module *M, Instruction *TI,
Xinliang David Li63248ab2016-08-19 06:31:45 +00001023 ArrayRef<uint64_t> EdgeCounts, uint64_t MaxCount) {
Xinliang David Li2c933682016-08-19 05:31:33 +00001024 MDBuilder MDB(M->getContext());
1025 assert(MaxCount > 0 && "Bad max count");
1026 uint64_t Scale = calculateCountScale(MaxCount);
1027 SmallVector<unsigned, 4> Weights;
1028 for (const auto &ECI : EdgeCounts)
1029 Weights.push_back(scaleBranchCount(ECI, Scale));
1030
1031 DEBUG(dbgs() << "Weight is: ";
Rong Xu0a2a1312017-03-09 19:08:55 +00001032 for (const auto &W : Weights) { dbgs() << W << " "; }
Xinliang David Li2c933682016-08-19 05:31:33 +00001033 dbgs() << "\n";);
1034 TI->setMetadata(llvm::LLVMContext::MD_prof, MDB.createBranchWeights(Weights));
1035}
1036
Rong Xuf430ae42015-12-09 18:08:16 +00001037// Assign the scaled count values to the BB with multiple out edges.
1038void PGOUseFunc::setBranchWeights() {
1039 // Generate MD_prof metadata for every branch instruction.
1040 DEBUG(dbgs() << "\nSetting branch weights.\n");
Rong Xuf430ae42015-12-09 18:08:16 +00001041 for (auto &BB : F) {
1042 TerminatorInst *TI = BB.getTerminator();
1043 if (TI->getNumSuccessors() < 2)
1044 continue;
1045 if (!isa<BranchInst>(TI) && !isa<SwitchInst>(TI))
1046 continue;
1047 if (getBBInfo(&BB).CountValue == 0)
1048 continue;
1049
1050 // We have a non-zero Branch BB.
1051 const UseBBInfo &BBCountInfo = getBBInfo(&BB);
1052 unsigned Size = BBCountInfo.OutEdges.size();
Xinliang David Li63248ab2016-08-19 06:31:45 +00001053 SmallVector<uint64_t, 2> EdgeCounts(Size, 0);
Rong Xuf430ae42015-12-09 18:08:16 +00001054 uint64_t MaxCount = 0;
1055 for (unsigned s = 0; s < Size; s++) {
1056 const PGOUseEdge *E = BBCountInfo.OutEdges[s];
1057 const BasicBlock *SrcBB = E->SrcBB;
1058 const BasicBlock *DestBB = E->DestBB;
Eugene Zelenko6ac3f732016-01-26 18:48:36 +00001059 if (DestBB == nullptr)
Rong Xuf430ae42015-12-09 18:08:16 +00001060 continue;
1061 unsigned SuccNum = GetSuccessorNumber(SrcBB, DestBB);
1062 uint64_t EdgeCount = E->CountValue;
1063 if (EdgeCount > MaxCount)
1064 MaxCount = EdgeCount;
1065 EdgeCounts[SuccNum] = EdgeCount;
1066 }
Xinliang David Li2c933682016-08-19 05:31:33 +00001067 setProfMetadata(M, TI, EdgeCounts, MaxCount);
Rong Xuf430ae42015-12-09 18:08:16 +00001068 }
1069}
Rong Xu13b01dc2016-02-10 18:24:45 +00001070
Xinliang David Li4ca17332016-09-18 18:34:07 +00001071void SelectInstVisitor::instrumentOneSelectInst(SelectInst &SI) {
1072 Module *M = F.getParent();
1073 IRBuilder<> Builder(&SI);
1074 Type *Int64Ty = Builder.getInt64Ty();
1075 Type *I8PtrTy = Builder.getInt8PtrTy();
1076 auto *Step = Builder.CreateZExt(SI.getCondition(), Int64Ty);
1077 Builder.CreateCall(
1078 Intrinsic::getDeclaration(M, Intrinsic::instrprof_increment_step),
1079 {llvm::ConstantExpr::getBitCast(FuncNameVar, I8PtrTy),
Rong Xu0a2a1312017-03-09 19:08:55 +00001080 Builder.getInt64(FuncHash), Builder.getInt32(TotalNumCtrs),
1081 Builder.getInt32(*CurCtrIdx), Step});
Xinliang David Li4ca17332016-09-18 18:34:07 +00001082 ++(*CurCtrIdx);
1083}
1084
1085void SelectInstVisitor::annotateOneSelectInst(SelectInst &SI) {
1086 std::vector<uint64_t> &CountFromProfile = UseFunc->getProfileRecord().Counts;
1087 assert(*CurCtrIdx < CountFromProfile.size() &&
1088 "Out of bound access of counters");
1089 uint64_t SCounts[2];
1090 SCounts[0] = CountFromProfile[*CurCtrIdx]; // True count
1091 ++(*CurCtrIdx);
Rong Xua5b57452016-12-02 19:10:29 +00001092 uint64_t TotalCount = 0;
1093 auto BI = UseFunc->findBBInfo(SI.getParent());
1094 if (BI != nullptr)
1095 TotalCount = BI->CountValue;
Xinliang David Li4ca17332016-09-18 18:34:07 +00001096 // False Count
1097 SCounts[1] = (TotalCount > SCounts[0] ? TotalCount - SCounts[0] : 0);
1098 uint64_t MaxCount = std::max(SCounts[0], SCounts[1]);
Xinliang David Lic7368282016-09-20 20:20:01 +00001099 if (MaxCount)
1100 setProfMetadata(F.getParent(), &SI, SCounts, MaxCount);
Xinliang David Li4ca17332016-09-18 18:34:07 +00001101}
1102
1103void SelectInstVisitor::visitSelectInst(SelectInst &SI) {
1104 if (!PGOInstrSelect)
1105 return;
1106 // FIXME: do not handle this yet.
1107 if (SI.getCondition()->getType()->isVectorTy())
1108 return;
1109
Xinliang David Li4ca17332016-09-18 18:34:07 +00001110 switch (Mode) {
1111 case VM_counting:
Vitaly Bukaca6ecd22017-03-15 23:07:41 +00001112 NSIs++;
Xinliang David Li4ca17332016-09-18 18:34:07 +00001113 return;
1114 case VM_instrument:
1115 instrumentOneSelectInst(SI);
Simon Pilgrimf33a6b72016-09-18 21:08:35 +00001116 return;
Xinliang David Li4ca17332016-09-18 18:34:07 +00001117 case VM_annotate:
1118 annotateOneSelectInst(SI);
Simon Pilgrimf33a6b72016-09-18 21:08:35 +00001119 return;
Xinliang David Li4ca17332016-09-18 18:34:07 +00001120 }
Simon Pilgrimf33a6b72016-09-18 21:08:35 +00001121
1122 llvm_unreachable("Unknown visiting mode");
Xinliang David Li4ca17332016-09-18 18:34:07 +00001123}
1124
Rong Xu4ed52792017-03-15 21:47:27 +00001125void MemIntrinsicVisitor::instrumentOneMemIntrinsic(MemIntrinsic &MI) {
1126 Module *M = F.getParent();
1127 IRBuilder<> Builder(&MI);
1128 Type *Int64Ty = Builder.getInt64Ty();
1129 Type *I8PtrTy = Builder.getInt8PtrTy();
1130 Value *Length = MI.getLength();
1131 assert(!dyn_cast<ConstantInt>(Length));
1132 Builder.CreateCall(
1133 Intrinsic::getDeclaration(M, Intrinsic::instrprof_value_profile),
1134 {llvm::ConstantExpr::getBitCast(FuncNameVar, I8PtrTy),
1135 Builder.getInt64(FuncHash), Builder.CreatePtrToInt(Length, Int64Ty),
1136 Builder.getInt32(IPVK_MemOPSize), Builder.getInt32(CurCtrId)});
1137 ++CurCtrId;
1138}
1139
1140void MemIntrinsicVisitor::visitMemIntrinsic(MemIntrinsic &MI) {
1141 if (!PGOInstrMemOP)
1142 return;
1143 Value *Length = MI.getLength();
1144 // Not instrument constant length calls.
1145 if (dyn_cast<ConstantInt>(Length))
1146 return;
1147
1148 NMemIs++;
1149 switch (Mode) {
1150 case VM_counting:
1151 return;
1152 case VM_instrument:
1153 instrumentOneMemIntrinsic(MI);
1154 return;
1155 case VM_annotate:
1156 break;
1157 }
1158 llvm_unreachable("Unknown visiting mode");
1159}
1160
Rong Xua3bbf962017-03-15 18:23:39 +00001161// Traverse all valuesites and annotate the instructions for all value kind.
1162void PGOUseFunc::annotateValueSites() {
Rong Xu13b01dc2016-02-10 18:24:45 +00001163 if (DisableValueProfiling)
1164 return;
1165
Rong Xu8e8fe852016-04-01 16:43:30 +00001166 // Create the PGOFuncName meta data.
Rong Xuf8f051c2016-04-22 21:00:17 +00001167 createPGOFuncNameMetadata(F, FuncInfo.FuncName);
Rong Xub5341662016-03-30 18:37:52 +00001168
Rong Xua3bbf962017-03-15 18:23:39 +00001169 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
1170 annotateValueSites(Kind);
1171}
1172
1173// Annotate the instructions for a specific value kind.
1174void PGOUseFunc::annotateValueSites(uint32_t Kind) {
1175 unsigned ValueSiteIndex = 0;
1176 auto &ValueSites = FuncInfo.ValueSites[Kind];
1177 unsigned NumValueSites = ProfileRecord.getNumValueSites(Kind);
1178 if (NumValueSites != ValueSites.size()) {
Rong Xu13b01dc2016-02-10 18:24:45 +00001179 auto &Ctx = M->getContext();
Rong Xua3bbf962017-03-15 18:23:39 +00001180 Ctx.diagnose(DiagnosticInfoPGOProfile(
1181 M->getName().data(),
1182 Twine("Inconsistent number of value sites for kind = ") + Twine(Kind) +
1183 " in " + F.getName().str(),
1184 DS_Warning));
Rong Xu13b01dc2016-02-10 18:24:45 +00001185 return;
1186 }
1187
Rong Xua3bbf962017-03-15 18:23:39 +00001188 for (auto &I : ValueSites) {
1189 DEBUG(dbgs() << "Read one value site profile (kind = " << Kind
1190 << "): Index = " << ValueSiteIndex << " out of "
1191 << NumValueSites << "\n");
1192 annotateValueSite(*M, *I, ProfileRecord,
1193 static_cast<InstrProfValueKind>(Kind), ValueSiteIndex,
1194 MaxNumAnnotations);
1195 ValueSiteIndex++;
Rong Xu13b01dc2016-02-10 18:24:45 +00001196 }
1197}
Rong Xuf430ae42015-12-09 18:08:16 +00001198} // end anonymous namespace
1199
Xinliang David Lid382e9d2016-07-22 04:46:56 +00001200// Create a COMDAT variable INSTR_PROF_RAW_VERSION_VAR to make the runtime
Rong Xu33c76c02016-02-10 17:18:30 +00001201// aware this is an ir_level profile so it can set the version flag.
1202static void createIRLevelProfileFlagVariable(Module &M) {
1203 Type *IntTy64 = Type::getInt64Ty(M.getContext());
1204 uint64_t ProfileVersion = (INSTR_PROF_RAW_VERSION | VARIANT_MASK_IR_PROF);
Rong Xu9e926e82016-02-29 19:16:04 +00001205 auto IRLevelVersionVariable = new GlobalVariable(
1206 M, IntTy64, true, GlobalVariable::ExternalLinkage,
1207 Constant::getIntegerValue(IntTy64, APInt(64, ProfileVersion)),
Xinliang David Lid382e9d2016-07-22 04:46:56 +00001208 INSTR_PROF_QUOTE(INSTR_PROF_RAW_VERSION_VAR));
Rong Xu33c76c02016-02-10 17:18:30 +00001209 IRLevelVersionVariable->setVisibility(GlobalValue::DefaultVisibility);
1210 Triple TT(M.getTargetTriple());
Xinliang David Li11c849c2016-05-27 16:22:03 +00001211 if (!TT.supportsCOMDAT())
Rong Xuca28a0a2016-05-11 00:31:59 +00001212 IRLevelVersionVariable->setLinkage(GlobalValue::WeakAnyLinkage);
Rong Xu33c76c02016-02-10 17:18:30 +00001213 else
Rong Xu9e926e82016-02-29 19:16:04 +00001214 IRLevelVersionVariable->setComdat(M.getOrInsertComdat(
Xinliang David Lid382e9d2016-07-22 04:46:56 +00001215 StringRef(INSTR_PROF_QUOTE(INSTR_PROF_RAW_VERSION_VAR))));
Rong Xu33c76c02016-02-10 17:18:30 +00001216}
1217
Rong Xu705f7772016-07-25 18:45:37 +00001218// Collect the set of members for each Comdat in module M and store
1219// in ComdatMembers.
1220static void collectComdatMembers(
1221 Module &M,
1222 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers) {
1223 if (!DoComdatRenaming)
1224 return;
1225 for (Function &F : M)
1226 if (Comdat *C = F.getComdat())
1227 ComdatMembers.insert(std::make_pair(C, &F));
1228 for (GlobalVariable &GV : M.globals())
1229 if (Comdat *C = GV.getComdat())
1230 ComdatMembers.insert(std::make_pair(C, &GV));
1231 for (GlobalAlias &GA : M.aliases())
1232 if (Comdat *C = GA.getComdat())
1233 ComdatMembers.insert(std::make_pair(C, &GA));
1234}
1235
Xinliang David Li5ad7c822016-05-02 20:33:59 +00001236static bool InstrumentAllFunctions(
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001237 Module &M, function_ref<BranchProbabilityInfo *(Function &)> LookupBPI,
1238 function_ref<BlockFrequencyInfo *(Function &)> LookupBFI) {
Rong Xu33c76c02016-02-10 17:18:30 +00001239 createIRLevelProfileFlagVariable(M);
Rong Xu705f7772016-07-25 18:45:37 +00001240 std::unordered_multimap<Comdat *, GlobalValue *> ComdatMembers;
1241 collectComdatMembers(M, ComdatMembers);
1242
Rong Xuf430ae42015-12-09 18:08:16 +00001243 for (auto &F : M) {
1244 if (F.isDeclaration())
1245 continue;
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001246 auto *BPI = LookupBPI(F);
1247 auto *BFI = LookupBFI(F);
Rong Xu705f7772016-07-25 18:45:37 +00001248 instrumentOneFunc(F, &M, BPI, BFI, ComdatMembers);
Rong Xuf430ae42015-12-09 18:08:16 +00001249 }
1250 return true;
1251}
1252
Xinliang David Li8aebf442016-05-06 05:49:19 +00001253bool PGOInstrumentationGenLegacyPass::runOnModule(Module &M) {
Xinliang David Li5ad7c822016-05-02 20:33:59 +00001254 if (skipModule(M))
1255 return false;
1256
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001257 auto LookupBPI = [this](Function &F) {
1258 return &this->getAnalysis<BranchProbabilityInfoWrapperPass>(F).getBPI();
Xinliang David Li5ad7c822016-05-02 20:33:59 +00001259 };
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001260 auto LookupBFI = [this](Function &F) {
1261 return &this->getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI();
Xinliang David Li5ad7c822016-05-02 20:33:59 +00001262 };
1263 return InstrumentAllFunctions(M, LookupBPI, LookupBFI);
1264}
1265
Xinliang David Li8aebf442016-05-06 05:49:19 +00001266PreservedAnalyses PGOInstrumentationGen::run(Module &M,
Sean Silvafd03ac62016-08-09 00:28:38 +00001267 ModuleAnalysisManager &AM) {
Xinliang David Li8aebf442016-05-06 05:49:19 +00001268
1269 auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001270 auto LookupBPI = [&FAM](Function &F) {
1271 return &FAM.getResult<BranchProbabilityAnalysis>(F);
Xinliang David Li8aebf442016-05-06 05:49:19 +00001272 };
1273
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001274 auto LookupBFI = [&FAM](Function &F) {
1275 return &FAM.getResult<BlockFrequencyAnalysis>(F);
Xinliang David Li8aebf442016-05-06 05:49:19 +00001276 };
1277
1278 if (!InstrumentAllFunctions(M, LookupBPI, LookupBFI))
1279 return PreservedAnalyses::all();
1280
1281 return PreservedAnalyses::none();
1282}
1283
Xinliang David Lida195582016-05-10 21:59:52 +00001284static bool annotateAllFunctions(
1285 Module &M, StringRef ProfileFileName,
1286 function_ref<BranchProbabilityInfo *(Function &)> LookupBPI,
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001287 function_ref<BlockFrequencyInfo *(Function &)> LookupBFI) {
Rong Xuf430ae42015-12-09 18:08:16 +00001288 DEBUG(dbgs() << "Read in profile counters: ");
1289 auto &Ctx = M.getContext();
1290 // Read the counter array from file.
1291 auto ReaderOrErr = IndexedInstrProfReader::create(ProfileFileName);
Vedant Kumar9152fd12016-05-19 03:54:45 +00001292 if (Error E = ReaderOrErr.takeError()) {
1293 handleAllErrors(std::move(E), [&](const ErrorInfoBase &EI) {
1294 Ctx.diagnose(
1295 DiagnosticInfoPGOProfile(ProfileFileName.data(), EI.message()));
1296 });
Rong Xuf430ae42015-12-09 18:08:16 +00001297 return false;
1298 }
1299
Xinliang David Lida195582016-05-10 21:59:52 +00001300 std::unique_ptr<IndexedInstrProfReader> PGOReader =
1301 std::move(ReaderOrErr.get());
Rong Xuf430ae42015-12-09 18:08:16 +00001302 if (!PGOReader) {
1303 Ctx.diagnose(DiagnosticInfoPGOProfile(ProfileFileName.data(),
Xinliang David Lida195582016-05-10 21:59:52 +00001304 StringRef("Cannot get PGOReader")));
Rong Xuf430ae42015-12-09 18:08:16 +00001305 return false;
1306 }
Rong Xu33c76c02016-02-10 17:18:30 +00001307 // TODO: might need to change the warning once the clang option is finalized.
1308 if (!PGOReader->isIRLevelProfile()) {
1309 Ctx.diagnose(DiagnosticInfoPGOProfile(
1310 ProfileFileName.data(), "Not an IR level instrumentation profile"));
1311 return false;
1312 }
1313
Rong Xu705f7772016-07-25 18:45:37 +00001314 std::unordered_multimap<Comdat *, GlobalValue *> ComdatMembers;
1315 collectComdatMembers(M, ComdatMembers);
Rong Xu6090afd2016-03-28 17:08:56 +00001316 std::vector<Function *> HotFunctions;
1317 std::vector<Function *> ColdFunctions;
Rong Xuf430ae42015-12-09 18:08:16 +00001318 for (auto &F : M) {
1319 if (F.isDeclaration())
1320 continue;
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001321 auto *BPI = LookupBPI(F);
1322 auto *BFI = LookupBFI(F);
Rong Xu705f7772016-07-25 18:45:37 +00001323 PGOUseFunc Func(F, &M, ComdatMembers, BPI, BFI);
Sean Silva2e8f0952016-05-28 04:19:40 +00001324 if (!Func.readCounters(PGOReader.get()))
1325 continue;
1326 Func.populateCounters();
1327 Func.setBranchWeights();
Rong Xua3bbf962017-03-15 18:23:39 +00001328 Func.annotateValueSites();
Sean Silva9dd4b5c2016-05-28 03:56:25 +00001329 PGOUseFunc::FuncFreqAttr FreqAttr = Func.getFuncFreqAttr();
1330 if (FreqAttr == PGOUseFunc::FFA_Cold)
Sean Silva2a730192016-05-28 03:02:50 +00001331 ColdFunctions.push_back(&F);
Sean Silva9dd4b5c2016-05-28 03:56:25 +00001332 else if (FreqAttr == PGOUseFunc::FFA_Hot)
1333 HotFunctions.push_back(&F);
Xinliang David Li58fcc9b2017-02-02 21:29:17 +00001334 if (PGOViewCounts && (ViewBlockFreqFuncName.empty() ||
1335 F.getName().equals(ViewBlockFreqFuncName))) {
Xinliang David Licb253ce2017-01-23 18:58:24 +00001336 LoopInfo LI{DominatorTree(F)};
1337 std::unique_ptr<BranchProbabilityInfo> NewBPI =
1338 llvm::make_unique<BranchProbabilityInfo>(F, LI);
1339 std::unique_ptr<BlockFrequencyInfo> NewBFI =
1340 llvm::make_unique<BlockFrequencyInfo>(F, *NewBPI, LI);
1341
1342 NewBFI->view();
1343 }
Xinliang David Li58fcc9b2017-02-02 21:29:17 +00001344 if (PGOViewRawCounts && (ViewBlockFreqFuncName.empty() ||
1345 F.getName().equals(ViewBlockFreqFuncName))) {
1346 if (ViewBlockFreqFuncName.empty())
Xinliang David Lid289e452017-01-27 19:06:25 +00001347 WriteGraph(&Func, Twine("PGORawCounts_") + Func.getFunc().getName());
1348 else
1349 ViewGraph(&Func, Twine("PGORawCounts_") + Func.getFunc().getName());
1350 }
Rong Xuf430ae42015-12-09 18:08:16 +00001351 }
Easwaran Raman8bceb9d2016-06-21 19:29:49 +00001352 M.setProfileSummary(PGOReader->getSummary().getMD(M.getContext()));
Rong Xu6090afd2016-03-28 17:08:56 +00001353 // Set function hotness attribute from the profile.
Sean Silva42cc3422016-05-28 04:24:39 +00001354 // We have to apply these attributes at the end because their presence
1355 // can affect the BranchProbabilityInfo of any callers, resulting in an
1356 // inconsistent MST between prof-gen and prof-use.
Rong Xu6090afd2016-03-28 17:08:56 +00001357 for (auto &F : HotFunctions) {
1358 F->addFnAttr(llvm::Attribute::InlineHint);
1359 DEBUG(dbgs() << "Set inline attribute to function: " << F->getName()
1360 << "\n");
1361 }
1362 for (auto &F : ColdFunctions) {
1363 F->addFnAttr(llvm::Attribute::Cold);
1364 DEBUG(dbgs() << "Set cold attribute to function: " << F->getName() << "\n");
1365 }
Rong Xuf430ae42015-12-09 18:08:16 +00001366 return true;
1367}
Xinliang David Lid55827f2016-05-07 05:39:12 +00001368
Xinliang David Lida195582016-05-10 21:59:52 +00001369PGOInstrumentationUse::PGOInstrumentationUse(std::string Filename)
Benjamin Kramer82de7d32016-05-27 14:27:24 +00001370 : ProfileFileName(std::move(Filename)) {
Xinliang David Lida195582016-05-10 21:59:52 +00001371 if (!PGOTestProfileFile.empty())
1372 ProfileFileName = PGOTestProfileFile;
1373}
1374
1375PreservedAnalyses PGOInstrumentationUse::run(Module &M,
Sean Silvafd03ac62016-08-09 00:28:38 +00001376 ModuleAnalysisManager &AM) {
Xinliang David Lida195582016-05-10 21:59:52 +00001377
1378 auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
1379 auto LookupBPI = [&FAM](Function &F) {
1380 return &FAM.getResult<BranchProbabilityAnalysis>(F);
1381 };
1382
1383 auto LookupBFI = [&FAM](Function &F) {
1384 return &FAM.getResult<BlockFrequencyAnalysis>(F);
1385 };
1386
1387 if (!annotateAllFunctions(M, ProfileFileName, LookupBPI, LookupBFI))
1388 return PreservedAnalyses::all();
1389
1390 return PreservedAnalyses::none();
1391}
1392
Xinliang David Lid55827f2016-05-07 05:39:12 +00001393bool PGOInstrumentationUseLegacyPass::runOnModule(Module &M) {
1394 if (skipModule(M))
1395 return false;
1396
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001397 auto LookupBPI = [this](Function &F) {
1398 return &this->getAnalysis<BranchProbabilityInfoWrapperPass>(F).getBPI();
Xinliang David Lid55827f2016-05-07 05:39:12 +00001399 };
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001400 auto LookupBFI = [this](Function &F) {
1401 return &this->getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI();
Xinliang David Lid55827f2016-05-07 05:39:12 +00001402 };
1403
Xinliang David Lida195582016-05-10 21:59:52 +00001404 return annotateAllFunctions(M, ProfileFileName, LookupBPI, LookupBFI);
Xinliang David Lid55827f2016-05-07 05:39:12 +00001405}
Xinliang David Lid289e452017-01-27 19:06:25 +00001406
1407namespace llvm {
1408template <> struct GraphTraits<PGOUseFunc *> {
1409 typedef const BasicBlock *NodeRef;
1410 typedef succ_const_iterator ChildIteratorType;
1411 typedef pointer_iterator<Function::const_iterator> nodes_iterator;
1412
1413 static NodeRef getEntryNode(const PGOUseFunc *G) {
1414 return &G->getFunc().front();
1415 }
1416 static ChildIteratorType child_begin(const NodeRef N) {
1417 return succ_begin(N);
1418 }
1419 static ChildIteratorType child_end(const NodeRef N) { return succ_end(N); }
1420 static nodes_iterator nodes_begin(const PGOUseFunc *G) {
1421 return nodes_iterator(G->getFunc().begin());
1422 }
1423 static nodes_iterator nodes_end(const PGOUseFunc *G) {
1424 return nodes_iterator(G->getFunc().end());
1425 }
1426};
1427
Xinliang David Li6144a592017-02-03 21:57:51 +00001428static std::string getSimpleNodeName(const BasicBlock *Node) {
1429 if (!Node->getName().empty())
1430 return Node->getName();
1431
1432 std::string SimpleNodeName;
1433 raw_string_ostream OS(SimpleNodeName);
1434 Node->printAsOperand(OS, false);
1435 return OS.str();
1436}
1437
Xinliang David Lid289e452017-01-27 19:06:25 +00001438template <> struct DOTGraphTraits<PGOUseFunc *> : DefaultDOTGraphTraits {
1439 explicit DOTGraphTraits(bool isSimple = false)
1440 : DefaultDOTGraphTraits(isSimple) {}
1441
1442 static std::string getGraphName(const PGOUseFunc *G) {
1443 return G->getFunc().getName();
1444 }
1445
1446 std::string getNodeLabel(const BasicBlock *Node, const PGOUseFunc *Graph) {
1447 std::string Result;
1448 raw_string_ostream OS(Result);
Xinliang David Li6144a592017-02-03 21:57:51 +00001449
1450 OS << getSimpleNodeName(Node) << ":\\l";
Xinliang David Lid289e452017-01-27 19:06:25 +00001451 UseBBInfo *BI = Graph->findBBInfo(Node);
Xinliang David Li6144a592017-02-03 21:57:51 +00001452 OS << "Count : ";
Xinliang David Lid289e452017-01-27 19:06:25 +00001453 if (BI && BI->CountValid)
Xinliang David Li6144a592017-02-03 21:57:51 +00001454 OS << BI->CountValue << "\\l";
Xinliang David Lid289e452017-01-27 19:06:25 +00001455 else
Xinliang David Li6144a592017-02-03 21:57:51 +00001456 OS << "Unknown\\l";
1457
1458 if (!PGOInstrSelect)
1459 return Result;
1460
1461 for (auto BI = Node->begin(); BI != Node->end(); ++BI) {
1462 auto *I = &*BI;
1463 if (!isa<SelectInst>(I))
1464 continue;
1465 // Display scaled counts for SELECT instruction:
1466 OS << "SELECT : { T = ";
1467 uint64_t TC, FC;
Xinliang David Lic7db0d02017-02-04 07:40:43 +00001468 bool HasProf = I->extractProfMetadata(TC, FC);
1469 if (!HasProf)
Xinliang David Li6144a592017-02-03 21:57:51 +00001470 OS << "Unknown, F = Unknown }\\l";
1471 else
1472 OS << TC << ", F = " << FC << " }\\l";
1473 }
Xinliang David Lid289e452017-01-27 19:06:25 +00001474 return Result;
1475 }
1476};
Rong Xu0a2a1312017-03-09 19:08:55 +00001477} // namespace llvm