1 //===- PGOInstrumentation.cpp - MST-based PGO Instrumentation -------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file implements PGO instrumentation using a minimum spanning tree based
10 // on the following paper:
11 // [1] Donald E. Knuth, Francis R. Stevenson. Optimal measurement of points
12 // for program frequency counts. BIT Numerical Mathematics 1973, Volume 13,
13 // Issue 3, pp 313-322
14 // The idea of the algorithm based on the fact that for each node (except for
15 // the entry and exit), the sum of incoming edge counts equals the sum of
16 // outgoing edge counts. The count of edge on spanning tree can be derived from
17 // those edges not on the spanning tree. Knuth proves this method instruments
18 // the minimum number of edges.
20 // The minimal spanning tree here is actually a maximum weight tree -- on-tree
21 // edges have higher frequencies (more likely to execute). The idea is to
22 // instrument those less frequently executed edges to reduce the runtime
23 // overhead of instrumented binaries.
25 // This file contains two passes:
26 // (1) Pass PGOInstrumentationGen which instruments the IR to generate edge
27 // count profile, and generates the instrumentation for indirect call
29 // (2) Pass PGOInstrumentationUse which reads the edge count profile and
30 // annotates the branch weights. It also reads the indirect call value
31 // profiling records and annotate the indirect call instructions.
33 // To get the precise counter information, These two passes need to invoke at
34 // the same compilation point (so they see the same IR). For pass
35 // PGOInstrumentationGen, the real work is done in instrumentOneFunc(). For
36 // pass PGOInstrumentationUse, the real work in done in class PGOUseFunc and
37 // the profile is opened in module level and passed to each PGOUseFunc instance.
38 // The shared code for PGOInstrumentationGen and PGOInstrumentationUse is put
39 // in class FuncPGOInstrumentation.
41 // Class PGOEdge represents a CFG edge and some auxiliary information. Class
42 // BBInfo contains auxiliary information for each BB. These two classes are used
43 // in pass PGOInstrumentationGen. Class PGOUseEdge and UseBBInfo are the derived
44 // class of PGOEdge and BBInfo, respectively. They contains extra data structure
45 // used in populating profile counters.
46 // The MST implementation is in Class CFGMST (CFGMST.h).
48 //===----------------------------------------------------------------------===//
51 #include "llvm/ADT/APInt.h"
52 #include "llvm/ADT/ArrayRef.h"
53 #include "llvm/ADT/STLExtras.h"
54 #include "llvm/ADT/SmallVector.h"
55 #include "llvm/ADT/Statistic.h"
56 #include "llvm/ADT/StringRef.h"
57 #include "llvm/ADT/Triple.h"
58 #include "llvm/ADT/Twine.h"
59 #include "llvm/ADT/iterator.h"
60 #include "llvm/ADT/iterator_range.h"
61 #include "llvm/Analysis/BlockFrequencyInfo.h"
62 #include "llvm/Analysis/BranchProbabilityInfo.h"
63 #include "llvm/Analysis/CFG.h"
64 #include "llvm/Analysis/IndirectCallVisitor.h"
65 #include "llvm/Analysis/LoopInfo.h"
66 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
67 #include "llvm/Analysis/ProfileSummaryInfo.h"
68 #include "llvm/IR/Attributes.h"
69 #include "llvm/IR/BasicBlock.h"
70 #include "llvm/IR/CFG.h"
71 #include "llvm/IR/CallSite.h"
72 #include "llvm/IR/Comdat.h"
73 #include "llvm/IR/Constant.h"
74 #include "llvm/IR/Constants.h"
75 #include "llvm/IR/DiagnosticInfo.h"
76 #include "llvm/IR/Dominators.h"
77 #include "llvm/IR/Function.h"
78 #include "llvm/IR/GlobalAlias.h"
79 #include "llvm/IR/GlobalValue.h"
80 #include "llvm/IR/GlobalVariable.h"
81 #include "llvm/IR/IRBuilder.h"
82 #include "llvm/IR/InstVisitor.h"
83 #include "llvm/IR/InstrTypes.h"
84 #include "llvm/IR/Instruction.h"
85 #include "llvm/IR/Instructions.h"
86 #include "llvm/IR/IntrinsicInst.h"
87 #include "llvm/IR/Intrinsics.h"
88 #include "llvm/IR/LLVMContext.h"
89 #include "llvm/IR/MDBuilder.h"
90 #include "llvm/IR/Module.h"
91 #include "llvm/IR/PassManager.h"
92 #include "llvm/IR/ProfileSummary.h"
93 #include "llvm/IR/Type.h"
94 #include "llvm/IR/Value.h"
95 #include "llvm/Pass.h"
96 #include "llvm/ProfileData/InstrProf.h"
97 #include "llvm/ProfileData/InstrProfReader.h"
98 #include "llvm/Support/BranchProbability.h"
99 #include "llvm/Support/Casting.h"
100 #include "llvm/Support/CommandLine.h"
101 #include "llvm/Support/DOTGraphTraits.h"
102 #include "llvm/Support/Debug.h"
103 #include "llvm/Support/Error.h"
104 #include "llvm/Support/ErrorHandling.h"
105 #include "llvm/Support/GraphWriter.h"
106 #include "llvm/Support/JamCRC.h"
107 #include "llvm/Support/raw_ostream.h"
108 #include "llvm/Transforms/Instrumentation.h"
109 #include "llvm/Transforms/Instrumentation/PGOInstrumentation.h"
110 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
111 #include "llvm/Transforms/Utils/MisExpect.h"
118 #include <unordered_map>
122 using namespace llvm
;
123 using ProfileCount
= Function::ProfileCount
;
125 #define DEBUG_TYPE "pgo-instrumentation"
127 STATISTIC(NumOfPGOInstrument
, "Number of edges instrumented.");
128 STATISTIC(NumOfPGOSelectInsts
, "Number of select instruction instrumented.");
129 STATISTIC(NumOfPGOMemIntrinsics
, "Number of mem intrinsics instrumented.");
130 STATISTIC(NumOfPGOEdge
, "Number of edges.");
131 STATISTIC(NumOfPGOBB
, "Number of basic-blocks.");
132 STATISTIC(NumOfPGOSplit
, "Number of critical edge splits.");
133 STATISTIC(NumOfPGOFunc
, "Number of functions having valid profile counts.");
134 STATISTIC(NumOfPGOMismatch
, "Number of functions having mismatch profile.");
135 STATISTIC(NumOfPGOMissing
, "Number of functions without profile.");
136 STATISTIC(NumOfPGOICall
, "Number of indirect call value instrumentations.");
137 STATISTIC(NumOfCSPGOInstrument
, "Number of edges instrumented in CSPGO.");
138 STATISTIC(NumOfCSPGOSelectInsts
,
139 "Number of select instruction instrumented in CSPGO.");
140 STATISTIC(NumOfCSPGOMemIntrinsics
,
141 "Number of mem intrinsics instrumented in CSPGO.");
142 STATISTIC(NumOfCSPGOEdge
, "Number of edges in CSPGO.");
143 STATISTIC(NumOfCSPGOBB
, "Number of basic-blocks in CSPGO.");
144 STATISTIC(NumOfCSPGOSplit
, "Number of critical edge splits in CSPGO.");
145 STATISTIC(NumOfCSPGOFunc
,
146 "Number of functions having valid profile counts in CSPGO.");
147 STATISTIC(NumOfCSPGOMismatch
,
148 "Number of functions having mismatch profile in CSPGO.");
149 STATISTIC(NumOfCSPGOMissing
, "Number of functions without profile in CSPGO.");
151 // Command line option to specify the file to read profile from. This is
152 // mainly used for testing.
153 static cl::opt
<std::string
>
154 PGOTestProfileFile("pgo-test-profile-file", cl::init(""), cl::Hidden
,
155 cl::value_desc("filename"),
156 cl::desc("Specify the path of profile data file. This is"
157 "mainly for test purpose."));
158 static cl::opt
<std::string
> PGOTestProfileRemappingFile(
159 "pgo-test-profile-remapping-file", cl::init(""), cl::Hidden
,
160 cl::value_desc("filename"),
161 cl::desc("Specify the path of profile remapping file. This is mainly for "
164 // Command line option to disable value profiling. The default is false:
165 // i.e. value profiling is enabled by default. This is for debug purpose.
166 static cl::opt
<bool> DisableValueProfiling("disable-vp", cl::init(false),
168 cl::desc("Disable Value Profiling"));
170 // Command line option to set the maximum number of VP annotations to write to
171 // the metadata for a single indirect call callsite.
172 static cl::opt
<unsigned> MaxNumAnnotations(
173 "icp-max-annotations", cl::init(3), cl::Hidden
, cl::ZeroOrMore
,
174 cl::desc("Max number of annotations for a single indirect "
177 // Command line option to set the maximum number of value annotations
178 // to write to the metadata for a single memop intrinsic.
179 static cl::opt
<unsigned> MaxNumMemOPAnnotations(
180 "memop-max-annotations", cl::init(4), cl::Hidden
, cl::ZeroOrMore
,
181 cl::desc("Max number of preicise value annotations for a single memop"
184 // Command line option to control appending FunctionHash to the name of a COMDAT
185 // function. This is to avoid the hash mismatch caused by the preinliner.
186 static cl::opt
<bool> DoComdatRenaming(
187 "do-comdat-renaming", cl::init(false), cl::Hidden
,
188 cl::desc("Append function hash to the name of COMDAT function to avoid "
189 "function hash mismatch due to the preinliner"));
191 // Command line option to enable/disable the warning about missing profile
194 PGOWarnMissing("pgo-warn-missing-function", cl::init(false), cl::Hidden
,
195 cl::desc("Use this option to turn on/off "
196 "warnings about missing profile data for "
199 // Command line option to enable/disable the warning about a hash mismatch in
202 NoPGOWarnMismatch("no-pgo-warn-mismatch", cl::init(false), cl::Hidden
,
203 cl::desc("Use this option to turn off/on "
204 "warnings about profile cfg mismatch."));
206 // Command line option to enable/disable the warning about a hash mismatch in
207 // the profile data for Comdat functions, which often turns out to be false
208 // positive due to the pre-instrumentation inline.
210 NoPGOWarnMismatchComdat("no-pgo-warn-mismatch-comdat", cl::init(true),
212 cl::desc("The option is used to turn on/off "
213 "warnings about hash mismatch for comdat "
216 // Command line option to enable/disable select instruction instrumentation.
218 PGOInstrSelect("pgo-instr-select", cl::init(true), cl::Hidden
,
219 cl::desc("Use this option to turn on/off SELECT "
220 "instruction instrumentation. "));
222 // Command line option to turn on CFG dot or text dump of raw profile counts
223 static cl::opt
<PGOViewCountsType
> PGOViewRawCounts(
224 "pgo-view-raw-counts", cl::Hidden
,
225 cl::desc("A boolean option to show CFG dag or text "
226 "with raw profile counts from "
227 "profile data. See also option "
228 "-pgo-view-counts. To limit graph "
229 "display to only one function, use "
230 "filtering option -view-bfi-func-name."),
231 cl::values(clEnumValN(PGOVCT_None
, "none", "do not show."),
232 clEnumValN(PGOVCT_Graph
, "graph", "show a graph."),
233 clEnumValN(PGOVCT_Text
, "text", "show in text.")));
235 // Command line option to enable/disable memop intrinsic call.size profiling.
237 PGOInstrMemOP("pgo-instr-memop", cl::init(true), cl::Hidden
,
238 cl::desc("Use this option to turn on/off "
239 "memory intrinsic size profiling."));
241 // Emit branch probability as optimization remarks.
243 EmitBranchProbability("pgo-emit-branch-prob", cl::init(false), cl::Hidden
,
244 cl::desc("When this option is on, the annotated "
245 "branch probability will be emitted as "
246 "optimization remarks: -{Rpass|"
247 "pass-remarks}=pgo-instrumentation"));
249 // Command line option to turn on CFG dot dump after profile annotation.
250 // Defined in Analysis/BlockFrequencyInfo.cpp: -pgo-view-counts
251 extern cl::opt
<PGOViewCountsType
> PGOViewCounts
;
253 // Command line option to specify the name of the function for CFG dump
254 // Defined in Analysis/BlockFrequencyInfo.cpp: -view-bfi-func-name=
255 extern cl::opt
<std::string
> ViewBlockFreqFuncName
;
257 // Return a string describing the branch condition that can be
258 // used in static branch probability heuristics:
259 static std::string
getBranchCondString(Instruction
*TI
) {
260 BranchInst
*BI
= dyn_cast
<BranchInst
>(TI
);
261 if (!BI
|| !BI
->isConditional())
262 return std::string();
264 Value
*Cond
= BI
->getCondition();
265 ICmpInst
*CI
= dyn_cast
<ICmpInst
>(Cond
);
267 return std::string();
270 raw_string_ostream
OS(result
);
271 OS
<< CmpInst::getPredicateName(CI
->getPredicate()) << "_";
272 CI
->getOperand(0)->getType()->print(OS
, true);
274 Value
*RHS
= CI
->getOperand(1);
275 ConstantInt
*CV
= dyn_cast
<ConstantInt
>(RHS
);
279 else if (CV
->isOne())
281 else if (CV
->isMinusOne())
292 /// The select instruction visitor plays three roles specified
293 /// by the mode. In \c VM_counting mode, it simply counts the number of
294 /// select instructions. In \c VM_instrument mode, it inserts code to count
295 /// the number times TrueValue of select is taken. In \c VM_annotate mode,
296 /// it reads the profile data and annotate the select instruction with metadata.
297 enum VisitMode
{ VM_counting
, VM_instrument
, VM_annotate
};
300 /// Instruction Visitor class to visit select instructions.
301 struct SelectInstVisitor
: public InstVisitor
<SelectInstVisitor
> {
303 unsigned NSIs
= 0; // Number of select instructions instrumented.
304 VisitMode Mode
= VM_counting
; // Visiting mode.
305 unsigned *CurCtrIdx
= nullptr; // Pointer to current counter index.
306 unsigned TotalNumCtrs
= 0; // Total number of counters
307 GlobalVariable
*FuncNameVar
= nullptr;
308 uint64_t FuncHash
= 0;
309 PGOUseFunc
*UseFunc
= nullptr;
311 SelectInstVisitor(Function
&Func
) : F(Func
) {}
313 void countSelects(Function
&Func
) {
319 // Visit the IR stream and instrument all select instructions. \p
320 // Ind is a pointer to the counter index variable; \p TotalNC
321 // is the total number of counters; \p FNV is the pointer to the
322 // PGO function name var; \p FHash is the function hash.
323 void instrumentSelects(Function
&Func
, unsigned *Ind
, unsigned TotalNC
,
324 GlobalVariable
*FNV
, uint64_t FHash
) {
325 Mode
= VM_instrument
;
327 TotalNumCtrs
= TotalNC
;
333 // Visit the IR stream and annotate all select instructions.
334 void annotateSelects(Function
&Func
, PGOUseFunc
*UF
, unsigned *Ind
) {
341 void instrumentOneSelectInst(SelectInst
&SI
);
342 void annotateOneSelectInst(SelectInst
&SI
);
344 // Visit \p SI instruction and perform tasks according to visit mode.
345 void visitSelectInst(SelectInst
&SI
);
347 // Return the number of select instructions. This needs be called after
349 unsigned getNumOfSelectInsts() const { return NSIs
; }
352 /// Instruction Visitor class to visit memory intrinsic calls.
353 struct MemIntrinsicVisitor
: public InstVisitor
<MemIntrinsicVisitor
> {
355 unsigned NMemIs
= 0; // Number of memIntrinsics instrumented.
356 VisitMode Mode
= VM_counting
; // Visiting mode.
357 unsigned CurCtrId
= 0; // Current counter index.
358 unsigned TotalNumCtrs
= 0; // Total number of counters
359 GlobalVariable
*FuncNameVar
= nullptr;
360 uint64_t FuncHash
= 0;
361 PGOUseFunc
*UseFunc
= nullptr;
362 std::vector
<Instruction
*> Candidates
;
364 MemIntrinsicVisitor(Function
&Func
) : F(Func
) {}
366 void countMemIntrinsics(Function
&Func
) {
372 void instrumentMemIntrinsics(Function
&Func
, unsigned TotalNC
,
373 GlobalVariable
*FNV
, uint64_t FHash
) {
374 Mode
= VM_instrument
;
375 TotalNumCtrs
= TotalNC
;
381 std::vector
<Instruction
*> findMemIntrinsics(Function
&Func
) {
388 // Visit the IR stream and annotate all mem intrinsic call instructions.
389 void instrumentOneMemIntrinsic(MemIntrinsic
&MI
);
391 // Visit \p MI instruction and perform tasks according to visit mode.
392 void visitMemIntrinsic(MemIntrinsic
&SI
);
394 unsigned getNumOfMemIntrinsics() const { return NMemIs
; }
397 class PGOInstrumentationGenLegacyPass
: public ModulePass
{
401 PGOInstrumentationGenLegacyPass(bool IsCS
= false)
402 : ModulePass(ID
), IsCS(IsCS
) {
403 initializePGOInstrumentationGenLegacyPassPass(
404 *PassRegistry::getPassRegistry());
407 StringRef
getPassName() const override
{ return "PGOInstrumentationGenPass"; }
410 // Is this is context-sensitive instrumentation.
412 bool runOnModule(Module
&M
) override
;
414 void getAnalysisUsage(AnalysisUsage
&AU
) const override
{
415 AU
.addRequired
<BlockFrequencyInfoWrapperPass
>();
419 class PGOInstrumentationUseLegacyPass
: public ModulePass
{
423 // Provide the profile filename as the parameter.
424 PGOInstrumentationUseLegacyPass(std::string Filename
= "", bool IsCS
= false)
425 : ModulePass(ID
), ProfileFileName(std::move(Filename
)), IsCS(IsCS
) {
426 if (!PGOTestProfileFile
.empty())
427 ProfileFileName
= PGOTestProfileFile
;
428 initializePGOInstrumentationUseLegacyPassPass(
429 *PassRegistry::getPassRegistry());
432 StringRef
getPassName() const override
{ return "PGOInstrumentationUsePass"; }
435 std::string ProfileFileName
;
436 // Is this is context-sensitive instrumentation use.
439 bool runOnModule(Module
&M
) override
;
441 void getAnalysisUsage(AnalysisUsage
&AU
) const override
{
442 AU
.addRequired
<ProfileSummaryInfoWrapperPass
>();
443 AU
.addRequired
<BlockFrequencyInfoWrapperPass
>();
447 class PGOInstrumentationGenCreateVarLegacyPass
: public ModulePass
{
450 StringRef
getPassName() const override
{
451 return "PGOInstrumentationGenCreateVarPass";
453 PGOInstrumentationGenCreateVarLegacyPass(std::string CSInstrName
= "")
454 : ModulePass(ID
), InstrProfileOutput(CSInstrName
) {
455 initializePGOInstrumentationGenCreateVarLegacyPassPass(
456 *PassRegistry::getPassRegistry());
460 bool runOnModule(Module
&M
) override
{
461 createProfileFileNameVar(M
, InstrProfileOutput
);
462 createIRLevelProfileFlagVar(M
, true);
465 std::string InstrProfileOutput
;
468 } // end anonymous namespace
470 char PGOInstrumentationGenLegacyPass::ID
= 0;
472 INITIALIZE_PASS_BEGIN(PGOInstrumentationGenLegacyPass
, "pgo-instr-gen",
473 "PGO instrumentation.", false, false)
474 INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass
)
475 INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass
)
476 INITIALIZE_PASS_END(PGOInstrumentationGenLegacyPass
, "pgo-instr-gen",
477 "PGO instrumentation.", false, false)
479 ModulePass
*llvm::createPGOInstrumentationGenLegacyPass(bool IsCS
) {
480 return new PGOInstrumentationGenLegacyPass(IsCS
);
483 char PGOInstrumentationUseLegacyPass::ID
= 0;
485 INITIALIZE_PASS_BEGIN(PGOInstrumentationUseLegacyPass
, "pgo-instr-use",
486 "Read PGO instrumentation profile.", false, false)
487 INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass
)
488 INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass
)
489 INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass
)
490 INITIALIZE_PASS_END(PGOInstrumentationUseLegacyPass
, "pgo-instr-use",
491 "Read PGO instrumentation profile.", false, false)
493 ModulePass
*llvm::createPGOInstrumentationUseLegacyPass(StringRef Filename
,
495 return new PGOInstrumentationUseLegacyPass(Filename
.str(), IsCS
);
498 char PGOInstrumentationGenCreateVarLegacyPass::ID
= 0;
500 INITIALIZE_PASS(PGOInstrumentationGenCreateVarLegacyPass
,
501 "pgo-instr-gen-create-var",
502 "Create PGO instrumentation version variable for CSPGO.", false,
506 llvm::createPGOInstrumentationGenCreateVarLegacyPass(StringRef CSInstrName
) {
507 return new PGOInstrumentationGenCreateVarLegacyPass(CSInstrName
);
512 /// An MST based instrumentation for PGO
514 /// Implements a Minimum Spanning Tree (MST) based instrumentation for PGO
515 /// in the function level.
517 // This class implements the CFG edges. Note the CFG can be a multi-graph.
518 // So there might be multiple edges with same SrcBB and DestBB.
519 const BasicBlock
*SrcBB
;
520 const BasicBlock
*DestBB
;
523 bool Removed
= false;
524 bool IsCritical
= false;
526 PGOEdge(const BasicBlock
*Src
, const BasicBlock
*Dest
, uint64_t W
= 1)
527 : SrcBB(Src
), DestBB(Dest
), Weight(W
) {}
529 // Return the information string of an edge.
530 const std::string
infoString() const {
531 return (Twine(Removed
? "-" : " ") + (InMST
? " " : "*") +
532 (IsCritical
? "c" : " ") + " W=" + Twine(Weight
)).str();
536 // This class stores the auxiliary information for each BB.
542 BBInfo(unsigned IX
) : Group(this), Index(IX
) {}
544 // Return the information string of this object.
545 const std::string
infoString() const {
546 return (Twine("Index=") + Twine(Index
)).str();
549 // Empty function -- only applicable to UseBBInfo.
550 void addOutEdge(PGOEdge
*E LLVM_ATTRIBUTE_UNUSED
) {}
552 // Empty function -- only applicable to UseBBInfo.
553 void addInEdge(PGOEdge
*E LLVM_ATTRIBUTE_UNUSED
) {}
556 // This class implements the CFG edges. Note the CFG can be a multi-graph.
557 template <class Edge
, class BBInfo
> class FuncPGOInstrumentation
{
561 // Is this is context-sensitive instrumentation.
564 // A map that stores the Comdat group in function F.
565 std::unordered_multimap
<Comdat
*, GlobalValue
*> &ComdatMembers
;
567 void computeCFGHash();
568 void renameComdatFunction();
571 std::vector
<std::vector
<Instruction
*>> ValueSites
;
572 SelectInstVisitor SIVisitor
;
573 MemIntrinsicVisitor MIVisitor
;
574 std::string FuncName
;
575 GlobalVariable
*FuncNameVar
;
577 // CFG hash value for this function.
578 uint64_t FunctionHash
= 0;
580 // The Minimum Spanning Tree of function CFG.
581 CFGMST
<Edge
, BBInfo
> MST
;
583 // Collect all the BBs that will be instrumented, and store them in
585 void getInstrumentBBs(std::vector
<BasicBlock
*> &InstrumentBBs
);
587 // Give an edge, find the BB that will be instrumented.
588 // Return nullptr if there is no BB to be instrumented.
589 BasicBlock
*getInstrBB(Edge
*E
);
591 // Return the auxiliary BB information.
592 BBInfo
&getBBInfo(const BasicBlock
*BB
) const { return MST
.getBBInfo(BB
); }
594 // Return the auxiliary BB information if available.
595 BBInfo
*findBBInfo(const BasicBlock
*BB
) const { return MST
.findBBInfo(BB
); }
597 // Dump edges and BB information.
598 void dumpInfo(std::string Str
= "") const {
599 MST
.dumpEdges(dbgs(), Twine("Dump Function ") + FuncName
+ " Hash: " +
600 Twine(FunctionHash
) + "\t" + Str
);
603 FuncPGOInstrumentation(
605 std::unordered_multimap
<Comdat
*, GlobalValue
*> &ComdatMembers
,
606 bool CreateGlobalVar
= false, BranchProbabilityInfo
*BPI
= nullptr,
607 BlockFrequencyInfo
*BFI
= nullptr, bool IsCS
= false)
608 : F(Func
), IsCS(IsCS
), ComdatMembers(ComdatMembers
),
609 ValueSites(IPVK_Last
+ 1), SIVisitor(Func
), MIVisitor(Func
),
611 // This should be done before CFG hash computation.
612 SIVisitor
.countSelects(Func
);
613 MIVisitor
.countMemIntrinsics(Func
);
615 NumOfPGOSelectInsts
+= SIVisitor
.getNumOfSelectInsts();
616 NumOfPGOMemIntrinsics
+= MIVisitor
.getNumOfMemIntrinsics();
617 NumOfPGOBB
+= MST
.BBInfos
.size();
618 ValueSites
[IPVK_IndirectCallTarget
] = findIndirectCalls(Func
);
620 NumOfCSPGOSelectInsts
+= SIVisitor
.getNumOfSelectInsts();
621 NumOfCSPGOMemIntrinsics
+= MIVisitor
.getNumOfMemIntrinsics();
622 NumOfCSPGOBB
+= MST
.BBInfos
.size();
624 ValueSites
[IPVK_MemOPSize
] = MIVisitor
.findMemIntrinsics(Func
);
626 FuncName
= getPGOFuncName(F
);
628 if (!ComdatMembers
.empty())
629 renameComdatFunction();
630 LLVM_DEBUG(dumpInfo("after CFGMST"));
632 for (auto &E
: MST
.AllEdges
) {
635 IsCS
? NumOfCSPGOEdge
++ : NumOfPGOEdge
++;
637 IsCS
? NumOfCSPGOInstrument
++ : NumOfPGOInstrument
++;
641 FuncNameVar
= createPGOFuncNameVar(F
, FuncName
);
645 } // end anonymous namespace
647 // Compute Hash value for the CFG: the lower 32 bits are CRC32 of the index
648 // value of each BB in the CFG. The higher 32 bits record the number of edges.
649 template <class Edge
, class BBInfo
>
650 void FuncPGOInstrumentation
<Edge
, BBInfo
>::computeCFGHash() {
651 std::vector
<char> Indexes
;
654 const Instruction
*TI
= BB
.getTerminator();
655 for (unsigned I
= 0, E
= TI
->getNumSuccessors(); I
!= E
; ++I
) {
656 BasicBlock
*Succ
= TI
->getSuccessor(I
);
657 auto BI
= findBBInfo(Succ
);
660 uint32_t Index
= BI
->Index
;
661 for (int J
= 0; J
< 4; J
++)
662 Indexes
.push_back((char)(Index
>> (J
* 8)));
667 // Hash format for context sensitive profile. Reserve 4 bits for other
669 FunctionHash
= (uint64_t)SIVisitor
.getNumOfSelectInsts() << 56 |
670 (uint64_t)ValueSites
[IPVK_IndirectCallTarget
].size() << 48 |
671 //(uint64_t)ValueSites[IPVK_MemOPSize].size() << 40 |
672 (uint64_t)MST
.AllEdges
.size() << 32 | JC
.getCRC();
673 // Reserve bit 60-63 for other information purpose.
674 FunctionHash
&= 0x0FFFFFFFFFFFFFFF;
676 NamedInstrProfRecord::setCSFlagInHash(FunctionHash
);
677 LLVM_DEBUG(dbgs() << "Function Hash Computation for " << F
.getName() << ":\n"
678 << " CRC = " << JC
.getCRC()
679 << ", Selects = " << SIVisitor
.getNumOfSelectInsts()
680 << ", Edges = " << MST
.AllEdges
.size() << ", ICSites = "
681 << ValueSites
[IPVK_IndirectCallTarget
].size()
682 << ", Hash = " << FunctionHash
<< "\n";);
685 // Check if we can safely rename this Comdat function.
686 static bool canRenameComdat(
688 std::unordered_multimap
<Comdat
*, GlobalValue
*> &ComdatMembers
) {
689 if (!DoComdatRenaming
|| !canRenameComdatFunc(F
, true))
692 // FIXME: Current only handle those Comdat groups that only containing one
693 // function and function aliases.
694 // (1) For a Comdat group containing multiple functions, we need to have a
695 // unique postfix based on the hashes for each function. There is a
696 // non-trivial code refactoring to do this efficiently.
697 // (2) Variables can not be renamed, so we can not rename Comdat function in a
698 // group including global vars.
699 Comdat
*C
= F
.getComdat();
700 for (auto &&CM
: make_range(ComdatMembers
.equal_range(C
))) {
701 if (dyn_cast
<GlobalAlias
>(CM
.second
))
703 Function
*FM
= dyn_cast
<Function
>(CM
.second
);
710 // Append the CFGHash to the Comdat function name.
711 template <class Edge
, class BBInfo
>
712 void FuncPGOInstrumentation
<Edge
, BBInfo
>::renameComdatFunction() {
713 if (!canRenameComdat(F
, ComdatMembers
))
715 std::string OrigName
= F
.getName().str();
716 std::string NewFuncName
=
717 Twine(F
.getName() + "." + Twine(FunctionHash
)).str();
718 F
.setName(Twine(NewFuncName
));
719 GlobalAlias::create(GlobalValue::WeakAnyLinkage
, OrigName
, &F
);
720 FuncName
= Twine(FuncName
+ "." + Twine(FunctionHash
)).str();
722 Module
*M
= F
.getParent();
723 // For AvailableExternallyLinkage functions, change the linkage to
724 // LinkOnceODR and put them into comdat. This is because after renaming, there
725 // is no backup external copy available for the function.
726 if (!F
.hasComdat()) {
727 assert(F
.getLinkage() == GlobalValue::AvailableExternallyLinkage
);
728 NewComdat
= M
->getOrInsertComdat(StringRef(NewFuncName
));
729 F
.setLinkage(GlobalValue::LinkOnceODRLinkage
);
730 F
.setComdat(NewComdat
);
734 // This function belongs to a single function Comdat group.
735 Comdat
*OrigComdat
= F
.getComdat();
736 std::string NewComdatName
=
737 Twine(OrigComdat
->getName() + "." + Twine(FunctionHash
)).str();
738 NewComdat
= M
->getOrInsertComdat(StringRef(NewComdatName
));
739 NewComdat
->setSelectionKind(OrigComdat
->getSelectionKind());
741 for (auto &&CM
: make_range(ComdatMembers
.equal_range(OrigComdat
))) {
742 if (GlobalAlias
*GA
= dyn_cast
<GlobalAlias
>(CM
.second
)) {
743 // For aliases, change the name directly.
744 assert(dyn_cast
<Function
>(GA
->getAliasee()->stripPointerCasts()) == &F
);
745 std::string OrigGAName
= GA
->getName().str();
746 GA
->setName(Twine(GA
->getName() + "." + Twine(FunctionHash
)));
747 GlobalAlias::create(GlobalValue::WeakAnyLinkage
, OrigGAName
, GA
);
750 // Must be a function.
751 Function
*CF
= dyn_cast
<Function
>(CM
.second
);
753 CF
->setComdat(NewComdat
);
757 // Collect all the BBs that will be instruments and return them in
758 // InstrumentBBs and setup InEdges/OutEdge for UseBBInfo.
759 template <class Edge
, class BBInfo
>
760 void FuncPGOInstrumentation
<Edge
, BBInfo
>::getInstrumentBBs(
761 std::vector
<BasicBlock
*> &InstrumentBBs
) {
762 // Use a worklist as we will update the vector during the iteration.
763 std::vector
<Edge
*> EdgeList
;
764 EdgeList
.reserve(MST
.AllEdges
.size());
765 for (auto &E
: MST
.AllEdges
)
766 EdgeList
.push_back(E
.get());
768 for (auto &E
: EdgeList
) {
769 BasicBlock
*InstrBB
= getInstrBB(E
);
771 InstrumentBBs
.push_back(InstrBB
);
774 // Set up InEdges/OutEdges for all BBs.
775 for (auto &E
: MST
.AllEdges
) {
778 const BasicBlock
*SrcBB
= E
->SrcBB
;
779 const BasicBlock
*DestBB
= E
->DestBB
;
780 BBInfo
&SrcInfo
= getBBInfo(SrcBB
);
781 BBInfo
&DestInfo
= getBBInfo(DestBB
);
782 SrcInfo
.addOutEdge(E
.get());
783 DestInfo
.addInEdge(E
.get());
787 // Given a CFG E to be instrumented, find which BB to place the instrumented
788 // code. The function will split the critical edge if necessary.
789 template <class Edge
, class BBInfo
>
790 BasicBlock
*FuncPGOInstrumentation
<Edge
, BBInfo
>::getInstrBB(Edge
*E
) {
791 if (E
->InMST
|| E
->Removed
)
794 BasicBlock
*SrcBB
= const_cast<BasicBlock
*>(E
->SrcBB
);
795 BasicBlock
*DestBB
= const_cast<BasicBlock
*>(E
->DestBB
);
796 // For a fake edge, instrument the real BB.
797 if (SrcBB
== nullptr)
799 if (DestBB
== nullptr)
802 auto canInstrument
= [](BasicBlock
*BB
) -> BasicBlock
* {
803 // There are basic blocks (such as catchswitch) cannot be instrumented.
804 // If the returned first insertion point is the end of BB, skip this BB.
805 if (BB
->getFirstInsertionPt() == BB
->end())
810 // Instrument the SrcBB if it has a single successor,
811 // otherwise, the DestBB if this is not a critical edge.
812 Instruction
*TI
= SrcBB
->getTerminator();
813 if (TI
->getNumSuccessors() <= 1)
814 return canInstrument(SrcBB
);
816 return canInstrument(DestBB
);
818 unsigned SuccNum
= GetSuccessorNumber(SrcBB
, DestBB
);
819 BasicBlock
*InstrBB
= SplitCriticalEdge(TI
, SuccNum
);
822 dbgs() << "Fail to split critical edge: not instrument this edge.\n");
825 // For a critical edge, we have to split. Instrument the newly
827 IsCS
? NumOfCSPGOSplit
++ : NumOfPGOSplit
++;
828 LLVM_DEBUG(dbgs() << "Split critical edge: " << getBBInfo(SrcBB
).Index
829 << " --> " << getBBInfo(DestBB
).Index
<< "\n");
830 // Need to add two new edges. First one: Add new edge of SrcBB->InstrBB.
831 MST
.addEdge(SrcBB
, InstrBB
, 0);
832 // Second one: Add new edge of InstrBB->DestBB.
833 Edge
&NewEdge1
= MST
.addEdge(InstrBB
, DestBB
, 0);
834 NewEdge1
.InMST
= true;
837 return canInstrument(InstrBB
);
840 // Visit all edge and instrument the edges not in MST, and do value profiling.
841 // Critical edges will be split.
842 static void instrumentOneFunc(
843 Function
&F
, Module
*M
, BranchProbabilityInfo
*BPI
, BlockFrequencyInfo
*BFI
,
844 std::unordered_multimap
<Comdat
*, GlobalValue
*> &ComdatMembers
,
846 // Split indirectbr critical edges here before computing the MST rather than
847 // later in getInstrBB() to avoid invalidating it.
848 SplitIndirectBrCriticalEdges(F
, BPI
, BFI
);
850 FuncPGOInstrumentation
<PGOEdge
, BBInfo
> FuncInfo(F
, ComdatMembers
, true, BPI
,
852 std::vector
<BasicBlock
*> InstrumentBBs
;
853 FuncInfo
.getInstrumentBBs(InstrumentBBs
);
854 unsigned NumCounters
=
855 InstrumentBBs
.size() + FuncInfo
.SIVisitor
.getNumOfSelectInsts();
858 Type
*I8PtrTy
= Type::getInt8PtrTy(M
->getContext());
859 for (auto *InstrBB
: InstrumentBBs
) {
860 IRBuilder
<> Builder(InstrBB
, InstrBB
->getFirstInsertionPt());
861 assert(Builder
.GetInsertPoint() != InstrBB
->end() &&
862 "Cannot get the Instrumentation point");
864 Intrinsic::getDeclaration(M
, Intrinsic::instrprof_increment
),
865 {ConstantExpr::getBitCast(FuncInfo
.FuncNameVar
, I8PtrTy
),
866 Builder
.getInt64(FuncInfo
.FunctionHash
), Builder
.getInt32(NumCounters
),
867 Builder
.getInt32(I
++)});
870 // Now instrument select instructions:
871 FuncInfo
.SIVisitor
.instrumentSelects(F
, &I
, NumCounters
, FuncInfo
.FuncNameVar
,
872 FuncInfo
.FunctionHash
);
873 assert(I
== NumCounters
);
875 if (DisableValueProfiling
)
878 unsigned NumIndirectCalls
= 0;
879 for (auto &I
: FuncInfo
.ValueSites
[IPVK_IndirectCallTarget
]) {
881 Value
*Callee
= CS
.getCalledValue();
882 LLVM_DEBUG(dbgs() << "Instrument one indirect call: CallSite Index = "
883 << NumIndirectCalls
<< "\n");
884 IRBuilder
<> Builder(I
);
885 assert(Builder
.GetInsertPoint() != I
->getParent()->end() &&
886 "Cannot get the Instrumentation point");
888 Intrinsic::getDeclaration(M
, Intrinsic::instrprof_value_profile
),
889 {ConstantExpr::getBitCast(FuncInfo
.FuncNameVar
, I8PtrTy
),
890 Builder
.getInt64(FuncInfo
.FunctionHash
),
891 Builder
.CreatePtrToInt(Callee
, Builder
.getInt64Ty()),
892 Builder
.getInt32(IPVK_IndirectCallTarget
),
893 Builder
.getInt32(NumIndirectCalls
++)});
895 NumOfPGOICall
+= NumIndirectCalls
;
897 // Now instrument memop intrinsic calls.
898 FuncInfo
.MIVisitor
.instrumentMemIntrinsics(
899 F
, NumCounters
, FuncInfo
.FuncNameVar
, FuncInfo
.FunctionHash
);
904 // This class represents a CFG edge in profile use compilation.
905 struct PGOUseEdge
: public PGOEdge
{
906 bool CountValid
= false;
907 uint64_t CountValue
= 0;
909 PGOUseEdge(const BasicBlock
*Src
, const BasicBlock
*Dest
, uint64_t W
= 1)
910 : PGOEdge(Src
, Dest
, W
) {}
912 // Set edge count value
913 void setEdgeCount(uint64_t Value
) {
918 // Return the information string for this object.
919 const std::string
infoString() const {
921 return PGOEdge::infoString();
922 return (Twine(PGOEdge::infoString()) + " Count=" + Twine(CountValue
))
927 using DirectEdges
= SmallVector
<PGOUseEdge
*, 2>;
929 // This class stores the auxiliary information for each BB.
930 struct UseBBInfo
: public BBInfo
{
931 uint64_t CountValue
= 0;
933 int32_t UnknownCountInEdge
= 0;
934 int32_t UnknownCountOutEdge
= 0;
936 DirectEdges OutEdges
;
938 UseBBInfo(unsigned IX
) : BBInfo(IX
), CountValid(false) {}
940 UseBBInfo(unsigned IX
, uint64_t C
)
941 : BBInfo(IX
), CountValue(C
), CountValid(true) {}
943 // Set the profile count value for this BB.
944 void setBBInfoCount(uint64_t Value
) {
949 // Return the information string of this object.
950 const std::string
infoString() const {
952 return BBInfo::infoString();
953 return (Twine(BBInfo::infoString()) + " Count=" + Twine(CountValue
)).str();
956 // Add an OutEdge and update the edge count.
957 void addOutEdge(PGOUseEdge
*E
) {
958 OutEdges
.push_back(E
);
959 UnknownCountOutEdge
++;
962 // Add an InEdge and update the edge count.
963 void addInEdge(PGOUseEdge
*E
) {
964 InEdges
.push_back(E
);
965 UnknownCountInEdge
++;
969 } // end anonymous namespace
971 // Sum up the count values for all the edges.
972 static uint64_t sumEdgeCount(const ArrayRef
<PGOUseEdge
*> Edges
) {
974 for (auto &E
: Edges
) {
977 Total
+= E
->CountValue
;
986 PGOUseFunc(Function
&Func
, Module
*Modu
,
987 std::unordered_multimap
<Comdat
*, GlobalValue
*> &ComdatMembers
,
988 BranchProbabilityInfo
*BPI
, BlockFrequencyInfo
*BFIin
,
989 ProfileSummaryInfo
*PSI
, bool IsCS
)
990 : F(Func
), M(Modu
), BFI(BFIin
), PSI(PSI
),
991 FuncInfo(Func
, ComdatMembers
, false, BPI
, BFIin
, IsCS
),
992 FreqAttr(FFA_Normal
), IsCS(IsCS
) {}
994 // Read counts for the instrumented BB from profile.
995 bool readCounters(IndexedInstrProfReader
*PGOReader
, bool &AllZeros
);
997 // Populate the counts for all BBs.
998 void populateCounters();
1000 // Set the branch weights based on the count values.
1001 void setBranchWeights();
1003 // Annotate the value profile call sites for all value kind.
1004 void annotateValueSites();
1006 // Annotate the value profile call sites for one value kind.
1007 void annotateValueSites(uint32_t Kind
);
1009 // Annotate the irreducible loop header weights.
1010 void annotateIrrLoopHeaderWeights();
1012 // The hotness of the function from the profile count.
1013 enum FuncFreqAttr
{ FFA_Normal
, FFA_Cold
, FFA_Hot
};
1015 // Return the function hotness from the profile.
1016 FuncFreqAttr
getFuncFreqAttr() const { return FreqAttr
; }
1018 // Return the function hash.
1019 uint64_t getFuncHash() const { return FuncInfo
.FunctionHash
; }
1021 // Return the profile record for this function;
1022 InstrProfRecord
&getProfileRecord() { return ProfileRecord
; }
1024 // Return the auxiliary BB information.
1025 UseBBInfo
&getBBInfo(const BasicBlock
*BB
) const {
1026 return FuncInfo
.getBBInfo(BB
);
1029 // Return the auxiliary BB information if available.
1030 UseBBInfo
*findBBInfo(const BasicBlock
*BB
) const {
1031 return FuncInfo
.findBBInfo(BB
);
1034 Function
&getFunc() const { return F
; }
1036 void dumpInfo(std::string Str
= "") const {
1037 FuncInfo
.dumpInfo(Str
);
1040 uint64_t getProgramMaxCount() const { return ProgramMaxCount
; }
1044 BlockFrequencyInfo
*BFI
;
1045 ProfileSummaryInfo
*PSI
;
1047 // This member stores the shared information with class PGOGenFunc.
1048 FuncPGOInstrumentation
<PGOUseEdge
, UseBBInfo
> FuncInfo
;
1050 // The maximum count value in the profile. This is only used in PGO use
1052 uint64_t ProgramMaxCount
;
1054 // Position of counter that remains to be read.
1055 uint32_t CountPosition
= 0;
1057 // Total size of the profile count for this function.
1058 uint32_t ProfileCountSize
= 0;
1060 // ProfileRecord for this function.
1061 InstrProfRecord ProfileRecord
;
1063 // Function hotness info derived from profile.
1064 FuncFreqAttr FreqAttr
;
1066 // Is to use the context sensitive profile.
1069 // Find the Instrumented BB and set the value. Return false on error.
1070 bool setInstrumentedCounts(const std::vector
<uint64_t> &CountFromProfile
);
1072 // Set the edge counter value for the unknown edge -- there should be only
1073 // one unknown edge.
1074 void setEdgeCount(DirectEdges
&Edges
, uint64_t Value
);
1076 // Return FuncName string;
1077 const std::string
getFuncName() const { return FuncInfo
.FuncName
; }
1079 // Set the hot/cold inline hints based on the count values.
1080 // FIXME: This function should be removed once the functionality in
1081 // the inliner is implemented.
1082 void markFunctionAttributes(uint64_t EntryCount
, uint64_t MaxCount
) {
1083 if (PSI
->isHotCount(EntryCount
))
1085 else if (PSI
->isColdCount(MaxCount
))
1086 FreqAttr
= FFA_Cold
;
1090 } // end anonymous namespace
1092 // Visit all the edges and assign the count value for the instrumented
1093 // edges and the BB. Return false on error.
1094 bool PGOUseFunc::setInstrumentedCounts(
1095 const std::vector
<uint64_t> &CountFromProfile
) {
1097 std::vector
<BasicBlock
*> InstrumentBBs
;
1098 FuncInfo
.getInstrumentBBs(InstrumentBBs
);
1099 unsigned NumCounters
=
1100 InstrumentBBs
.size() + FuncInfo
.SIVisitor
.getNumOfSelectInsts();
1101 // The number of counters here should match the number of counters
1102 // in profile. Return if they mismatch.
1103 if (NumCounters
!= CountFromProfile
.size()) {
1106 // Set the profile count to the Instrumented BBs.
1108 for (BasicBlock
*InstrBB
: InstrumentBBs
) {
1109 uint64_t CountValue
= CountFromProfile
[I
++];
1110 UseBBInfo
&Info
= getBBInfo(InstrBB
);
1111 Info
.setBBInfoCount(CountValue
);
1113 ProfileCountSize
= CountFromProfile
.size();
1116 // Set the edge count and update the count of unknown edges for BBs.
1117 auto setEdgeCount
= [this](PGOUseEdge
*E
, uint64_t Value
) -> void {
1118 E
->setEdgeCount(Value
);
1119 this->getBBInfo(E
->SrcBB
).UnknownCountOutEdge
--;
1120 this->getBBInfo(E
->DestBB
).UnknownCountInEdge
--;
1123 // Set the profile count the Instrumented edges. There are BBs that not in
1124 // MST but not instrumented. Need to set the edge count value so that we can
1125 // populate the profile counts later.
1126 for (auto &E
: FuncInfo
.MST
.AllEdges
) {
1127 if (E
->Removed
|| E
->InMST
)
1129 const BasicBlock
*SrcBB
= E
->SrcBB
;
1130 UseBBInfo
&SrcInfo
= getBBInfo(SrcBB
);
1132 // If only one out-edge, the edge profile count should be the same as BB
1134 if (SrcInfo
.CountValid
&& SrcInfo
.OutEdges
.size() == 1)
1135 setEdgeCount(E
.get(), SrcInfo
.CountValue
);
1137 const BasicBlock
*DestBB
= E
->DestBB
;
1138 UseBBInfo
&DestInfo
= getBBInfo(DestBB
);
1139 // If only one in-edge, the edge profile count should be the same as BB
1141 if (DestInfo
.CountValid
&& DestInfo
.InEdges
.size() == 1)
1142 setEdgeCount(E
.get(), DestInfo
.CountValue
);
1146 // E's count should have been set from profile. If not, this meenas E skips
1147 // the instrumentation. We set the count to 0.
1148 setEdgeCount(E
.get(), 0);
1153 // Set the count value for the unknown edge. There should be one and only one
1154 // unknown edge in Edges vector.
1155 void PGOUseFunc::setEdgeCount(DirectEdges
&Edges
, uint64_t Value
) {
1156 for (auto &E
: Edges
) {
1159 E
->setEdgeCount(Value
);
1161 getBBInfo(E
->SrcBB
).UnknownCountOutEdge
--;
1162 getBBInfo(E
->DestBB
).UnknownCountInEdge
--;
1165 llvm_unreachable("Cannot find the unknown count edge");
1168 // Read the profile from ProfileFileName and assign the value to the
1169 // instrumented BB and the edges. This function also updates ProgramMaxCount.
1170 // Return true if the profile are successfully read, and false on errors.
1171 bool PGOUseFunc::readCounters(IndexedInstrProfReader
*PGOReader
, bool &AllZeros
) {
1172 auto &Ctx
= M
->getContext();
1173 Expected
<InstrProfRecord
> Result
=
1174 PGOReader
->getInstrProfRecord(FuncInfo
.FuncName
, FuncInfo
.FunctionHash
);
1175 if (Error E
= Result
.takeError()) {
1176 handleAllErrors(std::move(E
), [&](const InstrProfError
&IPE
) {
1177 auto Err
= IPE
.get();
1178 bool SkipWarning
= false;
1179 LLVM_DEBUG(dbgs() << "Error in reading profile for Func "
1180 << FuncInfo
.FuncName
<< ": ");
1181 if (Err
== instrprof_error::unknown_function
) {
1182 IsCS
? NumOfCSPGOMissing
++ : NumOfPGOMissing
++;
1183 SkipWarning
= !PGOWarnMissing
;
1184 LLVM_DEBUG(dbgs() << "unknown function");
1185 } else if (Err
== instrprof_error::hash_mismatch
||
1186 Err
== instrprof_error::malformed
) {
1187 IsCS
? NumOfCSPGOMismatch
++ : NumOfPGOMismatch
++;
1189 NoPGOWarnMismatch
||
1190 (NoPGOWarnMismatchComdat
&&
1192 F
.getLinkage() == GlobalValue::AvailableExternallyLinkage
));
1193 LLVM_DEBUG(dbgs() << "hash mismatch (skip=" << SkipWarning
<< ")");
1196 LLVM_DEBUG(dbgs() << " IsCS=" << IsCS
<< "\n");
1200 std::string Msg
= IPE
.message() + std::string(" ") + F
.getName().str() +
1201 std::string(" Hash = ") +
1202 std::to_string(FuncInfo
.FunctionHash
);
1205 DiagnosticInfoPGOProfile(M
->getName().data(), Msg
, DS_Warning
));
1209 ProfileRecord
= std::move(Result
.get());
1210 std::vector
<uint64_t> &CountFromProfile
= ProfileRecord
.Counts
;
1212 IsCS
? NumOfCSPGOFunc
++ : NumOfPGOFunc
++;
1213 LLVM_DEBUG(dbgs() << CountFromProfile
.size() << " counts\n");
1214 uint64_t ValueSum
= 0;
1215 for (unsigned I
= 0, S
= CountFromProfile
.size(); I
< S
; I
++) {
1216 LLVM_DEBUG(dbgs() << " " << I
<< ": " << CountFromProfile
[I
] << "\n");
1217 ValueSum
+= CountFromProfile
[I
];
1219 AllZeros
= (ValueSum
== 0);
1221 LLVM_DEBUG(dbgs() << "SUM = " << ValueSum
<< "\n");
1223 getBBInfo(nullptr).UnknownCountOutEdge
= 2;
1224 getBBInfo(nullptr).UnknownCountInEdge
= 2;
1226 if (!setInstrumentedCounts(CountFromProfile
)) {
1228 dbgs() << "Inconsistent number of counts, skipping this function");
1229 Ctx
.diagnose(DiagnosticInfoPGOProfile(
1230 M
->getName().data(),
1231 Twine("Inconsistent number of counts in ") + F
.getName().str()
1232 + Twine(": the profile may be stale or there is a function name collision."),
1236 ProgramMaxCount
= PGOReader
->getMaximumFunctionCount(IsCS
);
1240 // Populate the counters from instrumented BBs to all BBs.
1241 // In the end of this operation, all BBs should have a valid count value.
1242 void PGOUseFunc::populateCounters() {
1243 bool Changes
= true;
1244 unsigned NumPasses
= 0;
1249 // For efficient traversal, it's better to start from the end as most
1250 // of the instrumented edges are at the end.
1251 for (auto &BB
: reverse(F
)) {
1252 UseBBInfo
*Count
= findBBInfo(&BB
);
1253 if (Count
== nullptr)
1255 if (!Count
->CountValid
) {
1256 if (Count
->UnknownCountOutEdge
== 0) {
1257 Count
->CountValue
= sumEdgeCount(Count
->OutEdges
);
1258 Count
->CountValid
= true;
1260 } else if (Count
->UnknownCountInEdge
== 0) {
1261 Count
->CountValue
= sumEdgeCount(Count
->InEdges
);
1262 Count
->CountValid
= true;
1266 if (Count
->CountValid
) {
1267 if (Count
->UnknownCountOutEdge
== 1) {
1269 uint64_t OutSum
= sumEdgeCount(Count
->OutEdges
);
1270 // If the one of the successor block can early terminate (no-return),
1271 // we can end up with situation where out edge sum count is larger as
1272 // the source BB's count is collected by a post-dominated block.
1273 if (Count
->CountValue
> OutSum
)
1274 Total
= Count
->CountValue
- OutSum
;
1275 setEdgeCount(Count
->OutEdges
, Total
);
1278 if (Count
->UnknownCountInEdge
== 1) {
1280 uint64_t InSum
= sumEdgeCount(Count
->InEdges
);
1281 if (Count
->CountValue
> InSum
)
1282 Total
= Count
->CountValue
- InSum
;
1283 setEdgeCount(Count
->InEdges
, Total
);
1290 LLVM_DEBUG(dbgs() << "Populate counts in " << NumPasses
<< " passes.\n");
1292 // Assert every BB has a valid counter.
1293 for (auto &BB
: F
) {
1294 auto BI
= findBBInfo(&BB
);
1297 assert(BI
->CountValid
&& "BB count is not valid");
1300 uint64_t FuncEntryCount
= getBBInfo(&*F
.begin()).CountValue
;
1301 F
.setEntryCount(ProfileCount(FuncEntryCount
, Function::PCT_Real
));
1302 uint64_t FuncMaxCount
= FuncEntryCount
;
1303 for (auto &BB
: F
) {
1304 auto BI
= findBBInfo(&BB
);
1307 FuncMaxCount
= std::max(FuncMaxCount
, BI
->CountValue
);
1309 markFunctionAttributes(FuncEntryCount
, FuncMaxCount
);
1311 // Now annotate select instructions
1312 FuncInfo
.SIVisitor
.annotateSelects(F
, this, &CountPosition
);
1313 assert(CountPosition
== ProfileCountSize
);
1315 LLVM_DEBUG(FuncInfo
.dumpInfo("after reading profile."));
1318 // Assign the scaled count values to the BB with multiple out edges.
1319 void PGOUseFunc::setBranchWeights() {
1320 // Generate MD_prof metadata for every branch instruction.
1321 LLVM_DEBUG(dbgs() << "\nSetting branch weights for func " << F
.getName()
1322 << " IsCS=" << IsCS
<< "\n");
1323 for (auto &BB
: F
) {
1324 Instruction
*TI
= BB
.getTerminator();
1325 if (TI
->getNumSuccessors() < 2)
1327 if (!(isa
<BranchInst
>(TI
) || isa
<SwitchInst
>(TI
) ||
1328 isa
<IndirectBrInst
>(TI
)))
1331 if (getBBInfo(&BB
).CountValue
== 0)
1334 // We have a non-zero Branch BB.
1335 const UseBBInfo
&BBCountInfo
= getBBInfo(&BB
);
1336 unsigned Size
= BBCountInfo
.OutEdges
.size();
1337 SmallVector
<uint64_t, 2> EdgeCounts(Size
, 0);
1338 uint64_t MaxCount
= 0;
1339 for (unsigned s
= 0; s
< Size
; s
++) {
1340 const PGOUseEdge
*E
= BBCountInfo
.OutEdges
[s
];
1341 const BasicBlock
*SrcBB
= E
->SrcBB
;
1342 const BasicBlock
*DestBB
= E
->DestBB
;
1343 if (DestBB
== nullptr)
1345 unsigned SuccNum
= GetSuccessorNumber(SrcBB
, DestBB
);
1346 uint64_t EdgeCount
= E
->CountValue
;
1347 if (EdgeCount
> MaxCount
)
1348 MaxCount
= EdgeCount
;
1349 EdgeCounts
[SuccNum
] = EdgeCount
;
1351 setProfMetadata(M
, TI
, EdgeCounts
, MaxCount
);
1355 static bool isIndirectBrTarget(BasicBlock
*BB
) {
1356 for (pred_iterator PI
= pred_begin(BB
), E
= pred_end(BB
); PI
!= E
; ++PI
) {
1357 if (isa
<IndirectBrInst
>((*PI
)->getTerminator()))
1363 void PGOUseFunc::annotateIrrLoopHeaderWeights() {
1364 LLVM_DEBUG(dbgs() << "\nAnnotating irreducible loop header weights.\n");
1365 // Find irr loop headers
1366 for (auto &BB
: F
) {
1367 // As a heuristic also annotate indrectbr targets as they have a high chance
1368 // to become an irreducible loop header after the indirectbr tail
1370 if (BFI
->isIrrLoopHeader(&BB
) || isIndirectBrTarget(&BB
)) {
1371 Instruction
*TI
= BB
.getTerminator();
1372 const UseBBInfo
&BBCountInfo
= getBBInfo(&BB
);
1373 setIrrLoopHeaderMetadata(M
, TI
, BBCountInfo
.CountValue
);
1378 void SelectInstVisitor::instrumentOneSelectInst(SelectInst
&SI
) {
1379 Module
*M
= F
.getParent();
1380 IRBuilder
<> Builder(&SI
);
1381 Type
*Int64Ty
= Builder
.getInt64Ty();
1382 Type
*I8PtrTy
= Builder
.getInt8PtrTy();
1383 auto *Step
= Builder
.CreateZExt(SI
.getCondition(), Int64Ty
);
1385 Intrinsic::getDeclaration(M
, Intrinsic::instrprof_increment_step
),
1386 {ConstantExpr::getBitCast(FuncNameVar
, I8PtrTy
),
1387 Builder
.getInt64(FuncHash
), Builder
.getInt32(TotalNumCtrs
),
1388 Builder
.getInt32(*CurCtrIdx
), Step
});
1392 void SelectInstVisitor::annotateOneSelectInst(SelectInst
&SI
) {
1393 std::vector
<uint64_t> &CountFromProfile
= UseFunc
->getProfileRecord().Counts
;
1394 assert(*CurCtrIdx
< CountFromProfile
.size() &&
1395 "Out of bound access of counters");
1396 uint64_t SCounts
[2];
1397 SCounts
[0] = CountFromProfile
[*CurCtrIdx
]; // True count
1399 uint64_t TotalCount
= 0;
1400 auto BI
= UseFunc
->findBBInfo(SI
.getParent());
1402 TotalCount
= BI
->CountValue
;
1404 SCounts
[1] = (TotalCount
> SCounts
[0] ? TotalCount
- SCounts
[0] : 0);
1405 uint64_t MaxCount
= std::max(SCounts
[0], SCounts
[1]);
1407 setProfMetadata(F
.getParent(), &SI
, SCounts
, MaxCount
);
1410 void SelectInstVisitor::visitSelectInst(SelectInst
&SI
) {
1411 if (!PGOInstrSelect
)
1413 // FIXME: do not handle this yet.
1414 if (SI
.getCondition()->getType()->isVectorTy())
1422 instrumentOneSelectInst(SI
);
1425 annotateOneSelectInst(SI
);
1429 llvm_unreachable("Unknown visiting mode");
1432 void MemIntrinsicVisitor::instrumentOneMemIntrinsic(MemIntrinsic
&MI
) {
1433 Module
*M
= F
.getParent();
1434 IRBuilder
<> Builder(&MI
);
1435 Type
*Int64Ty
= Builder
.getInt64Ty();
1436 Type
*I8PtrTy
= Builder
.getInt8PtrTy();
1437 Value
*Length
= MI
.getLength();
1438 assert(!isa
<ConstantInt
>(Length
));
1440 Intrinsic::getDeclaration(M
, Intrinsic::instrprof_value_profile
),
1441 {ConstantExpr::getBitCast(FuncNameVar
, I8PtrTy
),
1442 Builder
.getInt64(FuncHash
), Builder
.CreateZExtOrTrunc(Length
, Int64Ty
),
1443 Builder
.getInt32(IPVK_MemOPSize
), Builder
.getInt32(CurCtrId
)});
1447 void MemIntrinsicVisitor::visitMemIntrinsic(MemIntrinsic
&MI
) {
1450 Value
*Length
= MI
.getLength();
1451 // Not instrument constant length calls.
1452 if (dyn_cast
<ConstantInt
>(Length
))
1460 instrumentOneMemIntrinsic(MI
);
1463 Candidates
.push_back(&MI
);
1466 llvm_unreachable("Unknown visiting mode");
1469 // Traverse all valuesites and annotate the instructions for all value kind.
1470 void PGOUseFunc::annotateValueSites() {
1471 if (DisableValueProfiling
)
1474 // Create the PGOFuncName meta data.
1475 createPGOFuncNameMetadata(F
, FuncInfo
.FuncName
);
1477 for (uint32_t Kind
= IPVK_First
; Kind
<= IPVK_Last
; ++Kind
)
1478 annotateValueSites(Kind
);
1481 static const char *ValueProfKindDescr
[] = {
1482 #define VALUE_PROF_KIND(Enumerator, Value, Descr) Descr,
1483 #include "llvm/ProfileData/InstrProfData.inc"
1486 // Annotate the instructions for a specific value kind.
1487 void PGOUseFunc::annotateValueSites(uint32_t Kind
) {
1488 assert(Kind
<= IPVK_Last
);
1489 unsigned ValueSiteIndex
= 0;
1490 auto &ValueSites
= FuncInfo
.ValueSites
[Kind
];
1491 unsigned NumValueSites
= ProfileRecord
.getNumValueSites(Kind
);
1492 if (NumValueSites
!= ValueSites
.size()) {
1493 auto &Ctx
= M
->getContext();
1494 Ctx
.diagnose(DiagnosticInfoPGOProfile(
1495 M
->getName().data(),
1496 Twine("Inconsistent number of value sites for ") +
1497 Twine(ValueProfKindDescr
[Kind
]) +
1498 Twine(" profiling in \"") + F
.getName().str() +
1499 Twine("\", possibly due to the use of a stale profile."),
1504 for (auto &I
: ValueSites
) {
1505 LLVM_DEBUG(dbgs() << "Read one value site profile (kind = " << Kind
1506 << "): Index = " << ValueSiteIndex
<< " out of "
1507 << NumValueSites
<< "\n");
1508 annotateValueSite(*M
, *I
, ProfileRecord
,
1509 static_cast<InstrProfValueKind
>(Kind
), ValueSiteIndex
,
1510 Kind
== IPVK_MemOPSize
? MaxNumMemOPAnnotations
1511 : MaxNumAnnotations
);
1516 // Collect the set of members for each Comdat in module M and store
1517 // in ComdatMembers.
1518 static void collectComdatMembers(
1520 std::unordered_multimap
<Comdat
*, GlobalValue
*> &ComdatMembers
) {
1521 if (!DoComdatRenaming
)
1523 for (Function
&F
: M
)
1524 if (Comdat
*C
= F
.getComdat())
1525 ComdatMembers
.insert(std::make_pair(C
, &F
));
1526 for (GlobalVariable
&GV
: M
.globals())
1527 if (Comdat
*C
= GV
.getComdat())
1528 ComdatMembers
.insert(std::make_pair(C
, &GV
));
1529 for (GlobalAlias
&GA
: M
.aliases())
1530 if (Comdat
*C
= GA
.getComdat())
1531 ComdatMembers
.insert(std::make_pair(C
, &GA
));
1534 static bool InstrumentAllFunctions(
1535 Module
&M
, function_ref
<BranchProbabilityInfo
*(Function
&)> LookupBPI
,
1536 function_ref
<BlockFrequencyInfo
*(Function
&)> LookupBFI
, bool IsCS
) {
1537 // For the context-sensitve instrumentation, we should have a separated pass
1538 // (before LTO/ThinLTO linking) to create these variables.
1540 createIRLevelProfileFlagVar(M
, /* IsCS */ false);
1541 std::unordered_multimap
<Comdat
*, GlobalValue
*> ComdatMembers
;
1542 collectComdatMembers(M
, ComdatMembers
);
1545 if (F
.isDeclaration())
1547 auto *BPI
= LookupBPI(F
);
1548 auto *BFI
= LookupBFI(F
);
1549 instrumentOneFunc(F
, &M
, BPI
, BFI
, ComdatMembers
, IsCS
);
1555 PGOInstrumentationGenCreateVar::run(Module
&M
, ModuleAnalysisManager
&AM
) {
1556 createProfileFileNameVar(M
, CSInstrName
);
1557 createIRLevelProfileFlagVar(M
, /* IsCS */ true);
1558 return PreservedAnalyses::all();
1561 bool PGOInstrumentationGenLegacyPass::runOnModule(Module
&M
) {
1565 auto LookupBPI
= [this](Function
&F
) {
1566 return &this->getAnalysis
<BranchProbabilityInfoWrapperPass
>(F
).getBPI();
1568 auto LookupBFI
= [this](Function
&F
) {
1569 return &this->getAnalysis
<BlockFrequencyInfoWrapperPass
>(F
).getBFI();
1571 return InstrumentAllFunctions(M
, LookupBPI
, LookupBFI
, IsCS
);
1574 PreservedAnalyses
PGOInstrumentationGen::run(Module
&M
,
1575 ModuleAnalysisManager
&AM
) {
1576 auto &FAM
= AM
.getResult
<FunctionAnalysisManagerModuleProxy
>(M
).getManager();
1577 auto LookupBPI
= [&FAM
](Function
&F
) {
1578 return &FAM
.getResult
<BranchProbabilityAnalysis
>(F
);
1581 auto LookupBFI
= [&FAM
](Function
&F
) {
1582 return &FAM
.getResult
<BlockFrequencyAnalysis
>(F
);
1585 if (!InstrumentAllFunctions(M
, LookupBPI
, LookupBFI
, IsCS
))
1586 return PreservedAnalyses::all();
1588 return PreservedAnalyses::none();
1591 static bool annotateAllFunctions(
1592 Module
&M
, StringRef ProfileFileName
, StringRef ProfileRemappingFileName
,
1593 function_ref
<BranchProbabilityInfo
*(Function
&)> LookupBPI
,
1594 function_ref
<BlockFrequencyInfo
*(Function
&)> LookupBFI
,
1595 ProfileSummaryInfo
*PSI
, bool IsCS
) {
1596 LLVM_DEBUG(dbgs() << "Read in profile counters: ");
1597 auto &Ctx
= M
.getContext();
1598 // Read the counter array from file.
1600 IndexedInstrProfReader::create(ProfileFileName
, ProfileRemappingFileName
);
1601 if (Error E
= ReaderOrErr
.takeError()) {
1602 handleAllErrors(std::move(E
), [&](const ErrorInfoBase
&EI
) {
1604 DiagnosticInfoPGOProfile(ProfileFileName
.data(), EI
.message()));
1609 std::unique_ptr
<IndexedInstrProfReader
> PGOReader
=
1610 std::move(ReaderOrErr
.get());
1612 Ctx
.diagnose(DiagnosticInfoPGOProfile(ProfileFileName
.data(),
1613 StringRef("Cannot get PGOReader")));
1616 if (!PGOReader
->hasCSIRLevelProfile() && IsCS
)
1619 // TODO: might need to change the warning once the clang option is finalized.
1620 if (!PGOReader
->isIRLevelProfile()) {
1621 Ctx
.diagnose(DiagnosticInfoPGOProfile(
1622 ProfileFileName
.data(), "Not an IR level instrumentation profile"));
1626 // Add the profile summary (read from the header of the indexed summary) here
1627 // so that we can use it below when reading counters (which checks if the
1628 // function should be marked with a cold or inlinehint attribute).
1629 M
.setProfileSummary(PGOReader
->getSummary(IsCS
).getMD(M
.getContext()),
1630 IsCS
? ProfileSummary::PSK_CSInstr
1631 : ProfileSummary::PSK_Instr
);
1633 std::unordered_multimap
<Comdat
*, GlobalValue
*> ComdatMembers
;
1634 collectComdatMembers(M
, ComdatMembers
);
1635 std::vector
<Function
*> HotFunctions
;
1636 std::vector
<Function
*> ColdFunctions
;
1638 if (F
.isDeclaration())
1640 auto *BPI
= LookupBPI(F
);
1641 auto *BFI
= LookupBFI(F
);
1642 // Split indirectbr critical edges here before computing the MST rather than
1643 // later in getInstrBB() to avoid invalidating it.
1644 SplitIndirectBrCriticalEdges(F
, BPI
, BFI
);
1645 PGOUseFunc
Func(F
, &M
, ComdatMembers
, BPI
, BFI
, PSI
, IsCS
);
1646 bool AllZeros
= false;
1647 if (!Func
.readCounters(PGOReader
.get(), AllZeros
))
1650 F
.setEntryCount(ProfileCount(0, Function::PCT_Real
));
1651 if (Func
.getProgramMaxCount() != 0)
1652 ColdFunctions
.push_back(&F
);
1655 Func
.populateCounters();
1656 Func
.setBranchWeights();
1657 Func
.annotateValueSites();
1658 Func
.annotateIrrLoopHeaderWeights();
1659 PGOUseFunc::FuncFreqAttr FreqAttr
= Func
.getFuncFreqAttr();
1660 if (FreqAttr
== PGOUseFunc::FFA_Cold
)
1661 ColdFunctions
.push_back(&F
);
1662 else if (FreqAttr
== PGOUseFunc::FFA_Hot
)
1663 HotFunctions
.push_back(&F
);
1664 if (PGOViewCounts
!= PGOVCT_None
&&
1665 (ViewBlockFreqFuncName
.empty() ||
1666 F
.getName().equals(ViewBlockFreqFuncName
))) {
1667 LoopInfo LI
{DominatorTree(F
)};
1668 std::unique_ptr
<BranchProbabilityInfo
> NewBPI
=
1669 std::make_unique
<BranchProbabilityInfo
>(F
, LI
);
1670 std::unique_ptr
<BlockFrequencyInfo
> NewBFI
=
1671 std::make_unique
<BlockFrequencyInfo
>(F
, *NewBPI
, LI
);
1672 if (PGOViewCounts
== PGOVCT_Graph
)
1674 else if (PGOViewCounts
== PGOVCT_Text
) {
1675 dbgs() << "pgo-view-counts: " << Func
.getFunc().getName() << "\n";
1676 NewBFI
->print(dbgs());
1679 if (PGOViewRawCounts
!= PGOVCT_None
&&
1680 (ViewBlockFreqFuncName
.empty() ||
1681 F
.getName().equals(ViewBlockFreqFuncName
))) {
1682 if (PGOViewRawCounts
== PGOVCT_Graph
)
1683 if (ViewBlockFreqFuncName
.empty())
1684 WriteGraph(&Func
, Twine("PGORawCounts_") + Func
.getFunc().getName());
1686 ViewGraph(&Func
, Twine("PGORawCounts_") + Func
.getFunc().getName());
1687 else if (PGOViewRawCounts
== PGOVCT_Text
) {
1688 dbgs() << "pgo-view-raw-counts: " << Func
.getFunc().getName() << "\n";
1694 // Set function hotness attribute from the profile.
1695 // We have to apply these attributes at the end because their presence
1696 // can affect the BranchProbabilityInfo of any callers, resulting in an
1697 // inconsistent MST between prof-gen and prof-use.
1698 for (auto &F
: HotFunctions
) {
1699 F
->addFnAttr(Attribute::InlineHint
);
1700 LLVM_DEBUG(dbgs() << "Set inline attribute to function: " << F
->getName()
1703 for (auto &F
: ColdFunctions
) {
1704 F
->addFnAttr(Attribute::Cold
);
1705 LLVM_DEBUG(dbgs() << "Set cold attribute to function: " << F
->getName()
1711 PGOInstrumentationUse::PGOInstrumentationUse(std::string Filename
,
1712 std::string RemappingFilename
,
1714 : ProfileFileName(std::move(Filename
)),
1715 ProfileRemappingFileName(std::move(RemappingFilename
)), IsCS(IsCS
) {
1716 if (!PGOTestProfileFile
.empty())
1717 ProfileFileName
= PGOTestProfileFile
;
1718 if (!PGOTestProfileRemappingFile
.empty())
1719 ProfileRemappingFileName
= PGOTestProfileRemappingFile
;
1722 PreservedAnalyses
PGOInstrumentationUse::run(Module
&M
,
1723 ModuleAnalysisManager
&AM
) {
1725 auto &FAM
= AM
.getResult
<FunctionAnalysisManagerModuleProxy
>(M
).getManager();
1726 auto LookupBPI
= [&FAM
](Function
&F
) {
1727 return &FAM
.getResult
<BranchProbabilityAnalysis
>(F
);
1730 auto LookupBFI
= [&FAM
](Function
&F
) {
1731 return &FAM
.getResult
<BlockFrequencyAnalysis
>(F
);
1734 auto *PSI
= &AM
.getResult
<ProfileSummaryAnalysis
>(M
);
1736 if (!annotateAllFunctions(M
, ProfileFileName
, ProfileRemappingFileName
,
1737 LookupBPI
, LookupBFI
, PSI
, IsCS
))
1738 return PreservedAnalyses::all();
1740 return PreservedAnalyses::none();
1743 bool PGOInstrumentationUseLegacyPass::runOnModule(Module
&M
) {
1747 auto LookupBPI
= [this](Function
&F
) {
1748 return &this->getAnalysis
<BranchProbabilityInfoWrapperPass
>(F
).getBPI();
1750 auto LookupBFI
= [this](Function
&F
) {
1751 return &this->getAnalysis
<BlockFrequencyInfoWrapperPass
>(F
).getBFI();
1754 auto *PSI
= &getAnalysis
<ProfileSummaryInfoWrapperPass
>().getPSI();
1755 return annotateAllFunctions(M
, ProfileFileName
, "", LookupBPI
, LookupBFI
, PSI
,
1759 static std::string
getSimpleNodeName(const BasicBlock
*Node
) {
1760 if (!Node
->getName().empty())
1761 return Node
->getName();
1763 std::string SimpleNodeName
;
1764 raw_string_ostream
OS(SimpleNodeName
);
1765 Node
->printAsOperand(OS
, false);
1769 void llvm::setProfMetadata(Module
*M
, Instruction
*TI
,
1770 ArrayRef
<uint64_t> EdgeCounts
,
1771 uint64_t MaxCount
) {
1772 MDBuilder
MDB(M
->getContext());
1773 assert(MaxCount
> 0 && "Bad max count");
1774 uint64_t Scale
= calculateCountScale(MaxCount
);
1775 SmallVector
<unsigned, 4> Weights
;
1776 for (const auto &ECI
: EdgeCounts
)
1777 Weights
.push_back(scaleBranchCount(ECI
, Scale
));
1779 LLVM_DEBUG(dbgs() << "Weight is: "; for (const auto &W
1784 misexpect::verifyMisExpect(TI
, Weights
, TI
->getContext());
1786 TI
->setMetadata(LLVMContext::MD_prof
, MDB
.createBranchWeights(Weights
));
1787 if (EmitBranchProbability
) {
1788 std::string BrCondStr
= getBranchCondString(TI
);
1789 if (BrCondStr
.empty())
1793 std::accumulate(Weights
.begin(), Weights
.end(), (uint64_t)0,
1794 [](uint64_t w1
, uint64_t w2
) { return w1
+ w2
; });
1795 uint64_t TotalCount
=
1796 std::accumulate(EdgeCounts
.begin(), EdgeCounts
.end(), (uint64_t)0,
1797 [](uint64_t c1
, uint64_t c2
) { return c1
+ c2
; });
1798 Scale
= calculateCountScale(WSum
);
1799 BranchProbability
BP(scaleBranchCount(Weights
[0], Scale
),
1800 scaleBranchCount(WSum
, Scale
));
1801 std::string BranchProbStr
;
1802 raw_string_ostream
OS(BranchProbStr
);
1804 OS
<< " (total count : " << TotalCount
<< ")";
1806 Function
*F
= TI
->getParent()->getParent();
1807 OptimizationRemarkEmitter
ORE(F
);
1809 return OptimizationRemark(DEBUG_TYPE
, "pgo-instrumentation", TI
)
1810 << BrCondStr
<< " is true with probability : " << BranchProbStr
;
1817 void setIrrLoopHeaderMetadata(Module
*M
, Instruction
*TI
, uint64_t Count
) {
1818 MDBuilder
MDB(M
->getContext());
1819 TI
->setMetadata(llvm::LLVMContext::MD_irr_loop
,
1820 MDB
.createIrrLoopHeaderWeight(Count
));
1823 template <> struct GraphTraits
<PGOUseFunc
*> {
1824 using NodeRef
= const BasicBlock
*;
1825 using ChildIteratorType
= succ_const_iterator
;
1826 using nodes_iterator
= pointer_iterator
<Function::const_iterator
>;
1828 static NodeRef
getEntryNode(const PGOUseFunc
*G
) {
1829 return &G
->getFunc().front();
1832 static ChildIteratorType
child_begin(const NodeRef N
) {
1833 return succ_begin(N
);
1836 static ChildIteratorType
child_end(const NodeRef N
) { return succ_end(N
); }
1838 static nodes_iterator
nodes_begin(const PGOUseFunc
*G
) {
1839 return nodes_iterator(G
->getFunc().begin());
1842 static nodes_iterator
nodes_end(const PGOUseFunc
*G
) {
1843 return nodes_iterator(G
->getFunc().end());
1847 template <> struct DOTGraphTraits
<PGOUseFunc
*> : DefaultDOTGraphTraits
{
1848 explicit DOTGraphTraits(bool isSimple
= false)
1849 : DefaultDOTGraphTraits(isSimple
) {}
1851 static std::string
getGraphName(const PGOUseFunc
*G
) {
1852 return G
->getFunc().getName();
1855 std::string
getNodeLabel(const BasicBlock
*Node
, const PGOUseFunc
*Graph
) {
1857 raw_string_ostream
OS(Result
);
1859 OS
<< getSimpleNodeName(Node
) << ":\\l";
1860 UseBBInfo
*BI
= Graph
->findBBInfo(Node
);
1862 if (BI
&& BI
->CountValid
)
1863 OS
<< BI
->CountValue
<< "\\l";
1867 if (!PGOInstrSelect
)
1870 for (auto BI
= Node
->begin(); BI
!= Node
->end(); ++BI
) {
1872 if (!isa
<SelectInst
>(I
))
1874 // Display scaled counts for SELECT instruction:
1875 OS
<< "SELECT : { T = ";
1877 bool HasProf
= I
->extractProfMetadata(TC
, FC
);
1879 OS
<< "Unknown, F = Unknown }\\l";
1881 OS
<< TC
<< ", F = " << FC
<< " }\\l";
1887 } // end namespace llvm