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 "CodeGenOptions.h"
23#include "llvm/ADT/DenseMap.h"
24#include "llvm/ADT/DenseSet.h"
27#include "llvm/CodeGen/Passes.h"
29#include "llvm/Support/Debug.h"
30
31using namespace llvm;
32
33#define DEBUG_TYPE "machine-block-match-infer"
34
35/// The object is used to identify and match basic blocks given their hashes.
37public:
38 /// Initialize stale matcher.
39 void init(const std::vector<MachineBasicBlock *> &Blocks,
40 const std::vector<BlendedBlockHash> &Hashes) {
41 assert(Blocks.size() == Hashes.size() &&
42 "incorrect matcher initialization");
43 for (size_t I = 0; I < Blocks.size(); I++) {
44 MachineBasicBlock *Block = Blocks[I];
45 uint16_t OpHash = Hashes[I].getOpcodeHash();
46 OpHashToBlocks[OpHash].push_back(std::make_pair(Hashes[I], Block));
47 }
48 }
49
50 /// Find the most similar block for a given hash.
52 auto BlockIt = OpHashToBlocks.find(BlendedHash.getOpcodeHash());
53 if (BlockIt == OpHashToBlocks.end()) {
54 return nullptr;
55 }
56 MachineBasicBlock *BestBlock = nullptr;
57 uint64_t BestDist = std::numeric_limits<uint64_t>::max();
58 for (auto It : BlockIt->second) {
59 MachineBasicBlock *Block = It.second;
60 BlendedBlockHash Hash = It.first;
61 uint64_t Dist = Hash.distance(BlendedHash);
62 if (BestBlock == nullptr || Dist < BestDist) {
63 BestDist = Dist;
64 BestBlock = Block;
65 }
66 }
67 return BestBlock;
68 }
69
70private:
71 using HashBlockPairType = std::pair<BlendedBlockHash, MachineBasicBlock *>;
73};
74
76 "machine-block-match-infer",
77 "Machine Block Matching and Inference Analysis", true,
78 true)
82 "Machine Block Matching and Inference Analysis", true, true)
83
85
88
95
96std::optional<BasicBlockMatchingAndInference::WeightInfo>
98 auto It = ProgramWeightInfo.find(FuncName);
99 if (It == ProgramWeightInfo.end()) {
100 return std::nullopt;
101 }
102 return It->second;
103}
104
105BasicBlockMatchingAndInference::WeightInfo
106BasicBlockMatchingAndInference::initWeightInfoByMatching(MachineFunction &MF) {
107 std::vector<MachineBasicBlock *> Blocks;
108 std::vector<BlendedBlockHash> Hashes;
111 for (auto &Block : MF) {
112 Blocks.push_back(&Block);
113 Hashes.push_back(BlendedBlockHash(MBHI->getMBBHash(Block)));
114 }
115 StaleMatcher Matcher;
116 Matcher.init(Blocks, Hashes);
117 BasicBlockMatchingAndInference::WeightInfo MatchWeight;
118 const CFGProfile *CFG = BSPR->getFunctionCFGProfile(MF.getName());
119 if (CFG == nullptr)
120 return MatchWeight;
121 for (auto &BlockCount : CFG->NodeCounts) {
122 if (CFG->BBHashes.count(BlockCount.first.BaseID)) {
123 auto Hash = CFG->BBHashes.lookup(BlockCount.first.BaseID);
124 MachineBasicBlock *Block = Matcher.matchBlock(BlendedBlockHash(Hash));
125 // When a basic block has clone copies, sum their counts.
126 if (Block != nullptr)
127 MatchWeight.BlockWeights[Block] += BlockCount.second;
128 }
129 }
130 for (auto &PredItem : CFG->EdgeCounts) {
131 auto PredID = PredItem.first.BaseID;
132 if (!CFG->BBHashes.count(PredID))
133 continue;
134 auto PredHash = CFG->BBHashes.lookup(PredID);
135 MachineBasicBlock *PredBlock =
136 Matcher.matchBlock(BlendedBlockHash(PredHash));
137 if (PredBlock == nullptr)
138 continue;
139 for (auto &SuccItem : PredItem.second) {
140 auto SuccID = SuccItem.first.BaseID;
141 auto EdgeWeight = SuccItem.second;
142 if (CFG->BBHashes.count(SuccID)) {
143 auto SuccHash = CFG->BBHashes.lookup(SuccID);
144 MachineBasicBlock *SuccBlock =
145 Matcher.matchBlock(BlendedBlockHash(SuccHash));
146 // When an edge has clone copies, sum their counts.
147 if (SuccBlock != nullptr)
148 MatchWeight.EdgeWeights[std::make_pair(PredBlock, SuccBlock)] +=
149 EdgeWeight;
150 }
151 }
152 }
153 return MatchWeight;
154}
155
156BasicBlockMatchingAndInference::WeightInfo
157BasicBlockMatchingAndInference::initWeightInfoByBBID(MachineFunction &MF,
158 const CFGProfile &CFG) {
159 // Match blocks by their full UniqueBBID (including CloneID). If a cloned
160 // block in the profile does not exist in MF (e.g., because its cloning path
161 // was rejected), fall back to the original block so its counts are
162 // attributed to the original block.
163 DenseMap<UniqueBBID, MachineBasicBlock *> BBIDToMBB;
164 for (auto &MBB : MF)
165 BBIDToMBB[*MBB.getBBID()] = &MBB;
166 auto FindMBB = [&](const UniqueBBID &BBID) {
167 if (MachineBasicBlock *MBB = BBIDToMBB.lookup(BBID))
168 return MBB;
169 return BBIDToMBB.lookup(UniqueBBID{BBID.BaseID, 0});
170 };
171
172 // A basic block is matched only if it exists in CFG.NodeCounts and all of its
173 // edges in the CFG profile are also edges in the MIR. The profile may omit
174 // edges without samples, so MIR edges missing from the profile are allowed.
175 // Both ends of a profile edge that is not in the MIR are kept as unknown.
176 DenseSet<const MachineBasicBlock *> MismatchedMBBs;
177 for (const auto &[PredID, Succs] : CFG.EdgeCounts) {
178 MachineBasicBlock *PredMBB = FindMBB(PredID);
179 for (const auto &[SuccID, EdgeCount] : Succs) {
180 MachineBasicBlock *SuccMBB = FindMBB(SuccID);
181 if (PredMBB && SuccMBB && PredMBB->isSuccessor(SuccMBB))
182 continue;
183 if (PredMBB)
184 MismatchedMBBs.insert(PredMBB);
185 if (SuccMBB)
186 MismatchedMBBs.insert(SuccMBB);
187 }
188 }
189 DenseSet<const MachineBasicBlock *> ProfiledMBBs;
190 for (const auto &[BBID, BlockCount] : CFG.NodeCounts)
191 if (MachineBasicBlock *MBB = FindMBB(BBID))
192 ProfiledMBBs.insert(MBB);
193 DenseSet<const MachineBasicBlock *> MatchedMBBs;
194 for (auto &MBB : MF) {
195 if (!ProfiledMBBs.contains(&MBB))
196 continue;
197 if (MismatchedMBBs.contains(&MBB))
198 LLVM_DEBUG(dbgs() << MF.getName() << ": bb." << MBB.getNumber()
199 << " has profile edges that are not in the CFG\n");
200 else
201 MatchedMBBs.insert(&MBB);
202 }
203
204 BasicBlockMatchingAndInference::WeightInfo MatchWeight;
205 for (const auto &[BBID, BlockCount] : CFG.NodeCounts) {
206 MachineBasicBlock *MBB = FindMBB(BBID);
207 if (MBB && MatchedMBBs.count(MBB))
208 MatchWeight.BlockWeights[MBB] += BlockCount;
209 }
210 for (const auto &[PredID, Succs] : CFG.EdgeCounts) {
211 MachineBasicBlock *PredMBB = FindMBB(PredID);
212 if (!PredMBB || !MatchedMBBs.count(PredMBB))
213 continue;
214 for (const auto &[SuccID, EdgeCount] : Succs) {
215 MachineBasicBlock *SuccMBB = FindMBB(SuccID);
216 if (!SuccMBB || !MatchedMBBs.count(SuccMBB))
217 continue;
218 MatchWeight.EdgeWeights[std::make_pair(PredMBB, SuccMBB)] += EdgeCount;
219 }
220 }
221 return MatchWeight;
222}
223
224void BasicBlockMatchingAndInference::generateWeightInfoByInference(
225 MachineFunction &MF,
226 BasicBlockMatchingAndInference::WeightInfo &MatchWeight) {
227 BlockEdgeMap Successors;
228 for (auto &Block : MF) {
229 for (auto *Succ : Block.successors())
230 Successors[&Block].push_back(Succ);
231 }
232 SampleProfileInference<MachineFunction> SPI(
233 MF, Successors, MatchWeight.BlockWeights, MatchWeight.EdgeWeights);
234 BlockWeightMap BlockWeights;
235 EdgeWeightMap EdgeWeights;
236 SPI.apply(BlockWeights, EdgeWeights);
237 ProgramWeightInfo.try_emplace(
238 MF.getName(), BasicBlockMatchingAndInference::WeightInfo{
239 std::move(BlockWeights), std::move(EdgeWeights)});
240}
241
243 if (MF.empty())
244 return false;
246 const CFGProfile *CFG = BSPR->getFunctionCFGProfile(MF.getName());
247 if (CFG == nullptr || (CFG->NodeCounts.empty() && CFG->EdgeCounts.empty()))
248 return false;
249
250 const CodeGenOptions &Opts = getCodeGenOptions(MF);
251 BasicBlockMatchingAndInference::WeightInfo MatchWeight;
252 if (Opts.propeller_match_bbid) {
253 MatchWeight = initWeightInfoByBBID(MF, *CFG);
254 } else {
255 MatchWeight = initWeightInfoByMatching(MF);
256 // If the ratio of the number of MBBs in matching to the total number of
257 // MBBs in the function is less than the threshold value, the processing
258 // should be abandoned.
259 if (static_cast<float>(MatchWeight.BlockWeights.size()) / MF.size() <
260 Opts.propeller_infer_threshold) {
261 return false;
262 }
263 }
264 generateWeightInfoByInference(MF, MatchWeight);
265 return false;
266}
267
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock & MBB
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:717
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:793
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
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...
const CodeGenOptions & getCodeGenOptions(const LLVMContext &C)
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.