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