1//===- StaticDataSplitter.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// The pass uses branch profile data to assign hotness based section qualifiers
10// for the following types of static data:
11// - Jump tables
12// - Module-internal global variables
13// - Constant pools
14//
15// For the original RFC of this pass please see
16// https://discourse.llvm.org/t/rfc-profile-guided-static-data-partitioning/83744
17
18#include "llvm/ADT/Statistic.h"
19#include "llvm/Analysis/ProfileSummaryInfo.h"
20#include "llvm/Analysis/StaticDataProfileInfo.h"
21#include "llvm/CodeGen/MBFIWrapper.h"
22#include "llvm/CodeGen/MachineBasicBlock.h"
23#include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
24#include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
25#include "llvm/CodeGen/MachineConstantPool.h"
26#include "llvm/CodeGen/MachineFunction.h"
27#include "llvm/CodeGen/MachineFunctionPass.h"
28#include "llvm/CodeGen/MachineJumpTableInfo.h"
29#include "llvm/CodeGen/Passes.h"
30#include "llvm/IR/GlobalVariable.h"
31#include "llvm/InitializePasses.h"
32#include "llvm/Pass.h"
33#include "llvm/Target/TargetLoweringObjectFile.h"
34
35using namespace llvm;
36
37#define DEBUG_TYPE "static-data-splitter"
38
39STATISTIC(NumHotJumpTables, "Number of hot jump tables seen.");
40STATISTIC(NumColdJumpTables, "Number of cold jump tables seen.");
41STATISTIC(NumUnknownJumpTables,
42 "Number of jump tables with unknown hotness. They are from functions "
43 "without profile information.");
44
45class StaticDataSplitter : public MachineFunctionPass {
46 const MachineBranchProbabilityInfo *MBPI = nullptr;
47 const MachineBlockFrequencyInfo *MBFI = nullptr;
48 const ProfileSummaryInfo *PSI = nullptr;
49 StaticDataProfileInfo *SDPI = nullptr;
50
51 // If the global value is a local linkage global variable, return it.
52 // Otherwise, return nullptr.
53 const GlobalVariable *getLocalLinkageGlobalVariable(const GlobalValue *GV);
54
55 // Returns true if the global variable is in one of {.rodata, .bss, .data,
56 // .data.rel.ro} sections.
57 bool inStaticDataSection(const GlobalVariable &GV, const TargetMachine &TM);
58
59 // Returns the constant if the operand refers to a global variable or constant
60 // that gets lowered to static data sections. Otherwise, return nullptr.
61 const Constant *getConstant(const MachineOperand &Op, const TargetMachine &TM,
62 const MachineConstantPool *MCP);
63
64 // Use profiles to partition static data.
65 bool partitionStaticDataWithProfiles(MachineFunction &MF);
66
67 // Update LLVM statistics for a machine function with profiles.
68 void updateStatsWithProfiles(const MachineFunction &MF);
69
70 // Update LLVM statistics for a machine function without profiles.
71 void updateStatsWithoutProfiles(const MachineFunction &MF);
72
73 void annotateStaticDataWithoutProfiles(const MachineFunction &MF);
74
75public:
76 static char ID;
77
78 StaticDataSplitter() : MachineFunctionPass(ID) {}
79
80 StringRef getPassName() const override { return "Static Data Splitter"; }
81
82 void getAnalysisUsage(AnalysisUsage &AU) const override {
83 MachineFunctionPass::getAnalysisUsage(AU);
84 AU.addRequired<MachineBranchProbabilityInfoWrapperPass>();
85 AU.addRequired<MachineBlockFrequencyInfoWrapperPass>();
86 AU.addRequired<ProfileSummaryInfoWrapperPass>();
87 AU.addRequired<StaticDataProfileInfoWrapperPass>();
88 // This pass does not modify any required analysis results except
89 // StaticDataProfileInfoWrapperPass, but StaticDataProfileInfoWrapperPass
90 // is made an immutable pass that it won't be re-scheduled by pass manager
91 // anyway. So mark setPreservesAll() here for faster compile time.
92 AU.setPreservesAll();
93 }
94
95 bool runOnMachineFunction(MachineFunction &MF) override;
96};
97
98bool StaticDataSplitter::runOnMachineFunction(MachineFunction &MF) {
99 MBPI = &getAnalysis<MachineBranchProbabilityInfoWrapperPass>().getMBPI();
100 MBFI = &getAnalysis<MachineBlockFrequencyInfoWrapperPass>().getMBFI();
101 PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
102
103 SDPI = &getAnalysis<StaticDataProfileInfoWrapperPass>()
104 .getStaticDataProfileInfo();
105
106 const bool ProfileAvailable = PSI && PSI->hasProfileSummary() && MBFI &&
107 MF.getFunction().hasProfileData();
108
109 if (!ProfileAvailable) {
110 annotateStaticDataWithoutProfiles(MF);
111 updateStatsWithoutProfiles(MF);
112 return false;
113 }
114
115 bool Changed = partitionStaticDataWithProfiles(MF);
116
117 updateStatsWithProfiles(MF);
118 return Changed;
119}
120
121const Constant *
122StaticDataSplitter::getConstant(const MachineOperand &Op,
123 const TargetMachine &TM,
124 const MachineConstantPool *MCP) {
125 if (!Op.isGlobal() && !Op.isCPI())
126 return nullptr;
127
128 if (Op.isGlobal()) {
129 // Find global variables with local linkage.
130 const GlobalVariable *GV = getLocalLinkageGlobalVariable(GV: Op.getGlobal());
131 // Skip those not eligible for annotation or not in static data sections.
132 if (!GV || !llvm::memprof::IsAnnotationOK(GV: *GV) ||
133 !inStaticDataSection(GV: *GV, TM))
134 return nullptr;
135 return GV;
136 }
137 assert(Op.isCPI() && "Op must be constant pool index in this branch");
138 int CPI = Op.getIndex();
139 if (CPI == -1)
140 return nullptr;
141
142 assert(MCP != nullptr && "Constant pool info is not available.");
143 const MachineConstantPoolEntry &CPE = MCP->getConstants()[CPI];
144
145 if (CPE.isMachineConstantPoolEntry())
146 return nullptr;
147
148 return CPE.Val.ConstVal;
149}
150
151bool StaticDataSplitter::partitionStaticDataWithProfiles(MachineFunction &MF) {
152 // If any of the static data (jump tables, global variables, constant pools)
153 // are captured by the analysis, set `Changed` to true. Note this pass won't
154 // invalidate any analysis pass (see `getAnalysisUsage` above), so the main
155 // purpose of tracking and conveying the change (to pass manager) is
156 // informative as opposed to invalidating any analysis results. As an example
157 // of where this information is useful, `PMDataManager::dumpPassInfo` will
158 // only dump pass info if a local change happens, otherwise a pass appears as
159 // "skipped".
160 bool Changed = false;
161
162 MachineJumpTableInfo *MJTI = MF.getJumpTableInfo();
163
164 // Jump table could be used by either terminating instructions or
165 // non-terminating ones, so we walk all instructions and use
166 // `MachineOperand::isJTI()` to identify jump table operands.
167 // Similarly, `MachineOperand::isCPI()` is used to identify constant pool
168 // usages in the same loop.
169 for (const auto &MBB : MF) {
170 std::optional<uint64_t> Count = MBFI->getBlockProfileCount(MBB: &MBB);
171 for (const MachineInstr &I : MBB) {
172 for (const MachineOperand &Op : I.operands()) {
173 if (!Op.isJTI() && !Op.isGlobal() && !Op.isCPI())
174 continue;
175
176 if (Op.isJTI()) {
177 assert(MJTI != nullptr && "Jump table info is not available.");
178 const int JTI = Op.getIndex();
179 // This is not a source block of jump table.
180 if (JTI == -1)
181 continue;
182
183 auto Hotness = MachineFunctionDataHotness::Hot;
184
185 // Hotness is based on source basic block hotness.
186 // TODO: PSI APIs are about instruction hotness. Introduce API for
187 // data access hotness.
188 if (Count && PSI->isColdCount(C: *Count))
189 Hotness = MachineFunctionDataHotness::Cold;
190
191 Changed |= MJTI->updateJumpTableEntryHotness(JTI, Hotness);
192 } else if (const Constant *C =
193 getConstant(Op, TM: MF.getTarget(), MCP: MF.getConstantPool())) {
194 SDPI->addConstantProfileCount(C, Count);
195 Changed = true;
196 }
197 }
198 }
199 }
200 return Changed;
201}
202
203const GlobalVariable *
204StaticDataSplitter::getLocalLinkageGlobalVariable(const GlobalValue *GV) {
205 // LLVM IR Verifier requires that a declaration must have valid declaration
206 // linkage, and local linkages are not among the valid ones. So there is no
207 // need to check GV is not a declaration here.
208 return (GV && GV->hasLocalLinkage()) ? dyn_cast<GlobalVariable>(Val: GV) : nullptr;
209}
210
211bool StaticDataSplitter::inStaticDataSection(const GlobalVariable &GV,
212 const TargetMachine &TM) {
213
214 SectionKind Kind = TargetLoweringObjectFile::getKindForGlobal(GO: &GV, TM);
215 return Kind.isData() || Kind.isReadOnly() || Kind.isReadOnlyWithRel() ||
216 Kind.isBSS();
217}
218
219void StaticDataSplitter::updateStatsWithProfiles(const MachineFunction &MF) {
220 if (!AreStatisticsEnabled())
221 return;
222
223 if (const MachineJumpTableInfo *MJTI = MF.getJumpTableInfo()) {
224 for (const auto &JumpTable : MJTI->getJumpTables()) {
225 if (JumpTable.Hotness == MachineFunctionDataHotness::Hot) {
226 ++NumHotJumpTables;
227 } else {
228 assert(JumpTable.Hotness == MachineFunctionDataHotness::Cold &&
229 "A jump table is either hot or cold when profile information is "
230 "available.");
231 ++NumColdJumpTables;
232 }
233 }
234 }
235}
236
237void StaticDataSplitter::annotateStaticDataWithoutProfiles(
238 const MachineFunction &MF) {
239 for (const auto &MBB : MF)
240 for (const MachineInstr &I : MBB)
241 for (const MachineOperand &Op : I.operands())
242 if (const Constant *C =
243 getConstant(Op, TM: MF.getTarget(), MCP: MF.getConstantPool()))
244 SDPI->addConstantProfileCount(C, Count: std::nullopt);
245}
246
247void StaticDataSplitter::updateStatsWithoutProfiles(const MachineFunction &MF) {
248 if (!AreStatisticsEnabled())
249 return;
250
251 if (const MachineJumpTableInfo *MJTI = MF.getJumpTableInfo()) {
252 NumUnknownJumpTables += MJTI->getJumpTables().size();
253 }
254}
255
256char StaticDataSplitter::ID = 0;
257
258INITIALIZE_PASS_BEGIN(StaticDataSplitter, DEBUG_TYPE, "Split static data",
259 false, false)
260INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfoWrapperPass)
261INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfoWrapperPass)
262INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
263INITIALIZE_PASS_DEPENDENCY(StaticDataProfileInfoWrapperPass)
264INITIALIZE_PASS_END(StaticDataSplitter, DEBUG_TYPE, "Split static data", false,
265 false)
266
267MachineFunctionPass *llvm::createStaticDataSplitterPass() {
268 return new StaticDataSplitter();
269}
270