1 //===-- PGOInstrumentation.cpp - MST-based PGO Instrumentation ------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
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.
26 // This file contains two passes:
27 // (1) Pass PGOInstrumentationGen which instruments the IR to generate edge
28 // count profile, and generates the instrumentation for indirect call
30 // (2) Pass PGOInstrumentationUse which reads the edge count profile and
31 // annotates the branch weights. It also reads the indirect call value
32 // profiling records and annotate the indirect call instructions.
34 // 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.
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).
49 //===----------------------------------------------------------------------===//
51 #include "llvm/Transforms/PGOInstrumentation.h"
53 #include "llvm/ADT/STLExtras.h"
54 #include "llvm/ADT/SmallVector.h"
55 #include "llvm/ADT/Statistic.h"
56 #include "llvm/ADT/Triple.h"
57 #include "llvm/Analysis/BlockFrequencyInfo.h"
58 #include "llvm/Analysis/BranchProbabilityInfo.h"
59 #include "llvm/Analysis/CFG.h"
60 #include "llvm/Analysis/IndirectCallSiteVisitor.h"
61 #include "llvm/Analysis/LoopInfo.h"
62 #include "llvm/IR/CallSite.h"
63 #include "llvm/IR/DiagnosticInfo.h"
64 #include "llvm/IR/Dominators.h"
65 #include "llvm/IR/GlobalValue.h"
66 #include "llvm/IR/IRBuilder.h"
67 #include "llvm/IR/InstIterator.h"
68 #include "llvm/IR/Instructions.h"
69 #include "llvm/IR/IntrinsicInst.h"
70 #include "llvm/IR/MDBuilder.h"
71 #include "llvm/IR/Module.h"
72 #include "llvm/Pass.h"
73 #include "llvm/ProfileData/InstrProfReader.h"
74 #include "llvm/ProfileData/ProfileCommon.h"
75 #include "llvm/Support/BranchProbability.h"
76 #include "llvm/Support/DOTGraphTraits.h"
77 #include "llvm/Support/Debug.h"
78 #include "llvm/Support/GraphWriter.h"
79 #include "llvm/Support/JamCRC.h"
80 #include "llvm/Transforms/Instrumentation.h"
81 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
84 #include <unordered_map>
90 #define DEBUG_TYPE "pgo-instrumentation"
92 STATISTIC(NumOfPGOInstrument, "Number of edges instrumented.");
93 STATISTIC(NumOfPGOSelectInsts, "Number of select instruction instrumented.");
94 STATISTIC(NumOfPGOMemIntrinsics, "Number of mem intrinsics instrumented.");
95 STATISTIC(NumOfPGOEdge, "Number of edges.");
96 STATISTIC(NumOfPGOBB, "Number of basic-blocks.");
97 STATISTIC(NumOfPGOSplit, "Number of critical edge splits.");
98 STATISTIC(NumOfPGOFunc, "Number of functions having valid profile counts.");
99 STATISTIC(NumOfPGOMismatch, "Number of functions having mismatch profile.");
100 STATISTIC(NumOfPGOMissing, "Number of functions without profile.");
101 STATISTIC(NumOfPGOICall, "Number of indirect call value instrumentations.");
103 // Command line option to specify the file to read profile from. This is
104 // mainly used for testing.
105 static cl::opt<std::string>
106 PGOTestProfileFile("pgo-test-profile-file", cl::init(""), cl::Hidden,
107 cl::value_desc("filename"),
108 cl::desc("Specify the path of profile data file. This is"
109 "mainly for test purpose."));
111 // Command line option to disable value profiling. The default is false:
112 // i.e. value profiling is enabled by default. This is for debug purpose.
113 static cl::opt<bool> DisableValueProfiling("disable-vp", cl::init(false),
115 cl::desc("Disable Value Profiling"));
117 // Command line option to set the maximum number of VP annotations to write to
118 // the metadata for a single indirect call callsite.
119 static cl::opt<unsigned> MaxNumAnnotations(
120 "icp-max-annotations", cl::init(3), cl::Hidden, cl::ZeroOrMore,
121 cl::desc("Max number of annotations for a single indirect "
124 // Command line option to set the maximum number of value annotations
125 // to write to the metadata for a single memop intrinsic.
126 static cl::opt<unsigned> MaxNumMemOPAnnotations(
127 "memop-max-annotations", cl::init(4), cl::Hidden, cl::ZeroOrMore,
128 cl::desc("Max number of preicise value annotations for a single memop"
131 // Command line option to control appending FunctionHash to the name of a COMDAT
132 // function. This is to avoid the hash mismatch caused by the preinliner.
133 static cl::opt<bool> DoComdatRenaming(
134 "do-comdat-renaming", cl::init(false), cl::Hidden,
135 cl::desc("Append function hash to the name of COMDAT function to avoid "
136 "function hash mismatch due to the preinliner"));
138 // Command line option to enable/disable the warning about missing profile
141 PGOWarnMissing("pgo-warn-missing-function", cl::init(false), cl::Hidden,
142 cl::desc("Use this option to turn on/off "
143 "warnings about missing profile data for "
146 // Command line option to enable/disable the warning about a hash mismatch in
149 NoPGOWarnMismatch("no-pgo-warn-mismatch", cl::init(false), cl::Hidden,
150 cl::desc("Use this option to turn off/on "
151 "warnings about profile cfg mismatch."));
153 // Command line option to enable/disable the warning about a hash mismatch in
154 // the profile data for Comdat functions, which often turns out to be false
155 // positive due to the pre-instrumentation inline.
157 NoPGOWarnMismatchComdat("no-pgo-warn-mismatch-comdat", cl::init(true),
159 cl::desc("The option is used to turn on/off "
160 "warnings about hash mismatch for comdat "
163 // Command line option to enable/disable select instruction instrumentation.
165 PGOInstrSelect("pgo-instr-select", cl::init(true), cl::Hidden,
166 cl::desc("Use this option to turn on/off SELECT "
167 "instruction instrumentation. "));
169 // Command line option to turn on CFG dot dump of raw profile counts
171 PGOViewRawCounts("pgo-view-raw-counts", cl::init(false), cl::Hidden,
172 cl::desc("A boolean option to show CFG dag "
173 "with raw profile counts from "
174 "profile data. See also option "
175 "-pgo-view-counts. To limit graph "
176 "display to only one function, use "
177 "filtering option -view-bfi-func-name."));
179 // Command line option to enable/disable memop intrinsic call.size profiling.
181 PGOInstrMemOP("pgo-instr-memop", cl::init(true), cl::Hidden,
182 cl::desc("Use this option to turn on/off "
183 "memory intrinsic size profiling."));
185 // Command line option to turn on CFG dot dump after profile annotation.
186 // Defined in Analysis/BlockFrequencyInfo.cpp: -pgo-view-counts
187 extern cl::opt<bool> PGOViewCounts;
189 // Command line option to specify the name of the function for CFG dump
190 // Defined in Analysis/BlockFrequencyInfo.cpp: -view-bfi-func-name=
191 extern cl::opt<std::string> ViewBlockFreqFuncName;
195 /// The select instruction visitor plays three roles specified
196 /// by the mode. In \c VM_counting mode, it simply counts the number of
197 /// select instructions. In \c VM_instrument mode, it inserts code to count
198 /// the number times TrueValue of select is taken. In \c VM_annotate mode,
199 /// it reads the profile data and annotate the select instruction with metadata.
200 enum VisitMode { VM_counting, VM_instrument, VM_annotate };
203 /// Instruction Visitor class to visit select instructions.
204 struct SelectInstVisitor : public InstVisitor<SelectInstVisitor> {
206 unsigned NSIs = 0; // Number of select instructions instrumented.
207 VisitMode Mode = VM_counting; // Visiting mode.
208 unsigned *CurCtrIdx = nullptr; // Pointer to current counter index.
209 unsigned TotalNumCtrs = 0; // Total number of counters
210 GlobalVariable *FuncNameVar = nullptr;
211 uint64_t FuncHash = 0;
212 PGOUseFunc *UseFunc = nullptr;
214 SelectInstVisitor(Function &Func) : F(Func) {}
216 void countSelects(Function &Func) {
221 // Visit the IR stream and instrument all select instructions. \p
222 // Ind is a pointer to the counter index variable; \p TotalNC
223 // is the total number of counters; \p FNV is the pointer to the
224 // PGO function name var; \p FHash is the function hash.
225 void instrumentSelects(Function &Func, unsigned *Ind, unsigned TotalNC,
226 GlobalVariable *FNV, uint64_t FHash) {
227 Mode = VM_instrument;
229 TotalNumCtrs = TotalNC;
235 // Visit the IR stream and annotate all select instructions.
236 void annotateSelects(Function &Func, PGOUseFunc *UF, unsigned *Ind) {
243 void instrumentOneSelectInst(SelectInst &SI);
244 void annotateOneSelectInst(SelectInst &SI);
245 // Visit \p SI instruction and perform tasks according to visit mode.
246 void visitSelectInst(SelectInst &SI);
247 // Return the number of select instructions. This needs be called after
249 unsigned getNumOfSelectInsts() const { return NSIs; }
252 /// Instruction Visitor class to visit memory intrinsic calls.
253 struct MemIntrinsicVisitor : public InstVisitor<MemIntrinsicVisitor> {
255 unsigned NMemIs = 0; // Number of memIntrinsics instrumented.
256 VisitMode Mode = VM_counting; // Visiting mode.
257 unsigned CurCtrId = 0; // Current counter index.
258 unsigned TotalNumCtrs = 0; // Total number of counters
259 GlobalVariable *FuncNameVar = nullptr;
260 uint64_t FuncHash = 0;
261 PGOUseFunc *UseFunc = nullptr;
262 std::vector<Instruction *> Candidates;
264 MemIntrinsicVisitor(Function &Func) : F(Func) {}
266 void countMemIntrinsics(Function &Func) {
272 void instrumentMemIntrinsics(Function &Func, unsigned TotalNC,
273 GlobalVariable *FNV, uint64_t FHash) {
274 Mode = VM_instrument;
275 TotalNumCtrs = TotalNC;
281 std::vector<Instruction *> findMemIntrinsics(Function &Func) {
288 // Visit the IR stream and annotate all mem intrinsic call instructions.
289 void instrumentOneMemIntrinsic(MemIntrinsic &MI);
290 // Visit \p MI instruction and perform tasks according to visit mode.
291 void visitMemIntrinsic(MemIntrinsic &SI);
292 unsigned getNumOfMemIntrinsics() const { return NMemIs; }
295 class PGOInstrumentationGenLegacyPass : public ModulePass {
299 PGOInstrumentationGenLegacyPass() : ModulePass(ID) {
300 initializePGOInstrumentationGenLegacyPassPass(
301 *PassRegistry::getPassRegistry());
304 StringRef getPassName() const override { return "PGOInstrumentationGenPass"; }
307 bool runOnModule(Module &M) override;
309 void getAnalysisUsage(AnalysisUsage &AU) const override {
310 AU.addRequired<BlockFrequencyInfoWrapperPass>();
314 class PGOInstrumentationUseLegacyPass : public ModulePass {
318 // Provide the profile filename as the parameter.
319 PGOInstrumentationUseLegacyPass(std::string Filename = "")
320 : ModulePass(ID), ProfileFileName(std::move(Filename)) {
321 if (!PGOTestProfileFile.empty())
322 ProfileFileName = PGOTestProfileFile;
323 initializePGOInstrumentationUseLegacyPassPass(
324 *PassRegistry::getPassRegistry());
327 StringRef getPassName() const override { return "PGOInstrumentationUsePass"; }
330 std::string ProfileFileName;
332 bool runOnModule(Module &M) override;
333 void getAnalysisUsage(AnalysisUsage &AU) const override {
334 AU.addRequired<BlockFrequencyInfoWrapperPass>();
338 } // end anonymous namespace
340 char PGOInstrumentationGenLegacyPass::ID = 0;
341 INITIALIZE_PASS_BEGIN(PGOInstrumentationGenLegacyPass, "pgo-instr-gen",
342 "PGO instrumentation.", false, false)
343 INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
344 INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
345 INITIALIZE_PASS_END(PGOInstrumentationGenLegacyPass, "pgo-instr-gen",
346 "PGO instrumentation.", false, false)
348 ModulePass *llvm::createPGOInstrumentationGenLegacyPass() {
349 return new PGOInstrumentationGenLegacyPass();
352 char PGOInstrumentationUseLegacyPass::ID = 0;
353 INITIALIZE_PASS_BEGIN(PGOInstrumentationUseLegacyPass, "pgo-instr-use",
354 "Read PGO instrumentation profile.", false, false)
355 INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
356 INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
357 INITIALIZE_PASS_END(PGOInstrumentationUseLegacyPass, "pgo-instr-use",
358 "Read PGO instrumentation profile.", false, false)
360 ModulePass *llvm::createPGOInstrumentationUseLegacyPass(StringRef Filename) {
361 return new PGOInstrumentationUseLegacyPass(Filename.str());
365 /// \brief An MST based instrumentation for PGO
367 /// Implements a Minimum Spanning Tree (MST) based instrumentation for PGO
368 /// in the function level.
370 // This class implements the CFG edges. Note the CFG can be a multi-graph.
371 // So there might be multiple edges with same SrcBB and DestBB.
372 const BasicBlock *SrcBB;
373 const BasicBlock *DestBB;
378 PGOEdge(const BasicBlock *Src, const BasicBlock *Dest, unsigned W = 1)
379 : SrcBB(Src), DestBB(Dest), Weight(W), InMST(false), Removed(false),
381 // Return the information string of an edge.
382 const std::string infoString() const {
383 return (Twine(Removed ? "-" : " ") + (InMST ? " " : "*") +
384 (IsCritical ? "c" : " ") + " W=" + Twine(Weight)).str();
388 // This class stores the auxiliary information for each BB.
394 BBInfo(unsigned IX) : Group(this), Index(IX), Rank(0) {}
396 // Return the information string of this object.
397 const std::string infoString() const {
398 return (Twine("Index=") + Twine(Index)).str();
402 // This class implements the CFG edges. Note the CFG can be a multi-graph.
403 template <class Edge, class BBInfo> class FuncPGOInstrumentation {
406 void computeCFGHash();
407 void renameComdatFunction();
408 // A map that stores the Comdat group in function F.
409 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers;
412 std::vector<std::vector<Instruction *>> ValueSites;
413 SelectInstVisitor SIVisitor;
414 MemIntrinsicVisitor MIVisitor;
415 std::string FuncName;
416 GlobalVariable *FuncNameVar;
417 // CFG hash value for this function.
418 uint64_t FunctionHash;
420 // The Minimum Spanning Tree of function CFG.
421 CFGMST<Edge, BBInfo> MST;
423 // Give an edge, find the BB that will be instrumented.
424 // Return nullptr if there is no BB to be instrumented.
425 BasicBlock *getInstrBB(Edge *E);
427 // Return the auxiliary BB information.
428 BBInfo &getBBInfo(const BasicBlock *BB) const { return MST.getBBInfo(BB); }
430 // Return the auxiliary BB information if available.
431 BBInfo *findBBInfo(const BasicBlock *BB) const { return MST.findBBInfo(BB); }
433 // Dump edges and BB information.
434 void dumpInfo(std::string Str = "") const {
435 MST.dumpEdges(dbgs(), Twine("Dump Function ") + FuncName + " Hash: " +
436 Twine(FunctionHash) + "\t" + Str);
439 FuncPGOInstrumentation(
441 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers,
442 bool CreateGlobalVar = false, BranchProbabilityInfo *BPI = nullptr,
443 BlockFrequencyInfo *BFI = nullptr)
444 : F(Func), ComdatMembers(ComdatMembers), ValueSites(IPVK_Last + 1),
445 SIVisitor(Func), MIVisitor(Func), FunctionHash(0), MST(F, BPI, BFI) {
447 // This should be done before CFG hash computation.
448 SIVisitor.countSelects(Func);
449 MIVisitor.countMemIntrinsics(Func);
450 NumOfPGOSelectInsts += SIVisitor.getNumOfSelectInsts();
451 NumOfPGOMemIntrinsics += MIVisitor.getNumOfMemIntrinsics();
452 ValueSites[IPVK_IndirectCallTarget] = findIndirectCallSites(Func);
453 ValueSites[IPVK_MemOPSize] = MIVisitor.findMemIntrinsics(Func);
455 FuncName = getPGOFuncName(F);
457 if (ComdatMembers.size())
458 renameComdatFunction();
459 DEBUG(dumpInfo("after CFGMST"));
461 NumOfPGOBB += MST.BBInfos.size();
462 for (auto &E : MST.AllEdges) {
467 NumOfPGOInstrument++;
471 FuncNameVar = createPGOFuncNameVar(F, FuncName);
474 // Return the number of profile counters needed for the function.
475 unsigned getNumCounters() {
476 unsigned NumCounters = 0;
477 for (auto &E : this->MST.AllEdges) {
478 if (!E->InMST && !E->Removed)
481 return NumCounters + SIVisitor.getNumOfSelectInsts();
485 // Compute Hash value for the CFG: the lower 32 bits are CRC32 of the index
486 // value of each BB in the CFG. The higher 32 bits record the number of edges.
487 template <class Edge, class BBInfo>
488 void FuncPGOInstrumentation<Edge, BBInfo>::computeCFGHash() {
489 std::vector<char> Indexes;
492 const TerminatorInst *TI = BB.getTerminator();
493 for (unsigned I = 0, E = TI->getNumSuccessors(); I != E; ++I) {
494 BasicBlock *Succ = TI->getSuccessor(I);
495 auto BI = findBBInfo(Succ);
498 uint32_t Index = BI->Index;
499 for (int J = 0; J < 4; J++)
500 Indexes.push_back((char)(Index >> (J * 8)));
504 FunctionHash = (uint64_t)SIVisitor.getNumOfSelectInsts() << 56 |
505 (uint64_t)ValueSites[IPVK_IndirectCallTarget].size() << 48 |
506 (uint64_t)MST.AllEdges.size() << 32 | JC.getCRC();
509 // Check if we can safely rename this Comdat function.
510 static bool canRenameComdat(
512 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers) {
513 if (!DoComdatRenaming || !canRenameComdatFunc(F, true))
516 // FIXME: Current only handle those Comdat groups that only containing one
517 // function and function aliases.
518 // (1) For a Comdat group containing multiple functions, we need to have a
519 // unique postfix based on the hashes for each function. There is a
520 // non-trivial code refactoring to do this efficiently.
521 // (2) Variables can not be renamed, so we can not rename Comdat function in a
522 // group including global vars.
523 Comdat *C = F.getComdat();
524 for (auto &&CM : make_range(ComdatMembers.equal_range(C))) {
525 if (dyn_cast<GlobalAlias>(CM.second))
527 Function *FM = dyn_cast<Function>(CM.second);
534 // Append the CFGHash to the Comdat function name.
535 template <class Edge, class BBInfo>
536 void FuncPGOInstrumentation<Edge, BBInfo>::renameComdatFunction() {
537 if (!canRenameComdat(F, ComdatMembers))
539 std::string OrigName = F.getName().str();
540 std::string NewFuncName =
541 Twine(F.getName() + "." + Twine(FunctionHash)).str();
542 F.setName(Twine(NewFuncName));
543 GlobalAlias::create(GlobalValue::WeakAnyLinkage, OrigName, &F);
544 FuncName = Twine(FuncName + "." + Twine(FunctionHash)).str();
546 Module *M = F.getParent();
547 // For AvailableExternallyLinkage functions, change the linkage to
548 // LinkOnceODR and put them into comdat. This is because after renaming, there
549 // is no backup external copy available for the function.
550 if (!F.hasComdat()) {
551 assert(F.getLinkage() == GlobalValue::AvailableExternallyLinkage);
552 NewComdat = M->getOrInsertComdat(StringRef(NewFuncName));
553 F.setLinkage(GlobalValue::LinkOnceODRLinkage);
554 F.setComdat(NewComdat);
558 // This function belongs to a single function Comdat group.
559 Comdat *OrigComdat = F.getComdat();
560 std::string NewComdatName =
561 Twine(OrigComdat->getName() + "." + Twine(FunctionHash)).str();
562 NewComdat = M->getOrInsertComdat(StringRef(NewComdatName));
563 NewComdat->setSelectionKind(OrigComdat->getSelectionKind());
565 for (auto &&CM : make_range(ComdatMembers.equal_range(OrigComdat))) {
566 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(CM.second)) {
567 // For aliases, change the name directly.
568 assert(dyn_cast<Function>(GA->getAliasee()->stripPointerCasts()) == &F);
569 std::string OrigGAName = GA->getName().str();
570 GA->setName(Twine(GA->getName() + "." + Twine(FunctionHash)));
571 GlobalAlias::create(GlobalValue::WeakAnyLinkage, OrigGAName, GA);
574 // Must be a function.
575 Function *CF = dyn_cast<Function>(CM.second);
577 CF->setComdat(NewComdat);
581 // Given a CFG E to be instrumented, find which BB to place the instrumented
582 // code. The function will split the critical edge if necessary.
583 template <class Edge, class BBInfo>
584 BasicBlock *FuncPGOInstrumentation<Edge, BBInfo>::getInstrBB(Edge *E) {
585 if (E->InMST || E->Removed)
588 BasicBlock *SrcBB = const_cast<BasicBlock *>(E->SrcBB);
589 BasicBlock *DestBB = const_cast<BasicBlock *>(E->DestBB);
590 // For a fake edge, instrument the real BB.
591 if (SrcBB == nullptr)
593 if (DestBB == nullptr)
596 // Instrument the SrcBB if it has a single successor,
597 // otherwise, the DestBB if this is not a critical edge.
598 TerminatorInst *TI = SrcBB->getTerminator();
599 if (TI->getNumSuccessors() <= 1)
604 // For a critical edge, we have to split. Instrument the newly
607 DEBUG(dbgs() << "Split critical edge: " << getBBInfo(SrcBB).Index << " --> "
608 << getBBInfo(DestBB).Index << "\n");
609 unsigned SuccNum = GetSuccessorNumber(SrcBB, DestBB);
610 BasicBlock *InstrBB = SplitCriticalEdge(TI, SuccNum);
611 assert(InstrBB && "Critical edge is not split");
617 // Visit all edge and instrument the edges not in MST, and do value profiling.
618 // Critical edges will be split.
619 static void instrumentOneFunc(
620 Function &F, Module *M, BranchProbabilityInfo *BPI, BlockFrequencyInfo *BFI,
621 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers) {
622 FuncPGOInstrumentation<PGOEdge, BBInfo> FuncInfo(F, ComdatMembers, true, BPI,
624 unsigned NumCounters = FuncInfo.getNumCounters();
627 Type *I8PtrTy = Type::getInt8PtrTy(M->getContext());
628 for (auto &E : FuncInfo.MST.AllEdges) {
629 BasicBlock *InstrBB = FuncInfo.getInstrBB(E.get());
633 IRBuilder<> Builder(InstrBB, InstrBB->getFirstInsertionPt());
634 assert(Builder.GetInsertPoint() != InstrBB->end() &&
635 "Cannot get the Instrumentation point");
637 Intrinsic::getDeclaration(M, Intrinsic::instrprof_increment),
638 {llvm::ConstantExpr::getBitCast(FuncInfo.FuncNameVar, I8PtrTy),
639 Builder.getInt64(FuncInfo.FunctionHash), Builder.getInt32(NumCounters),
640 Builder.getInt32(I++)});
643 // Now instrument select instructions:
644 FuncInfo.SIVisitor.instrumentSelects(F, &I, NumCounters, FuncInfo.FuncNameVar,
645 FuncInfo.FunctionHash);
646 assert(I == NumCounters);
648 if (DisableValueProfiling)
651 unsigned NumIndirectCallSites = 0;
652 for (auto &I : FuncInfo.ValueSites[IPVK_IndirectCallTarget]) {
654 Value *Callee = CS.getCalledValue();
655 DEBUG(dbgs() << "Instrument one indirect call: CallSite Index = "
656 << NumIndirectCallSites << "\n");
657 IRBuilder<> Builder(I);
658 assert(Builder.GetInsertPoint() != I->getParent()->end() &&
659 "Cannot get the Instrumentation point");
661 Intrinsic::getDeclaration(M, Intrinsic::instrprof_value_profile),
662 {llvm::ConstantExpr::getBitCast(FuncInfo.FuncNameVar, I8PtrTy),
663 Builder.getInt64(FuncInfo.FunctionHash),
664 Builder.CreatePtrToInt(Callee, Builder.getInt64Ty()),
665 Builder.getInt32(IPVK_IndirectCallTarget),
666 Builder.getInt32(NumIndirectCallSites++)});
668 NumOfPGOICall += NumIndirectCallSites;
670 // Now instrument memop intrinsic calls.
671 FuncInfo.MIVisitor.instrumentMemIntrinsics(
672 F, NumCounters, FuncInfo.FuncNameVar, FuncInfo.FunctionHash);
675 // This class represents a CFG edge in profile use compilation.
676 struct PGOUseEdge : public PGOEdge {
679 PGOUseEdge(const BasicBlock *Src, const BasicBlock *Dest, unsigned W = 1)
680 : PGOEdge(Src, Dest, W), CountValid(false), CountValue(0) {}
682 // Set edge count value
683 void setEdgeCount(uint64_t Value) {
688 // Return the information string for this object.
689 const std::string infoString() const {
691 return PGOEdge::infoString();
692 return (Twine(PGOEdge::infoString()) + " Count=" + Twine(CountValue))
697 typedef SmallVector<PGOUseEdge *, 2> DirectEdges;
699 // This class stores the auxiliary information for each BB.
700 struct UseBBInfo : public BBInfo {
703 int32_t UnknownCountInEdge;
704 int32_t UnknownCountOutEdge;
706 DirectEdges OutEdges;
707 UseBBInfo(unsigned IX)
708 : BBInfo(IX), CountValue(0), CountValid(false), UnknownCountInEdge(0),
709 UnknownCountOutEdge(0) {}
710 UseBBInfo(unsigned IX, uint64_t C)
711 : BBInfo(IX), CountValue(C), CountValid(true), UnknownCountInEdge(0),
712 UnknownCountOutEdge(0) {}
714 // Set the profile count value for this BB.
715 void setBBInfoCount(uint64_t Value) {
720 // Return the information string of this object.
721 const std::string infoString() const {
723 return BBInfo::infoString();
724 return (Twine(BBInfo::infoString()) + " Count=" + Twine(CountValue)).str();
728 // Sum up the count values for all the edges.
729 static uint64_t sumEdgeCount(const ArrayRef<PGOUseEdge *> Edges) {
731 for (auto &E : Edges) {
734 Total += E->CountValue;
741 PGOUseFunc(Function &Func, Module *Modu,
742 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers,
743 BranchProbabilityInfo *BPI = nullptr,
744 BlockFrequencyInfo *BFI = nullptr)
745 : F(Func), M(Modu), FuncInfo(Func, ComdatMembers, false, BPI, BFI),
746 CountPosition(0), ProfileCountSize(0), FreqAttr(FFA_Normal) {}
748 // Read counts for the instrumented BB from profile.
749 bool readCounters(IndexedInstrProfReader *PGOReader);
751 // Populate the counts for all BBs.
752 void populateCounters();
754 // Set the branch weights based on the count values.
755 void setBranchWeights();
757 // Annotate the value profile call sites all all value kind.
758 void annotateValueSites();
760 // Annotate the value profile call sites for one value kind.
761 void annotateValueSites(uint32_t Kind);
763 // The hotness of the function from the profile count.
764 enum FuncFreqAttr { FFA_Normal, FFA_Cold, FFA_Hot };
766 // Return the function hotness from the profile.
767 FuncFreqAttr getFuncFreqAttr() const { return FreqAttr; }
769 // Return the function hash.
770 uint64_t getFuncHash() const { return FuncInfo.FunctionHash; }
771 // Return the profile record for this function;
772 InstrProfRecord &getProfileRecord() { return ProfileRecord; }
774 // Return the auxiliary BB information.
775 UseBBInfo &getBBInfo(const BasicBlock *BB) const {
776 return FuncInfo.getBBInfo(BB);
779 // Return the auxiliary BB information if available.
780 UseBBInfo *findBBInfo(const BasicBlock *BB) const {
781 return FuncInfo.findBBInfo(BB);
784 Function &getFunc() const { return F; }
789 // This member stores the shared information with class PGOGenFunc.
790 FuncPGOInstrumentation<PGOUseEdge, UseBBInfo> FuncInfo;
792 // The maximum count value in the profile. This is only used in PGO use
794 uint64_t ProgramMaxCount;
796 // Position of counter that remains to be read.
797 uint32_t CountPosition;
799 // Total size of the profile count for this function.
800 uint32_t ProfileCountSize;
802 // ProfileRecord for this function.
803 InstrProfRecord ProfileRecord;
805 // Function hotness info derived from profile.
806 FuncFreqAttr FreqAttr;
808 // Find the Instrumented BB and set the value.
809 void setInstrumentedCounts(const std::vector<uint64_t> &CountFromProfile);
811 // Set the edge counter value for the unknown edge -- there should be only
813 void setEdgeCount(DirectEdges &Edges, uint64_t Value);
815 // Return FuncName string;
816 const std::string getFuncName() const { return FuncInfo.FuncName; }
818 // Set the hot/cold inline hints based on the count values.
819 // FIXME: This function should be removed once the functionality in
820 // the inliner is implemented.
821 void markFunctionAttributes(uint64_t EntryCount, uint64_t MaxCount) {
822 if (ProgramMaxCount == 0)
824 // Threshold of the hot functions.
825 const BranchProbability HotFunctionThreshold(1, 100);
826 // Threshold of the cold functions.
827 const BranchProbability ColdFunctionThreshold(2, 10000);
828 if (EntryCount >= HotFunctionThreshold.scale(ProgramMaxCount))
830 else if (MaxCount <= ColdFunctionThreshold.scale(ProgramMaxCount))
835 // Visit all the edges and assign the count value for the instrumented
837 void PGOUseFunc::setInstrumentedCounts(
838 const std::vector<uint64_t> &CountFromProfile) {
840 assert(FuncInfo.getNumCounters() == CountFromProfile.size());
841 // Use a worklist as we will update the vector during the iteration.
842 std::vector<PGOUseEdge *> WorkList;
843 for (auto &E : FuncInfo.MST.AllEdges)
844 WorkList.push_back(E.get());
847 for (auto &E : WorkList) {
848 BasicBlock *InstrBB = FuncInfo.getInstrBB(E);
851 uint64_t CountValue = CountFromProfile[I++];
853 getBBInfo(InstrBB).setBBInfoCount(CountValue);
854 E->setEdgeCount(CountValue);
858 // Need to add two new edges.
859 BasicBlock *SrcBB = const_cast<BasicBlock *>(E->SrcBB);
860 BasicBlock *DestBB = const_cast<BasicBlock *>(E->DestBB);
861 // Add new edge of SrcBB->InstrBB.
862 PGOUseEdge &NewEdge = FuncInfo.MST.addEdge(SrcBB, InstrBB, 0);
863 NewEdge.setEdgeCount(CountValue);
864 // Add new edge of InstrBB->DestBB.
865 PGOUseEdge &NewEdge1 = FuncInfo.MST.addEdge(InstrBB, DestBB, 0);
866 NewEdge1.setEdgeCount(CountValue);
867 NewEdge1.InMST = true;
868 getBBInfo(InstrBB).setBBInfoCount(CountValue);
870 ProfileCountSize = CountFromProfile.size();
874 // Set the count value for the unknown edge. There should be one and only one
875 // unknown edge in Edges vector.
876 void PGOUseFunc::setEdgeCount(DirectEdges &Edges, uint64_t Value) {
877 for (auto &E : Edges) {
880 E->setEdgeCount(Value);
882 getBBInfo(E->SrcBB).UnknownCountOutEdge--;
883 getBBInfo(E->DestBB).UnknownCountInEdge--;
886 llvm_unreachable("Cannot find the unknown count edge");
889 // Read the profile from ProfileFileName and assign the value to the
890 // instrumented BB and the edges. This function also updates ProgramMaxCount.
891 // Return true if the profile are successfully read, and false on errors.
892 bool PGOUseFunc::readCounters(IndexedInstrProfReader *PGOReader) {
893 auto &Ctx = M->getContext();
894 Expected<InstrProfRecord> Result =
895 PGOReader->getInstrProfRecord(FuncInfo.FuncName, FuncInfo.FunctionHash);
896 if (Error E = Result.takeError()) {
897 handleAllErrors(std::move(E), [&](const InstrProfError &IPE) {
898 auto Err = IPE.get();
899 bool SkipWarning = false;
900 if (Err == instrprof_error::unknown_function) {
902 SkipWarning = !PGOWarnMissing;
903 } else if (Err == instrprof_error::hash_mismatch ||
904 Err == instrprof_error::malformed) {
908 (NoPGOWarnMismatchComdat &&
910 F.getLinkage() == GlobalValue::AvailableExternallyLinkage));
916 std::string Msg = IPE.message() + std::string(" ") + F.getName().str();
918 DiagnosticInfoPGOProfile(M->getName().data(), Msg, DS_Warning));
922 ProfileRecord = std::move(Result.get());
923 std::vector<uint64_t> &CountFromProfile = ProfileRecord.Counts;
926 DEBUG(dbgs() << CountFromProfile.size() << " counts\n");
927 uint64_t ValueSum = 0;
928 for (unsigned I = 0, S = CountFromProfile.size(); I < S; I++) {
929 DEBUG(dbgs() << " " << I << ": " << CountFromProfile[I] << "\n");
930 ValueSum += CountFromProfile[I];
933 DEBUG(dbgs() << "SUM = " << ValueSum << "\n");
935 getBBInfo(nullptr).UnknownCountOutEdge = 2;
936 getBBInfo(nullptr).UnknownCountInEdge = 2;
938 setInstrumentedCounts(CountFromProfile);
939 ProgramMaxCount = PGOReader->getMaximumFunctionCount();
943 // Populate the counters from instrumented BBs to all BBs.
944 // In the end of this operation, all BBs should have a valid count value.
945 void PGOUseFunc::populateCounters() {
946 // First set up Count variable for all BBs.
947 for (auto &E : FuncInfo.MST.AllEdges) {
951 const BasicBlock *SrcBB = E->SrcBB;
952 const BasicBlock *DestBB = E->DestBB;
953 UseBBInfo &SrcInfo = getBBInfo(SrcBB);
954 UseBBInfo &DestInfo = getBBInfo(DestBB);
955 SrcInfo.OutEdges.push_back(E.get());
956 DestInfo.InEdges.push_back(E.get());
957 SrcInfo.UnknownCountOutEdge++;
958 DestInfo.UnknownCountInEdge++;
962 DestInfo.UnknownCountInEdge--;
963 SrcInfo.UnknownCountOutEdge--;
967 unsigned NumPasses = 0;
972 // For efficient traversal, it's better to start from the end as most
973 // of the instrumented edges are at the end.
974 for (auto &BB : reverse(F)) {
975 UseBBInfo *Count = findBBInfo(&BB);
976 if (Count == nullptr)
978 if (!Count->CountValid) {
979 if (Count->UnknownCountOutEdge == 0) {
980 Count->CountValue = sumEdgeCount(Count->OutEdges);
981 Count->CountValid = true;
983 } else if (Count->UnknownCountInEdge == 0) {
984 Count->CountValue = sumEdgeCount(Count->InEdges);
985 Count->CountValid = true;
989 if (Count->CountValid) {
990 if (Count->UnknownCountOutEdge == 1) {
992 uint64_t OutSum = sumEdgeCount(Count->OutEdges);
993 // If the one of the successor block can early terminate (no-return),
994 // we can end up with situation where out edge sum count is larger as
995 // the source BB's count is collected by a post-dominated block.
996 if (Count->CountValue > OutSum)
997 Total = Count->CountValue - OutSum;
998 setEdgeCount(Count->OutEdges, Total);
1001 if (Count->UnknownCountInEdge == 1) {
1003 uint64_t InSum = sumEdgeCount(Count->InEdges);
1004 if (Count->CountValue > InSum)
1005 Total = Count->CountValue - InSum;
1006 setEdgeCount(Count->InEdges, Total);
1013 DEBUG(dbgs() << "Populate counts in " << NumPasses << " passes.\n");
1015 // Assert every BB has a valid counter.
1016 for (auto &BB : F) {
1017 auto BI = findBBInfo(&BB);
1020 assert(BI->CountValid && "BB count is not valid");
1023 uint64_t FuncEntryCount = getBBInfo(&*F.begin()).CountValue;
1024 F.setEntryCount(FuncEntryCount);
1025 uint64_t FuncMaxCount = FuncEntryCount;
1026 for (auto &BB : F) {
1027 auto BI = findBBInfo(&BB);
1030 FuncMaxCount = std::max(FuncMaxCount, BI->CountValue);
1032 markFunctionAttributes(FuncEntryCount, FuncMaxCount);
1034 // Now annotate select instructions
1035 FuncInfo.SIVisitor.annotateSelects(F, this, &CountPosition);
1036 assert(CountPosition == ProfileCountSize);
1038 DEBUG(FuncInfo.dumpInfo("after reading profile."));
1041 // Assign the scaled count values to the BB with multiple out edges.
1042 void PGOUseFunc::setBranchWeights() {
1043 // Generate MD_prof metadata for every branch instruction.
1044 DEBUG(dbgs() << "\nSetting branch weights.\n");
1045 for (auto &BB : F) {
1046 TerminatorInst *TI = BB.getTerminator();
1047 if (TI->getNumSuccessors() < 2)
1049 if (!isa<BranchInst>(TI) && !isa<SwitchInst>(TI))
1051 if (getBBInfo(&BB).CountValue == 0)
1054 // We have a non-zero Branch BB.
1055 const UseBBInfo &BBCountInfo = getBBInfo(&BB);
1056 unsigned Size = BBCountInfo.OutEdges.size();
1057 SmallVector<uint64_t, 2> EdgeCounts(Size, 0);
1058 uint64_t MaxCount = 0;
1059 for (unsigned s = 0; s < Size; s++) {
1060 const PGOUseEdge *E = BBCountInfo.OutEdges[s];
1061 const BasicBlock *SrcBB = E->SrcBB;
1062 const BasicBlock *DestBB = E->DestBB;
1063 if (DestBB == nullptr)
1065 unsigned SuccNum = GetSuccessorNumber(SrcBB, DestBB);
1066 uint64_t EdgeCount = E->CountValue;
1067 if (EdgeCount > MaxCount)
1068 MaxCount = EdgeCount;
1069 EdgeCounts[SuccNum] = EdgeCount;
1071 setProfMetadata(M, TI, EdgeCounts, MaxCount);
1075 void SelectInstVisitor::instrumentOneSelectInst(SelectInst &SI) {
1076 Module *M = F.getParent();
1077 IRBuilder<> Builder(&SI);
1078 Type *Int64Ty = Builder.getInt64Ty();
1079 Type *I8PtrTy = Builder.getInt8PtrTy();
1080 auto *Step = Builder.CreateZExt(SI.getCondition(), Int64Ty);
1082 Intrinsic::getDeclaration(M, Intrinsic::instrprof_increment_step),
1083 {llvm::ConstantExpr::getBitCast(FuncNameVar, I8PtrTy),
1084 Builder.getInt64(FuncHash), Builder.getInt32(TotalNumCtrs),
1085 Builder.getInt32(*CurCtrIdx), Step});
1089 void SelectInstVisitor::annotateOneSelectInst(SelectInst &SI) {
1090 std::vector<uint64_t> &CountFromProfile = UseFunc->getProfileRecord().Counts;
1091 assert(*CurCtrIdx < CountFromProfile.size() &&
1092 "Out of bound access of counters");
1093 uint64_t SCounts[2];
1094 SCounts[0] = CountFromProfile[*CurCtrIdx]; // True count
1096 uint64_t TotalCount = 0;
1097 auto BI = UseFunc->findBBInfo(SI.getParent());
1099 TotalCount = BI->CountValue;
1101 SCounts[1] = (TotalCount > SCounts[0] ? TotalCount - SCounts[0] : 0);
1102 uint64_t MaxCount = std::max(SCounts[0], SCounts[1]);
1104 setProfMetadata(F.getParent(), &SI, SCounts, MaxCount);
1107 void SelectInstVisitor::visitSelectInst(SelectInst &SI) {
1108 if (!PGOInstrSelect)
1110 // FIXME: do not handle this yet.
1111 if (SI.getCondition()->getType()->isVectorTy())
1119 instrumentOneSelectInst(SI);
1122 annotateOneSelectInst(SI);
1126 llvm_unreachable("Unknown visiting mode");
1129 void MemIntrinsicVisitor::instrumentOneMemIntrinsic(MemIntrinsic &MI) {
1130 Module *M = F.getParent();
1131 IRBuilder<> Builder(&MI);
1132 Type *Int64Ty = Builder.getInt64Ty();
1133 Type *I8PtrTy = Builder.getInt8PtrTy();
1134 Value *Length = MI.getLength();
1135 assert(!dyn_cast<ConstantInt>(Length));
1137 Intrinsic::getDeclaration(M, Intrinsic::instrprof_value_profile),
1138 {llvm::ConstantExpr::getBitCast(FuncNameVar, I8PtrTy),
1139 Builder.getInt64(FuncHash), Builder.CreatePtrToInt(Length, Int64Ty),
1140 Builder.getInt32(IPVK_MemOPSize), Builder.getInt32(CurCtrId)});
1144 void MemIntrinsicVisitor::visitMemIntrinsic(MemIntrinsic &MI) {
1147 Value *Length = MI.getLength();
1148 // Not instrument constant length calls.
1149 if (dyn_cast<ConstantInt>(Length))
1157 instrumentOneMemIntrinsic(MI);
1160 Candidates.push_back(&MI);
1163 llvm_unreachable("Unknown visiting mode");
1166 // Traverse all valuesites and annotate the instructions for all value kind.
1167 void PGOUseFunc::annotateValueSites() {
1168 if (DisableValueProfiling)
1171 // Create the PGOFuncName meta data.
1172 createPGOFuncNameMetadata(F, FuncInfo.FuncName);
1174 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
1175 annotateValueSites(Kind);
1178 // Annotate the instructions for a specific value kind.
1179 void PGOUseFunc::annotateValueSites(uint32_t Kind) {
1180 unsigned ValueSiteIndex = 0;
1181 auto &ValueSites = FuncInfo.ValueSites[Kind];
1182 unsigned NumValueSites = ProfileRecord.getNumValueSites(Kind);
1183 if (NumValueSites != ValueSites.size()) {
1184 auto &Ctx = M->getContext();
1185 Ctx.diagnose(DiagnosticInfoPGOProfile(
1186 M->getName().data(),
1187 Twine("Inconsistent number of value sites for kind = ") + Twine(Kind) +
1188 " in " + F.getName().str(),
1193 for (auto &I : ValueSites) {
1194 DEBUG(dbgs() << "Read one value site profile (kind = " << Kind
1195 << "): Index = " << ValueSiteIndex << " out of "
1196 << NumValueSites << "\n");
1197 annotateValueSite(*M, *I, ProfileRecord,
1198 static_cast<InstrProfValueKind>(Kind), ValueSiteIndex,
1199 Kind == IPVK_MemOPSize ? MaxNumMemOPAnnotations
1200 : MaxNumAnnotations);
1204 } // end anonymous namespace
1206 // Create a COMDAT variable INSTR_PROF_RAW_VERSION_VAR to make the runtime
1207 // aware this is an ir_level profile so it can set the version flag.
1208 static void createIRLevelProfileFlagVariable(Module &M) {
1209 Type *IntTy64 = Type::getInt64Ty(M.getContext());
1210 uint64_t ProfileVersion = (INSTR_PROF_RAW_VERSION | VARIANT_MASK_IR_PROF);
1211 auto IRLevelVersionVariable = new GlobalVariable(
1212 M, IntTy64, true, GlobalVariable::ExternalLinkage,
1213 Constant::getIntegerValue(IntTy64, APInt(64, ProfileVersion)),
1214 INSTR_PROF_QUOTE(INSTR_PROF_RAW_VERSION_VAR));
1215 IRLevelVersionVariable->setVisibility(GlobalValue::DefaultVisibility);
1216 Triple TT(M.getTargetTriple());
1217 if (!TT.supportsCOMDAT())
1218 IRLevelVersionVariable->setLinkage(GlobalValue::WeakAnyLinkage);
1220 IRLevelVersionVariable->setComdat(M.getOrInsertComdat(
1221 StringRef(INSTR_PROF_QUOTE(INSTR_PROF_RAW_VERSION_VAR))));
1224 // Collect the set of members for each Comdat in module M and store
1225 // in ComdatMembers.
1226 static void collectComdatMembers(
1228 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers) {
1229 if (!DoComdatRenaming)
1231 for (Function &F : M)
1232 if (Comdat *C = F.getComdat())
1233 ComdatMembers.insert(std::make_pair(C, &F));
1234 for (GlobalVariable &GV : M.globals())
1235 if (Comdat *C = GV.getComdat())
1236 ComdatMembers.insert(std::make_pair(C, &GV));
1237 for (GlobalAlias &GA : M.aliases())
1238 if (Comdat *C = GA.getComdat())
1239 ComdatMembers.insert(std::make_pair(C, &GA));
1242 static bool InstrumentAllFunctions(
1243 Module &M, function_ref<BranchProbabilityInfo *(Function &)> LookupBPI,
1244 function_ref<BlockFrequencyInfo *(Function &)> LookupBFI) {
1245 createIRLevelProfileFlagVariable(M);
1246 std::unordered_multimap<Comdat *, GlobalValue *> ComdatMembers;
1247 collectComdatMembers(M, ComdatMembers);
1250 if (F.isDeclaration())
1252 auto *BPI = LookupBPI(F);
1253 auto *BFI = LookupBFI(F);
1254 instrumentOneFunc(F, &M, BPI, BFI, ComdatMembers);
1259 bool PGOInstrumentationGenLegacyPass::runOnModule(Module &M) {
1263 auto LookupBPI = [this](Function &F) {
1264 return &this->getAnalysis<BranchProbabilityInfoWrapperPass>(F).getBPI();
1266 auto LookupBFI = [this](Function &F) {
1267 return &this->getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI();
1269 return InstrumentAllFunctions(M, LookupBPI, LookupBFI);
1272 PreservedAnalyses PGOInstrumentationGen::run(Module &M,
1273 ModuleAnalysisManager &AM) {
1275 auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
1276 auto LookupBPI = [&FAM](Function &F) {
1277 return &FAM.getResult<BranchProbabilityAnalysis>(F);
1280 auto LookupBFI = [&FAM](Function &F) {
1281 return &FAM.getResult<BlockFrequencyAnalysis>(F);
1284 if (!InstrumentAllFunctions(M, LookupBPI, LookupBFI))
1285 return PreservedAnalyses::all();
1287 return PreservedAnalyses::none();
1290 static bool annotateAllFunctions(
1291 Module &M, StringRef ProfileFileName,
1292 function_ref<BranchProbabilityInfo *(Function &)> LookupBPI,
1293 function_ref<BlockFrequencyInfo *(Function &)> LookupBFI) {
1294 DEBUG(dbgs() << "Read in profile counters: ");
1295 auto &Ctx = M.getContext();
1296 // Read the counter array from file.
1297 auto ReaderOrErr = IndexedInstrProfReader::create(ProfileFileName);
1298 if (Error E = ReaderOrErr.takeError()) {
1299 handleAllErrors(std::move(E), [&](const ErrorInfoBase &EI) {
1301 DiagnosticInfoPGOProfile(ProfileFileName.data(), EI.message()));
1306 std::unique_ptr<IndexedInstrProfReader> PGOReader =
1307 std::move(ReaderOrErr.get());
1309 Ctx.diagnose(DiagnosticInfoPGOProfile(ProfileFileName.data(),
1310 StringRef("Cannot get PGOReader")));
1313 // TODO: might need to change the warning once the clang option is finalized.
1314 if (!PGOReader->isIRLevelProfile()) {
1315 Ctx.diagnose(DiagnosticInfoPGOProfile(
1316 ProfileFileName.data(), "Not an IR level instrumentation profile"));
1320 std::unordered_multimap<Comdat *, GlobalValue *> ComdatMembers;
1321 collectComdatMembers(M, ComdatMembers);
1322 std::vector<Function *> HotFunctions;
1323 std::vector<Function *> ColdFunctions;
1325 if (F.isDeclaration())
1327 auto *BPI = LookupBPI(F);
1328 auto *BFI = LookupBFI(F);
1329 PGOUseFunc Func(F, &M, ComdatMembers, BPI, BFI);
1330 if (!Func.readCounters(PGOReader.get()))
1332 Func.populateCounters();
1333 Func.setBranchWeights();
1334 Func.annotateValueSites();
1335 PGOUseFunc::FuncFreqAttr FreqAttr = Func.getFuncFreqAttr();
1336 if (FreqAttr == PGOUseFunc::FFA_Cold)
1337 ColdFunctions.push_back(&F);
1338 else if (FreqAttr == PGOUseFunc::FFA_Hot)
1339 HotFunctions.push_back(&F);
1340 if (PGOViewCounts && (ViewBlockFreqFuncName.empty() ||
1341 F.getName().equals(ViewBlockFreqFuncName))) {
1342 LoopInfo LI{DominatorTree(F)};
1343 std::unique_ptr<BranchProbabilityInfo> NewBPI =
1344 llvm::make_unique<BranchProbabilityInfo>(F, LI);
1345 std::unique_ptr<BlockFrequencyInfo> NewBFI =
1346 llvm::make_unique<BlockFrequencyInfo>(F, *NewBPI, LI);
1350 if (PGOViewRawCounts && (ViewBlockFreqFuncName.empty() ||
1351 F.getName().equals(ViewBlockFreqFuncName))) {
1352 if (ViewBlockFreqFuncName.empty())
1353 WriteGraph(&Func, Twine("PGORawCounts_") + Func.getFunc().getName());
1355 ViewGraph(&Func, Twine("PGORawCounts_") + Func.getFunc().getName());
1358 M.setProfileSummary(PGOReader->getSummary().getMD(M.getContext()));
1359 // Set function hotness attribute from the profile.
1360 // We have to apply these attributes at the end because their presence
1361 // can affect the BranchProbabilityInfo of any callers, resulting in an
1362 // inconsistent MST between prof-gen and prof-use.
1363 for (auto &F : HotFunctions) {
1364 F->addFnAttr(llvm::Attribute::InlineHint);
1365 DEBUG(dbgs() << "Set inline attribute to function: " << F->getName()
1368 for (auto &F : ColdFunctions) {
1369 F->addFnAttr(llvm::Attribute::Cold);
1370 DEBUG(dbgs() << "Set cold attribute to function: " << F->getName() << "\n");
1375 PGOInstrumentationUse::PGOInstrumentationUse(std::string Filename)
1376 : ProfileFileName(std::move(Filename)) {
1377 if (!PGOTestProfileFile.empty())
1378 ProfileFileName = PGOTestProfileFile;
1381 PreservedAnalyses PGOInstrumentationUse::run(Module &M,
1382 ModuleAnalysisManager &AM) {
1384 auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
1385 auto LookupBPI = [&FAM](Function &F) {
1386 return &FAM.getResult<BranchProbabilityAnalysis>(F);
1389 auto LookupBFI = [&FAM](Function &F) {
1390 return &FAM.getResult<BlockFrequencyAnalysis>(F);
1393 if (!annotateAllFunctions(M, ProfileFileName, LookupBPI, LookupBFI))
1394 return PreservedAnalyses::all();
1396 return PreservedAnalyses::none();
1399 bool PGOInstrumentationUseLegacyPass::runOnModule(Module &M) {
1403 auto LookupBPI = [this](Function &F) {
1404 return &this->getAnalysis<BranchProbabilityInfoWrapperPass>(F).getBPI();
1406 auto LookupBFI = [this](Function &F) {
1407 return &this->getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI();
1410 return annotateAllFunctions(M, ProfileFileName, LookupBPI, LookupBFI);
1414 void setProfMetadata(Module *M, Instruction *TI, ArrayRef<uint64_t> EdgeCounts,
1415 uint64_t MaxCount) {
1416 MDBuilder MDB(M->getContext());
1417 assert(MaxCount > 0 && "Bad max count");
1418 uint64_t Scale = calculateCountScale(MaxCount);
1419 SmallVector<unsigned, 4> Weights;
1420 for (const auto &ECI : EdgeCounts)
1421 Weights.push_back(scaleBranchCount(ECI, Scale));
1423 DEBUG(dbgs() << "Weight is: ";
1424 for (const auto &W : Weights) { dbgs() << W << " "; }
1426 TI->setMetadata(llvm::LLVMContext::MD_prof, MDB.createBranchWeights(Weights));
1429 template <> struct GraphTraits<PGOUseFunc *> {
1430 typedef const BasicBlock *NodeRef;
1431 typedef succ_const_iterator ChildIteratorType;
1432 typedef pointer_iterator<Function::const_iterator> nodes_iterator;
1434 static NodeRef getEntryNode(const PGOUseFunc *G) {
1435 return &G->getFunc().front();
1437 static ChildIteratorType child_begin(const NodeRef N) {
1438 return succ_begin(N);
1440 static ChildIteratorType child_end(const NodeRef N) { return succ_end(N); }
1441 static nodes_iterator nodes_begin(const PGOUseFunc *G) {
1442 return nodes_iterator(G->getFunc().begin());
1444 static nodes_iterator nodes_end(const PGOUseFunc *G) {
1445 return nodes_iterator(G->getFunc().end());
1449 static std::string getSimpleNodeName(const BasicBlock *Node) {
1450 if (!Node->getName().empty())
1451 return Node->getName();
1453 std::string SimpleNodeName;
1454 raw_string_ostream OS(SimpleNodeName);
1455 Node->printAsOperand(OS, false);
1459 template <> struct DOTGraphTraits<PGOUseFunc *> : DefaultDOTGraphTraits {
1460 explicit DOTGraphTraits(bool isSimple = false)
1461 : DefaultDOTGraphTraits(isSimple) {}
1463 static std::string getGraphName(const PGOUseFunc *G) {
1464 return G->getFunc().getName();
1467 std::string getNodeLabel(const BasicBlock *Node, const PGOUseFunc *Graph) {
1469 raw_string_ostream OS(Result);
1471 OS << getSimpleNodeName(Node) << ":\\l";
1472 UseBBInfo *BI = Graph->findBBInfo(Node);
1474 if (BI && BI->CountValid)
1475 OS << BI->CountValue << "\\l";
1479 if (!PGOInstrSelect)
1482 for (auto BI = Node->begin(); BI != Node->end(); ++BI) {
1484 if (!isa<SelectInst>(I))
1486 // Display scaled counts for SELECT instruction:
1487 OS << "SELECT : { T = ";
1489 bool HasProf = I->extractProfMetadata(TC, FC);
1491 OS << "Unknown, F = Unknown }\\l";
1493 OS << TC << ", F = " << FC << " }\\l";