Skip to content

Commit f759739

Browse files
[BOLT][AArch64] Add support for SPE brstack format (llvm#129231)
Since Linux 6.14, Perf gained the ability to report SPE branch events using the `brstack` format, which matches the layout of LBR/BRBE. This patch reuses the existing LBR parsing logic to support SPE. Example SPE brstack format: ```bash perf script -i perf.data -F pid,brstack --itrace=bl ``` ``` PID FROM / TO / PREDICTED 16984 0x72e342e5f4/0x72e36192d0/M/-/-/11/RET/- 16984 0x72e7b8b3b4/0x72e7b8b3b8/PN/-/-/11/COND/- 16984 0x72e7b92b48/0x72e7b92b4c/PN/-/-/8/COND/- 16984 0x72eacc6b7c/0x760cc94b00/P/-/-/9/RET/- 16984 0x72e3f210fc/0x72e3f21068/P/-/-/4//- 16984 0x72e39b8c5c/0x72e3627b24/P/-/-/4//- 16984 0x72e7b89d20/0x72e7b92bbc/P/-/-/4/RET/- ``` SPE brstack flags can be two characters long: `PN` or `MN`: - `P` = predicted branch - `M` = mispredicted branch - `N` = optionally appears when the branch is NOT-TAKEN - flag is relevant only to conditional branches Example of usage with BOLT: 1. Capture SPE branch events: ```bash perf record -e 'arm_spe_0/branch_filter=1/u' -- binary ``` 2. Convert profile for BOLT: ```bash perf2bolt -p perf.data -o perf.fdata --spe binary ``` 3. Run BOLT Optimization: ```bash llvm-bolt binary -o binary.bolted --data perf.fdata ... ``` A unit test verifies the parsing of the 'SPE brstack format'. --------- Co-authored-by: Paschalis Mpeis <[email protected]>
1 parent dd4776d commit f759739

File tree

8 files changed

+258
-12
lines changed

8 files changed

+258
-12
lines changed

bolt/include/bolt/Profile/DataAggregator.h

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,8 @@ class DataAggregator : public DataReader {
8585
};
8686
friend raw_ostream &operator<<(raw_ostream &OS, const LBREntry &);
8787

88+
friend struct PerfSpeEventsTestHelper;
89+
8890
struct PerfBranchSample {
8991
SmallVector<LBREntry, 32> LBR;
9092
};

bolt/include/bolt/Utils/CommandLineOpts.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,7 @@ extern llvm::cl::OptionCategory BinaryAnalysisCategory;
4848
extern llvm::cl::opt<unsigned> AlignText;
4949
extern llvm::cl::opt<unsigned> AlignFunctions;
5050
extern llvm::cl::opt<bool> AggregateOnly;
51+
extern llvm::cl::opt<bool> ArmSPE;
5152
extern llvm::cl::opt<unsigned> BucketsPerLine;
5253
extern llvm::cl::opt<bool> CompactCodeModel;
5354
extern llvm::cl::opt<bool> DiffOnly;

bolt/lib/Profile/DataAggregator.cpp

Lines changed: 49 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,9 @@ static cl::opt<bool>
4949
cl::desc("aggregate basic samples (without LBR info)"),
5050
cl::cat(AggregatorCategory));
5151

