LLVM 24.0.0git
PGOInstrumentation.cpp
Go to the documentation of this file.
1//===- PGOInstrumentation.cpp - MST-based PGO Instrumentation -------------===//
2//
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
6//
7//===----------------------------------------------------------------------===//
8//
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.
19//
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.
24//
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
28// profiling.
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.
32//
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.
40//
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).
47//
48//===----------------------------------------------------------------------===//
49
52#include "llvm/ADT/APInt.h"
53#include "llvm/ADT/ArrayRef.h"
54#include "llvm/ADT/STLExtras.h"
56#include "llvm/ADT/Statistic.h"
57#include "llvm/ADT/StringRef.h"
58#include "llvm/ADT/StringSet.h"
59#include "llvm/ADT/Twine.h"
60#include "llvm/ADT/iterator.h"
64#include "llvm/Analysis/CFG.h"
69#include "llvm/IR/Attributes.h"
70#include "llvm/IR/BasicBlock.h"
71#include "llvm/IR/CFG.h"
72#include "llvm/IR/Comdat.h"
73#include "llvm/IR/Constant.h"
74#include "llvm/IR/Constants.h"
75#include "llvm/IR/CycleInfo.h"
77#include "llvm/IR/Dominators.h"
79#include "llvm/IR/Function.h"
80#include "llvm/IR/GlobalAlias.h"
81#include "llvm/IR/GlobalValue.h"
83#include "llvm/IR/IRBuilder.h"
84#include "llvm/IR/InstVisitor.h"
85#include "llvm/IR/InstrTypes.h"
86#include "llvm/IR/Instruction.h"
89#include "llvm/IR/Intrinsics.h"
90#include "llvm/IR/LLVMContext.h"
91#include "llvm/IR/MDBuilder.h"
92#include "llvm/IR/Module.h"
93#include "llvm/IR/PassManager.h"
96#include "llvm/IR/Type.h"
97#include "llvm/IR/Value.h"
101#include "llvm/Support/CRC.h"
102#include "llvm/Support/Casting.h"
106#include "llvm/Support/Debug.h"
107#include "llvm/Support/Error.h"
119#include <algorithm>
120#include <cassert>
121#include <cstdint>
122#include <memory>
123#include <numeric>
124#include <optional>
125#include <stack>
126#include <string>
127#include <unordered_map>
128#include <utility>
129#include <vector>
130
131using namespace llvm;
133
134#define DEBUG_TYPE "pgo-instrumentation"
135
136STATISTIC(NumOfPGOInstrument, "Number of edges instrumented.");
137STATISTIC(NumOfPGOSelectInsts, "Number of select instruction instrumented.");
138STATISTIC(NumOfPGOMemIntrinsics, "Number of mem intrinsics instrumented.");
139STATISTIC(NumOfPGOEdge, "Number of edges.");
140STATISTIC(NumOfPGOBB, "Number of basic-blocks.");
141STATISTIC(NumOfPGOSplit, "Number of critical edge splits.");
142STATISTIC(NumOfPGOFunc, "Number of functions having valid profile counts.");
143STATISTIC(NumOfPGOMismatch, "Number of functions having mismatch profile.");
144STATISTIC(NumOfPGOMissing, "Number of functions without profile.");
145STATISTIC(NumOfPGOICall, "Number of indirect call value instrumentations.");
146STATISTIC(NumOfCSPGOInstrument, "Number of edges instrumented in CSPGO.");
147STATISTIC(NumOfCSPGOSelectInsts,
148 "Number of select instruction instrumented in CSPGO.");
149STATISTIC(NumOfCSPGOMemIntrinsics,
150 "Number of mem intrinsics instrumented in CSPGO.");
151STATISTIC(NumOfCSPGOEdge, "Number of edges in CSPGO.");
152STATISTIC(NumOfCSPGOBB, "Number of basic-blocks in CSPGO.");
153STATISTIC(NumOfCSPGOSplit, "Number of critical edge splits in CSPGO.");
154STATISTIC(NumOfCSPGOFunc,
155 "Number of functions having valid profile counts in CSPGO.");
156STATISTIC(NumOfCSPGOMismatch,
157 "Number of functions having mismatch profile in CSPGO.");
158STATISTIC(NumOfCSPGOMissing, "Number of functions without profile in CSPGO.");
159STATISTIC(NumCoveredBlocks, "Number of basic blocks that were executed");
160
161// Command line option to specify the file to read profile from. This is
162// mainly used for testing.
164 "pgo-test-profile-file", cl::init(""), cl::Hidden,
165 cl::value_desc("filename"),
166 cl::desc("Specify the path of profile data file. This is "
167 "mainly for test purpose."));
169 "pgo-test-profile-remapping-file", cl::init(""), cl::Hidden,
170 cl::value_desc("filename"),
171 cl::desc("Specify the path of profile remapping file. This is mainly for "
172 "test purpose."));
173
174// Command line option to disable value profiling. The default is false:
175// i.e. value profiling is enabled by default. This is for debug purpose.
176static cl::opt<bool> DisableValueProfiling("disable-vp", cl::init(false),
178 cl::desc("Disable Value Profiling"));
179
180// Command line option to set the maximum number of VP annotations to write to
181// the metadata for a single indirect call callsite.
183 "icp-max-annotations", cl::init(3), cl::Hidden,
184 cl::desc("Max number of annotations for a single indirect "
185 "call callsite"));
186
187// Command line option to set the maximum number of value annotations
188// to write to the metadata for a single memop intrinsic.
190 "memop-max-annotations", cl::init(4), cl::Hidden,
191 cl::desc("Max number of precise value annotations for a single memop"
192 "intrinsic"));
193
194// Command line option to control appending FunctionHash to the name of a COMDAT
195// function. This is to avoid the hash mismatch caused by the preinliner.
197 "do-comdat-renaming", cl::init(false), cl::Hidden,
198 cl::desc("Append function hash to the name of COMDAT function to avoid "
199 "function hash mismatch due to the preinliner"));
200
201namespace llvm {
202// Command line option to enable/disable the warning about missing profile
203// information.
204cl::opt<bool> PGOWarnMissing("pgo-warn-missing-function", cl::init(false),
206 cl::desc("Use this option to turn on/off "
207 "warnings about missing profile data for "
208 "functions."));
209
210// Command line option to enable/disable the warning about a hash mismatch in
211// the profile data.
213 NoPGOWarnMismatch("no-pgo-warn-mismatch", cl::init(false), cl::Hidden,
214 cl::desc("Use this option to turn off/on "
215 "warnings about profile cfg mismatch."));
216
217// Command line option to enable/disable the warning about a hash mismatch in
218// the profile data for Comdat functions, which often turns out to be false
219// positive due to the pre-instrumentation inline.
221 "no-pgo-warn-mismatch-comdat-weak", cl::init(true), cl::Hidden,
222 cl::desc("The option is used to turn on/off "
223 "warnings about hash mismatch for comdat "
224 "or weak functions."));
225
226// Command line option to enable/disable select instruction instrumentation.
227static cl::opt<bool>
228 PGOInstrSelect("pgo-instr-select", cl::init(true), cl::Hidden,
229 cl::desc("Use this option to turn on/off SELECT "
230 "instruction instrumentation. "));
231
232// Command line option to turn on CFG dot or text dump of raw profile counts
234 "pgo-view-raw-counts", cl::Hidden,
235 cl::desc("A boolean option to show CFG dag or text "
236 "with raw profile counts from "
237 "profile data. See also option "
238 "-pgo-view-counts. To limit graph "
239 "display to only one function, use "
240 "filtering option -view-bfi-func-name."),
241 cl::values(clEnumValN(PGOVCT_None, "none", "do not show."),
242 clEnumValN(PGOVCT_Graph, "graph", "show a graph."),
243 clEnumValN(PGOVCT_Text, "text", "show in text.")));
244
245// Command line option to enable/disable memop intrinsic call.size profiling.
246static cl::opt<bool>
247 PGOInstrMemOP("pgo-instr-memop", cl::init(true), cl::Hidden,
248 cl::desc("Use this option to turn on/off "
249 "memory intrinsic size profiling."));
250
251// Emit branch probability as optimization remarks.
252static cl::opt<bool>
253 EmitBranchProbability("pgo-emit-branch-prob", cl::init(false), cl::Hidden,
254 cl::desc("When this option is on, the annotated "
255 "branch probability will be emitted as "
256 "optimization remarks: -{Rpass|"
257 "pass-remarks}=pgo-instrumentation"));
258
260 "pgo-instrument-entry", cl::init(false), cl::Hidden,
261 cl::desc("Force to instrument function entry basicblock."));
262
263static cl::opt<bool>
264 PGOInstrumentLoopEntries("pgo-instrument-loop-entries", cl::init(false),
266 cl::desc("Force to instrument loop entries."));
267
269 "pgo-function-entry-coverage", cl::Hidden,
270 cl::desc(
271 "Use this option to enable function entry coverage instrumentation."));
272
274 "pgo-block-coverage",
275 cl::desc("Use this option to enable basic block coverage instrumentation"));
276
277static cl::opt<bool>
278 PGOViewBlockCoverageGraph("pgo-view-block-coverage-graph",
279 cl::desc("Create a dot file of CFGs with block "
280 "coverage inference information"));
281
283 "pgo-temporal-instrumentation",
284 cl::desc("Use this option to enable temporal instrumentation"));
285
286static cl::opt<bool>
287 PGOFixEntryCount("pgo-fix-entry-count", cl::init(true), cl::Hidden,
288 cl::desc("Fix function entry count in profile use."));
289
291 "pgo-verify-hot-bfi", cl::init(false), cl::Hidden,
292 cl::desc("Print out the non-match BFI count if a hot raw profile count "
293 "becomes non-hot, or a cold raw profile count becomes hot. "
294 "The print is enabled under -Rpass-analysis=pgo, or "
295 "internal option -pass-remarks-analysis=pgo."));
296
298 "pgo-verify-bfi", cl::init(false), cl::Hidden,
299 cl::desc("Print out mismatched BFI counts after setting profile metadata "
300 "The print is enabled under -Rpass-analysis=pgo, or "
301 "internal option -pass-remarks-analysis=pgo."));
302
304 "pgo-verify-bfi-ratio", cl::init(2), cl::Hidden,
305 cl::desc("Set the threshold for pgo-verify-bfi: only print out "
306 "mismatched BFI if the difference percentage is greater than "
307 "this value (in percentage)."));
308
310 "pgo-verify-bfi-cutoff", cl::init(5), cl::Hidden,
311 cl::desc("Set the threshold for pgo-verify-bfi: skip the counts whose "
312 "profile count value is below."));
313
315 "pgo-trace-func-hash", cl::init("-"), cl::Hidden,
316 cl::value_desc("function name"),
317 cl::desc("Trace the hash of the function with this name."));
318
320 "pgo-function-size-threshold", cl::Hidden,
321 cl::desc("Do not instrument functions smaller than this threshold."));
322
324 "pgo-critical-edge-threshold", cl::init(20000), cl::Hidden,
325 cl::desc("Do not instrument functions with the number of critical edges "
326 " greater than this threshold."));
327
329 "pgo-cold-instrument-entry-threshold", cl::init(0), cl::Hidden,
330 cl::desc("For cold function instrumentation, skip instrumenting functions "
331 "whose entry count is above the given value."));
332
334 "pgo-treat-unknown-as-cold", cl::init(false), cl::Hidden,
335 cl::desc("For cold function instrumentation, treat count unknown(e.g. "
336 "unprofiled) functions as cold."));
337
339 "pgo-instrument-cold-function-only", cl::init(false), cl::Hidden,
340 cl::desc("Enable cold function only instrumentation."));
341
343 "ctx-prof-skip-callsite-instr", cl::Hidden,
344 cl::desc("Do not instrument callsites to functions in this list. Intended "
345 "for testing."));
346
348
349// Command line option to turn on CFG dot dump after profile annotation.
350// Defined in Analysis/BlockFrequencyInfo.cpp: -pgo-view-counts
352
353// Command line option to specify the name of the function for CFG dump
354// Defined in Analysis/BlockFrequencyInfo.cpp: -view-bfi-func-name=
356
357// Command line option to enable vtable value profiling. Defined in
358// ProfileData/InstrProf.cpp: -enable-vtable-value-profiling=
363} // namespace llvm
364
365namespace {
366class FunctionInstrumenter final {
367 Module &M;
368 Function &F;
370 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers;
371 BranchProbabilityInfo *const BPI;
372 BlockFrequencyInfo *const BFI;
373 LoopInfo *const LI;
374
375 const PGOInstrumentationType InstrumentationType;
376
377 // FIXME(mtrofin): re-enable this for ctx profiling, for non-indirect calls.
378 // Ctx profiling implicitly captures indirect call cases, but not other
379 // values. Supporting other values is relatively straight-forward - just
380 // another counter range within the context.
381 bool isValueProfilingDisabled() const {
382 // Value profiling is disabled for GPU targets because the device-side
383 // profiling runtime does not yet implement
384 // __llvm_profile_instrument_target. The existing compiler-rt implementation
385 // uses a linked-list with locks and eviction policy that is not efficient
386 // for massively parallel GPU execution. A GPU-optimized implementation is
387 // left as future work.
388 return DisableValueProfiling ||
389 InstrumentationType == PGOInstrumentationType::CTXPROF ||
391 }
392
393 bool shouldInstrumentEntryBB() const {
394 return PGOInstrumentEntry ||
395 InstrumentationType == PGOInstrumentationType::CTXPROF;
396 }
397
398 bool shouldInstrumentLoopEntries() const { return PGOInstrumentLoopEntries; }
399
400public:
401 FunctionInstrumenter(
403 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers,
404 BranchProbabilityInfo *BPI = nullptr, BlockFrequencyInfo *BFI = nullptr,
405 LoopInfo *LI = nullptr,
407 : M(M), F(F), TLI(TLI), ComdatMembers(ComdatMembers), BPI(BPI), BFI(BFI),
408 LI(LI), InstrumentationType(InstrumentationType) {}
409
410 void instrument();
411};
412} // namespace
413
414// Return a string describing the branch condition that can be
415// used in static branch probability heuristics:
416static std::string getBranchCondString(Instruction *TI) {
418 if (!BI)
419 return std::string();
420
421 Value *Cond = BI->getCondition();
423 if (!CI)
424 return std::string();
425
426 std::string result;
427 raw_string_ostream OS(result);
428 OS << CI->getPredicate() << "_";
429 CI->getOperand(0)->getType()->print(OS, true);
430
431 Value *RHS = CI->getOperand(1);
433 if (CV) {
434 if (CV->isZero())
435 OS << "_Zero";
436 else if (CV->isOne())
437 OS << "_One";
438 else if (CV->isMinusOne())
439 OS << "_MinusOne";
440 else
441 OS << "_Const";
442 }
443 return result;
444}
445
446static const char *ValueProfKindDescr[] = {
447#define VALUE_PROF_KIND(Enumerator, Value, Descr) Descr,
449};
450
451// Create a COMDAT variable INSTR_PROF_RAW_VERSION_VAR to make the runtime
452// aware this is an ir_level profile so it can set the version flag.
453static GlobalVariable *
455 PGOInstrumentationType InstrumentationType) {
457 Type *IntTy64 = Type::getInt64Ty(M.getContext());
459 if (InstrumentationType == PGOInstrumentationType::CSFDO)
460 ProfileVersion |= VARIANT_MASK_CSIR_PROF;
461 if (PGOInstrumentEntry ||
462 InstrumentationType == PGOInstrumentationType::CTXPROF)
463 ProfileVersion |= VARIANT_MASK_INSTR_ENTRY;
465 ProfileVersion |= VARIANT_MASK_INSTR_LOOP_ENTRIES;
467 ProfileVersion |= VARIANT_MASK_DBG_CORRELATE;
469 ProfileVersion |=
472 ProfileVersion |= VARIANT_MASK_BYTE_COVERAGE;
474 ProfileVersion |= VARIANT_MASK_TEMPORAL_PROF;
475 auto IRLevelVersionVariable = new GlobalVariable(
476 M, IntTy64, true, GlobalValue::WeakAnyLinkage,
477 Constant::getIntegerValue(IntTy64, APInt(64, ProfileVersion)), VarName);
478 IRLevelVersionVariable->setVisibility(GlobalValue::HiddenVisibility);
479
480 Triple TT(M.getTargetTriple());
481 if (TT.supportsCOMDAT()) {
482 IRLevelVersionVariable->setLinkage(GlobalValue::ExternalLinkage);
483 IRLevelVersionVariable->setComdat(M.getOrInsertComdat(VarName));
484 }
485 return IRLevelVersionVariable;
486}
487
488namespace {
489
490/// The select instruction visitor plays three roles specified
491/// by the mode. In \c VM_counting mode, it simply counts the number of
492/// select instructions. In \c VM_instrument mode, it inserts code to count
493/// the number times TrueValue of select is taken. In \c VM_annotate mode,
494/// it reads the profile data and annotate the select instruction with metadata.
495enum VisitMode { VM_counting, VM_instrument, VM_annotate };
496class PGOUseFunc;
497
498/// Instruction Visitor class to visit select instructions.
499struct SelectInstVisitor : public InstVisitor<SelectInstVisitor> {
500 Function &F;
501 unsigned NSIs = 0; // Number of select instructions instrumented.
502 VisitMode Mode = VM_counting; // Visiting mode.
503 unsigned *CurCtrIdx = nullptr; // Pointer to current counter index.
504 unsigned TotalNumCtrs = 0; // Total number of counters
505 GlobalValue *FuncNameVar = nullptr;
506 uint64_t FuncHash = 0;
507 PGOUseFunc *UseFunc = nullptr;
508 bool HasSingleByteCoverage;
509
510 SelectInstVisitor(Function &Func, bool HasSingleByteCoverage)
511 : F(Func), HasSingleByteCoverage(HasSingleByteCoverage) {}
512
513 void countSelects() {
514 NSIs = 0;
515 Mode = VM_counting;
516 visit(F);
517 }
518
519 // Visit the IR stream and instrument all select instructions. \p
520 // Ind is a pointer to the counter index variable; \p TotalNC
521 // is the total number of counters; \p FNV is the pointer to the
522 // PGO function name var; \p FHash is the function hash.
523 void instrumentSelects(unsigned *Ind, unsigned TotalNC, GlobalValue *FNV,
524 uint64_t FHash) {
525 Mode = VM_instrument;
526 CurCtrIdx = Ind;
527 TotalNumCtrs = TotalNC;
528 FuncHash = FHash;
529 FuncNameVar = FNV;
530 visit(F);
531 }
532
533 // Visit the IR stream and annotate all select instructions.
534 void annotateSelects(PGOUseFunc *UF, unsigned *Ind) {
535 Mode = VM_annotate;
536 UseFunc = UF;
537 CurCtrIdx = Ind;
538 visit(F);
539 }
540
541 void instrumentOneSelectInst(SelectInst &SI);
542 void annotateOneSelectInst(SelectInst &SI);
543
544 // Visit \p SI instruction and perform tasks according to visit mode.
545 void visitSelectInst(SelectInst &SI);
546
547 // Return the number of select instructions. This needs be called after
548 // countSelects().
549 unsigned getNumOfSelectInsts() const { return NSIs; }
550};
551
552/// This class implements the CFG edges for the Minimum Spanning Tree (MST)
553/// based instrumentation.
554/// Note that the CFG can be a multi-graph. So there might be multiple edges
555/// with the same SrcBB and DestBB.
556struct PGOEdge {
557 BasicBlock *SrcBB;
558 BasicBlock *DestBB;
559 uint64_t Weight;
560 bool InMST = false;
561 bool Removed = false;
562 bool IsCritical = false;
563
564 PGOEdge(BasicBlock *Src, BasicBlock *Dest, uint64_t W = 1)
565 : SrcBB(Src), DestBB(Dest), Weight(W) {}
566
567 /// Return the information string of an edge.
568 std::string infoString() const {
569 return (Twine(Removed ? "-" : " ") + (InMST ? " " : "*") +
570 (IsCritical ? "c" : " ") + " W=" + Twine(Weight))
571 .str();
572 }
573};
574
575/// This class stores the auxiliary information for each BB in the MST.
576struct PGOBBInfo {
577 PGOBBInfo *Group;
578 uint32_t Index;
579 uint32_t Rank = 0;
580
581 PGOBBInfo(unsigned IX) : Group(this), Index(IX) {}
582
583 /// Return the information string of this object.
584 std::string infoString() const {
585 return (Twine("Index=") + Twine(Index)).str();
586 }
587};
588
589// This class implements the CFG edges. Note the CFG can be a multi-graph.
590template <class Edge, class BBInfo> class FuncPGOInstrumentation {
591private:
592 Function &F;
593
594 // Is this is context-sensitive instrumentation.
595 bool IsCS;
596
597 // A map that stores the Comdat group in function F.
598 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers;
599
600 ValueProfileCollector VPC;
601
602 void computeCFGHash();
603 void renameComdatFunction();
604
605public:
606 const TargetLibraryInfo &TLI;
607 std::vector<std::vector<VPCandidateInfo>> ValueSites;
608 SelectInstVisitor SIVisitor;
609 std::string FuncName;
610 std::string DeprecatedFuncName;
611 GlobalVariable *FuncNameVar;
612
613 // CFG hash value for this function.
614 uint64_t FunctionHash = 0;
615
616 // The Minimum Spanning Tree of function CFG.
617 CFGMST<Edge, BBInfo> MST;
618
619 const std::optional<BlockCoverageInference> BCI;
620
621 static std::optional<BlockCoverageInference>
622 constructBCI(Function &Func, bool HasSingleByteCoverage,
623 bool InstrumentFuncEntry) {
624 if (HasSingleByteCoverage)
625 return BlockCoverageInference(Func, InstrumentFuncEntry);
626 return {};
627 }
628
629 // Collect all the BBs that will be instrumented, and store them in
630 // InstrumentBBs.
631 void getInstrumentBBs(std::vector<BasicBlock *> &InstrumentBBs);
632
633 // Give an edge, find the BB that will be instrumented.
634 // Return nullptr if there is no BB to be instrumented.
636
637 // Return the auxiliary BB information.
638 BBInfo &getBBInfo(const BasicBlock *BB) const { return MST.getBBInfo(BB); }
639
640 // Return the auxiliary BB information if available.
641 BBInfo *findBBInfo(const BasicBlock *BB) const { return MST.findBBInfo(BB); }
642
643 // Dump edges and BB information.
644 void dumpInfo(StringRef Str = "") const {
645 MST.dumpEdges(dbgs(), Twine("Dump Function ") + FuncName +
646 " Hash: " + Twine(FunctionHash) + "\t" + Str);
647 }
648
649 FuncPGOInstrumentation(
650 Function &Func, TargetLibraryInfo &TLI,
651 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers,
652 bool CreateGlobalVar = false, BranchProbabilityInfo *BPI = nullptr,
653 BlockFrequencyInfo *BFI = nullptr, LoopInfo *LI = nullptr,
654 bool IsCS = false, bool InstrumentFuncEntry = true,
655 bool InstrumentLoopEntries = false, bool HasSingleByteCoverage = false)
656 : F(Func), IsCS(IsCS), ComdatMembers(ComdatMembers), VPC(Func, TLI),
657 TLI(TLI), ValueSites(IPVK_Last + 1),
658 SIVisitor(Func, HasSingleByteCoverage),
659 MST(F, InstrumentFuncEntry, InstrumentLoopEntries, BPI, BFI, LI),
660 BCI(constructBCI(Func, HasSingleByteCoverage, InstrumentFuncEntry)) {
661 if (BCI && PGOViewBlockCoverageGraph)
662 BCI->viewBlockCoverageGraph();
663 // This should be done before CFG hash computation.
664 SIVisitor.countSelects();
665 ValueSites[IPVK_MemOPSize] = VPC.get(IPVK_MemOPSize);
666 if (!IsCS) {
667 NumOfPGOSelectInsts += SIVisitor.getNumOfSelectInsts();
668 NumOfPGOMemIntrinsics += ValueSites[IPVK_MemOPSize].size();
669 NumOfPGOBB += MST.bbInfoSize();
670 ValueSites[IPVK_IndirectCallTarget] = VPC.get(IPVK_IndirectCallTarget);
672 ValueSites[IPVK_VTableTarget] = VPC.get(IPVK_VTableTarget);
673 } else {
674 NumOfCSPGOSelectInsts += SIVisitor.getNumOfSelectInsts();
675 NumOfCSPGOMemIntrinsics += ValueSites[IPVK_MemOPSize].size();
676 NumOfCSPGOBB += MST.bbInfoSize();
677 }
678
679 FuncName = getIRPGOFuncName(F);
680 DeprecatedFuncName = getPGOFuncName(F);
681 computeCFGHash();
682 if (!ComdatMembers.empty())
683 renameComdatFunction();
684 LLVM_DEBUG(dumpInfo("after CFGMST"));
685
686 for (const auto &E : MST.allEdges()) {
687 if (E->Removed)
688 continue;
689 IsCS ? NumOfCSPGOEdge++ : NumOfPGOEdge++;
690 if (!E->InMST)
691 IsCS ? NumOfCSPGOInstrument++ : NumOfPGOInstrument++;
692 }
693
694 if (CreateGlobalVar)
695 FuncNameVar = createPGOFuncNameVar(F, FuncName);
696 }
697};
698
699} // end anonymous namespace
700
701// Compute Hash value for the CFG: the lower 32 bits are CRC32 of the index
702// value of each BB in the CFG. The higher 32 bits are the CRC32 of the numbers
703// of selects, indirect calls, mem ops and edges.
704template <class Edge, class BBInfo>
705void FuncPGOInstrumentation<Edge, BBInfo>::computeCFGHash() {
706 std::vector<uint8_t> Indexes;
707 JamCRC JC;
708 for (auto &BB : F) {
709 for (BasicBlock *Succ : successors(&BB)) {
710 auto BI = findBBInfo(Succ);
711 if (BI == nullptr)
712 continue;
713 uint32_t Index = BI->Index;
714 for (int J = 0; J < 4; J++)
715 Indexes.push_back((uint8_t)(Index >> (J * 8)));
716 }
717 }
718 JC.update(Indexes);
719
720 JamCRC JCH;
721 // The higher 32 bits.
722 auto updateJCH = [&JCH](uint64_t Num) {
723 uint8_t Data[8];
725 JCH.update(Data);
726 };
727 updateJCH((uint64_t)SIVisitor.getNumOfSelectInsts());
728 updateJCH((uint64_t)ValueSites[IPVK_IndirectCallTarget].size());
729 updateJCH((uint64_t)ValueSites[IPVK_MemOPSize].size());
730 if (BCI) {
731 updateJCH(BCI->getInstrumentedBlocksHash());
732 } else {
733 updateJCH((uint64_t)MST.numEdges());
734 }
735
736 // Hash format for context sensitive profile. Reserve 4 bits for other
737 // information.
738 FunctionHash = (((uint64_t)JCH.getCRC()) << 28) + JC.getCRC();
739
740 // Reserve bit 60-63 for other information purpose.
742 if (IsCS)
744 LLVM_DEBUG(dbgs() << "Function Hash Computation for " << F.getName() << ":\n"
745 << " CRC = " << JC.getCRC()
746 << ", Selects = " << SIVisitor.getNumOfSelectInsts()
747 << ", Edges = " << MST.numEdges() << ", ICSites = "
748 << ValueSites[IPVK_IndirectCallTarget].size()
749 << ", Memops = " << ValueSites[IPVK_MemOPSize].size()
750 << ", High32 CRC = " << JCH.getCRC()
751 << ", Hash = " << FunctionHash << "\n";);
752
753 if (PGOTraceFuncHash != "-" && F.getName().contains(PGOTraceFuncHash))
754 dbgs() << "Funcname=" << F.getName() << ", Hash=" << FunctionHash
755 << " in building " << F.getParent()->getSourceFileName() << "\n";
756}
757
758// Check if we can safely rename this Comdat function.
759static bool canRenameComdat(
760 Function &F,
761 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers) {
762 if (!DoComdatRenaming || !canRenameComdatFunc(F, true))
763 return false;
764
765 // FIXME: Current only handle those Comdat groups that only containing one
766 // function.
767 // (1) For a Comdat group containing multiple functions, we need to have a
768 // unique postfix based on the hashes for each function. There is a
769 // non-trivial code refactoring to do this efficiently.
770 // (2) Variables can not be renamed, so we can not rename Comdat function in a
771 // group including global vars.
772 Comdat *C = F.getComdat();
773 for (auto &&CM : make_range(ComdatMembers.equal_range(C))) {
774 assert(!isa<GlobalAlias>(CM.second));
775 Function *FM = dyn_cast<Function>(CM.second);
776 if (FM != &F)
777 return false;
778 }
779 return true;
780}
781
782// Append the CFGHash to the Comdat function name.
783template <class Edge, class BBInfo>
784void FuncPGOInstrumentation<Edge, BBInfo>::renameComdatFunction() {
785 if (!canRenameComdat(F, ComdatMembers))
786 return;
787 std::string OrigName = F.getName().str();
788 std::string NewFuncName =
789 Twine(F.getName() + "." + Twine(FunctionHash)).str();
790 F.setName(Twine(NewFuncName));
792 FuncName = Twine(FuncName + "." + Twine(FunctionHash)).str();
793 Comdat *NewComdat;
794 Module *M = F.getParent();
795 // For AvailableExternallyLinkage functions, change the linkage to
796 // LinkOnceODR and put them into comdat. This is because after renaming, there
797 // is no backup external copy available for the function.
798 if (!F.hasComdat()) {
800 NewComdat = M->getOrInsertComdat(StringRef(NewFuncName));
802 F.setComdat(NewComdat);
803 return;
804 }
805
806 // This function belongs to a single function Comdat group.
807 Comdat *OrigComdat = F.getComdat();
808 std::string NewComdatName =
809 Twine(OrigComdat->getName() + "." + Twine(FunctionHash)).str();
810 NewComdat = M->getOrInsertComdat(StringRef(NewComdatName));
811 NewComdat->setSelectionKind(OrigComdat->getSelectionKind());
812
813 for (auto &&CM : make_range(ComdatMembers.equal_range(OrigComdat))) {
814 // Must be a function.
815 cast<Function>(CM.second)->setComdat(NewComdat);
816 }
817}
818
819/// Collect all the BBs that will be instruments and add them to
820/// `InstrumentBBs`.
821template <class Edge, class BBInfo>
822void FuncPGOInstrumentation<Edge, BBInfo>::getInstrumentBBs(
823 std::vector<BasicBlock *> &InstrumentBBs) {
824 if (BCI) {
825 for (auto &BB : F)
826 if (BCI->shouldInstrumentBlock(BB))
827 InstrumentBBs.push_back(&BB);
828 return;
829 }
830
831 // Use a worklist as we will update the vector during the iteration.
832 std::vector<Edge *> EdgeList;
833 EdgeList.reserve(MST.numEdges());
834 for (const auto &E : MST.allEdges())
835 EdgeList.push_back(E.get());
836
837 for (auto &E : EdgeList) {
838 BasicBlock *InstrBB = getInstrBB(E);
839 if (InstrBB)
840 InstrumentBBs.push_back(InstrBB);
841 }
842}
843
844// Given a CFG E to be instrumented, find which BB to place the instrumented
845// code. The function will split the critical edge if necessary.
846template <class Edge, class BBInfo>
847BasicBlock *FuncPGOInstrumentation<Edge, BBInfo>::getInstrBB(Edge *E) {
848 if (E->InMST || E->Removed)
849 return nullptr;
850
851 BasicBlock *SrcBB = E->SrcBB;
852 BasicBlock *DestBB = E->DestBB;
853 // For a fake edge, instrument the real BB.
854 if (SrcBB == nullptr)
855 return DestBB;
856 if (DestBB == nullptr)
857 return SrcBB;
858
859 auto canInstrument = [](BasicBlock *BB) -> BasicBlock * {
860 // There are basic blocks (such as catchswitch) cannot be instrumented.
861 // If the returned first insertion point is the end of BB, skip this BB.
862 if (BB->getFirstNonPHIOrDbgOrAlloca() == BB->end())
863 return nullptr;
864 return BB;
865 };
866
867 // Instrument the SrcBB if it has a single successor,
868 // otherwise, the DestBB if this is not a critical edge.
869 Instruction *TI = SrcBB->getTerminator();
870 if (TI->getNumSuccessors() <= 1)
871 return canInstrument(SrcBB);
872 if (!E->IsCritical)
873 return canInstrument(DestBB);
874
875 // Some IndirectBr critical edges cannot be split by the previous
876 // SplitIndirectBrCriticalEdges call. Bail out.
877 unsigned SuccNum = GetSuccessorNumber(SrcBB, DestBB);
878 BasicBlock *InstrBB =
879 isa<IndirectBrInst>(TI) ? nullptr : SplitCriticalEdge(TI, SuccNum);
880 if (!InstrBB) {
882 dbgs() << "Fail to split critical edge: not instrument this edge.\n");
883 return nullptr;
884 }
885 // For a critical edge, we have to split. Instrument the newly
886 // created BB.
887 IsCS ? NumOfCSPGOSplit++ : NumOfPGOSplit++;
888 LLVM_DEBUG(dbgs() << "Split critical edge: " << getBBInfo(SrcBB).Index
889 << " --> " << getBBInfo(DestBB).Index << "\n");
890 // Need to add two new edges. First one: Add new edge of SrcBB->InstrBB.
891 MST.addEdge(SrcBB, InstrBB, 0);
892 // Second one: Add new edge of InstrBB->DestBB.
893 Edge &NewEdge1 = MST.addEdge(InstrBB, DestBB, 0);
894 NewEdge1.InMST = true;
895 E->Removed = true;
896
897 return canInstrument(InstrBB);
898}
899
900// When generating value profiling calls on Windows routines that make use of
901// handler funclets for exception processing an operand bundle needs to attached
902// to the called function. This routine will set \p OpBundles to contain the
903// funclet information, if any is needed, that should be placed on the generated
904// value profiling call for the value profile candidate call.
905static void
909 auto *OrigCall = dyn_cast<CallBase>(Cand.AnnotatedInst);
910 if (!OrigCall)
911 return;
912
913 if (!isa<IntrinsicInst>(OrigCall)) {
914 // The instrumentation call should belong to the same funclet as a
915 // non-intrinsic call, so just copy the operand bundle, if any exists.
916 std::optional<OperandBundleUse> ParentFunclet =
917 OrigCall->getOperandBundle(LLVMContext::OB_funclet);
918 if (ParentFunclet)
919 OpBundles.emplace_back(OperandBundleDef(*ParentFunclet));
920 } else {
921 // Intrinsics or other instructions do not get funclet information from the
922 // front-end. Need to use the BlockColors that was computed by the routine
923 // colorEHFunclets to determine whether a funclet is needed.
924 if (!BlockColors.empty()) {
925 const ColorVector &CV = BlockColors.find(OrigCall->getParent())->second;
926 assert(CV.size() == 1 && "non-unique color for block!");
928 if (EHPadIt->isEHPad())
929 OpBundles.emplace_back("funclet", &*EHPadIt);
930 }
931 }
932}
933
934// Visit all edge and instrument the edges not in MST, and do value profiling.
935// Critical edges will be split.
936void FunctionInstrumenter::instrument() {
937 if (!PGOBlockCoverage) {
938 // Split indirectbr critical edges here before computing the MST rather than
939 // later in getInstrBB() to avoid invalidating it.
940 SplitIndirectBrCriticalEdges(F, /*IgnoreBlocksWithoutPHI=*/false, BPI, BFI);
941 }
942
943 const bool IsCtxProf = InstrumentationType == PGOInstrumentationType::CTXPROF;
944 FuncPGOInstrumentation<PGOEdge, PGOBBInfo> FuncInfo(
945 F, TLI, ComdatMembers, /*CreateGlobalVar=*/!IsCtxProf, BPI, BFI, LI,
946 InstrumentationType == PGOInstrumentationType::CSFDO,
947 shouldInstrumentEntryBB(), shouldInstrumentLoopEntries(),
949
950 auto *const Name = IsCtxProf ? cast<GlobalValue>(&F) : FuncInfo.FuncNameVar;
951 auto *const CFGHash =
952 ConstantInt::get(Type::getInt64Ty(M.getContext()), FuncInfo.FunctionHash);
953 // Make sure that pointer to global is passed in with zero addrspace
954 // This is relevant during GPU profiling
955 auto *NormalizedNamePtr = ConstantExpr::getPointerBitCastOrAddrSpaceCast(
956 Name, PointerType::get(M.getContext(), 0));
958 auto &EntryBB = F.getEntryBlock();
959 IRBuilder<> Builder(&EntryBB, EntryBB.getFirstNonPHIOrDbgOrAlloca());
960 // llvm.instrprof.cover(i8* <name>, i64 <hash>, i32 <num-counters>,
961 // i32 <index>)
962 Builder.CreateIntrinsic(
963 Intrinsic::instrprof_cover,
964 {NormalizedNamePtr, CFGHash, Builder.getInt32(1), Builder.getInt32(0)});
965 return;
966 }
967
968 std::vector<BasicBlock *> InstrumentBBs;
969 FuncInfo.getInstrumentBBs(InstrumentBBs);
970 unsigned NumCounters =
971 InstrumentBBs.size() + FuncInfo.SIVisitor.getNumOfSelectInsts();
972
973 if (IsCtxProf) {
974 StringSet<> SkipCSInstr(llvm::from_range, CtxPGOSkipCallsiteInstrument);
975
976 auto *CSIntrinsic =
977 Intrinsic::getOrInsertDeclaration(&M, Intrinsic::instrprof_callsite);
978 // We want to count the instrumentable callsites, then instrument them. This
979 // is because the llvm.instrprof.callsite intrinsic has an argument (like
980 // the other instrprof intrinsics) capturing the total number of
981 // instrumented objects (counters, or callsites, in this case). In this
982 // case, we want that value so we can readily pass it to the compiler-rt
983 // APIs that may have to allocate memory based on the nr of callsites.
984 // The traversal logic is the same for both counting and instrumentation,
985 // just needs to be done in succession.
986 auto Visit = [&](llvm::function_ref<void(CallBase * CB)> Visitor) {
987 for (auto &BB : F)
988 for (auto &Instr : BB)
989 if (auto *CS = dyn_cast<CallBase>(&Instr)) {
991 continue;
992 if (CS->getCalledFunction() &&
993 SkipCSInstr.contains(CS->getCalledFunction()->getName()))
994 continue;
995 Visitor(CS);
996 }
997 };
998 // First, count callsites.
999 uint32_t TotalNumCallsites = 0;
1000 Visit([&TotalNumCallsites](auto *) { ++TotalNumCallsites; });
1001
1002 // Now instrument.
1003 uint32_t CallsiteIndex = 0;
1004 Visit([&](auto *CB) {
1005 IRBuilder<> Builder(CB);
1006 Builder.CreateCall(CSIntrinsic,
1007 {Name, CFGHash, Builder.getInt32(TotalNumCallsites),
1008 Builder.getInt32(CallsiteIndex++),
1009 CB->getCalledOperand()});
1010 });
1011 }
1012
1013 uint32_t I = 0;
1015 NumCounters += PGOBlockCoverage ? 8 : 1;
1016 auto &EntryBB = F.getEntryBlock();
1017 IRBuilder<> Builder(&EntryBB, EntryBB.getFirstNonPHIOrDbgOrAlloca());
1018 // llvm.instrprof.timestamp(i8* <name>, i64 <hash>, i32 <num-counters>,
1019 // i32 <index>)
1020 Builder.CreateIntrinsic(Intrinsic::instrprof_timestamp,
1021 {NormalizedNamePtr, CFGHash,
1022 Builder.getInt32(NumCounters),
1023 Builder.getInt32(I)});
1024 I += PGOBlockCoverage ? 8 : 1;
1025 }
1026
1027 for (auto *InstrBB : InstrumentBBs) {
1028 IRBuilder<> Builder(InstrBB, InstrBB->getFirstNonPHIOrDbgOrAlloca());
1029 assert(Builder.GetInsertPoint() != InstrBB->end() &&
1030 "Cannot get the Instrumentation point");
1031 // llvm.instrprof.increment(i8* <name>, i64 <hash>, i32 <num-counters>,
1032 // i32 <index>)
1033 Builder.CreateIntrinsic(PGOBlockCoverage ? Intrinsic::instrprof_cover
1034 : Intrinsic::instrprof_increment,
1035 {NormalizedNamePtr, CFGHash,
1036 Builder.getInt32(NumCounters),
1037 Builder.getInt32(I++)});
1038 }
1039
1040 // Now instrument select instructions:
1041 FuncInfo.SIVisitor.instrumentSelects(&I, NumCounters, Name,
1042 FuncInfo.FunctionHash);
1043 assert(I == NumCounters);
1044
1045 if (isValueProfilingDisabled())
1046 return;
1047
1048 NumOfPGOICall += FuncInfo.ValueSites[IPVK_IndirectCallTarget].size();
1049
1050 // Intrinsic function calls do not have funclet operand bundles needed for
1051 // Windows exception handling attached to them. However, if value profiling is
1052 // inserted for one of these calls, then a funclet value will need to be set
1053 // on the instrumentation call based on the funclet coloring.
1054 DenseMap<BasicBlock *, ColorVector> BlockColors;
1055 if (F.hasPersonalityFn() &&
1056 isScopedEHPersonality(classifyEHPersonality(F.getPersonalityFn())))
1057 BlockColors = colorEHFunclets(F);
1058
1059 // For each VP Kind, walk the VP candidates and instrument each one.
1060 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind) {
1061 unsigned SiteIndex = 0;
1062 if (Kind == IPVK_MemOPSize && !PGOInstrMemOP)
1063 continue;
1064
1065 for (VPCandidateInfo Cand : FuncInfo.ValueSites[Kind]) {
1066 LLVM_DEBUG(dbgs() << "Instrument one VP " << ValueProfKindDescr[Kind]
1067 << " site: CallSite Index = " << SiteIndex << "\n");
1068
1069 IRBuilder<> Builder(Cand.InsertPt);
1070 assert(Builder.GetInsertPoint() != Cand.InsertPt->getParent()->end() &&
1071 "Cannot get the Instrumentation point");
1072
1073 Value *ToProfile = nullptr;
1074 if (Cand.V->getType()->isIntegerTy())
1075 ToProfile = Builder.CreateZExtOrTrunc(Cand.V, Builder.getInt64Ty());
1076 else if (Cand.V->getType()->isPointerTy())
1077 ToProfile = Builder.CreatePtrToInt(Cand.V, Builder.getInt64Ty());
1078 assert(ToProfile && "value profiling Value is of unexpected type");
1079
1080 auto *NormalizedNamePtr = ConstantExpr::getPointerBitCastOrAddrSpaceCast(
1081 Name, PointerType::get(M.getContext(), 0));
1082
1084 populateEHOperandBundle(Cand, BlockColors, OpBundles);
1085 Builder.CreateCall(
1087 Intrinsic::instrprof_value_profile),
1088 {NormalizedNamePtr, Builder.getInt64(FuncInfo.FunctionHash),
1089 ToProfile, Builder.getInt32(Kind), Builder.getInt32(SiteIndex++)},
1090 OpBundles);
1091 }
1092 } // IPVK_First <= Kind <= IPVK_Last
1093}
1094
1095namespace {
1096
1097// This class represents a CFG edge in profile use compilation.
1098struct PGOUseEdge : public PGOEdge {
1099 using PGOEdge::PGOEdge;
1100
1101 std::optional<uint64_t> Count;
1102
1103 // Set edge count value
1104 void setEdgeCount(uint64_t Value) { Count = Value; }
1105
1106 // Return the information string for this object.
1107 std::string infoString() const {
1108 if (!Count)
1109 return PGOEdge::infoString();
1110 return (Twine(PGOEdge::infoString()) + " Count=" + Twine(*Count)).str();
1111 }
1112};
1113
1114using DirectEdges = SmallVector<PGOUseEdge *, 2>;
1115
1116// This class stores the auxiliary information for each BB.
1117struct PGOUseBBInfo : public PGOBBInfo {
1118 std::optional<uint64_t> Count;
1119 int32_t UnknownCountInEdge = 0;
1120 int32_t UnknownCountOutEdge = 0;
1121 DirectEdges InEdges;
1122 DirectEdges OutEdges;
1123
1124 PGOUseBBInfo(unsigned IX) : PGOBBInfo(IX) {}
1125
1126 // Set the profile count value for this BB.
1127 void setBBInfoCount(uint64_t Value) { Count = Value; }
1128
1129 // Return the information string of this object.
1130 std::string infoString() const {
1131 if (!Count)
1132 return PGOBBInfo::infoString();
1133 return (Twine(PGOBBInfo::infoString()) + " Count=" + Twine(*Count)).str();
1134 }
1135
1136 // Add an OutEdge and update the edge count.
1137 void addOutEdge(PGOUseEdge *E) {
1138 OutEdges.push_back(E);
1139 UnknownCountOutEdge++;
1140 }
1141
1142 // Add an InEdge and update the edge count.
1143 void addInEdge(PGOUseEdge *E) {
1144 InEdges.push_back(E);
1145 UnknownCountInEdge++;
1146 }
1147};
1148
1149} // end anonymous namespace
1150
1151// Sum up the count values for all the edges.
1153 uint64_t Total = 0;
1154 for (const auto &E : Edges) {
1155 if (E->Removed)
1156 continue;
1157 if (E->Count)
1158 Total += *E->Count;
1159 }
1160 return Total;
1161}
1162
1163namespace {
1164
1165class PGOUseFunc {
1166public:
1167 PGOUseFunc(Function &Func, Module *Modu, TargetLibraryInfo &TLI,
1168 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers,
1169 BranchProbabilityInfo *BPI, BlockFrequencyInfo *BFIin,
1170 LoopInfo *LI, ProfileSummaryInfo *PSI, bool IsCS,
1171 bool InstrumentFuncEntry, bool InstrumentLoopEntries,
1172 bool HasSingleByteCoverage)
1173 : F(Func), M(Modu), BFI(BFIin), PSI(PSI),
1174 FuncInfo(Func, TLI, ComdatMembers, false, BPI, BFIin, LI, IsCS,
1175 InstrumentFuncEntry, InstrumentLoopEntries,
1176 HasSingleByteCoverage),
1177 FreqAttr(FFA_Normal), IsCS(IsCS), VPC(Func, TLI) {}
1178
1179 void handleInstrProfError(Error Err, uint64_t MismatchedFuncSum);
1180
1181 /// Get the profile record, assign it to \p ProfileRecord, handle errors if
1182 /// necessary, and assign \p ProgramMaxCount. \returns true if there are no
1183 /// errors.
1184 bool getRecord(IndexedInstrProfReader *PGOReader);
1185
1186 // Read counts for the instrumented BB from profile.
1187 bool readCounters(bool &AllZeros,
1189
1190 // Populate the counts for all BBs.
1191 void populateCounters();
1192
1193 // Set block coverage based on profile coverage values.
1194 void populateCoverage();
1195
1196 // Set the branch weights based on the count values.
1197 void setBranchWeights();
1198
1199 // Annotate the value profile call sites for all value kind.
1200 void annotateValueSites();
1201
1202 // Annotate the value profile call sites for one value kind.
1203 void annotateValueSites(uint32_t Kind);
1204
1205 // Annotate the irreducible loop header weights.
1206 void annotateIrrLoopHeaderWeights();
1207
1208 // Annotate per-block uniformity info for offload profiling.
1209 void setBlockUniformityAttribute();
1210
1211 // The hotness of the function from the profile count.
1212 enum FuncFreqAttr { FFA_Normal, FFA_Cold, FFA_Hot };
1213
1214 // Return the function hotness from the profile.
1215 FuncFreqAttr getFuncFreqAttr() const { return FreqAttr; }
1216
1217 // Return the function hash.
1218 uint64_t getFuncHash() const { return FuncInfo.FunctionHash; }
1219
1220 // Return the profile record for this function;
1221 NamedInstrProfRecord &getProfileRecord() { return ProfileRecord; }
1222
1223 // Return the auxiliary BB information.
1224 PGOUseBBInfo &getBBInfo(const BasicBlock *BB) const {
1225 return FuncInfo.getBBInfo(BB);
1226 }
1227
1228 // Return the auxiliary BB information if available.
1229 PGOUseBBInfo *findBBInfo(const BasicBlock *BB) const {
1230 return FuncInfo.findBBInfo(BB);
1231 }
1232
1233 Function &getFunc() const { return F; }
1234
1235 void dumpInfo(StringRef Str = "") const { FuncInfo.dumpInfo(Str); }
1236
1237 uint64_t getProgramMaxCount() const { return ProgramMaxCount; }
1238
1239private:
1240 Function &F;
1241 Module *M;
1242 BlockFrequencyInfo *BFI;
1243 ProfileSummaryInfo *PSI;
1244
1245 // This member stores the shared information with class PGOGenFunc.
1246 FuncPGOInstrumentation<PGOUseEdge, PGOUseBBInfo> FuncInfo;
1247
1248 // The maximum count value in the profile. This is only used in PGO use
1249 // compilation.
1250 uint64_t ProgramMaxCount;
1251
1252 // Position of counter that remains to be read.
1253 uint32_t CountPosition = 0;
1254
1255 // Total size of the profile count for this function.
1256 uint32_t ProfileCountSize = 0;
1257
1258 // ProfileRecord for this function.
1259 NamedInstrProfRecord ProfileRecord;
1260
1261 // Function hotness info derived from profile.
1262 FuncFreqAttr FreqAttr;
1263
1264 // Is to use the context sensitive profile.
1265 bool IsCS;
1266
1267 ValueProfileCollector VPC;
1268
1269 // Find the Instrumented BB and set the value. Return false on error.
1270 bool setInstrumentedCounts(const std::vector<uint64_t> &CountFromProfile);
1271
1272 // Set the edge counter value for the unknown edge -- there should be only
1273 // one unknown edge.
1274 void setEdgeCount(DirectEdges &Edges, uint64_t Value);
1275
1276 // Set the hot/cold inline hints based on the count values.
1277 // FIXME: This function should be removed once the functionality in
1278 // the inliner is implemented.
1279 void markFunctionAttributes(uint64_t EntryCount, uint64_t MaxCount) {
1280 if (PSI->isHotCount(EntryCount))
1281 FreqAttr = FFA_Hot;
1282 else if (PSI->isColdCount(MaxCount))
1283 FreqAttr = FFA_Cold;
1284 }
1285};
1286
1287} // end anonymous namespace
1288
1289/// Set up InEdges/OutEdges for all BBs in the MST.
1291 const FuncPGOInstrumentation<PGOUseEdge, PGOUseBBInfo> &FuncInfo) {
1292 // This is not required when there is block coverage inference.
1293 if (FuncInfo.BCI)
1294 return;
1295 for (const auto &E : FuncInfo.MST.allEdges()) {
1296 if (E->Removed)
1297 continue;
1298 const BasicBlock *SrcBB = E->SrcBB;
1299 const BasicBlock *DestBB = E->DestBB;
1300 PGOUseBBInfo &SrcInfo = FuncInfo.getBBInfo(SrcBB);
1301 PGOUseBBInfo &DestInfo = FuncInfo.getBBInfo(DestBB);
1302 SrcInfo.addOutEdge(E.get());
1303 DestInfo.addInEdge(E.get());
1304 }
1305}
1306
1307// Visit all the edges and assign the count value for the instrumented
1308// edges and the BB. Return false on error.
1309bool PGOUseFunc::setInstrumentedCounts(
1310 const std::vector<uint64_t> &CountFromProfile) {
1311
1312 std::vector<BasicBlock *> InstrumentBBs;
1313 FuncInfo.getInstrumentBBs(InstrumentBBs);
1314
1315 setupBBInfoEdges(FuncInfo);
1316
1317 unsigned NumInstrumentedBBs = InstrumentBBs.size();
1318 unsigned NumSelects = FuncInfo.SIVisitor.getNumOfSelectInsts();
1319 unsigned NumCounters = NumInstrumentedBBs + NumSelects;
1320 // The number of counters here should match the number of counters
1321 // in profile. Return if they mismatch.
1322 if (NumCounters != CountFromProfile.size()) {
1323 LLVM_DEBUG({
1324 dbgs() << "PGO COUNTER MISMATCH for function " << F.getName() << ":\n";
1325 dbgs() << " Expected counters: " << NumCounters << "\n";
1326 dbgs() << " - From instrumented edges: " << NumInstrumentedBBs << "\n";
1327 for (size_t i = 0; i < InstrumentBBs.size(); ++i) {
1328 dbgs() << " " << i << ": ";
1329 InstrumentBBs[i]->printAsOperand(dbgs(), false);
1330 dbgs() << "\n";
1331 }
1332 dbgs() << " - From select instructions: " << NumSelects << "\n";
1333 dbgs() << " Actual counters from profile: " << CountFromProfile.size()
1334 << "\n";
1335 });
1336 return false;
1337 }
1338 auto *FuncEntry = &*F.begin();
1339
1340 // Set the profile count to the Instrumented BBs.
1341 uint32_t I = 0;
1342 for (BasicBlock *InstrBB : InstrumentBBs) {
1343 uint64_t CountValue = CountFromProfile[I++];
1344 PGOUseBBInfo &Info = getBBInfo(InstrBB);
1345 // If we reach here, we know that we have some nonzero count
1346 // values in this function. The entry count should not be 0.
1347 // Fix it if necessary.
1348 if (InstrBB == FuncEntry && CountValue == 0)
1349 CountValue = 1;
1350 Info.setBBInfoCount(CountValue);
1351 }
1352 ProfileCountSize = CountFromProfile.size();
1353 CountPosition = I;
1354
1355 // Set the edge count and update the count of unknown edges for BBs.
1356 auto setEdgeCount = [this](PGOUseEdge *E, uint64_t Value) -> void {
1357 E->setEdgeCount(Value);
1358 this->getBBInfo(E->SrcBB).UnknownCountOutEdge--;
1359 this->getBBInfo(E->DestBB).UnknownCountInEdge--;
1360 };
1361
1362 // Set the profile count the Instrumented edges. There are BBs that not in
1363 // MST but not instrumented. Need to set the edge count value so that we can
1364 // populate the profile counts later.
1365 for (const auto &E : FuncInfo.MST.allEdges()) {
1366 if (E->Removed || E->InMST)
1367 continue;
1368 const BasicBlock *SrcBB = E->SrcBB;
1369 PGOUseBBInfo &SrcInfo = getBBInfo(SrcBB);
1370
1371 // If only one out-edge, the edge profile count should be the same as BB
1372 // profile count.
1373 if (SrcInfo.Count && SrcInfo.OutEdges.size() == 1)
1374 setEdgeCount(E.get(), *SrcInfo.Count);
1375 else {
1376 const BasicBlock *DestBB = E->DestBB;
1377 PGOUseBBInfo &DestInfo = getBBInfo(DestBB);
1378 // If only one in-edge, the edge profile count should be the same as BB
1379 // profile count.
1380 if (DestInfo.Count && DestInfo.InEdges.size() == 1)
1381 setEdgeCount(E.get(), *DestInfo.Count);
1382 }
1383 if (E->Count)
1384 continue;
1385 // E's count should have been set from profile. If not, this meenas E skips
1386 // the instrumentation. We set the count to 0.
1387 setEdgeCount(E.get(), 0);
1388 }
1389 return true;
1390}
1391
1392// Set the count value for the unknown edge. There should be one and only one
1393// unknown edge in Edges vector.
1394void PGOUseFunc::setEdgeCount(DirectEdges &Edges, uint64_t Value) {
1395 for (auto &E : Edges) {
1396 if (E->Count)
1397 continue;
1398 E->setEdgeCount(Value);
1399
1400 getBBInfo(E->SrcBB).UnknownCountOutEdge--;
1401 getBBInfo(E->DestBB).UnknownCountInEdge--;
1402 return;
1403 }
1404 llvm_unreachable("Cannot find the unknown count edge");
1405}
1406
1407// Emit function metadata indicating PGO profile mismatch.
1409 const char MetadataName[] = "instr_prof_hash_mismatch";
1411 // If this metadata already exists, ignore.
1412 auto *Existing = F.getMetadata(LLVMContext::MD_annotation);
1413 if (Existing) {
1414 MDTuple *Tuple = cast<MDTuple>(Existing);
1415 for (const auto &N : Tuple->operands()) {
1416 if (N.equalsStr(MetadataName))
1417 return;
1418 Names.push_back(N.get());
1419 }
1420 }
1421
1422 MDBuilder MDB(ctx);
1423 Names.push_back(MDB.createString(MetadataName));
1424 MDNode *MD = MDTuple::get(ctx, Names);
1425 F.setMetadata(LLVMContext::MD_annotation, MD);
1426}
1427
1428void PGOUseFunc::handleInstrProfError(Error Err, uint64_t MismatchedFuncSum) {
1429 handleAllErrors(std::move(Err), [&](const InstrProfError &IPE) {
1430 auto &Ctx = M->getContext();
1431 auto Err = IPE.get();
1432 bool SkipWarning = false;
1433 LLVM_DEBUG(dbgs() << "Error in reading profile for Func "
1434 << FuncInfo.FuncName << ": ");
1435 if (Err == instrprof_error::unknown_function) {
1436 IsCS ? NumOfCSPGOMissing++ : NumOfPGOMissing++;
1437 SkipWarning = !PGOWarnMissing;
1438 LLVM_DEBUG(dbgs() << "unknown function");
1439 } else if (Err == instrprof_error::hash_mismatch ||
1440 Err == instrprof_error::malformed) {
1441 IsCS ? NumOfCSPGOMismatch++ : NumOfPGOMismatch++;
1442 SkipWarning =
1445 (F.hasComdat() || F.getLinkage() == GlobalValue::WeakAnyLinkage ||
1447 LLVM_DEBUG(dbgs() << "hash mismatch (hash= " << FuncInfo.FunctionHash
1448 << " skip=" << SkipWarning << ")");
1449 // Emit function metadata indicating PGO profile mismatch.
1450 annotateFunctionWithHashMismatch(F, M->getContext());
1451 }
1452
1453 LLVM_DEBUG(dbgs() << " IsCS=" << IsCS << "\n");
1454 if (SkipWarning)
1455 return;
1456
1457 std::string Msg =
1458 IPE.message() + std::string(" ") + F.getName().str() +
1459 std::string(" Hash = ") + std::to_string(FuncInfo.FunctionHash) +
1460 std::string(" up to ") + std::to_string(MismatchedFuncSum) +
1461 std::string(" count discarded");
1462
1463 Ctx.diagnose(
1464 DiagnosticInfoPGOProfile(M->getName().data(), Msg, DS_Warning));
1465 });
1466}
1467
1468bool PGOUseFunc::getRecord(IndexedInstrProfReader *PGOReader) {
1469 uint64_t MismatchedFuncSum = 0;
1470 auto Result = PGOReader->getInstrProfRecord(
1471 FuncInfo.FuncName, FuncInfo.FunctionHash, FuncInfo.DeprecatedFuncName,
1472 &MismatchedFuncSum);
1473 if (Error E = Result.takeError()) {
1474 handleInstrProfError(std::move(E), MismatchedFuncSum);
1475 return false;
1476 }
1477 ProfileRecord = std::move(Result.get());
1478 ProgramMaxCount = PGOReader->getMaximumFunctionCount(IsCS);
1479 return true;
1480}
1481
1482// Read the profile from ProfileFileName and assign the value to the
1483// instrumented BB and the edges. Return true if the profile are successfully
1484// read, and false on errors.
1485bool PGOUseFunc::readCounters(bool &AllZeros,
1487 auto &Ctx = M->getContext();
1488 PseudoKind = ProfileRecord.getCountPseudoKind();
1489 if (PseudoKind != InstrProfRecord::NotPseudo) {
1490 return true;
1491 }
1492 std::vector<uint64_t> &CountFromProfile = ProfileRecord.Counts;
1493
1494 IsCS ? NumOfCSPGOFunc++ : NumOfPGOFunc++;
1495 LLVM_DEBUG(dbgs() << CountFromProfile.size() << " counts\n");
1496
1497 uint64_t ValueSum = 0;
1498 for (unsigned I = 0, S = CountFromProfile.size(); I < S; I++) {
1499 LLVM_DEBUG(dbgs() << " " << I << ": " << CountFromProfile[I] << "\n");
1500 ValueSum += CountFromProfile[I];
1501 }
1502 AllZeros = (ValueSum == 0);
1503
1504 LLVM_DEBUG(dbgs() << "SUM = " << ValueSum << "\n");
1505
1506 getBBInfo(nullptr).UnknownCountOutEdge = 2;
1507 getBBInfo(nullptr).UnknownCountInEdge = 2;
1508
1509 if (!setInstrumentedCounts(CountFromProfile)) {
1510 LLVM_DEBUG(
1511 dbgs() << "Inconsistent number of counts, skipping this function");
1512 Ctx.diagnose(DiagnosticInfoPGOProfile(
1513 M->getName().data(),
1514 Twine("Inconsistent number of counts in ") + F.getName().str() +
1515 Twine(": the profile may be stale or there is a function name "
1516 "collision."),
1517 DS_Warning));
1518 return false;
1519 }
1520 return true;
1521}
1522
1523void PGOUseFunc::populateCoverage() {
1524 IsCS ? NumOfCSPGOFunc++ : NumOfPGOFunc++;
1525
1526 ArrayRef<uint64_t> CountsFromProfile = ProfileRecord.Counts;
1527 DenseMap<const BasicBlock *, bool> Coverage;
1528 unsigned Index = 0;
1529 for (auto &BB : F)
1530 if (FuncInfo.BCI->shouldInstrumentBlock(BB))
1531 Coverage[&BB] = (CountsFromProfile[Index++] != 0);
1532 assert(Index == CountsFromProfile.size());
1533
1534 // For each B in InverseDependencies[A], if A is covered then B is covered.
1535 DenseMap<const BasicBlock *, DenseSet<const BasicBlock *>>
1536 InverseDependencies;
1537 for (auto &BB : F) {
1538 for (auto *Dep : FuncInfo.BCI->getDependencies(BB)) {
1539 // If Dep is covered then BB is covered.
1540 InverseDependencies[Dep].insert(&BB);
1541 }
1542 }
1543
1544 // Infer coverage of the non-instrumented blocks using a flood-fill algorithm.
1545 std::stack<const BasicBlock *> CoveredBlocksToProcess;
1546 for (auto &[BB, IsCovered] : Coverage)
1547 if (IsCovered)
1548 CoveredBlocksToProcess.push(BB);
1549
1550 while (!CoveredBlocksToProcess.empty()) {
1551 auto *CoveredBlock = CoveredBlocksToProcess.top();
1552 assert(Coverage[CoveredBlock]);
1553 CoveredBlocksToProcess.pop();
1554 for (auto *BB : InverseDependencies[CoveredBlock]) {
1555 // If CoveredBlock is covered then BB is covered.
1556 bool &Cov = Coverage[BB];
1557 if (Cov)
1558 continue;
1559 Cov = true;
1560 CoveredBlocksToProcess.push(BB);
1561 }
1562 }
1563
1564 // Annotate block coverage.
1565 MDBuilder MDB(F.getContext());
1566 // We set the entry count to 10000 if the entry block is covered so that BFI
1567 // can propagate a fraction of this count to the other covered blocks.
1568 F.setEntryCount(Coverage[&F.getEntryBlock()] ? 10000 : 0);
1569 for (auto &BB : F) {
1570 // For a block A and its successor B, we set the edge weight as follows:
1571 // If A is covered and B is covered, set weight=1.
1572 // If A is covered and B is uncovered, set weight=0.
1573 // If A is uncovered, set weight=1.
1574 // This setup will allow BFI to give nonzero profile counts to only covered
1575 // blocks.
1576 SmallVector<uint32_t, 4> Weights;
1577 for (auto *Succ : successors(&BB))
1578 Weights.push_back((Coverage[Succ] || !Coverage[&BB]) ? 1 : 0);
1579 if (Weights.size() >= 2)
1580 llvm::setBranchWeights(*BB.getTerminator(), Weights,
1581 /*IsExpected=*/false);
1582 }
1583
1584 unsigned NumCorruptCoverage = 0;
1585 DominatorTree DT(F);
1586 CycleInfo CI;
1587 CI.compute(F);
1588 LoopInfo LI(DT);
1589 BranchProbabilityInfo BPI(F, CI);
1590 BlockFrequencyInfo BFI(F, BPI, LI);
1591 auto IsBlockDead = [&](const BasicBlock &BB) -> std::optional<bool> {
1592 if (auto C = BFI.getBlockProfileCount(&BB))
1593 return C == 0;
1594 return {};
1595 };
1596 LLVM_DEBUG(dbgs() << "Block Coverage: (Instrumented=*, Covered=X)\n");
1597 for (auto &BB : F) {
1598 LLVM_DEBUG(dbgs() << (FuncInfo.BCI->shouldInstrumentBlock(BB) ? "* " : " ")
1599 << (Coverage[&BB] ? "X " : " ") << " " << BB.getName()
1600 << "\n");
1601 // In some cases it is possible to find a covered block that has no covered
1602 // successors, e.g., when a block calls a function that may call exit(). In
1603 // those cases, BFI could find its successor to be covered while BCI could
1604 // find its successor to be dead.
1605 const bool &Cov = Coverage[&BB];
1606 if (Cov == IsBlockDead(BB).value_or(false)) {
1607 LLVM_DEBUG(
1608 dbgs() << "Found inconsistent block covearge for " << BB.getName()
1609 << ": BCI=" << (Cov ? "Covered" : "Dead") << " BFI="
1610 << (IsBlockDead(BB).value() ? "Dead" : "Covered") << "\n");
1611 ++NumCorruptCoverage;
1612 }
1613 if (Cov)
1614 ++NumCoveredBlocks;
1615 }
1616 if (PGOVerifyBFI && NumCorruptCoverage) {
1617 auto &Ctx = M->getContext();
1618 Ctx.diagnose(DiagnosticInfoPGOProfile(
1619 M->getName().data(),
1620 Twine("Found inconsistent block coverage for function ") + F.getName() +
1621 " in " + Twine(NumCorruptCoverage) + " blocks.",
1622 DS_Warning));
1623 }
1625 FuncInfo.BCI->viewBlockCoverageGraph(&Coverage);
1626}
1627
1628// Populate the counters from instrumented BBs to all BBs.
1629// In the end of this operation, all BBs should have a valid count value.
1630void PGOUseFunc::populateCounters() {
1631 bool Changes = true;
1632 unsigned NumPasses = 0;
1633 while (Changes) {
1634 NumPasses++;
1635 Changes = false;
1636
1637 // For efficient traversal, it's better to start from the end as most
1638 // of the instrumented edges are at the end.
1639 for (auto &BB : reverse(F)) {
1640 PGOUseBBInfo *UseBBInfo = findBBInfo(&BB);
1641 if (UseBBInfo == nullptr)
1642 continue;
1643 if (!UseBBInfo->Count) {
1644 if (UseBBInfo->UnknownCountOutEdge == 0) {
1645 UseBBInfo->Count = sumEdgeCount(UseBBInfo->OutEdges);
1646 Changes = true;
1647 } else if (UseBBInfo->UnknownCountInEdge == 0) {
1648 UseBBInfo->Count = sumEdgeCount(UseBBInfo->InEdges);
1649 Changes = true;
1650 }
1651 }
1652 if (UseBBInfo->Count) {
1653 if (UseBBInfo->UnknownCountOutEdge == 1) {
1654 uint64_t Total = 0;
1655 uint64_t OutSum = sumEdgeCount(UseBBInfo->OutEdges);
1656 // If the one of the successor block can early terminate (no-return),
1657 // we can end up with situation where out edge sum count is larger as
1658 // the source BB's count is collected by a post-dominated block.
1659 if (*UseBBInfo->Count > OutSum)
1660 Total = *UseBBInfo->Count - OutSum;
1661 setEdgeCount(UseBBInfo->OutEdges, Total);
1662 Changes = true;
1663 }
1664 if (UseBBInfo->UnknownCountInEdge == 1) {
1665 uint64_t Total = 0;
1666 uint64_t InSum = sumEdgeCount(UseBBInfo->InEdges);
1667 if (*UseBBInfo->Count > InSum)
1668 Total = *UseBBInfo->Count - InSum;
1669 setEdgeCount(UseBBInfo->InEdges, Total);
1670 Changes = true;
1671 }
1672 }
1673 }
1674 }
1675
1676 LLVM_DEBUG(dbgs() << "Populate counts in " << NumPasses << " passes.\n");
1677 (void)NumPasses;
1678#ifndef NDEBUG
1679 // Assert every BB has a valid counter.
1680 for (auto &BB : F) {
1681 auto BI = findBBInfo(&BB);
1682 if (BI == nullptr)
1683 continue;
1684 assert(BI->Count && "BB count is not valid");
1685 }
1686#endif
1687 // Now annotate select instructions. This may fixup impossible block counts.
1688 FuncInfo.SIVisitor.annotateSelects(this, &CountPosition);
1689 assert(CountPosition == ProfileCountSize);
1690
1691 uint64_t FuncEntryCount = *getBBInfo(&*F.begin()).Count;
1692 uint64_t FuncMaxCount = FuncEntryCount;
1693 for (auto &BB : F) {
1694 auto BI = findBBInfo(&BB);
1695 if (BI == nullptr)
1696 continue;
1697 FuncMaxCount = std::max(FuncMaxCount, *BI->Count);
1698 }
1699
1700 // Fix the obviously inconsistent entry count.
1701 if (FuncMaxCount > 0 && FuncEntryCount == 0)
1702 FuncEntryCount = 1;
1703 F.setEntryCount(FuncEntryCount);
1704 markFunctionAttributes(FuncEntryCount, FuncMaxCount);
1705
1706 LLVM_DEBUG(FuncInfo.dumpInfo("after reading profile."));
1707}
1708
1709// Assign the scaled count values to the BB with multiple out edges.
1710void PGOUseFunc::setBranchWeights() {
1711 // Generate MD_prof metadata for every branch instruction.
1712 LLVM_DEBUG(dbgs() << "\nSetting branch weights for func " << F.getName()
1713 << " IsCS=" << IsCS << "\n");
1714 for (auto &BB : F) {
1715 Instruction *TI = BB.getTerminator();
1716 if (TI->getNumSuccessors() < 2)
1717 continue;
1718 if (!(isa<CondBrInst>(TI) || isa<SwitchInst>(TI) ||
1720 isa<CallBrInst>(TI)))
1721 continue;
1722
1723 const PGOUseBBInfo &BBCountInfo = getBBInfo(&BB);
1724 if (!*BBCountInfo.Count)
1725 continue;
1726
1727 // We have a non-zero Branch BB.
1728
1729 // SuccessorCount can be greater than OutEdgesCount, because
1730 // removed edges don't appear in OutEdges.
1731 unsigned OutEdgesCount = BBCountInfo.OutEdges.size();
1732 unsigned SuccessorCount = BB.getTerminator()->getNumSuccessors();
1733 assert(OutEdgesCount <= SuccessorCount);
1734
1735 SmallVector<uint64_t, 2> EdgeCounts(SuccessorCount, 0);
1736 uint64_t MaxCount = 0;
1737 for (unsigned It = 0; It < OutEdgesCount; It++) {
1738 const PGOUseEdge *E = BBCountInfo.OutEdges[It];
1739 const BasicBlock *SrcBB = E->SrcBB;
1740 const BasicBlock *DestBB = E->DestBB;
1741 if (DestBB == nullptr)
1742 continue;
1743 unsigned SuccNum = GetSuccessorNumber(SrcBB, DestBB);
1744 uint64_t EdgeCount = *E->Count;
1745 if (EdgeCount > MaxCount)
1746 MaxCount = EdgeCount;
1747 EdgeCounts[SuccNum] = EdgeCount;
1748 }
1749
1750 if (MaxCount)
1751 setProfMetadata(TI, EdgeCounts, MaxCount);
1752 else {
1753 // A zero MaxCount can come about when we have a BB with a positive
1754 // count, and whose successor blocks all have 0 count. This can happen
1755 // when there is no exit block and the code exits via a noreturn function.
1756 auto &Ctx = M->getContext();
1757 Ctx.diagnose(DiagnosticInfoPGOProfile(
1758 M->getName().data(),
1759 Twine("Profile in ") + F.getName().str() +
1760 Twine(" partially ignored") +
1761 Twine(", possibly due to the lack of a return path."),
1762 DS_Warning));
1763 }
1764 }
1765}
1766
1768 for (BasicBlock *Pred : predecessors(BB)) {
1769 if (isa<IndirectBrInst>(Pred->getTerminator()))
1770 return true;
1771 }
1772 return false;
1773}
1774
1775void PGOUseFunc::annotateIrrLoopHeaderWeights() {
1776 LLVM_DEBUG(dbgs() << "\nAnnotating irreducible loop header weights.\n");
1777 // Find irr loop headers
1778 for (auto &BB : F) {
1779 // As a heuristic also annotate indrectbr targets as they have a high chance
1780 // to become an irreducible loop header after the indirectbr tail
1781 // duplication.
1782 if (BFI->isIrrLoopHeader(&BB) || isIndirectBrTarget(&BB)) {
1783 Instruction *TI = BB.getTerminator();
1784 const PGOUseBBInfo &BBCountInfo = getBBInfo(&BB);
1785 setIrrLoopHeaderMetadata(M, TI, *BBCountInfo.Count);
1786 }
1787 }
1788}
1789
1790void PGOUseFunc::setBlockUniformityAttribute() {
1791 if (ProfileRecord.UniformityBits.empty())
1792 return;
1793
1794 // Annotate uniformity on each instrumented IR basic block so later codegen
1795 // passes (MachineFunction) can consume it without relying on fragile block
1796 // numbering heuristics.
1797 //
1798 // Metadata kind: LLVMContext::MD_block_uniformity_profile
1799 // Payload: i1 (true = uniform, false = divergent)
1800
1801 std::vector<BasicBlock *> InstrumentBBs;
1802 FuncInfo.getInstrumentBBs(InstrumentBBs);
1803
1804 LLVMContext &Ctx = F.getContext();
1805 Type *Int1Ty = Type::getInt1Ty(Ctx);
1806
1807 for (size_t I = 0, E = InstrumentBBs.size(); I < E; ++I) {
1808 BasicBlock *BB = InstrumentBBs[I];
1809 if (!BB || !BB->getTerminator())
1810 continue;
1811 bool IsUniform = ProfileRecord.isBlockUniform(I);
1812 auto *MD = MDNode::get(
1813 Ctx, ConstantAsMetadata::get(ConstantInt::get(Int1Ty, IsUniform)));
1814 BB->getTerminator()->setMetadata(LLVMContext::MD_block_uniformity_profile,
1815 MD);
1816 }
1817
1818 LLVM_DEBUG({
1819 dbgs() << "PGO: Set block uniformity profile for " << F.getName() << ": ";
1820 for (size_t I = 0, E = InstrumentBBs.size(); I < E; ++I)
1821 dbgs() << (ProfileRecord.isBlockUniform(I) ? 'U' : 'D');
1822 dbgs() << "\n";
1823 });
1824}
1825
1826void SelectInstVisitor::instrumentOneSelectInst(SelectInst &SI) {
1827 Module *M = F.getParent();
1828 IRBuilder<> Builder(&SI);
1829 Type *Int64Ty = Builder.getInt64Ty();
1830 auto *Step = Builder.CreateZExt(SI.getCondition(), Int64Ty);
1831 auto *NormalizedFuncNameVarPtr =
1833 FuncNameVar, PointerType::get(M->getContext(), 0));
1834 Builder.CreateIntrinsic(Intrinsic::instrprof_increment_step,
1835 {NormalizedFuncNameVarPtr, Builder.getInt64(FuncHash),
1836 Builder.getInt32(TotalNumCtrs),
1837 Builder.getInt32(*CurCtrIdx), Step});
1838 ++(*CurCtrIdx);
1839}
1840
1841void SelectInstVisitor::annotateOneSelectInst(SelectInst &SI) {
1842 std::vector<uint64_t> &CountFromProfile = UseFunc->getProfileRecord().Counts;
1843 assert(*CurCtrIdx < CountFromProfile.size() &&
1844 "Out of bound access of counters");
1845 uint64_t SCounts[2];
1846 SCounts[0] = CountFromProfile[*CurCtrIdx]; // True count
1847 ++(*CurCtrIdx);
1848 uint64_t TotalCount = 0;
1849 auto BI = UseFunc->findBBInfo(SI.getParent());
1850 if (BI != nullptr) {
1851 TotalCount = *BI->Count;
1852
1853 // Fix the block count if it is impossible.
1854 if (TotalCount < SCounts[0])
1855 BI->Count = SCounts[0];
1856 }
1857 // False Count
1858 SCounts[1] = (TotalCount > SCounts[0] ? TotalCount - SCounts[0] : 0);
1859 uint64_t MaxCount = std::max(SCounts[0], SCounts[1]);
1860 if (MaxCount)
1861 setProfMetadata(&SI, SCounts, MaxCount);
1862}
1863
1864void SelectInstVisitor::visitSelectInst(SelectInst &SI) {
1865 if (!PGOInstrSelect || PGOFunctionEntryCoverage || HasSingleByteCoverage)
1866 return;
1867 // FIXME: do not handle this yet.
1868 if (SI.getCondition()->getType()->isVectorTy())
1869 return;
1870
1871 switch (Mode) {
1872 case VM_counting:
1873 NSIs++;
1874 return;
1875 case VM_instrument:
1876 instrumentOneSelectInst(SI);
1877 return;
1878 case VM_annotate:
1879 annotateOneSelectInst(SI);
1880 return;
1881 }
1882
1883 llvm_unreachable("Unknown visiting mode");
1884}
1885
1887 if (ValueProfKind == IPVK_MemOPSize)
1889 if (ValueProfKind == llvm::IPVK_VTableTarget)
1891 return MaxNumAnnotations;
1892}
1893
1894// Traverse all valuesites and annotate the instructions for all value kind.
1895void PGOUseFunc::annotateValueSites() {
1897 return;
1898
1899 // Create the PGOFuncName meta data.
1900 createPGOFuncNameMetadata(F, FuncInfo.FuncName);
1901
1902 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
1903 annotateValueSites(Kind);
1904}
1905
1906// Annotate the instructions for a specific value kind.
1907void PGOUseFunc::annotateValueSites(uint32_t Kind) {
1908 assert(Kind <= IPVK_Last);
1909 unsigned ValueSiteIndex = 0;
1910
1911 unsigned NumValueSites = ProfileRecord.getNumValueSites(Kind);
1912
1913 // Since there isn't a reliable or fast way for profile reader to tell if a
1914 // profile is generated with `-enable-vtable-value-profiling` on, we run the
1915 // value profile collector over the function IR to find the instrumented sites
1916 // iff function profile records shows the number of instrumented vtable sites
1917 // is not zero. Function cfg already takes the number of instrumented
1918 // indirect call sites into account so it doesn't hash the number of
1919 // instrumented vtables; as a side effect it makes it easier to enable
1920 // profiling and profile use in two steps if needed.
1921 // TODO: Remove this if/when -enable-vtable-value-profiling is on by default.
1922 if (NumValueSites > 0 && Kind == IPVK_VTableTarget &&
1923 NumValueSites != FuncInfo.ValueSites[IPVK_VTableTarget].size() &&
1925 FuncInfo.ValueSites[IPVK_VTableTarget] = VPC.get(IPVK_VTableTarget);
1926 auto &ValueSites = FuncInfo.ValueSites[Kind];
1927 if (NumValueSites != ValueSites.size()) {
1928 auto &Ctx = M->getContext();
1929 Ctx.diagnose(DiagnosticInfoPGOProfile(
1930 M->getName().data(),
1931 Twine("Inconsistent number of value sites for ") +
1932 Twine(ValueProfKindDescr[Kind]) + Twine(" profiling in \"") +
1933 F.getName().str() +
1934 Twine("\", possibly due to the use of a stale profile."),
1935 DS_Warning));
1936 return;
1937 }
1938
1939 for (VPCandidateInfo &I : ValueSites) {
1940 LLVM_DEBUG(dbgs() << "Read one value site profile (kind = " << Kind
1941 << "): Index = " << ValueSiteIndex << " out of "
1942 << NumValueSites << "\n");
1944 *M, *I.AnnotatedInst, ProfileRecord,
1945 static_cast<InstrProfValueKind>(Kind), ValueSiteIndex,
1946 getMaxNumAnnotations(static_cast<InstrProfValueKind>(Kind)));
1947 ValueSiteIndex++;
1948 }
1949}
1950
1951// Collect the set of members for each Comdat in module M and store
1952// in ComdatMembers.
1954 Module &M,
1955 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers) {
1956 if (!DoComdatRenaming)
1957 return;
1958 for (Function &F : M)
1959 if (Comdat *C = F.getComdat())
1960 ComdatMembers.insert(std::make_pair(C, &F));
1961 for (GlobalVariable &GV : M.globals())
1962 if (Comdat *C = GV.getComdat())
1963 ComdatMembers.insert(std::make_pair(C, &GV));
1964 for (GlobalAlias &GA : M.aliases())
1965 if (Comdat *C = GA.getComdat())
1966 ComdatMembers.insert(std::make_pair(C, &GA));
1967}
1968
1969// Return true if we should not find instrumentation data for this function
1970static bool skipPGOUse(const Function &F) {
1971 if (F.isDeclaration())
1972 return true;
1973 // If there are too many critical edges, PGO might cause
1974 // compiler time problem. Skip PGO if the number of
1975 // critical edges execeed the threshold.
1976 unsigned NumCriticalEdges = 0;
1977 for (auto &BB : F) {
1978 const Instruction *TI = BB.getTerminator();
1979 for (unsigned I = 0, E = TI->getNumSuccessors(); I != E; ++I) {
1980 if (isCriticalEdge(TI, I))
1981 NumCriticalEdges++;
1982 }
1983 }
1984 if (NumCriticalEdges > PGOFunctionCriticalEdgeThreshold) {
1985 LLVM_DEBUG(dbgs() << "In func " << F.getName()
1986 << ", NumCriticalEdges=" << NumCriticalEdges
1987 << " exceed the threshold. Skip PGO.\n");
1988 return true;
1989 }
1990 return false;
1991}
1992
1993// Return true if we should not instrument this function
1994static bool skipPGOGen(const Function &F) {
1995 if (skipPGOUse(F))
1996 return true;
1997 if (F.hasFnAttribute(llvm::Attribute::Naked))
1998 return true;
1999 if (F.hasFnAttribute(llvm::Attribute::NoProfile))
2000 return true;
2001 if (F.hasFnAttribute(llvm::Attribute::SkipProfile))
2002 return true;
2003 if (F.getInstructionCount() < PGOFunctionSizeThreshold)
2004 return true;
2006 if (auto EntryCount = F.getEntryCount())
2007 return *EntryCount > PGOColdInstrumentEntryThreshold;
2008 return !PGOTreatUnknownAsCold;
2009 }
2010 return false;
2011}
2012
2014 Module &M, function_ref<TargetLibraryInfo &(Function &)> LookupTLI,
2017 function_ref<LoopInfo *(Function &)> LookupLI,
2018 PGOInstrumentationType InstrumentationType) {
2019 // For the context-sensitive instrumentation, we should have a separated pass
2020 // (before LTO/ThinLTO linking) to create these variables.
2021 if (InstrumentationType == PGOInstrumentationType::FDO)
2022 createIRLevelProfileFlagVar(M, InstrumentationType);
2023
2024 Triple TT(M.getTargetTriple());
2025 LLVMContext &Ctx = M.getContext();
2026 if (!TT.isOSBinFormatELF() && EnableVTableValueProfiling)
2028 M.getName().data(),
2029 Twine("VTable value profiling is presently not "
2030 "supported for non-ELF object formats"),
2031 DS_Warning));
2032 std::unordered_multimap<Comdat *, GlobalValue *> ComdatMembers;
2033 collectComdatMembers(M, ComdatMembers);
2034
2035 for (auto &F : M) {
2036 if (skipPGOGen(F))
2037 continue;
2038 TargetLibraryInfo &TLI = LookupTLI(F);
2039 BranchProbabilityInfo *BPI = LookupBPI(F);
2040 BlockFrequencyInfo *BFI = LookupBFI(F);
2041 LoopInfo *LI = LookupLI(F);
2042 FunctionInstrumenter FI(M, F, TLI, ComdatMembers, BPI, BFI, LI,
2043 InstrumentationType);
2044 FI.instrument();
2045 }
2046 return true;
2047}
2048
2049PreservedAnalyses
2051 createProfileFileNameVar(M, CSInstrName);
2052 // The variable in a comdat may be discarded by LTO. Ensure the declaration
2053 // will be retained.
2056 if (ProfileSampling)
2061 return PA;
2062}
2063
2066 auto &FAM = MAM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
2067 auto LookupTLI = [&FAM](Function &F) -> TargetLibraryInfo & {
2068 return FAM.getResult<TargetLibraryAnalysis>(F);
2069 };
2070 auto LookupBPI = [&FAM](Function &F) {
2071 return &FAM.getResult<BranchProbabilityAnalysis>(F);
2072 };
2073 auto LookupBFI = [&FAM](Function &F) {
2074 return &FAM.getResult<BlockFrequencyAnalysis>(F);
2075 };
2076 auto LookupLI = [&FAM](Function &F) {
2077 return &FAM.getResult<LoopAnalysis>(F);
2078 };
2079
2080 if (!InstrumentAllFunctions(M, LookupTLI, LookupBPI, LookupBFI, LookupLI,
2081 InstrumentationType))
2082 return PreservedAnalyses::all();
2083
2084 return PreservedAnalyses::none();
2085}
2086
2087// Using the ratio b/w sums of profile count values and BFI count values to
2088// adjust the func entry count.
2089static void fixFuncEntryCount(PGOUseFunc &Func, LoopInfo &LI,
2090 BranchProbabilityInfo &NBPI) {
2091 Function &F = Func.getFunc();
2092 BlockFrequencyInfo NBFI(F, NBPI, LI);
2093#ifndef NDEBUG
2094 auto BFIEntryCount = F.getEntryCount();
2095 assert(BFIEntryCount && (*BFIEntryCount > 0) && "Invalid BFI Entrycount");
2096#endif
2097 auto SumCount = APFloat::getZero(APFloat::IEEEdouble());
2098 auto SumBFICount = APFloat::getZero(APFloat::IEEEdouble());
2099 for (auto &BBI : F) {
2100 uint64_t CountValue = 0;
2101 uint64_t BFICountValue = 0;
2102 if (!Func.findBBInfo(&BBI))
2103 continue;
2104 auto BFICount = NBFI.getBlockProfileCount(&BBI);
2105 CountValue = *Func.getBBInfo(&BBI).Count;
2106 BFICountValue = *BFICount;
2107 SumCount.add(APFloat(CountValue * 1.0), APFloat::rmNearestTiesToEven);
2108 SumBFICount.add(APFloat(BFICountValue * 1.0), APFloat::rmNearestTiesToEven);
2109 }
2110 if (SumCount.isZero())
2111 return;
2112
2113 assert(SumBFICount.compare(APFloat(0.0)) == APFloat::cmpGreaterThan &&
2114 "Incorrect sum of BFI counts");
2115 if (SumBFICount.compare(SumCount) == APFloat::cmpEqual)
2116 return;
2117 double Scale = (SumCount / SumBFICount).convertToDouble();
2118 if (Scale < 1.001 && Scale > 0.999)
2119 return;
2120
2121 uint64_t FuncEntryCount = *Func.getBBInfo(&*F.begin()).Count;
2122 uint64_t NewEntryCount = 0.5 + FuncEntryCount * Scale;
2123 if (NewEntryCount == 0)
2124 NewEntryCount = 1;
2125 if (NewEntryCount != FuncEntryCount) {
2126 F.setEntryCount(NewEntryCount);
2127 LLVM_DEBUG(dbgs() << "FixFuncEntryCount: in " << F.getName()
2128 << ", entry_count " << FuncEntryCount << " --> "
2129 << NewEntryCount << "\n");
2130 }
2131}
2132
2133// Compare the profile count values with BFI count values, and print out
2134// the non-matching ones.
2135static void verifyFuncBFI(PGOUseFunc &Func, LoopInfo &LI,
2137 uint64_t HotCountThreshold,
2139 Function &F = Func.getFunc();
2140 BlockFrequencyInfo NBFI(F, NBPI, LI);
2141 // bool PrintFunc = false;
2142 bool HotBBOnly = PGOVerifyHotBFI;
2143 StringRef Msg;
2145
2146 unsigned BBNum = 0, BBMisMatchNum = 0, NonZeroBBNum = 0;
2147 for (auto &BBI : F) {
2148 PGOUseBBInfo *BBInfo = Func.findBBInfo(&BBI);
2149 if (!BBInfo)
2150 continue;
2151
2152 uint64_t CountValue = BBInfo->Count.value_or(CountValue);
2153 uint64_t BFICountValue = 0;
2154
2155 BBNum++;
2156 if (CountValue)
2157 NonZeroBBNum++;
2158 auto BFICount = NBFI.getBlockProfileCount(&BBI);
2159 if (BFICount)
2160 BFICountValue = *BFICount;
2161
2162 if (HotBBOnly) {
2163 bool rawIsHot = CountValue >= HotCountThreshold;
2164 bool BFIIsHot = BFICountValue >= HotCountThreshold;
2165 bool rawIsCold = CountValue <= ColdCountThreshold;
2166 bool ShowCount = false;
2167 if (rawIsHot && !BFIIsHot) {
2168 Msg = "raw-Hot to BFI-nonHot";
2169 ShowCount = true;
2170 } else if (rawIsCold && BFIIsHot) {
2171 Msg = "raw-Cold to BFI-Hot";
2172 ShowCount = true;
2173 }
2174 if (!ShowCount)
2175 continue;
2176 } else {
2177 if ((CountValue < PGOVerifyBFICutoff) &&
2178 (BFICountValue < PGOVerifyBFICutoff))
2179 continue;
2180 uint64_t Diff = (BFICountValue >= CountValue)
2181 ? BFICountValue - CountValue
2182 : CountValue - BFICountValue;
2183 if (Diff <= CountValue / 100 * PGOVerifyBFIRatio)
2184 continue;
2185 }
2186 BBMisMatchNum++;
2187
2188 ORE.emit([&]() {
2190 F.getSubprogram(), &BBI);
2191 Remark << "BB " << ore::NV("Block", BBI.getName())
2192 << " Count=" << ore::NV("Count", CountValue)
2193 << " BFI_Count=" << ore::NV("Count", BFICountValue);
2194 if (!Msg.empty())
2195 Remark << " (" << Msg << ")";
2196 return Remark;
2197 });
2198 }
2199 if (BBMisMatchNum)
2200 ORE.emit([&]() {
2201 return OptimizationRemarkAnalysis(DEBUG_TYPE, "bfi-verify",
2202 F.getSubprogram(), &F.getEntryBlock())
2203 << "In Func " << ore::NV("Function", F.getName())
2204 << ": Num_of_BB=" << ore::NV("Count", BBNum)
2205 << ", Num_of_non_zerovalue_BB=" << ore::NV("Count", NonZeroBBNum)
2206 << ", Num_of_mis_matching_BB=" << ore::NV("Count", BBMisMatchNum);
2207 });
2208}
2209
2211 Module &M, StringRef ProfileFileName, StringRef ProfileRemappingFileName,
2212 vfs::FileSystem &FS,
2213 function_ref<TargetLibraryInfo &(Function &)> LookupTLI,
2216 function_ref<LoopInfo *(Function &)> LookupLI, ProfileSummaryInfo *PSI,
2217 bool IsCS) {
2218 LLVM_DEBUG(dbgs() << "Read in profile counters: ");
2219 auto &Ctx = M.getContext();
2220 // Read the counter array from file.
2221 auto ReaderOrErr = IndexedInstrProfReader::create(ProfileFileName, FS,
2222 ProfileRemappingFileName);
2223 if (Error E = ReaderOrErr.takeError()) {
2224 handleAllErrors(std::move(E), [&](const ErrorInfoBase &EI) {
2225 Ctx.diagnose(
2226 DiagnosticInfoPGOProfile(ProfileFileName.data(), EI.message()));
2227 });
2228 return false;
2229 }
2230
2231 std::unique_ptr<IndexedInstrProfReader> PGOReader =
2232 std::move(ReaderOrErr.get());
2233 if (!PGOReader) {
2234 Ctx.diagnose(DiagnosticInfoPGOProfile(ProfileFileName.data(),
2235 StringRef("Cannot get PGOReader")));
2236 return false;
2237 }
2238 if (!PGOReader->hasCSIRLevelProfile() && IsCS)
2239 return false;
2240
2241 // TODO: might need to change the warning once the clang option is finalized.
2242 if (!PGOReader->isIRLevelProfile()) {
2243 Ctx.diagnose(DiagnosticInfoPGOProfile(
2244 ProfileFileName.data(), "Not an IR level instrumentation profile"));
2245 return false;
2246 }
2247 if (PGOReader->functionEntryOnly()) {
2248 Ctx.diagnose(DiagnosticInfoPGOProfile(
2249 ProfileFileName.data(),
2250 "Function entry profiles are not yet supported for optimization"));
2251 return false;
2252 }
2253
2255 for (GlobalVariable &G : M.globals()) {
2256 if (!G.hasName() || !G.hasMetadata(LLVMContext::MD_type))
2257 continue;
2258
2259 // Create the PGOFuncName meta data.
2260 createPGONameMetadata(G, getPGOName(G, false /* InLTO*/));
2261 }
2262 }
2263
2264 // Add the profile summary (read from the header of the indexed summary) here
2265 // so that we can use it below when reading counters (which checks if the
2266 // function should be marked with a cold or inlinehint attribute).
2267 M.setProfileSummary(PGOReader->getSummary(IsCS).getMD(M.getContext()),
2270 PSI->refresh();
2271
2272 std::unordered_multimap<Comdat *, GlobalValue *> ComdatMembers;
2273 collectComdatMembers(M, ComdatMembers);
2274 std::vector<Function *> HotFunctions;
2275 std::vector<Function *> ColdFunctions;
2276
2277 // If the profile marked as always instrument the entry BB, do the
2278 // same. Note this can be overwritten by the internal option in CFGMST.h
2279 bool InstrumentFuncEntry = PGOReader->instrEntryBBEnabled();
2280 if (PGOInstrumentEntry.getNumOccurrences() > 0)
2281 InstrumentFuncEntry = PGOInstrumentEntry;
2282 bool InstrumentLoopEntries = PGOReader->instrLoopEntriesEnabled();
2283 if (PGOInstrumentLoopEntries.getNumOccurrences() > 0)
2284 InstrumentLoopEntries = PGOInstrumentLoopEntries;
2285
2286 bool HasSingleByteCoverage = PGOReader->hasSingleByteCoverage();
2287 for (auto &F : M) {
2288 if (skipPGOUse(F))
2289 continue;
2290 TargetLibraryInfo &TLI = LookupTLI(F);
2291 BranchProbabilityInfo *BPI = LookupBPI(F);
2292 BlockFrequencyInfo *BFI = LookupBFI(F);
2293 LoopInfo *LI = LookupLI(F);
2294 if (!HasSingleByteCoverage) {
2295 // Split indirectbr critical edges here before computing the MST rather
2296 // than later in getInstrBB() to avoid invalidating it.
2297 SplitIndirectBrCriticalEdges(F, /*IgnoreBlocksWithoutPHI=*/false, BPI,
2298 BFI);
2299 }
2300 PGOUseFunc Func(F, &M, TLI, ComdatMembers, BPI, BFI, LI, PSI, IsCS,
2301 InstrumentFuncEntry, InstrumentLoopEntries,
2302 HasSingleByteCoverage);
2303 if (!Func.getRecord(PGOReader.get()))
2304 continue;
2305 if (HasSingleByteCoverage) {
2306 Func.populateCoverage();
2307 continue;
2308 }
2309 // When PseudoKind is set to a value other than InstrProfRecord::NotPseudo,
2310 // it means the profile for the function is unrepresentative and this
2311 // function is actually hot / warm. We will reset the function hot / cold
2312 // attribute and drop all the profile counters.
2314 bool AllZeros = false;
2315 if (!Func.readCounters(AllZeros, PseudoKind))
2316 continue;
2317 if (AllZeros) {
2318 F.setEntryCount(0);
2319 if (Func.getProgramMaxCount() != 0)
2320 ColdFunctions.push_back(&F);
2321 continue;
2322 }
2323 if (PseudoKind != InstrProfRecord::NotPseudo) {
2324 // Clear function attribute cold.
2325 if (F.hasFnAttribute(Attribute::Cold))
2326 F.removeFnAttr(Attribute::Cold);
2327 // Set function attribute as hot.
2328 if (PseudoKind == InstrProfRecord::PseudoHot)
2329 F.addFnAttr(Attribute::Hot);
2330 continue;
2331 }
2332 Func.populateCounters();
2333 Func.setBranchWeights();
2334 Func.annotateValueSites();
2335 Func.annotateIrrLoopHeaderWeights();
2336 Func.setBlockUniformityAttribute();
2337 PGOUseFunc::FuncFreqAttr FreqAttr = Func.getFuncFreqAttr();
2338 if (FreqAttr == PGOUseFunc::FFA_Cold)
2339 ColdFunctions.push_back(&F);
2340 else if (FreqAttr == PGOUseFunc::FFA_Hot)
2341 HotFunctions.push_back(&F);
2342 if (PGOViewCounts != PGOVCT_None &&
2343 (ViewBlockFreqFuncName.empty() ||
2344 F.getName() == ViewBlockFreqFuncName)) {
2346 CycleInfo CI;
2347 CI.compute(F);
2348 std::unique_ptr<BranchProbabilityInfo> NewBPI =
2349 std::make_unique<BranchProbabilityInfo>(F, CI);
2350 std::unique_ptr<BlockFrequencyInfo> NewBFI =
2351 std::make_unique<BlockFrequencyInfo>(F, *NewBPI, LI);
2353 NewBFI->view();
2354 else if (PGOViewCounts == PGOVCT_Text) {
2355 dbgs() << "pgo-view-counts: " << Func.getFunc().getName() << "\n";
2356 NewBFI->print(dbgs());
2357 }
2358 }
2360 (ViewBlockFreqFuncName.empty() ||
2361 F.getName() == ViewBlockFreqFuncName)) {
2363 if (ViewBlockFreqFuncName.empty())
2364 WriteGraph(&Func, Twine("PGORawCounts_") + Func.getFunc().getName());
2365 else
2366 ViewGraph(&Func, Twine("PGORawCounts_") + Func.getFunc().getName());
2367 else if (PGOViewRawCounts == PGOVCT_Text) {
2368 dbgs() << "pgo-view-raw-counts: " << Func.getFunc().getName() << "\n";
2369 Func.dumpInfo();
2370 }
2371 }
2372
2374 CycleInfo CI;
2375 CI.compute(F);
2377 BranchProbabilityInfo NBPI(F, CI);
2378
2379 // Fix func entry count.
2380 if (PGOFixEntryCount)
2381 fixFuncEntryCount(Func, LI, NBPI);
2382
2383 // Verify BlockFrequency information.
2384 uint64_t HotCountThreshold = 0, ColdCountThreshold = 0;
2385 if (PGOVerifyHotBFI) {
2386 HotCountThreshold = PSI->getOrCompHotCountThreshold();
2388 }
2389 verifyFuncBFI(Func, LI, NBPI, HotCountThreshold, ColdCountThreshold);
2390 }
2391 }
2392
2393 // Set function hotness attribute from the profile.
2394 // We have to apply these attributes at the end because their presence
2395 // can affect the BranchProbabilityInfo of any callers, resulting in an
2396 // inconsistent MST between prof-gen and prof-use.
2397 for (auto &F : HotFunctions) {
2398 F->addFnAttr(Attribute::InlineHint);
2399 LLVM_DEBUG(dbgs() << "Set inline attribute to function: " << F->getName()
2400 << "\n");
2401 }
2402 for (auto &F : ColdFunctions) {
2403 // Only set when there is no Attribute::Hot set by the user. For Hot
2404 // attribute, user's annotation has the precedence over the profile.
2405 if (F->hasFnAttribute(Attribute::Hot)) {
2406 auto &Ctx = M.getContext();
2407 std::string Msg = std::string("Function ") + F->getName().str() +
2408 std::string(" is annotated as a hot function but"
2409 " the profile is cold");
2410 Ctx.diagnose(
2411 DiagnosticInfoPGOProfile(M.getName().data(), Msg, DS_Warning));
2412 continue;
2413 }
2414 F->addFnAttr(Attribute::Cold);
2415 LLVM_DEBUG(dbgs() << "Set cold attribute to function: " << F->getName()
2416 << "\n");
2417 }
2418 return true;
2419}
2420
2422 std::string Filename, std::string RemappingFilename, bool IsCS,
2424 : ProfileFileName(std::move(Filename)),
2425 ProfileRemappingFileName(std::move(RemappingFilename)), IsCS(IsCS),
2426 FS(std::move(VFS)) {
2427 if (!PGOTestProfileFile.empty())
2428 ProfileFileName = PGOTestProfileFile;
2430 ProfileRemappingFileName = PGOTestProfileRemappingFile;
2431 if (!FS)
2433}
2434
2437
2438 auto &FAM = MAM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
2439 auto LookupTLI = [&FAM](Function &F) -> TargetLibraryInfo & {
2440 return FAM.getResult<TargetLibraryAnalysis>(F);
2441 };
2442 auto LookupBPI = [&FAM](Function &F) {
2443 return &FAM.getResult<BranchProbabilityAnalysis>(F);
2444 };
2445 auto LookupBFI = [&FAM](Function &F) {
2446 return &FAM.getResult<BlockFrequencyAnalysis>(F);
2447 };
2448 auto LookupLI = [&FAM](Function &F) {
2449 return &FAM.getResult<LoopAnalysis>(F);
2450 };
2451
2452 auto *PSI = &MAM.getResult<ProfileSummaryAnalysis>(M);
2453 if (!annotateAllFunctions(M, ProfileFileName, ProfileRemappingFileName, *FS,
2454 LookupTLI, LookupBPI, LookupBFI, LookupLI, PSI,
2455 IsCS))
2456 return PreservedAnalyses::all();
2457
2458 return PreservedAnalyses::none();
2459}
2460
2461static std::string getSimpleNodeName(const BasicBlock *Node) {
2462 if (!Node->getName().empty())
2463 return Node->getName().str();
2464
2465 std::string SimpleNodeName;
2466 raw_string_ostream OS(SimpleNodeName);
2467 Node->printAsOperand(OS, false);
2468 return SimpleNodeName;
2469}
2470
2472 uint64_t MaxCount) {
2473 auto Weights = downscaleWeights(EdgeCounts, MaxCount);
2474
2475 LLVM_DEBUG(dbgs() << "Weight is: "; for (const auto &W : Weights) {
2476 dbgs() << W << " ";
2477 } dbgs() << "\n");
2478
2479 misexpect::checkExpectAnnotations(*TI, Weights, /*IsFrontend=*/false);
2480
2481 setBranchWeights(*TI, Weights, /*IsExpected=*/false);
2482
2484 std::string BrCondStr = getBranchCondString(TI);
2485 if (BrCondStr.empty())
2486 return;
2487
2488 uint64_t WSum =
2489 std::accumulate(Weights.begin(), Weights.end(), (uint64_t)0,
2490 [](uint64_t w1, uint64_t w2) { return w1 + w2; });
2491 uint64_t TotalCount =
2492 std::accumulate(EdgeCounts.begin(), EdgeCounts.end(), (uint64_t)0,
2493 [](uint64_t c1, uint64_t c2) { return c1 + c2; });
2494 uint64_t Scale = calculateCountScale(WSum);
2495 BranchProbability BP(scaleBranchCount(Weights[0], Scale),
2496 scaleBranchCount(WSum, Scale));
2497 std::string BranchProbStr;
2498 raw_string_ostream OS(BranchProbStr);
2499 OS << BP;
2500 OS << " (total count : " << TotalCount << ")";
2501 Function *F = TI->getParent()->getParent();
2503 ORE.emit([&]() {
2504 return OptimizationRemark(DEBUG_TYPE, "pgo-instrumentation", TI)
2505 << BrCondStr << " is true with probability : " << BranchProbStr;
2506 });
2507 }
2508}
2509
2510namespace llvm {
2511
2513 MDBuilder MDB(M->getContext());
2514 TI->setMetadata(llvm::LLVMContext::MD_irr_loop,
2516}
2517
2518template <> struct GraphTraits<PGOUseFunc *> {
2519 using NodeRef = const BasicBlock *;
2522
2523 static NodeRef getEntryNode(const PGOUseFunc *G) {
2524 return &G->getFunc().front();
2525 }
2526
2528 return succ_begin(N);
2529 }
2530
2531 static ChildIteratorType child_end(const NodeRef N) { return succ_end(N); }
2532
2533 static nodes_iterator nodes_begin(const PGOUseFunc *G) {
2534 return nodes_iterator(G->getFunc().begin());
2535 }
2536
2537 static nodes_iterator nodes_end(const PGOUseFunc *G) {
2538 return nodes_iterator(G->getFunc().end());
2539 }
2540};
2541
2542template <> struct DOTGraphTraits<PGOUseFunc *> : DefaultDOTGraphTraits {
2543 explicit DOTGraphTraits(bool isSimple = false)
2545
2546 static std::string getGraphName(const PGOUseFunc *G) {
2547 return std::string(G->getFunc().getName());
2548 }
2549
2550 std::string getNodeLabel(const BasicBlock *Node, const PGOUseFunc *Graph) {
2551 std::string Result;
2552 raw_string_ostream OS(Result);
2553
2554 OS << getSimpleNodeName(Node) << ":\\l";
2555 PGOUseBBInfo *BI = Graph->findBBInfo(Node);
2556 OS << "Count : ";
2557 if (BI && BI->Count)
2558 OS << *BI->Count << "\\l";
2559 else
2560 OS << "Unknown\\l";
2561
2562 if (!PGOInstrSelect)
2563 return Result;
2564
2565 for (const Instruction &I : *Node) {
2566 if (!isa<SelectInst>(&I))
2567 continue;
2568 // Display scaled counts for SELECT instruction:
2569 OS << "SELECT : { T = ";
2570 uint64_t TC, FC;
2571 bool HasProf = extractBranchWeights(I, TC, FC);
2572 if (!HasProf)
2573 OS << "Unknown, F = Unknown }\\l";
2574 else
2575 OS << TC << ", F = " << FC << " }\\l";
2576 }
2577 return Result;
2578 }
2579};
2580
2581} // end namespace llvm
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file implements a class to represent arbitrary precision integral constant values and operations...
Function Alias Analysis false
This file contains the simple types necessary to represent the attributes associated with functions a...
This file finds the minimum set of blocks on a CFG that must be instrumented to infer execution cover...
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define clEnumValN(ENUMVAL, FLAGNAME, DESC)
#define LLVM_ABI
Definition Compiler.h:215
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file declares the LLVM IR specialization of the GenericCycle templates.
post inline ee instrument
static BasicBlock * getInstrBB(CFGMST< Edge, BBInfo > &MST, Edge &E, const DenseSet< const BasicBlock * > &ExecBlocks)
#define DEBUG_TYPE
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
Module.h This file contains the declarations for the Module class.
This header defines various interfaces for pass management in LLVM.
#define INSTR_PROF_QUOTE(x)
#define VARIANT_MASK_CSIR_PROF
#define VARIANT_MASK_DBG_CORRELATE
#define INSTR_PROF_RAW_VERSION
#define INSTR_PROF_RAW_VERSION_VAR
#define VARIANT_MASK_TEMPORAL_PROF
#define VARIANT_MASK_IR_PROF
#define VARIANT_MASK_BYTE_COVERAGE
#define VARIANT_MASK_INSTR_ENTRY
#define VARIANT_MASK_FUNCTION_ENTRY_ONLY
#define VARIANT_MASK_INSTR_LOOP_ENTRIES
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define G(x, y, z)
Definition MD5.cpp:55
Machine Check Debug Module
static cl::opt< unsigned > ColdCountThreshold("mfs-count-threshold", cl::desc("Minimum number of times a block must be executed to be retained."), cl::init(1), cl::Hidden)
static constexpr StringLiteral Filename
static GlobalVariable * createIRLevelProfileFlagVar(Module &M, PGOInstrumentationType InstrumentationType)
static cl::opt< std::string > PGOTestProfileRemappingFile("pgo-test-profile-remapping-file", cl::init(""), cl::Hidden, cl::value_desc("filename"), cl::desc("Specify the path of profile remapping file. This is mainly for " "test purpose."))
static void fixFuncEntryCount(PGOUseFunc &Func, LoopInfo &LI, BranchProbabilityInfo &NBPI)
static void annotateFunctionWithHashMismatch(Function &F, LLVMContext &ctx)
static cl::opt< unsigned > MaxNumMemOPAnnotations("memop-max-annotations", cl::init(4), cl::Hidden, cl::desc("Max number of precise value annotations for a single memop" "intrinsic"))
static cl::opt< unsigned > MaxNumAnnotations("icp-max-annotations", cl::init(3), cl::Hidden, cl::desc("Max number of annotations for a single indirect " "call callsite"))
static bool skipPGOGen(const Function &F)
static void collectComdatMembers(Module &M, std::unordered_multimap< Comdat *, GlobalValue * > &ComdatMembers)
static void populateEHOperandBundle(VPCandidateInfo &Cand, DenseMap< BasicBlock *, ColorVector > &BlockColors, SmallVectorImpl< OperandBundleDef > &OpBundles)
static void verifyFuncBFI(PGOUseFunc &Func, LoopInfo &LI, BranchProbabilityInfo &NBPI, uint64_t HotCountThreshold, uint64_t ColdCountThreshold)
static cl::opt< bool > DoComdatRenaming("do-comdat-renaming", cl::init(false), cl::Hidden, cl::desc("Append function hash to the name of COMDAT function to avoid " "function hash mismatch due to the preinliner"))
static bool annotateAllFunctions(Module &M, StringRef ProfileFileName, StringRef ProfileRemappingFileName, vfs::FileSystem &FS, function_ref< TargetLibraryInfo &(Function &)> LookupTLI, function_ref< BranchProbabilityInfo *(Function &)> LookupBPI, function_ref< BlockFrequencyInfo *(Function &)> LookupBFI, function_ref< LoopInfo *(Function &)> LookupLI, ProfileSummaryInfo *PSI, bool IsCS)
static void setupBBInfoEdges(const FuncPGOInstrumentation< PGOUseEdge, PGOUseBBInfo > &FuncInfo)
Set up InEdges/OutEdges for all BBs in the MST.
static bool skipPGOUse(const Function &F)
static bool canRenameComdat(Function &F, std::unordered_multimap< Comdat *, GlobalValue * > &ComdatMembers)
ValueProfileCollector::CandidateInfo VPCandidateInfo
static bool InstrumentAllFunctions(Module &M, function_ref< TargetLibraryInfo &(Function &)> LookupTLI, function_ref< BranchProbabilityInfo *(Function &)> LookupBPI, function_ref< BlockFrequencyInfo *(Function &)> LookupBFI, function_ref< LoopInfo *(Function &)> LookupLI, PGOInstrumentationType InstrumentationType)
static uint64_t sumEdgeCount(const ArrayRef< PGOUseEdge * > Edges)
static uint32_t getMaxNumAnnotations(InstrProfValueKind ValueProfKind)
static cl::opt< bool > DisableValueProfiling("disable-vp", cl::init(false), cl::Hidden, cl::desc("Disable Value Profiling"))
static std::string getSimpleNodeName(const BasicBlock *Node)
static bool isIndirectBrTarget(BasicBlock *BB)
static cl::opt< std::string > PGOTestProfileFile("pgo-test-profile-file", cl::init(""), cl::Hidden, cl::value_desc("filename"), cl::desc("Specify the path of profile data file. This is " "mainly for test purpose."))
static std::string getBranchCondString(Instruction *TI)
static const char * ValueProfKindDescr[]
This file provides the interface for IR based instrumentation passes ( (profile-gen,...
FunctionAnalysisManager FAM
ModuleAnalysisManager MAM
if(PassOpts->AAPipeline)
This file contains the declarations for profiling metadata utility functions.
const SmallVectorImpl< MachineOperand > & Cond
static cl::opt< RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode > Mode("regalloc-enable-advisor", cl::Hidden, cl::init(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default), cl::desc("Enable regalloc advisor mode"), cl::values(clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default, "default", "Default"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Release, "release", "precompiled"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Development, "development", "for training")))
const char * Msg
static void visit(BasicBlock &Start, std::function< bool(BasicBlock *)> op)
std::pair< BasicBlock *, BasicBlock * > Edge
This file contains some templates that are useful if you are working with the STL at all.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
StringSet - A set-like wrapper for the StringMap.
#define LLVM_DEBUG(...)
Definition Debug.h:119
Defines the virtual file system interface vfs::FileSystem.
Value * RHS
void printAsOperand(OutputBuffer &OB, Prec P=Prec::Default, bool StrictlyWorse=false) const
static const fltSemantics & IEEEdouble()
Definition APFloat.h:298
static constexpr roundingMode rmNearestTiesToEven
Definition APFloat.h:345
static APFloat getZero(const fltSemantics &Sem, bool Negative=false)
Factory for Positive and Negative Zero.
Definition APFloat.h:1165
Class for arbitrary precision integers.
Definition APInt.h:78
This templated class represents "all analyses that operate over <aparticular IR unit>" (e....
Definition Analysis.h:50
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
iterator end() const
Definition ArrayRef.h:130
size_t size() const
Get the array size.
Definition ArrayRef.h:141
iterator begin() const
Definition ArrayRef.h:129
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator end()
Definition BasicBlock.h:474
LLVM_ABI InstListType::const_iterator getFirstNonPHIIt() const
Returns an iterator to the first instruction in this block that is not a PHINode instruction.
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
LLVM_ABI const_iterator getFirstNonPHIOrDbgOrAlloca() const
Returns an iterator to the first instruction in this block that is not a PHINode, a debug intrinsic,...
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
Analysis pass which computes BlockFrequencyInfo.
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
LLVM_ABI bool isIrrLoopHeader(const BasicBlock *BB)
Returns true if BB is an irreducible loop header block.
LLVM_ABI std::optional< uint64_t > getBlockProfileCount(const BasicBlock *BB, bool AllowSynthetic=false) const
Returns the estimated profile count of BB.
Analysis pass which computes BranchProbabilityInfo.
Analysis providing branch probability information.
Edge & addEdge(BasicBlock *Src, BasicBlock *Dest, uint64_t W)
Definition CFGMST.h:330
const std::vector< std::unique_ptr< Edge > > & allEdges() const
Definition CFGMST.h:367
size_t numEdges() const
Definition CFGMST.h:373
Predicate getPredicate() const
Return the predicate for this instruction.
Definition InstrTypes.h:828
LLVM_ABI StringRef getName() const
Definition Comdat.cpp:28
void setSelectionKind(SelectionKind Val)
Definition Comdat.h:48
SelectionKind getSelectionKind() const
Definition Comdat.h:47
Conditional Branch instruction.
Value * getCondition() const
static ConstantAsMetadata * get(Constant *C)
Definition Metadata.h:537
static LLVM_ABI Constant * getPointerBitCastOrAddrSpaceCast(Constant *C, Type *Ty)
Create a BitCast or AddrSpaceCast for a pointer type depending on the address space.
This is the shared class of boolean and integer constants.
Definition Constants.h:87
bool isMinusOne() const
This function will return true iff every bit in this constant is set to true.
Definition Constants.h:231
bool isOne() const
This is just a convenience method to make client code smaller for a common case.
Definition Constants.h:225
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
Definition Constants.h:219
static LLVM_ABI Constant * getIntegerValue(Type *Ty, const APInt &V)
Return the value for an integer or pointer constant, or a vector thereof, with the given scalar value...
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:223
bool empty() const
Definition DenseMap.h:171
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:284
Diagnostic information for the PGO profiler.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:151
Base class for error info classes.
Definition Error.h:44
virtual std::string message() const
Return the error message as a string.
Definition Error.h:52
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
void compute(FunctionT &F)
Compute the cycle info for a function.
static LLVM_ABI GlobalAlias * create(Type *Ty, unsigned AddressSpace, LinkageTypes Linkage, const Twine &Name, Constant *Aliasee, Module *Parent)
If a parent module is specified, the alias is automatically inserted into the end of the specified mo...
Definition Globals.cpp:692
@ HiddenVisibility
The GV is hidden.
Definition GlobalValue.h:69
@ ExternalLinkage
Externally visible function.
Definition GlobalValue.h:53
@ WeakAnyLinkage
Keep one copy of named function when linking (weak)
Definition GlobalValue.h:57
@ AvailableExternallyLinkage
Available for inspection, not emission.
Definition GlobalValue.h:54
@ LinkOnceODRLinkage
Same, but only replaced by something equivalent.
Definition GlobalValue.h:56
This instruction compares its operands according to the predicate given to the constructor.
static Expected< std::unique_ptr< IndexedInstrProfReader > > create(const Twine &Path, vfs::FileSystem &FS, const Twine &RemappingPath="")
Factory method to create an indexed reader.
uint64_t getMaximumFunctionCount(bool UseCS)
Return the maximum of all known function counts.
Expected< NamedInstrProfRecord > getInstrProfRecord(StringRef FuncName, uint64_t FuncHash, StringRef DeprecatedFuncName="", uint64_t *MismatchedFuncSum=nullptr)
Return the NamedInstrProfRecord associated with FuncName and FuncHash.
Base class for instruction visitors.
Definition InstVisitor.h:78
static bool canInstrumentCallsite(const CallBase &CB)
instrprof_error get() const
Definition InstrProf.h:476
std::string message() const override
Return the error message as a string.
LLVM_ABI unsigned getNumSuccessors() const LLVM_READONLY
Return the number of successors that this instruction has.
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
A smart pointer to a reference-counted object that inherits from RefCountedBase or ThreadSafeRefCount...
uint32_t getCRC() const
Definition CRC.h:53
LLVM_ABI void update(ArrayRef< uint8_t > Data)
Definition CRC.cpp:103
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
LLVM_ABI void diagnose(const DiagnosticInfo &DI)
Report a message to the currently installed diagnostic handler.
Analysis pass that exposes the LoopInfo for a function.
Definition LoopInfo.h:588
LLVM_ABI MDString * createString(StringRef Str)
Return the given string as metadata.
Definition MDBuilder.cpp:21
LLVM_ABI MDNode * createIrrLoopHeaderWeight(uint64_t Weight)
Return metadata containing an irreducible loop header weight.
Metadata node.
Definition Metadata.h:1069
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1565
Tuple of metadata.
Definition Metadata.h:1482
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1511
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
Diagnostic information for optimization analysis remarks.
The optimization diagnostic interface.
LLVM_ABI void emit(DiagnosticInfoOptimizationBase &OptDiag)
Output the remark via the diagnostic handler and to the optimization record file.
Diagnostic information for applied optimization remarks.
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &MAM)
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &MAM)
LLVM_ABI PGOInstrumentationUse(std::string Filename="", std::string RemappingFilename="", bool IsCS=false, IntrusiveRefCntPtr< vfs::FileSystem > FS=nullptr)
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &MAM)
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition Analysis.h:115
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & preserveSet()
Mark an analysis set as preserved.
Definition Analysis.h:151
PreservedAnalyses & preserve()
Mark an analysis as preserved.
Definition Analysis.h:132
An analysis pass based on the new PM to deliver ProfileSummaryInfo.
Analysis providing profile information.
LLVM_ABI uint64_t getOrCompColdCountThreshold() const
Returns ColdCountThreshold if set.
LLVM_ABI bool isColdCount(uint64_t C) const
Returns true if count C is considered cold.
LLVM_ABI void refresh(std::unique_ptr< ProfileSummary > &&Other=nullptr)
If a summary is provided as argument, use that.
LLVM_ABI bool isHotCount(uint64_t C) const
Returns true if count C is considered hot.
LLVM_ABI uint64_t getOrCompHotCountThreshold() const
Returns HotCountThreshold if set.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
constexpr const char * data() const
Get a pointer to the start of the string (which may not be null terminated).
Definition StringRef.h:138
Analysis pass providing the TargetLibraryInfo.
Provides information about what library functions are available for the current target.
EltTy front() const
unsigned size() const
Triple - Helper class for working with autoconf configuration names.
Definition Triple.h:48
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
LLVM_ABI std::string str() const
Return the twine contents as a std::string.
Definition Twine.cpp:17
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
Definition Type.cpp:310
LLVM_ABI void print(raw_ostream &O, bool IsForDebug=false, bool NoDetails=false) const
Print the current type.
Value * getOperand(unsigned i) const
Definition User.h:207
std::vector< CandidateInfo > get(InstrProfValueKind Kind) const
returns a list of value profiling candidates of the given kind
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:255
An efficient, type-erasing, non-owning reference to a callable.
const ParentTy * getParent() const
Definition ilist_node.h:34
A raw_ostream that writes to an std::string.
The virtual file system interface.
This provides a very simple, boring adaptor for a begin and end iterator into a range type.
This file contains the declaration of the Comdat class, which represents a single COMDAT in LLVM.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:81
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > OverloadTys={})
Look up the Function declaration of the intrinsic id in the Module M.
ValuesClass values(OptsTy... Options)
Helper to build a ValuesClass by forwarding a variable number of arguments as an initializer list to ...
initializer< Ty > init(const Ty &Val)
uint64_t getFuncHash(const FuncRecordTy *Record)
Return the structural hash associated with the function.
LLVM_ABI void checkExpectAnnotations(const Instruction &I, ArrayRef< uint32_t > ExistingWeights, bool IsFrontend)
checkExpectAnnotations - compares PGO counters to the thresholds used for llvm.expect and warns if th...
DiagnosticInfoOptimizationBase::Argument NV
NodeAddr< FuncNode * > Func
Definition RDFGraph.h:395
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
void write64le(void *P, uint64_t V)
Definition Endian.h:478
LLVM_ABI IntrusiveRefCntPtr< FileSystem > getRealFileSystem()
Gets an vfs::FileSystem for the 'real' file system, as seen by the operating system.
This is an optimization pass for GlobalISel generic memory operations.
static cl::opt< bool > PGOTreatUnknownAsCold("pgo-treat-unknown-as-cold", cl::init(false), cl::Hidden, cl::desc("For cold function instrumentation, treat count unknown(e.g. " "unprofiled) functions as cold."))
static cl::opt< bool > PGOInstrMemOP("pgo-instr-memop", cl::init(true), cl::Hidden, cl::desc("Use this option to turn on/off " "memory intrinsic size profiling."))
LLVM_ABI void setIrrLoopHeaderMetadata(Module *M, Instruction *TI, uint64_t Count)
LLVM_ABI void setProfMetadata(Instruction *TI, ArrayRef< uint64_t > EdgeCounts, uint64_t MaxCount)
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition STLExtras.h:1669
LLVM_ABI std::string getPGOFuncName(const Function &F, bool InLTO=false, uint64_t Version=INSTR_PROF_INDEX_VERSION)
Please use getIRPGOFuncName for LLVM IR instrumentation.
static cl::opt< bool > PGOViewBlockCoverageGraph("pgo-view-block-coverage-graph", cl::desc("Create a dot file of CFGs with block " "coverage inference information"))
LLVM_ABI void createPGOFuncNameMetadata(Function &F, StringRef PGOFuncName)
Create the PGOFuncName meta data if PGOFuncName is different from function's raw name.
LLVM_ABI unsigned GetSuccessorNumber(const BasicBlock *BB, const BasicBlock *Succ)
Search for the specified successor of basic block BB and return its position in the terminator instru...
Definition CFG.cpp:90
LLVM_ABI std::string getIRPGOFuncName(const Function &F, bool InLTO=false)
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
RelativeUniformCounterPtr ValuesPtrExpr NumValueSites[IPVK_Last+1]
Definition InstrProf.h:95
auto successors(const MachineBasicBlock *BB)
LLVM_ABI void createProfileSamplingVar(Module &M)
void handleAllErrors(Error E, HandlerTs &&... Handlers)
Behaves the same as handleErrors, except that by contract all errors must be handled by the given han...
Definition Error.h:1013
constexpr from_range_t from_range
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
LLVM_ABI bool SplitIndirectBrCriticalEdges(Function &F, bool IgnoreBlocksWithoutPHI, BranchProbabilityInfo *BPI=nullptr, BlockFrequencyInfo *BFI=nullptr, DomTreeUpdater *DTU=nullptr)
LLVM_ABI DenseMap< BasicBlock *, ColorVector > colorEHFunclets(Function &F)
If an EH funclet personality is in use (see isFuncletEHPersonality), this will recompute which blocks...
LLVM_ABI void createPGONameMetadata(GlobalObject &GO, StringRef PGOName)
Create the PGOName metadata if a global object's PGO name is different from its mangled name.
InnerAnalysisManagerProxy< FunctionAnalysisManager, Module > FunctionAnalysisManagerModuleProxy
Provide the FunctionAnalysisManager to Module proxy.
static cl::opt< bool > PGOBlockCoverage("pgo-block-coverage", cl::desc("Use this option to enable basic block coverage instrumentation"))
cl::opt< bool > PGOWarnMissing
raw_ostream & WriteGraph(raw_ostream &O, const GraphType &G, bool ShortNames=false, const Twine &Title="")
cl::opt< unsigned > MaxNumVTableAnnotations("icp-max-num-vtables", cl::init(6), cl::Hidden, cl::desc("Max number of vtables annotated for a vtable load instruction."))
static cl::opt< bool > PGOTemporalInstrumentation("pgo-temporal-instrumentation", cl::desc("Use this option to enable temporal instrumentation"))
cl::opt< bool > EnableVTableProfileUse("enable-vtable-profile-use", cl::init(false), cl::desc("If ThinLTO and WPD is enabled and this option is true, vtable " "profiles will be used by ICP pass for more efficient indirect " "call sequence. If false, type profiles won't be used."))
bool isScopedEHPersonality(EHPersonality Pers)
Returns true if this personality uses scope-style EH IR instructions: catchswitch,...
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
LLVM_ABI void setBranchWeights(Instruction &I, ArrayRef< uint32_t > Weights, bool IsExpected, bool ElideAllZero=false)
Create a new branch_weights metadata node and add or overwrite a prof metadata reference to instructi...
FuncHash
Definition InstrProf.h:78
LLVM_ABI std::string getPGOName(const GlobalVariable &V, bool InLTO=false)
cl::opt< std::string > ViewBlockFreqFuncName("view-bfi-func-name", cl::Hidden, cl::desc("The option to specify " "the name of the function " "whose CFG will be displayed."))
LLVM_ABI GlobalVariable * createPGOFuncNameVar(Function &F, StringRef PGOFuncName)
Create and return the global variable for function name used in PGO instrumentation.
LLVM_ABI void annotateValueSite(Module &M, Instruction &Inst, const InstrProfRecord &InstrProfR, InstrProfValueKind ValueKind, uint32_t SiteIndx, uint32_t MaxMDCount=3)
Get the value profile data for value site SiteIdx from InstrProfR and annotate the instruction Inst w...
auto reverse(ContainerTy &&C)
Definition STLExtras.h:407
static cl::opt< bool > EmitBranchProbability("pgo-emit-branch-prob", cl::init(false), cl::Hidden, cl::desc("When this option is on, the annotated " "branch probability will be emitted as " "optimization remarks: -{Rpass|" "pass-remarks}=pgo-instrumentation"))
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
static cl::opt< unsigned > PGOVerifyBFIRatio("pgo-verify-bfi-ratio", cl::init(2), cl::Hidden, cl::desc("Set the threshold for pgo-verify-bfi: only print out " "mismatched BFI if the difference percentage is greater than " "this value (in percentage)."))
static cl::opt< bool > PGOInstrumentLoopEntries("pgo-instrument-loop-entries", cl::init(false), cl::Hidden, cl::desc("Force to instrument loop entries."))
static cl::opt< unsigned > PGOFunctionSizeThreshold("pgo-function-size-threshold", cl::Hidden, cl::desc("Do not instrument functions smaller than this threshold."))
LLVM_ABI EHPersonality classifyEHPersonality(const Value *Pers)
See if the given exception handling personality function is one that we understand.
static cl::opt< bool > PGOFixEntryCount("pgo-fix-entry-count", cl::init(true), cl::Hidden, cl::desc("Fix function entry count in profile use."))
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
static cl::opt< PGOViewCountsType > PGOViewRawCounts("pgo-view-raw-counts", cl::Hidden, cl::desc("A boolean option to show CFG dag or text " "with raw profile counts from " "profile data. See also option " "-pgo-view-counts. To limit graph " "display to only one function, use " "filtering option -view-bfi-func-name."), cl::values(clEnumValN(PGOVCT_None, "none", "do not show."), clEnumValN(PGOVCT_Graph, "graph", "show a graph."), clEnumValN(PGOVCT_Text, "text", "show in text.")))
static cl::opt< bool > PGOVerifyBFI("pgo-verify-bfi", cl::init(false), cl::Hidden, cl::desc("Print out mismatched BFI counts after setting profile metadata " "The print is enabled under -Rpass-analysis=pgo, or " "internal option -pass-remarks-analysis=pgo."))
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
cl::opt< bool > NoPGOWarnMismatch
RNSuccIterator< NodeRef, BlockT, RegionT > succ_begin(NodeRef Node)
static cl::opt< uint64_t > PGOColdInstrumentEntryThreshold("pgo-cold-instrument-entry-threshold", cl::init(0), cl::Hidden, cl::desc("For cold function instrumentation, skip instrumenting functions " "whose entry count is above the given value."))
IRBuilder(LLVMContext &, FolderTy, InserterTy, MDNode *, ArrayRef< OperandBundleDef >) -> IRBuilder< FolderTy, InserterTy >
InstrProfValueKind
Definition InstrProf.h:323
cl::opt< PGOViewCountsType > PGOViewCounts("pgo-view-counts", cl::Hidden, cl::desc("A boolean option to show CFG dag or text with " "block profile counts and branch probabilities " "right after PGO profile annotation step. The " "profile counts are computed using branch " "probabilities from the runtime profile data and " "block frequency propagation algorithm. To view " "the raw counts from the profile, use option " "-pgo-view-raw-counts instead. To limit graph " "display to only one function, use filtering option " "-view-bfi-func-name."), cl::values(clEnumValN(PGOVCT_None, "none", "do not show."), clEnumValN(PGOVCT_Graph, "graph", "show a graph."), clEnumValN(PGOVCT_Text, "text", "show in text.")))
RNSuccIterator< NodeRef, BlockT, RegionT > succ_end(NodeRef Node)
OperandBundleDefT< Value * > OperandBundleDef
Definition AutoUpgrade.h:34
LLVM_ABI void appendToCompilerUsed(Module &M, ArrayRef< GlobalValue * > Values)
Adds global values to the llvm.compiler.used list.
static cl::opt< unsigned > PGOVerifyBFICutoff("pgo-verify-bfi-cutoff", cl::init(5), cl::Hidden, cl::desc("Set the threshold for pgo-verify-bfi: skip the counts whose " "profile count value is below."))
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
LLVM_ABI BasicBlock * SplitCriticalEdge(Instruction *TI, unsigned SuccNum, const CriticalEdgeSplittingOptions &Options=CriticalEdgeSplittingOptions(), const Twine &BBName="")
If this edge is a critical edge, insert a new node to split the critical edge.
void ViewGraph(const GraphType &G, const Twine &Name, bool ShortNames=false, const Twine &Title="", GraphProgram::Name Program=GraphProgram::DOT)
ViewGraph - Emit a dot graph, run 'dot', run gv on the postscript file, then cleanup.
LLVM_ABI bool isCriticalEdge(const Instruction *TI, unsigned SuccNum, bool AllowIdenticalEdges=false)
Return true if the specified edge is a critical edge.
Definition CFG.cpp:106
cl::opt< bool > PGOInstrumentColdFunctionOnly
cl::list< std::string > CtxPGOSkipCallsiteInstrument("ctx-prof-skip-callsite-instr", cl::Hidden, cl::desc("Do not instrument callsites to functions in this list. Intended " "for testing."))
LLVM_ABI bool canRenameComdatFunc(const Function &F, bool CheckAddressTaken=false)
Check if we can safely rename this Comdat function.
static cl::opt< bool > PGOInstrSelect("pgo-instr-select", cl::init(true), cl::Hidden, cl::desc("Use this option to turn on/off SELECT " "instruction instrumentation. "))
LLVM_ABI void createProfileFileNameVar(Module &M, StringRef InstrProfileOutput)
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1917
TinyPtrVector< BasicBlock * > ColorVector
LLVM_ABI bool extractBranchWeights(const MDNode *ProfileData, SmallVectorImpl< uint32_t > &Weights)
Extract branch weights from MD_prof metadata.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
auto predecessors(const MachineBasicBlock *BB)
Instruction::const_succ_iterator const_succ_iterator
Definition CFG.h:127
llvm::cl::opt< llvm::InstrProfCorrelator::ProfCorrelatorKind > ProfileCorrelate
static cl::opt< bool > PGOFunctionEntryCoverage("pgo-function-entry-coverage", cl::Hidden, cl::desc("Use this option to enable function entry coverage instrumentation."))
static cl::opt< unsigned > PGOFunctionCriticalEdgeThreshold("pgo-critical-edge-threshold", cl::init(20000), cl::Hidden, cl::desc("Do not instrument functions with the number of critical edges " " greater than this threshold."))
uint32_t scaleBranchCount(uint64_t Count, uint64_t Scale)
Scale an individual branch count.
static cl::opt< bool > PGOVerifyHotBFI("pgo-verify-hot-bfi", cl::init(false), cl::Hidden, cl::desc("Print out the non-match BFI count if a hot raw profile count " "becomes non-hot, or a cold raw profile count becomes hot. " "The print is enabled under -Rpass-analysis=pgo, or " "internal option -pass-remarks-analysis=pgo."))
uint64_t calculateCountScale(uint64_t MaxCount)
Calculate what to divide by to scale counts.
LLVM_ABI SmallVector< uint32_t > downscaleWeights(ArrayRef< uint64_t > Weights, std::optional< uint64_t > KnownMaxCount=std::nullopt)
downscale the given weights preserving the ratio.
LLVM_ABI bool isGPUProfTarget(const Module &M)
Determines whether module targets a GPU eligable for PGO instrumentation.
cl::opt< bool > EnableVTableValueProfiling("enable-vtable-value-profiling", cl::init(false), cl::desc("If true, the virtual table address will be instrumented to know " "the types of a C++ pointer. The information is used in indirect " "call promotion to do selective vtable-based comparison."))
static cl::opt< bool > PGOInstrumentEntry("pgo-instrument-entry", cl::init(false), cl::Hidden, cl::desc("Force to instrument function entry basicblock."))
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition MIRParser.h:39
static cl::opt< std::string > PGOTraceFuncHash("pgo-trace-func-hash", cl::init("-"), cl::Hidden, cl::value_desc("function name"), cl::desc("Trace the hash of the function with this name."))
cl::opt< bool > NoPGOWarnMismatchComdatWeak
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:878
#define N
static std::string getGraphName(const PGOUseFunc *G)
std::string getNodeLabel(const BasicBlock *Node, const PGOUseFunc *Graph)
DefaultDOTGraphTraits(bool simple=false)
static ChildIteratorType child_end(const NodeRef N)
static NodeRef getEntryNode(const PGOUseFunc *G)
static ChildIteratorType child_begin(const NodeRef N)
static nodes_iterator nodes_end(const PGOUseFunc *G)
static nodes_iterator nodes_begin(const PGOUseFunc *G)
pointer_iterator< Function::const_iterator > nodes_iterator
bool isBlockUniform(unsigned BlockIdx) const
Check if a basic block is entered via a wave-uniform branch.
Definition InstrProf.h:952
std::vector< uint64_t > Counts
Definition InstrProf.h:907
CountPseudoKind getCountPseudoKind() const
Definition InstrProf.h:1035
uint32_t getNumValueSites(uint32_t ValueKind) const
Return the number of instrumented sites for ValueKind.
Definition InstrProf.h:1147
std::vector< uint8_t > UniformityBits
For AMDGPU offload profiling: 1 bit per basic block indicating whether the block is usually entered w...
Definition InstrProf.h:915
static void setCSFlagInHash(uint64_t &FuncHash)
Definition InstrProf.h:1128
static constexpr uint64_t FUNC_HASH_MASK
Definition InstrProf.h:1103