blob: 8a57f0099751045a7296c24362a34ef4a4b0c052 [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"
Xinliang David Lifd3f6452017-01-29 01:57:02 +000035#include "llvm/Analysis/BlockFrequencyInfoImpl.h"
Chandler Carruth8b9737c2011-10-21 08:57:37 +000036#include "llvm/CodeGen/MachineBasicBlock.h"
Chandler Carruth10281422011-10-21 06:46:38 +000037#include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
38#include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
Daniel Jasper471e8562015-03-04 11:05:34 +000039#include "llvm/CodeGen/MachineDominators.h"
Chandler Carruth10281422011-10-21 06:46:38 +000040#include "llvm/CodeGen/MachineFunction.h"
Chandler Carruth10281422011-10-21 06:46:38 +000041#include "llvm/CodeGen/MachineFunctionPass.h"
Chandler Carruth8b9737c2011-10-21 08:57:37 +000042#include "llvm/CodeGen/MachineLoopInfo.h"
43#include "llvm/CodeGen/MachineModuleInfo.h"
Kyle Buttb15c0662017-01-31 23:48:32 +000044#include "llvm/CodeGen/MachinePostDominators.h"
Kyle Butt0846e562016-10-11 20:36:43 +000045#include "llvm/CodeGen/TailDuplicator.h"
Chandler Carruth10281422011-10-21 06:46:38 +000046#include "llvm/Support/Allocator.h"
Nadav Rotemc3b0f502013-04-12 00:48:32 +000047#include "llvm/Support/CommandLine.h"
Chandler Carruthbd1be4d2011-10-23 09:18:45 +000048#include "llvm/Support/Debug.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000049#include "llvm/Support/raw_ostream.h"
Chandler Carruth10281422011-10-21 06:46:38 +000050#include "llvm/Target/TargetInstrInfo.h"
Chandler Carruth8b9737c2011-10-21 08:57:37 +000051#include "llvm/Target/TargetLowering.h"
Eric Christopherd9134482014-08-04 21:25:23 +000052#include "llvm/Target/TargetSubtargetInfo.h"
Chandler Carruth10281422011-10-21 06:46:38 +000053#include <algorithm>
Kyle Buttb15c0662017-01-31 23:48:32 +000054#include <functional>
55#include <utility>
Chandler Carruth10281422011-10-21 06:46:38 +000056using namespace llvm;
57
Chandler Carruthd0dced52015-03-05 02:28:25 +000058#define DEBUG_TYPE "block-placement"
Chandler Carruth1b9dde02014-04-22 02:02:50 +000059
Chandler Carruthae4e8002011-11-02 07:17:12 +000060STATISTIC(NumCondBranches, "Number of conditional branches");
Craig Topper77ec0772015-09-16 03:52:32 +000061STATISTIC(NumUncondBranches, "Number of unconditional branches");
Chandler Carruthae4e8002011-11-02 07:17:12 +000062STATISTIC(CondBranchTakenFreq,
63 "Potential frequency of taking conditional branches");
64STATISTIC(UncondBranchTakenFreq,
65 "Potential frequency of taking unconditional branches");
66
Nadav Rotemc3b0f502013-04-12 00:48:32 +000067static cl::opt<unsigned> AlignAllBlock("align-all-blocks",
68 cl::desc("Force the alignment of all "
69 "blocks in the function."),
70 cl::init(0), cl::Hidden);
71
Geoff Berry10494ac2016-01-21 17:25:52 +000072static cl::opt<unsigned> AlignAllNonFallThruBlocks(
73 "align-all-nofallthru-blocks",
74 cl::desc("Force the alignment of all "
75 "blocks that have no fall-through predecessors (i.e. don't add "
76 "nops that are executed)."),
77 cl::init(0), cl::Hidden);
78
Benjamin Kramerc8160d62013-11-20 19:08:44 +000079// FIXME: Find a good default for this flag and remove the flag.
Chandler Carruth2fc3fe12015-03-05 02:35:31 +000080static cl::opt<unsigned> ExitBlockBias(
81 "block-placement-exit-block-bias",
82 cl::desc("Block frequency percentage a loop exit block needs "
83 "over the original exit to be considered the new exit."),
84 cl::init(0), cl::Hidden);
Benjamin Kramerc8160d62013-11-20 19:08:44 +000085
Sjoerd Meijer5e11a182016-07-27 08:49:23 +000086// Definition:
87// - Outlining: placement of a basic block outside the chain or hot path.
88
Daniel Jasper471e8562015-03-04 11:05:34 +000089static cl::opt<bool> OutlineOptionalBranches(
90 "outline-optional-branches",
Sjoerd Meijer5e11a182016-07-27 08:49:23 +000091 cl::desc("Outlining optional branches will place blocks that are optional "
92 "branches, i.e. branches with a common post dominator, outside "
93 "the hot path or chain"),
Daniel Jasper471e8562015-03-04 11:05:34 +000094 cl::init(false), cl::Hidden);
95
Daniel Jasper214997c2015-03-20 10:00:37 +000096static cl::opt<unsigned> OutlineOptionalThreshold(
97 "outline-optional-threshold",
98 cl::desc("Don't outline optional branches that are a single block with an "
99 "instruction count below this threshold"),
100 cl::init(4), cl::Hidden);
101
Cong Houb90b9e02015-11-02 21:24:00 +0000102static cl::opt<unsigned> LoopToColdBlockRatio(
103 "loop-to-cold-block-ratio",
104 cl::desc("Outline loop blocks from loop chain if (frequency of loop) / "
105 "(frequency of block) is greater than this ratio"),
106 cl::init(5), cl::Hidden);
107
Cong Hou7745dbc2015-10-19 23:16:40 +0000108static cl::opt<bool>
109 PreciseRotationCost("precise-rotation-cost",
110 cl::desc("Model the cost of loop rotation more "
111 "precisely by using profile data."),
112 cl::init(false), cl::Hidden);
Xinliang David Lif0ab6df2016-05-12 02:04:41 +0000113static cl::opt<bool>
114 ForcePreciseRotationCost("force-precise-rotation-cost",
Xinliang David Lib840bb82016-05-12 16:39:02 +0000115 cl::desc("Force the use of precise cost "
116 "loop rotation strategy."),
Xinliang David Lif0ab6df2016-05-12 02:04:41 +0000117 cl::init(false), cl::Hidden);
Cong Hou7745dbc2015-10-19 23:16:40 +0000118
119static cl::opt<unsigned> MisfetchCost(
120 "misfetch-cost",
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +0000121 cl::desc("Cost that models the probabilistic risk of an instruction "
Cong Hou7745dbc2015-10-19 23:16:40 +0000122 "misfetch due to a jump comparing to falling through, whose cost "
123 "is zero."),
124 cl::init(1), cl::Hidden);
125
126static cl::opt<unsigned> JumpInstCost("jump-inst-cost",
127 cl::desc("Cost of jump instructions."),
128 cl::init(1), cl::Hidden);
Kyle Butt0846e562016-10-11 20:36:43 +0000129static cl::opt<bool>
130TailDupPlacement("tail-dup-placement",
131 cl::desc("Perform tail duplication during placement. "
132 "Creates more fallthrough opportunites in "
133 "outline branches."),
134 cl::init(true), cl::Hidden);
Cong Hou7745dbc2015-10-19 23:16:40 +0000135
Haicheng Wu5b458cc2016-06-09 15:24:29 +0000136static cl::opt<bool>
137BranchFoldPlacement("branch-fold-placement",
138 cl::desc("Perform branch folding during placement. "
139 "Reduces code size."),
140 cl::init(true), cl::Hidden);
141
Kyle Butt0846e562016-10-11 20:36:43 +0000142// Heuristic for tail duplication.
Kyle Buttb15c0662017-01-31 23:48:32 +0000143static cl::opt<unsigned> TailDupPlacementThreshold(
Kyle Butt0846e562016-10-11 20:36:43 +0000144 "tail-dup-placement-threshold",
145 cl::desc("Instruction cutoff for tail duplication during layout. "
146 "Tail merging during layout is forced to have a threshold "
147 "that won't conflict."), cl::init(2),
148 cl::Hidden);
149
Kyle Buttb15c0662017-01-31 23:48:32 +0000150// Heuristic for tail duplication.
151static cl::opt<unsigned> TailDupPlacementPenalty(
152 "tail-dup-placement-penalty",
153 cl::desc("Cost penalty for blocks that can avoid breaking CFG by copying. "
154 "Copying can increase fallthrough, but it also increases icache "
155 "pressure. This parameter controls the penalty to account for that. "
156 "Percent as integer."),
157 cl::init(2),
158 cl::Hidden);
159
Xinliang David Liff287372016-06-03 23:48:36 +0000160extern cl::opt<unsigned> StaticLikelyProb;
Dehao Chen9f2bdfb2016-06-14 22:27:17 +0000161extern cl::opt<unsigned> ProfileLikelyProb;
Xinliang David Liff287372016-06-03 23:48:36 +0000162
Xinliang David Li58fcc9b2017-02-02 21:29:17 +0000163// Internal option used to control BFI display only after MBP pass.
164// Defined in CodeGen/MachineBlockFrequencyInfo.cpp:
165// -view-block-layout-with-bfi=
Xinliang David Lifd3f6452017-01-29 01:57:02 +0000166extern cl::opt<GVDAGType> ViewBlockLayoutWithBFI;
Xinliang David Li58fcc9b2017-02-02 21:29:17 +0000167
168// Command line option to specify the name of the function for CFG dump
169// Defined in Analysis/BlockFrequencyInfo.cpp: -view-bfi-func-name=
Xinliang David Lifd3f6452017-01-29 01:57:02 +0000170extern cl::opt<std::string> ViewBlockFreqFuncName;
Xinliang David Lifd3f6452017-01-29 01:57:02 +0000171
Chandler Carruth10281422011-10-21 06:46:38 +0000172namespace {
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000173class BlockChain;
Chandler Carruth10281422011-10-21 06:46:38 +0000174/// \brief Type for our function-wide basic block -> block chain mapping.
Kyle Butte9425c4f2017-02-04 02:26:32 +0000175typedef DenseMap<const MachineBasicBlock *, BlockChain *> BlockToChainMapType;
Chandler Carruth10281422011-10-21 06:46:38 +0000176}
177
178namespace {
179/// \brief A chain of blocks which will be laid out contiguously.
180///
181/// This is the datastructure representing a chain of consecutive blocks that
182/// are profitable to layout together in order to maximize fallthrough
Chandler Carruth9139f442012-06-26 05:16:37 +0000183/// probabilities and code locality. We also can use a block chain to represent
184/// a sequence of basic blocks which have some external (correctness)
185/// requirement for sequential layout.
Chandler Carruth10281422011-10-21 06:46:38 +0000186///
Chandler Carruth9139f442012-06-26 05:16:37 +0000187/// Chains can be built around a single basic block and can be merged to grow
188/// them. They participate in a block-to-chain mapping, which is updated
189/// automatically as chains are merged together.
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000190class BlockChain {
191 /// \brief The sequence of blocks belonging to this chain.
Chandler Carruth10281422011-10-21 06:46:38 +0000192 ///
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000193 /// This is the sequence of blocks for a particular chain. These will be laid
194 /// out in-order within the function.
195 SmallVector<MachineBasicBlock *, 4> Blocks;
Chandler Carruth10281422011-10-21 06:46:38 +0000196
197 /// \brief A handle to the function-wide basic block to block chain mapping.
198 ///
199 /// This is retained in each block chain to simplify the computation of child
200 /// block chains for SCC-formation and iteration. We store the edges to child
201 /// basic blocks, and map them back to their associated chains using this
202 /// structure.
203 BlockToChainMapType &BlockToChain;
204
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000205public:
Chandler Carruth10281422011-10-21 06:46:38 +0000206 /// \brief Construct a new BlockChain.
207 ///
208 /// This builds a new block chain representing a single basic block in the
209 /// function. It also registers itself as the chain that block participates
210 /// in with the BlockToChain mapping.
211 BlockChain(BlockToChainMapType &BlockToChain, MachineBasicBlock *BB)
Philip Reamesae27b232016-03-03 00:58:43 +0000212 : Blocks(1, BB), BlockToChain(BlockToChain), UnscheduledPredecessors(0) {
Chandler Carruth10281422011-10-21 06:46:38 +0000213 assert(BB && "Cannot create a chain with a null basic block");
214 BlockToChain[BB] = this;
215 }
216
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000217 /// \brief Iterator over blocks within the chain.
Chandler Carruthccc7e422012-04-16 01:12:56 +0000218 typedef SmallVectorImpl<MachineBasicBlock *>::iterator iterator;
Kyle Butte9425c4f2017-02-04 02:26:32 +0000219 typedef SmallVectorImpl<MachineBasicBlock *>::const_iterator const_iterator;
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000220
221 /// \brief Beginning of blocks within the chain.
Chandler Carruthccc7e422012-04-16 01:12:56 +0000222 iterator begin() { return Blocks.begin(); }
Kyle Butte9425c4f2017-02-04 02:26:32 +0000223 const_iterator begin() const { return Blocks.begin(); }
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000224
225 /// \brief End of blocks within the chain.
Chandler Carruthccc7e422012-04-16 01:12:56 +0000226 iterator end() { return Blocks.end(); }
Kyle Butte9425c4f2017-02-04 02:26:32 +0000227 const_iterator end() const { return Blocks.end(); }
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000228
Kyle Butt0846e562016-10-11 20:36:43 +0000229 bool remove(MachineBasicBlock* BB) {
230 for(iterator i = begin(); i != end(); ++i) {
231 if (*i == BB) {
232 Blocks.erase(i);
233 return true;
234 }
235 }
236 return false;
237 }
238
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000239 /// \brief Merge a block chain into this one.
Chandler Carruth10281422011-10-21 06:46:38 +0000240 ///
241 /// This routine merges a block chain into this one. It takes care of forming
242 /// a contiguous sequence of basic blocks, updating the edge list, and
243 /// updating the block -> chain mapping. It does not free or tear down the
244 /// old chain, but the old chain's block list is no longer valid.
Jakub Staszak90616162011-12-21 23:02:08 +0000245 void merge(MachineBasicBlock *BB, BlockChain *Chain) {
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000246 assert(BB);
247 assert(!Blocks.empty());
Chandler Carruth10281422011-10-21 06:46:38 +0000248
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000249 // Fast path in case we don't have a chain already.
250 if (!Chain) {
251 assert(!BlockToChain[BB]);
252 Blocks.push_back(BB);
253 BlockToChain[BB] = this;
254 return;
Chandler Carruth10281422011-10-21 06:46:38 +0000255 }
256
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000257 assert(BB == *Chain->begin());
258 assert(Chain->begin() != Chain->end());
Chandler Carruth10281422011-10-21 06:46:38 +0000259
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000260 // Update the incoming blocks to point to this chain, and add them to the
261 // chain structure.
Chandler Carruth7a715da2015-03-05 03:19:05 +0000262 for (MachineBasicBlock *ChainBB : *Chain) {
263 Blocks.push_back(ChainBB);
264 assert(BlockToChain[ChainBB] == Chain && "Incoming blocks not in chain");
265 BlockToChain[ChainBB] = this;
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000266 }
Chandler Carruth10281422011-10-21 06:46:38 +0000267 }
Chandler Carruth8d150782011-11-13 11:20:44 +0000268
Chandler Carruth49158902012-04-08 14:37:01 +0000269#ifndef NDEBUG
270 /// \brief Dump the blocks in this chain.
Nico Weber7408c702014-01-03 22:53:37 +0000271 LLVM_DUMP_METHOD void dump() {
Chandler Carruth7a715da2015-03-05 03:19:05 +0000272 for (MachineBasicBlock *MBB : *this)
273 MBB->dump();
Chandler Carruth49158902012-04-08 14:37:01 +0000274 }
275#endif // NDEBUG
276
Philip Reamesae27b232016-03-03 00:58:43 +0000277 /// \brief Count of predecessors of any block within the chain which have not
278 /// yet been scheduled. In general, we will delay scheduling this chain
279 /// until those predecessors are scheduled (or we find a sufficiently good
280 /// reason to override this heuristic.) Note that when forming loop chains,
281 /// blocks outside the loop are ignored and treated as if they were already
282 /// scheduled.
Chandler Carruth8d150782011-11-13 11:20:44 +0000283 ///
Philip Reamesae27b232016-03-03 00:58:43 +0000284 /// Note: This field is reinitialized multiple times - once for each loop,
285 /// and then once for the function as a whole.
286 unsigned UnscheduledPredecessors;
Chandler Carruth10281422011-10-21 06:46:38 +0000287};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000288}
Chandler Carruth10281422011-10-21 06:46:38 +0000289
290namespace {
291class MachineBlockPlacement : public MachineFunctionPass {
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000292 /// \brief A typedef for a block filter set.
Kyle Butte9425c4f2017-02-04 02:26:32 +0000293 typedef SmallSetVector<const MachineBasicBlock *, 16> BlockFilterSet;
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000294
Kyle Buttb15c0662017-01-31 23:48:32 +0000295 /// Pair struct containing basic block and taildup profitiability
296 struct BlockAndTailDupResult {
297 MachineBasicBlock * BB;
298 bool ShouldTailDup;
299 };
300
Xinliang David Li93926ac2016-07-01 05:46:48 +0000301 /// \brief work lists of blocks that are ready to be laid out
302 SmallVector<MachineBasicBlock *, 16> BlockWorkList;
303 SmallVector<MachineBasicBlock *, 16> EHPadWorkList;
304
Xinliang David Li52530a72016-06-13 22:23:44 +0000305 /// \brief Machine Function
306 MachineFunction *F;
307
Chandler Carruth10281422011-10-21 06:46:38 +0000308 /// \brief A handle to the branch probability pass.
309 const MachineBranchProbabilityInfo *MBPI;
310
311 /// \brief A handle to the function-wide block frequency pass.
Haicheng Wu5b458cc2016-06-09 15:24:29 +0000312 std::unique_ptr<BranchFolder::MBFIWrapper> MBFI;
Chandler Carruth10281422011-10-21 06:46:38 +0000313
Chandler Carruth8b9737c2011-10-21 08:57:37 +0000314 /// \brief A handle to the loop info.
Haicheng Wu5b458cc2016-06-09 15:24:29 +0000315 MachineLoopInfo *MLI;
Chandler Carruth8b9737c2011-10-21 08:57:37 +0000316
Kyle Buttab9cca72016-10-27 21:37:20 +0000317 /// \brief Preferred loop exit.
318 /// Member variable for convenience. It may be removed by duplication deep
319 /// in the call stack.
320 MachineBasicBlock *PreferredLoopExit;
321
Chandler Carruth10281422011-10-21 06:46:38 +0000322 /// \brief A handle to the target's instruction info.
323 const TargetInstrInfo *TII;
324
Chandler Carruth8b9737c2011-10-21 08:57:37 +0000325 /// \brief A handle to the target's lowering info.
Benjamin Kramer56b31bd2013-01-11 20:05:37 +0000326 const TargetLoweringBase *TLI;
Chandler Carruth8b9737c2011-10-21 08:57:37 +0000327
Kyle Buttb15c0662017-01-31 23:48:32 +0000328 /// \brief A handle to the dominator tree.
Daniel Jasper471e8562015-03-04 11:05:34 +0000329 MachineDominatorTree *MDT;
330
Kyle Buttb15c0662017-01-31 23:48:32 +0000331 /// \brief A handle to the post dominator tree.
332 MachinePostDominatorTree *MPDT;
333
Kyle Butt0846e562016-10-11 20:36:43 +0000334 /// \brief Duplicator used to duplicate tails during placement.
335 ///
336 /// Placement decisions can open up new tail duplication opportunities, but
337 /// since tail duplication affects placement decisions of later blocks, it
338 /// must be done inline.
339 TailDuplicator TailDup;
340
Daniel Jasper471e8562015-03-04 11:05:34 +0000341 /// \brief A set of blocks that are unavoidably execute, i.e. they dominate
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000342 /// all terminators of the MachineFunction.
Kyle Butte9425c4f2017-02-04 02:26:32 +0000343 SmallPtrSet<const MachineBasicBlock *, 4> UnavoidableBlocks;
Daniel Jasper471e8562015-03-04 11:05:34 +0000344
Chandler Carruth10281422011-10-21 06:46:38 +0000345 /// \brief Allocator and owner of BlockChain structures.
346 ///
Chandler Carruth9139f442012-06-26 05:16:37 +0000347 /// We build BlockChains lazily while processing the loop structure of
348 /// a function. To reduce malloc traffic, we allocate them using this
349 /// slab-like allocator, and destroy them after the pass completes. An
350 /// important guarantee is that this allocator produces stable pointers to
351 /// the chains.
Chandler Carruth10281422011-10-21 06:46:38 +0000352 SpecificBumpPtrAllocator<BlockChain> ChainAllocator;
353
354 /// \brief Function wide BasicBlock to BlockChain mapping.
355 ///
356 /// This mapping allows efficiently moving from any given basic block to the
357 /// BlockChain it participates in, if any. We use it to, among other things,
358 /// allow implicitly defining edges between chains as the existing edges
359 /// between basic blocks.
Kyle Butte9425c4f2017-02-04 02:26:32 +0000360 DenseMap<const MachineBasicBlock *, BlockChain *> BlockToChain;
Chandler Carruth10281422011-10-21 06:46:38 +0000361
Sanjoy Dasd7389d62016-12-15 05:08:57 +0000362#ifndef NDEBUG
363 /// The set of basic blocks that have terminators that cannot be fully
364 /// analyzed. These basic blocks cannot be re-ordered safely by
365 /// MachineBlockPlacement, and we must preserve physical layout of these
366 /// blocks and their successors through the pass.
367 SmallPtrSet<MachineBasicBlock *, 4> BlocksWithUnanalyzableExits;
368#endif
369
Kyle Butt0846e562016-10-11 20:36:43 +0000370 /// Decrease the UnscheduledPredecessors count for all blocks in chain, and
371 /// if the count goes to 0, add them to the appropriate work list.
Kyle Butte9425c4f2017-02-04 02:26:32 +0000372 void markChainSuccessors(
373 const BlockChain &Chain, const MachineBasicBlock *LoopHeaderBB,
374 const BlockFilterSet *BlockFilter = nullptr);
Kyle Butt0846e562016-10-11 20:36:43 +0000375
376 /// Decrease the UnscheduledPredecessors count for a single block, and
377 /// if the count goes to 0, add them to the appropriate work list.
378 void markBlockSuccessors(
Kyle Butte9425c4f2017-02-04 02:26:32 +0000379 const BlockChain &Chain, const MachineBasicBlock *BB,
380 const MachineBasicBlock *LoopHeaderBB,
Kyle Butt0846e562016-10-11 20:36:43 +0000381 const BlockFilterSet *BlockFilter = nullptr);
382
Xinliang David Li594ffa32016-06-11 18:35:40 +0000383 BranchProbability
Kyle Butte9425c4f2017-02-04 02:26:32 +0000384 collectViableSuccessors(
385 const MachineBasicBlock *BB, const BlockChain &Chain,
386 const BlockFilterSet *BlockFilter,
387 SmallVector<MachineBasicBlock *, 4> &Successors);
388 bool shouldPredBlockBeOutlined(
389 const MachineBasicBlock *BB, const MachineBasicBlock *Succ,
390 const BlockChain &Chain, const BlockFilterSet *BlockFilter,
391 BranchProbability SuccProb, BranchProbability HotProb);
Kyle Butt0846e562016-10-11 20:36:43 +0000392 bool repeatedlyTailDuplicateBlock(
393 MachineBasicBlock *BB, MachineBasicBlock *&LPred,
Kyle Butte9425c4f2017-02-04 02:26:32 +0000394 const MachineBasicBlock *LoopHeaderBB,
Kyle Butt0846e562016-10-11 20:36:43 +0000395 BlockChain &Chain, BlockFilterSet *BlockFilter,
396 MachineFunction::iterator &PrevUnplacedBlockIt);
Kyle Butte9425c4f2017-02-04 02:26:32 +0000397 bool maybeTailDuplicateBlock(
398 MachineBasicBlock *BB, MachineBasicBlock *LPred,
399 BlockChain &Chain, BlockFilterSet *BlockFilter,
400 MachineFunction::iterator &PrevUnplacedBlockIt,
401 bool &DuplicatedToPred);
402 bool hasBetterLayoutPredecessor(
403 const MachineBasicBlock *BB, const MachineBasicBlock *Succ,
404 const BlockChain &SuccChain, BranchProbability SuccProb,
405 BranchProbability RealSuccProb, const BlockChain &Chain,
406 const BlockFilterSet *BlockFilter);
407 BlockAndTailDupResult selectBestSuccessor(
408 const MachineBasicBlock *BB, const BlockChain &Chain,
409 const BlockFilterSet *BlockFilter);
410 MachineBasicBlock *selectBestCandidateBlock(
411 const BlockChain &Chain, SmallVectorImpl<MachineBasicBlock *> &WorkList);
412 MachineBasicBlock *getFirstUnplacedBlock(
413 const BlockChain &PlacedChain,
414 MachineFunction::iterator &PrevUnplacedBlockIt,
415 const BlockFilterSet *BlockFilter);
Amaury Secheteae09c22016-03-14 21:24:11 +0000416
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +0000417 /// \brief Add a basic block to the work list if it is appropriate.
Amaury Secheteae09c22016-03-14 21:24:11 +0000418 ///
419 /// If the optional parameter BlockFilter is provided, only MBB
420 /// present in the set will be added to the worklist. If nullptr
421 /// is provided, no filtering occurs.
Kyle Butte9425c4f2017-02-04 02:26:32 +0000422 void fillWorkLists(const MachineBasicBlock *MBB,
Amaury Secheteae09c22016-03-14 21:24:11 +0000423 SmallPtrSetImpl<BlockChain *> &UpdatedPreds,
Amaury Secheteae09c22016-03-14 21:24:11 +0000424 const BlockFilterSet *BlockFilter);
Kyle Butte9425c4f2017-02-04 02:26:32 +0000425 void buildChain(const MachineBasicBlock *BB, BlockChain &Chain,
Kyle Butt0846e562016-10-11 20:36:43 +0000426 BlockFilterSet *BlockFilter = nullptr);
Kyle Butte9425c4f2017-02-04 02:26:32 +0000427 MachineBasicBlock *findBestLoopTop(
428 const MachineLoop &L, const BlockFilterSet &LoopBlockSet);
429 MachineBasicBlock *findBestLoopExit(
430 const MachineLoop &L, const BlockFilterSet &LoopBlockSet);
431 BlockFilterSet collectLoopBlockSet(const MachineLoop &L);
432 void buildLoopChains(const MachineLoop &L);
433 void rotateLoop(
434 BlockChain &LoopChain, const MachineBasicBlock *ExitingBB,
435 const BlockFilterSet &LoopBlockSet);
436 void rotateLoopWithProfile(
437 BlockChain &LoopChain, const MachineLoop &L,
438 const BlockFilterSet &LoopBlockSet);
Xinliang David Li52530a72016-06-13 22:23:44 +0000439 void collectMustExecuteBBs();
440 void buildCFGChains();
441 void optimizeBranches();
442 void alignBlocks();
Kyle Buttb15c0662017-01-31 23:48:32 +0000443 bool shouldTailDuplicate(MachineBasicBlock *BB);
444 /// Check the edge frequencies to see if tail duplication will increase
445 /// fallthroughs.
446 bool isProfitableToTailDup(
Kyle Butte9425c4f2017-02-04 02:26:32 +0000447 const MachineBasicBlock *BB, const MachineBasicBlock *Succ,
Kyle Buttb15c0662017-01-31 23:48:32 +0000448 BranchProbability AdjustedSumProb,
Kyle Butte9425c4f2017-02-04 02:26:32 +0000449 const BlockChain &Chain, const BlockFilterSet *BlockFilter);
Kyle Buttb15c0662017-01-31 23:48:32 +0000450 /// Returns true if a block can tail duplicate into all unplaced
451 /// predecessors. Filters based on loop.
452 bool canTailDuplicateUnplacedPreds(
Kyle Butte9425c4f2017-02-04 02:26:32 +0000453 const MachineBasicBlock *BB, MachineBasicBlock *Succ,
454 const BlockChain &Chain, const BlockFilterSet *BlockFilter);
Chandler Carruth10281422011-10-21 06:46:38 +0000455
456public:
457 static char ID; // Pass identification, replacement for typeid
458 MachineBlockPlacement() : MachineFunctionPass(ID) {
459 initializeMachineBlockPlacementPass(*PassRegistry::getPassRegistry());
460 }
461
Craig Topper4584cd52014-03-07 09:26:03 +0000462 bool runOnMachineFunction(MachineFunction &F) override;
Chandler Carruth10281422011-10-21 06:46:38 +0000463
Craig Topper4584cd52014-03-07 09:26:03 +0000464 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruth10281422011-10-21 06:46:38 +0000465 AU.addRequired<MachineBranchProbabilityInfo>();
466 AU.addRequired<MachineBlockFrequencyInfo>();
Daniel Jasper471e8562015-03-04 11:05:34 +0000467 AU.addRequired<MachineDominatorTree>();
Kyle Buttb15c0662017-01-31 23:48:32 +0000468 if (TailDupPlacement)
469 AU.addRequired<MachinePostDominatorTree>();
Chandler Carruth8b9737c2011-10-21 08:57:37 +0000470 AU.addRequired<MachineLoopInfo>();
Haicheng Wu5b458cc2016-06-09 15:24:29 +0000471 AU.addRequired<TargetPassConfig>();
Chandler Carruth10281422011-10-21 06:46:38 +0000472 MachineFunctionPass::getAnalysisUsage(AU);
473 }
Chandler Carruth10281422011-10-21 06:46:38 +0000474};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000475}
Chandler Carruth10281422011-10-21 06:46:38 +0000476
477char MachineBlockPlacement::ID = 0;
Andrew Trick1fa5bcb2012-02-08 21:23:13 +0000478char &llvm::MachineBlockPlacementID = MachineBlockPlacement::ID;
Chandler Carruthd0dced52015-03-05 02:28:25 +0000479INITIALIZE_PASS_BEGIN(MachineBlockPlacement, "block-placement",
Chandler Carruth10281422011-10-21 06:46:38 +0000480 "Branch Probability Basic Block Placement", false, false)
481INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
482INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
Daniel Jasper471e8562015-03-04 11:05:34 +0000483INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
Kyle Buttb15c0662017-01-31 23:48:32 +0000484INITIALIZE_PASS_DEPENDENCY(MachinePostDominatorTree)
Chandler Carruth8b9737c2011-10-21 08:57:37 +0000485INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
Chandler Carruthd0dced52015-03-05 02:28:25 +0000486INITIALIZE_PASS_END(MachineBlockPlacement, "block-placement",
Chandler Carruth10281422011-10-21 06:46:38 +0000487 "Branch Probability Basic Block Placement", false, false)
488
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000489#ifndef NDEBUG
490/// \brief Helper to print the name of a MBB.
491///
492/// Only used by debug logging.
Kyle Butte9425c4f2017-02-04 02:26:32 +0000493static std::string getBlockName(const MachineBasicBlock *BB) {
Alp Tokere69170a2014-06-26 22:52:05 +0000494 std::string Result;
495 raw_string_ostream OS(Result);
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000496 OS << "BB#" << BB->getNumber();
Philip Reamesb9688f42016-03-02 21:45:13 +0000497 OS << " ('" << BB->getName() << "')";
Alp Tokere69170a2014-06-26 22:52:05 +0000498 OS.flush();
499 return Result;
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000500}
501#endif
502
Chandler Carrutheb4ec3a2011-11-13 11:34:55 +0000503/// \brief Mark a chain's successors as having one fewer preds.
504///
505/// When a chain is being merged into the "placed" chain, this routine will
506/// quickly walk the successors of each block in the chain and mark them as
507/// having one fewer active predecessor. It also adds any successors of this
Kyle Butt0846e562016-10-11 20:36:43 +0000508/// chain which reach the zero-predecessor state to the appropriate worklist.
Chandler Carruth8d150782011-11-13 11:20:44 +0000509void MachineBlockPlacement::markChainSuccessors(
Kyle Butte9425c4f2017-02-04 02:26:32 +0000510 const BlockChain &Chain, const MachineBasicBlock *LoopHeaderBB,
Jakub Staszak90616162011-12-21 23:02:08 +0000511 const BlockFilterSet *BlockFilter) {
Chandler Carruth8d150782011-11-13 11:20:44 +0000512 // Walk all the blocks in this chain, marking their successors as having
513 // a predecessor placed.
Chandler Carruth7a715da2015-03-05 03:19:05 +0000514 for (MachineBasicBlock *MBB : Chain) {
Kyle Butt0846e562016-10-11 20:36:43 +0000515 markBlockSuccessors(Chain, MBB, LoopHeaderBB, BlockFilter);
516 }
517}
Chandler Carruth10281422011-10-21 06:46:38 +0000518
Kyle Butt0846e562016-10-11 20:36:43 +0000519/// \brief Mark a single block's successors as having one fewer preds.
520///
521/// Under normal circumstances, this is only called by markChainSuccessors,
522/// but if a block that was to be placed is completely tail-duplicated away,
523/// and was duplicated into the chain end, we need to redo markBlockSuccessors
524/// for just that block.
525void MachineBlockPlacement::markBlockSuccessors(
Kyle Butte9425c4f2017-02-04 02:26:32 +0000526 const BlockChain &Chain, const MachineBasicBlock *MBB,
527 const MachineBasicBlock *LoopHeaderBB, const BlockFilterSet *BlockFilter) {
Kyle Butt0846e562016-10-11 20:36:43 +0000528 // Add any successors for which this is the only un-placed in-loop
529 // predecessor to the worklist as a viable candidate for CFG-neutral
530 // placement. No subsequent placement of this block will violate the CFG
531 // shape, so we get to use heuristics to choose a favorable placement.
532 for (MachineBasicBlock *Succ : MBB->successors()) {
533 if (BlockFilter && !BlockFilter->count(Succ))
534 continue;
535 BlockChain &SuccChain = *BlockToChain[Succ];
536 // Disregard edges within a fixed chain, or edges to the loop header.
537 if (&Chain == &SuccChain || Succ == LoopHeaderBB)
538 continue;
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000539
Kyle Butt0846e562016-10-11 20:36:43 +0000540 // This is a cross-chain edge that is within the loop, so decrement the
541 // loop predecessor count of the destination chain.
542 if (SuccChain.UnscheduledPredecessors == 0 ||
543 --SuccChain.UnscheduledPredecessors > 0)
544 continue;
545
546 auto *NewBB = *SuccChain.begin();
547 if (NewBB->isEHPad())
548 EHPadWorkList.push_back(NewBB);
549 else
550 BlockWorkList.push_back(NewBB);
Chandler Carruth10281422011-10-21 06:46:38 +0000551 }
Chandler Carruth8d150782011-11-13 11:20:44 +0000552}
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000553
Xinliang David Li594ffa32016-06-11 18:35:40 +0000554/// This helper function collects the set of successors of block
555/// \p BB that are allowed to be its layout successors, and return
556/// the total branch probability of edges from \p BB to those
557/// blocks.
558BranchProbability MachineBlockPlacement::collectViableSuccessors(
Kyle Butte9425c4f2017-02-04 02:26:32 +0000559 const MachineBasicBlock *BB, const BlockChain &Chain,
560 const BlockFilterSet *BlockFilter,
Xinliang David Li594ffa32016-06-11 18:35:40 +0000561 SmallVector<MachineBasicBlock *, 4> &Successors) {
Cong Houd97c1002015-12-01 05:29:22 +0000562 // Adjust edge probabilities by excluding edges pointing to blocks that is
563 // either not in BlockFilter or is already in the current chain. Consider the
564 // following CFG:
Cong Hou41cf1a52015-11-18 00:52:52 +0000565 //
566 // --->A
567 // | / \
568 // | B C
569 // | \ / \
570 // ----D E
571 //
572 // Assume A->C is very hot (>90%), and C->D has a 50% probability, then after
573 // A->C is chosen as a fall-through, D won't be selected as a successor of C
574 // due to CFG constraint (the probability of C->D is not greater than
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +0000575 // HotProb to break top-order). If we exclude E that is not in BlockFilter
Xinliang David Li594ffa32016-06-11 18:35:40 +0000576 // when calculating the probability of C->D, D will be selected and we
577 // will get A C D B as the layout of this loop.
Cong Houd97c1002015-12-01 05:29:22 +0000578 auto AdjustedSumProb = BranchProbability::getOne();
Cong Hou41cf1a52015-11-18 00:52:52 +0000579 for (MachineBasicBlock *Succ : BB->successors()) {
580 bool SkipSucc = false;
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000581 if (Succ->isEHPad() || (BlockFilter && !BlockFilter->count(Succ))) {
Cong Hou41cf1a52015-11-18 00:52:52 +0000582 SkipSucc = true;
583 } else {
584 BlockChain *SuccChain = BlockToChain[Succ];
585 if (SuccChain == &Chain) {
Cong Hou41cf1a52015-11-18 00:52:52 +0000586 SkipSucc = true;
587 } else if (Succ != *SuccChain->begin()) {
588 DEBUG(dbgs() << " " << getBlockName(Succ) << " -> Mid chain!\n");
589 continue;
590 }
591 }
592 if (SkipSucc)
Cong Houd97c1002015-12-01 05:29:22 +0000593 AdjustedSumProb -= MBPI->getEdgeProbability(BB, Succ);
Cong Hou41cf1a52015-11-18 00:52:52 +0000594 else
595 Successors.push_back(Succ);
596 }
597
Xinliang David Li594ffa32016-06-11 18:35:40 +0000598 return AdjustedSumProb;
599}
600
601/// The helper function returns the branch probability that is adjusted
602/// or normalized over the new total \p AdjustedSumProb.
Xinliang David Li594ffa32016-06-11 18:35:40 +0000603static BranchProbability
604getAdjustedProbability(BranchProbability OrigProb,
605 BranchProbability AdjustedSumProb) {
606 BranchProbability SuccProb;
607 uint32_t SuccProbN = OrigProb.getNumerator();
608 uint32_t SuccProbD = AdjustedSumProb.getNumerator();
609 if (SuccProbN >= SuccProbD)
610 SuccProb = BranchProbability::getOne();
611 else
612 SuccProb = BranchProbability(SuccProbN, SuccProbD);
613
614 return SuccProb;
615}
616
Kyle Buttb15c0662017-01-31 23:48:32 +0000617/// Check if a block should be tail duplicated.
618/// \p BB Block to check.
619bool MachineBlockPlacement::shouldTailDuplicate(MachineBasicBlock *BB) {
620 // Blocks with single successors don't create additional fallthrough
621 // opportunities. Don't duplicate them. TODO: When conditional exits are
622 // analyzable, allow them to be duplicated.
623 bool IsSimple = TailDup.isSimpleBB(BB);
624
625 if (BB->succ_size() == 1)
626 return false;
627 return TailDup.shouldTailDuplicate(IsSimple, *BB);
628}
629
630/// Compare 2 BlockFrequency's with a small penalty for \p A.
631/// In order to be conservative, we apply a X% penalty to account for
632/// increased icache pressure and static heuristics. For small frequencies
633/// we use only the numerators to improve accuracy. For simplicity, we assume the
634/// penalty is less than 100%
635/// TODO(iteratee): Use 64-bit fixed point edge frequencies everywhere.
636static bool greaterWithBias(BlockFrequency A, BlockFrequency B,
637 uint64_t EntryFreq) {
638 BranchProbability ThresholdProb(TailDupPlacementPenalty, 100);
639 BlockFrequency Gain = A - B;
640 return (Gain / ThresholdProb).getFrequency() >= EntryFreq;
641}
642
643/// Check the edge frequencies to see if tail duplication will increase
644/// fallthroughs. It only makes sense to call this function when
645/// \p Succ would not be chosen otherwise. Tail duplication of \p Succ is
646/// always locally profitable if we would have picked \p Succ without
647/// considering duplication.
648bool MachineBlockPlacement::isProfitableToTailDup(
Kyle Butte9425c4f2017-02-04 02:26:32 +0000649 const MachineBasicBlock *BB, const MachineBasicBlock *Succ,
Kyle Buttb15c0662017-01-31 23:48:32 +0000650 BranchProbability QProb,
Kyle Butte9425c4f2017-02-04 02:26:32 +0000651 const BlockChain &Chain, const BlockFilterSet *BlockFilter) {
Kyle Buttb15c0662017-01-31 23:48:32 +0000652 // We need to do a probability calculation to make sure this is profitable.
653 // First: does succ have a successor that post-dominates? This affects the
654 // calculation. The 2 relevant cases are:
655 // BB BB
656 // | \Qout | \Qout
657 // P| C |P C
658 // = C' = C'
659 // | /Qin | /Qin
660 // | / | /
661 // Succ Succ
662 // / \ | \ V
663 // U/ =V |U \
664 // / \ = D
665 // D E | /
666 // | /
667 // |/
668 // PDom
669 // '=' : Branch taken for that CFG edge
670 // In the second case, Placing Succ while duplicating it into C prevents the
671 // fallthrough of Succ into either D or PDom, because they now have C as an
672 // unplaced predecessor
673
674 // Start by figuring out which case we fall into
675 MachineBasicBlock *PDom = nullptr;
676 SmallVector<MachineBasicBlock *, 4> SuccSuccs;
677 // Only scan the relevant successors
678 auto AdjustedSuccSumProb =
679 collectViableSuccessors(Succ, Chain, BlockFilter, SuccSuccs);
680 BranchProbability PProb = MBPI->getEdgeProbability(BB, Succ);
681 auto BBFreq = MBFI->getBlockFreq(BB);
682 auto SuccFreq = MBFI->getBlockFreq(Succ);
683 BlockFrequency P = BBFreq * PProb;
684 BlockFrequency Qout = BBFreq * QProb;
685 uint64_t EntryFreq = MBFI->getEntryFreq();
686 // If there are no more successors, it is profitable to copy, as it strictly
687 // increases fallthrough.
688 if (SuccSuccs.size() == 0)
689 return greaterWithBias(P, Qout, EntryFreq);
690
691 auto BestSuccSucc = BranchProbability::getZero();
692 // Find the PDom or the best Succ if no PDom exists.
693 for (MachineBasicBlock *SuccSucc : SuccSuccs) {
694 auto Prob = MBPI->getEdgeProbability(Succ, SuccSucc);
695 if (Prob > BestSuccSucc)
696 BestSuccSucc = Prob;
697 if (PDom == nullptr)
698 if (MPDT->dominates(SuccSucc, Succ)) {
699 PDom = SuccSucc;
700 break;
701 }
702 }
703 // For the comparisons, we need to know Succ's best incoming edge that isn't
704 // from BB.
705 auto SuccBestPred = BlockFrequency(0);
706 for (MachineBasicBlock *SuccPred : Succ->predecessors()) {
707 if (SuccPred == Succ || SuccPred == BB
708 || BlockToChain[SuccPred] == &Chain
709 || (BlockFilter && !BlockFilter->count(SuccPred)))
710 continue;
711 auto Freq = MBFI->getBlockFreq(SuccPred)
712 * MBPI->getEdgeProbability(SuccPred, Succ);
713 if (Freq > SuccBestPred)
714 SuccBestPred = Freq;
715 }
716 // Qin is Succ's best unplaced incoming edge that isn't BB
717 BlockFrequency Qin = SuccBestPred;
718 // If it doesn't have a post-dominating successor, here is the calculation:
719 // BB BB
720 // | \Qout | \
721 // P| C | =
722 // = C' | C
723 // | /Qin | |
724 // | / | C' (+Succ)
725 // Succ Succ /|
726 // / \ | \/ |
727 // U/ =V = /= =
728 // / \ | / \|
729 // D E D E
730 // '=' : Branch taken for that CFG edge
731 // Cost in the first case is: P + V
732 // For this calculation, we always assume P > Qout. If Qout > P
733 // The result of this function will be ignored at the caller.
734 // Cost in the second case is: Qout + Qin * V + P * U + P * V
735 // TODO(iteratee): If we lay out D after Succ, the P * U term
736 // goes away. This logic is coming in D28522.
737
738 if (PDom == nullptr || !Succ->isSuccessor(PDom)) {
739 BranchProbability UProb = BestSuccSucc;
740 BranchProbability VProb = AdjustedSuccSumProb - UProb;
741 BlockFrequency V = SuccFreq * VProb;
742 BlockFrequency QinV = Qin * VProb;
743 BlockFrequency BaseCost = P + V;
744 BlockFrequency DupCost = Qout + QinV + P * AdjustedSuccSumProb;
745 return greaterWithBias(BaseCost, DupCost, EntryFreq);
746 }
747 BranchProbability UProb = MBPI->getEdgeProbability(Succ, PDom);
748 BranchProbability VProb = AdjustedSuccSumProb - UProb;
749 BlockFrequency U = SuccFreq * UProb;
750 BlockFrequency V = SuccFreq * VProb;
751 // If there is a post-dominating successor, here is the calculation:
752 // BB BB BB BB
753 // | \Qout | \ | \Qout | \
754 // |P C | = |P C | =
755 // = C' |P C = C' |P C
756 // | /Qin | | | /Qin | |
757 // | / | C' (+Succ) | / | C' (+Succ)
758 // Succ Succ /| Succ Succ /|
759 // | \ V | \/ | | \ V | \/ |
760 // |U \ |U /\ | |U = |U /\ |
761 // = D = = =| | D | = =|
762 // | / |/ D | / |/ D
763 // | / | / | = | /
764 // |/ | / |/ | =
765 // Dom Dom Dom Dom
766 // '=' : Branch taken for that CFG edge
767 // The cost for taken branches in the first case is P + U
768 // The cost in the second case (assuming independence), given the layout:
769 // BB, Succ, (C+Succ), D, Dom
770 // is Qout + P * V + Qin * U
771 // compare P + U vs Qout + P + Qin * U.
772 //
773 // The 3rd and 4th cases cover when Dom would be chosen to follow Succ.
774 //
775 // For the 3rd case, the cost is P + 2 * V
776 // For the 4th case, the cost is Qout + Qin * U + P * V + V
777 // We choose 4 over 3 when (P + V) > Qout + Qin * U + P * V
778 if (UProb > AdjustedSuccSumProb / 2
779 && !hasBetterLayoutPredecessor(Succ, PDom, *BlockToChain[PDom],
780 UProb, UProb, Chain, BlockFilter)) {
781 // Cases 3 & 4
782 return greaterWithBias((P + V), (Qout + Qin * UProb + P * VProb),
783 EntryFreq);
784 }
785 // Cases 1 & 2
786 return greaterWithBias(
787 (P + U), (Qout + Qin * UProb + P * AdjustedSuccSumProb), EntryFreq);
788}
789
790
791/// When the option TailDupPlacement is on, this method checks if the
792/// fallthrough candidate block \p Succ (of block \p BB) can be tail-duplicated
793/// into all of its unplaced, unfiltered predecessors, that are not BB.
794bool MachineBlockPlacement::canTailDuplicateUnplacedPreds(
Kyle Butte9425c4f2017-02-04 02:26:32 +0000795 const MachineBasicBlock *BB, MachineBasicBlock *Succ,
796 const BlockChain &Chain, const BlockFilterSet *BlockFilter) {
Kyle Buttb15c0662017-01-31 23:48:32 +0000797 if (!shouldTailDuplicate(Succ))
798 return false;
799
800 for (MachineBasicBlock *Pred : Succ->predecessors()) {
801 // Make sure all unplaced and unfiltered predecessors can be
802 // tail-duplicated into.
Kyle Butte9425c4f2017-02-04 02:26:32 +0000803 // Skip any blocks that are already placed or not in this loop.
Kyle Buttb15c0662017-01-31 23:48:32 +0000804 if (Pred == BB || (BlockFilter && !BlockFilter->count(Pred))
805 || BlockToChain[Pred] == &Chain)
806 continue;
807 if (!TailDup.canTailDuplicate(Succ, Pred))
808 return false;
809 }
810 return true;
811}
812
Xinliang David Li071d0f12016-06-12 16:54:03 +0000813/// When the option OutlineOptionalBranches is on, this method
814/// checks if the fallthrough candidate block \p Succ (of block
815/// \p BB) also has other unscheduled predecessor blocks which
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +0000816/// are also successors of \p BB (forming triangular shape CFG).
Xinliang David Li071d0f12016-06-12 16:54:03 +0000817/// If none of such predecessors are small, it returns true.
818/// The caller can choose to select \p Succ as the layout successors
819/// so that \p Succ's predecessors (optional branches) can be
820/// outlined.
821/// FIXME: fold this with more general layout cost analysis.
822bool MachineBlockPlacement::shouldPredBlockBeOutlined(
Kyle Butte9425c4f2017-02-04 02:26:32 +0000823 const MachineBasicBlock *BB, const MachineBasicBlock *Succ,
824 const BlockChain &Chain, const BlockFilterSet *BlockFilter,
825 BranchProbability SuccProb, BranchProbability HotProb) {
Xinliang David Li071d0f12016-06-12 16:54:03 +0000826 if (!OutlineOptionalBranches)
827 return false;
828 // If we outline optional branches, look whether Succ is unavoidable, i.e.
829 // dominates all terminators of the MachineFunction. If it does, other
830 // successors must be optional. Don't do this for cold branches.
831 if (SuccProb > HotProb.getCompl() && UnavoidableBlocks.count(Succ) > 0) {
832 for (MachineBasicBlock *Pred : Succ->predecessors()) {
833 // Check whether there is an unplaced optional branch.
834 if (Pred == Succ || (BlockFilter && !BlockFilter->count(Pred)) ||
835 BlockToChain[Pred] == &Chain)
836 continue;
837 // Check whether the optional branch has exactly one BB.
838 if (Pred->pred_size() > 1 || *Pred->pred_begin() != BB)
839 continue;
840 // Check whether the optional branch is small.
841 if (Pred->size() < OutlineOptionalThreshold)
842 return false;
843 }
844 return true;
845 } else
846 return false;
847}
848
Dehao Chen9f2bdfb2016-06-14 22:27:17 +0000849// When profile is not present, return the StaticLikelyProb.
850// When profile is available, we need to handle the triangle-shape CFG.
851static BranchProbability getLayoutSuccessorProbThreshold(
Kyle Butte9425c4f2017-02-04 02:26:32 +0000852 const MachineBasicBlock *BB) {
Dehao Chen9f2bdfb2016-06-14 22:27:17 +0000853 if (!BB->getParent()->getFunction()->getEntryCount())
854 return BranchProbability(StaticLikelyProb, 100);
855 if (BB->succ_size() == 2) {
856 const MachineBasicBlock *Succ1 = *BB->succ_begin();
857 const MachineBasicBlock *Succ2 = *(BB->succ_begin() + 1);
Xinliang David Lie34ed832016-06-15 03:03:30 +0000858 if (Succ1->isSuccessor(Succ2) || Succ2->isSuccessor(Succ1)) {
859 /* See case 1 below for the cost analysis. For BB->Succ to
860 * be taken with smaller cost, the following needs to hold:
Kyle Buttb15c0662017-01-31 23:48:32 +0000861 * Prob(BB->Succ) > 2 * Prob(BB->Pred)
862 * So the threshold T in the calculation below
863 * (1-T) * Prob(BB->Succ) > T * Prob(BB->Pred)
864 * So T / (1 - T) = 2, Yielding T = 2/3
865 * Also adding user specified branch bias, we have
Xinliang David Lie34ed832016-06-15 03:03:30 +0000866 * T = (2/3)*(ProfileLikelyProb/50)
867 * = (2*ProfileLikelyProb)/150)
868 */
869 return BranchProbability(2 * ProfileLikelyProb, 150);
870 }
Dehao Chen9f2bdfb2016-06-14 22:27:17 +0000871 }
872 return BranchProbability(ProfileLikelyProb, 100);
Xinliang David Licbf12142016-06-13 20:24:19 +0000873}
874
875/// Checks to see if the layout candidate block \p Succ has a better layout
876/// predecessor than \c BB. If yes, returns true.
Kyle Buttb15c0662017-01-31 23:48:32 +0000877/// \p SuccProb: The probability adjusted for only remaining blocks.
878/// Only used for logging
879/// \p RealSuccProb: The un-adjusted probability.
880/// \p Chain: The chain that BB belongs to and Succ is being considered for.
881/// \p BlockFilter: if non-null, the set of blocks that make up the loop being
882/// considered
Xinliang David Licbf12142016-06-13 20:24:19 +0000883bool MachineBlockPlacement::hasBetterLayoutPredecessor(
Kyle Butte9425c4f2017-02-04 02:26:32 +0000884 const MachineBasicBlock *BB, const MachineBasicBlock *Succ,
885 const BlockChain &SuccChain, BranchProbability SuccProb,
886 BranchProbability RealSuccProb, const BlockChain &Chain,
887 const BlockFilterSet *BlockFilter) {
Xinliang David Licbf12142016-06-13 20:24:19 +0000888
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +0000889 // There isn't a better layout when there are no unscheduled predecessors.
Xinliang David Licbf12142016-06-13 20:24:19 +0000890 if (SuccChain.UnscheduledPredecessors == 0)
891 return false;
892
893 // There are two basic scenarios here:
894 // -------------------------------------
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +0000895 // Case 1: triangular shape CFG (if-then):
Xinliang David Licbf12142016-06-13 20:24:19 +0000896 // BB
897 // | \
898 // | \
899 // | Pred
900 // | /
901 // Succ
902 // In this case, we are evaluating whether to select edge -> Succ, e.g.
903 // set Succ as the layout successor of BB. Picking Succ as BB's
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +0000904 // successor breaks the CFG constraints (FIXME: define these constraints).
905 // With this layout, Pred BB
Xinliang David Licbf12142016-06-13 20:24:19 +0000906 // is forced to be outlined, so the overall cost will be cost of the
907 // branch taken from BB to Pred, plus the cost of back taken branch
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +0000908 // from Pred to Succ, as well as the additional cost associated
Xinliang David Licbf12142016-06-13 20:24:19 +0000909 // with the needed unconditional jump instruction from Pred To Succ.
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +0000910
Xinliang David Licbf12142016-06-13 20:24:19 +0000911 // The cost of the topological order layout is the taken branch cost
912 // from BB to Succ, so to make BB->Succ a viable candidate, the following
913 // must hold:
914 // 2 * freq(BB->Pred) * taken_branch_cost + unconditional_jump_cost
915 // < freq(BB->Succ) * taken_branch_cost.
916 // Ignoring unconditional jump cost, we get
917 // freq(BB->Succ) > 2 * freq(BB->Pred), i.e.,
918 // prob(BB->Succ) > 2 * prob(BB->Pred)
919 //
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +0000920 // When real profile data is available, we can precisely compute the
921 // probability threshold that is needed for edge BB->Succ to be considered.
922 // Without profile data, the heuristic requires the branch bias to be
Xinliang David Licbf12142016-06-13 20:24:19 +0000923 // a lot larger to make sure the signal is very strong (e.g. 80% default).
924 // -----------------------------------------------------------------
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +0000925 // Case 2: diamond like CFG (if-then-else):
Xinliang David Licbf12142016-06-13 20:24:19 +0000926 // S
927 // / \
928 // | \
929 // BB Pred
930 // \ /
931 // Succ
932 // ..
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +0000933 //
934 // The current block is BB and edge BB->Succ is now being evaluated.
935 // Note that edge S->BB was previously already selected because
936 // prob(S->BB) > prob(S->Pred).
937 // At this point, 2 blocks can be placed after BB: Pred or Succ. If we
938 // choose Pred, we will have a topological ordering as shown on the left
939 // in the picture below. If we choose Succ, we have the solution as shown
940 // on the right:
941 //
942 // topo-order:
943 //
944 // S----- ---S
945 // | | | |
946 // ---BB | | BB
947 // | | | |
948 // | pred-- | Succ--
949 // | | | |
950 // ---succ ---pred--
951 //
952 // cost = freq(S->Pred) + freq(BB->Succ) cost = 2 * freq (S->Pred)
953 // = freq(S->Pred) + freq(S->BB)
954 //
955 // If we have profile data (i.e, branch probabilities can be trusted), the
956 // cost (number of taken branches) with layout S->BB->Succ->Pred is 2 *
957 // freq(S->Pred) while the cost of topo order is freq(S->Pred) + freq(S->BB).
958 // We know Prob(S->BB) > Prob(S->Pred), so freq(S->BB) > freq(S->Pred), which
959 // means the cost of topological order is greater.
Xinliang David Licbf12142016-06-13 20:24:19 +0000960 // When profile data is not available, however, we need to be more
961 // conservative. If the branch prediction is wrong, breaking the topo-order
962 // will actually yield a layout with large cost. For this reason, we need
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +0000963 // strong biased branch at block S with Prob(S->BB) in order to select
964 // BB->Succ. This is equivalent to looking the CFG backward with backward
Xinliang David Licbf12142016-06-13 20:24:19 +0000965 // edge: Prob(Succ->BB) needs to >= HotProb in order to be selected (without
966 // profile data).
Kyle Butt02d8d052016-07-29 18:09:28 +0000967 // --------------------------------------------------------------------------
968 // Case 3: forked diamond
969 // S
970 // / \
971 // / \
972 // BB Pred
973 // | \ / |
974 // | \ / |
975 // | X |
976 // | / \ |
977 // | / \ |
978 // S1 S2
979 //
980 // The current block is BB and edge BB->S1 is now being evaluated.
981 // As above S->BB was already selected because
982 // prob(S->BB) > prob(S->Pred). Assume that prob(BB->S1) >= prob(BB->S2).
983 //
984 // topo-order:
985 //
986 // S-------| ---S
987 // | | | |
988 // ---BB | | BB
989 // | | | |
990 // | Pred----| | S1----
991 // | | | |
992 // --(S1 or S2) ---Pred--
993 //
994 // topo-cost = freq(S->Pred) + freq(BB->S1) + freq(BB->S2)
995 // + min(freq(Pred->S1), freq(Pred->S2))
996 // Non-topo-order cost:
997 // In the worst case, S2 will not get laid out after Pred.
998 // non-topo-cost = 2 * freq(S->Pred) + freq(BB->S2).
999 // To be conservative, we can assume that min(freq(Pred->S1), freq(Pred->S2))
1000 // is 0. Then the non topo layout is better when
1001 // freq(S->Pred) < freq(BB->S1).
1002 // This is exactly what is checked below.
1003 // Note there are other shapes that apply (Pred may not be a single block,
1004 // but they all fit this general pattern.)
Dehao Chen9f2bdfb2016-06-14 22:27:17 +00001005 BranchProbability HotProb = getLayoutSuccessorProbThreshold(BB);
Xinliang David Licbf12142016-06-13 20:24:19 +00001006
Xinliang David Licbf12142016-06-13 20:24:19 +00001007 // Make sure that a hot successor doesn't have a globally more
1008 // important predecessor.
1009 BlockFrequency CandidateEdgeFreq = MBFI->getBlockFreq(BB) * RealSuccProb;
1010 bool BadCFGConflict = false;
1011
1012 for (MachineBasicBlock *Pred : Succ->predecessors()) {
1013 if (Pred == Succ || BlockToChain[Pred] == &SuccChain ||
1014 (BlockFilter && !BlockFilter->count(Pred)) ||
Kyle Buttb15c0662017-01-31 23:48:32 +00001015 BlockToChain[Pred] == &Chain ||
1016 // This check is redundant except for look ahead. This function is
1017 // called for lookahead by isProfitableToTailDup when BB hasn't been
1018 // placed yet.
1019 (Pred == BB))
Xinliang David Licbf12142016-06-13 20:24:19 +00001020 continue;
Kyle Butt02d8d052016-07-29 18:09:28 +00001021 // Do backward checking.
1022 // For all cases above, we need a backward checking to filter out edges that
Kyle Buttb15c0662017-01-31 23:48:32 +00001023 // are not 'strongly' biased.
Xinliang David Licbf12142016-06-13 20:24:19 +00001024 // BB Pred
1025 // \ /
1026 // Succ
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00001027 // We select edge BB->Succ if
Xinliang David Licbf12142016-06-13 20:24:19 +00001028 // freq(BB->Succ) > freq(Succ) * HotProb
1029 // i.e. freq(BB->Succ) > freq(BB->Succ) * HotProb + freq(Pred->Succ) *
1030 // HotProb
1031 // i.e. freq((BB->Succ) * (1 - HotProb) > freq(Pred->Succ) * HotProb
Kyle Butt02d8d052016-07-29 18:09:28 +00001032 // Case 1 is covered too, because the first equation reduces to:
1033 // prob(BB->Succ) > HotProb. (freq(Succ) = freq(BB) for a triangle)
Xinliang David Licbf12142016-06-13 20:24:19 +00001034 BlockFrequency PredEdgeFreq =
1035 MBFI->getBlockFreq(Pred) * MBPI->getEdgeProbability(Pred, Succ);
1036 if (PredEdgeFreq * HotProb >= CandidateEdgeFreq * HotProb.getCompl()) {
1037 BadCFGConflict = true;
1038 break;
1039 }
1040 }
1041
1042 if (BadCFGConflict) {
Sjoerd Meijer5e11a182016-07-27 08:49:23 +00001043 DEBUG(dbgs() << " Not a candidate: " << getBlockName(Succ) << " -> " << SuccProb
Xinliang David Licbf12142016-06-13 20:24:19 +00001044 << " (prob) (non-cold CFG conflict)\n");
1045 return true;
1046 }
1047
1048 return false;
1049}
1050
Xinliang David Li594ffa32016-06-11 18:35:40 +00001051/// \brief Select the best successor for a block.
1052///
1053/// This looks across all successors of a particular block and attempts to
1054/// select the "best" one to be the layout successor. It only considers direct
1055/// successors which also pass the block filter. It will attempt to avoid
1056/// breaking CFG structure, but cave and break such structures in the case of
1057/// very hot successor edges.
1058///
Kyle Buttb15c0662017-01-31 23:48:32 +00001059/// \returns The best successor block found, or null if none are viable, along
1060/// with a boolean indicating if tail duplication is necessary.
1061MachineBlockPlacement::BlockAndTailDupResult
Kyle Butte9425c4f2017-02-04 02:26:32 +00001062MachineBlockPlacement::selectBestSuccessor(
1063 const MachineBasicBlock *BB, const BlockChain &Chain,
1064 const BlockFilterSet *BlockFilter) {
Xinliang David Li594ffa32016-06-11 18:35:40 +00001065 const BranchProbability HotProb(StaticLikelyProb, 100);
1066
Kyle Buttb15c0662017-01-31 23:48:32 +00001067 BlockAndTailDupResult BestSucc = { nullptr, false };
Xinliang David Li594ffa32016-06-11 18:35:40 +00001068 auto BestProb = BranchProbability::getZero();
1069
1070 SmallVector<MachineBasicBlock *, 4> Successors;
1071 auto AdjustedSumProb =
1072 collectViableSuccessors(BB, Chain, BlockFilter, Successors);
1073
Sjoerd Meijer5e11a182016-07-27 08:49:23 +00001074 DEBUG(dbgs() << "Selecting best successor for: " << getBlockName(BB) << "\n");
Kyle Buttb15c0662017-01-31 23:48:32 +00001075
1076 // For blocks with CFG violations, we may be able to lay them out anyway with
1077 // tail-duplication. We keep this vector so we can perform the probability
1078 // calculations the minimum number of times.
1079 SmallVector<std::tuple<BranchProbability, MachineBasicBlock *>, 4>
1080 DupCandidates;
Cong Hou41cf1a52015-11-18 00:52:52 +00001081 for (MachineBasicBlock *Succ : Successors) {
Xinliang David Li594ffa32016-06-11 18:35:40 +00001082 auto RealSuccProb = MBPI->getEdgeProbability(BB, Succ);
1083 BranchProbability SuccProb =
1084 getAdjustedProbability(RealSuccProb, AdjustedSumProb);
Chandler Carruthb3361722011-11-13 11:34:53 +00001085
Xinliang David Li071d0f12016-06-12 16:54:03 +00001086 // This heuristic is off by default.
1087 if (shouldPredBlockBeOutlined(BB, Succ, Chain, BlockFilter, SuccProb,
Kyle Buttb15c0662017-01-31 23:48:32 +00001088 HotProb)) {
1089 BestSucc.BB = Succ;
1090 return BestSucc;
1091 }
Daniel Jasper471e8562015-03-04 11:05:34 +00001092
Cong Hou41cf1a52015-11-18 00:52:52 +00001093 BlockChain &SuccChain = *BlockToChain[Succ];
Xinliang David Licbf12142016-06-13 20:24:19 +00001094 // Skip the edge \c BB->Succ if block \c Succ has a better layout
1095 // predecessor that yields lower global cost.
1096 if (hasBetterLayoutPredecessor(BB, Succ, SuccChain, SuccProb, RealSuccProb,
Kyle Buttb15c0662017-01-31 23:48:32 +00001097 Chain, BlockFilter)) {
1098 // If tail duplication would make Succ profitable, place it.
1099 if (TailDupPlacement && shouldTailDuplicate(Succ))
1100 DupCandidates.push_back(std::make_tuple(SuccProb, Succ));
Xinliang David Licbf12142016-06-13 20:24:19 +00001101 continue;
Kyle Buttb15c0662017-01-31 23:48:32 +00001102 }
Chandler Carruth18dfac32011-11-20 11:22:06 +00001103
Xinliang David Licbf12142016-06-13 20:24:19 +00001104 DEBUG(
Sjoerd Meijer5e11a182016-07-27 08:49:23 +00001105 dbgs() << " Candidate: " << getBlockName(Succ) << ", probability: "
1106 << SuccProb
Xinliang David Licbf12142016-06-13 20:24:19 +00001107 << (SuccChain.UnscheduledPredecessors != 0 ? " (CFG break)" : "")
1108 << "\n");
Sjoerd Meijer5e11a182016-07-27 08:49:23 +00001109
Kyle Buttb15c0662017-01-31 23:48:32 +00001110 if (BestSucc.BB && BestProb >= SuccProb) {
Sjoerd Meijer5e11a182016-07-27 08:49:23 +00001111 DEBUG(dbgs() << " Not the best candidate, continuing\n");
Chandler Carruthb3361722011-11-13 11:34:53 +00001112 continue;
Sjoerd Meijer5e11a182016-07-27 08:49:23 +00001113 }
1114
1115 DEBUG(dbgs() << " Setting it as best candidate\n");
Kyle Buttb15c0662017-01-31 23:48:32 +00001116 BestSucc.BB = Succ;
Cong Houd97c1002015-12-01 05:29:22 +00001117 BestProb = SuccProb;
Chandler Carruthb3361722011-11-13 11:34:53 +00001118 }
Kyle Buttb15c0662017-01-31 23:48:32 +00001119 // Handle the tail duplication candidates in order of decreasing probability.
1120 // Stop at the first one that is profitable. Also stop if they are less
1121 // profitable than BestSucc. Position is important because we preserve it and
1122 // prefer first best match. Here we aren't comparing in order, so we capture
1123 // the position instead.
1124 if (DupCandidates.size() != 0) {
1125 auto cmp =
1126 [](const std::tuple<BranchProbability, MachineBasicBlock *> &a,
1127 const std::tuple<BranchProbability, MachineBasicBlock *> &b) {
1128 return std::get<0>(a) > std::get<0>(b);
1129 };
1130 std::stable_sort(DupCandidates.begin(), DupCandidates.end(), cmp);
1131 }
1132 for(auto &Tup : DupCandidates) {
1133 BranchProbability DupProb;
1134 MachineBasicBlock *Succ;
1135 std::tie(DupProb, Succ) = Tup;
1136 if (DupProb < BestProb)
1137 break;
1138 if (canTailDuplicateUnplacedPreds(BB, Succ, Chain, BlockFilter)
1139 // If tail duplication gives us fallthrough when we otherwise wouldn't
1140 // have it, that is a strict gain.
1141 && (BestSucc.BB == nullptr
1142 || isProfitableToTailDup(BB, Succ, BestProb, Chain,
1143 BlockFilter))) {
1144 DEBUG(
1145 dbgs() << " Candidate: " << getBlockName(Succ) << ", probability: "
1146 << DupProb
1147 << " (Tail Duplicate)\n");
1148 BestSucc.BB = Succ;
1149 BestSucc.ShouldTailDup = true;
1150 break;
1151 }
1152 }
1153
1154 if (BestSucc.BB)
1155 DEBUG(dbgs() << " Selected: " << getBlockName(BestSucc.BB) << "\n");
Sjoerd Meijer5e11a182016-07-27 08:49:23 +00001156
Chandler Carruthb3361722011-11-13 11:34:53 +00001157 return BestSucc;
1158}
1159
Chandler Carruthf9213fe2011-11-13 11:42:26 +00001160/// \brief Select the best block from a worklist.
1161///
1162/// This looks through the provided worklist as a list of candidate basic
1163/// blocks and select the most profitable one to place. The definition of
1164/// profitable only really makes sense in the context of a loop. This returns
1165/// the most frequently visited block in the worklist, which in the case of
1166/// a loop, is the one most desirable to be physically close to the rest of the
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00001167/// loop body in order to improve i-cache behavior.
Chandler Carruthf9213fe2011-11-13 11:42:26 +00001168///
1169/// \returns The best block found, or null if none are viable.
1170MachineBasicBlock *MachineBlockPlacement::selectBestCandidateBlock(
Kyle Butte9425c4f2017-02-04 02:26:32 +00001171 const BlockChain &Chain, SmallVectorImpl<MachineBasicBlock *> &WorkList) {
Chandler Carruth0af6a0b2011-11-14 09:46:33 +00001172 // Once we need to walk the worklist looking for a candidate, cleanup the
1173 // worklist of already placed entries.
1174 // FIXME: If this shows up on profiles, it could be folded (at the cost of
1175 // some code complexity) into the loop below.
David Majnemerc7004902016-08-12 04:32:37 +00001176 WorkList.erase(remove_if(WorkList,
1177 [&](MachineBasicBlock *BB) {
1178 return BlockToChain.lookup(BB) == &Chain;
1179 }),
Chandler Carruth0af6a0b2011-11-14 09:46:33 +00001180 WorkList.end());
1181
Amaury Sechetc53ad4f2016-04-07 21:29:39 +00001182 if (WorkList.empty())
1183 return nullptr;
1184
1185 bool IsEHPad = WorkList[0]->isEHPad();
1186
Craig Topperc0196b12014-04-14 00:51:57 +00001187 MachineBasicBlock *BestBlock = nullptr;
Chandler Carruthf9213fe2011-11-13 11:42:26 +00001188 BlockFrequency BestFreq;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001189 for (MachineBasicBlock *MBB : WorkList) {
Amaury Sechetc53ad4f2016-04-07 21:29:39 +00001190 assert(MBB->isEHPad() == IsEHPad);
1191
Chandler Carruth7a715da2015-03-05 03:19:05 +00001192 BlockChain &SuccChain = *BlockToChain[MBB];
Philip Reames02e11322016-03-02 22:40:51 +00001193 if (&SuccChain == &Chain)
Chandler Carruthf9213fe2011-11-13 11:42:26 +00001194 continue;
Junmo Park4ba6cf62016-03-11 05:07:07 +00001195
Philip Reamesae27b232016-03-03 00:58:43 +00001196 assert(SuccChain.UnscheduledPredecessors == 0 && "Found CFG-violating block");
Chandler Carruthf9213fe2011-11-13 11:42:26 +00001197
Chandler Carruth7a715da2015-03-05 03:19:05 +00001198 BlockFrequency CandidateFreq = MBFI->getBlockFreq(MBB);
1199 DEBUG(dbgs() << " " << getBlockName(MBB) << " -> ";
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001200 MBFI->printBlockFreq(dbgs(), CandidateFreq) << " (freq)\n");
Amaury Sechetc53ad4f2016-04-07 21:29:39 +00001201
1202 // For ehpad, we layout the least probable first as to avoid jumping back
1203 // from least probable landingpads to more probable ones.
1204 //
1205 // FIXME: Using probability is probably (!) not the best way to achieve
1206 // this. We should probably have a more principled approach to layout
1207 // cleanup code.
1208 //
1209 // The goal is to get:
1210 //
1211 // +--------------------------+
1212 // | V
1213 // InnerLp -> InnerCleanup OuterLp -> OuterCleanup -> Resume
1214 //
1215 // Rather than:
1216 //
1217 // +-------------------------------------+
1218 // V |
1219 // OuterLp -> OuterCleanup -> Resume InnerLp -> InnerCleanup
1220 if (BestBlock && (IsEHPad ^ (BestFreq >= CandidateFreq)))
Chandler Carruthf9213fe2011-11-13 11:42:26 +00001221 continue;
Amaury Sechetc53ad4f2016-04-07 21:29:39 +00001222
Chandler Carruth7a715da2015-03-05 03:19:05 +00001223 BestBlock = MBB;
Chandler Carruthf9213fe2011-11-13 11:42:26 +00001224 BestFreq = CandidateFreq;
1225 }
Amaury Sechetc53ad4f2016-04-07 21:29:39 +00001226
Chandler Carruthf9213fe2011-11-13 11:42:26 +00001227 return BestBlock;
1228}
1229
Chandler Carruth1071cfa2011-11-14 00:00:35 +00001230/// \brief Retrieve the first unplaced basic block.
1231///
1232/// This routine is called when we are unable to use the CFG to walk through
1233/// all of the basic blocks and form a chain due to unnatural loops in the CFG.
Chandler Carruth9b548a7f2011-11-15 06:26:43 +00001234/// We walk through the function's blocks in order, starting from the
1235/// LastUnplacedBlockIt. We update this iterator on each call to avoid
1236/// re-scanning the entire sequence on repeated calls to this routine.
Chandler Carruth1071cfa2011-11-14 00:00:35 +00001237MachineBasicBlock *MachineBlockPlacement::getFirstUnplacedBlock(
Xinliang David Li52530a72016-06-13 22:23:44 +00001238 const BlockChain &PlacedChain,
Chandler Carruth9b548a7f2011-11-15 06:26:43 +00001239 MachineFunction::iterator &PrevUnplacedBlockIt,
Jakub Staszak90616162011-12-21 23:02:08 +00001240 const BlockFilterSet *BlockFilter) {
Xinliang David Li52530a72016-06-13 22:23:44 +00001241 for (MachineFunction::iterator I = PrevUnplacedBlockIt, E = F->end(); I != E;
Chandler Carruth9b548a7f2011-11-15 06:26:43 +00001242 ++I) {
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +00001243 if (BlockFilter && !BlockFilter->count(&*I))
Chandler Carruth9b548a7f2011-11-15 06:26:43 +00001244 continue;
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +00001245 if (BlockToChain[&*I] != &PlacedChain) {
Chandler Carruth9b548a7f2011-11-15 06:26:43 +00001246 PrevUnplacedBlockIt = I;
Chandler Carruth4a87aa02011-11-23 03:03:21 +00001247 // Now select the head of the chain to which the unplaced block belongs
1248 // as the block to place. This will force the entire chain to be placed,
1249 // and satisfies the requirements of merging chains.
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +00001250 return *BlockToChain[&*I]->begin();
Chandler Carruth1071cfa2011-11-14 00:00:35 +00001251 }
1252 }
Craig Topperc0196b12014-04-14 00:51:57 +00001253 return nullptr;
Chandler Carruth1071cfa2011-11-14 00:00:35 +00001254}
1255
Amaury Secheteae09c22016-03-14 21:24:11 +00001256void MachineBlockPlacement::fillWorkLists(
Kyle Butte9425c4f2017-02-04 02:26:32 +00001257 const MachineBasicBlock *MBB,
Amaury Secheteae09c22016-03-14 21:24:11 +00001258 SmallPtrSetImpl<BlockChain *> &UpdatedPreds,
Amaury Secheteae09c22016-03-14 21:24:11 +00001259 const BlockFilterSet *BlockFilter = nullptr) {
1260 BlockChain &Chain = *BlockToChain[MBB];
1261 if (!UpdatedPreds.insert(&Chain).second)
1262 return;
1263
1264 assert(Chain.UnscheduledPredecessors == 0);
1265 for (MachineBasicBlock *ChainBB : Chain) {
1266 assert(BlockToChain[ChainBB] == &Chain);
1267 for (MachineBasicBlock *Pred : ChainBB->predecessors()) {
1268 if (BlockFilter && !BlockFilter->count(Pred))
1269 continue;
1270 if (BlockToChain[Pred] == &Chain)
1271 continue;
1272 ++Chain.UnscheduledPredecessors;
1273 }
1274 }
1275
Amaury Sechetc53ad4f2016-04-07 21:29:39 +00001276 if (Chain.UnscheduledPredecessors != 0)
1277 return;
1278
Kyle Butte9425c4f2017-02-04 02:26:32 +00001279 MachineBasicBlock *BB = *Chain.begin();
1280 if (BB->isEHPad())
1281 EHPadWorkList.push_back(BB);
Amaury Sechetc53ad4f2016-04-07 21:29:39 +00001282 else
Kyle Butte9425c4f2017-02-04 02:26:32 +00001283 BlockWorkList.push_back(BB);
Amaury Secheteae09c22016-03-14 21:24:11 +00001284}
1285
Chandler Carruth8d150782011-11-13 11:20:44 +00001286void MachineBlockPlacement::buildChain(
Kyle Butte9425c4f2017-02-04 02:26:32 +00001287 const MachineBasicBlock *HeadBB, BlockChain &Chain,
Kyle Butt0846e562016-10-11 20:36:43 +00001288 BlockFilterSet *BlockFilter) {
Kyle Butte9425c4f2017-02-04 02:26:32 +00001289 assert(HeadBB && "BB must not be null.\n");
1290 assert(BlockToChain[HeadBB] == &Chain && "BlockToChainMap mis-match.\n");
Xinliang David Li52530a72016-06-13 22:23:44 +00001291 MachineFunction::iterator PrevUnplacedBlockIt = F->begin();
Chandler Carruth1071cfa2011-11-14 00:00:35 +00001292
Kyle Butte9425c4f2017-02-04 02:26:32 +00001293 const MachineBasicBlock *LoopHeaderBB = HeadBB;
Xinliang David Li93926ac2016-07-01 05:46:48 +00001294 markChainSuccessors(Chain, LoopHeaderBB, BlockFilter);
Kyle Butte9425c4f2017-02-04 02:26:32 +00001295 MachineBasicBlock *BB = *std::prev(Chain.end());
Chandler Carruth8d150782011-11-13 11:20:44 +00001296 for (;;) {
Kyle Butt82c22902016-06-28 22:50:54 +00001297 assert(BB && "null block found at end of chain in loop.");
1298 assert(BlockToChain[BB] == &Chain && "BlockToChainMap mis-match in loop.");
1299 assert(*std::prev(Chain.end()) == BB && "BB Not found at end of chain.");
1300
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00001301
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +00001302 // Look for the best viable successor if there is one to place immediately
1303 // after this block.
Kyle Buttb15c0662017-01-31 23:48:32 +00001304 auto Result = selectBestSuccessor(BB, Chain, BlockFilter);
1305 MachineBasicBlock* BestSucc = Result.BB;
1306 bool ShouldTailDup = Result.ShouldTailDup;
1307 if (TailDupPlacement)
1308 ShouldTailDup |= (BestSucc && shouldTailDuplicate(BestSucc));
Chandler Carruth8d150782011-11-13 11:20:44 +00001309
1310 // If an immediate successor isn't available, look for the best viable
1311 // block among those we've identified as not violating the loop's CFG at
1312 // this point. This won't be a fallthrough, but it will increase locality.
Chandler Carruthf9213fe2011-11-13 11:42:26 +00001313 if (!BestSucc)
Amaury Sechet9ee4ddd2016-04-07 06:34:47 +00001314 BestSucc = selectBestCandidateBlock(Chain, BlockWorkList);
Amaury Sechetc53ad4f2016-04-07 21:29:39 +00001315 if (!BestSucc)
1316 BestSucc = selectBestCandidateBlock(Chain, EHPadWorkList);
Chandler Carruth8d150782011-11-13 11:20:44 +00001317
Chandler Carruth8d150782011-11-13 11:20:44 +00001318 if (!BestSucc) {
Xinliang David Li52530a72016-06-13 22:23:44 +00001319 BestSucc = getFirstUnplacedBlock(Chain, PrevUnplacedBlockIt, BlockFilter);
Chandler Carruth1071cfa2011-11-14 00:00:35 +00001320 if (!BestSucc)
1321 break;
1322
1323 DEBUG(dbgs() << "Unnatural loop CFG detected, forcibly merging the "
1324 "layout successor until the CFG reduces\n");
Chandler Carruth8d150782011-11-13 11:20:44 +00001325 }
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00001326
Kyle Butt0846e562016-10-11 20:36:43 +00001327 // Placement may have changed tail duplication opportunities.
1328 // Check for that now.
Kyle Buttb15c0662017-01-31 23:48:32 +00001329 if (TailDupPlacement && BestSucc && ShouldTailDup) {
Kyle Butt0846e562016-10-11 20:36:43 +00001330 // If the chosen successor was duplicated into all its predecessors,
1331 // don't bother laying it out, just go round the loop again with BB as
1332 // the chain end.
1333 if (repeatedlyTailDuplicateBlock(BestSucc, BB, LoopHeaderBB, Chain,
1334 BlockFilter, PrevUnplacedBlockIt))
1335 continue;
1336 }
1337
Chandler Carruth8d150782011-11-13 11:20:44 +00001338 // Place this block, updating the datastructures to reflect its placement.
Jakub Staszak90616162011-12-21 23:02:08 +00001339 BlockChain &SuccChain = *BlockToChain[BestSucc];
Philip Reamesae27b232016-03-03 00:58:43 +00001340 // Zero out UnscheduledPredecessors for the successor we're about to merge in case
Chandler Carruth1071cfa2011-11-14 00:00:35 +00001341 // we selected a successor that didn't fit naturally into the CFG.
Philip Reamesae27b232016-03-03 00:58:43 +00001342 SuccChain.UnscheduledPredecessors = 0;
Philip Reamesb9688f42016-03-02 21:45:13 +00001343 DEBUG(dbgs() << "Merging from " << getBlockName(BB) << " to "
1344 << getBlockName(BestSucc) << "\n");
Xinliang David Li93926ac2016-07-01 05:46:48 +00001345 markChainSuccessors(SuccChain, LoopHeaderBB, BlockFilter);
Chandler Carruth8d150782011-11-13 11:20:44 +00001346 Chain.merge(BestSucc, &SuccChain);
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001347 BB = *std::prev(Chain.end());
Jakub Staszak190c7122011-12-07 19:46:10 +00001348 }
Chandler Carruth1071cfa2011-11-14 00:00:35 +00001349
1350 DEBUG(dbgs() << "Finished forming chain for header block "
Philip Reamesb9688f42016-03-02 21:45:13 +00001351 << getBlockName(*Chain.begin()) << "\n");
Chandler Carruth10281422011-10-21 06:46:38 +00001352}
1353
Chandler Carruth03adbd42011-11-27 13:34:33 +00001354/// \brief Find the best loop top block for layout.
Chandler Carruth9ffb97e2011-11-27 00:38:03 +00001355///
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001356/// Look for a block which is strictly better than the loop header for laying
1357/// out at the top of the loop. This looks for one and only one pattern:
1358/// a latch block with no conditional exit. This block will cause a conditional
1359/// jump around it or will be the bottom of the loop if we lay it out in place,
1360/// but if it it doesn't end up at the bottom of the loop for any reason,
1361/// rotation alone won't fix it. Because such a block will always result in an
1362/// unconditional jump (for the backedge) rotating it in front of the loop
1363/// header is always profitable.
1364MachineBasicBlock *
Kyle Butte9425c4f2017-02-04 02:26:32 +00001365MachineBlockPlacement::findBestLoopTop(const MachineLoop &L,
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001366 const BlockFilterSet &LoopBlockSet) {
Sjoerd Meijer15c81b02016-08-16 19:50:33 +00001367 // Placing the latch block before the header may introduce an extra branch
1368 // that skips this block the first time the loop is executed, which we want
1369 // to avoid when optimising for size.
1370 // FIXME: in theory there is a case that does not introduce a new branch,
1371 // i.e. when the layout predecessor does not fallthrough to the loop header.
1372 // In practice this never happens though: there always seems to be a preheader
1373 // that can fallthrough and that is also placed before the header.
1374 if (F->getFunction()->optForSize())
1375 return L.getHeader();
1376
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001377 // Check that the header hasn't been fused with a preheader block due to
1378 // crazy branches. If it has, we need to start with the header at the top to
1379 // prevent pulling the preheader into the loop body.
1380 BlockChain &HeaderChain = *BlockToChain[L.getHeader()];
1381 if (!LoopBlockSet.count(*HeaderChain.begin()))
1382 return L.getHeader();
1383
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001384 DEBUG(dbgs() << "Finding best loop top for: " << getBlockName(L.getHeader())
1385 << "\n");
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001386
1387 BlockFrequency BestPredFreq;
Craig Topperc0196b12014-04-14 00:51:57 +00001388 MachineBasicBlock *BestPred = nullptr;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001389 for (MachineBasicBlock *Pred : L.getHeader()->predecessors()) {
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001390 if (!LoopBlockSet.count(Pred))
1391 continue;
Sjoerd Meijer5e11a182016-07-27 08:49:23 +00001392 DEBUG(dbgs() << " header pred: " << getBlockName(Pred) << ", has "
Michael Gottesmanb78dec82013-12-14 00:25:45 +00001393 << Pred->succ_size() << " successors, ";
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001394 MBFI->printBlockFreq(dbgs(), Pred) << " freq\n");
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001395 if (Pred->succ_size() > 1)
1396 continue;
1397
1398 BlockFrequency PredFreq = MBFI->getBlockFreq(Pred);
1399 if (!BestPred || PredFreq > BestPredFreq ||
1400 (!(PredFreq < BestPredFreq) &&
1401 Pred->isLayoutSuccessor(L.getHeader()))) {
1402 BestPred = Pred;
1403 BestPredFreq = PredFreq;
1404 }
1405 }
1406
1407 // If no direct predecessor is fine, just use the loop header.
Philip Reamesb9688f42016-03-02 21:45:13 +00001408 if (!BestPred) {
1409 DEBUG(dbgs() << " final top unchanged\n");
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001410 return L.getHeader();
Philip Reamesb9688f42016-03-02 21:45:13 +00001411 }
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001412
1413 // Walk backwards through any straight line of predecessors.
1414 while (BestPred->pred_size() == 1 &&
1415 (*BestPred->pred_begin())->succ_size() == 1 &&
1416 *BestPred->pred_begin() != L.getHeader())
1417 BestPred = *BestPred->pred_begin();
1418
1419 DEBUG(dbgs() << " final top: " << getBlockName(BestPred) << "\n");
1420 return BestPred;
1421}
1422
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001423/// \brief Find the best loop exiting block for layout.
1424///
Chandler Carruth03adbd42011-11-27 13:34:33 +00001425/// This routine implements the logic to analyze the loop looking for the best
1426/// block to layout at the top of the loop. Typically this is done to maximize
1427/// fallthrough opportunities.
1428MachineBasicBlock *
Kyle Butte9425c4f2017-02-04 02:26:32 +00001429MachineBlockPlacement::findBestLoopExit(const MachineLoop &L,
Chandler Carruthccc7e422012-04-16 01:12:56 +00001430 const BlockFilterSet &LoopBlockSet) {
Chandler Carruth68062612012-04-10 13:35:57 +00001431 // We don't want to layout the loop linearly in all cases. If the loop header
1432 // is just a normal basic block in the loop, we want to look for what block
1433 // within the loop is the best one to layout at the top. However, if the loop
1434 // header has be pre-merged into a chain due to predecessors not having
1435 // analyzable branches, *and* the predecessor it is merged with is *not* part
1436 // of the loop, rotating the header into the middle of the loop will create
1437 // a non-contiguous range of blocks which is Very Bad. So start with the
1438 // header and only rotate if safe.
1439 BlockChain &HeaderChain = *BlockToChain[L.getHeader()];
1440 if (!LoopBlockSet.count(*HeaderChain.begin()))
Craig Topperc0196b12014-04-14 00:51:57 +00001441 return nullptr;
Chandler Carruth68062612012-04-10 13:35:57 +00001442
Chandler Carruth03adbd42011-11-27 13:34:33 +00001443 BlockFrequency BestExitEdgeFreq;
Chandler Carruthccc7e422012-04-16 01:12:56 +00001444 unsigned BestExitLoopDepth = 0;
Craig Topperc0196b12014-04-14 00:51:57 +00001445 MachineBasicBlock *ExitingBB = nullptr;
Chandler Carruth4f567202011-11-27 20:18:00 +00001446 // If there are exits to outer loops, loop rotation can severely limit
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00001447 // fallthrough opportunities unless it selects such an exit. Keep a set of
Chandler Carruth4f567202011-11-27 20:18:00 +00001448 // blocks where rotating to exit with that block will reach an outer loop.
1449 SmallPtrSet<MachineBasicBlock *, 4> BlocksExitingToOuterLoop;
1450
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001451 DEBUG(dbgs() << "Finding best loop exit for: " << getBlockName(L.getHeader())
1452 << "\n");
Chandler Carruth7a715da2015-03-05 03:19:05 +00001453 for (MachineBasicBlock *MBB : L.getBlocks()) {
1454 BlockChain &Chain = *BlockToChain[MBB];
Chandler Carruth03adbd42011-11-27 13:34:33 +00001455 // Ensure that this block is at the end of a chain; otherwise it could be
Chandler Carruth9a512a42015-04-15 13:19:54 +00001456 // mid-way through an inner loop or a successor of an unanalyzable branch.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001457 if (MBB != *std::prev(Chain.end()))
Chandler Carruth9ffb97e2011-11-27 00:38:03 +00001458 continue;
Chandler Carruth9ffb97e2011-11-27 00:38:03 +00001459
Chandler Carruth03adbd42011-11-27 13:34:33 +00001460 // Now walk the successors. We need to establish whether this has a viable
1461 // exiting successor and whether it has a viable non-exiting successor.
1462 // We store the old exiting state and restore it if a viable looping
1463 // successor isn't found.
1464 MachineBasicBlock *OldExitingBB = ExitingBB;
1465 BlockFrequency OldBestExitEdgeFreq = BestExitEdgeFreq;
Chandler Carruthccc7e422012-04-16 01:12:56 +00001466 bool HasLoopingSucc = false;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001467 for (MachineBasicBlock *Succ : MBB->successors()) {
Reid Kleckner0e288232015-08-27 23:27:47 +00001468 if (Succ->isEHPad())
Chandler Carruth03adbd42011-11-27 13:34:33 +00001469 continue;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001470 if (Succ == MBB)
Chandler Carruth03adbd42011-11-27 13:34:33 +00001471 continue;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001472 BlockChain &SuccChain = *BlockToChain[Succ];
Chandler Carruth03adbd42011-11-27 13:34:33 +00001473 // Don't split chains, either this chain or the successor's chain.
Chandler Carruthccc7e422012-04-16 01:12:56 +00001474 if (&Chain == &SuccChain) {
Chandler Carruth7a715da2015-03-05 03:19:05 +00001475 DEBUG(dbgs() << " exiting: " << getBlockName(MBB) << " -> "
1476 << getBlockName(Succ) << " (chain conflict)\n");
Chandler Carruth03adbd42011-11-27 13:34:33 +00001477 continue;
1478 }
1479
Cong Houd97c1002015-12-01 05:29:22 +00001480 auto SuccProb = MBPI->getEdgeProbability(MBB, Succ);
Chandler Carruth7a715da2015-03-05 03:19:05 +00001481 if (LoopBlockSet.count(Succ)) {
1482 DEBUG(dbgs() << " looping: " << getBlockName(MBB) << " -> "
Cong Houd97c1002015-12-01 05:29:22 +00001483 << getBlockName(Succ) << " (" << SuccProb << ")\n");
Chandler Carruthccc7e422012-04-16 01:12:56 +00001484 HasLoopingSucc = true;
Chandler Carruth03adbd42011-11-27 13:34:33 +00001485 continue;
1486 }
1487
Chandler Carruthccc7e422012-04-16 01:12:56 +00001488 unsigned SuccLoopDepth = 0;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001489 if (MachineLoop *ExitLoop = MLI->getLoopFor(Succ)) {
Chandler Carruthccc7e422012-04-16 01:12:56 +00001490 SuccLoopDepth = ExitLoop->getLoopDepth();
1491 if (ExitLoop->contains(&L))
Chandler Carruth7a715da2015-03-05 03:19:05 +00001492 BlocksExitingToOuterLoop.insert(MBB);
Chandler Carruthccc7e422012-04-16 01:12:56 +00001493 }
1494
Chandler Carruth7a715da2015-03-05 03:19:05 +00001495 BlockFrequency ExitEdgeFreq = MBFI->getBlockFreq(MBB) * SuccProb;
1496 DEBUG(dbgs() << " exiting: " << getBlockName(MBB) << " -> "
1497 << getBlockName(Succ) << " [L:" << SuccLoopDepth << "] (";
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001498 MBFI->printBlockFreq(dbgs(), ExitEdgeFreq) << ")\n");
Benjamin Kramerc8160d62013-11-20 19:08:44 +00001499 // Note that we bias this toward an existing layout successor to retain
1500 // incoming order in the absence of better information. The exit must have
1501 // a frequency higher than the current exit before we consider breaking
1502 // the layout.
1503 BranchProbability Bias(100 - ExitBlockBias, 100);
Chandler Carruth26d30172015-04-15 13:39:42 +00001504 if (!ExitingBB || SuccLoopDepth > BestExitLoopDepth ||
Chandler Carruthccc7e422012-04-16 01:12:56 +00001505 ExitEdgeFreq > BestExitEdgeFreq ||
Chandler Carruth7a715da2015-03-05 03:19:05 +00001506 (MBB->isLayoutSuccessor(Succ) &&
Benjamin Kramerc8160d62013-11-20 19:08:44 +00001507 !(ExitEdgeFreq < BestExitEdgeFreq * Bias))) {
Chandler Carruth03adbd42011-11-27 13:34:33 +00001508 BestExitEdgeFreq = ExitEdgeFreq;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001509 ExitingBB = MBB;
Chandler Carrutha0545802011-11-27 09:22:53 +00001510 }
Chandler Carruth9ffb97e2011-11-27 00:38:03 +00001511 }
Chandler Carruth03adbd42011-11-27 13:34:33 +00001512
Chandler Carruthccc7e422012-04-16 01:12:56 +00001513 if (!HasLoopingSucc) {
Chandler Carruthcfb2b9d2015-04-15 13:26:41 +00001514 // Restore the old exiting state, no viable looping successor was found.
Chandler Carruth03adbd42011-11-27 13:34:33 +00001515 ExitingBB = OldExitingBB;
1516 BestExitEdgeFreq = OldBestExitEdgeFreq;
Chandler Carruth03adbd42011-11-27 13:34:33 +00001517 }
Chandler Carruth9ffb97e2011-11-27 00:38:03 +00001518 }
Chandler Carruthccc7e422012-04-16 01:12:56 +00001519 // Without a candidate exiting block or with only a single block in the
Chandler Carruth03adbd42011-11-27 13:34:33 +00001520 // loop, just use the loop header to layout the loop.
Sjoerd Meijer5e11a182016-07-27 08:49:23 +00001521 if (!ExitingBB) {
1522 DEBUG(dbgs() << " No other candidate exit blocks, using loop header\n");
Craig Topperc0196b12014-04-14 00:51:57 +00001523 return nullptr;
Sjoerd Meijer5e11a182016-07-27 08:49:23 +00001524 }
1525 if (L.getNumBlocks() == 1) {
1526 DEBUG(dbgs() << " Loop has 1 block, using loop header as exit\n");
1527 return nullptr;
1528 }
Chandler Carruth9ffb97e2011-11-27 00:38:03 +00001529
Chandler Carruth4f567202011-11-27 20:18:00 +00001530 // Also, if we have exit blocks which lead to outer loops but didn't select
1531 // one of them as the exiting block we are rotating toward, disable loop
1532 // rotation altogether.
1533 if (!BlocksExitingToOuterLoop.empty() &&
1534 !BlocksExitingToOuterLoop.count(ExitingBB))
Craig Topperc0196b12014-04-14 00:51:57 +00001535 return nullptr;
Chandler Carruth4f567202011-11-27 20:18:00 +00001536
Chandler Carruth03adbd42011-11-27 13:34:33 +00001537 DEBUG(dbgs() << " Best exiting block: " << getBlockName(ExitingBB) << "\n");
Chandler Carruthccc7e422012-04-16 01:12:56 +00001538 return ExitingBB;
Chandler Carruth9ffb97e2011-11-27 00:38:03 +00001539}
1540
Chandler Carruth8c74c7b2012-04-16 09:31:23 +00001541/// \brief Attempt to rotate an exiting block to the bottom of the loop.
1542///
1543/// Once we have built a chain, try to rotate it to line up the hot exit block
1544/// with fallthrough out of the loop if doing so doesn't introduce unnecessary
1545/// branches. For example, if the loop has fallthrough into its header and out
1546/// of its bottom already, don't rotate it.
1547void MachineBlockPlacement::rotateLoop(BlockChain &LoopChain,
Kyle Butte9425c4f2017-02-04 02:26:32 +00001548 const MachineBasicBlock *ExitingBB,
Chandler Carruth8c74c7b2012-04-16 09:31:23 +00001549 const BlockFilterSet &LoopBlockSet) {
1550 if (!ExitingBB)
1551 return;
1552
1553 MachineBasicBlock *Top = *LoopChain.begin();
1554 bool ViableTopFallthrough = false;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001555 for (MachineBasicBlock *Pred : Top->predecessors()) {
1556 BlockChain *PredChain = BlockToChain[Pred];
1557 if (!LoopBlockSet.count(Pred) &&
1558 (!PredChain || Pred == *std::prev(PredChain->end()))) {
Chandler Carruth8c74c7b2012-04-16 09:31:23 +00001559 ViableTopFallthrough = true;
1560 break;
1561 }
1562 }
1563
1564 // If the header has viable fallthrough, check whether the current loop
1565 // bottom is a viable exiting block. If so, bail out as rotating will
1566 // introduce an unnecessary branch.
1567 if (ViableTopFallthrough) {
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001568 MachineBasicBlock *Bottom = *std::prev(LoopChain.end());
Chandler Carruth7a715da2015-03-05 03:19:05 +00001569 for (MachineBasicBlock *Succ : Bottom->successors()) {
1570 BlockChain *SuccChain = BlockToChain[Succ];
1571 if (!LoopBlockSet.count(Succ) &&
1572 (!SuccChain || Succ == *SuccChain->begin()))
Chandler Carruth8c74c7b2012-04-16 09:31:23 +00001573 return;
1574 }
1575 }
1576
David Majnemer0d955d02016-08-11 22:21:41 +00001577 BlockChain::iterator ExitIt = find(LoopChain, ExitingBB);
Chandler Carruth8c74c7b2012-04-16 09:31:23 +00001578 if (ExitIt == LoopChain.end())
1579 return;
1580
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001581 std::rotate(LoopChain.begin(), std::next(ExitIt), LoopChain.end());
Chandler Carruth8c74c7b2012-04-16 09:31:23 +00001582}
1583
Cong Hou7745dbc2015-10-19 23:16:40 +00001584/// \brief Attempt to rotate a loop based on profile data to reduce branch cost.
1585///
1586/// With profile data, we can determine the cost in terms of missed fall through
1587/// opportunities when rotating a loop chain and select the best rotation.
1588/// Basically, there are three kinds of cost to consider for each rotation:
1589/// 1. The possibly missed fall through edge (if it exists) from BB out of
1590/// the loop to the loop header.
1591/// 2. The possibly missed fall through edges (if they exist) from the loop
1592/// exits to BB out of the loop.
1593/// 3. The missed fall through edge (if it exists) from the last BB to the
1594/// first BB in the loop chain.
1595/// Therefore, the cost for a given rotation is the sum of costs listed above.
1596/// We select the best rotation with the smallest cost.
1597void MachineBlockPlacement::rotateLoopWithProfile(
Kyle Butte9425c4f2017-02-04 02:26:32 +00001598 BlockChain &LoopChain, const MachineLoop &L,
1599 const BlockFilterSet &LoopBlockSet) {
Cong Hou7745dbc2015-10-19 23:16:40 +00001600 auto HeaderBB = L.getHeader();
David Majnemer0d955d02016-08-11 22:21:41 +00001601 auto HeaderIter = find(LoopChain, HeaderBB);
Cong Hou7745dbc2015-10-19 23:16:40 +00001602 auto RotationPos = LoopChain.end();
1603
1604 BlockFrequency SmallestRotationCost = BlockFrequency::getMaxFrequency();
1605
1606 // A utility lambda that scales up a block frequency by dividing it by a
1607 // branch probability which is the reciprocal of the scale.
1608 auto ScaleBlockFrequency = [](BlockFrequency Freq,
1609 unsigned Scale) -> BlockFrequency {
1610 if (Scale == 0)
1611 return 0;
1612 // Use operator / between BlockFrequency and BranchProbability to implement
1613 // saturating multiplication.
1614 return Freq / BranchProbability(1, Scale);
1615 };
1616
1617 // Compute the cost of the missed fall-through edge to the loop header if the
1618 // chain head is not the loop header. As we only consider natural loops with
1619 // single header, this computation can be done only once.
1620 BlockFrequency HeaderFallThroughCost(0);
1621 for (auto *Pred : HeaderBB->predecessors()) {
1622 BlockChain *PredChain = BlockToChain[Pred];
1623 if (!LoopBlockSet.count(Pred) &&
1624 (!PredChain || Pred == *std::prev(PredChain->end()))) {
1625 auto EdgeFreq =
1626 MBFI->getBlockFreq(Pred) * MBPI->getEdgeProbability(Pred, HeaderBB);
1627 auto FallThruCost = ScaleBlockFrequency(EdgeFreq, MisfetchCost);
1628 // If the predecessor has only an unconditional jump to the header, we
1629 // need to consider the cost of this jump.
1630 if (Pred->succ_size() == 1)
1631 FallThruCost += ScaleBlockFrequency(EdgeFreq, JumpInstCost);
1632 HeaderFallThroughCost = std::max(HeaderFallThroughCost, FallThruCost);
1633 }
1634 }
1635
1636 // Here we collect all exit blocks in the loop, and for each exit we find out
1637 // its hottest exit edge. For each loop rotation, we define the loop exit cost
1638 // as the sum of frequencies of exit edges we collect here, excluding the exit
1639 // edge from the tail of the loop chain.
1640 SmallVector<std::pair<MachineBasicBlock *, BlockFrequency>, 4> ExitsWithFreq;
1641 for (auto BB : LoopChain) {
Cong Houd97c1002015-12-01 05:29:22 +00001642 auto LargestExitEdgeProb = BranchProbability::getZero();
Cong Hou7745dbc2015-10-19 23:16:40 +00001643 for (auto *Succ : BB->successors()) {
1644 BlockChain *SuccChain = BlockToChain[Succ];
1645 if (!LoopBlockSet.count(Succ) &&
1646 (!SuccChain || Succ == *SuccChain->begin())) {
Cong Houd97c1002015-12-01 05:29:22 +00001647 auto SuccProb = MBPI->getEdgeProbability(BB, Succ);
1648 LargestExitEdgeProb = std::max(LargestExitEdgeProb, SuccProb);
Cong Hou7745dbc2015-10-19 23:16:40 +00001649 }
1650 }
Cong Houd97c1002015-12-01 05:29:22 +00001651 if (LargestExitEdgeProb > BranchProbability::getZero()) {
1652 auto ExitFreq = MBFI->getBlockFreq(BB) * LargestExitEdgeProb;
Cong Hou7745dbc2015-10-19 23:16:40 +00001653 ExitsWithFreq.emplace_back(BB, ExitFreq);
1654 }
1655 }
1656
1657 // In this loop we iterate every block in the loop chain and calculate the
1658 // cost assuming the block is the head of the loop chain. When the loop ends,
1659 // we should have found the best candidate as the loop chain's head.
1660 for (auto Iter = LoopChain.begin(), TailIter = std::prev(LoopChain.end()),
1661 EndIter = LoopChain.end();
1662 Iter != EndIter; Iter++, TailIter++) {
1663 // TailIter is used to track the tail of the loop chain if the block we are
1664 // checking (pointed by Iter) is the head of the chain.
1665 if (TailIter == LoopChain.end())
1666 TailIter = LoopChain.begin();
1667
1668 auto TailBB = *TailIter;
1669
1670 // Calculate the cost by putting this BB to the top.
1671 BlockFrequency Cost = 0;
1672
1673 // If the current BB is the loop header, we need to take into account the
1674 // cost of the missed fall through edge from outside of the loop to the
1675 // header.
1676 if (Iter != HeaderIter)
1677 Cost += HeaderFallThroughCost;
1678
1679 // Collect the loop exit cost by summing up frequencies of all exit edges
1680 // except the one from the chain tail.
1681 for (auto &ExitWithFreq : ExitsWithFreq)
1682 if (TailBB != ExitWithFreq.first)
1683 Cost += ExitWithFreq.second;
1684
1685 // The cost of breaking the once fall-through edge from the tail to the top
1686 // of the loop chain. Here we need to consider three cases:
1687 // 1. If the tail node has only one successor, then we will get an
1688 // additional jmp instruction. So the cost here is (MisfetchCost +
1689 // JumpInstCost) * tail node frequency.
1690 // 2. If the tail node has two successors, then we may still get an
1691 // additional jmp instruction if the layout successor after the loop
1692 // chain is not its CFG successor. Note that the more frequently executed
1693 // jmp instruction will be put ahead of the other one. Assume the
1694 // frequency of those two branches are x and y, where x is the frequency
1695 // of the edge to the chain head, then the cost will be
1696 // (x * MisfetechCost + min(x, y) * JumpInstCost) * tail node frequency.
1697 // 3. If the tail node has more than two successors (this rarely happens),
1698 // we won't consider any additional cost.
1699 if (TailBB->isSuccessor(*Iter)) {
1700 auto TailBBFreq = MBFI->getBlockFreq(TailBB);
1701 if (TailBB->succ_size() == 1)
1702 Cost += ScaleBlockFrequency(TailBBFreq.getFrequency(),
1703 MisfetchCost + JumpInstCost);
1704 else if (TailBB->succ_size() == 2) {
1705 auto TailToHeadProb = MBPI->getEdgeProbability(TailBB, *Iter);
1706 auto TailToHeadFreq = TailBBFreq * TailToHeadProb;
1707 auto ColderEdgeFreq = TailToHeadProb > BranchProbability(1, 2)
1708 ? TailBBFreq * TailToHeadProb.getCompl()
1709 : TailToHeadFreq;
1710 Cost += ScaleBlockFrequency(TailToHeadFreq, MisfetchCost) +
1711 ScaleBlockFrequency(ColderEdgeFreq, JumpInstCost);
1712 }
1713 }
1714
Philip Reamesb9688f42016-03-02 21:45:13 +00001715 DEBUG(dbgs() << "The cost of loop rotation by making " << getBlockName(*Iter)
Cong Hou7745dbc2015-10-19 23:16:40 +00001716 << " to the top: " << Cost.getFrequency() << "\n");
1717
1718 if (Cost < SmallestRotationCost) {
1719 SmallestRotationCost = Cost;
1720 RotationPos = Iter;
1721 }
1722 }
1723
1724 if (RotationPos != LoopChain.end()) {
Philip Reamesb9688f42016-03-02 21:45:13 +00001725 DEBUG(dbgs() << "Rotate loop by making " << getBlockName(*RotationPos)
Cong Hou7745dbc2015-10-19 23:16:40 +00001726 << " to the top\n");
1727 std::rotate(LoopChain.begin(), RotationPos, LoopChain.end());
1728 }
1729}
1730
Cong Houb90b9e02015-11-02 21:24:00 +00001731/// \brief Collect blocks in the given loop that are to be placed.
1732///
1733/// When profile data is available, exclude cold blocks from the returned set;
1734/// otherwise, collect all blocks in the loop.
1735MachineBlockPlacement::BlockFilterSet
Kyle Butte9425c4f2017-02-04 02:26:32 +00001736MachineBlockPlacement::collectLoopBlockSet(const MachineLoop &L) {
Cong Houb90b9e02015-11-02 21:24:00 +00001737 BlockFilterSet LoopBlockSet;
1738
1739 // Filter cold blocks off from LoopBlockSet when profile data is available.
1740 // Collect the sum of frequencies of incoming edges to the loop header from
1741 // outside. If we treat the loop as a super block, this is the frequency of
1742 // the loop. Then for each block in the loop, we calculate the ratio between
1743 // its frequency and the frequency of the loop block. When it is too small,
1744 // don't add it to the loop chain. If there are outer loops, then this block
1745 // will be merged into the first outer loop chain for which this block is not
1746 // cold anymore. This needs precise profile data and we only do this when
1747 // profile data is available.
Xinliang David Li52530a72016-06-13 22:23:44 +00001748 if (F->getFunction()->getEntryCount()) {
Cong Houb90b9e02015-11-02 21:24:00 +00001749 BlockFrequency LoopFreq(0);
1750 for (auto LoopPred : L.getHeader()->predecessors())
1751 if (!L.contains(LoopPred))
1752 LoopFreq += MBFI->getBlockFreq(LoopPred) *
1753 MBPI->getEdgeProbability(LoopPred, L.getHeader());
1754
1755 for (MachineBasicBlock *LoopBB : L.getBlocks()) {
1756 auto Freq = MBFI->getBlockFreq(LoopBB).getFrequency();
1757 if (Freq == 0 || LoopFreq.getFrequency() / Freq > LoopToColdBlockRatio)
1758 continue;
1759 LoopBlockSet.insert(LoopBB);
1760 }
1761 } else
1762 LoopBlockSet.insert(L.block_begin(), L.block_end());
1763
1764 return LoopBlockSet;
1765}
1766
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00001767/// \brief Forms basic block chains from the natural loop structures.
Chandler Carruth10281422011-10-21 06:46:38 +00001768///
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00001769/// These chains are designed to preserve the existing *structure* of the code
1770/// as much as possible. We can then stitch the chains together in a way which
1771/// both preserves the topological structure and minimizes taken conditional
1772/// branches.
Kyle Butte9425c4f2017-02-04 02:26:32 +00001773void MachineBlockPlacement::buildLoopChains(const MachineLoop &L) {
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00001774 // First recurse through any nested loops, building chains for those inner
1775 // loops.
Kyle Butte9425c4f2017-02-04 02:26:32 +00001776 for (const MachineLoop *InnerLoop : L)
Xinliang David Li52530a72016-06-13 22:23:44 +00001777 buildLoopChains(*InnerLoop);
Chandler Carruth10281422011-10-21 06:46:38 +00001778
Xinliang David Li93926ac2016-07-01 05:46:48 +00001779 assert(BlockWorkList.empty());
1780 assert(EHPadWorkList.empty());
Xinliang David Li52530a72016-06-13 22:23:44 +00001781 BlockFilterSet LoopBlockSet = collectLoopBlockSet(L);
Chandler Carruth03adbd42011-11-27 13:34:33 +00001782
Cong Hou7745dbc2015-10-19 23:16:40 +00001783 // Check if we have profile data for this function. If yes, we will rotate
1784 // this loop by modeling costs more precisely which requires the profile data
1785 // for better layout.
1786 bool RotateLoopWithProfile =
Xinliang David Lif0ab6df2016-05-12 02:04:41 +00001787 ForcePreciseRotationCost ||
Xinliang David Li52530a72016-06-13 22:23:44 +00001788 (PreciseRotationCost && F->getFunction()->getEntryCount());
Cong Hou7745dbc2015-10-19 23:16:40 +00001789
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001790 // First check to see if there is an obviously preferable top block for the
1791 // loop. This will default to the header, but may end up as one of the
1792 // predecessors to the header if there is one which will result in strictly
1793 // fewer branches in the loop body.
Cong Hou7745dbc2015-10-19 23:16:40 +00001794 // When we use profile data to rotate the loop, this is unnecessary.
1795 MachineBasicBlock *LoopTop =
1796 RotateLoopWithProfile ? L.getHeader() : findBestLoopTop(L, LoopBlockSet);
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001797
1798 // If we selected just the header for the loop top, look for a potentially
1799 // profitable exit block in the event that rotating the loop can eliminate
1800 // branches by placing an exit edge at the bottom.
Cong Hou7745dbc2015-10-19 23:16:40 +00001801 if (!RotateLoopWithProfile && LoopTop == L.getHeader())
Kyle Buttab9cca72016-10-27 21:37:20 +00001802 PreferredLoopExit = findBestLoopExit(L, LoopBlockSet);
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001803
1804 BlockChain &LoopChain = *BlockToChain[LoopTop];
Chandler Carruth10281422011-10-21 06:46:38 +00001805
Chandler Carruth8d150782011-11-13 11:20:44 +00001806 // FIXME: This is a really lame way of walking the chains in the loop: we
1807 // walk the blocks, and use a set to prevent visiting a particular chain
1808 // twice.
Jakub Staszak90616162011-12-21 23:02:08 +00001809 SmallPtrSet<BlockChain *, 4> UpdatedPreds;
Philip Reamesae27b232016-03-03 00:58:43 +00001810 assert(LoopChain.UnscheduledPredecessors == 0);
Jakub Staszak190c7122011-12-07 19:46:10 +00001811 UpdatedPreds.insert(&LoopChain);
Cong Houb90b9e02015-11-02 21:24:00 +00001812
Kyle Butte9425c4f2017-02-04 02:26:32 +00001813 for (const MachineBasicBlock *LoopBB : LoopBlockSet)
Xinliang David Li93926ac2016-07-01 05:46:48 +00001814 fillWorkLists(LoopBB, UpdatedPreds, &LoopBlockSet);
Chandler Carruth8d150782011-11-13 11:20:44 +00001815
Xinliang David Li93926ac2016-07-01 05:46:48 +00001816 buildChain(LoopTop, LoopChain, &LoopBlockSet);
Cong Hou7745dbc2015-10-19 23:16:40 +00001817
1818 if (RotateLoopWithProfile)
1819 rotateLoopWithProfile(LoopChain, L, LoopBlockSet);
1820 else
Kyle Buttab9cca72016-10-27 21:37:20 +00001821 rotateLoop(LoopChain, PreferredLoopExit, LoopBlockSet);
Chandler Carruth8d150782011-11-13 11:20:44 +00001822
1823 DEBUG({
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001824 // Crash at the end so we get all of the debugging output first.
1825 bool BadLoop = false;
Philip Reamesae27b232016-03-03 00:58:43 +00001826 if (LoopChain.UnscheduledPredecessors) {
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001827 BadLoop = true;
Chandler Carruth8d150782011-11-13 11:20:44 +00001828 dbgs() << "Loop chain contains a block without its preds placed!\n"
1829 << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
1830 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n";
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001831 }
Chandler Carruth7a715da2015-03-05 03:19:05 +00001832 for (MachineBasicBlock *ChainBB : LoopChain) {
1833 dbgs() << " ... " << getBlockName(ChainBB) << "\n";
Rong Xu66827422016-11-16 20:50:06 +00001834 if (!LoopBlockSet.remove(ChainBB)) {
Chandler Carruth0a31d142011-11-14 10:55:53 +00001835 // We don't mark the loop as bad here because there are real situations
1836 // where this can occur. For example, with an unanalyzable fallthrough
Chandler Carruth99fe42f2011-11-23 10:35:36 +00001837 // from a loop block to a non-loop block or vice versa.
Chandler Carruth8d150782011-11-13 11:20:44 +00001838 dbgs() << "Loop chain contains a block not contained by the loop!\n"
1839 << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
1840 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
Chandler Carruth7a715da2015-03-05 03:19:05 +00001841 << " Bad block: " << getBlockName(ChainBB) << "\n";
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001842 }
Chandler Carruthccc7e422012-04-16 01:12:56 +00001843 }
Chandler Carruth8d150782011-11-13 11:20:44 +00001844
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001845 if (!LoopBlockSet.empty()) {
1846 BadLoop = true;
Kyle Butte9425c4f2017-02-04 02:26:32 +00001847 for (const MachineBasicBlock *LoopBB : LoopBlockSet)
Chandler Carruth8d150782011-11-13 11:20:44 +00001848 dbgs() << "Loop contains blocks never placed into a chain!\n"
1849 << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
1850 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
Chandler Carruth7a715da2015-03-05 03:19:05 +00001851 << " Bad block: " << getBlockName(LoopBB) << "\n";
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001852 }
1853 assert(!BadLoop && "Detected problems with the placement of this loop.");
Chandler Carruth8d150782011-11-13 11:20:44 +00001854 });
Xinliang David Li93926ac2016-07-01 05:46:48 +00001855
1856 BlockWorkList.clear();
1857 EHPadWorkList.clear();
Chandler Carruth10281422011-10-21 06:46:38 +00001858}
1859
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00001860/// When OutlineOpitonalBranches is on, this method collects BBs that
Xinliang David Li071d0f12016-06-12 16:54:03 +00001861/// dominates all terminator blocks of the function \p F.
Xinliang David Li52530a72016-06-13 22:23:44 +00001862void MachineBlockPlacement::collectMustExecuteBBs() {
Xinliang David Li071d0f12016-06-12 16:54:03 +00001863 if (OutlineOptionalBranches) {
1864 // Find the nearest common dominator of all of F's terminators.
1865 MachineBasicBlock *Terminator = nullptr;
Xinliang David Li52530a72016-06-13 22:23:44 +00001866 for (MachineBasicBlock &MBB : *F) {
Xinliang David Li071d0f12016-06-12 16:54:03 +00001867 if (MBB.succ_size() == 0) {
1868 if (Terminator == nullptr)
1869 Terminator = &MBB;
1870 else
1871 Terminator = MDT->findNearestCommonDominator(Terminator, &MBB);
1872 }
1873 }
1874
1875 // MBBs dominating this common dominator are unavoidable.
1876 UnavoidableBlocks.clear();
Xinliang David Li52530a72016-06-13 22:23:44 +00001877 for (MachineBasicBlock &MBB : *F) {
Xinliang David Li071d0f12016-06-12 16:54:03 +00001878 if (MDT->dominates(&MBB, Terminator)) {
1879 UnavoidableBlocks.insert(&MBB);
1880 }
1881 }
1882 }
1883}
1884
Xinliang David Li52530a72016-06-13 22:23:44 +00001885void MachineBlockPlacement::buildCFGChains() {
Chandler Carruth8d150782011-11-13 11:20:44 +00001886 // Ensure that every BB in the function has an associated chain to simplify
1887 // the assumptions of the remaining algorithm.
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +00001888 SmallVector<MachineOperand, 4> Cond; // For AnalyzeBranch.
Xinliang David Li52530a72016-06-13 22:23:44 +00001889 for (MachineFunction::iterator FI = F->begin(), FE = F->end(); FI != FE;
1890 ++FI) {
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +00001891 MachineBasicBlock *BB = &*FI;
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001892 BlockChain *Chain =
1893 new (ChainAllocator.Allocate()) BlockChain(BlockToChain, BB);
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +00001894 // Also, merge any blocks which we cannot reason about and must preserve
1895 // the exact fallthrough behavior for.
1896 for (;;) {
1897 Cond.clear();
Craig Topperc0196b12014-04-14 00:51:57 +00001898 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
Jacques Pienaar71c30a12016-07-15 14:41:04 +00001899 if (!TII->analyzeBranch(*BB, TBB, FBB, Cond) || !FI->canFallThrough())
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +00001900 break;
1901
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +00001902 MachineFunction::iterator NextFI = std::next(FI);
1903 MachineBasicBlock *NextBB = &*NextFI;
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +00001904 // Ensure that the layout successor is a viable block, as we know that
1905 // fallthrough is a possibility.
1906 assert(NextFI != FE && "Can't fallthrough past the last block.");
1907 DEBUG(dbgs() << "Pre-merging due to unanalyzable fallthrough: "
1908 << getBlockName(BB) << " -> " << getBlockName(NextBB)
1909 << "\n");
Craig Topperc0196b12014-04-14 00:51:57 +00001910 Chain->merge(NextBB, nullptr);
Hal Finkel34f9d6a2016-12-15 05:33:19 +00001911#ifndef NDEBUG
Sanjoy Dasd7389d62016-12-15 05:08:57 +00001912 BlocksWithUnanalyzableExits.insert(&*BB);
Hal Finkel34f9d6a2016-12-15 05:33:19 +00001913#endif
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +00001914 FI = NextFI;
1915 BB = NextBB;
1916 }
1917 }
Chandler Carruth8d150782011-11-13 11:20:44 +00001918
Xinliang David Li071d0f12016-06-12 16:54:03 +00001919 // Turned on with OutlineOptionalBranches option
Xinliang David Li52530a72016-06-13 22:23:44 +00001920 collectMustExecuteBBs();
Daniel Jasper471e8562015-03-04 11:05:34 +00001921
Chandler Carruth8d150782011-11-13 11:20:44 +00001922 // Build any loop-based chains.
Sam McCall2a36eee2016-11-01 22:02:14 +00001923 PreferredLoopExit = nullptr;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001924 for (MachineLoop *L : *MLI)
Xinliang David Li52530a72016-06-13 22:23:44 +00001925 buildLoopChains(*L);
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00001926
Xinliang David Li93926ac2016-07-01 05:46:48 +00001927 assert(BlockWorkList.empty());
1928 assert(EHPadWorkList.empty());
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00001929
Chandler Carruth8d150782011-11-13 11:20:44 +00001930 SmallPtrSet<BlockChain *, 4> UpdatedPreds;
Xinliang David Li52530a72016-06-13 22:23:44 +00001931 for (MachineBasicBlock &MBB : *F)
Xinliang David Li93926ac2016-07-01 05:46:48 +00001932 fillWorkLists(&MBB, UpdatedPreds);
Chandler Carruth8d150782011-11-13 11:20:44 +00001933
Xinliang David Li52530a72016-06-13 22:23:44 +00001934 BlockChain &FunctionChain = *BlockToChain[&F->front()];
Xinliang David Li93926ac2016-07-01 05:46:48 +00001935 buildChain(&F->front(), FunctionChain);
Chandler Carruth8d150782011-11-13 11:20:44 +00001936
Matt Arsenault0f5f0152013-12-10 18:55:37 +00001937#ifndef NDEBUG
Matt Arsenault79d55f52013-12-05 20:02:18 +00001938 typedef SmallPtrSet<MachineBasicBlock *, 16> FunctionBlockSetType;
Matt Arsenault0f5f0152013-12-10 18:55:37 +00001939#endif
Chandler Carruth8d150782011-11-13 11:20:44 +00001940 DEBUG({
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001941 // Crash at the end so we get all of the debugging output first.
1942 bool BadFunc = false;
Chandler Carruth8d150782011-11-13 11:20:44 +00001943 FunctionBlockSetType FunctionBlockSet;
Xinliang David Li52530a72016-06-13 22:23:44 +00001944 for (MachineBasicBlock &MBB : *F)
Chandler Carruth7a715da2015-03-05 03:19:05 +00001945 FunctionBlockSet.insert(&MBB);
Chandler Carruth8d150782011-11-13 11:20:44 +00001946
Chandler Carruth7a715da2015-03-05 03:19:05 +00001947 for (MachineBasicBlock *ChainBB : FunctionChain)
1948 if (!FunctionBlockSet.erase(ChainBB)) {
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001949 BadFunc = true;
Chandler Carruth8d150782011-11-13 11:20:44 +00001950 dbgs() << "Function chain contains a block not in the function!\n"
Chandler Carruth7a715da2015-03-05 03:19:05 +00001951 << " Bad block: " << getBlockName(ChainBB) << "\n";
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001952 }
Chandler Carruth8d150782011-11-13 11:20:44 +00001953
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001954 if (!FunctionBlockSet.empty()) {
1955 BadFunc = true;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001956 for (MachineBasicBlock *RemainingBB : FunctionBlockSet)
Chandler Carruth8d150782011-11-13 11:20:44 +00001957 dbgs() << "Function contains blocks never placed into a chain!\n"
Chandler Carruth7a715da2015-03-05 03:19:05 +00001958 << " Bad block: " << getBlockName(RemainingBB) << "\n";
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001959 }
1960 assert(!BadFunc && "Detected problems with the block placement.");
Chandler Carruth8d150782011-11-13 11:20:44 +00001961 });
1962
1963 // Splice the blocks into place.
Xinliang David Li52530a72016-06-13 22:23:44 +00001964 MachineFunction::iterator InsertPos = F->begin();
Xinliang David Li449cdfd2016-06-24 22:54:21 +00001965 DEBUG(dbgs() << "[MBP] Function: "<< F->getName() << "\n");
Chandler Carruth7a715da2015-03-05 03:19:05 +00001966 for (MachineBasicBlock *ChainBB : FunctionChain) {
1967 DEBUG(dbgs() << (ChainBB == *FunctionChain.begin() ? "Placing chain "
1968 : " ... ")
1969 << getBlockName(ChainBB) << "\n");
1970 if (InsertPos != MachineFunction::iterator(ChainBB))
Xinliang David Li52530a72016-06-13 22:23:44 +00001971 F->splice(InsertPos, ChainBB);
Chandler Carruth8d150782011-11-13 11:20:44 +00001972 else
1973 ++InsertPos;
1974
1975 // Update the terminator of the previous block.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001976 if (ChainBB == *FunctionChain.begin())
Chandler Carruth8d150782011-11-13 11:20:44 +00001977 continue;
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +00001978 MachineBasicBlock *PrevBB = &*std::prev(MachineFunction::iterator(ChainBB));
Chandler Carruth8d150782011-11-13 11:20:44 +00001979
Chandler Carruth10281422011-10-21 06:46:38 +00001980 // FIXME: It would be awesome of updateTerminator would just return rather
1981 // than assert when the branch cannot be analyzed in order to remove this
1982 // boiler plate.
1983 Cond.clear();
Craig Topperc0196b12014-04-14 00:51:57 +00001984 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
Shuxin Yang8b8fd212013-06-04 01:00:57 +00001985
Sanjoy Dasd7389d62016-12-15 05:08:57 +00001986#ifndef NDEBUG
1987 if (!BlocksWithUnanalyzableExits.count(PrevBB)) {
1988 // Given the exact block placement we chose, we may actually not _need_ to
1989 // be able to edit PrevBB's terminator sequence, but not being _able_ to
1990 // do that at this point is a bug.
1991 assert((!TII->analyzeBranch(*PrevBB, TBB, FBB, Cond) ||
1992 !PrevBB->canFallThrough()) &&
1993 "Unexpected block with un-analyzable fallthrough!");
1994 Cond.clear();
1995 TBB = FBB = nullptr;
1996 }
1997#endif
1998
Haicheng Wu90a55652016-05-24 22:16:14 +00001999 // The "PrevBB" is not yet updated to reflect current code layout, so,
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00002000 // o. it may fall-through to a block without explicit "goto" instruction
Haicheng Wu90a55652016-05-24 22:16:14 +00002001 // before layout, and no longer fall-through it after layout; or
2002 // o. just opposite.
2003 //
Jacques Pienaar71c30a12016-07-15 14:41:04 +00002004 // analyzeBranch() may return erroneous value for FBB when these two
Haicheng Wu90a55652016-05-24 22:16:14 +00002005 // situations take place. For the first scenario FBB is mistakenly set NULL;
2006 // for the 2nd scenario, the FBB, which is expected to be NULL, is
2007 // mistakenly pointing to "*BI".
2008 // Thus, if the future change needs to use FBB before the layout is set, it
2009 // has to correct FBB first by using the code similar to the following:
2010 //
2011 // if (!Cond.empty() && (!FBB || FBB == ChainBB)) {
2012 // PrevBB->updateTerminator();
2013 // Cond.clear();
2014 // TBB = FBB = nullptr;
Jacques Pienaar71c30a12016-07-15 14:41:04 +00002015 // if (TII->analyzeBranch(*PrevBB, TBB, FBB, Cond)) {
Haicheng Wu90a55652016-05-24 22:16:14 +00002016 // // FIXME: This should never take place.
2017 // TBB = FBB = nullptr;
2018 // }
2019 // }
Jacques Pienaar71c30a12016-07-15 14:41:04 +00002020 if (!TII->analyzeBranch(*PrevBB, TBB, FBB, Cond))
Haicheng Wu90a55652016-05-24 22:16:14 +00002021 PrevBB->updateTerminator();
Chandler Carruth10281422011-10-21 06:46:38 +00002022 }
Chandler Carruth8d150782011-11-13 11:20:44 +00002023
2024 // Fixup the last block.
2025 Cond.clear();
Craig Topperc0196b12014-04-14 00:51:57 +00002026 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
Jacques Pienaar71c30a12016-07-15 14:41:04 +00002027 if (!TII->analyzeBranch(F->back(), TBB, FBB, Cond))
Xinliang David Li52530a72016-06-13 22:23:44 +00002028 F->back().updateTerminator();
Xinliang David Li93926ac2016-07-01 05:46:48 +00002029
2030 BlockWorkList.clear();
2031 EHPadWorkList.clear();
Haicheng Wu90a55652016-05-24 22:16:14 +00002032}
2033
Xinliang David Li52530a72016-06-13 22:23:44 +00002034void MachineBlockPlacement::optimizeBranches() {
2035 BlockChain &FunctionChain = *BlockToChain[&F->front()];
Haicheng Wu90a55652016-05-24 22:16:14 +00002036 SmallVector<MachineOperand, 4> Cond; // For AnalyzeBranch.
Quentin Colombet776e6de2016-05-02 22:58:59 +00002037
2038 // Now that all the basic blocks in the chain have the proper layout,
2039 // make a final call to AnalyzeBranch with AllowModify set.
2040 // Indeed, the target may be able to optimize the branches in a way we
2041 // cannot because all branches may not be analyzable.
2042 // E.g., the target may be able to remove an unconditional branch to
2043 // a fallthrough when it occurs after predicated terminators.
2044 for (MachineBasicBlock *ChainBB : FunctionChain) {
2045 Cond.clear();
Haicheng Wu90a55652016-05-24 22:16:14 +00002046 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
Jacques Pienaar71c30a12016-07-15 14:41:04 +00002047 if (!TII->analyzeBranch(*ChainBB, TBB, FBB, Cond, /*AllowModify*/ true)) {
Haicheng Wu90a55652016-05-24 22:16:14 +00002048 // If PrevBB has a two-way branch, try to re-order the branches
2049 // such that we branch to the successor with higher probability first.
2050 if (TBB && !Cond.empty() && FBB &&
2051 MBPI->getEdgeProbability(ChainBB, FBB) >
2052 MBPI->getEdgeProbability(ChainBB, TBB) &&
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +00002053 !TII->reverseBranchCondition(Cond)) {
Haicheng Wu90a55652016-05-24 22:16:14 +00002054 DEBUG(dbgs() << "Reverse order of the two branches: "
2055 << getBlockName(ChainBB) << "\n");
2056 DEBUG(dbgs() << " Edge probability: "
2057 << MBPI->getEdgeProbability(ChainBB, FBB) << " vs "
2058 << MBPI->getEdgeProbability(ChainBB, TBB) << "\n");
2059 DebugLoc dl; // FIXME: this is nowhere
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +00002060 TII->removeBranch(*ChainBB);
Matt Arsenaulte8e0f5c2016-09-14 17:24:15 +00002061 TII->insertBranch(*ChainBB, FBB, TBB, Cond, dl);
Haicheng Wu90a55652016-05-24 22:16:14 +00002062 ChainBB->updateTerminator();
2063 }
2064 }
Quentin Colombet776e6de2016-05-02 22:58:59 +00002065 }
Haicheng Wue749ce52016-04-29 17:06:44 +00002066}
Chandler Carruth10281422011-10-21 06:46:38 +00002067
Xinliang David Li52530a72016-06-13 22:23:44 +00002068void MachineBlockPlacement::alignBlocks() {
Chandler Carruthccc7e422012-04-16 01:12:56 +00002069 // Walk through the backedges of the function now that we have fully laid out
2070 // the basic blocks and align the destination of each backedge. We don't rely
Chandler Carruth881d0a72012-08-07 09:45:24 +00002071 // exclusively on the loop info here so that we can align backedges in
2072 // unnatural CFGs and backedges that were introduced purely because of the
2073 // loop rotations done during this layout pass.
Xinliang David Li52530a72016-06-13 22:23:44 +00002074 if (F->getFunction()->optForSize())
Chandler Carruth8b9737c2011-10-21 08:57:37 +00002075 return;
Xinliang David Li52530a72016-06-13 22:23:44 +00002076 BlockChain &FunctionChain = *BlockToChain[&F->front()];
Chandler Carruth881d0a72012-08-07 09:45:24 +00002077 if (FunctionChain.begin() == FunctionChain.end())
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00002078 return; // Empty chain.
Chandler Carruth8b9737c2011-10-21 08:57:37 +00002079
Chandler Carruth881d0a72012-08-07 09:45:24 +00002080 const BranchProbability ColdProb(1, 5); // 20%
Xinliang David Li52530a72016-06-13 22:23:44 +00002081 BlockFrequency EntryFreq = MBFI->getBlockFreq(&F->front());
Chandler Carruth881d0a72012-08-07 09:45:24 +00002082 BlockFrequency WeightedEntryFreq = EntryFreq * ColdProb;
Chandler Carruth7a715da2015-03-05 03:19:05 +00002083 for (MachineBasicBlock *ChainBB : FunctionChain) {
2084 if (ChainBB == *FunctionChain.begin())
2085 continue;
2086
Chandler Carruth881d0a72012-08-07 09:45:24 +00002087 // Don't align non-looping basic blocks. These are unlikely to execute
2088 // enough times to matter in practice. Note that we'll still handle
2089 // unnatural CFGs inside of a natural outer loop (the common case) and
2090 // rotated loops.
Chandler Carruth7a715da2015-03-05 03:19:05 +00002091 MachineLoop *L = MLI->getLoopFor(ChainBB);
Chandler Carruth881d0a72012-08-07 09:45:24 +00002092 if (!L)
2093 continue;
2094
Hal Finkel57725662015-01-03 17:58:24 +00002095 unsigned Align = TLI->getPrefLoopAlignment(L);
2096 if (!Align)
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00002097 continue; // Don't care about loop alignment.
Hal Finkel57725662015-01-03 17:58:24 +00002098
Chandler Carruth881d0a72012-08-07 09:45:24 +00002099 // If the block is cold relative to the function entry don't waste space
2100 // aligning it.
Chandler Carruth7a715da2015-03-05 03:19:05 +00002101 BlockFrequency Freq = MBFI->getBlockFreq(ChainBB);
Chandler Carruth881d0a72012-08-07 09:45:24 +00002102 if (Freq < WeightedEntryFreq)
2103 continue;
2104
2105 // If the block is cold relative to its loop header, don't align it
2106 // regardless of what edges into the block exist.
2107 MachineBasicBlock *LoopHeader = L->getHeader();
2108 BlockFrequency LoopHeaderFreq = MBFI->getBlockFreq(LoopHeader);
2109 if (Freq < (LoopHeaderFreq * ColdProb))
2110 continue;
2111
2112 // Check for the existence of a non-layout predecessor which would benefit
2113 // from aligning this block.
Chandler Carruth7a715da2015-03-05 03:19:05 +00002114 MachineBasicBlock *LayoutPred =
2115 &*std::prev(MachineFunction::iterator(ChainBB));
Chandler Carruth881d0a72012-08-07 09:45:24 +00002116
2117 // Force alignment if all the predecessors are jumps. We already checked
2118 // that the block isn't cold above.
Chandler Carruth7a715da2015-03-05 03:19:05 +00002119 if (!LayoutPred->isSuccessor(ChainBB)) {
2120 ChainBB->setAlignment(Align);
Chandler Carruth881d0a72012-08-07 09:45:24 +00002121 continue;
2122 }
2123
2124 // Align this block if the layout predecessor's edge into this block is
Nadav Rotem6036f582013-03-29 16:34:23 +00002125 // cold relative to the block. When this is true, other predecessors make up
Chandler Carruth881d0a72012-08-07 09:45:24 +00002126 // all of the hot entries into the block and thus alignment is likely to be
2127 // important.
Chandler Carruth7a715da2015-03-05 03:19:05 +00002128 BranchProbability LayoutProb =
2129 MBPI->getEdgeProbability(LayoutPred, ChainBB);
Chandler Carruth881d0a72012-08-07 09:45:24 +00002130 BlockFrequency LayoutEdgeFreq = MBFI->getBlockFreq(LayoutPred) * LayoutProb;
2131 if (LayoutEdgeFreq <= (Freq * ColdProb))
Chandler Carruth7a715da2015-03-05 03:19:05 +00002132 ChainBB->setAlignment(Align);
Chandler Carruthccc7e422012-04-16 01:12:56 +00002133 }
Chandler Carruth8b9737c2011-10-21 08:57:37 +00002134}
2135
Kyle Butt0846e562016-10-11 20:36:43 +00002136/// Tail duplicate \p BB into (some) predecessors if profitable, repeating if
2137/// it was duplicated into its chain predecessor and removed.
2138/// \p BB - Basic block that may be duplicated.
2139///
2140/// \p LPred - Chosen layout predecessor of \p BB.
2141/// Updated to be the chain end if LPred is removed.
2142/// \p Chain - Chain to which \p LPred belongs, and \p BB will belong.
2143/// \p BlockFilter - Set of blocks that belong to the loop being laid out.
2144/// Used to identify which blocks to update predecessor
2145/// counts.
2146/// \p PrevUnplacedBlockIt - Iterator pointing to the last block that was
2147/// chosen in the given order due to unnatural CFG
2148/// only needed if \p BB is removed and
2149/// \p PrevUnplacedBlockIt pointed to \p BB.
2150/// @return true if \p BB was removed.
2151bool MachineBlockPlacement::repeatedlyTailDuplicateBlock(
2152 MachineBasicBlock *BB, MachineBasicBlock *&LPred,
Kyle Butte9425c4f2017-02-04 02:26:32 +00002153 const MachineBasicBlock *LoopHeaderBB,
Kyle Butt0846e562016-10-11 20:36:43 +00002154 BlockChain &Chain, BlockFilterSet *BlockFilter,
2155 MachineFunction::iterator &PrevUnplacedBlockIt) {
2156 bool Removed, DuplicatedToLPred;
2157 bool DuplicatedToOriginalLPred;
2158 Removed = maybeTailDuplicateBlock(BB, LPred, Chain, BlockFilter,
2159 PrevUnplacedBlockIt,
2160 DuplicatedToLPred);
2161 if (!Removed)
2162 return false;
2163 DuplicatedToOriginalLPred = DuplicatedToLPred;
2164 // Iteratively try to duplicate again. It can happen that a block that is
2165 // duplicated into is still small enough to be duplicated again.
2166 // No need to call markBlockSuccessors in this case, as the blocks being
2167 // duplicated from here on are already scheduled.
2168 // Note that DuplicatedToLPred always implies Removed.
2169 while (DuplicatedToLPred) {
2170 assert (Removed && "Block must have been removed to be duplicated into its "
2171 "layout predecessor.");
2172 MachineBasicBlock *DupBB, *DupPred;
2173 // The removal callback causes Chain.end() to be updated when a block is
2174 // removed. On the first pass through the loop, the chain end should be the
2175 // same as it was on function entry. On subsequent passes, because we are
2176 // duplicating the block at the end of the chain, if it is removed the
2177 // chain will have shrunk by one block.
2178 BlockChain::iterator ChainEnd = Chain.end();
2179 DupBB = *(--ChainEnd);
2180 // Now try to duplicate again.
2181 if (ChainEnd == Chain.begin())
2182 break;
2183 DupPred = *std::prev(ChainEnd);
2184 Removed = maybeTailDuplicateBlock(DupBB, DupPred, Chain, BlockFilter,
2185 PrevUnplacedBlockIt,
2186 DuplicatedToLPred);
2187 }
2188 // If BB was duplicated into LPred, it is now scheduled. But because it was
2189 // removed, markChainSuccessors won't be called for its chain. Instead we
2190 // call markBlockSuccessors for LPred to achieve the same effect. This must go
2191 // at the end because repeating the tail duplication can increase the number
2192 // of unscheduled predecessors.
2193 LPred = *std::prev(Chain.end());
2194 if (DuplicatedToOriginalLPred)
2195 markBlockSuccessors(Chain, LPred, LoopHeaderBB, BlockFilter);
2196 return true;
2197}
2198
2199/// Tail duplicate \p BB into (some) predecessors if profitable.
2200/// \p BB - Basic block that may be duplicated
2201/// \p LPred - Chosen layout predecessor of \p BB
2202/// \p Chain - Chain to which \p LPred belongs, and \p BB will belong.
2203/// \p BlockFilter - Set of blocks that belong to the loop being laid out.
2204/// Used to identify which blocks to update predecessor
2205/// counts.
2206/// \p PrevUnplacedBlockIt - Iterator pointing to the last block that was
2207/// chosen in the given order due to unnatural CFG
2208/// only needed if \p BB is removed and
2209/// \p PrevUnplacedBlockIt pointed to \p BB.
2210/// \p DuplicatedToLPred - True if the block was duplicated into LPred. Will
2211/// only be true if the block was removed.
2212/// \return - True if the block was duplicated into all preds and removed.
2213bool MachineBlockPlacement::maybeTailDuplicateBlock(
2214 MachineBasicBlock *BB, MachineBasicBlock *LPred,
Kyle Butte9425c4f2017-02-04 02:26:32 +00002215 BlockChain &Chain, BlockFilterSet *BlockFilter,
Kyle Butt0846e562016-10-11 20:36:43 +00002216 MachineFunction::iterator &PrevUnplacedBlockIt,
2217 bool &DuplicatedToLPred) {
Kyle Butt0846e562016-10-11 20:36:43 +00002218 DuplicatedToLPred = false;
Kyle Buttc7d67eef2017-02-04 02:26:34 +00002219 if (!shouldTailDuplicate(BB))
2220 return false;
2221
Kyle Butt0846e562016-10-11 20:36:43 +00002222 DEBUG(dbgs() << "Redoing tail duplication for Succ#"
2223 << BB->getNumber() << "\n");
Kyle Buttb15c0662017-01-31 23:48:32 +00002224
Kyle Butt0846e562016-10-11 20:36:43 +00002225 // This has to be a callback because none of it can be done after
2226 // BB is deleted.
2227 bool Removed = false;
2228 auto RemovalCallback =
2229 [&](MachineBasicBlock *RemBB) {
2230 // Signal to outer function
2231 Removed = true;
2232
2233 // Conservative default.
2234 bool InWorkList = true;
2235 // Remove from the Chain and Chain Map
2236 if (BlockToChain.count(RemBB)) {
2237 BlockChain *Chain = BlockToChain[RemBB];
2238 InWorkList = Chain->UnscheduledPredecessors == 0;
2239 Chain->remove(RemBB);
2240 BlockToChain.erase(RemBB);
2241 }
2242
2243 // Handle the unplaced block iterator
2244 if (&(*PrevUnplacedBlockIt) == RemBB) {
2245 PrevUnplacedBlockIt++;
2246 }
2247
2248 // Handle the Work Lists
2249 if (InWorkList) {
2250 SmallVectorImpl<MachineBasicBlock *> &RemoveList = BlockWorkList;
2251 if (RemBB->isEHPad())
2252 RemoveList = EHPadWorkList;
2253 RemoveList.erase(
2254 remove_if(RemoveList,
2255 [RemBB](MachineBasicBlock *BB) {return BB == RemBB;}),
2256 RemoveList.end());
2257 }
2258
2259 // Handle the filter set
2260 if (BlockFilter) {
Rong Xu66827422016-11-16 20:50:06 +00002261 BlockFilter->remove(RemBB);
Kyle Butt0846e562016-10-11 20:36:43 +00002262 }
2263
2264 // Remove the block from loop info.
2265 MLI->removeBlock(RemBB);
Kyle Buttab9cca72016-10-27 21:37:20 +00002266 if (RemBB == PreferredLoopExit)
2267 PreferredLoopExit = nullptr;
Kyle Butt0846e562016-10-11 20:36:43 +00002268
Kyle Butt0846e562016-10-11 20:36:43 +00002269 DEBUG(dbgs() << "TailDuplicator deleted block: "
2270 << getBlockName(RemBB) << "\n");
2271 };
2272 auto RemovalCallbackRef =
2273 llvm::function_ref<void(MachineBasicBlock*)>(RemovalCallback);
2274
2275 SmallVector<MachineBasicBlock *, 8> DuplicatedPreds;
Kyle Buttb15c0662017-01-31 23:48:32 +00002276 bool IsSimple = TailDup.isSimpleBB(BB);
Kyle Butt0846e562016-10-11 20:36:43 +00002277 TailDup.tailDuplicateAndUpdate(IsSimple, BB, LPred,
2278 &DuplicatedPreds, &RemovalCallbackRef);
2279
2280 // Update UnscheduledPredecessors to reflect tail-duplication.
2281 DuplicatedToLPred = false;
2282 for (MachineBasicBlock *Pred : DuplicatedPreds) {
2283 // We're only looking for unscheduled predecessors that match the filter.
2284 BlockChain* PredChain = BlockToChain[Pred];
2285 if (Pred == LPred)
2286 DuplicatedToLPred = true;
2287 if (Pred == LPred || (BlockFilter && !BlockFilter->count(Pred))
2288 || PredChain == &Chain)
2289 continue;
2290 for (MachineBasicBlock *NewSucc : Pred->successors()) {
2291 if (BlockFilter && !BlockFilter->count(NewSucc))
2292 continue;
2293 BlockChain *NewChain = BlockToChain[NewSucc];
2294 if (NewChain != &Chain && NewChain != PredChain)
2295 NewChain->UnscheduledPredecessors++;
2296 }
2297 }
2298 return Removed;
2299}
2300
Xinliang David Li52530a72016-06-13 22:23:44 +00002301bool MachineBlockPlacement::runOnMachineFunction(MachineFunction &MF) {
2302 if (skipFunction(*MF.getFunction()))
Andrew Kaylor50271f72016-05-03 22:32:30 +00002303 return false;
2304
Chandler Carruth10281422011-10-21 06:46:38 +00002305 // Check for single-block functions and skip them.
Xinliang David Li52530a72016-06-13 22:23:44 +00002306 if (std::next(MF.begin()) == MF.end())
Chandler Carruth10281422011-10-21 06:46:38 +00002307 return false;
2308
Xinliang David Li52530a72016-06-13 22:23:44 +00002309 F = &MF;
Chandler Carruth10281422011-10-21 06:46:38 +00002310 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
Haicheng Wu5b458cc2016-06-09 15:24:29 +00002311 MBFI = llvm::make_unique<BranchFolder::MBFIWrapper>(
2312 getAnalysis<MachineBlockFrequencyInfo>());
Chandler Carruth8b9737c2011-10-21 08:57:37 +00002313 MLI = &getAnalysis<MachineLoopInfo>();
Xinliang David Li52530a72016-06-13 22:23:44 +00002314 TII = MF.getSubtarget().getInstrInfo();
2315 TLI = MF.getSubtarget().getTargetLowering();
Daniel Jasper471e8562015-03-04 11:05:34 +00002316 MDT = &getAnalysis<MachineDominatorTree>();
Kyle Buttb15c0662017-01-31 23:48:32 +00002317 MPDT = nullptr;
Eric Christopher690f8e52016-11-01 22:15:50 +00002318
2319 // Initialize PreferredLoopExit to nullptr here since it may never be set if
2320 // there are no MachineLoops.
2321 PreferredLoopExit = nullptr;
2322
Kyle Butt0846e562016-10-11 20:36:43 +00002323 if (TailDupPlacement) {
Kyle Buttb15c0662017-01-31 23:48:32 +00002324 MPDT = &getAnalysis<MachinePostDominatorTree>();
2325 unsigned TailDupSize = TailDupPlacementThreshold;
Kyle Butt0846e562016-10-11 20:36:43 +00002326 if (MF.getFunction()->optForSize())
2327 TailDupSize = 1;
2328 TailDup.initMF(MF, MBPI, /* LayoutMode */ true, TailDupSize);
2329 }
2330
Chandler Carruth10281422011-10-21 06:46:38 +00002331 assert(BlockToChain.empty());
Chandler Carruth10281422011-10-21 06:46:38 +00002332
Xinliang David Li52530a72016-06-13 22:23:44 +00002333 buildCFGChains();
Haicheng Wu5b458cc2016-06-09 15:24:29 +00002334
2335 // Changing the layout can create new tail merging opportunities.
2336 TargetPassConfig *PassConfig = &getAnalysis<TargetPassConfig>();
2337 // TailMerge can create jump into if branches that make CFG irreducible for
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00002338 // HW that requires structured CFG.
Xinliang David Li52530a72016-06-13 22:23:44 +00002339 bool EnableTailMerge = !MF.getTarget().requiresStructuredCFG() &&
Haicheng Wu5b458cc2016-06-09 15:24:29 +00002340 PassConfig->getEnableTailMerge() &&
2341 BranchFoldPlacement;
2342 // No tail merging opportunities if the block number is less than four.
Xinliang David Li52530a72016-06-13 22:23:44 +00002343 if (MF.size() > 3 && EnableTailMerge) {
Kyle Buttb15c0662017-01-31 23:48:32 +00002344 unsigned TailMergeSize = TailDupPlacementThreshold + 1;
Haicheng Wu5b458cc2016-06-09 15:24:29 +00002345 BranchFolder BF(/*EnableTailMerge=*/true, /*CommonHoist=*/false, *MBFI,
Kyle Butt64e42812016-08-18 18:57:29 +00002346 *MBPI, TailMergeSize);
Haicheng Wu5b458cc2016-06-09 15:24:29 +00002347
Xinliang David Li52530a72016-06-13 22:23:44 +00002348 if (BF.OptimizeFunction(MF, TII, MF.getSubtarget().getRegisterInfo(),
Haicheng Wu5b458cc2016-06-09 15:24:29 +00002349 getAnalysisIfAvailable<MachineModuleInfo>(), MLI,
2350 /*AfterBlockPlacement=*/true)) {
2351 // Redo the layout if tail merging creates/removes/moves blocks.
2352 BlockToChain.clear();
Kyle Butt0846e562016-10-11 20:36:43 +00002353 // Must redo the dominator tree if blocks were changed.
2354 MDT->runOnMachineFunction(MF);
Kyle Buttb15c0662017-01-31 23:48:32 +00002355 if (MPDT)
2356 MPDT->runOnMachineFunction(MF);
Haicheng Wu5b458cc2016-06-09 15:24:29 +00002357 ChainAllocator.DestroyAll();
Xinliang David Li52530a72016-06-13 22:23:44 +00002358 buildCFGChains();
Haicheng Wu5b458cc2016-06-09 15:24:29 +00002359 }
2360 }
2361
Xinliang David Li52530a72016-06-13 22:23:44 +00002362 optimizeBranches();
2363 alignBlocks();
Chandler Carruth10281422011-10-21 06:46:38 +00002364
Chandler Carruth10281422011-10-21 06:46:38 +00002365 BlockToChain.clear();
Chandler Carruthfd9b4d92011-11-14 10:57:23 +00002366 ChainAllocator.DestroyAll();
Chandler Carruth10281422011-10-21 06:46:38 +00002367
Nadav Rotemc0adc9f2013-04-12 01:24:16 +00002368 if (AlignAllBlock)
2369 // Align all of the blocks in the function to a specific alignment.
Xinliang David Li52530a72016-06-13 22:23:44 +00002370 for (MachineBasicBlock &MBB : MF)
Chandler Carruth7a715da2015-03-05 03:19:05 +00002371 MBB.setAlignment(AlignAllBlock);
Geoff Berry10494ac2016-01-21 17:25:52 +00002372 else if (AlignAllNonFallThruBlocks) {
2373 // Align all of the blocks that have no fall-through predecessors to a
2374 // specific alignment.
Xinliang David Li52530a72016-06-13 22:23:44 +00002375 for (auto MBI = std::next(MF.begin()), MBE = MF.end(); MBI != MBE; ++MBI) {
Geoff Berry10494ac2016-01-21 17:25:52 +00002376 auto LayoutPred = std::prev(MBI);
2377 if (!LayoutPred->isSuccessor(&*MBI))
2378 MBI->setAlignment(AlignAllNonFallThruBlocks);
2379 }
2380 }
Xinliang David Lifd3f6452017-01-29 01:57:02 +00002381 if (ViewBlockLayoutWithBFI != GVDT_None &&
2382 (ViewBlockFreqFuncName.empty() ||
2383 F->getFunction()->getName().equals(ViewBlockFreqFuncName))) {
2384 MBFI->view(false);
2385 }
Xinliang David Lifd3f6452017-01-29 01:57:02 +00002386
Nadav Rotemc0adc9f2013-04-12 01:24:16 +00002387
Chandler Carruth10281422011-10-21 06:46:38 +00002388 // We always return true as we have no way to track whether the final order
2389 // differs from the original order.
2390 return true;
2391}
Chandler Carruthae4e8002011-11-02 07:17:12 +00002392
2393namespace {
2394/// \brief A pass to compute block placement statistics.
2395///
2396/// A separate pass to compute interesting statistics for evaluating block
2397/// placement. This is separate from the actual placement pass so that they can
Benjamin Kramerbde91762012-06-02 10:20:22 +00002398/// be computed in the absence of any placement transformations or when using
Chandler Carruthae4e8002011-11-02 07:17:12 +00002399/// alternative placement strategies.
2400class MachineBlockPlacementStats : public MachineFunctionPass {
2401 /// \brief A handle to the branch probability pass.
2402 const MachineBranchProbabilityInfo *MBPI;
2403
2404 /// \brief A handle to the function-wide block frequency pass.
2405 const MachineBlockFrequencyInfo *MBFI;
2406
2407public:
2408 static char ID; // Pass identification, replacement for typeid
2409 MachineBlockPlacementStats() : MachineFunctionPass(ID) {
2410 initializeMachineBlockPlacementStatsPass(*PassRegistry::getPassRegistry());
2411 }
2412
Craig Topper4584cd52014-03-07 09:26:03 +00002413 bool runOnMachineFunction(MachineFunction &F) override;
Chandler Carruthae4e8002011-11-02 07:17:12 +00002414
Craig Topper4584cd52014-03-07 09:26:03 +00002415 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruthae4e8002011-11-02 07:17:12 +00002416 AU.addRequired<MachineBranchProbabilityInfo>();
2417 AU.addRequired<MachineBlockFrequencyInfo>();
2418 AU.setPreservesAll();
2419 MachineFunctionPass::getAnalysisUsage(AU);
2420 }
Chandler Carruthae4e8002011-11-02 07:17:12 +00002421};
Alexander Kornienkof00654e2015-06-23 09:49:53 +00002422}
Chandler Carruthae4e8002011-11-02 07:17:12 +00002423
2424char MachineBlockPlacementStats::ID = 0;
Andrew Trick1fa5bcb2012-02-08 21:23:13 +00002425char &llvm::MachineBlockPlacementStatsID = MachineBlockPlacementStats::ID;
Chandler Carruthae4e8002011-11-02 07:17:12 +00002426INITIALIZE_PASS_BEGIN(MachineBlockPlacementStats, "block-placement-stats",
2427 "Basic Block Placement Stats", false, false)
2428INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
2429INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
2430INITIALIZE_PASS_END(MachineBlockPlacementStats, "block-placement-stats",
2431 "Basic Block Placement Stats", false, false)
2432
Chandler Carruthae4e8002011-11-02 07:17:12 +00002433bool MachineBlockPlacementStats::runOnMachineFunction(MachineFunction &F) {
2434 // Check for single-block functions and skip them.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00002435 if (std::next(F.begin()) == F.end())
Chandler Carruthae4e8002011-11-02 07:17:12 +00002436 return false;
2437
2438 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
2439 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
2440
Chandler Carruth7a715da2015-03-05 03:19:05 +00002441 for (MachineBasicBlock &MBB : F) {
2442 BlockFrequency BlockFreq = MBFI->getBlockFreq(&MBB);
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00002443 Statistic &NumBranches =
Chandler Carruth7a715da2015-03-05 03:19:05 +00002444 (MBB.succ_size() > 1) ? NumCondBranches : NumUncondBranches;
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00002445 Statistic &BranchTakenFreq =
Chandler Carruth7a715da2015-03-05 03:19:05 +00002446 (MBB.succ_size() > 1) ? CondBranchTakenFreq : UncondBranchTakenFreq;
2447 for (MachineBasicBlock *Succ : MBB.successors()) {
Chandler Carruthae4e8002011-11-02 07:17:12 +00002448 // Skip if this successor is a fallthrough.
Chandler Carruth7a715da2015-03-05 03:19:05 +00002449 if (MBB.isLayoutSuccessor(Succ))
Chandler Carruthae4e8002011-11-02 07:17:12 +00002450 continue;
2451
Chandler Carruth7a715da2015-03-05 03:19:05 +00002452 BlockFrequency EdgeFreq =
2453 BlockFreq * MBPI->getEdgeProbability(&MBB, Succ);
Chandler Carruthae4e8002011-11-02 07:17:12 +00002454 ++NumBranches;
2455 BranchTakenFreq += EdgeFreq.getFrequency();
2456 }
2457 }
2458
2459 return false;
2460}