blob: 2f43d2c06d517cba1cfc1db6dececc64fe5cd0c3 [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.
267 typedef SmallPtrSet<MachineBasicBlock *, 16> BlockFilterSet;
268
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
Kyle Butt0846e562016-10-11 20:36:43 +0000327 /// Decrease the UnscheduledPredecessors count for all blocks in chain, and
328 /// if the count goes to 0, add them to the appropriate work list.
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000329 void markChainSuccessors(BlockChain &Chain, MachineBasicBlock *LoopHeaderBB,
Craig Topperc0196b12014-04-14 00:51:57 +0000330 const BlockFilterSet *BlockFilter = nullptr);
Kyle Butt0846e562016-10-11 20:36:43 +0000331
332 /// Decrease the UnscheduledPredecessors count for a single block, and
333 /// if the count goes to 0, add them to the appropriate work list.
334 void markBlockSuccessors(
335 BlockChain &Chain, MachineBasicBlock *BB, MachineBasicBlock *LoopHeaderBB,
336 const BlockFilterSet *BlockFilter = nullptr);
337
338
Xinliang David Li594ffa32016-06-11 18:35:40 +0000339 BranchProbability
340 collectViableSuccessors(MachineBasicBlock *BB, BlockChain &Chain,
341 const BlockFilterSet *BlockFilter,
342 SmallVector<MachineBasicBlock *, 4> &Successors);
Xinliang David Li071d0f12016-06-12 16:54:03 +0000343 bool shouldPredBlockBeOutlined(MachineBasicBlock *BB, MachineBasicBlock *Succ,
344 BlockChain &Chain,
345 const BlockFilterSet *BlockFilter,
346 BranchProbability SuccProb,
347 BranchProbability HotProb);
Kyle Butt0846e562016-10-11 20:36:43 +0000348 bool repeatedlyTailDuplicateBlock(
349 MachineBasicBlock *BB, MachineBasicBlock *&LPred,
350 MachineBasicBlock *LoopHeaderBB,
351 BlockChain &Chain, BlockFilterSet *BlockFilter,
352 MachineFunction::iterator &PrevUnplacedBlockIt);
353 bool maybeTailDuplicateBlock(MachineBasicBlock *BB, MachineBasicBlock *LPred,
354 const BlockChain &Chain,
355 BlockFilterSet *BlockFilter,
356 MachineFunction::iterator &PrevUnplacedBlockIt,
357 bool &DuplicatedToPred);
Xinliang David Licbf12142016-06-13 20:24:19 +0000358 bool
359 hasBetterLayoutPredecessor(MachineBasicBlock *BB, MachineBasicBlock *Succ,
360 BlockChain &SuccChain, BranchProbability SuccProb,
361 BranchProbability RealSuccProb, BlockChain &Chain,
362 const BlockFilterSet *BlockFilter);
Jakub Staszak90616162011-12-21 23:02:08 +0000363 MachineBasicBlock *selectBestSuccessor(MachineBasicBlock *BB,
364 BlockChain &Chain,
365 const BlockFilterSet *BlockFilter);
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000366 MachineBasicBlock *
367 selectBestCandidateBlock(BlockChain &Chain,
Amaury Sechet9ee4ddd2016-04-07 06:34:47 +0000368 SmallVectorImpl<MachineBasicBlock *> &WorkList);
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000369 MachineBasicBlock *
Xinliang David Li52530a72016-06-13 22:23:44 +0000370 getFirstUnplacedBlock(const BlockChain &PlacedChain,
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000371 MachineFunction::iterator &PrevUnplacedBlockIt,
372 const BlockFilterSet *BlockFilter);
Amaury Secheteae09c22016-03-14 21:24:11 +0000373
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +0000374 /// \brief Add a basic block to the work list if it is appropriate.
Amaury Secheteae09c22016-03-14 21:24:11 +0000375 ///
376 /// If the optional parameter BlockFilter is provided, only MBB
377 /// present in the set will be added to the worklist. If nullptr
378 /// is provided, no filtering occurs.
379 void fillWorkLists(MachineBasicBlock *MBB,
380 SmallPtrSetImpl<BlockChain *> &UpdatedPreds,
Amaury Secheteae09c22016-03-14 21:24:11 +0000381 const BlockFilterSet *BlockFilter);
Chandler Carruth8d150782011-11-13 11:20:44 +0000382 void buildChain(MachineBasicBlock *BB, BlockChain &Chain,
Kyle Butt0846e562016-10-11 20:36:43 +0000383 BlockFilterSet *BlockFilter = nullptr);
Chandler Carruth8c0b41d2012-04-16 13:33:36 +0000384 MachineBasicBlock *findBestLoopTop(MachineLoop &L,
385 const BlockFilterSet &LoopBlockSet);
Xinliang David Li52530a72016-06-13 22:23:44 +0000386 MachineBasicBlock *findBestLoopExit(MachineLoop &L,
Chandler Carruthccc7e422012-04-16 01:12:56 +0000387 const BlockFilterSet &LoopBlockSet);
Xinliang David Li52530a72016-06-13 22:23:44 +0000388 BlockFilterSet collectLoopBlockSet(MachineLoop &L);
389 void buildLoopChains(MachineLoop &L);
Chandler Carruth8c74c7b2012-04-16 09:31:23 +0000390 void rotateLoop(BlockChain &LoopChain, MachineBasicBlock *ExitingBB,
391 const BlockFilterSet &LoopBlockSet);
Cong Hou7745dbc2015-10-19 23:16:40 +0000392 void rotateLoopWithProfile(BlockChain &LoopChain, MachineLoop &L,
393 const BlockFilterSet &LoopBlockSet);
Xinliang David Li52530a72016-06-13 22:23:44 +0000394 void collectMustExecuteBBs();
395 void buildCFGChains();
396 void optimizeBranches();
397 void alignBlocks();
Chandler Carruth10281422011-10-21 06:46:38 +0000398
399public:
400 static char ID; // Pass identification, replacement for typeid
401 MachineBlockPlacement() : MachineFunctionPass(ID) {
402 initializeMachineBlockPlacementPass(*PassRegistry::getPassRegistry());
403 }
404
Craig Topper4584cd52014-03-07 09:26:03 +0000405 bool runOnMachineFunction(MachineFunction &F) override;
Chandler Carruth10281422011-10-21 06:46:38 +0000406
Craig Topper4584cd52014-03-07 09:26:03 +0000407 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruth10281422011-10-21 06:46:38 +0000408 AU.addRequired<MachineBranchProbabilityInfo>();
409 AU.addRequired<MachineBlockFrequencyInfo>();
Daniel Jasper471e8562015-03-04 11:05:34 +0000410 AU.addRequired<MachineDominatorTree>();
Chandler Carruth8b9737c2011-10-21 08:57:37 +0000411 AU.addRequired<MachineLoopInfo>();
Haicheng Wu5b458cc2016-06-09 15:24:29 +0000412 AU.addRequired<TargetPassConfig>();
Chandler Carruth10281422011-10-21 06:46:38 +0000413 MachineFunctionPass::getAnalysisUsage(AU);
414 }
Chandler Carruth10281422011-10-21 06:46:38 +0000415};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000416}
Chandler Carruth10281422011-10-21 06:46:38 +0000417
418char MachineBlockPlacement::ID = 0;
Andrew Trick1fa5bcb2012-02-08 21:23:13 +0000419char &llvm::MachineBlockPlacementID = MachineBlockPlacement::ID;
Chandler Carruthd0dced52015-03-05 02:28:25 +0000420INITIALIZE_PASS_BEGIN(MachineBlockPlacement, "block-placement",
Chandler Carruth10281422011-10-21 06:46:38 +0000421 "Branch Probability Basic Block Placement", false, false)
422INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
423INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
Daniel Jasper471e8562015-03-04 11:05:34 +0000424INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
Chandler Carruth8b9737c2011-10-21 08:57:37 +0000425INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
Chandler Carruthd0dced52015-03-05 02:28:25 +0000426INITIALIZE_PASS_END(MachineBlockPlacement, "block-placement",
Chandler Carruth10281422011-10-21 06:46:38 +0000427 "Branch Probability Basic Block Placement", false, false)
428
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000429#ifndef NDEBUG
430/// \brief Helper to print the name of a MBB.
431///
432/// Only used by debug logging.
Jakub Staszak90616162011-12-21 23:02:08 +0000433static std::string getBlockName(MachineBasicBlock *BB) {
Alp Tokere69170a2014-06-26 22:52:05 +0000434 std::string Result;
435 raw_string_ostream OS(Result);
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000436 OS << "BB#" << BB->getNumber();
Philip Reamesb9688f42016-03-02 21:45:13 +0000437 OS << " ('" << BB->getName() << "')";
Alp Tokere69170a2014-06-26 22:52:05 +0000438 OS.flush();
439 return Result;
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000440}
441#endif
442
Chandler Carrutheb4ec3a2011-11-13 11:34:55 +0000443/// \brief Mark a chain's successors as having one fewer preds.
444///
445/// When a chain is being merged into the "placed" chain, this routine will
446/// quickly walk the successors of each block in the chain and mark them as
447/// having one fewer active predecessor. It also adds any successors of this
Kyle Butt0846e562016-10-11 20:36:43 +0000448/// chain which reach the zero-predecessor state to the appropriate worklist.
Chandler Carruth8d150782011-11-13 11:20:44 +0000449void MachineBlockPlacement::markChainSuccessors(
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000450 BlockChain &Chain, MachineBasicBlock *LoopHeaderBB,
Jakub Staszak90616162011-12-21 23:02:08 +0000451 const BlockFilterSet *BlockFilter) {
Chandler Carruth8d150782011-11-13 11:20:44 +0000452 // Walk all the blocks in this chain, marking their successors as having
453 // a predecessor placed.
Chandler Carruth7a715da2015-03-05 03:19:05 +0000454 for (MachineBasicBlock *MBB : Chain) {
Kyle Butt0846e562016-10-11 20:36:43 +0000455 markBlockSuccessors(Chain, MBB, LoopHeaderBB, BlockFilter);
456 }
457}
Chandler Carruth10281422011-10-21 06:46:38 +0000458
Kyle Butt0846e562016-10-11 20:36:43 +0000459/// \brief Mark a single block's successors as having one fewer preds.
460///
461/// Under normal circumstances, this is only called by markChainSuccessors,
462/// but if a block that was to be placed is completely tail-duplicated away,
463/// and was duplicated into the chain end, we need to redo markBlockSuccessors
464/// for just that block.
465void MachineBlockPlacement::markBlockSuccessors(
466 BlockChain &Chain, MachineBasicBlock *MBB, MachineBasicBlock *LoopHeaderBB,
467 const BlockFilterSet *BlockFilter) {
468 // Add any successors for which this is the only un-placed in-loop
469 // predecessor to the worklist as a viable candidate for CFG-neutral
470 // placement. No subsequent placement of this block will violate the CFG
471 // shape, so we get to use heuristics to choose a favorable placement.
472 for (MachineBasicBlock *Succ : MBB->successors()) {
473 if (BlockFilter && !BlockFilter->count(Succ))
474 continue;
475 BlockChain &SuccChain = *BlockToChain[Succ];
476 // Disregard edges within a fixed chain, or edges to the loop header.
477 if (&Chain == &SuccChain || Succ == LoopHeaderBB)
478 continue;
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000479
Kyle Butt0846e562016-10-11 20:36:43 +0000480 // This is a cross-chain edge that is within the loop, so decrement the
481 // loop predecessor count of the destination chain.
482 if (SuccChain.UnscheduledPredecessors == 0 ||
483 --SuccChain.UnscheduledPredecessors > 0)
484 continue;
485
486 auto *NewBB = *SuccChain.begin();
487 if (NewBB->isEHPad())
488 EHPadWorkList.push_back(NewBB);
489 else
490 BlockWorkList.push_back(NewBB);
Chandler Carruth10281422011-10-21 06:46:38 +0000491 }
Chandler Carruth8d150782011-11-13 11:20:44 +0000492}
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000493
Xinliang David Li594ffa32016-06-11 18:35:40 +0000494/// This helper function collects the set of successors of block
495/// \p BB that are allowed to be its layout successors, and return
496/// the total branch probability of edges from \p BB to those
497/// blocks.
498BranchProbability MachineBlockPlacement::collectViableSuccessors(
499 MachineBasicBlock *BB, BlockChain &Chain, const BlockFilterSet *BlockFilter,
500 SmallVector<MachineBasicBlock *, 4> &Successors) {
Cong Houd97c1002015-12-01 05:29:22 +0000501 // Adjust edge probabilities by excluding edges pointing to blocks that is
502 // either not in BlockFilter or is already in the current chain. Consider the
503 // following CFG:
Cong Hou41cf1a52015-11-18 00:52:52 +0000504 //
505 // --->A
506 // | / \
507 // | B C
508 // | \ / \
509 // ----D E
510 //
511 // Assume A->C is very hot (>90%), and C->D has a 50% probability, then after
512 // A->C is chosen as a fall-through, D won't be selected as a successor of C
513 // due to CFG constraint (the probability of C->D is not greater than
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +0000514 // HotProb to break top-order). If we exclude E that is not in BlockFilter
Xinliang David Li594ffa32016-06-11 18:35:40 +0000515 // when calculating the probability of C->D, D will be selected and we
516 // will get A C D B as the layout of this loop.
Cong Houd97c1002015-12-01 05:29:22 +0000517 auto AdjustedSumProb = BranchProbability::getOne();
Cong Hou41cf1a52015-11-18 00:52:52 +0000518 for (MachineBasicBlock *Succ : BB->successors()) {
519 bool SkipSucc = false;
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000520 if (Succ->isEHPad() || (BlockFilter && !BlockFilter->count(Succ))) {
Cong Hou41cf1a52015-11-18 00:52:52 +0000521 SkipSucc = true;
522 } else {
523 BlockChain *SuccChain = BlockToChain[Succ];
524 if (SuccChain == &Chain) {
Cong Hou41cf1a52015-11-18 00:52:52 +0000525 SkipSucc = true;
526 } else if (Succ != *SuccChain->begin()) {
527 DEBUG(dbgs() << " " << getBlockName(Succ) << " -> Mid chain!\n");
528 continue;
529 }
530 }
531 if (SkipSucc)
Cong Houd97c1002015-12-01 05:29:22 +0000532 AdjustedSumProb -= MBPI->getEdgeProbability(BB, Succ);
Cong Hou41cf1a52015-11-18 00:52:52 +0000533 else
534 Successors.push_back(Succ);
535 }
536
Xinliang David Li594ffa32016-06-11 18:35:40 +0000537 return AdjustedSumProb;
538}
539
540/// The helper function returns the branch probability that is adjusted
541/// or normalized over the new total \p AdjustedSumProb.
Xinliang David Li594ffa32016-06-11 18:35:40 +0000542static BranchProbability
543getAdjustedProbability(BranchProbability OrigProb,
544 BranchProbability AdjustedSumProb) {
545 BranchProbability SuccProb;
546 uint32_t SuccProbN = OrigProb.getNumerator();
547 uint32_t SuccProbD = AdjustedSumProb.getNumerator();
548 if (SuccProbN >= SuccProbD)
549 SuccProb = BranchProbability::getOne();
550 else
551 SuccProb = BranchProbability(SuccProbN, SuccProbD);
552
553 return SuccProb;
554}
555
Xinliang David Li071d0f12016-06-12 16:54:03 +0000556/// When the option OutlineOptionalBranches is on, this method
557/// checks if the fallthrough candidate block \p Succ (of block
558/// \p BB) also has other unscheduled predecessor blocks which
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +0000559/// are also successors of \p BB (forming triangular shape CFG).
Xinliang David Li071d0f12016-06-12 16:54:03 +0000560/// If none of such predecessors are small, it returns true.
561/// The caller can choose to select \p Succ as the layout successors
562/// so that \p Succ's predecessors (optional branches) can be
563/// outlined.
564/// FIXME: fold this with more general layout cost analysis.
565bool MachineBlockPlacement::shouldPredBlockBeOutlined(
566 MachineBasicBlock *BB, MachineBasicBlock *Succ, BlockChain &Chain,
567 const BlockFilterSet *BlockFilter, BranchProbability SuccProb,
568 BranchProbability HotProb) {
569 if (!OutlineOptionalBranches)
570 return false;
571 // If we outline optional branches, look whether Succ is unavoidable, i.e.
572 // dominates all terminators of the MachineFunction. If it does, other
573 // successors must be optional. Don't do this for cold branches.
574 if (SuccProb > HotProb.getCompl() && UnavoidableBlocks.count(Succ) > 0) {
575 for (MachineBasicBlock *Pred : Succ->predecessors()) {
576 // Check whether there is an unplaced optional branch.
577 if (Pred == Succ || (BlockFilter && !BlockFilter->count(Pred)) ||
578 BlockToChain[Pred] == &Chain)
579 continue;
580 // Check whether the optional branch has exactly one BB.
581 if (Pred->pred_size() > 1 || *Pred->pred_begin() != BB)
582 continue;
583 // Check whether the optional branch is small.
584 if (Pred->size() < OutlineOptionalThreshold)
585 return false;
586 }
587 return true;
588 } else
589 return false;
590}
591
Dehao Chen9f2bdfb2016-06-14 22:27:17 +0000592// When profile is not present, return the StaticLikelyProb.
593// When profile is available, we need to handle the triangle-shape CFG.
594static BranchProbability getLayoutSuccessorProbThreshold(
595 MachineBasicBlock *BB) {
596 if (!BB->getParent()->getFunction()->getEntryCount())
597 return BranchProbability(StaticLikelyProb, 100);
598 if (BB->succ_size() == 2) {
599 const MachineBasicBlock *Succ1 = *BB->succ_begin();
600 const MachineBasicBlock *Succ2 = *(BB->succ_begin() + 1);
Xinliang David Lie34ed832016-06-15 03:03:30 +0000601 if (Succ1->isSuccessor(Succ2) || Succ2->isSuccessor(Succ1)) {
602 /* See case 1 below for the cost analysis. For BB->Succ to
603 * be taken with smaller cost, the following needs to hold:
604 * Prob(BB->Succ) > 2* Prob(BB->Pred)
605 * So the threshold T
606 * T = 2 * (1-Prob(BB->Pred). Since T + Prob(BB->Pred) == 1,
607 * We have T + T/2 = 1, i.e. T = 2/3. Also adding user specified
608 * branch bias, we have
609 * T = (2/3)*(ProfileLikelyProb/50)
610 * = (2*ProfileLikelyProb)/150)
611 */
612 return BranchProbability(2 * ProfileLikelyProb, 150);
613 }
Dehao Chen9f2bdfb2016-06-14 22:27:17 +0000614 }
615 return BranchProbability(ProfileLikelyProb, 100);
Xinliang David Licbf12142016-06-13 20:24:19 +0000616}
617
618/// Checks to see if the layout candidate block \p Succ has a better layout
619/// predecessor than \c BB. If yes, returns true.
620bool MachineBlockPlacement::hasBetterLayoutPredecessor(
621 MachineBasicBlock *BB, MachineBasicBlock *Succ, BlockChain &SuccChain,
622 BranchProbability SuccProb, BranchProbability RealSuccProb,
623 BlockChain &Chain, const BlockFilterSet *BlockFilter) {
624
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +0000625 // There isn't a better layout when there are no unscheduled predecessors.
Xinliang David Licbf12142016-06-13 20:24:19 +0000626 if (SuccChain.UnscheduledPredecessors == 0)
627 return false;
628
629 // There are two basic scenarios here:
630 // -------------------------------------
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +0000631 // Case 1: triangular shape CFG (if-then):
Xinliang David Licbf12142016-06-13 20:24:19 +0000632 // BB
633 // | \
634 // | \
635 // | Pred
636 // | /
637 // Succ
638 // In this case, we are evaluating whether to select edge -> Succ, e.g.
639 // set Succ as the layout successor of BB. Picking Succ as BB's
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +0000640 // successor breaks the CFG constraints (FIXME: define these constraints).
641 // With this layout, Pred BB
Xinliang David Licbf12142016-06-13 20:24:19 +0000642 // is forced to be outlined, so the overall cost will be cost of the
643 // branch taken from BB to Pred, plus the cost of back taken branch
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +0000644 // from Pred to Succ, as well as the additional cost associated
Xinliang David Licbf12142016-06-13 20:24:19 +0000645 // with the needed unconditional jump instruction from Pred To Succ.
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +0000646
Xinliang David Licbf12142016-06-13 20:24:19 +0000647 // The cost of the topological order layout is the taken branch cost
648 // from BB to Succ, so to make BB->Succ a viable candidate, the following
649 // must hold:
650 // 2 * freq(BB->Pred) * taken_branch_cost + unconditional_jump_cost
651 // < freq(BB->Succ) * taken_branch_cost.
652 // Ignoring unconditional jump cost, we get
653 // freq(BB->Succ) > 2 * freq(BB->Pred), i.e.,
654 // prob(BB->Succ) > 2 * prob(BB->Pred)
655 //
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +0000656 // When real profile data is available, we can precisely compute the
657 // probability threshold that is needed for edge BB->Succ to be considered.
658 // Without profile data, the heuristic requires the branch bias to be
Xinliang David Licbf12142016-06-13 20:24:19 +0000659 // a lot larger to make sure the signal is very strong (e.g. 80% default).
660 // -----------------------------------------------------------------
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +0000661 // Case 2: diamond like CFG (if-then-else):
Xinliang David Licbf12142016-06-13 20:24:19 +0000662 // S
663 // / \
664 // | \
665 // BB Pred
666 // \ /
667 // Succ
668 // ..
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +0000669 //
670 // The current block is BB and edge BB->Succ is now being evaluated.
671 // Note that edge S->BB was previously already selected because
672 // prob(S->BB) > prob(S->Pred).
673 // At this point, 2 blocks can be placed after BB: Pred or Succ. If we
674 // choose Pred, we will have a topological ordering as shown on the left
675 // in the picture below. If we choose Succ, we have the solution as shown
676 // on the right:
677 //
678 // topo-order:
679 //
680 // S----- ---S
681 // | | | |
682 // ---BB | | BB
683 // | | | |
684 // | pred-- | Succ--
685 // | | | |
686 // ---succ ---pred--
687 //
688 // cost = freq(S->Pred) + freq(BB->Succ) cost = 2 * freq (S->Pred)
689 // = freq(S->Pred) + freq(S->BB)
690 //
691 // If we have profile data (i.e, branch probabilities can be trusted), the
692 // cost (number of taken branches) with layout S->BB->Succ->Pred is 2 *
693 // freq(S->Pred) while the cost of topo order is freq(S->Pred) + freq(S->BB).
694 // We know Prob(S->BB) > Prob(S->Pred), so freq(S->BB) > freq(S->Pred), which
695 // means the cost of topological order is greater.
Xinliang David Licbf12142016-06-13 20:24:19 +0000696 // When profile data is not available, however, we need to be more
697 // conservative. If the branch prediction is wrong, breaking the topo-order
698 // will actually yield a layout with large cost. For this reason, we need
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +0000699 // strong biased branch at block S with Prob(S->BB) in order to select
700 // BB->Succ. This is equivalent to looking the CFG backward with backward
Xinliang David Licbf12142016-06-13 20:24:19 +0000701 // edge: Prob(Succ->BB) needs to >= HotProb in order to be selected (without
702 // profile data).
Kyle Butt02d8d052016-07-29 18:09:28 +0000703 // --------------------------------------------------------------------------
704 // Case 3: forked diamond
705 // S
706 // / \
707 // / \
708 // BB Pred
709 // | \ / |
710 // | \ / |
711 // | X |
712 // | / \ |
713 // | / \ |
714 // S1 S2
715 //
716 // The current block is BB and edge BB->S1 is now being evaluated.
717 // As above S->BB was already selected because
718 // prob(S->BB) > prob(S->Pred). Assume that prob(BB->S1) >= prob(BB->S2).
719 //
720 // topo-order:
721 //
722 // S-------| ---S
723 // | | | |
724 // ---BB | | BB
725 // | | | |
726 // | Pred----| | S1----
727 // | | | |
728 // --(S1 or S2) ---Pred--
729 //
730 // topo-cost = freq(S->Pred) + freq(BB->S1) + freq(BB->S2)
731 // + min(freq(Pred->S1), freq(Pred->S2))
732 // Non-topo-order cost:
733 // In the worst case, S2 will not get laid out after Pred.
734 // non-topo-cost = 2 * freq(S->Pred) + freq(BB->S2).
735 // To be conservative, we can assume that min(freq(Pred->S1), freq(Pred->S2))
736 // is 0. Then the non topo layout is better when
737 // freq(S->Pred) < freq(BB->S1).
738 // This is exactly what is checked below.
739 // Note there are other shapes that apply (Pred may not be a single block,
740 // but they all fit this general pattern.)
Dehao Chen9f2bdfb2016-06-14 22:27:17 +0000741 BranchProbability HotProb = getLayoutSuccessorProbThreshold(BB);
Xinliang David Licbf12142016-06-13 20:24:19 +0000742
Xinliang David Licbf12142016-06-13 20:24:19 +0000743 // Make sure that a hot successor doesn't have a globally more
744 // important predecessor.
745 BlockFrequency CandidateEdgeFreq = MBFI->getBlockFreq(BB) * RealSuccProb;
746 bool BadCFGConflict = false;
747
748 for (MachineBasicBlock *Pred : Succ->predecessors()) {
749 if (Pred == Succ || BlockToChain[Pred] == &SuccChain ||
750 (BlockFilter && !BlockFilter->count(Pred)) ||
751 BlockToChain[Pred] == &Chain)
752 continue;
Kyle Butt02d8d052016-07-29 18:09:28 +0000753 // Do backward checking.
754 // For all cases above, we need a backward checking to filter out edges that
755 // are not 'strongly' biased. With profile data available, the check is
756 // mostly redundant for case 2 (when threshold prob is set at 50%) unless S
757 // has more than two successors.
Xinliang David Licbf12142016-06-13 20:24:19 +0000758 // BB Pred
759 // \ /
760 // Succ
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +0000761 // We select edge BB->Succ if
Xinliang David Licbf12142016-06-13 20:24:19 +0000762 // freq(BB->Succ) > freq(Succ) * HotProb
763 // i.e. freq(BB->Succ) > freq(BB->Succ) * HotProb + freq(Pred->Succ) *
764 // HotProb
765 // i.e. freq((BB->Succ) * (1 - HotProb) > freq(Pred->Succ) * HotProb
Kyle Butt02d8d052016-07-29 18:09:28 +0000766 // Case 1 is covered too, because the first equation reduces to:
767 // prob(BB->Succ) > HotProb. (freq(Succ) = freq(BB) for a triangle)
Xinliang David Licbf12142016-06-13 20:24:19 +0000768 BlockFrequency PredEdgeFreq =
769 MBFI->getBlockFreq(Pred) * MBPI->getEdgeProbability(Pred, Succ);
770 if (PredEdgeFreq * HotProb >= CandidateEdgeFreq * HotProb.getCompl()) {
771 BadCFGConflict = true;
772 break;
773 }
774 }
775
776 if (BadCFGConflict) {
Sjoerd Meijer5e11a182016-07-27 08:49:23 +0000777 DEBUG(dbgs() << " Not a candidate: " << getBlockName(Succ) << " -> " << SuccProb
Xinliang David Licbf12142016-06-13 20:24:19 +0000778 << " (prob) (non-cold CFG conflict)\n");
779 return true;
780 }
781
782 return false;
783}
784
Xinliang David Li594ffa32016-06-11 18:35:40 +0000785/// \brief Select the best successor for a block.
786///
787/// This looks across all successors of a particular block and attempts to
788/// select the "best" one to be the layout successor. It only considers direct
789/// successors which also pass the block filter. It will attempt to avoid
790/// breaking CFG structure, but cave and break such structures in the case of
791/// very hot successor edges.
792///
793/// \returns The best successor block found, or null if none are viable.
794MachineBasicBlock *
795MachineBlockPlacement::selectBestSuccessor(MachineBasicBlock *BB,
796 BlockChain &Chain,
797 const BlockFilterSet *BlockFilter) {
798 const BranchProbability HotProb(StaticLikelyProb, 100);
799
800 MachineBasicBlock *BestSucc = nullptr;
801 auto BestProb = BranchProbability::getZero();
802
803 SmallVector<MachineBasicBlock *, 4> Successors;
804 auto AdjustedSumProb =
805 collectViableSuccessors(BB, Chain, BlockFilter, Successors);
806
Sjoerd Meijer5e11a182016-07-27 08:49:23 +0000807 DEBUG(dbgs() << "Selecting best successor for: " << getBlockName(BB) << "\n");
Cong Hou41cf1a52015-11-18 00:52:52 +0000808 for (MachineBasicBlock *Succ : Successors) {
Xinliang David Li594ffa32016-06-11 18:35:40 +0000809 auto RealSuccProb = MBPI->getEdgeProbability(BB, Succ);
810 BranchProbability SuccProb =
811 getAdjustedProbability(RealSuccProb, AdjustedSumProb);
Chandler Carruthb3361722011-11-13 11:34:53 +0000812
Xinliang David Li071d0f12016-06-12 16:54:03 +0000813 // This heuristic is off by default.
814 if (shouldPredBlockBeOutlined(BB, Succ, Chain, BlockFilter, SuccProb,
815 HotProb))
816 return Succ;
Daniel Jasper471e8562015-03-04 11:05:34 +0000817
Cong Hou41cf1a52015-11-18 00:52:52 +0000818 BlockChain &SuccChain = *BlockToChain[Succ];
Xinliang David Licbf12142016-06-13 20:24:19 +0000819 // Skip the edge \c BB->Succ if block \c Succ has a better layout
820 // predecessor that yields lower global cost.
821 if (hasBetterLayoutPredecessor(BB, Succ, SuccChain, SuccProb, RealSuccProb,
822 Chain, BlockFilter))
823 continue;
Chandler Carruth18dfac32011-11-20 11:22:06 +0000824
Xinliang David Licbf12142016-06-13 20:24:19 +0000825 DEBUG(
Sjoerd Meijer5e11a182016-07-27 08:49:23 +0000826 dbgs() << " Candidate: " << getBlockName(Succ) << ", probability: "
827 << SuccProb
Xinliang David Licbf12142016-06-13 20:24:19 +0000828 << (SuccChain.UnscheduledPredecessors != 0 ? " (CFG break)" : "")
829 << "\n");
Sjoerd Meijer5e11a182016-07-27 08:49:23 +0000830
831 if (BestSucc && BestProb >= SuccProb) {
832 DEBUG(dbgs() << " Not the best candidate, continuing\n");
Chandler Carruthb3361722011-11-13 11:34:53 +0000833 continue;
Sjoerd Meijer5e11a182016-07-27 08:49:23 +0000834 }
835
836 DEBUG(dbgs() << " Setting it as best candidate\n");
Daniel Jaspered9eb722015-02-18 08:19:16 +0000837 BestSucc = Succ;
Cong Houd97c1002015-12-01 05:29:22 +0000838 BestProb = SuccProb;
Chandler Carruthb3361722011-11-13 11:34:53 +0000839 }
Sjoerd Meijer5e11a182016-07-27 08:49:23 +0000840 if (BestSucc)
841 DEBUG(dbgs() << " Selected: " << getBlockName(BestSucc) << "\n");
842
Chandler Carruthb3361722011-11-13 11:34:53 +0000843 return BestSucc;
844}
845
Chandler Carruthf9213fe2011-11-13 11:42:26 +0000846/// \brief Select the best block from a worklist.
847///
848/// This looks through the provided worklist as a list of candidate basic
849/// blocks and select the most profitable one to place. The definition of
850/// profitable only really makes sense in the context of a loop. This returns
851/// the most frequently visited block in the worklist, which in the case of
852/// a loop, is the one most desirable to be physically close to the rest of the
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +0000853/// loop body in order to improve i-cache behavior.
Chandler Carruthf9213fe2011-11-13 11:42:26 +0000854///
855/// \returns The best block found, or null if none are viable.
856MachineBasicBlock *MachineBlockPlacement::selectBestCandidateBlock(
Amaury Sechet9ee4ddd2016-04-07 06:34:47 +0000857 BlockChain &Chain, SmallVectorImpl<MachineBasicBlock *> &WorkList) {
Chandler Carruth0af6a0b2011-11-14 09:46:33 +0000858 // Once we need to walk the worklist looking for a candidate, cleanup the
859 // worklist of already placed entries.
860 // FIXME: If this shows up on profiles, it could be folded (at the cost of
861 // some code complexity) into the loop below.
David Majnemerc7004902016-08-12 04:32:37 +0000862 WorkList.erase(remove_if(WorkList,
863 [&](MachineBasicBlock *BB) {
864 return BlockToChain.lookup(BB) == &Chain;
865 }),
Chandler Carruth0af6a0b2011-11-14 09:46:33 +0000866 WorkList.end());
867
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000868 if (WorkList.empty())
869 return nullptr;
870
871 bool IsEHPad = WorkList[0]->isEHPad();
872
Craig Topperc0196b12014-04-14 00:51:57 +0000873 MachineBasicBlock *BestBlock = nullptr;
Chandler Carruthf9213fe2011-11-13 11:42:26 +0000874 BlockFrequency BestFreq;
Chandler Carruth7a715da2015-03-05 03:19:05 +0000875 for (MachineBasicBlock *MBB : WorkList) {
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000876 assert(MBB->isEHPad() == IsEHPad);
877
Chandler Carruth7a715da2015-03-05 03:19:05 +0000878 BlockChain &SuccChain = *BlockToChain[MBB];
Philip Reames02e11322016-03-02 22:40:51 +0000879 if (&SuccChain == &Chain)
Chandler Carruthf9213fe2011-11-13 11:42:26 +0000880 continue;
Junmo Park4ba6cf62016-03-11 05:07:07 +0000881
Philip Reamesae27b232016-03-03 00:58:43 +0000882 assert(SuccChain.UnscheduledPredecessors == 0 && "Found CFG-violating block");
Chandler Carruthf9213fe2011-11-13 11:42:26 +0000883
Chandler Carruth7a715da2015-03-05 03:19:05 +0000884 BlockFrequency CandidateFreq = MBFI->getBlockFreq(MBB);
885 DEBUG(dbgs() << " " << getBlockName(MBB) << " -> ";
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000886 MBFI->printBlockFreq(dbgs(), CandidateFreq) << " (freq)\n");
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000887
888 // For ehpad, we layout the least probable first as to avoid jumping back
889 // from least probable landingpads to more probable ones.
890 //
891 // FIXME: Using probability is probably (!) not the best way to achieve
892 // this. We should probably have a more principled approach to layout
893 // cleanup code.
894 //
895 // The goal is to get:
896 //
897 // +--------------------------+
898 // | V
899 // InnerLp -> InnerCleanup OuterLp -> OuterCleanup -> Resume
900 //
901 // Rather than:
902 //
903 // +-------------------------------------+
904 // V |
905 // OuterLp -> OuterCleanup -> Resume InnerLp -> InnerCleanup
906 if (BestBlock && (IsEHPad ^ (BestFreq >= CandidateFreq)))
Chandler Carruthf9213fe2011-11-13 11:42:26 +0000907 continue;
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000908
Chandler Carruth7a715da2015-03-05 03:19:05 +0000909 BestBlock = MBB;
Chandler Carruthf9213fe2011-11-13 11:42:26 +0000910 BestFreq = CandidateFreq;
911 }
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000912
Chandler Carruthf9213fe2011-11-13 11:42:26 +0000913 return BestBlock;
914}
915
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000916/// \brief Retrieve the first unplaced basic block.
917///
918/// This routine is called when we are unable to use the CFG to walk through
919/// all of the basic blocks and form a chain due to unnatural loops in the CFG.
Chandler Carruth9b548a7f2011-11-15 06:26:43 +0000920/// We walk through the function's blocks in order, starting from the
921/// LastUnplacedBlockIt. We update this iterator on each call to avoid
922/// re-scanning the entire sequence on repeated calls to this routine.
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000923MachineBasicBlock *MachineBlockPlacement::getFirstUnplacedBlock(
Xinliang David Li52530a72016-06-13 22:23:44 +0000924 const BlockChain &PlacedChain,
Chandler Carruth9b548a7f2011-11-15 06:26:43 +0000925 MachineFunction::iterator &PrevUnplacedBlockIt,
Jakub Staszak90616162011-12-21 23:02:08 +0000926 const BlockFilterSet *BlockFilter) {
Xinliang David Li52530a72016-06-13 22:23:44 +0000927 for (MachineFunction::iterator I = PrevUnplacedBlockIt, E = F->end(); I != E;
Chandler Carruth9b548a7f2011-11-15 06:26:43 +0000928 ++I) {
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +0000929 if (BlockFilter && !BlockFilter->count(&*I))
Chandler Carruth9b548a7f2011-11-15 06:26:43 +0000930 continue;
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +0000931 if (BlockToChain[&*I] != &PlacedChain) {
Chandler Carruth9b548a7f2011-11-15 06:26:43 +0000932 PrevUnplacedBlockIt = I;
Chandler Carruth4a87aa02011-11-23 03:03:21 +0000933 // Now select the head of the chain to which the unplaced block belongs
934 // as the block to place. This will force the entire chain to be placed,
935 // and satisfies the requirements of merging chains.
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +0000936 return *BlockToChain[&*I]->begin();
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000937 }
938 }
Craig Topperc0196b12014-04-14 00:51:57 +0000939 return nullptr;
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000940}
941
Amaury Secheteae09c22016-03-14 21:24:11 +0000942void MachineBlockPlacement::fillWorkLists(
943 MachineBasicBlock *MBB,
944 SmallPtrSetImpl<BlockChain *> &UpdatedPreds,
Amaury Secheteae09c22016-03-14 21:24:11 +0000945 const BlockFilterSet *BlockFilter = nullptr) {
946 BlockChain &Chain = *BlockToChain[MBB];
947 if (!UpdatedPreds.insert(&Chain).second)
948 return;
949
950 assert(Chain.UnscheduledPredecessors == 0);
951 for (MachineBasicBlock *ChainBB : Chain) {
952 assert(BlockToChain[ChainBB] == &Chain);
953 for (MachineBasicBlock *Pred : ChainBB->predecessors()) {
954 if (BlockFilter && !BlockFilter->count(Pred))
955 continue;
956 if (BlockToChain[Pred] == &Chain)
957 continue;
958 ++Chain.UnscheduledPredecessors;
959 }
960 }
961
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000962 if (Chain.UnscheduledPredecessors != 0)
963 return;
964
965 MBB = *Chain.begin();
966 if (MBB->isEHPad())
967 EHPadWorkList.push_back(MBB);
968 else
969 BlockWorkList.push_back(MBB);
Amaury Secheteae09c22016-03-14 21:24:11 +0000970}
971
Chandler Carruth8d150782011-11-13 11:20:44 +0000972void MachineBlockPlacement::buildChain(
Daniel Jasper471e8562015-03-04 11:05:34 +0000973 MachineBasicBlock *BB, BlockChain &Chain,
Kyle Butt0846e562016-10-11 20:36:43 +0000974 BlockFilterSet *BlockFilter) {
Kyle Buttb3875ea2016-06-17 22:40:19 +0000975 assert(BB && "BB must not be null.\n");
976 assert(BlockToChain[BB] == &Chain && "BlockToChainMap mis-match.\n");
Xinliang David Li52530a72016-06-13 22:23:44 +0000977 MachineFunction::iterator PrevUnplacedBlockIt = F->begin();
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000978
Chandler Carruth8d150782011-11-13 11:20:44 +0000979 MachineBasicBlock *LoopHeaderBB = BB;
Xinliang David Li93926ac2016-07-01 05:46:48 +0000980 markChainSuccessors(Chain, LoopHeaderBB, BlockFilter);
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000981 BB = *std::prev(Chain.end());
Chandler Carruth8d150782011-11-13 11:20:44 +0000982 for (;;) {
Kyle Butt82c22902016-06-28 22:50:54 +0000983 assert(BB && "null block found at end of chain in loop.");
984 assert(BlockToChain[BB] == &Chain && "BlockToChainMap mis-match in loop.");
985 assert(*std::prev(Chain.end()) == BB && "BB Not found at end of chain.");
986
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000987
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +0000988 // Look for the best viable successor if there is one to place immediately
989 // after this block.
Duncan Sands291d47e2012-09-14 09:00:11 +0000990 MachineBasicBlock *BestSucc = selectBestSuccessor(BB, Chain, BlockFilter);
Chandler Carruth8d150782011-11-13 11:20:44 +0000991
992 // If an immediate successor isn't available, look for the best viable
993 // block among those we've identified as not violating the loop's CFG at
994 // this point. This won't be a fallthrough, but it will increase locality.
Chandler Carruthf9213fe2011-11-13 11:42:26 +0000995 if (!BestSucc)
Amaury Sechet9ee4ddd2016-04-07 06:34:47 +0000996 BestSucc = selectBestCandidateBlock(Chain, BlockWorkList);
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000997 if (!BestSucc)
998 BestSucc = selectBestCandidateBlock(Chain, EHPadWorkList);
Chandler Carruth8d150782011-11-13 11:20:44 +0000999
Chandler Carruth8d150782011-11-13 11:20:44 +00001000 if (!BestSucc) {
Xinliang David Li52530a72016-06-13 22:23:44 +00001001 BestSucc = getFirstUnplacedBlock(Chain, PrevUnplacedBlockIt, BlockFilter);
Chandler Carruth1071cfa2011-11-14 00:00:35 +00001002 if (!BestSucc)
1003 break;
1004
1005 DEBUG(dbgs() << "Unnatural loop CFG detected, forcibly merging the "
1006 "layout successor until the CFG reduces\n");
Chandler Carruth8d150782011-11-13 11:20:44 +00001007 }
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00001008
Kyle Butt0846e562016-10-11 20:36:43 +00001009 // Placement may have changed tail duplication opportunities.
1010 // Check for that now.
1011 if (TailDupPlacement && BestSucc) {
1012 // If the chosen successor was duplicated into all its predecessors,
1013 // don't bother laying it out, just go round the loop again with BB as
1014 // the chain end.
1015 if (repeatedlyTailDuplicateBlock(BestSucc, BB, LoopHeaderBB, Chain,
1016 BlockFilter, PrevUnplacedBlockIt))
1017 continue;
1018 }
1019
Chandler Carruth8d150782011-11-13 11:20:44 +00001020 // Place this block, updating the datastructures to reflect its placement.
Jakub Staszak90616162011-12-21 23:02:08 +00001021 BlockChain &SuccChain = *BlockToChain[BestSucc];
Philip Reamesae27b232016-03-03 00:58:43 +00001022 // Zero out UnscheduledPredecessors for the successor we're about to merge in case
Chandler Carruth1071cfa2011-11-14 00:00:35 +00001023 // we selected a successor that didn't fit naturally into the CFG.
Philip Reamesae27b232016-03-03 00:58:43 +00001024 SuccChain.UnscheduledPredecessors = 0;
Philip Reamesb9688f42016-03-02 21:45:13 +00001025 DEBUG(dbgs() << "Merging from " << getBlockName(BB) << " to "
1026 << getBlockName(BestSucc) << "\n");
Xinliang David Li93926ac2016-07-01 05:46:48 +00001027 markChainSuccessors(SuccChain, LoopHeaderBB, BlockFilter);
Chandler Carruth8d150782011-11-13 11:20:44 +00001028 Chain.merge(BestSucc, &SuccChain);
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001029 BB = *std::prev(Chain.end());
Jakub Staszak190c7122011-12-07 19:46:10 +00001030 }
Chandler Carruth1071cfa2011-11-14 00:00:35 +00001031
1032 DEBUG(dbgs() << "Finished forming chain for header block "
Philip Reamesb9688f42016-03-02 21:45:13 +00001033 << getBlockName(*Chain.begin()) << "\n");
Chandler Carruth10281422011-10-21 06:46:38 +00001034}
1035
Chandler Carruth03adbd42011-11-27 13:34:33 +00001036/// \brief Find the best loop top block for layout.
Chandler Carruth9ffb97e2011-11-27 00:38:03 +00001037///
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001038/// Look for a block which is strictly better than the loop header for laying
1039/// out at the top of the loop. This looks for one and only one pattern:
1040/// a latch block with no conditional exit. This block will cause a conditional
1041/// jump around it or will be the bottom of the loop if we lay it out in place,
1042/// but if it it doesn't end up at the bottom of the loop for any reason,
1043/// rotation alone won't fix it. Because such a block will always result in an
1044/// unconditional jump (for the backedge) rotating it in front of the loop
1045/// header is always profitable.
1046MachineBasicBlock *
1047MachineBlockPlacement::findBestLoopTop(MachineLoop &L,
1048 const BlockFilterSet &LoopBlockSet) {
Sjoerd Meijer15c81b02016-08-16 19:50:33 +00001049 // Placing the latch block before the header may introduce an extra branch
1050 // that skips this block the first time the loop is executed, which we want
1051 // to avoid when optimising for size.
1052 // FIXME: in theory there is a case that does not introduce a new branch,
1053 // i.e. when the layout predecessor does not fallthrough to the loop header.
1054 // In practice this never happens though: there always seems to be a preheader
1055 // that can fallthrough and that is also placed before the header.
1056 if (F->getFunction()->optForSize())
1057 return L.getHeader();
1058
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001059 // Check that the header hasn't been fused with a preheader block due to
1060 // crazy branches. If it has, we need to start with the header at the top to
1061 // prevent pulling the preheader into the loop body.
1062 BlockChain &HeaderChain = *BlockToChain[L.getHeader()];
1063 if (!LoopBlockSet.count(*HeaderChain.begin()))
1064 return L.getHeader();
1065
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001066 DEBUG(dbgs() << "Finding best loop top for: " << getBlockName(L.getHeader())
1067 << "\n");
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001068
1069 BlockFrequency BestPredFreq;
Craig Topperc0196b12014-04-14 00:51:57 +00001070 MachineBasicBlock *BestPred = nullptr;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001071 for (MachineBasicBlock *Pred : L.getHeader()->predecessors()) {
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001072 if (!LoopBlockSet.count(Pred))
1073 continue;
Sjoerd Meijer5e11a182016-07-27 08:49:23 +00001074 DEBUG(dbgs() << " header pred: " << getBlockName(Pred) << ", has "
Michael Gottesmanb78dec82013-12-14 00:25:45 +00001075 << Pred->succ_size() << " successors, ";
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001076 MBFI->printBlockFreq(dbgs(), Pred) << " freq\n");
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001077 if (Pred->succ_size() > 1)
1078 continue;
1079
1080 BlockFrequency PredFreq = MBFI->getBlockFreq(Pred);
1081 if (!BestPred || PredFreq > BestPredFreq ||
1082 (!(PredFreq < BestPredFreq) &&
1083 Pred->isLayoutSuccessor(L.getHeader()))) {
1084 BestPred = Pred;
1085 BestPredFreq = PredFreq;
1086 }
1087 }
1088
1089 // If no direct predecessor is fine, just use the loop header.
Philip Reamesb9688f42016-03-02 21:45:13 +00001090 if (!BestPred) {
1091 DEBUG(dbgs() << " final top unchanged\n");
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001092 return L.getHeader();
Philip Reamesb9688f42016-03-02 21:45:13 +00001093 }
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001094
1095 // Walk backwards through any straight line of predecessors.
1096 while (BestPred->pred_size() == 1 &&
1097 (*BestPred->pred_begin())->succ_size() == 1 &&
1098 *BestPred->pred_begin() != L.getHeader())
1099 BestPred = *BestPred->pred_begin();
1100
1101 DEBUG(dbgs() << " final top: " << getBlockName(BestPred) << "\n");
1102 return BestPred;
1103}
1104
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001105/// \brief Find the best loop exiting block for layout.
1106///
Chandler Carruth03adbd42011-11-27 13:34:33 +00001107/// This routine implements the logic to analyze the loop looking for the best
1108/// block to layout at the top of the loop. Typically this is done to maximize
1109/// fallthrough opportunities.
1110MachineBasicBlock *
Xinliang David Li52530a72016-06-13 22:23:44 +00001111MachineBlockPlacement::findBestLoopExit(MachineLoop &L,
Chandler Carruthccc7e422012-04-16 01:12:56 +00001112 const BlockFilterSet &LoopBlockSet) {
Chandler Carruth68062612012-04-10 13:35:57 +00001113 // We don't want to layout the loop linearly in all cases. If the loop header
1114 // is just a normal basic block in the loop, we want to look for what block
1115 // within the loop is the best one to layout at the top. However, if the loop
1116 // header has be pre-merged into a chain due to predecessors not having
1117 // analyzable branches, *and* the predecessor it is merged with is *not* part
1118 // of the loop, rotating the header into the middle of the loop will create
1119 // a non-contiguous range of blocks which is Very Bad. So start with the
1120 // header and only rotate if safe.
1121 BlockChain &HeaderChain = *BlockToChain[L.getHeader()];
1122 if (!LoopBlockSet.count(*HeaderChain.begin()))
Craig Topperc0196b12014-04-14 00:51:57 +00001123 return nullptr;
Chandler Carruth68062612012-04-10 13:35:57 +00001124
Chandler Carruth03adbd42011-11-27 13:34:33 +00001125 BlockFrequency BestExitEdgeFreq;
Chandler Carruthccc7e422012-04-16 01:12:56 +00001126 unsigned BestExitLoopDepth = 0;
Craig Topperc0196b12014-04-14 00:51:57 +00001127 MachineBasicBlock *ExitingBB = nullptr;
Chandler Carruth4f567202011-11-27 20:18:00 +00001128 // If there are exits to outer loops, loop rotation can severely limit
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00001129 // fallthrough opportunities unless it selects such an exit. Keep a set of
Chandler Carruth4f567202011-11-27 20:18:00 +00001130 // blocks where rotating to exit with that block will reach an outer loop.
1131 SmallPtrSet<MachineBasicBlock *, 4> BlocksExitingToOuterLoop;
1132
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001133 DEBUG(dbgs() << "Finding best loop exit for: " << getBlockName(L.getHeader())
1134 << "\n");
Chandler Carruth7a715da2015-03-05 03:19:05 +00001135 for (MachineBasicBlock *MBB : L.getBlocks()) {
1136 BlockChain &Chain = *BlockToChain[MBB];
Chandler Carruth03adbd42011-11-27 13:34:33 +00001137 // Ensure that this block is at the end of a chain; otherwise it could be
Chandler Carruth9a512a42015-04-15 13:19:54 +00001138 // mid-way through an inner loop or a successor of an unanalyzable branch.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001139 if (MBB != *std::prev(Chain.end()))
Chandler Carruth9ffb97e2011-11-27 00:38:03 +00001140 continue;
Chandler Carruth9ffb97e2011-11-27 00:38:03 +00001141
Chandler Carruth03adbd42011-11-27 13:34:33 +00001142 // Now walk the successors. We need to establish whether this has a viable
1143 // exiting successor and whether it has a viable non-exiting successor.
1144 // We store the old exiting state and restore it if a viable looping
1145 // successor isn't found.
1146 MachineBasicBlock *OldExitingBB = ExitingBB;
1147 BlockFrequency OldBestExitEdgeFreq = BestExitEdgeFreq;
Chandler Carruthccc7e422012-04-16 01:12:56 +00001148 bool HasLoopingSucc = false;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001149 for (MachineBasicBlock *Succ : MBB->successors()) {
Reid Kleckner0e288232015-08-27 23:27:47 +00001150 if (Succ->isEHPad())
Chandler Carruth03adbd42011-11-27 13:34:33 +00001151 continue;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001152 if (Succ == MBB)
Chandler Carruth03adbd42011-11-27 13:34:33 +00001153 continue;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001154 BlockChain &SuccChain = *BlockToChain[Succ];
Chandler Carruth03adbd42011-11-27 13:34:33 +00001155 // Don't split chains, either this chain or the successor's chain.
Chandler Carruthccc7e422012-04-16 01:12:56 +00001156 if (&Chain == &SuccChain) {
Chandler Carruth7a715da2015-03-05 03:19:05 +00001157 DEBUG(dbgs() << " exiting: " << getBlockName(MBB) << " -> "
1158 << getBlockName(Succ) << " (chain conflict)\n");
Chandler Carruth03adbd42011-11-27 13:34:33 +00001159 continue;
1160 }
1161
Cong Houd97c1002015-12-01 05:29:22 +00001162 auto SuccProb = MBPI->getEdgeProbability(MBB, Succ);
Chandler Carruth7a715da2015-03-05 03:19:05 +00001163 if (LoopBlockSet.count(Succ)) {
1164 DEBUG(dbgs() << " looping: " << getBlockName(MBB) << " -> "
Cong Houd97c1002015-12-01 05:29:22 +00001165 << getBlockName(Succ) << " (" << SuccProb << ")\n");
Chandler Carruthccc7e422012-04-16 01:12:56 +00001166 HasLoopingSucc = true;
Chandler Carruth03adbd42011-11-27 13:34:33 +00001167 continue;
1168 }
1169
Chandler Carruthccc7e422012-04-16 01:12:56 +00001170 unsigned SuccLoopDepth = 0;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001171 if (MachineLoop *ExitLoop = MLI->getLoopFor(Succ)) {
Chandler Carruthccc7e422012-04-16 01:12:56 +00001172 SuccLoopDepth = ExitLoop->getLoopDepth();
1173 if (ExitLoop->contains(&L))
Chandler Carruth7a715da2015-03-05 03:19:05 +00001174 BlocksExitingToOuterLoop.insert(MBB);
Chandler Carruthccc7e422012-04-16 01:12:56 +00001175 }
1176
Chandler Carruth7a715da2015-03-05 03:19:05 +00001177 BlockFrequency ExitEdgeFreq = MBFI->getBlockFreq(MBB) * SuccProb;
1178 DEBUG(dbgs() << " exiting: " << getBlockName(MBB) << " -> "
1179 << getBlockName(Succ) << " [L:" << SuccLoopDepth << "] (";
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001180 MBFI->printBlockFreq(dbgs(), ExitEdgeFreq) << ")\n");
Benjamin Kramerc8160d62013-11-20 19:08:44 +00001181 // Note that we bias this toward an existing layout successor to retain
1182 // incoming order in the absence of better information. The exit must have
1183 // a frequency higher than the current exit before we consider breaking
1184 // the layout.
1185 BranchProbability Bias(100 - ExitBlockBias, 100);
Chandler Carruth26d30172015-04-15 13:39:42 +00001186 if (!ExitingBB || SuccLoopDepth > BestExitLoopDepth ||
Chandler Carruthccc7e422012-04-16 01:12:56 +00001187 ExitEdgeFreq > BestExitEdgeFreq ||
Chandler Carruth7a715da2015-03-05 03:19:05 +00001188 (MBB->isLayoutSuccessor(Succ) &&
Benjamin Kramerc8160d62013-11-20 19:08:44 +00001189 !(ExitEdgeFreq < BestExitEdgeFreq * Bias))) {
Chandler Carruth03adbd42011-11-27 13:34:33 +00001190 BestExitEdgeFreq = ExitEdgeFreq;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001191 ExitingBB = MBB;
Chandler Carrutha0545802011-11-27 09:22:53 +00001192 }
Chandler Carruth9ffb97e2011-11-27 00:38:03 +00001193 }
Chandler Carruth03adbd42011-11-27 13:34:33 +00001194
Chandler Carruthccc7e422012-04-16 01:12:56 +00001195 if (!HasLoopingSucc) {
Chandler Carruthcfb2b9d2015-04-15 13:26:41 +00001196 // Restore the old exiting state, no viable looping successor was found.
Chandler Carruth03adbd42011-11-27 13:34:33 +00001197 ExitingBB = OldExitingBB;
1198 BestExitEdgeFreq = OldBestExitEdgeFreq;
Chandler Carruth03adbd42011-11-27 13:34:33 +00001199 }
Chandler Carruth9ffb97e2011-11-27 00:38:03 +00001200 }
Chandler Carruthccc7e422012-04-16 01:12:56 +00001201 // Without a candidate exiting block or with only a single block in the
Chandler Carruth03adbd42011-11-27 13:34:33 +00001202 // loop, just use the loop header to layout the loop.
Sjoerd Meijer5e11a182016-07-27 08:49:23 +00001203 if (!ExitingBB) {
1204 DEBUG(dbgs() << " No other candidate exit blocks, using loop header\n");
Craig Topperc0196b12014-04-14 00:51:57 +00001205 return nullptr;
Sjoerd Meijer5e11a182016-07-27 08:49:23 +00001206 }
1207 if (L.getNumBlocks() == 1) {
1208 DEBUG(dbgs() << " Loop has 1 block, using loop header as exit\n");
1209 return nullptr;
1210 }
Chandler Carruth9ffb97e2011-11-27 00:38:03 +00001211
Chandler Carruth4f567202011-11-27 20:18:00 +00001212 // Also, if we have exit blocks which lead to outer loops but didn't select
1213 // one of them as the exiting block we are rotating toward, disable loop
1214 // rotation altogether.
1215 if (!BlocksExitingToOuterLoop.empty() &&
1216 !BlocksExitingToOuterLoop.count(ExitingBB))
Craig Topperc0196b12014-04-14 00:51:57 +00001217 return nullptr;
Chandler Carruth4f567202011-11-27 20:18:00 +00001218
Chandler Carruth03adbd42011-11-27 13:34:33 +00001219 DEBUG(dbgs() << " Best exiting block: " << getBlockName(ExitingBB) << "\n");
Chandler Carruthccc7e422012-04-16 01:12:56 +00001220 return ExitingBB;
Chandler Carruth9ffb97e2011-11-27 00:38:03 +00001221}
1222
Chandler Carruth8c74c7b2012-04-16 09:31:23 +00001223/// \brief Attempt to rotate an exiting block to the bottom of the loop.
1224///
1225/// Once we have built a chain, try to rotate it to line up the hot exit block
1226/// with fallthrough out of the loop if doing so doesn't introduce unnecessary
1227/// branches. For example, if the loop has fallthrough into its header and out
1228/// of its bottom already, don't rotate it.
1229void MachineBlockPlacement::rotateLoop(BlockChain &LoopChain,
1230 MachineBasicBlock *ExitingBB,
1231 const BlockFilterSet &LoopBlockSet) {
1232 if (!ExitingBB)
1233 return;
1234
1235 MachineBasicBlock *Top = *LoopChain.begin();
1236 bool ViableTopFallthrough = false;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001237 for (MachineBasicBlock *Pred : Top->predecessors()) {
1238 BlockChain *PredChain = BlockToChain[Pred];
1239 if (!LoopBlockSet.count(Pred) &&
1240 (!PredChain || Pred == *std::prev(PredChain->end()))) {
Chandler Carruth8c74c7b2012-04-16 09:31:23 +00001241 ViableTopFallthrough = true;
1242 break;
1243 }
1244 }
1245
1246 // If the header has viable fallthrough, check whether the current loop
1247 // bottom is a viable exiting block. If so, bail out as rotating will
1248 // introduce an unnecessary branch.
1249 if (ViableTopFallthrough) {
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001250 MachineBasicBlock *Bottom = *std::prev(LoopChain.end());
Chandler Carruth7a715da2015-03-05 03:19:05 +00001251 for (MachineBasicBlock *Succ : Bottom->successors()) {
1252 BlockChain *SuccChain = BlockToChain[Succ];
1253 if (!LoopBlockSet.count(Succ) &&
1254 (!SuccChain || Succ == *SuccChain->begin()))
Chandler Carruth8c74c7b2012-04-16 09:31:23 +00001255 return;
1256 }
1257 }
1258
David Majnemer0d955d02016-08-11 22:21:41 +00001259 BlockChain::iterator ExitIt = find(LoopChain, ExitingBB);
Chandler Carruth8c74c7b2012-04-16 09:31:23 +00001260 if (ExitIt == LoopChain.end())
1261 return;
1262
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001263 std::rotate(LoopChain.begin(), std::next(ExitIt), LoopChain.end());
Chandler Carruth8c74c7b2012-04-16 09:31:23 +00001264}
1265
Cong Hou7745dbc2015-10-19 23:16:40 +00001266/// \brief Attempt to rotate a loop based on profile data to reduce branch cost.
1267///
1268/// With profile data, we can determine the cost in terms of missed fall through
1269/// opportunities when rotating a loop chain and select the best rotation.
1270/// Basically, there are three kinds of cost to consider for each rotation:
1271/// 1. The possibly missed fall through edge (if it exists) from BB out of
1272/// the loop to the loop header.
1273/// 2. The possibly missed fall through edges (if they exist) from the loop
1274/// exits to BB out of the loop.
1275/// 3. The missed fall through edge (if it exists) from the last BB to the
1276/// first BB in the loop chain.
1277/// Therefore, the cost for a given rotation is the sum of costs listed above.
1278/// We select the best rotation with the smallest cost.
1279void MachineBlockPlacement::rotateLoopWithProfile(
1280 BlockChain &LoopChain, MachineLoop &L, const BlockFilterSet &LoopBlockSet) {
1281 auto HeaderBB = L.getHeader();
David Majnemer0d955d02016-08-11 22:21:41 +00001282 auto HeaderIter = find(LoopChain, HeaderBB);
Cong Hou7745dbc2015-10-19 23:16:40 +00001283 auto RotationPos = LoopChain.end();
1284
1285 BlockFrequency SmallestRotationCost = BlockFrequency::getMaxFrequency();
1286
1287 // A utility lambda that scales up a block frequency by dividing it by a
1288 // branch probability which is the reciprocal of the scale.
1289 auto ScaleBlockFrequency = [](BlockFrequency Freq,
1290 unsigned Scale) -> BlockFrequency {
1291 if (Scale == 0)
1292 return 0;
1293 // Use operator / between BlockFrequency and BranchProbability to implement
1294 // saturating multiplication.
1295 return Freq / BranchProbability(1, Scale);
1296 };
1297
1298 // Compute the cost of the missed fall-through edge to the loop header if the
1299 // chain head is not the loop header. As we only consider natural loops with
1300 // single header, this computation can be done only once.
1301 BlockFrequency HeaderFallThroughCost(0);
1302 for (auto *Pred : HeaderBB->predecessors()) {
1303 BlockChain *PredChain = BlockToChain[Pred];
1304 if (!LoopBlockSet.count(Pred) &&
1305 (!PredChain || Pred == *std::prev(PredChain->end()))) {
1306 auto EdgeFreq =
1307 MBFI->getBlockFreq(Pred) * MBPI->getEdgeProbability(Pred, HeaderBB);
1308 auto FallThruCost = ScaleBlockFrequency(EdgeFreq, MisfetchCost);
1309 // If the predecessor has only an unconditional jump to the header, we
1310 // need to consider the cost of this jump.
1311 if (Pred->succ_size() == 1)
1312 FallThruCost += ScaleBlockFrequency(EdgeFreq, JumpInstCost);
1313 HeaderFallThroughCost = std::max(HeaderFallThroughCost, FallThruCost);
1314 }
1315 }
1316
1317 // Here we collect all exit blocks in the loop, and for each exit we find out
1318 // its hottest exit edge. For each loop rotation, we define the loop exit cost
1319 // as the sum of frequencies of exit edges we collect here, excluding the exit
1320 // edge from the tail of the loop chain.
1321 SmallVector<std::pair<MachineBasicBlock *, BlockFrequency>, 4> ExitsWithFreq;
1322 for (auto BB : LoopChain) {
Cong Houd97c1002015-12-01 05:29:22 +00001323 auto LargestExitEdgeProb = BranchProbability::getZero();
Cong Hou7745dbc2015-10-19 23:16:40 +00001324 for (auto *Succ : BB->successors()) {
1325 BlockChain *SuccChain = BlockToChain[Succ];
1326 if (!LoopBlockSet.count(Succ) &&
1327 (!SuccChain || Succ == *SuccChain->begin())) {
Cong Houd97c1002015-12-01 05:29:22 +00001328 auto SuccProb = MBPI->getEdgeProbability(BB, Succ);
1329 LargestExitEdgeProb = std::max(LargestExitEdgeProb, SuccProb);
Cong Hou7745dbc2015-10-19 23:16:40 +00001330 }
1331 }
Cong Houd97c1002015-12-01 05:29:22 +00001332 if (LargestExitEdgeProb > BranchProbability::getZero()) {
1333 auto ExitFreq = MBFI->getBlockFreq(BB) * LargestExitEdgeProb;
Cong Hou7745dbc2015-10-19 23:16:40 +00001334 ExitsWithFreq.emplace_back(BB, ExitFreq);
1335 }
1336 }
1337
1338 // In this loop we iterate every block in the loop chain and calculate the
1339 // cost assuming the block is the head of the loop chain. When the loop ends,
1340 // we should have found the best candidate as the loop chain's head.
1341 for (auto Iter = LoopChain.begin(), TailIter = std::prev(LoopChain.end()),
1342 EndIter = LoopChain.end();
1343 Iter != EndIter; Iter++, TailIter++) {
1344 // TailIter is used to track the tail of the loop chain if the block we are
1345 // checking (pointed by Iter) is the head of the chain.
1346 if (TailIter == LoopChain.end())
1347 TailIter = LoopChain.begin();
1348
1349 auto TailBB = *TailIter;
1350
1351 // Calculate the cost by putting this BB to the top.
1352 BlockFrequency Cost = 0;
1353
1354 // If the current BB is the loop header, we need to take into account the
1355 // cost of the missed fall through edge from outside of the loop to the
1356 // header.
1357 if (Iter != HeaderIter)
1358 Cost += HeaderFallThroughCost;
1359
1360 // Collect the loop exit cost by summing up frequencies of all exit edges
1361 // except the one from the chain tail.
1362 for (auto &ExitWithFreq : ExitsWithFreq)
1363 if (TailBB != ExitWithFreq.first)
1364 Cost += ExitWithFreq.second;
1365
1366 // The cost of breaking the once fall-through edge from the tail to the top
1367 // of the loop chain. Here we need to consider three cases:
1368 // 1. If the tail node has only one successor, then we will get an
1369 // additional jmp instruction. So the cost here is (MisfetchCost +
1370 // JumpInstCost) * tail node frequency.
1371 // 2. If the tail node has two successors, then we may still get an
1372 // additional jmp instruction if the layout successor after the loop
1373 // chain is not its CFG successor. Note that the more frequently executed
1374 // jmp instruction will be put ahead of the other one. Assume the
1375 // frequency of those two branches are x and y, where x is the frequency
1376 // of the edge to the chain head, then the cost will be
1377 // (x * MisfetechCost + min(x, y) * JumpInstCost) * tail node frequency.
1378 // 3. If the tail node has more than two successors (this rarely happens),
1379 // we won't consider any additional cost.
1380 if (TailBB->isSuccessor(*Iter)) {
1381 auto TailBBFreq = MBFI->getBlockFreq(TailBB);
1382 if (TailBB->succ_size() == 1)
1383 Cost += ScaleBlockFrequency(TailBBFreq.getFrequency(),
1384 MisfetchCost + JumpInstCost);
1385 else if (TailBB->succ_size() == 2) {
1386 auto TailToHeadProb = MBPI->getEdgeProbability(TailBB, *Iter);
1387 auto TailToHeadFreq = TailBBFreq * TailToHeadProb;
1388 auto ColderEdgeFreq = TailToHeadProb > BranchProbability(1, 2)
1389 ? TailBBFreq * TailToHeadProb.getCompl()
1390 : TailToHeadFreq;
1391 Cost += ScaleBlockFrequency(TailToHeadFreq, MisfetchCost) +
1392 ScaleBlockFrequency(ColderEdgeFreq, JumpInstCost);
1393 }
1394 }
1395
Philip Reamesb9688f42016-03-02 21:45:13 +00001396 DEBUG(dbgs() << "The cost of loop rotation by making " << getBlockName(*Iter)
Cong Hou7745dbc2015-10-19 23:16:40 +00001397 << " to the top: " << Cost.getFrequency() << "\n");
1398
1399 if (Cost < SmallestRotationCost) {
1400 SmallestRotationCost = Cost;
1401 RotationPos = Iter;
1402 }
1403 }
1404
1405 if (RotationPos != LoopChain.end()) {
Philip Reamesb9688f42016-03-02 21:45:13 +00001406 DEBUG(dbgs() << "Rotate loop by making " << getBlockName(*RotationPos)
Cong Hou7745dbc2015-10-19 23:16:40 +00001407 << " to the top\n");
1408 std::rotate(LoopChain.begin(), RotationPos, LoopChain.end());
1409 }
1410}
1411
Cong Houb90b9e02015-11-02 21:24:00 +00001412/// \brief Collect blocks in the given loop that are to be placed.
1413///
1414/// When profile data is available, exclude cold blocks from the returned set;
1415/// otherwise, collect all blocks in the loop.
1416MachineBlockPlacement::BlockFilterSet
Xinliang David Li52530a72016-06-13 22:23:44 +00001417MachineBlockPlacement::collectLoopBlockSet(MachineLoop &L) {
Cong Houb90b9e02015-11-02 21:24:00 +00001418 BlockFilterSet LoopBlockSet;
1419
1420 // Filter cold blocks off from LoopBlockSet when profile data is available.
1421 // Collect the sum of frequencies of incoming edges to the loop header from
1422 // outside. If we treat the loop as a super block, this is the frequency of
1423 // the loop. Then for each block in the loop, we calculate the ratio between
1424 // its frequency and the frequency of the loop block. When it is too small,
1425 // don't add it to the loop chain. If there are outer loops, then this block
1426 // will be merged into the first outer loop chain for which this block is not
1427 // cold anymore. This needs precise profile data and we only do this when
1428 // profile data is available.
Xinliang David Li52530a72016-06-13 22:23:44 +00001429 if (F->getFunction()->getEntryCount()) {
Cong Houb90b9e02015-11-02 21:24:00 +00001430 BlockFrequency LoopFreq(0);
1431 for (auto LoopPred : L.getHeader()->predecessors())
1432 if (!L.contains(LoopPred))
1433 LoopFreq += MBFI->getBlockFreq(LoopPred) *
1434 MBPI->getEdgeProbability(LoopPred, L.getHeader());
1435
1436 for (MachineBasicBlock *LoopBB : L.getBlocks()) {
1437 auto Freq = MBFI->getBlockFreq(LoopBB).getFrequency();
1438 if (Freq == 0 || LoopFreq.getFrequency() / Freq > LoopToColdBlockRatio)
1439 continue;
1440 LoopBlockSet.insert(LoopBB);
1441 }
1442 } else
1443 LoopBlockSet.insert(L.block_begin(), L.block_end());
1444
1445 return LoopBlockSet;
1446}
1447
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00001448/// \brief Forms basic block chains from the natural loop structures.
Chandler Carruth10281422011-10-21 06:46:38 +00001449///
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00001450/// These chains are designed to preserve the existing *structure* of the code
1451/// as much as possible. We can then stitch the chains together in a way which
1452/// both preserves the topological structure and minimizes taken conditional
1453/// branches.
Xinliang David Li52530a72016-06-13 22:23:44 +00001454void MachineBlockPlacement::buildLoopChains(MachineLoop &L) {
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00001455 // First recurse through any nested loops, building chains for those inner
1456 // loops.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001457 for (MachineLoop *InnerLoop : L)
Xinliang David Li52530a72016-06-13 22:23:44 +00001458 buildLoopChains(*InnerLoop);
Chandler Carruth10281422011-10-21 06:46:38 +00001459
Xinliang David Li93926ac2016-07-01 05:46:48 +00001460 assert(BlockWorkList.empty());
1461 assert(EHPadWorkList.empty());
Xinliang David Li52530a72016-06-13 22:23:44 +00001462 BlockFilterSet LoopBlockSet = collectLoopBlockSet(L);
Chandler Carruth03adbd42011-11-27 13:34:33 +00001463
Cong Hou7745dbc2015-10-19 23:16:40 +00001464 // Check if we have profile data for this function. If yes, we will rotate
1465 // this loop by modeling costs more precisely which requires the profile data
1466 // for better layout.
1467 bool RotateLoopWithProfile =
Xinliang David Lif0ab6df2016-05-12 02:04:41 +00001468 ForcePreciseRotationCost ||
Xinliang David Li52530a72016-06-13 22:23:44 +00001469 (PreciseRotationCost && F->getFunction()->getEntryCount());
Cong Hou7745dbc2015-10-19 23:16:40 +00001470
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001471 // First check to see if there is an obviously preferable top block for the
1472 // loop. This will default to the header, but may end up as one of the
1473 // predecessors to the header if there is one which will result in strictly
1474 // fewer branches in the loop body.
Cong Hou7745dbc2015-10-19 23:16:40 +00001475 // When we use profile data to rotate the loop, this is unnecessary.
1476 MachineBasicBlock *LoopTop =
1477 RotateLoopWithProfile ? L.getHeader() : findBestLoopTop(L, LoopBlockSet);
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001478
1479 // If we selected just the header for the loop top, look for a potentially
1480 // profitable exit block in the event that rotating the loop can eliminate
1481 // branches by placing an exit edge at the bottom.
Cong Hou7745dbc2015-10-19 23:16:40 +00001482 if (!RotateLoopWithProfile && LoopTop == L.getHeader())
Kyle Buttab9cca72016-10-27 21:37:20 +00001483 PreferredLoopExit = findBestLoopExit(L, LoopBlockSet);
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001484
1485 BlockChain &LoopChain = *BlockToChain[LoopTop];
Chandler Carruth10281422011-10-21 06:46:38 +00001486
Chandler Carruth8d150782011-11-13 11:20:44 +00001487 // FIXME: This is a really lame way of walking the chains in the loop: we
1488 // walk the blocks, and use a set to prevent visiting a particular chain
1489 // twice.
Jakub Staszak90616162011-12-21 23:02:08 +00001490 SmallPtrSet<BlockChain *, 4> UpdatedPreds;
Philip Reamesae27b232016-03-03 00:58:43 +00001491 assert(LoopChain.UnscheduledPredecessors == 0);
Jakub Staszak190c7122011-12-07 19:46:10 +00001492 UpdatedPreds.insert(&LoopChain);
Cong Houb90b9e02015-11-02 21:24:00 +00001493
Amaury Secheteae09c22016-03-14 21:24:11 +00001494 for (MachineBasicBlock *LoopBB : LoopBlockSet)
Xinliang David Li93926ac2016-07-01 05:46:48 +00001495 fillWorkLists(LoopBB, UpdatedPreds, &LoopBlockSet);
Chandler Carruth8d150782011-11-13 11:20:44 +00001496
Xinliang David Li93926ac2016-07-01 05:46:48 +00001497 buildChain(LoopTop, LoopChain, &LoopBlockSet);
Cong Hou7745dbc2015-10-19 23:16:40 +00001498
1499 if (RotateLoopWithProfile)
1500 rotateLoopWithProfile(LoopChain, L, LoopBlockSet);
1501 else
Kyle Buttab9cca72016-10-27 21:37:20 +00001502 rotateLoop(LoopChain, PreferredLoopExit, LoopBlockSet);
Chandler Carruth8d150782011-11-13 11:20:44 +00001503
1504 DEBUG({
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001505 // Crash at the end so we get all of the debugging output first.
1506 bool BadLoop = false;
Philip Reamesae27b232016-03-03 00:58:43 +00001507 if (LoopChain.UnscheduledPredecessors) {
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001508 BadLoop = true;
Chandler Carruth8d150782011-11-13 11:20:44 +00001509 dbgs() << "Loop chain contains a block without its preds placed!\n"
1510 << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
1511 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n";
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001512 }
Chandler Carruth7a715da2015-03-05 03:19:05 +00001513 for (MachineBasicBlock *ChainBB : LoopChain) {
1514 dbgs() << " ... " << getBlockName(ChainBB) << "\n";
1515 if (!LoopBlockSet.erase(ChainBB)) {
Chandler Carruth0a31d142011-11-14 10:55:53 +00001516 // We don't mark the loop as bad here because there are real situations
1517 // where this can occur. For example, with an unanalyzable fallthrough
Chandler Carruth99fe42f2011-11-23 10:35:36 +00001518 // from a loop block to a non-loop block or vice versa.
Chandler Carruth8d150782011-11-13 11:20:44 +00001519 dbgs() << "Loop chain contains a block not contained by the loop!\n"
1520 << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
1521 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
Chandler Carruth7a715da2015-03-05 03:19:05 +00001522 << " Bad block: " << getBlockName(ChainBB) << "\n";
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001523 }
Chandler Carruthccc7e422012-04-16 01:12:56 +00001524 }
Chandler Carruth8d150782011-11-13 11:20:44 +00001525
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001526 if (!LoopBlockSet.empty()) {
1527 BadLoop = true;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001528 for (MachineBasicBlock *LoopBB : LoopBlockSet)
Chandler Carruth8d150782011-11-13 11:20:44 +00001529 dbgs() << "Loop contains blocks never placed into a chain!\n"
1530 << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
1531 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
Chandler Carruth7a715da2015-03-05 03:19:05 +00001532 << " Bad block: " << getBlockName(LoopBB) << "\n";
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001533 }
1534 assert(!BadLoop && "Detected problems with the placement of this loop.");
Chandler Carruth8d150782011-11-13 11:20:44 +00001535 });
Xinliang David Li93926ac2016-07-01 05:46:48 +00001536
1537 BlockWorkList.clear();
1538 EHPadWorkList.clear();
Chandler Carruth10281422011-10-21 06:46:38 +00001539}
1540
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00001541/// When OutlineOpitonalBranches is on, this method collects BBs that
Xinliang David Li071d0f12016-06-12 16:54:03 +00001542/// dominates all terminator blocks of the function \p F.
Xinliang David Li52530a72016-06-13 22:23:44 +00001543void MachineBlockPlacement::collectMustExecuteBBs() {
Xinliang David Li071d0f12016-06-12 16:54:03 +00001544 if (OutlineOptionalBranches) {
1545 // Find the nearest common dominator of all of F's terminators.
1546 MachineBasicBlock *Terminator = nullptr;
Xinliang David Li52530a72016-06-13 22:23:44 +00001547 for (MachineBasicBlock &MBB : *F) {
Xinliang David Li071d0f12016-06-12 16:54:03 +00001548 if (MBB.succ_size() == 0) {
1549 if (Terminator == nullptr)
1550 Terminator = &MBB;
1551 else
1552 Terminator = MDT->findNearestCommonDominator(Terminator, &MBB);
1553 }
1554 }
1555
1556 // MBBs dominating this common dominator are unavoidable.
1557 UnavoidableBlocks.clear();
Xinliang David Li52530a72016-06-13 22:23:44 +00001558 for (MachineBasicBlock &MBB : *F) {
Xinliang David Li071d0f12016-06-12 16:54:03 +00001559 if (MDT->dominates(&MBB, Terminator)) {
1560 UnavoidableBlocks.insert(&MBB);
1561 }
1562 }
1563 }
1564}
1565
Xinliang David Li52530a72016-06-13 22:23:44 +00001566void MachineBlockPlacement::buildCFGChains() {
Chandler Carruth8d150782011-11-13 11:20:44 +00001567 // Ensure that every BB in the function has an associated chain to simplify
1568 // the assumptions of the remaining algorithm.
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +00001569 SmallVector<MachineOperand, 4> Cond; // For AnalyzeBranch.
Xinliang David Li52530a72016-06-13 22:23:44 +00001570 for (MachineFunction::iterator FI = F->begin(), FE = F->end(); FI != FE;
1571 ++FI) {
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +00001572 MachineBasicBlock *BB = &*FI;
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001573 BlockChain *Chain =
1574 new (ChainAllocator.Allocate()) BlockChain(BlockToChain, BB);
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +00001575 // Also, merge any blocks which we cannot reason about and must preserve
1576 // the exact fallthrough behavior for.
1577 for (;;) {
1578 Cond.clear();
Craig Topperc0196b12014-04-14 00:51:57 +00001579 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
Jacques Pienaar71c30a12016-07-15 14:41:04 +00001580 if (!TII->analyzeBranch(*BB, TBB, FBB, Cond) || !FI->canFallThrough())
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +00001581 break;
1582
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +00001583 MachineFunction::iterator NextFI = std::next(FI);
1584 MachineBasicBlock *NextBB = &*NextFI;
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +00001585 // Ensure that the layout successor is a viable block, as we know that
1586 // fallthrough is a possibility.
1587 assert(NextFI != FE && "Can't fallthrough past the last block.");
1588 DEBUG(dbgs() << "Pre-merging due to unanalyzable fallthrough: "
1589 << getBlockName(BB) << " -> " << getBlockName(NextBB)
1590 << "\n");
Craig Topperc0196b12014-04-14 00:51:57 +00001591 Chain->merge(NextBB, nullptr);
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +00001592 FI = NextFI;
1593 BB = NextBB;
1594 }
1595 }
Chandler Carruth8d150782011-11-13 11:20:44 +00001596
Xinliang David Li071d0f12016-06-12 16:54:03 +00001597 // Turned on with OutlineOptionalBranches option
Xinliang David Li52530a72016-06-13 22:23:44 +00001598 collectMustExecuteBBs();
Daniel Jasper471e8562015-03-04 11:05:34 +00001599
Chandler Carruth8d150782011-11-13 11:20:44 +00001600 // Build any loop-based chains.
Sam McCall2a36eee2016-11-01 22:02:14 +00001601 PreferredLoopExit = nullptr;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001602 for (MachineLoop *L : *MLI)
Xinliang David Li52530a72016-06-13 22:23:44 +00001603 buildLoopChains(*L);
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00001604
Xinliang David Li93926ac2016-07-01 05:46:48 +00001605 assert(BlockWorkList.empty());
1606 assert(EHPadWorkList.empty());
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00001607
Chandler Carruth8d150782011-11-13 11:20:44 +00001608 SmallPtrSet<BlockChain *, 4> UpdatedPreds;
Xinliang David Li52530a72016-06-13 22:23:44 +00001609 for (MachineBasicBlock &MBB : *F)
Xinliang David Li93926ac2016-07-01 05:46:48 +00001610 fillWorkLists(&MBB, UpdatedPreds);
Chandler Carruth8d150782011-11-13 11:20:44 +00001611
Xinliang David Li52530a72016-06-13 22:23:44 +00001612 BlockChain &FunctionChain = *BlockToChain[&F->front()];
Xinliang David Li93926ac2016-07-01 05:46:48 +00001613 buildChain(&F->front(), FunctionChain);
Chandler Carruth8d150782011-11-13 11:20:44 +00001614
Matt Arsenault0f5f0152013-12-10 18:55:37 +00001615#ifndef NDEBUG
Matt Arsenault79d55f52013-12-05 20:02:18 +00001616 typedef SmallPtrSet<MachineBasicBlock *, 16> FunctionBlockSetType;
Matt Arsenault0f5f0152013-12-10 18:55:37 +00001617#endif
Chandler Carruth8d150782011-11-13 11:20:44 +00001618 DEBUG({
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001619 // Crash at the end so we get all of the debugging output first.
1620 bool BadFunc = false;
Chandler Carruth8d150782011-11-13 11:20:44 +00001621 FunctionBlockSetType FunctionBlockSet;
Xinliang David Li52530a72016-06-13 22:23:44 +00001622 for (MachineBasicBlock &MBB : *F)
Chandler Carruth7a715da2015-03-05 03:19:05 +00001623 FunctionBlockSet.insert(&MBB);
Chandler Carruth8d150782011-11-13 11:20:44 +00001624
Chandler Carruth7a715da2015-03-05 03:19:05 +00001625 for (MachineBasicBlock *ChainBB : FunctionChain)
1626 if (!FunctionBlockSet.erase(ChainBB)) {
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001627 BadFunc = true;
Chandler Carruth8d150782011-11-13 11:20:44 +00001628 dbgs() << "Function chain contains a block not in the function!\n"
Chandler Carruth7a715da2015-03-05 03:19:05 +00001629 << " Bad block: " << getBlockName(ChainBB) << "\n";
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001630 }
Chandler Carruth8d150782011-11-13 11:20:44 +00001631
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001632 if (!FunctionBlockSet.empty()) {
1633 BadFunc = true;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001634 for (MachineBasicBlock *RemainingBB : FunctionBlockSet)
Chandler Carruth8d150782011-11-13 11:20:44 +00001635 dbgs() << "Function contains blocks never placed into a chain!\n"
Chandler Carruth7a715da2015-03-05 03:19:05 +00001636 << " Bad block: " << getBlockName(RemainingBB) << "\n";
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001637 }
1638 assert(!BadFunc && "Detected problems with the block placement.");
Chandler Carruth8d150782011-11-13 11:20:44 +00001639 });
1640
1641 // Splice the blocks into place.
Xinliang David Li52530a72016-06-13 22:23:44 +00001642 MachineFunction::iterator InsertPos = F->begin();
Xinliang David Li449cdfd2016-06-24 22:54:21 +00001643 DEBUG(dbgs() << "[MBP] Function: "<< F->getName() << "\n");
Chandler Carruth7a715da2015-03-05 03:19:05 +00001644 for (MachineBasicBlock *ChainBB : FunctionChain) {
1645 DEBUG(dbgs() << (ChainBB == *FunctionChain.begin() ? "Placing chain "
1646 : " ... ")
1647 << getBlockName(ChainBB) << "\n");
1648 if (InsertPos != MachineFunction::iterator(ChainBB))
Xinliang David Li52530a72016-06-13 22:23:44 +00001649 F->splice(InsertPos, ChainBB);
Chandler Carruth8d150782011-11-13 11:20:44 +00001650 else
1651 ++InsertPos;
1652
1653 // Update the terminator of the previous block.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001654 if (ChainBB == *FunctionChain.begin())
Chandler Carruth8d150782011-11-13 11:20:44 +00001655 continue;
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +00001656 MachineBasicBlock *PrevBB = &*std::prev(MachineFunction::iterator(ChainBB));
Chandler Carruth8d150782011-11-13 11:20:44 +00001657
Chandler Carruth10281422011-10-21 06:46:38 +00001658 // FIXME: It would be awesome of updateTerminator would just return rather
1659 // than assert when the branch cannot be analyzed in order to remove this
1660 // boiler plate.
1661 Cond.clear();
Craig Topperc0196b12014-04-14 00:51:57 +00001662 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
Shuxin Yang8b8fd212013-06-04 01:00:57 +00001663
Haicheng Wu90a55652016-05-24 22:16:14 +00001664 // The "PrevBB" is not yet updated to reflect current code layout, so,
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00001665 // o. it may fall-through to a block without explicit "goto" instruction
Haicheng Wu90a55652016-05-24 22:16:14 +00001666 // before layout, and no longer fall-through it after layout; or
1667 // o. just opposite.
1668 //
Jacques Pienaar71c30a12016-07-15 14:41:04 +00001669 // analyzeBranch() may return erroneous value for FBB when these two
Haicheng Wu90a55652016-05-24 22:16:14 +00001670 // situations take place. For the first scenario FBB is mistakenly set NULL;
1671 // for the 2nd scenario, the FBB, which is expected to be NULL, is
1672 // mistakenly pointing to "*BI".
1673 // Thus, if the future change needs to use FBB before the layout is set, it
1674 // has to correct FBB first by using the code similar to the following:
1675 //
1676 // if (!Cond.empty() && (!FBB || FBB == ChainBB)) {
1677 // PrevBB->updateTerminator();
1678 // Cond.clear();
1679 // TBB = FBB = nullptr;
Jacques Pienaar71c30a12016-07-15 14:41:04 +00001680 // if (TII->analyzeBranch(*PrevBB, TBB, FBB, Cond)) {
Haicheng Wu90a55652016-05-24 22:16:14 +00001681 // // FIXME: This should never take place.
1682 // TBB = FBB = nullptr;
1683 // }
1684 // }
Jacques Pienaar71c30a12016-07-15 14:41:04 +00001685 if (!TII->analyzeBranch(*PrevBB, TBB, FBB, Cond))
Haicheng Wu90a55652016-05-24 22:16:14 +00001686 PrevBB->updateTerminator();
Chandler Carruth10281422011-10-21 06:46:38 +00001687 }
Chandler Carruth8d150782011-11-13 11:20:44 +00001688
1689 // Fixup the last block.
1690 Cond.clear();
Craig Topperc0196b12014-04-14 00:51:57 +00001691 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
Jacques Pienaar71c30a12016-07-15 14:41:04 +00001692 if (!TII->analyzeBranch(F->back(), TBB, FBB, Cond))
Xinliang David Li52530a72016-06-13 22:23:44 +00001693 F->back().updateTerminator();
Xinliang David Li93926ac2016-07-01 05:46:48 +00001694
1695 BlockWorkList.clear();
1696 EHPadWorkList.clear();
Haicheng Wu90a55652016-05-24 22:16:14 +00001697}
1698
Xinliang David Li52530a72016-06-13 22:23:44 +00001699void MachineBlockPlacement::optimizeBranches() {
1700 BlockChain &FunctionChain = *BlockToChain[&F->front()];
Haicheng Wu90a55652016-05-24 22:16:14 +00001701 SmallVector<MachineOperand, 4> Cond; // For AnalyzeBranch.
Quentin Colombet776e6de2016-05-02 22:58:59 +00001702
1703 // Now that all the basic blocks in the chain have the proper layout,
1704 // make a final call to AnalyzeBranch with AllowModify set.
1705 // Indeed, the target may be able to optimize the branches in a way we
1706 // cannot because all branches may not be analyzable.
1707 // E.g., the target may be able to remove an unconditional branch to
1708 // a fallthrough when it occurs after predicated terminators.
1709 for (MachineBasicBlock *ChainBB : FunctionChain) {
1710 Cond.clear();
Haicheng Wu90a55652016-05-24 22:16:14 +00001711 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
Jacques Pienaar71c30a12016-07-15 14:41:04 +00001712 if (!TII->analyzeBranch(*ChainBB, TBB, FBB, Cond, /*AllowModify*/ true)) {
Haicheng Wu90a55652016-05-24 22:16:14 +00001713 // If PrevBB has a two-way branch, try to re-order the branches
1714 // such that we branch to the successor with higher probability first.
1715 if (TBB && !Cond.empty() && FBB &&
1716 MBPI->getEdgeProbability(ChainBB, FBB) >
1717 MBPI->getEdgeProbability(ChainBB, TBB) &&
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +00001718 !TII->reverseBranchCondition(Cond)) {
Haicheng Wu90a55652016-05-24 22:16:14 +00001719 DEBUG(dbgs() << "Reverse order of the two branches: "
1720 << getBlockName(ChainBB) << "\n");
1721 DEBUG(dbgs() << " Edge probability: "
1722 << MBPI->getEdgeProbability(ChainBB, FBB) << " vs "
1723 << MBPI->getEdgeProbability(ChainBB, TBB) << "\n");
1724 DebugLoc dl; // FIXME: this is nowhere
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +00001725 TII->removeBranch(*ChainBB);
Matt Arsenaulte8e0f5c2016-09-14 17:24:15 +00001726 TII->insertBranch(*ChainBB, FBB, TBB, Cond, dl);
Haicheng Wu90a55652016-05-24 22:16:14 +00001727 ChainBB->updateTerminator();
1728 }
1729 }
Quentin Colombet776e6de2016-05-02 22:58:59 +00001730 }
Haicheng Wue749ce52016-04-29 17:06:44 +00001731}
Chandler Carruth10281422011-10-21 06:46:38 +00001732
Xinliang David Li52530a72016-06-13 22:23:44 +00001733void MachineBlockPlacement::alignBlocks() {
Chandler Carruthccc7e422012-04-16 01:12:56 +00001734 // Walk through the backedges of the function now that we have fully laid out
1735 // the basic blocks and align the destination of each backedge. We don't rely
Chandler Carruth881d0a72012-08-07 09:45:24 +00001736 // exclusively on the loop info here so that we can align backedges in
1737 // unnatural CFGs and backedges that were introduced purely because of the
1738 // loop rotations done during this layout pass.
Xinliang David Li52530a72016-06-13 22:23:44 +00001739 if (F->getFunction()->optForSize())
Chandler Carruth8b9737c2011-10-21 08:57:37 +00001740 return;
Xinliang David Li52530a72016-06-13 22:23:44 +00001741 BlockChain &FunctionChain = *BlockToChain[&F->front()];
Chandler Carruth881d0a72012-08-07 09:45:24 +00001742 if (FunctionChain.begin() == FunctionChain.end())
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001743 return; // Empty chain.
Chandler Carruth8b9737c2011-10-21 08:57:37 +00001744
Chandler Carruth881d0a72012-08-07 09:45:24 +00001745 const BranchProbability ColdProb(1, 5); // 20%
Xinliang David Li52530a72016-06-13 22:23:44 +00001746 BlockFrequency EntryFreq = MBFI->getBlockFreq(&F->front());
Chandler Carruth881d0a72012-08-07 09:45:24 +00001747 BlockFrequency WeightedEntryFreq = EntryFreq * ColdProb;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001748 for (MachineBasicBlock *ChainBB : FunctionChain) {
1749 if (ChainBB == *FunctionChain.begin())
1750 continue;
1751
Chandler Carruth881d0a72012-08-07 09:45:24 +00001752 // Don't align non-looping basic blocks. These are unlikely to execute
1753 // enough times to matter in practice. Note that we'll still handle
1754 // unnatural CFGs inside of a natural outer loop (the common case) and
1755 // rotated loops.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001756 MachineLoop *L = MLI->getLoopFor(ChainBB);
Chandler Carruth881d0a72012-08-07 09:45:24 +00001757 if (!L)
1758 continue;
1759
Hal Finkel57725662015-01-03 17:58:24 +00001760 unsigned Align = TLI->getPrefLoopAlignment(L);
1761 if (!Align)
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001762 continue; // Don't care about loop alignment.
Hal Finkel57725662015-01-03 17:58:24 +00001763
Chandler Carruth881d0a72012-08-07 09:45:24 +00001764 // If the block is cold relative to the function entry don't waste space
1765 // aligning it.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001766 BlockFrequency Freq = MBFI->getBlockFreq(ChainBB);
Chandler Carruth881d0a72012-08-07 09:45:24 +00001767 if (Freq < WeightedEntryFreq)
1768 continue;
1769
1770 // If the block is cold relative to its loop header, don't align it
1771 // regardless of what edges into the block exist.
1772 MachineBasicBlock *LoopHeader = L->getHeader();
1773 BlockFrequency LoopHeaderFreq = MBFI->getBlockFreq(LoopHeader);
1774 if (Freq < (LoopHeaderFreq * ColdProb))
1775 continue;
1776
1777 // Check for the existence of a non-layout predecessor which would benefit
1778 // from aligning this block.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001779 MachineBasicBlock *LayoutPred =
1780 &*std::prev(MachineFunction::iterator(ChainBB));
Chandler Carruth881d0a72012-08-07 09:45:24 +00001781
1782 // Force alignment if all the predecessors are jumps. We already checked
1783 // that the block isn't cold above.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001784 if (!LayoutPred->isSuccessor(ChainBB)) {
1785 ChainBB->setAlignment(Align);
Chandler Carruth881d0a72012-08-07 09:45:24 +00001786 continue;
1787 }
1788
1789 // Align this block if the layout predecessor's edge into this block is
Nadav Rotem6036f582013-03-29 16:34:23 +00001790 // cold relative to the block. When this is true, other predecessors make up
Chandler Carruth881d0a72012-08-07 09:45:24 +00001791 // all of the hot entries into the block and thus alignment is likely to be
1792 // important.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001793 BranchProbability LayoutProb =
1794 MBPI->getEdgeProbability(LayoutPred, ChainBB);
Chandler Carruth881d0a72012-08-07 09:45:24 +00001795 BlockFrequency LayoutEdgeFreq = MBFI->getBlockFreq(LayoutPred) * LayoutProb;
1796 if (LayoutEdgeFreq <= (Freq * ColdProb))
Chandler Carruth7a715da2015-03-05 03:19:05 +00001797 ChainBB->setAlignment(Align);
Chandler Carruthccc7e422012-04-16 01:12:56 +00001798 }
Chandler Carruth8b9737c2011-10-21 08:57:37 +00001799}
1800
Kyle Butt0846e562016-10-11 20:36:43 +00001801/// Tail duplicate \p BB into (some) predecessors if profitable, repeating if
1802/// it was duplicated into its chain predecessor and removed.
1803/// \p BB - Basic block that may be duplicated.
1804///
1805/// \p LPred - Chosen layout predecessor of \p BB.
1806/// Updated to be the chain end if LPred is removed.
1807/// \p Chain - Chain to which \p LPred belongs, and \p BB will belong.
1808/// \p BlockFilter - Set of blocks that belong to the loop being laid out.
1809/// Used to identify which blocks to update predecessor
1810/// counts.
1811/// \p PrevUnplacedBlockIt - Iterator pointing to the last block that was
1812/// chosen in the given order due to unnatural CFG
1813/// only needed if \p BB is removed and
1814/// \p PrevUnplacedBlockIt pointed to \p BB.
1815/// @return true if \p BB was removed.
1816bool MachineBlockPlacement::repeatedlyTailDuplicateBlock(
1817 MachineBasicBlock *BB, MachineBasicBlock *&LPred,
1818 MachineBasicBlock *LoopHeaderBB,
1819 BlockChain &Chain, BlockFilterSet *BlockFilter,
1820 MachineFunction::iterator &PrevUnplacedBlockIt) {
1821 bool Removed, DuplicatedToLPred;
1822 bool DuplicatedToOriginalLPred;
1823 Removed = maybeTailDuplicateBlock(BB, LPred, Chain, BlockFilter,
1824 PrevUnplacedBlockIt,
1825 DuplicatedToLPred);
1826 if (!Removed)
1827 return false;
1828 DuplicatedToOriginalLPred = DuplicatedToLPred;
1829 // Iteratively try to duplicate again. It can happen that a block that is
1830 // duplicated into is still small enough to be duplicated again.
1831 // No need to call markBlockSuccessors in this case, as the blocks being
1832 // duplicated from here on are already scheduled.
1833 // Note that DuplicatedToLPred always implies Removed.
1834 while (DuplicatedToLPred) {
1835 assert (Removed && "Block must have been removed to be duplicated into its "
1836 "layout predecessor.");
1837 MachineBasicBlock *DupBB, *DupPred;
1838 // The removal callback causes Chain.end() to be updated when a block is
1839 // removed. On the first pass through the loop, the chain end should be the
1840 // same as it was on function entry. On subsequent passes, because we are
1841 // duplicating the block at the end of the chain, if it is removed the
1842 // chain will have shrunk by one block.
1843 BlockChain::iterator ChainEnd = Chain.end();
1844 DupBB = *(--ChainEnd);
1845 // Now try to duplicate again.
1846 if (ChainEnd == Chain.begin())
1847 break;
1848 DupPred = *std::prev(ChainEnd);
1849 Removed = maybeTailDuplicateBlock(DupBB, DupPred, Chain, BlockFilter,
1850 PrevUnplacedBlockIt,
1851 DuplicatedToLPred);
1852 }
1853 // If BB was duplicated into LPred, it is now scheduled. But because it was
1854 // removed, markChainSuccessors won't be called for its chain. Instead we
1855 // call markBlockSuccessors for LPred to achieve the same effect. This must go
1856 // at the end because repeating the tail duplication can increase the number
1857 // of unscheduled predecessors.
1858 LPred = *std::prev(Chain.end());
1859 if (DuplicatedToOriginalLPred)
1860 markBlockSuccessors(Chain, LPred, LoopHeaderBB, BlockFilter);
1861 return true;
1862}
1863
1864/// Tail duplicate \p BB into (some) predecessors if profitable.
1865/// \p BB - Basic block that may be duplicated
1866/// \p LPred - Chosen layout predecessor of \p BB
1867/// \p Chain - Chain to which \p LPred belongs, and \p BB will belong.
1868/// \p BlockFilter - Set of blocks that belong to the loop being laid out.
1869/// Used to identify which blocks to update predecessor
1870/// counts.
1871/// \p PrevUnplacedBlockIt - Iterator pointing to the last block that was
1872/// chosen in the given order due to unnatural CFG
1873/// only needed if \p BB is removed and
1874/// \p PrevUnplacedBlockIt pointed to \p BB.
1875/// \p DuplicatedToLPred - True if the block was duplicated into LPred. Will
1876/// only be true if the block was removed.
1877/// \return - True if the block was duplicated into all preds and removed.
1878bool MachineBlockPlacement::maybeTailDuplicateBlock(
1879 MachineBasicBlock *BB, MachineBasicBlock *LPred,
1880 const BlockChain &Chain, BlockFilterSet *BlockFilter,
1881 MachineFunction::iterator &PrevUnplacedBlockIt,
1882 bool &DuplicatedToLPred) {
1883
1884 DuplicatedToLPred = false;
1885 DEBUG(dbgs() << "Redoing tail duplication for Succ#"
1886 << BB->getNumber() << "\n");
1887 bool IsSimple = TailDup.isSimpleBB(BB);
1888 // Blocks with single successors don't create additional fallthrough
1889 // opportunities. Don't duplicate them. TODO: When conditional exits are
1890 // analyzable, allow them to be duplicated.
1891 if (!IsSimple && BB->succ_size() == 1)
1892 return false;
1893 if (!TailDup.shouldTailDuplicate(IsSimple, *BB))
1894 return false;
1895 // This has to be a callback because none of it can be done after
1896 // BB is deleted.
1897 bool Removed = false;
1898 auto RemovalCallback =
1899 [&](MachineBasicBlock *RemBB) {
1900 // Signal to outer function
1901 Removed = true;
1902
1903 // Conservative default.
1904 bool InWorkList = true;
1905 // Remove from the Chain and Chain Map
1906 if (BlockToChain.count(RemBB)) {
1907 BlockChain *Chain = BlockToChain[RemBB];
1908 InWorkList = Chain->UnscheduledPredecessors == 0;
1909 Chain->remove(RemBB);
1910 BlockToChain.erase(RemBB);
1911 }
1912
1913 // Handle the unplaced block iterator
1914 if (&(*PrevUnplacedBlockIt) == RemBB) {
1915 PrevUnplacedBlockIt++;
1916 }
1917
1918 // Handle the Work Lists
1919 if (InWorkList) {
1920 SmallVectorImpl<MachineBasicBlock *> &RemoveList = BlockWorkList;
1921 if (RemBB->isEHPad())
1922 RemoveList = EHPadWorkList;
1923 RemoveList.erase(
1924 remove_if(RemoveList,
1925 [RemBB](MachineBasicBlock *BB) {return BB == RemBB;}),
1926 RemoveList.end());
1927 }
1928
1929 // Handle the filter set
1930 if (BlockFilter) {
1931 BlockFilter->erase(RemBB);
1932 }
1933
1934 // Remove the block from loop info.
1935 MLI->removeBlock(RemBB);
Kyle Buttab9cca72016-10-27 21:37:20 +00001936 if (RemBB == PreferredLoopExit)
1937 PreferredLoopExit = nullptr;
Kyle Butt0846e562016-10-11 20:36:43 +00001938
Kyle Butt0846e562016-10-11 20:36:43 +00001939 DEBUG(dbgs() << "TailDuplicator deleted block: "
1940 << getBlockName(RemBB) << "\n");
1941 };
1942 auto RemovalCallbackRef =
1943 llvm::function_ref<void(MachineBasicBlock*)>(RemovalCallback);
1944
1945 SmallVector<MachineBasicBlock *, 8> DuplicatedPreds;
1946 TailDup.tailDuplicateAndUpdate(IsSimple, BB, LPred,
1947 &DuplicatedPreds, &RemovalCallbackRef);
1948
1949 // Update UnscheduledPredecessors to reflect tail-duplication.
1950 DuplicatedToLPred = false;
1951 for (MachineBasicBlock *Pred : DuplicatedPreds) {
1952 // We're only looking for unscheduled predecessors that match the filter.
1953 BlockChain* PredChain = BlockToChain[Pred];
1954 if (Pred == LPred)
1955 DuplicatedToLPred = true;
1956 if (Pred == LPred || (BlockFilter && !BlockFilter->count(Pred))
1957 || PredChain == &Chain)
1958 continue;
1959 for (MachineBasicBlock *NewSucc : Pred->successors()) {
1960 if (BlockFilter && !BlockFilter->count(NewSucc))
1961 continue;
1962 BlockChain *NewChain = BlockToChain[NewSucc];
1963 if (NewChain != &Chain && NewChain != PredChain)
1964 NewChain->UnscheduledPredecessors++;
1965 }
1966 }
1967 return Removed;
1968}
1969
Xinliang David Li52530a72016-06-13 22:23:44 +00001970bool MachineBlockPlacement::runOnMachineFunction(MachineFunction &MF) {
1971 if (skipFunction(*MF.getFunction()))
Andrew Kaylor50271f72016-05-03 22:32:30 +00001972 return false;
1973
Chandler Carruth10281422011-10-21 06:46:38 +00001974 // Check for single-block functions and skip them.
Xinliang David Li52530a72016-06-13 22:23:44 +00001975 if (std::next(MF.begin()) == MF.end())
Chandler Carruth10281422011-10-21 06:46:38 +00001976 return false;
1977
Xinliang David Li52530a72016-06-13 22:23:44 +00001978 F = &MF;
Chandler Carruth10281422011-10-21 06:46:38 +00001979 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
Haicheng Wu5b458cc2016-06-09 15:24:29 +00001980 MBFI = llvm::make_unique<BranchFolder::MBFIWrapper>(
1981 getAnalysis<MachineBlockFrequencyInfo>());
Chandler Carruth8b9737c2011-10-21 08:57:37 +00001982 MLI = &getAnalysis<MachineLoopInfo>();
Xinliang David Li52530a72016-06-13 22:23:44 +00001983 TII = MF.getSubtarget().getInstrInfo();
1984 TLI = MF.getSubtarget().getTargetLowering();
Daniel Jasper471e8562015-03-04 11:05:34 +00001985 MDT = &getAnalysis<MachineDominatorTree>();
Eric Christopher690f8e52016-11-01 22:15:50 +00001986
1987 // Initialize PreferredLoopExit to nullptr here since it may never be set if
1988 // there are no MachineLoops.
1989 PreferredLoopExit = nullptr;
1990
Kyle Butt0846e562016-10-11 20:36:43 +00001991 if (TailDupPlacement) {
1992 unsigned TailDupSize = TailDuplicatePlacementThreshold;
1993 if (MF.getFunction()->optForSize())
1994 TailDupSize = 1;
1995 TailDup.initMF(MF, MBPI, /* LayoutMode */ true, TailDupSize);
1996 }
1997
Chandler Carruth10281422011-10-21 06:46:38 +00001998 assert(BlockToChain.empty());
Chandler Carruth10281422011-10-21 06:46:38 +00001999
Xinliang David Li52530a72016-06-13 22:23:44 +00002000 buildCFGChains();
Haicheng Wu5b458cc2016-06-09 15:24:29 +00002001
2002 // Changing the layout can create new tail merging opportunities.
2003 TargetPassConfig *PassConfig = &getAnalysis<TargetPassConfig>();
2004 // TailMerge can create jump into if branches that make CFG irreducible for
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00002005 // HW that requires structured CFG.
Xinliang David Li52530a72016-06-13 22:23:44 +00002006 bool EnableTailMerge = !MF.getTarget().requiresStructuredCFG() &&
Haicheng Wu5b458cc2016-06-09 15:24:29 +00002007 PassConfig->getEnableTailMerge() &&
2008 BranchFoldPlacement;
2009 // No tail merging opportunities if the block number is less than four.
Xinliang David Li52530a72016-06-13 22:23:44 +00002010 if (MF.size() > 3 && EnableTailMerge) {
Kyle Butt0846e562016-10-11 20:36:43 +00002011 unsigned TailMergeSize = TailDuplicatePlacementThreshold + 1;
Haicheng Wu5b458cc2016-06-09 15:24:29 +00002012 BranchFolder BF(/*EnableTailMerge=*/true, /*CommonHoist=*/false, *MBFI,
Kyle Butt64e42812016-08-18 18:57:29 +00002013 *MBPI, TailMergeSize);
Haicheng Wu5b458cc2016-06-09 15:24:29 +00002014
Xinliang David Li52530a72016-06-13 22:23:44 +00002015 if (BF.OptimizeFunction(MF, TII, MF.getSubtarget().getRegisterInfo(),
Haicheng Wu5b458cc2016-06-09 15:24:29 +00002016 getAnalysisIfAvailable<MachineModuleInfo>(), MLI,
2017 /*AfterBlockPlacement=*/true)) {
2018 // Redo the layout if tail merging creates/removes/moves blocks.
2019 BlockToChain.clear();
Kyle Butt0846e562016-10-11 20:36:43 +00002020 // Must redo the dominator tree if blocks were changed.
2021 MDT->runOnMachineFunction(MF);
Haicheng Wu5b458cc2016-06-09 15:24:29 +00002022 ChainAllocator.DestroyAll();
Xinliang David Li52530a72016-06-13 22:23:44 +00002023 buildCFGChains();
Haicheng Wu5b458cc2016-06-09 15:24:29 +00002024 }
2025 }
2026
Xinliang David Li52530a72016-06-13 22:23:44 +00002027 optimizeBranches();
2028 alignBlocks();
Chandler Carruth10281422011-10-21 06:46:38 +00002029
Chandler Carruth10281422011-10-21 06:46:38 +00002030 BlockToChain.clear();
Chandler Carruthfd9b4d92011-11-14 10:57:23 +00002031 ChainAllocator.DestroyAll();
Chandler Carruth10281422011-10-21 06:46:38 +00002032
Nadav Rotemc0adc9f2013-04-12 01:24:16 +00002033 if (AlignAllBlock)
2034 // Align all of the blocks in the function to a specific alignment.
Xinliang David Li52530a72016-06-13 22:23:44 +00002035 for (MachineBasicBlock &MBB : MF)
Chandler Carruth7a715da2015-03-05 03:19:05 +00002036 MBB.setAlignment(AlignAllBlock);
Geoff Berry10494ac2016-01-21 17:25:52 +00002037 else if (AlignAllNonFallThruBlocks) {
2038 // Align all of the blocks that have no fall-through predecessors to a
2039 // specific alignment.
Xinliang David Li52530a72016-06-13 22:23:44 +00002040 for (auto MBI = std::next(MF.begin()), MBE = MF.end(); MBI != MBE; ++MBI) {
Geoff Berry10494ac2016-01-21 17:25:52 +00002041 auto LayoutPred = std::prev(MBI);
2042 if (!LayoutPred->isSuccessor(&*MBI))
2043 MBI->setAlignment(AlignAllNonFallThruBlocks);
2044 }
2045 }
Nadav Rotemc0adc9f2013-04-12 01:24:16 +00002046
Chandler Carruth10281422011-10-21 06:46:38 +00002047 // We always return true as we have no way to track whether the final order
2048 // differs from the original order.
2049 return true;
2050}
Chandler Carruthae4e8002011-11-02 07:17:12 +00002051
2052namespace {
2053/// \brief A pass to compute block placement statistics.
2054///
2055/// A separate pass to compute interesting statistics for evaluating block
2056/// placement. This is separate from the actual placement pass so that they can
Benjamin Kramerbde91762012-06-02 10:20:22 +00002057/// be computed in the absence of any placement transformations or when using
Chandler Carruthae4e8002011-11-02 07:17:12 +00002058/// alternative placement strategies.
2059class MachineBlockPlacementStats : public MachineFunctionPass {
2060 /// \brief A handle to the branch probability pass.
2061 const MachineBranchProbabilityInfo *MBPI;
2062
2063 /// \brief A handle to the function-wide block frequency pass.
2064 const MachineBlockFrequencyInfo *MBFI;
2065
2066public:
2067 static char ID; // Pass identification, replacement for typeid
2068 MachineBlockPlacementStats() : MachineFunctionPass(ID) {
2069 initializeMachineBlockPlacementStatsPass(*PassRegistry::getPassRegistry());
2070 }
2071
Craig Topper4584cd52014-03-07 09:26:03 +00002072 bool runOnMachineFunction(MachineFunction &F) override;
Chandler Carruthae4e8002011-11-02 07:17:12 +00002073
Craig Topper4584cd52014-03-07 09:26:03 +00002074 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruthae4e8002011-11-02 07:17:12 +00002075 AU.addRequired<MachineBranchProbabilityInfo>();
2076 AU.addRequired<MachineBlockFrequencyInfo>();
2077 AU.setPreservesAll();
2078 MachineFunctionPass::getAnalysisUsage(AU);
2079 }
Chandler Carruthae4e8002011-11-02 07:17:12 +00002080};
Alexander Kornienkof00654e2015-06-23 09:49:53 +00002081}
Chandler Carruthae4e8002011-11-02 07:17:12 +00002082
2083char MachineBlockPlacementStats::ID = 0;
Andrew Trick1fa5bcb2012-02-08 21:23:13 +00002084char &llvm::MachineBlockPlacementStatsID = MachineBlockPlacementStats::ID;
Chandler Carruthae4e8002011-11-02 07:17:12 +00002085INITIALIZE_PASS_BEGIN(MachineBlockPlacementStats, "block-placement-stats",
2086 "Basic Block Placement Stats", false, false)
2087INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
2088INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
2089INITIALIZE_PASS_END(MachineBlockPlacementStats, "block-placement-stats",
2090 "Basic Block Placement Stats", false, false)
2091
Chandler Carruthae4e8002011-11-02 07:17:12 +00002092bool MachineBlockPlacementStats::runOnMachineFunction(MachineFunction &F) {
2093 // Check for single-block functions and skip them.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00002094 if (std::next(F.begin()) == F.end())
Chandler Carruthae4e8002011-11-02 07:17:12 +00002095 return false;
2096
2097 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
2098 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
2099
Chandler Carruth7a715da2015-03-05 03:19:05 +00002100 for (MachineBasicBlock &MBB : F) {
2101 BlockFrequency BlockFreq = MBFI->getBlockFreq(&MBB);
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00002102 Statistic &NumBranches =
Chandler Carruth7a715da2015-03-05 03:19:05 +00002103 (MBB.succ_size() > 1) ? NumCondBranches : NumUncondBranches;
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00002104 Statistic &BranchTakenFreq =
Chandler Carruth7a715da2015-03-05 03:19:05 +00002105 (MBB.succ_size() > 1) ? CondBranchTakenFreq : UncondBranchTakenFreq;
2106 for (MachineBasicBlock *Succ : MBB.successors()) {
Chandler Carruthae4e8002011-11-02 07:17:12 +00002107 // Skip if this successor is a fallthrough.
Chandler Carruth7a715da2015-03-05 03:19:05 +00002108 if (MBB.isLayoutSuccessor(Succ))
Chandler Carruthae4e8002011-11-02 07:17:12 +00002109 continue;
2110
Chandler Carruth7a715da2015-03-05 03:19:05 +00002111 BlockFrequency EdgeFreq =
2112 BlockFreq * MBPI->getEdgeProbability(&MBB, Succ);
Chandler Carruthae4e8002011-11-02 07:17:12 +00002113 ++NumBranches;
2114 BranchTakenFreq += EdgeFreq.getFrequency();
2115 }
2116 }
2117
2118 return false;
2119}