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. Every cluster's section is labeled with a symbol to allow the
25 // linker to reorder the sections in any arbitrary sequence. A global order of
26 // these sections would encapsulate the function layout.
27 //
28 // There are a couple of challenges to be addressed:
29 //
30 // 1. The last basic block of every cluster should not have any implicit
31 //    fallthrough to its next basic block, as it can be reordered by the linker.
32 //    The compiler should make these fallthroughs explicit by adding
33 //    unconditional jumps..
34 //
35 // 2. All inter-cluster branch targets would now need to be resolved by the
36 //    linker as they cannot be calculated during compile time. This is done
37 //    using static relocations. Further, the compiler tries to use short branch
38 //    instructions on some ISAs for small branch offsets. This is not possible
39 //    for inter-cluster branches as the offset is not determined at compile
40 //    time, and therefore, long branch instructions have to be used for those.
41 //
42 // 3. Debug Information (DebugInfo) and Call Frame Information (CFI) emission
43 //    needs special handling with basic block sections. DebugInfo needs to be
44 //    emitted with more relocations as basic block sections can break a
45 //    function into potentially several disjoint pieces, and CFI needs to be
46 //    emitted per cluster. This also bloats the object file and binary sizes.
47 //
48 // Basic Block Labels
49 // ==================
50 //
51 // With -fbasic-block-sections=labels, or when a basic block is placed in a
52 // unique section, it is labelled with a symbol.  This allows easy mapping of
53 // virtual addresses from PMU profiles back to the corresponding basic blocks.
54 // Since the number of basic blocks is large, the labeling bloats the symbol
55 // table sizes and the string table sizes significantly. While the binary size
56 // does increase, it does not affect performance as the symbol table is not
57 // loaded in memory during run-time. The string table size bloat is kept very
58 // minimal using a unary naming scheme that uses string suffix compression. The
59 // basic blocks for function foo are named "a.BB.foo", "aa.BB.foo", ... This
60 // turns out to be very good for string table sizes and the bloat in the string
61 // table size for a very large binary is ~8 %.  The naming also allows using
62 // the --symbol-ordering-file option in LLD to arbitrarily reorder the
63 // sections.
64 //
65 //===----------------------------------------------------------------------===//
66 
67 #include "llvm/ADT/Optional.h"
68 #include "llvm/ADT/SmallSet.h"
69 #include "llvm/ADT/SmallVector.h"
70 #include "llvm/ADT/StringMap.h"
71 #include "llvm/ADT/StringRef.h"
72 #include "llvm/CodeGen/BasicBlockSectionUtils.h"
73 #include "llvm/CodeGen/MachineFunction.h"
74 #include "llvm/CodeGen/MachineFunctionPass.h"
75 #include "llvm/CodeGen/MachineModuleInfo.h"
76 #include "llvm/CodeGen/Passes.h"
77 #include "llvm/CodeGen/TargetInstrInfo.h"
78 #include "llvm/InitializePasses.h"
79 #include "llvm/Support/Error.h"
80 #include "llvm/Support/LineIterator.h"
81 #include "llvm/Support/MemoryBuffer.h"
82 #include "llvm/Target/TargetMachine.h"
83 
84 using llvm::SmallSet;
85 using llvm::SmallVector;
86 using llvm::StringMap;
87 using llvm::StringRef;
88 using namespace llvm;
89 
90 namespace {
91 
92 // This struct represents the cluster information for a machine basic block.
93 struct BBClusterInfo {
94   // MachineBasicBlock ID.
95   unsigned MBBNumber;
96   // Cluster ID this basic block belongs to.
97   unsigned ClusterID;
98   // Position of basic block within the cluster.
99   unsigned PositionInCluster;
100 };
101 
102 using ProgramBBClusterInfoMapTy = StringMap<SmallVector<BBClusterInfo, 4>>;
103 
104 class BasicBlockSections : public MachineFunctionPass {
105 public:
106   static char ID;
107 
108   // This contains the basic-block-sections profile.
109   const MemoryBuffer *MBuf = nullptr;
110 
111   // This encapsulates the BB cluster information for the whole program.
112   //
113   // For every function name, it contains the cluster information for (all or
114   // some of) its basic blocks. The cluster information for every basic block
115   // includes its cluster ID along with the position of the basic block in that
116   // cluster.
117   ProgramBBClusterInfoMapTy ProgramBBClusterInfo;
118 
119   // Some functions have alias names. We use this map to find the main alias
120   // name for which we have mapping in ProgramBBClusterInfo.
121   StringMap<StringRef> FuncAliasMap;
122 
123   BasicBlockSections(const MemoryBuffer *Buf)
124       : MachineFunctionPass(ID), MBuf(Buf) {
125     initializeBasicBlockSectionsPass(*PassRegistry::getPassRegistry());
126   };
127 
128   BasicBlockSections() : MachineFunctionPass(ID) {
129     initializeBasicBlockSectionsPass(*PassRegistry::getPassRegistry());
130   }
131 
132   StringRef getPassName() const override {
133     return "Basic Block Sections Analysis";
134   }
135 
136   void getAnalysisUsage(AnalysisUsage &AU) const override;
137 
138   /// Read profiles of basic blocks if available here.
139   bool doInitialization(Module &M) override;
140 
141   /// Identify basic blocks that need separate sections and prepare to emit them
142   /// accordingly.
143   bool runOnMachineFunction(MachineFunction &MF) override;
144 };
145 
146 } // end anonymous namespace
147 
148 char BasicBlockSections::ID = 0;
149 INITIALIZE_PASS(BasicBlockSections, "bbsections-prepare",
150                 "Prepares for basic block sections, by splitting functions "
151                 "into clusters of basic blocks.",
152                 false, false)
153 
154 // This function updates and optimizes the branching instructions of every basic
155 // block in a given function to account for changes in the layout.
156 static void updateBranches(
157     MachineFunction &MF,
158     const SmallVector<MachineBasicBlock *, 4> &PreLayoutFallThroughs) {
159   const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
160   SmallVector<MachineOperand, 4> Cond;
161   for (auto &MBB : MF) {
162     auto NextMBBI = std::next(MBB.getIterator());
163     auto *FTMBB = PreLayoutFallThroughs[MBB.getNumber()];
164     // If this block had a fallthrough before we need an explicit unconditional
165     // branch to that block if either
166     //     1- the block ends a section, which means its next block may be
167     //        reorderd by the linker, or
168     //     2- the fallthrough block is not adjacent to the block in the new
169     //        order.
170     if (FTMBB && (MBB.isEndSection() || &*NextMBBI != FTMBB))
171       TII->insertUnconditionalBranch(MBB, FTMBB, MBB.findBranchDebugLoc());
172 
173     // We do not optimize branches for machine basic blocks ending sections, as
174     // their adjacent block might be reordered by the linker.
175     if (MBB.isEndSection())
176       continue;
177 
178     // It might be possible to optimize branches by flipping the branch
179     // condition.
180     Cond.clear();
181     MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For analyzeBranch.
182     if (TII->analyzeBranch(MBB, TBB, FBB, Cond))
183       continue;
184     MBB.updateTerminator(FTMBB);
185   }
186 }
187 
188 // This function provides the BBCluster information associated with a function.
189 // Returns true if a valid association exists and false otherwise.
190 static bool getBBClusterInfoForFunction(
191     const MachineFunction &MF, const StringMap<StringRef> FuncAliasMap,
192     const ProgramBBClusterInfoMapTy &ProgramBBClusterInfo,
193     std::vector<Optional<BBClusterInfo>> &V) {
194   // Get the main alias name for the function.
195   auto FuncName = MF.getName();
196   auto R = FuncAliasMap.find(FuncName);
197   StringRef AliasName = R == FuncAliasMap.end() ? FuncName : R->second;
198 
199   // Find the assoicated cluster information.
200   auto P = ProgramBBClusterInfo.find(AliasName);
201   if (P == ProgramBBClusterInfo.end())
202     return false;
203 
204   if (P->second.empty()) {
205     // This indicates that sections are desired for all basic blocks of this
206     // function. We clear the BBClusterInfo vector to denote this.
207     V.clear();
208     return true;
209   }
210 
211   V.resize(MF.getNumBlockIDs());
212   for (auto bbClusterInfo : P->second) {
213     // Bail out if the cluster information contains invalid MBB numbers.
214     if (bbClusterInfo.MBBNumber >= MF.getNumBlockIDs())
215       return false;
216     V[bbClusterInfo.MBBNumber] = bbClusterInfo;
217   }
218   return true;
219 }
220 
221 // This function sorts basic blocks according to the cluster's information.
222 // All explicitly specified clusters of basic blocks will be ordered
223 // accordingly. All non-specified BBs go into a separate "Cold" section.
224 // Additionally, if exception handling landing pads end up in more than one
225 // clusters, they are moved into a single "Exception" section. Eventually,
226 // clusters are ordered in increasing order of their IDs, with the "Exception"
227 // and "Cold" succeeding all other clusters.
228 // FuncBBClusterInfo represent the cluster information for basic blocks. If this
229 // is empty, it means unique sections for all basic blocks in the function.
230 static void
231 assignSections(MachineFunction &MF,
232                const std::vector<Optional<BBClusterInfo>> &FuncBBClusterInfo) {
233   assert(MF.hasBBSections() && "BB Sections is not set for function.");
234   // This variable stores the section ID of the cluster containing eh_pads (if
235   // all eh_pads are one cluster). If more than one cluster contain eh_pads, we
236   // set it equal to ExceptionSectionID.
237   Optional<MBBSectionID> EHPadsSectionID;
238 
239   for (auto &MBB : MF) {
240     // With the 'all' option, every basic block is placed in a unique section.
241     // With the 'list' option, every basic block is placed in a section
242     // associated with its cluster, unless we want individual unique sections
243     // for every basic block in this function (if FuncBBClusterInfo is empty).
244     if (MF.getTarget().getBBSectionsType() == llvm::BasicBlockSection::All ||
245         FuncBBClusterInfo.empty()) {
246       // If unique sections are desired for all basic blocks of the function, we
247       // set every basic block's section ID equal to its number (basic block
248       // id). This further ensures that basic blocks are ordered canonically.
249       MBB.setSectionID({static_cast<unsigned int>(MBB.getNumber())});
250     } else if (FuncBBClusterInfo[MBB.getNumber()].hasValue())
251       MBB.setSectionID(FuncBBClusterInfo[MBB.getNumber()]->ClusterID);
252     else {
253       // BB goes into the special cold section if it is not specified in the
254       // cluster info map.
255       MBB.setSectionID(MBBSectionID::ColdSectionID);
256     }
257 
258     if (MBB.isEHPad() && EHPadsSectionID != MBB.getSectionID() &&
259         EHPadsSectionID != MBBSectionID::ExceptionSectionID) {
260       // If we already have one cluster containing eh_pads, this must be updated
261       // to ExceptionSectionID. Otherwise, we set it equal to the current
262       // section ID.
263       EHPadsSectionID = EHPadsSectionID.hasValue()
264                             ? MBBSectionID::ExceptionSectionID
265                             : MBB.getSectionID();
266     }
267   }
268 
269   // If EHPads are in more than one section, this places all of them in the
270   // special exception section.
271   if (EHPadsSectionID == MBBSectionID::ExceptionSectionID)
272     for (auto &MBB : MF)
273       if (MBB.isEHPad())
274         MBB.setSectionID(EHPadsSectionID.getValue());
275 }
276 
277 void llvm::sortBasicBlocksAndUpdateBranches(
278     MachineFunction &MF, MachineBasicBlockComparator MBBCmp) {
279   SmallVector<MachineBasicBlock *, 4> PreLayoutFallThroughs(
280       MF.getNumBlockIDs());
281   for (auto &MBB : MF)
282     PreLayoutFallThroughs[MBB.getNumber()] = MBB.getFallThrough();
283 
284   MF.sort(MBBCmp);
285 
286   // Set IsBeginSection and IsEndSection according to the assigned section IDs.
287   MF.assignBeginEndSections();
288 
289   // After reordering basic blocks, we must update basic block branches to
290   // insert explicit fallthrough branches when required and optimize branches
291   // when possible.
292   updateBranches(MF, PreLayoutFallThroughs);
293 }
294 
295 bool BasicBlockSections::runOnMachineFunction(MachineFunction &MF) {
296   auto BBSectionsType = MF.getTarget().getBBSectionsType();
297   assert(BBSectionsType != BasicBlockSection::None &&
298          "BB Sections not enabled!");
299   // Renumber blocks before sorting them for basic block sections.  This is
300   // useful during sorting, basic blocks in the same section will retain the
301   // default order.  This renumbering should also be done for basic block
302   // labels to match the profiles with the correct blocks.
303   MF.RenumberBlocks();
304 
305   if (BBSectionsType == BasicBlockSection::Labels) {
306     MF.setBBSectionsType(BBSectionsType);
307     MF.createBBLabels();
308     return true;
309   }
310 
311   std::vector<Optional<BBClusterInfo>> FuncBBClusterInfo;
312   if (BBSectionsType == BasicBlockSection::List &&
313       !getBBClusterInfoForFunction(MF, FuncAliasMap, ProgramBBClusterInfo,
314                                    FuncBBClusterInfo))
315     return true;
316   MF.setBBSectionsType(BBSectionsType);
317   MF.createBBLabels();
318   assignSections(MF, FuncBBClusterInfo);
319 
320   // We make sure that the cluster including the entry basic block precedes all
321   // other clusters.
322   auto EntryBBSectionID = MF.front().getSectionID();
323 
324   // Helper function for ordering BB sections as follows:
325   //   * Entry section (section including the entry block).
326   //   * Regular sections (in increasing order of their Number).
327   //     ...
328   //   * Exception section
329   //   * Cold section
330   auto MBBSectionOrder = [EntryBBSectionID](const MBBSectionID &LHS,
331                                             const MBBSectionID &RHS) {
332     // We make sure that the section containing the entry block precedes all the
333     // other sections.
334     if (LHS == EntryBBSectionID || RHS == EntryBBSectionID)
335       return LHS == EntryBBSectionID;
336     return LHS.Type == RHS.Type ? LHS.Number < RHS.Number : LHS.Type < RHS.Type;
337   };
338 
339   // We sort all basic blocks to make sure the basic blocks of every cluster are
340   // contiguous and ordered accordingly. Furthermore, clusters are ordered in
341   // increasing order of their section IDs, with the exception and the
342   // cold section placed at the end of the function.
343   auto Comparator = [&](const MachineBasicBlock &X,
344                         const MachineBasicBlock &Y) {
345     auto XSectionID = X.getSectionID();
346     auto YSectionID = Y.getSectionID();
347     if (XSectionID != YSectionID)
348       return MBBSectionOrder(XSectionID, YSectionID);
349     // If the two basic block are in the same section, the order is decided by
350     // their position within the section.
351     if (XSectionID.Type == MBBSectionID::SectionType::Default)
352       return FuncBBClusterInfo[X.getNumber()]->PositionInCluster <
353              FuncBBClusterInfo[Y.getNumber()]->PositionInCluster;
354     return X.getNumber() < Y.getNumber();
355   };
356 
357   sortBasicBlocksAndUpdateBranches(MF, Comparator);
358   return true;
359 }
360 
361 // Basic Block Sections can be enabled for a subset of machine basic blocks.
362 // This is done by passing a file containing names of functions for which basic
363 // block sections are desired.  Additionally, machine basic block ids of the
364 // functions can also be specified for a finer granularity. Moreover, a cluster
365 // of basic blocks could be assigned to the same section.
366 // A file with basic block sections for all of function main and three blocks
367 // for function foo (of which 1 and 2 are placed in a cluster) looks like this:
368 // ----------------------------
369 // list.txt:
370 // !main
371 // !foo
372 // !!1 2
373 // !!4
374 static Error getBBClusterInfo(const MemoryBuffer *MBuf,
375                               ProgramBBClusterInfoMapTy &ProgramBBClusterInfo,
376                               StringMap<StringRef> &FuncAliasMap) {
377   assert(MBuf);
378   line_iterator LineIt(*MBuf, /*SkipBlanks=*/true, /*CommentMarker=*/'#');
379 
380   auto invalidProfileError = [&](auto Message) {
381     return make_error<StringError>(
382         Twine("Invalid profile " + MBuf->getBufferIdentifier() + " at line " +
383               Twine(LineIt.line_number()) + ": " + Message),
384         inconvertibleErrorCode());
385   };
386 
387   auto FI = ProgramBBClusterInfo.end();
388 
389   // Current cluster ID corresponding to this function.
390   unsigned CurrentCluster = 0;
391   // Current position in the current cluster.
392   unsigned CurrentPosition = 0;
393 
394   // Temporary set to ensure every basic block ID appears once in the clusters
395   // of a function.
396   SmallSet<unsigned, 4> FuncBBIDs;
397 
398   for (; !LineIt.is_at_eof(); ++LineIt) {
399     StringRef S(*LineIt);
400     if (S[0] == '@')
401       continue;
402     // Check for the leading "!"
403     if (!S.consume_front("!") || S.empty())
404       break;
405     // Check for second "!" which indicates a cluster of basic blocks.
406     if (S.consume_front("!")) {
407       if (FI == ProgramBBClusterInfo.end())
408         return invalidProfileError(
409             "Cluster list does not follow a function name specifier.");
410       SmallVector<StringRef, 4> BBIndexes;
411       S.split(BBIndexes, ' ');
412       // Reset current cluster position.
413       CurrentPosition = 0;
414       for (auto BBIndexStr : BBIndexes) {
415         unsigned long long BBIndex;
416         if (getAsUnsignedInteger(BBIndexStr, 10, BBIndex))
417           return invalidProfileError(Twine("Unsigned integer expected: '") +
418                                      BBIndexStr + "'.");
419         if (!FuncBBIDs.insert(BBIndex).second)
420           return invalidProfileError(Twine("Duplicate basic block id found '") +
421                                      BBIndexStr + "'.");
422         if (!BBIndex && CurrentPosition)
423           return invalidProfileError("Entry BB (0) does not begin a cluster.");
424 
425         FI->second.emplace_back(BBClusterInfo{
426             ((unsigned)BBIndex), CurrentCluster, CurrentPosition++});
427       }
428       CurrentCluster++;
429     } else { // This is a function name specifier.
430       // Function aliases are separated using '/'. We use the first function
431       // name for the cluster info mapping and delegate all other aliases to
432       // this one.
433       SmallVector<StringRef, 4> Aliases;
434       S.split(Aliases, '/');
435       for (size_t i = 1; i < Aliases.size(); ++i)
436         FuncAliasMap.try_emplace(Aliases[i], Aliases.front());
437 
438       // Prepare for parsing clusters of this function name.
439       // Start a new cluster map for this function name.
440       FI = ProgramBBClusterInfo.try_emplace(Aliases.front()).first;
441       CurrentCluster = 0;
442       FuncBBIDs.clear();
443     }
444   }
445   return Error::success();
446 }
447 
448 bool BasicBlockSections::doInitialization(Module &M) {
449   if (!MBuf)
450     return false;
451   if (auto Err = getBBClusterInfo(MBuf, ProgramBBClusterInfo, FuncAliasMap))
452     report_fatal_error(std::move(Err));
453   return false;
454 }
455 
456 void BasicBlockSections::getAnalysisUsage(AnalysisUsage &AU) const {
457   AU.setPreservesAll();
458   MachineFunctionPass::getAnalysisUsage(AU);
459 }
460 
461 MachineFunctionPass *
462 llvm::createBasicBlockSectionsPass(const MemoryBuffer *Buf) {
463   return new BasicBlockSections(Buf);
464 }
465