blob: 40e3840e6b0b39b5113ec0cb132554e9bcaf0fdf [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"
Haicheng Wu5b458cc2016-06-09 15:24:29 +000029#include "llvm/CodeGen/TargetPassConfig.h"
30#include "BranchFolding.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000031#include "llvm/ADT/DenseMap.h"
32#include "llvm/ADT/SmallPtrSet.h"
33#include "llvm/ADT/SmallVector.h"
34#include "llvm/ADT/Statistic.h"
Chandler Carruth8b9737c2011-10-21 08:57:37 +000035#include "llvm/CodeGen/MachineBasicBlock.h"
Chandler Carruth10281422011-10-21 06:46:38 +000036#include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
37#include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
Daniel Jasper471e8562015-03-04 11:05:34 +000038#include "llvm/CodeGen/MachineDominators.h"
Chandler Carruth10281422011-10-21 06:46:38 +000039#include "llvm/CodeGen/MachineFunction.h"
Chandler Carruth10281422011-10-21 06:46:38 +000040#include "llvm/CodeGen/MachineFunctionPass.h"
Chandler Carruth8b9737c2011-10-21 08:57:37 +000041#include "llvm/CodeGen/MachineLoopInfo.h"
42#include "llvm/CodeGen/MachineModuleInfo.h"
Kyle Butt0846e562016-10-11 20:36:43 +000043#include "llvm/CodeGen/TailDuplicator.h"
Chandler Carruth10281422011-10-21 06:46:38 +000044#include "llvm/Support/Allocator.h"
Nadav Rotemc3b0f502013-04-12 00:48:32 +000045#include "llvm/Support/CommandLine.h"
Chandler Carruthbd1be4d2011-10-23 09:18:45 +000046#include "llvm/Support/Debug.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000047#include "llvm/Support/raw_ostream.h"
Chandler Carruth10281422011-10-21 06:46:38 +000048#include "llvm/Target/TargetInstrInfo.h"
Chandler Carruth8b9737c2011-10-21 08:57:37 +000049#include "llvm/Target/TargetLowering.h"
Eric Christopherd9134482014-08-04 21:25:23 +000050#include "llvm/Target/TargetSubtargetInfo.h"
Chandler Carruth10281422011-10-21 06:46:38 +000051#include <algorithm>
52using namespace llvm;
53
Chandler Carruthd0dced52015-03-05 02:28:25 +000054#define DEBUG_TYPE "block-placement"
Chandler Carruth1b9dde02014-04-22 02:02:50 +000055
Chandler Carruthae4e8002011-11-02 07:17:12 +000056STATISTIC(NumCondBranches, "Number of conditional branches");
Craig Topper77ec0772015-09-16 03:52:32 +000057STATISTIC(NumUncondBranches, "Number of unconditional branches");
Chandler Carruthae4e8002011-11-02 07:17:12 +000058STATISTIC(CondBranchTakenFreq,
59 "Potential frequency of taking conditional branches");
60STATISTIC(UncondBranchTakenFreq,
61 "Potential frequency of taking unconditional branches");
62
Nadav Rotemc3b0f502013-04-12 00:48:32 +000063static cl::opt<unsigned> AlignAllBlock("align-all-blocks",
64 cl::desc("Force the alignment of all "
65 "blocks in the function."),
66 cl::init(0), cl::Hidden);
67
Geoff Berry10494ac2016-01-21 17:25:52 +000068static cl::opt<unsigned> AlignAllNonFallThruBlocks(
69 "align-all-nofallthru-blocks",
70 cl::desc("Force the alignment of all "
71 "blocks that have no fall-through predecessors (i.e. don't add "
72 "nops that are executed)."),
73 cl::init(0), cl::Hidden);
74
Benjamin Kramerc8160d62013-11-20 19:08:44 +000075// FIXME: Find a good default for this flag and remove the flag.
Chandler Carruth2fc3fe12015-03-05 02:35:31 +000076static cl::opt<unsigned> ExitBlockBias(
77 "block-placement-exit-block-bias",
78 cl::desc("Block frequency percentage a loop exit block needs "
79 "over the original exit to be considered the new exit."),
80 cl::init(0), cl::Hidden);
Benjamin Kramerc8160d62013-11-20 19:08:44 +000081
Sjoerd Meijer5e11a182016-07-27 08:49:23 +000082// Definition:
83// - Outlining: placement of a basic block outside the chain or hot path.
84
Daniel Jasper471e8562015-03-04 11:05:34 +000085static cl::opt<bool> OutlineOptionalBranches(
86 "outline-optional-branches",
Sjoerd Meijer5e11a182016-07-27 08:49:23 +000087 cl::desc("Outlining optional branches will place blocks that are optional "
88 "branches, i.e. branches with a common post dominator, outside "
89 "the hot path or chain"),
Daniel Jasper471e8562015-03-04 11:05:34 +000090 cl::init(false), cl::Hidden);
91
Daniel Jasper214997c2015-03-20 10:00:37 +000092static cl::opt<unsigned> OutlineOptionalThreshold(
93 "outline-optional-threshold",
94 cl::desc("Don't outline optional branches that are a single block with an "
95 "instruction count below this threshold"),
96 cl::init(4), cl::Hidden);
97
Cong Houb90b9e02015-11-02 21:24:00 +000098static cl::opt<unsigned> LoopToColdBlockRatio(
99 "loop-to-cold-block-ratio",
100 cl::desc("Outline loop blocks from loop chain if (frequency of loop) / "
101 "(frequency of block) is greater than this ratio"),
102 cl::init(5), cl::Hidden);
103
Cong Hou7745dbc2015-10-19 23:16:40 +0000104static cl::opt<bool>
105 PreciseRotationCost("precise-rotation-cost",
106 cl::desc("Model the cost of loop rotation more "
107 "precisely by using profile data."),
108 cl::init(false), cl::Hidden);
Xinliang David Lif0ab6df2016-05-12 02:04:41 +0000109static cl::opt<bool>
110 ForcePreciseRotationCost("force-precise-rotation-cost",
Xinliang David Lib840bb82016-05-12 16:39:02 +0000111 cl::desc("Force the use of precise cost "
112 "loop rotation strategy."),
Xinliang David Lif0ab6df2016-05-12 02:04:41 +0000113 cl::init(false), cl::Hidden);
Cong Hou7745dbc2015-10-19 23:16:40 +0000114
115static cl::opt<unsigned> MisfetchCost(
116 "misfetch-cost",
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +0000117 cl::desc("Cost that models the probabilistic risk of an instruction "
Cong Hou7745dbc2015-10-19 23:16:40 +0000118 "misfetch due to a jump comparing to falling through, whose cost "
119 "is zero."),
120 cl::init(1), cl::Hidden);
121
122static cl::opt<unsigned> JumpInstCost("jump-inst-cost",
123 cl::desc("Cost of jump instructions."),
124 cl::init(1), cl::Hidden);
Kyle Butt0846e562016-10-11 20:36:43 +0000125static cl::opt<bool>
126TailDupPlacement("tail-dup-placement",
127 cl::desc("Perform tail duplication during placement. "
128 "Creates more fallthrough opportunites in "
129 "outline branches."),
130 cl::init(true), cl::Hidden);
Cong Hou7745dbc2015-10-19 23:16:40 +0000131
Haicheng Wu5b458cc2016-06-09 15:24:29 +0000132static cl::opt<bool>
133BranchFoldPlacement("branch-fold-placement",
134 cl::desc("Perform branch folding during placement. "
135 "Reduces code size."),
136 cl::init(true), cl::Hidden);
137
Kyle Butt0846e562016-10-11 20:36:43 +0000138// Heuristic for tail duplication.
139static cl::opt<unsigned> TailDuplicatePlacementThreshold(
140 "tail-dup-placement-threshold",
141 cl::desc("Instruction cutoff for tail duplication during layout. "
142 "Tail merging during layout is forced to have a threshold "
143 "that won't conflict."), cl::init(2),
144 cl::Hidden);
145
Xinliang David Liff287372016-06-03 23:48:36 +0000146extern cl::opt<unsigned> StaticLikelyProb;
Dehao Chen9f2bdfb2016-06-14 22:27:17 +0000147extern cl::opt<unsigned> ProfileLikelyProb;
Xinliang David Liff287372016-06-03 23:48:36 +0000148
Chandler Carruth10281422011-10-21 06:46:38 +0000149namespace {
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000150class BlockChain;
Chandler Carruth10281422011-10-21 06:46:38 +0000151/// \brief Type for our function-wide basic block -> block chain mapping.
152typedef DenseMap<MachineBasicBlock *, BlockChain *> BlockToChainMapType;
153}
154
155namespace {
156/// \brief A chain of blocks which will be laid out contiguously.
157///
158/// This is the datastructure representing a chain of consecutive blocks that
159/// are profitable to layout together in order to maximize fallthrough
Chandler Carruth9139f442012-06-26 05:16:37 +0000160/// probabilities and code locality. We also can use a block chain to represent
161/// a sequence of basic blocks which have some external (correctness)
162/// requirement for sequential layout.
Chandler Carruth10281422011-10-21 06:46:38 +0000163///
Chandler Carruth9139f442012-06-26 05:16:37 +0000164/// Chains can be built around a single basic block and can be merged to grow
165/// them. They participate in a block-to-chain mapping, which is updated
166/// automatically as chains are merged together.
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000167class BlockChain {
168 /// \brief The sequence of blocks belonging to this chain.
Chandler Carruth10281422011-10-21 06:46:38 +0000169 ///
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000170 /// This is the sequence of blocks for a particular chain. These will be laid
171 /// out in-order within the function.
172 SmallVector<MachineBasicBlock *, 4> Blocks;
Chandler Carruth10281422011-10-21 06:46:38 +0000173
174 /// \brief A handle to the function-wide basic block to block chain mapping.
175 ///
176 /// This is retained in each block chain to simplify the computation of child
177 /// block chains for SCC-formation and iteration. We store the edges to child
178 /// basic blocks, and map them back to their associated chains using this
179 /// structure.
180 BlockToChainMapType &BlockToChain;
181
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000182public:
Chandler Carruth10281422011-10-21 06:46:38 +0000183 /// \brief Construct a new BlockChain.
184 ///
185 /// This builds a new block chain representing a single basic block in the
186 /// function. It also registers itself as the chain that block participates
187 /// in with the BlockToChain mapping.
188 BlockChain(BlockToChainMapType &BlockToChain, MachineBasicBlock *BB)
Philip Reamesae27b232016-03-03 00:58:43 +0000189 : Blocks(1, BB), BlockToChain(BlockToChain), UnscheduledPredecessors(0) {
Chandler Carruth10281422011-10-21 06:46:38 +0000190 assert(BB && "Cannot create a chain with a null basic block");
191 BlockToChain[BB] = this;
192 }
193
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000194 /// \brief Iterator over blocks within the chain.
Chandler Carruthccc7e422012-04-16 01:12:56 +0000195 typedef SmallVectorImpl<MachineBasicBlock *>::iterator iterator;
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000196
197 /// \brief Beginning of blocks within the chain.
Chandler Carruthccc7e422012-04-16 01:12:56 +0000198 iterator begin() { return Blocks.begin(); }
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000199
200 /// \brief End of blocks within the chain.
Chandler Carruthccc7e422012-04-16 01:12:56 +0000201 iterator end() { return Blocks.end(); }
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000202
Kyle Butt0846e562016-10-11 20:36:43 +0000203 bool remove(MachineBasicBlock* BB) {
204 for(iterator i = begin(); i != end(); ++i) {
205 if (*i == BB) {
206 Blocks.erase(i);
207 return true;
208 }
209 }
210 return false;
211 }
212
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000213 /// \brief Merge a block chain into this one.
Chandler Carruth10281422011-10-21 06:46:38 +0000214 ///
215 /// This routine merges a block chain into this one. It takes care of forming
216 /// a contiguous sequence of basic blocks, updating the edge list, and
217 /// updating the block -> chain mapping. It does not free or tear down the
218 /// old chain, but the old chain's block list is no longer valid.
Jakub Staszak90616162011-12-21 23:02:08 +0000219 void merge(MachineBasicBlock *BB, BlockChain *Chain) {
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000220 assert(BB);
221 assert(!Blocks.empty());
Chandler Carruth10281422011-10-21 06:46:38 +0000222
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000223 // Fast path in case we don't have a chain already.
224 if (!Chain) {
225 assert(!BlockToChain[BB]);
226 Blocks.push_back(BB);
227 BlockToChain[BB] = this;
228 return;
Chandler Carruth10281422011-10-21 06:46:38 +0000229 }
230
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000231 assert(BB == *Chain->begin());
232 assert(Chain->begin() != Chain->end());
Chandler Carruth10281422011-10-21 06:46:38 +0000233
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000234 // Update the incoming blocks to point to this chain, and add them to the
235 // chain structure.
Chandler Carruth7a715da2015-03-05 03:19:05 +0000236 for (MachineBasicBlock *ChainBB : *Chain) {
237 Blocks.push_back(ChainBB);
238 assert(BlockToChain[ChainBB] == Chain && "Incoming blocks not in chain");
239 BlockToChain[ChainBB] = this;
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000240 }
Chandler Carruth10281422011-10-21 06:46:38 +0000241 }
Chandler Carruth8d150782011-11-13 11:20:44 +0000242
Chandler Carruth49158902012-04-08 14:37:01 +0000243#ifndef NDEBUG
244 /// \brief Dump the blocks in this chain.
Nico Weber7408c702014-01-03 22:53:37 +0000245 LLVM_DUMP_METHOD void dump() {
Chandler Carruth7a715da2015-03-05 03:19:05 +0000246 for (MachineBasicBlock *MBB : *this)
247 MBB->dump();
Chandler Carruth49158902012-04-08 14:37:01 +0000248 }
249#endif // NDEBUG
250
Philip Reamesae27b232016-03-03 00:58:43 +0000251 /// \brief Count of predecessors of any block within the chain which have not
252 /// yet been scheduled. In general, we will delay scheduling this chain
253 /// until those predecessors are scheduled (or we find a sufficiently good
254 /// reason to override this heuristic.) Note that when forming loop chains,
255 /// blocks outside the loop are ignored and treated as if they were already
256 /// scheduled.
Chandler Carruth8d150782011-11-13 11:20:44 +0000257 ///
Philip Reamesae27b232016-03-03 00:58:43 +0000258 /// Note: This field is reinitialized multiple times - once for each loop,
259 /// and then once for the function as a whole.
260 unsigned UnscheduledPredecessors;
Chandler Carruth10281422011-10-21 06:46:38 +0000261};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000262}
Chandler Carruth10281422011-10-21 06:46:38 +0000263
264namespace {
265class MachineBlockPlacement : public MachineFunctionPass {
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000266 /// \brief A typedef for a block filter set.
Rong Xu66827422016-11-16 20:50:06 +0000267 typedef SmallSetVector<MachineBasicBlock *, 16> BlockFilterSet;
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000268
Xinliang David Li93926ac2016-07-01 05:46:48 +0000269 /// \brief work lists of blocks that are ready to be laid out
270 SmallVector<MachineBasicBlock *, 16> BlockWorkList;
271 SmallVector<MachineBasicBlock *, 16> EHPadWorkList;
272
Xinliang David Li52530a72016-06-13 22:23:44 +0000273 /// \brief Machine Function
274 MachineFunction *F;
275
Chandler Carruth10281422011-10-21 06:46:38 +0000276 /// \brief A handle to the branch probability pass.
277 const MachineBranchProbabilityInfo *MBPI;
278
279 /// \brief A handle to the function-wide block frequency pass.
Haicheng Wu5b458cc2016-06-09 15:24:29 +0000280 std::unique_ptr<BranchFolder::MBFIWrapper> MBFI;
Chandler Carruth10281422011-10-21 06:46:38 +0000281
Chandler Carruth8b9737c2011-10-21 08:57:37 +0000282 /// \brief A handle to the loop info.
Haicheng Wu5b458cc2016-06-09 15:24:29 +0000283 MachineLoopInfo *MLI;
Chandler Carruth8b9737c2011-10-21 08:57:37 +0000284
Kyle Buttab9cca72016-10-27 21:37:20 +0000285 /// \brief Preferred loop exit.
286 /// Member variable for convenience. It may be removed by duplication deep
287 /// in the call stack.
288 MachineBasicBlock *PreferredLoopExit;
289
Chandler Carruth10281422011-10-21 06:46:38 +0000290 /// \brief A handle to the target's instruction info.
291 const TargetInstrInfo *TII;
292
Chandler Carruth8b9737c2011-10-21 08:57:37 +0000293 /// \brief A handle to the target's lowering info.
Benjamin Kramer56b31bd2013-01-11 20:05:37 +0000294 const TargetLoweringBase *TLI;
Chandler Carruth8b9737c2011-10-21 08:57:37 +0000295
Daniel Jasper471e8562015-03-04 11:05:34 +0000296 /// \brief A handle to the post dominator tree.
297 MachineDominatorTree *MDT;
298
Kyle Butt0846e562016-10-11 20:36:43 +0000299 /// \brief Duplicator used to duplicate tails during placement.
300 ///
301 /// Placement decisions can open up new tail duplication opportunities, but
302 /// since tail duplication affects placement decisions of later blocks, it
303 /// must be done inline.
304 TailDuplicator TailDup;
305
Daniel Jasper471e8562015-03-04 11:05:34 +0000306 /// \brief A set of blocks that are unavoidably execute, i.e. they dominate
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000307 /// all terminators of the MachineFunction.
Daniel Jasper471e8562015-03-04 11:05:34 +0000308 SmallPtrSet<MachineBasicBlock *, 4> UnavoidableBlocks;
309
Chandler Carruth10281422011-10-21 06:46:38 +0000310 /// \brief Allocator and owner of BlockChain structures.
311 ///
Chandler Carruth9139f442012-06-26 05:16:37 +0000312 /// We build BlockChains lazily while processing the loop structure of
313 /// a function. To reduce malloc traffic, we allocate them using this
314 /// slab-like allocator, and destroy them after the pass completes. An
315 /// important guarantee is that this allocator produces stable pointers to
316 /// the chains.
Chandler Carruth10281422011-10-21 06:46:38 +0000317 SpecificBumpPtrAllocator<BlockChain> ChainAllocator;
318
319 /// \brief Function wide BasicBlock to BlockChain mapping.
320 ///
321 /// This mapping allows efficiently moving from any given basic block to the
322 /// BlockChain it participates in, if any. We use it to, among other things,
323 /// allow implicitly defining edges between chains as the existing edges
324 /// between basic blocks.
325 DenseMap<MachineBasicBlock *, BlockChain *> BlockToChain;
326
Sanjoy Dasd7389d62016-12-15 05:08:57 +0000327#ifndef NDEBUG
328 /// The set of basic blocks that have terminators that cannot be fully
329 /// analyzed. These basic blocks cannot be re-ordered safely by
330 /// MachineBlockPlacement, and we must preserve physical layout of these
331 /// blocks and their successors through the pass.
332 SmallPtrSet<MachineBasicBlock *, 4> BlocksWithUnanalyzableExits;
333#endif
334
Kyle Butt0846e562016-10-11 20:36:43 +0000335 /// Decrease the UnscheduledPredecessors count for all blocks in chain, and
336 /// if the count goes to 0, add them to the appropriate work list.
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000337 void markChainSuccessors(BlockChain &Chain, MachineBasicBlock *LoopHeaderBB,
Craig Topperc0196b12014-04-14 00:51:57 +0000338 const BlockFilterSet *BlockFilter = nullptr);
Kyle Butt0846e562016-10-11 20:36:43 +0000339
340 /// Decrease the UnscheduledPredecessors count for a single block, and
341 /// if the count goes to 0, add them to the appropriate work list.
342 void markBlockSuccessors(
343 BlockChain &Chain, MachineBasicBlock *BB, MachineBasicBlock *LoopHeaderBB,
344 const BlockFilterSet *BlockFilter = nullptr);
345
346
Xinliang David Li594ffa32016-06-11 18:35:40 +0000347 BranchProbability
348 collectViableSuccessors(MachineBasicBlock *BB, BlockChain &Chain,
349 const BlockFilterSet *BlockFilter,
350 SmallVector<MachineBasicBlock *, 4> &Successors);
Xinliang David Li071d0f12016-06-12 16:54:03 +0000351 bool shouldPredBlockBeOutlined(MachineBasicBlock *BB, MachineBasicBlock *Succ,
352 BlockChain &Chain,
353 const BlockFilterSet *BlockFilter,
354 BranchProbability SuccProb,
355 BranchProbability HotProb);
Kyle Butt0846e562016-10-11 20:36:43 +0000356 bool repeatedlyTailDuplicateBlock(
357 MachineBasicBlock *BB, MachineBasicBlock *&LPred,
358 MachineBasicBlock *LoopHeaderBB,
359 BlockChain &Chain, BlockFilterSet *BlockFilter,
360 MachineFunction::iterator &PrevUnplacedBlockIt);
361 bool maybeTailDuplicateBlock(MachineBasicBlock *BB, MachineBasicBlock *LPred,
362 const BlockChain &Chain,
363 BlockFilterSet *BlockFilter,
364 MachineFunction::iterator &PrevUnplacedBlockIt,
365 bool &DuplicatedToPred);
Xinliang David Licbf12142016-06-13 20:24:19 +0000366 bool
367 hasBetterLayoutPredecessor(MachineBasicBlock *BB, MachineBasicBlock *Succ,
368 BlockChain &SuccChain, BranchProbability SuccProb,
369 BranchProbability RealSuccProb, BlockChain &Chain,
370 const BlockFilterSet *BlockFilter);
Jakub Staszak90616162011-12-21 23:02:08 +0000371 MachineBasicBlock *selectBestSuccessor(MachineBasicBlock *BB,
372 BlockChain &Chain,
373 const BlockFilterSet *BlockFilter);
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000374 MachineBasicBlock *
375 selectBestCandidateBlock(BlockChain &Chain,
Amaury Sechet9ee4ddd2016-04-07 06:34:47 +0000376 SmallVectorImpl<MachineBasicBlock *> &WorkList);
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000377 MachineBasicBlock *
Xinliang David Li52530a72016-06-13 22:23:44 +0000378 getFirstUnplacedBlock(const BlockChain &PlacedChain,
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000379 MachineFunction::iterator &PrevUnplacedBlockIt,
380 const BlockFilterSet *BlockFilter);
Amaury Secheteae09c22016-03-14 21:24:11 +0000381
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +0000382 /// \brief Add a basic block to the work list if it is appropriate.
Amaury Secheteae09c22016-03-14 21:24:11 +0000383 ///
384 /// If the optional parameter BlockFilter is provided, only MBB
385 /// present in the set will be added to the worklist. If nullptr
386 /// is provided, no filtering occurs.
387 void fillWorkLists(MachineBasicBlock *MBB,
388 SmallPtrSetImpl<BlockChain *> &UpdatedPreds,
Amaury Secheteae09c22016-03-14 21:24:11 +0000389 const BlockFilterSet *BlockFilter);
Chandler Carruth8d150782011-11-13 11:20:44 +0000390 void buildChain(MachineBasicBlock *BB, BlockChain &Chain,
Kyle Butt0846e562016-10-11 20:36:43 +0000391 BlockFilterSet *BlockFilter = nullptr);
Chandler Carruth8c0b41d2012-04-16 13:33:36 +0000392 MachineBasicBlock *findBestLoopTop(MachineLoop &L,
393 const BlockFilterSet &LoopBlockSet);
Xinliang David Li52530a72016-06-13 22:23:44 +0000394 MachineBasicBlock *findBestLoopExit(MachineLoop &L,
Chandler Carruthccc7e422012-04-16 01:12:56 +0000395 const BlockFilterSet &LoopBlockSet);
Xinliang David Li52530a72016-06-13 22:23:44 +0000396 BlockFilterSet collectLoopBlockSet(MachineLoop &L);
397 void buildLoopChains(MachineLoop &L);
Chandler Carruth8c74c7b2012-04-16 09:31:23 +0000398 void rotateLoop(BlockChain &LoopChain, MachineBasicBlock *ExitingBB,
399 const BlockFilterSet &LoopBlockSet);
Cong Hou7745dbc2015-10-19 23:16:40 +0000400 void rotateLoopWithProfile(BlockChain &LoopChain, MachineLoop &L,
401 const BlockFilterSet &LoopBlockSet);
Xinliang David Li52530a72016-06-13 22:23:44 +0000402 void collectMustExecuteBBs();
403 void buildCFGChains();
404 void optimizeBranches();
405 void alignBlocks();
Chandler Carruth10281422011-10-21 06:46:38 +0000406
407public:
408 static char ID; // Pass identification, replacement for typeid
409 MachineBlockPlacement() : MachineFunctionPass(ID) {
410 initializeMachineBlockPlacementPass(*PassRegistry::getPassRegistry());
411 }
412
Craig Topper4584cd52014-03-07 09:26:03 +0000413 bool runOnMachineFunction(MachineFunction &F) override;
Chandler Carruth10281422011-10-21 06:46:38 +0000414
Craig Topper4584cd52014-03-07 09:26:03 +0000415 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruth10281422011-10-21 06:46:38 +0000416 AU.addRequired<MachineBranchProbabilityInfo>();
417 AU.addRequired<MachineBlockFrequencyInfo>();
Daniel Jasper471e8562015-03-04 11:05:34 +0000418 AU.addRequired<MachineDominatorTree>();
Chandler Carruth8b9737c2011-10-21 08:57:37 +0000419 AU.addRequired<MachineLoopInfo>();
Haicheng Wu5b458cc2016-06-09 15:24:29 +0000420 AU.addRequired<TargetPassConfig>();
Chandler Carruth10281422011-10-21 06:46:38 +0000421 MachineFunctionPass::getAnalysisUsage(AU);
422 }
Chandler Carruth10281422011-10-21 06:46:38 +0000423};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000424}
Chandler Carruth10281422011-10-21 06:46:38 +0000425
426char MachineBlockPlacement::ID = 0;
Andrew Trick1fa5bcb2012-02-08 21:23:13 +0000427char &llvm::MachineBlockPlacementID = MachineBlockPlacement::ID;
Chandler Carruthd0dced52015-03-05 02:28:25 +0000428INITIALIZE_PASS_BEGIN(MachineBlockPlacement, "block-placement",
Chandler Carruth10281422011-10-21 06:46:38 +0000429 "Branch Probability Basic Block Placement", false, false)
430INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
431INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
Daniel Jasper471e8562015-03-04 11:05:34 +0000432INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
Chandler Carruth8b9737c2011-10-21 08:57:37 +0000433INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
Chandler Carruthd0dced52015-03-05 02:28:25 +0000434INITIALIZE_PASS_END(MachineBlockPlacement, "block-placement",
Chandler Carruth10281422011-10-21 06:46:38 +0000435 "Branch Probability Basic Block Placement", false, false)
436
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000437#ifndef NDEBUG
438/// \brief Helper to print the name of a MBB.
439///
440/// Only used by debug logging.
Jakub Staszak90616162011-12-21 23:02:08 +0000441static std::string getBlockName(MachineBasicBlock *BB) {
Alp Tokere69170a2014-06-26 22:52:05 +0000442 std::string Result;
443 raw_string_ostream OS(Result);
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000444 OS << "BB#" << BB->getNumber();
Philip Reamesb9688f42016-03-02 21:45:13 +0000445 OS << " ('" << BB->getName() << "')";
Alp Tokere69170a2014-06-26 22:52:05 +0000446 OS.flush();
447 return Result;
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000448}
449#endif
450
Chandler Carrutheb4ec3a2011-11-13 11:34:55 +0000451/// \brief Mark a chain's successors as having one fewer preds.
452///
453/// When a chain is being merged into the "placed" chain, this routine will
454/// quickly walk the successors of each block in the chain and mark them as
455/// having one fewer active predecessor. It also adds any successors of this
Kyle Butt0846e562016-10-11 20:36:43 +0000456/// chain which reach the zero-predecessor state to the appropriate worklist.
Chandler Carruth8d150782011-11-13 11:20:44 +0000457void MachineBlockPlacement::markChainSuccessors(
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000458 BlockChain &Chain, MachineBasicBlock *LoopHeaderBB,
Jakub Staszak90616162011-12-21 23:02:08 +0000459 const BlockFilterSet *BlockFilter) {
Chandler Carruth8d150782011-11-13 11:20:44 +0000460 // Walk all the blocks in this chain, marking their successors as having
461 // a predecessor placed.
Chandler Carruth7a715da2015-03-05 03:19:05 +0000462 for (MachineBasicBlock *MBB : Chain) {
Kyle Butt0846e562016-10-11 20:36:43 +0000463 markBlockSuccessors(Chain, MBB, LoopHeaderBB, BlockFilter);
464 }
465}
Chandler Carruth10281422011-10-21 06:46:38 +0000466
Kyle Butt0846e562016-10-11 20:36:43 +0000467/// \brief Mark a single block's successors as having one fewer preds.
468///
469/// Under normal circumstances, this is only called by markChainSuccessors,
470/// but if a block that was to be placed is completely tail-duplicated away,
471/// and was duplicated into the chain end, we need to redo markBlockSuccessors
472/// for just that block.
473void MachineBlockPlacement::markBlockSuccessors(
474 BlockChain &Chain, MachineBasicBlock *MBB, MachineBasicBlock *LoopHeaderBB,
475 const BlockFilterSet *BlockFilter) {
476 // Add any successors for which this is the only un-placed in-loop
477 // predecessor to the worklist as a viable candidate for CFG-neutral
478 // placement. No subsequent placement of this block will violate the CFG
479 // shape, so we get to use heuristics to choose a favorable placement.
480 for (MachineBasicBlock *Succ : MBB->successors()) {
481 if (BlockFilter && !BlockFilter->count(Succ))
482 continue;
483 BlockChain &SuccChain = *BlockToChain[Succ];
484 // Disregard edges within a fixed chain, or edges to the loop header.
485 if (&Chain == &SuccChain || Succ == LoopHeaderBB)
486 continue;
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000487
Kyle Butt0846e562016-10-11 20:36:43 +0000488 // This is a cross-chain edge that is within the loop, so decrement the
489 // loop predecessor count of the destination chain.
490 if (SuccChain.UnscheduledPredecessors == 0 ||
491 --SuccChain.UnscheduledPredecessors > 0)
492 continue;
493
494 auto *NewBB = *SuccChain.begin();
495 if (NewBB->isEHPad())
496 EHPadWorkList.push_back(NewBB);
497 else
498 BlockWorkList.push_back(NewBB);
Chandler Carruth10281422011-10-21 06:46:38 +0000499 }
Chandler Carruth8d150782011-11-13 11:20:44 +0000500}
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000501
Xinliang David Li594ffa32016-06-11 18:35:40 +0000502/// This helper function collects the set of successors of block
503/// \p BB that are allowed to be its layout successors, and return
504/// the total branch probability of edges from \p BB to those
505/// blocks.
506BranchProbability MachineBlockPlacement::collectViableSuccessors(
507 MachineBasicBlock *BB, BlockChain &Chain, const BlockFilterSet *BlockFilter,
508 SmallVector<MachineBasicBlock *, 4> &Successors) {
Cong Houd97c1002015-12-01 05:29:22 +0000509 // Adjust edge probabilities by excluding edges pointing to blocks that is
510 // either not in BlockFilter or is already in the current chain. Consider the
511 // following CFG:
Cong Hou41cf1a52015-11-18 00:52:52 +0000512 //
513 // --->A
514 // | / \
515 // | B C
516 // | \ / \
517 // ----D E
518 //
519 // Assume A->C is very hot (>90%), and C->D has a 50% probability, then after
520 // A->C is chosen as a fall-through, D won't be selected as a successor of C
521 // due to CFG constraint (the probability of C->D is not greater than
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +0000522 // HotProb to break top-order). If we exclude E that is not in BlockFilter
Xinliang David Li594ffa32016-06-11 18:35:40 +0000523 // when calculating the probability of C->D, D will be selected and we
524 // will get A C D B as the layout of this loop.
Cong Houd97c1002015-12-01 05:29:22 +0000525 auto AdjustedSumProb = BranchProbability::getOne();
Cong Hou41cf1a52015-11-18 00:52:52 +0000526 for (MachineBasicBlock *Succ : BB->successors()) {
527 bool SkipSucc = false;
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000528 if (Succ->isEHPad() || (BlockFilter && !BlockFilter->count(Succ))) {
Cong Hou41cf1a52015-11-18 00:52:52 +0000529 SkipSucc = true;
530 } else {
531 BlockChain *SuccChain = BlockToChain[Succ];
532 if (SuccChain == &Chain) {
Cong Hou41cf1a52015-11-18 00:52:52 +0000533 SkipSucc = true;
534 } else if (Succ != *SuccChain->begin()) {
535 DEBUG(dbgs() << " " << getBlockName(Succ) << " -> Mid chain!\n");
536 continue;
537 }
538 }
539 if (SkipSucc)
Cong Houd97c1002015-12-01 05:29:22 +0000540 AdjustedSumProb -= MBPI->getEdgeProbability(BB, Succ);
Cong Hou41cf1a52015-11-18 00:52:52 +0000541 else
542 Successors.push_back(Succ);
543 }
544
Xinliang David Li594ffa32016-06-11 18:35:40 +0000545 return AdjustedSumProb;
546}
547
548/// The helper function returns the branch probability that is adjusted
549/// or normalized over the new total \p AdjustedSumProb.
Xinliang David Li594ffa32016-06-11 18:35:40 +0000550static BranchProbability
551getAdjustedProbability(BranchProbability OrigProb,
552 BranchProbability AdjustedSumProb) {
553 BranchProbability SuccProb;
554 uint32_t SuccProbN = OrigProb.getNumerator();
555 uint32_t SuccProbD = AdjustedSumProb.getNumerator();
556 if (SuccProbN >= SuccProbD)
557 SuccProb = BranchProbability::getOne();
558 else
559 SuccProb = BranchProbability(SuccProbN, SuccProbD);
560
561 return SuccProb;
562}
563
Xinliang David Li071d0f12016-06-12 16:54:03 +0000564/// When the option OutlineOptionalBranches is on, this method
565/// checks if the fallthrough candidate block \p Succ (of block
566/// \p BB) also has other unscheduled predecessor blocks which
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +0000567/// are also successors of \p BB (forming triangular shape CFG).
Xinliang David Li071d0f12016-06-12 16:54:03 +0000568/// If none of such predecessors are small, it returns true.
569/// The caller can choose to select \p Succ as the layout successors
570/// so that \p Succ's predecessors (optional branches) can be
571/// outlined.
572/// FIXME: fold this with more general layout cost analysis.
573bool MachineBlockPlacement::shouldPredBlockBeOutlined(
574 MachineBasicBlock *BB, MachineBasicBlock *Succ, BlockChain &Chain,
575 const BlockFilterSet *BlockFilter, BranchProbability SuccProb,
576 BranchProbability HotProb) {
577 if (!OutlineOptionalBranches)
578 return false;
579 // If we outline optional branches, look whether Succ is unavoidable, i.e.
580 // dominates all terminators of the MachineFunction. If it does, other
581 // successors must be optional. Don't do this for cold branches.
582 if (SuccProb > HotProb.getCompl() && UnavoidableBlocks.count(Succ) > 0) {
583 for (MachineBasicBlock *Pred : Succ->predecessors()) {
584 // Check whether there is an unplaced optional branch.
585 if (Pred == Succ || (BlockFilter && !BlockFilter->count(Pred)) ||
586 BlockToChain[Pred] == &Chain)
587 continue;
588 // Check whether the optional branch has exactly one BB.
589 if (Pred->pred_size() > 1 || *Pred->pred_begin() != BB)
590 continue;
591 // Check whether the optional branch is small.
592 if (Pred->size() < OutlineOptionalThreshold)
593 return false;
594 }
595 return true;
596 } else
597 return false;
598}
599
Dehao Chen9f2bdfb2016-06-14 22:27:17 +0000600// When profile is not present, return the StaticLikelyProb.
601// When profile is available, we need to handle the triangle-shape CFG.
602static BranchProbability getLayoutSuccessorProbThreshold(
603 MachineBasicBlock *BB) {
604 if (!BB->getParent()->getFunction()->getEntryCount())
605 return BranchProbability(StaticLikelyProb, 100);
606 if (BB->succ_size() == 2) {
607 const MachineBasicBlock *Succ1 = *BB->succ_begin();
608 const MachineBasicBlock *Succ2 = *(BB->succ_begin() + 1);
Xinliang David Lie34ed832016-06-15 03:03:30 +0000609 if (Succ1->isSuccessor(Succ2) || Succ2->isSuccessor(Succ1)) {
610 /* See case 1 below for the cost analysis. For BB->Succ to
611 * be taken with smaller cost, the following needs to hold:
612 * Prob(BB->Succ) > 2* Prob(BB->Pred)
613 * So the threshold T
614 * T = 2 * (1-Prob(BB->Pred). Since T + Prob(BB->Pred) == 1,
615 * We have T + T/2 = 1, i.e. T = 2/3. Also adding user specified
616 * branch bias, we have
617 * T = (2/3)*(ProfileLikelyProb/50)
618 * = (2*ProfileLikelyProb)/150)
619 */
620 return BranchProbability(2 * ProfileLikelyProb, 150);
621 }
Dehao Chen9f2bdfb2016-06-14 22:27:17 +0000622 }
623 return BranchProbability(ProfileLikelyProb, 100);
Xinliang David Licbf12142016-06-13 20:24:19 +0000624}
625
626/// Checks to see if the layout candidate block \p Succ has a better layout
627/// predecessor than \c BB. If yes, returns true.
628bool MachineBlockPlacement::hasBetterLayoutPredecessor(
629 MachineBasicBlock *BB, MachineBasicBlock *Succ, BlockChain &SuccChain,
630 BranchProbability SuccProb, BranchProbability RealSuccProb,
631 BlockChain &Chain, const BlockFilterSet *BlockFilter) {
632
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +0000633 // There isn't a better layout when there are no unscheduled predecessors.
Xinliang David Licbf12142016-06-13 20:24:19 +0000634 if (SuccChain.UnscheduledPredecessors == 0)
635 return false;
636
637 // There are two basic scenarios here:
638 // -------------------------------------
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +0000639 // Case 1: triangular shape CFG (if-then):
Xinliang David Licbf12142016-06-13 20:24:19 +0000640 // BB
641 // | \
642 // | \
643 // | Pred
644 // | /
645 // Succ
646 // In this case, we are evaluating whether to select edge -> Succ, e.g.
647 // set Succ as the layout successor of BB. Picking Succ as BB's
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +0000648 // successor breaks the CFG constraints (FIXME: define these constraints).
649 // With this layout, Pred BB
Xinliang David Licbf12142016-06-13 20:24:19 +0000650 // is forced to be outlined, so the overall cost will be cost of the
651 // branch taken from BB to Pred, plus the cost of back taken branch
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +0000652 // from Pred to Succ, as well as the additional cost associated
Xinliang David Licbf12142016-06-13 20:24:19 +0000653 // with the needed unconditional jump instruction from Pred To Succ.
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +0000654
Xinliang David Licbf12142016-06-13 20:24:19 +0000655 // The cost of the topological order layout is the taken branch cost
656 // from BB to Succ, so to make BB->Succ a viable candidate, the following
657 // must hold:
658 // 2 * freq(BB->Pred) * taken_branch_cost + unconditional_jump_cost
659 // < freq(BB->Succ) * taken_branch_cost.
660 // Ignoring unconditional jump cost, we get
661 // freq(BB->Succ) > 2 * freq(BB->Pred), i.e.,
662 // prob(BB->Succ) > 2 * prob(BB->Pred)
663 //
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +0000664 // When real profile data is available, we can precisely compute the
665 // probability threshold that is needed for edge BB->Succ to be considered.
666 // Without profile data, the heuristic requires the branch bias to be
Xinliang David Licbf12142016-06-13 20:24:19 +0000667 // a lot larger to make sure the signal is very strong (e.g. 80% default).
668 // -----------------------------------------------------------------
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +0000669 // Case 2: diamond like CFG (if-then-else):
Xinliang David Licbf12142016-06-13 20:24:19 +0000670 // S
671 // / \
672 // | \
673 // BB Pred
674 // \ /
675 // Succ
676 // ..
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +0000677 //
678 // The current block is BB and edge BB->Succ is now being evaluated.
679 // Note that edge S->BB was previously already selected because
680 // prob(S->BB) > prob(S->Pred).
681 // At this point, 2 blocks can be placed after BB: Pred or Succ. If we
682 // choose Pred, we will have a topological ordering as shown on the left
683 // in the picture below. If we choose Succ, we have the solution as shown
684 // on the right:
685 //
686 // topo-order:
687 //
688 // S----- ---S
689 // | | | |
690 // ---BB | | BB
691 // | | | |
692 // | pred-- | Succ--
693 // | | | |
694 // ---succ ---pred--
695 //
696 // cost = freq(S->Pred) + freq(BB->Succ) cost = 2 * freq (S->Pred)
697 // = freq(S->Pred) + freq(S->BB)
698 //
699 // If we have profile data (i.e, branch probabilities can be trusted), the
700 // cost (number of taken branches) with layout S->BB->Succ->Pred is 2 *
701 // freq(S->Pred) while the cost of topo order is freq(S->Pred) + freq(S->BB).
702 // We know Prob(S->BB) > Prob(S->Pred), so freq(S->BB) > freq(S->Pred), which
703 // means the cost of topological order is greater.
Xinliang David Licbf12142016-06-13 20:24:19 +0000704 // When profile data is not available, however, we need to be more
705 // conservative. If the branch prediction is wrong, breaking the topo-order
706 // will actually yield a layout with large cost. For this reason, we need
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +0000707 // strong biased branch at block S with Prob(S->BB) in order to select
708 // BB->Succ. This is equivalent to looking the CFG backward with backward
Xinliang David Licbf12142016-06-13 20:24:19 +0000709 // edge: Prob(Succ->BB) needs to >= HotProb in order to be selected (without
710 // profile data).
Kyle Butt02d8d052016-07-29 18:09:28 +0000711 // --------------------------------------------------------------------------
712 // Case 3: forked diamond
713 // S
714 // / \
715 // / \
716 // BB Pred
717 // | \ / |
718 // | \ / |
719 // | X |
720 // | / \ |
721 // | / \ |
722 // S1 S2
723 //
724 // The current block is BB and edge BB->S1 is now being evaluated.
725 // As above S->BB was already selected because
726 // prob(S->BB) > prob(S->Pred). Assume that prob(BB->S1) >= prob(BB->S2).
727 //
728 // topo-order:
729 //
730 // S-------| ---S
731 // | | | |
732 // ---BB | | BB
733 // | | | |
734 // | Pred----| | S1----
735 // | | | |
736 // --(S1 or S2) ---Pred--
737 //
738 // topo-cost = freq(S->Pred) + freq(BB->S1) + freq(BB->S2)
739 // + min(freq(Pred->S1), freq(Pred->S2))
740 // Non-topo-order cost:
741 // In the worst case, S2 will not get laid out after Pred.
742 // non-topo-cost = 2 * freq(S->Pred) + freq(BB->S2).
743 // To be conservative, we can assume that min(freq(Pred->S1), freq(Pred->S2))
744 // is 0. Then the non topo layout is better when
745 // freq(S->Pred) < freq(BB->S1).
746 // This is exactly what is checked below.
747 // Note there are other shapes that apply (Pred may not be a single block,
748 // but they all fit this general pattern.)
Dehao Chen9f2bdfb2016-06-14 22:27:17 +0000749 BranchProbability HotProb = getLayoutSuccessorProbThreshold(BB);
Xinliang David Licbf12142016-06-13 20:24:19 +0000750
Xinliang David Licbf12142016-06-13 20:24:19 +0000751 // Make sure that a hot successor doesn't have a globally more
752 // important predecessor.
753 BlockFrequency CandidateEdgeFreq = MBFI->getBlockFreq(BB) * RealSuccProb;
754 bool BadCFGConflict = false;
755
756 for (MachineBasicBlock *Pred : Succ->predecessors()) {
757 if (Pred == Succ || BlockToChain[Pred] == &SuccChain ||
758 (BlockFilter && !BlockFilter->count(Pred)) ||
759 BlockToChain[Pred] == &Chain)
760 continue;
Kyle Butt02d8d052016-07-29 18:09:28 +0000761 // Do backward checking.
762 // For all cases above, we need a backward checking to filter out edges that
763 // are not 'strongly' biased. With profile data available, the check is
764 // mostly redundant for case 2 (when threshold prob is set at 50%) unless S
765 // has more than two successors.
Xinliang David Licbf12142016-06-13 20:24:19 +0000766 // BB Pred
767 // \ /
768 // Succ
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +0000769 // We select edge BB->Succ if
Xinliang David Licbf12142016-06-13 20:24:19 +0000770 // freq(BB->Succ) > freq(Succ) * HotProb
771 // i.e. freq(BB->Succ) > freq(BB->Succ) * HotProb + freq(Pred->Succ) *
772 // HotProb
773 // i.e. freq((BB->Succ) * (1 - HotProb) > freq(Pred->Succ) * HotProb
Kyle Butt02d8d052016-07-29 18:09:28 +0000774 // Case 1 is covered too, because the first equation reduces to:
775 // prob(BB->Succ) > HotProb. (freq(Succ) = freq(BB) for a triangle)
Xinliang David Licbf12142016-06-13 20:24:19 +0000776 BlockFrequency PredEdgeFreq =
777 MBFI->getBlockFreq(Pred) * MBPI->getEdgeProbability(Pred, Succ);
778 if (PredEdgeFreq * HotProb >= CandidateEdgeFreq * HotProb.getCompl()) {
779 BadCFGConflict = true;
780 break;
781 }
782 }
783
784 if (BadCFGConflict) {
Sjoerd Meijer5e11a182016-07-27 08:49:23 +0000785 DEBUG(dbgs() << " Not a candidate: " << getBlockName(Succ) << " -> " << SuccProb
Xinliang David Licbf12142016-06-13 20:24:19 +0000786 << " (prob) (non-cold CFG conflict)\n");
787 return true;
788 }
789
790 return false;
791}
792
Xinliang David Li594ffa32016-06-11 18:35:40 +0000793/// \brief Select the best successor for a block.
794///
795/// This looks across all successors of a particular block and attempts to
796/// select the "best" one to be the layout successor. It only considers direct
797/// successors which also pass the block filter. It will attempt to avoid
798/// breaking CFG structure, but cave and break such structures in the case of
799/// very hot successor edges.
800///
801/// \returns The best successor block found, or null if none are viable.
802MachineBasicBlock *
803MachineBlockPlacement::selectBestSuccessor(MachineBasicBlock *BB,
804 BlockChain &Chain,
805 const BlockFilterSet *BlockFilter) {
806 const BranchProbability HotProb(StaticLikelyProb, 100);
807
808 MachineBasicBlock *BestSucc = nullptr;
809 auto BestProb = BranchProbability::getZero();
810
811 SmallVector<MachineBasicBlock *, 4> Successors;
812 auto AdjustedSumProb =
813 collectViableSuccessors(BB, Chain, BlockFilter, Successors);
814
Sjoerd Meijer5e11a182016-07-27 08:49:23 +0000815 DEBUG(dbgs() << "Selecting best successor for: " << getBlockName(BB) << "\n");
Cong Hou41cf1a52015-11-18 00:52:52 +0000816 for (MachineBasicBlock *Succ : Successors) {
Xinliang David Li594ffa32016-06-11 18:35:40 +0000817 auto RealSuccProb = MBPI->getEdgeProbability(BB, Succ);
818 BranchProbability SuccProb =
819 getAdjustedProbability(RealSuccProb, AdjustedSumProb);
Chandler Carruthb3361722011-11-13 11:34:53 +0000820
Xinliang David Li071d0f12016-06-12 16:54:03 +0000821 // This heuristic is off by default.
822 if (shouldPredBlockBeOutlined(BB, Succ, Chain, BlockFilter, SuccProb,
823 HotProb))
824 return Succ;
Daniel Jasper471e8562015-03-04 11:05:34 +0000825
Cong Hou41cf1a52015-11-18 00:52:52 +0000826 BlockChain &SuccChain = *BlockToChain[Succ];
Xinliang David Licbf12142016-06-13 20:24:19 +0000827 // Skip the edge \c BB->Succ if block \c Succ has a better layout
828 // predecessor that yields lower global cost.
829 if (hasBetterLayoutPredecessor(BB, Succ, SuccChain, SuccProb, RealSuccProb,
830 Chain, BlockFilter))
831 continue;
Chandler Carruth18dfac32011-11-20 11:22:06 +0000832
Xinliang David Licbf12142016-06-13 20:24:19 +0000833 DEBUG(
Sjoerd Meijer5e11a182016-07-27 08:49:23 +0000834 dbgs() << " Candidate: " << getBlockName(Succ) << ", probability: "
835 << SuccProb
Xinliang David Licbf12142016-06-13 20:24:19 +0000836 << (SuccChain.UnscheduledPredecessors != 0 ? " (CFG break)" : "")
837 << "\n");
Sjoerd Meijer5e11a182016-07-27 08:49:23 +0000838
839 if (BestSucc && BestProb >= SuccProb) {
840 DEBUG(dbgs() << " Not the best candidate, continuing\n");
Chandler Carruthb3361722011-11-13 11:34:53 +0000841 continue;
Sjoerd Meijer5e11a182016-07-27 08:49:23 +0000842 }
843
844 DEBUG(dbgs() << " Setting it as best candidate\n");
Daniel Jaspered9eb722015-02-18 08:19:16 +0000845 BestSucc = Succ;
Cong Houd97c1002015-12-01 05:29:22 +0000846 BestProb = SuccProb;
Chandler Carruthb3361722011-11-13 11:34:53 +0000847 }
Sjoerd Meijer5e11a182016-07-27 08:49:23 +0000848 if (BestSucc)
849 DEBUG(dbgs() << " Selected: " << getBlockName(BestSucc) << "\n");
850
Chandler Carruthb3361722011-11-13 11:34:53 +0000851 return BestSucc;
852}
853
Chandler Carruthf9213fe2011-11-13 11:42:26 +0000854/// \brief Select the best block from a worklist.
855///
856/// This looks through the provided worklist as a list of candidate basic
857/// blocks and select the most profitable one to place. The definition of
858/// profitable only really makes sense in the context of a loop. This returns
859/// the most frequently visited block in the worklist, which in the case of
860/// a loop, is the one most desirable to be physically close to the rest of the
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +0000861/// loop body in order to improve i-cache behavior.
Chandler Carruthf9213fe2011-11-13 11:42:26 +0000862///
863/// \returns The best block found, or null if none are viable.
864MachineBasicBlock *MachineBlockPlacement::selectBestCandidateBlock(
Amaury Sechet9ee4ddd2016-04-07 06:34:47 +0000865 BlockChain &Chain, SmallVectorImpl<MachineBasicBlock *> &WorkList) {
Chandler Carruth0af6a0b2011-11-14 09:46:33 +0000866 // Once we need to walk the worklist looking for a candidate, cleanup the
867 // worklist of already placed entries.
868 // FIXME: If this shows up on profiles, it could be folded (at the cost of
869 // some code complexity) into the loop below.
David Majnemerc7004902016-08-12 04:32:37 +0000870 WorkList.erase(remove_if(WorkList,
871 [&](MachineBasicBlock *BB) {
872 return BlockToChain.lookup(BB) == &Chain;
873 }),
Chandler Carruth0af6a0b2011-11-14 09:46:33 +0000874 WorkList.end());
875
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000876 if (WorkList.empty())
877 return nullptr;
878
879 bool IsEHPad = WorkList[0]->isEHPad();
880
Craig Topperc0196b12014-04-14 00:51:57 +0000881 MachineBasicBlock *BestBlock = nullptr;
Chandler Carruthf9213fe2011-11-13 11:42:26 +0000882 BlockFrequency BestFreq;
Chandler Carruth7a715da2015-03-05 03:19:05 +0000883 for (MachineBasicBlock *MBB : WorkList) {
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000884 assert(MBB->isEHPad() == IsEHPad);
885
Chandler Carruth7a715da2015-03-05 03:19:05 +0000886 BlockChain &SuccChain = *BlockToChain[MBB];
Philip Reames02e11322016-03-02 22:40:51 +0000887 if (&SuccChain == &Chain)
Chandler Carruthf9213fe2011-11-13 11:42:26 +0000888 continue;
Junmo Park4ba6cf62016-03-11 05:07:07 +0000889
Philip Reamesae27b232016-03-03 00:58:43 +0000890 assert(SuccChain.UnscheduledPredecessors == 0 && "Found CFG-violating block");
Chandler Carruthf9213fe2011-11-13 11:42:26 +0000891
Chandler Carruth7a715da2015-03-05 03:19:05 +0000892 BlockFrequency CandidateFreq = MBFI->getBlockFreq(MBB);
893 DEBUG(dbgs() << " " << getBlockName(MBB) << " -> ";
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000894 MBFI->printBlockFreq(dbgs(), CandidateFreq) << " (freq)\n");
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000895
896 // For ehpad, we layout the least probable first as to avoid jumping back
897 // from least probable landingpads to more probable ones.
898 //
899 // FIXME: Using probability is probably (!) not the best way to achieve
900 // this. We should probably have a more principled approach to layout
901 // cleanup code.
902 //
903 // The goal is to get:
904 //
905 // +--------------------------+
906 // | V
907 // InnerLp -> InnerCleanup OuterLp -> OuterCleanup -> Resume
908 //
909 // Rather than:
910 //
911 // +-------------------------------------+
912 // V |
913 // OuterLp -> OuterCleanup -> Resume InnerLp -> InnerCleanup
914 if (BestBlock && (IsEHPad ^ (BestFreq >= CandidateFreq)))
Chandler Carruthf9213fe2011-11-13 11:42:26 +0000915 continue;
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000916
Chandler Carruth7a715da2015-03-05 03:19:05 +0000917 BestBlock = MBB;
Chandler Carruthf9213fe2011-11-13 11:42:26 +0000918 BestFreq = CandidateFreq;
919 }
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000920
Chandler Carruthf9213fe2011-11-13 11:42:26 +0000921 return BestBlock;
922}
923
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000924/// \brief Retrieve the first unplaced basic block.
925///
926/// This routine is called when we are unable to use the CFG to walk through
927/// all of the basic blocks and form a chain due to unnatural loops in the CFG.
Chandler Carruth9b548a7f2011-11-15 06:26:43 +0000928/// We walk through the function's blocks in order, starting from the
929/// LastUnplacedBlockIt. We update this iterator on each call to avoid
930/// re-scanning the entire sequence on repeated calls to this routine.
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000931MachineBasicBlock *MachineBlockPlacement::getFirstUnplacedBlock(
Xinliang David Li52530a72016-06-13 22:23:44 +0000932 const BlockChain &PlacedChain,
Chandler Carruth9b548a7f2011-11-15 06:26:43 +0000933 MachineFunction::iterator &PrevUnplacedBlockIt,
Jakub Staszak90616162011-12-21 23:02:08 +0000934 const BlockFilterSet *BlockFilter) {
Xinliang David Li52530a72016-06-13 22:23:44 +0000935 for (MachineFunction::iterator I = PrevUnplacedBlockIt, E = F->end(); I != E;
Chandler Carruth9b548a7f2011-11-15 06:26:43 +0000936 ++I) {
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +0000937 if (BlockFilter && !BlockFilter->count(&*I))
Chandler Carruth9b548a7f2011-11-15 06:26:43 +0000938 continue;
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +0000939 if (BlockToChain[&*I] != &PlacedChain) {
Chandler Carruth9b548a7f2011-11-15 06:26:43 +0000940 PrevUnplacedBlockIt = I;
Chandler Carruth4a87aa02011-11-23 03:03:21 +0000941 // Now select the head of the chain to which the unplaced block belongs
942 // as the block to place. This will force the entire chain to be placed,
943 // and satisfies the requirements of merging chains.
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +0000944 return *BlockToChain[&*I]->begin();
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000945 }
946 }
Craig Topperc0196b12014-04-14 00:51:57 +0000947 return nullptr;
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000948}
949
Amaury Secheteae09c22016-03-14 21:24:11 +0000950void MachineBlockPlacement::fillWorkLists(
951 MachineBasicBlock *MBB,
952 SmallPtrSetImpl<BlockChain *> &UpdatedPreds,
Amaury Secheteae09c22016-03-14 21:24:11 +0000953 const BlockFilterSet *BlockFilter = nullptr) {
954 BlockChain &Chain = *BlockToChain[MBB];
955 if (!UpdatedPreds.insert(&Chain).second)
956 return;
957
958 assert(Chain.UnscheduledPredecessors == 0);
959 for (MachineBasicBlock *ChainBB : Chain) {
960 assert(BlockToChain[ChainBB] == &Chain);
961 for (MachineBasicBlock *Pred : ChainBB->predecessors()) {
962 if (BlockFilter && !BlockFilter->count(Pred))
963 continue;
964 if (BlockToChain[Pred] == &Chain)
965 continue;
966 ++Chain.UnscheduledPredecessors;
967 }
968 }
969
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000970 if (Chain.UnscheduledPredecessors != 0)
971 return;
972
973 MBB = *Chain.begin();
974 if (MBB->isEHPad())
975 EHPadWorkList.push_back(MBB);
976 else
977 BlockWorkList.push_back(MBB);
Amaury Secheteae09c22016-03-14 21:24:11 +0000978}
979
Chandler Carruth8d150782011-11-13 11:20:44 +0000980void MachineBlockPlacement::buildChain(
Daniel Jasper471e8562015-03-04 11:05:34 +0000981 MachineBasicBlock *BB, BlockChain &Chain,
Kyle Butt0846e562016-10-11 20:36:43 +0000982 BlockFilterSet *BlockFilter) {
Kyle Buttb3875ea2016-06-17 22:40:19 +0000983 assert(BB && "BB must not be null.\n");
984 assert(BlockToChain[BB] == &Chain && "BlockToChainMap mis-match.\n");
Xinliang David Li52530a72016-06-13 22:23:44 +0000985 MachineFunction::iterator PrevUnplacedBlockIt = F->begin();
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000986
Chandler Carruth8d150782011-11-13 11:20:44 +0000987 MachineBasicBlock *LoopHeaderBB = BB;
Xinliang David Li93926ac2016-07-01 05:46:48 +0000988 markChainSuccessors(Chain, LoopHeaderBB, BlockFilter);
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000989 BB = *std::prev(Chain.end());
Chandler Carruth8d150782011-11-13 11:20:44 +0000990 for (;;) {
Kyle Butt82c22902016-06-28 22:50:54 +0000991 assert(BB && "null block found at end of chain in loop.");
992 assert(BlockToChain[BB] == &Chain && "BlockToChainMap mis-match in loop.");
993 assert(*std::prev(Chain.end()) == BB && "BB Not found at end of chain.");
994
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000995
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +0000996 // Look for the best viable successor if there is one to place immediately
997 // after this block.
Duncan Sands291d47e2012-09-14 09:00:11 +0000998 MachineBasicBlock *BestSucc = selectBestSuccessor(BB, Chain, BlockFilter);
Chandler Carruth8d150782011-11-13 11:20:44 +0000999
1000 // If an immediate successor isn't available, look for the best viable
1001 // block among those we've identified as not violating the loop's CFG at
1002 // this point. This won't be a fallthrough, but it will increase locality.
Chandler Carruthf9213fe2011-11-13 11:42:26 +00001003 if (!BestSucc)
Amaury Sechet9ee4ddd2016-04-07 06:34:47 +00001004 BestSucc = selectBestCandidateBlock(Chain, BlockWorkList);
Amaury Sechetc53ad4f2016-04-07 21:29:39 +00001005 if (!BestSucc)
1006 BestSucc = selectBestCandidateBlock(Chain, EHPadWorkList);
Chandler Carruth8d150782011-11-13 11:20:44 +00001007
Chandler Carruth8d150782011-11-13 11:20:44 +00001008 if (!BestSucc) {
Xinliang David Li52530a72016-06-13 22:23:44 +00001009 BestSucc = getFirstUnplacedBlock(Chain, PrevUnplacedBlockIt, BlockFilter);
Chandler Carruth1071cfa2011-11-14 00:00:35 +00001010 if (!BestSucc)
1011 break;
1012
1013 DEBUG(dbgs() << "Unnatural loop CFG detected, forcibly merging the "
1014 "layout successor until the CFG reduces\n");
Chandler Carruth8d150782011-11-13 11:20:44 +00001015 }
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00001016
Kyle Butt0846e562016-10-11 20:36:43 +00001017 // Placement may have changed tail duplication opportunities.
1018 // Check for that now.
1019 if (TailDupPlacement && BestSucc) {
1020 // If the chosen successor was duplicated into all its predecessors,
1021 // don't bother laying it out, just go round the loop again with BB as
1022 // the chain end.
1023 if (repeatedlyTailDuplicateBlock(BestSucc, BB, LoopHeaderBB, Chain,
1024 BlockFilter, PrevUnplacedBlockIt))
1025 continue;
1026 }
1027
Chandler Carruth8d150782011-11-13 11:20:44 +00001028 // Place this block, updating the datastructures to reflect its placement.
Jakub Staszak90616162011-12-21 23:02:08 +00001029 BlockChain &SuccChain = *BlockToChain[BestSucc];
Philip Reamesae27b232016-03-03 00:58:43 +00001030 // Zero out UnscheduledPredecessors for the successor we're about to merge in case
Chandler Carruth1071cfa2011-11-14 00:00:35 +00001031 // we selected a successor that didn't fit naturally into the CFG.
Philip Reamesae27b232016-03-03 00:58:43 +00001032 SuccChain.UnscheduledPredecessors = 0;
Philip Reamesb9688f42016-03-02 21:45:13 +00001033 DEBUG(dbgs() << "Merging from " << getBlockName(BB) << " to "
1034 << getBlockName(BestSucc) << "\n");
Xinliang David Li93926ac2016-07-01 05:46:48 +00001035 markChainSuccessors(SuccChain, LoopHeaderBB, BlockFilter);
Chandler Carruth8d150782011-11-13 11:20:44 +00001036 Chain.merge(BestSucc, &SuccChain);
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001037 BB = *std::prev(Chain.end());
Jakub Staszak190c7122011-12-07 19:46:10 +00001038 }
Chandler Carruth1071cfa2011-11-14 00:00:35 +00001039
1040 DEBUG(dbgs() << "Finished forming chain for header block "
Philip Reamesb9688f42016-03-02 21:45:13 +00001041 << getBlockName(*Chain.begin()) << "\n");
Chandler Carruth10281422011-10-21 06:46:38 +00001042}
1043
Chandler Carruth03adbd42011-11-27 13:34:33 +00001044/// \brief Find the best loop top block for layout.
Chandler Carruth9ffb97e2011-11-27 00:38:03 +00001045///
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001046/// Look for a block which is strictly better than the loop header for laying
1047/// out at the top of the loop. This looks for one and only one pattern:
1048/// a latch block with no conditional exit. This block will cause a conditional
1049/// jump around it or will be the bottom of the loop if we lay it out in place,
1050/// but if it it doesn't end up at the bottom of the loop for any reason,
1051/// rotation alone won't fix it. Because such a block will always result in an
1052/// unconditional jump (for the backedge) rotating it in front of the loop
1053/// header is always profitable.
1054MachineBasicBlock *
1055MachineBlockPlacement::findBestLoopTop(MachineLoop &L,
1056 const BlockFilterSet &LoopBlockSet) {
Sjoerd Meijer15c81b02016-08-16 19:50:33 +00001057 // Placing the latch block before the header may introduce an extra branch
1058 // that skips this block the first time the loop is executed, which we want
1059 // to avoid when optimising for size.
1060 // FIXME: in theory there is a case that does not introduce a new branch,
1061 // i.e. when the layout predecessor does not fallthrough to the loop header.
1062 // In practice this never happens though: there always seems to be a preheader
1063 // that can fallthrough and that is also placed before the header.
1064 if (F->getFunction()->optForSize())
1065 return L.getHeader();
1066
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001067 // Check that the header hasn't been fused with a preheader block due to
1068 // crazy branches. If it has, we need to start with the header at the top to
1069 // prevent pulling the preheader into the loop body.
1070 BlockChain &HeaderChain = *BlockToChain[L.getHeader()];
1071 if (!LoopBlockSet.count(*HeaderChain.begin()))
1072 return L.getHeader();
1073
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001074 DEBUG(dbgs() << "Finding best loop top for: " << getBlockName(L.getHeader())
1075 << "\n");
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001076
1077 BlockFrequency BestPredFreq;
Craig Topperc0196b12014-04-14 00:51:57 +00001078 MachineBasicBlock *BestPred = nullptr;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001079 for (MachineBasicBlock *Pred : L.getHeader()->predecessors()) {
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001080 if (!LoopBlockSet.count(Pred))
1081 continue;
Sjoerd Meijer5e11a182016-07-27 08:49:23 +00001082 DEBUG(dbgs() << " header pred: " << getBlockName(Pred) << ", has "
Michael Gottesmanb78dec82013-12-14 00:25:45 +00001083 << Pred->succ_size() << " successors, ";
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001084 MBFI->printBlockFreq(dbgs(), Pred) << " freq\n");
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001085 if (Pred->succ_size() > 1)
1086 continue;
1087
1088 BlockFrequency PredFreq = MBFI->getBlockFreq(Pred);
1089 if (!BestPred || PredFreq > BestPredFreq ||
1090 (!(PredFreq < BestPredFreq) &&
1091 Pred->isLayoutSuccessor(L.getHeader()))) {
1092 BestPred = Pred;
1093 BestPredFreq = PredFreq;
1094 }
1095 }
1096
1097 // If no direct predecessor is fine, just use the loop header.
Philip Reamesb9688f42016-03-02 21:45:13 +00001098 if (!BestPred) {
1099 DEBUG(dbgs() << " final top unchanged\n");
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001100 return L.getHeader();
Philip Reamesb9688f42016-03-02 21:45:13 +00001101 }
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001102
1103 // Walk backwards through any straight line of predecessors.
1104 while (BestPred->pred_size() == 1 &&
1105 (*BestPred->pred_begin())->succ_size() == 1 &&
1106 *BestPred->pred_begin() != L.getHeader())
1107 BestPred = *BestPred->pred_begin();
1108
1109 DEBUG(dbgs() << " final top: " << getBlockName(BestPred) << "\n");
1110 return BestPred;
1111}
1112
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001113/// \brief Find the best loop exiting block for layout.
1114///
Chandler Carruth03adbd42011-11-27 13:34:33 +00001115/// This routine implements the logic to analyze the loop looking for the best
1116/// block to layout at the top of the loop. Typically this is done to maximize
1117/// fallthrough opportunities.
1118MachineBasicBlock *
Xinliang David Li52530a72016-06-13 22:23:44 +00001119MachineBlockPlacement::findBestLoopExit(MachineLoop &L,
Chandler Carruthccc7e422012-04-16 01:12:56 +00001120 const BlockFilterSet &LoopBlockSet) {
Chandler Carruth68062612012-04-10 13:35:57 +00001121 // We don't want to layout the loop linearly in all cases. If the loop header
1122 // is just a normal basic block in the loop, we want to look for what block
1123 // within the loop is the best one to layout at the top. However, if the loop
1124 // header has be pre-merged into a chain due to predecessors not having
1125 // analyzable branches, *and* the predecessor it is merged with is *not* part
1126 // of the loop, rotating the header into the middle of the loop will create
1127 // a non-contiguous range of blocks which is Very Bad. So start with the
1128 // header and only rotate if safe.
1129 BlockChain &HeaderChain = *BlockToChain[L.getHeader()];
1130 if (!LoopBlockSet.count(*HeaderChain.begin()))
Craig Topperc0196b12014-04-14 00:51:57 +00001131 return nullptr;
Chandler Carruth68062612012-04-10 13:35:57 +00001132
Chandler Carruth03adbd42011-11-27 13:34:33 +00001133 BlockFrequency BestExitEdgeFreq;
Chandler Carruthccc7e422012-04-16 01:12:56 +00001134 unsigned BestExitLoopDepth = 0;
Craig Topperc0196b12014-04-14 00:51:57 +00001135 MachineBasicBlock *ExitingBB = nullptr;
Chandler Carruth4f567202011-11-27 20:18:00 +00001136 // If there are exits to outer loops, loop rotation can severely limit
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00001137 // fallthrough opportunities unless it selects such an exit. Keep a set of
Chandler Carruth4f567202011-11-27 20:18:00 +00001138 // blocks where rotating to exit with that block will reach an outer loop.
1139 SmallPtrSet<MachineBasicBlock *, 4> BlocksExitingToOuterLoop;
1140
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001141 DEBUG(dbgs() << "Finding best loop exit for: " << getBlockName(L.getHeader())
1142 << "\n");
Chandler Carruth7a715da2015-03-05 03:19:05 +00001143 for (MachineBasicBlock *MBB : L.getBlocks()) {
1144 BlockChain &Chain = *BlockToChain[MBB];
Chandler Carruth03adbd42011-11-27 13:34:33 +00001145 // Ensure that this block is at the end of a chain; otherwise it could be
Chandler Carruth9a512a42015-04-15 13:19:54 +00001146 // mid-way through an inner loop or a successor of an unanalyzable branch.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001147 if (MBB != *std::prev(Chain.end()))
Chandler Carruth9ffb97e2011-11-27 00:38:03 +00001148 continue;
Chandler Carruth9ffb97e2011-11-27 00:38:03 +00001149
Chandler Carruth03adbd42011-11-27 13:34:33 +00001150 // Now walk the successors. We need to establish whether this has a viable
1151 // exiting successor and whether it has a viable non-exiting successor.
1152 // We store the old exiting state and restore it if a viable looping
1153 // successor isn't found.
1154 MachineBasicBlock *OldExitingBB = ExitingBB;
1155 BlockFrequency OldBestExitEdgeFreq = BestExitEdgeFreq;
Chandler Carruthccc7e422012-04-16 01:12:56 +00001156 bool HasLoopingSucc = false;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001157 for (MachineBasicBlock *Succ : MBB->successors()) {
Reid Kleckner0e288232015-08-27 23:27:47 +00001158 if (Succ->isEHPad())
Chandler Carruth03adbd42011-11-27 13:34:33 +00001159 continue;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001160 if (Succ == MBB)
Chandler Carruth03adbd42011-11-27 13:34:33 +00001161 continue;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001162 BlockChain &SuccChain = *BlockToChain[Succ];
Chandler Carruth03adbd42011-11-27 13:34:33 +00001163 // Don't split chains, either this chain or the successor's chain.
Chandler Carruthccc7e422012-04-16 01:12:56 +00001164 if (&Chain == &SuccChain) {
Chandler Carruth7a715da2015-03-05 03:19:05 +00001165 DEBUG(dbgs() << " exiting: " << getBlockName(MBB) << " -> "
1166 << getBlockName(Succ) << " (chain conflict)\n");
Chandler Carruth03adbd42011-11-27 13:34:33 +00001167 continue;
1168 }
1169
Cong Houd97c1002015-12-01 05:29:22 +00001170 auto SuccProb = MBPI->getEdgeProbability(MBB, Succ);
Chandler Carruth7a715da2015-03-05 03:19:05 +00001171 if (LoopBlockSet.count(Succ)) {
1172 DEBUG(dbgs() << " looping: " << getBlockName(MBB) << " -> "
Cong Houd97c1002015-12-01 05:29:22 +00001173 << getBlockName(Succ) << " (" << SuccProb << ")\n");
Chandler Carruthccc7e422012-04-16 01:12:56 +00001174 HasLoopingSucc = true;
Chandler Carruth03adbd42011-11-27 13:34:33 +00001175 continue;
1176 }
1177
Chandler Carruthccc7e422012-04-16 01:12:56 +00001178 unsigned SuccLoopDepth = 0;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001179 if (MachineLoop *ExitLoop = MLI->getLoopFor(Succ)) {
Chandler Carruthccc7e422012-04-16 01:12:56 +00001180 SuccLoopDepth = ExitLoop->getLoopDepth();
1181 if (ExitLoop->contains(&L))
Chandler Carruth7a715da2015-03-05 03:19:05 +00001182 BlocksExitingToOuterLoop.insert(MBB);
Chandler Carruthccc7e422012-04-16 01:12:56 +00001183 }
1184
Chandler Carruth7a715da2015-03-05 03:19:05 +00001185 BlockFrequency ExitEdgeFreq = MBFI->getBlockFreq(MBB) * SuccProb;
1186 DEBUG(dbgs() << " exiting: " << getBlockName(MBB) << " -> "
1187 << getBlockName(Succ) << " [L:" << SuccLoopDepth << "] (";
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001188 MBFI->printBlockFreq(dbgs(), ExitEdgeFreq) << ")\n");
Benjamin Kramerc8160d62013-11-20 19:08:44 +00001189 // Note that we bias this toward an existing layout successor to retain
1190 // incoming order in the absence of better information. The exit must have
1191 // a frequency higher than the current exit before we consider breaking
1192 // the layout.
1193 BranchProbability Bias(100 - ExitBlockBias, 100);
Chandler Carruth26d30172015-04-15 13:39:42 +00001194 if (!ExitingBB || SuccLoopDepth > BestExitLoopDepth ||
Chandler Carruthccc7e422012-04-16 01:12:56 +00001195 ExitEdgeFreq > BestExitEdgeFreq ||
Chandler Carruth7a715da2015-03-05 03:19:05 +00001196 (MBB->isLayoutSuccessor(Succ) &&
Benjamin Kramerc8160d62013-11-20 19:08:44 +00001197 !(ExitEdgeFreq < BestExitEdgeFreq * Bias))) {
Chandler Carruth03adbd42011-11-27 13:34:33 +00001198 BestExitEdgeFreq = ExitEdgeFreq;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001199 ExitingBB = MBB;
Chandler Carrutha0545802011-11-27 09:22:53 +00001200 }
Chandler Carruth9ffb97e2011-11-27 00:38:03 +00001201 }
Chandler Carruth03adbd42011-11-27 13:34:33 +00001202
Chandler Carruthccc7e422012-04-16 01:12:56 +00001203 if (!HasLoopingSucc) {
Chandler Carruthcfb2b9d2015-04-15 13:26:41 +00001204 // Restore the old exiting state, no viable looping successor was found.
Chandler Carruth03adbd42011-11-27 13:34:33 +00001205 ExitingBB = OldExitingBB;
1206 BestExitEdgeFreq = OldBestExitEdgeFreq;
Chandler Carruth03adbd42011-11-27 13:34:33 +00001207 }
Chandler Carruth9ffb97e2011-11-27 00:38:03 +00001208 }
Chandler Carruthccc7e422012-04-16 01:12:56 +00001209 // Without a candidate exiting block or with only a single block in the
Chandler Carruth03adbd42011-11-27 13:34:33 +00001210 // loop, just use the loop header to layout the loop.
Sjoerd Meijer5e11a182016-07-27 08:49:23 +00001211 if (!ExitingBB) {
1212 DEBUG(dbgs() << " No other candidate exit blocks, using loop header\n");
Craig Topperc0196b12014-04-14 00:51:57 +00001213 return nullptr;
Sjoerd Meijer5e11a182016-07-27 08:49:23 +00001214 }
1215 if (L.getNumBlocks() == 1) {
1216 DEBUG(dbgs() << " Loop has 1 block, using loop header as exit\n");
1217 return nullptr;
1218 }
Chandler Carruth9ffb97e2011-11-27 00:38:03 +00001219
Chandler Carruth4f567202011-11-27 20:18:00 +00001220 // Also, if we have exit blocks which lead to outer loops but didn't select
1221 // one of them as the exiting block we are rotating toward, disable loop
1222 // rotation altogether.
1223 if (!BlocksExitingToOuterLoop.empty() &&
1224 !BlocksExitingToOuterLoop.count(ExitingBB))
Craig Topperc0196b12014-04-14 00:51:57 +00001225 return nullptr;
Chandler Carruth4f567202011-11-27 20:18:00 +00001226
Chandler Carruth03adbd42011-11-27 13:34:33 +00001227 DEBUG(dbgs() << " Best exiting block: " << getBlockName(ExitingBB) << "\n");
Chandler Carruthccc7e422012-04-16 01:12:56 +00001228 return ExitingBB;
Chandler Carruth9ffb97e2011-11-27 00:38:03 +00001229}
1230
Chandler Carruth8c74c7b2012-04-16 09:31:23 +00001231/// \brief Attempt to rotate an exiting block to the bottom of the loop.
1232///
1233/// Once we have built a chain, try to rotate it to line up the hot exit block
1234/// with fallthrough out of the loop if doing so doesn't introduce unnecessary
1235/// branches. For example, if the loop has fallthrough into its header and out
1236/// of its bottom already, don't rotate it.
1237void MachineBlockPlacement::rotateLoop(BlockChain &LoopChain,
1238 MachineBasicBlock *ExitingBB,
1239 const BlockFilterSet &LoopBlockSet) {
1240 if (!ExitingBB)
1241 return;
1242
1243 MachineBasicBlock *Top = *LoopChain.begin();
1244 bool ViableTopFallthrough = false;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001245 for (MachineBasicBlock *Pred : Top->predecessors()) {
1246 BlockChain *PredChain = BlockToChain[Pred];
1247 if (!LoopBlockSet.count(Pred) &&
1248 (!PredChain || Pred == *std::prev(PredChain->end()))) {
Chandler Carruth8c74c7b2012-04-16 09:31:23 +00001249 ViableTopFallthrough = true;
1250 break;
1251 }
1252 }
1253
1254 // If the header has viable fallthrough, check whether the current loop
1255 // bottom is a viable exiting block. If so, bail out as rotating will
1256 // introduce an unnecessary branch.
1257 if (ViableTopFallthrough) {
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001258 MachineBasicBlock *Bottom = *std::prev(LoopChain.end());
Chandler Carruth7a715da2015-03-05 03:19:05 +00001259 for (MachineBasicBlock *Succ : Bottom->successors()) {
1260 BlockChain *SuccChain = BlockToChain[Succ];
1261 if (!LoopBlockSet.count(Succ) &&
1262 (!SuccChain || Succ == *SuccChain->begin()))
Chandler Carruth8c74c7b2012-04-16 09:31:23 +00001263 return;
1264 }
1265 }
1266
David Majnemer0d955d02016-08-11 22:21:41 +00001267 BlockChain::iterator ExitIt = find(LoopChain, ExitingBB);
Chandler Carruth8c74c7b2012-04-16 09:31:23 +00001268 if (ExitIt == LoopChain.end())
1269 return;
1270
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001271 std::rotate(LoopChain.begin(), std::next(ExitIt), LoopChain.end());
Chandler Carruth8c74c7b2012-04-16 09:31:23 +00001272}
1273
Cong Hou7745dbc2015-10-19 23:16:40 +00001274/// \brief Attempt to rotate a loop based on profile data to reduce branch cost.
1275///
1276/// With profile data, we can determine the cost in terms of missed fall through
1277/// opportunities when rotating a loop chain and select the best rotation.
1278/// Basically, there are three kinds of cost to consider for each rotation:
1279/// 1. The possibly missed fall through edge (if it exists) from BB out of
1280/// the loop to the loop header.
1281/// 2. The possibly missed fall through edges (if they exist) from the loop
1282/// exits to BB out of the loop.
1283/// 3. The missed fall through edge (if it exists) from the last BB to the
1284/// first BB in the loop chain.
1285/// Therefore, the cost for a given rotation is the sum of costs listed above.
1286/// We select the best rotation with the smallest cost.
1287void MachineBlockPlacement::rotateLoopWithProfile(
1288 BlockChain &LoopChain, MachineLoop &L, const BlockFilterSet &LoopBlockSet) {
1289 auto HeaderBB = L.getHeader();
David Majnemer0d955d02016-08-11 22:21:41 +00001290 auto HeaderIter = find(LoopChain, HeaderBB);
Cong Hou7745dbc2015-10-19 23:16:40 +00001291 auto RotationPos = LoopChain.end();
1292
1293 BlockFrequency SmallestRotationCost = BlockFrequency::getMaxFrequency();
1294
1295 // A utility lambda that scales up a block frequency by dividing it by a
1296 // branch probability which is the reciprocal of the scale.
1297 auto ScaleBlockFrequency = [](BlockFrequency Freq,
1298 unsigned Scale) -> BlockFrequency {
1299 if (Scale == 0)
1300 return 0;
1301 // Use operator / between BlockFrequency and BranchProbability to implement
1302 // saturating multiplication.
1303 return Freq / BranchProbability(1, Scale);
1304 };
1305
1306 // Compute the cost of the missed fall-through edge to the loop header if the
1307 // chain head is not the loop header. As we only consider natural loops with
1308 // single header, this computation can be done only once.
1309 BlockFrequency HeaderFallThroughCost(0);
1310 for (auto *Pred : HeaderBB->predecessors()) {
1311 BlockChain *PredChain = BlockToChain[Pred];
1312 if (!LoopBlockSet.count(Pred) &&
1313 (!PredChain || Pred == *std::prev(PredChain->end()))) {
1314 auto EdgeFreq =
1315 MBFI->getBlockFreq(Pred) * MBPI->getEdgeProbability(Pred, HeaderBB);
1316 auto FallThruCost = ScaleBlockFrequency(EdgeFreq, MisfetchCost);
1317 // If the predecessor has only an unconditional jump to the header, we
1318 // need to consider the cost of this jump.
1319 if (Pred->succ_size() == 1)
1320 FallThruCost += ScaleBlockFrequency(EdgeFreq, JumpInstCost);
1321 HeaderFallThroughCost = std::max(HeaderFallThroughCost, FallThruCost);
1322 }
1323 }
1324
1325 // Here we collect all exit blocks in the loop, and for each exit we find out
1326 // its hottest exit edge. For each loop rotation, we define the loop exit cost
1327 // as the sum of frequencies of exit edges we collect here, excluding the exit
1328 // edge from the tail of the loop chain.
1329 SmallVector<std::pair<MachineBasicBlock *, BlockFrequency>, 4> ExitsWithFreq;
1330 for (auto BB : LoopChain) {
Cong Houd97c1002015-12-01 05:29:22 +00001331 auto LargestExitEdgeProb = BranchProbability::getZero();
Cong Hou7745dbc2015-10-19 23:16:40 +00001332 for (auto *Succ : BB->successors()) {
1333 BlockChain *SuccChain = BlockToChain[Succ];
1334 if (!LoopBlockSet.count(Succ) &&
1335 (!SuccChain || Succ == *SuccChain->begin())) {
Cong Houd97c1002015-12-01 05:29:22 +00001336 auto SuccProb = MBPI->getEdgeProbability(BB, Succ);
1337 LargestExitEdgeProb = std::max(LargestExitEdgeProb, SuccProb);
Cong Hou7745dbc2015-10-19 23:16:40 +00001338 }
1339 }
Cong Houd97c1002015-12-01 05:29:22 +00001340 if (LargestExitEdgeProb > BranchProbability::getZero()) {
1341 auto ExitFreq = MBFI->getBlockFreq(BB) * LargestExitEdgeProb;
Cong Hou7745dbc2015-10-19 23:16:40 +00001342 ExitsWithFreq.emplace_back(BB, ExitFreq);
1343 }
1344 }
1345
1346 // In this loop we iterate every block in the loop chain and calculate the
1347 // cost assuming the block is the head of the loop chain. When the loop ends,
1348 // we should have found the best candidate as the loop chain's head.
1349 for (auto Iter = LoopChain.begin(), TailIter = std::prev(LoopChain.end()),
1350 EndIter = LoopChain.end();
1351 Iter != EndIter; Iter++, TailIter++) {
1352 // TailIter is used to track the tail of the loop chain if the block we are
1353 // checking (pointed by Iter) is the head of the chain.
1354 if (TailIter == LoopChain.end())
1355 TailIter = LoopChain.begin();
1356
1357 auto TailBB = *TailIter;
1358
1359 // Calculate the cost by putting this BB to the top.
1360 BlockFrequency Cost = 0;
1361
1362 // If the current BB is the loop header, we need to take into account the
1363 // cost of the missed fall through edge from outside of the loop to the
1364 // header.
1365 if (Iter != HeaderIter)
1366 Cost += HeaderFallThroughCost;
1367
1368 // Collect the loop exit cost by summing up frequencies of all exit edges
1369 // except the one from the chain tail.
1370 for (auto &ExitWithFreq : ExitsWithFreq)
1371 if (TailBB != ExitWithFreq.first)
1372 Cost += ExitWithFreq.second;
1373
1374 // The cost of breaking the once fall-through edge from the tail to the top
1375 // of the loop chain. Here we need to consider three cases:
1376 // 1. If the tail node has only one successor, then we will get an
1377 // additional jmp instruction. So the cost here is (MisfetchCost +
1378 // JumpInstCost) * tail node frequency.
1379 // 2. If the tail node has two successors, then we may still get an
1380 // additional jmp instruction if the layout successor after the loop
1381 // chain is not its CFG successor. Note that the more frequently executed
1382 // jmp instruction will be put ahead of the other one. Assume the
1383 // frequency of those two branches are x and y, where x is the frequency
1384 // of the edge to the chain head, then the cost will be
1385 // (x * MisfetechCost + min(x, y) * JumpInstCost) * tail node frequency.
1386 // 3. If the tail node has more than two successors (this rarely happens),
1387 // we won't consider any additional cost.
1388 if (TailBB->isSuccessor(*Iter)) {
1389 auto TailBBFreq = MBFI->getBlockFreq(TailBB);
1390 if (TailBB->succ_size() == 1)
1391 Cost += ScaleBlockFrequency(TailBBFreq.getFrequency(),
1392 MisfetchCost + JumpInstCost);
1393 else if (TailBB->succ_size() == 2) {
1394 auto TailToHeadProb = MBPI->getEdgeProbability(TailBB, *Iter);
1395 auto TailToHeadFreq = TailBBFreq * TailToHeadProb;
1396 auto ColderEdgeFreq = TailToHeadProb > BranchProbability(1, 2)
1397 ? TailBBFreq * TailToHeadProb.getCompl()
1398 : TailToHeadFreq;
1399 Cost += ScaleBlockFrequency(TailToHeadFreq, MisfetchCost) +
1400 ScaleBlockFrequency(ColderEdgeFreq, JumpInstCost);
1401 }
1402 }
1403
Philip Reamesb9688f42016-03-02 21:45:13 +00001404 DEBUG(dbgs() << "The cost of loop rotation by making " << getBlockName(*Iter)
Cong Hou7745dbc2015-10-19 23:16:40 +00001405 << " to the top: " << Cost.getFrequency() << "\n");
1406
1407 if (Cost < SmallestRotationCost) {
1408 SmallestRotationCost = Cost;
1409 RotationPos = Iter;
1410 }
1411 }
1412
1413 if (RotationPos != LoopChain.end()) {
Philip Reamesb9688f42016-03-02 21:45:13 +00001414 DEBUG(dbgs() << "Rotate loop by making " << getBlockName(*RotationPos)
Cong Hou7745dbc2015-10-19 23:16:40 +00001415 << " to the top\n");
1416 std::rotate(LoopChain.begin(), RotationPos, LoopChain.end());
1417 }
1418}
1419
Cong Houb90b9e02015-11-02 21:24:00 +00001420/// \brief Collect blocks in the given loop that are to be placed.
1421///
1422/// When profile data is available, exclude cold blocks from the returned set;
1423/// otherwise, collect all blocks in the loop.
1424MachineBlockPlacement::BlockFilterSet
Xinliang David Li52530a72016-06-13 22:23:44 +00001425MachineBlockPlacement::collectLoopBlockSet(MachineLoop &L) {
Cong Houb90b9e02015-11-02 21:24:00 +00001426 BlockFilterSet LoopBlockSet;
1427
1428 // Filter cold blocks off from LoopBlockSet when profile data is available.
1429 // Collect the sum of frequencies of incoming edges to the loop header from
1430 // outside. If we treat the loop as a super block, this is the frequency of
1431 // the loop. Then for each block in the loop, we calculate the ratio between
1432 // its frequency and the frequency of the loop block. When it is too small,
1433 // don't add it to the loop chain. If there are outer loops, then this block
1434 // will be merged into the first outer loop chain for which this block is not
1435 // cold anymore. This needs precise profile data and we only do this when
1436 // profile data is available.
Xinliang David Li52530a72016-06-13 22:23:44 +00001437 if (F->getFunction()->getEntryCount()) {
Cong Houb90b9e02015-11-02 21:24:00 +00001438 BlockFrequency LoopFreq(0);
1439 for (auto LoopPred : L.getHeader()->predecessors())
1440 if (!L.contains(LoopPred))
1441 LoopFreq += MBFI->getBlockFreq(LoopPred) *
1442 MBPI->getEdgeProbability(LoopPred, L.getHeader());
1443
1444 for (MachineBasicBlock *LoopBB : L.getBlocks()) {
1445 auto Freq = MBFI->getBlockFreq(LoopBB).getFrequency();
1446 if (Freq == 0 || LoopFreq.getFrequency() / Freq > LoopToColdBlockRatio)
1447 continue;
1448 LoopBlockSet.insert(LoopBB);
1449 }
1450 } else
1451 LoopBlockSet.insert(L.block_begin(), L.block_end());
1452
1453 return LoopBlockSet;
1454}
1455
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00001456/// \brief Forms basic block chains from the natural loop structures.
Chandler Carruth10281422011-10-21 06:46:38 +00001457///
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00001458/// These chains are designed to preserve the existing *structure* of the code
1459/// as much as possible. We can then stitch the chains together in a way which
1460/// both preserves the topological structure and minimizes taken conditional
1461/// branches.
Xinliang David Li52530a72016-06-13 22:23:44 +00001462void MachineBlockPlacement::buildLoopChains(MachineLoop &L) {
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00001463 // First recurse through any nested loops, building chains for those inner
1464 // loops.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001465 for (MachineLoop *InnerLoop : L)
Xinliang David Li52530a72016-06-13 22:23:44 +00001466 buildLoopChains(*InnerLoop);
Chandler Carruth10281422011-10-21 06:46:38 +00001467
Xinliang David Li93926ac2016-07-01 05:46:48 +00001468 assert(BlockWorkList.empty());
1469 assert(EHPadWorkList.empty());
Xinliang David Li52530a72016-06-13 22:23:44 +00001470 BlockFilterSet LoopBlockSet = collectLoopBlockSet(L);
Chandler Carruth03adbd42011-11-27 13:34:33 +00001471
Cong Hou7745dbc2015-10-19 23:16:40 +00001472 // Check if we have profile data for this function. If yes, we will rotate
1473 // this loop by modeling costs more precisely which requires the profile data
1474 // for better layout.
1475 bool RotateLoopWithProfile =
Xinliang David Lif0ab6df2016-05-12 02:04:41 +00001476 ForcePreciseRotationCost ||
Xinliang David Li52530a72016-06-13 22:23:44 +00001477 (PreciseRotationCost && F->getFunction()->getEntryCount());
Cong Hou7745dbc2015-10-19 23:16:40 +00001478
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001479 // First check to see if there is an obviously preferable top block for the
1480 // loop. This will default to the header, but may end up as one of the
1481 // predecessors to the header if there is one which will result in strictly
1482 // fewer branches in the loop body.
Cong Hou7745dbc2015-10-19 23:16:40 +00001483 // When we use profile data to rotate the loop, this is unnecessary.
1484 MachineBasicBlock *LoopTop =
1485 RotateLoopWithProfile ? L.getHeader() : findBestLoopTop(L, LoopBlockSet);
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001486
1487 // If we selected just the header for the loop top, look for a potentially
1488 // profitable exit block in the event that rotating the loop can eliminate
1489 // branches by placing an exit edge at the bottom.
Cong Hou7745dbc2015-10-19 23:16:40 +00001490 if (!RotateLoopWithProfile && LoopTop == L.getHeader())
Kyle Buttab9cca72016-10-27 21:37:20 +00001491 PreferredLoopExit = findBestLoopExit(L, LoopBlockSet);
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001492
1493 BlockChain &LoopChain = *BlockToChain[LoopTop];
Chandler Carruth10281422011-10-21 06:46:38 +00001494
Chandler Carruth8d150782011-11-13 11:20:44 +00001495 // FIXME: This is a really lame way of walking the chains in the loop: we
1496 // walk the blocks, and use a set to prevent visiting a particular chain
1497 // twice.
Jakub Staszak90616162011-12-21 23:02:08 +00001498 SmallPtrSet<BlockChain *, 4> UpdatedPreds;
Philip Reamesae27b232016-03-03 00:58:43 +00001499 assert(LoopChain.UnscheduledPredecessors == 0);
Jakub Staszak190c7122011-12-07 19:46:10 +00001500 UpdatedPreds.insert(&LoopChain);
Cong Houb90b9e02015-11-02 21:24:00 +00001501
Amaury Secheteae09c22016-03-14 21:24:11 +00001502 for (MachineBasicBlock *LoopBB : LoopBlockSet)
Xinliang David Li93926ac2016-07-01 05:46:48 +00001503 fillWorkLists(LoopBB, UpdatedPreds, &LoopBlockSet);
Chandler Carruth8d150782011-11-13 11:20:44 +00001504
Xinliang David Li93926ac2016-07-01 05:46:48 +00001505 buildChain(LoopTop, LoopChain, &LoopBlockSet);
Cong Hou7745dbc2015-10-19 23:16:40 +00001506
1507 if (RotateLoopWithProfile)
1508 rotateLoopWithProfile(LoopChain, L, LoopBlockSet);
1509 else
Kyle Buttab9cca72016-10-27 21:37:20 +00001510 rotateLoop(LoopChain, PreferredLoopExit, LoopBlockSet);
Chandler Carruth8d150782011-11-13 11:20:44 +00001511
1512 DEBUG({
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001513 // Crash at the end so we get all of the debugging output first.
1514 bool BadLoop = false;
Philip Reamesae27b232016-03-03 00:58:43 +00001515 if (LoopChain.UnscheduledPredecessors) {
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001516 BadLoop = true;
Chandler Carruth8d150782011-11-13 11:20:44 +00001517 dbgs() << "Loop chain contains a block without its preds placed!\n"
1518 << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
1519 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n";
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001520 }
Chandler Carruth7a715da2015-03-05 03:19:05 +00001521 for (MachineBasicBlock *ChainBB : LoopChain) {
1522 dbgs() << " ... " << getBlockName(ChainBB) << "\n";
Rong Xu66827422016-11-16 20:50:06 +00001523 if (!LoopBlockSet.remove(ChainBB)) {
Chandler Carruth0a31d142011-11-14 10:55:53 +00001524 // We don't mark the loop as bad here because there are real situations
1525 // where this can occur. For example, with an unanalyzable fallthrough
Chandler Carruth99fe42f2011-11-23 10:35:36 +00001526 // from a loop block to a non-loop block or vice versa.
Chandler Carruth8d150782011-11-13 11:20:44 +00001527 dbgs() << "Loop chain contains a block not contained by the loop!\n"
1528 << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
1529 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
Chandler Carruth7a715da2015-03-05 03:19:05 +00001530 << " Bad block: " << getBlockName(ChainBB) << "\n";
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001531 }
Chandler Carruthccc7e422012-04-16 01:12:56 +00001532 }
Chandler Carruth8d150782011-11-13 11:20:44 +00001533
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001534 if (!LoopBlockSet.empty()) {
1535 BadLoop = true;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001536 for (MachineBasicBlock *LoopBB : LoopBlockSet)
Chandler Carruth8d150782011-11-13 11:20:44 +00001537 dbgs() << "Loop contains blocks never placed into a chain!\n"
1538 << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
1539 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
Chandler Carruth7a715da2015-03-05 03:19:05 +00001540 << " Bad block: " << getBlockName(LoopBB) << "\n";
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001541 }
1542 assert(!BadLoop && "Detected problems with the placement of this loop.");
Chandler Carruth8d150782011-11-13 11:20:44 +00001543 });
Xinliang David Li93926ac2016-07-01 05:46:48 +00001544
1545 BlockWorkList.clear();
1546 EHPadWorkList.clear();
Chandler Carruth10281422011-10-21 06:46:38 +00001547}
1548
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00001549/// When OutlineOpitonalBranches is on, this method collects BBs that
Xinliang David Li071d0f12016-06-12 16:54:03 +00001550/// dominates all terminator blocks of the function \p F.
Xinliang David Li52530a72016-06-13 22:23:44 +00001551void MachineBlockPlacement::collectMustExecuteBBs() {
Xinliang David Li071d0f12016-06-12 16:54:03 +00001552 if (OutlineOptionalBranches) {
1553 // Find the nearest common dominator of all of F's terminators.
1554 MachineBasicBlock *Terminator = nullptr;
Xinliang David Li52530a72016-06-13 22:23:44 +00001555 for (MachineBasicBlock &MBB : *F) {
Xinliang David Li071d0f12016-06-12 16:54:03 +00001556 if (MBB.succ_size() == 0) {
1557 if (Terminator == nullptr)
1558 Terminator = &MBB;
1559 else
1560 Terminator = MDT->findNearestCommonDominator(Terminator, &MBB);
1561 }
1562 }
1563
1564 // MBBs dominating this common dominator are unavoidable.
1565 UnavoidableBlocks.clear();
Xinliang David Li52530a72016-06-13 22:23:44 +00001566 for (MachineBasicBlock &MBB : *F) {
Xinliang David Li071d0f12016-06-12 16:54:03 +00001567 if (MDT->dominates(&MBB, Terminator)) {
1568 UnavoidableBlocks.insert(&MBB);
1569 }
1570 }
1571 }
1572}
1573
Xinliang David Li52530a72016-06-13 22:23:44 +00001574void MachineBlockPlacement::buildCFGChains() {
Chandler Carruth8d150782011-11-13 11:20:44 +00001575 // Ensure that every BB in the function has an associated chain to simplify
1576 // the assumptions of the remaining algorithm.
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +00001577 SmallVector<MachineOperand, 4> Cond; // For AnalyzeBranch.
Xinliang David Li52530a72016-06-13 22:23:44 +00001578 for (MachineFunction::iterator FI = F->begin(), FE = F->end(); FI != FE;
1579 ++FI) {
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +00001580 MachineBasicBlock *BB = &*FI;
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001581 BlockChain *Chain =
1582 new (ChainAllocator.Allocate()) BlockChain(BlockToChain, BB);
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +00001583 // Also, merge any blocks which we cannot reason about and must preserve
1584 // the exact fallthrough behavior for.
1585 for (;;) {
1586 Cond.clear();
Craig Topperc0196b12014-04-14 00:51:57 +00001587 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
Jacques Pienaar71c30a12016-07-15 14:41:04 +00001588 if (!TII->analyzeBranch(*BB, TBB, FBB, Cond) || !FI->canFallThrough())
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +00001589 break;
1590
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +00001591 MachineFunction::iterator NextFI = std::next(FI);
1592 MachineBasicBlock *NextBB = &*NextFI;
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +00001593 // Ensure that the layout successor is a viable block, as we know that
1594 // fallthrough is a possibility.
1595 assert(NextFI != FE && "Can't fallthrough past the last block.");
1596 DEBUG(dbgs() << "Pre-merging due to unanalyzable fallthrough: "
1597 << getBlockName(BB) << " -> " << getBlockName(NextBB)
1598 << "\n");
Craig Topperc0196b12014-04-14 00:51:57 +00001599 Chain->merge(NextBB, nullptr);
Hal Finkel34f9d6a2016-12-15 05:33:19 +00001600#ifndef NDEBUG
Sanjoy Dasd7389d62016-12-15 05:08:57 +00001601 BlocksWithUnanalyzableExits.insert(&*BB);
Hal Finkel34f9d6a2016-12-15 05:33:19 +00001602#endif
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +00001603 FI = NextFI;
1604 BB = NextBB;
1605 }
1606 }
Chandler Carruth8d150782011-11-13 11:20:44 +00001607
Xinliang David Li071d0f12016-06-12 16:54:03 +00001608 // Turned on with OutlineOptionalBranches option
Xinliang David Li52530a72016-06-13 22:23:44 +00001609 collectMustExecuteBBs();
Daniel Jasper471e8562015-03-04 11:05:34 +00001610
Chandler Carruth8d150782011-11-13 11:20:44 +00001611 // Build any loop-based chains.
Sam McCall2a36eee2016-11-01 22:02:14 +00001612 PreferredLoopExit = nullptr;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001613 for (MachineLoop *L : *MLI)
Xinliang David Li52530a72016-06-13 22:23:44 +00001614 buildLoopChains(*L);
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00001615
Xinliang David Li93926ac2016-07-01 05:46:48 +00001616 assert(BlockWorkList.empty());
1617 assert(EHPadWorkList.empty());
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00001618
Chandler Carruth8d150782011-11-13 11:20:44 +00001619 SmallPtrSet<BlockChain *, 4> UpdatedPreds;
Xinliang David Li52530a72016-06-13 22:23:44 +00001620 for (MachineBasicBlock &MBB : *F)
Xinliang David Li93926ac2016-07-01 05:46:48 +00001621 fillWorkLists(&MBB, UpdatedPreds);
Chandler Carruth8d150782011-11-13 11:20:44 +00001622
Xinliang David Li52530a72016-06-13 22:23:44 +00001623 BlockChain &FunctionChain = *BlockToChain[&F->front()];
Xinliang David Li93926ac2016-07-01 05:46:48 +00001624 buildChain(&F->front(), FunctionChain);
Chandler Carruth8d150782011-11-13 11:20:44 +00001625
Matt Arsenault0f5f0152013-12-10 18:55:37 +00001626#ifndef NDEBUG
Matt Arsenault79d55f52013-12-05 20:02:18 +00001627 typedef SmallPtrSet<MachineBasicBlock *, 16> FunctionBlockSetType;
Matt Arsenault0f5f0152013-12-10 18:55:37 +00001628#endif
Chandler Carruth8d150782011-11-13 11:20:44 +00001629 DEBUG({
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001630 // Crash at the end so we get all of the debugging output first.
1631 bool BadFunc = false;
Chandler Carruth8d150782011-11-13 11:20:44 +00001632 FunctionBlockSetType FunctionBlockSet;
Xinliang David Li52530a72016-06-13 22:23:44 +00001633 for (MachineBasicBlock &MBB : *F)
Chandler Carruth7a715da2015-03-05 03:19:05 +00001634 FunctionBlockSet.insert(&MBB);
Chandler Carruth8d150782011-11-13 11:20:44 +00001635
Chandler Carruth7a715da2015-03-05 03:19:05 +00001636 for (MachineBasicBlock *ChainBB : FunctionChain)
1637 if (!FunctionBlockSet.erase(ChainBB)) {
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001638 BadFunc = true;
Chandler Carruth8d150782011-11-13 11:20:44 +00001639 dbgs() << "Function chain contains a block not in the function!\n"
Chandler Carruth7a715da2015-03-05 03:19:05 +00001640 << " Bad block: " << getBlockName(ChainBB) << "\n";
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001641 }
Chandler Carruth8d150782011-11-13 11:20:44 +00001642
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001643 if (!FunctionBlockSet.empty()) {
1644 BadFunc = true;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001645 for (MachineBasicBlock *RemainingBB : FunctionBlockSet)
Chandler Carruth8d150782011-11-13 11:20:44 +00001646 dbgs() << "Function contains blocks never placed into a chain!\n"
Chandler Carruth7a715da2015-03-05 03:19:05 +00001647 << " Bad block: " << getBlockName(RemainingBB) << "\n";
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001648 }
1649 assert(!BadFunc && "Detected problems with the block placement.");
Chandler Carruth8d150782011-11-13 11:20:44 +00001650 });
1651
1652 // Splice the blocks into place.
Xinliang David Li52530a72016-06-13 22:23:44 +00001653 MachineFunction::iterator InsertPos = F->begin();
Xinliang David Li449cdfd2016-06-24 22:54:21 +00001654 DEBUG(dbgs() << "[MBP] Function: "<< F->getName() << "\n");
Chandler Carruth7a715da2015-03-05 03:19:05 +00001655 for (MachineBasicBlock *ChainBB : FunctionChain) {
1656 DEBUG(dbgs() << (ChainBB == *FunctionChain.begin() ? "Placing chain "
1657 : " ... ")
1658 << getBlockName(ChainBB) << "\n");
1659 if (InsertPos != MachineFunction::iterator(ChainBB))
Xinliang David Li52530a72016-06-13 22:23:44 +00001660 F->splice(InsertPos, ChainBB);
Chandler Carruth8d150782011-11-13 11:20:44 +00001661 else
1662 ++InsertPos;
1663
1664 // Update the terminator of the previous block.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001665 if (ChainBB == *FunctionChain.begin())
Chandler Carruth8d150782011-11-13 11:20:44 +00001666 continue;
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +00001667 MachineBasicBlock *PrevBB = &*std::prev(MachineFunction::iterator(ChainBB));
Chandler Carruth8d150782011-11-13 11:20:44 +00001668
Chandler Carruth10281422011-10-21 06:46:38 +00001669 // FIXME: It would be awesome of updateTerminator would just return rather
1670 // than assert when the branch cannot be analyzed in order to remove this
1671 // boiler plate.
1672 Cond.clear();
Craig Topperc0196b12014-04-14 00:51:57 +00001673 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
Shuxin Yang8b8fd212013-06-04 01:00:57 +00001674
Sanjoy Dasd7389d62016-12-15 05:08:57 +00001675#ifndef NDEBUG
1676 if (!BlocksWithUnanalyzableExits.count(PrevBB)) {
1677 // Given the exact block placement we chose, we may actually not _need_ to
1678 // be able to edit PrevBB's terminator sequence, but not being _able_ to
1679 // do that at this point is a bug.
1680 assert((!TII->analyzeBranch(*PrevBB, TBB, FBB, Cond) ||
1681 !PrevBB->canFallThrough()) &&
1682 "Unexpected block with un-analyzable fallthrough!");
1683 Cond.clear();
1684 TBB = FBB = nullptr;
1685 }
1686#endif
1687
Haicheng Wu90a55652016-05-24 22:16:14 +00001688 // The "PrevBB" is not yet updated to reflect current code layout, so,
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00001689 // o. it may fall-through to a block without explicit "goto" instruction
Haicheng Wu90a55652016-05-24 22:16:14 +00001690 // before layout, and no longer fall-through it after layout; or
1691 // o. just opposite.
1692 //
Jacques Pienaar71c30a12016-07-15 14:41:04 +00001693 // analyzeBranch() may return erroneous value for FBB when these two
Haicheng Wu90a55652016-05-24 22:16:14 +00001694 // situations take place. For the first scenario FBB is mistakenly set NULL;
1695 // for the 2nd scenario, the FBB, which is expected to be NULL, is
1696 // mistakenly pointing to "*BI".
1697 // Thus, if the future change needs to use FBB before the layout is set, it
1698 // has to correct FBB first by using the code similar to the following:
1699 //
1700 // if (!Cond.empty() && (!FBB || FBB == ChainBB)) {
1701 // PrevBB->updateTerminator();
1702 // Cond.clear();
1703 // TBB = FBB = nullptr;
Jacques Pienaar71c30a12016-07-15 14:41:04 +00001704 // if (TII->analyzeBranch(*PrevBB, TBB, FBB, Cond)) {
Haicheng Wu90a55652016-05-24 22:16:14 +00001705 // // FIXME: This should never take place.
1706 // TBB = FBB = nullptr;
1707 // }
1708 // }
Jacques Pienaar71c30a12016-07-15 14:41:04 +00001709 if (!TII->analyzeBranch(*PrevBB, TBB, FBB, Cond))
Haicheng Wu90a55652016-05-24 22:16:14 +00001710 PrevBB->updateTerminator();
Chandler Carruth10281422011-10-21 06:46:38 +00001711 }
Chandler Carruth8d150782011-11-13 11:20:44 +00001712
1713 // Fixup the last block.
1714 Cond.clear();
Craig Topperc0196b12014-04-14 00:51:57 +00001715 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
Jacques Pienaar71c30a12016-07-15 14:41:04 +00001716 if (!TII->analyzeBranch(F->back(), TBB, FBB, Cond))
Xinliang David Li52530a72016-06-13 22:23:44 +00001717 F->back().updateTerminator();
Xinliang David Li93926ac2016-07-01 05:46:48 +00001718
1719 BlockWorkList.clear();
1720 EHPadWorkList.clear();
Haicheng Wu90a55652016-05-24 22:16:14 +00001721}
1722
Xinliang David Li52530a72016-06-13 22:23:44 +00001723void MachineBlockPlacement::optimizeBranches() {
1724 BlockChain &FunctionChain = *BlockToChain[&F->front()];
Haicheng Wu90a55652016-05-24 22:16:14 +00001725 SmallVector<MachineOperand, 4> Cond; // For AnalyzeBranch.
Quentin Colombet776e6de2016-05-02 22:58:59 +00001726
1727 // Now that all the basic blocks in the chain have the proper layout,
1728 // make a final call to AnalyzeBranch with AllowModify set.
1729 // Indeed, the target may be able to optimize the branches in a way we
1730 // cannot because all branches may not be analyzable.
1731 // E.g., the target may be able to remove an unconditional branch to
1732 // a fallthrough when it occurs after predicated terminators.
1733 for (MachineBasicBlock *ChainBB : FunctionChain) {
1734 Cond.clear();
Haicheng Wu90a55652016-05-24 22:16:14 +00001735 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
Jacques Pienaar71c30a12016-07-15 14:41:04 +00001736 if (!TII->analyzeBranch(*ChainBB, TBB, FBB, Cond, /*AllowModify*/ true)) {
Haicheng Wu90a55652016-05-24 22:16:14 +00001737 // If PrevBB has a two-way branch, try to re-order the branches
1738 // such that we branch to the successor with higher probability first.
1739 if (TBB && !Cond.empty() && FBB &&
1740 MBPI->getEdgeProbability(ChainBB, FBB) >
1741 MBPI->getEdgeProbability(ChainBB, TBB) &&
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +00001742 !TII->reverseBranchCondition(Cond)) {
Haicheng Wu90a55652016-05-24 22:16:14 +00001743 DEBUG(dbgs() << "Reverse order of the two branches: "
1744 << getBlockName(ChainBB) << "\n");
1745 DEBUG(dbgs() << " Edge probability: "
1746 << MBPI->getEdgeProbability(ChainBB, FBB) << " vs "
1747 << MBPI->getEdgeProbability(ChainBB, TBB) << "\n");
1748 DebugLoc dl; // FIXME: this is nowhere
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +00001749 TII->removeBranch(*ChainBB);
Matt Arsenaulte8e0f5c2016-09-14 17:24:15 +00001750 TII->insertBranch(*ChainBB, FBB, TBB, Cond, dl);
Haicheng Wu90a55652016-05-24 22:16:14 +00001751 ChainBB->updateTerminator();
1752 }
1753 }
Quentin Colombet776e6de2016-05-02 22:58:59 +00001754 }
Haicheng Wue749ce52016-04-29 17:06:44 +00001755}
Chandler Carruth10281422011-10-21 06:46:38 +00001756
Xinliang David Li52530a72016-06-13 22:23:44 +00001757void MachineBlockPlacement::alignBlocks() {
Chandler Carruthccc7e422012-04-16 01:12:56 +00001758 // Walk through the backedges of the function now that we have fully laid out
1759 // the basic blocks and align the destination of each backedge. We don't rely
Chandler Carruth881d0a72012-08-07 09:45:24 +00001760 // exclusively on the loop info here so that we can align backedges in
1761 // unnatural CFGs and backedges that were introduced purely because of the
1762 // loop rotations done during this layout pass.
Xinliang David Li52530a72016-06-13 22:23:44 +00001763 if (F->getFunction()->optForSize())
Chandler Carruth8b9737c2011-10-21 08:57:37 +00001764 return;
Xinliang David Li52530a72016-06-13 22:23:44 +00001765 BlockChain &FunctionChain = *BlockToChain[&F->front()];
Chandler Carruth881d0a72012-08-07 09:45:24 +00001766 if (FunctionChain.begin() == FunctionChain.end())
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001767 return; // Empty chain.
Chandler Carruth8b9737c2011-10-21 08:57:37 +00001768
Chandler Carruth881d0a72012-08-07 09:45:24 +00001769 const BranchProbability ColdProb(1, 5); // 20%
Xinliang David Li52530a72016-06-13 22:23:44 +00001770 BlockFrequency EntryFreq = MBFI->getBlockFreq(&F->front());
Chandler Carruth881d0a72012-08-07 09:45:24 +00001771 BlockFrequency WeightedEntryFreq = EntryFreq * ColdProb;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001772 for (MachineBasicBlock *ChainBB : FunctionChain) {
1773 if (ChainBB == *FunctionChain.begin())
1774 continue;
1775
Chandler Carruth881d0a72012-08-07 09:45:24 +00001776 // Don't align non-looping basic blocks. These are unlikely to execute
1777 // enough times to matter in practice. Note that we'll still handle
1778 // unnatural CFGs inside of a natural outer loop (the common case) and
1779 // rotated loops.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001780 MachineLoop *L = MLI->getLoopFor(ChainBB);
Chandler Carruth881d0a72012-08-07 09:45:24 +00001781 if (!L)
1782 continue;
1783
Hal Finkel57725662015-01-03 17:58:24 +00001784 unsigned Align = TLI->getPrefLoopAlignment(L);
1785 if (!Align)
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001786 continue; // Don't care about loop alignment.
Hal Finkel57725662015-01-03 17:58:24 +00001787
Chandler Carruth881d0a72012-08-07 09:45:24 +00001788 // If the block is cold relative to the function entry don't waste space
1789 // aligning it.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001790 BlockFrequency Freq = MBFI->getBlockFreq(ChainBB);
Chandler Carruth881d0a72012-08-07 09:45:24 +00001791 if (Freq < WeightedEntryFreq)
1792 continue;
1793
1794 // If the block is cold relative to its loop header, don't align it
1795 // regardless of what edges into the block exist.
1796 MachineBasicBlock *LoopHeader = L->getHeader();
1797 BlockFrequency LoopHeaderFreq = MBFI->getBlockFreq(LoopHeader);
1798 if (Freq < (LoopHeaderFreq * ColdProb))
1799 continue;
1800
1801 // Check for the existence of a non-layout predecessor which would benefit
1802 // from aligning this block.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001803 MachineBasicBlock *LayoutPred =
1804 &*std::prev(MachineFunction::iterator(ChainBB));
Chandler Carruth881d0a72012-08-07 09:45:24 +00001805
1806 // Force alignment if all the predecessors are jumps. We already checked
1807 // that the block isn't cold above.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001808 if (!LayoutPred->isSuccessor(ChainBB)) {
1809 ChainBB->setAlignment(Align);
Chandler Carruth881d0a72012-08-07 09:45:24 +00001810 continue;
1811 }
1812
1813 // Align this block if the layout predecessor's edge into this block is
Nadav Rotem6036f582013-03-29 16:34:23 +00001814 // cold relative to the block. When this is true, other predecessors make up
Chandler Carruth881d0a72012-08-07 09:45:24 +00001815 // all of the hot entries into the block and thus alignment is likely to be
1816 // important.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001817 BranchProbability LayoutProb =
1818 MBPI->getEdgeProbability(LayoutPred, ChainBB);
Chandler Carruth881d0a72012-08-07 09:45:24 +00001819 BlockFrequency LayoutEdgeFreq = MBFI->getBlockFreq(LayoutPred) * LayoutProb;
1820 if (LayoutEdgeFreq <= (Freq * ColdProb))
Chandler Carruth7a715da2015-03-05 03:19:05 +00001821 ChainBB->setAlignment(Align);
Chandler Carruthccc7e422012-04-16 01:12:56 +00001822 }
Chandler Carruth8b9737c2011-10-21 08:57:37 +00001823}
1824
Kyle Butt0846e562016-10-11 20:36:43 +00001825/// Tail duplicate \p BB into (some) predecessors if profitable, repeating if
1826/// it was duplicated into its chain predecessor and removed.
1827/// \p BB - Basic block that may be duplicated.
1828///
1829/// \p LPred - Chosen layout predecessor of \p BB.
1830/// Updated to be the chain end if LPred is removed.
1831/// \p Chain - Chain to which \p LPred belongs, and \p BB will belong.
1832/// \p BlockFilter - Set of blocks that belong to the loop being laid out.
1833/// Used to identify which blocks to update predecessor
1834/// counts.
1835/// \p PrevUnplacedBlockIt - Iterator pointing to the last block that was
1836/// chosen in the given order due to unnatural CFG
1837/// only needed if \p BB is removed and
1838/// \p PrevUnplacedBlockIt pointed to \p BB.
1839/// @return true if \p BB was removed.
1840bool MachineBlockPlacement::repeatedlyTailDuplicateBlock(
1841 MachineBasicBlock *BB, MachineBasicBlock *&LPred,
1842 MachineBasicBlock *LoopHeaderBB,
1843 BlockChain &Chain, BlockFilterSet *BlockFilter,
1844 MachineFunction::iterator &PrevUnplacedBlockIt) {
1845 bool Removed, DuplicatedToLPred;
1846 bool DuplicatedToOriginalLPred;
1847 Removed = maybeTailDuplicateBlock(BB, LPred, Chain, BlockFilter,
1848 PrevUnplacedBlockIt,
1849 DuplicatedToLPred);
1850 if (!Removed)
1851 return false;
1852 DuplicatedToOriginalLPred = DuplicatedToLPred;
1853 // Iteratively try to duplicate again. It can happen that a block that is
1854 // duplicated into is still small enough to be duplicated again.
1855 // No need to call markBlockSuccessors in this case, as the blocks being
1856 // duplicated from here on are already scheduled.
1857 // Note that DuplicatedToLPred always implies Removed.
1858 while (DuplicatedToLPred) {
1859 assert (Removed && "Block must have been removed to be duplicated into its "
1860 "layout predecessor.");
1861 MachineBasicBlock *DupBB, *DupPred;
1862 // The removal callback causes Chain.end() to be updated when a block is
1863 // removed. On the first pass through the loop, the chain end should be the
1864 // same as it was on function entry. On subsequent passes, because we are
1865 // duplicating the block at the end of the chain, if it is removed the
1866 // chain will have shrunk by one block.
1867 BlockChain::iterator ChainEnd = Chain.end();
1868 DupBB = *(--ChainEnd);
1869 // Now try to duplicate again.
1870 if (ChainEnd == Chain.begin())
1871 break;
1872 DupPred = *std::prev(ChainEnd);
1873 Removed = maybeTailDuplicateBlock(DupBB, DupPred, Chain, BlockFilter,
1874 PrevUnplacedBlockIt,
1875 DuplicatedToLPred);
1876 }
1877 // If BB was duplicated into LPred, it is now scheduled. But because it was
1878 // removed, markChainSuccessors won't be called for its chain. Instead we
1879 // call markBlockSuccessors for LPred to achieve the same effect. This must go
1880 // at the end because repeating the tail duplication can increase the number
1881 // of unscheduled predecessors.
1882 LPred = *std::prev(Chain.end());
1883 if (DuplicatedToOriginalLPred)
1884 markBlockSuccessors(Chain, LPred, LoopHeaderBB, BlockFilter);
1885 return true;
1886}
1887
1888/// Tail duplicate \p BB into (some) predecessors if profitable.
1889/// \p BB - Basic block that may be duplicated
1890/// \p LPred - Chosen layout predecessor of \p BB
1891/// \p Chain - Chain to which \p LPred belongs, and \p BB will belong.
1892/// \p BlockFilter - Set of blocks that belong to the loop being laid out.
1893/// Used to identify which blocks to update predecessor
1894/// counts.
1895/// \p PrevUnplacedBlockIt - Iterator pointing to the last block that was
1896/// chosen in the given order due to unnatural CFG
1897/// only needed if \p BB is removed and
1898/// \p PrevUnplacedBlockIt pointed to \p BB.
1899/// \p DuplicatedToLPred - True if the block was duplicated into LPred. Will
1900/// only be true if the block was removed.
1901/// \return - True if the block was duplicated into all preds and removed.
1902bool MachineBlockPlacement::maybeTailDuplicateBlock(
1903 MachineBasicBlock *BB, MachineBasicBlock *LPred,
1904 const BlockChain &Chain, BlockFilterSet *BlockFilter,
1905 MachineFunction::iterator &PrevUnplacedBlockIt,
1906 bool &DuplicatedToLPred) {
1907
1908 DuplicatedToLPred = false;
1909 DEBUG(dbgs() << "Redoing tail duplication for Succ#"
1910 << BB->getNumber() << "\n");
1911 bool IsSimple = TailDup.isSimpleBB(BB);
1912 // Blocks with single successors don't create additional fallthrough
1913 // opportunities. Don't duplicate them. TODO: When conditional exits are
1914 // analyzable, allow them to be duplicated.
1915 if (!IsSimple && BB->succ_size() == 1)
1916 return false;
1917 if (!TailDup.shouldTailDuplicate(IsSimple, *BB))
1918 return false;
1919 // This has to be a callback because none of it can be done after
1920 // BB is deleted.
1921 bool Removed = false;
1922 auto RemovalCallback =
1923 [&](MachineBasicBlock *RemBB) {
1924 // Signal to outer function
1925 Removed = true;
1926
1927 // Conservative default.
1928 bool InWorkList = true;
1929 // Remove from the Chain and Chain Map
1930 if (BlockToChain.count(RemBB)) {
1931 BlockChain *Chain = BlockToChain[RemBB];
1932 InWorkList = Chain->UnscheduledPredecessors == 0;
1933 Chain->remove(RemBB);
1934 BlockToChain.erase(RemBB);
1935 }
1936
1937 // Handle the unplaced block iterator
1938 if (&(*PrevUnplacedBlockIt) == RemBB) {
1939 PrevUnplacedBlockIt++;
1940 }
1941
1942 // Handle the Work Lists
1943 if (InWorkList) {
1944 SmallVectorImpl<MachineBasicBlock *> &RemoveList = BlockWorkList;
1945 if (RemBB->isEHPad())
1946 RemoveList = EHPadWorkList;
1947 RemoveList.erase(
1948 remove_if(RemoveList,
1949 [RemBB](MachineBasicBlock *BB) {return BB == RemBB;}),
1950 RemoveList.end());
1951 }
1952
1953 // Handle the filter set
1954 if (BlockFilter) {
Rong Xu66827422016-11-16 20:50:06 +00001955 BlockFilter->remove(RemBB);
Kyle Butt0846e562016-10-11 20:36:43 +00001956 }
1957
1958 // Remove the block from loop info.
1959 MLI->removeBlock(RemBB);
Kyle Buttab9cca72016-10-27 21:37:20 +00001960 if (RemBB == PreferredLoopExit)
1961 PreferredLoopExit = nullptr;
Kyle Butt0846e562016-10-11 20:36:43 +00001962
Kyle Butt0846e562016-10-11 20:36:43 +00001963 DEBUG(dbgs() << "TailDuplicator deleted block: "
1964 << getBlockName(RemBB) << "\n");
1965 };
1966 auto RemovalCallbackRef =
1967 llvm::function_ref<void(MachineBasicBlock*)>(RemovalCallback);
1968
1969 SmallVector<MachineBasicBlock *, 8> DuplicatedPreds;
1970 TailDup.tailDuplicateAndUpdate(IsSimple, BB, LPred,
1971 &DuplicatedPreds, &RemovalCallbackRef);
1972
1973 // Update UnscheduledPredecessors to reflect tail-duplication.
1974 DuplicatedToLPred = false;
1975 for (MachineBasicBlock *Pred : DuplicatedPreds) {
1976 // We're only looking for unscheduled predecessors that match the filter.
1977 BlockChain* PredChain = BlockToChain[Pred];
1978 if (Pred == LPred)
1979 DuplicatedToLPred = true;
1980 if (Pred == LPred || (BlockFilter && !BlockFilter->count(Pred))
1981 || PredChain == &Chain)
1982 continue;
1983 for (MachineBasicBlock *NewSucc : Pred->successors()) {
1984 if (BlockFilter && !BlockFilter->count(NewSucc))
1985 continue;
1986 BlockChain *NewChain = BlockToChain[NewSucc];
1987 if (NewChain != &Chain && NewChain != PredChain)
1988 NewChain->UnscheduledPredecessors++;
1989 }
1990 }
1991 return Removed;
1992}
1993
Xinliang David Li52530a72016-06-13 22:23:44 +00001994bool MachineBlockPlacement::runOnMachineFunction(MachineFunction &MF) {
1995 if (skipFunction(*MF.getFunction()))
Andrew Kaylor50271f72016-05-03 22:32:30 +00001996 return false;
1997
Chandler Carruth10281422011-10-21 06:46:38 +00001998 // Check for single-block functions and skip them.
Xinliang David Li52530a72016-06-13 22:23:44 +00001999 if (std::next(MF.begin()) == MF.end())
Chandler Carruth10281422011-10-21 06:46:38 +00002000 return false;
2001
Xinliang David Li52530a72016-06-13 22:23:44 +00002002 F = &MF;
Chandler Carruth10281422011-10-21 06:46:38 +00002003 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
Haicheng Wu5b458cc2016-06-09 15:24:29 +00002004 MBFI = llvm::make_unique<BranchFolder::MBFIWrapper>(
2005 getAnalysis<MachineBlockFrequencyInfo>());
Chandler Carruth8b9737c2011-10-21 08:57:37 +00002006 MLI = &getAnalysis<MachineLoopInfo>();
Xinliang David Li52530a72016-06-13 22:23:44 +00002007 TII = MF.getSubtarget().getInstrInfo();
2008 TLI = MF.getSubtarget().getTargetLowering();
Daniel Jasper471e8562015-03-04 11:05:34 +00002009 MDT = &getAnalysis<MachineDominatorTree>();
Eric Christopher690f8e52016-11-01 22:15:50 +00002010
2011 // Initialize PreferredLoopExit to nullptr here since it may never be set if
2012 // there are no MachineLoops.
2013 PreferredLoopExit = nullptr;
2014
Kyle Butt0846e562016-10-11 20:36:43 +00002015 if (TailDupPlacement) {
2016 unsigned TailDupSize = TailDuplicatePlacementThreshold;
2017 if (MF.getFunction()->optForSize())
2018 TailDupSize = 1;
2019 TailDup.initMF(MF, MBPI, /* LayoutMode */ true, TailDupSize);
2020 }
2021
Chandler Carruth10281422011-10-21 06:46:38 +00002022 assert(BlockToChain.empty());
Chandler Carruth10281422011-10-21 06:46:38 +00002023
Xinliang David Li52530a72016-06-13 22:23:44 +00002024 buildCFGChains();
Haicheng Wu5b458cc2016-06-09 15:24:29 +00002025
2026 // Changing the layout can create new tail merging opportunities.
2027 TargetPassConfig *PassConfig = &getAnalysis<TargetPassConfig>();
2028 // TailMerge can create jump into if branches that make CFG irreducible for
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00002029 // HW that requires structured CFG.
Xinliang David Li52530a72016-06-13 22:23:44 +00002030 bool EnableTailMerge = !MF.getTarget().requiresStructuredCFG() &&
Haicheng Wu5b458cc2016-06-09 15:24:29 +00002031 PassConfig->getEnableTailMerge() &&
2032 BranchFoldPlacement;
2033 // No tail merging opportunities if the block number is less than four.
Xinliang David Li52530a72016-06-13 22:23:44 +00002034 if (MF.size() > 3 && EnableTailMerge) {
Kyle Butt0846e562016-10-11 20:36:43 +00002035 unsigned TailMergeSize = TailDuplicatePlacementThreshold + 1;
Haicheng Wu5b458cc2016-06-09 15:24:29 +00002036 BranchFolder BF(/*EnableTailMerge=*/true, /*CommonHoist=*/false, *MBFI,
Kyle Butt64e42812016-08-18 18:57:29 +00002037 *MBPI, TailMergeSize);
Haicheng Wu5b458cc2016-06-09 15:24:29 +00002038
Xinliang David Li52530a72016-06-13 22:23:44 +00002039 if (BF.OptimizeFunction(MF, TII, MF.getSubtarget().getRegisterInfo(),
Haicheng Wu5b458cc2016-06-09 15:24:29 +00002040 getAnalysisIfAvailable<MachineModuleInfo>(), MLI,
2041 /*AfterBlockPlacement=*/true)) {
2042 // Redo the layout if tail merging creates/removes/moves blocks.
2043 BlockToChain.clear();
Kyle Butt0846e562016-10-11 20:36:43 +00002044 // Must redo the dominator tree if blocks were changed.
2045 MDT->runOnMachineFunction(MF);
Haicheng Wu5b458cc2016-06-09 15:24:29 +00002046 ChainAllocator.DestroyAll();
Xinliang David Li52530a72016-06-13 22:23:44 +00002047 buildCFGChains();
Haicheng Wu5b458cc2016-06-09 15:24:29 +00002048 }
2049 }
2050
Xinliang David Li52530a72016-06-13 22:23:44 +00002051 optimizeBranches();
2052 alignBlocks();
Chandler Carruth10281422011-10-21 06:46:38 +00002053
Chandler Carruth10281422011-10-21 06:46:38 +00002054 BlockToChain.clear();
Chandler Carruthfd9b4d92011-11-14 10:57:23 +00002055 ChainAllocator.DestroyAll();
Chandler Carruth10281422011-10-21 06:46:38 +00002056
Nadav Rotemc0adc9f2013-04-12 01:24:16 +00002057 if (AlignAllBlock)
2058 // Align all of the blocks in the function to a specific alignment.
Xinliang David Li52530a72016-06-13 22:23:44 +00002059 for (MachineBasicBlock &MBB : MF)
Chandler Carruth7a715da2015-03-05 03:19:05 +00002060 MBB.setAlignment(AlignAllBlock);
Geoff Berry10494ac2016-01-21 17:25:52 +00002061 else if (AlignAllNonFallThruBlocks) {
2062 // Align all of the blocks that have no fall-through predecessors to a
2063 // specific alignment.
Xinliang David Li52530a72016-06-13 22:23:44 +00002064 for (auto MBI = std::next(MF.begin()), MBE = MF.end(); MBI != MBE; ++MBI) {
Geoff Berry10494ac2016-01-21 17:25:52 +00002065 auto LayoutPred = std::prev(MBI);
2066 if (!LayoutPred->isSuccessor(&*MBI))
2067 MBI->setAlignment(AlignAllNonFallThruBlocks);
2068 }
2069 }
Nadav Rotemc0adc9f2013-04-12 01:24:16 +00002070
Chandler Carruth10281422011-10-21 06:46:38 +00002071 // We always return true as we have no way to track whether the final order
2072 // differs from the original order.
2073 return true;
2074}
Chandler Carruthae4e8002011-11-02 07:17:12 +00002075
2076namespace {
2077/// \brief A pass to compute block placement statistics.
2078///
2079/// A separate pass to compute interesting statistics for evaluating block
2080/// placement. This is separate from the actual placement pass so that they can
Benjamin Kramerbde91762012-06-02 10:20:22 +00002081/// be computed in the absence of any placement transformations or when using
Chandler Carruthae4e8002011-11-02 07:17:12 +00002082/// alternative placement strategies.
2083class MachineBlockPlacementStats : public MachineFunctionPass {
2084 /// \brief A handle to the branch probability pass.
2085 const MachineBranchProbabilityInfo *MBPI;
2086
2087 /// \brief A handle to the function-wide block frequency pass.
2088 const MachineBlockFrequencyInfo *MBFI;
2089
2090public:
2091 static char ID; // Pass identification, replacement for typeid
2092 MachineBlockPlacementStats() : MachineFunctionPass(ID) {
2093 initializeMachineBlockPlacementStatsPass(*PassRegistry::getPassRegistry());
2094 }
2095
Craig Topper4584cd52014-03-07 09:26:03 +00002096 bool runOnMachineFunction(MachineFunction &F) override;
Chandler Carruthae4e8002011-11-02 07:17:12 +00002097
Craig Topper4584cd52014-03-07 09:26:03 +00002098 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruthae4e8002011-11-02 07:17:12 +00002099 AU.addRequired<MachineBranchProbabilityInfo>();
2100 AU.addRequired<MachineBlockFrequencyInfo>();
2101 AU.setPreservesAll();
2102 MachineFunctionPass::getAnalysisUsage(AU);
2103 }
Chandler Carruthae4e8002011-11-02 07:17:12 +00002104};
Alexander Kornienkof00654e2015-06-23 09:49:53 +00002105}
Chandler Carruthae4e8002011-11-02 07:17:12 +00002106
2107char MachineBlockPlacementStats::ID = 0;
Andrew Trick1fa5bcb2012-02-08 21:23:13 +00002108char &llvm::MachineBlockPlacementStatsID = MachineBlockPlacementStats::ID;
Chandler Carruthae4e8002011-11-02 07:17:12 +00002109INITIALIZE_PASS_BEGIN(MachineBlockPlacementStats, "block-placement-stats",
2110 "Basic Block Placement Stats", false, false)
2111INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
2112INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
2113INITIALIZE_PASS_END(MachineBlockPlacementStats, "block-placement-stats",
2114 "Basic Block Placement Stats", false, false)
2115
Chandler Carruthae4e8002011-11-02 07:17:12 +00002116bool MachineBlockPlacementStats::runOnMachineFunction(MachineFunction &F) {
2117 // Check for single-block functions and skip them.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00002118 if (std::next(F.begin()) == F.end())
Chandler Carruthae4e8002011-11-02 07:17:12 +00002119 return false;
2120
2121 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
2122 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
2123
Chandler Carruth7a715da2015-03-05 03:19:05 +00002124 for (MachineBasicBlock &MBB : F) {
2125 BlockFrequency BlockFreq = MBFI->getBlockFreq(&MBB);
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00002126 Statistic &NumBranches =
Chandler Carruth7a715da2015-03-05 03:19:05 +00002127 (MBB.succ_size() > 1) ? NumCondBranches : NumUncondBranches;
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00002128 Statistic &BranchTakenFreq =
Chandler Carruth7a715da2015-03-05 03:19:05 +00002129 (MBB.succ_size() > 1) ? CondBranchTakenFreq : UncondBranchTakenFreq;
2130 for (MachineBasicBlock *Succ : MBB.successors()) {
Chandler Carruthae4e8002011-11-02 07:17:12 +00002131 // Skip if this successor is a fallthrough.
Chandler Carruth7a715da2015-03-05 03:19:05 +00002132 if (MBB.isLayoutSuccessor(Succ))
Chandler Carruthae4e8002011-11-02 07:17:12 +00002133 continue;
2134
Chandler Carruth7a715da2015-03-05 03:19:05 +00002135 BlockFrequency EdgeFreq =
2136 BlockFreq * MBPI->getEdgeProbability(&MBB, Succ);
Chandler Carruthae4e8002011-11-02 07:17:12 +00002137 ++NumBranches;
2138 BranchTakenFreq += EdgeFreq.getFrequency();
2139 }
2140 }
2141
2142 return false;
2143}