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"
27*fe013be4SDimitry Andric #include "llvm/Analysis/BlockFrequencyInfo.h"
28*fe013be4SDimitry Andric #include "llvm/Analysis/BranchProbabilityInfo.h"
29*fe013be4SDimitry Andric #include "llvm/Analysis/EHUtils.h"
30e8d8bef9SDimitry Andric #include "llvm/Analysis/ProfileSummaryInfo.h"
31e8d8bef9SDimitry Andric #include "llvm/CodeGen/BasicBlockSectionUtils.h"
32e8d8bef9SDimitry Andric #include "llvm/CodeGen/MachineBasicBlock.h"
33e8d8bef9SDimitry Andric #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
34e8d8bef9SDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
35e8d8bef9SDimitry Andric #include "llvm/CodeGen/MachineFunctionPass.h"
36e8d8bef9SDimitry Andric #include "llvm/CodeGen/MachineModuleInfo.h"
37e8d8bef9SDimitry Andric #include "llvm/CodeGen/Passes.h"
38e8d8bef9SDimitry Andric #include "llvm/IR/Function.h"
39e8d8bef9SDimitry Andric #include "llvm/InitializePasses.h"
40e8d8bef9SDimitry Andric #include "llvm/Support/CommandLine.h"
41bdd1243dSDimitry Andric #include <optional>
42e8d8bef9SDimitry Andric 
43e8d8bef9SDimitry Andric using namespace llvm;
44e8d8bef9SDimitry Andric 
45e8d8bef9SDimitry Andric // FIXME: This cutoff value is CPU dependent and should be moved to
46e8d8bef9SDimitry Andric // TargetTransformInfo once we consider enabling this on other platforms.
47e8d8bef9SDimitry Andric // The value is expressed as a ProfileSummaryInfo integer percentile cutoff.
48e8d8bef9SDimitry Andric // Defaults to 999950, i.e. all blocks colder than 99.995 percentile are split.
49e8d8bef9SDimitry Andric // The default was empirically determined to be optimal when considering cutoff
50e8d8bef9SDimitry Andric // values between 99%-ile to 100%-ile with respect to iTLB and icache metrics on
51e8d8bef9SDimitry Andric // Intel CPUs.
52e8d8bef9SDimitry Andric static cl::opt<unsigned>
53e8d8bef9SDimitry Andric     PercentileCutoff("mfs-psi-cutoff",
54e8d8bef9SDimitry Andric                      cl::desc("Percentile profile summary cutoff used to "
55e8d8bef9SDimitry Andric                               "determine cold blocks. Unused if set to zero."),
56e8d8bef9SDimitry Andric                      cl::init(999950), cl::Hidden);
57e8d8bef9SDimitry Andric 
58e8d8bef9SDimitry Andric static cl::opt<unsigned> ColdCountThreshold(
59e8d8bef9SDimitry Andric     "mfs-count-threshold",
60e8d8bef9SDimitry Andric     cl::desc(
61e8d8bef9SDimitry Andric         "Minimum number of times a block must be executed to be retained."),
62e8d8bef9SDimitry Andric     cl::init(1), cl::Hidden);
63e8d8bef9SDimitry Andric 
64bdd1243dSDimitry Andric static cl::opt<bool> SplitAllEHCode(
65bdd1243dSDimitry Andric     "mfs-split-ehcode",
66bdd1243dSDimitry Andric     cl::desc("Splits all EH code and it's descendants by default."),
67bdd1243dSDimitry Andric     cl::init(false), cl::Hidden);
68bdd1243dSDimitry Andric 
69e8d8bef9SDimitry Andric namespace {
70e8d8bef9SDimitry Andric 
71e8d8bef9SDimitry Andric class MachineFunctionSplitter : public MachineFunctionPass {
72e8d8bef9SDimitry Andric public:
73e8d8bef9SDimitry Andric   static char ID;
74e8d8bef9SDimitry Andric   MachineFunctionSplitter() : MachineFunctionPass(ID) {
75e8d8bef9SDimitry Andric     initializeMachineFunctionSplitterPass(*PassRegistry::getPassRegistry());
76e8d8bef9SDimitry Andric   }
77e8d8bef9SDimitry Andric 
78e8d8bef9SDimitry Andric   StringRef getPassName() const override {
79e8d8bef9SDimitry Andric     return "Machine Function Splitter Transformation";
80e8d8bef9SDimitry Andric   }
81e8d8bef9SDimitry Andric 
82e8d8bef9SDimitry Andric   void getAnalysisUsage(AnalysisUsage &AU) const override;
83e8d8bef9SDimitry Andric 
84e8d8bef9SDimitry Andric   bool runOnMachineFunction(MachineFunction &F) override;
85e8d8bef9SDimitry Andric };
86e8d8bef9SDimitry Andric } // end anonymous namespace
87e8d8bef9SDimitry Andric 
88bdd1243dSDimitry Andric /// setDescendantEHBlocksCold - This splits all EH pads and blocks reachable
89*fe013be4SDimitry Andric /// only by EH pad as cold. This will help mark EH pads statically cold
90*fe013be4SDimitry Andric /// instead of relying on profile data.
91*fe013be4SDimitry Andric static void setDescendantEHBlocksCold(MachineFunction &MF) {
92*fe013be4SDimitry Andric   DenseSet<MachineBasicBlock *> EHBlocks;
93*fe013be4SDimitry Andric   computeEHOnlyBlocks(MF, EHBlocks);
94*fe013be4SDimitry Andric   for (auto Block : EHBlocks) {
95*fe013be4SDimitry Andric     Block->setSectionID(MBBSectionID::ColdSectionID);
96*fe013be4SDimitry Andric   }
97*fe013be4SDimitry Andric }
98bdd1243dSDimitry Andric 
99*fe013be4SDimitry Andric static void finishAdjustingBasicBlocksAndLandingPads(MachineFunction &MF) {
100*fe013be4SDimitry Andric   auto Comparator = [](const MachineBasicBlock &X, const MachineBasicBlock &Y) {
101*fe013be4SDimitry Andric     return X.getSectionID().Type < Y.getSectionID().Type;
102bdd1243dSDimitry Andric   };
103*fe013be4SDimitry Andric   llvm::sortBasicBlocksAndUpdateBranches(MF, Comparator);
104*fe013be4SDimitry Andric   llvm::avoidZeroOffsetLandingPad(MF);
105bdd1243dSDimitry Andric }
106bdd1243dSDimitry Andric 
107fe6060f1SDimitry Andric static bool isColdBlock(const MachineBasicBlock &MBB,
108e8d8bef9SDimitry Andric                         const MachineBlockFrequencyInfo *MBFI,
109e8d8bef9SDimitry Andric                         ProfileSummaryInfo *PSI) {
110bdd1243dSDimitry Andric   std::optional<uint64_t> Count = MBFI->getBlockProfileCount(&MBB);
111*fe013be4SDimitry Andric   // For instrumentation profiles and sample profiles, we use different ways
112*fe013be4SDimitry Andric   // to judge whether a block is cold and should be split.
113*fe013be4SDimitry Andric   if (PSI->hasInstrumentationProfile() || PSI->hasCSInstrumentationProfile()) {
114*fe013be4SDimitry Andric     // If using instrument profile, which is deemed "accurate", no count means
115*fe013be4SDimitry Andric     // cold.
11681ad6265SDimitry Andric     if (!Count)
117e8d8bef9SDimitry Andric       return true;
118*fe013be4SDimitry Andric     if (PercentileCutoff > 0)
119e8d8bef9SDimitry Andric       return PSI->isColdCountNthPercentile(PercentileCutoff, *Count);
120*fe013be4SDimitry Andric     // Fallthrough to end of function.
121*fe013be4SDimitry Andric   } else if (PSI->hasSampleProfile()) {
122*fe013be4SDimitry Andric     // For sample profile, no count means "do not judege coldness".
123*fe013be4SDimitry Andric     if (!Count)
124*fe013be4SDimitry Andric       return false;
125e8d8bef9SDimitry Andric   }
126*fe013be4SDimitry Andric 
127e8d8bef9SDimitry Andric   return (*Count < ColdCountThreshold);
128e8d8bef9SDimitry Andric }
129e8d8bef9SDimitry Andric 
130e8d8bef9SDimitry Andric bool MachineFunctionSplitter::runOnMachineFunction(MachineFunction &MF) {
131bdd1243dSDimitry Andric   // We target functions with profile data. Static information in the form
132bdd1243dSDimitry Andric   // of exception handling code may be split to cold if user passes the
133bdd1243dSDimitry Andric   // mfs-split-ehcode flag.
134bdd1243dSDimitry Andric   bool UseProfileData = MF.getFunction().hasProfileData();
135bdd1243dSDimitry Andric   if (!UseProfileData && !SplitAllEHCode)
136e8d8bef9SDimitry Andric     return false;
137e8d8bef9SDimitry Andric 
138e8d8bef9SDimitry Andric   // TODO: We don't split functions where a section attribute has been set
139e8d8bef9SDimitry Andric   // since the split part may not be placed in a contiguous region. It may also
140e8d8bef9SDimitry Andric   // be more beneficial to augment the linker to ensure contiguous layout of
141e8d8bef9SDimitry Andric   // split functions within the same section as specified by the attribute.
142fe6060f1SDimitry Andric   if (MF.getFunction().hasSection() ||
143fe6060f1SDimitry Andric       MF.getFunction().hasFnAttribute("implicit-section-name"))
144e8d8bef9SDimitry Andric     return false;
145e8d8bef9SDimitry Andric 
146e8d8bef9SDimitry Andric   // We don't want to proceed further for cold functions
147e8d8bef9SDimitry Andric   // or functions of unknown hotness. Lukewarm functions have no prefix.
148bdd1243dSDimitry Andric   std::optional<StringRef> SectionPrefix = MF.getFunction().getSectionPrefix();
149bdd1243dSDimitry Andric   if (SectionPrefix &&
150bdd1243dSDimitry Andric       (*SectionPrefix == "unlikely" || *SectionPrefix == "unknown")) {
151e8d8bef9SDimitry Andric     return false;
152e8d8bef9SDimitry Andric   }
153e8d8bef9SDimitry Andric 
154e8d8bef9SDimitry Andric   // Renumbering blocks here preserves the order of the blocks as
155e8d8bef9SDimitry Andric   // sortBasicBlocksAndUpdateBranches uses the numeric identifier to sort
156e8d8bef9SDimitry Andric   // blocks. Preserving the order of blocks is essential to retaining decisions
157e8d8bef9SDimitry Andric   // made by prior passes such as MachineBlockPlacement.
158e8d8bef9SDimitry Andric   MF.RenumberBlocks();
159e8d8bef9SDimitry Andric   MF.setBBSectionsType(BasicBlockSection::Preset);
160bdd1243dSDimitry Andric 
161bdd1243dSDimitry Andric   MachineBlockFrequencyInfo *MBFI = nullptr;
162bdd1243dSDimitry Andric   ProfileSummaryInfo *PSI = nullptr;
163bdd1243dSDimitry Andric   if (UseProfileData) {
164bdd1243dSDimitry Andric     MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
165bdd1243dSDimitry Andric     PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
166*fe013be4SDimitry Andric     // If we don't have a good profile (sample profile is not deemed
167*fe013be4SDimitry Andric     // as a "good profile") and the function is not hot, then early
168*fe013be4SDimitry Andric     // return. (Because we can only trust hot functions when profile
169*fe013be4SDimitry Andric     // quality is not good.)
170*fe013be4SDimitry Andric     if (PSI->hasSampleProfile() && !PSI->isFunctionHotInCallGraph(&MF, *MBFI)) {
171*fe013be4SDimitry Andric       // Split all EH code and it's descendant statically by default.
172*fe013be4SDimitry Andric       if (SplitAllEHCode)
173*fe013be4SDimitry Andric         setDescendantEHBlocksCold(MF);
174*fe013be4SDimitry Andric       finishAdjustingBasicBlocksAndLandingPads(MF);
175*fe013be4SDimitry Andric       return true;
176*fe013be4SDimitry Andric     }
177bdd1243dSDimitry Andric   }
178e8d8bef9SDimitry Andric 
179fe6060f1SDimitry Andric   SmallVector<MachineBasicBlock *, 2> LandingPads;
180e8d8bef9SDimitry Andric   for (auto &MBB : MF) {
181fe6060f1SDimitry Andric     if (MBB.isEntryBlock())
182e8d8bef9SDimitry Andric       continue;
183fe6060f1SDimitry Andric 
184fe6060f1SDimitry Andric     if (MBB.isEHPad())
185fe6060f1SDimitry Andric       LandingPads.push_back(&MBB);
186bdd1243dSDimitry Andric     else if (UseProfileData && isColdBlock(MBB, MBFI, PSI) && !SplitAllEHCode)
187e8d8bef9SDimitry Andric       MBB.setSectionID(MBBSectionID::ColdSectionID);
188e8d8bef9SDimitry Andric   }
189e8d8bef9SDimitry Andric 
190bdd1243dSDimitry Andric   // Split all EH code and it's descendant statically by default.
191bdd1243dSDimitry Andric   if (SplitAllEHCode)
192*fe013be4SDimitry Andric     setDescendantEHBlocksCold(MF);
193fe6060f1SDimitry Andric   // We only split out eh pads if all of them are cold.
194bdd1243dSDimitry Andric   else {
195*fe013be4SDimitry Andric     // Here we have UseProfileData == true.
196fe6060f1SDimitry Andric     bool HasHotLandingPads = false;
197fe6060f1SDimitry Andric     for (const MachineBasicBlock *LP : LandingPads) {
198fe6060f1SDimitry Andric       if (!isColdBlock(*LP, MBFI, PSI))
199fe6060f1SDimitry Andric         HasHotLandingPads = true;
200fe6060f1SDimitry Andric     }
201fe6060f1SDimitry Andric     if (!HasHotLandingPads) {
202fe6060f1SDimitry Andric       for (MachineBasicBlock *LP : LandingPads)
203fe6060f1SDimitry Andric         LP->setSectionID(MBBSectionID::ColdSectionID);
204fe6060f1SDimitry Andric     }
205bdd1243dSDimitry Andric   }
206*fe013be4SDimitry Andric 
207*fe013be4SDimitry Andric   finishAdjustingBasicBlocksAndLandingPads(MF);
208e8d8bef9SDimitry Andric   return true;
209e8d8bef9SDimitry Andric }
210e8d8bef9SDimitry Andric 
211e8d8bef9SDimitry Andric void MachineFunctionSplitter::getAnalysisUsage(AnalysisUsage &AU) const {
212e8d8bef9SDimitry Andric   AU.addRequired<MachineModuleInfoWrapperPass>();
213e8d8bef9SDimitry Andric   AU.addRequired<MachineBlockFrequencyInfo>();
214e8d8bef9SDimitry Andric   AU.addRequired<ProfileSummaryInfoWrapperPass>();
215e8d8bef9SDimitry Andric }
216e8d8bef9SDimitry Andric 
217e8d8bef9SDimitry Andric char MachineFunctionSplitter::ID = 0;
218e8d8bef9SDimitry Andric INITIALIZE_PASS(MachineFunctionSplitter, "machine-function-splitter",
219e8d8bef9SDimitry Andric                 "Split machine functions using profile information", false,
220e8d8bef9SDimitry Andric                 false)
221e8d8bef9SDimitry Andric 
222e8d8bef9SDimitry Andric MachineFunctionPass *llvm::createMachineFunctionSplitterPass() {
223e8d8bef9SDimitry Andric   return new MachineFunctionSplitter();
224e8d8bef9SDimitry Andric }
225