52+
cl::opt<bool> ArmSPE("spe", cl::desc("Enable Arm SPE mode."),
53+
cl::cat(AggregatorCategory));
54+
5255
static cl::opt<std::string>
5356
ITraceAggregation("itrace",
5457
cl::desc("Generate LBR info with perf itrace argument"),
@@ -181,11 +184,21 @@ void DataAggregator::start() {
181184

182185
findPerfExecutable();
183186

187+
if (opts::ArmSPE) {
188+
// pid from_ip to_ip flags
189+
// where flags could be:
190+
// P/M: whether branch was Predicted or Mispredicted.
191+
// N: optionally appears when the branch was Not-Taken (ie fall-through)
192+
// 12345 0x123/0x456/PN/-/-/8/RET/-
193+
opts::ITraceAggregation = "bl";
194+
opts::ParseMemProfile = true;
195+
opts::BasicAggregation = false;
196+
}
197+
184198
if (opts::BasicAggregation) {
185-
launchPerfProcess("events without LBR",
186-
MainEventsPPI,
199+
launchPerfProcess("events without LBR", MainEventsPPI,
187200
"script -F pid,event,ip",
188-
/*Wait = */false);
201+
/*Wait = */ false);
189202
} else if (!opts::ITraceAggregation.empty()) {
190203
// Disable parsing memory profile from trace data, unless requested by user.
191204
if (!opts::ParseMemProfile.getNumOccurrences())
@@ -994,9 +1007,22 @@ ErrorOr<DataAggregator::LBREntry> DataAggregator::parseLBREntry() {
9941007
if (std::error_code EC = MispredStrRes.getError())
9951008
return EC;
9961009
StringRef MispredStr = MispredStrRes.get();
997-
if (MispredStr.size() != 1 ||
998-
(MispredStr[0] != 'P' && MispredStr[0] != 'M' && MispredStr[0] != '-')) {
999-
reportError("expected single char for mispred bit");
1010+
// SPE brstack mispredicted flags might be up to two characters long:
1011+
// 'PN' or 'MN'. Where 'N' optionally appears.
1012+
bool ValidStrSize = opts::ArmSPE
1013+
? MispredStr.size() >= 1 && MispredStr.size() <= 2
1014+
: MispredStr.size() == 1;
1015+
bool SpeTakenBitErr =
1016+
(opts::ArmSPE && MispredStr.size() == 2 && MispredStr[1] != 'N');
1017+
bool PredictionBitErr =
1018+
!ValidStrSize ||
1019+
(MispredStr[0] != 'P' && MispredStr[0] != 'M' && MispredStr[0] != '-');
1020+
if (SpeTakenBitErr)
1021+
reportError("expected 'N' as SPE prediction bit for a not-taken branch");
1022+
if (PredictionBitErr)
1023+
reportError("expected 'P', 'M' or '-' char as a prediction bit");
1024+
1025+
if (SpeTakenBitErr || PredictionBitErr) {
10001026
Diag << "Found: " << MispredStr << "\n";
10011027
return make_error_code(llvm::errc::io_error);
10021028
}
@@ -1497,7 +1523,9 @@ void DataAggregator::printBranchStacksDiagnostics(
14971523
}
14981524

14991525
std::error_code DataAggregator::parseBranchEvents() {
1500-
outs() << "PERF2BOLT: parse branch events...\n";
1526+
std::string BranchEventTypeStr =
1527+
opts::ArmSPE ? "SPE branch events in LBR-format" : "branch events";
1528+
outs() << "PERF2BOLT: parse " << BranchEventTypeStr << "...\n";
15011529
NamedRegionTimer T("parseBranch", "Parsing branch events", TimerGroupName,
15021530
TimerGroupDesc, opts::TimeAggregator);
15031531

@@ -1525,7 +1553,8 @@ std::error_code DataAggregator::parseBranchEvents() {
15251553
}
15261554

15271555
NumEntries += Sample.LBR.size();
1528-
if (BAT && Sample.LBR.size() == 32 && !NeedsSkylakeFix) {
1556+
if (this->BC->isX86() && BAT && Sample.LBR.size() == 32 &&
1557+
!NeedsSkylakeFix) {
15291558
errs() << "PERF2BOLT-WARNING: using Intel Skylake bug workaround\n";
15301559
NeedsSkylakeFix = true;
15311560
}
@@ -1548,10 +1577,18 @@ std::error_code DataAggregator::parseBranchEvents() {
15481577
if (NumSamples && NumSamplesNoLBR == NumSamples) {
15491578
// Note: we don't know if perf2bolt is being used to parse memory samples
15501579
// at this point. In this case, it is OK to parse zero LBRs.
1551-
errs() << "PERF2BOLT-WARNING: all recorded samples for this binary lack "
1552-
"LBR. Record profile with perf record -j any or run perf2bolt "
1553-
"in no-LBR mode with -nl (the performance improvement in -nl "
1554-
"mode may be limited)\n";
1580+
if (!opts::ArmSPE)
1581+
errs()
1582+
<< "PERF2BOLT-WARNING: all recorded samples for this binary lack "
1583+
"LBR. Record profile with perf record -j any or run perf2bolt "
1584+
"in no-LBR mode with -nl (the performance improvement in -nl "
1585+
"mode may be limited)\n";
1586+
else
1587+
errs()
1588+
<< "PERF2BOLT-WARNING: All recorded samples for this binary lack "
1589+
"SPE brstack entries. Make sure you are running Linux perf 6.14 "
1590+
"or later, otherwise you get zero samples. Record the profile "
1591+
"with: perf record -e 'arm_spe_0/branch_filter=1/'.";
15551592
} else {
15561593
printBranchStacksDiagnostics(NumTotalSamples - NumSamples);
15571594
}
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
## Check that Arm SPE mode is available on AArch64.
2+
3+
REQUIRES: system-linux,perf,target=aarch64{{.*}}
4+
5+
RUN: %clang %cflags %p/../../Inputs/asm_foo.s %p/../../Inputs/asm_main.c -o %t.exe
6+
7+
RUN: perf record -e cycles -q -o %t.perf.data -- %t.exe 2> /dev/null
8+
9+
RUN: (perf2bolt -p %t.perf.data -o %t.perf.boltdata --spe %t.exe 2> /dev/null; exit 0) | FileCheck %s --check-prefix=CHECK-SPE-LBR
10+
11+
CHECK-SPE-LBR: PERF2BOLT: parse SPE branch events in LBR-format
12+
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
## Check that Arm SPE mode is unavailable on X86.
2+
3+
REQUIRES: system-linux,x86_64-linux
4+
5+
RUN: %clang %cflags %p/../../Inputs/asm_foo.s %p/../../Inputs/asm_main.c -o %t.exe
6+
RUN: touch %t.empty.perf.data
7+
RUN: not perf2bolt -p %t.empty.perf.data -o %t.perf.boltdata --spe --pa %t.exe 2>&1 | FileCheck %s
8+
9+
CHECK: perf2bolt: -spe is available only on AArch64.

bolt/tools/driver/llvm-bolt.cpp

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -237,6 +237,13 @@ int main(int argc, char **argv) {
237237
if (Error E = RIOrErr.takeError())
238238
report_error(opts::InputFilename, std::move(E));
239239
RewriteInstance &RI = *RIOrErr.get();
240+
241+
if (opts::AggregateOnly && !RI.getBinaryContext().isAArch64() &&
242+
opts::ArmSPE) {
243+
errs() << ToolName << ": -spe is available only on AArch64.\n";
244+
exit(1);
245+
}
246+
240247
if (!opts::PerfData.empty()) {
241248
if (!opts::AggregateOnly) {
242249
errs() << ToolName

bolt/unittests/Profile/CMakeLists.txt

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,25 @@
1+
set(LLVM_LINK_COMPONENTS
2+
DebugInfoDWARF
3+
Object
4+
${LLVM_TARGETS_TO_BUILD}
5+
)
6+
17
add_bolt_unittest(ProfileTests
28
DataAggregator.cpp
9+
PerfSpeEvents.cpp
310

411
DISABLE_LLVM_LINK_LLVM_DYLIB
512
)
613

714
target_link_libraries(ProfileTests
815
PRIVATE
16+
LLVMBOLTCore
917
LLVMBOLTProfile
18+
LLVMTargetParser
19+
LLVMTestingSupport
1020
)
1121

22+
foreach (tgt ${BOLT_TARGETS_TO_BUILD})
23+
string(TOUPPER "${tgt}" upper)
24+
target_compile_definitions(ProfileTests PRIVATE "${upper}_AVAILABLE")
25+
endforeach()
Lines changed: 164 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,164 @@
1+
//===- bolt/unittests/Profile/PerfSpeEvents.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+
#ifdef AARCH64_AVAILABLE
10+
11+
#include "bolt/Core/BinaryContext.h"
12+
#include "bolt/Profile/DataAggregator.h"
13+
#include "llvm/BinaryFormat/ELF.h"
14+
#include "llvm/DebugInfo/DWARF/DWARFContext.h"
15+
#include "llvm/Support/CommandLine.h"
16+
#include "llvm/Support/TargetSelect.h"
17+
#include "gtest/gtest.h"
18+
19+
using namespace llvm;
20+
using namespace llvm::bolt;
21+
using namespace llvm::object;
22+
using namespace llvm::ELF;
23+
24+
namespace opts {
25+
extern cl::opt<std::string> ReadPerfEvents;
26+
extern cl::opt<bool> ArmSPE;
27+
} // namespace opts
28+
29+
namespace llvm {
30+
namespace bolt {
31+
32+
/// Perform checks on perf SPE branch events.
33+
struct PerfSpeEventsTestHelper : public testing::Test {
34+
void SetUp() override {
35+
initalizeLLVM();
36+
prepareElf();
37+
initializeBOLT();
38+
}
39+
40+
protected:
41+
using Trace = DataAggregator::Trace;
42+
using TakenBranchInfo = DataAggregator::TakenBranchInfo;
43+
44+
void initalizeLLVM() {
45+
llvm::InitializeAllTargetInfos();
46+
llvm::InitializeAllTargetMCs();
47+
llvm::InitializeAllAsmParsers();
48+
llvm::InitializeAllDisassemblers();
49+
llvm::InitializeAllTargets();
50+
llvm::InitializeAllAsmPrinters();
51+
}
52+
53+
void prepareElf() {
54+
memcpy(ElfBuf, "\177ELF", 4);
55+
ELF64LE::Ehdr *EHdr = reinterpret_cast<typename ELF64LE::Ehdr *>(ElfBuf);
56+
EHdr->e_ident[llvm::ELF::EI_CLASS] = llvm::ELF::ELFCLASS64;
57+
EHdr->e_ident[llvm::ELF::EI_DATA] = llvm::ELF::ELFDATA2LSB;
58+
EHdr->e_machine = llvm::ELF::EM_AARCH64;
59+
MemoryBufferRef Source(StringRef(ElfBuf, sizeof(ElfBuf)), "ELF");
60+
ObjFile = cantFail(ObjectFile::createObjectFile(Source));
61+
}
62+
63+
void initializeBOLT() {
64+
Relocation::Arch = ObjFile->makeTriple().getArch();
65+
BC = cantFail(BinaryContext::createBinaryContext(
66+
ObjFile->makeTriple(), std::make_shared<orc::SymbolStringPool>(),
67+
ObjFile->getFileName(), nullptr, /*IsPIC*/ false,
68+
DWARFContext::create(*ObjFile.get()), {llvm::outs(), llvm::errs()}));
69+
ASSERT_FALSE(!BC);
70+
}
71+
72+
char ElfBuf[sizeof(typename ELF64LE::Ehdr)] = {};
73+
std::unique_ptr<ObjectFile> ObjFile;
74+
std::unique_ptr<BinaryContext> BC;
75+
76+
/// Helper function to export lists to show the mismatch.
77+
void reportBrStackEventMismatch(
78+
const std::vector<std::pair<Trace, TakenBranchInfo>> &Traces,
79+
const std::vector<std::pair<Trace, TakenBranchInfo>> &ExpectedSamples) {
80+
llvm::errs() << "Traces items: \n";
81+
for (const auto &[Trace, BI] : Traces)
82+
llvm::errs() << "{" << Trace.Branch << ", " << Trace.From << ","
83+
<< Trace.To << ", " << BI.TakenCount << ", "
84+
<< BI.MispredCount << "}" << "\n";
85+
86+
llvm::errs() << "Expected items: \n";
87+
for (const auto &[Trace, BI] : ExpectedSamples)
88+
llvm::errs() << "{" << Trace.Branch << ", " << Trace.From << ", "
89+
<< Trace.To << ", " << BI.TakenCount << ", "
90+
<< BI.MispredCount << "}" << "\n";
91+
}
92+
93+
/// Parse and check SPE brstack as LBR.
94+
void parseAndCheckBrstackEvents(
95+
uint64_t PID,
96+
const std::vector<std::pair<Trace, TakenBranchInfo>> &ExpectedSamples) {
97+
DataAggregator DA("<pseudo input>");
98+
DA.ParsingBuf = opts::ReadPerfEvents;
99+
DA.BC = BC.get();
100+
DataAggregator::MMapInfo MMap;
101+
DA.BinaryMMapInfo.insert(std::make_pair(PID, MMap));
102+
103+
DA.parseBranchEvents();
104+
105+
EXPECT_EQ(DA.Traces.size(), ExpectedSamples.size());
106+
if (DA.Traces.size() != ExpectedSamples.size())
107+
reportBrStackEventMismatch(DA.Traces, ExpectedSamples);
108+
109+
const auto TracesBegin = DA.Traces.begin();
110+
const auto TracesEnd = DA.Traces.end();
111+
for (const auto &BI : ExpectedSamples) {
112+
auto it = find_if(TracesBegin, TracesEnd,
113+
[&BI](const auto &Tr) { return Tr.first == BI.first; });
114+
115+
EXPECT_NE(it, TracesEnd);
116+
EXPECT_EQ(it->second.MispredCount, BI.second.MispredCount);
117+
EXPECT_EQ(it->second.TakenCount, BI.second.TakenCount);
118+
}
119+
}
120+
};
121+
122+
} // namespace bolt
123+
} // namespace llvm
124+
125+
TEST_F(PerfSpeEventsTestHelper, SpeBranchesWithBrstack) {
126+
// Check perf input with SPE branch events as brstack format.
127+
// Example collection command:
128+
// ```
129+
// perf record -e 'arm_spe_0/branch_filter=1/u' -- BINARY
130+
// ```
131+
// How Bolt extracts the branch events:
132+
// ```
133+
// perf script -F pid,brstack --itrace=bl
134+
// ```
135+
136+
opts::ArmSPE = true;
137+
opts::ReadPerfEvents = " 1234 0xa001/0xa002/PN/-/-/10/COND/-\n"
138+
" 1234 0xb001/0xb002/P/-/-/4/RET/-\n"
139+
" 1234 0xc456/0xc789/P/-/-/13/-/-\n"
140+
" 1234 0xd123/0xd456/M/-/-/7/RET/-\n"
141+
" 1234 0xe001/0xe002/P/-/-/14/RET/-\n"
142+
" 1234 0xd123/0xd456/M/-/-/7/RET/-\n"
143+
" 1234 0xf001/0xf002/MN/-/-/8/COND/-\n"
144+
" 1234 0xc456/0xc789/M/-/-/13/-/-\n";
145+
146+
// ExpectedSamples contains the aggregated information about
147+
// a branch {{Branch From, To}, {TakenCount, MispredCount}}.
148+
// Consider this example trace: {{0xd123, 0xd456, Trace::BR_ONLY},
149+
// {2,2}}. This entry has a TakenCount = 2, as we have two samples for
150+
// (0xd123, 0xd456) in our input. It also has MispredsCount = 2,
151+
// as 'M' misprediction flag appears in both cases. BR_ONLY means
152+
// the trace only contains branch data.
153+
std::vector<std::pair<Trace, TakenBranchInfo>> ExpectedSamples = {
154+
{{0xa001, 0xa002, Trace::BR_ONLY}, {1, 0}},
155+
{{0xb001, 0xb002, Trace::BR_ONLY}, {1, 0}},
156+
{{0xc456, 0xc789, Trace::BR_ONLY}, {2, 1}},
157+
{{0xd123, 0xd456, Trace::BR_ONLY}, {2, 2}},
158+
{{0xe001, 0xe002, Trace::BR_ONLY}, {1, 0}},
159+
{{0xf001, 0xf002, Trace::BR_ONLY}, {1, 1}}};
160+
161+
parseAndCheckBrstackEvents(1234, ExpectedSamples);
162+
}
163+
164+
#endif

0 commit comments

Comments
 (0)