blob: d7321a82ce20b179dd173c0968ea32d54abac79e [file] [log] [blame]
Chandler Carruth10281422011-10-21 06:46:38 +00001//===-- MachineBlockPlacement.cpp - Basic Block Code Layout optimization --===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Chandler Carruthbd1be4d2011-10-23 09:18:45 +000010// This file implements basic block placement transformations using the CFG
11// structure and branch probability estimates.
Chandler Carruth10281422011-10-21 06:46:38 +000012//
Chandler Carruthbd1be4d2011-10-23 09:18:45 +000013// The pass strives to preserve the structure of the CFG (that is, retain
Benjamin Kramerbde91762012-06-02 10:20:22 +000014// a topological ordering of basic blocks) in the absence of a *strong* signal
Chandler Carruthbd1be4d2011-10-23 09:18:45 +000015// to the contrary from probabilities. However, within the CFG structure, it
16// attempts to choose an ordering which favors placing more likely sequences of
17// blocks adjacent to each other.
18//
19// The algorithm works from the inner-most loop within a function outward, and
20// at each stage walks through the basic blocks, trying to coalesce them into
21// sequential chains where allowed by the CFG (or demanded by heavy
22// probabilities). Finally, it walks the blocks in topological order, and the
23// first time it reaches a chain of basic blocks, it schedules them in the
24// function in-order.
Chandler Carruth10281422011-10-21 06:46:38 +000025//
26//===----------------------------------------------------------------------===//
27
Chandler Carruthed0881b2012-12-03 16:50:05 +000028#include "llvm/CodeGen/Passes.h"
Haicheng Wu5b458cc2016-06-09 15:24:29 +000029#include "llvm/CodeGen/TargetPassConfig.h"
30#include "BranchFolding.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000031#include "llvm/ADT/DenseMap.h"
32#include "llvm/ADT/SmallPtrSet.h"
33#include "llvm/ADT/SmallVector.h"
34#include "llvm/ADT/Statistic.h"
Chandler Carruth8b9737c2011-10-21 08:57:37 +000035#include "llvm/CodeGen/MachineBasicBlock.h"
Chandler Carruth10281422011-10-21 06:46:38 +000036#include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
37#include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
Daniel Jasper471e8562015-03-04 11:05:34 +000038#include "llvm/CodeGen/MachineDominators.h"
Chandler Carruth10281422011-10-21 06:46:38 +000039#include "llvm/CodeGen/MachineFunction.h"
Chandler Carruth10281422011-10-21 06:46:38 +000040#include "llvm/CodeGen/MachineFunctionPass.h"
Chandler Carruth8b9737c2011-10-21 08:57:37 +000041#include "llvm/CodeGen/MachineLoopInfo.h"
42#include "llvm/CodeGen/MachineModuleInfo.h"
Chandler Carruth10281422011-10-21 06:46:38 +000043#include "llvm/Support/Allocator.h"
Nadav Rotemc3b0f502013-04-12 00:48:32 +000044#include "llvm/Support/CommandLine.h"
Chandler Carruthbd1be4d2011-10-23 09:18:45 +000045#include "llvm/Support/Debug.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000046#include "llvm/Support/raw_ostream.h"
Chandler Carruth10281422011-10-21 06:46:38 +000047#include "llvm/Target/TargetInstrInfo.h"
Chandler Carruth8b9737c2011-10-21 08:57:37 +000048#include "llvm/Target/TargetLowering.h"
Eric Christopherd9134482014-08-04 21:25:23 +000049#include "llvm/Target/TargetSubtargetInfo.h"
Chandler Carruth10281422011-10-21 06:46:38 +000050#include <algorithm>
51using namespace llvm;
52
Chandler Carruthd0dced52015-03-05 02:28:25 +000053#define DEBUG_TYPE "block-placement"
Chandler Carruth1b9dde02014-04-22 02:02:50 +000054
Chandler Carruthae4e8002011-11-02 07:17:12 +000055STATISTIC(NumCondBranches, "Number of conditional branches");
Craig Topper77ec0772015-09-16 03:52:32 +000056STATISTIC(NumUncondBranches, "Number of unconditional branches");
Chandler Carruthae4e8002011-11-02 07:17:12 +000057STATISTIC(CondBranchTakenFreq,
58 "Potential frequency of taking conditional branches");
59STATISTIC(UncondBranchTakenFreq,
60 "Potential frequency of taking unconditional branches");
61
Nadav Rotemc3b0f502013-04-12 00:48:32 +000062static cl::opt<unsigned> AlignAllBlock("align-all-blocks",
63 cl::desc("Force the alignment of all "
64 "blocks in the function."),
65 cl::init(0), cl::Hidden);
66
Geoff Berry10494ac2016-01-21 17:25:52 +000067static cl::opt<unsigned> AlignAllNonFallThruBlocks(
68 "align-all-nofallthru-blocks",
69 cl::desc("Force the alignment of all "
70 "blocks that have no fall-through predecessors (i.e. don't add "
71 "nops that are executed)."),
72 cl::init(0), cl::Hidden);
73
Benjamin Kramerc8160d62013-11-20 19:08:44 +000074// FIXME: Find a good default for this flag and remove the flag.
Chandler Carruth2fc3fe12015-03-05 02:35:31 +000075static cl::opt<unsigned> ExitBlockBias(
76 "block-placement-exit-block-bias",
77 cl::desc("Block frequency percentage a loop exit block needs "
78 "over the original exit to be considered the new exit."),
79 cl::init(0), cl::Hidden);
Benjamin Kramerc8160d62013-11-20 19:08:44 +000080
Daniel Jasper471e8562015-03-04 11:05:34 +000081static cl::opt<bool> OutlineOptionalBranches(
82 "outline-optional-branches",
83 cl::desc("Put completely optional branches, i.e. branches with a common "
84 "post dominator, out of line."),
85 cl::init(false), cl::Hidden);
86
Daniel Jasper214997c2015-03-20 10:00:37 +000087static cl::opt<unsigned> OutlineOptionalThreshold(
88 "outline-optional-threshold",
89 cl::desc("Don't outline optional branches that are a single block with an "
90 "instruction count below this threshold"),
91 cl::init(4), cl::Hidden);
92
Cong Houb90b9e02015-11-02 21:24:00 +000093static cl::opt<unsigned> LoopToColdBlockRatio(
94 "loop-to-cold-block-ratio",
95 cl::desc("Outline loop blocks from loop chain if (frequency of loop) / "
96 "(frequency of block) is greater than this ratio"),
97 cl::init(5), cl::Hidden);
98
Cong Hou7745dbc2015-10-19 23:16:40 +000099static cl::opt<bool>
100 PreciseRotationCost("precise-rotation-cost",
101 cl::desc("Model the cost of loop rotation more "
102 "precisely by using profile data."),
103 cl::init(false), cl::Hidden);
Xinliang David Lif0ab6df2016-05-12 02:04:41 +0000104static cl::opt<bool>
105 ForcePreciseRotationCost("force-precise-rotation-cost",
Xinliang David Lib840bb82016-05-12 16:39:02 +0000106 cl::desc("Force the use of precise cost "
107 "loop rotation strategy."),
Xinliang David Lif0ab6df2016-05-12 02:04:41 +0000108 cl::init(false), cl::Hidden);
Cong Hou7745dbc2015-10-19 23:16:40 +0000109
110static cl::opt<unsigned> MisfetchCost(
111 "misfetch-cost",
112 cl::desc("Cost that models the probablistic risk of an instruction "
113 "misfetch due to a jump comparing to falling through, whose cost "
114 "is zero."),
115 cl::init(1), cl::Hidden);
116
117static cl::opt<unsigned> JumpInstCost("jump-inst-cost",
118 cl::desc("Cost of jump instructions."),
119 cl::init(1), cl::Hidden);
120
Haicheng Wu5b458cc2016-06-09 15:24:29 +0000121static cl::opt<bool>
122BranchFoldPlacement("branch-fold-placement",
123 cl::desc("Perform branch folding during placement. "
124 "Reduces code size."),
125 cl::init(true), cl::Hidden);
126
Xinliang David Liff287372016-06-03 23:48:36 +0000127extern cl::opt<unsigned> StaticLikelyProb;
128
Chandler Carruth10281422011-10-21 06:46:38 +0000129namespace {
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000130class BlockChain;
Chandler Carruth10281422011-10-21 06:46:38 +0000131/// \brief Type for our function-wide basic block -> block chain mapping.
132typedef DenseMap<MachineBasicBlock *, BlockChain *> BlockToChainMapType;
133}
134
135namespace {
136/// \brief A chain of blocks which will be laid out contiguously.
137///
138/// This is the datastructure representing a chain of consecutive blocks that
139/// are profitable to layout together in order to maximize fallthrough
Chandler Carruth9139f442012-06-26 05:16:37 +0000140/// probabilities and code locality. We also can use a block chain to represent
141/// a sequence of basic blocks which have some external (correctness)
142/// requirement for sequential layout.
Chandler Carruth10281422011-10-21 06:46:38 +0000143///
Chandler Carruth9139f442012-06-26 05:16:37 +0000144/// Chains can be built around a single basic block and can be merged to grow
145/// them. They participate in a block-to-chain mapping, which is updated
146/// automatically as chains are merged together.
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000147class BlockChain {
148 /// \brief The sequence of blocks belonging to this chain.
Chandler Carruth10281422011-10-21 06:46:38 +0000149 ///
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000150 /// This is the sequence of blocks for a particular chain. These will be laid
151 /// out in-order within the function.
152 SmallVector<MachineBasicBlock *, 4> Blocks;
Chandler Carruth10281422011-10-21 06:46:38 +0000153
154 /// \brief A handle to the function-wide basic block to block chain mapping.
155 ///
156 /// This is retained in each block chain to simplify the computation of child
157 /// block chains for SCC-formation and iteration. We store the edges to child
158 /// basic blocks, and map them back to their associated chains using this
159 /// structure.
160 BlockToChainMapType &BlockToChain;
161
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000162public:
Chandler Carruth10281422011-10-21 06:46:38 +0000163 /// \brief Construct a new BlockChain.
164 ///
165 /// This builds a new block chain representing a single basic block in the
166 /// function. It also registers itself as the chain that block participates
167 /// in with the BlockToChain mapping.
168 BlockChain(BlockToChainMapType &BlockToChain, MachineBasicBlock *BB)
Philip Reamesae27b232016-03-03 00:58:43 +0000169 : Blocks(1, BB), BlockToChain(BlockToChain), UnscheduledPredecessors(0) {
Chandler Carruth10281422011-10-21 06:46:38 +0000170 assert(BB && "Cannot create a chain with a null basic block");
171 BlockToChain[BB] = this;
172 }
173
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000174 /// \brief Iterator over blocks within the chain.
Chandler Carruthccc7e422012-04-16 01:12:56 +0000175 typedef SmallVectorImpl<MachineBasicBlock *>::iterator iterator;
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000176
177 /// \brief Beginning of blocks within the chain.
Chandler Carruthccc7e422012-04-16 01:12:56 +0000178 iterator begin() { return Blocks.begin(); }
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000179
180 /// \brief End of blocks within the chain.
Chandler Carruthccc7e422012-04-16 01:12:56 +0000181 iterator end() { return Blocks.end(); }
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000182
183 /// \brief Merge a block chain into this one.
Chandler Carruth10281422011-10-21 06:46:38 +0000184 ///
185 /// This routine merges a block chain into this one. It takes care of forming
186 /// a contiguous sequence of basic blocks, updating the edge list, and
187 /// updating the block -> chain mapping. It does not free or tear down the
188 /// old chain, but the old chain's block list is no longer valid.
Jakub Staszak90616162011-12-21 23:02:08 +0000189 void merge(MachineBasicBlock *BB, BlockChain *Chain) {
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000190 assert(BB);
191 assert(!Blocks.empty());
Chandler Carruth10281422011-10-21 06:46:38 +0000192
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000193 // Fast path in case we don't have a chain already.
194 if (!Chain) {
195 assert(!BlockToChain[BB]);
196 Blocks.push_back(BB);
197 BlockToChain[BB] = this;
198 return;
Chandler Carruth10281422011-10-21 06:46:38 +0000199 }
200
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000201 assert(BB == *Chain->begin());
202 assert(Chain->begin() != Chain->end());
Chandler Carruth10281422011-10-21 06:46:38 +0000203
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000204 // Update the incoming blocks to point to this chain, and add them to the
205 // chain structure.
Chandler Carruth7a715da2015-03-05 03:19:05 +0000206 for (MachineBasicBlock *ChainBB : *Chain) {
207 Blocks.push_back(ChainBB);
208 assert(BlockToChain[ChainBB] == Chain && "Incoming blocks not in chain");
209 BlockToChain[ChainBB] = this;
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000210 }
Chandler Carruth10281422011-10-21 06:46:38 +0000211 }
Chandler Carruth8d150782011-11-13 11:20:44 +0000212
Chandler Carruth49158902012-04-08 14:37:01 +0000213#ifndef NDEBUG
214 /// \brief Dump the blocks in this chain.
Nico Weber7408c702014-01-03 22:53:37 +0000215 LLVM_DUMP_METHOD void dump() {
Chandler Carruth7a715da2015-03-05 03:19:05 +0000216 for (MachineBasicBlock *MBB : *this)
217 MBB->dump();
Chandler Carruth49158902012-04-08 14:37:01 +0000218 }
219#endif // NDEBUG
220
Philip Reamesae27b232016-03-03 00:58:43 +0000221 /// \brief Count of predecessors of any block within the chain which have not
222 /// yet been scheduled. In general, we will delay scheduling this chain
223 /// until those predecessors are scheduled (or we find a sufficiently good
224 /// reason to override this heuristic.) Note that when forming loop chains,
225 /// blocks outside the loop are ignored and treated as if they were already
226 /// scheduled.
Chandler Carruth8d150782011-11-13 11:20:44 +0000227 ///
Philip Reamesae27b232016-03-03 00:58:43 +0000228 /// Note: This field is reinitialized multiple times - once for each loop,
229 /// and then once for the function as a whole.
230 unsigned UnscheduledPredecessors;
Chandler Carruth10281422011-10-21 06:46:38 +0000231};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000232}
Chandler Carruth10281422011-10-21 06:46:38 +0000233
234namespace {
235class MachineBlockPlacement : public MachineFunctionPass {
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000236 /// \brief A typedef for a block filter set.
237 typedef SmallPtrSet<MachineBasicBlock *, 16> BlockFilterSet;
238
Chandler Carruth10281422011-10-21 06:46:38 +0000239 /// \brief A handle to the branch probability pass.
240 const MachineBranchProbabilityInfo *MBPI;
241
242 /// \brief A handle to the function-wide block frequency pass.
Haicheng Wu5b458cc2016-06-09 15:24:29 +0000243 std::unique_ptr<BranchFolder::MBFIWrapper> MBFI;
Chandler Carruth10281422011-10-21 06:46:38 +0000244
Chandler Carruth8b9737c2011-10-21 08:57:37 +0000245 /// \brief A handle to the loop info.
Haicheng Wu5b458cc2016-06-09 15:24:29 +0000246 MachineLoopInfo *MLI;
Chandler Carruth8b9737c2011-10-21 08:57:37 +0000247
Chandler Carruth10281422011-10-21 06:46:38 +0000248 /// \brief A handle to the target's instruction info.
249 const TargetInstrInfo *TII;
250
Chandler Carruth8b9737c2011-10-21 08:57:37 +0000251 /// \brief A handle to the target's lowering info.
Benjamin Kramer56b31bd2013-01-11 20:05:37 +0000252 const TargetLoweringBase *TLI;
Chandler Carruth8b9737c2011-10-21 08:57:37 +0000253
Daniel Jasper471e8562015-03-04 11:05:34 +0000254 /// \brief A handle to the post dominator tree.
255 MachineDominatorTree *MDT;
256
257 /// \brief A set of blocks that are unavoidably execute, i.e. they dominate
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000258 /// all terminators of the MachineFunction.
Daniel Jasper471e8562015-03-04 11:05:34 +0000259 SmallPtrSet<MachineBasicBlock *, 4> UnavoidableBlocks;
260
Chandler Carruth10281422011-10-21 06:46:38 +0000261 /// \brief Allocator and owner of BlockChain structures.
262 ///
Chandler Carruth9139f442012-06-26 05:16:37 +0000263 /// We build BlockChains lazily while processing the loop structure of
264 /// a function. To reduce malloc traffic, we allocate them using this
265 /// slab-like allocator, and destroy them after the pass completes. An
266 /// important guarantee is that this allocator produces stable pointers to
267 /// the chains.
Chandler Carruth10281422011-10-21 06:46:38 +0000268 SpecificBumpPtrAllocator<BlockChain> ChainAllocator;
269
270 /// \brief Function wide BasicBlock to BlockChain mapping.
271 ///
272 /// This mapping allows efficiently moving from any given basic block to the
273 /// BlockChain it participates in, if any. We use it to, among other things,
274 /// allow implicitly defining edges between chains as the existing edges
275 /// between basic blocks.
276 DenseMap<MachineBasicBlock *, BlockChain *> BlockToChain;
277
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000278 void markChainSuccessors(BlockChain &Chain, MachineBasicBlock *LoopHeaderBB,
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000279 SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000280 SmallVectorImpl<MachineBasicBlock *> &EHPadWorkList,
Craig Topperc0196b12014-04-14 00:51:57 +0000281 const BlockFilterSet *BlockFilter = nullptr);
Jakub Staszak90616162011-12-21 23:02:08 +0000282 MachineBasicBlock *selectBestSuccessor(MachineBasicBlock *BB,
283 BlockChain &Chain,
284 const BlockFilterSet *BlockFilter);
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000285 MachineBasicBlock *
286 selectBestCandidateBlock(BlockChain &Chain,
Amaury Sechet9ee4ddd2016-04-07 06:34:47 +0000287 SmallVectorImpl<MachineBasicBlock *> &WorkList);
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000288 MachineBasicBlock *
289 getFirstUnplacedBlock(MachineFunction &F, const BlockChain &PlacedChain,
290 MachineFunction::iterator &PrevUnplacedBlockIt,
291 const BlockFilterSet *BlockFilter);
Amaury Secheteae09c22016-03-14 21:24:11 +0000292
293 /// \brief Add a basic block to the work list if it is apropriate.
294 ///
295 /// If the optional parameter BlockFilter is provided, only MBB
296 /// present in the set will be added to the worklist. If nullptr
297 /// is provided, no filtering occurs.
298 void fillWorkLists(MachineBasicBlock *MBB,
299 SmallPtrSetImpl<BlockChain *> &UpdatedPreds,
300 SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000301 SmallVectorImpl<MachineBasicBlock *> &EHPadWorkList,
Amaury Secheteae09c22016-03-14 21:24:11 +0000302 const BlockFilterSet *BlockFilter);
Chandler Carruth8d150782011-11-13 11:20:44 +0000303 void buildChain(MachineBasicBlock *BB, BlockChain &Chain,
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000304 SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000305 SmallVectorImpl<MachineBasicBlock *> &EHPadWorkList,
Craig Topperc0196b12014-04-14 00:51:57 +0000306 const BlockFilterSet *BlockFilter = nullptr);
Chandler Carruth8c0b41d2012-04-16 13:33:36 +0000307 MachineBasicBlock *findBestLoopTop(MachineLoop &L,
308 const BlockFilterSet &LoopBlockSet);
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000309 MachineBasicBlock *findBestLoopExit(MachineFunction &F, MachineLoop &L,
Chandler Carruthccc7e422012-04-16 01:12:56 +0000310 const BlockFilterSet &LoopBlockSet);
Cong Houb90b9e02015-11-02 21:24:00 +0000311 BlockFilterSet collectLoopBlockSet(MachineFunction &F, MachineLoop &L);
Jakub Staszak90616162011-12-21 23:02:08 +0000312 void buildLoopChains(MachineFunction &F, MachineLoop &L);
Chandler Carruth8c74c7b2012-04-16 09:31:23 +0000313 void rotateLoop(BlockChain &LoopChain, MachineBasicBlock *ExitingBB,
314 const BlockFilterSet &LoopBlockSet);
Cong Hou7745dbc2015-10-19 23:16:40 +0000315 void rotateLoopWithProfile(BlockChain &LoopChain, MachineLoop &L,
316 const BlockFilterSet &LoopBlockSet);
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000317 void buildCFGChains(MachineFunction &F);
Haicheng Wu90a55652016-05-24 22:16:14 +0000318 void optimizeBranches(MachineFunction &F);
Haicheng Wue749ce52016-04-29 17:06:44 +0000319 void alignBlocks(MachineFunction &F);
Chandler Carruth10281422011-10-21 06:46:38 +0000320
321public:
322 static char ID; // Pass identification, replacement for typeid
323 MachineBlockPlacement() : MachineFunctionPass(ID) {
324 initializeMachineBlockPlacementPass(*PassRegistry::getPassRegistry());
325 }
326
Craig Topper4584cd52014-03-07 09:26:03 +0000327 bool runOnMachineFunction(MachineFunction &F) override;
Chandler Carruth10281422011-10-21 06:46:38 +0000328
Craig Topper4584cd52014-03-07 09:26:03 +0000329 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruth10281422011-10-21 06:46:38 +0000330 AU.addRequired<MachineBranchProbabilityInfo>();
331 AU.addRequired<MachineBlockFrequencyInfo>();
Daniel Jasper471e8562015-03-04 11:05:34 +0000332 AU.addRequired<MachineDominatorTree>();
Chandler Carruth8b9737c2011-10-21 08:57:37 +0000333 AU.addRequired<MachineLoopInfo>();
Haicheng Wu5b458cc2016-06-09 15:24:29 +0000334 AU.addRequired<TargetPassConfig>();
Chandler Carruth10281422011-10-21 06:46:38 +0000335 MachineFunctionPass::getAnalysisUsage(AU);
336 }
Chandler Carruth10281422011-10-21 06:46:38 +0000337};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000338}
Chandler Carruth10281422011-10-21 06:46:38 +0000339
340char MachineBlockPlacement::ID = 0;
Andrew Trick1fa5bcb2012-02-08 21:23:13 +0000341char &llvm::MachineBlockPlacementID = MachineBlockPlacement::ID;
Chandler Carruthd0dced52015-03-05 02:28:25 +0000342INITIALIZE_PASS_BEGIN(MachineBlockPlacement, "block-placement",
Chandler Carruth10281422011-10-21 06:46:38 +0000343 "Branch Probability Basic Block Placement", false, false)
344INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
345INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
Daniel Jasper471e8562015-03-04 11:05:34 +0000346INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
Chandler Carruth8b9737c2011-10-21 08:57:37 +0000347INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
Chandler Carruthd0dced52015-03-05 02:28:25 +0000348INITIALIZE_PASS_END(MachineBlockPlacement, "block-placement",
Chandler Carruth10281422011-10-21 06:46:38 +0000349 "Branch Probability Basic Block Placement", false, false)
350
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000351#ifndef NDEBUG
352/// \brief Helper to print the name of a MBB.
353///
354/// Only used by debug logging.
Jakub Staszak90616162011-12-21 23:02:08 +0000355static std::string getBlockName(MachineBasicBlock *BB) {
Alp Tokere69170a2014-06-26 22:52:05 +0000356 std::string Result;
357 raw_string_ostream OS(Result);
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000358 OS << "BB#" << BB->getNumber();
Philip Reamesb9688f42016-03-02 21:45:13 +0000359 OS << " ('" << BB->getName() << "')";
Alp Tokere69170a2014-06-26 22:52:05 +0000360 OS.flush();
361 return Result;
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000362}
363#endif
364
Chandler Carrutheb4ec3a2011-11-13 11:34:55 +0000365/// \brief Mark a chain's successors as having one fewer preds.
366///
367/// When a chain is being merged into the "placed" chain, this routine will
368/// quickly walk the successors of each block in the chain and mark them as
369/// having one fewer active predecessor. It also adds any successors of this
370/// chain which reach the zero-predecessor state to the worklist passed in.
Chandler Carruth8d150782011-11-13 11:20:44 +0000371void MachineBlockPlacement::markChainSuccessors(
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000372 BlockChain &Chain, MachineBasicBlock *LoopHeaderBB,
Chandler Carruth8d150782011-11-13 11:20:44 +0000373 SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000374 SmallVectorImpl<MachineBasicBlock *> &EHPadWorkList,
Jakub Staszak90616162011-12-21 23:02:08 +0000375 const BlockFilterSet *BlockFilter) {
Chandler Carruth8d150782011-11-13 11:20:44 +0000376 // Walk all the blocks in this chain, marking their successors as having
377 // a predecessor placed.
Chandler Carruth7a715da2015-03-05 03:19:05 +0000378 for (MachineBasicBlock *MBB : Chain) {
Chandler Carruth8d150782011-11-13 11:20:44 +0000379 // Add any successors for which this is the only un-placed in-loop
380 // predecessor to the worklist as a viable candidate for CFG-neutral
381 // placement. No subsequent placement of this block will violate the CFG
382 // shape, so we get to use heuristics to choose a favorable placement.
Chandler Carruth7a715da2015-03-05 03:19:05 +0000383 for (MachineBasicBlock *Succ : MBB->successors()) {
384 if (BlockFilter && !BlockFilter->count(Succ))
Chandler Carruth8d150782011-11-13 11:20:44 +0000385 continue;
Chandler Carruth7a715da2015-03-05 03:19:05 +0000386 BlockChain &SuccChain = *BlockToChain[Succ];
Chandler Carruth8d150782011-11-13 11:20:44 +0000387 // Disregard edges within a fixed chain, or edges to the loop header.
Chandler Carruth7a715da2015-03-05 03:19:05 +0000388 if (&Chain == &SuccChain || Succ == LoopHeaderBB)
Chandler Carruth8d150782011-11-13 11:20:44 +0000389 continue;
Chandler Carruth10281422011-10-21 06:46:38 +0000390
Chandler Carruth8d150782011-11-13 11:20:44 +0000391 // This is a cross-chain edge that is within the loop, so decrement the
392 // loop predecessor count of the destination chain.
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000393 if (SuccChain.UnscheduledPredecessors == 0 ||
394 --SuccChain.UnscheduledPredecessors > 0)
395 continue;
396
397 auto *MBB = *SuccChain.begin();
398 if (MBB->isEHPad())
399 EHPadWorkList.push_back(MBB);
400 else
401 BlockWorkList.push_back(MBB);
Chandler Carruth10281422011-10-21 06:46:38 +0000402 }
403 }
Chandler Carruth8d150782011-11-13 11:20:44 +0000404}
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000405
Chandler Carruthb3361722011-11-13 11:34:53 +0000406/// \brief Select the best successor for a block.
407///
408/// This looks across all successors of a particular block and attempts to
409/// select the "best" one to be the layout successor. It only considers direct
410/// successors which also pass the block filter. It will attempt to avoid
411/// breaking CFG structure, but cave and break such structures in the case of
412/// very hot successor edges.
413///
414/// \returns The best successor block found, or null if none are viable.
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000415MachineBasicBlock *
416MachineBlockPlacement::selectBestSuccessor(MachineBasicBlock *BB,
417 BlockChain &Chain,
418 const BlockFilterSet *BlockFilter) {
Xinliang David Liff287372016-06-03 23:48:36 +0000419 const BranchProbability HotProb(StaticLikelyProb, 100);
Chandler Carruthb3361722011-11-13 11:34:53 +0000420
Craig Topperc0196b12014-04-14 00:51:57 +0000421 MachineBasicBlock *BestSucc = nullptr;
Cong Houd97c1002015-12-01 05:29:22 +0000422 auto BestProb = BranchProbability::getZero();
Chandler Carruthb3361722011-11-13 11:34:53 +0000423
Cong Houd97c1002015-12-01 05:29:22 +0000424 // Adjust edge probabilities by excluding edges pointing to blocks that is
425 // either not in BlockFilter or is already in the current chain. Consider the
426 // following CFG:
Cong Hou41cf1a52015-11-18 00:52:52 +0000427 //
428 // --->A
429 // | / \
430 // | B C
431 // | \ / \
432 // ----D E
433 //
434 // Assume A->C is very hot (>90%), and C->D has a 50% probability, then after
435 // A->C is chosen as a fall-through, D won't be selected as a successor of C
436 // due to CFG constraint (the probability of C->D is not greater than
437 // HotProb). If we exclude E that is not in BlockFilter when calculating the
438 // probability of C->D, D will be selected and we will get A C D B as the
439 // layout of this loop.
Cong Houd97c1002015-12-01 05:29:22 +0000440 auto AdjustedSumProb = BranchProbability::getOne();
Cong Hou41cf1a52015-11-18 00:52:52 +0000441 SmallVector<MachineBasicBlock *, 4> Successors;
442 for (MachineBasicBlock *Succ : BB->successors()) {
443 bool SkipSucc = false;
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000444 if (Succ->isEHPad() || (BlockFilter && !BlockFilter->count(Succ))) {
Cong Hou41cf1a52015-11-18 00:52:52 +0000445 SkipSucc = true;
446 } else {
447 BlockChain *SuccChain = BlockToChain[Succ];
448 if (SuccChain == &Chain) {
Cong Hou41cf1a52015-11-18 00:52:52 +0000449 SkipSucc = true;
450 } else if (Succ != *SuccChain->begin()) {
451 DEBUG(dbgs() << " " << getBlockName(Succ) << " -> Mid chain!\n");
452 continue;
453 }
454 }
455 if (SkipSucc)
Cong Houd97c1002015-12-01 05:29:22 +0000456 AdjustedSumProb -= MBPI->getEdgeProbability(BB, Succ);
Cong Hou41cf1a52015-11-18 00:52:52 +0000457 else
458 Successors.push_back(Succ);
459 }
460
461 DEBUG(dbgs() << "Attempting merge from: " << getBlockName(BB) << "\n");
462 for (MachineBasicBlock *Succ : Successors) {
Cong Houd97c1002015-12-01 05:29:22 +0000463 BranchProbability SuccProb;
464 uint32_t SuccProbN = MBPI->getEdgeProbability(BB, Succ).getNumerator();
465 uint32_t SuccProbD = AdjustedSumProb.getNumerator();
466 if (SuccProbN >= SuccProbD)
467 SuccProb = BranchProbability::getOne();
468 else
469 SuccProb = BranchProbability(SuccProbN, SuccProbD);
Chandler Carruthb3361722011-11-13 11:34:53 +0000470
Daniel Jasper471e8562015-03-04 11:05:34 +0000471 // If we outline optional branches, look whether Succ is unavoidable, i.e.
472 // dominates all terminators of the MachineFunction. If it does, other
473 // successors must be optional. Don't do this for cold branches.
474 if (OutlineOptionalBranches && SuccProb > HotProb.getCompl() &&
Daniel Jasper214997c2015-03-20 10:00:37 +0000475 UnavoidableBlocks.count(Succ) > 0) {
476 auto HasShortOptionalBranch = [&]() {
477 for (MachineBasicBlock *Pred : Succ->predecessors()) {
478 // Check whether there is an unplaced optional branch.
479 if (Pred == Succ || (BlockFilter && !BlockFilter->count(Pred)) ||
480 BlockToChain[Pred] == &Chain)
481 continue;
482 // Check whether the optional branch has exactly one BB.
483 if (Pred->pred_size() > 1 || *Pred->pred_begin() != BB)
484 continue;
485 // Check whether the optional branch is small.
486 if (Pred->size() < OutlineOptionalThreshold)
487 return true;
488 }
489 return false;
490 };
491 if (!HasShortOptionalBranch())
492 return Succ;
493 }
Daniel Jasper471e8562015-03-04 11:05:34 +0000494
Chandler Carruthb3361722011-11-13 11:34:53 +0000495 // Only consider successors which are either "hot", or wouldn't violate
496 // any CFG constraints.
Cong Hou41cf1a52015-11-18 00:52:52 +0000497 BlockChain &SuccChain = *BlockToChain[Succ];
Philip Reamesae27b232016-03-03 00:58:43 +0000498 if (SuccChain.UnscheduledPredecessors != 0) {
Chandler Carruth18dfac32011-11-20 11:22:06 +0000499 if (SuccProb < HotProb) {
Daniel Jaspered9eb722015-02-18 08:19:16 +0000500 DEBUG(dbgs() << " " << getBlockName(Succ) << " -> " << SuccProb
Chandler Carruth260258b2013-11-25 00:43:41 +0000501 << " (prob) (CFG conflict)\n");
Chandler Carruth18dfac32011-11-20 11:22:06 +0000502 continue;
503 }
504
Daniel Jasper4d7b0432015-02-18 08:18:07 +0000505 // Make sure that a hot successor doesn't have a globally more
506 // important predecessor.
Cong Houd97c1002015-12-01 05:29:22 +0000507 auto RealSuccProb = MBPI->getEdgeProbability(BB, Succ);
Dehao Chen769219b2016-06-08 21:30:12 +0000508 BlockFrequency CandidateEdgeFreq = MBFI->getBlockFreq(BB) * RealSuccProb;
Daniel Jasper4d7b0432015-02-18 08:18:07 +0000509 bool BadCFGConflict = false;
Daniel Jaspered9eb722015-02-18 08:19:16 +0000510 for (MachineBasicBlock *Pred : Succ->predecessors()) {
Philip Reames23d93392016-03-03 00:01:42 +0000511 if (Pred == Succ || BlockToChain[Pred] == &SuccChain ||
512 (BlockFilter && !BlockFilter->count(Pred)) ||
Daniel Jaspered9eb722015-02-18 08:19:16 +0000513 BlockToChain[Pred] == &Chain)
Chandler Carruthe3288142015-01-14 20:19:29 +0000514 continue;
Daniel Jasper4d7b0432015-02-18 08:18:07 +0000515 BlockFrequency PredEdgeFreq =
Daniel Jaspered9eb722015-02-18 08:19:16 +0000516 MBFI->getBlockFreq(Pred) * MBPI->getEdgeProbability(Pred, Succ);
Dehao Chen769219b2016-06-08 21:30:12 +0000517 // A B
518 // \ /
519 // C
520 // We layout ACB iff A.freq > C.freq * HotProb
521 // i.e. A.freq > A.freq * HotProb + B.freq * HotProb
522 // i.e. A.freq * (1 - HotProb) > B.freq * HotProb
523 // A: CandidateEdge
524 // B: PredEdge
525 if (PredEdgeFreq * HotProb >= CandidateEdgeFreq * HotProb.getCompl()) {
Daniel Jasper4d7b0432015-02-18 08:18:07 +0000526 BadCFGConflict = true;
527 break;
Chandler Carruthe3288142015-01-14 20:19:29 +0000528 }
Chandler Carruth18dfac32011-11-20 11:22:06 +0000529 }
Daniel Jasper4d7b0432015-02-18 08:18:07 +0000530 if (BadCFGConflict) {
Daniel Jaspered9eb722015-02-18 08:19:16 +0000531 DEBUG(dbgs() << " " << getBlockName(Succ) << " -> " << SuccProb
Daniel Jasper4d7b0432015-02-18 08:18:07 +0000532 << " (prob) (non-cold CFG conflict)\n");
533 continue;
534 }
Chandler Carruthb3361722011-11-13 11:34:53 +0000535 }
536
Daniel Jaspered9eb722015-02-18 08:19:16 +0000537 DEBUG(dbgs() << " " << getBlockName(Succ) << " -> " << SuccProb
Chandler Carruthb3361722011-11-13 11:34:53 +0000538 << " (prob)"
Philip Reamesae27b232016-03-03 00:58:43 +0000539 << (SuccChain.UnscheduledPredecessors != 0 ? " (CFG break)" : "")
Chandler Carruthb3361722011-11-13 11:34:53 +0000540 << "\n");
Cong Houd97c1002015-12-01 05:29:22 +0000541 if (BestSucc && BestProb >= SuccProb)
Chandler Carruthb3361722011-11-13 11:34:53 +0000542 continue;
Daniel Jaspered9eb722015-02-18 08:19:16 +0000543 BestSucc = Succ;
Cong Houd97c1002015-12-01 05:29:22 +0000544 BestProb = SuccProb;
Chandler Carruthb3361722011-11-13 11:34:53 +0000545 }
546 return BestSucc;
547}
548
Chandler Carruthf9213fe2011-11-13 11:42:26 +0000549/// \brief Select the best block from a worklist.
550///
551/// This looks through the provided worklist as a list of candidate basic
552/// blocks and select the most profitable one to place. The definition of
553/// profitable only really makes sense in the context of a loop. This returns
554/// the most frequently visited block in the worklist, which in the case of
555/// a loop, is the one most desirable to be physically close to the rest of the
556/// loop body in order to improve icache behavior.
557///
558/// \returns The best block found, or null if none are viable.
559MachineBasicBlock *MachineBlockPlacement::selectBestCandidateBlock(
Amaury Sechet9ee4ddd2016-04-07 06:34:47 +0000560 BlockChain &Chain, SmallVectorImpl<MachineBasicBlock *> &WorkList) {
Chandler Carruth0af6a0b2011-11-14 09:46:33 +0000561 // Once we need to walk the worklist looking for a candidate, cleanup the
562 // worklist of already placed entries.
563 // FIXME: If this shows up on profiles, it could be folded (at the cost of
564 // some code complexity) into the loop below.
565 WorkList.erase(std::remove_if(WorkList.begin(), WorkList.end(),
Benjamin Kramer3a377bc2014-03-01 11:47:00 +0000566 [&](MachineBasicBlock *BB) {
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000567 return BlockToChain.lookup(BB) == &Chain;
568 }),
Chandler Carruth0af6a0b2011-11-14 09:46:33 +0000569 WorkList.end());
570
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000571 if (WorkList.empty())
572 return nullptr;
573
574 bool IsEHPad = WorkList[0]->isEHPad();
575
Craig Topperc0196b12014-04-14 00:51:57 +0000576 MachineBasicBlock *BestBlock = nullptr;
Chandler Carruthf9213fe2011-11-13 11:42:26 +0000577 BlockFrequency BestFreq;
Chandler Carruth7a715da2015-03-05 03:19:05 +0000578 for (MachineBasicBlock *MBB : WorkList) {
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000579 assert(MBB->isEHPad() == IsEHPad);
580
Chandler Carruth7a715da2015-03-05 03:19:05 +0000581 BlockChain &SuccChain = *BlockToChain[MBB];
Philip Reames02e11322016-03-02 22:40:51 +0000582 if (&SuccChain == &Chain)
Chandler Carruthf9213fe2011-11-13 11:42:26 +0000583 continue;
Junmo Park4ba6cf62016-03-11 05:07:07 +0000584
Philip Reamesae27b232016-03-03 00:58:43 +0000585 assert(SuccChain.UnscheduledPredecessors == 0 && "Found CFG-violating block");
Chandler Carruthf9213fe2011-11-13 11:42:26 +0000586
Chandler Carruth7a715da2015-03-05 03:19:05 +0000587 BlockFrequency CandidateFreq = MBFI->getBlockFreq(MBB);
588 DEBUG(dbgs() << " " << getBlockName(MBB) << " -> ";
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000589 MBFI->printBlockFreq(dbgs(), CandidateFreq) << " (freq)\n");
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000590
591 // For ehpad, we layout the least probable first as to avoid jumping back
592 // from least probable landingpads to more probable ones.
593 //
594 // FIXME: Using probability is probably (!) not the best way to achieve
595 // this. We should probably have a more principled approach to layout
596 // cleanup code.
597 //
598 // The goal is to get:
599 //
600 // +--------------------------+
601 // | V
602 // InnerLp -> InnerCleanup OuterLp -> OuterCleanup -> Resume
603 //
604 // Rather than:
605 //
606 // +-------------------------------------+
607 // V |
608 // OuterLp -> OuterCleanup -> Resume InnerLp -> InnerCleanup
609 if (BestBlock && (IsEHPad ^ (BestFreq >= CandidateFreq)))
Chandler Carruthf9213fe2011-11-13 11:42:26 +0000610 continue;
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000611
Chandler Carruth7a715da2015-03-05 03:19:05 +0000612 BestBlock = MBB;
Chandler Carruthf9213fe2011-11-13 11:42:26 +0000613 BestFreq = CandidateFreq;
614 }
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000615
Chandler Carruthf9213fe2011-11-13 11:42:26 +0000616 return BestBlock;
617}
618
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000619/// \brief Retrieve the first unplaced basic block.
620///
621/// This routine is called when we are unable to use the CFG to walk through
622/// all of the basic blocks and form a chain due to unnatural loops in the CFG.
Chandler Carruth9b548a7f2011-11-15 06:26:43 +0000623/// We walk through the function's blocks in order, starting from the
624/// LastUnplacedBlockIt. We update this iterator on each call to avoid
625/// re-scanning the entire sequence on repeated calls to this routine.
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000626MachineBasicBlock *MachineBlockPlacement::getFirstUnplacedBlock(
Chandler Carruth9b548a7f2011-11-15 06:26:43 +0000627 MachineFunction &F, const BlockChain &PlacedChain,
628 MachineFunction::iterator &PrevUnplacedBlockIt,
Jakub Staszak90616162011-12-21 23:02:08 +0000629 const BlockFilterSet *BlockFilter) {
Chandler Carruth9b548a7f2011-11-15 06:26:43 +0000630 for (MachineFunction::iterator I = PrevUnplacedBlockIt, E = F.end(); I != E;
631 ++I) {
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +0000632 if (BlockFilter && !BlockFilter->count(&*I))
Chandler Carruth9b548a7f2011-11-15 06:26:43 +0000633 continue;
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +0000634 if (BlockToChain[&*I] != &PlacedChain) {
Chandler Carruth9b548a7f2011-11-15 06:26:43 +0000635 PrevUnplacedBlockIt = I;
Chandler Carruth4a87aa02011-11-23 03:03:21 +0000636 // Now select the head of the chain to which the unplaced block belongs
637 // as the block to place. This will force the entire chain to be placed,
638 // and satisfies the requirements of merging chains.
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +0000639 return *BlockToChain[&*I]->begin();
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000640 }
641 }
Craig Topperc0196b12014-04-14 00:51:57 +0000642 return nullptr;
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000643}
644
Amaury Secheteae09c22016-03-14 21:24:11 +0000645void MachineBlockPlacement::fillWorkLists(
646 MachineBasicBlock *MBB,
647 SmallPtrSetImpl<BlockChain *> &UpdatedPreds,
648 SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000649 SmallVectorImpl<MachineBasicBlock *> &EHPadWorkList,
Amaury Secheteae09c22016-03-14 21:24:11 +0000650 const BlockFilterSet *BlockFilter = nullptr) {
651 BlockChain &Chain = *BlockToChain[MBB];
652 if (!UpdatedPreds.insert(&Chain).second)
653 return;
654
655 assert(Chain.UnscheduledPredecessors == 0);
656 for (MachineBasicBlock *ChainBB : Chain) {
657 assert(BlockToChain[ChainBB] == &Chain);
658 for (MachineBasicBlock *Pred : ChainBB->predecessors()) {
659 if (BlockFilter && !BlockFilter->count(Pred))
660 continue;
661 if (BlockToChain[Pred] == &Chain)
662 continue;
663 ++Chain.UnscheduledPredecessors;
664 }
665 }
666
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000667 if (Chain.UnscheduledPredecessors != 0)
668 return;
669
670 MBB = *Chain.begin();
671 if (MBB->isEHPad())
672 EHPadWorkList.push_back(MBB);
673 else
674 BlockWorkList.push_back(MBB);
Amaury Secheteae09c22016-03-14 21:24:11 +0000675}
676
Chandler Carruth8d150782011-11-13 11:20:44 +0000677void MachineBlockPlacement::buildChain(
Daniel Jasper471e8562015-03-04 11:05:34 +0000678 MachineBasicBlock *BB, BlockChain &Chain,
Chandler Carruth8d150782011-11-13 11:20:44 +0000679 SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000680 SmallVectorImpl<MachineBasicBlock *> &EHPadWorkList,
Jakub Staszak90616162011-12-21 23:02:08 +0000681 const BlockFilterSet *BlockFilter) {
Chandler Carruth8d150782011-11-13 11:20:44 +0000682 assert(BB);
Jakub Staszak90616162011-12-21 23:02:08 +0000683 assert(BlockToChain[BB] == &Chain);
Chandler Carruth9b548a7f2011-11-15 06:26:43 +0000684 MachineFunction &F = *BB->getParent();
685 MachineFunction::iterator PrevUnplacedBlockIt = F.begin();
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000686
Chandler Carruth8d150782011-11-13 11:20:44 +0000687 MachineBasicBlock *LoopHeaderBB = BB;
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000688 markChainSuccessors(Chain, LoopHeaderBB, BlockWorkList, EHPadWorkList,
689 BlockFilter);
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000690 BB = *std::prev(Chain.end());
Chandler Carruth8d150782011-11-13 11:20:44 +0000691 for (;;) {
692 assert(BB);
Jakub Staszak90616162011-12-21 23:02:08 +0000693 assert(BlockToChain[BB] == &Chain);
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000694 assert(*std::prev(Chain.end()) == BB);
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000695
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +0000696 // Look for the best viable successor if there is one to place immediately
697 // after this block.
Duncan Sands291d47e2012-09-14 09:00:11 +0000698 MachineBasicBlock *BestSucc = selectBestSuccessor(BB, Chain, BlockFilter);
Chandler Carruth8d150782011-11-13 11:20:44 +0000699
700 // If an immediate successor isn't available, look for the best viable
701 // block among those we've identified as not violating the loop's CFG at
702 // this point. This won't be a fallthrough, but it will increase locality.
Chandler Carruthf9213fe2011-11-13 11:42:26 +0000703 if (!BestSucc)
Amaury Sechet9ee4ddd2016-04-07 06:34:47 +0000704 BestSucc = selectBestCandidateBlock(Chain, BlockWorkList);
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000705 if (!BestSucc)
706 BestSucc = selectBestCandidateBlock(Chain, EHPadWorkList);
Chandler Carruth8d150782011-11-13 11:20:44 +0000707
Chandler Carruth8d150782011-11-13 11:20:44 +0000708 if (!BestSucc) {
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000709 BestSucc =
710 getFirstUnplacedBlock(F, Chain, PrevUnplacedBlockIt, BlockFilter);
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000711 if (!BestSucc)
712 break;
713
714 DEBUG(dbgs() << "Unnatural loop CFG detected, forcibly merging the "
715 "layout successor until the CFG reduces\n");
Chandler Carruth8d150782011-11-13 11:20:44 +0000716 }
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000717
Chandler Carruth8d150782011-11-13 11:20:44 +0000718 // Place this block, updating the datastructures to reflect its placement.
Jakub Staszak90616162011-12-21 23:02:08 +0000719 BlockChain &SuccChain = *BlockToChain[BestSucc];
Philip Reamesae27b232016-03-03 00:58:43 +0000720 // Zero out UnscheduledPredecessors for the successor we're about to merge in case
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000721 // we selected a successor that didn't fit naturally into the CFG.
Philip Reamesae27b232016-03-03 00:58:43 +0000722 SuccChain.UnscheduledPredecessors = 0;
Philip Reamesb9688f42016-03-02 21:45:13 +0000723 DEBUG(dbgs() << "Merging from " << getBlockName(BB) << " to "
724 << getBlockName(BestSucc) << "\n");
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000725 markChainSuccessors(SuccChain, LoopHeaderBB, BlockWorkList, EHPadWorkList,
726 BlockFilter);
Chandler Carruth8d150782011-11-13 11:20:44 +0000727 Chain.merge(BestSucc, &SuccChain);
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000728 BB = *std::prev(Chain.end());
Jakub Staszak190c7122011-12-07 19:46:10 +0000729 }
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000730
731 DEBUG(dbgs() << "Finished forming chain for header block "
Philip Reamesb9688f42016-03-02 21:45:13 +0000732 << getBlockName(*Chain.begin()) << "\n");
Chandler Carruth10281422011-10-21 06:46:38 +0000733}
734
Chandler Carruth03adbd42011-11-27 13:34:33 +0000735/// \brief Find the best loop top block for layout.
Chandler Carruth9ffb97e2011-11-27 00:38:03 +0000736///
Chandler Carruth8c0b41d2012-04-16 13:33:36 +0000737/// Look for a block which is strictly better than the loop header for laying
738/// out at the top of the loop. This looks for one and only one pattern:
739/// a latch block with no conditional exit. This block will cause a conditional
740/// jump around it or will be the bottom of the loop if we lay it out in place,
741/// but if it it doesn't end up at the bottom of the loop for any reason,
742/// rotation alone won't fix it. Because such a block will always result in an
743/// unconditional jump (for the backedge) rotating it in front of the loop
744/// header is always profitable.
745MachineBasicBlock *
746MachineBlockPlacement::findBestLoopTop(MachineLoop &L,
747 const BlockFilterSet &LoopBlockSet) {
748 // Check that the header hasn't been fused with a preheader block due to
749 // crazy branches. If it has, we need to start with the header at the top to
750 // prevent pulling the preheader into the loop body.
751 BlockChain &HeaderChain = *BlockToChain[L.getHeader()];
752 if (!LoopBlockSet.count(*HeaderChain.begin()))
753 return L.getHeader();
754
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000755 DEBUG(dbgs() << "Finding best loop top for: " << getBlockName(L.getHeader())
756 << "\n");
Chandler Carruth8c0b41d2012-04-16 13:33:36 +0000757
758 BlockFrequency BestPredFreq;
Craig Topperc0196b12014-04-14 00:51:57 +0000759 MachineBasicBlock *BestPred = nullptr;
Chandler Carruth7a715da2015-03-05 03:19:05 +0000760 for (MachineBasicBlock *Pred : L.getHeader()->predecessors()) {
Chandler Carruth8c0b41d2012-04-16 13:33:36 +0000761 if (!LoopBlockSet.count(Pred))
762 continue;
763 DEBUG(dbgs() << " header pred: " << getBlockName(Pred) << ", "
Michael Gottesmanb78dec82013-12-14 00:25:45 +0000764 << Pred->succ_size() << " successors, ";
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000765 MBFI->printBlockFreq(dbgs(), Pred) << " freq\n");
Chandler Carruth8c0b41d2012-04-16 13:33:36 +0000766 if (Pred->succ_size() > 1)
767 continue;
768
769 BlockFrequency PredFreq = MBFI->getBlockFreq(Pred);
770 if (!BestPred || PredFreq > BestPredFreq ||
771 (!(PredFreq < BestPredFreq) &&
772 Pred->isLayoutSuccessor(L.getHeader()))) {
773 BestPred = Pred;
774 BestPredFreq = PredFreq;
775 }
776 }
777
778 // If no direct predecessor is fine, just use the loop header.
Philip Reamesb9688f42016-03-02 21:45:13 +0000779 if (!BestPred) {
780 DEBUG(dbgs() << " final top unchanged\n");
Chandler Carruth8c0b41d2012-04-16 13:33:36 +0000781 return L.getHeader();
Philip Reamesb9688f42016-03-02 21:45:13 +0000782 }
Chandler Carruth8c0b41d2012-04-16 13:33:36 +0000783
784 // Walk backwards through any straight line of predecessors.
785 while (BestPred->pred_size() == 1 &&
786 (*BestPred->pred_begin())->succ_size() == 1 &&
787 *BestPred->pred_begin() != L.getHeader())
788 BestPred = *BestPred->pred_begin();
789
790 DEBUG(dbgs() << " final top: " << getBlockName(BestPred) << "\n");
791 return BestPred;
792}
793
Chandler Carruth8c0b41d2012-04-16 13:33:36 +0000794/// \brief Find the best loop exiting block for layout.
795///
Chandler Carruth03adbd42011-11-27 13:34:33 +0000796/// This routine implements the logic to analyze the loop looking for the best
797/// block to layout at the top of the loop. Typically this is done to maximize
798/// fallthrough opportunities.
799MachineBasicBlock *
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000800MachineBlockPlacement::findBestLoopExit(MachineFunction &F, MachineLoop &L,
Chandler Carruthccc7e422012-04-16 01:12:56 +0000801 const BlockFilterSet &LoopBlockSet) {
Chandler Carruth68062612012-04-10 13:35:57 +0000802 // We don't want to layout the loop linearly in all cases. If the loop header
803 // is just a normal basic block in the loop, we want to look for what block
804 // within the loop is the best one to layout at the top. However, if the loop
805 // header has be pre-merged into a chain due to predecessors not having
806 // analyzable branches, *and* the predecessor it is merged with is *not* part
807 // of the loop, rotating the header into the middle of the loop will create
808 // a non-contiguous range of blocks which is Very Bad. So start with the
809 // header and only rotate if safe.
810 BlockChain &HeaderChain = *BlockToChain[L.getHeader()];
811 if (!LoopBlockSet.count(*HeaderChain.begin()))
Craig Topperc0196b12014-04-14 00:51:57 +0000812 return nullptr;
Chandler Carruth68062612012-04-10 13:35:57 +0000813
Chandler Carruth03adbd42011-11-27 13:34:33 +0000814 BlockFrequency BestExitEdgeFreq;
Chandler Carruthccc7e422012-04-16 01:12:56 +0000815 unsigned BestExitLoopDepth = 0;
Craig Topperc0196b12014-04-14 00:51:57 +0000816 MachineBasicBlock *ExitingBB = nullptr;
Chandler Carruth4f567202011-11-27 20:18:00 +0000817 // If there are exits to outer loops, loop rotation can severely limit
818 // fallthrough opportunites unless it selects such an exit. Keep a set of
819 // blocks where rotating to exit with that block will reach an outer loop.
820 SmallPtrSet<MachineBasicBlock *, 4> BlocksExitingToOuterLoop;
821
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000822 DEBUG(dbgs() << "Finding best loop exit for: " << getBlockName(L.getHeader())
823 << "\n");
Chandler Carruth7a715da2015-03-05 03:19:05 +0000824 for (MachineBasicBlock *MBB : L.getBlocks()) {
825 BlockChain &Chain = *BlockToChain[MBB];
Chandler Carruth03adbd42011-11-27 13:34:33 +0000826 // Ensure that this block is at the end of a chain; otherwise it could be
Chandler Carruth9a512a42015-04-15 13:19:54 +0000827 // mid-way through an inner loop or a successor of an unanalyzable branch.
Chandler Carruth7a715da2015-03-05 03:19:05 +0000828 if (MBB != *std::prev(Chain.end()))
Chandler Carruth9ffb97e2011-11-27 00:38:03 +0000829 continue;
Chandler Carruth9ffb97e2011-11-27 00:38:03 +0000830
Chandler Carruth03adbd42011-11-27 13:34:33 +0000831 // Now walk the successors. We need to establish whether this has a viable
832 // exiting successor and whether it has a viable non-exiting successor.
833 // We store the old exiting state and restore it if a viable looping
834 // successor isn't found.
835 MachineBasicBlock *OldExitingBB = ExitingBB;
836 BlockFrequency OldBestExitEdgeFreq = BestExitEdgeFreq;
Chandler Carruthccc7e422012-04-16 01:12:56 +0000837 bool HasLoopingSucc = false;
Chandler Carruth7a715da2015-03-05 03:19:05 +0000838 for (MachineBasicBlock *Succ : MBB->successors()) {
Reid Kleckner0e288232015-08-27 23:27:47 +0000839 if (Succ->isEHPad())
Chandler Carruth03adbd42011-11-27 13:34:33 +0000840 continue;
Chandler Carruth7a715da2015-03-05 03:19:05 +0000841 if (Succ == MBB)
Chandler Carruth03adbd42011-11-27 13:34:33 +0000842 continue;
Chandler Carruth7a715da2015-03-05 03:19:05 +0000843 BlockChain &SuccChain = *BlockToChain[Succ];
Chandler Carruth03adbd42011-11-27 13:34:33 +0000844 // Don't split chains, either this chain or the successor's chain.
Chandler Carruthccc7e422012-04-16 01:12:56 +0000845 if (&Chain == &SuccChain) {
Chandler Carruth7a715da2015-03-05 03:19:05 +0000846 DEBUG(dbgs() << " exiting: " << getBlockName(MBB) << " -> "
847 << getBlockName(Succ) << " (chain conflict)\n");
Chandler Carruth03adbd42011-11-27 13:34:33 +0000848 continue;
849 }
850
Cong Houd97c1002015-12-01 05:29:22 +0000851 auto SuccProb = MBPI->getEdgeProbability(MBB, Succ);
Chandler Carruth7a715da2015-03-05 03:19:05 +0000852 if (LoopBlockSet.count(Succ)) {
853 DEBUG(dbgs() << " looping: " << getBlockName(MBB) << " -> "
Cong Houd97c1002015-12-01 05:29:22 +0000854 << getBlockName(Succ) << " (" << SuccProb << ")\n");
Chandler Carruthccc7e422012-04-16 01:12:56 +0000855 HasLoopingSucc = true;
Chandler Carruth03adbd42011-11-27 13:34:33 +0000856 continue;
857 }
858
Chandler Carruthccc7e422012-04-16 01:12:56 +0000859 unsigned SuccLoopDepth = 0;
Chandler Carruth7a715da2015-03-05 03:19:05 +0000860 if (MachineLoop *ExitLoop = MLI->getLoopFor(Succ)) {
Chandler Carruthccc7e422012-04-16 01:12:56 +0000861 SuccLoopDepth = ExitLoop->getLoopDepth();
862 if (ExitLoop->contains(&L))
Chandler Carruth7a715da2015-03-05 03:19:05 +0000863 BlocksExitingToOuterLoop.insert(MBB);
Chandler Carruthccc7e422012-04-16 01:12:56 +0000864 }
865
Chandler Carruth7a715da2015-03-05 03:19:05 +0000866 BlockFrequency ExitEdgeFreq = MBFI->getBlockFreq(MBB) * SuccProb;
867 DEBUG(dbgs() << " exiting: " << getBlockName(MBB) << " -> "
868 << getBlockName(Succ) << " [L:" << SuccLoopDepth << "] (";
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000869 MBFI->printBlockFreq(dbgs(), ExitEdgeFreq) << ")\n");
Benjamin Kramerc8160d62013-11-20 19:08:44 +0000870 // Note that we bias this toward an existing layout successor to retain
871 // incoming order in the absence of better information. The exit must have
872 // a frequency higher than the current exit before we consider breaking
873 // the layout.
874 BranchProbability Bias(100 - ExitBlockBias, 100);
Chandler Carruth26d30172015-04-15 13:39:42 +0000875 if (!ExitingBB || SuccLoopDepth > BestExitLoopDepth ||
Chandler Carruthccc7e422012-04-16 01:12:56 +0000876 ExitEdgeFreq > BestExitEdgeFreq ||
Chandler Carruth7a715da2015-03-05 03:19:05 +0000877 (MBB->isLayoutSuccessor(Succ) &&
Benjamin Kramerc8160d62013-11-20 19:08:44 +0000878 !(ExitEdgeFreq < BestExitEdgeFreq * Bias))) {
Chandler Carruth03adbd42011-11-27 13:34:33 +0000879 BestExitEdgeFreq = ExitEdgeFreq;
Chandler Carruth7a715da2015-03-05 03:19:05 +0000880 ExitingBB = MBB;
Chandler Carrutha0545802011-11-27 09:22:53 +0000881 }
Chandler Carruth9ffb97e2011-11-27 00:38:03 +0000882 }
Chandler Carruth03adbd42011-11-27 13:34:33 +0000883
Chandler Carruthccc7e422012-04-16 01:12:56 +0000884 if (!HasLoopingSucc) {
Chandler Carruthcfb2b9d2015-04-15 13:26:41 +0000885 // Restore the old exiting state, no viable looping successor was found.
Chandler Carruth03adbd42011-11-27 13:34:33 +0000886 ExitingBB = OldExitingBB;
887 BestExitEdgeFreq = OldBestExitEdgeFreq;
Chandler Carruth03adbd42011-11-27 13:34:33 +0000888 }
Chandler Carruth9ffb97e2011-11-27 00:38:03 +0000889 }
Chandler Carruthccc7e422012-04-16 01:12:56 +0000890 // Without a candidate exiting block or with only a single block in the
Chandler Carruth03adbd42011-11-27 13:34:33 +0000891 // loop, just use the loop header to layout the loop.
892 if (!ExitingBB || L.getNumBlocks() == 1)
Craig Topperc0196b12014-04-14 00:51:57 +0000893 return nullptr;
Chandler Carruth9ffb97e2011-11-27 00:38:03 +0000894
Chandler Carruth4f567202011-11-27 20:18:00 +0000895 // Also, if we have exit blocks which lead to outer loops but didn't select
896 // one of them as the exiting block we are rotating toward, disable loop
897 // rotation altogether.
898 if (!BlocksExitingToOuterLoop.empty() &&
899 !BlocksExitingToOuterLoop.count(ExitingBB))
Craig Topperc0196b12014-04-14 00:51:57 +0000900 return nullptr;
Chandler Carruth4f567202011-11-27 20:18:00 +0000901
Chandler Carruth03adbd42011-11-27 13:34:33 +0000902 DEBUG(dbgs() << " Best exiting block: " << getBlockName(ExitingBB) << "\n");
Chandler Carruthccc7e422012-04-16 01:12:56 +0000903 return ExitingBB;
Chandler Carruth9ffb97e2011-11-27 00:38:03 +0000904}
905
Chandler Carruth8c74c7b2012-04-16 09:31:23 +0000906/// \brief Attempt to rotate an exiting block to the bottom of the loop.
907///
908/// Once we have built a chain, try to rotate it to line up the hot exit block
909/// with fallthrough out of the loop if doing so doesn't introduce unnecessary
910/// branches. For example, if the loop has fallthrough into its header and out
911/// of its bottom already, don't rotate it.
912void MachineBlockPlacement::rotateLoop(BlockChain &LoopChain,
913 MachineBasicBlock *ExitingBB,
914 const BlockFilterSet &LoopBlockSet) {
915 if (!ExitingBB)
916 return;
917
918 MachineBasicBlock *Top = *LoopChain.begin();
919 bool ViableTopFallthrough = false;
Chandler Carruth7a715da2015-03-05 03:19:05 +0000920 for (MachineBasicBlock *Pred : Top->predecessors()) {
921 BlockChain *PredChain = BlockToChain[Pred];
922 if (!LoopBlockSet.count(Pred) &&
923 (!PredChain || Pred == *std::prev(PredChain->end()))) {
Chandler Carruth8c74c7b2012-04-16 09:31:23 +0000924 ViableTopFallthrough = true;
925 break;
926 }
927 }
928
929 // If the header has viable fallthrough, check whether the current loop
930 // bottom is a viable exiting block. If so, bail out as rotating will
931 // introduce an unnecessary branch.
932 if (ViableTopFallthrough) {
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000933 MachineBasicBlock *Bottom = *std::prev(LoopChain.end());
Chandler Carruth7a715da2015-03-05 03:19:05 +0000934 for (MachineBasicBlock *Succ : Bottom->successors()) {
935 BlockChain *SuccChain = BlockToChain[Succ];
936 if (!LoopBlockSet.count(Succ) &&
937 (!SuccChain || Succ == *SuccChain->begin()))
Chandler Carruth8c74c7b2012-04-16 09:31:23 +0000938 return;
939 }
940 }
941
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000942 BlockChain::iterator ExitIt =
943 std::find(LoopChain.begin(), LoopChain.end(), ExitingBB);
Chandler Carruth8c74c7b2012-04-16 09:31:23 +0000944 if (ExitIt == LoopChain.end())
945 return;
946
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000947 std::rotate(LoopChain.begin(), std::next(ExitIt), LoopChain.end());
Chandler Carruth8c74c7b2012-04-16 09:31:23 +0000948}
949
Cong Hou7745dbc2015-10-19 23:16:40 +0000950/// \brief Attempt to rotate a loop based on profile data to reduce branch cost.
951///
952/// With profile data, we can determine the cost in terms of missed fall through
953/// opportunities when rotating a loop chain and select the best rotation.
954/// Basically, there are three kinds of cost to consider for each rotation:
955/// 1. The possibly missed fall through edge (if it exists) from BB out of
956/// the loop to the loop header.
957/// 2. The possibly missed fall through edges (if they exist) from the loop
958/// exits to BB out of the loop.
959/// 3. The missed fall through edge (if it exists) from the last BB to the
960/// first BB in the loop chain.
961/// Therefore, the cost for a given rotation is the sum of costs listed above.
962/// We select the best rotation with the smallest cost.
963void MachineBlockPlacement::rotateLoopWithProfile(
964 BlockChain &LoopChain, MachineLoop &L, const BlockFilterSet &LoopBlockSet) {
965 auto HeaderBB = L.getHeader();
966 auto HeaderIter = std::find(LoopChain.begin(), LoopChain.end(), HeaderBB);
967 auto RotationPos = LoopChain.end();
968
969 BlockFrequency SmallestRotationCost = BlockFrequency::getMaxFrequency();
970
971 // A utility lambda that scales up a block frequency by dividing it by a
972 // branch probability which is the reciprocal of the scale.
973 auto ScaleBlockFrequency = [](BlockFrequency Freq,
974 unsigned Scale) -> BlockFrequency {
975 if (Scale == 0)
976 return 0;
977 // Use operator / between BlockFrequency and BranchProbability to implement
978 // saturating multiplication.
979 return Freq / BranchProbability(1, Scale);
980 };
981
982 // Compute the cost of the missed fall-through edge to the loop header if the
983 // chain head is not the loop header. As we only consider natural loops with
984 // single header, this computation can be done only once.
985 BlockFrequency HeaderFallThroughCost(0);
986 for (auto *Pred : HeaderBB->predecessors()) {
987 BlockChain *PredChain = BlockToChain[Pred];
988 if (!LoopBlockSet.count(Pred) &&
989 (!PredChain || Pred == *std::prev(PredChain->end()))) {
990 auto EdgeFreq =
991 MBFI->getBlockFreq(Pred) * MBPI->getEdgeProbability(Pred, HeaderBB);
992 auto FallThruCost = ScaleBlockFrequency(EdgeFreq, MisfetchCost);
993 // If the predecessor has only an unconditional jump to the header, we
994 // need to consider the cost of this jump.
995 if (Pred->succ_size() == 1)
996 FallThruCost += ScaleBlockFrequency(EdgeFreq, JumpInstCost);
997 HeaderFallThroughCost = std::max(HeaderFallThroughCost, FallThruCost);
998 }
999 }
1000
1001 // Here we collect all exit blocks in the loop, and for each exit we find out
1002 // its hottest exit edge. For each loop rotation, we define the loop exit cost
1003 // as the sum of frequencies of exit edges we collect here, excluding the exit
1004 // edge from the tail of the loop chain.
1005 SmallVector<std::pair<MachineBasicBlock *, BlockFrequency>, 4> ExitsWithFreq;
1006 for (auto BB : LoopChain) {
Cong Houd97c1002015-12-01 05:29:22 +00001007 auto LargestExitEdgeProb = BranchProbability::getZero();
Cong Hou7745dbc2015-10-19 23:16:40 +00001008 for (auto *Succ : BB->successors()) {
1009 BlockChain *SuccChain = BlockToChain[Succ];
1010 if (!LoopBlockSet.count(Succ) &&
1011 (!SuccChain || Succ == *SuccChain->begin())) {
Cong Houd97c1002015-12-01 05:29:22 +00001012 auto SuccProb = MBPI->getEdgeProbability(BB, Succ);
1013 LargestExitEdgeProb = std::max(LargestExitEdgeProb, SuccProb);
Cong Hou7745dbc2015-10-19 23:16:40 +00001014 }
1015 }
Cong Houd97c1002015-12-01 05:29:22 +00001016 if (LargestExitEdgeProb > BranchProbability::getZero()) {
1017 auto ExitFreq = MBFI->getBlockFreq(BB) * LargestExitEdgeProb;
Cong Hou7745dbc2015-10-19 23:16:40 +00001018 ExitsWithFreq.emplace_back(BB, ExitFreq);
1019 }
1020 }
1021
1022 // In this loop we iterate every block in the loop chain and calculate the
1023 // cost assuming the block is the head of the loop chain. When the loop ends,
1024 // we should have found the best candidate as the loop chain's head.
1025 for (auto Iter = LoopChain.begin(), TailIter = std::prev(LoopChain.end()),
1026 EndIter = LoopChain.end();
1027 Iter != EndIter; Iter++, TailIter++) {
1028 // TailIter is used to track the tail of the loop chain if the block we are
1029 // checking (pointed by Iter) is the head of the chain.
1030 if (TailIter == LoopChain.end())
1031 TailIter = LoopChain.begin();
1032
1033 auto TailBB = *TailIter;
1034
1035 // Calculate the cost by putting this BB to the top.
1036 BlockFrequency Cost = 0;
1037
1038 // If the current BB is the loop header, we need to take into account the
1039 // cost of the missed fall through edge from outside of the loop to the
1040 // header.
1041 if (Iter != HeaderIter)
1042 Cost += HeaderFallThroughCost;
1043
1044 // Collect the loop exit cost by summing up frequencies of all exit edges
1045 // except the one from the chain tail.
1046 for (auto &ExitWithFreq : ExitsWithFreq)
1047 if (TailBB != ExitWithFreq.first)
1048 Cost += ExitWithFreq.second;
1049
1050 // The cost of breaking the once fall-through edge from the tail to the top
1051 // of the loop chain. Here we need to consider three cases:
1052 // 1. If the tail node has only one successor, then we will get an
1053 // additional jmp instruction. So the cost here is (MisfetchCost +
1054 // JumpInstCost) * tail node frequency.
1055 // 2. If the tail node has two successors, then we may still get an
1056 // additional jmp instruction if the layout successor after the loop
1057 // chain is not its CFG successor. Note that the more frequently executed
1058 // jmp instruction will be put ahead of the other one. Assume the
1059 // frequency of those two branches are x and y, where x is the frequency
1060 // of the edge to the chain head, then the cost will be
1061 // (x * MisfetechCost + min(x, y) * JumpInstCost) * tail node frequency.
1062 // 3. If the tail node has more than two successors (this rarely happens),
1063 // we won't consider any additional cost.
1064 if (TailBB->isSuccessor(*Iter)) {
1065 auto TailBBFreq = MBFI->getBlockFreq(TailBB);
1066 if (TailBB->succ_size() == 1)
1067 Cost += ScaleBlockFrequency(TailBBFreq.getFrequency(),
1068 MisfetchCost + JumpInstCost);
1069 else if (TailBB->succ_size() == 2) {
1070 auto TailToHeadProb = MBPI->getEdgeProbability(TailBB, *Iter);
1071 auto TailToHeadFreq = TailBBFreq * TailToHeadProb;
1072 auto ColderEdgeFreq = TailToHeadProb > BranchProbability(1, 2)
1073 ? TailBBFreq * TailToHeadProb.getCompl()
1074 : TailToHeadFreq;
1075 Cost += ScaleBlockFrequency(TailToHeadFreq, MisfetchCost) +
1076 ScaleBlockFrequency(ColderEdgeFreq, JumpInstCost);
1077 }
1078 }
1079
Philip Reamesb9688f42016-03-02 21:45:13 +00001080 DEBUG(dbgs() << "The cost of loop rotation by making " << getBlockName(*Iter)
Cong Hou7745dbc2015-10-19 23:16:40 +00001081 << " to the top: " << Cost.getFrequency() << "\n");
1082
1083 if (Cost < SmallestRotationCost) {
1084 SmallestRotationCost = Cost;
1085 RotationPos = Iter;
1086 }
1087 }
1088
1089 if (RotationPos != LoopChain.end()) {
Philip Reamesb9688f42016-03-02 21:45:13 +00001090 DEBUG(dbgs() << "Rotate loop by making " << getBlockName(*RotationPos)
Cong Hou7745dbc2015-10-19 23:16:40 +00001091 << " to the top\n");
1092 std::rotate(LoopChain.begin(), RotationPos, LoopChain.end());
1093 }
1094}
1095
Cong Houb90b9e02015-11-02 21:24:00 +00001096/// \brief Collect blocks in the given loop that are to be placed.
1097///
1098/// When profile data is available, exclude cold blocks from the returned set;
1099/// otherwise, collect all blocks in the loop.
1100MachineBlockPlacement::BlockFilterSet
1101MachineBlockPlacement::collectLoopBlockSet(MachineFunction &F, MachineLoop &L) {
1102 BlockFilterSet LoopBlockSet;
1103
1104 // Filter cold blocks off from LoopBlockSet when profile data is available.
1105 // Collect the sum of frequencies of incoming edges to the loop header from
1106 // outside. If we treat the loop as a super block, this is the frequency of
1107 // the loop. Then for each block in the loop, we calculate the ratio between
1108 // its frequency and the frequency of the loop block. When it is too small,
1109 // don't add it to the loop chain. If there are outer loops, then this block
1110 // will be merged into the first outer loop chain for which this block is not
1111 // cold anymore. This needs precise profile data and we only do this when
1112 // profile data is available.
1113 if (F.getFunction()->getEntryCount()) {
1114 BlockFrequency LoopFreq(0);
1115 for (auto LoopPred : L.getHeader()->predecessors())
1116 if (!L.contains(LoopPred))
1117 LoopFreq += MBFI->getBlockFreq(LoopPred) *
1118 MBPI->getEdgeProbability(LoopPred, L.getHeader());
1119
1120 for (MachineBasicBlock *LoopBB : L.getBlocks()) {
1121 auto Freq = MBFI->getBlockFreq(LoopBB).getFrequency();
1122 if (Freq == 0 || LoopFreq.getFrequency() / Freq > LoopToColdBlockRatio)
1123 continue;
1124 LoopBlockSet.insert(LoopBB);
1125 }
1126 } else
1127 LoopBlockSet.insert(L.block_begin(), L.block_end());
1128
1129 return LoopBlockSet;
1130}
1131
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00001132/// \brief Forms basic block chains from the natural loop structures.
Chandler Carruth10281422011-10-21 06:46:38 +00001133///
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00001134/// These chains are designed to preserve the existing *structure* of the code
1135/// as much as possible. We can then stitch the chains together in a way which
1136/// both preserves the topological structure and minimizes taken conditional
1137/// branches.
Chandler Carruth8d150782011-11-13 11:20:44 +00001138void MachineBlockPlacement::buildLoopChains(MachineFunction &F,
Jakub Staszak90616162011-12-21 23:02:08 +00001139 MachineLoop &L) {
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00001140 // First recurse through any nested loops, building chains for those inner
1141 // loops.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001142 for (MachineLoop *InnerLoop : L)
1143 buildLoopChains(F, *InnerLoop);
Chandler Carruth10281422011-10-21 06:46:38 +00001144
Chandler Carruth8d150782011-11-13 11:20:44 +00001145 SmallVector<MachineBasicBlock *, 16> BlockWorkList;
Amaury Sechetc53ad4f2016-04-07 21:29:39 +00001146 SmallVector<MachineBasicBlock *, 16> EHPadWorkList;
Cong Houb90b9e02015-11-02 21:24:00 +00001147 BlockFilterSet LoopBlockSet = collectLoopBlockSet(F, L);
Chandler Carruth03adbd42011-11-27 13:34:33 +00001148
Cong Hou7745dbc2015-10-19 23:16:40 +00001149 // Check if we have profile data for this function. If yes, we will rotate
1150 // this loop by modeling costs more precisely which requires the profile data
1151 // for better layout.
1152 bool RotateLoopWithProfile =
Xinliang David Lif0ab6df2016-05-12 02:04:41 +00001153 ForcePreciseRotationCost ||
1154 (PreciseRotationCost && F.getFunction()->getEntryCount());
Cong Hou7745dbc2015-10-19 23:16:40 +00001155
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001156 // First check to see if there is an obviously preferable top block for the
1157 // loop. This will default to the header, but may end up as one of the
1158 // predecessors to the header if there is one which will result in strictly
1159 // fewer branches in the loop body.
Cong Hou7745dbc2015-10-19 23:16:40 +00001160 // When we use profile data to rotate the loop, this is unnecessary.
1161 MachineBasicBlock *LoopTop =
1162 RotateLoopWithProfile ? L.getHeader() : findBestLoopTop(L, LoopBlockSet);
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001163
1164 // If we selected just the header for the loop top, look for a potentially
1165 // profitable exit block in the event that rotating the loop can eliminate
1166 // branches by placing an exit edge at the bottom.
Craig Topperc0196b12014-04-14 00:51:57 +00001167 MachineBasicBlock *ExitingBB = nullptr;
Cong Hou7745dbc2015-10-19 23:16:40 +00001168 if (!RotateLoopWithProfile && LoopTop == L.getHeader())
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001169 ExitingBB = findBestLoopExit(F, L, LoopBlockSet);
1170
1171 BlockChain &LoopChain = *BlockToChain[LoopTop];
Chandler Carruth10281422011-10-21 06:46:38 +00001172
Chandler Carruth8d150782011-11-13 11:20:44 +00001173 // FIXME: This is a really lame way of walking the chains in the loop: we
1174 // walk the blocks, and use a set to prevent visiting a particular chain
1175 // twice.
Jakub Staszak90616162011-12-21 23:02:08 +00001176 SmallPtrSet<BlockChain *, 4> UpdatedPreds;
Philip Reamesae27b232016-03-03 00:58:43 +00001177 assert(LoopChain.UnscheduledPredecessors == 0);
Jakub Staszak190c7122011-12-07 19:46:10 +00001178 UpdatedPreds.insert(&LoopChain);
Cong Houb90b9e02015-11-02 21:24:00 +00001179
Amaury Secheteae09c22016-03-14 21:24:11 +00001180 for (MachineBasicBlock *LoopBB : LoopBlockSet)
Amaury Sechetc53ad4f2016-04-07 21:29:39 +00001181 fillWorkLists(LoopBB, UpdatedPreds, BlockWorkList, EHPadWorkList,
1182 &LoopBlockSet);
Chandler Carruth8d150782011-11-13 11:20:44 +00001183
Amaury Sechetc53ad4f2016-04-07 21:29:39 +00001184 buildChain(LoopTop, LoopChain, BlockWorkList, EHPadWorkList, &LoopBlockSet);
Cong Hou7745dbc2015-10-19 23:16:40 +00001185
1186 if (RotateLoopWithProfile)
1187 rotateLoopWithProfile(LoopChain, L, LoopBlockSet);
1188 else
1189 rotateLoop(LoopChain, ExitingBB, LoopBlockSet);
Chandler Carruth8d150782011-11-13 11:20:44 +00001190
1191 DEBUG({
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001192 // Crash at the end so we get all of the debugging output first.
1193 bool BadLoop = false;
Philip Reamesae27b232016-03-03 00:58:43 +00001194 if (LoopChain.UnscheduledPredecessors) {
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001195 BadLoop = true;
Chandler Carruth8d150782011-11-13 11:20:44 +00001196 dbgs() << "Loop chain contains a block without its preds placed!\n"
1197 << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
1198 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n";
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001199 }
Chandler Carruth7a715da2015-03-05 03:19:05 +00001200 for (MachineBasicBlock *ChainBB : LoopChain) {
1201 dbgs() << " ... " << getBlockName(ChainBB) << "\n";
1202 if (!LoopBlockSet.erase(ChainBB)) {
Chandler Carruth0a31d142011-11-14 10:55:53 +00001203 // We don't mark the loop as bad here because there are real situations
1204 // where this can occur. For example, with an unanalyzable fallthrough
Chandler Carruth99fe42f2011-11-23 10:35:36 +00001205 // from a loop block to a non-loop block or vice versa.
Chandler Carruth8d150782011-11-13 11:20:44 +00001206 dbgs() << "Loop chain contains a block not contained by the loop!\n"
1207 << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
1208 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
Chandler Carruth7a715da2015-03-05 03:19:05 +00001209 << " Bad block: " << getBlockName(ChainBB) << "\n";
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001210 }
Chandler Carruthccc7e422012-04-16 01:12:56 +00001211 }
Chandler Carruth8d150782011-11-13 11:20:44 +00001212
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001213 if (!LoopBlockSet.empty()) {
1214 BadLoop = true;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001215 for (MachineBasicBlock *LoopBB : LoopBlockSet)
Chandler Carruth8d150782011-11-13 11:20:44 +00001216 dbgs() << "Loop contains blocks never placed into a chain!\n"
1217 << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
1218 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
Chandler Carruth7a715da2015-03-05 03:19:05 +00001219 << " Bad block: " << getBlockName(LoopBB) << "\n";
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001220 }
1221 assert(!BadLoop && "Detected problems with the placement of this loop.");
Chandler Carruth8d150782011-11-13 11:20:44 +00001222 });
Chandler Carruth10281422011-10-21 06:46:38 +00001223}
1224
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00001225void MachineBlockPlacement::buildCFGChains(MachineFunction &F) {
Chandler Carruth8d150782011-11-13 11:20:44 +00001226 // Ensure that every BB in the function has an associated chain to simplify
1227 // the assumptions of the remaining algorithm.
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +00001228 SmallVector<MachineOperand, 4> Cond; // For AnalyzeBranch.
1229 for (MachineFunction::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +00001230 MachineBasicBlock *BB = &*FI;
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001231 BlockChain *Chain =
1232 new (ChainAllocator.Allocate()) BlockChain(BlockToChain, BB);
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +00001233 // Also, merge any blocks which we cannot reason about and must preserve
1234 // the exact fallthrough behavior for.
1235 for (;;) {
1236 Cond.clear();
Craig Topperc0196b12014-04-14 00:51:57 +00001237 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +00001238 if (!TII->AnalyzeBranch(*BB, TBB, FBB, Cond) || !FI->canFallThrough())
1239 break;
1240
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +00001241 MachineFunction::iterator NextFI = std::next(FI);
1242 MachineBasicBlock *NextBB = &*NextFI;
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +00001243 // Ensure that the layout successor is a viable block, as we know that
1244 // fallthrough is a possibility.
1245 assert(NextFI != FE && "Can't fallthrough past the last block.");
1246 DEBUG(dbgs() << "Pre-merging due to unanalyzable fallthrough: "
1247 << getBlockName(BB) << " -> " << getBlockName(NextBB)
1248 << "\n");
Craig Topperc0196b12014-04-14 00:51:57 +00001249 Chain->merge(NextBB, nullptr);
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +00001250 FI = NextFI;
1251 BB = NextBB;
1252 }
1253 }
Chandler Carruth8d150782011-11-13 11:20:44 +00001254
Daniel Jasper471e8562015-03-04 11:05:34 +00001255 if (OutlineOptionalBranches) {
1256 // Find the nearest common dominator of all of F's terminators.
1257 MachineBasicBlock *Terminator = nullptr;
1258 for (MachineBasicBlock &MBB : F) {
1259 if (MBB.succ_size() == 0) {
1260 if (Terminator == nullptr)
1261 Terminator = &MBB;
1262 else
1263 Terminator = MDT->findNearestCommonDominator(Terminator, &MBB);
1264 }
1265 }
1266
1267 // MBBs dominating this common dominator are unavoidable.
1268 UnavoidableBlocks.clear();
1269 for (MachineBasicBlock &MBB : F) {
1270 if (MDT->dominates(&MBB, Terminator)) {
1271 UnavoidableBlocks.insert(&MBB);
1272 }
1273 }
1274 }
1275
Chandler Carruth8d150782011-11-13 11:20:44 +00001276 // Build any loop-based chains.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001277 for (MachineLoop *L : *MLI)
1278 buildLoopChains(F, *L);
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00001279
Chandler Carruth8d150782011-11-13 11:20:44 +00001280 SmallVector<MachineBasicBlock *, 16> BlockWorkList;
Amaury Sechetc53ad4f2016-04-07 21:29:39 +00001281 SmallVector<MachineBasicBlock *, 16> EHPadWorkList;
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00001282
Chandler Carruth8d150782011-11-13 11:20:44 +00001283 SmallPtrSet<BlockChain *, 4> UpdatedPreds;
Amaury Secheteae09c22016-03-14 21:24:11 +00001284 for (MachineBasicBlock &MBB : F)
Amaury Sechetc53ad4f2016-04-07 21:29:39 +00001285 fillWorkLists(&MBB, UpdatedPreds, BlockWorkList, EHPadWorkList);
Chandler Carruth8d150782011-11-13 11:20:44 +00001286
1287 BlockChain &FunctionChain = *BlockToChain[&F.front()];
Amaury Sechetc53ad4f2016-04-07 21:29:39 +00001288 buildChain(&F.front(), FunctionChain, BlockWorkList, EHPadWorkList);
Chandler Carruth8d150782011-11-13 11:20:44 +00001289
Matt Arsenault0f5f0152013-12-10 18:55:37 +00001290#ifndef NDEBUG
Matt Arsenault79d55f52013-12-05 20:02:18 +00001291 typedef SmallPtrSet<MachineBasicBlock *, 16> FunctionBlockSetType;
Matt Arsenault0f5f0152013-12-10 18:55:37 +00001292#endif
Chandler Carruth8d150782011-11-13 11:20:44 +00001293 DEBUG({
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001294 // Crash at the end so we get all of the debugging output first.
1295 bool BadFunc = false;
Chandler Carruth8d150782011-11-13 11:20:44 +00001296 FunctionBlockSetType FunctionBlockSet;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001297 for (MachineBasicBlock &MBB : F)
1298 FunctionBlockSet.insert(&MBB);
Chandler Carruth8d150782011-11-13 11:20:44 +00001299
Chandler Carruth7a715da2015-03-05 03:19:05 +00001300 for (MachineBasicBlock *ChainBB : FunctionChain)
1301 if (!FunctionBlockSet.erase(ChainBB)) {
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001302 BadFunc = true;
Chandler Carruth8d150782011-11-13 11:20:44 +00001303 dbgs() << "Function chain contains a block not in the function!\n"
Chandler Carruth7a715da2015-03-05 03:19:05 +00001304 << " Bad block: " << getBlockName(ChainBB) << "\n";
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001305 }
Chandler Carruth8d150782011-11-13 11:20:44 +00001306
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001307 if (!FunctionBlockSet.empty()) {
1308 BadFunc = true;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001309 for (MachineBasicBlock *RemainingBB : FunctionBlockSet)
Chandler Carruth8d150782011-11-13 11:20:44 +00001310 dbgs() << "Function contains blocks never placed into a chain!\n"
Chandler Carruth7a715da2015-03-05 03:19:05 +00001311 << " Bad block: " << getBlockName(RemainingBB) << "\n";
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001312 }
1313 assert(!BadFunc && "Detected problems with the block placement.");
Chandler Carruth8d150782011-11-13 11:20:44 +00001314 });
1315
1316 // Splice the blocks into place.
1317 MachineFunction::iterator InsertPos = F.begin();
Chandler Carruth7a715da2015-03-05 03:19:05 +00001318 for (MachineBasicBlock *ChainBB : FunctionChain) {
1319 DEBUG(dbgs() << (ChainBB == *FunctionChain.begin() ? "Placing chain "
1320 : " ... ")
1321 << getBlockName(ChainBB) << "\n");
1322 if (InsertPos != MachineFunction::iterator(ChainBB))
1323 F.splice(InsertPos, ChainBB);
Chandler Carruth8d150782011-11-13 11:20:44 +00001324 else
1325 ++InsertPos;
1326
1327 // Update the terminator of the previous block.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001328 if (ChainBB == *FunctionChain.begin())
Chandler Carruth8d150782011-11-13 11:20:44 +00001329 continue;
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +00001330 MachineBasicBlock *PrevBB = &*std::prev(MachineFunction::iterator(ChainBB));
Chandler Carruth8d150782011-11-13 11:20:44 +00001331
Chandler Carruth10281422011-10-21 06:46:38 +00001332 // FIXME: It would be awesome of updateTerminator would just return rather
1333 // than assert when the branch cannot be analyzed in order to remove this
1334 // boiler plate.
1335 Cond.clear();
Craig Topperc0196b12014-04-14 00:51:57 +00001336 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
Shuxin Yang8b8fd212013-06-04 01:00:57 +00001337
Haicheng Wu90a55652016-05-24 22:16:14 +00001338 // The "PrevBB" is not yet updated to reflect current code layout, so,
1339 // o. it may fall-through to a block without explict "goto" instruction
1340 // before layout, and no longer fall-through it after layout; or
1341 // o. just opposite.
1342 //
1343 // AnalyzeBranch() may return erroneous value for FBB when these two
1344 // situations take place. For the first scenario FBB is mistakenly set NULL;
1345 // for the 2nd scenario, the FBB, which is expected to be NULL, is
1346 // mistakenly pointing to "*BI".
1347 // Thus, if the future change needs to use FBB before the layout is set, it
1348 // has to correct FBB first by using the code similar to the following:
1349 //
1350 // if (!Cond.empty() && (!FBB || FBB == ChainBB)) {
1351 // PrevBB->updateTerminator();
1352 // Cond.clear();
1353 // TBB = FBB = nullptr;
1354 // if (TII->AnalyzeBranch(*PrevBB, TBB, FBB, Cond)) {
1355 // // FIXME: This should never take place.
1356 // TBB = FBB = nullptr;
1357 // }
1358 // }
1359 if (!TII->AnalyzeBranch(*PrevBB, TBB, FBB, Cond))
1360 PrevBB->updateTerminator();
Chandler Carruth10281422011-10-21 06:46:38 +00001361 }
Chandler Carruth8d150782011-11-13 11:20:44 +00001362
1363 // Fixup the last block.
1364 Cond.clear();
Craig Topperc0196b12014-04-14 00:51:57 +00001365 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
Chandler Carruth8d150782011-11-13 11:20:44 +00001366 if (!TII->AnalyzeBranch(F.back(), TBB, FBB, Cond))
1367 F.back().updateTerminator();
Haicheng Wu90a55652016-05-24 22:16:14 +00001368}
1369
1370void MachineBlockPlacement::optimizeBranches(MachineFunction &F) {
1371 BlockChain &FunctionChain = *BlockToChain[&F.front()];
1372 SmallVector<MachineOperand, 4> Cond; // For AnalyzeBranch.
Quentin Colombet776e6de2016-05-02 22:58:59 +00001373
1374 // Now that all the basic blocks in the chain have the proper layout,
1375 // make a final call to AnalyzeBranch with AllowModify set.
1376 // Indeed, the target may be able to optimize the branches in a way we
1377 // cannot because all branches may not be analyzable.
1378 // E.g., the target may be able to remove an unconditional branch to
1379 // a fallthrough when it occurs after predicated terminators.
1380 for (MachineBasicBlock *ChainBB : FunctionChain) {
1381 Cond.clear();
Haicheng Wu90a55652016-05-24 22:16:14 +00001382 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
1383 if (!TII->AnalyzeBranch(*ChainBB, TBB, FBB, Cond, /*AllowModify*/ true)) {
1384 // If PrevBB has a two-way branch, try to re-order the branches
1385 // such that we branch to the successor with higher probability first.
1386 if (TBB && !Cond.empty() && FBB &&
1387 MBPI->getEdgeProbability(ChainBB, FBB) >
1388 MBPI->getEdgeProbability(ChainBB, TBB) &&
1389 !TII->ReverseBranchCondition(Cond)) {
1390 DEBUG(dbgs() << "Reverse order of the two branches: "
1391 << getBlockName(ChainBB) << "\n");
1392 DEBUG(dbgs() << " Edge probability: "
1393 << MBPI->getEdgeProbability(ChainBB, FBB) << " vs "
1394 << MBPI->getEdgeProbability(ChainBB, TBB) << "\n");
1395 DebugLoc dl; // FIXME: this is nowhere
1396 TII->RemoveBranch(*ChainBB);
1397 TII->InsertBranch(*ChainBB, FBB, TBB, Cond, dl);
1398 ChainBB->updateTerminator();
1399 }
1400 }
Quentin Colombet776e6de2016-05-02 22:58:59 +00001401 }
Haicheng Wue749ce52016-04-29 17:06:44 +00001402}
Chandler Carruth10281422011-10-21 06:46:38 +00001403
Haicheng Wue749ce52016-04-29 17:06:44 +00001404void MachineBlockPlacement::alignBlocks(MachineFunction &F) {
Chandler Carruthccc7e422012-04-16 01:12:56 +00001405 // Walk through the backedges of the function now that we have fully laid out
1406 // the basic blocks and align the destination of each backedge. We don't rely
Chandler Carruth881d0a72012-08-07 09:45:24 +00001407 // exclusively on the loop info here so that we can align backedges in
1408 // unnatural CFGs and backedges that were introduced purely because of the
1409 // loop rotations done during this layout pass.
Haicheng Wu4afe0422016-04-29 22:01:10 +00001410 if (F.getFunction()->optForSize())
Chandler Carruth8b9737c2011-10-21 08:57:37 +00001411 return;
Haicheng Wue749ce52016-04-29 17:06:44 +00001412 BlockChain &FunctionChain = *BlockToChain[&F.front()];
Chandler Carruth881d0a72012-08-07 09:45:24 +00001413 if (FunctionChain.begin() == FunctionChain.end())
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001414 return; // Empty chain.
Chandler Carruth8b9737c2011-10-21 08:57:37 +00001415
Chandler Carruth881d0a72012-08-07 09:45:24 +00001416 const BranchProbability ColdProb(1, 5); // 20%
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +00001417 BlockFrequency EntryFreq = MBFI->getBlockFreq(&F.front());
Chandler Carruth881d0a72012-08-07 09:45:24 +00001418 BlockFrequency WeightedEntryFreq = EntryFreq * ColdProb;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001419 for (MachineBasicBlock *ChainBB : FunctionChain) {
1420 if (ChainBB == *FunctionChain.begin())
1421 continue;
1422
Chandler Carruth881d0a72012-08-07 09:45:24 +00001423 // Don't align non-looping basic blocks. These are unlikely to execute
1424 // enough times to matter in practice. Note that we'll still handle
1425 // unnatural CFGs inside of a natural outer loop (the common case) and
1426 // rotated loops.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001427 MachineLoop *L = MLI->getLoopFor(ChainBB);
Chandler Carruth881d0a72012-08-07 09:45:24 +00001428 if (!L)
1429 continue;
1430
Hal Finkel57725662015-01-03 17:58:24 +00001431 unsigned Align = TLI->getPrefLoopAlignment(L);
1432 if (!Align)
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001433 continue; // Don't care about loop alignment.
Hal Finkel57725662015-01-03 17:58:24 +00001434
Chandler Carruth881d0a72012-08-07 09:45:24 +00001435 // If the block is cold relative to the function entry don't waste space
1436 // aligning it.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001437 BlockFrequency Freq = MBFI->getBlockFreq(ChainBB);
Chandler Carruth881d0a72012-08-07 09:45:24 +00001438 if (Freq < WeightedEntryFreq)
1439 continue;
1440
1441 // If the block is cold relative to its loop header, don't align it
1442 // regardless of what edges into the block exist.
1443 MachineBasicBlock *LoopHeader = L->getHeader();
1444 BlockFrequency LoopHeaderFreq = MBFI->getBlockFreq(LoopHeader);
1445 if (Freq < (LoopHeaderFreq * ColdProb))
1446 continue;
1447
1448 // Check for the existence of a non-layout predecessor which would benefit
1449 // from aligning this block.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001450 MachineBasicBlock *LayoutPred =
1451 &*std::prev(MachineFunction::iterator(ChainBB));
Chandler Carruth881d0a72012-08-07 09:45:24 +00001452
1453 // Force alignment if all the predecessors are jumps. We already checked
1454 // that the block isn't cold above.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001455 if (!LayoutPred->isSuccessor(ChainBB)) {
1456 ChainBB->setAlignment(Align);
Chandler Carruth881d0a72012-08-07 09:45:24 +00001457 continue;
1458 }
1459
1460 // Align this block if the layout predecessor's edge into this block is
Nadav Rotem6036f582013-03-29 16:34:23 +00001461 // cold relative to the block. When this is true, other predecessors make up
Chandler Carruth881d0a72012-08-07 09:45:24 +00001462 // all of the hot entries into the block and thus alignment is likely to be
1463 // important.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001464 BranchProbability LayoutProb =
1465 MBPI->getEdgeProbability(LayoutPred, ChainBB);
Chandler Carruth881d0a72012-08-07 09:45:24 +00001466 BlockFrequency LayoutEdgeFreq = MBFI->getBlockFreq(LayoutPred) * LayoutProb;
1467 if (LayoutEdgeFreq <= (Freq * ColdProb))
Chandler Carruth7a715da2015-03-05 03:19:05 +00001468 ChainBB->setAlignment(Align);
Chandler Carruthccc7e422012-04-16 01:12:56 +00001469 }
Chandler Carruth8b9737c2011-10-21 08:57:37 +00001470}
1471
Chandler Carruth10281422011-10-21 06:46:38 +00001472bool MachineBlockPlacement::runOnMachineFunction(MachineFunction &F) {
Andrew Kaylor50271f72016-05-03 22:32:30 +00001473 if (skipFunction(*F.getFunction()))
1474 return false;
1475
Chandler Carruth10281422011-10-21 06:46:38 +00001476 // Check for single-block functions and skip them.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001477 if (std::next(F.begin()) == F.end())
Chandler Carruth10281422011-10-21 06:46:38 +00001478 return false;
1479
1480 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
Haicheng Wu5b458cc2016-06-09 15:24:29 +00001481 MBFI = llvm::make_unique<BranchFolder::MBFIWrapper>(
1482 getAnalysis<MachineBlockFrequencyInfo>());
Chandler Carruth8b9737c2011-10-21 08:57:37 +00001483 MLI = &getAnalysis<MachineLoopInfo>();
Eric Christopherfc6de422014-08-05 02:39:49 +00001484 TII = F.getSubtarget().getInstrInfo();
1485 TLI = F.getSubtarget().getTargetLowering();
Daniel Jasper471e8562015-03-04 11:05:34 +00001486 MDT = &getAnalysis<MachineDominatorTree>();
Chandler Carruth10281422011-10-21 06:46:38 +00001487 assert(BlockToChain.empty());
Chandler Carruth10281422011-10-21 06:46:38 +00001488
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00001489 buildCFGChains(F);
Haicheng Wu5b458cc2016-06-09 15:24:29 +00001490
1491 // Changing the layout can create new tail merging opportunities.
1492 TargetPassConfig *PassConfig = &getAnalysis<TargetPassConfig>();
1493 // TailMerge can create jump into if branches that make CFG irreducible for
1494 // HW that requires structurized CFG.
1495 bool EnableTailMerge = !F.getTarget().requiresStructuredCFG() &&
1496 PassConfig->getEnableTailMerge() &&
1497 BranchFoldPlacement;
1498 // No tail merging opportunities if the block number is less than four.
1499 if (F.size() > 3 && EnableTailMerge) {
1500 BranchFolder BF(/*EnableTailMerge=*/true, /*CommonHoist=*/false, *MBFI,
1501 *MBPI);
1502
1503 if (BF.OptimizeFunction(F, TII, F.getSubtarget().getRegisterInfo(),
1504 getAnalysisIfAvailable<MachineModuleInfo>(), MLI,
1505 /*AfterBlockPlacement=*/true)) {
1506 // Redo the layout if tail merging creates/removes/moves blocks.
1507 BlockToChain.clear();
1508 ChainAllocator.DestroyAll();
1509 buildCFGChains(F);
1510 }
1511 }
1512
Haicheng Wu90a55652016-05-24 22:16:14 +00001513 optimizeBranches(F);
Haicheng Wue749ce52016-04-29 17:06:44 +00001514 alignBlocks(F);
Chandler Carruth10281422011-10-21 06:46:38 +00001515
Chandler Carruth10281422011-10-21 06:46:38 +00001516 BlockToChain.clear();
Chandler Carruthfd9b4d92011-11-14 10:57:23 +00001517 ChainAllocator.DestroyAll();
Chandler Carruth10281422011-10-21 06:46:38 +00001518
Nadav Rotemc0adc9f2013-04-12 01:24:16 +00001519 if (AlignAllBlock)
1520 // Align all of the blocks in the function to a specific alignment.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001521 for (MachineBasicBlock &MBB : F)
1522 MBB.setAlignment(AlignAllBlock);
Geoff Berry10494ac2016-01-21 17:25:52 +00001523 else if (AlignAllNonFallThruBlocks) {
1524 // Align all of the blocks that have no fall-through predecessors to a
1525 // specific alignment.
1526 for (auto MBI = std::next(F.begin()), MBE = F.end(); MBI != MBE; ++MBI) {
1527 auto LayoutPred = std::prev(MBI);
1528 if (!LayoutPred->isSuccessor(&*MBI))
1529 MBI->setAlignment(AlignAllNonFallThruBlocks);
1530 }
1531 }
Nadav Rotemc0adc9f2013-04-12 01:24:16 +00001532
Chandler Carruth10281422011-10-21 06:46:38 +00001533 // We always return true as we have no way to track whether the final order
1534 // differs from the original order.
1535 return true;
1536}
Chandler Carruthae4e8002011-11-02 07:17:12 +00001537
1538namespace {
1539/// \brief A pass to compute block placement statistics.
1540///
1541/// A separate pass to compute interesting statistics for evaluating block
1542/// placement. This is separate from the actual placement pass so that they can
Benjamin Kramerbde91762012-06-02 10:20:22 +00001543/// be computed in the absence of any placement transformations or when using
Chandler Carruthae4e8002011-11-02 07:17:12 +00001544/// alternative placement strategies.
1545class MachineBlockPlacementStats : public MachineFunctionPass {
1546 /// \brief A handle to the branch probability pass.
1547 const MachineBranchProbabilityInfo *MBPI;
1548
1549 /// \brief A handle to the function-wide block frequency pass.
1550 const MachineBlockFrequencyInfo *MBFI;
1551
1552public:
1553 static char ID; // Pass identification, replacement for typeid
1554 MachineBlockPlacementStats() : MachineFunctionPass(ID) {
1555 initializeMachineBlockPlacementStatsPass(*PassRegistry::getPassRegistry());
1556 }
1557
Craig Topper4584cd52014-03-07 09:26:03 +00001558 bool runOnMachineFunction(MachineFunction &F) override;
Chandler Carruthae4e8002011-11-02 07:17:12 +00001559
Craig Topper4584cd52014-03-07 09:26:03 +00001560 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruthae4e8002011-11-02 07:17:12 +00001561 AU.addRequired<MachineBranchProbabilityInfo>();
1562 AU.addRequired<MachineBlockFrequencyInfo>();
1563 AU.setPreservesAll();
1564 MachineFunctionPass::getAnalysisUsage(AU);
1565 }
Chandler Carruthae4e8002011-11-02 07:17:12 +00001566};
Alexander Kornienkof00654e2015-06-23 09:49:53 +00001567}
Chandler Carruthae4e8002011-11-02 07:17:12 +00001568
1569char MachineBlockPlacementStats::ID = 0;
Andrew Trick1fa5bcb2012-02-08 21:23:13 +00001570char &llvm::MachineBlockPlacementStatsID = MachineBlockPlacementStats::ID;
Chandler Carruthae4e8002011-11-02 07:17:12 +00001571INITIALIZE_PASS_BEGIN(MachineBlockPlacementStats, "block-placement-stats",
1572 "Basic Block Placement Stats", false, false)
1573INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
1574INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
1575INITIALIZE_PASS_END(MachineBlockPlacementStats, "block-placement-stats",
1576 "Basic Block Placement Stats", false, false)
1577
Chandler Carruthae4e8002011-11-02 07:17:12 +00001578bool MachineBlockPlacementStats::runOnMachineFunction(MachineFunction &F) {
1579 // Check for single-block functions and skip them.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001580 if (std::next(F.begin()) == F.end())
Chandler Carruthae4e8002011-11-02 07:17:12 +00001581 return false;
1582
1583 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
1584 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
1585
Chandler Carruth7a715da2015-03-05 03:19:05 +00001586 for (MachineBasicBlock &MBB : F) {
1587 BlockFrequency BlockFreq = MBFI->getBlockFreq(&MBB);
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001588 Statistic &NumBranches =
Chandler Carruth7a715da2015-03-05 03:19:05 +00001589 (MBB.succ_size() > 1) ? NumCondBranches : NumUncondBranches;
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001590 Statistic &BranchTakenFreq =
Chandler Carruth7a715da2015-03-05 03:19:05 +00001591 (MBB.succ_size() > 1) ? CondBranchTakenFreq : UncondBranchTakenFreq;
1592 for (MachineBasicBlock *Succ : MBB.successors()) {
Chandler Carruthae4e8002011-11-02 07:17:12 +00001593 // Skip if this successor is a fallthrough.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001594 if (MBB.isLayoutSuccessor(Succ))
Chandler Carruthae4e8002011-11-02 07:17:12 +00001595 continue;
1596
Chandler Carruth7a715da2015-03-05 03:19:05 +00001597 BlockFrequency EdgeFreq =
1598 BlockFreq * MBPI->getEdgeProbability(&MBB, Succ);
Chandler Carruthae4e8002011-11-02 07:17:12 +00001599 ++NumBranches;
1600 BranchTakenFreq += EdgeFreq.getFrequency();
1601 }
1602 }
1603
1604 return false;
1605}