xref: /llvm-project/llvm/lib/CodeGen/BasicBlockSections.cpp (revision acec6419e811a46050b0603dfa72fc6a169aa0f7)
1 //===-- BasicBlockSections.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 // BasicBlockSections implementation.
10 //
11 // The purpose of this pass is to assign sections to basic blocks when
12 // -fbasic-block-sections= option is used. Further, with profile information
13 // only the subset of basic blocks with profiles are placed in separate sections
14 // and the rest are grouped in a cold section. The exception handling blocks are
15 // treated specially to ensure they are all in one seciton.
16 //
17 // Basic Block Sections
18 // ====================
19 //
20 // With option, -fbasic-block-sections=list, every function may be split into
21 // clusters of basic blocks. Every cluster will be emitted into a separate
22 // section with its basic blocks sequenced in the given order. To get the
23 // optimized performance, the clusters must form an optimal BB layout for the
24 // function. We insert a symbol at the beginning of every cluster's section to
25 // allow the linker to reorder the sections in any arbitrary sequence. A global
26 // order of these sections would encapsulate the function layout.
27 // For example, consider the following clusters for a function foo (consisting
28 // of 6 basic blocks 0, 1, ..., 5).
29 //
30 // 0 2
31 // 1 3 5
32 //
33 // * Basic blocks 0 and 2 are placed in one section with symbol `foo`
34 //   referencing the beginning of this section.
35 // * Basic blocks 1, 3, 5 are placed in a separate section. A new symbol
36 //   `foo.__part.1` will reference the beginning of this section.
37 // * Basic block 4 (note that it is not referenced in the list) is placed in
38 //   one section, and a new symbol `foo.cold` will point to it.
39 //
40 // There are a couple of challenges to be addressed:
41 //
42 // 1. The last basic block of every cluster should not have any implicit
43 //    fallthrough to its next basic block, as it can be reordered by the linker.
44 //    The compiler should make these fallthroughs explicit by adding
45 //    unconditional jumps..
46 //
47 // 2. All inter-cluster branch targets would now need to be resolved by the
48 //    linker as they cannot be calculated during compile time. This is done
49 //    using static relocations. Further, the compiler tries to use short branch
50 //    instructions on some ISAs for small branch offsets. This is not possible
51 //    for inter-cluster branches as the offset is not determined at compile
52 //    time, and therefore, long branch instructions have to be used for those.
53 //
54 // 3. Debug Information (DebugInfo) and Call Frame Information (CFI) emission
55 //    needs special handling with basic block sections. DebugInfo needs to be
56 //    emitted with more relocations as basic block sections can break a
57 //    function into potentially several disjoint pieces, and CFI needs to be
58 //    emitted per cluster. This also bloats the object file and binary sizes.
59 //
60 // Basic Block Address Map
61 // ==================
62 //
63 // With -fbasic-block-address-map, we emit the offsets of BB addresses of
64 // every function into the .llvm_bb_addr_map section. Along with the function
65 // symbols, this allows for mapping of virtual addresses in PMU profiles back to
66 // the corresponding basic blocks. This logic is implemented in AsmPrinter. This
67 // pass only assigns the BBSectionType of every function to ``labels``.
68 //
69 //===----------------------------------------------------------------------===//
70 
71 #include "llvm/ADT/SmallVector.h"
72 #include "llvm/ADT/StringRef.h"
73 #include "llvm/CodeGen/BasicBlockSectionUtils.h"
74 #include "llvm/CodeGen/BasicBlockSectionsProfileReader.h"
75 #include "llvm/CodeGen/MachineFunction.h"
76 #include "llvm/CodeGen/MachineFunctionPass.h"
77 #include "llvm/CodeGen/Passes.h"
78 #include "llvm/CodeGen/TargetInstrInfo.h"
79 #include "llvm/InitializePasses.h"
80 #include "llvm/Target/TargetMachine.h"
81 #include <optional>
82 
83 using namespace llvm;
84 
85 // Placing the cold clusters in a separate section mitigates against poor
86 // profiles and allows optimizations such as hugepage mapping to be applied at a
87 // section granularity. Defaults to ".text.split." which is recognized by lld
88 // via the `-z keep-text-section-prefix` flag.
89 cl::opt<std::string> llvm::BBSectionsColdTextPrefix(
90     "bbsections-cold-text-prefix",
91     cl::desc("The text prefix to use for cold basic block clusters"),
92     cl::init(".text.split."), cl::Hidden);
93 
94 static cl::opt<bool> BBSectionsDetectSourceDrift(
95     "bbsections-detect-source-drift",
96     cl::desc("This checks if there is a fdo instr. profile hash "
97              "mismatch for this function"),
98     cl::init(true), cl::Hidden);
99 
100 namespace {
101 
102 class BasicBlockSections : public MachineFunctionPass {
103 public:
104   static char ID;
105 
106   BasicBlockSectionsProfileReaderWrapperPass *BBSectionsProfileReader = nullptr;
107 
108   BasicBlockSections() : MachineFunctionPass(ID) {
109     initializeBasicBlockSectionsPass(*PassRegistry::getPassRegistry());
110   }
111 
112   StringRef getPassName() const override {
113     return "Basic Block Sections Analysis";
114   }
115 
116   void getAnalysisUsage(AnalysisUsage &AU) const override;
117 
118   /// Identify basic blocks that need separate sections and prepare to emit them
119   /// accordingly.
120   bool runOnMachineFunction(MachineFunction &MF) override;
121 
122 private:
123   bool handleBBSections(MachineFunction &MF);
124   bool handleBBAddrMap(MachineFunction &MF);
125 };
126 
127 } // end anonymous namespace
128 
129 char BasicBlockSections::ID = 0;
130 INITIALIZE_PASS_BEGIN(
131     BasicBlockSections, "bbsections-prepare",
132     "Prepares for basic block sections, by splitting functions "
133     "into clusters of basic blocks.",
134     false, false)
135 INITIALIZE_PASS_DEPENDENCY(BasicBlockSectionsProfileReaderWrapperPass)
136 INITIALIZE_PASS_END(BasicBlockSections, "bbsections-prepare",
137                     "Prepares for basic block sections, by splitting functions "
138                     "into clusters of basic blocks.",
139                     false, false)
140 
141 // This function updates and optimizes the branching instructions of every basic
142 // block in a given function to account for changes in the layout.
143 static void
144 updateBranches(MachineFunction &MF,
145                const SmallVector<MachineBasicBlock *> &PreLayoutFallThroughs) {
146   const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
147   SmallVector<MachineOperand, 4> Cond;
148   for (auto &MBB : MF) {
149     auto NextMBBI = std::next(MBB.getIterator());
150     auto *FTMBB = PreLayoutFallThroughs[MBB.getNumber()];
151     // If this block had a fallthrough before we need an explicit unconditional
152     // branch to that block if either
153     //     1- the block ends a section, which means its next block may be
154     //        reorderd by the linker, or
155     //     2- the fallthrough block is not adjacent to the block in the new
156     //        order.
157     if (FTMBB && (MBB.isEndSection() || &*NextMBBI != FTMBB))
158       TII->insertUnconditionalBranch(MBB, FTMBB, MBB.findBranchDebugLoc());
159 
160     // We do not optimize branches for machine basic blocks ending sections, as
161     // their adjacent block might be reordered by the linker.
162     if (MBB.isEndSection())
163       continue;
164 
165     // It might be possible to optimize branches by flipping the branch
166     // condition.
167     Cond.clear();
168     MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For analyzeBranch.
169     if (TII->analyzeBranch(MBB, TBB, FBB, Cond))
170       continue;
171     MBB.updateTerminator(FTMBB);
172   }
173 }
174 
175 // This function sorts basic blocks according to the cluster's information.
176 // All explicitly specified clusters of basic blocks will be ordered
177 // accordingly. All non-specified BBs go into a separate "Cold" section.
178 // Additionally, if exception handling landing pads end up in more than one
179 // clusters, they are moved into a single "Exception" section. Eventually,
180 // clusters are ordered in increasing order of their IDs, with the "Exception"
181 // and "Cold" succeeding all other clusters.
182 // FuncClusterInfo represents the cluster information for basic blocks. It
183 // maps from BBID of basic blocks to their cluster information. If this is
184 // empty, it means unique sections for all basic blocks in the function.
185 static void
186 assignSections(MachineFunction &MF,
187                const DenseMap<UniqueBBID, BBClusterInfo> &FuncClusterInfo) {
188   assert(MF.hasBBSections() && "BB Sections is not set for function.");
189   // This variable stores the section ID of the cluster containing eh_pads (if
190   // all eh_pads are one cluster). If more than one cluster contain eh_pads, we
191   // set it equal to ExceptionSectionID.
192   std::optional<MBBSectionID> EHPadsSectionID;
193 
194   for (auto &MBB : MF) {
195     // With the 'all' option, every basic block is placed in a unique section.
196     // With the 'list' option, every basic block is placed in a section
197     // associated with its cluster, unless we want individual unique sections
198     // for every basic block in this function (if FuncClusterInfo is empty).
199     if (MF.getTarget().getBBSectionsType() == llvm::BasicBlockSection::All ||
200         FuncClusterInfo.empty()) {
201       // If unique sections are desired for all basic blocks of the function, we
202       // set every basic block's section ID equal to its original position in
203       // the layout (which is equal to its number). This ensures that basic
204       // blocks are ordered canonically.
205       MBB.setSectionID(MBB.getNumber());
206     } else {
207       auto I = FuncClusterInfo.find(*MBB.getBBID());
208       if (I != FuncClusterInfo.end()) {
209         MBB.setSectionID(I->second.ClusterID);
210       } else {
211         // BB goes into the special cold section if it is not specified in the
212         // cluster info map.
213         MBB.setSectionID(MBBSectionID::ColdSectionID);
214       }
215     }
216 
217     if (MBB.isEHPad() && EHPadsSectionID != MBB.getSectionID() &&
218         EHPadsSectionID != MBBSectionID::ExceptionSectionID) {
219       // If we already have one cluster containing eh_pads, this must be updated
220       // to ExceptionSectionID. Otherwise, we set it equal to the current
221       // section ID.
222       EHPadsSectionID = EHPadsSectionID ? MBBSectionID::ExceptionSectionID
223                                         : MBB.getSectionID();
224     }
225   }
226 
227   // If EHPads are in more than one section, this places all of them in the
228   // special exception section.
229   if (EHPadsSectionID == MBBSectionID::ExceptionSectionID)
230     for (auto &MBB : MF)
231       if (MBB.isEHPad())
232         MBB.setSectionID(*EHPadsSectionID);
233 }
234 
235 void llvm::sortBasicBlocksAndUpdateBranches(
236     MachineFunction &MF, MachineBasicBlockComparator MBBCmp) {
237   [[maybe_unused]] const MachineBasicBlock *EntryBlock = &MF.front();
238   SmallVector<MachineBasicBlock *> PreLayoutFallThroughs(MF.getNumBlockIDs());
239   for (auto &MBB : MF)
240     PreLayoutFallThroughs[MBB.getNumber()] =
241         MBB.getFallThrough(/*JumpToFallThrough=*/false);
242 
243   MF.sort(MBBCmp);
244   assert(&MF.front() == EntryBlock &&
245          "Entry block should not be displaced by basic block sections");
246 
247   // Set IsBeginSection and IsEndSection according to the assigned section IDs.
248   MF.assignBeginEndSections();
249 
250   // After reordering basic blocks, we must update basic block branches to
251   // insert explicit fallthrough branches when required and optimize branches
252   // when possible.
253   updateBranches(MF, PreLayoutFallThroughs);
254 }
255 
256 // If the exception section begins with a landing pad, that landing pad will
257 // assume a zero offset (relative to @LPStart) in the LSDA. However, a value of
258 // zero implies "no landing pad." This function inserts a NOP just before the EH
259 // pad label to ensure a nonzero offset.
260 void llvm::avoidZeroOffsetLandingPad(MachineFunction &MF) {
261   for (auto &MBB : MF) {
262     if (MBB.isBeginSection() && MBB.isEHPad()) {
263       MachineBasicBlock::iterator MI = MBB.begin();
264       while (!MI->isEHLabel())
265         ++MI;
266       MF.getSubtarget().getInstrInfo()->insertNoop(MBB, MI);
267     }
268   }
269 }
270 
271 bool llvm::hasInstrProfHashMismatch(MachineFunction &MF) {
272   if (!BBSectionsDetectSourceDrift)
273     return false;
274 
275   const char MetadataName[] = "instr_prof_hash_mismatch";
276   auto *Existing = MF.getFunction().getMetadata(LLVMContext::MD_annotation);
277   if (Existing) {
278     MDTuple *Tuple = cast<MDTuple>(Existing);
279     for (const auto &N : Tuple->operands())
280       if (N.equalsStr(MetadataName))
281         return true;
282   }
283 
284   return false;
285 }
286 
287 // Identify, arrange, and modify basic blocks which need separate sections
288 // according to the specification provided by the -fbasic-block-sections flag.
289 bool BasicBlockSections::handleBBSections(MachineFunction &MF) {
290   auto BBSectionsType = MF.getTarget().getBBSectionsType();
291   if (BBSectionsType == BasicBlockSection::None)
292     return false;
293 
294   // Check for source drift. If the source has changed since the profiles
295   // were obtained, optimizing basic blocks might be sub-optimal.
296   // This only applies to BasicBlockSection::List as it creates
297   // clusters of basic blocks using basic block ids. Source drift can
298   // invalidate these groupings leading to sub-optimal code generation with
299   // regards to performance.
300   if (BBSectionsType == BasicBlockSection::List &&
301       hasInstrProfHashMismatch(MF))
302     return false;
303   // Renumber blocks before sorting them. This is useful for accessing the
304   // original layout positions and finding the original fallthroughs.
305   MF.RenumberBlocks();
306 
307   if (BBSectionsType == BasicBlockSection::Labels) {
308     MF.setBBSectionsType(BBSectionsType);
309     return true;
310   }
311 
312   DenseMap<UniqueBBID, BBClusterInfo> FuncClusterInfo;
313   if (BBSectionsType == BasicBlockSection::List) {
314     auto [HasProfile, ClusterInfo] =
315         getAnalysis<BasicBlockSectionsProfileReaderWrapperPass>()
316             .getClusterInfoForFunction(MF.getName());
317     if (!HasProfile)
318       return false;
319     for (auto &BBClusterInfo : ClusterInfo) {
320       FuncClusterInfo.try_emplace(BBClusterInfo.BBID, BBClusterInfo);
321     }
322   }
323 
324   MF.setBBSectionsType(BBSectionsType);
325   assignSections(MF, FuncClusterInfo);
326 
327   const MachineBasicBlock &EntryBB = MF.front();
328   auto EntryBBSectionID = EntryBB.getSectionID();
329 
330   // Helper function for ordering BB sections as follows:
331   //   * Entry section (section including the entry block).
332   //   * Regular sections (in increasing order of their Number).
333   //     ...
334   //   * Exception section
335   //   * Cold section
336   auto MBBSectionOrder = [EntryBBSectionID](const MBBSectionID &LHS,
337                                             const MBBSectionID &RHS) {
338     // We make sure that the section containing the entry block precedes all the
339     // other sections.
340     if (LHS == EntryBBSectionID || RHS == EntryBBSectionID)
341       return LHS == EntryBBSectionID;
342     return LHS.Type == RHS.Type ? LHS.Number < RHS.Number : LHS.Type < RHS.Type;
343   };
344 
345   // We sort all basic blocks to make sure the basic blocks of every cluster are
346   // contiguous and ordered accordingly. Furthermore, clusters are ordered in
347   // increasing order of their section IDs, with the exception and the
348   // cold section placed at the end of the function.
349   // Also, we force the entry block of the function to be placed at the
350   // beginning of the function, regardless of the requested order.
351   auto Comparator = [&](const MachineBasicBlock &X,
352                         const MachineBasicBlock &Y) {
353     auto XSectionID = X.getSectionID();
354     auto YSectionID = Y.getSectionID();
355     if (XSectionID != YSectionID)
356       return MBBSectionOrder(XSectionID, YSectionID);
357     // Make sure that the entry block is placed at the beginning.
358     if (&X == &EntryBB || &Y == &EntryBB)
359       return &X == &EntryBB;
360     // If the two basic block are in the same section, the order is decided by
361     // their position within the section.
362     if (XSectionID.Type == MBBSectionID::SectionType::Default)
363       return FuncClusterInfo.lookup(*X.getBBID()).PositionInCluster <
364              FuncClusterInfo.lookup(*Y.getBBID()).PositionInCluster;
365     return X.getNumber() < Y.getNumber();
366   };
367 
368   sortBasicBlocksAndUpdateBranches(MF, Comparator);
369   avoidZeroOffsetLandingPad(MF);
370   return true;
371 }
372 
373 // When the BB address map needs to be generated, this renumbers basic blocks to
374 // make them appear in increasing order of their IDs in the function. This
375 // avoids the need to store basic block IDs in the BB address map section, since
376 // they can be determined implicitly.
377 bool BasicBlockSections::handleBBAddrMap(MachineFunction &MF) {
378   if (MF.getTarget().getBBSectionsType() == BasicBlockSection::Labels)
379     return false;
380   if (!MF.getTarget().Options.BBAddrMap)
381     return false;
382   MF.RenumberBlocks();
383   return true;
384 }
385 
386 bool BasicBlockSections::runOnMachineFunction(MachineFunction &MF) {
387   // First handle the basic block sections.
388   auto R1 = handleBBSections(MF);
389   // Handle basic block address map after basic block sections are finalized.
390   auto R2 = handleBBAddrMap(MF);
391   return R1 || R2;
392 }
393 
394 void BasicBlockSections::getAnalysisUsage(AnalysisUsage &AU) const {
395   AU.setPreservesAll();
396   AU.addRequired<BasicBlockSectionsProfileReaderWrapperPass>();
397   MachineFunctionPass::getAnalysisUsage(AU);
398 }
399 
400 MachineFunctionPass *llvm::createBasicBlockSectionsPass() {
401   return new BasicBlockSections();
402 }
403