LLVM 23.0.0git
CtxProfAnalysis.h
Go to the documentation of this file.
1//===- CtxProfAnalysis.h - maintain contextual profile info -*- C++ ---*-===//
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#ifndef LLVM_ANALYSIS_CTXPROFANALYSIS_H
10#define LLVM_ANALYSIS_CTXPROFANALYSIS_H
11
12#include "llvm/ADT/SetVector.h"
13#include "llvm/IR/GlobalValue.h"
14#include "llvm/IR/InstrTypes.h"
16#include "llvm/IR/PassManager.h"
19#include <optional>
20
21namespace llvm {
22
23class CtxProfAnalysis;
24
28
29/// The instrumented contextual profile, produced by the CtxProfAnalysis.
30class PGOContextualProfile {
31 friend class CtxProfAnalysis;
33 struct FunctionInfo {
34 uint32_t NextCounterIndex = 0;
35 uint32_t NextCallsiteIndex = 0;
36 const std::string Name;
38 FunctionInfo(StringRef Name) : Name(Name) {}
39 };
40 PGOCtxProfile Profiles;
41
42 // True if this module is a post-thinlto module containing just functions
43 // participating in one or more contextual profiles.
44 bool IsInSpecializedModule = false;
45
46 // For the GUIDs in this module, associate metadata about each function which
47 // we'll need when we maintain the profiles during IPO transformations.
48 std::map<GlobalValue::GUID, FunctionInfo> FuncInfo;
49
50 // This is meant to be constructed from CtxProfAnalysis, which will also set
51 // its state piecemeal.
52 PGOContextualProfile() = default;
53
54 void initIndex();
55
56public:
57 PGOContextualProfile(const PGOContextualProfile &) = delete;
58 PGOContextualProfile(PGOContextualProfile &&) = default;
59
61 return Profiles.Contexts;
62 }
63
64 const PGOCtxProfile &profiles() const { return Profiles; }
65
67
68 bool isFunctionKnown(const Function &F) const { return !F.isDeclaration(); }
69
71 auto It = FuncInfo.find(GUID);
72 if (It == FuncInfo.end())
73 return "";
74 return It->second.Name;
75 }
76
79 return FuncInfo.find(F.getGUID())->second.NextCounterIndex;
80 }
81
84 return FuncInfo.find(F.getGUID())->second.NextCallsiteIndex;
85 }
86
89 return FuncInfo.find(F.getGUID())->second.NextCounterIndex++;
90 }
91
94 return FuncInfo.find(F.getGUID())->second.NextCallsiteIndex++;
95 }
96
99
100 LLVM_ABI void update(Visitor, const Function &F);
101 LLVM_ABI void visit(ConstVisitor, const Function *F = nullptr) const;
102
103 LLVM_ABI const CtxProfFlatProfile flatten() const;
105
107 ModuleAnalysisManager::Invalidator &) {
108 // Check whether the analysis has been explicitly invalidated. Otherwise,
109 // it's stateless and remains preserved.
110 auto PAC = PA.getChecker<CtxProfAnalysis>();
111 return !PAC.preservedWhenStateless();
112 }
113};
114
115class CtxProfAnalysis : public AnalysisInfoMixin<CtxProfAnalysis> {
116 const std::optional<StringRef> Profile;
117
118public:
120 LLVM_ABI explicit CtxProfAnalysis(
121 std::optional<StringRef> Profile = std::nullopt);
122
124
126
127 /// Get the instruction instrumenting a callsite, or nullptr if that cannot be
128 /// found.
130
131 /// Get the instruction instrumenting a BB, or nullptr if not present.
133
134 /// Get the step instrumentation associated with a `select`
137
138 // FIXME: refactor to an advisor model, and separate
140 CallBase &IC, Result &Profile,
141 SetVector<std::pair<CallBase *, Function *>> &Candidates);
142};
143
145 : public RequiredPassInfoMixin<CtxProfAnalysisPrinterPass> {
146public:
147 enum class PrintMode { Everything, YAML };
149
151
152private:
153 raw_ostream &OS;
154 const PrintMode Mode;
155};
156
157/// Utility that propagates counter values to each basic block and to each edge
158/// when a basic block has more than one outgoing edge, using an adaptation of
159/// PGOUseFunc::populateCounters.
160// FIXME(mtrofin): look into factoring the code to share one implementation.
161class ProfileAnnotatorImpl;
163 std::unique_ptr<ProfileAnnotatorImpl> PImpl;
164
165public:
167 LLVM_ABI uint64_t getBBCount(const BasicBlock &BB) const;
168
169 // Finds the true and false counts for the given select instruction. Returns
170 // false if the select doesn't have instrumentation or if the count of the
171 // parent BB is 0.
173 uint64_t &FalseCount) const;
174 // Clears Profile and populates it with the edge weights, in the same order as
175 // they need to appear in the MD_prof metadata. Also computes the max of those
176 // weights an returns it in MaxCount. Returs false if:
177 // - the BB has less than 2 successors
178 // - the counts are 0
181 uint64_t &MaxCount) const;
183};
184
185} // namespace llvm
186#endif // LLVM_ANALYSIS_CTXPROFANALYSIS_H
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
#define LLVM_ABI
Definition Compiler.h:213
This header defines various interfaces for pass management in LLVM.
#define F(x, y, z)
Definition MD5.cpp:54
Load MIR Sample Profile
Reader for contextual iFDO profile, which comes in bitstream format.
ModuleAnalysisManager MAM
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")))
This file implements a set that has insertion order iteration characteristics.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
LLVM Basic Block Representation.
Definition BasicBlock.h:62
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &MAM)
LLVM_ABI CtxProfAnalysisPrinterPass(raw_ostream &OS)
LLVM_ABI PGOContextualProfile run(Module &M, ModuleAnalysisManager &MAM)
static LLVM_ABI InstrProfIncrementInst * getBBInstrumentation(BasicBlock &BB)
Get the instruction instrumenting a BB, or nullptr if not present.
static LLVM_ABI InstrProfIncrementInstStep * getSelectInstrumentation(SelectInst &SI)
Get the step instrumentation associated with a select
static LLVM_ABI void collectIndirectCallPromotionList(CallBase &IC, Result &Profile, SetVector< std::pair< CallBase *, Function * > > &Candidates)
static LLVM_ABI InstrProfCallsite * getCallsiteInstrumentation(CallBase &CB)
Get the instruction instrumenting a callsite, or nullptr if that cannot be found.
static LLVM_ABI AnalysisKey Key
PGOContextualProfile Result
LLVM_ABI CtxProfAnalysis(std::optional< StringRef > Profile=std::nullopt)
uint64_t GUID
Declare a type to represent a global unique identifier for a global value.
This represents the llvm.instrprof.callsite intrinsic.
This represents the llvm.instrprof.increment.step intrinsic.
This represents the llvm.instrprof.increment intrinsic.
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
The instrumented contextual profile, produced by the CtxProfAnalysis.
LLVM_ABI void visit(ConstVisitor, const Function *F=nullptr) const
friend class CtxProfAnalysisPrinterPass
PGOContextualProfile(PGOContextualProfile &&)=default
LLVM_ABI const CtxProfFlatProfile flatten() const
LLVM_ABI bool isInSpecializedModule() const
LLVM_ABI void update(Visitor, const Function &F)
StringRef getFunctionName(GlobalValue::GUID GUID) const
bool invalidate(Module &, const PreservedAnalyses &PA, ModuleAnalysisManager::Invalidator &)
uint32_t getNumCounters(const Function &F) const
function_ref< void(PGOCtxProfContext &)> Visitor
uint32_t allocateNextCounterIndex(const Function &F)
const PGOCtxProfile & profiles() const
function_ref< void(const PGOCtxProfContext &)> ConstVisitor
const CtxProfContextualProfiles & contexts() const
PGOContextualProfile(const PGOContextualProfile &)=delete
uint32_t getNumCallsites(const Function &F) const
uint32_t allocateNextCallsiteIndex(const Function &F)
LLVM_ABI const CtxProfFlatIndirectCallProfile flattenVirtCalls() const
bool isFunctionKnown(const Function &F) const
A node (context) in the loaded contextual profile, suitable for mutation during IPO passes.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
PreservedAnalysisChecker getChecker() const
Build a checker for this PreservedAnalyses and the specified analysis type.
Definition Analysis.h:275
LLVM_ABI ~ProfileAnnotator()
LLVM_ABI bool getSelectInstrProfile(SelectInst &SI, uint64_t &TrueCount, uint64_t &FalseCount) const
LLVM_ABI bool getOutgoingBranchWeights(BasicBlock &BB, SmallVectorImpl< uint64_t > &Profile, uint64_t &MaxCount) const
LLVM_ABI uint64_t getBBCount(const BasicBlock &BB) const
LLVM_ABI ProfileAnnotator(const Function &F, ArrayRef< uint64_t > RawCounters)
This class represents the LLVM 'select' instruction.
A vector that has set insertion semantics.
Definition SetVector.h:57
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
size_t find(char C, size_t From=0) const
Search for the first character C in the string.
Definition StringRef.h:290
An efficient, type-erasing, non-owning reference to a callable.
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
This is an optimization pass for GlobalISel generic memory operations.
std::map< GlobalValue::GUID, SmallVector< uint64_t, 1 > > CtxProfFlatProfile
DenseMap< GlobalValue::GUID, uint64_t > FlatIndirectTargets
std::map< GlobalValue::GUID, PGOCtxProfContext > CtxProfContextualProfiles
DenseMap< GlobalValue::GUID, DenseMap< uint32_t, FlatIndirectTargets > > CtxProfFlatIndirectCallProfile
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition MIRParser.h:39
A CRTP mix-in that provides informational APIs needed for analysis passes.
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition Analysis.h:29
A CRTP mix-in for passes that should not be skipped.