1dff0c46cSDimitry Andric //===-- MachineBlockPlacement.cpp - Basic Block Code Layout optimization --===//
2dff0c46cSDimitry Andric //
3dff0c46cSDimitry Andric //                     The LLVM Compiler Infrastructure
4dff0c46cSDimitry Andric //
5dff0c46cSDimitry Andric // This file is distributed under the University of Illinois Open Source
6dff0c46cSDimitry Andric // License. See LICENSE.TXT for details.
7dff0c46cSDimitry Andric //
8dff0c46cSDimitry Andric //===----------------------------------------------------------------------===//
9dff0c46cSDimitry Andric //
10dff0c46cSDimitry Andric // This file implements basic block placement transformations using the CFG
11dff0c46cSDimitry Andric // structure and branch probability estimates.
12dff0c46cSDimitry Andric //
13dff0c46cSDimitry Andric // The pass strives to preserve the structure of the CFG (that is, retain
147ae0e2c9SDimitry Andric // a topological ordering of basic blocks) in the absence of a *strong* signal
15dff0c46cSDimitry Andric // to the contrary from probabilities. However, within the CFG structure, it
16dff0c46cSDimitry Andric // attempts to choose an ordering which favors placing more likely sequences of
17dff0c46cSDimitry Andric // blocks adjacent to each other.
18dff0c46cSDimitry Andric //
19dff0c46cSDimitry Andric // The algorithm works from the inner-most loop within a function outward, and
20dff0c46cSDimitry Andric // at each stage walks through the basic blocks, trying to coalesce them into
21dff0c46cSDimitry Andric // sequential chains where allowed by the CFG (or demanded by heavy
22dff0c46cSDimitry Andric // probabilities). Finally, it walks the blocks in topological order, and the
23dff0c46cSDimitry Andric // first time it reaches a chain of basic blocks, it schedules them in the
24dff0c46cSDimitry Andric // function in-order.
25dff0c46cSDimitry Andric //
26dff0c46cSDimitry Andric //===----------------------------------------------------------------------===//
27dff0c46cSDimitry Andric 
28139f7f9bSDimitry Andric #include "llvm/CodeGen/Passes.h"
29139f7f9bSDimitry Andric #include "llvm/ADT/DenseMap.h"
30139f7f9bSDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
31139f7f9bSDimitry Andric #include "llvm/ADT/SmallVector.h"
32139f7f9bSDimitry Andric #include "llvm/ADT/Statistic.h"
33dff0c46cSDimitry Andric #include "llvm/CodeGen/MachineBasicBlock.h"
34dff0c46cSDimitry Andric #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
35dff0c46cSDimitry Andric #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
36ff0cc061SDimitry Andric #include "llvm/CodeGen/MachineDominators.h"
37dff0c46cSDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
38dff0c46cSDimitry Andric #include "llvm/CodeGen/MachineFunctionPass.h"
39dff0c46cSDimitry Andric #include "llvm/CodeGen/MachineLoopInfo.h"
40dff0c46cSDimitry Andric #include "llvm/CodeGen/MachineModuleInfo.h"
41dff0c46cSDimitry Andric #include "llvm/Support/Allocator.h"
42284c1978SDimitry Andric #include "llvm/Support/CommandLine.h"
43dff0c46cSDimitry Andric #include "llvm/Support/Debug.h"
44ff0cc061SDimitry Andric #include "llvm/Support/raw_ostream.h"
45dff0c46cSDimitry Andric #include "llvm/Target/TargetInstrInfo.h"
46dff0c46cSDimitry Andric #include "llvm/Target/TargetLowering.h"
4739d628a0SDimitry Andric #include "llvm/Target/TargetSubtargetInfo.h"
48dff0c46cSDimitry Andric #include <algorithm>
49dff0c46cSDimitry Andric using namespace llvm;
50dff0c46cSDimitry Andric 
51ff0cc061SDimitry Andric #define DEBUG_TYPE "block-placement"
5291bc56edSDimitry Andric 
53dff0c46cSDimitry Andric STATISTIC(NumCondBranches, "Number of conditional branches");
54dff0c46cSDimitry Andric STATISTIC(NumUncondBranches, "Number of uncondittional branches");
55dff0c46cSDimitry Andric STATISTIC(CondBranchTakenFreq,
56dff0c46cSDimitry Andric           "Potential frequency of taking conditional branches");
57dff0c46cSDimitry Andric STATISTIC(UncondBranchTakenFreq,
58dff0c46cSDimitry Andric           "Potential frequency of taking unconditional branches");
59dff0c46cSDimitry Andric 
60284c1978SDimitry Andric static cl::opt<unsigned> AlignAllBlock("align-all-blocks",
61284c1978SDimitry Andric                                        cl::desc("Force the alignment of all "
62284c1978SDimitry Andric                                                 "blocks in the function."),
63284c1978SDimitry Andric                                        cl::init(0), cl::Hidden);
64284c1978SDimitry Andric 
6591bc56edSDimitry Andric // FIXME: Find a good default for this flag and remove the flag.
66ff0cc061SDimitry Andric static cl::opt<unsigned> ExitBlockBias(
67ff0cc061SDimitry Andric     "block-placement-exit-block-bias",
6891bc56edSDimitry Andric     cl::desc("Block frequency percentage a loop exit block needs "
6991bc56edSDimitry Andric              "over the original exit to be considered the new exit."),
7091bc56edSDimitry Andric     cl::init(0), cl::Hidden);
7191bc56edSDimitry Andric 
72ff0cc061SDimitry Andric static cl::opt<bool> OutlineOptionalBranches(
73ff0cc061SDimitry Andric     "outline-optional-branches",
74ff0cc061SDimitry Andric     cl::desc("Put completely optional branches, i.e. branches with a common "
75ff0cc061SDimitry Andric              "post dominator, out of line."),
76ff0cc061SDimitry Andric     cl::init(false), cl::Hidden);
77ff0cc061SDimitry Andric 
78ff0cc061SDimitry Andric static cl::opt<unsigned> OutlineOptionalThreshold(
79ff0cc061SDimitry Andric     "outline-optional-threshold",
80ff0cc061SDimitry Andric     cl::desc("Don't outline optional branches that are a single block with an "
81ff0cc061SDimitry Andric              "instruction count below this threshold"),
82ff0cc061SDimitry Andric     cl::init(4), cl::Hidden);
83ff0cc061SDimitry Andric 
84dff0c46cSDimitry Andric namespace {
85dff0c46cSDimitry Andric class BlockChain;
86dff0c46cSDimitry Andric /// \brief Type for our function-wide basic block -> block chain mapping.
87dff0c46cSDimitry Andric typedef DenseMap<MachineBasicBlock *, BlockChain *> BlockToChainMapType;
88dff0c46cSDimitry Andric }
89dff0c46cSDimitry Andric 
90dff0c46cSDimitry Andric namespace {
91dff0c46cSDimitry Andric /// \brief A chain of blocks which will be laid out contiguously.
92dff0c46cSDimitry Andric ///
93dff0c46cSDimitry Andric /// This is the datastructure representing a chain of consecutive blocks that
94dff0c46cSDimitry Andric /// are profitable to layout together in order to maximize fallthrough
957ae0e2c9SDimitry Andric /// probabilities and code locality. We also can use a block chain to represent
967ae0e2c9SDimitry Andric /// a sequence of basic blocks which have some external (correctness)
977ae0e2c9SDimitry Andric /// requirement for sequential layout.
98dff0c46cSDimitry Andric ///
997ae0e2c9SDimitry Andric /// Chains can be built around a single basic block and can be merged to grow
1007ae0e2c9SDimitry Andric /// them. They participate in a block-to-chain mapping, which is updated
1017ae0e2c9SDimitry Andric /// automatically as chains are merged together.
102dff0c46cSDimitry Andric class BlockChain {
103dff0c46cSDimitry Andric   /// \brief The sequence of blocks belonging to this chain.
104dff0c46cSDimitry Andric   ///
105dff0c46cSDimitry Andric   /// This is the sequence of blocks for a particular chain. These will be laid
106dff0c46cSDimitry Andric   /// out in-order within the function.
107dff0c46cSDimitry Andric   SmallVector<MachineBasicBlock *, 4> Blocks;
108dff0c46cSDimitry Andric 
109dff0c46cSDimitry Andric   /// \brief A handle to the function-wide basic block to block chain mapping.
110dff0c46cSDimitry Andric   ///
111dff0c46cSDimitry Andric   /// This is retained in each block chain to simplify the computation of child
112dff0c46cSDimitry Andric   /// block chains for SCC-formation and iteration. We store the edges to child
113dff0c46cSDimitry Andric   /// basic blocks, and map them back to their associated chains using this
114dff0c46cSDimitry Andric   /// structure.
115dff0c46cSDimitry Andric   BlockToChainMapType &BlockToChain;
116dff0c46cSDimitry Andric 
117dff0c46cSDimitry Andric public:
118dff0c46cSDimitry Andric   /// \brief Construct a new BlockChain.
119dff0c46cSDimitry Andric   ///
120dff0c46cSDimitry Andric   /// This builds a new block chain representing a single basic block in the
121dff0c46cSDimitry Andric   /// function. It also registers itself as the chain that block participates
122dff0c46cSDimitry Andric   /// in with the BlockToChain mapping.
123dff0c46cSDimitry Andric   BlockChain(BlockToChainMapType &BlockToChain, MachineBasicBlock *BB)
124dff0c46cSDimitry Andric       : Blocks(1, BB), BlockToChain(BlockToChain), LoopPredecessors(0) {
125dff0c46cSDimitry Andric     assert(BB && "Cannot create a chain with a null basic block");
126dff0c46cSDimitry Andric     BlockToChain[BB] = this;
127dff0c46cSDimitry Andric   }
128dff0c46cSDimitry Andric 
129dff0c46cSDimitry Andric   /// \brief Iterator over blocks within the chain.
130cb4dff85SDimitry Andric   typedef SmallVectorImpl<MachineBasicBlock *>::iterator iterator;
131dff0c46cSDimitry Andric 
132dff0c46cSDimitry Andric   /// \brief Beginning of blocks within the chain.
133cb4dff85SDimitry Andric   iterator begin() { return Blocks.begin(); }
134dff0c46cSDimitry Andric 
135dff0c46cSDimitry Andric   /// \brief End of blocks within the chain.
136cb4dff85SDimitry Andric   iterator end() { return Blocks.end(); }
137dff0c46cSDimitry Andric 
138dff0c46cSDimitry Andric   /// \brief Merge a block chain into this one.
139dff0c46cSDimitry Andric   ///
140dff0c46cSDimitry Andric   /// This routine merges a block chain into this one. It takes care of forming
141dff0c46cSDimitry Andric   /// a contiguous sequence of basic blocks, updating the edge list, and
142dff0c46cSDimitry Andric   /// updating the block -> chain mapping. It does not free or tear down the
143dff0c46cSDimitry Andric   /// old chain, but the old chain's block list is no longer valid.
144dff0c46cSDimitry Andric   void merge(MachineBasicBlock *BB, BlockChain *Chain) {
145dff0c46cSDimitry Andric     assert(BB);
146dff0c46cSDimitry Andric     assert(!Blocks.empty());
147dff0c46cSDimitry Andric 
148dff0c46cSDimitry Andric     // Fast path in case we don't have a chain already.
149dff0c46cSDimitry Andric     if (!Chain) {
150dff0c46cSDimitry Andric       assert(!BlockToChain[BB]);
151dff0c46cSDimitry Andric       Blocks.push_back(BB);
152dff0c46cSDimitry Andric       BlockToChain[BB] = this;
153dff0c46cSDimitry Andric       return;
154dff0c46cSDimitry Andric     }
155dff0c46cSDimitry Andric 
156dff0c46cSDimitry Andric     assert(BB == *Chain->begin());
157dff0c46cSDimitry Andric     assert(Chain->begin() != Chain->end());
158dff0c46cSDimitry Andric 
159dff0c46cSDimitry Andric     // Update the incoming blocks to point to this chain, and add them to the
160dff0c46cSDimitry Andric     // chain structure.
161ff0cc061SDimitry Andric     for (MachineBasicBlock *ChainBB : *Chain) {
162ff0cc061SDimitry Andric       Blocks.push_back(ChainBB);
163ff0cc061SDimitry Andric       assert(BlockToChain[ChainBB] == Chain && "Incoming blocks not in chain");
164ff0cc061SDimitry Andric       BlockToChain[ChainBB] = this;
165dff0c46cSDimitry Andric     }
166dff0c46cSDimitry Andric   }
167dff0c46cSDimitry Andric 
168dff0c46cSDimitry Andric #ifndef NDEBUG
169dff0c46cSDimitry Andric   /// \brief Dump the blocks in this chain.
17091bc56edSDimitry Andric   LLVM_DUMP_METHOD void dump() {
171ff0cc061SDimitry Andric     for (MachineBasicBlock *MBB : *this)
172ff0cc061SDimitry Andric       MBB->dump();
173dff0c46cSDimitry Andric   }
174dff0c46cSDimitry Andric #endif // NDEBUG
175dff0c46cSDimitry Andric 
176dff0c46cSDimitry Andric   /// \brief Count of predecessors within the loop currently being processed.
177dff0c46cSDimitry Andric   ///
178dff0c46cSDimitry Andric   /// This count is updated at each loop we process to represent the number of
179dff0c46cSDimitry Andric   /// in-loop predecessors of this chain.
180dff0c46cSDimitry Andric   unsigned LoopPredecessors;
181dff0c46cSDimitry Andric };
1823dac3a9bSDimitry Andric }
183dff0c46cSDimitry Andric 
184dff0c46cSDimitry Andric namespace {
185dff0c46cSDimitry Andric class MachineBlockPlacement : public MachineFunctionPass {
186dff0c46cSDimitry Andric   /// \brief A typedef for a block filter set.
187dff0c46cSDimitry Andric   typedef SmallPtrSet<MachineBasicBlock *, 16> BlockFilterSet;
188dff0c46cSDimitry Andric 
189dff0c46cSDimitry Andric   /// \brief A handle to the branch probability pass.
190dff0c46cSDimitry Andric   const MachineBranchProbabilityInfo *MBPI;
191dff0c46cSDimitry Andric 
192dff0c46cSDimitry Andric   /// \brief A handle to the function-wide block frequency pass.
193dff0c46cSDimitry Andric   const MachineBlockFrequencyInfo *MBFI;
194dff0c46cSDimitry Andric 
195dff0c46cSDimitry Andric   /// \brief A handle to the loop info.
196dff0c46cSDimitry Andric   const MachineLoopInfo *MLI;
197dff0c46cSDimitry Andric 
198dff0c46cSDimitry Andric   /// \brief A handle to the target's instruction info.
199dff0c46cSDimitry Andric   const TargetInstrInfo *TII;
200dff0c46cSDimitry Andric 
201dff0c46cSDimitry Andric   /// \brief A handle to the target's lowering info.
202139f7f9bSDimitry Andric   const TargetLoweringBase *TLI;
203dff0c46cSDimitry Andric 
204ff0cc061SDimitry Andric   /// \brief A handle to the post dominator tree.
205ff0cc061SDimitry Andric   MachineDominatorTree *MDT;
206ff0cc061SDimitry Andric 
207ff0cc061SDimitry Andric   /// \brief A set of blocks that are unavoidably execute, i.e. they dominate
208ff0cc061SDimitry Andric   /// all terminators of the MachineFunction.
209ff0cc061SDimitry Andric   SmallPtrSet<MachineBasicBlock *, 4> UnavoidableBlocks;
210ff0cc061SDimitry Andric 
211dff0c46cSDimitry Andric   /// \brief Allocator and owner of BlockChain structures.
212dff0c46cSDimitry Andric   ///
2137ae0e2c9SDimitry Andric   /// We build BlockChains lazily while processing the loop structure of
2147ae0e2c9SDimitry Andric   /// a function. To reduce malloc traffic, we allocate them using this
2157ae0e2c9SDimitry Andric   /// slab-like allocator, and destroy them after the pass completes. An
2167ae0e2c9SDimitry Andric   /// important guarantee is that this allocator produces stable pointers to
2177ae0e2c9SDimitry Andric   /// the chains.
218dff0c46cSDimitry Andric   SpecificBumpPtrAllocator<BlockChain> ChainAllocator;
219dff0c46cSDimitry Andric 
220dff0c46cSDimitry Andric   /// \brief Function wide BasicBlock to BlockChain mapping.
221dff0c46cSDimitry Andric   ///
222dff0c46cSDimitry Andric   /// This mapping allows efficiently moving from any given basic block to the
223dff0c46cSDimitry Andric   /// BlockChain it participates in, if any. We use it to, among other things,
224dff0c46cSDimitry Andric   /// allow implicitly defining edges between chains as the existing edges
225dff0c46cSDimitry Andric   /// between basic blocks.
226dff0c46cSDimitry Andric   DenseMap<MachineBasicBlock *, BlockChain *> BlockToChain;
227dff0c46cSDimitry Andric 
228ff0cc061SDimitry Andric   void markChainSuccessors(BlockChain &Chain, MachineBasicBlock *LoopHeaderBB,
229dff0c46cSDimitry Andric                            SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
23091bc56edSDimitry Andric                            const BlockFilterSet *BlockFilter = nullptr);
231dff0c46cSDimitry Andric   MachineBasicBlock *selectBestSuccessor(MachineBasicBlock *BB,
232dff0c46cSDimitry Andric                                          BlockChain &Chain,
233dff0c46cSDimitry Andric                                          const BlockFilterSet *BlockFilter);
234ff0cc061SDimitry Andric   MachineBasicBlock *
235ff0cc061SDimitry Andric   selectBestCandidateBlock(BlockChain &Chain,
236ff0cc061SDimitry Andric                            SmallVectorImpl<MachineBasicBlock *> &WorkList,
237dff0c46cSDimitry Andric                            const BlockFilterSet *BlockFilter);
238ff0cc061SDimitry Andric   MachineBasicBlock *
239ff0cc061SDimitry Andric   getFirstUnplacedBlock(MachineFunction &F, const BlockChain &PlacedChain,
240dff0c46cSDimitry Andric                         MachineFunction::iterator &PrevUnplacedBlockIt,
241dff0c46cSDimitry Andric                         const BlockFilterSet *BlockFilter);
242dff0c46cSDimitry Andric   void buildChain(MachineBasicBlock *BB, BlockChain &Chain,
243dff0c46cSDimitry Andric                   SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
24491bc56edSDimitry Andric                   const BlockFilterSet *BlockFilter = nullptr);
245cb4dff85SDimitry Andric   MachineBasicBlock *findBestLoopTop(MachineLoop &L,
246cb4dff85SDimitry Andric                                      const BlockFilterSet &LoopBlockSet);
247ff0cc061SDimitry Andric   MachineBasicBlock *findBestLoopExit(MachineFunction &F, MachineLoop &L,
248dff0c46cSDimitry Andric                                       const BlockFilterSet &LoopBlockSet);
249dff0c46cSDimitry Andric   void buildLoopChains(MachineFunction &F, MachineLoop &L);
250cb4dff85SDimitry Andric   void rotateLoop(BlockChain &LoopChain, MachineBasicBlock *ExitingBB,
251cb4dff85SDimitry Andric                   const BlockFilterSet &LoopBlockSet);
252dff0c46cSDimitry Andric   void buildCFGChains(MachineFunction &F);
253dff0c46cSDimitry Andric 
254dff0c46cSDimitry Andric public:
255dff0c46cSDimitry Andric   static char ID; // Pass identification, replacement for typeid
256dff0c46cSDimitry Andric   MachineBlockPlacement() : MachineFunctionPass(ID) {
257dff0c46cSDimitry Andric     initializeMachineBlockPlacementPass(*PassRegistry::getPassRegistry());
258dff0c46cSDimitry Andric   }
259dff0c46cSDimitry Andric 
26091bc56edSDimitry Andric   bool runOnMachineFunction(MachineFunction &F) override;
261dff0c46cSDimitry Andric 
26291bc56edSDimitry Andric   void getAnalysisUsage(AnalysisUsage &AU) const override {
263dff0c46cSDimitry Andric     AU.addRequired<MachineBranchProbabilityInfo>();
264dff0c46cSDimitry Andric     AU.addRequired<MachineBlockFrequencyInfo>();
265ff0cc061SDimitry Andric     AU.addRequired<MachineDominatorTree>();
266dff0c46cSDimitry Andric     AU.addRequired<MachineLoopInfo>();
267dff0c46cSDimitry Andric     MachineFunctionPass::getAnalysisUsage(AU);
268dff0c46cSDimitry Andric   }
269dff0c46cSDimitry Andric };
2703dac3a9bSDimitry Andric }
271dff0c46cSDimitry Andric 
272dff0c46cSDimitry Andric char MachineBlockPlacement::ID = 0;
273dff0c46cSDimitry Andric char &llvm::MachineBlockPlacementID = MachineBlockPlacement::ID;
274ff0cc061SDimitry Andric INITIALIZE_PASS_BEGIN(MachineBlockPlacement, "block-placement",
275dff0c46cSDimitry Andric                       "Branch Probability Basic Block Placement", false, false)
276dff0c46cSDimitry Andric INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
277dff0c46cSDimitry Andric INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
278ff0cc061SDimitry Andric INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
279dff0c46cSDimitry Andric INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
280ff0cc061SDimitry Andric INITIALIZE_PASS_END(MachineBlockPlacement, "block-placement",
281dff0c46cSDimitry Andric                     "Branch Probability Basic Block Placement", false, false)
282dff0c46cSDimitry Andric 
283dff0c46cSDimitry Andric #ifndef NDEBUG
284dff0c46cSDimitry Andric /// \brief Helper to print the name of a MBB.
285dff0c46cSDimitry Andric ///
286dff0c46cSDimitry Andric /// Only used by debug logging.
287dff0c46cSDimitry Andric static std::string getBlockName(MachineBasicBlock *BB) {
288dff0c46cSDimitry Andric   std::string Result;
289dff0c46cSDimitry Andric   raw_string_ostream OS(Result);
290ff0cc061SDimitry Andric   OS << "BB#" << BB->getNumber();
291ff0cc061SDimitry Andric   OS << " (derived from LLVM BB '" << BB->getName() << "')";
292dff0c46cSDimitry Andric   OS.flush();
293dff0c46cSDimitry Andric   return Result;
294dff0c46cSDimitry Andric }
295dff0c46cSDimitry Andric 
296dff0c46cSDimitry Andric /// \brief Helper to print the number of a MBB.
297dff0c46cSDimitry Andric ///
298dff0c46cSDimitry Andric /// Only used by debug logging.
299dff0c46cSDimitry Andric static std::string getBlockNum(MachineBasicBlock *BB) {
300dff0c46cSDimitry Andric   std::string Result;
301dff0c46cSDimitry Andric   raw_string_ostream OS(Result);
302dff0c46cSDimitry Andric   OS << "BB#" << BB->getNumber();
303dff0c46cSDimitry Andric   OS.flush();
304dff0c46cSDimitry Andric   return Result;
305dff0c46cSDimitry Andric }
306dff0c46cSDimitry Andric #endif
307dff0c46cSDimitry Andric 
308dff0c46cSDimitry Andric /// \brief Mark a chain's successors as having one fewer preds.
309dff0c46cSDimitry Andric ///
310dff0c46cSDimitry Andric /// When a chain is being merged into the "placed" chain, this routine will
311dff0c46cSDimitry Andric /// quickly walk the successors of each block in the chain and mark them as
312dff0c46cSDimitry Andric /// having one fewer active predecessor. It also adds any successors of this
313dff0c46cSDimitry Andric /// chain which reach the zero-predecessor state to the worklist passed in.
314dff0c46cSDimitry Andric void MachineBlockPlacement::markChainSuccessors(
315ff0cc061SDimitry Andric     BlockChain &Chain, MachineBasicBlock *LoopHeaderBB,
316dff0c46cSDimitry Andric     SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
317dff0c46cSDimitry Andric     const BlockFilterSet *BlockFilter) {
318dff0c46cSDimitry Andric   // Walk all the blocks in this chain, marking their successors as having
319dff0c46cSDimitry Andric   // a predecessor placed.
320ff0cc061SDimitry Andric   for (MachineBasicBlock *MBB : Chain) {
321dff0c46cSDimitry Andric     // Add any successors for which this is the only un-placed in-loop
322dff0c46cSDimitry Andric     // predecessor to the worklist as a viable candidate for CFG-neutral
323dff0c46cSDimitry Andric     // placement. No subsequent placement of this block will violate the CFG
324dff0c46cSDimitry Andric     // shape, so we get to use heuristics to choose a favorable placement.
325ff0cc061SDimitry Andric     for (MachineBasicBlock *Succ : MBB->successors()) {
326ff0cc061SDimitry Andric       if (BlockFilter && !BlockFilter->count(Succ))
327dff0c46cSDimitry Andric         continue;
328ff0cc061SDimitry Andric       BlockChain &SuccChain = *BlockToChain[Succ];
329dff0c46cSDimitry Andric       // Disregard edges within a fixed chain, or edges to the loop header.
330ff0cc061SDimitry Andric       if (&Chain == &SuccChain || Succ == LoopHeaderBB)
331dff0c46cSDimitry Andric         continue;
332dff0c46cSDimitry Andric 
333dff0c46cSDimitry Andric       // This is a cross-chain edge that is within the loop, so decrement the
334dff0c46cSDimitry Andric       // loop predecessor count of the destination chain.
335dff0c46cSDimitry Andric       if (SuccChain.LoopPredecessors > 0 && --SuccChain.LoopPredecessors == 0)
336dff0c46cSDimitry Andric         BlockWorkList.push_back(*SuccChain.begin());
337dff0c46cSDimitry Andric     }
338dff0c46cSDimitry Andric   }
339dff0c46cSDimitry Andric }
340dff0c46cSDimitry Andric 
341dff0c46cSDimitry Andric /// \brief Select the best successor for a block.
342dff0c46cSDimitry Andric ///
343dff0c46cSDimitry Andric /// This looks across all successors of a particular block and attempts to
344dff0c46cSDimitry Andric /// select the "best" one to be the layout successor. It only considers direct
345dff0c46cSDimitry Andric /// successors which also pass the block filter. It will attempt to avoid
346dff0c46cSDimitry Andric /// breaking CFG structure, but cave and break such structures in the case of
347dff0c46cSDimitry Andric /// very hot successor edges.
348dff0c46cSDimitry Andric ///
349dff0c46cSDimitry Andric /// \returns The best successor block found, or null if none are viable.
350ff0cc061SDimitry Andric MachineBasicBlock *
351ff0cc061SDimitry Andric MachineBlockPlacement::selectBestSuccessor(MachineBasicBlock *BB,
352ff0cc061SDimitry Andric                                            BlockChain &Chain,
353dff0c46cSDimitry Andric                                            const BlockFilterSet *BlockFilter) {
354dff0c46cSDimitry Andric   const BranchProbability HotProb(4, 5); // 80%
355dff0c46cSDimitry Andric 
35691bc56edSDimitry Andric   MachineBasicBlock *BestSucc = nullptr;
357dff0c46cSDimitry Andric   // FIXME: Due to the performance of the probability and weight routines in
358dff0c46cSDimitry Andric   // the MBPI analysis, we manually compute probabilities using the edge
359dff0c46cSDimitry Andric   // weights. This is suboptimal as it means that the somewhat subtle
360dff0c46cSDimitry Andric   // definition of edge weight semantics is encoded here as well. We should
3617ae0e2c9SDimitry Andric   // improve the MBPI interface to efficiently support query patterns such as
362dff0c46cSDimitry Andric   // this.
363dff0c46cSDimitry Andric   uint32_t BestWeight = 0;
364dff0c46cSDimitry Andric   uint32_t WeightScale = 0;
365dff0c46cSDimitry Andric   uint32_t SumWeight = MBPI->getSumForBlock(BB, WeightScale);
366dff0c46cSDimitry Andric   DEBUG(dbgs() << "Attempting merge from: " << getBlockName(BB) << "\n");
367ff0cc061SDimitry Andric   for (MachineBasicBlock *Succ : BB->successors()) {
368ff0cc061SDimitry Andric     if (BlockFilter && !BlockFilter->count(Succ))
369dff0c46cSDimitry Andric       continue;
370ff0cc061SDimitry Andric     BlockChain &SuccChain = *BlockToChain[Succ];
371dff0c46cSDimitry Andric     if (&SuccChain == &Chain) {
372ff0cc061SDimitry Andric       DEBUG(dbgs() << "    " << getBlockName(Succ) << " -> Already merged!\n");
373dff0c46cSDimitry Andric       continue;
374dff0c46cSDimitry Andric     }
375ff0cc061SDimitry Andric     if (Succ != *SuccChain.begin()) {
376ff0cc061SDimitry Andric       DEBUG(dbgs() << "    " << getBlockName(Succ) << " -> Mid chain!\n");
377dff0c46cSDimitry Andric       continue;
378dff0c46cSDimitry Andric     }
379dff0c46cSDimitry Andric 
380ff0cc061SDimitry Andric     uint32_t SuccWeight = MBPI->getEdgeWeight(BB, Succ);
381dff0c46cSDimitry Andric     BranchProbability SuccProb(SuccWeight / WeightScale, SumWeight);
382dff0c46cSDimitry Andric 
383ff0cc061SDimitry Andric     // If we outline optional branches, look whether Succ is unavoidable, i.e.
384ff0cc061SDimitry Andric     // dominates all terminators of the MachineFunction. If it does, other
385ff0cc061SDimitry Andric     // successors must be optional. Don't do this for cold branches.
386ff0cc061SDimitry Andric     if (OutlineOptionalBranches && SuccProb > HotProb.getCompl() &&
387ff0cc061SDimitry Andric         UnavoidableBlocks.count(Succ) > 0) {
388ff0cc061SDimitry Andric       auto HasShortOptionalBranch = [&]() {
389ff0cc061SDimitry Andric         for (MachineBasicBlock *Pred : Succ->predecessors()) {
390ff0cc061SDimitry Andric           // Check whether there is an unplaced optional branch.
391ff0cc061SDimitry Andric           if (Pred == Succ || (BlockFilter && !BlockFilter->count(Pred)) ||
392ff0cc061SDimitry Andric               BlockToChain[Pred] == &Chain)
393ff0cc061SDimitry Andric             continue;
394ff0cc061SDimitry Andric           // Check whether the optional branch has exactly one BB.
395ff0cc061SDimitry Andric           if (Pred->pred_size() > 1 || *Pred->pred_begin() != BB)
396ff0cc061SDimitry Andric             continue;
397ff0cc061SDimitry Andric           // Check whether the optional branch is small.
398ff0cc061SDimitry Andric           if (Pred->size() < OutlineOptionalThreshold)
399ff0cc061SDimitry Andric             return true;
400ff0cc061SDimitry Andric         }
401ff0cc061SDimitry Andric         return false;
402ff0cc061SDimitry Andric       };
403ff0cc061SDimitry Andric       if (!HasShortOptionalBranch())
404ff0cc061SDimitry Andric         return Succ;
405ff0cc061SDimitry Andric     }
406ff0cc061SDimitry Andric 
407dff0c46cSDimitry Andric     // Only consider successors which are either "hot", or wouldn't violate
408dff0c46cSDimitry Andric     // any CFG constraints.
409dff0c46cSDimitry Andric     if (SuccChain.LoopPredecessors != 0) {
410dff0c46cSDimitry Andric       if (SuccProb < HotProb) {
411ff0cc061SDimitry Andric         DEBUG(dbgs() << "    " << getBlockName(Succ) << " -> " << SuccProb
41291bc56edSDimitry Andric                      << " (prob) (CFG conflict)\n");
413dff0c46cSDimitry Andric         continue;
414dff0c46cSDimitry Andric       }
415dff0c46cSDimitry Andric 
416ff0cc061SDimitry Andric       // Make sure that a hot successor doesn't have a globally more
417ff0cc061SDimitry Andric       // important predecessor.
418ff0cc061SDimitry Andric       BlockFrequency CandidateEdgeFreq =
419ff0cc061SDimitry Andric           MBFI->getBlockFreq(BB) * SuccProb * HotProb.getCompl();
420dff0c46cSDimitry Andric       bool BadCFGConflict = false;
421ff0cc061SDimitry Andric       for (MachineBasicBlock *Pred : Succ->predecessors()) {
422ff0cc061SDimitry Andric         if (Pred == Succ || (BlockFilter && !BlockFilter->count(Pred)) ||
423ff0cc061SDimitry Andric             BlockToChain[Pred] == &Chain)
424dff0c46cSDimitry Andric           continue;
425ff0cc061SDimitry Andric         BlockFrequency PredEdgeFreq =
426ff0cc061SDimitry Andric             MBFI->getBlockFreq(Pred) * MBPI->getEdgeProbability(Pred, Succ);
427dff0c46cSDimitry Andric         if (PredEdgeFreq >= CandidateEdgeFreq) {
428dff0c46cSDimitry Andric           BadCFGConflict = true;
429dff0c46cSDimitry Andric           break;
430dff0c46cSDimitry Andric         }
431dff0c46cSDimitry Andric       }
432dff0c46cSDimitry Andric       if (BadCFGConflict) {
433ff0cc061SDimitry Andric         DEBUG(dbgs() << "    " << getBlockName(Succ) << " -> " << SuccProb
43491bc56edSDimitry Andric                      << " (prob) (non-cold CFG conflict)\n");
435dff0c46cSDimitry Andric         continue;
436dff0c46cSDimitry Andric       }
437dff0c46cSDimitry Andric     }
438dff0c46cSDimitry Andric 
439ff0cc061SDimitry Andric     DEBUG(dbgs() << "    " << getBlockName(Succ) << " -> " << SuccProb
440dff0c46cSDimitry Andric                  << " (prob)"
441dff0c46cSDimitry Andric                  << (SuccChain.LoopPredecessors != 0 ? " (CFG break)" : "")
442dff0c46cSDimitry Andric                  << "\n");
443dff0c46cSDimitry Andric     if (BestSucc && BestWeight >= SuccWeight)
444dff0c46cSDimitry Andric       continue;
445ff0cc061SDimitry Andric     BestSucc = Succ;
446dff0c46cSDimitry Andric     BestWeight = SuccWeight;
447dff0c46cSDimitry Andric   }
448dff0c46cSDimitry Andric   return BestSucc;
449dff0c46cSDimitry Andric }
450dff0c46cSDimitry Andric 
451dff0c46cSDimitry Andric /// \brief Select the best block from a worklist.
452dff0c46cSDimitry Andric ///
453dff0c46cSDimitry Andric /// This looks through the provided worklist as a list of candidate basic
454dff0c46cSDimitry Andric /// blocks and select the most profitable one to place. The definition of
455dff0c46cSDimitry Andric /// profitable only really makes sense in the context of a loop. This returns
456dff0c46cSDimitry Andric /// the most frequently visited block in the worklist, which in the case of
457dff0c46cSDimitry Andric /// a loop, is the one most desirable to be physically close to the rest of the
458dff0c46cSDimitry Andric /// loop body in order to improve icache behavior.
459dff0c46cSDimitry Andric ///
460dff0c46cSDimitry Andric /// \returns The best block found, or null if none are viable.
461dff0c46cSDimitry Andric MachineBasicBlock *MachineBlockPlacement::selectBestCandidateBlock(
462dff0c46cSDimitry Andric     BlockChain &Chain, SmallVectorImpl<MachineBasicBlock *> &WorkList,
463dff0c46cSDimitry Andric     const BlockFilterSet *BlockFilter) {
464dff0c46cSDimitry Andric   // Once we need to walk the worklist looking for a candidate, cleanup the
465dff0c46cSDimitry Andric   // worklist of already placed entries.
466dff0c46cSDimitry Andric   // FIXME: If this shows up on profiles, it could be folded (at the cost of
467dff0c46cSDimitry Andric   // some code complexity) into the loop below.
468dff0c46cSDimitry Andric   WorkList.erase(std::remove_if(WorkList.begin(), WorkList.end(),
46991bc56edSDimitry Andric                                 [&](MachineBasicBlock *BB) {
47091bc56edSDimitry Andric                                   return BlockToChain.lookup(BB) == &Chain;
47191bc56edSDimitry Andric                                 }),
472dff0c46cSDimitry Andric                  WorkList.end());
473dff0c46cSDimitry Andric 
47491bc56edSDimitry Andric   MachineBasicBlock *BestBlock = nullptr;
475dff0c46cSDimitry Andric   BlockFrequency BestFreq;
476ff0cc061SDimitry Andric   for (MachineBasicBlock *MBB : WorkList) {
477ff0cc061SDimitry Andric     BlockChain &SuccChain = *BlockToChain[MBB];
478dff0c46cSDimitry Andric     if (&SuccChain == &Chain) {
479ff0cc061SDimitry Andric       DEBUG(dbgs() << "    " << getBlockName(MBB) << " -> Already merged!\n");
480dff0c46cSDimitry Andric       continue;
481dff0c46cSDimitry Andric     }
482dff0c46cSDimitry Andric     assert(SuccChain.LoopPredecessors == 0 && "Found CFG-violating block");
483dff0c46cSDimitry Andric 
484ff0cc061SDimitry Andric     BlockFrequency CandidateFreq = MBFI->getBlockFreq(MBB);
485ff0cc061SDimitry Andric     DEBUG(dbgs() << "    " << getBlockName(MBB) << " -> ";
48691bc56edSDimitry Andric           MBFI->printBlockFreq(dbgs(), CandidateFreq) << " (freq)\n");
487dff0c46cSDimitry Andric     if (BestBlock && BestFreq >= CandidateFreq)
488dff0c46cSDimitry Andric       continue;
489ff0cc061SDimitry Andric     BestBlock = MBB;
490dff0c46cSDimitry Andric     BestFreq = CandidateFreq;
491dff0c46cSDimitry Andric   }
492dff0c46cSDimitry Andric   return BestBlock;
493dff0c46cSDimitry Andric }
494dff0c46cSDimitry Andric 
495dff0c46cSDimitry Andric /// \brief Retrieve the first unplaced basic block.
496dff0c46cSDimitry Andric ///
497dff0c46cSDimitry Andric /// This routine is called when we are unable to use the CFG to walk through
498dff0c46cSDimitry Andric /// all of the basic blocks and form a chain due to unnatural loops in the CFG.
499dff0c46cSDimitry Andric /// We walk through the function's blocks in order, starting from the
500dff0c46cSDimitry Andric /// LastUnplacedBlockIt. We update this iterator on each call to avoid
501dff0c46cSDimitry Andric /// re-scanning the entire sequence on repeated calls to this routine.
502dff0c46cSDimitry Andric MachineBasicBlock *MachineBlockPlacement::getFirstUnplacedBlock(
503dff0c46cSDimitry Andric     MachineFunction &F, const BlockChain &PlacedChain,
504dff0c46cSDimitry Andric     MachineFunction::iterator &PrevUnplacedBlockIt,
505dff0c46cSDimitry Andric     const BlockFilterSet *BlockFilter) {
506dff0c46cSDimitry Andric   for (MachineFunction::iterator I = PrevUnplacedBlockIt, E = F.end(); I != E;
507dff0c46cSDimitry Andric        ++I) {
508dff0c46cSDimitry Andric     if (BlockFilter && !BlockFilter->count(I))
509dff0c46cSDimitry Andric       continue;
510dff0c46cSDimitry Andric     if (BlockToChain[I] != &PlacedChain) {
511dff0c46cSDimitry Andric       PrevUnplacedBlockIt = I;
512dff0c46cSDimitry Andric       // Now select the head of the chain to which the unplaced block belongs
513dff0c46cSDimitry Andric       // as the block to place. This will force the entire chain to be placed,
514dff0c46cSDimitry Andric       // and satisfies the requirements of merging chains.
515dff0c46cSDimitry Andric       return *BlockToChain[I]->begin();
516dff0c46cSDimitry Andric     }
517dff0c46cSDimitry Andric   }
51891bc56edSDimitry Andric   return nullptr;
519dff0c46cSDimitry Andric }
520dff0c46cSDimitry Andric 
521dff0c46cSDimitry Andric void MachineBlockPlacement::buildChain(
522ff0cc061SDimitry Andric     MachineBasicBlock *BB, BlockChain &Chain,
523dff0c46cSDimitry Andric     SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
524dff0c46cSDimitry Andric     const BlockFilterSet *BlockFilter) {
525dff0c46cSDimitry Andric   assert(BB);
526dff0c46cSDimitry Andric   assert(BlockToChain[BB] == &Chain);
527dff0c46cSDimitry Andric   MachineFunction &F = *BB->getParent();
528dff0c46cSDimitry Andric   MachineFunction::iterator PrevUnplacedBlockIt = F.begin();
529dff0c46cSDimitry Andric 
530dff0c46cSDimitry Andric   MachineBasicBlock *LoopHeaderBB = BB;
531dff0c46cSDimitry Andric   markChainSuccessors(Chain, LoopHeaderBB, BlockWorkList, BlockFilter);
53291bc56edSDimitry Andric   BB = *std::prev(Chain.end());
533dff0c46cSDimitry Andric   for (;;) {
534dff0c46cSDimitry Andric     assert(BB);
535dff0c46cSDimitry Andric     assert(BlockToChain[BB] == &Chain);
53691bc56edSDimitry Andric     assert(*std::prev(Chain.end()) == BB);
537dff0c46cSDimitry Andric 
538dff0c46cSDimitry Andric     // Look for the best viable successor if there is one to place immediately
539dff0c46cSDimitry Andric     // after this block.
5403861d79fSDimitry Andric     MachineBasicBlock *BestSucc = selectBestSuccessor(BB, Chain, BlockFilter);
541dff0c46cSDimitry Andric 
542dff0c46cSDimitry Andric     // If an immediate successor isn't available, look for the best viable
543dff0c46cSDimitry Andric     // block among those we've identified as not violating the loop's CFG at
544dff0c46cSDimitry Andric     // this point. This won't be a fallthrough, but it will increase locality.
545dff0c46cSDimitry Andric     if (!BestSucc)
546dff0c46cSDimitry Andric       BestSucc = selectBestCandidateBlock(Chain, BlockWorkList, BlockFilter);
547dff0c46cSDimitry Andric 
548dff0c46cSDimitry Andric     if (!BestSucc) {
549ff0cc061SDimitry Andric       BestSucc =
550ff0cc061SDimitry Andric           getFirstUnplacedBlock(F, Chain, PrevUnplacedBlockIt, BlockFilter);
551dff0c46cSDimitry Andric       if (!BestSucc)
552dff0c46cSDimitry Andric         break;
553dff0c46cSDimitry Andric 
554dff0c46cSDimitry Andric       DEBUG(dbgs() << "Unnatural loop CFG detected, forcibly merging the "
555dff0c46cSDimitry Andric                       "layout successor until the CFG reduces\n");
556dff0c46cSDimitry Andric     }
557dff0c46cSDimitry Andric 
558dff0c46cSDimitry Andric     // Place this block, updating the datastructures to reflect its placement.
559dff0c46cSDimitry Andric     BlockChain &SuccChain = *BlockToChain[BestSucc];
560dff0c46cSDimitry Andric     // Zero out LoopPredecessors for the successor we're about to merge in case
561dff0c46cSDimitry Andric     // we selected a successor that didn't fit naturally into the CFG.
562dff0c46cSDimitry Andric     SuccChain.LoopPredecessors = 0;
563ff0cc061SDimitry Andric     DEBUG(dbgs() << "Merging from " << getBlockNum(BB) << " to "
564ff0cc061SDimitry Andric                  << getBlockNum(BestSucc) << "\n");
565dff0c46cSDimitry Andric     markChainSuccessors(SuccChain, LoopHeaderBB, BlockWorkList, BlockFilter);
566dff0c46cSDimitry Andric     Chain.merge(BestSucc, &SuccChain);
56791bc56edSDimitry Andric     BB = *std::prev(Chain.end());
568dff0c46cSDimitry Andric   }
569dff0c46cSDimitry Andric 
570dff0c46cSDimitry Andric   DEBUG(dbgs() << "Finished forming chain for header block "
571dff0c46cSDimitry Andric                << getBlockNum(*Chain.begin()) << "\n");
572dff0c46cSDimitry Andric }
573dff0c46cSDimitry Andric 
574dff0c46cSDimitry Andric /// \brief Find the best loop top block for layout.
575dff0c46cSDimitry Andric ///
576cb4dff85SDimitry Andric /// Look for a block which is strictly better than the loop header for laying
577cb4dff85SDimitry Andric /// out at the top of the loop. This looks for one and only one pattern:
578cb4dff85SDimitry Andric /// a latch block with no conditional exit. This block will cause a conditional
579cb4dff85SDimitry Andric /// jump around it or will be the bottom of the loop if we lay it out in place,
580cb4dff85SDimitry Andric /// but if it it doesn't end up at the bottom of the loop for any reason,
581cb4dff85SDimitry Andric /// rotation alone won't fix it. Because such a block will always result in an
582cb4dff85SDimitry Andric /// unconditional jump (for the backedge) rotating it in front of the loop
583cb4dff85SDimitry Andric /// header is always profitable.
584cb4dff85SDimitry Andric MachineBasicBlock *
585cb4dff85SDimitry Andric MachineBlockPlacement::findBestLoopTop(MachineLoop &L,
586cb4dff85SDimitry Andric                                        const BlockFilterSet &LoopBlockSet) {
587cb4dff85SDimitry Andric   // Check that the header hasn't been fused with a preheader block due to
588cb4dff85SDimitry Andric   // crazy branches. If it has, we need to start with the header at the top to
589cb4dff85SDimitry Andric   // prevent pulling the preheader into the loop body.
590cb4dff85SDimitry Andric   BlockChain &HeaderChain = *BlockToChain[L.getHeader()];
591cb4dff85SDimitry Andric   if (!LoopBlockSet.count(*HeaderChain.begin()))
592cb4dff85SDimitry Andric     return L.getHeader();
593cb4dff85SDimitry Andric 
594ff0cc061SDimitry Andric   DEBUG(dbgs() << "Finding best loop top for: " << getBlockName(L.getHeader())
595ff0cc061SDimitry Andric                << "\n");
596cb4dff85SDimitry Andric 
597cb4dff85SDimitry Andric   BlockFrequency BestPredFreq;
59891bc56edSDimitry Andric   MachineBasicBlock *BestPred = nullptr;
599ff0cc061SDimitry Andric   for (MachineBasicBlock *Pred : L.getHeader()->predecessors()) {
600cb4dff85SDimitry Andric     if (!LoopBlockSet.count(Pred))
601cb4dff85SDimitry Andric       continue;
602cb4dff85SDimitry Andric     DEBUG(dbgs() << "    header pred: " << getBlockName(Pred) << ", "
60391bc56edSDimitry Andric                  << Pred->succ_size() << " successors, ";
60491bc56edSDimitry Andric           MBFI->printBlockFreq(dbgs(), Pred) << " freq\n");
605cb4dff85SDimitry Andric     if (Pred->succ_size() > 1)
606cb4dff85SDimitry Andric       continue;
607cb4dff85SDimitry Andric 
608cb4dff85SDimitry Andric     BlockFrequency PredFreq = MBFI->getBlockFreq(Pred);
609cb4dff85SDimitry Andric     if (!BestPred || PredFreq > BestPredFreq ||
610cb4dff85SDimitry Andric         (!(PredFreq < BestPredFreq) &&
611cb4dff85SDimitry Andric          Pred->isLayoutSuccessor(L.getHeader()))) {
612cb4dff85SDimitry Andric       BestPred = Pred;
613cb4dff85SDimitry Andric       BestPredFreq = PredFreq;
614cb4dff85SDimitry Andric     }
615cb4dff85SDimitry Andric   }
616cb4dff85SDimitry Andric 
617cb4dff85SDimitry Andric   // If no direct predecessor is fine, just use the loop header.
618cb4dff85SDimitry Andric   if (!BestPred)
619cb4dff85SDimitry Andric     return L.getHeader();
620cb4dff85SDimitry Andric 
621cb4dff85SDimitry Andric   // Walk backwards through any straight line of predecessors.
622cb4dff85SDimitry Andric   while (BestPred->pred_size() == 1 &&
623cb4dff85SDimitry Andric          (*BestPred->pred_begin())->succ_size() == 1 &&
624cb4dff85SDimitry Andric          *BestPred->pred_begin() != L.getHeader())
625cb4dff85SDimitry Andric     BestPred = *BestPred->pred_begin();
626cb4dff85SDimitry Andric 
627cb4dff85SDimitry Andric   DEBUG(dbgs() << "    final top: " << getBlockName(BestPred) << "\n");
628cb4dff85SDimitry Andric   return BestPred;
629cb4dff85SDimitry Andric }
630cb4dff85SDimitry Andric 
631cb4dff85SDimitry Andric /// \brief Find the best loop exiting block for layout.
632cb4dff85SDimitry Andric ///
633dff0c46cSDimitry Andric /// This routine implements the logic to analyze the loop looking for the best
634dff0c46cSDimitry Andric /// block to layout at the top of the loop. Typically this is done to maximize
635dff0c46cSDimitry Andric /// fallthrough opportunities.
636dff0c46cSDimitry Andric MachineBasicBlock *
637ff0cc061SDimitry Andric MachineBlockPlacement::findBestLoopExit(MachineFunction &F, MachineLoop &L,
638dff0c46cSDimitry Andric                                         const BlockFilterSet &LoopBlockSet) {
639dff0c46cSDimitry Andric   // We don't want to layout the loop linearly in all cases. If the loop header
640dff0c46cSDimitry Andric   // is just a normal basic block in the loop, we want to look for what block
641dff0c46cSDimitry Andric   // within the loop is the best one to layout at the top. However, if the loop
642dff0c46cSDimitry Andric   // header has be pre-merged into a chain due to predecessors not having
643dff0c46cSDimitry Andric   // analyzable branches, *and* the predecessor it is merged with is *not* part
644dff0c46cSDimitry Andric   // of the loop, rotating the header into the middle of the loop will create
645dff0c46cSDimitry Andric   // a non-contiguous range of blocks which is Very Bad. So start with the
646dff0c46cSDimitry Andric   // header and only rotate if safe.
647dff0c46cSDimitry Andric   BlockChain &HeaderChain = *BlockToChain[L.getHeader()];
648dff0c46cSDimitry Andric   if (!LoopBlockSet.count(*HeaderChain.begin()))
64991bc56edSDimitry Andric     return nullptr;
650dff0c46cSDimitry Andric 
651dff0c46cSDimitry Andric   BlockFrequency BestExitEdgeFreq;
652cb4dff85SDimitry Andric   unsigned BestExitLoopDepth = 0;
65391bc56edSDimitry Andric   MachineBasicBlock *ExitingBB = nullptr;
654dff0c46cSDimitry Andric   // If there are exits to outer loops, loop rotation can severely limit
655dff0c46cSDimitry Andric   // fallthrough opportunites unless it selects such an exit. Keep a set of
656dff0c46cSDimitry Andric   // blocks where rotating to exit with that block will reach an outer loop.
657dff0c46cSDimitry Andric   SmallPtrSet<MachineBasicBlock *, 4> BlocksExitingToOuterLoop;
658dff0c46cSDimitry Andric 
659ff0cc061SDimitry Andric   DEBUG(dbgs() << "Finding best loop exit for: " << getBlockName(L.getHeader())
660ff0cc061SDimitry Andric                << "\n");
661ff0cc061SDimitry Andric   for (MachineBasicBlock *MBB : L.getBlocks()) {
662ff0cc061SDimitry Andric     BlockChain &Chain = *BlockToChain[MBB];
663dff0c46cSDimitry Andric     // Ensure that this block is at the end of a chain; otherwise it could be
664ff0cc061SDimitry Andric     // mid-way through an inner loop or a successor of an unanalyzable branch.
665ff0cc061SDimitry Andric     if (MBB != *std::prev(Chain.end()))
666dff0c46cSDimitry Andric       continue;
667dff0c46cSDimitry Andric 
668dff0c46cSDimitry Andric     // Now walk the successors. We need to establish whether this has a viable
669dff0c46cSDimitry Andric     // exiting successor and whether it has a viable non-exiting successor.
670dff0c46cSDimitry Andric     // We store the old exiting state and restore it if a viable looping
671dff0c46cSDimitry Andric     // successor isn't found.
672dff0c46cSDimitry Andric     MachineBasicBlock *OldExitingBB = ExitingBB;
673dff0c46cSDimitry Andric     BlockFrequency OldBestExitEdgeFreq = BestExitEdgeFreq;
674cb4dff85SDimitry Andric     bool HasLoopingSucc = false;
675dff0c46cSDimitry Andric     // FIXME: Due to the performance of the probability and weight routines in
676cb4dff85SDimitry Andric     // the MBPI analysis, we use the internal weights and manually compute the
677cb4dff85SDimitry Andric     // probabilities to avoid quadratic behavior.
678dff0c46cSDimitry Andric     uint32_t WeightScale = 0;
679ff0cc061SDimitry Andric     uint32_t SumWeight = MBPI->getSumForBlock(MBB, WeightScale);
680ff0cc061SDimitry Andric     for (MachineBasicBlock *Succ : MBB->successors()) {
681ff0cc061SDimitry Andric       if (Succ->isLandingPad())
682dff0c46cSDimitry Andric         continue;
683ff0cc061SDimitry Andric       if (Succ == MBB)
684dff0c46cSDimitry Andric         continue;
685ff0cc061SDimitry Andric       BlockChain &SuccChain = *BlockToChain[Succ];
686dff0c46cSDimitry Andric       // Don't split chains, either this chain or the successor's chain.
687cb4dff85SDimitry Andric       if (&Chain == &SuccChain) {
688ff0cc061SDimitry Andric         DEBUG(dbgs() << "    exiting: " << getBlockName(MBB) << " -> "
689ff0cc061SDimitry Andric                      << getBlockName(Succ) << " (chain conflict)\n");
690dff0c46cSDimitry Andric         continue;
691dff0c46cSDimitry Andric       }
692dff0c46cSDimitry Andric 
693ff0cc061SDimitry Andric       uint32_t SuccWeight = MBPI->getEdgeWeight(MBB, Succ);
694ff0cc061SDimitry Andric       if (LoopBlockSet.count(Succ)) {
695ff0cc061SDimitry Andric         DEBUG(dbgs() << "    looping: " << getBlockName(MBB) << " -> "
696ff0cc061SDimitry Andric                      << getBlockName(Succ) << " (" << SuccWeight << ")\n");
697cb4dff85SDimitry Andric         HasLoopingSucc = true;
698dff0c46cSDimitry Andric         continue;
699cb4dff85SDimitry Andric       }
700dff0c46cSDimitry Andric 
701cb4dff85SDimitry Andric       unsigned SuccLoopDepth = 0;
702ff0cc061SDimitry Andric       if (MachineLoop *ExitLoop = MLI->getLoopFor(Succ)) {
703cb4dff85SDimitry Andric         SuccLoopDepth = ExitLoop->getLoopDepth();
704cb4dff85SDimitry Andric         if (ExitLoop->contains(&L))
705ff0cc061SDimitry Andric           BlocksExitingToOuterLoop.insert(MBB);
706dff0c46cSDimitry Andric       }
707dff0c46cSDimitry Andric 
708dff0c46cSDimitry Andric       BranchProbability SuccProb(SuccWeight / WeightScale, SumWeight);
709ff0cc061SDimitry Andric       BlockFrequency ExitEdgeFreq = MBFI->getBlockFreq(MBB) * SuccProb;
710ff0cc061SDimitry Andric       DEBUG(dbgs() << "    exiting: " << getBlockName(MBB) << " -> "
711ff0cc061SDimitry Andric                    << getBlockName(Succ) << " [L:" << SuccLoopDepth << "] (";
71291bc56edSDimitry Andric             MBFI->printBlockFreq(dbgs(), ExitEdgeFreq) << ")\n");
71391bc56edSDimitry Andric       // Note that we bias this toward an existing layout successor to retain
71491bc56edSDimitry Andric       // incoming order in the absence of better information. The exit must have
71591bc56edSDimitry Andric       // a frequency higher than the current exit before we consider breaking
71691bc56edSDimitry Andric       // the layout.
71791bc56edSDimitry Andric       BranchProbability Bias(100 - ExitBlockBias, 100);
718ff0cc061SDimitry Andric       if (!ExitingBB || SuccLoopDepth > BestExitLoopDepth ||
719cb4dff85SDimitry Andric           ExitEdgeFreq > BestExitEdgeFreq ||
720ff0cc061SDimitry Andric           (MBB->isLayoutSuccessor(Succ) &&
72191bc56edSDimitry Andric            !(ExitEdgeFreq < BestExitEdgeFreq * Bias))) {
722dff0c46cSDimitry Andric         BestExitEdgeFreq = ExitEdgeFreq;
723ff0cc061SDimitry Andric         ExitingBB = MBB;
724dff0c46cSDimitry Andric       }
725dff0c46cSDimitry Andric     }
726dff0c46cSDimitry Andric 
727cb4dff85SDimitry Andric     if (!HasLoopingSucc) {
728ff0cc061SDimitry Andric       // Restore the old exiting state, no viable looping successor was found.
729dff0c46cSDimitry Andric       ExitingBB = OldExitingBB;
730dff0c46cSDimitry Andric       BestExitEdgeFreq = OldBestExitEdgeFreq;
731dff0c46cSDimitry Andric       continue;
732dff0c46cSDimitry Andric     }
733dff0c46cSDimitry Andric   }
734cb4dff85SDimitry Andric   // Without a candidate exiting block or with only a single block in the
735dff0c46cSDimitry Andric   // loop, just use the loop header to layout the loop.
736dff0c46cSDimitry Andric   if (!ExitingBB || L.getNumBlocks() == 1)
73791bc56edSDimitry Andric     return nullptr;
738dff0c46cSDimitry Andric 
739dff0c46cSDimitry Andric   // Also, if we have exit blocks which lead to outer loops but didn't select
740dff0c46cSDimitry Andric   // one of them as the exiting block we are rotating toward, disable loop
741dff0c46cSDimitry Andric   // rotation altogether.
742dff0c46cSDimitry Andric   if (!BlocksExitingToOuterLoop.empty() &&
743dff0c46cSDimitry Andric       !BlocksExitingToOuterLoop.count(ExitingBB))
74491bc56edSDimitry Andric     return nullptr;
745dff0c46cSDimitry Andric 
746dff0c46cSDimitry Andric   DEBUG(dbgs() << "  Best exiting block: " << getBlockName(ExitingBB) << "\n");
747cb4dff85SDimitry Andric   return ExitingBB;
748cb4dff85SDimitry Andric }
749cb4dff85SDimitry Andric 
750cb4dff85SDimitry Andric /// \brief Attempt to rotate an exiting block to the bottom of the loop.
751cb4dff85SDimitry Andric ///
752cb4dff85SDimitry Andric /// Once we have built a chain, try to rotate it to line up the hot exit block
753cb4dff85SDimitry Andric /// with fallthrough out of the loop if doing so doesn't introduce unnecessary
754cb4dff85SDimitry Andric /// branches. For example, if the loop has fallthrough into its header and out
755cb4dff85SDimitry Andric /// of its bottom already, don't rotate it.
756cb4dff85SDimitry Andric void MachineBlockPlacement::rotateLoop(BlockChain &LoopChain,
757cb4dff85SDimitry Andric                                        MachineBasicBlock *ExitingBB,
758cb4dff85SDimitry Andric                                        const BlockFilterSet &LoopBlockSet) {
759cb4dff85SDimitry Andric   if (!ExitingBB)
760cb4dff85SDimitry Andric     return;
761cb4dff85SDimitry Andric 
762cb4dff85SDimitry Andric   MachineBasicBlock *Top = *LoopChain.begin();
763cb4dff85SDimitry Andric   bool ViableTopFallthrough = false;
764ff0cc061SDimitry Andric   for (MachineBasicBlock *Pred : Top->predecessors()) {
765ff0cc061SDimitry Andric     BlockChain *PredChain = BlockToChain[Pred];
766ff0cc061SDimitry Andric     if (!LoopBlockSet.count(Pred) &&
767ff0cc061SDimitry Andric         (!PredChain || Pred == *std::prev(PredChain->end()))) {
768cb4dff85SDimitry Andric       ViableTopFallthrough = true;
769cb4dff85SDimitry Andric       break;
770cb4dff85SDimitry Andric     }
771cb4dff85SDimitry Andric   }
772cb4dff85SDimitry Andric 
773cb4dff85SDimitry Andric   // If the header has viable fallthrough, check whether the current loop
774cb4dff85SDimitry Andric   // bottom is a viable exiting block. If so, bail out as rotating will
775cb4dff85SDimitry Andric   // introduce an unnecessary branch.
776cb4dff85SDimitry Andric   if (ViableTopFallthrough) {
77791bc56edSDimitry Andric     MachineBasicBlock *Bottom = *std::prev(LoopChain.end());
778ff0cc061SDimitry Andric     for (MachineBasicBlock *Succ : Bottom->successors()) {
779ff0cc061SDimitry Andric       BlockChain *SuccChain = BlockToChain[Succ];
780ff0cc061SDimitry Andric       if (!LoopBlockSet.count(Succ) &&
781ff0cc061SDimitry Andric           (!SuccChain || Succ == *SuccChain->begin()))
782cb4dff85SDimitry Andric         return;
783cb4dff85SDimitry Andric     }
784cb4dff85SDimitry Andric   }
785cb4dff85SDimitry Andric 
786ff0cc061SDimitry Andric   BlockChain::iterator ExitIt =
787ff0cc061SDimitry Andric       std::find(LoopChain.begin(), LoopChain.end(), ExitingBB);
788cb4dff85SDimitry Andric   if (ExitIt == LoopChain.end())
789cb4dff85SDimitry Andric     return;
790cb4dff85SDimitry Andric 
79191bc56edSDimitry Andric   std::rotate(LoopChain.begin(), std::next(ExitIt), LoopChain.end());
792dff0c46cSDimitry Andric }
793dff0c46cSDimitry Andric 
794dff0c46cSDimitry Andric /// \brief Forms basic block chains from the natural loop structures.
795dff0c46cSDimitry Andric ///
796dff0c46cSDimitry Andric /// These chains are designed to preserve the existing *structure* of the code
797dff0c46cSDimitry Andric /// as much as possible. We can then stitch the chains together in a way which
798dff0c46cSDimitry Andric /// both preserves the topological structure and minimizes taken conditional
799dff0c46cSDimitry Andric /// branches.
800dff0c46cSDimitry Andric void MachineBlockPlacement::buildLoopChains(MachineFunction &F,
801dff0c46cSDimitry Andric                                             MachineLoop &L) {
802dff0c46cSDimitry Andric   // First recurse through any nested loops, building chains for those inner
803dff0c46cSDimitry Andric   // loops.
804ff0cc061SDimitry Andric   for (MachineLoop *InnerLoop : L)
805ff0cc061SDimitry Andric     buildLoopChains(F, *InnerLoop);
806dff0c46cSDimitry Andric 
807dff0c46cSDimitry Andric   SmallVector<MachineBasicBlock *, 16> BlockWorkList;
808dff0c46cSDimitry Andric   BlockFilterSet LoopBlockSet(L.block_begin(), L.block_end());
809dff0c46cSDimitry Andric 
810cb4dff85SDimitry Andric   // First check to see if there is an obviously preferable top block for the
811cb4dff85SDimitry Andric   // loop. This will default to the header, but may end up as one of the
812cb4dff85SDimitry Andric   // predecessors to the header if there is one which will result in strictly
813cb4dff85SDimitry Andric   // fewer branches in the loop body.
814cb4dff85SDimitry Andric   MachineBasicBlock *LoopTop = findBestLoopTop(L, LoopBlockSet);
815cb4dff85SDimitry Andric 
816cb4dff85SDimitry Andric   // If we selected just the header for the loop top, look for a potentially
817cb4dff85SDimitry Andric   // profitable exit block in the event that rotating the loop can eliminate
818cb4dff85SDimitry Andric   // branches by placing an exit edge at the bottom.
81991bc56edSDimitry Andric   MachineBasicBlock *ExitingBB = nullptr;
820cb4dff85SDimitry Andric   if (LoopTop == L.getHeader())
821cb4dff85SDimitry Andric     ExitingBB = findBestLoopExit(F, L, LoopBlockSet);
822cb4dff85SDimitry Andric 
823cb4dff85SDimitry Andric   BlockChain &LoopChain = *BlockToChain[LoopTop];
824dff0c46cSDimitry Andric 
825dff0c46cSDimitry Andric   // FIXME: This is a really lame way of walking the chains in the loop: we
826dff0c46cSDimitry Andric   // walk the blocks, and use a set to prevent visiting a particular chain
827dff0c46cSDimitry Andric   // twice.
828dff0c46cSDimitry Andric   SmallPtrSet<BlockChain *, 4> UpdatedPreds;
829dff0c46cSDimitry Andric   assert(LoopChain.LoopPredecessors == 0);
830dff0c46cSDimitry Andric   UpdatedPreds.insert(&LoopChain);
831ff0cc061SDimitry Andric   for (MachineBasicBlock *LoopBB : L.getBlocks()) {
832ff0cc061SDimitry Andric     BlockChain &Chain = *BlockToChain[LoopBB];
83339d628a0SDimitry Andric     if (!UpdatedPreds.insert(&Chain).second)
834dff0c46cSDimitry Andric       continue;
835dff0c46cSDimitry Andric 
836dff0c46cSDimitry Andric     assert(Chain.LoopPredecessors == 0);
837ff0cc061SDimitry Andric     for (MachineBasicBlock *ChainBB : Chain) {
838ff0cc061SDimitry Andric       assert(BlockToChain[ChainBB] == &Chain);
839ff0cc061SDimitry Andric       for (MachineBasicBlock *Pred : ChainBB->predecessors()) {
840ff0cc061SDimitry Andric         if (BlockToChain[Pred] == &Chain || !LoopBlockSet.count(Pred))
841dff0c46cSDimitry Andric           continue;
842dff0c46cSDimitry Andric         ++Chain.LoopPredecessors;
843dff0c46cSDimitry Andric       }
844dff0c46cSDimitry Andric     }
845dff0c46cSDimitry Andric 
846dff0c46cSDimitry Andric     if (Chain.LoopPredecessors == 0)
847dff0c46cSDimitry Andric       BlockWorkList.push_back(*Chain.begin());
848dff0c46cSDimitry Andric   }
849dff0c46cSDimitry Andric 
850cb4dff85SDimitry Andric   buildChain(LoopTop, LoopChain, BlockWorkList, &LoopBlockSet);
851cb4dff85SDimitry Andric   rotateLoop(LoopChain, ExitingBB, LoopBlockSet);
852dff0c46cSDimitry Andric 
853dff0c46cSDimitry Andric   DEBUG({
854dff0c46cSDimitry Andric     // Crash at the end so we get all of the debugging output first.
855dff0c46cSDimitry Andric     bool BadLoop = false;
856dff0c46cSDimitry Andric     if (LoopChain.LoopPredecessors) {
857dff0c46cSDimitry Andric       BadLoop = true;
858dff0c46cSDimitry Andric       dbgs() << "Loop chain contains a block without its preds placed!\n"
859dff0c46cSDimitry Andric              << "  Loop header:  " << getBlockName(*L.block_begin()) << "\n"
860dff0c46cSDimitry Andric              << "  Chain header: " << getBlockName(*LoopChain.begin()) << "\n";
861dff0c46cSDimitry Andric     }
862ff0cc061SDimitry Andric     for (MachineBasicBlock *ChainBB : LoopChain) {
863ff0cc061SDimitry Andric       dbgs() << "          ... " << getBlockName(ChainBB) << "\n";
864ff0cc061SDimitry Andric       if (!LoopBlockSet.erase(ChainBB)) {
865dff0c46cSDimitry Andric         // We don't mark the loop as bad here because there are real situations
866dff0c46cSDimitry Andric         // where this can occur. For example, with an unanalyzable fallthrough
867dff0c46cSDimitry Andric         // from a loop block to a non-loop block or vice versa.
868dff0c46cSDimitry Andric         dbgs() << "Loop chain contains a block not contained by the loop!\n"
869dff0c46cSDimitry Andric                << "  Loop header:  " << getBlockName(*L.block_begin()) << "\n"
870dff0c46cSDimitry Andric                << "  Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
871ff0cc061SDimitry Andric                << "  Bad block:    " << getBlockName(ChainBB) << "\n";
872dff0c46cSDimitry Andric       }
873cb4dff85SDimitry Andric     }
874dff0c46cSDimitry Andric 
875dff0c46cSDimitry Andric     if (!LoopBlockSet.empty()) {
876dff0c46cSDimitry Andric       BadLoop = true;
877ff0cc061SDimitry Andric       for (MachineBasicBlock *LoopBB : LoopBlockSet)
878dff0c46cSDimitry Andric         dbgs() << "Loop contains blocks never placed into a chain!\n"
879dff0c46cSDimitry Andric                << "  Loop header:  " << getBlockName(*L.block_begin()) << "\n"
880dff0c46cSDimitry Andric                << "  Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
881ff0cc061SDimitry Andric                << "  Bad block:    " << getBlockName(LoopBB) << "\n";
882dff0c46cSDimitry Andric     }
883dff0c46cSDimitry Andric     assert(!BadLoop && "Detected problems with the placement of this loop.");
884dff0c46cSDimitry Andric   });
885dff0c46cSDimitry Andric }
886dff0c46cSDimitry Andric 
887dff0c46cSDimitry Andric void MachineBlockPlacement::buildCFGChains(MachineFunction &F) {
888dff0c46cSDimitry Andric   // Ensure that every BB in the function has an associated chain to simplify
889dff0c46cSDimitry Andric   // the assumptions of the remaining algorithm.
890dff0c46cSDimitry Andric   SmallVector<MachineOperand, 4> Cond; // For AnalyzeBranch.
891dff0c46cSDimitry Andric   for (MachineFunction::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
892dff0c46cSDimitry Andric     MachineBasicBlock *BB = FI;
893ff0cc061SDimitry Andric     BlockChain *Chain =
894ff0cc061SDimitry Andric         new (ChainAllocator.Allocate()) BlockChain(BlockToChain, BB);
895dff0c46cSDimitry Andric     // Also, merge any blocks which we cannot reason about and must preserve
896dff0c46cSDimitry Andric     // the exact fallthrough behavior for.
897dff0c46cSDimitry Andric     for (;;) {
898dff0c46cSDimitry Andric       Cond.clear();
89991bc56edSDimitry Andric       MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
900dff0c46cSDimitry Andric       if (!TII->AnalyzeBranch(*BB, TBB, FBB, Cond) || !FI->canFallThrough())
901dff0c46cSDimitry Andric         break;
902dff0c46cSDimitry Andric 
90391bc56edSDimitry Andric       MachineFunction::iterator NextFI(std::next(FI));
904dff0c46cSDimitry Andric       MachineBasicBlock *NextBB = NextFI;
905dff0c46cSDimitry Andric       // Ensure that the layout successor is a viable block, as we know that
906dff0c46cSDimitry Andric       // fallthrough is a possibility.
907dff0c46cSDimitry Andric       assert(NextFI != FE && "Can't fallthrough past the last block.");
908dff0c46cSDimitry Andric       DEBUG(dbgs() << "Pre-merging due to unanalyzable fallthrough: "
909dff0c46cSDimitry Andric                    << getBlockName(BB) << " -> " << getBlockName(NextBB)
910dff0c46cSDimitry Andric                    << "\n");
91191bc56edSDimitry Andric       Chain->merge(NextBB, nullptr);
912dff0c46cSDimitry Andric       FI = NextFI;
913dff0c46cSDimitry Andric       BB = NextBB;
914dff0c46cSDimitry Andric     }
915dff0c46cSDimitry Andric   }
916dff0c46cSDimitry Andric 
917ff0cc061SDimitry Andric   if (OutlineOptionalBranches) {
918ff0cc061SDimitry Andric     // Find the nearest common dominator of all of F's terminators.
919ff0cc061SDimitry Andric     MachineBasicBlock *Terminator = nullptr;
920ff0cc061SDimitry Andric     for (MachineBasicBlock &MBB : F) {
921ff0cc061SDimitry Andric       if (MBB.succ_size() == 0) {
922ff0cc061SDimitry Andric         if (Terminator == nullptr)
923ff0cc061SDimitry Andric           Terminator = &MBB;
924ff0cc061SDimitry Andric         else
925ff0cc061SDimitry Andric           Terminator = MDT->findNearestCommonDominator(Terminator, &MBB);
926ff0cc061SDimitry Andric       }
927ff0cc061SDimitry Andric     }
928ff0cc061SDimitry Andric 
929ff0cc061SDimitry Andric     // MBBs dominating this common dominator are unavoidable.
930ff0cc061SDimitry Andric     UnavoidableBlocks.clear();
931ff0cc061SDimitry Andric     for (MachineBasicBlock &MBB : F) {
932ff0cc061SDimitry Andric       if (MDT->dominates(&MBB, Terminator)) {
933ff0cc061SDimitry Andric         UnavoidableBlocks.insert(&MBB);
934ff0cc061SDimitry Andric       }
935ff0cc061SDimitry Andric     }
936ff0cc061SDimitry Andric   }
937ff0cc061SDimitry Andric 
938dff0c46cSDimitry Andric   // Build any loop-based chains.
939ff0cc061SDimitry Andric   for (MachineLoop *L : *MLI)
940ff0cc061SDimitry Andric     buildLoopChains(F, *L);
941dff0c46cSDimitry Andric 
942dff0c46cSDimitry Andric   SmallVector<MachineBasicBlock *, 16> BlockWorkList;
943dff0c46cSDimitry Andric 
944dff0c46cSDimitry Andric   SmallPtrSet<BlockChain *, 4> UpdatedPreds;
945ff0cc061SDimitry Andric   for (MachineBasicBlock &MBB : F) {
946ff0cc061SDimitry Andric     BlockChain &Chain = *BlockToChain[&MBB];
94739d628a0SDimitry Andric     if (!UpdatedPreds.insert(&Chain).second)
948dff0c46cSDimitry Andric       continue;
949dff0c46cSDimitry Andric 
950dff0c46cSDimitry Andric     assert(Chain.LoopPredecessors == 0);
951ff0cc061SDimitry Andric     for (MachineBasicBlock *ChainBB : Chain) {
952ff0cc061SDimitry Andric       assert(BlockToChain[ChainBB] == &Chain);
953ff0cc061SDimitry Andric       for (MachineBasicBlock *Pred : ChainBB->predecessors()) {
954ff0cc061SDimitry Andric         if (BlockToChain[Pred] == &Chain)
955dff0c46cSDimitry Andric           continue;
956dff0c46cSDimitry Andric         ++Chain.LoopPredecessors;
957dff0c46cSDimitry Andric       }
958dff0c46cSDimitry Andric     }
959dff0c46cSDimitry Andric 
960dff0c46cSDimitry Andric     if (Chain.LoopPredecessors == 0)
961dff0c46cSDimitry Andric       BlockWorkList.push_back(*Chain.begin());
962dff0c46cSDimitry Andric   }
963dff0c46cSDimitry Andric 
964dff0c46cSDimitry Andric   BlockChain &FunctionChain = *BlockToChain[&F.front()];
965dff0c46cSDimitry Andric   buildChain(&F.front(), FunctionChain, BlockWorkList);
966dff0c46cSDimitry Andric 
96791bc56edSDimitry Andric #ifndef NDEBUG
968dff0c46cSDimitry Andric   typedef SmallPtrSet<MachineBasicBlock *, 16> FunctionBlockSetType;
96991bc56edSDimitry Andric #endif
970dff0c46cSDimitry Andric   DEBUG({
971dff0c46cSDimitry Andric     // Crash at the end so we get all of the debugging output first.
972dff0c46cSDimitry Andric     bool BadFunc = false;
973dff0c46cSDimitry Andric     FunctionBlockSetType FunctionBlockSet;
974ff0cc061SDimitry Andric     for (MachineBasicBlock &MBB : F)
975ff0cc061SDimitry Andric       FunctionBlockSet.insert(&MBB);
976dff0c46cSDimitry Andric 
977ff0cc061SDimitry Andric     for (MachineBasicBlock *ChainBB : FunctionChain)
978ff0cc061SDimitry Andric       if (!FunctionBlockSet.erase(ChainBB)) {
979dff0c46cSDimitry Andric         BadFunc = true;
980dff0c46cSDimitry Andric         dbgs() << "Function chain contains a block not in the function!\n"
981ff0cc061SDimitry Andric                << "  Bad block:    " << getBlockName(ChainBB) << "\n";
982dff0c46cSDimitry Andric       }
983dff0c46cSDimitry Andric 
984dff0c46cSDimitry Andric     if (!FunctionBlockSet.empty()) {
985dff0c46cSDimitry Andric       BadFunc = true;
986ff0cc061SDimitry Andric       for (MachineBasicBlock *RemainingBB : FunctionBlockSet)
987dff0c46cSDimitry Andric         dbgs() << "Function contains blocks never placed into a chain!\n"
988ff0cc061SDimitry Andric                << "  Bad block:    " << getBlockName(RemainingBB) << "\n";
989dff0c46cSDimitry Andric     }
990dff0c46cSDimitry Andric     assert(!BadFunc && "Detected problems with the block placement.");
991dff0c46cSDimitry Andric   });
992dff0c46cSDimitry Andric 
993dff0c46cSDimitry Andric   // Splice the blocks into place.
994dff0c46cSDimitry Andric   MachineFunction::iterator InsertPos = F.begin();
995ff0cc061SDimitry Andric   for (MachineBasicBlock *ChainBB : FunctionChain) {
996ff0cc061SDimitry Andric     DEBUG(dbgs() << (ChainBB == *FunctionChain.begin() ? "Placing chain "
997dff0c46cSDimitry Andric                                                        : "          ... ")
998ff0cc061SDimitry Andric                  << getBlockName(ChainBB) << "\n");
999ff0cc061SDimitry Andric     if (InsertPos != MachineFunction::iterator(ChainBB))
1000ff0cc061SDimitry Andric       F.splice(InsertPos, ChainBB);
1001dff0c46cSDimitry Andric     else
1002dff0c46cSDimitry Andric       ++InsertPos;
1003dff0c46cSDimitry Andric 
1004dff0c46cSDimitry Andric     // Update the terminator of the previous block.
1005ff0cc061SDimitry Andric     if (ChainBB == *FunctionChain.begin())
1006dff0c46cSDimitry Andric       continue;
1007ff0cc061SDimitry Andric     MachineBasicBlock *PrevBB = std::prev(MachineFunction::iterator(ChainBB));
1008dff0c46cSDimitry Andric 
1009dff0c46cSDimitry Andric     // FIXME: It would be awesome of updateTerminator would just return rather
1010dff0c46cSDimitry Andric     // than assert when the branch cannot be analyzed in order to remove this
1011dff0c46cSDimitry Andric     // boiler plate.
1012dff0c46cSDimitry Andric     Cond.clear();
101391bc56edSDimitry Andric     MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
10147ae0e2c9SDimitry Andric     if (!TII->AnalyzeBranch(*PrevBB, TBB, FBB, Cond)) {
1015f785676fSDimitry Andric       // The "PrevBB" is not yet updated to reflect current code layout, so,
1016f785676fSDimitry Andric       //   o. it may fall-through to a block without explict "goto" instruction
1017f785676fSDimitry Andric       //      before layout, and no longer fall-through it after layout; or
1018f785676fSDimitry Andric       //   o. just opposite.
1019f785676fSDimitry Andric       //
1020f785676fSDimitry Andric       // AnalyzeBranch() may return erroneous value for FBB when these two
1021f785676fSDimitry Andric       // situations take place. For the first scenario FBB is mistakenly set
1022f785676fSDimitry Andric       // NULL; for the 2nd scenario, the FBB, which is expected to be NULL,
1023f785676fSDimitry Andric       // is mistakenly pointing to "*BI".
1024f785676fSDimitry Andric       //
1025f785676fSDimitry Andric       bool needUpdateBr = true;
1026ff0cc061SDimitry Andric       if (!Cond.empty() && (!FBB || FBB == ChainBB)) {
1027f785676fSDimitry Andric         PrevBB->updateTerminator();
1028f785676fSDimitry Andric         needUpdateBr = false;
1029f785676fSDimitry Andric         Cond.clear();
103091bc56edSDimitry Andric         TBB = FBB = nullptr;
1031f785676fSDimitry Andric         if (TII->AnalyzeBranch(*PrevBB, TBB, FBB, Cond)) {
1032f785676fSDimitry Andric           // FIXME: This should never take place.
103391bc56edSDimitry Andric           TBB = FBB = nullptr;
1034f785676fSDimitry Andric         }
1035f785676fSDimitry Andric       }
1036f785676fSDimitry Andric 
10377ae0e2c9SDimitry Andric       // If PrevBB has a two-way branch, try to re-order the branches
10387ae0e2c9SDimitry Andric       // such that we branch to the successor with higher weight first.
10397ae0e2c9SDimitry Andric       if (TBB && !Cond.empty() && FBB &&
10407ae0e2c9SDimitry Andric           MBPI->getEdgeWeight(PrevBB, FBB) > MBPI->getEdgeWeight(PrevBB, TBB) &&
10417ae0e2c9SDimitry Andric           !TII->ReverseBranchCondition(Cond)) {
10427ae0e2c9SDimitry Andric         DEBUG(dbgs() << "Reverse order of the two branches: "
10437ae0e2c9SDimitry Andric                      << getBlockName(PrevBB) << "\n");
10447ae0e2c9SDimitry Andric         DEBUG(dbgs() << "    Edge weight: " << MBPI->getEdgeWeight(PrevBB, FBB)
10457ae0e2c9SDimitry Andric                      << " vs " << MBPI->getEdgeWeight(PrevBB, TBB) << "\n");
10467ae0e2c9SDimitry Andric         DebugLoc dl; // FIXME: this is nowhere
10477ae0e2c9SDimitry Andric         TII->RemoveBranch(*PrevBB);
10487ae0e2c9SDimitry Andric         TII->InsertBranch(*PrevBB, FBB, TBB, Cond, dl);
1049f785676fSDimitry Andric         needUpdateBr = true;
10507ae0e2c9SDimitry Andric       }
1051f785676fSDimitry Andric       if (needUpdateBr)
1052dff0c46cSDimitry Andric         PrevBB->updateTerminator();
1053dff0c46cSDimitry Andric     }
10547ae0e2c9SDimitry Andric   }
1055dff0c46cSDimitry Andric 
1056dff0c46cSDimitry Andric   // Fixup the last block.
1057dff0c46cSDimitry Andric   Cond.clear();
105891bc56edSDimitry Andric   MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
1059dff0c46cSDimitry Andric   if (!TII->AnalyzeBranch(F.back(), TBB, FBB, Cond))
1060dff0c46cSDimitry Andric     F.back().updateTerminator();
1061dff0c46cSDimitry Andric 
1062cb4dff85SDimitry Andric   // Walk through the backedges of the function now that we have fully laid out
1063cb4dff85SDimitry Andric   // the basic blocks and align the destination of each backedge. We don't rely
10647ae0e2c9SDimitry Andric   // exclusively on the loop info here so that we can align backedges in
10657ae0e2c9SDimitry Andric   // unnatural CFGs and backedges that were introduced purely because of the
10667ae0e2c9SDimitry Andric   // loop rotations done during this layout pass.
1067ff0cc061SDimitry Andric   if (F.getFunction()->hasFnAttribute(Attribute::OptimizeForSize))
1068dff0c46cSDimitry Andric     return;
10697ae0e2c9SDimitry Andric   if (FunctionChain.begin() == FunctionChain.end())
10707ae0e2c9SDimitry Andric     return; // Empty chain.
1071dff0c46cSDimitry Andric 
10727ae0e2c9SDimitry Andric   const BranchProbability ColdProb(1, 5); // 20%
10737ae0e2c9SDimitry Andric   BlockFrequency EntryFreq = MBFI->getBlockFreq(F.begin());
10747ae0e2c9SDimitry Andric   BlockFrequency WeightedEntryFreq = EntryFreq * ColdProb;
1075ff0cc061SDimitry Andric   for (MachineBasicBlock *ChainBB : FunctionChain) {
1076ff0cc061SDimitry Andric     if (ChainBB == *FunctionChain.begin())
1077ff0cc061SDimitry Andric       continue;
1078ff0cc061SDimitry Andric 
10797ae0e2c9SDimitry Andric     // Don't align non-looping basic blocks. These are unlikely to execute
10807ae0e2c9SDimitry Andric     // enough times to matter in practice. Note that we'll still handle
10817ae0e2c9SDimitry Andric     // unnatural CFGs inside of a natural outer loop (the common case) and
10827ae0e2c9SDimitry Andric     // rotated loops.
1083ff0cc061SDimitry Andric     MachineLoop *L = MLI->getLoopFor(ChainBB);
10847ae0e2c9SDimitry Andric     if (!L)
10857ae0e2c9SDimitry Andric       continue;
10867ae0e2c9SDimitry Andric 
108739d628a0SDimitry Andric     unsigned Align = TLI->getPrefLoopAlignment(L);
108839d628a0SDimitry Andric     if (!Align)
108939d628a0SDimitry Andric       continue; // Don't care about loop alignment.
109039d628a0SDimitry Andric 
10917ae0e2c9SDimitry Andric     // If the block is cold relative to the function entry don't waste space
10927ae0e2c9SDimitry Andric     // aligning it.
1093ff0cc061SDimitry Andric     BlockFrequency Freq = MBFI->getBlockFreq(ChainBB);
10947ae0e2c9SDimitry Andric     if (Freq < WeightedEntryFreq)
10957ae0e2c9SDimitry Andric       continue;
10967ae0e2c9SDimitry Andric 
10977ae0e2c9SDimitry Andric     // If the block is cold relative to its loop header, don't align it
10987ae0e2c9SDimitry Andric     // regardless of what edges into the block exist.
10997ae0e2c9SDimitry Andric     MachineBasicBlock *LoopHeader = L->getHeader();
11007ae0e2c9SDimitry Andric     BlockFrequency LoopHeaderFreq = MBFI->getBlockFreq(LoopHeader);
11017ae0e2c9SDimitry Andric     if (Freq < (LoopHeaderFreq * ColdProb))
11027ae0e2c9SDimitry Andric       continue;
11037ae0e2c9SDimitry Andric 
11047ae0e2c9SDimitry Andric     // Check for the existence of a non-layout predecessor which would benefit
11057ae0e2c9SDimitry Andric     // from aligning this block.
1106ff0cc061SDimitry Andric     MachineBasicBlock *LayoutPred =
1107ff0cc061SDimitry Andric         &*std::prev(MachineFunction::iterator(ChainBB));
11087ae0e2c9SDimitry Andric 
11097ae0e2c9SDimitry Andric     // Force alignment if all the predecessors are jumps. We already checked
11107ae0e2c9SDimitry Andric     // that the block isn't cold above.
1111ff0cc061SDimitry Andric     if (!LayoutPred->isSuccessor(ChainBB)) {
1112ff0cc061SDimitry Andric       ChainBB->setAlignment(Align);
11137ae0e2c9SDimitry Andric       continue;
11147ae0e2c9SDimitry Andric     }
11157ae0e2c9SDimitry Andric 
11167ae0e2c9SDimitry Andric     // Align this block if the layout predecessor's edge into this block is
1117139f7f9bSDimitry Andric     // cold relative to the block. When this is true, other predecessors make up
11187ae0e2c9SDimitry Andric     // all of the hot entries into the block and thus alignment is likely to be
11197ae0e2c9SDimitry Andric     // important.
1120ff0cc061SDimitry Andric     BranchProbability LayoutProb =
1121ff0cc061SDimitry Andric         MBPI->getEdgeProbability(LayoutPred, ChainBB);
11227ae0e2c9SDimitry Andric     BlockFrequency LayoutEdgeFreq = MBFI->getBlockFreq(LayoutPred) * LayoutProb;
11237ae0e2c9SDimitry Andric     if (LayoutEdgeFreq <= (Freq * ColdProb))
1124ff0cc061SDimitry Andric       ChainBB->setAlignment(Align);
1125cb4dff85SDimitry Andric   }
1126dff0c46cSDimitry Andric }
1127dff0c46cSDimitry Andric 
1128dff0c46cSDimitry Andric bool MachineBlockPlacement::runOnMachineFunction(MachineFunction &F) {
1129dff0c46cSDimitry Andric   // Check for single-block functions and skip them.
113091bc56edSDimitry Andric   if (std::next(F.begin()) == F.end())
113191bc56edSDimitry Andric     return false;
113291bc56edSDimitry Andric 
113391bc56edSDimitry Andric   if (skipOptnoneFunction(*F.getFunction()))
1134dff0c46cSDimitry Andric     return false;
1135dff0c46cSDimitry Andric 
1136dff0c46cSDimitry Andric   MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
1137dff0c46cSDimitry Andric   MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
1138dff0c46cSDimitry Andric   MLI = &getAnalysis<MachineLoopInfo>();
113939d628a0SDimitry Andric   TII = F.getSubtarget().getInstrInfo();
114039d628a0SDimitry Andric   TLI = F.getSubtarget().getTargetLowering();
1141ff0cc061SDimitry Andric   MDT = &getAnalysis<MachineDominatorTree>();
1142dff0c46cSDimitry Andric   assert(BlockToChain.empty());
1143dff0c46cSDimitry Andric 
1144dff0c46cSDimitry Andric   buildCFGChains(F);
1145dff0c46cSDimitry Andric 
1146dff0c46cSDimitry Andric   BlockToChain.clear();
1147dff0c46cSDimitry Andric   ChainAllocator.DestroyAll();
1148dff0c46cSDimitry Andric 
1149284c1978SDimitry Andric   if (AlignAllBlock)
1150284c1978SDimitry Andric     // Align all of the blocks in the function to a specific alignment.
1151ff0cc061SDimitry Andric     for (MachineBasicBlock &MBB : F)
1152ff0cc061SDimitry Andric       MBB.setAlignment(AlignAllBlock);
1153284c1978SDimitry Andric 
1154dff0c46cSDimitry Andric   // We always return true as we have no way to track whether the final order
1155dff0c46cSDimitry Andric   // differs from the original order.
1156dff0c46cSDimitry Andric   return true;
1157dff0c46cSDimitry Andric }
1158dff0c46cSDimitry Andric 
1159dff0c46cSDimitry Andric namespace {
1160dff0c46cSDimitry Andric /// \brief A pass to compute block placement statistics.
1161dff0c46cSDimitry Andric ///
1162dff0c46cSDimitry Andric /// A separate pass to compute interesting statistics for evaluating block
1163dff0c46cSDimitry Andric /// placement. This is separate from the actual placement pass so that they can
11647ae0e2c9SDimitry Andric /// be computed in the absence of any placement transformations or when using
1165dff0c46cSDimitry Andric /// alternative placement strategies.
1166dff0c46cSDimitry Andric class MachineBlockPlacementStats : public MachineFunctionPass {
1167dff0c46cSDimitry Andric   /// \brief A handle to the branch probability pass.
1168dff0c46cSDimitry Andric   const MachineBranchProbabilityInfo *MBPI;
1169dff0c46cSDimitry Andric 
1170dff0c46cSDimitry Andric   /// \brief A handle to the function-wide block frequency pass.
1171dff0c46cSDimitry Andric   const MachineBlockFrequencyInfo *MBFI;
1172dff0c46cSDimitry Andric 
1173dff0c46cSDimitry Andric public:
1174dff0c46cSDimitry Andric   static char ID; // Pass identification, replacement for typeid
1175dff0c46cSDimitry Andric   MachineBlockPlacementStats() : MachineFunctionPass(ID) {
1176dff0c46cSDimitry Andric     initializeMachineBlockPlacementStatsPass(*PassRegistry::getPassRegistry());
1177dff0c46cSDimitry Andric   }
1178dff0c46cSDimitry Andric 
117991bc56edSDimitry Andric   bool runOnMachineFunction(MachineFunction &F) override;
1180dff0c46cSDimitry Andric 
118191bc56edSDimitry Andric   void getAnalysisUsage(AnalysisUsage &AU) const override {
1182dff0c46cSDimitry Andric     AU.addRequired<MachineBranchProbabilityInfo>();
1183dff0c46cSDimitry Andric     AU.addRequired<MachineBlockFrequencyInfo>();
1184dff0c46cSDimitry Andric     AU.setPreservesAll();
1185dff0c46cSDimitry Andric     MachineFunctionPass::getAnalysisUsage(AU);
1186dff0c46cSDimitry Andric   }
1187dff0c46cSDimitry Andric };
11883dac3a9bSDimitry Andric }
1189dff0c46cSDimitry Andric 
1190dff0c46cSDimitry Andric char MachineBlockPlacementStats::ID = 0;
1191dff0c46cSDimitry Andric char &llvm::MachineBlockPlacementStatsID = MachineBlockPlacementStats::ID;
1192dff0c46cSDimitry Andric INITIALIZE_PASS_BEGIN(MachineBlockPlacementStats, "block-placement-stats",
1193dff0c46cSDimitry Andric                       "Basic Block Placement Stats", false, false)
1194dff0c46cSDimitry Andric INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
1195dff0c46cSDimitry Andric INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
1196dff0c46cSDimitry Andric INITIALIZE_PASS_END(MachineBlockPlacementStats, "block-placement-stats",
1197dff0c46cSDimitry Andric                     "Basic Block Placement Stats", false, false)
1198dff0c46cSDimitry Andric 
1199dff0c46cSDimitry Andric bool MachineBlockPlacementStats::runOnMachineFunction(MachineFunction &F) {
1200dff0c46cSDimitry Andric   // Check for single-block functions and skip them.
120191bc56edSDimitry Andric   if (std::next(F.begin()) == F.end())
1202dff0c46cSDimitry Andric     return false;
1203dff0c46cSDimitry Andric 
1204dff0c46cSDimitry Andric   MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
1205dff0c46cSDimitry Andric   MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
1206dff0c46cSDimitry Andric 
1207ff0cc061SDimitry Andric   for (MachineBasicBlock &MBB : F) {
1208ff0cc061SDimitry Andric     BlockFrequency BlockFreq = MBFI->getBlockFreq(&MBB);
1209ff0cc061SDimitry Andric     Statistic &NumBranches =
1210ff0cc061SDimitry Andric         (MBB.succ_size() > 1) ? NumCondBranches : NumUncondBranches;
1211ff0cc061SDimitry Andric     Statistic &BranchTakenFreq =
1212ff0cc061SDimitry Andric         (MBB.succ_size() > 1) ? CondBranchTakenFreq : UncondBranchTakenFreq;
1213ff0cc061SDimitry Andric     for (MachineBasicBlock *Succ : MBB.successors()) {
1214dff0c46cSDimitry Andric       // Skip if this successor is a fallthrough.
1215ff0cc061SDimitry Andric       if (MBB.isLayoutSuccessor(Succ))
1216dff0c46cSDimitry Andric         continue;
1217dff0c46cSDimitry Andric 
1218ff0cc061SDimitry Andric       BlockFrequency EdgeFreq =
1219ff0cc061SDimitry Andric           BlockFreq * MBPI->getEdgeProbability(&MBB, Succ);
1220dff0c46cSDimitry Andric       ++NumBranches;
1221dff0c46cSDimitry Andric       BranchTakenFreq += EdgeFreq.getFrequency();
1222dff0c46cSDimitry Andric     }
1223dff0c46cSDimitry Andric   }
1224dff0c46cSDimitry Andric 
1225dff0c46cSDimitry Andric   return false;
1226dff0c46cSDimitry Andric }
1227dff0c46cSDimitry Andric 
1228