blob: 04f9a64bef9fc7ee757953209cd56c38112a0532 [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"
Rong Xued9fec72016-01-21 18:11:44 +000061#include "llvm/IR/CallSite.h"
Rong Xuf430ae42015-12-09 18:08:16 +000062#include "llvm/IR/DiagnosticInfo.h"
Rong Xu705f7772016-07-25 18:45:37 +000063#include "llvm/IR/GlobalValue.h"
Rong Xuf430ae42015-12-09 18:08:16 +000064#include "llvm/IR/IRBuilder.h"
65#include "llvm/IR/InstIterator.h"
66#include "llvm/IR/Instructions.h"
67#include "llvm/IR/IntrinsicInst.h"
68#include "llvm/IR/MDBuilder.h"
69#include "llvm/IR/Module.h"
70#include "llvm/Pass.h"
71#include "llvm/ProfileData/InstrProfReader.h"
Easwaran Raman5fe04a12016-05-26 22:57:11 +000072#include "llvm/ProfileData/ProfileCommon.h"
Rong Xuf430ae42015-12-09 18:08:16 +000073#include "llvm/Support/BranchProbability.h"
74#include "llvm/Support/Debug.h"
75#include "llvm/Support/JamCRC.h"
Rong Xued9fec72016-01-21 18:11:44 +000076#include "llvm/Transforms/Instrumentation.h"
Rong Xuf430ae42015-12-09 18:08:16 +000077#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Xinliang David Li8aebf442016-05-06 05:49:19 +000078#include <algorithm>
Rong Xuf430ae42015-12-09 18:08:16 +000079#include <string>
Rong Xu705f7772016-07-25 18:45:37 +000080#include <unordered_map>
Rong Xuf430ae42015-12-09 18:08:16 +000081#include <utility>
82#include <vector>
83
84using namespace llvm;
85
86#define DEBUG_TYPE "pgo-instrumentation"
87
88STATISTIC(NumOfPGOInstrument, "Number of edges instrumented.");
Xinliang David Li4ca17332016-09-18 18:34:07 +000089STATISTIC(NumOfPGOSelectInsts, "Number of select instruction instrumented.");
Rong Xuf430ae42015-12-09 18:08:16 +000090STATISTIC(NumOfPGOEdge, "Number of edges.");
91STATISTIC(NumOfPGOBB, "Number of basic-blocks.");
92STATISTIC(NumOfPGOSplit, "Number of critical edge splits.");
93STATISTIC(NumOfPGOFunc, "Number of functions having valid profile counts.");
94STATISTIC(NumOfPGOMismatch, "Number of functions having mismatch profile.");
95STATISTIC(NumOfPGOMissing, "Number of functions without profile.");
Rong Xu13b01dc2016-02-10 18:24:45 +000096STATISTIC(NumOfPGOICall, "Number of indirect call value instrumentations.");
Rong Xuf430ae42015-12-09 18:08:16 +000097
98// Command line option to specify the file to read profile from. This is
99// mainly used for testing.
100static cl::opt<std::string>
101 PGOTestProfileFile("pgo-test-profile-file", cl::init(""), cl::Hidden,
102 cl::value_desc("filename"),
103 cl::desc("Specify the path of profile data file. This is"
104 "mainly for test purpose."));
105
Rong Xuecdc98f2016-03-04 22:08:44 +0000106// Command line option to disable value profiling. The default is false:
Rong Xu13b01dc2016-02-10 18:24:45 +0000107// i.e. value profiling is enabled by default. This is for debug purpose.
Rong Xu9e926e82016-02-29 19:16:04 +0000108static cl::opt<bool> DisableValueProfiling("disable-vp", cl::init(false),
109 cl::Hidden,
110 cl::desc("Disable Value Profiling"));
Rong Xued9fec72016-01-21 18:11:44 +0000111
Rong Xuecdc98f2016-03-04 22:08:44 +0000112// Command line option to set the maximum number of VP annotations to write to
Rong Xu08afb052016-04-28 17:31:22 +0000113// the metadata for a single indirect call callsite.
114static cl::opt<unsigned> MaxNumAnnotations(
115 "icp-max-annotations", cl::init(3), cl::Hidden, cl::ZeroOrMore,
116 cl::desc("Max number of annotations for a single indirect "
117 "call callsite"));
Rong Xuecdc98f2016-03-04 22:08:44 +0000118
Rong Xu705f7772016-07-25 18:45:37 +0000119// Command line option to control appending FunctionHash to the name of a COMDAT
120// function. This is to avoid the hash mismatch caused by the preinliner.
121static cl::opt<bool> DoComdatRenaming(
Rong Xu20f5df12017-01-11 20:19:41 +0000122 "do-comdat-renaming", cl::init(false), cl::Hidden,
Rong Xu705f7772016-07-25 18:45:37 +0000123 cl::desc("Append function hash to the name of COMDAT function to avoid "
124 "function hash mismatch due to the preinliner"));
125
Rong Xu0698de92016-05-13 17:26:06 +0000126// Command line option to enable/disable the warning about missing profile
127// information.
Xinliang David Li76a01082016-08-11 05:09:30 +0000128static cl::opt<bool> PGOWarnMissing("pgo-warn-missing-function",
129 cl::init(false),
130 cl::Hidden);
Rong Xu0698de92016-05-13 17:26:06 +0000131
132// Command line option to enable/disable the warning about a hash mismatch in
133// the profile data.
134static cl::opt<bool> NoPGOWarnMismatch("no-pgo-warn-mismatch", cl::init(false),
135 cl::Hidden);
136
Rong Xu20f5df12017-01-11 20:19:41 +0000137// Command line option to enable/disable the warning about a hash mismatch in
138// the profile data for Comdat functions, which often turns out to be false
139// positive due to the pre-instrumentation inline.
140static cl::opt<bool> NoPGOWarnMismatchComdat("no-pgo-warn-mismatch-comdat",
141 cl::init(true), cl::Hidden);
142
Xinliang David Li4ca17332016-09-18 18:34:07 +0000143// Command line option to enable/disable select instruction instrumentation.
144static cl::opt<bool> PGOInstrSelect("pgo-instr-select", cl::init(true),
145 cl::Hidden);
Rong Xuf430ae42015-12-09 18:08:16 +0000146namespace {
Xinliang David Li4ca17332016-09-18 18:34:07 +0000147
148/// The select instruction visitor plays three roles specified
149/// by the mode. In \c VM_counting mode, it simply counts the number of
150/// select instructions. In \c VM_instrument mode, it inserts code to count
151/// the number times TrueValue of select is taken. In \c VM_annotate mode,
152/// it reads the profile data and annotate the select instruction with metadata.
153enum VisitMode { VM_counting, VM_instrument, VM_annotate };
154class PGOUseFunc;
155
156/// Instruction Visitor class to visit select instructions.
157struct SelectInstVisitor : public InstVisitor<SelectInstVisitor> {
158 Function &F;
159 unsigned NSIs = 0; // Number of select instructions instrumented.
160 VisitMode Mode = VM_counting; // Visiting mode.
161 unsigned *CurCtrIdx = nullptr; // Pointer to current counter index.
162 unsigned TotalNumCtrs = 0; // Total number of counters
163 GlobalVariable *FuncNameVar = nullptr;
164 uint64_t FuncHash = 0;
165 PGOUseFunc *UseFunc = nullptr;
166
167 SelectInstVisitor(Function &Func) : F(Func) {}
168
169 void countSelects(Function &Func) {
170 Mode = VM_counting;
171 visit(Func);
172 }
173 // Visit the IR stream and instrument all select instructions. \p
174 // Ind is a pointer to the counter index variable; \p TotalNC
175 // is the total number of counters; \p FNV is the pointer to the
176 // PGO function name var; \p FHash is the function hash.
177 void instrumentSelects(Function &Func, unsigned *Ind, unsigned TotalNC,
178 GlobalVariable *FNV, uint64_t FHash) {
179 Mode = VM_instrument;
180 CurCtrIdx = Ind;
181 TotalNumCtrs = TotalNC;
182 FuncHash = FHash;
183 FuncNameVar = FNV;
184 visit(Func);
185 }
186
187 // Visit the IR stream and annotate all select instructions.
188 void annotateSelects(Function &Func, PGOUseFunc *UF, unsigned *Ind) {
189 Mode = VM_annotate;
190 UseFunc = UF;
191 CurCtrIdx = Ind;
192 visit(Func);
193 }
194
195 void instrumentOneSelectInst(SelectInst &SI);
196 void annotateOneSelectInst(SelectInst &SI);
197 // Visit \p SI instruction and perform tasks according to visit mode.
198 void visitSelectInst(SelectInst &SI);
199 unsigned getNumOfSelectInsts() const { return NSIs; }
200};
201
Xinliang David Li8aebf442016-05-06 05:49:19 +0000202class PGOInstrumentationGenLegacyPass : public ModulePass {
Rong Xuf430ae42015-12-09 18:08:16 +0000203public:
204 static char ID;
205
Xinliang David Lidfa21c32016-05-09 21:37:12 +0000206 PGOInstrumentationGenLegacyPass() : ModulePass(ID) {
Xinliang David Li8aebf442016-05-06 05:49:19 +0000207 initializePGOInstrumentationGenLegacyPassPass(
208 *PassRegistry::getPassRegistry());
Rong Xuf430ae42015-12-09 18:08:16 +0000209 }
210
Mehdi Amini117296c2016-10-01 02:56:57 +0000211 StringRef getPassName() const override { return "PGOInstrumentationGenPass"; }
Rong Xuf430ae42015-12-09 18:08:16 +0000212
213private:
214 bool runOnModule(Module &M) override;
215
216 void getAnalysisUsage(AnalysisUsage &AU) const override {
217 AU.addRequired<BlockFrequencyInfoWrapperPass>();
218 }
219};
220
Xinliang David Lid55827f2016-05-07 05:39:12 +0000221class PGOInstrumentationUseLegacyPass : public ModulePass {
Rong Xuf430ae42015-12-09 18:08:16 +0000222public:
223 static char ID;
224
225 // Provide the profile filename as the parameter.
Xinliang David Lid55827f2016-05-07 05:39:12 +0000226 PGOInstrumentationUseLegacyPass(std::string Filename = "")
Benjamin Kramer82de7d32016-05-27 14:27:24 +0000227 : ModulePass(ID), ProfileFileName(std::move(Filename)) {
Rong Xuf430ae42015-12-09 18:08:16 +0000228 if (!PGOTestProfileFile.empty())
229 ProfileFileName = PGOTestProfileFile;
Xinliang David Lid55827f2016-05-07 05:39:12 +0000230 initializePGOInstrumentationUseLegacyPassPass(
231 *PassRegistry::getPassRegistry());
Rong Xuf430ae42015-12-09 18:08:16 +0000232 }
233
Mehdi Amini117296c2016-10-01 02:56:57 +0000234 StringRef getPassName() const override { return "PGOInstrumentationUsePass"; }
Rong Xuf430ae42015-12-09 18:08:16 +0000235
236private:
237 std::string ProfileFileName;
Rong Xuf430ae42015-12-09 18:08:16 +0000238
Xinliang David Lida195582016-05-10 21:59:52 +0000239 bool runOnModule(Module &M) override;
Rong Xuf430ae42015-12-09 18:08:16 +0000240 void getAnalysisUsage(AnalysisUsage &AU) const override {
241 AU.addRequired<BlockFrequencyInfoWrapperPass>();
242 }
243};
Xinliang David Li4ca17332016-09-18 18:34:07 +0000244
Rong Xuf430ae42015-12-09 18:08:16 +0000245} // end anonymous namespace
246
Xinliang David Li8aebf442016-05-06 05:49:19 +0000247char PGOInstrumentationGenLegacyPass::ID = 0;
248INITIALIZE_PASS_BEGIN(PGOInstrumentationGenLegacyPass, "pgo-instr-gen",
Rong Xuf430ae42015-12-09 18:08:16 +0000249 "PGO instrumentation.", false, false)
250INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
251INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
Xinliang David Li8aebf442016-05-06 05:49:19 +0000252INITIALIZE_PASS_END(PGOInstrumentationGenLegacyPass, "pgo-instr-gen",
Rong Xuf430ae42015-12-09 18:08:16 +0000253 "PGO instrumentation.", false, false)
254
Xinliang David Li8aebf442016-05-06 05:49:19 +0000255ModulePass *llvm::createPGOInstrumentationGenLegacyPass() {
256 return new PGOInstrumentationGenLegacyPass();
Rong Xuf430ae42015-12-09 18:08:16 +0000257}
258
Xinliang David Lid55827f2016-05-07 05:39:12 +0000259char PGOInstrumentationUseLegacyPass::ID = 0;
260INITIALIZE_PASS_BEGIN(PGOInstrumentationUseLegacyPass, "pgo-instr-use",
Rong Xuf430ae42015-12-09 18:08:16 +0000261 "Read PGO instrumentation profile.", false, false)
262INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
263INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
Xinliang David Lid55827f2016-05-07 05:39:12 +0000264INITIALIZE_PASS_END(PGOInstrumentationUseLegacyPass, "pgo-instr-use",
Rong Xuf430ae42015-12-09 18:08:16 +0000265 "Read PGO instrumentation profile.", false, false)
266
Xinliang David Lid55827f2016-05-07 05:39:12 +0000267ModulePass *llvm::createPGOInstrumentationUseLegacyPass(StringRef Filename) {
268 return new PGOInstrumentationUseLegacyPass(Filename.str());
Rong Xuf430ae42015-12-09 18:08:16 +0000269}
270
271namespace {
272/// \brief An MST based instrumentation for PGO
273///
274/// Implements a Minimum Spanning Tree (MST) based instrumentation for PGO
275/// in the function level.
276struct PGOEdge {
277 // This class implements the CFG edges. Note the CFG can be a multi-graph.
278 // So there might be multiple edges with same SrcBB and DestBB.
279 const BasicBlock *SrcBB;
280 const BasicBlock *DestBB;
281 uint64_t Weight;
282 bool InMST;
283 bool Removed;
284 bool IsCritical;
285 PGOEdge(const BasicBlock *Src, const BasicBlock *Dest, unsigned W = 1)
286 : SrcBB(Src), DestBB(Dest), Weight(W), InMST(false), Removed(false),
287 IsCritical(false) {}
288 // Return the information string of an edge.
289 const std::string infoString() const {
290 return (Twine(Removed ? "-" : " ") + (InMST ? " " : "*") +
291 (IsCritical ? "c" : " ") + " W=" + Twine(Weight)).str();
292 }
293};
294
295// This class stores the auxiliary information for each BB.
296struct BBInfo {
297 BBInfo *Group;
298 uint32_t Index;
299 uint32_t Rank;
300
301 BBInfo(unsigned IX) : Group(this), Index(IX), Rank(0) {}
302
303 // Return the information string of this object.
304 const std::string infoString() const {
305 return (Twine("Index=") + Twine(Index)).str();
306 }
307};
308
309// This class implements the CFG edges. Note the CFG can be a multi-graph.
310template <class Edge, class BBInfo> class FuncPGOInstrumentation {
311private:
312 Function &F;
313 void computeCFGHash();
Rong Xu705f7772016-07-25 18:45:37 +0000314 void renameComdatFunction();
315 // A map that stores the Comdat group in function F.
316 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers;
Rong Xuf430ae42015-12-09 18:08:16 +0000317
318public:
Xinliang David Li9780fc12016-09-20 22:39:47 +0000319 std::vector<Instruction *> IndirectCallSites;
Xinliang David Li4ca17332016-09-18 18:34:07 +0000320 SelectInstVisitor SIVisitor;
Rong Xuf430ae42015-12-09 18:08:16 +0000321 std::string FuncName;
322 GlobalVariable *FuncNameVar;
323 // CFG hash value for this function.
324 uint64_t FunctionHash;
325
326 // The Minimum Spanning Tree of function CFG.
327 CFGMST<Edge, BBInfo> MST;
328
329 // Give an edge, find the BB that will be instrumented.
330 // Return nullptr if there is no BB to be instrumented.
331 BasicBlock *getInstrBB(Edge *E);
332
333 // Return the auxiliary BB information.
334 BBInfo &getBBInfo(const BasicBlock *BB) const { return MST.getBBInfo(BB); }
335
Rong Xua5b57452016-12-02 19:10:29 +0000336 // Return the auxiliary BB information if available.
337 BBInfo *findBBInfo(const BasicBlock *BB) const { return MST.findBBInfo(BB); }
338
Rong Xuf430ae42015-12-09 18:08:16 +0000339 // Dump edges and BB information.
340 void dumpInfo(std::string Str = "") const {
341 MST.dumpEdges(dbgs(), Twine("Dump Function ") + FuncName + " Hash: " +
Rong Xued9fec72016-01-21 18:11:44 +0000342 Twine(FunctionHash) + "\t" + Str);
Rong Xuf430ae42015-12-09 18:08:16 +0000343 }
344
Rong Xu705f7772016-07-25 18:45:37 +0000345 FuncPGOInstrumentation(
346 Function &Func,
347 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers,
348 bool CreateGlobalVar = false, BranchProbabilityInfo *BPI = nullptr,
349 BlockFrequencyInfo *BFI = nullptr)
Xinliang David Li4ca17332016-09-18 18:34:07 +0000350 : F(Func), ComdatMembers(ComdatMembers), SIVisitor(Func), FunctionHash(0),
Rong Xu705f7772016-07-25 18:45:37 +0000351 MST(F, BPI, BFI) {
Xinliang David Li4ca17332016-09-18 18:34:07 +0000352
353 // This should be done before CFG hash computation.
354 SIVisitor.countSelects(Func);
355 NumOfPGOSelectInsts += SIVisitor.getNumOfSelectInsts();
Xinliang David Li9780fc12016-09-20 22:39:47 +0000356 IndirectCallSites = findIndirectCallSites(Func);
Xinliang David Li4ca17332016-09-18 18:34:07 +0000357
Rong Xuf430ae42015-12-09 18:08:16 +0000358 FuncName = getPGOFuncName(F);
359 computeCFGHash();
Rong Xu705f7772016-07-25 18:45:37 +0000360 if (ComdatMembers.size())
361 renameComdatFunction();
Rong Xuf430ae42015-12-09 18:08:16 +0000362 DEBUG(dumpInfo("after CFGMST"));
363
364 NumOfPGOBB += MST.BBInfos.size();
365 for (auto &E : MST.AllEdges) {
366 if (E->Removed)
367 continue;
368 NumOfPGOEdge++;
369 if (!E->InMST)
370 NumOfPGOInstrument++;
371 }
372
373 if (CreateGlobalVar)
374 FuncNameVar = createPGOFuncNameVar(F, FuncName);
Eugene Zelenko6ac3f732016-01-26 18:48:36 +0000375 }
Xinliang David Lid1197612016-08-01 20:25:06 +0000376
377 // Return the number of profile counters needed for the function.
378 unsigned getNumCounters() {
379 unsigned NumCounters = 0;
380 for (auto &E : this->MST.AllEdges) {
381 if (!E->InMST && !E->Removed)
382 NumCounters++;
383 }
Xinliang David Li4ca17332016-09-18 18:34:07 +0000384 return NumCounters + SIVisitor.getNumOfSelectInsts();
Xinliang David Lid1197612016-08-01 20:25:06 +0000385 }
Rong Xuf430ae42015-12-09 18:08:16 +0000386};
387
388// Compute Hash value for the CFG: the lower 32 bits are CRC32 of the index
389// value of each BB in the CFG. The higher 32 bits record the number of edges.
390template <class Edge, class BBInfo>
391void FuncPGOInstrumentation<Edge, BBInfo>::computeCFGHash() {
392 std::vector<char> Indexes;
393 JamCRC JC;
394 for (auto &BB : F) {
395 const TerminatorInst *TI = BB.getTerminator();
396 for (unsigned I = 0, E = TI->getNumSuccessors(); I != E; ++I) {
397 BasicBlock *Succ = TI->getSuccessor(I);
Rong Xua5b57452016-12-02 19:10:29 +0000398 auto BI = findBBInfo(Succ);
399 if (BI == nullptr)
400 continue;
401 uint32_t Index = BI->Index;
Rong Xuf430ae42015-12-09 18:08:16 +0000402 for (int J = 0; J < 4; J++)
403 Indexes.push_back((char)(Index >> (J * 8)));
404 }
405 }
406 JC.update(Indexes);
Xinliang David Li4ca17332016-09-18 18:34:07 +0000407 FunctionHash = (uint64_t)SIVisitor.getNumOfSelectInsts() << 56 |
Xinliang David Li9780fc12016-09-20 22:39:47 +0000408 (uint64_t)IndirectCallSites.size() << 48 |
Rong Xu705f7772016-07-25 18:45:37 +0000409 (uint64_t)MST.AllEdges.size() << 32 | JC.getCRC();
410}
411
412// Check if we can safely rename this Comdat function.
413static bool canRenameComdat(
414 Function &F,
415 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers) {
Rong Xu20f5df12017-01-11 20:19:41 +0000416 if (!DoComdatRenaming || !canRenameComdatFunc(F, true))
Rong Xu705f7772016-07-25 18:45:37 +0000417 return false;
Rong Xu705f7772016-07-25 18:45:37 +0000418
419 // FIXME: Current only handle those Comdat groups that only containing one
420 // function and function aliases.
421 // (1) For a Comdat group containing multiple functions, we need to have a
422 // unique postfix based on the hashes for each function. There is a
423 // non-trivial code refactoring to do this efficiently.
424 // (2) Variables can not be renamed, so we can not rename Comdat function in a
425 // group including global vars.
426 Comdat *C = F.getComdat();
427 for (auto &&CM : make_range(ComdatMembers.equal_range(C))) {
428 if (dyn_cast<GlobalAlias>(CM.second))
429 continue;
430 Function *FM = dyn_cast<Function>(CM.second);
431 if (FM != &F)
432 return false;
433 }
434 return true;
435}
436
437// Append the CFGHash to the Comdat function name.
438template <class Edge, class BBInfo>
439void FuncPGOInstrumentation<Edge, BBInfo>::renameComdatFunction() {
440 if (!canRenameComdat(F, ComdatMembers))
441 return;
Rong Xu0e79f7d2016-10-06 20:38:13 +0000442 std::string OrigName = F.getName().str();
Rong Xu705f7772016-07-25 18:45:37 +0000443 std::string NewFuncName =
444 Twine(F.getName() + "." + Twine(FunctionHash)).str();
445 F.setName(Twine(NewFuncName));
Rong Xu0e79f7d2016-10-06 20:38:13 +0000446 GlobalAlias::create(GlobalValue::WeakAnyLinkage, OrigName, &F);
Rong Xu705f7772016-07-25 18:45:37 +0000447 FuncName = Twine(FuncName + "." + Twine(FunctionHash)).str();
448 Comdat *NewComdat;
449 Module *M = F.getParent();
450 // For AvailableExternallyLinkage functions, change the linkage to
451 // LinkOnceODR and put them into comdat. This is because after renaming, there
452 // is no backup external copy available for the function.
453 if (!F.hasComdat()) {
454 assert(F.getLinkage() == GlobalValue::AvailableExternallyLinkage);
455 NewComdat = M->getOrInsertComdat(StringRef(NewFuncName));
456 F.setLinkage(GlobalValue::LinkOnceODRLinkage);
457 F.setComdat(NewComdat);
458 return;
459 }
460
461 // This function belongs to a single function Comdat group.
462 Comdat *OrigComdat = F.getComdat();
463 std::string NewComdatName =
464 Twine(OrigComdat->getName() + "." + Twine(FunctionHash)).str();
465 NewComdat = M->getOrInsertComdat(StringRef(NewComdatName));
466 NewComdat->setSelectionKind(OrigComdat->getSelectionKind());
467
468 for (auto &&CM : make_range(ComdatMembers.equal_range(OrigComdat))) {
469 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(CM.second)) {
470 // For aliases, change the name directly.
471 assert(dyn_cast<Function>(GA->getAliasee()->stripPointerCasts()) == &F);
Rong Xu0e79f7d2016-10-06 20:38:13 +0000472 std::string OrigGAName = GA->getName().str();
Rong Xu705f7772016-07-25 18:45:37 +0000473 GA->setName(Twine(GA->getName() + "." + Twine(FunctionHash)));
Rong Xu0e79f7d2016-10-06 20:38:13 +0000474 GlobalAlias::create(GlobalValue::WeakAnyLinkage, OrigGAName, GA);
Rong Xu705f7772016-07-25 18:45:37 +0000475 continue;
476 }
477 // Must be a function.
478 Function *CF = dyn_cast<Function>(CM.second);
479 assert(CF);
480 CF->setComdat(NewComdat);
481 }
Rong Xuf430ae42015-12-09 18:08:16 +0000482}
483
484// Given a CFG E to be instrumented, find which BB to place the instrumented
485// code. The function will split the critical edge if necessary.
486template <class Edge, class BBInfo>
487BasicBlock *FuncPGOInstrumentation<Edge, BBInfo>::getInstrBB(Edge *E) {
488 if (E->InMST || E->Removed)
489 return nullptr;
490
491 BasicBlock *SrcBB = const_cast<BasicBlock *>(E->SrcBB);
492 BasicBlock *DestBB = const_cast<BasicBlock *>(E->DestBB);
493 // For a fake edge, instrument the real BB.
494 if (SrcBB == nullptr)
495 return DestBB;
496 if (DestBB == nullptr)
497 return SrcBB;
498
499 // Instrument the SrcBB if it has a single successor,
500 // otherwise, the DestBB if this is not a critical edge.
501 TerminatorInst *TI = SrcBB->getTerminator();
502 if (TI->getNumSuccessors() <= 1)
503 return SrcBB;
504 if (!E->IsCritical)
505 return DestBB;
506
507 // For a critical edge, we have to split. Instrument the newly
508 // created BB.
509 NumOfPGOSplit++;
510 DEBUG(dbgs() << "Split critical edge: " << getBBInfo(SrcBB).Index << " --> "
511 << getBBInfo(DestBB).Index << "\n");
512 unsigned SuccNum = GetSuccessorNumber(SrcBB, DestBB);
513 BasicBlock *InstrBB = SplitCriticalEdge(TI, SuccNum);
514 assert(InstrBB && "Critical edge is not split");
515
516 E->Removed = true;
517 return InstrBB;
518}
519
Rong Xued9fec72016-01-21 18:11:44 +0000520// Visit all edge and instrument the edges not in MST, and do value profiling.
Rong Xuf430ae42015-12-09 18:08:16 +0000521// Critical edges will be split.
Rong Xu705f7772016-07-25 18:45:37 +0000522static void instrumentOneFunc(
523 Function &F, Module *M, BranchProbabilityInfo *BPI, BlockFrequencyInfo *BFI,
524 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers) {
Rong Xu705f7772016-07-25 18:45:37 +0000525 FuncPGOInstrumentation<PGOEdge, BBInfo> FuncInfo(F, ComdatMembers, true, BPI,
526 BFI);
Xinliang David Lid1197612016-08-01 20:25:06 +0000527 unsigned NumCounters = FuncInfo.getNumCounters();
528
Rong Xuf430ae42015-12-09 18:08:16 +0000529 uint32_t I = 0;
Rong Xued9fec72016-01-21 18:11:44 +0000530 Type *I8PtrTy = Type::getInt8PtrTy(M->getContext());
Rong Xuf430ae42015-12-09 18:08:16 +0000531 for (auto &E : FuncInfo.MST.AllEdges) {
532 BasicBlock *InstrBB = FuncInfo.getInstrBB(E.get());
533 if (!InstrBB)
534 continue;
535
536 IRBuilder<> Builder(InstrBB, InstrBB->getFirstInsertionPt());
537 assert(Builder.GetInsertPoint() != InstrBB->end() &&
538 "Cannot get the Instrumentation point");
Rong Xuf430ae42015-12-09 18:08:16 +0000539 Builder.CreateCall(
540 Intrinsic::getDeclaration(M, Intrinsic::instrprof_increment),
541 {llvm::ConstantExpr::getBitCast(FuncInfo.FuncNameVar, I8PtrTy),
542 Builder.getInt64(FuncInfo.FunctionHash), Builder.getInt32(NumCounters),
543 Builder.getInt32(I++)});
544 }
Xinliang David Li4ca17332016-09-18 18:34:07 +0000545
546 // Now instrument select instructions:
547 FuncInfo.SIVisitor.instrumentSelects(F, &I, NumCounters, FuncInfo.FuncNameVar,
548 FuncInfo.FunctionHash);
Xinliang David Lid1197612016-08-01 20:25:06 +0000549 assert(I == NumCounters);
Rong Xued9fec72016-01-21 18:11:44 +0000550
551 if (DisableValueProfiling)
552 return;
553
554 unsigned NumIndirectCallSites = 0;
Xinliang David Li9780fc12016-09-20 22:39:47 +0000555 for (auto &I : FuncInfo.IndirectCallSites) {
Rong Xued9fec72016-01-21 18:11:44 +0000556 CallSite CS(I);
557 Value *Callee = CS.getCalledValue();
558 DEBUG(dbgs() << "Instrument one indirect call: CallSite Index = "
559 << NumIndirectCallSites << "\n");
560 IRBuilder<> Builder(I);
561 assert(Builder.GetInsertPoint() != I->getParent()->end() &&
562 "Cannot get the Instrumentation point");
563 Builder.CreateCall(
564 Intrinsic::getDeclaration(M, Intrinsic::instrprof_value_profile),
565 {llvm::ConstantExpr::getBitCast(FuncInfo.FuncNameVar, I8PtrTy),
566 Builder.getInt64(FuncInfo.FunctionHash),
567 Builder.CreatePtrToInt(Callee, Builder.getInt64Ty()),
568 Builder.getInt32(llvm::InstrProfValueKind::IPVK_IndirectCallTarget),
569 Builder.getInt32(NumIndirectCallSites++)});
570 }
571 NumOfPGOICall += NumIndirectCallSites;
Rong Xuf430ae42015-12-09 18:08:16 +0000572}
573
574// This class represents a CFG edge in profile use compilation.
575struct PGOUseEdge : public PGOEdge {
576 bool CountValid;
577 uint64_t CountValue;
578 PGOUseEdge(const BasicBlock *Src, const BasicBlock *Dest, unsigned W = 1)
579 : PGOEdge(Src, Dest, W), CountValid(false), CountValue(0) {}
580
581 // Set edge count value
582 void setEdgeCount(uint64_t Value) {
583 CountValue = Value;
584 CountValid = true;
585 }
586
587 // Return the information string for this object.
588 const std::string infoString() const {
589 if (!CountValid)
590 return PGOEdge::infoString();
Rong Xu9e926e82016-02-29 19:16:04 +0000591 return (Twine(PGOEdge::infoString()) + " Count=" + Twine(CountValue))
592 .str();
Rong Xuf430ae42015-12-09 18:08:16 +0000593 }
594};
595
596typedef SmallVector<PGOUseEdge *, 2> DirectEdges;
597
598// This class stores the auxiliary information for each BB.
599struct UseBBInfo : public BBInfo {
600 uint64_t CountValue;
601 bool CountValid;
602 int32_t UnknownCountInEdge;
603 int32_t UnknownCountOutEdge;
604 DirectEdges InEdges;
605 DirectEdges OutEdges;
606 UseBBInfo(unsigned IX)
607 : BBInfo(IX), CountValue(0), CountValid(false), UnknownCountInEdge(0),
608 UnknownCountOutEdge(0) {}
609 UseBBInfo(unsigned IX, uint64_t C)
610 : BBInfo(IX), CountValue(C), CountValid(true), UnknownCountInEdge(0),
611 UnknownCountOutEdge(0) {}
612
613 // Set the profile count value for this BB.
614 void setBBInfoCount(uint64_t Value) {
615 CountValue = Value;
616 CountValid = true;
617 }
618
619 // Return the information string of this object.
620 const std::string infoString() const {
621 if (!CountValid)
622 return BBInfo::infoString();
623 return (Twine(BBInfo::infoString()) + " Count=" + Twine(CountValue)).str();
624 }
625};
626
627// Sum up the count values for all the edges.
628static uint64_t sumEdgeCount(const ArrayRef<PGOUseEdge *> Edges) {
629 uint64_t Total = 0;
630 for (auto &E : Edges) {
631 if (E->Removed)
632 continue;
633 Total += E->CountValue;
634 }
635 return Total;
636}
637
638class PGOUseFunc {
Rong Xu6090afd2016-03-28 17:08:56 +0000639public:
Rong Xu705f7772016-07-25 18:45:37 +0000640 PGOUseFunc(Function &Func, Module *Modu,
641 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers,
642 BranchProbabilityInfo *BPI = nullptr,
Rong Xu6090afd2016-03-28 17:08:56 +0000643 BlockFrequencyInfo *BFI = nullptr)
Rong Xu705f7772016-07-25 18:45:37 +0000644 : F(Func), M(Modu), FuncInfo(Func, ComdatMembers, false, BPI, BFI),
Rong Xu33308f92016-10-25 21:47:24 +0000645 CountPosition(0), ProfileCountSize(0), FreqAttr(FFA_Normal) {}
Rong Xu6090afd2016-03-28 17:08:56 +0000646
647 // Read counts for the instrumented BB from profile.
648 bool readCounters(IndexedInstrProfReader *PGOReader);
649
650 // Populate the counts for all BBs.
651 void populateCounters();
652
653 // Set the branch weights based on the count values.
654 void setBranchWeights();
655
656 // Annotate the indirect call sites.
657 void annotateIndirectCallSites();
658
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000659 // The hotness of the function from the profile count.
660 enum FuncFreqAttr { FFA_Normal, FFA_Cold, FFA_Hot };
661
662 // Return the function hotness from the profile.
663 FuncFreqAttr getFuncFreqAttr() const { return FreqAttr; }
664
Rong Xu705f7772016-07-25 18:45:37 +0000665 // Return the function hash.
666 uint64_t getFuncHash() const { return FuncInfo.FunctionHash; }
Easwaran Raman5fe04a12016-05-26 22:57:11 +0000667 // Return the profile record for this function;
668 InstrProfRecord &getProfileRecord() { return ProfileRecord; }
669
Xinliang David Li4ca17332016-09-18 18:34:07 +0000670 // Return the auxiliary BB information.
671 UseBBInfo &getBBInfo(const BasicBlock *BB) const {
672 return FuncInfo.getBBInfo(BB);
673 }
674
Rong Xua5b57452016-12-02 19:10:29 +0000675 // Return the auxiliary BB information if available.
676 UseBBInfo *findBBInfo(const BasicBlock *BB) const {
677 return FuncInfo.findBBInfo(BB);
678 }
679
Rong Xuf430ae42015-12-09 18:08:16 +0000680private:
681 Function &F;
682 Module *M;
683 // This member stores the shared information with class PGOGenFunc.
684 FuncPGOInstrumentation<PGOUseEdge, UseBBInfo> FuncInfo;
685
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000686 // The maximum count value in the profile. This is only used in PGO use
687 // compilation.
688 uint64_t ProgramMaxCount;
689
Rong Xu33308f92016-10-25 21:47:24 +0000690 // Position of counter that remains to be read.
691 uint32_t CountPosition;
692
693 // Total size of the profile count for this function.
694 uint32_t ProfileCountSize;
695
Rong Xu13b01dc2016-02-10 18:24:45 +0000696 // ProfileRecord for this function.
697 InstrProfRecord ProfileRecord;
698
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000699 // Function hotness info derived from profile.
700 FuncFreqAttr FreqAttr;
701
Rong Xuf430ae42015-12-09 18:08:16 +0000702 // Find the Instrumented BB and set the value.
703 void setInstrumentedCounts(const std::vector<uint64_t> &CountFromProfile);
704
705 // Set the edge counter value for the unknown edge -- there should be only
706 // one unknown edge.
707 void setEdgeCount(DirectEdges &Edges, uint64_t Value);
708
709 // Return FuncName string;
710 const std::string getFuncName() const { return FuncInfo.FuncName; }
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000711
712 // Set the hot/cold inline hints based on the count values.
713 // FIXME: This function should be removed once the functionality in
714 // the inliner is implemented.
715 void markFunctionAttributes(uint64_t EntryCount, uint64_t MaxCount) {
716 if (ProgramMaxCount == 0)
717 return;
718 // Threshold of the hot functions.
719 const BranchProbability HotFunctionThreshold(1, 100);
720 // Threshold of the cold functions.
721 const BranchProbability ColdFunctionThreshold(2, 10000);
722 if (EntryCount >= HotFunctionThreshold.scale(ProgramMaxCount))
723 FreqAttr = FFA_Hot;
724 else if (MaxCount <= ColdFunctionThreshold.scale(ProgramMaxCount))
725 FreqAttr = FFA_Cold;
726 }
Rong Xuf430ae42015-12-09 18:08:16 +0000727};
728
729// Visit all the edges and assign the count value for the instrumented
730// edges and the BB.
731void PGOUseFunc::setInstrumentedCounts(
732 const std::vector<uint64_t> &CountFromProfile) {
733
Xinliang David Lid1197612016-08-01 20:25:06 +0000734 assert(FuncInfo.getNumCounters() == CountFromProfile.size());
Rong Xuf430ae42015-12-09 18:08:16 +0000735 // Use a worklist as we will update the vector during the iteration.
736 std::vector<PGOUseEdge *> WorkList;
737 for (auto &E : FuncInfo.MST.AllEdges)
738 WorkList.push_back(E.get());
739
740 uint32_t I = 0;
741 for (auto &E : WorkList) {
742 BasicBlock *InstrBB = FuncInfo.getInstrBB(E);
743 if (!InstrBB)
744 continue;
745 uint64_t CountValue = CountFromProfile[I++];
746 if (!E->Removed) {
747 getBBInfo(InstrBB).setBBInfoCount(CountValue);
748 E->setEdgeCount(CountValue);
749 continue;
750 }
751
752 // Need to add two new edges.
753 BasicBlock *SrcBB = const_cast<BasicBlock *>(E->SrcBB);
754 BasicBlock *DestBB = const_cast<BasicBlock *>(E->DestBB);
755 // Add new edge of SrcBB->InstrBB.
756 PGOUseEdge &NewEdge = FuncInfo.MST.addEdge(SrcBB, InstrBB, 0);
757 NewEdge.setEdgeCount(CountValue);
758 // Add new edge of InstrBB->DestBB.
759 PGOUseEdge &NewEdge1 = FuncInfo.MST.addEdge(InstrBB, DestBB, 0);
760 NewEdge1.setEdgeCount(CountValue);
761 NewEdge1.InMST = true;
762 getBBInfo(InstrBB).setBBInfoCount(CountValue);
763 }
Rong Xu33308f92016-10-25 21:47:24 +0000764 ProfileCountSize = CountFromProfile.size();
765 CountPosition = I;
Rong Xuf430ae42015-12-09 18:08:16 +0000766}
767
768// Set the count value for the unknown edge. There should be one and only one
769// unknown edge in Edges vector.
770void PGOUseFunc::setEdgeCount(DirectEdges &Edges, uint64_t Value) {
771 for (auto &E : Edges) {
772 if (E->CountValid)
773 continue;
774 E->setEdgeCount(Value);
775
776 getBBInfo(E->SrcBB).UnknownCountOutEdge--;
777 getBBInfo(E->DestBB).UnknownCountInEdge--;
778 return;
779 }
780 llvm_unreachable("Cannot find the unknown count edge");
781}
782
783// Read the profile from ProfileFileName and assign the value to the
784// instrumented BB and the edges. This function also updates ProgramMaxCount.
785// Return true if the profile are successfully read, and false on errors.
786bool PGOUseFunc::readCounters(IndexedInstrProfReader *PGOReader) {
787 auto &Ctx = M->getContext();
Vedant Kumar9152fd12016-05-19 03:54:45 +0000788 Expected<InstrProfRecord> Result =
Rong Xuf430ae42015-12-09 18:08:16 +0000789 PGOReader->getInstrProfRecord(FuncInfo.FuncName, FuncInfo.FunctionHash);
Vedant Kumar9152fd12016-05-19 03:54:45 +0000790 if (Error E = Result.takeError()) {
791 handleAllErrors(std::move(E), [&](const InstrProfError &IPE) {
792 auto Err = IPE.get();
793 bool SkipWarning = false;
794 if (Err == instrprof_error::unknown_function) {
795 NumOfPGOMissing++;
Xinliang David Li76a01082016-08-11 05:09:30 +0000796 SkipWarning = !PGOWarnMissing;
Vedant Kumar9152fd12016-05-19 03:54:45 +0000797 } else if (Err == instrprof_error::hash_mismatch ||
798 Err == instrprof_error::malformed) {
799 NumOfPGOMismatch++;
Rong Xu20f5df12017-01-11 20:19:41 +0000800 SkipWarning =
801 NoPGOWarnMismatch ||
802 (NoPGOWarnMismatchComdat &&
803 (F.hasComdat() ||
804 F.getLinkage() == GlobalValue::AvailableExternallyLinkage));
Vedant Kumar9152fd12016-05-19 03:54:45 +0000805 }
Rong Xuf430ae42015-12-09 18:08:16 +0000806
Vedant Kumar9152fd12016-05-19 03:54:45 +0000807 if (SkipWarning)
808 return;
809
810 std::string Msg = IPE.message() + std::string(" ") + F.getName().str();
811 Ctx.diagnose(
812 DiagnosticInfoPGOProfile(M->getName().data(), Msg, DS_Warning));
813 });
Rong Xuf430ae42015-12-09 18:08:16 +0000814 return false;
815 }
Rong Xu13b01dc2016-02-10 18:24:45 +0000816 ProfileRecord = std::move(Result.get());
817 std::vector<uint64_t> &CountFromProfile = ProfileRecord.Counts;
Rong Xuf430ae42015-12-09 18:08:16 +0000818
819 NumOfPGOFunc++;
820 DEBUG(dbgs() << CountFromProfile.size() << " counts\n");
821 uint64_t ValueSum = 0;
822 for (unsigned I = 0, S = CountFromProfile.size(); I < S; I++) {
823 DEBUG(dbgs() << " " << I << ": " << CountFromProfile[I] << "\n");
824 ValueSum += CountFromProfile[I];
825 }
826
827 DEBUG(dbgs() << "SUM = " << ValueSum << "\n");
828
829 getBBInfo(nullptr).UnknownCountOutEdge = 2;
830 getBBInfo(nullptr).UnknownCountInEdge = 2;
831
832 setInstrumentedCounts(CountFromProfile);
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000833 ProgramMaxCount = PGOReader->getMaximumFunctionCount();
Rong Xuf430ae42015-12-09 18:08:16 +0000834 return true;
835}
836
837// Populate the counters from instrumented BBs to all BBs.
838// In the end of this operation, all BBs should have a valid count value.
839void PGOUseFunc::populateCounters() {
840 // First set up Count variable for all BBs.
841 for (auto &E : FuncInfo.MST.AllEdges) {
842 if (E->Removed)
843 continue;
844
845 const BasicBlock *SrcBB = E->SrcBB;
846 const BasicBlock *DestBB = E->DestBB;
847 UseBBInfo &SrcInfo = getBBInfo(SrcBB);
848 UseBBInfo &DestInfo = getBBInfo(DestBB);
849 SrcInfo.OutEdges.push_back(E.get());
850 DestInfo.InEdges.push_back(E.get());
851 SrcInfo.UnknownCountOutEdge++;
852 DestInfo.UnknownCountInEdge++;
853
854 if (!E->CountValid)
855 continue;
856 DestInfo.UnknownCountInEdge--;
857 SrcInfo.UnknownCountOutEdge--;
858 }
859
860 bool Changes = true;
861 unsigned NumPasses = 0;
862 while (Changes) {
863 NumPasses++;
864 Changes = false;
865
866 // For efficient traversal, it's better to start from the end as most
867 // of the instrumented edges are at the end.
868 for (auto &BB : reverse(F)) {
Rong Xua5b57452016-12-02 19:10:29 +0000869 UseBBInfo *Count = findBBInfo(&BB);
870 if (Count == nullptr)
871 continue;
872 if (!Count->CountValid) {
873 if (Count->UnknownCountOutEdge == 0) {
874 Count->CountValue = sumEdgeCount(Count->OutEdges);
875 Count->CountValid = true;
Rong Xuf430ae42015-12-09 18:08:16 +0000876 Changes = true;
Rong Xua5b57452016-12-02 19:10:29 +0000877 } else if (Count->UnknownCountInEdge == 0) {
878 Count->CountValue = sumEdgeCount(Count->InEdges);
879 Count->CountValid = true;
Rong Xuf430ae42015-12-09 18:08:16 +0000880 Changes = true;
881 }
882 }
Rong Xua5b57452016-12-02 19:10:29 +0000883 if (Count->CountValid) {
884 if (Count->UnknownCountOutEdge == 1) {
Rong Xu51a1e3c2016-12-13 06:41:14 +0000885 uint64_t Total = 0;
886 uint64_t OutSum = sumEdgeCount(Count->OutEdges);
887 // If the one of the successor block can early terminate (no-return),
888 // we can end up with situation where out edge sum count is larger as
889 // the source BB's count is collected by a post-dominated block.
890 if (Count->CountValue > OutSum)
891 Total = Count->CountValue - OutSum;
Rong Xua5b57452016-12-02 19:10:29 +0000892 setEdgeCount(Count->OutEdges, Total);
Rong Xuf430ae42015-12-09 18:08:16 +0000893 Changes = true;
894 }
Rong Xua5b57452016-12-02 19:10:29 +0000895 if (Count->UnknownCountInEdge == 1) {
Rong Xu51a1e3c2016-12-13 06:41:14 +0000896 uint64_t Total = 0;
897 uint64_t InSum = sumEdgeCount(Count->InEdges);
898 if (Count->CountValue > InSum)
899 Total = Count->CountValue - InSum;
Rong Xua5b57452016-12-02 19:10:29 +0000900 setEdgeCount(Count->InEdges, Total);
Rong Xuf430ae42015-12-09 18:08:16 +0000901 Changes = true;
902 }
903 }
904 }
905 }
906
907 DEBUG(dbgs() << "Populate counts in " << NumPasses << " passes.\n");
Sean Silva8c7e1212016-05-28 04:19:45 +0000908#ifndef NDEBUG
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000909 // Assert every BB has a valid counter.
Rong Xua5b57452016-12-02 19:10:29 +0000910 for (auto &BB : F) {
911 auto BI = findBBInfo(&BB);
912 if (BI == nullptr)
913 continue;
914 assert(BI->CountValid && "BB count is not valid");
915 }
Sean Silva8c7e1212016-05-28 04:19:45 +0000916#endif
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000917 uint64_t FuncEntryCount = getBBInfo(&*F.begin()).CountValue;
Sean Silva02b9d892016-05-28 04:05:36 +0000918 F.setEntryCount(FuncEntryCount);
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000919 uint64_t FuncMaxCount = FuncEntryCount;
Rong Xua5b57452016-12-02 19:10:29 +0000920 for (auto &BB : F) {
921 auto BI = findBBInfo(&BB);
922 if (BI == nullptr)
923 continue;
924 FuncMaxCount = std::max(FuncMaxCount, BI->CountValue);
925 }
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000926 markFunctionAttributes(FuncEntryCount, FuncMaxCount);
Rong Xuf430ae42015-12-09 18:08:16 +0000927
Rong Xu33308f92016-10-25 21:47:24 +0000928 // Now annotate select instructions
929 FuncInfo.SIVisitor.annotateSelects(F, this, &CountPosition);
930 assert(CountPosition == ProfileCountSize);
931
Rong Xuf430ae42015-12-09 18:08:16 +0000932 DEBUG(FuncInfo.dumpInfo("after reading profile."));
933}
934
Xinliang David Li4ca17332016-09-18 18:34:07 +0000935static void setProfMetadata(Module *M, Instruction *TI,
Xinliang David Li63248ab2016-08-19 06:31:45 +0000936 ArrayRef<uint64_t> EdgeCounts, uint64_t MaxCount) {
Xinliang David Li2c933682016-08-19 05:31:33 +0000937 MDBuilder MDB(M->getContext());
938 assert(MaxCount > 0 && "Bad max count");
939 uint64_t Scale = calculateCountScale(MaxCount);
940 SmallVector<unsigned, 4> Weights;
941 for (const auto &ECI : EdgeCounts)
942 Weights.push_back(scaleBranchCount(ECI, Scale));
943
944 DEBUG(dbgs() << "Weight is: ";
945 for (const auto &W : Weights) { dbgs() << W << " "; }
946 dbgs() << "\n";);
947 TI->setMetadata(llvm::LLVMContext::MD_prof, MDB.createBranchWeights(Weights));
948}
949
Rong Xuf430ae42015-12-09 18:08:16 +0000950// Assign the scaled count values to the BB with multiple out edges.
951void PGOUseFunc::setBranchWeights() {
952 // Generate MD_prof metadata for every branch instruction.
953 DEBUG(dbgs() << "\nSetting branch weights.\n");
Rong Xuf430ae42015-12-09 18:08:16 +0000954 for (auto &BB : F) {
955 TerminatorInst *TI = BB.getTerminator();
956 if (TI->getNumSuccessors() < 2)
957 continue;
958 if (!isa<BranchInst>(TI) && !isa<SwitchInst>(TI))
959 continue;
960 if (getBBInfo(&BB).CountValue == 0)
961 continue;
962
963 // We have a non-zero Branch BB.
964 const UseBBInfo &BBCountInfo = getBBInfo(&BB);
965 unsigned Size = BBCountInfo.OutEdges.size();
Xinliang David Li63248ab2016-08-19 06:31:45 +0000966 SmallVector<uint64_t, 2> EdgeCounts(Size, 0);
Rong Xuf430ae42015-12-09 18:08:16 +0000967 uint64_t MaxCount = 0;
968 for (unsigned s = 0; s < Size; s++) {
969 const PGOUseEdge *E = BBCountInfo.OutEdges[s];
970 const BasicBlock *SrcBB = E->SrcBB;
971 const BasicBlock *DestBB = E->DestBB;
Eugene Zelenko6ac3f732016-01-26 18:48:36 +0000972 if (DestBB == nullptr)
Rong Xuf430ae42015-12-09 18:08:16 +0000973 continue;
974 unsigned SuccNum = GetSuccessorNumber(SrcBB, DestBB);
975 uint64_t EdgeCount = E->CountValue;
976 if (EdgeCount > MaxCount)
977 MaxCount = EdgeCount;
978 EdgeCounts[SuccNum] = EdgeCount;
979 }
Xinliang David Li2c933682016-08-19 05:31:33 +0000980 setProfMetadata(M, TI, EdgeCounts, MaxCount);
Rong Xuf430ae42015-12-09 18:08:16 +0000981 }
982}
Rong Xu13b01dc2016-02-10 18:24:45 +0000983
Xinliang David Li4ca17332016-09-18 18:34:07 +0000984void SelectInstVisitor::instrumentOneSelectInst(SelectInst &SI) {
985 Module *M = F.getParent();
986 IRBuilder<> Builder(&SI);
987 Type *Int64Ty = Builder.getInt64Ty();
988 Type *I8PtrTy = Builder.getInt8PtrTy();
989 auto *Step = Builder.CreateZExt(SI.getCondition(), Int64Ty);
990 Builder.CreateCall(
991 Intrinsic::getDeclaration(M, Intrinsic::instrprof_increment_step),
992 {llvm::ConstantExpr::getBitCast(FuncNameVar, I8PtrTy),
993 Builder.getInt64(FuncHash),
994 Builder.getInt32(TotalNumCtrs), Builder.getInt32(*CurCtrIdx), Step});
995 ++(*CurCtrIdx);
996}
997
998void SelectInstVisitor::annotateOneSelectInst(SelectInst &SI) {
999 std::vector<uint64_t> &CountFromProfile = UseFunc->getProfileRecord().Counts;
1000 assert(*CurCtrIdx < CountFromProfile.size() &&
1001 "Out of bound access of counters");
1002 uint64_t SCounts[2];
1003 SCounts[0] = CountFromProfile[*CurCtrIdx]; // True count
1004 ++(*CurCtrIdx);
Rong Xua5b57452016-12-02 19:10:29 +00001005 uint64_t TotalCount = 0;
1006 auto BI = UseFunc->findBBInfo(SI.getParent());
1007 if (BI != nullptr)
1008 TotalCount = BI->CountValue;
Xinliang David Li4ca17332016-09-18 18:34:07 +00001009 // False Count
1010 SCounts[1] = (TotalCount > SCounts[0] ? TotalCount - SCounts[0] : 0);
1011 uint64_t MaxCount = std::max(SCounts[0], SCounts[1]);
Xinliang David Lic7368282016-09-20 20:20:01 +00001012 if (MaxCount)
1013 setProfMetadata(F.getParent(), &SI, SCounts, MaxCount);
Xinliang David Li4ca17332016-09-18 18:34:07 +00001014}
1015
1016void SelectInstVisitor::visitSelectInst(SelectInst &SI) {
1017 if (!PGOInstrSelect)
1018 return;
1019 // FIXME: do not handle this yet.
1020 if (SI.getCondition()->getType()->isVectorTy())
1021 return;
1022
1023 NSIs++;
1024 switch (Mode) {
1025 case VM_counting:
1026 return;
1027 case VM_instrument:
1028 instrumentOneSelectInst(SI);
Simon Pilgrimf33a6b72016-09-18 21:08:35 +00001029 return;
Xinliang David Li4ca17332016-09-18 18:34:07 +00001030 case VM_annotate:
1031 annotateOneSelectInst(SI);
Simon Pilgrimf33a6b72016-09-18 21:08:35 +00001032 return;
Xinliang David Li4ca17332016-09-18 18:34:07 +00001033 }
Simon Pilgrimf33a6b72016-09-18 21:08:35 +00001034
1035 llvm_unreachable("Unknown visiting mode");
Xinliang David Li4ca17332016-09-18 18:34:07 +00001036}
1037
Rong Xu13b01dc2016-02-10 18:24:45 +00001038// Traverse all the indirect callsites and annotate the instructions.
1039void PGOUseFunc::annotateIndirectCallSites() {
1040 if (DisableValueProfiling)
1041 return;
1042
Rong Xu8e8fe852016-04-01 16:43:30 +00001043 // Create the PGOFuncName meta data.
Rong Xuf8f051c2016-04-22 21:00:17 +00001044 createPGOFuncNameMetadata(F, FuncInfo.FuncName);
Rong Xub5341662016-03-30 18:37:52 +00001045
Rong Xu13b01dc2016-02-10 18:24:45 +00001046 unsigned IndirectCallSiteIndex = 0;
Xinliang David Li9780fc12016-09-20 22:39:47 +00001047 auto &IndirectCallSites = FuncInfo.IndirectCallSites;
Rong Xu9e926e82016-02-29 19:16:04 +00001048 unsigned NumValueSites =
Rong Xu13b01dc2016-02-10 18:24:45 +00001049 ProfileRecord.getNumValueSites(IPVK_IndirectCallTarget);
Rong Xu0eb36032016-04-01 23:16:44 +00001050 if (NumValueSites != IndirectCallSites.size()) {
Rong Xu13b01dc2016-02-10 18:24:45 +00001051 std::string Msg =
1052 std::string("Inconsistent number of indirect call sites: ") +
Rong Xu9e926e82016-02-29 19:16:04 +00001053 F.getName().str();
Rong Xu13b01dc2016-02-10 18:24:45 +00001054 auto &Ctx = M->getContext();
1055 Ctx.diagnose(
1056 DiagnosticInfoPGOProfile(M->getName().data(), Msg, DS_Warning));
1057 return;
1058 }
1059
Rong Xu0eb36032016-04-01 23:16:44 +00001060 for (auto &I : IndirectCallSites) {
Rong Xu13b01dc2016-02-10 18:24:45 +00001061 DEBUG(dbgs() << "Read one indirect call instrumentation: Index="
Rong Xu9e926e82016-02-29 19:16:04 +00001062 << IndirectCallSiteIndex << " out of " << NumValueSites
1063 << "\n");
Rong Xu13b01dc2016-02-10 18:24:45 +00001064 annotateValueSite(*M, *I, ProfileRecord, IPVK_IndirectCallTarget,
Rong Xuecdc98f2016-03-04 22:08:44 +00001065 IndirectCallSiteIndex, MaxNumAnnotations);
Rong Xu13b01dc2016-02-10 18:24:45 +00001066 IndirectCallSiteIndex++;
1067 }
1068}
Rong Xuf430ae42015-12-09 18:08:16 +00001069} // end anonymous namespace
1070
Xinliang David Lid382e9d2016-07-22 04:46:56 +00001071// Create a COMDAT variable INSTR_PROF_RAW_VERSION_VAR to make the runtime
Rong Xu33c76c02016-02-10 17:18:30 +00001072// aware this is an ir_level profile so it can set the version flag.
1073static void createIRLevelProfileFlagVariable(Module &M) {
1074 Type *IntTy64 = Type::getInt64Ty(M.getContext());
1075 uint64_t ProfileVersion = (INSTR_PROF_RAW_VERSION | VARIANT_MASK_IR_PROF);
Rong Xu9e926e82016-02-29 19:16:04 +00001076 auto IRLevelVersionVariable = new GlobalVariable(
1077 M, IntTy64, true, GlobalVariable::ExternalLinkage,
1078 Constant::getIntegerValue(IntTy64, APInt(64, ProfileVersion)),
Xinliang David Lid382e9d2016-07-22 04:46:56 +00001079 INSTR_PROF_QUOTE(INSTR_PROF_RAW_VERSION_VAR));
Rong Xu33c76c02016-02-10 17:18:30 +00001080 IRLevelVersionVariable->setVisibility(GlobalValue::DefaultVisibility);
1081 Triple TT(M.getTargetTriple());
Xinliang David Li11c849c2016-05-27 16:22:03 +00001082 if (!TT.supportsCOMDAT())
Rong Xuca28a0a2016-05-11 00:31:59 +00001083 IRLevelVersionVariable->setLinkage(GlobalValue::WeakAnyLinkage);
Rong Xu33c76c02016-02-10 17:18:30 +00001084 else
Rong Xu9e926e82016-02-29 19:16:04 +00001085 IRLevelVersionVariable->setComdat(M.getOrInsertComdat(
Xinliang David Lid382e9d2016-07-22 04:46:56 +00001086 StringRef(INSTR_PROF_QUOTE(INSTR_PROF_RAW_VERSION_VAR))));
Rong Xu33c76c02016-02-10 17:18:30 +00001087}
1088
Rong Xu705f7772016-07-25 18:45:37 +00001089// Collect the set of members for each Comdat in module M and store
1090// in ComdatMembers.
1091static void collectComdatMembers(
1092 Module &M,
1093 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers) {
1094 if (!DoComdatRenaming)
1095 return;
1096 for (Function &F : M)
1097 if (Comdat *C = F.getComdat())
1098 ComdatMembers.insert(std::make_pair(C, &F));
1099 for (GlobalVariable &GV : M.globals())
1100 if (Comdat *C = GV.getComdat())
1101 ComdatMembers.insert(std::make_pair(C, &GV));
1102 for (GlobalAlias &GA : M.aliases())
1103 if (Comdat *C = GA.getComdat())
1104 ComdatMembers.insert(std::make_pair(C, &GA));
1105}
1106
Xinliang David Li5ad7c822016-05-02 20:33:59 +00001107static bool InstrumentAllFunctions(
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001108 Module &M, function_ref<BranchProbabilityInfo *(Function &)> LookupBPI,
1109 function_ref<BlockFrequencyInfo *(Function &)> LookupBFI) {
Rong Xu33c76c02016-02-10 17:18:30 +00001110 createIRLevelProfileFlagVariable(M);
Rong Xu705f7772016-07-25 18:45:37 +00001111 std::unordered_multimap<Comdat *, GlobalValue *> ComdatMembers;
1112 collectComdatMembers(M, ComdatMembers);
1113
Rong Xuf430ae42015-12-09 18:08:16 +00001114 for (auto &F : M) {
1115 if (F.isDeclaration())
1116 continue;
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001117 auto *BPI = LookupBPI(F);
1118 auto *BFI = LookupBFI(F);
Rong Xu705f7772016-07-25 18:45:37 +00001119 instrumentOneFunc(F, &M, BPI, BFI, ComdatMembers);
Rong Xuf430ae42015-12-09 18:08:16 +00001120 }
1121 return true;
1122}
1123
Xinliang David Li8aebf442016-05-06 05:49:19 +00001124bool PGOInstrumentationGenLegacyPass::runOnModule(Module &M) {
Xinliang David Li5ad7c822016-05-02 20:33:59 +00001125 if (skipModule(M))
1126 return false;
1127
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001128 auto LookupBPI = [this](Function &F) {
1129 return &this->getAnalysis<BranchProbabilityInfoWrapperPass>(F).getBPI();
Xinliang David Li5ad7c822016-05-02 20:33:59 +00001130 };
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001131 auto LookupBFI = [this](Function &F) {
1132 return &this->getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI();
Xinliang David Li5ad7c822016-05-02 20:33:59 +00001133 };
1134 return InstrumentAllFunctions(M, LookupBPI, LookupBFI);
1135}
1136
Xinliang David Li8aebf442016-05-06 05:49:19 +00001137PreservedAnalyses PGOInstrumentationGen::run(Module &M,
Sean Silvafd03ac62016-08-09 00:28:38 +00001138 ModuleAnalysisManager &AM) {
Xinliang David Li8aebf442016-05-06 05:49:19 +00001139
1140 auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001141 auto LookupBPI = [&FAM](Function &F) {
1142 return &FAM.getResult<BranchProbabilityAnalysis>(F);
Xinliang David Li8aebf442016-05-06 05:49:19 +00001143 };
1144
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001145 auto LookupBFI = [&FAM](Function &F) {
1146 return &FAM.getResult<BlockFrequencyAnalysis>(F);
Xinliang David Li8aebf442016-05-06 05:49:19 +00001147 };
1148
1149 if (!InstrumentAllFunctions(M, LookupBPI, LookupBFI))
1150 return PreservedAnalyses::all();
1151
1152 return PreservedAnalyses::none();
1153}
1154
Xinliang David Lida195582016-05-10 21:59:52 +00001155static bool annotateAllFunctions(
1156 Module &M, StringRef ProfileFileName,
1157 function_ref<BranchProbabilityInfo *(Function &)> LookupBPI,
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001158 function_ref<BlockFrequencyInfo *(Function &)> LookupBFI) {
Rong Xuf430ae42015-12-09 18:08:16 +00001159 DEBUG(dbgs() << "Read in profile counters: ");
1160 auto &Ctx = M.getContext();
1161 // Read the counter array from file.
1162 auto ReaderOrErr = IndexedInstrProfReader::create(ProfileFileName);
Vedant Kumar9152fd12016-05-19 03:54:45 +00001163 if (Error E = ReaderOrErr.takeError()) {
1164 handleAllErrors(std::move(E), [&](const ErrorInfoBase &EI) {
1165 Ctx.diagnose(
1166 DiagnosticInfoPGOProfile(ProfileFileName.data(), EI.message()));
1167 });
Rong Xuf430ae42015-12-09 18:08:16 +00001168 return false;
1169 }
1170
Xinliang David Lida195582016-05-10 21:59:52 +00001171 std::unique_ptr<IndexedInstrProfReader> PGOReader =
1172 std::move(ReaderOrErr.get());
Rong Xuf430ae42015-12-09 18:08:16 +00001173 if (!PGOReader) {
1174 Ctx.diagnose(DiagnosticInfoPGOProfile(ProfileFileName.data(),
Xinliang David Lida195582016-05-10 21:59:52 +00001175 StringRef("Cannot get PGOReader")));
Rong Xuf430ae42015-12-09 18:08:16 +00001176 return false;
1177 }
Rong Xu33c76c02016-02-10 17:18:30 +00001178 // TODO: might need to change the warning once the clang option is finalized.
1179 if (!PGOReader->isIRLevelProfile()) {
1180 Ctx.diagnose(DiagnosticInfoPGOProfile(
1181 ProfileFileName.data(), "Not an IR level instrumentation profile"));
1182 return false;
1183 }
1184
Rong Xu705f7772016-07-25 18:45:37 +00001185 std::unordered_multimap<Comdat *, GlobalValue *> ComdatMembers;
1186 collectComdatMembers(M, ComdatMembers);
Rong Xu6090afd2016-03-28 17:08:56 +00001187 std::vector<Function *> HotFunctions;
1188 std::vector<Function *> ColdFunctions;
Rong Xuf430ae42015-12-09 18:08:16 +00001189 for (auto &F : M) {
1190 if (F.isDeclaration())
1191 continue;
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001192 auto *BPI = LookupBPI(F);
1193 auto *BFI = LookupBFI(F);
Rong Xu705f7772016-07-25 18:45:37 +00001194 PGOUseFunc Func(F, &M, ComdatMembers, BPI, BFI);
Sean Silva2e8f0952016-05-28 04:19:40 +00001195 if (!Func.readCounters(PGOReader.get()))
1196 continue;
1197 Func.populateCounters();
1198 Func.setBranchWeights();
1199 Func.annotateIndirectCallSites();
Sean Silva9dd4b5c2016-05-28 03:56:25 +00001200 PGOUseFunc::FuncFreqAttr FreqAttr = Func.getFuncFreqAttr();
1201 if (FreqAttr == PGOUseFunc::FFA_Cold)
Sean Silva2a730192016-05-28 03:02:50 +00001202 ColdFunctions.push_back(&F);
Sean Silva9dd4b5c2016-05-28 03:56:25 +00001203 else if (FreqAttr == PGOUseFunc::FFA_Hot)
1204 HotFunctions.push_back(&F);
Rong Xuf430ae42015-12-09 18:08:16 +00001205 }
Easwaran Raman8bceb9d2016-06-21 19:29:49 +00001206 M.setProfileSummary(PGOReader->getSummary().getMD(M.getContext()));
Rong Xu6090afd2016-03-28 17:08:56 +00001207 // Set function hotness attribute from the profile.
Sean Silva42cc3422016-05-28 04:24:39 +00001208 // We have to apply these attributes at the end because their presence
1209 // can affect the BranchProbabilityInfo of any callers, resulting in an
1210 // inconsistent MST between prof-gen and prof-use.
Rong Xu6090afd2016-03-28 17:08:56 +00001211 for (auto &F : HotFunctions) {
1212 F->addFnAttr(llvm::Attribute::InlineHint);
1213 DEBUG(dbgs() << "Set inline attribute to function: " << F->getName()
1214 << "\n");
1215 }
1216 for (auto &F : ColdFunctions) {
1217 F->addFnAttr(llvm::Attribute::Cold);
1218 DEBUG(dbgs() << "Set cold attribute to function: " << F->getName() << "\n");
1219 }
Rong Xuf430ae42015-12-09 18:08:16 +00001220 return true;
1221}
Xinliang David Lid55827f2016-05-07 05:39:12 +00001222
Xinliang David Lida195582016-05-10 21:59:52 +00001223PGOInstrumentationUse::PGOInstrumentationUse(std::string Filename)
Benjamin Kramer82de7d32016-05-27 14:27:24 +00001224 : ProfileFileName(std::move(Filename)) {
Xinliang David Lida195582016-05-10 21:59:52 +00001225 if (!PGOTestProfileFile.empty())
1226 ProfileFileName = PGOTestProfileFile;
1227}
1228
1229PreservedAnalyses PGOInstrumentationUse::run(Module &M,
Sean Silvafd03ac62016-08-09 00:28:38 +00001230 ModuleAnalysisManager &AM) {
Xinliang David Lida195582016-05-10 21:59:52 +00001231
1232 auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
1233 auto LookupBPI = [&FAM](Function &F) {
1234 return &FAM.getResult<BranchProbabilityAnalysis>(F);
1235 };
1236
1237 auto LookupBFI = [&FAM](Function &F) {
1238 return &FAM.getResult<BlockFrequencyAnalysis>(F);
1239 };
1240
1241 if (!annotateAllFunctions(M, ProfileFileName, LookupBPI, LookupBFI))
1242 return PreservedAnalyses::all();
1243
1244 return PreservedAnalyses::none();
1245}
1246
Xinliang David Lid55827f2016-05-07 05:39:12 +00001247bool PGOInstrumentationUseLegacyPass::runOnModule(Module &M) {
1248 if (skipModule(M))
1249 return false;
1250
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001251 auto LookupBPI = [this](Function &F) {
1252 return &this->getAnalysis<BranchProbabilityInfoWrapperPass>(F).getBPI();
Xinliang David Lid55827f2016-05-07 05:39:12 +00001253 };
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001254 auto LookupBFI = [this](Function &F) {
1255 return &this->getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI();
Xinliang David Lid55827f2016-05-07 05:39:12 +00001256 };
1257
Xinliang David Lida195582016-05-10 21:59:52 +00001258 return annotateAllFunctions(M, ProfileFileName, LookupBPI, LookupBFI);
Xinliang David Lid55827f2016-05-07 05:39:12 +00001259}