blob: 379f7c5ebed95764b972eca7705cca59f065be39 [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 Xu0eb36032016-04-01 23:16:44 +000053#include "IndirectCallSiteVisitor.h"
Rong Xuf430ae42015-12-09 18:08:16 +000054#include "llvm/ADT/STLExtras.h"
55#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"
Rong Xued9fec72016-01-21 18:11:44 +000060#include "llvm/IR/CallSite.h"
Rong Xuf430ae42015-12-09 18:08:16 +000061#include "llvm/IR/DiagnosticInfo.h"
62#include "llvm/IR/IRBuilder.h"
63#include "llvm/IR/InstIterator.h"
64#include "llvm/IR/Instructions.h"
65#include "llvm/IR/IntrinsicInst.h"
66#include "llvm/IR/MDBuilder.h"
67#include "llvm/IR/Module.h"
68#include "llvm/Pass.h"
69#include "llvm/ProfileData/InstrProfReader.h"
70#include "llvm/Support/BranchProbability.h"
71#include "llvm/Support/Debug.h"
72#include "llvm/Support/JamCRC.h"
Rong Xued9fec72016-01-21 18:11:44 +000073#include "llvm/Transforms/Instrumentation.h"
Rong Xuf430ae42015-12-09 18:08:16 +000074#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Xinliang David Li8aebf442016-05-06 05:49:19 +000075#include <algorithm>
Rong Xuf430ae42015-12-09 18:08:16 +000076#include <string>
77#include <utility>
78#include <vector>
79
80using namespace llvm;
81
82#define DEBUG_TYPE "pgo-instrumentation"
83
84STATISTIC(NumOfPGOInstrument, "Number of edges instrumented.");
85STATISTIC(NumOfPGOEdge, "Number of edges.");
86STATISTIC(NumOfPGOBB, "Number of basic-blocks.");
87STATISTIC(NumOfPGOSplit, "Number of critical edge splits.");
88STATISTIC(NumOfPGOFunc, "Number of functions having valid profile counts.");
89STATISTIC(NumOfPGOMismatch, "Number of functions having mismatch profile.");
90STATISTIC(NumOfPGOMissing, "Number of functions without profile.");
Rong Xu13b01dc2016-02-10 18:24:45 +000091STATISTIC(NumOfPGOICall, "Number of indirect call value instrumentations.");
Rong Xuf430ae42015-12-09 18:08:16 +000092
93// Command line option to specify the file to read profile from. This is
94// mainly used for testing.
95static cl::opt<std::string>
96 PGOTestProfileFile("pgo-test-profile-file", cl::init(""), cl::Hidden,
97 cl::value_desc("filename"),
98 cl::desc("Specify the path of profile data file. This is"
99 "mainly for test purpose."));
100
Rong Xuecdc98f2016-03-04 22:08:44 +0000101// Command line option to disable value profiling. The default is false:
Rong Xu13b01dc2016-02-10 18:24:45 +0000102// i.e. value profiling is enabled by default. This is for debug purpose.
Rong Xu9e926e82016-02-29 19:16:04 +0000103static cl::opt<bool> DisableValueProfiling("disable-vp", cl::init(false),
104 cl::Hidden,
105 cl::desc("Disable Value Profiling"));
Rong Xued9fec72016-01-21 18:11:44 +0000106
Rong Xuecdc98f2016-03-04 22:08:44 +0000107// Command line option to set the maximum number of VP annotations to write to
Rong Xu08afb052016-04-28 17:31:22 +0000108// the metadata for a single indirect call callsite.
109static cl::opt<unsigned> MaxNumAnnotations(
110 "icp-max-annotations", cl::init(3), cl::Hidden, cl::ZeroOrMore,
111 cl::desc("Max number of annotations for a single indirect "
112 "call callsite"));
Rong Xuecdc98f2016-03-04 22:08:44 +0000113
Rong Xu0698de92016-05-13 17:26:06 +0000114// Command line option to enable/disable the warning about missing profile
115// information.
116static cl::opt<bool> NoPGOWarnMissing("no-pgo-warn-missing", cl::init(false),
117 cl::Hidden);
118
119// Command line option to enable/disable the warning about a hash mismatch in
120// the profile data.
121static cl::opt<bool> NoPGOWarnMismatch("no-pgo-warn-mismatch", cl::init(false),
122 cl::Hidden);
123
Rong Xuf430ae42015-12-09 18:08:16 +0000124namespace {
Xinliang David Li8aebf442016-05-06 05:49:19 +0000125class PGOInstrumentationGenLegacyPass : public ModulePass {
Rong Xuf430ae42015-12-09 18:08:16 +0000126public:
127 static char ID;
128
Xinliang David Lidfa21c32016-05-09 21:37:12 +0000129 PGOInstrumentationGenLegacyPass() : ModulePass(ID) {
Xinliang David Li8aebf442016-05-06 05:49:19 +0000130 initializePGOInstrumentationGenLegacyPassPass(
131 *PassRegistry::getPassRegistry());
Rong Xuf430ae42015-12-09 18:08:16 +0000132 }
133
134 const char *getPassName() const override {
135 return "PGOInstrumentationGenPass";
136 }
137
138private:
139 bool runOnModule(Module &M) override;
140
141 void getAnalysisUsage(AnalysisUsage &AU) const override {
142 AU.addRequired<BlockFrequencyInfoWrapperPass>();
143 }
144};
145
Xinliang David Lid55827f2016-05-07 05:39:12 +0000146class PGOInstrumentationUseLegacyPass : public ModulePass {
Rong Xuf430ae42015-12-09 18:08:16 +0000147public:
148 static char ID;
149
150 // Provide the profile filename as the parameter.
Xinliang David Lid55827f2016-05-07 05:39:12 +0000151 PGOInstrumentationUseLegacyPass(std::string Filename = "")
Rong Xuf430ae42015-12-09 18:08:16 +0000152 : ModulePass(ID), ProfileFileName(Filename) {
153 if (!PGOTestProfileFile.empty())
154 ProfileFileName = PGOTestProfileFile;
Xinliang David Lid55827f2016-05-07 05:39:12 +0000155 initializePGOInstrumentationUseLegacyPassPass(
156 *PassRegistry::getPassRegistry());
Rong Xuf430ae42015-12-09 18:08:16 +0000157 }
158
159 const char *getPassName() const override {
160 return "PGOInstrumentationUsePass";
161 }
162
163private:
164 std::string ProfileFileName;
Rong Xuf430ae42015-12-09 18:08:16 +0000165
Xinliang David Lida195582016-05-10 21:59:52 +0000166 bool runOnModule(Module &M) override;
Rong Xuf430ae42015-12-09 18:08:16 +0000167 void getAnalysisUsage(AnalysisUsage &AU) const override {
168 AU.addRequired<BlockFrequencyInfoWrapperPass>();
169 }
170};
171} // end anonymous namespace
172
Xinliang David Li8aebf442016-05-06 05:49:19 +0000173char PGOInstrumentationGenLegacyPass::ID = 0;
174INITIALIZE_PASS_BEGIN(PGOInstrumentationGenLegacyPass, "pgo-instr-gen",
Rong Xuf430ae42015-12-09 18:08:16 +0000175 "PGO instrumentation.", false, false)
176INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
177INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
Xinliang David Li8aebf442016-05-06 05:49:19 +0000178INITIALIZE_PASS_END(PGOInstrumentationGenLegacyPass, "pgo-instr-gen",
Rong Xuf430ae42015-12-09 18:08:16 +0000179 "PGO instrumentation.", false, false)
180
Xinliang David Li8aebf442016-05-06 05:49:19 +0000181ModulePass *llvm::createPGOInstrumentationGenLegacyPass() {
182 return new PGOInstrumentationGenLegacyPass();
Rong Xuf430ae42015-12-09 18:08:16 +0000183}
184
Xinliang David Lid55827f2016-05-07 05:39:12 +0000185char PGOInstrumentationUseLegacyPass::ID = 0;
186INITIALIZE_PASS_BEGIN(PGOInstrumentationUseLegacyPass, "pgo-instr-use",
Rong Xuf430ae42015-12-09 18:08:16 +0000187 "Read PGO instrumentation profile.", false, false)
188INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
189INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
Xinliang David Lid55827f2016-05-07 05:39:12 +0000190INITIALIZE_PASS_END(PGOInstrumentationUseLegacyPass, "pgo-instr-use",
Rong Xuf430ae42015-12-09 18:08:16 +0000191 "Read PGO instrumentation profile.", false, false)
192
Xinliang David Lid55827f2016-05-07 05:39:12 +0000193ModulePass *llvm::createPGOInstrumentationUseLegacyPass(StringRef Filename) {
194 return new PGOInstrumentationUseLegacyPass(Filename.str());
Rong Xuf430ae42015-12-09 18:08:16 +0000195}
196
197namespace {
198/// \brief An MST based instrumentation for PGO
199///
200/// Implements a Minimum Spanning Tree (MST) based instrumentation for PGO
201/// in the function level.
202struct PGOEdge {
203 // This class implements the CFG edges. Note the CFG can be a multi-graph.
204 // So there might be multiple edges with same SrcBB and DestBB.
205 const BasicBlock *SrcBB;
206 const BasicBlock *DestBB;
207 uint64_t Weight;
208 bool InMST;
209 bool Removed;
210 bool IsCritical;
211 PGOEdge(const BasicBlock *Src, const BasicBlock *Dest, unsigned W = 1)
212 : SrcBB(Src), DestBB(Dest), Weight(W), InMST(false), Removed(false),
213 IsCritical(false) {}
214 // Return the information string of an edge.
215 const std::string infoString() const {
216 return (Twine(Removed ? "-" : " ") + (InMST ? " " : "*") +
217 (IsCritical ? "c" : " ") + " W=" + Twine(Weight)).str();
218 }
219};
220
221// This class stores the auxiliary information for each BB.
222struct BBInfo {
223 BBInfo *Group;
224 uint32_t Index;
225 uint32_t Rank;
226
227 BBInfo(unsigned IX) : Group(this), Index(IX), Rank(0) {}
228
229 // Return the information string of this object.
230 const std::string infoString() const {
231 return (Twine("Index=") + Twine(Index)).str();
232 }
233};
234
235// This class implements the CFG edges. Note the CFG can be a multi-graph.
236template <class Edge, class BBInfo> class FuncPGOInstrumentation {
237private:
238 Function &F;
239 void computeCFGHash();
240
241public:
242 std::string FuncName;
243 GlobalVariable *FuncNameVar;
244 // CFG hash value for this function.
245 uint64_t FunctionHash;
246
247 // The Minimum Spanning Tree of function CFG.
248 CFGMST<Edge, BBInfo> MST;
249
250 // Give an edge, find the BB that will be instrumented.
251 // Return nullptr if there is no BB to be instrumented.
252 BasicBlock *getInstrBB(Edge *E);
253
254 // Return the auxiliary BB information.
255 BBInfo &getBBInfo(const BasicBlock *BB) const { return MST.getBBInfo(BB); }
256
257 // Dump edges and BB information.
258 void dumpInfo(std::string Str = "") const {
259 MST.dumpEdges(dbgs(), Twine("Dump Function ") + FuncName + " Hash: " +
Rong Xued9fec72016-01-21 18:11:44 +0000260 Twine(FunctionHash) + "\t" + Str);
Rong Xuf430ae42015-12-09 18:08:16 +0000261 }
262
263 FuncPGOInstrumentation(Function &Func, bool CreateGlobalVar = false,
264 BranchProbabilityInfo *BPI = nullptr,
265 BlockFrequencyInfo *BFI = nullptr)
266 : F(Func), FunctionHash(0), MST(F, BPI, BFI) {
267 FuncName = getPGOFuncName(F);
268 computeCFGHash();
269 DEBUG(dumpInfo("after CFGMST"));
270
271 NumOfPGOBB += MST.BBInfos.size();
272 for (auto &E : MST.AllEdges) {
273 if (E->Removed)
274 continue;
275 NumOfPGOEdge++;
276 if (!E->InMST)
277 NumOfPGOInstrument++;
278 }
279
280 if (CreateGlobalVar)
281 FuncNameVar = createPGOFuncNameVar(F, FuncName);
Eugene Zelenko6ac3f732016-01-26 18:48:36 +0000282 }
Rong Xuf430ae42015-12-09 18:08:16 +0000283};
284
285// Compute Hash value for the CFG: the lower 32 bits are CRC32 of the index
286// value of each BB in the CFG. The higher 32 bits record the number of edges.
287template <class Edge, class BBInfo>
288void FuncPGOInstrumentation<Edge, BBInfo>::computeCFGHash() {
289 std::vector<char> Indexes;
290 JamCRC JC;
291 for (auto &BB : F) {
292 const TerminatorInst *TI = BB.getTerminator();
293 for (unsigned I = 0, E = TI->getNumSuccessors(); I != E; ++I) {
294 BasicBlock *Succ = TI->getSuccessor(I);
295 uint32_t Index = getBBInfo(Succ).Index;
296 for (int J = 0; J < 4; J++)
297 Indexes.push_back((char)(Index >> (J * 8)));
298 }
299 }
300 JC.update(Indexes);
301 FunctionHash = (uint64_t)MST.AllEdges.size() << 32 | JC.getCRC();
302}
303
304// Given a CFG E to be instrumented, find which BB to place the instrumented
305// code. The function will split the critical edge if necessary.
306template <class Edge, class BBInfo>
307BasicBlock *FuncPGOInstrumentation<Edge, BBInfo>::getInstrBB(Edge *E) {
308 if (E->InMST || E->Removed)
309 return nullptr;
310
311 BasicBlock *SrcBB = const_cast<BasicBlock *>(E->SrcBB);
312 BasicBlock *DestBB = const_cast<BasicBlock *>(E->DestBB);
313 // For a fake edge, instrument the real BB.
314 if (SrcBB == nullptr)
315 return DestBB;
316 if (DestBB == nullptr)
317 return SrcBB;
318
319 // Instrument the SrcBB if it has a single successor,
320 // otherwise, the DestBB if this is not a critical edge.
321 TerminatorInst *TI = SrcBB->getTerminator();
322 if (TI->getNumSuccessors() <= 1)
323 return SrcBB;
324 if (!E->IsCritical)
325 return DestBB;
326
327 // For a critical edge, we have to split. Instrument the newly
328 // created BB.
329 NumOfPGOSplit++;
330 DEBUG(dbgs() << "Split critical edge: " << getBBInfo(SrcBB).Index << " --> "
331 << getBBInfo(DestBB).Index << "\n");
332 unsigned SuccNum = GetSuccessorNumber(SrcBB, DestBB);
333 BasicBlock *InstrBB = SplitCriticalEdge(TI, SuccNum);
334 assert(InstrBB && "Critical edge is not split");
335
336 E->Removed = true;
337 return InstrBB;
338}
339
Rong Xued9fec72016-01-21 18:11:44 +0000340// Visit all edge and instrument the edges not in MST, and do value profiling.
Rong Xuf430ae42015-12-09 18:08:16 +0000341// Critical edges will be split.
342static void instrumentOneFunc(Function &F, Module *M,
343 BranchProbabilityInfo *BPI,
344 BlockFrequencyInfo *BFI) {
345 unsigned NumCounters = 0;
346 FuncPGOInstrumentation<PGOEdge, BBInfo> FuncInfo(F, true, BPI, BFI);
347 for (auto &E : FuncInfo.MST.AllEdges) {
348 if (!E->InMST && !E->Removed)
349 NumCounters++;
350 }
351
352 uint32_t I = 0;
Rong Xued9fec72016-01-21 18:11:44 +0000353 Type *I8PtrTy = Type::getInt8PtrTy(M->getContext());
Rong Xuf430ae42015-12-09 18:08:16 +0000354 for (auto &E : FuncInfo.MST.AllEdges) {
355 BasicBlock *InstrBB = FuncInfo.getInstrBB(E.get());
356 if (!InstrBB)
357 continue;
358
359 IRBuilder<> Builder(InstrBB, InstrBB->getFirstInsertionPt());
360 assert(Builder.GetInsertPoint() != InstrBB->end() &&
361 "Cannot get the Instrumentation point");
Rong Xuf430ae42015-12-09 18:08:16 +0000362 Builder.CreateCall(
363 Intrinsic::getDeclaration(M, Intrinsic::instrprof_increment),
364 {llvm::ConstantExpr::getBitCast(FuncInfo.FuncNameVar, I8PtrTy),
365 Builder.getInt64(FuncInfo.FunctionHash), Builder.getInt32(NumCounters),
366 Builder.getInt32(I++)});
367 }
Rong Xued9fec72016-01-21 18:11:44 +0000368
369 if (DisableValueProfiling)
370 return;
371
372 unsigned NumIndirectCallSites = 0;
Rong Xu0eb36032016-04-01 23:16:44 +0000373 for (auto &I : findIndirectCallSites(F)) {
Rong Xued9fec72016-01-21 18:11:44 +0000374 CallSite CS(I);
375 Value *Callee = CS.getCalledValue();
376 DEBUG(dbgs() << "Instrument one indirect call: CallSite Index = "
377 << NumIndirectCallSites << "\n");
378 IRBuilder<> Builder(I);
379 assert(Builder.GetInsertPoint() != I->getParent()->end() &&
380 "Cannot get the Instrumentation point");
381 Builder.CreateCall(
382 Intrinsic::getDeclaration(M, Intrinsic::instrprof_value_profile),
383 {llvm::ConstantExpr::getBitCast(FuncInfo.FuncNameVar, I8PtrTy),
384 Builder.getInt64(FuncInfo.FunctionHash),
385 Builder.CreatePtrToInt(Callee, Builder.getInt64Ty()),
386 Builder.getInt32(llvm::InstrProfValueKind::IPVK_IndirectCallTarget),
387 Builder.getInt32(NumIndirectCallSites++)});
388 }
389 NumOfPGOICall += NumIndirectCallSites;
Rong Xuf430ae42015-12-09 18:08:16 +0000390}
391
392// This class represents a CFG edge in profile use compilation.
393struct PGOUseEdge : public PGOEdge {
394 bool CountValid;
395 uint64_t CountValue;
396 PGOUseEdge(const BasicBlock *Src, const BasicBlock *Dest, unsigned W = 1)
397 : PGOEdge(Src, Dest, W), CountValid(false), CountValue(0) {}
398
399 // Set edge count value
400 void setEdgeCount(uint64_t Value) {
401 CountValue = Value;
402 CountValid = true;
403 }
404
405 // Return the information string for this object.
406 const std::string infoString() const {
407 if (!CountValid)
408 return PGOEdge::infoString();
Rong Xu9e926e82016-02-29 19:16:04 +0000409 return (Twine(PGOEdge::infoString()) + " Count=" + Twine(CountValue))
410 .str();
Rong Xuf430ae42015-12-09 18:08:16 +0000411 }
412};
413
414typedef SmallVector<PGOUseEdge *, 2> DirectEdges;
415
416// This class stores the auxiliary information for each BB.
417struct UseBBInfo : public BBInfo {
418 uint64_t CountValue;
419 bool CountValid;
420 int32_t UnknownCountInEdge;
421 int32_t UnknownCountOutEdge;
422 DirectEdges InEdges;
423 DirectEdges OutEdges;
424 UseBBInfo(unsigned IX)
425 : BBInfo(IX), CountValue(0), CountValid(false), UnknownCountInEdge(0),
426 UnknownCountOutEdge(0) {}
427 UseBBInfo(unsigned IX, uint64_t C)
428 : BBInfo(IX), CountValue(C), CountValid(true), UnknownCountInEdge(0),
429 UnknownCountOutEdge(0) {}
430
431 // Set the profile count value for this BB.
432 void setBBInfoCount(uint64_t Value) {
433 CountValue = Value;
434 CountValid = true;
435 }
436
437 // Return the information string of this object.
438 const std::string infoString() const {
439 if (!CountValid)
440 return BBInfo::infoString();
441 return (Twine(BBInfo::infoString()) + " Count=" + Twine(CountValue)).str();
442 }
443};
444
445// Sum up the count values for all the edges.
446static uint64_t sumEdgeCount(const ArrayRef<PGOUseEdge *> Edges) {
447 uint64_t Total = 0;
448 for (auto &E : Edges) {
449 if (E->Removed)
450 continue;
451 Total += E->CountValue;
452 }
453 return Total;
454}
455
456class PGOUseFunc {
Rong Xu6090afd2016-03-28 17:08:56 +0000457public:
458 PGOUseFunc(Function &Func, Module *Modu, BranchProbabilityInfo *BPI = nullptr,
459 BlockFrequencyInfo *BFI = nullptr)
460 : F(Func), M(Modu), FuncInfo(Func, false, BPI, BFI),
461 FreqAttr(FFA_Normal) {}
462
463 // Read counts for the instrumented BB from profile.
464 bool readCounters(IndexedInstrProfReader *PGOReader);
465
466 // Populate the counts for all BBs.
467 void populateCounters();
468
469 // Set the branch weights based on the count values.
470 void setBranchWeights();
471
472 // Annotate the indirect call sites.
473 void annotateIndirectCallSites();
474
475 // The hotness of the function from the profile count.
476 enum FuncFreqAttr { FFA_Normal, FFA_Cold, FFA_Hot };
477
Rong Xu08afb052016-04-28 17:31:22 +0000478 // Return the function hotness from the profile.
479 FuncFreqAttr getFuncFreqAttr() const { return FreqAttr; }
Rong Xu6090afd2016-03-28 17:08:56 +0000480
Rong Xuf430ae42015-12-09 18:08:16 +0000481private:
482 Function &F;
483 Module *M;
484 // This member stores the shared information with class PGOGenFunc.
485 FuncPGOInstrumentation<PGOUseEdge, UseBBInfo> FuncInfo;
486
487 // Return the auxiliary BB information.
488 UseBBInfo &getBBInfo(const BasicBlock *BB) const {
489 return FuncInfo.getBBInfo(BB);
490 }
491
492 // The maximum count value in the profile. This is only used in PGO use
493 // compilation.
494 uint64_t ProgramMaxCount;
495
Rong Xu13b01dc2016-02-10 18:24:45 +0000496 // ProfileRecord for this function.
497 InstrProfRecord ProfileRecord;
498
Rong Xu6090afd2016-03-28 17:08:56 +0000499 // Function hotness info derived from profile.
500 FuncFreqAttr FreqAttr;
501
Rong Xuf430ae42015-12-09 18:08:16 +0000502 // Find the Instrumented BB and set the value.
503 void setInstrumentedCounts(const std::vector<uint64_t> &CountFromProfile);
504
505 // Set the edge counter value for the unknown edge -- there should be only
506 // one unknown edge.
507 void setEdgeCount(DirectEdges &Edges, uint64_t Value);
508
509 // Return FuncName string;
510 const std::string getFuncName() const { return FuncInfo.FuncName; }
511
512 // Set the hot/cold inline hints based on the count values.
513 // FIXME: This function should be removed once the functionality in
514 // the inliner is implemented.
Rong Xu6090afd2016-03-28 17:08:56 +0000515 void markFunctionAttributes(uint64_t EntryCount, uint64_t MaxCount) {
Rong Xuf430ae42015-12-09 18:08:16 +0000516 if (ProgramMaxCount == 0)
517 return;
518 // Threshold of the hot functions.
519 const BranchProbability HotFunctionThreshold(1, 100);
520 // Threshold of the cold functions.
521 const BranchProbability ColdFunctionThreshold(2, 10000);
522 if (EntryCount >= HotFunctionThreshold.scale(ProgramMaxCount))
Rong Xu6090afd2016-03-28 17:08:56 +0000523 FreqAttr = FFA_Hot;
Rong Xuf430ae42015-12-09 18:08:16 +0000524 else if (MaxCount <= ColdFunctionThreshold.scale(ProgramMaxCount))
Rong Xu6090afd2016-03-28 17:08:56 +0000525 FreqAttr = FFA_Cold;
Rong Xuf430ae42015-12-09 18:08:16 +0000526 }
Rong Xuf430ae42015-12-09 18:08:16 +0000527};
528
529// Visit all the edges and assign the count value for the instrumented
530// edges and the BB.
531void PGOUseFunc::setInstrumentedCounts(
532 const std::vector<uint64_t> &CountFromProfile) {
533
534 // Use a worklist as we will update the vector during the iteration.
535 std::vector<PGOUseEdge *> WorkList;
536 for (auto &E : FuncInfo.MST.AllEdges)
537 WorkList.push_back(E.get());
538
539 uint32_t I = 0;
540 for (auto &E : WorkList) {
541 BasicBlock *InstrBB = FuncInfo.getInstrBB(E);
542 if (!InstrBB)
543 continue;
544 uint64_t CountValue = CountFromProfile[I++];
545 if (!E->Removed) {
546 getBBInfo(InstrBB).setBBInfoCount(CountValue);
547 E->setEdgeCount(CountValue);
548 continue;
549 }
550
551 // Need to add two new edges.
552 BasicBlock *SrcBB = const_cast<BasicBlock *>(E->SrcBB);
553 BasicBlock *DestBB = const_cast<BasicBlock *>(E->DestBB);
554 // Add new edge of SrcBB->InstrBB.
555 PGOUseEdge &NewEdge = FuncInfo.MST.addEdge(SrcBB, InstrBB, 0);
556 NewEdge.setEdgeCount(CountValue);
557 // Add new edge of InstrBB->DestBB.
558 PGOUseEdge &NewEdge1 = FuncInfo.MST.addEdge(InstrBB, DestBB, 0);
559 NewEdge1.setEdgeCount(CountValue);
560 NewEdge1.InMST = true;
561 getBBInfo(InstrBB).setBBInfoCount(CountValue);
562 }
563}
564
565// Set the count value for the unknown edge. There should be one and only one
566// unknown edge in Edges vector.
567void PGOUseFunc::setEdgeCount(DirectEdges &Edges, uint64_t Value) {
568 for (auto &E : Edges) {
569 if (E->CountValid)
570 continue;
571 E->setEdgeCount(Value);
572
573 getBBInfo(E->SrcBB).UnknownCountOutEdge--;
574 getBBInfo(E->DestBB).UnknownCountInEdge--;
575 return;
576 }
577 llvm_unreachable("Cannot find the unknown count edge");
578}
579
580// Read the profile from ProfileFileName and assign the value to the
581// instrumented BB and the edges. This function also updates ProgramMaxCount.
582// Return true if the profile are successfully read, and false on errors.
583bool PGOUseFunc::readCounters(IndexedInstrProfReader *PGOReader) {
584 auto &Ctx = M->getContext();
585 ErrorOr<InstrProfRecord> Result =
586 PGOReader->getInstrProfRecord(FuncInfo.FuncName, FuncInfo.FunctionHash);
587 if (std::error_code EC = Result.getError()) {
Rong Xu0698de92016-05-13 17:26:06 +0000588 if (EC == instrprof_error::unknown_function) {
Rong Xuf430ae42015-12-09 18:08:16 +0000589 NumOfPGOMissing++;
Rong Xu0698de92016-05-13 17:26:06 +0000590 if (NoPGOWarnMissing)
591 return false;
592 } else if (EC == instrprof_error::hash_mismatch ||
593 EC == llvm::instrprof_error::malformed) {
Rong Xuf430ae42015-12-09 18:08:16 +0000594 NumOfPGOMismatch++;
Rong Xu0698de92016-05-13 17:26:06 +0000595 if (NoPGOWarnMismatch)
596 return false;
597 }
Rong Xuf430ae42015-12-09 18:08:16 +0000598
599 std::string Msg = EC.message() + std::string(" ") + F.getName().str();
600 Ctx.diagnose(
601 DiagnosticInfoPGOProfile(M->getName().data(), Msg, DS_Warning));
602 return false;
603 }
Rong Xu13b01dc2016-02-10 18:24:45 +0000604 ProfileRecord = std::move(Result.get());
605 std::vector<uint64_t> &CountFromProfile = ProfileRecord.Counts;
Rong Xuf430ae42015-12-09 18:08:16 +0000606
607 NumOfPGOFunc++;
608 DEBUG(dbgs() << CountFromProfile.size() << " counts\n");
609 uint64_t ValueSum = 0;
610 for (unsigned I = 0, S = CountFromProfile.size(); I < S; I++) {
611 DEBUG(dbgs() << " " << I << ": " << CountFromProfile[I] << "\n");
612 ValueSum += CountFromProfile[I];
613 }
614
615 DEBUG(dbgs() << "SUM = " << ValueSum << "\n");
616
617 getBBInfo(nullptr).UnknownCountOutEdge = 2;
618 getBBInfo(nullptr).UnknownCountInEdge = 2;
619
620 setInstrumentedCounts(CountFromProfile);
621 ProgramMaxCount = PGOReader->getMaximumFunctionCount();
622 return true;
623}
624
625// Populate the counters from instrumented BBs to all BBs.
626// In the end of this operation, all BBs should have a valid count value.
627void PGOUseFunc::populateCounters() {
628 // First set up Count variable for all BBs.
629 for (auto &E : FuncInfo.MST.AllEdges) {
630 if (E->Removed)
631 continue;
632
633 const BasicBlock *SrcBB = E->SrcBB;
634 const BasicBlock *DestBB = E->DestBB;
635 UseBBInfo &SrcInfo = getBBInfo(SrcBB);
636 UseBBInfo &DestInfo = getBBInfo(DestBB);
637 SrcInfo.OutEdges.push_back(E.get());
638 DestInfo.InEdges.push_back(E.get());
639 SrcInfo.UnknownCountOutEdge++;
640 DestInfo.UnknownCountInEdge++;
641
642 if (!E->CountValid)
643 continue;
644 DestInfo.UnknownCountInEdge--;
645 SrcInfo.UnknownCountOutEdge--;
646 }
647
648 bool Changes = true;
649 unsigned NumPasses = 0;
650 while (Changes) {
651 NumPasses++;
652 Changes = false;
653
654 // For efficient traversal, it's better to start from the end as most
655 // of the instrumented edges are at the end.
656 for (auto &BB : reverse(F)) {
657 UseBBInfo &Count = getBBInfo(&BB);
658 if (!Count.CountValid) {
659 if (Count.UnknownCountOutEdge == 0) {
660 Count.CountValue = sumEdgeCount(Count.OutEdges);
661 Count.CountValid = true;
662 Changes = true;
663 } else if (Count.UnknownCountInEdge == 0) {
664 Count.CountValue = sumEdgeCount(Count.InEdges);
665 Count.CountValid = true;
666 Changes = true;
667 }
668 }
669 if (Count.CountValid) {
670 if (Count.UnknownCountOutEdge == 1) {
671 uint64_t Total = Count.CountValue - sumEdgeCount(Count.OutEdges);
672 setEdgeCount(Count.OutEdges, Total);
673 Changes = true;
674 }
675 if (Count.UnknownCountInEdge == 1) {
676 uint64_t Total = Count.CountValue - sumEdgeCount(Count.InEdges);
677 setEdgeCount(Count.InEdges, Total);
678 Changes = true;
679 }
680 }
681 }
682 }
683
684 DEBUG(dbgs() << "Populate counts in " << NumPasses << " passes.\n");
685 // Assert every BB has a valid counter.
686 uint64_t FuncEntryCount = getBBInfo(&*F.begin()).CountValue;
687 uint64_t FuncMaxCount = FuncEntryCount;
688 for (auto &BB : F) {
689 assert(getBBInfo(&BB).CountValid && "BB count is not valid");
690 uint64_t Count = getBBInfo(&BB).CountValue;
691 if (Count > FuncMaxCount)
692 FuncMaxCount = Count;
693 }
Rong Xu6090afd2016-03-28 17:08:56 +0000694 markFunctionAttributes(FuncEntryCount, FuncMaxCount);
Rong Xuf430ae42015-12-09 18:08:16 +0000695
696 DEBUG(FuncInfo.dumpInfo("after reading profile."));
697}
698
699// Assign the scaled count values to the BB with multiple out edges.
700void PGOUseFunc::setBranchWeights() {
701 // Generate MD_prof metadata for every branch instruction.
702 DEBUG(dbgs() << "\nSetting branch weights.\n");
703 MDBuilder MDB(M->getContext());
704 for (auto &BB : F) {
705 TerminatorInst *TI = BB.getTerminator();
706 if (TI->getNumSuccessors() < 2)
707 continue;
708 if (!isa<BranchInst>(TI) && !isa<SwitchInst>(TI))
709 continue;
710 if (getBBInfo(&BB).CountValue == 0)
711 continue;
712
713 // We have a non-zero Branch BB.
714 const UseBBInfo &BBCountInfo = getBBInfo(&BB);
715 unsigned Size = BBCountInfo.OutEdges.size();
716 SmallVector<unsigned, 2> EdgeCounts(Size, 0);
717 uint64_t MaxCount = 0;
718 for (unsigned s = 0; s < Size; s++) {
719 const PGOUseEdge *E = BBCountInfo.OutEdges[s];
720 const BasicBlock *SrcBB = E->SrcBB;
721 const BasicBlock *DestBB = E->DestBB;
Eugene Zelenko6ac3f732016-01-26 18:48:36 +0000722 if (DestBB == nullptr)
Rong Xuf430ae42015-12-09 18:08:16 +0000723 continue;
724 unsigned SuccNum = GetSuccessorNumber(SrcBB, DestBB);
725 uint64_t EdgeCount = E->CountValue;
726 if (EdgeCount > MaxCount)
727 MaxCount = EdgeCount;
728 EdgeCounts[SuccNum] = EdgeCount;
729 }
730 assert(MaxCount > 0 && "Bad max count");
731 uint64_t Scale = calculateCountScale(MaxCount);
732 SmallVector<unsigned, 4> Weights;
733 for (const auto &ECI : EdgeCounts)
734 Weights.push_back(scaleBranchCount(ECI, Scale));
735
736 TI->setMetadata(llvm::LLVMContext::MD_prof,
737 MDB.createBranchWeights(Weights));
738 DEBUG(dbgs() << "Weight is: ";
739 for (const auto &W : Weights) { dbgs() << W << " "; }
740 dbgs() << "\n";);
741 }
742}
Rong Xu13b01dc2016-02-10 18:24:45 +0000743
744// Traverse all the indirect callsites and annotate the instructions.
745void PGOUseFunc::annotateIndirectCallSites() {
746 if (DisableValueProfiling)
747 return;
748
Rong Xu8e8fe852016-04-01 16:43:30 +0000749 // Create the PGOFuncName meta data.
Rong Xuf8f051c2016-04-22 21:00:17 +0000750 createPGOFuncNameMetadata(F, FuncInfo.FuncName);
Rong Xub5341662016-03-30 18:37:52 +0000751
Rong Xu13b01dc2016-02-10 18:24:45 +0000752 unsigned IndirectCallSiteIndex = 0;
Rong Xu0eb36032016-04-01 23:16:44 +0000753 auto IndirectCallSites = findIndirectCallSites(F);
Rong Xu9e926e82016-02-29 19:16:04 +0000754 unsigned NumValueSites =
Rong Xu13b01dc2016-02-10 18:24:45 +0000755 ProfileRecord.getNumValueSites(IPVK_IndirectCallTarget);
Rong Xu0eb36032016-04-01 23:16:44 +0000756 if (NumValueSites != IndirectCallSites.size()) {
Rong Xu13b01dc2016-02-10 18:24:45 +0000757 std::string Msg =
758 std::string("Inconsistent number of indirect call sites: ") +
Rong Xu9e926e82016-02-29 19:16:04 +0000759 F.getName().str();
Rong Xu13b01dc2016-02-10 18:24:45 +0000760 auto &Ctx = M->getContext();
761 Ctx.diagnose(
762 DiagnosticInfoPGOProfile(M->getName().data(), Msg, DS_Warning));
763 return;
764 }
765
Rong Xu0eb36032016-04-01 23:16:44 +0000766 for (auto &I : IndirectCallSites) {
Rong Xu13b01dc2016-02-10 18:24:45 +0000767 DEBUG(dbgs() << "Read one indirect call instrumentation: Index="
Rong Xu9e926e82016-02-29 19:16:04 +0000768 << IndirectCallSiteIndex << " out of " << NumValueSites
769 << "\n");
Rong Xu13b01dc2016-02-10 18:24:45 +0000770 annotateValueSite(*M, *I, ProfileRecord, IPVK_IndirectCallTarget,
Rong Xuecdc98f2016-03-04 22:08:44 +0000771 IndirectCallSiteIndex, MaxNumAnnotations);
Rong Xu13b01dc2016-02-10 18:24:45 +0000772 IndirectCallSiteIndex++;
773 }
774}
Rong Xuf430ae42015-12-09 18:08:16 +0000775} // end anonymous namespace
776
Rong Xu33c76c02016-02-10 17:18:30 +0000777// Create a COMDAT variable IR_LEVEL_PROF_VARNAME to make the runtime
778// aware this is an ir_level profile so it can set the version flag.
779static void createIRLevelProfileFlagVariable(Module &M) {
780 Type *IntTy64 = Type::getInt64Ty(M.getContext());
781 uint64_t ProfileVersion = (INSTR_PROF_RAW_VERSION | VARIANT_MASK_IR_PROF);
Rong Xu9e926e82016-02-29 19:16:04 +0000782 auto IRLevelVersionVariable = new GlobalVariable(
783 M, IntTy64, true, GlobalVariable::ExternalLinkage,
784 Constant::getIntegerValue(IntTy64, APInt(64, ProfileVersion)),
785 INSTR_PROF_QUOTE(IR_LEVEL_PROF_VERSION_VAR));
Rong Xu33c76c02016-02-10 17:18:30 +0000786 IRLevelVersionVariable->setVisibility(GlobalValue::DefaultVisibility);
787 Triple TT(M.getTargetTriple());
788 if (TT.isOSBinFormatMachO())
Rong Xuca28a0a2016-05-11 00:31:59 +0000789 IRLevelVersionVariable->setLinkage(GlobalValue::WeakAnyLinkage);
Rong Xu33c76c02016-02-10 17:18:30 +0000790 else
Rong Xu9e926e82016-02-29 19:16:04 +0000791 IRLevelVersionVariable->setComdat(M.getOrInsertComdat(
792 StringRef(INSTR_PROF_QUOTE(IR_LEVEL_PROF_VERSION_VAR))));
Rong Xu33c76c02016-02-10 17:18:30 +0000793}
794
Xinliang David Li5ad7c822016-05-02 20:33:59 +0000795static bool InstrumentAllFunctions(
Xinliang David Lidfa21c32016-05-09 21:37:12 +0000796 Module &M, function_ref<BranchProbabilityInfo *(Function &)> LookupBPI,
797 function_ref<BlockFrequencyInfo *(Function &)> LookupBFI) {
Rong Xu33c76c02016-02-10 17:18:30 +0000798 createIRLevelProfileFlagVariable(M);
Rong Xuf430ae42015-12-09 18:08:16 +0000799 for (auto &F : M) {
800 if (F.isDeclaration())
801 continue;
Xinliang David Lidfa21c32016-05-09 21:37:12 +0000802 auto *BPI = LookupBPI(F);
803 auto *BFI = LookupBFI(F);
804 instrumentOneFunc(F, &M, BPI, BFI);
Rong Xuf430ae42015-12-09 18:08:16 +0000805 }
806 return true;
807}
808
Xinliang David Li8aebf442016-05-06 05:49:19 +0000809bool PGOInstrumentationGenLegacyPass::runOnModule(Module &M) {
Xinliang David Li5ad7c822016-05-02 20:33:59 +0000810 if (skipModule(M))
811 return false;
812
Xinliang David Lidfa21c32016-05-09 21:37:12 +0000813 auto LookupBPI = [this](Function &F) {
814 return &this->getAnalysis<BranchProbabilityInfoWrapperPass>(F).getBPI();
Xinliang David Li5ad7c822016-05-02 20:33:59 +0000815 };
Xinliang David Lidfa21c32016-05-09 21:37:12 +0000816 auto LookupBFI = [this](Function &F) {
817 return &this->getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI();
Xinliang David Li5ad7c822016-05-02 20:33:59 +0000818 };
819 return InstrumentAllFunctions(M, LookupBPI, LookupBFI);
820}
821
Xinliang David Li8aebf442016-05-06 05:49:19 +0000822PreservedAnalyses PGOInstrumentationGen::run(Module &M,
823 AnalysisManager<Module> &AM) {
824
825 auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
Xinliang David Lidfa21c32016-05-09 21:37:12 +0000826 auto LookupBPI = [&FAM](Function &F) {
827 return &FAM.getResult<BranchProbabilityAnalysis>(F);
Xinliang David Li8aebf442016-05-06 05:49:19 +0000828 };
829
Xinliang David Lidfa21c32016-05-09 21:37:12 +0000830 auto LookupBFI = [&FAM](Function &F) {
831 return &FAM.getResult<BlockFrequencyAnalysis>(F);
Xinliang David Li8aebf442016-05-06 05:49:19 +0000832 };
833
834 if (!InstrumentAllFunctions(M, LookupBPI, LookupBFI))
835 return PreservedAnalyses::all();
836
837 return PreservedAnalyses::none();
838}
839
Rong Xuf430ae42015-12-09 18:08:16 +0000840static void setPGOCountOnFunc(PGOUseFunc &Func,
841 IndexedInstrProfReader *PGOReader) {
842 if (Func.readCounters(PGOReader)) {
843 Func.populateCounters();
844 Func.setBranchWeights();
Rong Xu13b01dc2016-02-10 18:24:45 +0000845 Func.annotateIndirectCallSites();
Rong Xuf430ae42015-12-09 18:08:16 +0000846 }
847}
848
Xinliang David Lida195582016-05-10 21:59:52 +0000849static bool annotateAllFunctions(
850 Module &M, StringRef ProfileFileName,
851 function_ref<BranchProbabilityInfo *(Function &)> LookupBPI,
Xinliang David Lidfa21c32016-05-09 21:37:12 +0000852 function_ref<BlockFrequencyInfo *(Function &)> LookupBFI) {
Rong Xuf430ae42015-12-09 18:08:16 +0000853 DEBUG(dbgs() << "Read in profile counters: ");
854 auto &Ctx = M.getContext();
855 // Read the counter array from file.
856 auto ReaderOrErr = IndexedInstrProfReader::create(ProfileFileName);
857 if (std::error_code EC = ReaderOrErr.getError()) {
858 Ctx.diagnose(
859 DiagnosticInfoPGOProfile(ProfileFileName.data(), EC.message()));
860 return false;
861 }
862
Xinliang David Lida195582016-05-10 21:59:52 +0000863 std::unique_ptr<IndexedInstrProfReader> PGOReader =
864 std::move(ReaderOrErr.get());
Rong Xuf430ae42015-12-09 18:08:16 +0000865 if (!PGOReader) {
866 Ctx.diagnose(DiagnosticInfoPGOProfile(ProfileFileName.data(),
Xinliang David Lida195582016-05-10 21:59:52 +0000867 StringRef("Cannot get PGOReader")));
Rong Xuf430ae42015-12-09 18:08:16 +0000868 return false;
869 }
Rong Xu33c76c02016-02-10 17:18:30 +0000870 // TODO: might need to change the warning once the clang option is finalized.
871 if (!PGOReader->isIRLevelProfile()) {
872 Ctx.diagnose(DiagnosticInfoPGOProfile(
873 ProfileFileName.data(), "Not an IR level instrumentation profile"));
874 return false;
875 }
876
Rong Xu6090afd2016-03-28 17:08:56 +0000877 std::vector<Function *> HotFunctions;
878 std::vector<Function *> ColdFunctions;
Rong Xuf430ae42015-12-09 18:08:16 +0000879 for (auto &F : M) {
880 if (F.isDeclaration())
881 continue;
Xinliang David Lidfa21c32016-05-09 21:37:12 +0000882 auto *BPI = LookupBPI(F);
883 auto *BFI = LookupBFI(F);
884 PGOUseFunc Func(F, &M, BPI, BFI);
Rong Xuf430ae42015-12-09 18:08:16 +0000885 setPGOCountOnFunc(Func, PGOReader.get());
Rong Xu6090afd2016-03-28 17:08:56 +0000886 PGOUseFunc::FuncFreqAttr FreqAttr = Func.getFuncFreqAttr();
887 if (FreqAttr == PGOUseFunc::FFA_Cold)
888 ColdFunctions.push_back(&F);
889 else if (FreqAttr == PGOUseFunc::FFA_Hot)
890 HotFunctions.push_back(&F);
Rong Xuf430ae42015-12-09 18:08:16 +0000891 }
Rong Xu6090afd2016-03-28 17:08:56 +0000892
893 // Set function hotness attribute from the profile.
894 for (auto &F : HotFunctions) {
895 F->addFnAttr(llvm::Attribute::InlineHint);
896 DEBUG(dbgs() << "Set inline attribute to function: " << F->getName()
897 << "\n");
898 }
899 for (auto &F : ColdFunctions) {
900 F->addFnAttr(llvm::Attribute::Cold);
901 DEBUG(dbgs() << "Set cold attribute to function: " << F->getName() << "\n");
902 }
903
Rong Xuf430ae42015-12-09 18:08:16 +0000904 return true;
905}
Xinliang David Lid55827f2016-05-07 05:39:12 +0000906
Xinliang David Lida195582016-05-10 21:59:52 +0000907PGOInstrumentationUse::PGOInstrumentationUse(std::string Filename)
908 : ProfileFileName(Filename) {
909 if (!PGOTestProfileFile.empty())
910 ProfileFileName = PGOTestProfileFile;
911}
912
913PreservedAnalyses PGOInstrumentationUse::run(Module &M,
914 AnalysisManager<Module> &AM) {
915
916 auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
917 auto LookupBPI = [&FAM](Function &F) {
918 return &FAM.getResult<BranchProbabilityAnalysis>(F);
919 };
920
921 auto LookupBFI = [&FAM](Function &F) {
922 return &FAM.getResult<BlockFrequencyAnalysis>(F);
923 };
924
925 if (!annotateAllFunctions(M, ProfileFileName, LookupBPI, LookupBFI))
926 return PreservedAnalyses::all();
927
928 return PreservedAnalyses::none();
929}
930
Xinliang David Lid55827f2016-05-07 05:39:12 +0000931bool PGOInstrumentationUseLegacyPass::runOnModule(Module &M) {
932 if (skipModule(M))
933 return false;
934
Xinliang David Lidfa21c32016-05-09 21:37:12 +0000935 auto LookupBPI = [this](Function &F) {
936 return &this->getAnalysis<BranchProbabilityInfoWrapperPass>(F).getBPI();
Xinliang David Lid55827f2016-05-07 05:39:12 +0000937 };
Xinliang David Lidfa21c32016-05-09 21:37:12 +0000938 auto LookupBFI = [this](Function &F) {
939 return &this->getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI();
Xinliang David Lid55827f2016-05-07 05:39:12 +0000940 };
941
Xinliang David Lida195582016-05-10 21:59:52 +0000942 return annotateAllFunctions(M, ProfileFileName, LookupBPI, LookupBFI);
Xinliang David Lid55827f2016-05-07 05:39:12 +0000943}