LLVM 24.0.0git
BasicBlockMatchingAndInference.cpp
Go to the documentation of this file.
1//===- llvm/CodeGen/BasicBlockMatchingAndInference.cpp ----------*- 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// In Propeller's profile, we have already read the hash values of basic blocks,
10// as well as the weights of basic blocks and edges in the CFG. In this file,
11// we first match the basic blocks in the profile with those in the current
12// MachineFunction using the basic block hash, thereby obtaining the weights of
13// some basic blocks and edges. Subsequently, we infer the weights of all basic
14// blocks using an inference algorithm.
15//
16// TODO: Integrate part of the code in this file with BOLT's implementation into
17// the LLVM infrastructure, enabling both BOLT and Propeller to reuse it.
18//
19//===----------------------------------------------------------------------===//
20
22#include "llvm/ADT/DenseMap.h"
23#include "llvm/ADT/DenseSet.h"
26#include "llvm/CodeGen/Passes.h"
28#include "llvm/Support/Debug.h"
30
31using namespace llvm;
32
33#define DEBUG_TYPE "machine-block-match-infer"
34
35static cl::opt<float>
36 PropellerInferThreshold("propeller-infer-threshold",
37 cl::desc("Threshold for infer stale profile"),
38 cl::init(0.6));
39
40static cl::opt<bool>
41 PropellerMatchBBID("propeller-match-bbid",
42 cl::desc("Match basic blocks using BBIDs instead of "
43 "hashes for Propeller inference"),
44 cl::init(false), cl::Optional);
45
46/// The object is used to identify and match basic blocks given their hashes.
48public:
49 /// Initialize stale matcher.
50 void init(const std::vector<MachineBasicBlock *> &Blocks,
51 const std::vector<BlendedBlockHash> &Hashes) {
52 assert(Blocks.size() == Hashes.size() &&
53 "incorrect matcher initialization");
54 for (size_t I = 0; I < Blocks.size(); I++) {
55 MachineBasicBlock *Block = Blocks[I];
56 uint16_t OpHash = Hashes[I].getOpcodeHash();
57 OpHashToBlocks[OpHash].push_back(std::make_pair(Hashes[I], Block));
58 }
59 }
60
61 /// Find the most similar block for a given hash.
63 auto BlockIt = OpHashToBlocks.find(BlendedHash.getOpcodeHash());
64 if (BlockIt == OpHashToBlocks.end()) {
65 return nullptr;
66 }
67 MachineBasicBlock *BestBlock = nullptr;
68 uint64_t BestDist = std::numeric_limits<uint64_t>::max();
69 for (auto It : BlockIt->second) {
70 MachineBasicBlock *Block = It.second;
71 BlendedBlockHash Hash = It.first;
72 uint64_t Dist = Hash.distance(BlendedHash);
73 if (BestBlock == nullptr || Dist < BestDist) {
74 BestDist = Dist;
75 BestBlock = Block;
76 }
77 }
78 return BestBlock;
79 }
80
81private:
82 using HashBlockPairType = std::pair<BlendedBlockHash, MachineBasicBlock *>;
84};
85
87 "machine-block-match-infer",
88 "Machine Block Matching and Inference Analysis", true,
89 true)
93 "Machine Block Matching and Inference Analysis", true, true)
94
96
99
106
107std::optional<BasicBlockMatchingAndInference::WeightInfo>
109 auto It = ProgramWeightInfo.find(FuncName);
110 if (It == ProgramWeightInfo.end()) {
111 return std::nullopt;
112 }
113 return It->second;
114}
115
116BasicBlockMatchingAndInference::WeightInfo
117BasicBlockMatchingAndInference::initWeightInfoByMatching(MachineFunction &MF) {
118 std::vector<MachineBasicBlock *> Blocks;
119 std::vector<BlendedBlockHash> Hashes;
122 for (auto &Block : MF) {
123 Blocks.push_back(&Block);
124 Hashes.push_back(BlendedBlockHash(MBHI->getMBBHash(Block)));
125 }
126 StaleMatcher Matcher;
127 Matcher.init(Blocks, Hashes);
128 BasicBlockMatchingAndInference::WeightInfo MatchWeight;
129 const CFGProfile *CFG = BSPR->getFunctionCFGProfile(MF.getName());
130 if (CFG == nullptr)
131 return MatchWeight;
132 for (auto &BlockCount : CFG->NodeCounts) {
133 if (CFG->BBHashes.count(BlockCount.first.BaseID)) {
134 auto Hash = CFG->BBHashes.lookup(BlockCount.first.BaseID);
135 MachineBasicBlock *Block = Matcher.matchBlock(BlendedBlockHash(Hash));
136 // When a basic block has clone copies, sum their counts.
137 if (Block != nullptr)
138 MatchWeight.BlockWeights[Block] += BlockCount.second;
139 }
140 }
141 for (auto &PredItem : CFG->EdgeCounts) {
142 auto PredID = PredItem.first.BaseID;
143 if (!CFG->BBHashes.count(PredID))
144 continue;
145 auto PredHash = CFG->BBHashes.lookup(PredID);
146 MachineBasicBlock *PredBlock =
147 Matcher.matchBlock(BlendedBlockHash(PredHash));
148 if (PredBlock == nullptr)
149 continue;
150 for (auto &SuccItem : PredItem.second) {
151 auto SuccID = SuccItem.first.BaseID;
152 auto EdgeWeight = SuccItem.second;
153 if (CFG->BBHashes.count(SuccID)) {
154 auto SuccHash = CFG->BBHashes.lookup(SuccID);
155 MachineBasicBlock *SuccBlock =
156 Matcher.matchBlock(BlendedBlockHash(SuccHash));
157 // When an edge has clone copies, sum their counts.
158 if (SuccBlock != nullptr)
159 MatchWeight.EdgeWeights[std::make_pair(PredBlock, SuccBlock)] +=
160 EdgeWeight;
161 }
162 }
163 }
164 return MatchWeight;
165}
166
167BasicBlockMatchingAndInference::WeightInfo
168BasicBlockMatchingAndInference::initWeightInfoByBBID(MachineFunction &MF,
169 const CFGProfile &CFG) {
170 // Path cloning does not run before matching and inference, so blocks are
171 // identified by their base IDs. The counts of clones in the profile are
172 // attributed to the original block.
173 DenseMap<unsigned, MachineBasicBlock *> BaseIDToMBB;
174 for (auto &MBB : MF) {
175 unsigned BaseID = MBB.getBBID() ? MBB.getBBID()->BaseID
176 : static_cast<unsigned>(MBB.getNumber());
177 BaseIDToMBB[BaseID] = &MBB;
178 }
179 auto FindMBB = [&](const UniqueBBID &BBID) {
180 return BaseIDToMBB.lookup(BBID.BaseID);
181 };
182
183 // A basic block is matched only if it exists in CFG.NodeCounts and all of its
184 // edges in the CFG profile are also edges in the MIR. The profile may omit
185 // edges without samples, so MIR edges missing from the profile are allowed.
186 // Both ends of a profile edge that is not in the MIR are kept as unknown.
187 DenseSet<const MachineBasicBlock *> MismatchedMBBs;
188 for (const auto &[PredID, Succs] : CFG.EdgeCounts) {
189 MachineBasicBlock *PredMBB = FindMBB(PredID);
190 for (const auto &[SuccID, EdgeCount] : Succs) {
191 MachineBasicBlock *SuccMBB = FindMBB(SuccID);
192 if (PredMBB && SuccMBB && PredMBB->isSuccessor(SuccMBB))
193 continue;
194 if (PredMBB)
195 MismatchedMBBs.insert(PredMBB);
196 if (SuccMBB)
197 MismatchedMBBs.insert(SuccMBB);
198 }
199 }
200 DenseSet<const MachineBasicBlock *> ProfiledMBBs;
201 for (const auto &[BBID, BlockCount] : CFG.NodeCounts)
202 if (MachineBasicBlock *MBB = FindMBB(BBID))
203 ProfiledMBBs.insert(MBB);
204 DenseSet<const MachineBasicBlock *> MatchedMBBs;
205 for (auto &MBB : MF) {
206 if (!ProfiledMBBs.contains(&MBB))
207 continue;
208 if (MismatchedMBBs.contains(&MBB))
209 LLVM_DEBUG(dbgs() << MF.getName() << ": bb." << MBB.getNumber()
210 << " has profile edges that are not in the CFG\n");
211 else
212 MatchedMBBs.insert(&MBB);
213 }
214
215 BasicBlockMatchingAndInference::WeightInfo MatchWeight;
216 for (const auto &[BBID, BlockCount] : CFG.NodeCounts) {
217 MachineBasicBlock *MBB = FindMBB(BBID);
218 if (MBB && MatchedMBBs.count(MBB))
219 MatchWeight.BlockWeights[MBB] += BlockCount;
220 }
221 for (const auto &[PredID, Succs] : CFG.EdgeCounts) {
222 MachineBasicBlock *PredMBB = FindMBB(PredID);
223 if (!PredMBB || !MatchedMBBs.count(PredMBB))
224 continue;
225 for (const auto &[SuccID, EdgeCount] : Succs) {
226 MachineBasicBlock *SuccMBB = FindMBB(SuccID);
227 if (!SuccMBB || !MatchedMBBs.count(SuccMBB))
228 continue;
229 MatchWeight.EdgeWeights[std::make_pair(PredMBB, SuccMBB)] += EdgeCount;
230 }
231 }
232 return MatchWeight;
233}
234
235void BasicBlockMatchingAndInference::generateWeightInfoByInference(
236 MachineFunction &MF,
237 BasicBlockMatchingAndInference::WeightInfo &MatchWeight) {
238 BlockEdgeMap Successors;
239 for (auto &Block : MF) {
240 for (auto *Succ : Block.successors())
241 Successors[&Block].push_back(Succ);
242 }
243 SampleProfileInference<MachineFunction> SPI(
244 MF, Successors, MatchWeight.BlockWeights, MatchWeight.EdgeWeights);
245 BlockWeightMap BlockWeights;
246 EdgeWeightMap EdgeWeights;
247 SPI.apply(BlockWeights, EdgeWeights);
248 ProgramWeightInfo.try_emplace(
249 MF.getName(), BasicBlockMatchingAndInference::WeightInfo{
250 std::move(BlockWeights), std::move(EdgeWeights)});
251}
252
254 if (MF.empty())
255 return false;
257 const CFGProfile *CFG = BSPR->getFunctionCFGProfile(MF.getName());
258 if (CFG == nullptr || (CFG->NodeCounts.empty() && CFG->EdgeCounts.empty()))
259 return false;
260
261 BasicBlockMatchingAndInference::WeightInfo MatchWeight;
262 if (PropellerMatchBBID) {
263 MatchWeight = initWeightInfoByBBID(MF, *CFG);
264 } else {
265 MatchWeight = initWeightInfoByMatching(MF);
266 // If the ratio of the number of MBBs in matching to the total number of
267 // MBBs in the function is less than the threshold value, the processing
268 // should be abandoned.
269 if (static_cast<float>(MatchWeight.BlockWeights.size()) / MF.size() <
271 return false;
272 }
273 }
274 generateWeightInfoByInference(MF, MatchWeight);
275 return false;
276}
277
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock & MBB
static cl::opt< float > PropellerInferThreshold("propeller-infer-threshold", cl::desc("Threshold for infer stale profile"), cl::init(0.6))
static cl::opt< bool > PropellerMatchBBID("propeller-match-bbid", cl::desc("Match basic blocks using BBIDs instead of " "hashes for Propeller inference"), cl::init(false), cl::Optional)
This file defines the DenseMap class.
This file defines the DenseSet and SmallDenseSet classes.
Flatten the CFG
#define I(x, y, z)
Definition MD5.cpp:57
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
#define LLVM_DEBUG(...)
Definition Debug.h:119
The object is used to identify and match basic blocks given their hashes.
void init(const std::vector< MachineBasicBlock * > &Blocks, const std::vector< BlendedBlockHash > &Hashes)
Initialize stale matcher.
MachineBasicBlock * matchBlock(BlendedBlockHash BlendedHash) const
Find the most similar block for a given hash.
Represent the analysis usage information of a pass.
AnalysisUsage & addRequired()
void setPreservesAll()
Set by analyses that do not transform their input at all.
std::optional< WeightInfo > getWeightInfo(StringRef FuncName) const
bool runOnMachineFunction(MachineFunction &F) override
runOnMachineFunction - This method must be overloaded to perform the desired machine code transformat...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
unsigned size() const
Definition DenseMap.h:718
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
Definition DenseMap.h:794
int getNumber() const
MachineBasicBlocks are uniquely numbered at the function level, unless they're not in a MachineFuncti...
std::optional< UniqueBBID > getBBID() const
LLVM_ABI bool isSuccessor(const MachineBasicBlock *MBB) const
Return true if the specified MBB is a successor of this block.
Legacy MachineFunctionPass for MachineBlockHashInfo.
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
AnalysisType & getAnalysis() const
getAnalysis<AnalysisType>() - This function is used by subclasses to get to the analysis information ...
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:209
bool contains(const_arg_type_t< ValueT > V) const
Check if the set contains the given element.
Definition DenseSet.h:182
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
Definition DenseSet.h:187
initializer< Ty > init(const Ty &Val)
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI MachineFunctionPass * createBasicBlockMatchingAndInferencePass()
createBasicBlockMatchingAndInferencePass - This pass enables matching and inference when using propel...
An object wrapping several components of a basic block hash.
uint64_t distance(const BlendedBlockHash &BBH) const
Compute a distance between two given blended hashes.