LLVM 23.0.0git
ProfDataUtils.h
Go to the documentation of this file.
1//===- llvm/IR/ProfDataUtils.h - Profiling Metadata Utilities ---*- 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/// @file
10/// This file contains the declarations for profiling metadata utility
11/// functions.
12//
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_IR_PROFDATAUTILS_H
16#define LLVM_IR_PROFDATAUTILS_H
17
20#include "llvm/IR/Metadata.h"
23#include <cstddef>
24#include <type_traits>
25
26namespace llvm {
28 LLVM_ABI static const char *BranchWeights;
29 LLVM_ABI static const char *ValueProfile;
30 LLVM_ABI static const char *FunctionEntryCount;
32 LLVM_ABI static const char *ExpectedBranchWeights;
34};
35
37
38/// Profile-based loop metadata that should be accessed only by using
39/// \c llvm::getLoopEstimatedTripCount and \c llvm::setLoopEstimatedTripCount.
40LLVM_ABI extern const char *LLVMLoopEstimatedTripCount;
41
42/// Checks if an Instruction has MD_prof Metadata
43LLVM_ABI bool hasProfMD(const Instruction &I);
44
45/// Checks if an MDNode contains Branch Weight Metadata
46LLVM_ABI bool isBranchWeightMD(const MDNode *ProfileData);
47
48/// Checks if an MDNode contains value profiling Metadata
49LLVM_ABI bool isValueProfileMD(const MDNode *ProfileData);
50
51/// Checks if an instructions has Branch Weight Metadata
52///
53/// \param I The instruction to check
54/// \returns True if I has an MD_prof node containing Branch Weights. False
55/// otherwise.
57
58/// Checks if an instructions has valid Branch Weight Metadata
59///
60/// \param I The instruction to check
61/// \returns True if I has an MD_prof node containing valid Branch Weights,
62/// i.e., one weight for each successor. False otherwise.
64
65/// Get the branch weights metadata node
66///
67/// \param I The Instruction to get the weights from.
68/// \returns A pointer to I's branch weights metadata node, if it exists.
69/// Nullptr otherwise.
71
72/// Get the valid branch weights metadata node
73///
74/// \param I The Instruction to get the weights from.
75/// \returns A pointer to I's valid branch weights metadata node, if it exists.
76/// Nullptr otherwise.
78
79/// Check if Branch Weight Metadata has an "expected" field from an llvm.expect*
80/// intrinsic
82
83/// Check if Branch Weight Metadata has an "expected" field from an llvm.expect*
84/// intrinsic
85LLVM_ABI bool hasBranchWeightOrigin(const MDNode *ProfileData);
86
87/// Return the offset to the first branch weight data
88LLVM_ABI unsigned getBranchWeightOffset(const MDNode *ProfileData);
89
90LLVM_ABI unsigned getNumBranchWeights(const MDNode &ProfileData);
91
92/// Extract branch weights from MD_prof metadata
93///
94/// \param ProfileData A pointer to an MDNode.
95/// \param [out] Weights An output vector to fill with branch weights
96/// \returns True if weights were extracted, False otherwise. When false Weights
97/// will be cleared.
98LLVM_ABI bool extractBranchWeights(const MDNode *ProfileData,
100
101/// Faster version of extractBranchWeights() that skips checks and must only
102/// be called with "branch_weights" metadata nodes. Supports uint32_t.
103LLVM_ABI void extractFromBranchWeightMD32(const MDNode *ProfileData,
105
106/// Faster version of extractBranchWeights() that skips checks and must only
107/// be called with "branch_weights" metadata nodes. Supports uint64_t.
108LLVM_ABI void extractFromBranchWeightMD64(const MDNode *ProfileData,
110
111/// Extract branch weights attatched to an Instruction
112///
113/// \param I The Instruction to extract weights from.
114/// \param [out] Weights An output vector to fill with branch weights
115/// \returns True if weights were extracted, False otherwise. When false Weights
116/// will be cleared.
119
120/// Extract branch weights from a conditional branch or select Instruction.
121///
122/// \param I The instruction to extract branch weights from.
123/// \param [out] TrueVal will contain the branch weight for the True branch
124/// \param [out] FalseVal will contain the branch weight for the False branch
125/// \returns True on success with profile weights filled in. False if no
126/// metadata or invalid metadata was found.
128 uint64_t &FalseVal);
129
130/// Retrieve the total of all weights from MD_prof data.
131///
132/// \param ProfileData The profile data to extract the total weight from
133/// \param [out] TotalWeights input variable to fill with total weights
134/// \returns True on success with profile total weights filled in. False if no
135/// metadata was found.
136LLVM_ABI bool extractProfTotalWeight(const MDNode *ProfileData,
137 uint64_t &TotalWeights);
138
139/// Retrieve the total of all weights from an instruction.
140///
141/// \param I The instruction to extract the total weight from
142/// \param [out] TotalWeights input variable to fill with total weights
143/// \returns True on success with profile total weights filled in. False if no
144/// metadata was found.
146 uint64_t &TotalWeights);
147
148/// Create a new `branch_weights` metadata node and add or overwrite
149/// a `prof` metadata reference to instruction `I`.
150/// \param I the Instruction to set branch weights on.
151/// \param Weights an array of weights to set on instruction I.
152/// \param IsExpected were these weights added from an llvm.expect* intrinsic.
154 bool IsExpected, bool ElideAllZero = false);
155
156/// Push the weights right to fit in uint32_t.
158
159/// Variant of `setBranchWeights` where the `Weights` will be fit first to
160/// uint32_t by shifting right.
162 bool IsExpected,
163 bool ElideAllZero = false);
164
165/// downscale the given weights preserving the ratio. If the maximum value is
166/// not already known and not provided via \param KnownMaxCount , it will be
167/// obtained from \param Weights.
170 std::optional<uint64_t> KnownMaxCount = std::nullopt);
171
172/// Calculate what to divide by to scale counts.
173///
174/// Given the maximum count, calculate a divisor that will scale all the
175/// weights to strictly less than std::numeric_limits<uint32_t>::max().
177 return MaxCount < std::numeric_limits<uint32_t>::max()
178 ? 1
179 : MaxCount / std::numeric_limits<uint32_t>::max() + 1;
180}
181
182/// Scale an individual branch count.
183///
184/// Scale a 64-bit weight down to 32-bits using \c Scale.
185///
187 uint64_t Scaled = Count / Scale;
188 assert(Scaled <= std::numeric_limits<uint32_t>::max() && "overflow 32-bits");
189 return Scaled;
190}
191
192/// Specify that the branch weights for this terminator cannot be known at
193/// compile time. This should only be called by passes, and never as a default
194/// behavior in e.g. MDBuilder. The goal is to use this info to validate passes
195/// do not accidentally drop profile info, and this API is called in cases where
196/// the pass explicitly cannot provide that info. Defaulting it in would hide
197/// bugs where the pass forgets to transfer over or otherwise specify profile
198/// info. Use `PassName` to capture the pass name (i.e. DEBUG_TYPE) for
199/// debuggability.
201 StringRef PassName);
202
203/// Like setExplicitlyUnknownBranchWeights(...), but only sets unknown branch
204/// weights in the new instruction if the parent function of the original
205/// instruction has an entry count. This is to not confuse users by injecting
206/// profile data into non-profiled functions. If \p F is nullptr, we will fetch
207/// the function from \p I.
208LLVM_ABI void
210 const Function *F = nullptr);
211
212/// Returns a metadata node containing unknown branch weights if the function
213/// has an entry count, otherwise returns nullptr.
214LLVM_ABI MDNode *
216
217/// Analogous to setExplicitlyUnknownBranchWeights, but for functions and their
218/// entry counts.
220 StringRef PassName);
221
222LLVM_ABI bool isExplicitlyUnknownProfileMetadata(const MDNode &MD);
223LLVM_ABI bool hasExplicitlyUnknownBranchWeights(const Instruction &I);
224
225/// Scaling the profile data attached to 'I' using the ratio of S/T.
226LLVM_ABI void scaleProfData(Instruction &I, uint64_t S, uint64_t T);
227
228// Helper to apply a metadata setting function to an Instruction* if profiling
229// is enabled. If profiling is disabled (ProfcheckDisableMetadataFixes is true)
230// or V is not an Instruction, the callback will not be invoked.
232 Value *V, llvm::function_ref<void(Instruction *)> setMetadataCallback);
233
234/// Get the branch weights of a branch conditioned on b1 || b2, where b1 and b2
235/// are 2 booleans that are the conditions of 2 branches for which we have the
236/// branch weights B1 and B2, respectively. In both B1 and B2, the first
237/// position (index 0) is for the 'true' branch, and the second position (index
238/// 1) is for the 'false' branch.
239template <typename T1, typename T2,
240 typename = typename std::enable_if<
241 std::is_arithmetic_v<T1> && std::is_arithmetic_v<T2> &&
242 sizeof(T1) <= sizeof(uint64_t) && sizeof(T2) <= sizeof(uint64_t)>>
245 const SmallVector<T2, 2> &B2) {
246 // For the first conditional branch, the probability the "true" case is taken
247 // is p(b1) = B1[0] / (B1[0] + B1[1]). The "false" case's probability is
248 // p(not b1) = B1[1] / (B1[0] + B1[1]).
249 // Similarly for the second conditional branch and B2.
250 //
251 // The probability of the new branch NOT being taken is:
252 // not P = p((not b1) and (not b2)) =
253 // = B1[1] / (B1[0]+B1[1]) * B2[1] / (B2[0]+B2[1]) =
254 // = B1[1] * B2[1] / (B1[0] + B1[1]) * (B2[0] + B2[1])
255 // Then the probability of it being taken is: P = 1 - (not P).
256 // The denominator will be the same as above, and the numerator of P will be:
257 // (B1[0] + B1[1]) * (B2[0] + B2[1]) - B1[1]*B2[1]
258 // Which then reduces to what's shown below (out of the 4 terms coming out of
259 // the product of sums, the subtracted one cancels out).
260 assert(B1.size() == 2);
261 assert(B2.size() == 2);
262
263 uint64_t FalseWeight, TrueWeight;
264
266 FalseWeight = static_cast<uint64_t>(B1[1]) * B2[1];
267 TrueWeight =
268 static_cast<uint64_t>(B1[0]) * (static_cast<uint64_t>(B2[0]) + B2[1]) +
269 static_cast<uint64_t>(B1[1]) * B2[0];
270 } else {
271 FalseWeight = B1[1] * B2[1];
272 TrueWeight = B1[0] * (B2[0] + B2[1]) + B1[1] * B2[0];
273 }
274 return {TrueWeight, FalseWeight};
275}
276} // namespace llvm
277#endif
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
@ Scaled
#define LLVM_ABI
Definition Compiler.h:213
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
This file contains the declarations for metadata subclasses.
#define T
#define T1
This file defines the SmallVector class.
static const char PassName[]
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
Metadata node.
Definition Metadata.h:1080
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An efficient, type-erasing, non-owning reference to a callable.
This is an optimization pass for GlobalISel generic memory operations.
cl::opt< bool > ProfcheckDisableMetadataFixes
Definition LoopInfo.cpp:60
LLVM_ABI bool extractProfTotalWeight(const MDNode *ProfileData, uint64_t &TotalWeights)
Retrieve the total of all weights from MD_prof data.
LLVM_ABI unsigned getBranchWeightOffset(const MDNode *ProfileData)
Return the offset to the first branch weight data.
LLVM_ABI void setExplicitlyUnknownBranchWeightsIfProfiled(Instruction &I, StringRef PassName, const Function *F=nullptr)
Like setExplicitlyUnknownBranchWeights(...), but only sets unknown branch weights in the new instruct...
LLVM_ABI bool isBranchWeightMD(const MDNode *ProfileData)
Checks if an MDNode contains Branch Weight Metadata.
LLVM_ABI bool isExplicitlyUnknownProfileMetadata(const MDNode &MD)
LLVM_ABI MDNode * getBranchWeightMDNode(const Instruction &I)
Get the branch weights metadata node.
LLVM_ABI void applyProfMetadataIfEnabled(Value *V, llvm::function_ref< void(Instruction *)> setMetadataCallback)
LLVM_ABI void setExplicitlyUnknownBranchWeights(Instruction &I, StringRef PassName)
Specify that the branch weights for this terminator cannot be known at compile time.
LLVM_ABI bool hasBranchWeightOrigin(const Instruction &I)
Check if Branch Weight Metadata has an "expected" field from an llvm.expect* intrinsic.
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...
LLVM_ABI SmallVector< uint32_t > fitWeights(ArrayRef< uint64_t > Weights)
Push the weights right to fit in uint32_t.
LLVM_ABI MDNode * getValidBranchWeightMDNode(const Instruction &I)
Get the valid branch weights metadata node.
LLVM_ABI bool hasValidBranchWeightMD(const Instruction &I)
Checks if an instructions has valid Branch Weight Metadata.
FunctionAddr VTableAddr Count
Definition InstrProf.h:139
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
LLVM_ABI MDNode * getExplicitlyUnknownBranchWeightsIfProfiled(Function &F, StringRef PassName)
Returns a metadata node containing unknown branch weights if the function has an entry count,...
LLVM_ABI void setExplicitlyUnknownFunctionEntryCount(Function &F, StringRef PassName)
Analogous to setExplicitlyUnknownBranchWeights, but for functions and their entry counts.
LLVM_ABI bool isValueProfileMD(const MDNode *ProfileData)
Checks if an MDNode contains value profiling Metadata.
LLVM_ABI unsigned getNumBranchWeights(const MDNode &ProfileData)
LLVM_ABI void extractFromBranchWeightMD32(const MDNode *ProfileData, SmallVectorImpl< uint32_t > &Weights)
Faster version of extractBranchWeights() that skips checks and must only be called with "branch_weigh...
LLVM_ABI bool hasExplicitlyUnknownBranchWeights(const Instruction &I)
LLVM_ABI bool hasProfMD(const Instruction &I)
Checks if an Instruction has MD_prof Metadata.
LLVM_ABI bool extractBranchWeights(const MDNode *ProfileData, SmallVectorImpl< uint32_t > &Weights)
Extract branch weights from MD_prof metadata.
LLVM_ABI const char * LLVMLoopEstimatedTripCount
Profile-based loop metadata that should be accessed only by using llvm::getLoopEstimatedTripCount and...
uint32_t scaleBranchCount(uint64_t Count, uint64_t Scale)
Scale an individual branch count.
SmallVector< uint64_t, 2 > getDisjunctionWeights(const SmallVector< T1, 2 > &B1, const SmallVector< T2, 2 > &B2)
Get the branch weights of a branch conditioned on b1 || b2, where b1 and b2 are 2 booleans that are t...
LLVM_ABI bool hasBranchWeightMD(const Instruction &I)
Checks if an instructions has Branch Weight Metadata.
LLVM_ABI void setFittedBranchWeights(Instruction &I, ArrayRef< uint64_t > Weights, bool IsExpected, bool ElideAllZero=false)
Variant of setBranchWeights where the Weights will be fit first to uint32_t by shifting right.
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 void scaleProfData(Instruction &I, uint64_t S, uint64_t T)
Scaling the profile data attached to 'I' using the ratio of S/T.
LLVM_ABI void extractFromBranchWeightMD64(const MDNode *ProfileData, SmallVectorImpl< uint64_t > &Weights)
Faster version of extractBranchWeights() that skips checks and must only be called with "branch_weigh...
static LLVM_ABI const char * ExpectedBranchWeights
static LLVM_ABI const char * SyntheticFunctionEntryCount
static LLVM_ABI const char * UnknownBranchWeightsMarker
static LLVM_ABI const char * ValueProfile
static LLVM_ABI const char * FunctionEntryCount
static LLVM_ABI const char * BranchWeights