LLVM 22.0.0git
BasicBlockSectionsProfileReader.cpp
Go to the documentation of this file.
1//===-- BasicBlockSectionsProfileReader.cpp -------------------------------===//
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// Implementation of the basic block sections profile reader pass. It parses
10// and stores the basic block sections profile file (which is specified via the
11// `-basic-block-sections` flag).
12//
13//===----------------------------------------------------------------------===//
14
16#include "llvm/ADT/DenseSet.h"
17#include "llvm/ADT/SmallSet.h"
20#include "llvm/ADT/StringMap.h"
21#include "llvm/ADT/StringRef.h"
23#include "llvm/Pass.h"
24#include "llvm/Support/Error.h"
28#include "llvm/Support/Path.h"
30#include <llvm/ADT/STLExtras.h>
31
32using namespace llvm;
33
36 "bbsections-profile-reader",
37 "Reads and parses a basic block sections profile.", false,
38 false)
39
41BasicBlockSectionsProfileReader::parseUniqueBBID(StringRef S) const {
43 S.split(Parts, '.');
44 if (Parts.size() > 2)
45 return createProfileParseError(Twine("unable to parse basic block id: '") +
46 S + "'");
47 unsigned long long BaseBBID;
48 if (getAsUnsignedInteger(Parts[0], 10, BaseBBID))
49 return createProfileParseError(
50 Twine("unable to parse BB id: '" + Parts[0]) +
51 "': unsigned integer expected");
52 unsigned long long CloneID = 0;
53 if (Parts.size() > 1 && getAsUnsignedInteger(Parts[1], 10, CloneID))
54 return createProfileParseError(Twine("unable to parse clone id: '") +
55 Parts[1] + "': unsigned integer expected");
56 return UniqueBBID{static_cast<unsigned>(BaseBBID),
57 static_cast<unsigned>(CloneID)};
58}
59
61 return !getClusterInfoForFunction(FuncName).empty();
62}
63
66 StringRef FuncName) const {
67 auto R = ProgramPathAndClusterInfo.find(getAliasName(FuncName));
68 return R != ProgramPathAndClusterInfo.end() ? R->second.ClusterInfo
70}
71
74 StringRef FuncName) const {
75 auto R = ProgramPathAndClusterInfo.find(getAliasName(FuncName));
76 return R != ProgramPathAndClusterInfo.end()
77 ? R->second.ClonePaths
79}
80
82 StringRef FuncName, const UniqueBBID &SrcBBID,
83 const UniqueBBID &SinkBBID) const {
84 auto It = ProgramPathAndClusterInfo.find(getAliasName(FuncName));
85 if (It == ProgramPathAndClusterInfo.end())
86 return 0;
87 auto NodeIt = It->second.EdgeCounts.find(SrcBBID);
88 if (NodeIt == It->second.EdgeCounts.end())
89 return 0;
90 auto EdgeIt = NodeIt->second.find(SinkBBID);
91 if (EdgeIt == NodeIt->second.end())
92 return 0;
93 return EdgeIt->second;
94}
95
96std::pair<bool, FunctionPathAndClusterInfo>
98 StringRef FuncName) const {
99 auto R = ProgramPathAndClusterInfo.find(getAliasName(FuncName));
100 return R != ProgramPathAndClusterInfo.end()
101 ? std::pair(true, R->second)
102 : std::pair(false, FunctionPathAndClusterInfo());
103}
104
105// Reads the version 1 basic block sections profile. Profile for each function
106// is encoded as follows:
107// m <module_name>
108// f <function_name_1> <function_name_2> ...
109// c <bb_id_1> <bb_id_2> <bb_id_3>
110// c <bb_id_4> <bb_id_5>
111// ...
112// Module name specifier (starting with 'm') is optional and allows
113// distinguishing profile for internal-linkage functions with the same name. If
114// not specified, it will apply to any function with the same name. Function
115// name specifier (starting with 'f') can specify multiple function name
116// aliases. Basic block clusters are specified by 'c' and specify the cluster of
117// basic blocks, and the internal order in which they must be placed in the same
118// section.
119// This profile can also specify cloning paths which instruct the compiler to
120// clone basic blocks along a path. The cloned blocks are then specified in the
121// cluster information.
122// The following profile lists two cloning paths (starting with 'p') for
123// function bar and places the total 9 blocks within two clusters. The first two
124// blocks of a cloning path specify the edge along which the path is cloned. For
125// instance, path 1 (1 -> 3 -> 4) instructs that 3 and 4 must be cloned along
126// the edge 1->3. Within the given clusters, each cloned block is identified by
127// "<original block id>.<clone id>". For instance, 3.1 represents the first
128// clone of block 3. Original blocks are specified just with their block ids. A
129// block cloned multiple times appears with distinct clone ids. The CFG for bar
130// is shown below before and after cloning with its final clusters labeled.
131//
132// f main
133// f bar
134// p 1 3 4 # cloning path 1
135// p 4 2 # cloning path 2
136// c 1 3.1 4.1 6 # basic block cluster 1
137// c 0 2 3 4 2.1 5 # basic block cluster 2
138// ****************************************************************************
139// function bar before and after cloning with basic block clusters shown.
140// ****************************************************************************
141// .... ..............
142// 0 -------+ : 0 :---->: 1 ---> 3.1 :
143// | | : | : :........ | :
144// v v : v : : v :
145// +--> 2 --> 5 1 ~~~~~~> +---: 2 : : 4.1: clsuter 1
146// | | | | : | : : | :
147// | v | | : v ....... : v :
148// | 3 <------+ | : 3 <--+ : : 6 :
149// | | | : | | : :....:
150// | v | : v | :
151// +--- 4 ---> 6 | : 4 | :
152// | : | | :
153// | : v | :
154// | :2.1---+ : cluster 2
155// | : | ......:
156// | : v :
157// +-->: 5 :
158// ....
159// ****************************************************************************
160Error BasicBlockSectionsProfileReader::ReadV1Profile() {
161 auto FI = ProgramPathAndClusterInfo.end();
162
163 // Current cluster ID corresponding to this function.
164 unsigned CurrentCluster = 0;
165 // Current position in the current cluster.
166 unsigned CurrentPosition = 0;
167
168 // Temporary set to ensure every basic block ID appears once in the clusters
169 // of a function.
170 DenseSet<UniqueBBID> FuncBBIDs;
171
172 // Debug-info-based module filename for the current function. Empty string
173 // means no filename.
174 StringRef DIFilename;
175
176 for (; !LineIt.is_at_eof(); ++LineIt) {
177 StringRef S(*LineIt);
178 char Specifier = S[0];
179 S = S.drop_front().trim();
181 S.split(Values, ' ');
182 switch (Specifier) {
183 case '@':
184 continue;
185 case 'm': // Module name speicifer.
186 if (Values.size() != 1) {
187 return createProfileParseError(Twine("invalid module name value: '") +
188 S + "'");
189 }
190 DIFilename = sys::path::remove_leading_dotslash(Values[0]);
191 continue;
192 case 'f': { // Function names specifier.
193 bool FunctionFound = any_of(Values, [&](StringRef Alias) {
194 auto It = FunctionNameToDIFilename.find(Alias);
195 // No match if this function name is not found in this module.
196 if (It == FunctionNameToDIFilename.end())
197 return false;
198 // Return a match if debug-info-filename is not specified. Otherwise,
199 // check for equality.
200 return DIFilename.empty() || It->second == DIFilename;
201 });
202 if (!FunctionFound) {
203 // Skip the following profile by setting the profile iterator (FI) to
204 // the past-the-end element.
205 FI = ProgramPathAndClusterInfo.end();
206 DIFilename = "";
207 continue;
208 }
209 for (size_t i = 1; i < Values.size(); ++i)
210 FuncAliasMap.try_emplace(Values[i], Values.front());
211
212 // Prepare for parsing clusters of this function name.
213 // Start a new cluster map for this function name.
214 auto R = ProgramPathAndClusterInfo.try_emplace(Values.front());
215 // Report error when multiple profiles have been specified for the same
216 // function.
217 if (!R.second)
218 return createProfileParseError("duplicate profile for function '" +
219 Values.front() + "'");
220 FI = R.first;
221 CurrentCluster = 0;
222 FuncBBIDs.clear();
223 // We won't need DIFilename anymore. Clean it up to avoid its application
224 // on the next function.
225 DIFilename = "";
226 continue;
227 }
228 case 'c': // Basic block cluster specifier.
229 // Skip the profile when we the profile iterator (FI) refers to the
230 // past-the-end element.
231 if (FI == ProgramPathAndClusterInfo.end())
232 continue;
233 // Reset current cluster position.
234 CurrentPosition = 0;
235 for (auto BasicBlockIDStr : Values) {
236 auto BasicBlockID = parseUniqueBBID(BasicBlockIDStr);
237 if (!BasicBlockID)
238 return BasicBlockID.takeError();
239 if (!FuncBBIDs.insert(*BasicBlockID).second)
240 return createProfileParseError(
241 Twine("duplicate basic block id found '") + BasicBlockIDStr +
242 "'");
243
244 FI->second.ClusterInfo.emplace_back(BBClusterInfo{
245 *std::move(BasicBlockID), CurrentCluster, CurrentPosition++});
246 }
247 CurrentCluster++;
248 continue;
249 case 'p': { // Basic block cloning path specifier.
250 // Skip the profile when we the profile iterator (FI) refers to the
251 // past-the-end element.
252 if (FI == ProgramPathAndClusterInfo.end())
253 continue;
254 SmallSet<unsigned, 5> BBsInPath;
255 FI->second.ClonePaths.push_back({});
256 for (size_t I = 0; I < Values.size(); ++I) {
257 auto BaseBBIDStr = Values[I];
258 unsigned long long BaseBBID = 0;
259 if (getAsUnsignedInteger(BaseBBIDStr, 10, BaseBBID))
260 return createProfileParseError(Twine("unsigned integer expected: '") +
261 BaseBBIDStr + "'");
262 if (I != 0 && !BBsInPath.insert(BaseBBID).second)
263 return createProfileParseError(
264 Twine("duplicate cloned block in path: '") + BaseBBIDStr + "'");
265 FI->second.ClonePaths.back().push_back(BaseBBID);
266 }
267 continue;
268 }
269 case 'g': { // CFG profile specifier.
270 // Skip the profile when we the profile iterator (FI) refers to the
271 // past-the-end element.
272 if (FI == ProgramPathAndClusterInfo.end())
273 continue;
274 // For each node, its CFG profile is encoded as
275 // <src>:<count>,<sink_1>:<count_1>,<sink_2>:<count_2>,...
276 for (auto BasicBlockEdgeProfile : Values) {
277 if (BasicBlockEdgeProfile.empty())
278 continue;
279 SmallVector<StringRef, 4> NodeEdgeCounts;
280 BasicBlockEdgeProfile.split(NodeEdgeCounts, ',');
281 UniqueBBID SrcBBID;
282 for (size_t i = 0; i < NodeEdgeCounts.size(); ++i) {
283 auto [BBIDStr, CountStr] = NodeEdgeCounts[i].split(':');
284 auto BBID = parseUniqueBBID(BBIDStr);
285 if (!BBID)
286 return BBID.takeError();
287 unsigned long long Count = 0;
288 if (getAsUnsignedInteger(CountStr, 10, Count))
289 return createProfileParseError(
290 Twine("unsigned integer expected: '") + CountStr + "'");
291 if (i == 0) {
292 // The first element represents the source and its total count.
293 FI->second.NodeCounts[SrcBBID = *BBID] = Count;
294 continue;
295 }
296 FI->second.EdgeCounts[SrcBBID][*BBID] = Count;
297 }
298 }
299 continue;
300 }
301 case 'h': { // Basic block hash secifier.
302 // Skip the profile when the profile iterator (FI) refers to the
303 // past-the-end element.
304 if (FI == ProgramPathAndClusterInfo.end())
305 continue;
306 for (auto BBIDHashStr : Values) {
307 auto [BBIDStr, HashStr] = BBIDHashStr.split(':');
308 unsigned long long BBID = 0, Hash = 0;
309 if (getAsUnsignedInteger(BBIDStr, 10, BBID))
310 return createProfileParseError(Twine("unsigned integer expected: '") +
311 BBIDStr + "'");
312 if (getAsUnsignedInteger(HashStr, 16, Hash))
313 return createProfileParseError(
314 Twine("unsigned integer expected in hex format: '") + HashStr +
315 "'");
316 FI->second.BBHashes[BBID] = Hash;
317 }
318 continue;
319 }
320 default:
321 return createProfileParseError(Twine("invalid specifier: '") +
322 Twine(Specifier) + "'");
323 }
324 llvm_unreachable("should not break from this switch statement");
325 }
326 return Error::success();
327}
328
329Error BasicBlockSectionsProfileReader::ReadV0Profile() {
330 auto FI = ProgramPathAndClusterInfo.end();
331 // Current cluster ID corresponding to this function.
332 unsigned CurrentCluster = 0;
333 // Current position in the current cluster.
334 unsigned CurrentPosition = 0;
335
336 // Temporary set to ensure every basic block ID appears once in the clusters
337 // of a function.
338 SmallSet<unsigned, 4> FuncBBIDs;
339
340 for (; !LineIt.is_at_eof(); ++LineIt) {
341 StringRef S(*LineIt);
342 if (S[0] == '@')
343 continue;
344 // Check for the leading "!"
345 if (!S.consume_front("!") || S.empty())
346 break;
347 // Check for second "!" which indicates a cluster of basic blocks.
348 if (S.consume_front("!")) {
349 // Skip the profile when we the profile iterator (FI) refers to the
350 // past-the-end element.
351 if (FI == ProgramPathAndClusterInfo.end())
352 continue;
354 S.split(BBIDs, ' ');
355 // Reset current cluster position.
356 CurrentPosition = 0;
357 for (auto BBIDStr : BBIDs) {
358 unsigned long long BBID;
359 if (getAsUnsignedInteger(BBIDStr, 10, BBID))
360 return createProfileParseError(Twine("unsigned integer expected: '") +
361 BBIDStr + "'");
362 if (!FuncBBIDs.insert(BBID).second)
363 return createProfileParseError(
364 Twine("duplicate basic block id found '") + BBIDStr + "'");
365
366 FI->second.ClusterInfo.emplace_back(
367 BBClusterInfo({{static_cast<unsigned>(BBID), 0},
368 CurrentCluster,
369 CurrentPosition++}));
370 }
371 CurrentCluster++;
372 } else {
373 // This is a function name specifier. It may include a debug info filename
374 // specifier starting with `M=`.
375 auto [AliasesStr, DIFilenameStr] = S.split(' ');
376 SmallString<128> DIFilename;
377 if (DIFilenameStr.starts_with("M=")) {
378 DIFilename =
379 sys::path::remove_leading_dotslash(DIFilenameStr.substr(2));
380 if (DIFilename.empty())
381 return createProfileParseError("empty module name specifier");
382 } else if (!DIFilenameStr.empty()) {
383 return createProfileParseError("unknown string found: '" +
384 DIFilenameStr + "'");
385 }
386 // Function aliases are separated using '/'. We use the first function
387 // name for the cluster info mapping and delegate all other aliases to
388 // this one.
390 AliasesStr.split(Aliases, '/');
391 bool FunctionFound = any_of(Aliases, [&](StringRef Alias) {
392 auto It = FunctionNameToDIFilename.find(Alias);
393 // No match if this function name is not found in this module.
394 if (It == FunctionNameToDIFilename.end())
395 return false;
396 // Return a match if debug-info-filename is not specified. Otherwise,
397 // check for equality.
398 return DIFilename.empty() || It->second == DIFilename;
399 });
400 if (!FunctionFound) {
401 // Skip the following profile by setting the profile iterator (FI) to
402 // the past-the-end element.
403 FI = ProgramPathAndClusterInfo.end();
404 continue;
405 }
406 for (size_t i = 1; i < Aliases.size(); ++i)
407 FuncAliasMap.try_emplace(Aliases[i], Aliases.front());
408
409 // Prepare for parsing clusters of this function name.
410 // Start a new cluster map for this function name.
411 auto R = ProgramPathAndClusterInfo.try_emplace(Aliases.front());
412 // Report error when multiple profiles have been specified for the same
413 // function.
414 if (!R.second)
415 return createProfileParseError("duplicate profile for function '" +
416 Aliases.front() + "'");
417 FI = R.first;
418 CurrentCluster = 0;
419 FuncBBIDs.clear();
420 }
421 }
422 return Error::success();
423}
424
425// Basic Block Sections can be enabled for a subset of machine basic blocks.
426// This is done by passing a file containing names of functions for which basic
427// block sections are desired. Additionally, machine basic block ids of the
428// functions can also be specified for a finer granularity. Moreover, a cluster
429// of basic blocks could be assigned to the same section.
430// Optionally, a debug-info filename can be specified for each function to allow
431// distinguishing internal-linkage functions of the same name.
432// A file with basic block sections for all of function main and three blocks
433// for function foo (of which 1 and 2 are placed in a cluster) looks like this:
434// (Profile for function foo is only loaded when its debug-info filename
435// matches 'path/to/foo_file.cc').
436// ----------------------------
437// list.txt:
438// !main
439// !foo M=path/to/foo_file.cc
440// !!1 2
441// !!4
442Error BasicBlockSectionsProfileReader::ReadProfile() {
443 assert(MBuf);
444
445 unsigned long long Version = 0;
446 StringRef FirstLine(*LineIt);
447 if (FirstLine.consume_front("v")) {
448 if (getAsUnsignedInteger(FirstLine, 10, Version)) {
449 return createProfileParseError(Twine("version number expected: '") +
450 FirstLine + "'");
451 }
452 if (Version > 1) {
453 return createProfileParseError(Twine("invalid profile version: ") +
454 Twine(Version));
455 }
456 ++LineIt;
457 }
458
459 switch (Version) {
460 case 0:
461 // TODO: Deprecate V0 once V1 is fully integrated downstream.
462 return ReadV0Profile();
463 case 1:
464 return ReadV1Profile();
465 default:
466 llvm_unreachable("Invalid profile version.");
467 }
468}
469
471 if (!BBSPR.MBuf)
472 return false;
473 // Get the function name to debug info filename mapping.
474 BBSPR.FunctionNameToDIFilename.clear();
475 for (const Function &F : M) {
476 SmallString<128> DIFilename;
477 if (F.isDeclaration())
478 continue;
479 DISubprogram *Subprogram = F.getSubprogram();
480 if (Subprogram) {
481 llvm::DICompileUnit *CU = Subprogram->getUnit();
482 if (CU)
483 DIFilename = sys::path::remove_leading_dotslash(CU->getFilename());
484 }
485 [[maybe_unused]] bool inserted =
486 BBSPR.FunctionNameToDIFilename.try_emplace(F.getName(), DIFilename)
487 .second;
488 assert(inserted);
489 }
490 if (auto Err = BBSPR.ReadProfile())
491 report_fatal_error(std::move(Err));
492 return false;
493}
494
496
502
504 StringRef FuncName) const {
505 return BBSPR.isFunctionHot(FuncName);
506}
507
510 StringRef FuncName) const {
511 return BBSPR.getClusterInfoForFunction(FuncName);
512}
513
516 StringRef FuncName) const {
517 return BBSPR.getClonePathsForFunction(FuncName);
518}
519
521 StringRef FuncName, const UniqueBBID &SrcBBID,
522 const UniqueBBID &SinkBBID) const {
523 return BBSPR.getEdgeCount(FuncName, SrcBBID, SinkBBID);
524}
525
526std::pair<bool, FunctionPathAndClusterInfo>
528 StringRef FuncName) const {
529 return BBSPR.getFunctionPathAndClusterInfo(FuncName);
530}
531
536
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file defines the StringMap class.
Function Alias Analysis false
This file defines the DenseSet and SmallDenseSet classes.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
This file contains some templates that are useful if you are working with the STL at all.
This file defines the SmallSet class.
This file defines the SmallString class.
This file defines the SmallVector class.
Result run(Function &F, FunctionAnalysisManager &AM)
bool doInitialization(Module &M) override
doInitialization - Virtual method overridden by subclasses to do any necessary initialization before ...
SmallVector< SmallVector< unsigned > > getClonePathsForFunction(StringRef FuncName) const
SmallVector< BBClusterInfo > getClusterInfoForFunction(StringRef FuncName) const
std::pair< bool, FunctionPathAndClusterInfo > getFunctionPathAndClusterInfo(StringRef FuncName) const
uint64_t getEdgeCount(StringRef FuncName, const UniqueBBID &SrcBBID, const UniqueBBID &DestBBID) const
std::pair< bool, FunctionPathAndClusterInfo > getFunctionPathAndClusterInfo(StringRef FuncName) const
bool isFunctionHot(StringRef FuncName) const
SmallVector< SmallVector< unsigned > > getClonePathsForFunction(StringRef FuncName) const
uint64_t getEdgeCount(StringRef FuncName, const UniqueBBID &SrcBBID, const UniqueBBID &SinkBBID) const
SmallVector< BBClusterInfo > getClusterInfoForFunction(StringRef FuncName) const
Subprogram description. Uses SubclassData1.
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
static ErrorSuccess success()
Create a success value.
Definition Error.h:336
Tagged union holding either a T or a Error.
Definition Error.h:485
ImmutablePass class - This class is used to provide information that does not need to be run.
Definition Pass.h:285
This interface provides simple read-only access to a block of memory, and provides simple methods for...
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
Definition SmallSet.h:183
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition SmallString.h:26
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
std::pair< StringRef, StringRef > split(char Separator) const
Split into two substrings around the first occurrence of a separator character.
Definition StringRef.h:702
constexpr bool empty() const
empty - Check if the string is empty.
Definition StringRef.h:143
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:202
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
LLVM_ABI StringRef remove_leading_dotslash(StringRef path LLVM_LIFETIME_BOUND, Style style=Style::native)
Remove redundant leading "./" pieces and consecutive separators.
This is an optimization pass for GlobalISel generic memory operations.
ImmutablePass * createBasicBlockSectionsProfileReaderWrapperPass(const MemoryBuffer *Buf)
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1744
FunctionAddr VTableAddr uintptr_t uintptr_t Version
Definition InstrProf.h:302
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:167
FunctionAddr VTableAddr Count
Definition InstrProf.h:139
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
LLVM_ABI bool getAsUnsignedInteger(StringRef Str, unsigned Radix, unsigned long long &Result)
Helper functions for StringRef::getAsInteger.
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition Analysis.h:29