LLVM 22.0.0git
ProfileVerify.cpp
Go to the documentation of this file.
1//===- ProfileVerify.cpp - Verify profile info for testing ----------------===//
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
11#include "llvm/ADT/STLExtras.h"
13#include "llvm/IR/Analysis.h"
14#include "llvm/IR/Dominators.h"
15#include "llvm/IR/Function.h"
17#include "llvm/IR/LLVMContext.h"
18#include "llvm/IR/MDBuilder.h"
22
23using namespace llvm;
25 DefaultFunctionEntryCount("profcheck-default-function-entry-count",
26 cl::init(1000));
27static cl::opt<bool>
28 AnnotateSelect("profcheck-annotate-select", cl::init(true),
29 cl::desc("Also inject (if missing) and verify MD_prof for "
30 "`select` instructions"));
31static cl::opt<bool>
32 WeightsForTest("profcheck-weights-for-test", cl::init(false),
33 cl::desc("Generate weights with small values for tests."));
34
36 "profcheck-default-select-true-weight", cl::init(2U),
37 cl::desc("When annotating `select` instructions, this value will be used "
38 "for the first ('true') case."));
40 "profcheck-default-select-false-weight", cl::init(3U),
41 cl::desc("When annotating `select` instructions, this value will be used "
42 "for the second ('false') case."));
43namespace {
44class ProfileInjector {
45 Function &F;
47
48public:
49 static const Instruction *
50 getTerminatorBenefitingFromMDProf(const BasicBlock &BB) {
51 if (succ_size(&BB) < 2)
52 return nullptr;
53 auto *Term = BB.getTerminator();
54 return (isa<BranchInst>(Term) || isa<SwitchInst>(Term) ||
56 ? Term
57 : nullptr;
58 }
59
60 static Instruction *getTerminatorBenefitingFromMDProf(BasicBlock &BB) {
61 return const_cast<Instruction *>(
62 getTerminatorBenefitingFromMDProf(const_cast<const BasicBlock &>(BB)));
63 }
64
65 ProfileInjector(Function &F, FunctionAnalysisManager &FAM) : F(F), FAM(FAM) {}
66 bool inject();
67};
68} // namespace
69
70// FIXME: currently this injects only for terminators. Select isn't yet
71// supported.
72bool ProfileInjector::inject() {
73 // Get whatever branch probability info can be derived from the given IR -
74 // whether it has or not metadata. The main intention for this pass is to
75 // ensure that other passes don't drop or "forget" to update MD_prof. We do
76 // this as a mode in which lit tests would run. We want to avoid changing the
77 // behavior of those tests. A pass may use BPI (or BFI, which is computed from
78 // BPI). If no metadata is present, BPI is guesstimated by
79 // BranchProbabilityAnalysis. The injector (this pass) only persists whatever
80 // information the analysis provides, in other words, the pass being tested
81 // will get the same BPI it does if the injector wasn't running.
82 auto &BPI = FAM.getResult<BranchProbabilityAnalysis>(F);
83
84 // Inject a function count if there's none. It's reasonable for a pass to
85 // want to clear the MD_prof of a function with zero entry count. If the
86 // original profile (iFDO or AFDO) is empty for a function, it's simpler to
87 // require assigning it the 0-entry count explicitly than to mark every branch
88 // as cold (we do want some explicit information in the spirit of what this
89 // verifier wants to achieve - make dropping / corrupting MD_prof
90 // unit-testable)
91 if (!F.getEntryCount(/*AllowSynthetic=*/true))
92 F.setEntryCount(DefaultFunctionEntryCount);
93 // If there is an entry count that's 0, then don't bother injecting. We won't
94 // verify these either.
95 if (F.getEntryCount(/*AllowSynthetic=*/true)->getCount() == 0)
96 return false;
97 bool Changed = false;
98 // Cycle through the weights list. If we didn't, tests with more than (say)
99 // one conditional branch would have the same !prof metadata on all of them,
100 // and numerically that may make for a poor unit test.
101 uint32_t WeightsForTestOffset = 0;
102 for (auto &BB : F) {
103 if (AnnotateSelect) {
104 for (auto &I : BB) {
105 if (auto *SI = dyn_cast<SelectInst>(&I)) {
106 if (SI->getCondition()->getType()->isVectorTy())
107 continue;
108 if (I.getMetadata(LLVMContext::MD_prof))
109 continue;
111 /*IsExpected=*/false);
112 }
113 }
114 }
115 auto *Term = getTerminatorBenefitingFromMDProf(BB);
116 if (!Term || Term->getMetadata(LLVMContext::MD_prof))
117 continue;
118 SmallVector<BranchProbability> Probs;
119
120 SmallVector<uint32_t> Weights;
121 Weights.reserve(Term->getNumSuccessors());
122 if (WeightsForTest) {
123 static const std::array Primes{3, 5, 7, 11, 13, 17, 19, 23, 29, 31,
124 37, 41, 43, 47, 53, 59, 61, 67, 71};
125 for (uint32_t I = 0, E = Term->getNumSuccessors(); I < E; ++I)
126 Weights.emplace_back(
127 Primes[(WeightsForTestOffset + I) % Primes.size()]);
128 ++WeightsForTestOffset;
129 } else {
130 Probs.reserve(Term->getNumSuccessors());
131 for (auto I = 0U, E = Term->getNumSuccessors(); I < E; ++I)
132 Probs.emplace_back(BPI.getEdgeProbability(&BB, Term->getSuccessor(I)));
133
134 assert(llvm::find_if(Probs,
135 [](const BranchProbability &P) {
136 return P.isUnknown();
137 }) == Probs.end() &&
138 "All branch probabilities should be valid");
139 const auto *FirstZeroDenominator =
140 find_if(Probs, [](const BranchProbability &P) {
141 return P.getDenominator() == 0;
142 });
143 (void)FirstZeroDenominator;
144 assert(FirstZeroDenominator == Probs.end());
145 const auto *FirstNonZeroNumerator = find_if(
146 Probs, [](const BranchProbability &P) { return !P.isZero(); });
147 assert(FirstNonZeroNumerator != Probs.end());
148 DynamicAPInt LCM(Probs[0].getDenominator());
149 DynamicAPInt GCD(FirstNonZeroNumerator->getNumerator());
150 for (const auto &Prob : drop_begin(Probs)) {
151 if (!Prob.getNumerator())
152 continue;
153 LCM = llvm::lcm(LCM, DynamicAPInt(Prob.getDenominator()));
154 GCD = llvm::gcd(GCD, DynamicAPInt(Prob.getNumerator()));
155 }
156 for (const auto &Prob : Probs) {
157 DynamicAPInt W =
158 (Prob.getNumerator() * LCM / GCD) / Prob.getDenominator();
159 Weights.emplace_back(static_cast<uint32_t>((int64_t)W));
160 }
161 }
162 setBranchWeights(*Term, Weights, /*IsExpected=*/false);
163 Changed = true;
164 }
165 return Changed;
166}
167
170 ProfileInjector PI(F, FAM);
171 if (!PI.inject())
172 return PreservedAnalyses::all();
173
175}
176
179 const auto EntryCount = F.getEntryCount(/*AllowSynthetic=*/true);
180 if (!EntryCount) {
181 auto *MD = F.getMetadata(LLVMContext::MD_prof);
182 if (!MD || !isExplicitlyUnknownProfileMetadata(*MD)) {
183 F.getContext().emitError("Profile verification failed: function entry "
184 "count missing (set to 0 if cold)");
185 return PreservedAnalyses::all();
186 }
187 } else if (EntryCount->getCount() == 0) {
188 return PreservedAnalyses::all();
189 }
190 for (const auto &BB : F) {
191 if (AnnotateSelect) {
192 for (const auto &I : BB)
193 if (auto *SI = dyn_cast<SelectInst>(&I)) {
194 if (SI->getCondition()->getType()->isVectorTy())
195 continue;
196 if (I.getMetadata(LLVMContext::MD_prof))
197 continue;
198 F.getContext().emitError(
199 "Profile verification failed: select annotation missing");
200 }
201 }
202 if (const auto *Term =
203 ProfileInjector::getTerminatorBenefitingFromMDProf(BB))
204 if (!Term->getMetadata(LLVMContext::MD_prof))
205 F.getContext().emitError(
206 "Profile verification failed: branch annotation missing");
207 }
208 return PreservedAnalyses::all();
209}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define P(N)
FunctionAnalysisManager FAM
This file contains the declarations for profiling metadata utility functions.
static cl::opt< bool > WeightsForTest("profcheck-weights-for-test", cl::init(false), cl::desc("Generate weights with small values for tests."))
static cl::opt< uint32_t > SelectFalseWeight("profcheck-default-select-false-weight", cl::init(3U), cl::desc("When annotating `select` instructions, this value will be used " "for the second ('false') case."))
static cl::opt< int64_t > DefaultFunctionEntryCount("profcheck-default-function-entry-count", cl::init(1000))
static cl::opt< bool > AnnotateSelect("profcheck-annotate-select", cl::init(true), cl::desc("Also inject (if missing) and verify MD_prof for " "`select` instructions"))
static cl::opt< uint32_t > SelectTrueWeight("profcheck-default-select-true-weight", cl::init(2U), cl::desc("When annotating `select` instructions, this value will be used " "for the first ('true') case."))
This file contains some templates that are useful if you are working with the STL at all.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition BasicBlock.h:233
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
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &FAM)
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &FAM)
reference emplace_back(ArgTypes &&... Args)
void reserve(size_type N)
Changed
Pass manager infrastructure for declaring and invalidating analyses.
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:81
initializer< Ty > init(const Ty &Val)
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:316
LLVM_ATTRIBUTE_ALWAYS_INLINE DynamicAPInt gcd(const DynamicAPInt &A, const DynamicAPInt &B)
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
LLVM_ABI bool isExplicitlyUnknownProfileMetadata(const MDNode &MD)
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...
auto succ_size(const MachineBasicBlock *BB)
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
LLVM_ATTRIBUTE_ALWAYS_INLINE DynamicAPInt lcm(const DynamicAPInt &A, const DynamicAPInt &B)
Returns the least common multiple of A and B.
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1758
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.