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
53#include "llvm/ADT/APInt.h"
54#include "llvm/ADT/ArrayRef.h"
55#include "llvm/ADT/STLExtras.h"
57#include "llvm/ADT/Statistic.h"
58#include "llvm/ADT/StringRef.h"
59#include "llvm/ADT/StringSet.h"
60#include "llvm/ADT/Twine.h"
61#include "llvm/ADT/iterator.h"
65#include "llvm/Analysis/CFG.h"
71#include "llvm/IR/Attributes.h"
72#include "llvm/IR/BasicBlock.h"
73#include "llvm/IR/CFG.h"
74#include "llvm/IR/Comdat.h"
75#include "llvm/IR/Constant.h"
76#include "llvm/IR/Constants.h"
77#include "llvm/IR/CycleInfo.h"
80#include "llvm/IR/Function.h"
81#include "llvm/IR/GlobalAlias.h"
82#include "llvm/IR/GlobalValue.h"
84#include "llvm/IR/IRBuilder.h"
85#include "llvm/IR/InstVisitor.h"
86#include "llvm/IR/InstrTypes.h"
87#include "llvm/IR/Instruction.h"
90#include "llvm/IR/Intrinsics.h"
91#include "llvm/IR/LLVMContext.h"
92#include "llvm/IR/MDBuilder.h"
93#include "llvm/IR/Module.h"
94#include "llvm/IR/PassManager.h"
97#include "llvm/IR/Type.h"
98#include "llvm/IR/Value.h"
102#include "llvm/Support/CRC.h"
103#include "llvm/Support/Casting.h"
107#include "llvm/Support/Debug.h"
108#include "llvm/Support/Error.h"
120#include <algorithm>
121#include <cassert>
122#include <cstdint>
123#include <memory>
124#include <numeric>
125#include <optional>
126#include <stack>
127#include <string>
128#include <unordered_map>
129#include <utility>
130#include <vector>
131
132using namespace llvm;
134
135#define DEBUG_TYPE "pgo-instrumentation"
136
137STATISTIC(NumOfPGOInstrument, "Number of edges instrumented.");
138STATISTIC(NumOfPGOSelectInsts, "Number of select instruction instrumented.");
139STATISTIC(NumOfPGOMemIntrinsics, "Number of mem intrinsics instrumented.");
140STATISTIC(NumOfPGOEdge, "Number of edges.");
141STATISTIC(NumOfPGOBB, "Number of basic-blocks.");
142STATISTIC(NumOfPGOSplit, "Number of critical edge splits.");
143STATISTIC(NumOfPGOFunc, "Number of functions having valid profile counts.");
144STATISTIC(NumOfPGOMismatch, "Number of functions having mismatch profile.");
145STATISTIC(NumOfPGOMissing, "Number of functions without profile.");
146STATISTIC(NumOfPGOICall, "Number of indirect call value instrumentations.");
147STATISTIC(NumOfCSPGOInstrument, "Number of edges instrumented in CSPGO.");
148STATISTIC(NumOfCSPGOSelectInsts,
149 "Number of select instruction instrumented in CSPGO.");
150STATISTIC(NumOfCSPGOMemIntrinsics,
151 "Number of mem intrinsics instrumented in CSPGO.");
152STATISTIC(NumOfCSPGOEdge, "Number of edges in CSPGO.");
153STATISTIC(NumOfCSPGOBB, "Number of basic-blocks in CSPGO.");
154STATISTIC(NumOfCSPGOSplit, "Number of critical edge splits in CSPGO.");
155STATISTIC(NumOfCSPGOFunc,
156 "Number of functions having valid profile counts in CSPGO.");
157STATISTIC(NumOfCSPGOMismatch,
158 "Number of functions having mismatch profile in CSPGO.");
159STATISTIC(NumOfCSPGOMissing, "Number of functions without profile in CSPGO.");
160STATISTIC(NumCoveredBlocks, "Number of basic blocks that were executed");
161
162namespace llvm {
163
164// Command line option to enable/disable the warning about a hash mismatch in
165// the profile data.
167 NoPGOWarnMismatch("no-pgo-warn-mismatch", cl::init(false), cl::Hidden,
168 cl::desc("Use this option to turn off/on "
169 "warnings about profile cfg mismatch."));
170
172
173// Command line option to turn on CFG dot dump after profile annotation.
174// Defined in Analysis/BlockFrequencyInfo.cpp: -pgo-view-counts
176
177// Command line option to specify the name of the function for CFG dump
178// Defined in Analysis/BlockFrequencyInfo.cpp: -view-bfi-func-name=
180
181// Command line option to enable vtable value profiling. Defined in
182// ProfileData/InstrProf.cpp: -enable-vtable-value-profiling=
185} // namespace llvm
186
188 return InstrumentationOptions::Global.pgo_instrument_cold_function_only;
189}
190
191namespace {
192class FunctionInstrumenter final {
193 const InstrumentationOptions &Opts;
194 Module &M;
195 Function &F;
197 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers;
198 BranchProbabilityInfo *const BPI;
199 BlockFrequencyInfo *const BFI;
200 LoopInfo *const LI;
201
202 const PGOInstrumentationType InstrumentationType;
203
204 // FIXME(mtrofin): re-enable this for ctx profiling, for non-indirect calls.
205 // Ctx profiling implicitly captures indirect call cases, but not other
206 // values. Supporting other values is relatively straight-forward - just
207 // another counter range within the context.
208 bool isValueProfilingDisabled() const {
209 // Value profiling is disabled for GPU targets because the device-side
210 // profiling runtime does not yet implement
211 // __llvm_profile_instrument_target. The existing compiler-rt implementation
212 // uses a linked-list with locks and eviction policy that is not efficient
213 // for massively parallel GPU execution. A GPU-optimized implementation is
214 // left as future work.
215 return Opts.disable_vp ||
216 InstrumentationType == PGOInstrumentationType::CTXPROF ||
218 }
219
220 bool shouldInstrumentEntryBB() const {
221 return valueOr(Opts.pgo_instrument_entry, false) ||
222 InstrumentationType == PGOInstrumentationType::CTXPROF;
223 }
224
225 bool shouldInstrumentLoopEntries() const {
226 return valueOr(Opts.pgo_instrument_loop_entries, false);
227 }
228
229public:
230 FunctionInstrumenter(
231 const InstrumentationOptions &Opts, Module &M, Function &F,
232 TargetLibraryInfo &TLI,
233 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers,
234 BranchProbabilityInfo *BPI = nullptr, BlockFrequencyInfo *BFI = nullptr,
235 LoopInfo *LI = nullptr,
236 PGOInstrumentationType InstrumentationType = PGOInstrumentationType::FDO)
237 : Opts(Opts), M(M), F(F), TLI(TLI), ComdatMembers(ComdatMembers),
238 BPI(BPI), BFI(BFI), LI(LI), InstrumentationType(InstrumentationType) {}
239
240 void instrument();
241};
242} // namespace
243
244// Return a string describing the branch condition that can be
245// used in static branch probability heuristics:
246static std::string getBranchCondString(Instruction *TI) {
248 if (!BI)
249 return std::string();
250
251 Value *Cond = BI->getCondition();
253 if (!CI)
254 return std::string();
255
256 std::string result;
257 raw_string_ostream OS(result);
258 OS << CI->getPredicate() << "_";
259 CI->getOperand(0)->getType()->print(OS, true);
260
261 Value *RHS = CI->getOperand(1);
263 if (CV) {
264 if (CV->isZero())
265 OS << "_Zero";
266 else if (CV->isOne())
267 OS << "_One";
268 else if (CV->isMinusOne())
269 OS << "_MinusOne";
270 else
271 OS << "_Const";
272 }
273 return result;
274}
275
276static const char *ValueProfKindDescr[] = {
277#define VALUE_PROF_KIND(Enumerator, Value, Descr) Descr,
279};
280
281// Create a COMDAT variable INSTR_PROF_RAW_VERSION_VAR to make the runtime
282// aware this is an ir_level profile so it can set the version flag.
283static GlobalVariable *
284createIRLevelProfileFlagVar(const InstrumentationOptions &Opts, Module &M,
285 PGOInstrumentationType InstrumentationType) {
287 Type *IntTy64 = Type::getInt64Ty(M.getContext());
289 if (InstrumentationType == PGOInstrumentationType::CSFDO)
290 ProfileVersion |= VARIANT_MASK_CSIR_PROF;
291 if (valueOr(Opts.pgo_instrument_entry, false) ||
292 InstrumentationType == PGOInstrumentationType::CTXPROF)
293 ProfileVersion |= VARIANT_MASK_INSTR_ENTRY;
294 if (valueOr(Opts.pgo_instrument_loop_entries, false))
295 ProfileVersion |= VARIANT_MASK_INSTR_LOOP_ENTRIES;
296 if (Opts.profile_correlate == InstrProfCorrelator::DEBUG_INFO)
297 ProfileVersion |= VARIANT_MASK_DBG_CORRELATE;
298 if (Opts.pgo_function_entry_coverage)
299 ProfileVersion |=
301 if (Opts.pgo_block_coverage)
302 ProfileVersion |= VARIANT_MASK_BYTE_COVERAGE;
303 if (Opts.pgo_temporal_instrumentation)
304 ProfileVersion |= VARIANT_MASK_TEMPORAL_PROF;
305 auto IRLevelVersionVariable = new GlobalVariable(
306 M, IntTy64, true, GlobalValue::WeakAnyLinkage,
307 Constant::getIntegerValue(IntTy64, APInt(64, ProfileVersion)), VarName);
308 IRLevelVersionVariable->setVisibility(GlobalValue::HiddenVisibility);
309
310 Triple TT(M.getTargetTriple());
311 if (TT.supportsCOMDAT()) {
312 IRLevelVersionVariable->setLinkage(GlobalValue::ExternalLinkage);
313 IRLevelVersionVariable->setComdat(M.getOrInsertComdat(VarName));
314 }
315 return IRLevelVersionVariable;
316}
317
318namespace {
319
320/// The select instruction visitor plays three roles specified
321/// by the mode. In \c VM_counting mode, it simply counts the number of
322/// select instructions. In \c VM_instrument mode, it inserts code to count
323/// the number times TrueValue of select is taken. In \c VM_annotate mode,
324/// it reads the profile data and annotate the select instruction with metadata.
325enum VisitMode { VM_counting, VM_instrument, VM_annotate };
326class PGOUseFunc;
327
328/// Instruction Visitor class to visit select instructions.
329struct SelectInstVisitor : public InstVisitor<SelectInstVisitor> {
330 const InstrumentationOptions &Opts;
331 Function &F;
332 unsigned NSIs = 0; // Number of select instructions instrumented.
333 VisitMode Mode = VM_counting; // Visiting mode.
334 unsigned *CurCtrIdx = nullptr; // Pointer to current counter index.
335 unsigned TotalNumCtrs = 0; // Total number of counters
336 GlobalValue *FuncNameVar = nullptr;
337 uint64_t FuncHash = 0;
338 PGOUseFunc *UseFunc = nullptr;
339 bool HasSingleByteCoverage;
340
341 SelectInstVisitor(const InstrumentationOptions &Opts, Function &Func,
342 bool HasSingleByteCoverage)
343 : Opts(Opts), F(Func), HasSingleByteCoverage(HasSingleByteCoverage) {}
344
345 void countSelects() {
346 NSIs = 0;
347 Mode = VM_counting;
348 visit(F);
349 }
350
351 // Visit the IR stream and instrument all select instructions. \p
352 // Ind is a pointer to the counter index variable; \p TotalNC
353 // is the total number of counters; \p FNV is the pointer to the
354 // PGO function name var; \p FHash is the function hash.
355 void instrumentSelects(unsigned *Ind, unsigned TotalNC, GlobalValue *FNV,
356 uint64_t FHash) {
357 Mode = VM_instrument;
358 CurCtrIdx = Ind;
359 TotalNumCtrs = TotalNC;
360 FuncHash = FHash;
361 FuncNameVar = FNV;
362 visit(F);
363 }
364
365 // Visit the IR stream and annotate all select instructions.
366 void annotateSelects(PGOUseFunc *UF, unsigned *Ind) {
367 Mode = VM_annotate;
368 UseFunc = UF;
369 CurCtrIdx = Ind;
370 visit(F);
371 }
372
373 void instrumentOneSelectInst(SelectInst &SI);
374 void annotateOneSelectInst(SelectInst &SI);
375
376 // Visit \p SI instruction and perform tasks according to visit mode.
377 void visitSelectInst(SelectInst &SI);
378
379 // Return the number of select instructions. This needs be called after
380 // countSelects().
381 unsigned getNumOfSelectInsts() const { return NSIs; }
382};
383
384/// This class implements the CFG edges for the Minimum Spanning Tree (MST)
385/// based instrumentation.
386/// Note that the CFG can be a multi-graph. So there might be multiple edges
387/// with the same SrcBB and DestBB.
388struct PGOEdge {
389 BasicBlock *SrcBB;
390 BasicBlock *DestBB;
391 uint64_t Weight;
392 bool InMST = false;
393 bool Removed = false;
394 bool IsCritical = false;
395
396 PGOEdge(BasicBlock *Src, BasicBlock *Dest, uint64_t W = 1)
397 : SrcBB(Src), DestBB(Dest), Weight(W) {}
398
399 /// Return the information string of an edge.
400 std::string infoString() const {
401 return (Twine(Removed ? "-" : " ") + (InMST ? " " : "*") +
402 (IsCritical ? "c" : " ") + " W=" + Twine(Weight))
403 .str();
404 }
405};
406
407/// This class stores the auxiliary information for each BB in the MST.
408struct PGOBBInfo {
409 PGOBBInfo *Group;
410 uint32_t Index;
411 uint32_t Rank = 0;
412
413 PGOBBInfo(unsigned IX) : Group(this), Index(IX) {}
414
415 /// Return the information string of this object.
416 std::string infoString() const {
417 return (Twine("Index=") + Twine(Index)).str();
418 }
419};
420
421// This class implements the CFG edges. Note the CFG can be a multi-graph.
422template <class Edge, class BBInfo> class FuncPGOInstrumentation {
423private:
424 const InstrumentationOptions &Opts;
425 Function &F;
426
427 // Is this is context-sensitive instrumentation.
428 bool IsCS;
429
430 // A map that stores the Comdat group in function F.
431 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers;
432
433 ValueProfileCollector VPC;
434
435 void computeCFGHash();
436 void renameComdatFunction();
437
438public:
439 const TargetLibraryInfo &TLI;
440 std::vector<std::vector<VPCandidateInfo>> ValueSites;
441 SelectInstVisitor SIVisitor;
442 std::string FuncName;
443 std::string DeprecatedFuncName;
444 GlobalVariable *FuncNameVar;
445
446 // CFG hash value for this function.
447 uint64_t FunctionHash = 0;
448
449 // The Minimum Spanning Tree of function CFG.
450 CFGMST<Edge, BBInfo> MST;
451
452 const std::optional<BlockCoverageInference> BCI;
453
454 static std::optional<BlockCoverageInference>
455 constructBCI(Function &Func, bool HasSingleByteCoverage,
456 bool InstrumentFuncEntry) {
457 if (HasSingleByteCoverage)
458 return BlockCoverageInference(Func, InstrumentFuncEntry);
459 return {};
460 }
461
462 // Collect all the BBs that will be instrumented, and store them in
463 // InstrumentBBs.
464 void getInstrumentBBs(std::vector<BasicBlock *> &InstrumentBBs);
465
466 // Give an edge, find the BB that will be instrumented.
467 // Return nullptr if there is no BB to be instrumented.
469
470 // Return the auxiliary BB information.
471 BBInfo &getBBInfo(const BasicBlock *BB) const { return MST.getBBInfo(BB); }
472
473 // Return the auxiliary BB information if available.
474 BBInfo *findBBInfo(const BasicBlock *BB) const { return MST.findBBInfo(BB); }
475
476 // Dump edges and BB information.
477 void dumpInfo(StringRef Str = "") const {
478 MST.dumpEdges(dbgs(), Twine("Dump Function ") + FuncName +
479 " Hash: " + Twine(FunctionHash) + "\t" + Str);
480 }
481
482 FuncPGOInstrumentation(
483 const InstrumentationOptions &Opts, Function &Func,
484 TargetLibraryInfo &TLI,
485 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers,
486 bool CreateGlobalVar = false, BranchProbabilityInfo *BPI = nullptr,
487 BlockFrequencyInfo *BFI = nullptr, LoopInfo *LI = nullptr,
488 bool IsCS = false, bool InstrumentFuncEntry = true,
489 bool InstrumentLoopEntries = false, bool HasSingleByteCoverage = false)
490 : Opts(Opts), F(Func), IsCS(IsCS), ComdatMembers(ComdatMembers),
491 VPC(Func, TLI), TLI(TLI), ValueSites(IPVK_Last + 1),
492 SIVisitor(Opts, Func, HasSingleByteCoverage),
493 MST(F, InstrumentFuncEntry, InstrumentLoopEntries, BPI, BFI, LI),
494 BCI(constructBCI(Func, HasSingleByteCoverage, InstrumentFuncEntry)) {
495 if (BCI && Opts.pgo_view_block_coverage_graph)
496 BCI->viewBlockCoverageGraph();
497 // This should be done before CFG hash computation.
498 SIVisitor.countSelects();
499 ValueSites[IPVK_MemOPSize] = VPC.get(IPVK_MemOPSize);
500 if (!IsCS) {
501 NumOfPGOSelectInsts += SIVisitor.getNumOfSelectInsts();
502 NumOfPGOMemIntrinsics += ValueSites[IPVK_MemOPSize].size();
503 NumOfPGOBB += MST.bbInfoSize();
504 ValueSites[IPVK_IndirectCallTarget] = VPC.get(IPVK_IndirectCallTarget);
506 ValueSites[IPVK_VTableTarget] = VPC.get(IPVK_VTableTarget);
507 } else {
508 NumOfCSPGOSelectInsts += SIVisitor.getNumOfSelectInsts();
509 NumOfCSPGOMemIntrinsics += ValueSites[IPVK_MemOPSize].size();
510 NumOfCSPGOBB += MST.bbInfoSize();
511 }
512
513 FuncName = getIRPGOObjectName(F);
514 DeprecatedFuncName = getPGOFuncName(F);
515 computeCFGHash();
516 if (!ComdatMembers.empty())
517 renameComdatFunction();
518 LLVM_DEBUG(dumpInfo("after CFGMST"));
519
520 for (const auto &E : MST.allEdges()) {
521 if (E->Removed)
522 continue;
523 IsCS ? NumOfCSPGOEdge++ : NumOfPGOEdge++;
524 if (!E->InMST)
525 IsCS ? NumOfCSPGOInstrument++ : NumOfPGOInstrument++;
526 }
527
528 if (CreateGlobalVar)
529 FuncNameVar = createPGOFuncNameVar(F, FuncName);
530 }
531};
532
533} // end anonymous namespace
534
535// Compute Hash value for the CFG: the lower 32 bits are CRC32 of the index
536// value of each BB in the CFG. The higher 32 bits are the CRC32 of the numbers
537// of selects, indirect calls, mem ops and edges.
538template <class Edge, class BBInfo>
539void FuncPGOInstrumentation<Edge, BBInfo>::computeCFGHash() {
540 std::vector<uint8_t> Indexes;
541 JamCRC JC;
542 for (auto &BB : F) {
543 for (BasicBlock *Succ : successors(&BB)) {
544 auto BI = findBBInfo(Succ);
545 if (BI == nullptr)
546 continue;
547 uint32_t Index = BI->Index;
548 for (int J = 0; J < 4; J++)
549 Indexes.push_back((uint8_t)(Index >> (J * 8)));
550 }
551 }
552 JC.update(Indexes);
553
554 JamCRC JCH;
555 // The higher 32 bits.
556 auto updateJCH = [&JCH](uint64_t Num) {
557 uint8_t Data[8];
559 JCH.update(Data);
560 };
561 updateJCH((uint64_t)SIVisitor.getNumOfSelectInsts());
562 updateJCH((uint64_t)ValueSites[IPVK_IndirectCallTarget].size());
563 updateJCH((uint64_t)ValueSites[IPVK_MemOPSize].size());
564 if (BCI) {
565 updateJCH(BCI->getInstrumentedBlocksHash());
566 } else {
567 updateJCH((uint64_t)MST.numEdges());
568 }
569
570 // Hash format for context sensitive profile. Reserve 4 bits for other
571 // information.
572 FunctionHash = (((uint64_t)JCH.getCRC()) << 28) + JC.getCRC();
573
574 // Reserve bit 60-63 for other information purpose.
576 if (IsCS)
578 LLVM_DEBUG(dbgs() << "Function Hash Computation for " << F.getName() << ":\n"
579 << " CRC = " << JC.getCRC()
580 << ", Selects = " << SIVisitor.getNumOfSelectInsts()
581 << ", Edges = " << MST.numEdges() << ", ICSites = "
582 << ValueSites[IPVK_IndirectCallTarget].size()
583 << ", Memops = " << ValueSites[IPVK_MemOPSize].size()
584 << ", High32 CRC = " << JCH.getCRC()
585 << ", Hash = " << FunctionHash << "\n";);
586
587 if (Opts.pgo_trace_func_hash != "-" &&
588 F.getName().contains(Opts.pgo_trace_func_hash))
589 dbgs() << "Funcname=" << F.getName() << ", Hash=" << FunctionHash
590 << " in building " << F.getParent()->getSourceFileName() << "\n";
591}
592
593// Check if we can safely rename this Comdat function.
594static bool canRenameComdat(
595 const InstrumentationOptions &Opts, Function &F,
596 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers) {
597 if (!Opts.do_comdat_renaming || !canRenameComdatFunc(F, true))
598 return false;
599
600 // FIXME: Current only handle those Comdat groups that only containing one
601 // function.
602 // (1) For a Comdat group containing multiple functions, we need to have a
603 // unique postfix based on the hashes for each function. There is a
604 // non-trivial code refactoring to do this efficiently.
605 // (2) Variables can not be renamed, so we can not rename Comdat function in a
606 // group including global vars.
607 Comdat *C = F.getComdat();
608 for (auto &&CM : make_range(ComdatMembers.equal_range(C))) {
609 assert(!isa<GlobalAlias>(CM.second));
610 Function *FM = dyn_cast<Function>(CM.second);
611 if (FM != &F)
612 return false;
613 }
614 return true;
615}
616
617// Append the CFGHash to the Comdat function name.
618template <class Edge, class BBInfo>
619void FuncPGOInstrumentation<Edge, BBInfo>::renameComdatFunction() {
620 if (!canRenameComdat(Opts, F, ComdatMembers))
621 return;
622 std::string OrigName = F.getName().str();
623 std::string NewFuncName =
624 Twine(F.getName() + "." + Twine(FunctionHash)).str();
625 F.setName(Twine(NewFuncName));
627 FuncName = Twine(FuncName + "." + Twine(FunctionHash)).str();
628 Comdat *NewComdat;
629 Module *M = F.getParent();
630 // For AvailableExternallyLinkage functions, change the linkage to
631 // LinkOnceODR and put them into comdat. This is because after renaming, there
632 // is no backup external copy available for the function.
633 if (!F.hasComdat()) {
635 NewComdat = M->getOrInsertComdat(StringRef(NewFuncName));
637 F.setComdat(NewComdat);
638 return;
639 }
640
641 // This function belongs to a single function Comdat group.
642 Comdat *OrigComdat = F.getComdat();
643 std::string NewComdatName =
644 Twine(OrigComdat->getName() + "." + Twine(FunctionHash)).str();
645 NewComdat = M->getOrInsertComdat(StringRef(NewComdatName));
646 NewComdat->setSelectionKind(OrigComdat->getSelectionKind());
647
648 for (auto &&CM : make_range(ComdatMembers.equal_range(OrigComdat))) {
649 // Must be a function.
650 cast<Function>(CM.second)->setComdat(NewComdat);
651 }
652}
653
654/// Collect all the BBs that will be instruments and add them to
655/// `InstrumentBBs`.
656template <class Edge, class BBInfo>
657void FuncPGOInstrumentation<Edge, BBInfo>::getInstrumentBBs(
658 std::vector<BasicBlock *> &InstrumentBBs) {
659 if (BCI) {
660 for (auto &BB : F)
661 if (BCI->shouldInstrumentBlock(BB))
662 InstrumentBBs.push_back(&BB);
663 return;
664 }
665
666 // Use a worklist as we will update the vector during the iteration.
667 std::vector<Edge *> EdgeList;
668 EdgeList.reserve(MST.numEdges());
669 for (const auto &E : MST.allEdges())
670 EdgeList.push_back(E.get());
671
672 for (auto &E : EdgeList) {
673 BasicBlock *InstrBB = getInstrBB(E);
674 if (InstrBB)
675 InstrumentBBs.push_back(InstrBB);
676 }
677}
678
679// Given a CFG E to be instrumented, find which BB to place the instrumented
680// code. The function will split the critical edge if necessary.
681template <class Edge, class BBInfo>
682BasicBlock *FuncPGOInstrumentation<Edge, BBInfo>::getInstrBB(Edge *E) {
683 if (E->InMST || E->Removed)
684 return nullptr;
685
686 BasicBlock *SrcBB = E->SrcBB;
687 BasicBlock *DestBB = E->DestBB;
688 // For a fake edge, instrument the real BB.
689 if (SrcBB == nullptr)
690 return DestBB;
691 if (DestBB == nullptr)
692 return SrcBB;
693
694 auto canInstrument = [](BasicBlock *BB) -> BasicBlock * {
695 // There are basic blocks (such as catchswitch) cannot be instrumented.
696 // If the returned first insertion point is the end of BB, skip this BB.
697 if (BB->getFirstNonPHIOrDbgOrAlloca() == BB->end())
698 return nullptr;
699 return BB;
700 };
701
702 // Instrument the SrcBB if it has a single successor,
703 // otherwise, the DestBB if this is not a critical edge.
704 Instruction *TI = SrcBB->getTerminator();
705 if (TI->getNumSuccessors() <= 1)
706 return canInstrument(SrcBB);
707 if (!E->IsCritical)
708 return canInstrument(DestBB);
709
710 // Some IndirectBr critical edges cannot be split by the previous
711 // SplitIndirectBrCriticalEdges call. Bail out.
712 unsigned SuccNum = GetSuccessorNumber(SrcBB, DestBB);
713 BasicBlock *InstrBB =
714 isa<IndirectBrInst>(TI) ? nullptr : SplitCriticalEdge(TI, SuccNum);
715 if (!InstrBB) {
717 dbgs() << "Fail to split critical edge: not instrument this edge.\n");
718 return nullptr;
719 }
720 // For a critical edge, we have to split. Instrument the newly
721 // created BB.
722 IsCS ? NumOfCSPGOSplit++ : NumOfPGOSplit++;
723 LLVM_DEBUG(dbgs() << "Split critical edge: " << getBBInfo(SrcBB).Index
724 << " --> " << getBBInfo(DestBB).Index << "\n");
725 // Need to add two new edges. First one: Add new edge of SrcBB->InstrBB.
726 MST.addEdge(SrcBB, InstrBB, 0);
727 // Second one: Add new edge of InstrBB->DestBB.
728 Edge &NewEdge1 = MST.addEdge(InstrBB, DestBB, 0);
729 NewEdge1.InMST = true;
730 E->Removed = true;
731
732 return canInstrument(InstrBB);
733}
734
735// When generating value profiling calls on Windows routines that make use of
736// handler funclets for exception processing an operand bundle needs to attached
737// to the called function. This routine will set \p OpBundles to contain the
738// funclet information, if any is needed, that should be placed on the generated
739// value profiling call for the value profile candidate call.
740static void
744 auto *OrigCall = dyn_cast<CallBase>(Cand.AnnotatedInst);
745 if (!OrigCall)
746 return;
747
748 if (!isa<IntrinsicInst>(OrigCall)) {
749 // The instrumentation call should belong to the same funclet as a
750 // non-intrinsic call, so just copy the operand bundle, if any exists.
751 std::optional<OperandBundleUse> ParentFunclet =
752 OrigCall->getOperandBundle(LLVMContext::OB_funclet);
753 if (ParentFunclet)
754 OpBundles.emplace_back(OperandBundleDef(*ParentFunclet));
755 } else {
756 // Intrinsics or other instructions do not get funclet information from the
757 // front-end. Need to use the BlockColors that was computed by the routine
758 // colorEHFunclets to determine whether a funclet is needed.
759 if (!BlockColors.empty()) {
760 const ColorVector &CV = BlockColors.find(OrigCall->getParent())->second;
761 assert(CV.size() == 1 && "non-unique color for block!");
763 if (EHPadIt->isEHPad())
764 OpBundles.emplace_back("funclet", &*EHPadIt);
765 }
766 }
767}
768
769// Visit all edge and instrument the edges not in MST, and do value profiling.
770// Critical edges will be split.
771void FunctionInstrumenter::instrument() {
772 if (!Opts.pgo_block_coverage) {
773 // Split indirectbr critical edges here before computing the MST rather than
774 // later in getInstrBB() to avoid invalidating it.
775 SplitIndirectBrCriticalEdges(F, /*IgnoreBlocksWithoutPHI=*/false, BPI, BFI);
776 }
777
778 const bool IsCtxProf = InstrumentationType == PGOInstrumentationType::CTXPROF;
779 FuncPGOInstrumentation<PGOEdge, PGOBBInfo> FuncInfo(
780 Opts, F, TLI, ComdatMembers, /*CreateGlobalVar=*/!IsCtxProf, BPI, BFI, LI,
781 InstrumentationType == PGOInstrumentationType::CSFDO,
782 shouldInstrumentEntryBB(), shouldInstrumentLoopEntries(),
783 Opts.pgo_block_coverage);
784
785 auto *const Name = IsCtxProf ? cast<GlobalValue>(&F) : FuncInfo.FuncNameVar;
786 auto *const CFGHash =
787 ConstantInt::get(Type::getInt64Ty(M.getContext()), FuncInfo.FunctionHash);
788 // Make sure that pointer to global is passed in with zero addrspace
789 // This is relevant during GPU profiling
790 auto *NormalizedNamePtr = ConstantExpr::getPointerBitCastOrAddrSpaceCast(
791 Name, PointerType::get(M.getContext(), 0));
792 if (Opts.pgo_function_entry_coverage) {
793 auto &EntryBB = F.getEntryBlock();
794 IRBuilder<> Builder(EntryBB.getFirstNonPHIOrDbgOrAlloca());
795 // llvm.instrprof.cover(i8* <name>, i64 <hash>, i32 <num-counters>,
796 // i32 <index>)
797 Builder.CreateIntrinsic(
798 Intrinsic::instrprof_cover,
799 {NormalizedNamePtr, CFGHash, Builder.getInt32(1), Builder.getInt32(0)});
800 return;
801 }
802
803 std::vector<BasicBlock *> InstrumentBBs;
804 FuncInfo.getInstrumentBBs(InstrumentBBs);
805 unsigned NumCounters =
806 InstrumentBBs.size() + FuncInfo.SIVisitor.getNumOfSelectInsts();
807
808 if (IsCtxProf) {
809 StringSet<> SkipCSInstr(llvm::from_range,
810 Opts.ctx_prof_skip_callsite_instr);
811
812 auto *CSIntrinsic =
813 Intrinsic::getOrInsertDeclaration(&M, Intrinsic::instrprof_callsite);
814 // We want to count the instrumentable callsites, then instrument them. This
815 // is because the llvm.instrprof.callsite intrinsic has an argument (like
816 // the other instrprof intrinsics) capturing the total number of
817 // instrumented objects (counters, or callsites, in this case). In this
818 // case, we want that value so we can readily pass it to the compiler-rt
819 // APIs that may have to allocate memory based on the nr of callsites.
820 // The traversal logic is the same for both counting and instrumentation,
821 // just needs to be done in succession.
822 auto Visit = [&](llvm::function_ref<void(CallBase * CB)> Visitor) {
823 for (auto &BB : F)
824 for (auto &Instr : BB)
825 if (auto *CS = dyn_cast<CallBase>(&Instr)) {
827 continue;
828 if (CS->getCalledFunction() &&
829 SkipCSInstr.contains(CS->getCalledFunction()->getName()))
830 continue;
831 Visitor(CS);
832 }
833 };
834 // First, count callsites.
835 uint32_t TotalNumCallsites = 0;
836 Visit([&TotalNumCallsites](auto *) { ++TotalNumCallsites; });
837
838 // Now instrument.
839 uint32_t CallsiteIndex = 0;
840 Visit([&](auto *CB) {
841 IRBuilder<> Builder(CB);
842 Builder.CreateCall(CSIntrinsic,
843 {Name, CFGHash, Builder.getInt32(TotalNumCallsites),
844 Builder.getInt32(CallsiteIndex++),
845 CB->getCalledOperand()});
846 });
847 }
848
849 uint32_t I = 0;
850 if (Opts.pgo_temporal_instrumentation) {
851 NumCounters += Opts.pgo_block_coverage ? 8 : 1;
852 auto &EntryBB = F.getEntryBlock();
853 IRBuilder<> Builder(EntryBB.getFirstNonPHIOrDbgOrAlloca());
854 // llvm.instrprof.timestamp(i8* <name>, i64 <hash>, i32 <num-counters>,
855 // i32 <index>)
856 Builder.CreateIntrinsic(Intrinsic::instrprof_timestamp,
857 {NormalizedNamePtr, CFGHash,
858 Builder.getInt32(NumCounters),
859 Builder.getInt32(I)});
860 I += Opts.pgo_block_coverage ? 8 : 1;
861 }
862
863 for (auto *InstrBB : InstrumentBBs) {
864 IRBuilder<> Builder(InstrBB->getFirstNonPHIOrDbgOrAlloca());
865 assert(Builder.GetInsertPoint() != InstrBB->end() &&
866 "Cannot get the Instrumentation point");
867 // llvm.instrprof.increment(i8* <name>, i64 <hash>, i32 <num-counters>,
868 // i32 <index>)
869 Builder.CreateIntrinsic(
870 Opts.pgo_block_coverage ? Intrinsic::instrprof_cover
871 : Intrinsic::instrprof_increment,
872 {NormalizedNamePtr, CFGHash, Builder.getInt32(NumCounters),
873 Builder.getInt32(I++)});
874 }
875
876 // Now instrument select instructions:
877 FuncInfo.SIVisitor.instrumentSelects(&I, NumCounters, Name,
878 FuncInfo.FunctionHash);
879 assert(I == NumCounters);
880
881 if (isValueProfilingDisabled())
882 return;
883
884 NumOfPGOICall += FuncInfo.ValueSites[IPVK_IndirectCallTarget].size();
885
886 // Intrinsic function calls do not have funclet operand bundles needed for
887 // Windows exception handling attached to them. However, if value profiling is
888 // inserted for one of these calls, then a funclet value will need to be set
889 // on the instrumentation call based on the funclet coloring.
890 DenseMap<BasicBlock *, ColorVector> BlockColors;
891 if (F.hasPersonalityFn() &&
892 isScopedEHPersonality(classifyEHPersonality(F.getPersonalityFn())))
893 BlockColors = colorEHFunclets(F);
894
895 // For each VP Kind, walk the VP candidates and instrument each one.
896 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind) {
897 unsigned SiteIndex = 0;
898 if (Kind == IPVK_MemOPSize && !Opts.pgo_instr_memop)
899 continue;
900
901 for (VPCandidateInfo Cand : FuncInfo.ValueSites[Kind]) {
902 LLVM_DEBUG(dbgs() << "Instrument one VP " << ValueProfKindDescr[Kind]
903 << " site: CallSite Index = " << SiteIndex << "\n");
904
905 IRBuilder<> Builder(Cand.InsertPt);
906 assert(Builder.GetInsertPoint() != Cand.InsertPt->getParent()->end() &&
907 "Cannot get the Instrumentation point");
908
909 Value *ToProfile = nullptr;
910 if (Cand.V->getType()->isIntegerTy())
911 ToProfile = Builder.CreateZExtOrTrunc(Cand.V, Builder.getInt64Ty());
912 else if (Cand.V->getType()->isPointerTy())
913 ToProfile = Builder.CreatePtrToInt(Cand.V, Builder.getInt64Ty());
914 assert(ToProfile && "value profiling Value is of unexpected type");
915
916 auto *NormalizedNamePtr = ConstantExpr::getPointerBitCastOrAddrSpaceCast(
917 Name, PointerType::get(M.getContext(), 0));
918
920 populateEHOperandBundle(Cand, BlockColors, OpBundles);
921 Builder.CreateCall(
923 Intrinsic::instrprof_value_profile),
924 {NormalizedNamePtr, Builder.getInt64(FuncInfo.FunctionHash),
925 ToProfile, Builder.getInt32(Kind), Builder.getInt32(SiteIndex++)},
926 OpBundles);
927 }
928 } // IPVK_First <= Kind <= IPVK_Last
929}
930
931namespace {
932
933// This class represents a CFG edge in profile use compilation.
934struct PGOUseEdge : public PGOEdge {
935 using PGOEdge::PGOEdge;
936
937 std::optional<uint64_t> Count;
938
939 // Set edge count value
940 void setEdgeCount(uint64_t Value) { Count = Value; }
941
942 // Return the information string for this object.
943 std::string infoString() const {
944 if (!Count)
945 return PGOEdge::infoString();
946 return (Twine(PGOEdge::infoString()) + " Count=" + Twine(*Count)).str();
947 }
948};
949
950using DirectEdges = SmallVector<PGOUseEdge *, 2>;
951
952// This class stores the auxiliary information for each BB.
953struct PGOUseBBInfo : public PGOBBInfo {
954 std::optional<uint64_t> Count;
955 int32_t UnknownCountInEdge = 0;
956 int32_t UnknownCountOutEdge = 0;
957 DirectEdges InEdges;
958 DirectEdges OutEdges;
959
960 PGOUseBBInfo(unsigned IX) : PGOBBInfo(IX) {}
961
962 // Set the profile count value for this BB.
963 void setBBInfoCount(uint64_t Value) { Count = Value; }
964
965 // Return the information string of this object.
966 std::string infoString() const {
967 if (!Count)
968 return PGOBBInfo::infoString();
969 return (Twine(PGOBBInfo::infoString()) + " Count=" + Twine(*Count)).str();
970 }
971
972 // Add an OutEdge and update the edge count.
973 void addOutEdge(PGOUseEdge *E) {
974 OutEdges.push_back(E);
975 UnknownCountOutEdge++;
976 }
977
978 // Add an InEdge and update the edge count.
979 void addInEdge(PGOUseEdge *E) {
980 InEdges.push_back(E);
981 UnknownCountInEdge++;
982 }
983};
984
985} // end anonymous namespace
986
987// Sum up the count values for all the edges.
989 uint64_t Total = 0;
990 for (const auto &E : Edges) {
991 if (E->Removed)
992 continue;
993 if (E->Count)
994 Total += *E->Count;
995 }
996 return Total;
997}
998
999namespace {
1000
1001class PGOUseFunc {
1002public:
1003 PGOUseFunc(const InstrumentationOptions &Opts, Function &Func, Module *Modu,
1004 TargetLibraryInfo &TLI,
1005 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers,
1006 BranchProbabilityInfo *BPI, BlockFrequencyInfo *BFIin,
1007 LoopInfo *LI, ProfileSummaryInfo *PSI, bool IsCS,
1008 bool InstrumentFuncEntry, bool InstrumentLoopEntries,
1009 bool HasSingleByteCoverage)
1010 : Opts(Opts), F(Func), M(Modu), BFI(BFIin), PSI(PSI),
1011 FuncInfo(Opts, Func, TLI, ComdatMembers, false, BPI, BFIin, LI, IsCS,
1012 InstrumentFuncEntry, InstrumentLoopEntries,
1013 HasSingleByteCoverage),
1014 FreqAttr(FFA_Normal), IsCS(IsCS), VPC(Func, TLI) {}
1015
1016 void handleInstrProfError(Error Err, uint64_t MismatchedFuncSum);
1017
1018 /// Get the profile record, assign it to \p ProfileRecord, handle errors if
1019 /// necessary, and assign \p ProgramMaxCount. \returns true if there are no
1020 /// errors.
1021 bool getRecord(IndexedInstrProfReader *PGOReader);
1022
1023 // Read counts for the instrumented BB from profile.
1024 bool readCounters(bool &AllZeros,
1026
1027 // Populate the counts for all BBs.
1028 void populateCounters();
1029
1030 // Set block coverage based on profile coverage values.
1031 void populateCoverage();
1032
1033 // Set the branch weights based on the count values.
1034 void setBranchWeights();
1035
1036 // Annotate the value profile call sites for all value kind.
1037 void annotateValueSites();
1038
1039 // Annotate the value profile call sites for one value kind.
1040 void annotateValueSites(uint32_t Kind);
1041
1042 // Annotate the irreducible loop header weights.
1043 void annotateIrrLoopHeaderWeights();
1044
1045 // Annotate per-block uniformity info for offload profiling.
1046 void setBlockUniformityAttribute();
1047
1048 // The hotness of the function from the profile count.
1049 enum FuncFreqAttr { FFA_Normal, FFA_Cold, FFA_Hot };
1050
1051 // Return the function hotness from the profile.
1052 FuncFreqAttr getFuncFreqAttr() const { return FreqAttr; }
1053
1054 // Return the function hash.
1055 uint64_t getFuncHash() const { return FuncInfo.FunctionHash; }
1056
1057 // Return the profile record for this function;
1058 NamedInstrProfRecord &getProfileRecord() { return ProfileRecord; }
1059
1060 // Return the auxiliary BB information.
1061 PGOUseBBInfo &getBBInfo(const BasicBlock *BB) const {
1062 return FuncInfo.getBBInfo(BB);
1063 }
1064
1065 // Return the auxiliary BB information if available.
1066 PGOUseBBInfo *findBBInfo(const BasicBlock *BB) const {
1067 return FuncInfo.findBBInfo(BB);
1068 }
1069
1070 Function &getFunc() const { return F; }
1071
1072 void dumpInfo(StringRef Str = "") const { FuncInfo.dumpInfo(Str); }
1073
1074 uint64_t getProgramMaxCount() const { return ProgramMaxCount; }
1075
1076private:
1077 const InstrumentationOptions &Opts;
1078 Function &F;
1079 Module *M;
1080 BlockFrequencyInfo *BFI;
1081 ProfileSummaryInfo *PSI;
1082
1083 // This member stores the shared information with class PGOGenFunc.
1084 FuncPGOInstrumentation<PGOUseEdge, PGOUseBBInfo> FuncInfo;
1085
1086 // The maximum count value in the profile. This is only used in PGO use
1087 // compilation.
1088 uint64_t ProgramMaxCount;
1089
1090 // Position of counter that remains to be read.
1091 uint32_t CountPosition = 0;
1092
1093 // Total size of the profile count for this function.
1094 uint32_t ProfileCountSize = 0;
1095
1096 // ProfileRecord for this function.
1097 NamedInstrProfRecord ProfileRecord;
1098
1099 // Function hotness info derived from profile.
1100 FuncFreqAttr FreqAttr;
1101
1102 // Is to use the context sensitive profile.
1103 bool IsCS;
1104
1105 ValueProfileCollector VPC;
1106
1107 // Find the Instrumented BB and set the value. Return false on error.
1108 bool setInstrumentedCounts(const std::vector<uint64_t> &CountFromProfile);
1109
1110 // Set the edge counter value for the unknown edge -- there should be only
1111 // one unknown edge.
1112 void setEdgeCount(DirectEdges &Edges, uint64_t Value);
1113
1114 // Set the hot/cold inline hints based on the count values.
1115 // FIXME: This function should be removed once the functionality in
1116 // the inliner is implemented.
1117 void markFunctionAttributes(uint64_t EntryCount, uint64_t MaxCount) {
1118 if (PSI->isHotCount(EntryCount))
1119 FreqAttr = FFA_Hot;
1120 else if (PSI->isColdCount(MaxCount))
1121 FreqAttr = FFA_Cold;
1122 }
1123};
1124
1125} // end anonymous namespace
1126
1127/// Set up InEdges/OutEdges for all BBs in the MST.
1129 const FuncPGOInstrumentation<PGOUseEdge, PGOUseBBInfo> &FuncInfo) {
1130 // This is not required when there is block coverage inference.
1131 if (FuncInfo.BCI)
1132 return;
1133 for (const auto &E : FuncInfo.MST.allEdges()) {
1134 if (E->Removed)
1135 continue;
1136 const BasicBlock *SrcBB = E->SrcBB;
1137 const BasicBlock *DestBB = E->DestBB;
1138 PGOUseBBInfo &SrcInfo = FuncInfo.getBBInfo(SrcBB);
1139 PGOUseBBInfo &DestInfo = FuncInfo.getBBInfo(DestBB);
1140 SrcInfo.addOutEdge(E.get());
1141 DestInfo.addInEdge(E.get());
1142 }
1143}
1144
1145// Visit all the edges and assign the count value for the instrumented
1146// edges and the BB. Return false on error.
1147bool PGOUseFunc::setInstrumentedCounts(
1148 const std::vector<uint64_t> &CountFromProfile) {
1149
1150 std::vector<BasicBlock *> InstrumentBBs;
1151 FuncInfo.getInstrumentBBs(InstrumentBBs);
1152
1153 setupBBInfoEdges(FuncInfo);
1154
1155 unsigned NumInstrumentedBBs = InstrumentBBs.size();
1156 unsigned NumSelects = FuncInfo.SIVisitor.getNumOfSelectInsts();
1157 unsigned NumCounters = NumInstrumentedBBs + NumSelects;
1158 // The number of counters here should match the number of counters
1159 // in profile. Return if they mismatch.
1160 if (NumCounters != CountFromProfile.size()) {
1161 LLVM_DEBUG({
1162 dbgs() << "PGO COUNTER MISMATCH for function " << F.getName() << ":\n";
1163 dbgs() << " Expected counters: " << NumCounters << "\n";
1164 dbgs() << " - From instrumented edges: " << NumInstrumentedBBs << "\n";
1165 for (size_t i = 0; i < InstrumentBBs.size(); ++i) {
1166 dbgs() << " " << i << ": ";
1167 InstrumentBBs[i]->printAsOperand(dbgs(), false);
1168 dbgs() << "\n";
1169 }
1170 dbgs() << " - From select instructions: " << NumSelects << "\n";
1171 dbgs() << " Actual counters from profile: " << CountFromProfile.size()
1172 << "\n";
1173 });
1174 return false;
1175 }
1176 auto *FuncEntry = &*F.begin();
1177
1178 // Set the profile count to the Instrumented BBs.
1179 uint32_t I = 0;
1180 for (BasicBlock *InstrBB : InstrumentBBs) {
1181 uint64_t CountValue = CountFromProfile[I++];
1182 PGOUseBBInfo &Info = getBBInfo(InstrBB);
1183 // If we reach here, we know that we have some nonzero count
1184 // values in this function. The entry count should not be 0.
1185 // Fix it if necessary.
1186 if (InstrBB == FuncEntry && CountValue == 0)
1187 CountValue = 1;
1188 Info.setBBInfoCount(CountValue);
1189 }
1190 ProfileCountSize = CountFromProfile.size();
1191 CountPosition = I;
1192
1193 // Set the edge count and update the count of unknown edges for BBs.
1194 auto setEdgeCount = [this](PGOUseEdge *E, uint64_t Value) -> void {
1195 E->setEdgeCount(Value);
1196 this->getBBInfo(E->SrcBB).UnknownCountOutEdge--;
1197 this->getBBInfo(E->DestBB).UnknownCountInEdge--;
1198 };
1199
1200 // Set the profile count the Instrumented edges. There are BBs that not in
1201 // MST but not instrumented. Need to set the edge count value so that we can
1202 // populate the profile counts later.
1203 for (const auto &E : FuncInfo.MST.allEdges()) {
1204 if (E->Removed || E->InMST)
1205 continue;
1206 const BasicBlock *SrcBB = E->SrcBB;
1207 PGOUseBBInfo &SrcInfo = getBBInfo(SrcBB);
1208
1209 // If only one out-edge, the edge profile count should be the same as BB
1210 // profile count.
1211 if (SrcInfo.Count && SrcInfo.OutEdges.size() == 1)
1212 setEdgeCount(E.get(), *SrcInfo.Count);
1213 else {
1214 const BasicBlock *DestBB = E->DestBB;
1215 PGOUseBBInfo &DestInfo = getBBInfo(DestBB);
1216 // If only one in-edge, the edge profile count should be the same as BB
1217 // profile count.
1218 if (DestInfo.Count && DestInfo.InEdges.size() == 1)
1219 setEdgeCount(E.get(), *DestInfo.Count);
1220 }
1221 if (E->Count)
1222 continue;
1223 // E's count should have been set from profile. If not, this meenas E skips
1224 // the instrumentation. We set the count to 0.
1225 setEdgeCount(E.get(), 0);
1226 }
1227 return true;
1228}
1229
1230// Set the count value for the unknown edge. There should be one and only one
1231// unknown edge in Edges vector.
1232void PGOUseFunc::setEdgeCount(DirectEdges &Edges, uint64_t Value) {
1233 for (auto &E : Edges) {
1234 if (E->Count)
1235 continue;
1236 E->setEdgeCount(Value);
1237
1238 getBBInfo(E->SrcBB).UnknownCountOutEdge--;
1239 getBBInfo(E->DestBB).UnknownCountInEdge--;
1240 return;
1241 }
1242 llvm_unreachable("Cannot find the unknown count edge");
1243}
1244
1245// Emit function metadata indicating PGO profile mismatch.
1247 const char MetadataName[] = "instr_prof_hash_mismatch";
1249 // If this metadata already exists, ignore.
1250 auto *Existing = F.getMetadata(LLVMContext::MD_annotation);
1251 if (Existing) {
1252 MDTuple *Tuple = cast<MDTuple>(Existing);
1253 for (const auto &N : Tuple->operands()) {
1254 if (N.equalsStr(MetadataName))
1255 return;
1256 Names.push_back(N.get());
1257 }
1258 }
1259
1260 MDBuilder MDB(ctx);
1261 Names.push_back(MDB.createString(MetadataName));
1262 MDNode *MD = MDTuple::get(ctx, Names);
1263 F.setMetadata(LLVMContext::MD_annotation, MD);
1264}
1265
1266void PGOUseFunc::handleInstrProfError(Error Err, uint64_t MismatchedFuncSum) {
1267 handleAllErrors(std::move(Err), [&](const InstrProfError &IPE) {
1268 auto &Ctx = M->getContext();
1269 auto Err = IPE.get();
1270 bool SkipWarning = false;
1271 LLVM_DEBUG(dbgs() << "Error in reading profile for Func "
1272 << FuncInfo.FuncName << ": ");
1273 if (Err == instrprof_error::unknown_function) {
1274 IsCS ? NumOfCSPGOMissing++ : NumOfPGOMissing++;
1275 SkipWarning = !Opts.pgo_warn_missing_function;
1276 LLVM_DEBUG(dbgs() << "unknown function");
1277 } else if (Err == instrprof_error::hash_mismatch ||
1278 Err == instrprof_error::malformed) {
1279 IsCS ? NumOfCSPGOMismatch++ : NumOfPGOMismatch++;
1280 SkipWarning =
1282 (Opts.no_pgo_warn_mismatch_comdat_weak &&
1283 (F.hasComdat() || F.getLinkage() == GlobalValue::WeakAnyLinkage ||
1285 LLVM_DEBUG(dbgs() << "hash mismatch (hash= " << FuncInfo.FunctionHash
1286 << " skip=" << SkipWarning << ")");
1287 // Emit function metadata indicating PGO profile mismatch.
1288 annotateFunctionWithHashMismatch(F, M->getContext());
1289 }
1290
1291 LLVM_DEBUG(dbgs() << " IsCS=" << IsCS << "\n");
1292 if (SkipWarning)
1293 return;
1294
1295 std::string Msg =
1296 IPE.message() + std::string(" ") + F.getName().str() +
1297 std::string(" Hash = ") + std::to_string(FuncInfo.FunctionHash) +
1298 std::string(" up to ") + std::to_string(MismatchedFuncSum) +
1299 std::string(" count discarded");
1300
1301 Ctx.diagnose(
1302 DiagnosticInfoPGOProfile(M->getName().data(), Msg, DS_Warning));
1303 });
1304}
1305
1306bool PGOUseFunc::getRecord(IndexedInstrProfReader *PGOReader) {
1307 uint64_t MismatchedFuncSum = 0;
1308 auto Result = PGOReader->getInstrProfRecord(
1309 FuncInfo.FuncName, FuncInfo.FunctionHash, FuncInfo.DeprecatedFuncName,
1310 &MismatchedFuncSum);
1311 if (Error E = Result.takeError()) {
1312 handleInstrProfError(std::move(E), MismatchedFuncSum);
1313 return false;
1314 }
1315 ProfileRecord = std::move(Result.get());
1316 ProgramMaxCount = PGOReader->getMaximumFunctionCount(IsCS);
1317 return true;
1318}
1319
1320// Read the profile from ProfileFileName and assign the value to the
1321// instrumented BB and the edges. Return true if the profile are successfully
1322// read, and false on errors.
1323bool PGOUseFunc::readCounters(bool &AllZeros,
1325 auto &Ctx = M->getContext();
1326 PseudoKind = ProfileRecord.getCountPseudoKind();
1327 if (PseudoKind != InstrProfRecord::NotPseudo) {
1328 return true;
1329 }
1330 std::vector<uint64_t> &CountFromProfile = ProfileRecord.Counts;
1331
1332 IsCS ? NumOfCSPGOFunc++ : NumOfPGOFunc++;
1333 LLVM_DEBUG(dbgs() << CountFromProfile.size() << " counts\n");
1334
1335 uint64_t ValueSum = 0;
1336 for (unsigned I = 0, S = CountFromProfile.size(); I < S; I++) {
1337 LLVM_DEBUG(dbgs() << " " << I << ": " << CountFromProfile[I] << "\n");
1338 ValueSum += CountFromProfile[I];
1339 }
1340 AllZeros = (ValueSum == 0);
1341
1342 LLVM_DEBUG(dbgs() << "SUM = " << ValueSum << "\n");
1343
1344 getBBInfo(nullptr).UnknownCountOutEdge = 2;
1345 getBBInfo(nullptr).UnknownCountInEdge = 2;
1346
1347 if (!setInstrumentedCounts(CountFromProfile)) {
1348 LLVM_DEBUG(
1349 dbgs() << "Inconsistent number of counts, skipping this function");
1350 Ctx.diagnose(DiagnosticInfoPGOProfile(
1351 M->getName().data(),
1352 Twine("Inconsistent number of counts in ") + F.getName().str() +
1353 Twine(": the profile may be stale or there is a function name "
1354 "collision."),
1355 DS_Warning));
1356 return false;
1357 }
1358 return true;
1359}
1360
1361void PGOUseFunc::populateCoverage() {
1362 IsCS ? NumOfCSPGOFunc++ : NumOfPGOFunc++;
1363
1364 ArrayRef<uint64_t> CountsFromProfile = ProfileRecord.Counts;
1365 DenseMap<const BasicBlock *, bool> Coverage;
1366 unsigned Index = 0;
1367 for (auto &BB : F)
1368 if (FuncInfo.BCI->shouldInstrumentBlock(BB))
1369 Coverage[&BB] = (CountsFromProfile[Index++] != 0);
1370 assert(Index == CountsFromProfile.size());
1371
1372 // For each B in InverseDependencies[A], if A is covered then B is covered.
1373 DenseMap<const BasicBlock *, DenseSet<const BasicBlock *>>
1374 InverseDependencies;
1375 for (auto &BB : F) {
1376 for (auto *Dep : FuncInfo.BCI->getDependencies(BB)) {
1377 // If Dep is covered then BB is covered.
1378 InverseDependencies[Dep].insert(&BB);
1379 }
1380 }
1381
1382 // Infer coverage of the non-instrumented blocks using a flood-fill algorithm.
1383 std::stack<const BasicBlock *> CoveredBlocksToProcess;
1384 for (auto &[BB, IsCovered] : Coverage)
1385 if (IsCovered)
1386 CoveredBlocksToProcess.push(BB);
1387
1388 while (!CoveredBlocksToProcess.empty()) {
1389 auto *CoveredBlock = CoveredBlocksToProcess.top();
1390 assert(Coverage[CoveredBlock]);
1391 CoveredBlocksToProcess.pop();
1392 for (auto *BB : InverseDependencies[CoveredBlock]) {
1393 // If CoveredBlock is covered then BB is covered.
1394 bool &Cov = Coverage[BB];
1395 if (Cov)
1396 continue;
1397 Cov = true;
1398 CoveredBlocksToProcess.push(BB);
1399 }
1400 }
1401
1402 // Annotate block coverage.
1403 MDBuilder MDB(F.getContext());
1404 // We set the entry count to 10000 if the entry block is covered so that BFI
1405 // can propagate a fraction of this count to the other covered blocks.
1406 F.setEntryCount(Coverage[&F.getEntryBlock()] ? 10000 : 0);
1407 for (auto &BB : F) {
1408 // For a block A and its successor B, we set the edge weight as follows:
1409 // If A is covered and B is covered, set weight=1.
1410 // If A is covered and B is uncovered, set weight=0.
1411 // If A is uncovered, set weight=1.
1412 // This setup will allow BFI to give nonzero profile counts to only covered
1413 // blocks.
1414 SmallVector<uint32_t, 4> Weights;
1415 for (auto *Succ : successors(&BB))
1416 Weights.push_back((Coverage[Succ] || !Coverage[&BB]) ? 1 : 0);
1417 if (Weights.size() >= 2)
1418 llvm::setBranchWeights(*BB.getTerminator(), Weights,
1419 /*IsExpected=*/false);
1420 }
1421
1422 unsigned NumCorruptCoverage = 0;
1423 CycleInfo CI;
1424 CI.compute(F);
1425 BranchProbabilityInfo BPI(F, CI);
1426 BlockFrequencyInfo BFI(F, BPI, CI);
1427 auto IsBlockDead = [&](const BasicBlock &BB) -> std::optional<bool> {
1428 if (auto C = BFI.getBlockProfileCount(&BB))
1429 return C == 0;
1430 return {};
1431 };
1432 LLVM_DEBUG(dbgs() << "Block Coverage: (Instrumented=*, Covered=X)\n");
1433 for (auto &BB : F) {
1434 LLVM_DEBUG(dbgs() << (FuncInfo.BCI->shouldInstrumentBlock(BB) ? "* " : " ")
1435 << (Coverage[&BB] ? "X " : " ") << " " << BB.getName()
1436 << "\n");
1437 // In some cases it is possible to find a covered block that has no covered
1438 // successors, e.g., when a block calls a function that may call exit(). In
1439 // those cases, BFI could find its successor to be covered while BCI could
1440 // find its successor to be dead.
1441 const bool &Cov = Coverage[&BB];
1442 if (Cov == IsBlockDead(BB).value_or(false)) {
1443 LLVM_DEBUG(
1444 dbgs() << "Found inconsistent block covearge for " << BB.getName()
1445 << ": BCI=" << (Cov ? "Covered" : "Dead") << " BFI="
1446 << (IsBlockDead(BB).value() ? "Dead" : "Covered") << "\n");
1447 ++NumCorruptCoverage;
1448 }
1449 if (Cov)
1450 ++NumCoveredBlocks;
1451 }
1452 if (Opts.pgo_verify_bfi && NumCorruptCoverage) {
1453 auto &Ctx = M->getContext();
1454 Ctx.diagnose(DiagnosticInfoPGOProfile(
1455 M->getName().data(),
1456 Twine("Found inconsistent block coverage for function ") + F.getName() +
1457 " in " + Twine(NumCorruptCoverage) + " blocks.",
1458 DS_Warning));
1459 }
1460 if (Opts.pgo_view_block_coverage_graph)
1461 FuncInfo.BCI->viewBlockCoverageGraph(&Coverage);
1462}
1463
1464// Populate the counters from instrumented BBs to all BBs.
1465// In the end of this operation, all BBs should have a valid count value.
1466void PGOUseFunc::populateCounters() {
1467 bool Changes = true;
1468 unsigned NumPasses = 0;
1469 while (Changes) {
1470 NumPasses++;
1471 Changes = false;
1472
1473 // For efficient traversal, it's better to start from the end as most
1474 // of the instrumented edges are at the end.
1475 for (auto &BB : reverse(F)) {
1476 PGOUseBBInfo *UseBBInfo = findBBInfo(&BB);
1477 if (UseBBInfo == nullptr)
1478 continue;
1479 if (!UseBBInfo->Count) {
1480 if (UseBBInfo->UnknownCountOutEdge == 0) {
1481 UseBBInfo->Count = sumEdgeCount(UseBBInfo->OutEdges);
1482 Changes = true;
1483 } else if (UseBBInfo->UnknownCountInEdge == 0) {
1484 UseBBInfo->Count = sumEdgeCount(UseBBInfo->InEdges);
1485 Changes = true;
1486 }
1487 }
1488 if (UseBBInfo->Count) {
1489 if (UseBBInfo->UnknownCountOutEdge == 1) {
1490 uint64_t Total = 0;
1491 uint64_t OutSum = sumEdgeCount(UseBBInfo->OutEdges);
1492 // If the one of the successor block can early terminate (no-return),
1493 // we can end up with situation where out edge sum count is larger as
1494 // the source BB's count is collected by a post-dominated block.
1495 if (*UseBBInfo->Count > OutSum)
1496 Total = *UseBBInfo->Count - OutSum;
1497 setEdgeCount(UseBBInfo->OutEdges, Total);
1498 Changes = true;
1499 }
1500 if (UseBBInfo->UnknownCountInEdge == 1) {
1501 uint64_t Total = 0;
1502 uint64_t InSum = sumEdgeCount(UseBBInfo->InEdges);
1503 if (*UseBBInfo->Count > InSum)
1504 Total = *UseBBInfo->Count - InSum;
1505 setEdgeCount(UseBBInfo->InEdges, Total);
1506 Changes = true;
1507 }
1508 }
1509 }
1510 }
1511
1512 LLVM_DEBUG(dbgs() << "Populate counts in " << NumPasses << " passes.\n");
1513 (void)NumPasses;
1514#ifndef NDEBUG
1515 // Assert every BB has a valid counter.
1516 for (auto &BB : F) {
1517 auto BI = findBBInfo(&BB);
1518 if (BI == nullptr)
1519 continue;
1520 assert(BI->Count && "BB count is not valid");
1521 }
1522#endif
1523 // Now annotate select instructions. This may fixup impossible block counts.
1524 FuncInfo.SIVisitor.annotateSelects(this, &CountPosition);
1525 assert(CountPosition == ProfileCountSize);
1526
1527 uint64_t FuncEntryCount = *getBBInfo(&*F.begin()).Count;
1528 uint64_t FuncMaxCount = FuncEntryCount;
1529 for (auto &BB : F) {
1530 auto BI = findBBInfo(&BB);
1531 if (BI == nullptr)
1532 continue;
1533 FuncMaxCount = std::max(FuncMaxCount, *BI->Count);
1534 }
1535
1536 // Fix the obviously inconsistent entry count.
1537 if (FuncMaxCount > 0 && FuncEntryCount == 0)
1538 FuncEntryCount = 1;
1539 F.setEntryCount(FuncEntryCount);
1540 markFunctionAttributes(FuncEntryCount, FuncMaxCount);
1541
1542 LLVM_DEBUG(FuncInfo.dumpInfo("after reading profile."));
1543}
1544
1545// Assign the scaled count values to the BB with multiple out edges.
1546void PGOUseFunc::setBranchWeights() {
1547 // Generate MD_prof metadata for every branch instruction.
1548 LLVM_DEBUG(dbgs() << "\nSetting branch weights for func " << F.getName()
1549 << " IsCS=" << IsCS << "\n");
1550 for (auto &BB : F) {
1551 Instruction *TI = BB.getTerminator();
1552 if (TI->getNumSuccessors() < 2)
1553 continue;
1554 if (!(isa<CondBrInst>(TI) || isa<SwitchInst>(TI) ||
1556 isa<CallBrInst>(TI)))
1557 continue;
1558
1559 const PGOUseBBInfo &BBCountInfo = getBBInfo(&BB);
1560 if (!*BBCountInfo.Count)
1561 continue;
1562
1563 // We have a non-zero Branch BB.
1564
1565 // SuccessorCount can be greater than OutEdgesCount, because
1566 // removed edges don't appear in OutEdges.
1567 unsigned OutEdgesCount = BBCountInfo.OutEdges.size();
1568 unsigned SuccessorCount = BB.getTerminator()->getNumSuccessors();
1569 assert(OutEdgesCount <= SuccessorCount);
1570
1571 SmallVector<uint64_t, 2> EdgeCounts(SuccessorCount, 0);
1572 uint64_t MaxCount = 0;
1573 for (unsigned It = 0; It < OutEdgesCount; It++) {
1574 const PGOUseEdge *E = BBCountInfo.OutEdges[It];
1575 const BasicBlock *SrcBB = E->SrcBB;
1576 const BasicBlock *DestBB = E->DestBB;
1577 if (DestBB == nullptr)
1578 continue;
1579 unsigned SuccNum = GetSuccessorNumber(SrcBB, DestBB);
1580 uint64_t EdgeCount = *E->Count;
1581 if (EdgeCount > MaxCount)
1582 MaxCount = EdgeCount;
1583 EdgeCounts[SuccNum] = EdgeCount;
1584 }
1585
1586 if (MaxCount)
1587 setProfMetadata(TI, EdgeCounts, MaxCount);
1588 else {
1589 // A zero MaxCount can come about when we have a BB with a positive
1590 // count, and whose successor blocks all have 0 count. This can happen
1591 // when there is no exit block and the code exits via a noreturn function.
1592 auto &Ctx = M->getContext();
1593 Ctx.diagnose(DiagnosticInfoPGOProfile(
1594 M->getName().data(),
1595 Twine("Profile in ") + F.getName().str() +
1596 Twine(" partially ignored") +
1597 Twine(", possibly due to the lack of a return path."),
1598 DS_Warning));
1599 }
1600 }
1601}
1602
1604 for (BasicBlock *Pred : predecessors(BB)) {
1605 if (isa<IndirectBrInst>(Pred->getTerminator()))
1606 return true;
1607 }
1608 return false;
1609}
1610
1611void PGOUseFunc::annotateIrrLoopHeaderWeights() {
1612 LLVM_DEBUG(dbgs() << "\nAnnotating irreducible loop header weights.\n");
1613 // Find irr loop headers
1614 for (auto &BB : F) {
1615 // As a heuristic also annotate indrectbr targets as they have a high chance
1616 // to become an irreducible loop header after the indirectbr tail
1617 // duplication.
1618 if (BFI->isIrrLoopHeader(&BB) || isIndirectBrTarget(&BB)) {
1619 Instruction *TI = BB.getTerminator();
1620 const PGOUseBBInfo &BBCountInfo = getBBInfo(&BB);
1621 setIrrLoopHeaderMetadata(M, TI, *BBCountInfo.Count);
1622 }
1623 }
1624}
1625
1626void PGOUseFunc::setBlockUniformityAttribute() {
1627 if (ProfileRecord.UniformityBits.empty())
1628 return;
1629
1630 // Annotate uniformity on each instrumented IR basic block so later codegen
1631 // passes (MachineFunction) can consume it without relying on fragile block
1632 // numbering heuristics.
1633 //
1634 // Metadata kind: LLVMContext::MD_block_uniformity_profile
1635 // Payload: i1 (true = uniform, false = divergent)
1636
1637 std::vector<BasicBlock *> InstrumentBBs;
1638 FuncInfo.getInstrumentBBs(InstrumentBBs);
1639
1640 LLVMContext &Ctx = F.getContext();
1641 Type *Int1Ty = Type::getInt1Ty(Ctx);
1642
1643 for (size_t I = 0, E = InstrumentBBs.size(); I < E; ++I) {
1644 BasicBlock *BB = InstrumentBBs[I];
1645 if (!BB || !BB->getTerminator())
1646 continue;
1647 bool IsUniform = ProfileRecord.isBlockUniform(I);
1648 auto *MD = MDNode::get(
1649 Ctx, ConstantAsMetadata::get(ConstantInt::get(Int1Ty, IsUniform)));
1650 BB->getTerminator()->setMetadata(LLVMContext::MD_block_uniformity_profile,
1651 MD);
1652 }
1653
1654 LLVM_DEBUG({
1655 dbgs() << "PGO: Set block uniformity profile for " << F.getName() << ": ";
1656 for (size_t I = 0, E = InstrumentBBs.size(); I < E; ++I)
1657 dbgs() << (ProfileRecord.isBlockUniform(I) ? 'U' : 'D');
1658 dbgs() << "\n";
1659 });
1660}
1661
1662void SelectInstVisitor::instrumentOneSelectInst(SelectInst &SI) {
1663 Module *M = F.getParent();
1664 IRBuilder<> Builder(&SI);
1665 Type *Int64Ty = Builder.getInt64Ty();
1666 Value *Cond = SI.getCondition();
1667 // Freeze the condition so that a poison condition can only increment by
1668 // 0 or 1, but not some other value.
1670 Cond = Builder.CreateFreeze(Cond);
1671 auto *Step = Builder.CreateZExt(Cond, Int64Ty);
1672 auto *NormalizedFuncNameVarPtr =
1674 FuncNameVar, PointerType::get(M->getContext(), 0));
1675 Builder.CreateIntrinsic(Intrinsic::instrprof_increment_step,
1676 {NormalizedFuncNameVarPtr, Builder.getInt64(FuncHash),
1677 Builder.getInt32(TotalNumCtrs),
1678 Builder.getInt32(*CurCtrIdx), Step});
1679 ++(*CurCtrIdx);
1680}
1681
1682void SelectInstVisitor::annotateOneSelectInst(SelectInst &SI) {
1683 std::vector<uint64_t> &CountFromProfile = UseFunc->getProfileRecord().Counts;
1684 assert(*CurCtrIdx < CountFromProfile.size() &&
1685 "Out of bound access of counters");
1686 uint64_t SCounts[2];
1687 SCounts[0] = CountFromProfile[*CurCtrIdx]; // True count
1688 ++(*CurCtrIdx);
1689 uint64_t TotalCount = 0;
1690 auto BI = UseFunc->findBBInfo(SI.getParent());
1691 if (BI != nullptr) {
1692 TotalCount = *BI->Count;
1693
1694 // Fix the block count if it is impossible.
1695 if (TotalCount < SCounts[0])
1696 BI->Count = SCounts[0];
1697 }
1698 // False Count
1699 SCounts[1] = (TotalCount > SCounts[0] ? TotalCount - SCounts[0] : 0);
1700 uint64_t MaxCount = std::max(SCounts[0], SCounts[1]);
1701 if (MaxCount)
1702 setProfMetadata(&SI, SCounts, MaxCount);
1703}
1704
1705void SelectInstVisitor::visitSelectInst(SelectInst &SI) {
1706 if (!Opts.pgo_instr_select || Opts.pgo_function_entry_coverage ||
1707 HasSingleByteCoverage)
1708 return;
1709 // FIXME: do not handle this yet.
1710 if (SI.getCondition()->getType()->isVectorTy())
1711 return;
1712
1713 switch (Mode) {
1714 case VM_counting:
1715 NSIs++;
1716 return;
1717 case VM_instrument:
1718 instrumentOneSelectInst(SI);
1719 return;
1720 case VM_annotate:
1721 annotateOneSelectInst(SI);
1722 return;
1723 }
1724
1725 llvm_unreachable("Unknown visiting mode");
1726}
1727
1728static uint32_t getMaxNumAnnotations(const InstrumentationOptions &Opts,
1729 InstrProfValueKind ValueProfKind) {
1730 if (ValueProfKind == IPVK_MemOPSize)
1731 return Opts.memop_max_annotations;
1732 if (ValueProfKind == llvm::IPVK_VTableTarget)
1734 return Opts.icp_max_annotations;
1735}
1736
1737// Traverse all valuesites and annotate the instructions for all value kind.
1738void PGOUseFunc::annotateValueSites() {
1739 if (Opts.disable_vp)
1740 return;
1741
1742 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
1743 annotateValueSites(Kind);
1744}
1745
1746// Annotate the instructions for a specific value kind.
1747void PGOUseFunc::annotateValueSites(uint32_t Kind) {
1748 assert(Kind <= IPVK_Last);
1749 unsigned ValueSiteIndex = 0;
1750
1751 unsigned NumValueSites = ProfileRecord.getNumValueSites(Kind);
1752
1753 // Since there isn't a reliable or fast way for profile reader to tell if a
1754 // profile is generated with `-enable-vtable-value-profiling` on, we run the
1755 // value profile collector over the function IR to find the instrumented sites
1756 // iff function profile records shows the number of instrumented vtable sites
1757 // is not zero. Function cfg already takes the number of instrumented
1758 // indirect call sites into account so it doesn't hash the number of
1759 // instrumented vtables; as a side effect it makes it easier to enable
1760 // profiling and profile use in two steps if needed.
1761 // TODO: Remove this if/when -enable-vtable-value-profiling is on by default.
1762 if (NumValueSites > 0 && Kind == IPVK_VTableTarget &&
1763 NumValueSites != FuncInfo.ValueSites[IPVK_VTableTarget].size() &&
1765 FuncInfo.ValueSites[IPVK_VTableTarget] = VPC.get(IPVK_VTableTarget);
1766 auto &ValueSites = FuncInfo.ValueSites[Kind];
1767 if (NumValueSites != ValueSites.size()) {
1768 auto &Ctx = M->getContext();
1769 Ctx.diagnose(DiagnosticInfoPGOProfile(
1770 M->getName().data(),
1771 Twine("Inconsistent number of value sites for ") +
1772 Twine(ValueProfKindDescr[Kind]) + Twine(" profiling in \"") +
1773 F.getName().str() +
1774 Twine("\", possibly due to the use of a stale profile."),
1775 DS_Warning));
1776 return;
1777 }
1778
1779 for (VPCandidateInfo &I : ValueSites) {
1780 LLVM_DEBUG(dbgs() << "Read one value site profile (kind = " << Kind
1781 << "): Index = " << ValueSiteIndex << " out of "
1782 << NumValueSites << "\n");
1784 *M, *I.AnnotatedInst, ProfileRecord,
1785 static_cast<InstrProfValueKind>(Kind), ValueSiteIndex,
1786 getMaxNumAnnotations(Opts, static_cast<InstrProfValueKind>(Kind)));
1787 ValueSiteIndex++;
1788 }
1789}
1790
1791// Collect the set of members for each Comdat in module M and store
1792// in ComdatMembers.
1794 const InstrumentationOptions &Opts, Module &M,
1795 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers) {
1796 if (!Opts.do_comdat_renaming)
1797 return;
1798 for (Function &F : M)
1799 if (Comdat *C = F.getComdat())
1800 ComdatMembers.insert(std::make_pair(C, &F));
1801 for (GlobalVariable &GV : M.globals())
1802 if (Comdat *C = GV.getComdat())
1803 ComdatMembers.insert(std::make_pair(C, &GV));
1804 for (GlobalAlias &GA : M.aliases())
1805 if (Comdat *C = GA.getComdat())
1806 ComdatMembers.insert(std::make_pair(C, &GA));
1807}
1808
1809// Return true if we should not find instrumentation data for this function
1810static bool skipPGOUse(const InstrumentationOptions &Opts, const Function &F) {
1811 if (F.isDeclaration())
1812 return true;
1813 // If there are too many critical edges, PGO might cause
1814 // compiler time problem. Skip PGO if the number of
1815 // critical edges execeed the threshold.
1816 unsigned NumCriticalEdges = 0;
1817 for (auto &BB : F) {
1818 const Instruction *TI = BB.getTerminator();
1819 for (unsigned I = 0, E = TI->getNumSuccessors(); I != E; ++I) {
1820 if (isCriticalEdge(TI, I))
1821 NumCriticalEdges++;
1822 }
1823 }
1824 if (NumCriticalEdges > Opts.pgo_critical_edge_threshold) {
1825 LLVM_DEBUG(dbgs() << "In func " << F.getName()
1826 << ", NumCriticalEdges=" << NumCriticalEdges
1827 << " exceed the threshold. Skip PGO.\n");
1828 return true;
1829 }
1830 return false;
1831}
1832
1833// Return true if we should not instrument this function
1834static bool skipPGOGen(const InstrumentationOptions &Opts, const Function &F) {
1835 if (skipPGOUse(Opts, F))
1836 return true;
1837 if (F.hasFnAttribute(llvm::Attribute::Naked))
1838 return true;
1839 if (F.hasFnAttribute(llvm::Attribute::NoProfile))
1840 return true;
1841 if (F.hasFnAttribute(llvm::Attribute::SkipProfile))
1842 return true;
1843 if (F.getInstructionCount() < Opts.pgo_function_size_threshold)
1844 return true;
1845 if (Opts.pgo_instrument_cold_function_only) {
1846 if (auto EntryCount = F.getEntryCount())
1847 return *EntryCount > Opts.pgo_cold_instrument_entry_threshold;
1848 return !Opts.pgo_treat_unknown_as_cold;
1849 }
1850 return false;
1851}
1852
1854 const InstrumentationOptions &Opts, Module &M,
1855 function_ref<TargetLibraryInfo &(Function &)> LookupTLI,
1858 function_ref<LoopInfo *(Function &)> LookupLI,
1859 PGOInstrumentationType InstrumentationType) {
1860 // For the context-sensitive instrumentation, we should have a separated pass
1861 // (before LTO/ThinLTO linking) to create these variables.
1862 if (InstrumentationType == PGOInstrumentationType::FDO)
1863 createIRLevelProfileFlagVar(Opts, M, InstrumentationType);
1864
1865 Triple TT(M.getTargetTriple());
1866 LLVMContext &Ctx = M.getContext();
1867 if (!TT.isOSBinFormatELF() && EnableVTableValueProfiling)
1869 M.getName().data(),
1870 Twine("VTable value profiling is presently not "
1871 "supported for non-ELF object formats"),
1872 DS_Warning));
1873 std::unordered_multimap<Comdat *, GlobalValue *> ComdatMembers;
1874 collectComdatMembers(Opts, M, ComdatMembers);
1875
1876 for (auto &F : M) {
1877 if (skipPGOGen(Opts, F))
1878 continue;
1879 TargetLibraryInfo &TLI = LookupTLI(F);
1880 BranchProbabilityInfo *BPI = LookupBPI(F);
1881 BlockFrequencyInfo *BFI = LookupBFI(F);
1882 LoopInfo *LI = LookupLI(F);
1883 FunctionInstrumenter FI(Opts, M, F, TLI, ComdatMembers, BPI, BFI, LI,
1884 InstrumentationType);
1885 FI.instrument();
1886 }
1887 return true;
1888}
1889
1890PreservedAnalyses
1892 createProfileFileNameVar(M, CSInstrName);
1893 // The variable in a comdat may be discarded by LTO. Ensure the declaration
1894 // will be retained.
1896 M, createIRLevelProfileFlagVar(InstrumentationOptions::Global, M,
1898 if (ProfileSampling)
1903 return PA;
1904}
1905
1908 auto &FAM = MAM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
1909 auto LookupTLI = [&FAM](Function &F) -> TargetLibraryInfo & {
1910 return FAM.getResult<TargetLibraryAnalysis>(F);
1911 };
1912 auto LookupBPI = [&FAM](Function &F) {
1913 return &FAM.getResult<BranchProbabilityAnalysis>(F);
1914 };
1915 auto LookupBFI = [&FAM](Function &F) {
1916 return &FAM.getResult<BlockFrequencyAnalysis>(F);
1917 };
1918 auto LookupLI = [&FAM](Function &F) {
1919 return &FAM.getResult<LoopAnalysis>(F);
1920 };
1921
1922 if (!instrumentAllFunctions(InstrumentationOptions::Global, M, LookupTLI,
1923 LookupBPI, LookupBFI, LookupLI,
1924 InstrumentationType))
1925 return PreservedAnalyses::all();
1926
1927 return PreservedAnalyses::none();
1928}
1929
1930// Using the ratio b/w sums of profile count values and BFI count values to
1931// adjust the func entry count.
1932static void fixFuncEntryCount(PGOUseFunc &Func, CycleInfo &CI,
1933 BranchProbabilityInfo &NBPI) {
1934 Function &F = Func.getFunc();
1935 BlockFrequencyInfo NBFI(F, NBPI, CI);
1936#ifndef NDEBUG
1937 auto BFIEntryCount = F.getEntryCount();
1938 assert(BFIEntryCount && (*BFIEntryCount > 0) && "Invalid BFI Entrycount");
1939#endif
1940 auto SumCount = APFloat::getZero(APFloat::IEEEdouble());
1941 auto SumBFICount = APFloat::getZero(APFloat::IEEEdouble());
1942 for (auto &BBI : F) {
1943 uint64_t CountValue = 0;
1944 uint64_t BFICountValue = 0;
1945 if (!Func.findBBInfo(&BBI))
1946 continue;
1947 auto BFICount = NBFI.getBlockProfileCount(&BBI);
1948 CountValue = *Func.getBBInfo(&BBI).Count;
1949 BFICountValue = *BFICount;
1950 SumCount.add(APFloat(CountValue * 1.0), APFloat::rmNearestTiesToEven);
1951 SumBFICount.add(APFloat(BFICountValue * 1.0), APFloat::rmNearestTiesToEven);
1952 }
1953 if (SumCount.isZero())
1954 return;
1955
1956 assert(SumBFICount.compare(APFloat(0.0)) == APFloat::cmpGreaterThan &&
1957 "Incorrect sum of BFI counts");
1958 if (SumBFICount.compare(SumCount) == APFloat::cmpEqual)
1959 return;
1960 double Scale = (SumCount / SumBFICount).convertToDouble();
1961 if (Scale < 1.001 && Scale > 0.999)
1962 return;
1963
1964 uint64_t FuncEntryCount = *Func.getBBInfo(&*F.begin()).Count;
1965 uint64_t NewEntryCount = 0.5 + FuncEntryCount * Scale;
1966 if (NewEntryCount == 0)
1967 NewEntryCount = 1;
1968 if (NewEntryCount != FuncEntryCount) {
1969 F.setEntryCount(NewEntryCount);
1970 LLVM_DEBUG(dbgs() << "FixFuncEntryCount: in " << F.getName()
1971 << ", entry_count " << FuncEntryCount << " --> "
1972 << NewEntryCount << "\n");
1973 }
1974}
1975
1976// Compare the profile count values with BFI count values, and print out
1977// the non-matching ones.
1978static void verifyFuncBFI(const InstrumentationOptions &Opts, PGOUseFunc &Func,
1980 uint64_t HotCountThreshold,
1982 Function &F = Func.getFunc();
1983 BlockFrequencyInfo NBFI(F, NBPI, CI);
1984 // bool PrintFunc = false;
1985 bool HotBBOnly = Opts.pgo_verify_hot_bfi;
1986 StringRef Msg;
1988
1989 unsigned BBNum = 0, BBMisMatchNum = 0, NonZeroBBNum = 0;
1990 for (auto &BBI : F) {
1991 PGOUseBBInfo *BBInfo = Func.findBBInfo(&BBI);
1992 if (!BBInfo)
1993 continue;
1994
1995 uint64_t CountValue = BBInfo->Count.value_or(CountValue);
1996 uint64_t BFICountValue = 0;
1997
1998 BBNum++;
1999 if (CountValue)
2000 NonZeroBBNum++;
2001 auto BFICount = NBFI.getBlockProfileCount(&BBI);
2002 if (BFICount)
2003 BFICountValue = *BFICount;
2004
2005 if (HotBBOnly) {
2006 bool rawIsHot = CountValue >= HotCountThreshold;
2007 bool BFIIsHot = BFICountValue >= HotCountThreshold;
2008 bool rawIsCold = CountValue <= ColdCountThreshold;
2009 bool ShowCount = false;
2010 if (rawIsHot && !BFIIsHot) {
2011 Msg = "raw-Hot to BFI-nonHot";
2012 ShowCount = true;
2013 } else if (rawIsCold && BFIIsHot) {
2014 Msg = "raw-Cold to BFI-Hot";
2015 ShowCount = true;
2016 }
2017 if (!ShowCount)
2018 continue;
2019 } else {
2020 if ((CountValue < Opts.pgo_verify_bfi_cutoff) &&
2021 (BFICountValue < Opts.pgo_verify_bfi_cutoff))
2022 continue;
2023 uint64_t Diff = (BFICountValue >= CountValue)
2024 ? BFICountValue - CountValue
2025 : CountValue - BFICountValue;
2026 if (Diff <= CountValue / 100 * Opts.pgo_verify_bfi_ratio)
2027 continue;
2028 }
2029 BBMisMatchNum++;
2030
2031 ORE.emit([&]() {
2033 F.getSubprogram(), &BBI);
2034 Remark << "BB " << ore::NV("Block", BBI.getName())
2035 << " Count=" << ore::NV("Count", CountValue)
2036 << " BFI_Count=" << ore::NV("Count", BFICountValue);
2037 if (!Msg.empty())
2038 Remark << " (" << Msg << ")";
2039 return Remark;
2040 });
2041 }
2042 if (BBMisMatchNum)
2043 ORE.emit([&]() {
2044 return OptimizationRemarkAnalysis(DEBUG_TYPE, "bfi-verify",
2045 F.getSubprogram(), &F.getEntryBlock())
2046 << "In Func " << ore::NV("Function", F.getName())
2047 << ": Num_of_BB=" << ore::NV("Count", BBNum)
2048 << ", Num_of_non_zerovalue_BB=" << ore::NV("Count", NonZeroBBNum)
2049 << ", Num_of_mis_matching_BB=" << ore::NV("Count", BBMisMatchNum);
2050 });
2051}
2052
2054 const InstrumentationOptions &Opts, Module &M, StringRef ProfileFileName,
2055 StringRef ProfileRemappingFileName, vfs::FileSystem &FS,
2056 function_ref<TargetLibraryInfo &(Function &)> LookupTLI,
2059 function_ref<LoopInfo *(Function &)> LookupLI, ProfileSummaryInfo *PSI,
2060 bool IsCS) {
2061 LLVM_DEBUG(dbgs() << "Read in profile counters: ");
2062 auto &Ctx = M.getContext();
2063 // Read the counter array from file.
2064 auto ReaderOrErr = IndexedInstrProfReader::create(ProfileFileName, FS,
2065 ProfileRemappingFileName);
2066 if (Error E = ReaderOrErr.takeError()) {
2067 handleAllErrors(std::move(E), [&](const ErrorInfoBase &EI) {
2068 Ctx.diagnose(
2069 DiagnosticInfoPGOProfile(ProfileFileName.data(), EI.message()));
2070 });
2071 return false;
2072 }
2073
2074 std::unique_ptr<IndexedInstrProfReader> PGOReader =
2075 std::move(ReaderOrErr.get());
2076 if (!PGOReader) {
2077 Ctx.diagnose(DiagnosticInfoPGOProfile(ProfileFileName.data(),
2078 StringRef("Cannot get PGOReader")));
2079 return false;
2080 }
2081 if (!PGOReader->hasCSIRLevelProfile() && IsCS)
2082 return false;
2083
2084 // TODO: might need to change the warning once the clang option is finalized.
2085 if (!PGOReader->isIRLevelProfile()) {
2086 Ctx.diagnose(DiagnosticInfoPGOProfile(
2087 ProfileFileName.data(), "Not an IR level instrumentation profile"));
2088 return false;
2089 }
2090 if (PGOReader->functionEntryOnly()) {
2091 Ctx.diagnose(DiagnosticInfoPGOProfile(
2092 ProfileFileName.data(),
2093 "Function entry profiles are not yet supported for optimization"));
2094 return false;
2095 }
2096
2097 // Add the profile summary (read from the header of the indexed summary) here
2098 // so that we can use it below when reading counters (which checks if the
2099 // function should be marked with a cold or inlinehint attribute).
2100 M.setProfileSummary(PGOReader->getSummary(IsCS).getMD(M.getContext()),
2103 PSI->refresh();
2104
2105 std::unordered_multimap<Comdat *, GlobalValue *> ComdatMembers;
2106 collectComdatMembers(Opts, M, ComdatMembers);
2107 std::vector<Function *> HotFunctions;
2108 std::vector<Function *> ColdFunctions;
2109
2110 // If the profile marked as always instrument the entry BB, do the
2111 // same. Note this can be overwritten by the internal option in CFGMST.h
2112 bool InstrumentFuncEntry =
2113 valueOr(Opts.pgo_instrument_entry, PGOReader->instrEntryBBEnabled());
2114 bool InstrumentLoopEntries = valueOr(Opts.pgo_instrument_loop_entries,
2115 PGOReader->instrLoopEntriesEnabled());
2116
2117 bool HasSingleByteCoverage = PGOReader->hasSingleByteCoverage();
2118 for (auto &F : M) {
2119 if (skipPGOUse(Opts, F))
2120 continue;
2121 TargetLibraryInfo &TLI = LookupTLI(F);
2122 BranchProbabilityInfo *BPI = LookupBPI(F);
2123 BlockFrequencyInfo *BFI = LookupBFI(F);
2124 LoopInfo *LI = LookupLI(F);
2125 if (!HasSingleByteCoverage) {
2126 // Split indirectbr critical edges here before computing the MST rather
2127 // than later in getInstrBB() to avoid invalidating it.
2128 SplitIndirectBrCriticalEdges(F, /*IgnoreBlocksWithoutPHI=*/false, BPI,
2129 BFI);
2130 }
2131 PGOUseFunc Func(Opts, F, &M, TLI, ComdatMembers, BPI, BFI, LI, PSI, IsCS,
2132 InstrumentFuncEntry, InstrumentLoopEntries,
2133 HasSingleByteCoverage);
2134 if (!Func.getRecord(PGOReader.get()))
2135 continue;
2136 if (HasSingleByteCoverage) {
2137 Func.populateCoverage();
2138 continue;
2139 }
2140 // When PseudoKind is set to a value other than InstrProfRecord::NotPseudo,
2141 // it means the profile for the function is unrepresentative and this
2142 // function is actually hot / warm. We will reset the function hot / cold
2143 // attribute and drop all the profile counters.
2145 bool AllZeros = false;
2146 if (!Func.readCounters(AllZeros, PseudoKind))
2147 continue;
2148 if (AllZeros) {
2149 F.setEntryCount(0);
2150 if (Func.getProgramMaxCount() != 0)
2151 ColdFunctions.push_back(&F);
2152 continue;
2153 }
2154 if (PseudoKind != InstrProfRecord::NotPseudo) {
2155 // Clear function attribute cold.
2156 if (F.hasFnAttribute(Attribute::Cold))
2157 F.removeFnAttr(Attribute::Cold);
2158 // Set function attribute as hot.
2159 if (PseudoKind == InstrProfRecord::PseudoHot)
2160 F.addFnAttr(Attribute::Hot);
2161 continue;
2162 }
2163 Func.populateCounters();
2164 Func.setBranchWeights();
2165 Func.annotateValueSites();
2166 Func.annotateIrrLoopHeaderWeights();
2167 Func.setBlockUniformityAttribute();
2168 PGOUseFunc::FuncFreqAttr FreqAttr = Func.getFuncFreqAttr();
2169 if (FreqAttr == PGOUseFunc::FFA_Cold)
2170 ColdFunctions.push_back(&F);
2171 else if (FreqAttr == PGOUseFunc::FFA_Hot)
2172 HotFunctions.push_back(&F);
2173 if (PGOViewCounts != PGOVCT_None &&
2174 (ViewBlockFreqFuncName.empty() ||
2175 F.getName() == ViewBlockFreqFuncName)) {
2176 CycleInfo CI;
2177 CI.compute(F);
2178 std::unique_ptr<BranchProbabilityInfo> NewBPI =
2179 std::make_unique<BranchProbabilityInfo>(F, CI);
2180 std::unique_ptr<BlockFrequencyInfo> NewBFI =
2181 std::make_unique<BlockFrequencyInfo>(F, *NewBPI, CI);
2183 NewBFI->view();
2184 else if (PGOViewCounts == PGOVCT_Text) {
2185 dbgs() << "pgo-view-counts: " << Func.getFunc().getName() << "\n";
2186 NewBFI->print(dbgs());
2187 }
2188 }
2189 if (Opts.pgo_view_raw_counts != PGOVCT_None &&
2190 (ViewBlockFreqFuncName.empty() ||
2191 F.getName() == ViewBlockFreqFuncName)) {
2192 if (Opts.pgo_view_raw_counts == PGOVCT_Graph)
2193 if (ViewBlockFreqFuncName.empty())
2194 WriteGraph(&Func, Twine("PGORawCounts_") + Func.getFunc().getName());
2195 else
2196 ViewGraph(&Func, Twine("PGORawCounts_") + Func.getFunc().getName());
2197 else if (Opts.pgo_view_raw_counts == PGOVCT_Text) {
2198 dbgs() << "pgo-view-raw-counts: " << Func.getFunc().getName() << "\n";
2199 Func.dumpInfo();
2200 }
2201 }
2202
2203 if (Opts.pgo_verify_bfi || Opts.pgo_verify_hot_bfi ||
2204 Opts.pgo_fix_entry_count) {
2205 CycleInfo CI;
2206 CI.compute(F);
2207 BranchProbabilityInfo NBPI(F, CI);
2208
2209 // Fix func entry count.
2210 if (Opts.pgo_fix_entry_count)
2211 fixFuncEntryCount(Func, CI, NBPI);
2212
2213 // Verify BlockFrequency information.
2214 uint64_t HotCountThreshold = 0, ColdCountThreshold = 0;
2215 if (Opts.pgo_verify_hot_bfi) {
2216 HotCountThreshold = PSI->getOrCompHotCountThreshold();
2218 }
2219 verifyFuncBFI(Opts, Func, CI, NBPI, HotCountThreshold,
2221 }
2222 }
2223
2224 // Set function hotness attribute from the profile.
2225 // We have to apply these attributes at the end because their presence
2226 // can affect the BranchProbabilityInfo of any callers, resulting in an
2227 // inconsistent MST between prof-gen and prof-use.
2228 for (auto &F : HotFunctions) {
2229 F->addFnAttr(Attribute::InlineHint);
2230 LLVM_DEBUG(dbgs() << "Set inline attribute to function: " << F->getName()
2231 << "\n");
2232 }
2233 for (auto &F : ColdFunctions) {
2234 // Only set when there is no Attribute::Hot set by the user. For Hot
2235 // attribute, user's annotation has the precedence over the profile.
2236 if (F->hasFnAttribute(Attribute::Hot)) {
2237 auto &Ctx = M.getContext();
2238 std::string Msg = std::string("Function ") + F->getName().str() +
2239 std::string(" is annotated as a hot function but"
2240 " the profile is cold");
2241 Ctx.diagnose(
2242 DiagnosticInfoPGOProfile(M.getName().data(), Msg, DS_Warning));
2243 continue;
2244 }
2245 F->addFnAttr(Attribute::Cold);
2246 LLVM_DEBUG(dbgs() << "Set cold attribute to function: " << F->getName()
2247 << "\n");
2248 }
2249 return true;
2250}
2251
2253 std::string Filename, std::string RemappingFilename, bool IsCS,
2255 : ProfileFileName(std::move(Filename)),
2256 ProfileRemappingFileName(std::move(RemappingFilename)), IsCS(IsCS),
2257 FS(std::move(VFS)) {
2258 const InstrumentationOptions &Opts = InstrumentationOptions::Global;
2259 if (!Opts.pgo_test_profile_file.empty())
2260 ProfileFileName = Opts.pgo_test_profile_file;
2261 if (!Opts.pgo_test_profile_remapping_file.empty())
2262 ProfileRemappingFileName = Opts.pgo_test_profile_remapping_file;
2263 if (!FS)
2265}
2266
2269
2270 auto &FAM = MAM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
2271 auto LookupTLI = [&FAM](Function &F) -> TargetLibraryInfo & {
2272 return FAM.getResult<TargetLibraryAnalysis>(F);
2273 };
2274 auto LookupBPI = [&FAM](Function &F) {
2275 return &FAM.getResult<BranchProbabilityAnalysis>(F);
2276 };
2277 auto LookupBFI = [&FAM](Function &F) {
2278 return &FAM.getResult<BlockFrequencyAnalysis>(F);
2279 };
2280 auto LookupLI = [&FAM](Function &F) {
2281 return &FAM.getResult<LoopAnalysis>(F);
2282 };
2283
2284 auto *PSI = &MAM.getResult<ProfileSummaryAnalysis>(M);
2285 if (!annotateAllFunctions(InstrumentationOptions::Global, M, ProfileFileName,
2286 ProfileRemappingFileName, *FS, LookupTLI, LookupBPI,
2287 LookupBFI, LookupLI, PSI, IsCS))
2288 return PreservedAnalyses::all();
2289
2290 return PreservedAnalyses::none();
2291}
2292
2293static std::string getSimpleNodeName(const BasicBlock *Node) {
2294 if (!Node->getName().empty())
2295 return Node->getName().str();
2296
2297 std::string SimpleNodeName;
2298 raw_string_ostream OS(SimpleNodeName);
2299 Node->printAsOperand(OS, false);
2300 return SimpleNodeName;
2301}
2302
2304 uint64_t MaxCount) {
2305 auto Weights = downscaleWeights(EdgeCounts, MaxCount);
2306
2307 LLVM_DEBUG(dbgs() << "Weight is: "; for (const auto &W : Weights) {
2308 dbgs() << W << " ";
2309 } dbgs() << "\n");
2310
2311 misexpect::checkExpectAnnotations(*TI, Weights, /*IsFrontend=*/false);
2312
2313 setBranchWeights(*TI, Weights, /*IsExpected=*/false);
2314
2315 if (InstrumentationOptions::Global.pgo_emit_branch_prob) {
2316 std::string BrCondStr = getBranchCondString(TI);
2317 if (BrCondStr.empty())
2318 return;
2319
2320 uint64_t WSum =
2321 std::accumulate(Weights.begin(), Weights.end(), (uint64_t)0,
2322 [](uint64_t w1, uint64_t w2) { return w1 + w2; });
2323 uint64_t TotalCount =
2324 std::accumulate(EdgeCounts.begin(), EdgeCounts.end(), (uint64_t)0,
2325 [](uint64_t c1, uint64_t c2) { return c1 + c2; });
2326 uint64_t Scale = calculateCountScale(WSum);
2327 BranchProbability BP(scaleBranchCount(Weights[0], Scale),
2328 scaleBranchCount(WSum, Scale));
2329 std::string BranchProbStr;
2330 raw_string_ostream OS(BranchProbStr);
2331 OS << BP;
2332 OS << " (total count : " << TotalCount << ")";
2333 Function *F = TI->getParent()->getParent();
2335 ORE.emit([&]() {
2336 return OptimizationRemark(DEBUG_TYPE, "pgo-instrumentation", TI)
2337 << BrCondStr << " is true with probability : " << BranchProbStr;
2338 });
2339 }
2340}
2341
2342namespace llvm {
2343
2345 MDBuilder MDB(M->getContext());
2346 TI->setMetadata(llvm::LLVMContext::MD_irr_loop,
2348}
2349
2350template <> struct GraphTraits<PGOUseFunc *> {
2351 using NodeRef = const BasicBlock *;
2354
2355 static NodeRef getEntryNode(const PGOUseFunc *G) {
2356 return &G->getFunc().front();
2357 }
2358
2360 return succ_begin(N);
2361 }
2362
2363 static ChildIteratorType child_end(const NodeRef N) { return succ_end(N); }
2364
2365 static nodes_iterator nodes_begin(const PGOUseFunc *G) {
2366 return nodes_iterator(G->getFunc().begin());
2367 }
2368
2369 static nodes_iterator nodes_end(const PGOUseFunc *G) {
2370 return nodes_iterator(G->getFunc().end());
2371 }
2372};
2373
2374template <> struct DOTGraphTraits<PGOUseFunc *> : DefaultDOTGraphTraits {
2375 explicit DOTGraphTraits(bool isSimple = false)
2377
2378 static std::string getGraphName(const PGOUseFunc *G) {
2379 return std::string(G->getFunc().getName());
2380 }
2381
2382 std::string getNodeLabel(const BasicBlock *Node, const PGOUseFunc *Graph) {
2383 std::string Result;
2384 raw_string_ostream OS(Result);
2385
2386 OS << getSimpleNodeName(Node) << ":\\l";
2387 PGOUseBBInfo *BI = Graph->findBBInfo(Node);
2388 OS << "Count : ";
2389 if (BI && BI->Count)
2390 OS << *BI->Count << "\\l";
2391 else
2392 OS << "Unknown\\l";
2393
2394 if (!InstrumentationOptions::Global.pgo_instr_select)
2395 return Result;
2396
2397 for (const Instruction &I : *Node) {
2398 if (!isa<SelectInst>(&I))
2399 continue;
2400 // Display scaled counts for SELECT instruction:
2401 OS << "SELECT : { T = ";
2402 uint64_t TC, FC;
2403 bool HasProf = extractBranchWeights(I, TC, FC);
2404 if (!HasProf)
2405 OS << "Unknown, F = Unknown }\\l";
2406 else
2407 OS << TC << ", F = " << FC << " }\\l";
2408 }
2409 return Result;
2410 }
2411};
2412
2413} // end namespace llvm
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned uint64_t
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< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
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 void annotateFunctionWithHashMismatch(Function &F, LLVMContext &ctx)
static bool instrumentAllFunctions(const InstrumentationOptions &Opts, 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 bool skipPGOGen(const InstrumentationOptions &Opts, const Function &F)
static void fixFuncEntryCount(PGOUseFunc &Func, CycleInfo &CI, BranchProbabilityInfo &NBPI)
static void populateEHOperandBundle(VPCandidateInfo &Cand, DenseMap< BasicBlock *, ColorVector > &BlockColors, SmallVectorImpl< OperandBundleDef > &OpBundles)
static void collectComdatMembers(const InstrumentationOptions &Opts, Module &M, std::unordered_multimap< Comdat *, GlobalValue * > &ComdatMembers)
static void setupBBInfoEdges(const FuncPGOInstrumentation< PGOUseEdge, PGOUseBBInfo > &FuncInfo)
Set up InEdges/OutEdges for all BBs in the MST.
ValueProfileCollector::CandidateInfo VPCandidateInfo
static bool skipPGOUse(const InstrumentationOptions &Opts, const Function &F)
static uint64_t sumEdgeCount(const ArrayRef< PGOUseEdge * > Edges)
static uint32_t getMaxNumAnnotations(const InstrumentationOptions &Opts, InstrProfValueKind ValueProfKind)
static std::string getSimpleNodeName(const BasicBlock *Node)
static bool isIndirectBrTarget(BasicBlock *BB)
static bool annotateAllFunctions(const InstrumentationOptions &Opts, 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 GlobalVariable * createIRLevelProfileFlagVar(const InstrumentationOptions &Opts, Module &M, PGOInstrumentationType InstrumentationType)
static void verifyFuncBFI(const InstrumentationOptions &Opts, PGOUseFunc &Func, CycleInfo &CI, BranchProbabilityInfo &NBPI, uint64_t HotCountThreshold, uint64_t ColdCountThreshold)
static bool canRenameComdat(const InstrumentationOptions &Opts, Function &F, std::unordered_multimap< Comdat *, GlobalValue * > &ComdatMembers)
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:305
static constexpr roundingMode rmNearestTiesToEven
Definition APFloat.h:361
static APFloat getZero(const fltSemantics &Sem, bool Negative=false)
Factory for Positive and Negative Zero.
Definition APFloat.h:1183
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:459
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) 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:548
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...
bool empty() const
Definition DenseMap.h:717
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:767
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:828
Diagnostic information for the PGO profiler.
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:459
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:77
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:594
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:1081
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1579
Tuple of metadata.
Definition Metadata.h:1496
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1525
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
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:300
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:257
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.
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > OverloadTys={})
Look up the Function declaration of the intrinsic id in the Module M.
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:393
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
void write64le(void *P, uint64_t V)
Definition Endian.h:458
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.
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:1685
LLVM_ABI std::string getPGOFuncName(const Function &F, bool InLTO=false, uint64_t Version=INSTR_PROF_INDEX_VERSION)
Please use getIRPGOObjectName for LLVM IR instrumentation.
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
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...
InnerAnalysisManagerProxy< FunctionAnalysisManager, Module > FunctionAnalysisManagerModuleProxy
Provide the FunctionAnalysisManager to Module proxy.
LLVM_ABI std::string getIRPGOObjectName(const GlobalObject &GO, bool InLTO=false)
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."))
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
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:408
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
IRBuilder(LLVMContext &, FolderTy, InserterTy) -> IRBuilder< FolderTy, InserterTy >
LLVM_ABI EHPersonality classifyEHPersonality(const Value *Pers)
See if the given exception handling personality function is one that we understand.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
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)
InstrProfValueKind
Definition InstrProf.h:324
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.
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
LLVM_ABI bool canRenameComdatFunc(const Function &F, bool CheckAddressTaken=false)
Check if we can safely rename this Comdat function.
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:1933
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
uint32_t scaleBranchCount(uint64_t Count, uint64_t Scale)
Scale an individual branch count.
constexpr bool valueOr(BoolOrDefault X, bool Default)
LLVM_ABI bool isGuaranteedNotToBePoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Returns true if V cannot be poison, but may be undef.
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."))
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition MIRParser.h:39
LLVM_ABI bool isPGOInstrumentColdFunctionOnly()
Return the value of -pgo-instrument-cold-function-only.
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:939
std::vector< uint64_t > Counts
Definition InstrProf.h:894
CountPseudoKind getCountPseudoKind() const
Definition InstrProf.h:1022
uint32_t getNumValueSites(uint32_t ValueKind) const
Return the number of instrumented sites for ValueKind.
Definition InstrProf.h:1134
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:902
static void setCSFlagInHash(uint64_t &FuncHash)
Definition InstrProf.h:1115
static constexpr uint64_t FUNC_HASH_MASK
Definition InstrProf.h:1090