blob: ecc093e97f58da882466d17559188f22ed999e78 [file] [log] [blame]
Chandler Carruth10281422011-10-21 06:46:38 +00001//===-- MachineBlockPlacement.cpp - Basic Block Code Layout optimization --===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Chandler Carruthbd1be4d2011-10-23 09:18:45 +000010// This file implements basic block placement transformations using the CFG
11// structure and branch probability estimates.
Chandler Carruth10281422011-10-21 06:46:38 +000012//
Chandler Carruthbd1be4d2011-10-23 09:18:45 +000013// The pass strives to preserve the structure of the CFG (that is, retain
Benjamin Kramerbde91762012-06-02 10:20:22 +000014// a topological ordering of basic blocks) in the absence of a *strong* signal
Chandler Carruthbd1be4d2011-10-23 09:18:45 +000015// to the contrary from probabilities. However, within the CFG structure, it
16// attempts to choose an ordering which favors placing more likely sequences of
17// blocks adjacent to each other.
18//
19// The algorithm works from the inner-most loop within a function outward, and
20// at each stage walks through the basic blocks, trying to coalesce them into
21// sequential chains where allowed by the CFG (or demanded by heavy
22// probabilities). Finally, it walks the blocks in topological order, and the
23// first time it reaches a chain of basic blocks, it schedules them in the
24// function in-order.
Chandler Carruth10281422011-10-21 06:46:38 +000025//
26//===----------------------------------------------------------------------===//
27
Chandler Carruthed0881b2012-12-03 16:50:05 +000028#include "llvm/CodeGen/Passes.h"
29#include "llvm/ADT/DenseMap.h"
30#include "llvm/ADT/SmallPtrSet.h"
31#include "llvm/ADT/SmallVector.h"
32#include "llvm/ADT/Statistic.h"
Chandler Carruth8b9737c2011-10-21 08:57:37 +000033#include "llvm/CodeGen/MachineBasicBlock.h"
Chandler Carruth10281422011-10-21 06:46:38 +000034#include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
35#include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
Daniel Jasper471e8562015-03-04 11:05:34 +000036#include "llvm/CodeGen/MachineDominators.h"
Chandler Carruth10281422011-10-21 06:46:38 +000037#include "llvm/CodeGen/MachineFunction.h"
Chandler Carruth10281422011-10-21 06:46:38 +000038#include "llvm/CodeGen/MachineFunctionPass.h"
Chandler Carruth8b9737c2011-10-21 08:57:37 +000039#include "llvm/CodeGen/MachineLoopInfo.h"
40#include "llvm/CodeGen/MachineModuleInfo.h"
Chandler Carruth10281422011-10-21 06:46:38 +000041#include "llvm/Support/Allocator.h"
Nadav Rotemc3b0f502013-04-12 00:48:32 +000042#include "llvm/Support/CommandLine.h"
Chandler Carruthbd1be4d2011-10-23 09:18:45 +000043#include "llvm/Support/Debug.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000044#include "llvm/Support/raw_ostream.h"
Chandler Carruth10281422011-10-21 06:46:38 +000045#include "llvm/Target/TargetInstrInfo.h"
Chandler Carruth8b9737c2011-10-21 08:57:37 +000046#include "llvm/Target/TargetLowering.h"
Eric Christopherd9134482014-08-04 21:25:23 +000047#include "llvm/Target/TargetSubtargetInfo.h"
Chandler Carruth10281422011-10-21 06:46:38 +000048#include <algorithm>
49using namespace llvm;
50
Chandler Carruthd0dced52015-03-05 02:28:25 +000051#define DEBUG_TYPE "block-placement"
Chandler Carruth1b9dde02014-04-22 02:02:50 +000052
Chandler Carruthae4e8002011-11-02 07:17:12 +000053STATISTIC(NumCondBranches, "Number of conditional branches");
54STATISTIC(NumUncondBranches, "Number of uncondittional branches");
55STATISTIC(CondBranchTakenFreq,
56 "Potential frequency of taking conditional branches");
57STATISTIC(UncondBranchTakenFreq,
58 "Potential frequency of taking unconditional branches");
59
Nadav Rotemc3b0f502013-04-12 00:48:32 +000060static cl::opt<unsigned> AlignAllBlock("align-all-blocks",
61 cl::desc("Force the alignment of all "
62 "blocks in the function."),
63 cl::init(0), cl::Hidden);
64
Benjamin Kramerc8160d62013-11-20 19:08:44 +000065// FIXME: Find a good default for this flag and remove the flag.
Chandler Carruth2fc3fe12015-03-05 02:35:31 +000066static cl::opt<unsigned> ExitBlockBias(
67 "block-placement-exit-block-bias",
68 cl::desc("Block frequency percentage a loop exit block needs "
69 "over the original exit to be considered the new exit."),
70 cl::init(0), cl::Hidden);
Benjamin Kramerc8160d62013-11-20 19:08:44 +000071
Daniel Jasper471e8562015-03-04 11:05:34 +000072static cl::opt<bool> OutlineOptionalBranches(
73 "outline-optional-branches",
74 cl::desc("Put completely optional branches, i.e. branches with a common "
75 "post dominator, out of line."),
76 cl::init(false), cl::Hidden);
77
Daniel Jasper214997c2015-03-20 10:00:37 +000078static cl::opt<unsigned> OutlineOptionalThreshold(
79 "outline-optional-threshold",
80 cl::desc("Don't outline optional branches that are a single block with an "
81 "instruction count below this threshold"),
82 cl::init(4), cl::Hidden);
83
Chandler Carruth10281422011-10-21 06:46:38 +000084namespace {
Chandler Carruthbd1be4d2011-10-23 09:18:45 +000085class BlockChain;
Chandler Carruth10281422011-10-21 06:46:38 +000086/// \brief Type for our function-wide basic block -> block chain mapping.
87typedef DenseMap<MachineBasicBlock *, BlockChain *> BlockToChainMapType;
88}
89
90namespace {
91/// \brief A chain of blocks which will be laid out contiguously.
92///
93/// This is the datastructure representing a chain of consecutive blocks that
94/// are profitable to layout together in order to maximize fallthrough
Chandler Carruth9139f442012-06-26 05:16:37 +000095/// probabilities and code locality. We also can use a block chain to represent
96/// a sequence of basic blocks which have some external (correctness)
97/// requirement for sequential layout.
Chandler Carruth10281422011-10-21 06:46:38 +000098///
Chandler Carruth9139f442012-06-26 05:16:37 +000099/// Chains can be built around a single basic block and can be merged to grow
100/// them. They participate in a block-to-chain mapping, which is updated
101/// automatically as chains are merged together.
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000102class BlockChain {
103 /// \brief The sequence of blocks belonging to this chain.
Chandler Carruth10281422011-10-21 06:46:38 +0000104 ///
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000105 /// This is the sequence of blocks for a particular chain. These will be laid
106 /// out in-order within the function.
107 SmallVector<MachineBasicBlock *, 4> Blocks;
Chandler Carruth10281422011-10-21 06:46:38 +0000108
109 /// \brief A handle to the function-wide basic block to block chain mapping.
110 ///
111 /// This is retained in each block chain to simplify the computation of child
112 /// block chains for SCC-formation and iteration. We store the edges to child
113 /// basic blocks, and map them back to their associated chains using this
114 /// structure.
115 BlockToChainMapType &BlockToChain;
116
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000117public:
Chandler Carruth10281422011-10-21 06:46:38 +0000118 /// \brief Construct a new BlockChain.
119 ///
120 /// This builds a new block chain representing a single basic block in the
121 /// function. It also registers itself as the chain that block participates
122 /// in with the BlockToChain mapping.
123 BlockChain(BlockToChainMapType &BlockToChain, MachineBasicBlock *BB)
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000124 : Blocks(1, BB), BlockToChain(BlockToChain), LoopPredecessors(0) {
Chandler Carruth10281422011-10-21 06:46:38 +0000125 assert(BB && "Cannot create a chain with a null basic block");
126 BlockToChain[BB] = this;
127 }
128
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000129 /// \brief Iterator over blocks within the chain.
Chandler Carruthccc7e422012-04-16 01:12:56 +0000130 typedef SmallVectorImpl<MachineBasicBlock *>::iterator iterator;
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000131
132 /// \brief Beginning of blocks within the chain.
Chandler Carruthccc7e422012-04-16 01:12:56 +0000133 iterator begin() { return Blocks.begin(); }
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000134
135 /// \brief End of blocks within the chain.
Chandler Carruthccc7e422012-04-16 01:12:56 +0000136 iterator end() { return Blocks.end(); }
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000137
138 /// \brief Merge a block chain into this one.
Chandler Carruth10281422011-10-21 06:46:38 +0000139 ///
140 /// This routine merges a block chain into this one. It takes care of forming
141 /// a contiguous sequence of basic blocks, updating the edge list, and
142 /// updating the block -> chain mapping. It does not free or tear down the
143 /// old chain, but the old chain's block list is no longer valid.
Jakub Staszak90616162011-12-21 23:02:08 +0000144 void merge(MachineBasicBlock *BB, BlockChain *Chain) {
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000145 assert(BB);
146 assert(!Blocks.empty());
Chandler Carruth10281422011-10-21 06:46:38 +0000147
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000148 // Fast path in case we don't have a chain already.
149 if (!Chain) {
150 assert(!BlockToChain[BB]);
151 Blocks.push_back(BB);
152 BlockToChain[BB] = this;
153 return;
Chandler Carruth10281422011-10-21 06:46:38 +0000154 }
155
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000156 assert(BB == *Chain->begin());
157 assert(Chain->begin() != Chain->end());
Chandler Carruth10281422011-10-21 06:46:38 +0000158
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000159 // Update the incoming blocks to point to this chain, and add them to the
160 // chain structure.
Chandler Carruth7a715da2015-03-05 03:19:05 +0000161 for (MachineBasicBlock *ChainBB : *Chain) {
162 Blocks.push_back(ChainBB);
163 assert(BlockToChain[ChainBB] == Chain && "Incoming blocks not in chain");
164 BlockToChain[ChainBB] = this;
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000165 }
Chandler Carruth10281422011-10-21 06:46:38 +0000166 }
Chandler Carruth8d150782011-11-13 11:20:44 +0000167
Chandler Carruth49158902012-04-08 14:37:01 +0000168#ifndef NDEBUG
169 /// \brief Dump the blocks in this chain.
Nico Weber7408c702014-01-03 22:53:37 +0000170 LLVM_DUMP_METHOD void dump() {
Chandler Carruth7a715da2015-03-05 03:19:05 +0000171 for (MachineBasicBlock *MBB : *this)
172 MBB->dump();
Chandler Carruth49158902012-04-08 14:37:01 +0000173 }
174#endif // NDEBUG
175
Chandler Carruth8d150782011-11-13 11:20:44 +0000176 /// \brief Count of predecessors within the loop currently being processed.
177 ///
178 /// This count is updated at each loop we process to represent the number of
179 /// in-loop predecessors of this chain.
180 unsigned LoopPredecessors;
Chandler Carruth10281422011-10-21 06:46:38 +0000181};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000182}
Chandler Carruth10281422011-10-21 06:46:38 +0000183
184namespace {
185class MachineBlockPlacement : public MachineFunctionPass {
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000186 /// \brief A typedef for a block filter set.
187 typedef SmallPtrSet<MachineBasicBlock *, 16> BlockFilterSet;
188
Chandler Carruth10281422011-10-21 06:46:38 +0000189 /// \brief A handle to the branch probability pass.
190 const MachineBranchProbabilityInfo *MBPI;
191
192 /// \brief A handle to the function-wide block frequency pass.
193 const MachineBlockFrequencyInfo *MBFI;
194
Chandler Carruth8b9737c2011-10-21 08:57:37 +0000195 /// \brief A handle to the loop info.
196 const MachineLoopInfo *MLI;
197
Chandler Carruth10281422011-10-21 06:46:38 +0000198 /// \brief A handle to the target's instruction info.
199 const TargetInstrInfo *TII;
200
Chandler Carruth8b9737c2011-10-21 08:57:37 +0000201 /// \brief A handle to the target's lowering info.
Benjamin Kramer56b31bd2013-01-11 20:05:37 +0000202 const TargetLoweringBase *TLI;
Chandler Carruth8b9737c2011-10-21 08:57:37 +0000203
Daniel Jasper471e8562015-03-04 11:05:34 +0000204 /// \brief A handle to the post dominator tree.
205 MachineDominatorTree *MDT;
206
207 /// \brief A set of blocks that are unavoidably execute, i.e. they dominate
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000208 /// all terminators of the MachineFunction.
Daniel Jasper471e8562015-03-04 11:05:34 +0000209 SmallPtrSet<MachineBasicBlock *, 4> UnavoidableBlocks;
210
Chandler Carruth10281422011-10-21 06:46:38 +0000211 /// \brief Allocator and owner of BlockChain structures.
212 ///
Chandler Carruth9139f442012-06-26 05:16:37 +0000213 /// We build BlockChains lazily while processing the loop structure of
214 /// a function. To reduce malloc traffic, we allocate them using this
215 /// slab-like allocator, and destroy them after the pass completes. An
216 /// important guarantee is that this allocator produces stable pointers to
217 /// the chains.
Chandler Carruth10281422011-10-21 06:46:38 +0000218 SpecificBumpPtrAllocator<BlockChain> ChainAllocator;
219
220 /// \brief Function wide BasicBlock to BlockChain mapping.
221 ///
222 /// This mapping allows efficiently moving from any given basic block to the
223 /// BlockChain it participates in, if any. We use it to, among other things,
224 /// allow implicitly defining edges between chains as the existing edges
225 /// between basic blocks.
226 DenseMap<MachineBasicBlock *, BlockChain *> BlockToChain;
227
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000228 void markChainSuccessors(BlockChain &Chain, MachineBasicBlock *LoopHeaderBB,
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000229 SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
Craig Topperc0196b12014-04-14 00:51:57 +0000230 const BlockFilterSet *BlockFilter = nullptr);
Jakub Staszak90616162011-12-21 23:02:08 +0000231 MachineBasicBlock *selectBestSuccessor(MachineBasicBlock *BB,
232 BlockChain &Chain,
233 const BlockFilterSet *BlockFilter);
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000234 MachineBasicBlock *
235 selectBestCandidateBlock(BlockChain &Chain,
236 SmallVectorImpl<MachineBasicBlock *> &WorkList,
237 const BlockFilterSet *BlockFilter);
238 MachineBasicBlock *
239 getFirstUnplacedBlock(MachineFunction &F, const BlockChain &PlacedChain,
240 MachineFunction::iterator &PrevUnplacedBlockIt,
241 const BlockFilterSet *BlockFilter);
Chandler Carruth8d150782011-11-13 11:20:44 +0000242 void buildChain(MachineBasicBlock *BB, BlockChain &Chain,
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000243 SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
Craig Topperc0196b12014-04-14 00:51:57 +0000244 const BlockFilterSet *BlockFilter = nullptr);
Chandler Carruth8c0b41d2012-04-16 13:33:36 +0000245 MachineBasicBlock *findBestLoopTop(MachineLoop &L,
246 const BlockFilterSet &LoopBlockSet);
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000247 MachineBasicBlock *findBestLoopExit(MachineFunction &F, MachineLoop &L,
Chandler Carruthccc7e422012-04-16 01:12:56 +0000248 const BlockFilterSet &LoopBlockSet);
Jakub Staszak90616162011-12-21 23:02:08 +0000249 void buildLoopChains(MachineFunction &F, MachineLoop &L);
Chandler Carruth8c74c7b2012-04-16 09:31:23 +0000250 void rotateLoop(BlockChain &LoopChain, MachineBasicBlock *ExitingBB,
251 const BlockFilterSet &LoopBlockSet);
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000252 void buildCFGChains(MachineFunction &F);
Chandler Carruth10281422011-10-21 06:46:38 +0000253
254public:
255 static char ID; // Pass identification, replacement for typeid
256 MachineBlockPlacement() : MachineFunctionPass(ID) {
257 initializeMachineBlockPlacementPass(*PassRegistry::getPassRegistry());
258 }
259
Craig Topper4584cd52014-03-07 09:26:03 +0000260 bool runOnMachineFunction(MachineFunction &F) override;
Chandler Carruth10281422011-10-21 06:46:38 +0000261
Craig Topper4584cd52014-03-07 09:26:03 +0000262 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruth10281422011-10-21 06:46:38 +0000263 AU.addRequired<MachineBranchProbabilityInfo>();
264 AU.addRequired<MachineBlockFrequencyInfo>();
Daniel Jasper471e8562015-03-04 11:05:34 +0000265 AU.addRequired<MachineDominatorTree>();
Chandler Carruth8b9737c2011-10-21 08:57:37 +0000266 AU.addRequired<MachineLoopInfo>();
Chandler Carruth10281422011-10-21 06:46:38 +0000267 MachineFunctionPass::getAnalysisUsage(AU);
268 }
Chandler Carruth10281422011-10-21 06:46:38 +0000269};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000270}
Chandler Carruth10281422011-10-21 06:46:38 +0000271
272char MachineBlockPlacement::ID = 0;
Andrew Trick1fa5bcb2012-02-08 21:23:13 +0000273char &llvm::MachineBlockPlacementID = MachineBlockPlacement::ID;
Chandler Carruthd0dced52015-03-05 02:28:25 +0000274INITIALIZE_PASS_BEGIN(MachineBlockPlacement, "block-placement",
Chandler Carruth10281422011-10-21 06:46:38 +0000275 "Branch Probability Basic Block Placement", false, false)
276INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
277INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
Daniel Jasper471e8562015-03-04 11:05:34 +0000278INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
Chandler Carruth8b9737c2011-10-21 08:57:37 +0000279INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
Chandler Carruthd0dced52015-03-05 02:28:25 +0000280INITIALIZE_PASS_END(MachineBlockPlacement, "block-placement",
Chandler Carruth10281422011-10-21 06:46:38 +0000281 "Branch Probability Basic Block Placement", false, false)
282
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000283#ifndef NDEBUG
284/// \brief Helper to print the name of a MBB.
285///
286/// Only used by debug logging.
Jakub Staszak90616162011-12-21 23:02:08 +0000287static std::string getBlockName(MachineBasicBlock *BB) {
Alp Tokere69170a2014-06-26 22:52:05 +0000288 std::string Result;
289 raw_string_ostream OS(Result);
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000290 OS << "BB#" << BB->getNumber();
291 OS << " (derived from LLVM BB '" << BB->getName() << "')";
Alp Tokere69170a2014-06-26 22:52:05 +0000292 OS.flush();
293 return Result;
Chandler Carruth10281422011-10-21 06:46:38 +0000294}
295
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000296/// \brief Helper to print the number of a MBB.
297///
298/// Only used by debug logging.
Jakub Staszak90616162011-12-21 23:02:08 +0000299static std::string getBlockNum(MachineBasicBlock *BB) {
Alp Tokere69170a2014-06-26 22:52:05 +0000300 std::string Result;
301 raw_string_ostream OS(Result);
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000302 OS << "BB#" << BB->getNumber();
Alp Tokere69170a2014-06-26 22:52:05 +0000303 OS.flush();
304 return Result;
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000305}
306#endif
307
Chandler Carrutheb4ec3a2011-11-13 11:34:55 +0000308/// \brief Mark a chain's successors as having one fewer preds.
309///
310/// When a chain is being merged into the "placed" chain, this routine will
311/// quickly walk the successors of each block in the chain and mark them as
312/// having one fewer active predecessor. It also adds any successors of this
313/// chain which reach the zero-predecessor state to the worklist passed in.
Chandler Carruth8d150782011-11-13 11:20:44 +0000314void MachineBlockPlacement::markChainSuccessors(
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000315 BlockChain &Chain, MachineBasicBlock *LoopHeaderBB,
Chandler Carruth8d150782011-11-13 11:20:44 +0000316 SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
Jakub Staszak90616162011-12-21 23:02:08 +0000317 const BlockFilterSet *BlockFilter) {
Chandler Carruth8d150782011-11-13 11:20:44 +0000318 // Walk all the blocks in this chain, marking their successors as having
319 // a predecessor placed.
Chandler Carruth7a715da2015-03-05 03:19:05 +0000320 for (MachineBasicBlock *MBB : Chain) {
Chandler Carruth8d150782011-11-13 11:20:44 +0000321 // Add any successors for which this is the only un-placed in-loop
322 // predecessor to the worklist as a viable candidate for CFG-neutral
323 // placement. No subsequent placement of this block will violate the CFG
324 // shape, so we get to use heuristics to choose a favorable placement.
Chandler Carruth7a715da2015-03-05 03:19:05 +0000325 for (MachineBasicBlock *Succ : MBB->successors()) {
326 if (BlockFilter && !BlockFilter->count(Succ))
Chandler Carruth8d150782011-11-13 11:20:44 +0000327 continue;
Chandler Carruth7a715da2015-03-05 03:19:05 +0000328 BlockChain &SuccChain = *BlockToChain[Succ];
Chandler Carruth8d150782011-11-13 11:20:44 +0000329 // Disregard edges within a fixed chain, or edges to the loop header.
Chandler Carruth7a715da2015-03-05 03:19:05 +0000330 if (&Chain == &SuccChain || Succ == LoopHeaderBB)
Chandler Carruth8d150782011-11-13 11:20:44 +0000331 continue;
Chandler Carruth10281422011-10-21 06:46:38 +0000332
Chandler Carruth8d150782011-11-13 11:20:44 +0000333 // This is a cross-chain edge that is within the loop, so decrement the
334 // loop predecessor count of the destination chain.
335 if (SuccChain.LoopPredecessors > 0 && --SuccChain.LoopPredecessors == 0)
Chandler Carruthd394baf2011-11-24 08:46:04 +0000336 BlockWorkList.push_back(*SuccChain.begin());
Chandler Carruth10281422011-10-21 06:46:38 +0000337 }
338 }
Chandler Carruth8d150782011-11-13 11:20:44 +0000339}
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000340
Chandler Carruthb3361722011-11-13 11:34:53 +0000341/// \brief Select the best successor for a block.
342///
343/// This looks across all successors of a particular block and attempts to
344/// select the "best" one to be the layout successor. It only considers direct
345/// successors which also pass the block filter. It will attempt to avoid
346/// breaking CFG structure, but cave and break such structures in the case of
347/// very hot successor edges.
348///
349/// \returns The best successor block found, or null if none are viable.
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000350MachineBasicBlock *
351MachineBlockPlacement::selectBestSuccessor(MachineBasicBlock *BB,
352 BlockChain &Chain,
353 const BlockFilterSet *BlockFilter) {
Chandler Carruthb3361722011-11-13 11:34:53 +0000354 const BranchProbability HotProb(4, 5); // 80%
355
Craig Topperc0196b12014-04-14 00:51:57 +0000356 MachineBasicBlock *BestSucc = nullptr;
Chandler Carruth84cd44c2011-11-14 09:12:57 +0000357 // FIXME: Due to the performance of the probability and weight routines in
358 // the MBPI analysis, we manually compute probabilities using the edge
359 // weights. This is suboptimal as it means that the somewhat subtle
360 // definition of edge weight semantics is encoded here as well. We should
Benjamin Kramerbde91762012-06-02 10:20:22 +0000361 // improve the MBPI interface to efficiently support query patterns such as
Chandler Carruth84cd44c2011-11-14 09:12:57 +0000362 // this.
363 uint32_t BestWeight = 0;
Cong Hou36e7e522015-08-05 22:01:20 +0000364 uint32_t SumWeight = MBPI->getSumForBlock(BB);
Chandler Carruthb3361722011-11-13 11:34:53 +0000365 DEBUG(dbgs() << "Attempting merge from: " << getBlockName(BB) << "\n");
Daniel Jaspered9eb722015-02-18 08:19:16 +0000366 for (MachineBasicBlock *Succ : BB->successors()) {
367 if (BlockFilter && !BlockFilter->count(Succ))
Chandler Carruthb3361722011-11-13 11:34:53 +0000368 continue;
Daniel Jaspered9eb722015-02-18 08:19:16 +0000369 BlockChain &SuccChain = *BlockToChain[Succ];
Chandler Carruthb3361722011-11-13 11:34:53 +0000370 if (&SuccChain == &Chain) {
Daniel Jaspered9eb722015-02-18 08:19:16 +0000371 DEBUG(dbgs() << " " << getBlockName(Succ) << " -> Already merged!\n");
Chandler Carruthb3361722011-11-13 11:34:53 +0000372 continue;
373 }
Daniel Jaspered9eb722015-02-18 08:19:16 +0000374 if (Succ != *SuccChain.begin()) {
375 DEBUG(dbgs() << " " << getBlockName(Succ) << " -> Mid chain!\n");
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +0000376 continue;
377 }
Chandler Carruthb3361722011-11-13 11:34:53 +0000378
Daniel Jaspered9eb722015-02-18 08:19:16 +0000379 uint32_t SuccWeight = MBPI->getEdgeWeight(BB, Succ);
Cong Hou36e7e522015-08-05 22:01:20 +0000380 BranchProbability SuccProb(SuccWeight, SumWeight);
Chandler Carruthb3361722011-11-13 11:34:53 +0000381
Daniel Jasper471e8562015-03-04 11:05:34 +0000382 // If we outline optional branches, look whether Succ is unavoidable, i.e.
383 // dominates all terminators of the MachineFunction. If it does, other
384 // successors must be optional. Don't do this for cold branches.
385 if (OutlineOptionalBranches && SuccProb > HotProb.getCompl() &&
Daniel Jasper214997c2015-03-20 10:00:37 +0000386 UnavoidableBlocks.count(Succ) > 0) {
387 auto HasShortOptionalBranch = [&]() {
388 for (MachineBasicBlock *Pred : Succ->predecessors()) {
389 // Check whether there is an unplaced optional branch.
390 if (Pred == Succ || (BlockFilter && !BlockFilter->count(Pred)) ||
391 BlockToChain[Pred] == &Chain)
392 continue;
393 // Check whether the optional branch has exactly one BB.
394 if (Pred->pred_size() > 1 || *Pred->pred_begin() != BB)
395 continue;
396 // Check whether the optional branch is small.
397 if (Pred->size() < OutlineOptionalThreshold)
398 return true;
399 }
400 return false;
401 };
402 if (!HasShortOptionalBranch())
403 return Succ;
404 }
Daniel Jasper471e8562015-03-04 11:05:34 +0000405
Chandler Carruthb3361722011-11-13 11:34:53 +0000406 // Only consider successors which are either "hot", or wouldn't violate
407 // any CFG constraints.
Chandler Carruth18dfac32011-11-20 11:22:06 +0000408 if (SuccChain.LoopPredecessors != 0) {
409 if (SuccProb < HotProb) {
Daniel Jaspered9eb722015-02-18 08:19:16 +0000410 DEBUG(dbgs() << " " << getBlockName(Succ) << " -> " << SuccProb
Chandler Carruth260258b2013-11-25 00:43:41 +0000411 << " (prob) (CFG conflict)\n");
Chandler Carruth18dfac32011-11-20 11:22:06 +0000412 continue;
413 }
414
Daniel Jasper4d7b0432015-02-18 08:18:07 +0000415 // Make sure that a hot successor doesn't have a globally more
416 // important predecessor.
417 BlockFrequency CandidateEdgeFreq =
418 MBFI->getBlockFreq(BB) * SuccProb * HotProb.getCompl();
419 bool BadCFGConflict = false;
Daniel Jaspered9eb722015-02-18 08:19:16 +0000420 for (MachineBasicBlock *Pred : Succ->predecessors()) {
421 if (Pred == Succ || (BlockFilter && !BlockFilter->count(Pred)) ||
422 BlockToChain[Pred] == &Chain)
Chandler Carruthe3288142015-01-14 20:19:29 +0000423 continue;
Daniel Jasper4d7b0432015-02-18 08:18:07 +0000424 BlockFrequency PredEdgeFreq =
Daniel Jaspered9eb722015-02-18 08:19:16 +0000425 MBFI->getBlockFreq(Pred) * MBPI->getEdgeProbability(Pred, Succ);
Daniel Jasper4d7b0432015-02-18 08:18:07 +0000426 if (PredEdgeFreq >= CandidateEdgeFreq) {
427 BadCFGConflict = true;
428 break;
Chandler Carruthe3288142015-01-14 20:19:29 +0000429 }
Chandler Carruth18dfac32011-11-20 11:22:06 +0000430 }
Daniel Jasper4d7b0432015-02-18 08:18:07 +0000431 if (BadCFGConflict) {
Daniel Jaspered9eb722015-02-18 08:19:16 +0000432 DEBUG(dbgs() << " " << getBlockName(Succ) << " -> " << SuccProb
Daniel Jasper4d7b0432015-02-18 08:18:07 +0000433 << " (prob) (non-cold CFG conflict)\n");
434 continue;
435 }
Chandler Carruthb3361722011-11-13 11:34:53 +0000436 }
437
Daniel Jaspered9eb722015-02-18 08:19:16 +0000438 DEBUG(dbgs() << " " << getBlockName(Succ) << " -> " << SuccProb
Chandler Carruthb3361722011-11-13 11:34:53 +0000439 << " (prob)"
440 << (SuccChain.LoopPredecessors != 0 ? " (CFG break)" : "")
441 << "\n");
Chandler Carruth84cd44c2011-11-14 09:12:57 +0000442 if (BestSucc && BestWeight >= SuccWeight)
Chandler Carruthb3361722011-11-13 11:34:53 +0000443 continue;
Daniel Jaspered9eb722015-02-18 08:19:16 +0000444 BestSucc = Succ;
Chandler Carruth84cd44c2011-11-14 09:12:57 +0000445 BestWeight = SuccWeight;
Chandler Carruthb3361722011-11-13 11:34:53 +0000446 }
447 return BestSucc;
448}
449
Chandler Carruthf9213fe2011-11-13 11:42:26 +0000450/// \brief Select the best block from a worklist.
451///
452/// This looks through the provided worklist as a list of candidate basic
453/// blocks and select the most profitable one to place. The definition of
454/// profitable only really makes sense in the context of a loop. This returns
455/// the most frequently visited block in the worklist, which in the case of
456/// a loop, is the one most desirable to be physically close to the rest of the
457/// loop body in order to improve icache behavior.
458///
459/// \returns The best block found, or null if none are viable.
460MachineBasicBlock *MachineBlockPlacement::selectBestCandidateBlock(
Jakub Staszak90616162011-12-21 23:02:08 +0000461 BlockChain &Chain, SmallVectorImpl<MachineBasicBlock *> &WorkList,
462 const BlockFilterSet *BlockFilter) {
Chandler Carruth0af6a0b2011-11-14 09:46:33 +0000463 // Once we need to walk the worklist looking for a candidate, cleanup the
464 // worklist of already placed entries.
465 // FIXME: If this shows up on profiles, it could be folded (at the cost of
466 // some code complexity) into the loop below.
467 WorkList.erase(std::remove_if(WorkList.begin(), WorkList.end(),
Benjamin Kramer3a377bc2014-03-01 11:47:00 +0000468 [&](MachineBasicBlock *BB) {
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000469 return BlockToChain.lookup(BB) == &Chain;
470 }),
Chandler Carruth0af6a0b2011-11-14 09:46:33 +0000471 WorkList.end());
472
Craig Topperc0196b12014-04-14 00:51:57 +0000473 MachineBasicBlock *BestBlock = nullptr;
Chandler Carruthf9213fe2011-11-13 11:42:26 +0000474 BlockFrequency BestFreq;
Chandler Carruth7a715da2015-03-05 03:19:05 +0000475 for (MachineBasicBlock *MBB : WorkList) {
476 BlockChain &SuccChain = *BlockToChain[MBB];
Chandler Carruthf9213fe2011-11-13 11:42:26 +0000477 if (&SuccChain == &Chain) {
Chandler Carruth7a715da2015-03-05 03:19:05 +0000478 DEBUG(dbgs() << " " << getBlockName(MBB) << " -> Already merged!\n");
Chandler Carruthf9213fe2011-11-13 11:42:26 +0000479 continue;
480 }
481 assert(SuccChain.LoopPredecessors == 0 && "Found CFG-violating block");
482
Chandler Carruth7a715da2015-03-05 03:19:05 +0000483 BlockFrequency CandidateFreq = MBFI->getBlockFreq(MBB);
484 DEBUG(dbgs() << " " << getBlockName(MBB) << " -> ";
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000485 MBFI->printBlockFreq(dbgs(), CandidateFreq) << " (freq)\n");
Chandler Carruthf9213fe2011-11-13 11:42:26 +0000486 if (BestBlock && BestFreq >= CandidateFreq)
487 continue;
Chandler Carruth7a715da2015-03-05 03:19:05 +0000488 BestBlock = MBB;
Chandler Carruthf9213fe2011-11-13 11:42:26 +0000489 BestFreq = CandidateFreq;
490 }
491 return BestBlock;
492}
493
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000494/// \brief Retrieve the first unplaced basic block.
495///
496/// This routine is called when we are unable to use the CFG to walk through
497/// all of the basic blocks and form a chain due to unnatural loops in the CFG.
Chandler Carruth9b548a7f2011-11-15 06:26:43 +0000498/// We walk through the function's blocks in order, starting from the
499/// LastUnplacedBlockIt. We update this iterator on each call to avoid
500/// re-scanning the entire sequence on repeated calls to this routine.
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000501MachineBasicBlock *MachineBlockPlacement::getFirstUnplacedBlock(
Chandler Carruth9b548a7f2011-11-15 06:26:43 +0000502 MachineFunction &F, const BlockChain &PlacedChain,
503 MachineFunction::iterator &PrevUnplacedBlockIt,
Jakub Staszak90616162011-12-21 23:02:08 +0000504 const BlockFilterSet *BlockFilter) {
Chandler Carruth9b548a7f2011-11-15 06:26:43 +0000505 for (MachineFunction::iterator I = PrevUnplacedBlockIt, E = F.end(); I != E;
506 ++I) {
507 if (BlockFilter && !BlockFilter->count(I))
508 continue;
Jakub Staszak90616162011-12-21 23:02:08 +0000509 if (BlockToChain[I] != &PlacedChain) {
Chandler Carruth9b548a7f2011-11-15 06:26:43 +0000510 PrevUnplacedBlockIt = I;
Chandler Carruth4a87aa02011-11-23 03:03:21 +0000511 // Now select the head of the chain to which the unplaced block belongs
512 // as the block to place. This will force the entire chain to be placed,
513 // and satisfies the requirements of merging chains.
Jakub Staszak90616162011-12-21 23:02:08 +0000514 return *BlockToChain[I]->begin();
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000515 }
516 }
Craig Topperc0196b12014-04-14 00:51:57 +0000517 return nullptr;
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000518}
519
Chandler Carruth8d150782011-11-13 11:20:44 +0000520void MachineBlockPlacement::buildChain(
Daniel Jasper471e8562015-03-04 11:05:34 +0000521 MachineBasicBlock *BB, BlockChain &Chain,
Chandler Carruth8d150782011-11-13 11:20:44 +0000522 SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
Jakub Staszak90616162011-12-21 23:02:08 +0000523 const BlockFilterSet *BlockFilter) {
Chandler Carruth8d150782011-11-13 11:20:44 +0000524 assert(BB);
Jakub Staszak90616162011-12-21 23:02:08 +0000525 assert(BlockToChain[BB] == &Chain);
Chandler Carruth9b548a7f2011-11-15 06:26:43 +0000526 MachineFunction &F = *BB->getParent();
527 MachineFunction::iterator PrevUnplacedBlockIt = F.begin();
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000528
Chandler Carruth8d150782011-11-13 11:20:44 +0000529 MachineBasicBlock *LoopHeaderBB = BB;
530 markChainSuccessors(Chain, LoopHeaderBB, BlockWorkList, BlockFilter);
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000531 BB = *std::prev(Chain.end());
Chandler Carruth8d150782011-11-13 11:20:44 +0000532 for (;;) {
533 assert(BB);
Jakub Staszak90616162011-12-21 23:02:08 +0000534 assert(BlockToChain[BB] == &Chain);
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000535 assert(*std::prev(Chain.end()) == BB);
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000536
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +0000537 // Look for the best viable successor if there is one to place immediately
538 // after this block.
Duncan Sands291d47e2012-09-14 09:00:11 +0000539 MachineBasicBlock *BestSucc = selectBestSuccessor(BB, Chain, BlockFilter);
Chandler Carruth8d150782011-11-13 11:20:44 +0000540
541 // If an immediate successor isn't available, look for the best viable
542 // block among those we've identified as not violating the loop's CFG at
543 // this point. This won't be a fallthrough, but it will increase locality.
Chandler Carruthf9213fe2011-11-13 11:42:26 +0000544 if (!BestSucc)
545 BestSucc = selectBestCandidateBlock(Chain, BlockWorkList, BlockFilter);
Chandler Carruth8d150782011-11-13 11:20:44 +0000546
Chandler Carruth8d150782011-11-13 11:20:44 +0000547 if (!BestSucc) {
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000548 BestSucc =
549 getFirstUnplacedBlock(F, Chain, PrevUnplacedBlockIt, BlockFilter);
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000550 if (!BestSucc)
551 break;
552
553 DEBUG(dbgs() << "Unnatural loop CFG detected, forcibly merging the "
554 "layout successor until the CFG reduces\n");
Chandler Carruth8d150782011-11-13 11:20:44 +0000555 }
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000556
Chandler Carruth8d150782011-11-13 11:20:44 +0000557 // Place this block, updating the datastructures to reflect its placement.
Jakub Staszak90616162011-12-21 23:02:08 +0000558 BlockChain &SuccChain = *BlockToChain[BestSucc];
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000559 // Zero out LoopPredecessors for the successor we're about to merge in case
560 // we selected a successor that didn't fit naturally into the CFG.
561 SuccChain.LoopPredecessors = 0;
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000562 DEBUG(dbgs() << "Merging from " << getBlockNum(BB) << " to "
563 << getBlockNum(BestSucc) << "\n");
Chandler Carruth8d150782011-11-13 11:20:44 +0000564 markChainSuccessors(SuccChain, LoopHeaderBB, BlockWorkList, BlockFilter);
565 Chain.merge(BestSucc, &SuccChain);
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000566 BB = *std::prev(Chain.end());
Jakub Staszak190c7122011-12-07 19:46:10 +0000567 }
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000568
569 DEBUG(dbgs() << "Finished forming chain for header block "
570 << getBlockNum(*Chain.begin()) << "\n");
Chandler Carruth10281422011-10-21 06:46:38 +0000571}
572
Chandler Carruth03adbd42011-11-27 13:34:33 +0000573/// \brief Find the best loop top block for layout.
Chandler Carruth9ffb97e2011-11-27 00:38:03 +0000574///
Chandler Carruth8c0b41d2012-04-16 13:33:36 +0000575/// Look for a block which is strictly better than the loop header for laying
576/// out at the top of the loop. This looks for one and only one pattern:
577/// a latch block with no conditional exit. This block will cause a conditional
578/// jump around it or will be the bottom of the loop if we lay it out in place,
579/// but if it it doesn't end up at the bottom of the loop for any reason,
580/// rotation alone won't fix it. Because such a block will always result in an
581/// unconditional jump (for the backedge) rotating it in front of the loop
582/// header is always profitable.
583MachineBasicBlock *
584MachineBlockPlacement::findBestLoopTop(MachineLoop &L,
585 const BlockFilterSet &LoopBlockSet) {
586 // Check that the header hasn't been fused with a preheader block due to
587 // crazy branches. If it has, we need to start with the header at the top to
588 // prevent pulling the preheader into the loop body.
589 BlockChain &HeaderChain = *BlockToChain[L.getHeader()];
590 if (!LoopBlockSet.count(*HeaderChain.begin()))
591 return L.getHeader();
592
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000593 DEBUG(dbgs() << "Finding best loop top for: " << getBlockName(L.getHeader())
594 << "\n");
Chandler Carruth8c0b41d2012-04-16 13:33:36 +0000595
596 BlockFrequency BestPredFreq;
Craig Topperc0196b12014-04-14 00:51:57 +0000597 MachineBasicBlock *BestPred = nullptr;
Chandler Carruth7a715da2015-03-05 03:19:05 +0000598 for (MachineBasicBlock *Pred : L.getHeader()->predecessors()) {
Chandler Carruth8c0b41d2012-04-16 13:33:36 +0000599 if (!LoopBlockSet.count(Pred))
600 continue;
601 DEBUG(dbgs() << " header pred: " << getBlockName(Pred) << ", "
Michael Gottesmanb78dec82013-12-14 00:25:45 +0000602 << Pred->succ_size() << " successors, ";
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000603 MBFI->printBlockFreq(dbgs(), Pred) << " freq\n");
Chandler Carruth8c0b41d2012-04-16 13:33:36 +0000604 if (Pred->succ_size() > 1)
605 continue;
606
607 BlockFrequency PredFreq = MBFI->getBlockFreq(Pred);
608 if (!BestPred || PredFreq > BestPredFreq ||
609 (!(PredFreq < BestPredFreq) &&
610 Pred->isLayoutSuccessor(L.getHeader()))) {
611 BestPred = Pred;
612 BestPredFreq = PredFreq;
613 }
614 }
615
616 // If no direct predecessor is fine, just use the loop header.
617 if (!BestPred)
618 return L.getHeader();
619
620 // Walk backwards through any straight line of predecessors.
621 while (BestPred->pred_size() == 1 &&
622 (*BestPred->pred_begin())->succ_size() == 1 &&
623 *BestPred->pred_begin() != L.getHeader())
624 BestPred = *BestPred->pred_begin();
625
626 DEBUG(dbgs() << " final top: " << getBlockName(BestPred) << "\n");
627 return BestPred;
628}
629
Chandler Carruth8c0b41d2012-04-16 13:33:36 +0000630/// \brief Find the best loop exiting block for layout.
631///
Chandler Carruth03adbd42011-11-27 13:34:33 +0000632/// This routine implements the logic to analyze the loop looking for the best
633/// block to layout at the top of the loop. Typically this is done to maximize
634/// fallthrough opportunities.
635MachineBasicBlock *
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000636MachineBlockPlacement::findBestLoopExit(MachineFunction &F, MachineLoop &L,
Chandler Carruthccc7e422012-04-16 01:12:56 +0000637 const BlockFilterSet &LoopBlockSet) {
Chandler Carruth68062612012-04-10 13:35:57 +0000638 // We don't want to layout the loop linearly in all cases. If the loop header
639 // is just a normal basic block in the loop, we want to look for what block
640 // within the loop is the best one to layout at the top. However, if the loop
641 // header has be pre-merged into a chain due to predecessors not having
642 // analyzable branches, *and* the predecessor it is merged with is *not* part
643 // of the loop, rotating the header into the middle of the loop will create
644 // a non-contiguous range of blocks which is Very Bad. So start with the
645 // header and only rotate if safe.
646 BlockChain &HeaderChain = *BlockToChain[L.getHeader()];
647 if (!LoopBlockSet.count(*HeaderChain.begin()))
Craig Topperc0196b12014-04-14 00:51:57 +0000648 return nullptr;
Chandler Carruth68062612012-04-10 13:35:57 +0000649
Chandler Carruth03adbd42011-11-27 13:34:33 +0000650 BlockFrequency BestExitEdgeFreq;
Chandler Carruthccc7e422012-04-16 01:12:56 +0000651 unsigned BestExitLoopDepth = 0;
Craig Topperc0196b12014-04-14 00:51:57 +0000652 MachineBasicBlock *ExitingBB = nullptr;
Chandler Carruth4f567202011-11-27 20:18:00 +0000653 // If there are exits to outer loops, loop rotation can severely limit
654 // fallthrough opportunites unless it selects such an exit. Keep a set of
655 // blocks where rotating to exit with that block will reach an outer loop.
656 SmallPtrSet<MachineBasicBlock *, 4> BlocksExitingToOuterLoop;
657
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000658 DEBUG(dbgs() << "Finding best loop exit for: " << getBlockName(L.getHeader())
659 << "\n");
Chandler Carruth7a715da2015-03-05 03:19:05 +0000660 for (MachineBasicBlock *MBB : L.getBlocks()) {
661 BlockChain &Chain = *BlockToChain[MBB];
Chandler Carruth03adbd42011-11-27 13:34:33 +0000662 // Ensure that this block is at the end of a chain; otherwise it could be
Chandler Carruth9a512a42015-04-15 13:19:54 +0000663 // mid-way through an inner loop or a successor of an unanalyzable branch.
Chandler Carruth7a715da2015-03-05 03:19:05 +0000664 if (MBB != *std::prev(Chain.end()))
Chandler Carruth9ffb97e2011-11-27 00:38:03 +0000665 continue;
Chandler Carruth9ffb97e2011-11-27 00:38:03 +0000666
Chandler Carruth03adbd42011-11-27 13:34:33 +0000667 // Now walk the successors. We need to establish whether this has a viable
668 // exiting successor and whether it has a viable non-exiting successor.
669 // We store the old exiting state and restore it if a viable looping
670 // successor isn't found.
671 MachineBasicBlock *OldExitingBB = ExitingBB;
672 BlockFrequency OldBestExitEdgeFreq = BestExitEdgeFreq;
Chandler Carruthccc7e422012-04-16 01:12:56 +0000673 bool HasLoopingSucc = false;
Chandler Carruth03adbd42011-11-27 13:34:33 +0000674 // FIXME: Due to the performance of the probability and weight routines in
Chandler Carruthccc7e422012-04-16 01:12:56 +0000675 // the MBPI analysis, we use the internal weights and manually compute the
676 // probabilities to avoid quadratic behavior.
Cong Hou36e7e522015-08-05 22:01:20 +0000677 uint32_t SumWeight = MBPI->getSumForBlock(MBB);
Chandler Carruth7a715da2015-03-05 03:19:05 +0000678 for (MachineBasicBlock *Succ : MBB->successors()) {
679 if (Succ->isLandingPad())
Chandler Carruth03adbd42011-11-27 13:34:33 +0000680 continue;
Chandler Carruth7a715da2015-03-05 03:19:05 +0000681 if (Succ == MBB)
Chandler Carruth03adbd42011-11-27 13:34:33 +0000682 continue;
Chandler Carruth7a715da2015-03-05 03:19:05 +0000683 BlockChain &SuccChain = *BlockToChain[Succ];
Chandler Carruth03adbd42011-11-27 13:34:33 +0000684 // Don't split chains, either this chain or the successor's chain.
Chandler Carruthccc7e422012-04-16 01:12:56 +0000685 if (&Chain == &SuccChain) {
Chandler Carruth7a715da2015-03-05 03:19:05 +0000686 DEBUG(dbgs() << " exiting: " << getBlockName(MBB) << " -> "
687 << getBlockName(Succ) << " (chain conflict)\n");
Chandler Carruth03adbd42011-11-27 13:34:33 +0000688 continue;
689 }
690
Chandler Carruth7a715da2015-03-05 03:19:05 +0000691 uint32_t SuccWeight = MBPI->getEdgeWeight(MBB, Succ);
692 if (LoopBlockSet.count(Succ)) {
693 DEBUG(dbgs() << " looping: " << getBlockName(MBB) << " -> "
694 << getBlockName(Succ) << " (" << SuccWeight << ")\n");
Chandler Carruthccc7e422012-04-16 01:12:56 +0000695 HasLoopingSucc = true;
Chandler Carruth03adbd42011-11-27 13:34:33 +0000696 continue;
697 }
698
Chandler Carruthccc7e422012-04-16 01:12:56 +0000699 unsigned SuccLoopDepth = 0;
Chandler Carruth7a715da2015-03-05 03:19:05 +0000700 if (MachineLoop *ExitLoop = MLI->getLoopFor(Succ)) {
Chandler Carruthccc7e422012-04-16 01:12:56 +0000701 SuccLoopDepth = ExitLoop->getLoopDepth();
702 if (ExitLoop->contains(&L))
Chandler Carruth7a715da2015-03-05 03:19:05 +0000703 BlocksExitingToOuterLoop.insert(MBB);
Chandler Carruthccc7e422012-04-16 01:12:56 +0000704 }
705
Cong Hou36e7e522015-08-05 22:01:20 +0000706 BranchProbability SuccProb(SuccWeight, SumWeight);
Chandler Carruth7a715da2015-03-05 03:19:05 +0000707 BlockFrequency ExitEdgeFreq = MBFI->getBlockFreq(MBB) * SuccProb;
708 DEBUG(dbgs() << " exiting: " << getBlockName(MBB) << " -> "
709 << getBlockName(Succ) << " [L:" << SuccLoopDepth << "] (";
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000710 MBFI->printBlockFreq(dbgs(), ExitEdgeFreq) << ")\n");
Benjamin Kramerc8160d62013-11-20 19:08:44 +0000711 // Note that we bias this toward an existing layout successor to retain
712 // incoming order in the absence of better information. The exit must have
713 // a frequency higher than the current exit before we consider breaking
714 // the layout.
715 BranchProbability Bias(100 - ExitBlockBias, 100);
Chandler Carruth26d30172015-04-15 13:39:42 +0000716 if (!ExitingBB || SuccLoopDepth > BestExitLoopDepth ||
Chandler Carruthccc7e422012-04-16 01:12:56 +0000717 ExitEdgeFreq > BestExitEdgeFreq ||
Chandler Carruth7a715da2015-03-05 03:19:05 +0000718 (MBB->isLayoutSuccessor(Succ) &&
Benjamin Kramerc8160d62013-11-20 19:08:44 +0000719 !(ExitEdgeFreq < BestExitEdgeFreq * Bias))) {
Chandler Carruth03adbd42011-11-27 13:34:33 +0000720 BestExitEdgeFreq = ExitEdgeFreq;
Chandler Carruth7a715da2015-03-05 03:19:05 +0000721 ExitingBB = MBB;
Chandler Carrutha0545802011-11-27 09:22:53 +0000722 }
Chandler Carruth9ffb97e2011-11-27 00:38:03 +0000723 }
Chandler Carruth03adbd42011-11-27 13:34:33 +0000724
Chandler Carruthccc7e422012-04-16 01:12:56 +0000725 if (!HasLoopingSucc) {
Chandler Carruthcfb2b9d2015-04-15 13:26:41 +0000726 // Restore the old exiting state, no viable looping successor was found.
Chandler Carruth03adbd42011-11-27 13:34:33 +0000727 ExitingBB = OldExitingBB;
728 BestExitEdgeFreq = OldBestExitEdgeFreq;
Chandler Carrutha0545802011-11-27 09:22:53 +0000729 continue;
Chandler Carruth03adbd42011-11-27 13:34:33 +0000730 }
Chandler Carruth9ffb97e2011-11-27 00:38:03 +0000731 }
Chandler Carruthccc7e422012-04-16 01:12:56 +0000732 // Without a candidate exiting block or with only a single block in the
Chandler Carruth03adbd42011-11-27 13:34:33 +0000733 // loop, just use the loop header to layout the loop.
734 if (!ExitingBB || L.getNumBlocks() == 1)
Craig Topperc0196b12014-04-14 00:51:57 +0000735 return nullptr;
Chandler Carruth9ffb97e2011-11-27 00:38:03 +0000736
Chandler Carruth4f567202011-11-27 20:18:00 +0000737 // Also, if we have exit blocks which lead to outer loops but didn't select
738 // one of them as the exiting block we are rotating toward, disable loop
739 // rotation altogether.
740 if (!BlocksExitingToOuterLoop.empty() &&
741 !BlocksExitingToOuterLoop.count(ExitingBB))
Craig Topperc0196b12014-04-14 00:51:57 +0000742 return nullptr;
Chandler Carruth4f567202011-11-27 20:18:00 +0000743
Chandler Carruth03adbd42011-11-27 13:34:33 +0000744 DEBUG(dbgs() << " Best exiting block: " << getBlockName(ExitingBB) << "\n");
Chandler Carruthccc7e422012-04-16 01:12:56 +0000745 return ExitingBB;
Chandler Carruth9ffb97e2011-11-27 00:38:03 +0000746}
747
Chandler Carruth8c74c7b2012-04-16 09:31:23 +0000748/// \brief Attempt to rotate an exiting block to the bottom of the loop.
749///
750/// Once we have built a chain, try to rotate it to line up the hot exit block
751/// with fallthrough out of the loop if doing so doesn't introduce unnecessary
752/// branches. For example, if the loop has fallthrough into its header and out
753/// of its bottom already, don't rotate it.
754void MachineBlockPlacement::rotateLoop(BlockChain &LoopChain,
755 MachineBasicBlock *ExitingBB,
756 const BlockFilterSet &LoopBlockSet) {
757 if (!ExitingBB)
758 return;
759
760 MachineBasicBlock *Top = *LoopChain.begin();
761 bool ViableTopFallthrough = false;
Chandler Carruth7a715da2015-03-05 03:19:05 +0000762 for (MachineBasicBlock *Pred : Top->predecessors()) {
763 BlockChain *PredChain = BlockToChain[Pred];
764 if (!LoopBlockSet.count(Pred) &&
765 (!PredChain || Pred == *std::prev(PredChain->end()))) {
Chandler Carruth8c74c7b2012-04-16 09:31:23 +0000766 ViableTopFallthrough = true;
767 break;
768 }
769 }
770
771 // If the header has viable fallthrough, check whether the current loop
772 // bottom is a viable exiting block. If so, bail out as rotating will
773 // introduce an unnecessary branch.
774 if (ViableTopFallthrough) {
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000775 MachineBasicBlock *Bottom = *std::prev(LoopChain.end());
Chandler Carruth7a715da2015-03-05 03:19:05 +0000776 for (MachineBasicBlock *Succ : Bottom->successors()) {
777 BlockChain *SuccChain = BlockToChain[Succ];
778 if (!LoopBlockSet.count(Succ) &&
779 (!SuccChain || Succ == *SuccChain->begin()))
Chandler Carruth8c74c7b2012-04-16 09:31:23 +0000780 return;
781 }
782 }
783
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000784 BlockChain::iterator ExitIt =
785 std::find(LoopChain.begin(), LoopChain.end(), ExitingBB);
Chandler Carruth8c74c7b2012-04-16 09:31:23 +0000786 if (ExitIt == LoopChain.end())
787 return;
788
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000789 std::rotate(LoopChain.begin(), std::next(ExitIt), LoopChain.end());
Chandler Carruth8c74c7b2012-04-16 09:31:23 +0000790}
791
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000792/// \brief Forms basic block chains from the natural loop structures.
Chandler Carruth10281422011-10-21 06:46:38 +0000793///
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000794/// These chains are designed to preserve the existing *structure* of the code
795/// as much as possible. We can then stitch the chains together in a way which
796/// both preserves the topological structure and minimizes taken conditional
797/// branches.
Chandler Carruth8d150782011-11-13 11:20:44 +0000798void MachineBlockPlacement::buildLoopChains(MachineFunction &F,
Jakub Staszak90616162011-12-21 23:02:08 +0000799 MachineLoop &L) {
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000800 // First recurse through any nested loops, building chains for those inner
801 // loops.
Chandler Carruth7a715da2015-03-05 03:19:05 +0000802 for (MachineLoop *InnerLoop : L)
803 buildLoopChains(F, *InnerLoop);
Chandler Carruth10281422011-10-21 06:46:38 +0000804
Chandler Carruth8d150782011-11-13 11:20:44 +0000805 SmallVector<MachineBasicBlock *, 16> BlockWorkList;
806 BlockFilterSet LoopBlockSet(L.block_begin(), L.block_end());
Chandler Carruth03adbd42011-11-27 13:34:33 +0000807
Chandler Carruth8c0b41d2012-04-16 13:33:36 +0000808 // First check to see if there is an obviously preferable top block for the
809 // loop. This will default to the header, but may end up as one of the
810 // predecessors to the header if there is one which will result in strictly
811 // fewer branches in the loop body.
812 MachineBasicBlock *LoopTop = findBestLoopTop(L, LoopBlockSet);
813
814 // If we selected just the header for the loop top, look for a potentially
815 // profitable exit block in the event that rotating the loop can eliminate
816 // branches by placing an exit edge at the bottom.
Craig Topperc0196b12014-04-14 00:51:57 +0000817 MachineBasicBlock *ExitingBB = nullptr;
Chandler Carruth8c0b41d2012-04-16 13:33:36 +0000818 if (LoopTop == L.getHeader())
819 ExitingBB = findBestLoopExit(F, L, LoopBlockSet);
820
821 BlockChain &LoopChain = *BlockToChain[LoopTop];
Chandler Carruth10281422011-10-21 06:46:38 +0000822
Chandler Carruth8d150782011-11-13 11:20:44 +0000823 // FIXME: This is a really lame way of walking the chains in the loop: we
824 // walk the blocks, and use a set to prevent visiting a particular chain
825 // twice.
Jakub Staszak90616162011-12-21 23:02:08 +0000826 SmallPtrSet<BlockChain *, 4> UpdatedPreds;
Jakub Staszak190c7122011-12-07 19:46:10 +0000827 assert(LoopChain.LoopPredecessors == 0);
828 UpdatedPreds.insert(&LoopChain);
Chandler Carruth7a715da2015-03-05 03:19:05 +0000829 for (MachineBasicBlock *LoopBB : L.getBlocks()) {
830 BlockChain &Chain = *BlockToChain[LoopBB];
David Blaikie70573dc2014-11-19 07:49:26 +0000831 if (!UpdatedPreds.insert(&Chain).second)
Chandler Carruth8d150782011-11-13 11:20:44 +0000832 continue;
833
834 assert(Chain.LoopPredecessors == 0);
Chandler Carruth7a715da2015-03-05 03:19:05 +0000835 for (MachineBasicBlock *ChainBB : Chain) {
836 assert(BlockToChain[ChainBB] == &Chain);
837 for (MachineBasicBlock *Pred : ChainBB->predecessors()) {
838 if (BlockToChain[Pred] == &Chain || !LoopBlockSet.count(Pred))
Chandler Carruth8d150782011-11-13 11:20:44 +0000839 continue;
840 ++Chain.LoopPredecessors;
841 }
842 }
843
844 if (Chain.LoopPredecessors == 0)
Chandler Carruthd394baf2011-11-24 08:46:04 +0000845 BlockWorkList.push_back(*Chain.begin());
Chandler Carruth10281422011-10-21 06:46:38 +0000846 }
Chandler Carruth8d150782011-11-13 11:20:44 +0000847
Chandler Carruth8c0b41d2012-04-16 13:33:36 +0000848 buildChain(LoopTop, LoopChain, BlockWorkList, &LoopBlockSet);
Chandler Carruth8c74c7b2012-04-16 09:31:23 +0000849 rotateLoop(LoopChain, ExitingBB, LoopBlockSet);
Chandler Carruth8d150782011-11-13 11:20:44 +0000850
851 DEBUG({
Chandler Carruth8e1d9062011-11-13 21:39:51 +0000852 // Crash at the end so we get all of the debugging output first.
853 bool BadLoop = false;
854 if (LoopChain.LoopPredecessors) {
855 BadLoop = true;
Chandler Carruth8d150782011-11-13 11:20:44 +0000856 dbgs() << "Loop chain contains a block without its preds placed!\n"
857 << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
858 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n";
Chandler Carruth8e1d9062011-11-13 21:39:51 +0000859 }
Chandler Carruth7a715da2015-03-05 03:19:05 +0000860 for (MachineBasicBlock *ChainBB : LoopChain) {
861 dbgs() << " ... " << getBlockName(ChainBB) << "\n";
862 if (!LoopBlockSet.erase(ChainBB)) {
Chandler Carruth0a31d142011-11-14 10:55:53 +0000863 // We don't mark the loop as bad here because there are real situations
864 // where this can occur. For example, with an unanalyzable fallthrough
Chandler Carruth99fe42f2011-11-23 10:35:36 +0000865 // from a loop block to a non-loop block or vice versa.
Chandler Carruth8d150782011-11-13 11:20:44 +0000866 dbgs() << "Loop chain contains a block not contained by the loop!\n"
867 << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
868 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
Chandler Carruth7a715da2015-03-05 03:19:05 +0000869 << " Bad block: " << getBlockName(ChainBB) << "\n";
Chandler Carruth8e1d9062011-11-13 21:39:51 +0000870 }
Chandler Carruthccc7e422012-04-16 01:12:56 +0000871 }
Chandler Carruth8d150782011-11-13 11:20:44 +0000872
Chandler Carruth8e1d9062011-11-13 21:39:51 +0000873 if (!LoopBlockSet.empty()) {
874 BadLoop = true;
Chandler Carruth7a715da2015-03-05 03:19:05 +0000875 for (MachineBasicBlock *LoopBB : LoopBlockSet)
Chandler Carruth8d150782011-11-13 11:20:44 +0000876 dbgs() << "Loop contains blocks never placed into a chain!\n"
877 << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
878 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
Chandler Carruth7a715da2015-03-05 03:19:05 +0000879 << " Bad block: " << getBlockName(LoopBB) << "\n";
Chandler Carruth8e1d9062011-11-13 21:39:51 +0000880 }
881 assert(!BadLoop && "Detected problems with the placement of this loop.");
Chandler Carruth8d150782011-11-13 11:20:44 +0000882 });
Chandler Carruth10281422011-10-21 06:46:38 +0000883}
884
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000885void MachineBlockPlacement::buildCFGChains(MachineFunction &F) {
Chandler Carruth8d150782011-11-13 11:20:44 +0000886 // Ensure that every BB in the function has an associated chain to simplify
887 // the assumptions of the remaining algorithm.
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +0000888 SmallVector<MachineOperand, 4> Cond; // For AnalyzeBranch.
889 for (MachineFunction::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
890 MachineBasicBlock *BB = FI;
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000891 BlockChain *Chain =
892 new (ChainAllocator.Allocate()) BlockChain(BlockToChain, BB);
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +0000893 // Also, merge any blocks which we cannot reason about and must preserve
894 // the exact fallthrough behavior for.
895 for (;;) {
896 Cond.clear();
Craig Topperc0196b12014-04-14 00:51:57 +0000897 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +0000898 if (!TII->AnalyzeBranch(*BB, TBB, FBB, Cond) || !FI->canFallThrough())
899 break;
900
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000901 MachineFunction::iterator NextFI(std::next(FI));
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +0000902 MachineBasicBlock *NextBB = NextFI;
903 // Ensure that the layout successor is a viable block, as we know that
904 // fallthrough is a possibility.
905 assert(NextFI != FE && "Can't fallthrough past the last block.");
906 DEBUG(dbgs() << "Pre-merging due to unanalyzable fallthrough: "
907 << getBlockName(BB) << " -> " << getBlockName(NextBB)
908 << "\n");
Craig Topperc0196b12014-04-14 00:51:57 +0000909 Chain->merge(NextBB, nullptr);
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +0000910 FI = NextFI;
911 BB = NextBB;
912 }
913 }
Chandler Carruth8d150782011-11-13 11:20:44 +0000914
Daniel Jasper471e8562015-03-04 11:05:34 +0000915 if (OutlineOptionalBranches) {
916 // Find the nearest common dominator of all of F's terminators.
917 MachineBasicBlock *Terminator = nullptr;
918 for (MachineBasicBlock &MBB : F) {
919 if (MBB.succ_size() == 0) {
920 if (Terminator == nullptr)
921 Terminator = &MBB;
922 else
923 Terminator = MDT->findNearestCommonDominator(Terminator, &MBB);
924 }
925 }
926
927 // MBBs dominating this common dominator are unavoidable.
928 UnavoidableBlocks.clear();
929 for (MachineBasicBlock &MBB : F) {
930 if (MDT->dominates(&MBB, Terminator)) {
931 UnavoidableBlocks.insert(&MBB);
932 }
933 }
934 }
935
Chandler Carruth8d150782011-11-13 11:20:44 +0000936 // Build any loop-based chains.
Chandler Carruth7a715da2015-03-05 03:19:05 +0000937 for (MachineLoop *L : *MLI)
938 buildLoopChains(F, *L);
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000939
Chandler Carruth8d150782011-11-13 11:20:44 +0000940 SmallVector<MachineBasicBlock *, 16> BlockWorkList;
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000941
Chandler Carruth8d150782011-11-13 11:20:44 +0000942 SmallPtrSet<BlockChain *, 4> UpdatedPreds;
Chandler Carruth7a715da2015-03-05 03:19:05 +0000943 for (MachineBasicBlock &MBB : F) {
944 BlockChain &Chain = *BlockToChain[&MBB];
David Blaikie70573dc2014-11-19 07:49:26 +0000945 if (!UpdatedPreds.insert(&Chain).second)
Chandler Carruth8d150782011-11-13 11:20:44 +0000946 continue;
947
948 assert(Chain.LoopPredecessors == 0);
Chandler Carruth7a715da2015-03-05 03:19:05 +0000949 for (MachineBasicBlock *ChainBB : Chain) {
950 assert(BlockToChain[ChainBB] == &Chain);
951 for (MachineBasicBlock *Pred : ChainBB->predecessors()) {
952 if (BlockToChain[Pred] == &Chain)
Chandler Carruth8d150782011-11-13 11:20:44 +0000953 continue;
954 ++Chain.LoopPredecessors;
955 }
956 }
957
958 if (Chain.LoopPredecessors == 0)
Chandler Carruthd394baf2011-11-24 08:46:04 +0000959 BlockWorkList.push_back(*Chain.begin());
Chandler Carruth8d150782011-11-13 11:20:44 +0000960 }
961
962 BlockChain &FunctionChain = *BlockToChain[&F.front()];
Chandler Carruth9b548a7f2011-11-15 06:26:43 +0000963 buildChain(&F.front(), FunctionChain, BlockWorkList);
Chandler Carruth8d150782011-11-13 11:20:44 +0000964
Matt Arsenault0f5f0152013-12-10 18:55:37 +0000965#ifndef NDEBUG
Matt Arsenault79d55f52013-12-05 20:02:18 +0000966 typedef SmallPtrSet<MachineBasicBlock *, 16> FunctionBlockSetType;
Matt Arsenault0f5f0152013-12-10 18:55:37 +0000967#endif
Chandler Carruth8d150782011-11-13 11:20:44 +0000968 DEBUG({
Chandler Carruth8e1d9062011-11-13 21:39:51 +0000969 // Crash at the end so we get all of the debugging output first.
970 bool BadFunc = false;
Chandler Carruth8d150782011-11-13 11:20:44 +0000971 FunctionBlockSetType FunctionBlockSet;
Chandler Carruth7a715da2015-03-05 03:19:05 +0000972 for (MachineBasicBlock &MBB : F)
973 FunctionBlockSet.insert(&MBB);
Chandler Carruth8d150782011-11-13 11:20:44 +0000974
Chandler Carruth7a715da2015-03-05 03:19:05 +0000975 for (MachineBasicBlock *ChainBB : FunctionChain)
976 if (!FunctionBlockSet.erase(ChainBB)) {
Chandler Carruth8e1d9062011-11-13 21:39:51 +0000977 BadFunc = true;
Chandler Carruth8d150782011-11-13 11:20:44 +0000978 dbgs() << "Function chain contains a block not in the function!\n"
Chandler Carruth7a715da2015-03-05 03:19:05 +0000979 << " Bad block: " << getBlockName(ChainBB) << "\n";
Chandler Carruth8e1d9062011-11-13 21:39:51 +0000980 }
Chandler Carruth8d150782011-11-13 11:20:44 +0000981
Chandler Carruth8e1d9062011-11-13 21:39:51 +0000982 if (!FunctionBlockSet.empty()) {
983 BadFunc = true;
Chandler Carruth7a715da2015-03-05 03:19:05 +0000984 for (MachineBasicBlock *RemainingBB : FunctionBlockSet)
Chandler Carruth8d150782011-11-13 11:20:44 +0000985 dbgs() << "Function contains blocks never placed into a chain!\n"
Chandler Carruth7a715da2015-03-05 03:19:05 +0000986 << " Bad block: " << getBlockName(RemainingBB) << "\n";
Chandler Carruth8e1d9062011-11-13 21:39:51 +0000987 }
988 assert(!BadFunc && "Detected problems with the block placement.");
Chandler Carruth8d150782011-11-13 11:20:44 +0000989 });
990
991 // Splice the blocks into place.
992 MachineFunction::iterator InsertPos = F.begin();
Chandler Carruth7a715da2015-03-05 03:19:05 +0000993 for (MachineBasicBlock *ChainBB : FunctionChain) {
994 DEBUG(dbgs() << (ChainBB == *FunctionChain.begin() ? "Placing chain "
995 : " ... ")
996 << getBlockName(ChainBB) << "\n");
997 if (InsertPos != MachineFunction::iterator(ChainBB))
998 F.splice(InsertPos, ChainBB);
Chandler Carruth8d150782011-11-13 11:20:44 +0000999 else
1000 ++InsertPos;
1001
1002 // Update the terminator of the previous block.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001003 if (ChainBB == *FunctionChain.begin())
Chandler Carruth8d150782011-11-13 11:20:44 +00001004 continue;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001005 MachineBasicBlock *PrevBB = std::prev(MachineFunction::iterator(ChainBB));
Chandler Carruth8d150782011-11-13 11:20:44 +00001006
Chandler Carruth10281422011-10-21 06:46:38 +00001007 // FIXME: It would be awesome of updateTerminator would just return rather
1008 // than assert when the branch cannot be analyzed in order to remove this
1009 // boiler plate.
1010 Cond.clear();
Craig Topperc0196b12014-04-14 00:51:57 +00001011 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
Manman Ren2b6a0df2012-07-31 01:11:07 +00001012 if (!TII->AnalyzeBranch(*PrevBB, TBB, FBB, Cond)) {
Shuxin Yang8b8fd212013-06-04 01:00:57 +00001013 // The "PrevBB" is not yet updated to reflect current code layout, so,
1014 // o. it may fall-through to a block without explict "goto" instruction
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001015 // before layout, and no longer fall-through it after layout; or
Shuxin Yang8b8fd212013-06-04 01:00:57 +00001016 // o. just opposite.
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001017 //
Shuxin Yang8b8fd212013-06-04 01:00:57 +00001018 // AnalyzeBranch() may return erroneous value for FBB when these two
1019 // situations take place. For the first scenario FBB is mistakenly set
1020 // NULL; for the 2nd scenario, the FBB, which is expected to be NULL,
1021 // is mistakenly pointing to "*BI".
1022 //
1023 bool needUpdateBr = true;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001024 if (!Cond.empty() && (!FBB || FBB == ChainBB)) {
Shuxin Yang8b8fd212013-06-04 01:00:57 +00001025 PrevBB->updateTerminator();
1026 needUpdateBr = false;
1027 Cond.clear();
Craig Topperc0196b12014-04-14 00:51:57 +00001028 TBB = FBB = nullptr;
Shuxin Yang8b8fd212013-06-04 01:00:57 +00001029 if (TII->AnalyzeBranch(*PrevBB, TBB, FBB, Cond)) {
1030 // FIXME: This should never take place.
Craig Topperc0196b12014-04-14 00:51:57 +00001031 TBB = FBB = nullptr;
Shuxin Yang8b8fd212013-06-04 01:00:57 +00001032 }
1033 }
1034
Manman Ren2b6a0df2012-07-31 01:11:07 +00001035 // If PrevBB has a two-way branch, try to re-order the branches
1036 // such that we branch to the successor with higher weight first.
1037 if (TBB && !Cond.empty() && FBB &&
1038 MBPI->getEdgeWeight(PrevBB, FBB) > MBPI->getEdgeWeight(PrevBB, TBB) &&
1039 !TII->ReverseBranchCondition(Cond)) {
1040 DEBUG(dbgs() << "Reverse order of the two branches: "
1041 << getBlockName(PrevBB) << "\n");
1042 DEBUG(dbgs() << " Edge weight: " << MBPI->getEdgeWeight(PrevBB, FBB)
1043 << " vs " << MBPI->getEdgeWeight(PrevBB, TBB) << "\n");
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001044 DebugLoc dl; // FIXME: this is nowhere
Manman Ren2b6a0df2012-07-31 01:11:07 +00001045 TII->RemoveBranch(*PrevBB);
1046 TII->InsertBranch(*PrevBB, FBB, TBB, Cond, dl);
Shuxin Yang8b8fd212013-06-04 01:00:57 +00001047 needUpdateBr = true;
Manman Ren2b6a0df2012-07-31 01:11:07 +00001048 }
Shuxin Yang8b8fd212013-06-04 01:00:57 +00001049 if (needUpdateBr)
1050 PrevBB->updateTerminator();
Manman Ren2b6a0df2012-07-31 01:11:07 +00001051 }
Chandler Carruth10281422011-10-21 06:46:38 +00001052 }
Chandler Carruth8d150782011-11-13 11:20:44 +00001053
1054 // Fixup the last block.
1055 Cond.clear();
Craig Topperc0196b12014-04-14 00:51:57 +00001056 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
Chandler Carruth8d150782011-11-13 11:20:44 +00001057 if (!TII->AnalyzeBranch(F.back(), TBB, FBB, Cond))
1058 F.back().updateTerminator();
Chandler Carruth10281422011-10-21 06:46:38 +00001059
Chandler Carruthccc7e422012-04-16 01:12:56 +00001060 // Walk through the backedges of the function now that we have fully laid out
1061 // the basic blocks and align the destination of each backedge. We don't rely
Chandler Carruth881d0a72012-08-07 09:45:24 +00001062 // exclusively on the loop info here so that we can align backedges in
1063 // unnatural CFGs and backedges that were introduced purely because of the
1064 // loop rotations done during this layout pass.
Sanjay Patel924879a2015-08-04 15:49:57 +00001065 // FIXME: Use Function::optForSize().
Duncan P. N. Exon Smith70eb9c52015-02-14 01:44:41 +00001066 if (F.getFunction()->hasFnAttribute(Attribute::OptimizeForSize))
Chandler Carruth8b9737c2011-10-21 08:57:37 +00001067 return;
Chandler Carruth881d0a72012-08-07 09:45:24 +00001068 if (FunctionChain.begin() == FunctionChain.end())
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001069 return; // Empty chain.
Chandler Carruth8b9737c2011-10-21 08:57:37 +00001070
Chandler Carruth881d0a72012-08-07 09:45:24 +00001071 const BranchProbability ColdProb(1, 5); // 20%
1072 BlockFrequency EntryFreq = MBFI->getBlockFreq(F.begin());
1073 BlockFrequency WeightedEntryFreq = EntryFreq * ColdProb;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001074 for (MachineBasicBlock *ChainBB : FunctionChain) {
1075 if (ChainBB == *FunctionChain.begin())
1076 continue;
1077
Chandler Carruth881d0a72012-08-07 09:45:24 +00001078 // Don't align non-looping basic blocks. These are unlikely to execute
1079 // enough times to matter in practice. Note that we'll still handle
1080 // unnatural CFGs inside of a natural outer loop (the common case) and
1081 // rotated loops.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001082 MachineLoop *L = MLI->getLoopFor(ChainBB);
Chandler Carruth881d0a72012-08-07 09:45:24 +00001083 if (!L)
1084 continue;
1085
Hal Finkel57725662015-01-03 17:58:24 +00001086 unsigned Align = TLI->getPrefLoopAlignment(L);
1087 if (!Align)
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001088 continue; // Don't care about loop alignment.
Hal Finkel57725662015-01-03 17:58:24 +00001089
Chandler Carruth881d0a72012-08-07 09:45:24 +00001090 // If the block is cold relative to the function entry don't waste space
1091 // aligning it.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001092 BlockFrequency Freq = MBFI->getBlockFreq(ChainBB);
Chandler Carruth881d0a72012-08-07 09:45:24 +00001093 if (Freq < WeightedEntryFreq)
1094 continue;
1095
1096 // If the block is cold relative to its loop header, don't align it
1097 // regardless of what edges into the block exist.
1098 MachineBasicBlock *LoopHeader = L->getHeader();
1099 BlockFrequency LoopHeaderFreq = MBFI->getBlockFreq(LoopHeader);
1100 if (Freq < (LoopHeaderFreq * ColdProb))
1101 continue;
1102
1103 // Check for the existence of a non-layout predecessor which would benefit
1104 // from aligning this block.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001105 MachineBasicBlock *LayoutPred =
1106 &*std::prev(MachineFunction::iterator(ChainBB));
Chandler Carruth881d0a72012-08-07 09:45:24 +00001107
1108 // Force alignment if all the predecessors are jumps. We already checked
1109 // that the block isn't cold above.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001110 if (!LayoutPred->isSuccessor(ChainBB)) {
1111 ChainBB->setAlignment(Align);
Chandler Carruth881d0a72012-08-07 09:45:24 +00001112 continue;
1113 }
1114
1115 // Align this block if the layout predecessor's edge into this block is
Nadav Rotem6036f582013-03-29 16:34:23 +00001116 // cold relative to the block. When this is true, other predecessors make up
Chandler Carruth881d0a72012-08-07 09:45:24 +00001117 // all of the hot entries into the block and thus alignment is likely to be
1118 // important.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001119 BranchProbability LayoutProb =
1120 MBPI->getEdgeProbability(LayoutPred, ChainBB);
Chandler Carruth881d0a72012-08-07 09:45:24 +00001121 BlockFrequency LayoutEdgeFreq = MBFI->getBlockFreq(LayoutPred) * LayoutProb;
1122 if (LayoutEdgeFreq <= (Freq * ColdProb))
Chandler Carruth7a715da2015-03-05 03:19:05 +00001123 ChainBB->setAlignment(Align);
Chandler Carruthccc7e422012-04-16 01:12:56 +00001124 }
Chandler Carruth8b9737c2011-10-21 08:57:37 +00001125}
1126
Chandler Carruth10281422011-10-21 06:46:38 +00001127bool MachineBlockPlacement::runOnMachineFunction(MachineFunction &F) {
1128 // Check for single-block functions and skip them.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001129 if (std::next(F.begin()) == F.end())
Chandler Carruth10281422011-10-21 06:46:38 +00001130 return false;
1131
Paul Robinson7c99ec52014-03-31 17:43:35 +00001132 if (skipOptnoneFunction(*F.getFunction()))
1133 return false;
1134
Chandler Carruth10281422011-10-21 06:46:38 +00001135 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
1136 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
Chandler Carruth8b9737c2011-10-21 08:57:37 +00001137 MLI = &getAnalysis<MachineLoopInfo>();
Eric Christopherfc6de422014-08-05 02:39:49 +00001138 TII = F.getSubtarget().getInstrInfo();
1139 TLI = F.getSubtarget().getTargetLowering();
Daniel Jasper471e8562015-03-04 11:05:34 +00001140 MDT = &getAnalysis<MachineDominatorTree>();
Chandler Carruth10281422011-10-21 06:46:38 +00001141 assert(BlockToChain.empty());
Chandler Carruth10281422011-10-21 06:46:38 +00001142
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00001143 buildCFGChains(F);
Chandler Carruth10281422011-10-21 06:46:38 +00001144
Chandler Carruth10281422011-10-21 06:46:38 +00001145 BlockToChain.clear();
Chandler Carruthfd9b4d92011-11-14 10:57:23 +00001146 ChainAllocator.DestroyAll();
Chandler Carruth10281422011-10-21 06:46:38 +00001147
Nadav Rotemc0adc9f2013-04-12 01:24:16 +00001148 if (AlignAllBlock)
1149 // Align all of the blocks in the function to a specific alignment.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001150 for (MachineBasicBlock &MBB : F)
1151 MBB.setAlignment(AlignAllBlock);
Nadav Rotemc0adc9f2013-04-12 01:24:16 +00001152
Chandler Carruth10281422011-10-21 06:46:38 +00001153 // We always return true as we have no way to track whether the final order
1154 // differs from the original order.
1155 return true;
1156}
Chandler Carruthae4e8002011-11-02 07:17:12 +00001157
1158namespace {
1159/// \brief A pass to compute block placement statistics.
1160///
1161/// A separate pass to compute interesting statistics for evaluating block
1162/// placement. This is separate from the actual placement pass so that they can
Benjamin Kramerbde91762012-06-02 10:20:22 +00001163/// be computed in the absence of any placement transformations or when using
Chandler Carruthae4e8002011-11-02 07:17:12 +00001164/// alternative placement strategies.
1165class MachineBlockPlacementStats : public MachineFunctionPass {
1166 /// \brief A handle to the branch probability pass.
1167 const MachineBranchProbabilityInfo *MBPI;
1168
1169 /// \brief A handle to the function-wide block frequency pass.
1170 const MachineBlockFrequencyInfo *MBFI;
1171
1172public:
1173 static char ID; // Pass identification, replacement for typeid
1174 MachineBlockPlacementStats() : MachineFunctionPass(ID) {
1175 initializeMachineBlockPlacementStatsPass(*PassRegistry::getPassRegistry());
1176 }
1177
Craig Topper4584cd52014-03-07 09:26:03 +00001178 bool runOnMachineFunction(MachineFunction &F) override;
Chandler Carruthae4e8002011-11-02 07:17:12 +00001179
Craig Topper4584cd52014-03-07 09:26:03 +00001180 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruthae4e8002011-11-02 07:17:12 +00001181 AU.addRequired<MachineBranchProbabilityInfo>();
1182 AU.addRequired<MachineBlockFrequencyInfo>();
1183 AU.setPreservesAll();
1184 MachineFunctionPass::getAnalysisUsage(AU);
1185 }
Chandler Carruthae4e8002011-11-02 07:17:12 +00001186};
Alexander Kornienkof00654e2015-06-23 09:49:53 +00001187}
Chandler Carruthae4e8002011-11-02 07:17:12 +00001188
1189char MachineBlockPlacementStats::ID = 0;
Andrew Trick1fa5bcb2012-02-08 21:23:13 +00001190char &llvm::MachineBlockPlacementStatsID = MachineBlockPlacementStats::ID;
Chandler Carruthae4e8002011-11-02 07:17:12 +00001191INITIALIZE_PASS_BEGIN(MachineBlockPlacementStats, "block-placement-stats",
1192 "Basic Block Placement Stats", false, false)
1193INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
1194INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
1195INITIALIZE_PASS_END(MachineBlockPlacementStats, "block-placement-stats",
1196 "Basic Block Placement Stats", false, false)
1197
Chandler Carruthae4e8002011-11-02 07:17:12 +00001198bool MachineBlockPlacementStats::runOnMachineFunction(MachineFunction &F) {
1199 // Check for single-block functions and skip them.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001200 if (std::next(F.begin()) == F.end())
Chandler Carruthae4e8002011-11-02 07:17:12 +00001201 return false;
1202
1203 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
1204 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
1205
Chandler Carruth7a715da2015-03-05 03:19:05 +00001206 for (MachineBasicBlock &MBB : F) {
1207 BlockFrequency BlockFreq = MBFI->getBlockFreq(&MBB);
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001208 Statistic &NumBranches =
Chandler Carruth7a715da2015-03-05 03:19:05 +00001209 (MBB.succ_size() > 1) ? NumCondBranches : NumUncondBranches;
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001210 Statistic &BranchTakenFreq =
Chandler Carruth7a715da2015-03-05 03:19:05 +00001211 (MBB.succ_size() > 1) ? CondBranchTakenFreq : UncondBranchTakenFreq;
1212 for (MachineBasicBlock *Succ : MBB.successors()) {
Chandler Carruthae4e8002011-11-02 07:17:12 +00001213 // Skip if this successor is a fallthrough.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001214 if (MBB.isLayoutSuccessor(Succ))
Chandler Carruthae4e8002011-11-02 07:17:12 +00001215 continue;
1216
Chandler Carruth7a715da2015-03-05 03:19:05 +00001217 BlockFrequency EdgeFreq =
1218 BlockFreq * MBPI->getEdgeProbability(&MBB, Succ);
Chandler Carruthae4e8002011-11-02 07:17:12 +00001219 ++NumBranches;
1220 BranchTakenFreq += EdgeFreq.getFrequency();
1221 }
1222 }
1223
1224 return false;
1225}