1e8d8bef9SDimitry Andric //===-- MachineFunctionSplitter.cpp - Split machine functions //-----------===//
2e8d8bef9SDimitry Andric //
3e8d8bef9SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e8d8bef9SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5e8d8bef9SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6e8d8bef9SDimitry Andric //
7e8d8bef9SDimitry Andric //===----------------------------------------------------------------------===//
8e8d8bef9SDimitry Andric //
9e8d8bef9SDimitry Andric // \file
10e8d8bef9SDimitry Andric // Uses profile information to split out cold blocks.
11e8d8bef9SDimitry Andric //
12e8d8bef9SDimitry Andric // This pass splits out cold machine basic blocks from the parent function. This
13e8d8bef9SDimitry Andric // implementation leverages the basic block section framework. Blocks marked
14e8d8bef9SDimitry Andric // cold by this pass are grouped together in a separate section prefixed with
15e8d8bef9SDimitry Andric // ".text.unlikely.*". The linker can then group these together as a cold
16e8d8bef9SDimitry Andric // section. The split part of the function is a contiguous region identified by
17e8d8bef9SDimitry Andric // the symbol "foo.cold". Grouping all cold blocks across functions together
18e8d8bef9SDimitry Andric // decreases fragmentation and improves icache and itlb utilization. Note that
19e8d8bef9SDimitry Andric // the overall changes to the binary size are negligible; only a small number of
20e8d8bef9SDimitry Andric // additional jump instructions may be introduced.
21e8d8bef9SDimitry Andric //
22e8d8bef9SDimitry Andric // For the original RFC of this pass please see
23e8d8bef9SDimitry Andric // https://groups.google.com/d/msg/llvm-dev/RUegaMg-iqc/wFAVxa6fCgAJ
24e8d8bef9SDimitry Andric //===----------------------------------------------------------------------===//
25e8d8bef9SDimitry Andric 
26fe6060f1SDimitry Andric #include "llvm/ADT/SmallVector.h"
27e8d8bef9SDimitry Andric #include "llvm/Analysis/ProfileSummaryInfo.h"
28e8d8bef9SDimitry Andric #include "llvm/CodeGen/BasicBlockSectionUtils.h"
29e8d8bef9SDimitry Andric #include "llvm/CodeGen/MachineBasicBlock.h"
30e8d8bef9SDimitry Andric #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
31e8d8bef9SDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
32e8d8bef9SDimitry Andric #include "llvm/CodeGen/MachineFunctionPass.h"
33e8d8bef9SDimitry Andric #include "llvm/CodeGen/MachineModuleInfo.h"
34e8d8bef9SDimitry Andric #include "llvm/CodeGen/Passes.h"
35e8d8bef9SDimitry Andric #include "llvm/IR/Function.h"
36e8d8bef9SDimitry Andric #include "llvm/InitializePasses.h"
37e8d8bef9SDimitry Andric #include "llvm/Support/CommandLine.h"
38bdd1243dSDimitry Andric #include <optional>
39e8d8bef9SDimitry Andric 
40e8d8bef9SDimitry Andric using namespace llvm;
41e8d8bef9SDimitry Andric 
42e8d8bef9SDimitry Andric // FIXME: This cutoff value is CPU dependent and should be moved to
43e8d8bef9SDimitry Andric // TargetTransformInfo once we consider enabling this on other platforms.
44e8d8bef9SDimitry Andric // The value is expressed as a ProfileSummaryInfo integer percentile cutoff.
45e8d8bef9SDimitry Andric // Defaults to 999950, i.e. all blocks colder than 99.995 percentile are split.
46e8d8bef9SDimitry Andric // The default was empirically determined to be optimal when considering cutoff
47e8d8bef9SDimitry Andric // values between 99%-ile to 100%-ile with respect to iTLB and icache metrics on
48e8d8bef9SDimitry Andric // Intel CPUs.
49e8d8bef9SDimitry Andric static cl::opt<unsigned>
50e8d8bef9SDimitry Andric     PercentileCutoff("mfs-psi-cutoff",
51e8d8bef9SDimitry Andric                      cl::desc("Percentile profile summary cutoff used to "
52e8d8bef9SDimitry Andric                               "determine cold blocks. Unused if set to zero."),
53e8d8bef9SDimitry Andric                      cl::init(999950), cl::Hidden);
54e8d8bef9SDimitry Andric 
55e8d8bef9SDimitry Andric static cl::opt<unsigned> ColdCountThreshold(
56e8d8bef9SDimitry Andric     "mfs-count-threshold",
57e8d8bef9SDimitry Andric     cl::desc(
58e8d8bef9SDimitry Andric         "Minimum number of times a block must be executed to be retained."),
59e8d8bef9SDimitry Andric     cl::init(1), cl::Hidden);
60e8d8bef9SDimitry Andric 
61bdd1243dSDimitry Andric static cl::opt<bool> SplitAllEHCode(
62bdd1243dSDimitry Andric     "mfs-split-ehcode",
63bdd1243dSDimitry Andric     cl::desc("Splits all EH code and it's descendants by default."),
64bdd1243dSDimitry Andric     cl::init(false), cl::Hidden);
65bdd1243dSDimitry Andric 
66e8d8bef9SDimitry Andric namespace {
67e8d8bef9SDimitry Andric 
68e8d8bef9SDimitry Andric class MachineFunctionSplitter : public MachineFunctionPass {
69e8d8bef9SDimitry Andric public:
70e8d8bef9SDimitry Andric   static char ID;
71e8d8bef9SDimitry Andric   MachineFunctionSplitter() : MachineFunctionPass(ID) {
72e8d8bef9SDimitry Andric     initializeMachineFunctionSplitterPass(*PassRegistry::getPassRegistry());
73e8d8bef9SDimitry Andric   }
74e8d8bef9SDimitry Andric 
75e8d8bef9SDimitry Andric   StringRef getPassName() const override {
76e8d8bef9SDimitry Andric     return "Machine Function Splitter Transformation";
77e8d8bef9SDimitry Andric   }
78e8d8bef9SDimitry Andric 
79e8d8bef9SDimitry Andric   void getAnalysisUsage(AnalysisUsage &AU) const override;
80e8d8bef9SDimitry Andric 
81e8d8bef9SDimitry Andric   bool runOnMachineFunction(MachineFunction &F) override;
82e8d8bef9SDimitry Andric };
83e8d8bef9SDimitry Andric } // end anonymous namespace
84e8d8bef9SDimitry Andric 
85bdd1243dSDimitry Andric /// setDescendantEHBlocksCold - This splits all EH pads and blocks reachable
86bdd1243dSDimitry Andric /// only by EH pad as cold. This will help mark EH pads statically cold instead
87bdd1243dSDimitry Andric /// of relying on profile data.
88bdd1243dSDimitry Andric static void
89bdd1243dSDimitry Andric setDescendantEHBlocksCold(SmallVectorImpl<MachineBasicBlock *> &EHBlocks,
90bdd1243dSDimitry Andric                           MachineFunction &MF) {
91bdd1243dSDimitry Andric   MachineBasicBlock *StartBlock = &MF.front();
92bdd1243dSDimitry Andric   // A block can be unknown if its not reachable from anywhere
93bdd1243dSDimitry Andric   // EH if its only reachable from start blocks via some path through EH pads
94bdd1243dSDimitry Andric   // NonEH if it's reachable from Non EH blocks as well.
95bdd1243dSDimitry Andric   enum Status { Unknown = 0, EH = 1, NonEH = 2 };
96bdd1243dSDimitry Andric   DenseSet<MachineBasicBlock *> WorkList;
97bdd1243dSDimitry Andric   DenseMap<MachineBasicBlock *, Status> Statuses;
98bdd1243dSDimitry Andric 
99bdd1243dSDimitry Andric   auto getStatus = [&](MachineBasicBlock *MBB) {
100bdd1243dSDimitry Andric     if (Statuses.find(MBB) != Statuses.end())
101bdd1243dSDimitry Andric       return Statuses[MBB];
102bdd1243dSDimitry Andric     else
103bdd1243dSDimitry Andric       return Unknown;
104bdd1243dSDimitry Andric   };
105bdd1243dSDimitry Andric 
106bdd1243dSDimitry Andric   auto checkPredecessors = [&](MachineBasicBlock *MBB, Status Stat) {
107bdd1243dSDimitry Andric     for (auto *PredMBB : MBB->predecessors()) {
108bdd1243dSDimitry Andric       Status PredStatus = getStatus(PredMBB);
109bdd1243dSDimitry Andric       // If status of predecessor block has gone above current block
110bdd1243dSDimitry Andric       // we update current blocks status.
111bdd1243dSDimitry Andric       if (PredStatus > Stat)
112bdd1243dSDimitry Andric         Stat = PredStatus;
113bdd1243dSDimitry Andric     }
114bdd1243dSDimitry Andric     return Stat;
115bdd1243dSDimitry Andric   };
116bdd1243dSDimitry Andric 
117bdd1243dSDimitry Andric   auto addSuccesors = [&](MachineBasicBlock *MBB) {
118bdd1243dSDimitry Andric     for (auto *SuccMBB : MBB->successors()) {
119bdd1243dSDimitry Andric       if (!SuccMBB->isEHPad())
120bdd1243dSDimitry Andric         WorkList.insert(SuccMBB);
121bdd1243dSDimitry Andric     }
122bdd1243dSDimitry Andric   };
123bdd1243dSDimitry Andric 
124bdd1243dSDimitry Andric   // Insert the successors of start block
125bdd1243dSDimitry Andric   // and landing pads successor.
126bdd1243dSDimitry Andric   Statuses[StartBlock] = NonEH;
127bdd1243dSDimitry Andric   addSuccesors(StartBlock);
128bdd1243dSDimitry Andric   for (auto *LP : EHBlocks) {
129bdd1243dSDimitry Andric     addSuccesors(LP);
130bdd1243dSDimitry Andric     Statuses[LP] = EH;
131bdd1243dSDimitry Andric   }
132bdd1243dSDimitry Andric 
133bdd1243dSDimitry Andric   // Worklist iterative algorithm.
134bdd1243dSDimitry Andric   while (!WorkList.empty()) {
135bdd1243dSDimitry Andric     auto *MBB = *WorkList.begin();
136bdd1243dSDimitry Andric     WorkList.erase(MBB);
137bdd1243dSDimitry Andric 
138bdd1243dSDimitry Andric     Status OldStatus = getStatus(MBB);
139bdd1243dSDimitry Andric 
140bdd1243dSDimitry Andric     // Check on predecessors and check for
141bdd1243dSDimitry Andric     // Status update.
142bdd1243dSDimitry Andric     Status NewStatus = checkPredecessors(MBB, OldStatus);
143bdd1243dSDimitry Andric 
144bdd1243dSDimitry Andric     // Did the block status change?
145bdd1243dSDimitry Andric     bool changed = OldStatus != NewStatus;
146bdd1243dSDimitry Andric     if (changed) {
147bdd1243dSDimitry Andric       addSuccesors(MBB);
148bdd1243dSDimitry Andric       Statuses[MBB] = NewStatus;
149bdd1243dSDimitry Andric     }
150bdd1243dSDimitry Andric   }
151bdd1243dSDimitry Andric 
152bdd1243dSDimitry Andric   for (auto Entry : Statuses) {
153bdd1243dSDimitry Andric     if (Entry.second == EH)
154bdd1243dSDimitry Andric       Entry.first->setSectionID(MBBSectionID::ColdSectionID);
155bdd1243dSDimitry Andric   }
156bdd1243dSDimitry Andric }
157bdd1243dSDimitry Andric 
158fe6060f1SDimitry Andric static bool isColdBlock(const MachineBasicBlock &MBB,
159e8d8bef9SDimitry Andric                         const MachineBlockFrequencyInfo *MBFI,
160e8d8bef9SDimitry Andric                         ProfileSummaryInfo *PSI) {
161bdd1243dSDimitry Andric   std::optional<uint64_t> Count = MBFI->getBlockProfileCount(&MBB);
16281ad6265SDimitry Andric   if (!Count)
163e8d8bef9SDimitry Andric     return true;
164e8d8bef9SDimitry Andric 
165e8d8bef9SDimitry Andric   if (PercentileCutoff > 0) {
166e8d8bef9SDimitry Andric     return PSI->isColdCountNthPercentile(PercentileCutoff, *Count);
167e8d8bef9SDimitry Andric   }
168e8d8bef9SDimitry Andric   return (*Count < ColdCountThreshold);
169e8d8bef9SDimitry Andric }
170e8d8bef9SDimitry Andric 
171e8d8bef9SDimitry Andric bool MachineFunctionSplitter::runOnMachineFunction(MachineFunction &MF) {
172bdd1243dSDimitry Andric   // We target functions with profile data. Static information in the form
173bdd1243dSDimitry Andric   // of exception handling code may be split to cold if user passes the
174bdd1243dSDimitry Andric   // mfs-split-ehcode flag.
175bdd1243dSDimitry Andric   bool UseProfileData = MF.getFunction().hasProfileData();
176bdd1243dSDimitry Andric   if (!UseProfileData && !SplitAllEHCode)
177e8d8bef9SDimitry Andric     return false;
178e8d8bef9SDimitry Andric 
179e8d8bef9SDimitry Andric   // TODO: We don't split functions where a section attribute has been set
180e8d8bef9SDimitry Andric   // since the split part may not be placed in a contiguous region. It may also
181e8d8bef9SDimitry Andric   // be more beneficial to augment the linker to ensure contiguous layout of
182e8d8bef9SDimitry Andric   // split functions within the same section as specified by the attribute.
183fe6060f1SDimitry Andric   if (MF.getFunction().hasSection() ||
184fe6060f1SDimitry Andric       MF.getFunction().hasFnAttribute("implicit-section-name"))
185e8d8bef9SDimitry Andric     return false;
186e8d8bef9SDimitry Andric 
187e8d8bef9SDimitry Andric   // We don't want to proceed further for cold functions
188e8d8bef9SDimitry Andric   // or functions of unknown hotness. Lukewarm functions have no prefix.
189bdd1243dSDimitry Andric   std::optional<StringRef> SectionPrefix = MF.getFunction().getSectionPrefix();
190bdd1243dSDimitry Andric   if (SectionPrefix &&
191bdd1243dSDimitry Andric       (*SectionPrefix == "unlikely" || *SectionPrefix == "unknown")) {
192e8d8bef9SDimitry Andric     return false;
193e8d8bef9SDimitry Andric   }
194e8d8bef9SDimitry Andric 
195e8d8bef9SDimitry Andric   // Renumbering blocks here preserves the order of the blocks as
196e8d8bef9SDimitry Andric   // sortBasicBlocksAndUpdateBranches uses the numeric identifier to sort
197e8d8bef9SDimitry Andric   // blocks. Preserving the order of blocks is essential to retaining decisions
198e8d8bef9SDimitry Andric   // made by prior passes such as MachineBlockPlacement.
199e8d8bef9SDimitry Andric   MF.RenumberBlocks();
200e8d8bef9SDimitry Andric   MF.setBBSectionsType(BasicBlockSection::Preset);
201bdd1243dSDimitry Andric 
202bdd1243dSDimitry Andric   MachineBlockFrequencyInfo *MBFI = nullptr;
203bdd1243dSDimitry Andric   ProfileSummaryInfo *PSI = nullptr;
204bdd1243dSDimitry Andric   if (UseProfileData) {
205bdd1243dSDimitry Andric     MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
206bdd1243dSDimitry Andric     PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
207bdd1243dSDimitry Andric   }
208e8d8bef9SDimitry Andric 
209fe6060f1SDimitry Andric   SmallVector<MachineBasicBlock *, 2> LandingPads;
210e8d8bef9SDimitry Andric   for (auto &MBB : MF) {
211fe6060f1SDimitry Andric     if (MBB.isEntryBlock())
212e8d8bef9SDimitry Andric       continue;
213fe6060f1SDimitry Andric 
214fe6060f1SDimitry Andric     if (MBB.isEHPad())
215fe6060f1SDimitry Andric       LandingPads.push_back(&MBB);
216bdd1243dSDimitry Andric     else if (UseProfileData && isColdBlock(MBB, MBFI, PSI) && !SplitAllEHCode)
217e8d8bef9SDimitry Andric       MBB.setSectionID(MBBSectionID::ColdSectionID);
218e8d8bef9SDimitry Andric   }
219e8d8bef9SDimitry Andric 
220bdd1243dSDimitry Andric   // Split all EH code and it's descendant statically by default.
221bdd1243dSDimitry Andric   if (SplitAllEHCode)
222bdd1243dSDimitry Andric     setDescendantEHBlocksCold(LandingPads, MF);
223fe6060f1SDimitry Andric   // We only split out eh pads if all of them are cold.
224bdd1243dSDimitry Andric   else {
225fe6060f1SDimitry Andric     bool HasHotLandingPads = false;
226fe6060f1SDimitry Andric     for (const MachineBasicBlock *LP : LandingPads) {
227fe6060f1SDimitry Andric       if (!isColdBlock(*LP, MBFI, PSI))
228fe6060f1SDimitry Andric         HasHotLandingPads = true;
229fe6060f1SDimitry Andric     }
230fe6060f1SDimitry Andric     if (!HasHotLandingPads) {
231fe6060f1SDimitry Andric       for (MachineBasicBlock *LP : LandingPads)
232fe6060f1SDimitry Andric         LP->setSectionID(MBBSectionID::ColdSectionID);
233fe6060f1SDimitry Andric     }
234bdd1243dSDimitry Andric   }
235e8d8bef9SDimitry Andric   auto Comparator = [](const MachineBasicBlock &X, const MachineBasicBlock &Y) {
236e8d8bef9SDimitry Andric     return X.getSectionID().Type < Y.getSectionID().Type;
237e8d8bef9SDimitry Andric   };
238e8d8bef9SDimitry Andric   llvm::sortBasicBlocksAndUpdateBranches(MF, Comparator);
239fcaf7f86SDimitry Andric   llvm::avoidZeroOffsetLandingPad(MF);
240e8d8bef9SDimitry Andric   return true;
241e8d8bef9SDimitry Andric }
242e8d8bef9SDimitry Andric 
243e8d8bef9SDimitry Andric void MachineFunctionSplitter::getAnalysisUsage(AnalysisUsage &AU) const {
244e8d8bef9SDimitry Andric   AU.addRequired<MachineModuleInfoWrapperPass>();
245e8d8bef9SDimitry Andric   AU.addRequired<MachineBlockFrequencyInfo>();
246e8d8bef9SDimitry Andric   AU.addRequired<ProfileSummaryInfoWrapperPass>();
247e8d8bef9SDimitry Andric }
248e8d8bef9SDimitry Andric 
249e8d8bef9SDimitry Andric char MachineFunctionSplitter::ID = 0;
250e8d8bef9SDimitry Andric INITIALIZE_PASS(MachineFunctionSplitter, "machine-function-splitter",
251e8d8bef9SDimitry Andric                 "Split machine functions using profile information", false,
252e8d8bef9SDimitry Andric                 false)
253e8d8bef9SDimitry Andric 
254e8d8bef9SDimitry Andric MachineFunctionPass *llvm::createMachineFunctionSplitterPass() {
255e8d8bef9SDimitry Andric   return new MachineFunctionSplitter();
256e8d8bef9SDimitry Andric }
257