LLVM 22.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
19#include "llvm/IR/Metadata.h"
21#include <cstddef>
22#include <type_traits>
23
24namespace llvm {
26 LLVM_ABI static const char *BranchWeights;
27 LLVM_ABI static const char *ValueProfile;
28 LLVM_ABI static const char *FunctionEntryCount;
30 LLVM_ABI static const char *ExpectedBranchWeights;
32};
33
34/// Profile-based loop metadata that should be accessed only by using
35/// \c llvm::getLoopEstimatedTripCount and \c llvm::setLoopEstimatedTripCount.
36LLVM_ABI extern const char *LLVMLoopEstimatedTripCount;
37
38/// Checks if an Instruction has MD_prof Metadata
39LLVM_ABI bool hasProfMD(const Instruction &I);
40
41/// Checks if an MDNode contains Branch Weight Metadata
42LLVM_ABI bool isBranchWeightMD(const MDNode *ProfileData);
43
44/// Checks if an MDNode contains value profiling Metadata
45LLVM_ABI bool isValueProfileMD(const MDNode *ProfileData);
46
47/// Checks if an instructions has Branch Weight Metadata
48///
49/// \param I The instruction to check
50/// \returns True if I has an MD_prof node containing Branch Weights. False
51/// otherwise.
53
54/// Checks if an instructions has valid Branch Weight Metadata
55///
56/// \param I The instruction to check
57/// \returns True if I has an MD_prof node containing valid Branch Weights,
58/// i.e., one weight for each successor. False otherwise.
60
61/// Get the branch weights metadata node
62///
63/// \param I The Instruction to get the weights from.
64/// \returns A pointer to I's branch weights metadata node, if it exists.
65/// Nullptr otherwise.
67
68/// Get the valid branch weights metadata node
69///
70/// \param I The Instruction to get the weights from.
71/// \returns A pointer to I's valid branch weights metadata node, if it exists.
72/// Nullptr otherwise.
74
75/// Check if Branch Weight Metadata has an "expected" field from an llvm.expect*
76/// intrinsic
78
79/// Check if Branch Weight Metadata has an "expected" field from an llvm.expect*
80/// intrinsic
81LLVM_ABI bool hasBranchWeightOrigin(const MDNode *ProfileData);
82
83/// Return the offset to the first branch weight data
84LLVM_ABI unsigned getBranchWeightOffset(const MDNode *ProfileData);
85
86LLVM_ABI unsigned getNumBranchWeights(const MDNode &ProfileData);
87
88/// Extract branch weights from MD_prof metadata
89///
90/// \param ProfileData A pointer to an MDNode.
91/// \param [out] Weights An output vector to fill with branch weights
92/// \returns True if weights were extracted, False otherwise. When false Weights
93/// will be cleared.
94LLVM_ABI bool extractBranchWeights(const MDNode *ProfileData,
96
97/// Faster version of extractBranchWeights() that skips checks and must only
98/// be called with "branch_weights" metadata nodes. Supports uint32_t.
99LLVM_ABI void extractFromBranchWeightMD32(const MDNode *ProfileData,
101
102/// Faster version of extractBranchWeights() that skips checks and must only
103/// be called with "branch_weights" metadata nodes. Supports uint64_t.
104LLVM_ABI void extractFromBranchWeightMD64(const MDNode *ProfileData,
106
107/// Extract branch weights attatched to an Instruction
108///
109/// \param I The Instruction to extract weights from.
110/// \param [out] Weights An output vector to fill with branch weights
111/// \returns True if weights were extracted, False otherwise. When false Weights
112/// will be cleared.
115
116/// Extract branch weights from a conditional branch or select Instruction.
117///
118/// \param I The instruction to extract branch weights from.
119/// \param [out] TrueVal will contain the branch weight for the True branch
120/// \param [out] FalseVal will contain the branch weight for the False branch
121/// \returns True on success with profile weights filled in. False if no
122/// metadata or invalid metadata was found.
124 uint64_t &FalseVal);
125
126/// Retrieve the total of all weights from MD_prof data.
127///
128/// \param ProfileData The profile data to extract the total weight from
129/// \param [out] TotalWeights input variable to fill with total weights
130/// \returns True on success with profile total weights filled in. False if no
131/// metadata was found.
132LLVM_ABI bool extractProfTotalWeight(const MDNode *ProfileData,
133 uint64_t &TotalWeights);
134
135/// Retrieve the total of all weights from an instruction.
136///
137/// \param I The instruction to extract the total weight from
138/// \param [out] TotalWeights input variable to fill with total weights
139/// \returns True on success with profile total weights filled in. False if no
140/// metadata was found.
142 uint64_t &TotalWeights);
143
144/// Create a new `branch_weights` metadata node and add or overwrite
145/// a `prof` metadata reference to instruction `I`.
146/// \param I the Instruction to set branch weights on.
147/// \param Weights an array of weights to set on instruction I.
148/// \param IsExpected were these weights added from an llvm.expect* intrinsic.
150 bool IsExpected, bool ElideAllZero = false);
151
152/// Push the weights right to fit in uint32_t.
154
155/// Variant of `setBranchWeights` where the `Weights` will be fit first to
156/// uint32_t by shifting right.
158 bool IsExpected,
159 bool ElideAllZero = false);
160
161/// downscale the given weights preserving the ratio. If the maximum value is
162/// not already known and not provided via \param KnownMaxCount , it will be
163/// obtained from \param Weights.
166 std::optional<uint64_t> KnownMaxCount = std::nullopt);
167
168/// Calculate what to divide by to scale counts.
169///
170/// Given the maximum count, calculate a divisor that will scale all the
171/// weights to strictly less than std::numeric_limits<uint32_t>::max().
173 return MaxCount < std::numeric_limits<uint32_t>::max()
174 ? 1
175 : MaxCount / std::numeric_limits<uint32_t>::max() + 1;
176}
177
178/// Scale an individual branch count.
179///
180/// Scale a 64-bit weight down to 32-bits using \c Scale.
181///
183 uint64_t Scaled = Count / Scale;
184 assert(Scaled <= std::numeric_limits<uint32_t>::max() && "overflow 32-bits");
185 return Scaled;
186}
187
188/// Specify that the branch weights for this terminator cannot be known at
189/// compile time. This should only be called by passes, and never as a default
190/// behavior in e.g. MDBuilder. The goal is to use this info to validate passes
191/// do not accidentally drop profile info, and this API is called in cases where
192/// the pass explicitly cannot provide that info. Defaulting it in would hide
193/// bugs where the pass forgets to transfer over or otherwise specify profile
194/// info. Use `PassName` to capture the pass name (i.e. DEBUG_TYPE) for
195/// debuggability.
197 StringRef PassName);
198
199/// Like setExplicitlyUnknownBranchWeights(...), but only sets unknown branch
200/// weights in the new instruction if the parent function of the original
201/// instruction has an entry count. This is to not confuse users by injecting
202/// profile data into non-profiled functions. If \p F is nullptr, we will fetch
203/// the function from \p I.
204LLVM_ABI void
206 const Function *F = nullptr);
207
208/// Analogous to setExplicitlyUnknownBranchWeights, but for functions and their
209/// entry counts.
211 StringRef PassName);
212
213LLVM_ABI bool isExplicitlyUnknownProfileMetadata(const MDNode &MD);
214LLVM_ABI bool hasExplicitlyUnknownBranchWeights(const Instruction &I);
215
216/// Scaling the profile data attached to 'I' using the ratio of S/T.
217LLVM_ABI void scaleProfData(Instruction &I, uint64_t S, uint64_t T);
218
219/// Get the branch weights of a branch conditioned on b1 || b2, where b1 and b2
220/// are 2 booleans that are the conditions of 2 branches for which we have the
221/// branch weights B1 and B2, respectively. In both B1 and B2, the first
222/// position (index 0) is for the 'true' branch, and the second position (index
223/// 1) is for the 'false' branch.
224template <typename T1, typename T2,
225 typename = typename std::enable_if<
226 std::is_arithmetic_v<T1> && std::is_arithmetic_v<T2> &&
227 sizeof(T1) <= sizeof(uint64_t) && sizeof(T2) <= sizeof(uint64_t)>>
230 const SmallVector<T2, 2> &B2) {
231 // For the first conditional branch, the probability the "true" case is taken
232 // is p(b1) = B1[0] / (B1[0] + B1[1]). The "false" case's probability is
233 // p(not b1) = B1[1] / (B1[0] + B1[1]).
234 // Similarly for the second conditional branch and B2.
235 //
236 // The probability of the new branch NOT being taken is:
237 // not P = p((not b1) and (not b2)) =
238 // = B1[1] / (B1[0]+B1[1]) * B2[1] / (B2[0]+B2[1]) =
239 // = B1[1] * B2[1] / (B1[0] + B1[1]) * (B2[0] + B2[1])
240 // Then the probability of it being taken is: P = 1 - (not P).
241 // The denominator will be the same as above, and the numerator of P will be:
242 // (B1[0] + B1[1]) * (B2[0] + B2[1]) - B1[1]*B2[1]
243 // Which then reduces to what's shown below (out of the 4 terms coming out of
244 // the product of sums, the subtracted one cancels out).
245 assert(B1.size() == 2);
246 assert(B2.size() == 2);
247 uint64_t FalseWeight = B1[1] * B2[1];
248 uint64_t TrueWeight = B1[0] * (B2[0] + B2[1]) + B1[1] * B2[0];
249 return {TrueWeight, FalseWeight};
250}
251} // namespace llvm
252#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:1078
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.
This is an optimization pass for GlobalISel generic memory operations.
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 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 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