1 //===-- MachineFunctionSplitter.cpp - Split machine functions //-----------===// 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 // \file 10 // Uses profile information to split out cold blocks. 11 // 12 // This pass splits out cold machine basic blocks from the parent function. This 13 // implementation leverages the basic block section framework. Blocks marked 14 // cold by this pass are grouped together in a separate section prefixed with 15 // ".text.unlikely.*". The linker can then group these together as a cold 16 // section. The split part of the function is a contiguous region identified by 17 // the symbol "foo.cold". Grouping all cold blocks across functions together 18 // decreases fragmentation and improves icache and itlb utilization. Note that 19 // the overall changes to the binary size are negligible; only a small number of 20 // additional jump instructions may be introduced. 21 // 22 // For the original RFC of this pass please see 23 // https://groups.google.com/d/msg/llvm-dev/RUegaMg-iqc/wFAVxa6fCgAJ 24 //===----------------------------------------------------------------------===// 25 26 #include "llvm/ADT/SmallVector.h" 27 #include "llvm/Analysis/BlockFrequencyInfo.h" 28 #include "llvm/Analysis/BranchProbabilityInfo.h" 29 #include "llvm/Analysis/EHUtils.h" 30 #include "llvm/Analysis/ProfileSummaryInfo.h" 31 #include "llvm/CodeGen/BasicBlockSectionUtils.h" 32 #include "llvm/CodeGen/MachineBasicBlock.h" 33 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h" 34 #include "llvm/CodeGen/MachineFunction.h" 35 #include "llvm/CodeGen/MachineFunctionPass.h" 36 #include "llvm/CodeGen/MachineModuleInfo.h" 37 #include "llvm/CodeGen/Passes.h" 38 #include "llvm/CodeGen/TargetInstrInfo.h" 39 #include "llvm/IR/Function.h" 40 #include "llvm/InitializePasses.h" 41 #include "llvm/Support/CommandLine.h" 42 #include <optional> 43 44 using namespace llvm; 45 46 // FIXME: This cutoff value is CPU dependent and should be moved to 47 // TargetTransformInfo once we consider enabling this on other platforms. 48 // The value is expressed as a ProfileSummaryInfo integer percentile cutoff. 49 // Defaults to 999950, i.e. all blocks colder than 99.995 percentile are split. 50 // The default was empirically determined to be optimal when considering cutoff 51 // values between 99%-ile to 100%-ile with respect to iTLB and icache metrics on 52 // Intel CPUs. 53 static cl::opt<unsigned> 54 PercentileCutoff("mfs-psi-cutoff", 55 cl::desc("Percentile profile summary cutoff used to " 56 "determine cold blocks. Unused if set to zero."), 57 cl::init(999950), cl::Hidden); 58 59 static cl::opt<unsigned> ColdCountThreshold( 60 "mfs-count-threshold", 61 cl::desc( 62 "Minimum number of times a block must be executed to be retained."), 63 cl::init(1), cl::Hidden); 64 65 static cl::opt<bool> SplitAllEHCode( 66 "mfs-split-ehcode", 67 cl::desc("Splits all EH code and it's descendants by default."), 68 cl::init(false), cl::Hidden); 69 70 static cl::opt<bool> AllowUnsupportedTriple( 71 "mfs-allow-unsupported-triple", 72 cl::desc( 73 "Splits functions even if the target triple isn't supported. This is " 74 "testing flag for targets that don't yet support function splitting."), 75 cl::init(false), cl::Hidden); 76 77 namespace { 78 79 class MachineFunctionSplitter : public MachineFunctionPass { 80 public: 81 static char ID; 82 MachineFunctionSplitter() : MachineFunctionPass(ID) { 83 initializeMachineFunctionSplitterPass(*PassRegistry::getPassRegistry()); 84 } 85 86 StringRef getPassName() const override { 87 return "Machine Function Splitter Transformation"; 88 } 89 90 void getAnalysisUsage(AnalysisUsage &AU) const override; 91 92 bool runOnMachineFunction(MachineFunction &F) override; 93 }; 94 } // end anonymous namespace 95 96 /// setDescendantEHBlocksCold - This splits all EH pads and blocks reachable 97 /// only by EH pad as cold. This will help mark EH pads statically cold 98 /// instead of relying on profile data. 99 static void setDescendantEHBlocksCold(MachineFunction &MF) { 100 DenseSet<MachineBasicBlock *> EHBlocks; 101 computeEHOnlyBlocks(MF, EHBlocks); 102 for (auto Block : EHBlocks) { 103 Block->setSectionID(MBBSectionID::ColdSectionID); 104 } 105 } 106 107 static void finishAdjustingBasicBlocksAndLandingPads(MachineFunction &MF) { 108 auto Comparator = [](const MachineBasicBlock &X, const MachineBasicBlock &Y) { 109 return X.getSectionID().Type < Y.getSectionID().Type; 110 }; 111 llvm::sortBasicBlocksAndUpdateBranches(MF, Comparator); 112 llvm::avoidZeroOffsetLandingPad(MF); 113 } 114 115 static bool isColdBlock(const MachineBasicBlock &MBB, 116 const MachineBlockFrequencyInfo *MBFI, 117 ProfileSummaryInfo *PSI) { 118 std::optional<uint64_t> Count = MBFI->getBlockProfileCount(&MBB); 119 // For instrumentation profiles and sample profiles, we use different ways 120 // to judge whether a block is cold and should be split. 121 if (PSI->hasInstrumentationProfile() || PSI->hasCSInstrumentationProfile()) { 122 // If using instrument profile, which is deemed "accurate", no count means 123 // cold. 124 if (!Count) 125 return true; 126 if (PercentileCutoff > 0) 127 return PSI->isColdCountNthPercentile(PercentileCutoff, *Count); 128 // Fallthrough to end of function. 129 } else if (PSI->hasSampleProfile()) { 130 // For sample profile, no count means "do not judege coldness". 131 if (!Count) 132 return false; 133 } 134 135 return (*Count < ColdCountThreshold); 136 } 137 138 bool MachineFunctionSplitter::runOnMachineFunction(MachineFunction &MF) { 139 // We target functions with profile data. Static information in the form 140 // of exception handling code may be split to cold if user passes the 141 // mfs-split-ehcode flag. 142 bool UseProfileData = MF.getFunction().hasProfileData(); 143 if (!UseProfileData && !SplitAllEHCode) 144 return false; 145 146 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 147 if (!TII.isFunctionSafeToSplit(MF)) 148 return false; 149 150 // Renumbering blocks here preserves the order of the blocks as 151 // sortBasicBlocksAndUpdateBranches uses the numeric identifier to sort 152 // blocks. Preserving the order of blocks is essential to retaining decisions 153 // made by prior passes such as MachineBlockPlacement. 154 MF.RenumberBlocks(); 155 MF.setBBSectionsType(BasicBlockSection::Preset); 156 157 MachineBlockFrequencyInfo *MBFI = nullptr; 158 ProfileSummaryInfo *PSI = nullptr; 159 if (UseProfileData) { 160 MBFI = &getAnalysis<MachineBlockFrequencyInfo>(); 161 PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI(); 162 // If we don't have a good profile (sample profile is not deemed 163 // as a "good profile") and the function is not hot, then early 164 // return. (Because we can only trust hot functions when profile 165 // quality is not good.) 166 if (PSI->hasSampleProfile() && !PSI->isFunctionHotInCallGraph(&MF, *MBFI)) { 167 // Split all EH code and it's descendant statically by default. 168 if (SplitAllEHCode) 169 setDescendantEHBlocksCold(MF); 170 finishAdjustingBasicBlocksAndLandingPads(MF); 171 return true; 172 } 173 } 174 175 SmallVector<MachineBasicBlock *, 2> LandingPads; 176 for (auto &MBB : MF) { 177 if (MBB.isEntryBlock()) 178 continue; 179 180 if (MBB.isEHPad()) 181 LandingPads.push_back(&MBB); 182 else if (UseProfileData && isColdBlock(MBB, MBFI, PSI) && !SplitAllEHCode) 183 MBB.setSectionID(MBBSectionID::ColdSectionID); 184 } 185 186 // Split all EH code and it's descendant statically by default. 187 if (SplitAllEHCode) 188 setDescendantEHBlocksCold(MF); 189 // We only split out eh pads if all of them are cold. 190 else { 191 // Here we have UseProfileData == true. 192 bool HasHotLandingPads = false; 193 for (const MachineBasicBlock *LP : LandingPads) { 194 if (!isColdBlock(*LP, MBFI, PSI)) 195 HasHotLandingPads = true; 196 } 197 if (!HasHotLandingPads) { 198 for (MachineBasicBlock *LP : LandingPads) 199 LP->setSectionID(MBBSectionID::ColdSectionID); 200 } 201 } 202 203 finishAdjustingBasicBlocksAndLandingPads(MF); 204 return true; 205 } 206 207 void MachineFunctionSplitter::getAnalysisUsage(AnalysisUsage &AU) const { 208 AU.addRequired<MachineModuleInfoWrapperPass>(); 209 AU.addRequired<MachineBlockFrequencyInfo>(); 210 AU.addRequired<ProfileSummaryInfoWrapperPass>(); 211 } 212 213 char MachineFunctionSplitter::ID = 0; 214 INITIALIZE_PASS(MachineFunctionSplitter, "machine-function-splitter", 215 "Split machine functions using profile information", false, 216 false) 217 218 MachineFunctionPass *llvm::createMachineFunctionSplitterPass() { 219 return new MachineFunctionSplitter(); 220 } 221