blob: c562af9d9648582ac4c1c1c165316e25e8234e38 [file] [log] [blame]
Chandler Carruth10281422011-10-21 06:46:38 +00001//===-- MachineBlockPlacement.cpp - Basic Block Code Layout optimization --===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Chandler Carruthbd1be4d2011-10-23 09:18:45 +000010// This file implements basic block placement transformations using the CFG
11// structure and branch probability estimates.
Chandler Carruth10281422011-10-21 06:46:38 +000012//
Chandler Carruthbd1be4d2011-10-23 09:18:45 +000013// The pass strives to preserve the structure of the CFG (that is, retain
Benjamin Kramerbde91762012-06-02 10:20:22 +000014// a topological ordering of basic blocks) in the absence of a *strong* signal
Chandler Carruthbd1be4d2011-10-23 09:18:45 +000015// to the contrary from probabilities. However, within the CFG structure, it
16// attempts to choose an ordering which favors placing more likely sequences of
17// blocks adjacent to each other.
18//
19// The algorithm works from the inner-most loop within a function outward, and
20// at each stage walks through the basic blocks, trying to coalesce them into
21// sequential chains where allowed by the CFG (or demanded by heavy
22// probabilities). Finally, it walks the blocks in topological order, and the
23// first time it reaches a chain of basic blocks, it schedules them in the
24// function in-order.
Chandler Carruth10281422011-10-21 06:46:38 +000025//
26//===----------------------------------------------------------------------===//
27
Chandler Carruthed0881b2012-12-03 16:50:05 +000028#include "llvm/CodeGen/Passes.h"
29#include "llvm/ADT/DenseMap.h"
30#include "llvm/ADT/SmallPtrSet.h"
31#include "llvm/ADT/SmallVector.h"
32#include "llvm/ADT/Statistic.h"
Chandler Carruth8b9737c2011-10-21 08:57:37 +000033#include "llvm/CodeGen/MachineBasicBlock.h"
Chandler Carruth10281422011-10-21 06:46:38 +000034#include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
35#include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
Daniel Jasper471e8562015-03-04 11:05:34 +000036#include "llvm/CodeGen/MachineDominators.h"
Chandler Carruth10281422011-10-21 06:46:38 +000037#include "llvm/CodeGen/MachineFunction.h"
Chandler Carruth10281422011-10-21 06:46:38 +000038#include "llvm/CodeGen/MachineFunctionPass.h"
Chandler Carruth8b9737c2011-10-21 08:57:37 +000039#include "llvm/CodeGen/MachineLoopInfo.h"
40#include "llvm/CodeGen/MachineModuleInfo.h"
Chandler Carruth10281422011-10-21 06:46:38 +000041#include "llvm/Support/Allocator.h"
Nadav Rotemc3b0f502013-04-12 00:48:32 +000042#include "llvm/Support/CommandLine.h"
Chandler Carruthbd1be4d2011-10-23 09:18:45 +000043#include "llvm/Support/Debug.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000044#include "llvm/Support/raw_ostream.h"
Chandler Carruth10281422011-10-21 06:46:38 +000045#include "llvm/Target/TargetInstrInfo.h"
Chandler Carruth8b9737c2011-10-21 08:57:37 +000046#include "llvm/Target/TargetLowering.h"
Eric Christopherd9134482014-08-04 21:25:23 +000047#include "llvm/Target/TargetSubtargetInfo.h"
Chandler Carruth10281422011-10-21 06:46:38 +000048#include <algorithm>
49using namespace llvm;
50
Chandler Carruthd0dced52015-03-05 02:28:25 +000051#define DEBUG_TYPE "block-placement"
Chandler Carruth1b9dde02014-04-22 02:02:50 +000052
Chandler Carruthae4e8002011-11-02 07:17:12 +000053STATISTIC(NumCondBranches, "Number of conditional branches");
Craig Topper77ec0772015-09-16 03:52:32 +000054STATISTIC(NumUncondBranches, "Number of unconditional branches");
Chandler Carruthae4e8002011-11-02 07:17:12 +000055STATISTIC(CondBranchTakenFreq,
56 "Potential frequency of taking conditional branches");
57STATISTIC(UncondBranchTakenFreq,
58 "Potential frequency of taking unconditional branches");
59
Nadav Rotemc3b0f502013-04-12 00:48:32 +000060static cl::opt<unsigned> AlignAllBlock("align-all-blocks",
61 cl::desc("Force the alignment of all "
62 "blocks in the function."),
63 cl::init(0), cl::Hidden);
64
Geoff Berry10494ac2016-01-21 17:25:52 +000065static cl::opt<unsigned> AlignAllNonFallThruBlocks(
66 "align-all-nofallthru-blocks",
67 cl::desc("Force the alignment of all "
68 "blocks that have no fall-through predecessors (i.e. don't add "
69 "nops that are executed)."),
70 cl::init(0), cl::Hidden);
71
Benjamin Kramerc8160d62013-11-20 19:08:44 +000072// FIXME: Find a good default for this flag and remove the flag.
Chandler Carruth2fc3fe12015-03-05 02:35:31 +000073static cl::opt<unsigned> ExitBlockBias(
74 "block-placement-exit-block-bias",
75 cl::desc("Block frequency percentage a loop exit block needs "
76 "over the original exit to be considered the new exit."),
77 cl::init(0), cl::Hidden);
Benjamin Kramerc8160d62013-11-20 19:08:44 +000078
Daniel Jasper471e8562015-03-04 11:05:34 +000079static cl::opt<bool> OutlineOptionalBranches(
80 "outline-optional-branches",
81 cl::desc("Put completely optional branches, i.e. branches with a common "
82 "post dominator, out of line."),
83 cl::init(false), cl::Hidden);
84
Daniel Jasper214997c2015-03-20 10:00:37 +000085static cl::opt<unsigned> OutlineOptionalThreshold(
86 "outline-optional-threshold",
87 cl::desc("Don't outline optional branches that are a single block with an "
88 "instruction count below this threshold"),
89 cl::init(4), cl::Hidden);
90
Cong Houb90b9e02015-11-02 21:24:00 +000091static cl::opt<unsigned> LoopToColdBlockRatio(
92 "loop-to-cold-block-ratio",
93 cl::desc("Outline loop blocks from loop chain if (frequency of loop) / "
94 "(frequency of block) is greater than this ratio"),
95 cl::init(5), cl::Hidden);
96
Cong Hou7745dbc2015-10-19 23:16:40 +000097static cl::opt<bool>
98 PreciseRotationCost("precise-rotation-cost",
99 cl::desc("Model the cost of loop rotation more "
100 "precisely by using profile data."),
101 cl::init(false), cl::Hidden);
Xinliang David Lif0ab6df2016-05-12 02:04:41 +0000102static cl::opt<bool>
103 ForcePreciseRotationCost("force-precise-rotation-cost",
Xinliang David Lib840bb82016-05-12 16:39:02 +0000104 cl::desc("Force the use of precise cost "
105 "loop rotation strategy."),
Xinliang David Lif0ab6df2016-05-12 02:04:41 +0000106 cl::init(false), cl::Hidden);
Cong Hou7745dbc2015-10-19 23:16:40 +0000107
108static cl::opt<unsigned> MisfetchCost(
109 "misfetch-cost",
110 cl::desc("Cost that models the probablistic risk of an instruction "
111 "misfetch due to a jump comparing to falling through, whose cost "
112 "is zero."),
113 cl::init(1), cl::Hidden);
114
115static cl::opt<unsigned> JumpInstCost("jump-inst-cost",
116 cl::desc("Cost of jump instructions."),
117 cl::init(1), cl::Hidden);
118
Xinliang David Liff287372016-06-03 23:48:36 +0000119extern cl::opt<unsigned> StaticLikelyProb;
120
Chandler Carruth10281422011-10-21 06:46:38 +0000121namespace {
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000122class BlockChain;
Chandler Carruth10281422011-10-21 06:46:38 +0000123/// \brief Type for our function-wide basic block -> block chain mapping.
124typedef DenseMap<MachineBasicBlock *, BlockChain *> BlockToChainMapType;
125}
126
127namespace {
128/// \brief A chain of blocks which will be laid out contiguously.
129///
130/// This is the datastructure representing a chain of consecutive blocks that
131/// are profitable to layout together in order to maximize fallthrough
Chandler Carruth9139f442012-06-26 05:16:37 +0000132/// probabilities and code locality. We also can use a block chain to represent
133/// a sequence of basic blocks which have some external (correctness)
134/// requirement for sequential layout.
Chandler Carruth10281422011-10-21 06:46:38 +0000135///
Chandler Carruth9139f442012-06-26 05:16:37 +0000136/// Chains can be built around a single basic block and can be merged to grow
137/// them. They participate in a block-to-chain mapping, which is updated
138/// automatically as chains are merged together.
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000139class BlockChain {
140 /// \brief The sequence of blocks belonging to this chain.
Chandler Carruth10281422011-10-21 06:46:38 +0000141 ///
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000142 /// This is the sequence of blocks for a particular chain. These will be laid
143 /// out in-order within the function.
144 SmallVector<MachineBasicBlock *, 4> Blocks;
Chandler Carruth10281422011-10-21 06:46:38 +0000145
146 /// \brief A handle to the function-wide basic block to block chain mapping.
147 ///
148 /// This is retained in each block chain to simplify the computation of child
149 /// block chains for SCC-formation and iteration. We store the edges to child
150 /// basic blocks, and map them back to their associated chains using this
151 /// structure.
152 BlockToChainMapType &BlockToChain;
153
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000154public:
Chandler Carruth10281422011-10-21 06:46:38 +0000155 /// \brief Construct a new BlockChain.
156 ///
157 /// This builds a new block chain representing a single basic block in the
158 /// function. It also registers itself as the chain that block participates
159 /// in with the BlockToChain mapping.
160 BlockChain(BlockToChainMapType &BlockToChain, MachineBasicBlock *BB)
Philip Reamesae27b232016-03-03 00:58:43 +0000161 : Blocks(1, BB), BlockToChain(BlockToChain), UnscheduledPredecessors(0) {
Chandler Carruth10281422011-10-21 06:46:38 +0000162 assert(BB && "Cannot create a chain with a null basic block");
163 BlockToChain[BB] = this;
164 }
165
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000166 /// \brief Iterator over blocks within the chain.
Chandler Carruthccc7e422012-04-16 01:12:56 +0000167 typedef SmallVectorImpl<MachineBasicBlock *>::iterator iterator;
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000168
169 /// \brief Beginning of blocks within the chain.
Chandler Carruthccc7e422012-04-16 01:12:56 +0000170 iterator begin() { return Blocks.begin(); }
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000171
172 /// \brief End of blocks within the chain.
Chandler Carruthccc7e422012-04-16 01:12:56 +0000173 iterator end() { return Blocks.end(); }
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000174
175 /// \brief Merge a block chain into this one.
Chandler Carruth10281422011-10-21 06:46:38 +0000176 ///
177 /// This routine merges a block chain into this one. It takes care of forming
178 /// a contiguous sequence of basic blocks, updating the edge list, and
179 /// updating the block -> chain mapping. It does not free or tear down the
180 /// old chain, but the old chain's block list is no longer valid.
Jakub Staszak90616162011-12-21 23:02:08 +0000181 void merge(MachineBasicBlock *BB, BlockChain *Chain) {
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000182 assert(BB);
183 assert(!Blocks.empty());
Chandler Carruth10281422011-10-21 06:46:38 +0000184
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000185 // Fast path in case we don't have a chain already.
186 if (!Chain) {
187 assert(!BlockToChain[BB]);
188 Blocks.push_back(BB);
189 BlockToChain[BB] = this;
190 return;
Chandler Carruth10281422011-10-21 06:46:38 +0000191 }
192
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000193 assert(BB == *Chain->begin());
194 assert(Chain->begin() != Chain->end());
Chandler Carruth10281422011-10-21 06:46:38 +0000195
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000196 // Update the incoming blocks to point to this chain, and add them to the
197 // chain structure.
Chandler Carruth7a715da2015-03-05 03:19:05 +0000198 for (MachineBasicBlock *ChainBB : *Chain) {
199 Blocks.push_back(ChainBB);
200 assert(BlockToChain[ChainBB] == Chain && "Incoming blocks not in chain");
201 BlockToChain[ChainBB] = this;
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000202 }
Chandler Carruth10281422011-10-21 06:46:38 +0000203 }
Chandler Carruth8d150782011-11-13 11:20:44 +0000204
Chandler Carruth49158902012-04-08 14:37:01 +0000205#ifndef NDEBUG
206 /// \brief Dump the blocks in this chain.
Nico Weber7408c702014-01-03 22:53:37 +0000207 LLVM_DUMP_METHOD void dump() {
Chandler Carruth7a715da2015-03-05 03:19:05 +0000208 for (MachineBasicBlock *MBB : *this)
209 MBB->dump();
Chandler Carruth49158902012-04-08 14:37:01 +0000210 }
211#endif // NDEBUG
212
Philip Reamesae27b232016-03-03 00:58:43 +0000213 /// \brief Count of predecessors of any block within the chain which have not
214 /// yet been scheduled. In general, we will delay scheduling this chain
215 /// until those predecessors are scheduled (or we find a sufficiently good
216 /// reason to override this heuristic.) Note that when forming loop chains,
217 /// blocks outside the loop are ignored and treated as if they were already
218 /// scheduled.
Chandler Carruth8d150782011-11-13 11:20:44 +0000219 ///
Philip Reamesae27b232016-03-03 00:58:43 +0000220 /// Note: This field is reinitialized multiple times - once for each loop,
221 /// and then once for the function as a whole.
222 unsigned UnscheduledPredecessors;
Chandler Carruth10281422011-10-21 06:46:38 +0000223};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000224}
Chandler Carruth10281422011-10-21 06:46:38 +0000225
226namespace {
227class MachineBlockPlacement : public MachineFunctionPass {
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000228 /// \brief A typedef for a block filter set.
229 typedef SmallPtrSet<MachineBasicBlock *, 16> BlockFilterSet;
230
Chandler Carruth10281422011-10-21 06:46:38 +0000231 /// \brief A handle to the branch probability pass.
232 const MachineBranchProbabilityInfo *MBPI;
233
234 /// \brief A handle to the function-wide block frequency pass.
235 const MachineBlockFrequencyInfo *MBFI;
236
Chandler Carruth8b9737c2011-10-21 08:57:37 +0000237 /// \brief A handle to the loop info.
238 const MachineLoopInfo *MLI;
239
Chandler Carruth10281422011-10-21 06:46:38 +0000240 /// \brief A handle to the target's instruction info.
241 const TargetInstrInfo *TII;
242
Chandler Carruth8b9737c2011-10-21 08:57:37 +0000243 /// \brief A handle to the target's lowering info.
Benjamin Kramer56b31bd2013-01-11 20:05:37 +0000244 const TargetLoweringBase *TLI;
Chandler Carruth8b9737c2011-10-21 08:57:37 +0000245
Daniel Jasper471e8562015-03-04 11:05:34 +0000246 /// \brief A handle to the post dominator tree.
247 MachineDominatorTree *MDT;
248
249 /// \brief A set of blocks that are unavoidably execute, i.e. they dominate
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000250 /// all terminators of the MachineFunction.
Daniel Jasper471e8562015-03-04 11:05:34 +0000251 SmallPtrSet<MachineBasicBlock *, 4> UnavoidableBlocks;
252
Chandler Carruth10281422011-10-21 06:46:38 +0000253 /// \brief Allocator and owner of BlockChain structures.
254 ///
Chandler Carruth9139f442012-06-26 05:16:37 +0000255 /// We build BlockChains lazily while processing the loop structure of
256 /// a function. To reduce malloc traffic, we allocate them using this
257 /// slab-like allocator, and destroy them after the pass completes. An
258 /// important guarantee is that this allocator produces stable pointers to
259 /// the chains.
Chandler Carruth10281422011-10-21 06:46:38 +0000260 SpecificBumpPtrAllocator<BlockChain> ChainAllocator;
261
262 /// \brief Function wide BasicBlock to BlockChain mapping.
263 ///
264 /// This mapping allows efficiently moving from any given basic block to the
265 /// BlockChain it participates in, if any. We use it to, among other things,
266 /// allow implicitly defining edges between chains as the existing edges
267 /// between basic blocks.
268 DenseMap<MachineBasicBlock *, BlockChain *> BlockToChain;
269
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000270 void markChainSuccessors(BlockChain &Chain, MachineBasicBlock *LoopHeaderBB,
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000271 SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000272 SmallVectorImpl<MachineBasicBlock *> &EHPadWorkList,
Craig Topperc0196b12014-04-14 00:51:57 +0000273 const BlockFilterSet *BlockFilter = nullptr);
Jakub Staszak90616162011-12-21 23:02:08 +0000274 MachineBasicBlock *selectBestSuccessor(MachineBasicBlock *BB,
275 BlockChain &Chain,
276 const BlockFilterSet *BlockFilter);
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000277 MachineBasicBlock *
278 selectBestCandidateBlock(BlockChain &Chain,
Amaury Sechet9ee4ddd2016-04-07 06:34:47 +0000279 SmallVectorImpl<MachineBasicBlock *> &WorkList);
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000280 MachineBasicBlock *
281 getFirstUnplacedBlock(MachineFunction &F, const BlockChain &PlacedChain,
282 MachineFunction::iterator &PrevUnplacedBlockIt,
283 const BlockFilterSet *BlockFilter);
Amaury Secheteae09c22016-03-14 21:24:11 +0000284
285 /// \brief Add a basic block to the work list if it is apropriate.
286 ///
287 /// If the optional parameter BlockFilter is provided, only MBB
288 /// present in the set will be added to the worklist. If nullptr
289 /// is provided, no filtering occurs.
290 void fillWorkLists(MachineBasicBlock *MBB,
291 SmallPtrSetImpl<BlockChain *> &UpdatedPreds,
292 SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000293 SmallVectorImpl<MachineBasicBlock *> &EHPadWorkList,
Amaury Secheteae09c22016-03-14 21:24:11 +0000294 const BlockFilterSet *BlockFilter);
Chandler Carruth8d150782011-11-13 11:20:44 +0000295 void buildChain(MachineBasicBlock *BB, BlockChain &Chain,
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000296 SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000297 SmallVectorImpl<MachineBasicBlock *> &EHPadWorkList,
Craig Topperc0196b12014-04-14 00:51:57 +0000298 const BlockFilterSet *BlockFilter = nullptr);
Chandler Carruth8c0b41d2012-04-16 13:33:36 +0000299 MachineBasicBlock *findBestLoopTop(MachineLoop &L,
300 const BlockFilterSet &LoopBlockSet);
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000301 MachineBasicBlock *findBestLoopExit(MachineFunction &F, MachineLoop &L,
Chandler Carruthccc7e422012-04-16 01:12:56 +0000302 const BlockFilterSet &LoopBlockSet);
Cong Houb90b9e02015-11-02 21:24:00 +0000303 BlockFilterSet collectLoopBlockSet(MachineFunction &F, MachineLoop &L);
Jakub Staszak90616162011-12-21 23:02:08 +0000304 void buildLoopChains(MachineFunction &F, MachineLoop &L);
Chandler Carruth8c74c7b2012-04-16 09:31:23 +0000305 void rotateLoop(BlockChain &LoopChain, MachineBasicBlock *ExitingBB,
306 const BlockFilterSet &LoopBlockSet);
Cong Hou7745dbc2015-10-19 23:16:40 +0000307 void rotateLoopWithProfile(BlockChain &LoopChain, MachineLoop &L,
308 const BlockFilterSet &LoopBlockSet);
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000309 void buildCFGChains(MachineFunction &F);
Haicheng Wu90a55652016-05-24 22:16:14 +0000310 void optimizeBranches(MachineFunction &F);
Haicheng Wue749ce52016-04-29 17:06:44 +0000311 void alignBlocks(MachineFunction &F);
Chandler Carruth10281422011-10-21 06:46:38 +0000312
313public:
314 static char ID; // Pass identification, replacement for typeid
315 MachineBlockPlacement() : MachineFunctionPass(ID) {
316 initializeMachineBlockPlacementPass(*PassRegistry::getPassRegistry());
317 }
318
Craig Topper4584cd52014-03-07 09:26:03 +0000319 bool runOnMachineFunction(MachineFunction &F) override;
Chandler Carruth10281422011-10-21 06:46:38 +0000320
Craig Topper4584cd52014-03-07 09:26:03 +0000321 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruth10281422011-10-21 06:46:38 +0000322 AU.addRequired<MachineBranchProbabilityInfo>();
323 AU.addRequired<MachineBlockFrequencyInfo>();
Daniel Jasper471e8562015-03-04 11:05:34 +0000324 AU.addRequired<MachineDominatorTree>();
Chandler Carruth8b9737c2011-10-21 08:57:37 +0000325 AU.addRequired<MachineLoopInfo>();
Chandler Carruth10281422011-10-21 06:46:38 +0000326 MachineFunctionPass::getAnalysisUsage(AU);
327 }
Chandler Carruth10281422011-10-21 06:46:38 +0000328};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000329}
Chandler Carruth10281422011-10-21 06:46:38 +0000330
331char MachineBlockPlacement::ID = 0;
Andrew Trick1fa5bcb2012-02-08 21:23:13 +0000332char &llvm::MachineBlockPlacementID = MachineBlockPlacement::ID;
Chandler Carruthd0dced52015-03-05 02:28:25 +0000333INITIALIZE_PASS_BEGIN(MachineBlockPlacement, "block-placement",
Chandler Carruth10281422011-10-21 06:46:38 +0000334 "Branch Probability Basic Block Placement", false, false)
335INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
336INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
Daniel Jasper471e8562015-03-04 11:05:34 +0000337INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
Chandler Carruth8b9737c2011-10-21 08:57:37 +0000338INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
Chandler Carruthd0dced52015-03-05 02:28:25 +0000339INITIALIZE_PASS_END(MachineBlockPlacement, "block-placement",
Chandler Carruth10281422011-10-21 06:46:38 +0000340 "Branch Probability Basic Block Placement", false, false)
341
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000342#ifndef NDEBUG
343/// \brief Helper to print the name of a MBB.
344///
345/// Only used by debug logging.
Jakub Staszak90616162011-12-21 23:02:08 +0000346static std::string getBlockName(MachineBasicBlock *BB) {
Alp Tokere69170a2014-06-26 22:52:05 +0000347 std::string Result;
348 raw_string_ostream OS(Result);
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000349 OS << "BB#" << BB->getNumber();
Philip Reamesb9688f42016-03-02 21:45:13 +0000350 OS << " ('" << BB->getName() << "')";
Alp Tokere69170a2014-06-26 22:52:05 +0000351 OS.flush();
352 return Result;
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000353}
354#endif
355
Chandler Carrutheb4ec3a2011-11-13 11:34:55 +0000356/// \brief Mark a chain's successors as having one fewer preds.
357///
358/// When a chain is being merged into the "placed" chain, this routine will
359/// quickly walk the successors of each block in the chain and mark them as
360/// having one fewer active predecessor. It also adds any successors of this
361/// chain which reach the zero-predecessor state to the worklist passed in.
Chandler Carruth8d150782011-11-13 11:20:44 +0000362void MachineBlockPlacement::markChainSuccessors(
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000363 BlockChain &Chain, MachineBasicBlock *LoopHeaderBB,
Chandler Carruth8d150782011-11-13 11:20:44 +0000364 SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000365 SmallVectorImpl<MachineBasicBlock *> &EHPadWorkList,
Jakub Staszak90616162011-12-21 23:02:08 +0000366 const BlockFilterSet *BlockFilter) {
Chandler Carruth8d150782011-11-13 11:20:44 +0000367 // Walk all the blocks in this chain, marking their successors as having
368 // a predecessor placed.
Chandler Carruth7a715da2015-03-05 03:19:05 +0000369 for (MachineBasicBlock *MBB : Chain) {
Chandler Carruth8d150782011-11-13 11:20:44 +0000370 // Add any successors for which this is the only un-placed in-loop
371 // predecessor to the worklist as a viable candidate for CFG-neutral
372 // placement. No subsequent placement of this block will violate the CFG
373 // shape, so we get to use heuristics to choose a favorable placement.
Chandler Carruth7a715da2015-03-05 03:19:05 +0000374 for (MachineBasicBlock *Succ : MBB->successors()) {
375 if (BlockFilter && !BlockFilter->count(Succ))
Chandler Carruth8d150782011-11-13 11:20:44 +0000376 continue;
Chandler Carruth7a715da2015-03-05 03:19:05 +0000377 BlockChain &SuccChain = *BlockToChain[Succ];
Chandler Carruth8d150782011-11-13 11:20:44 +0000378 // Disregard edges within a fixed chain, or edges to the loop header.
Chandler Carruth7a715da2015-03-05 03:19:05 +0000379 if (&Chain == &SuccChain || Succ == LoopHeaderBB)
Chandler Carruth8d150782011-11-13 11:20:44 +0000380 continue;
Chandler Carruth10281422011-10-21 06:46:38 +0000381
Chandler Carruth8d150782011-11-13 11:20:44 +0000382 // This is a cross-chain edge that is within the loop, so decrement the
383 // loop predecessor count of the destination chain.
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000384 if (SuccChain.UnscheduledPredecessors == 0 ||
385 --SuccChain.UnscheduledPredecessors > 0)
386 continue;
387
388 auto *MBB = *SuccChain.begin();
389 if (MBB->isEHPad())
390 EHPadWorkList.push_back(MBB);
391 else
392 BlockWorkList.push_back(MBB);
Chandler Carruth10281422011-10-21 06:46:38 +0000393 }
394 }
Chandler Carruth8d150782011-11-13 11:20:44 +0000395}
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000396
Chandler Carruthb3361722011-11-13 11:34:53 +0000397/// \brief Select the best successor for a block.
398///
399/// This looks across all successors of a particular block and attempts to
400/// select the "best" one to be the layout successor. It only considers direct
401/// successors which also pass the block filter. It will attempt to avoid
402/// breaking CFG structure, but cave and break such structures in the case of
403/// very hot successor edges.
404///
405/// \returns The best successor block found, or null if none are viable.
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000406MachineBasicBlock *
407MachineBlockPlacement::selectBestSuccessor(MachineBasicBlock *BB,
408 BlockChain &Chain,
409 const BlockFilterSet *BlockFilter) {
Xinliang David Liff287372016-06-03 23:48:36 +0000410 const BranchProbability HotProb(StaticLikelyProb, 100);
Chandler Carruthb3361722011-11-13 11:34:53 +0000411
Craig Topperc0196b12014-04-14 00:51:57 +0000412 MachineBasicBlock *BestSucc = nullptr;
Cong Houd97c1002015-12-01 05:29:22 +0000413 auto BestProb = BranchProbability::getZero();
Chandler Carruthb3361722011-11-13 11:34:53 +0000414
Cong Houd97c1002015-12-01 05:29:22 +0000415 // Adjust edge probabilities by excluding edges pointing to blocks that is
416 // either not in BlockFilter or is already in the current chain. Consider the
417 // following CFG:
Cong Hou41cf1a52015-11-18 00:52:52 +0000418 //
419 // --->A
420 // | / \
421 // | B C
422 // | \ / \
423 // ----D E
424 //
425 // Assume A->C is very hot (>90%), and C->D has a 50% probability, then after
426 // A->C is chosen as a fall-through, D won't be selected as a successor of C
427 // due to CFG constraint (the probability of C->D is not greater than
428 // HotProb). If we exclude E that is not in BlockFilter when calculating the
429 // probability of C->D, D will be selected and we will get A C D B as the
430 // layout of this loop.
Cong Houd97c1002015-12-01 05:29:22 +0000431 auto AdjustedSumProb = BranchProbability::getOne();
Cong Hou41cf1a52015-11-18 00:52:52 +0000432 SmallVector<MachineBasicBlock *, 4> Successors;
433 for (MachineBasicBlock *Succ : BB->successors()) {
434 bool SkipSucc = false;
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000435 if (Succ->isEHPad() || (BlockFilter && !BlockFilter->count(Succ))) {
Cong Hou41cf1a52015-11-18 00:52:52 +0000436 SkipSucc = true;
437 } else {
438 BlockChain *SuccChain = BlockToChain[Succ];
439 if (SuccChain == &Chain) {
Cong Hou41cf1a52015-11-18 00:52:52 +0000440 SkipSucc = true;
441 } else if (Succ != *SuccChain->begin()) {
442 DEBUG(dbgs() << " " << getBlockName(Succ) << " -> Mid chain!\n");
443 continue;
444 }
445 }
446 if (SkipSucc)
Cong Houd97c1002015-12-01 05:29:22 +0000447 AdjustedSumProb -= MBPI->getEdgeProbability(BB, Succ);
Cong Hou41cf1a52015-11-18 00:52:52 +0000448 else
449 Successors.push_back(Succ);
450 }
451
452 DEBUG(dbgs() << "Attempting merge from: " << getBlockName(BB) << "\n");
453 for (MachineBasicBlock *Succ : Successors) {
Cong Houd97c1002015-12-01 05:29:22 +0000454 BranchProbability SuccProb;
455 uint32_t SuccProbN = MBPI->getEdgeProbability(BB, Succ).getNumerator();
456 uint32_t SuccProbD = AdjustedSumProb.getNumerator();
457 if (SuccProbN >= SuccProbD)
458 SuccProb = BranchProbability::getOne();
459 else
460 SuccProb = BranchProbability(SuccProbN, SuccProbD);
Chandler Carruthb3361722011-11-13 11:34:53 +0000461
Daniel Jasper471e8562015-03-04 11:05:34 +0000462 // If we outline optional branches, look whether Succ is unavoidable, i.e.
463 // dominates all terminators of the MachineFunction. If it does, other
464 // successors must be optional. Don't do this for cold branches.
465 if (OutlineOptionalBranches && SuccProb > HotProb.getCompl() &&
Daniel Jasper214997c2015-03-20 10:00:37 +0000466 UnavoidableBlocks.count(Succ) > 0) {
467 auto HasShortOptionalBranch = [&]() {
468 for (MachineBasicBlock *Pred : Succ->predecessors()) {
469 // Check whether there is an unplaced optional branch.
470 if (Pred == Succ || (BlockFilter && !BlockFilter->count(Pred)) ||
471 BlockToChain[Pred] == &Chain)
472 continue;
473 // Check whether the optional branch has exactly one BB.
474 if (Pred->pred_size() > 1 || *Pred->pred_begin() != BB)
475 continue;
476 // Check whether the optional branch is small.
477 if (Pred->size() < OutlineOptionalThreshold)
478 return true;
479 }
480 return false;
481 };
482 if (!HasShortOptionalBranch())
483 return Succ;
484 }
Daniel Jasper471e8562015-03-04 11:05:34 +0000485
Chandler Carruthb3361722011-11-13 11:34:53 +0000486 // Only consider successors which are either "hot", or wouldn't violate
487 // any CFG constraints.
Cong Hou41cf1a52015-11-18 00:52:52 +0000488 BlockChain &SuccChain = *BlockToChain[Succ];
Philip Reamesae27b232016-03-03 00:58:43 +0000489 if (SuccChain.UnscheduledPredecessors != 0) {
Chandler Carruth18dfac32011-11-20 11:22:06 +0000490 if (SuccProb < HotProb) {
Daniel Jaspered9eb722015-02-18 08:19:16 +0000491 DEBUG(dbgs() << " " << getBlockName(Succ) << " -> " << SuccProb
Chandler Carruth260258b2013-11-25 00:43:41 +0000492 << " (prob) (CFG conflict)\n");
Chandler Carruth18dfac32011-11-20 11:22:06 +0000493 continue;
494 }
495
Daniel Jasper4d7b0432015-02-18 08:18:07 +0000496 // Make sure that a hot successor doesn't have a globally more
497 // important predecessor.
Cong Houd97c1002015-12-01 05:29:22 +0000498 auto RealSuccProb = MBPI->getEdgeProbability(BB, Succ);
Daniel Jasper4d7b0432015-02-18 08:18:07 +0000499 BlockFrequency CandidateEdgeFreq =
Cong Hou41cf1a52015-11-18 00:52:52 +0000500 MBFI->getBlockFreq(BB) * RealSuccProb * HotProb.getCompl();
Daniel Jasper4d7b0432015-02-18 08:18:07 +0000501 bool BadCFGConflict = false;
Daniel Jaspered9eb722015-02-18 08:19:16 +0000502 for (MachineBasicBlock *Pred : Succ->predecessors()) {
Philip Reames23d93392016-03-03 00:01:42 +0000503 if (Pred == Succ || BlockToChain[Pred] == &SuccChain ||
504 (BlockFilter && !BlockFilter->count(Pred)) ||
Daniel Jaspered9eb722015-02-18 08:19:16 +0000505 BlockToChain[Pred] == &Chain)
Chandler Carruthe3288142015-01-14 20:19:29 +0000506 continue;
Daniel Jasper4d7b0432015-02-18 08:18:07 +0000507 BlockFrequency PredEdgeFreq =
Daniel Jaspered9eb722015-02-18 08:19:16 +0000508 MBFI->getBlockFreq(Pred) * MBPI->getEdgeProbability(Pred, Succ);
Daniel Jasper4d7b0432015-02-18 08:18:07 +0000509 if (PredEdgeFreq >= CandidateEdgeFreq) {
510 BadCFGConflict = true;
511 break;
Chandler Carruthe3288142015-01-14 20:19:29 +0000512 }
Chandler Carruth18dfac32011-11-20 11:22:06 +0000513 }
Daniel Jasper4d7b0432015-02-18 08:18:07 +0000514 if (BadCFGConflict) {
Daniel Jaspered9eb722015-02-18 08:19:16 +0000515 DEBUG(dbgs() << " " << getBlockName(Succ) << " -> " << SuccProb
Daniel Jasper4d7b0432015-02-18 08:18:07 +0000516 << " (prob) (non-cold CFG conflict)\n");
517 continue;
518 }
Chandler Carruthb3361722011-11-13 11:34:53 +0000519 }
520
Daniel Jaspered9eb722015-02-18 08:19:16 +0000521 DEBUG(dbgs() << " " << getBlockName(Succ) << " -> " << SuccProb
Chandler Carruthb3361722011-11-13 11:34:53 +0000522 << " (prob)"
Philip Reamesae27b232016-03-03 00:58:43 +0000523 << (SuccChain.UnscheduledPredecessors != 0 ? " (CFG break)" : "")
Chandler Carruthb3361722011-11-13 11:34:53 +0000524 << "\n");
Cong Houd97c1002015-12-01 05:29:22 +0000525 if (BestSucc && BestProb >= SuccProb)
Chandler Carruthb3361722011-11-13 11:34:53 +0000526 continue;
Daniel Jaspered9eb722015-02-18 08:19:16 +0000527 BestSucc = Succ;
Cong Houd97c1002015-12-01 05:29:22 +0000528 BestProb = SuccProb;
Chandler Carruthb3361722011-11-13 11:34:53 +0000529 }
530 return BestSucc;
531}
532
Chandler Carruthf9213fe2011-11-13 11:42:26 +0000533/// \brief Select the best block from a worklist.
534///
535/// This looks through the provided worklist as a list of candidate basic
536/// blocks and select the most profitable one to place. The definition of
537/// profitable only really makes sense in the context of a loop. This returns
538/// the most frequently visited block in the worklist, which in the case of
539/// a loop, is the one most desirable to be physically close to the rest of the
540/// loop body in order to improve icache behavior.
541///
542/// \returns The best block found, or null if none are viable.
543MachineBasicBlock *MachineBlockPlacement::selectBestCandidateBlock(
Amaury Sechet9ee4ddd2016-04-07 06:34:47 +0000544 BlockChain &Chain, SmallVectorImpl<MachineBasicBlock *> &WorkList) {
Chandler Carruth0af6a0b2011-11-14 09:46:33 +0000545 // Once we need to walk the worklist looking for a candidate, cleanup the
546 // worklist of already placed entries.
547 // FIXME: If this shows up on profiles, it could be folded (at the cost of
548 // some code complexity) into the loop below.
549 WorkList.erase(std::remove_if(WorkList.begin(), WorkList.end(),
Benjamin Kramer3a377bc2014-03-01 11:47:00 +0000550 [&](MachineBasicBlock *BB) {
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000551 return BlockToChain.lookup(BB) == &Chain;
552 }),
Chandler Carruth0af6a0b2011-11-14 09:46:33 +0000553 WorkList.end());
554
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000555 if (WorkList.empty())
556 return nullptr;
557
558 bool IsEHPad = WorkList[0]->isEHPad();
559
Craig Topperc0196b12014-04-14 00:51:57 +0000560 MachineBasicBlock *BestBlock = nullptr;
Chandler Carruthf9213fe2011-11-13 11:42:26 +0000561 BlockFrequency BestFreq;
Chandler Carruth7a715da2015-03-05 03:19:05 +0000562 for (MachineBasicBlock *MBB : WorkList) {
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000563 assert(MBB->isEHPad() == IsEHPad);
564
Chandler Carruth7a715da2015-03-05 03:19:05 +0000565 BlockChain &SuccChain = *BlockToChain[MBB];
Philip Reames02e11322016-03-02 22:40:51 +0000566 if (&SuccChain == &Chain)
Chandler Carruthf9213fe2011-11-13 11:42:26 +0000567 continue;
Junmo Park4ba6cf62016-03-11 05:07:07 +0000568
Philip Reamesae27b232016-03-03 00:58:43 +0000569 assert(SuccChain.UnscheduledPredecessors == 0 && "Found CFG-violating block");
Chandler Carruthf9213fe2011-11-13 11:42:26 +0000570
Chandler Carruth7a715da2015-03-05 03:19:05 +0000571 BlockFrequency CandidateFreq = MBFI->getBlockFreq(MBB);
572 DEBUG(dbgs() << " " << getBlockName(MBB) << " -> ";
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000573 MBFI->printBlockFreq(dbgs(), CandidateFreq) << " (freq)\n");
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000574
575 // For ehpad, we layout the least probable first as to avoid jumping back
576 // from least probable landingpads to more probable ones.
577 //
578 // FIXME: Using probability is probably (!) not the best way to achieve
579 // this. We should probably have a more principled approach to layout
580 // cleanup code.
581 //
582 // The goal is to get:
583 //
584 // +--------------------------+
585 // | V
586 // InnerLp -> InnerCleanup OuterLp -> OuterCleanup -> Resume
587 //
588 // Rather than:
589 //
590 // +-------------------------------------+
591 // V |
592 // OuterLp -> OuterCleanup -> Resume InnerLp -> InnerCleanup
593 if (BestBlock && (IsEHPad ^ (BestFreq >= CandidateFreq)))
Chandler Carruthf9213fe2011-11-13 11:42:26 +0000594 continue;
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000595
Chandler Carruth7a715da2015-03-05 03:19:05 +0000596 BestBlock = MBB;
Chandler Carruthf9213fe2011-11-13 11:42:26 +0000597 BestFreq = CandidateFreq;
598 }
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000599
Chandler Carruthf9213fe2011-11-13 11:42:26 +0000600 return BestBlock;
601}
602
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000603/// \brief Retrieve the first unplaced basic block.
604///
605/// This routine is called when we are unable to use the CFG to walk through
606/// all of the basic blocks and form a chain due to unnatural loops in the CFG.
Chandler Carruth9b548a7f2011-11-15 06:26:43 +0000607/// We walk through the function's blocks in order, starting from the
608/// LastUnplacedBlockIt. We update this iterator on each call to avoid
609/// re-scanning the entire sequence on repeated calls to this routine.
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000610MachineBasicBlock *MachineBlockPlacement::getFirstUnplacedBlock(
Chandler Carruth9b548a7f2011-11-15 06:26:43 +0000611 MachineFunction &F, const BlockChain &PlacedChain,
612 MachineFunction::iterator &PrevUnplacedBlockIt,
Jakub Staszak90616162011-12-21 23:02:08 +0000613 const BlockFilterSet *BlockFilter) {
Chandler Carruth9b548a7f2011-11-15 06:26:43 +0000614 for (MachineFunction::iterator I = PrevUnplacedBlockIt, E = F.end(); I != E;
615 ++I) {
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +0000616 if (BlockFilter && !BlockFilter->count(&*I))
Chandler Carruth9b548a7f2011-11-15 06:26:43 +0000617 continue;
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +0000618 if (BlockToChain[&*I] != &PlacedChain) {
Chandler Carruth9b548a7f2011-11-15 06:26:43 +0000619 PrevUnplacedBlockIt = I;
Chandler Carruth4a87aa02011-11-23 03:03:21 +0000620 // Now select the head of the chain to which the unplaced block belongs
621 // as the block to place. This will force the entire chain to be placed,
622 // and satisfies the requirements of merging chains.
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +0000623 return *BlockToChain[&*I]->begin();
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000624 }
625 }
Craig Topperc0196b12014-04-14 00:51:57 +0000626 return nullptr;
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000627}
628
Amaury Secheteae09c22016-03-14 21:24:11 +0000629void MachineBlockPlacement::fillWorkLists(
630 MachineBasicBlock *MBB,
631 SmallPtrSetImpl<BlockChain *> &UpdatedPreds,
632 SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000633 SmallVectorImpl<MachineBasicBlock *> &EHPadWorkList,
Amaury Secheteae09c22016-03-14 21:24:11 +0000634 const BlockFilterSet *BlockFilter = nullptr) {
635 BlockChain &Chain = *BlockToChain[MBB];
636 if (!UpdatedPreds.insert(&Chain).second)
637 return;
638
639 assert(Chain.UnscheduledPredecessors == 0);
640 for (MachineBasicBlock *ChainBB : Chain) {
641 assert(BlockToChain[ChainBB] == &Chain);
642 for (MachineBasicBlock *Pred : ChainBB->predecessors()) {
643 if (BlockFilter && !BlockFilter->count(Pred))
644 continue;
645 if (BlockToChain[Pred] == &Chain)
646 continue;
647 ++Chain.UnscheduledPredecessors;
648 }
649 }
650
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000651 if (Chain.UnscheduledPredecessors != 0)
652 return;
653
654 MBB = *Chain.begin();
655 if (MBB->isEHPad())
656 EHPadWorkList.push_back(MBB);
657 else
658 BlockWorkList.push_back(MBB);
Amaury Secheteae09c22016-03-14 21:24:11 +0000659}
660
Chandler Carruth8d150782011-11-13 11:20:44 +0000661void MachineBlockPlacement::buildChain(
Daniel Jasper471e8562015-03-04 11:05:34 +0000662 MachineBasicBlock *BB, BlockChain &Chain,
Chandler Carruth8d150782011-11-13 11:20:44 +0000663 SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000664 SmallVectorImpl<MachineBasicBlock *> &EHPadWorkList,
Jakub Staszak90616162011-12-21 23:02:08 +0000665 const BlockFilterSet *BlockFilter) {
Chandler Carruth8d150782011-11-13 11:20:44 +0000666 assert(BB);
Jakub Staszak90616162011-12-21 23:02:08 +0000667 assert(BlockToChain[BB] == &Chain);
Chandler Carruth9b548a7f2011-11-15 06:26:43 +0000668 MachineFunction &F = *BB->getParent();
669 MachineFunction::iterator PrevUnplacedBlockIt = F.begin();
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000670
Chandler Carruth8d150782011-11-13 11:20:44 +0000671 MachineBasicBlock *LoopHeaderBB = BB;
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000672 markChainSuccessors(Chain, LoopHeaderBB, BlockWorkList, EHPadWorkList,
673 BlockFilter);
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000674 BB = *std::prev(Chain.end());
Chandler Carruth8d150782011-11-13 11:20:44 +0000675 for (;;) {
676 assert(BB);
Jakub Staszak90616162011-12-21 23:02:08 +0000677 assert(BlockToChain[BB] == &Chain);
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000678 assert(*std::prev(Chain.end()) == BB);
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000679
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +0000680 // Look for the best viable successor if there is one to place immediately
681 // after this block.
Duncan Sands291d47e2012-09-14 09:00:11 +0000682 MachineBasicBlock *BestSucc = selectBestSuccessor(BB, Chain, BlockFilter);
Chandler Carruth8d150782011-11-13 11:20:44 +0000683
684 // If an immediate successor isn't available, look for the best viable
685 // block among those we've identified as not violating the loop's CFG at
686 // this point. This won't be a fallthrough, but it will increase locality.
Chandler Carruthf9213fe2011-11-13 11:42:26 +0000687 if (!BestSucc)
Amaury Sechet9ee4ddd2016-04-07 06:34:47 +0000688 BestSucc = selectBestCandidateBlock(Chain, BlockWorkList);
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000689 if (!BestSucc)
690 BestSucc = selectBestCandidateBlock(Chain, EHPadWorkList);
Chandler Carruth8d150782011-11-13 11:20:44 +0000691
Chandler Carruth8d150782011-11-13 11:20:44 +0000692 if (!BestSucc) {
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000693 BestSucc =
694 getFirstUnplacedBlock(F, Chain, PrevUnplacedBlockIt, BlockFilter);
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000695 if (!BestSucc)
696 break;
697
698 DEBUG(dbgs() << "Unnatural loop CFG detected, forcibly merging the "
699 "layout successor until the CFG reduces\n");
Chandler Carruth8d150782011-11-13 11:20:44 +0000700 }
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000701
Chandler Carruth8d150782011-11-13 11:20:44 +0000702 // Place this block, updating the datastructures to reflect its placement.
Jakub Staszak90616162011-12-21 23:02:08 +0000703 BlockChain &SuccChain = *BlockToChain[BestSucc];
Philip Reamesae27b232016-03-03 00:58:43 +0000704 // Zero out UnscheduledPredecessors for the successor we're about to merge in case
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000705 // we selected a successor that didn't fit naturally into the CFG.
Philip Reamesae27b232016-03-03 00:58:43 +0000706 SuccChain.UnscheduledPredecessors = 0;
Philip Reamesb9688f42016-03-02 21:45:13 +0000707 DEBUG(dbgs() << "Merging from " << getBlockName(BB) << " to "
708 << getBlockName(BestSucc) << "\n");
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000709 markChainSuccessors(SuccChain, LoopHeaderBB, BlockWorkList, EHPadWorkList,
710 BlockFilter);
Chandler Carruth8d150782011-11-13 11:20:44 +0000711 Chain.merge(BestSucc, &SuccChain);
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000712 BB = *std::prev(Chain.end());
Jakub Staszak190c7122011-12-07 19:46:10 +0000713 }
Chandler Carruth1071cfa2011-11-14 00:00:35 +0000714
715 DEBUG(dbgs() << "Finished forming chain for header block "
Philip Reamesb9688f42016-03-02 21:45:13 +0000716 << getBlockName(*Chain.begin()) << "\n");
Chandler Carruth10281422011-10-21 06:46:38 +0000717}
718
Chandler Carruth03adbd42011-11-27 13:34:33 +0000719/// \brief Find the best loop top block for layout.
Chandler Carruth9ffb97e2011-11-27 00:38:03 +0000720///
Chandler Carruth8c0b41d2012-04-16 13:33:36 +0000721/// Look for a block which is strictly better than the loop header for laying
722/// out at the top of the loop. This looks for one and only one pattern:
723/// a latch block with no conditional exit. This block will cause a conditional
724/// jump around it or will be the bottom of the loop if we lay it out in place,
725/// but if it it doesn't end up at the bottom of the loop for any reason,
726/// rotation alone won't fix it. Because such a block will always result in an
727/// unconditional jump (for the backedge) rotating it in front of the loop
728/// header is always profitable.
729MachineBasicBlock *
730MachineBlockPlacement::findBestLoopTop(MachineLoop &L,
731 const BlockFilterSet &LoopBlockSet) {
732 // Check that the header hasn't been fused with a preheader block due to
733 // crazy branches. If it has, we need to start with the header at the top to
734 // prevent pulling the preheader into the loop body.
735 BlockChain &HeaderChain = *BlockToChain[L.getHeader()];
736 if (!LoopBlockSet.count(*HeaderChain.begin()))
737 return L.getHeader();
738
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000739 DEBUG(dbgs() << "Finding best loop top for: " << getBlockName(L.getHeader())
740 << "\n");
Chandler Carruth8c0b41d2012-04-16 13:33:36 +0000741
742 BlockFrequency BestPredFreq;
Craig Topperc0196b12014-04-14 00:51:57 +0000743 MachineBasicBlock *BestPred = nullptr;
Chandler Carruth7a715da2015-03-05 03:19:05 +0000744 for (MachineBasicBlock *Pred : L.getHeader()->predecessors()) {
Chandler Carruth8c0b41d2012-04-16 13:33:36 +0000745 if (!LoopBlockSet.count(Pred))
746 continue;
747 DEBUG(dbgs() << " header pred: " << getBlockName(Pred) << ", "
Michael Gottesmanb78dec82013-12-14 00:25:45 +0000748 << Pred->succ_size() << " successors, ";
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000749 MBFI->printBlockFreq(dbgs(), Pred) << " freq\n");
Chandler Carruth8c0b41d2012-04-16 13:33:36 +0000750 if (Pred->succ_size() > 1)
751 continue;
752
753 BlockFrequency PredFreq = MBFI->getBlockFreq(Pred);
754 if (!BestPred || PredFreq > BestPredFreq ||
755 (!(PredFreq < BestPredFreq) &&
756 Pred->isLayoutSuccessor(L.getHeader()))) {
757 BestPred = Pred;
758 BestPredFreq = PredFreq;
759 }
760 }
761
762 // If no direct predecessor is fine, just use the loop header.
Philip Reamesb9688f42016-03-02 21:45:13 +0000763 if (!BestPred) {
764 DEBUG(dbgs() << " final top unchanged\n");
Chandler Carruth8c0b41d2012-04-16 13:33:36 +0000765 return L.getHeader();
Philip Reamesb9688f42016-03-02 21:45:13 +0000766 }
Chandler Carruth8c0b41d2012-04-16 13:33:36 +0000767
768 // Walk backwards through any straight line of predecessors.
769 while (BestPred->pred_size() == 1 &&
770 (*BestPred->pred_begin())->succ_size() == 1 &&
771 *BestPred->pred_begin() != L.getHeader())
772 BestPred = *BestPred->pred_begin();
773
774 DEBUG(dbgs() << " final top: " << getBlockName(BestPred) << "\n");
775 return BestPred;
776}
777
Chandler Carruth8c0b41d2012-04-16 13:33:36 +0000778/// \brief Find the best loop exiting block for layout.
779///
Chandler Carruth03adbd42011-11-27 13:34:33 +0000780/// This routine implements the logic to analyze the loop looking for the best
781/// block to layout at the top of the loop. Typically this is done to maximize
782/// fallthrough opportunities.
783MachineBasicBlock *
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000784MachineBlockPlacement::findBestLoopExit(MachineFunction &F, MachineLoop &L,
Chandler Carruthccc7e422012-04-16 01:12:56 +0000785 const BlockFilterSet &LoopBlockSet) {
Chandler Carruth68062612012-04-10 13:35:57 +0000786 // We don't want to layout the loop linearly in all cases. If the loop header
787 // is just a normal basic block in the loop, we want to look for what block
788 // within the loop is the best one to layout at the top. However, if the loop
789 // header has be pre-merged into a chain due to predecessors not having
790 // analyzable branches, *and* the predecessor it is merged with is *not* part
791 // of the loop, rotating the header into the middle of the loop will create
792 // a non-contiguous range of blocks which is Very Bad. So start with the
793 // header and only rotate if safe.
794 BlockChain &HeaderChain = *BlockToChain[L.getHeader()];
795 if (!LoopBlockSet.count(*HeaderChain.begin()))
Craig Topperc0196b12014-04-14 00:51:57 +0000796 return nullptr;
Chandler Carruth68062612012-04-10 13:35:57 +0000797
Chandler Carruth03adbd42011-11-27 13:34:33 +0000798 BlockFrequency BestExitEdgeFreq;
Chandler Carruthccc7e422012-04-16 01:12:56 +0000799 unsigned BestExitLoopDepth = 0;
Craig Topperc0196b12014-04-14 00:51:57 +0000800 MachineBasicBlock *ExitingBB = nullptr;
Chandler Carruth4f567202011-11-27 20:18:00 +0000801 // If there are exits to outer loops, loop rotation can severely limit
802 // fallthrough opportunites unless it selects such an exit. Keep a set of
803 // blocks where rotating to exit with that block will reach an outer loop.
804 SmallPtrSet<MachineBasicBlock *, 4> BlocksExitingToOuterLoop;
805
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000806 DEBUG(dbgs() << "Finding best loop exit for: " << getBlockName(L.getHeader())
807 << "\n");
Chandler Carruth7a715da2015-03-05 03:19:05 +0000808 for (MachineBasicBlock *MBB : L.getBlocks()) {
809 BlockChain &Chain = *BlockToChain[MBB];
Chandler Carruth03adbd42011-11-27 13:34:33 +0000810 // Ensure that this block is at the end of a chain; otherwise it could be
Chandler Carruth9a512a42015-04-15 13:19:54 +0000811 // mid-way through an inner loop or a successor of an unanalyzable branch.
Chandler Carruth7a715da2015-03-05 03:19:05 +0000812 if (MBB != *std::prev(Chain.end()))
Chandler Carruth9ffb97e2011-11-27 00:38:03 +0000813 continue;
Chandler Carruth9ffb97e2011-11-27 00:38:03 +0000814
Chandler Carruth03adbd42011-11-27 13:34:33 +0000815 // Now walk the successors. We need to establish whether this has a viable
816 // exiting successor and whether it has a viable non-exiting successor.
817 // We store the old exiting state and restore it if a viable looping
818 // successor isn't found.
819 MachineBasicBlock *OldExitingBB = ExitingBB;
820 BlockFrequency OldBestExitEdgeFreq = BestExitEdgeFreq;
Chandler Carruthccc7e422012-04-16 01:12:56 +0000821 bool HasLoopingSucc = false;
Chandler Carruth7a715da2015-03-05 03:19:05 +0000822 for (MachineBasicBlock *Succ : MBB->successors()) {
Reid Kleckner0e288232015-08-27 23:27:47 +0000823 if (Succ->isEHPad())
Chandler Carruth03adbd42011-11-27 13:34:33 +0000824 continue;
Chandler Carruth7a715da2015-03-05 03:19:05 +0000825 if (Succ == MBB)
Chandler Carruth03adbd42011-11-27 13:34:33 +0000826 continue;
Chandler Carruth7a715da2015-03-05 03:19:05 +0000827 BlockChain &SuccChain = *BlockToChain[Succ];
Chandler Carruth03adbd42011-11-27 13:34:33 +0000828 // Don't split chains, either this chain or the successor's chain.
Chandler Carruthccc7e422012-04-16 01:12:56 +0000829 if (&Chain == &SuccChain) {
Chandler Carruth7a715da2015-03-05 03:19:05 +0000830 DEBUG(dbgs() << " exiting: " << getBlockName(MBB) << " -> "
831 << getBlockName(Succ) << " (chain conflict)\n");
Chandler Carruth03adbd42011-11-27 13:34:33 +0000832 continue;
833 }
834
Cong Houd97c1002015-12-01 05:29:22 +0000835 auto SuccProb = MBPI->getEdgeProbability(MBB, Succ);
Chandler Carruth7a715da2015-03-05 03:19:05 +0000836 if (LoopBlockSet.count(Succ)) {
837 DEBUG(dbgs() << " looping: " << getBlockName(MBB) << " -> "
Cong Houd97c1002015-12-01 05:29:22 +0000838 << getBlockName(Succ) << " (" << SuccProb << ")\n");
Chandler Carruthccc7e422012-04-16 01:12:56 +0000839 HasLoopingSucc = true;
Chandler Carruth03adbd42011-11-27 13:34:33 +0000840 continue;
841 }
842
Chandler Carruthccc7e422012-04-16 01:12:56 +0000843 unsigned SuccLoopDepth = 0;
Chandler Carruth7a715da2015-03-05 03:19:05 +0000844 if (MachineLoop *ExitLoop = MLI->getLoopFor(Succ)) {
Chandler Carruthccc7e422012-04-16 01:12:56 +0000845 SuccLoopDepth = ExitLoop->getLoopDepth();
846 if (ExitLoop->contains(&L))
Chandler Carruth7a715da2015-03-05 03:19:05 +0000847 BlocksExitingToOuterLoop.insert(MBB);
Chandler Carruthccc7e422012-04-16 01:12:56 +0000848 }
849
Chandler Carruth7a715da2015-03-05 03:19:05 +0000850 BlockFrequency ExitEdgeFreq = MBFI->getBlockFreq(MBB) * SuccProb;
851 DEBUG(dbgs() << " exiting: " << getBlockName(MBB) << " -> "
852 << getBlockName(Succ) << " [L:" << SuccLoopDepth << "] (";
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000853 MBFI->printBlockFreq(dbgs(), ExitEdgeFreq) << ")\n");
Benjamin Kramerc8160d62013-11-20 19:08:44 +0000854 // Note that we bias this toward an existing layout successor to retain
855 // incoming order in the absence of better information. The exit must have
856 // a frequency higher than the current exit before we consider breaking
857 // the layout.
858 BranchProbability Bias(100 - ExitBlockBias, 100);
Chandler Carruth26d30172015-04-15 13:39:42 +0000859 if (!ExitingBB || SuccLoopDepth > BestExitLoopDepth ||
Chandler Carruthccc7e422012-04-16 01:12:56 +0000860 ExitEdgeFreq > BestExitEdgeFreq ||
Chandler Carruth7a715da2015-03-05 03:19:05 +0000861 (MBB->isLayoutSuccessor(Succ) &&
Benjamin Kramerc8160d62013-11-20 19:08:44 +0000862 !(ExitEdgeFreq < BestExitEdgeFreq * Bias))) {
Chandler Carruth03adbd42011-11-27 13:34:33 +0000863 BestExitEdgeFreq = ExitEdgeFreq;
Chandler Carruth7a715da2015-03-05 03:19:05 +0000864 ExitingBB = MBB;
Chandler Carrutha0545802011-11-27 09:22:53 +0000865 }
Chandler Carruth9ffb97e2011-11-27 00:38:03 +0000866 }
Chandler Carruth03adbd42011-11-27 13:34:33 +0000867
Chandler Carruthccc7e422012-04-16 01:12:56 +0000868 if (!HasLoopingSucc) {
Chandler Carruthcfb2b9d2015-04-15 13:26:41 +0000869 // Restore the old exiting state, no viable looping successor was found.
Chandler Carruth03adbd42011-11-27 13:34:33 +0000870 ExitingBB = OldExitingBB;
871 BestExitEdgeFreq = OldBestExitEdgeFreq;
Chandler Carruth03adbd42011-11-27 13:34:33 +0000872 }
Chandler Carruth9ffb97e2011-11-27 00:38:03 +0000873 }
Chandler Carruthccc7e422012-04-16 01:12:56 +0000874 // Without a candidate exiting block or with only a single block in the
Chandler Carruth03adbd42011-11-27 13:34:33 +0000875 // loop, just use the loop header to layout the loop.
876 if (!ExitingBB || L.getNumBlocks() == 1)
Craig Topperc0196b12014-04-14 00:51:57 +0000877 return nullptr;
Chandler Carruth9ffb97e2011-11-27 00:38:03 +0000878
Chandler Carruth4f567202011-11-27 20:18:00 +0000879 // Also, if we have exit blocks which lead to outer loops but didn't select
880 // one of them as the exiting block we are rotating toward, disable loop
881 // rotation altogether.
882 if (!BlocksExitingToOuterLoop.empty() &&
883 !BlocksExitingToOuterLoop.count(ExitingBB))
Craig Topperc0196b12014-04-14 00:51:57 +0000884 return nullptr;
Chandler Carruth4f567202011-11-27 20:18:00 +0000885
Chandler Carruth03adbd42011-11-27 13:34:33 +0000886 DEBUG(dbgs() << " Best exiting block: " << getBlockName(ExitingBB) << "\n");
Chandler Carruthccc7e422012-04-16 01:12:56 +0000887 return ExitingBB;
Chandler Carruth9ffb97e2011-11-27 00:38:03 +0000888}
889
Chandler Carruth8c74c7b2012-04-16 09:31:23 +0000890/// \brief Attempt to rotate an exiting block to the bottom of the loop.
891///
892/// Once we have built a chain, try to rotate it to line up the hot exit block
893/// with fallthrough out of the loop if doing so doesn't introduce unnecessary
894/// branches. For example, if the loop has fallthrough into its header and out
895/// of its bottom already, don't rotate it.
896void MachineBlockPlacement::rotateLoop(BlockChain &LoopChain,
897 MachineBasicBlock *ExitingBB,
898 const BlockFilterSet &LoopBlockSet) {
899 if (!ExitingBB)
900 return;
901
902 MachineBasicBlock *Top = *LoopChain.begin();
903 bool ViableTopFallthrough = false;
Chandler Carruth7a715da2015-03-05 03:19:05 +0000904 for (MachineBasicBlock *Pred : Top->predecessors()) {
905 BlockChain *PredChain = BlockToChain[Pred];
906 if (!LoopBlockSet.count(Pred) &&
907 (!PredChain || Pred == *std::prev(PredChain->end()))) {
Chandler Carruth8c74c7b2012-04-16 09:31:23 +0000908 ViableTopFallthrough = true;
909 break;
910 }
911 }
912
913 // If the header has viable fallthrough, check whether the current loop
914 // bottom is a viable exiting block. If so, bail out as rotating will
915 // introduce an unnecessary branch.
916 if (ViableTopFallthrough) {
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000917 MachineBasicBlock *Bottom = *std::prev(LoopChain.end());
Chandler Carruth7a715da2015-03-05 03:19:05 +0000918 for (MachineBasicBlock *Succ : Bottom->successors()) {
919 BlockChain *SuccChain = BlockToChain[Succ];
920 if (!LoopBlockSet.count(Succ) &&
921 (!SuccChain || Succ == *SuccChain->begin()))
Chandler Carruth8c74c7b2012-04-16 09:31:23 +0000922 return;
923 }
924 }
925
Chandler Carruth2fc3fe12015-03-05 02:35:31 +0000926 BlockChain::iterator ExitIt =
927 std::find(LoopChain.begin(), LoopChain.end(), ExitingBB);
Chandler Carruth8c74c7b2012-04-16 09:31:23 +0000928 if (ExitIt == LoopChain.end())
929 return;
930
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000931 std::rotate(LoopChain.begin(), std::next(ExitIt), LoopChain.end());
Chandler Carruth8c74c7b2012-04-16 09:31:23 +0000932}
933
Cong Hou7745dbc2015-10-19 23:16:40 +0000934/// \brief Attempt to rotate a loop based on profile data to reduce branch cost.
935///
936/// With profile data, we can determine the cost in terms of missed fall through
937/// opportunities when rotating a loop chain and select the best rotation.
938/// Basically, there are three kinds of cost to consider for each rotation:
939/// 1. The possibly missed fall through edge (if it exists) from BB out of
940/// the loop to the loop header.
941/// 2. The possibly missed fall through edges (if they exist) from the loop
942/// exits to BB out of the loop.
943/// 3. The missed fall through edge (if it exists) from the last BB to the
944/// first BB in the loop chain.
945/// Therefore, the cost for a given rotation is the sum of costs listed above.
946/// We select the best rotation with the smallest cost.
947void MachineBlockPlacement::rotateLoopWithProfile(
948 BlockChain &LoopChain, MachineLoop &L, const BlockFilterSet &LoopBlockSet) {
949 auto HeaderBB = L.getHeader();
950 auto HeaderIter = std::find(LoopChain.begin(), LoopChain.end(), HeaderBB);
951 auto RotationPos = LoopChain.end();
952
953 BlockFrequency SmallestRotationCost = BlockFrequency::getMaxFrequency();
954
955 // A utility lambda that scales up a block frequency by dividing it by a
956 // branch probability which is the reciprocal of the scale.
957 auto ScaleBlockFrequency = [](BlockFrequency Freq,
958 unsigned Scale) -> BlockFrequency {
959 if (Scale == 0)
960 return 0;
961 // Use operator / between BlockFrequency and BranchProbability to implement
962 // saturating multiplication.
963 return Freq / BranchProbability(1, Scale);
964 };
965
966 // Compute the cost of the missed fall-through edge to the loop header if the
967 // chain head is not the loop header. As we only consider natural loops with
968 // single header, this computation can be done only once.
969 BlockFrequency HeaderFallThroughCost(0);
970 for (auto *Pred : HeaderBB->predecessors()) {
971 BlockChain *PredChain = BlockToChain[Pred];
972 if (!LoopBlockSet.count(Pred) &&
973 (!PredChain || Pred == *std::prev(PredChain->end()))) {
974 auto EdgeFreq =
975 MBFI->getBlockFreq(Pred) * MBPI->getEdgeProbability(Pred, HeaderBB);
976 auto FallThruCost = ScaleBlockFrequency(EdgeFreq, MisfetchCost);
977 // If the predecessor has only an unconditional jump to the header, we
978 // need to consider the cost of this jump.
979 if (Pred->succ_size() == 1)
980 FallThruCost += ScaleBlockFrequency(EdgeFreq, JumpInstCost);
981 HeaderFallThroughCost = std::max(HeaderFallThroughCost, FallThruCost);
982 }
983 }
984
985 // Here we collect all exit blocks in the loop, and for each exit we find out
986 // its hottest exit edge. For each loop rotation, we define the loop exit cost
987 // as the sum of frequencies of exit edges we collect here, excluding the exit
988 // edge from the tail of the loop chain.
989 SmallVector<std::pair<MachineBasicBlock *, BlockFrequency>, 4> ExitsWithFreq;
990 for (auto BB : LoopChain) {
Cong Houd97c1002015-12-01 05:29:22 +0000991 auto LargestExitEdgeProb = BranchProbability::getZero();
Cong Hou7745dbc2015-10-19 23:16:40 +0000992 for (auto *Succ : BB->successors()) {
993 BlockChain *SuccChain = BlockToChain[Succ];
994 if (!LoopBlockSet.count(Succ) &&
995 (!SuccChain || Succ == *SuccChain->begin())) {
Cong Houd97c1002015-12-01 05:29:22 +0000996 auto SuccProb = MBPI->getEdgeProbability(BB, Succ);
997 LargestExitEdgeProb = std::max(LargestExitEdgeProb, SuccProb);
Cong Hou7745dbc2015-10-19 23:16:40 +0000998 }
999 }
Cong Houd97c1002015-12-01 05:29:22 +00001000 if (LargestExitEdgeProb > BranchProbability::getZero()) {
1001 auto ExitFreq = MBFI->getBlockFreq(BB) * LargestExitEdgeProb;
Cong Hou7745dbc2015-10-19 23:16:40 +00001002 ExitsWithFreq.emplace_back(BB, ExitFreq);
1003 }
1004 }
1005
1006 // In this loop we iterate every block in the loop chain and calculate the
1007 // cost assuming the block is the head of the loop chain. When the loop ends,
1008 // we should have found the best candidate as the loop chain's head.
1009 for (auto Iter = LoopChain.begin(), TailIter = std::prev(LoopChain.end()),
1010 EndIter = LoopChain.end();
1011 Iter != EndIter; Iter++, TailIter++) {
1012 // TailIter is used to track the tail of the loop chain if the block we are
1013 // checking (pointed by Iter) is the head of the chain.
1014 if (TailIter == LoopChain.end())
1015 TailIter = LoopChain.begin();
1016
1017 auto TailBB = *TailIter;
1018
1019 // Calculate the cost by putting this BB to the top.
1020 BlockFrequency Cost = 0;
1021
1022 // If the current BB is the loop header, we need to take into account the
1023 // cost of the missed fall through edge from outside of the loop to the
1024 // header.
1025 if (Iter != HeaderIter)
1026 Cost += HeaderFallThroughCost;
1027
1028 // Collect the loop exit cost by summing up frequencies of all exit edges
1029 // except the one from the chain tail.
1030 for (auto &ExitWithFreq : ExitsWithFreq)
1031 if (TailBB != ExitWithFreq.first)
1032 Cost += ExitWithFreq.second;
1033
1034 // The cost of breaking the once fall-through edge from the tail to the top
1035 // of the loop chain. Here we need to consider three cases:
1036 // 1. If the tail node has only one successor, then we will get an
1037 // additional jmp instruction. So the cost here is (MisfetchCost +
1038 // JumpInstCost) * tail node frequency.
1039 // 2. If the tail node has two successors, then we may still get an
1040 // additional jmp instruction if the layout successor after the loop
1041 // chain is not its CFG successor. Note that the more frequently executed
1042 // jmp instruction will be put ahead of the other one. Assume the
1043 // frequency of those two branches are x and y, where x is the frequency
1044 // of the edge to the chain head, then the cost will be
1045 // (x * MisfetechCost + min(x, y) * JumpInstCost) * tail node frequency.
1046 // 3. If the tail node has more than two successors (this rarely happens),
1047 // we won't consider any additional cost.
1048 if (TailBB->isSuccessor(*Iter)) {
1049 auto TailBBFreq = MBFI->getBlockFreq(TailBB);
1050 if (TailBB->succ_size() == 1)
1051 Cost += ScaleBlockFrequency(TailBBFreq.getFrequency(),
1052 MisfetchCost + JumpInstCost);
1053 else if (TailBB->succ_size() == 2) {
1054 auto TailToHeadProb = MBPI->getEdgeProbability(TailBB, *Iter);
1055 auto TailToHeadFreq = TailBBFreq * TailToHeadProb;
1056 auto ColderEdgeFreq = TailToHeadProb > BranchProbability(1, 2)
1057 ? TailBBFreq * TailToHeadProb.getCompl()
1058 : TailToHeadFreq;
1059 Cost += ScaleBlockFrequency(TailToHeadFreq, MisfetchCost) +
1060 ScaleBlockFrequency(ColderEdgeFreq, JumpInstCost);
1061 }
1062 }
1063
Philip Reamesb9688f42016-03-02 21:45:13 +00001064 DEBUG(dbgs() << "The cost of loop rotation by making " << getBlockName(*Iter)
Cong Hou7745dbc2015-10-19 23:16:40 +00001065 << " to the top: " << Cost.getFrequency() << "\n");
1066
1067 if (Cost < SmallestRotationCost) {
1068 SmallestRotationCost = Cost;
1069 RotationPos = Iter;
1070 }
1071 }
1072
1073 if (RotationPos != LoopChain.end()) {
Philip Reamesb9688f42016-03-02 21:45:13 +00001074 DEBUG(dbgs() << "Rotate loop by making " << getBlockName(*RotationPos)
Cong Hou7745dbc2015-10-19 23:16:40 +00001075 << " to the top\n");
1076 std::rotate(LoopChain.begin(), RotationPos, LoopChain.end());
1077 }
1078}
1079
Cong Houb90b9e02015-11-02 21:24:00 +00001080/// \brief Collect blocks in the given loop that are to be placed.
1081///
1082/// When profile data is available, exclude cold blocks from the returned set;
1083/// otherwise, collect all blocks in the loop.
1084MachineBlockPlacement::BlockFilterSet
1085MachineBlockPlacement::collectLoopBlockSet(MachineFunction &F, MachineLoop &L) {
1086 BlockFilterSet LoopBlockSet;
1087
1088 // Filter cold blocks off from LoopBlockSet when profile data is available.
1089 // Collect the sum of frequencies of incoming edges to the loop header from
1090 // outside. If we treat the loop as a super block, this is the frequency of
1091 // the loop. Then for each block in the loop, we calculate the ratio between
1092 // its frequency and the frequency of the loop block. When it is too small,
1093 // don't add it to the loop chain. If there are outer loops, then this block
1094 // will be merged into the first outer loop chain for which this block is not
1095 // cold anymore. This needs precise profile data and we only do this when
1096 // profile data is available.
1097 if (F.getFunction()->getEntryCount()) {
1098 BlockFrequency LoopFreq(0);
1099 for (auto LoopPred : L.getHeader()->predecessors())
1100 if (!L.contains(LoopPred))
1101 LoopFreq += MBFI->getBlockFreq(LoopPred) *
1102 MBPI->getEdgeProbability(LoopPred, L.getHeader());
1103
1104 for (MachineBasicBlock *LoopBB : L.getBlocks()) {
1105 auto Freq = MBFI->getBlockFreq(LoopBB).getFrequency();
1106 if (Freq == 0 || LoopFreq.getFrequency() / Freq > LoopToColdBlockRatio)
1107 continue;
1108 LoopBlockSet.insert(LoopBB);
1109 }
1110 } else
1111 LoopBlockSet.insert(L.block_begin(), L.block_end());
1112
1113 return LoopBlockSet;
1114}
1115
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00001116/// \brief Forms basic block chains from the natural loop structures.
Chandler Carruth10281422011-10-21 06:46:38 +00001117///
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00001118/// These chains are designed to preserve the existing *structure* of the code
1119/// as much as possible. We can then stitch the chains together in a way which
1120/// both preserves the topological structure and minimizes taken conditional
1121/// branches.
Chandler Carruth8d150782011-11-13 11:20:44 +00001122void MachineBlockPlacement::buildLoopChains(MachineFunction &F,
Jakub Staszak90616162011-12-21 23:02:08 +00001123 MachineLoop &L) {
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00001124 // First recurse through any nested loops, building chains for those inner
1125 // loops.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001126 for (MachineLoop *InnerLoop : L)
1127 buildLoopChains(F, *InnerLoop);
Chandler Carruth10281422011-10-21 06:46:38 +00001128
Chandler Carruth8d150782011-11-13 11:20:44 +00001129 SmallVector<MachineBasicBlock *, 16> BlockWorkList;
Amaury Sechetc53ad4f2016-04-07 21:29:39 +00001130 SmallVector<MachineBasicBlock *, 16> EHPadWorkList;
Cong Houb90b9e02015-11-02 21:24:00 +00001131 BlockFilterSet LoopBlockSet = collectLoopBlockSet(F, L);
Chandler Carruth03adbd42011-11-27 13:34:33 +00001132
Cong Hou7745dbc2015-10-19 23:16:40 +00001133 // Check if we have profile data for this function. If yes, we will rotate
1134 // this loop by modeling costs more precisely which requires the profile data
1135 // for better layout.
1136 bool RotateLoopWithProfile =
Xinliang David Lif0ab6df2016-05-12 02:04:41 +00001137 ForcePreciseRotationCost ||
1138 (PreciseRotationCost && F.getFunction()->getEntryCount());
Cong Hou7745dbc2015-10-19 23:16:40 +00001139
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001140 // First check to see if there is an obviously preferable top block for the
1141 // loop. This will default to the header, but may end up as one of the
1142 // predecessors to the header if there is one which will result in strictly
1143 // fewer branches in the loop body.
Cong Hou7745dbc2015-10-19 23:16:40 +00001144 // When we use profile data to rotate the loop, this is unnecessary.
1145 MachineBasicBlock *LoopTop =
1146 RotateLoopWithProfile ? L.getHeader() : findBestLoopTop(L, LoopBlockSet);
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001147
1148 // If we selected just the header for the loop top, look for a potentially
1149 // profitable exit block in the event that rotating the loop can eliminate
1150 // branches by placing an exit edge at the bottom.
Craig Topperc0196b12014-04-14 00:51:57 +00001151 MachineBasicBlock *ExitingBB = nullptr;
Cong Hou7745dbc2015-10-19 23:16:40 +00001152 if (!RotateLoopWithProfile && LoopTop == L.getHeader())
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001153 ExitingBB = findBestLoopExit(F, L, LoopBlockSet);
1154
1155 BlockChain &LoopChain = *BlockToChain[LoopTop];
Chandler Carruth10281422011-10-21 06:46:38 +00001156
Chandler Carruth8d150782011-11-13 11:20:44 +00001157 // FIXME: This is a really lame way of walking the chains in the loop: we
1158 // walk the blocks, and use a set to prevent visiting a particular chain
1159 // twice.
Jakub Staszak90616162011-12-21 23:02:08 +00001160 SmallPtrSet<BlockChain *, 4> UpdatedPreds;
Philip Reamesae27b232016-03-03 00:58:43 +00001161 assert(LoopChain.UnscheduledPredecessors == 0);
Jakub Staszak190c7122011-12-07 19:46:10 +00001162 UpdatedPreds.insert(&LoopChain);
Cong Houb90b9e02015-11-02 21:24:00 +00001163
Amaury Secheteae09c22016-03-14 21:24:11 +00001164 for (MachineBasicBlock *LoopBB : LoopBlockSet)
Amaury Sechetc53ad4f2016-04-07 21:29:39 +00001165 fillWorkLists(LoopBB, UpdatedPreds, BlockWorkList, EHPadWorkList,
1166 &LoopBlockSet);
Chandler Carruth8d150782011-11-13 11:20:44 +00001167
Amaury Sechetc53ad4f2016-04-07 21:29:39 +00001168 buildChain(LoopTop, LoopChain, BlockWorkList, EHPadWorkList, &LoopBlockSet);
Cong Hou7745dbc2015-10-19 23:16:40 +00001169
1170 if (RotateLoopWithProfile)
1171 rotateLoopWithProfile(LoopChain, L, LoopBlockSet);
1172 else
1173 rotateLoop(LoopChain, ExitingBB, LoopBlockSet);
Chandler Carruth8d150782011-11-13 11:20:44 +00001174
1175 DEBUG({
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001176 // Crash at the end so we get all of the debugging output first.
1177 bool BadLoop = false;
Philip Reamesae27b232016-03-03 00:58:43 +00001178 if (LoopChain.UnscheduledPredecessors) {
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001179 BadLoop = true;
Chandler Carruth8d150782011-11-13 11:20:44 +00001180 dbgs() << "Loop chain contains a block without its preds placed!\n"
1181 << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
1182 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n";
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001183 }
Chandler Carruth7a715da2015-03-05 03:19:05 +00001184 for (MachineBasicBlock *ChainBB : LoopChain) {
1185 dbgs() << " ... " << getBlockName(ChainBB) << "\n";
1186 if (!LoopBlockSet.erase(ChainBB)) {
Chandler Carruth0a31d142011-11-14 10:55:53 +00001187 // We don't mark the loop as bad here because there are real situations
1188 // where this can occur. For example, with an unanalyzable fallthrough
Chandler Carruth99fe42f2011-11-23 10:35:36 +00001189 // from a loop block to a non-loop block or vice versa.
Chandler Carruth8d150782011-11-13 11:20:44 +00001190 dbgs() << "Loop chain contains a block not contained by the loop!\n"
1191 << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
1192 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
Chandler Carruth7a715da2015-03-05 03:19:05 +00001193 << " Bad block: " << getBlockName(ChainBB) << "\n";
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001194 }
Chandler Carruthccc7e422012-04-16 01:12:56 +00001195 }
Chandler Carruth8d150782011-11-13 11:20:44 +00001196
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001197 if (!LoopBlockSet.empty()) {
1198 BadLoop = true;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001199 for (MachineBasicBlock *LoopBB : LoopBlockSet)
Chandler Carruth8d150782011-11-13 11:20:44 +00001200 dbgs() << "Loop contains blocks never placed into a chain!\n"
1201 << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
1202 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
Chandler Carruth7a715da2015-03-05 03:19:05 +00001203 << " Bad block: " << getBlockName(LoopBB) << "\n";
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001204 }
1205 assert(!BadLoop && "Detected problems with the placement of this loop.");
Chandler Carruth8d150782011-11-13 11:20:44 +00001206 });
Chandler Carruth10281422011-10-21 06:46:38 +00001207}
1208
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00001209void MachineBlockPlacement::buildCFGChains(MachineFunction &F) {
Chandler Carruth8d150782011-11-13 11:20:44 +00001210 // Ensure that every BB in the function has an associated chain to simplify
1211 // the assumptions of the remaining algorithm.
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +00001212 SmallVector<MachineOperand, 4> Cond; // For AnalyzeBranch.
1213 for (MachineFunction::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +00001214 MachineBasicBlock *BB = &*FI;
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001215 BlockChain *Chain =
1216 new (ChainAllocator.Allocate()) BlockChain(BlockToChain, BB);
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +00001217 // Also, merge any blocks which we cannot reason about and must preserve
1218 // the exact fallthrough behavior for.
1219 for (;;) {
1220 Cond.clear();
Craig Topperc0196b12014-04-14 00:51:57 +00001221 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +00001222 if (!TII->AnalyzeBranch(*BB, TBB, FBB, Cond) || !FI->canFallThrough())
1223 break;
1224
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +00001225 MachineFunction::iterator NextFI = std::next(FI);
1226 MachineBasicBlock *NextBB = &*NextFI;
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +00001227 // Ensure that the layout successor is a viable block, as we know that
1228 // fallthrough is a possibility.
1229 assert(NextFI != FE && "Can't fallthrough past the last block.");
1230 DEBUG(dbgs() << "Pre-merging due to unanalyzable fallthrough: "
1231 << getBlockName(BB) << " -> " << getBlockName(NextBB)
1232 << "\n");
Craig Topperc0196b12014-04-14 00:51:57 +00001233 Chain->merge(NextBB, nullptr);
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +00001234 FI = NextFI;
1235 BB = NextBB;
1236 }
1237 }
Chandler Carruth8d150782011-11-13 11:20:44 +00001238
Daniel Jasper471e8562015-03-04 11:05:34 +00001239 if (OutlineOptionalBranches) {
1240 // Find the nearest common dominator of all of F's terminators.
1241 MachineBasicBlock *Terminator = nullptr;
1242 for (MachineBasicBlock &MBB : F) {
1243 if (MBB.succ_size() == 0) {
1244 if (Terminator == nullptr)
1245 Terminator = &MBB;
1246 else
1247 Terminator = MDT->findNearestCommonDominator(Terminator, &MBB);
1248 }
1249 }
1250
1251 // MBBs dominating this common dominator are unavoidable.
1252 UnavoidableBlocks.clear();
1253 for (MachineBasicBlock &MBB : F) {
1254 if (MDT->dominates(&MBB, Terminator)) {
1255 UnavoidableBlocks.insert(&MBB);
1256 }
1257 }
1258 }
1259
Chandler Carruth8d150782011-11-13 11:20:44 +00001260 // Build any loop-based chains.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001261 for (MachineLoop *L : *MLI)
1262 buildLoopChains(F, *L);
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00001263
Chandler Carruth8d150782011-11-13 11:20:44 +00001264 SmallVector<MachineBasicBlock *, 16> BlockWorkList;
Amaury Sechetc53ad4f2016-04-07 21:29:39 +00001265 SmallVector<MachineBasicBlock *, 16> EHPadWorkList;
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00001266
Chandler Carruth8d150782011-11-13 11:20:44 +00001267 SmallPtrSet<BlockChain *, 4> UpdatedPreds;
Amaury Secheteae09c22016-03-14 21:24:11 +00001268 for (MachineBasicBlock &MBB : F)
Amaury Sechetc53ad4f2016-04-07 21:29:39 +00001269 fillWorkLists(&MBB, UpdatedPreds, BlockWorkList, EHPadWorkList);
Chandler Carruth8d150782011-11-13 11:20:44 +00001270
1271 BlockChain &FunctionChain = *BlockToChain[&F.front()];
Amaury Sechetc53ad4f2016-04-07 21:29:39 +00001272 buildChain(&F.front(), FunctionChain, BlockWorkList, EHPadWorkList);
Chandler Carruth8d150782011-11-13 11:20:44 +00001273
Matt Arsenault0f5f0152013-12-10 18:55:37 +00001274#ifndef NDEBUG
Matt Arsenault79d55f52013-12-05 20:02:18 +00001275 typedef SmallPtrSet<MachineBasicBlock *, 16> FunctionBlockSetType;
Matt Arsenault0f5f0152013-12-10 18:55:37 +00001276#endif
Chandler Carruth8d150782011-11-13 11:20:44 +00001277 DEBUG({
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001278 // Crash at the end so we get all of the debugging output first.
1279 bool BadFunc = false;
Chandler Carruth8d150782011-11-13 11:20:44 +00001280 FunctionBlockSetType FunctionBlockSet;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001281 for (MachineBasicBlock &MBB : F)
1282 FunctionBlockSet.insert(&MBB);
Chandler Carruth8d150782011-11-13 11:20:44 +00001283
Chandler Carruth7a715da2015-03-05 03:19:05 +00001284 for (MachineBasicBlock *ChainBB : FunctionChain)
1285 if (!FunctionBlockSet.erase(ChainBB)) {
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001286 BadFunc = true;
Chandler Carruth8d150782011-11-13 11:20:44 +00001287 dbgs() << "Function chain contains a block not in the function!\n"
Chandler Carruth7a715da2015-03-05 03:19:05 +00001288 << " Bad block: " << getBlockName(ChainBB) << "\n";
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001289 }
Chandler Carruth8d150782011-11-13 11:20:44 +00001290
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001291 if (!FunctionBlockSet.empty()) {
1292 BadFunc = true;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001293 for (MachineBasicBlock *RemainingBB : FunctionBlockSet)
Chandler Carruth8d150782011-11-13 11:20:44 +00001294 dbgs() << "Function contains blocks never placed into a chain!\n"
Chandler Carruth7a715da2015-03-05 03:19:05 +00001295 << " Bad block: " << getBlockName(RemainingBB) << "\n";
Chandler Carruth8e1d9062011-11-13 21:39:51 +00001296 }
1297 assert(!BadFunc && "Detected problems with the block placement.");
Chandler Carruth8d150782011-11-13 11:20:44 +00001298 });
1299
1300 // Splice the blocks into place.
1301 MachineFunction::iterator InsertPos = F.begin();
Chandler Carruth7a715da2015-03-05 03:19:05 +00001302 for (MachineBasicBlock *ChainBB : FunctionChain) {
1303 DEBUG(dbgs() << (ChainBB == *FunctionChain.begin() ? "Placing chain "
1304 : " ... ")
1305 << getBlockName(ChainBB) << "\n");
1306 if (InsertPos != MachineFunction::iterator(ChainBB))
1307 F.splice(InsertPos, ChainBB);
Chandler Carruth8d150782011-11-13 11:20:44 +00001308 else
1309 ++InsertPos;
1310
1311 // Update the terminator of the previous block.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001312 if (ChainBB == *FunctionChain.begin())
Chandler Carruth8d150782011-11-13 11:20:44 +00001313 continue;
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +00001314 MachineBasicBlock *PrevBB = &*std::prev(MachineFunction::iterator(ChainBB));
Chandler Carruth8d150782011-11-13 11:20:44 +00001315
Chandler Carruth10281422011-10-21 06:46:38 +00001316 // FIXME: It would be awesome of updateTerminator would just return rather
1317 // than assert when the branch cannot be analyzed in order to remove this
1318 // boiler plate.
1319 Cond.clear();
Craig Topperc0196b12014-04-14 00:51:57 +00001320 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
Shuxin Yang8b8fd212013-06-04 01:00:57 +00001321
Haicheng Wu90a55652016-05-24 22:16:14 +00001322 // The "PrevBB" is not yet updated to reflect current code layout, so,
1323 // o. it may fall-through to a block without explict "goto" instruction
1324 // before layout, and no longer fall-through it after layout; or
1325 // o. just opposite.
1326 //
1327 // AnalyzeBranch() may return erroneous value for FBB when these two
1328 // situations take place. For the first scenario FBB is mistakenly set NULL;
1329 // for the 2nd scenario, the FBB, which is expected to be NULL, is
1330 // mistakenly pointing to "*BI".
1331 // Thus, if the future change needs to use FBB before the layout is set, it
1332 // has to correct FBB first by using the code similar to the following:
1333 //
1334 // if (!Cond.empty() && (!FBB || FBB == ChainBB)) {
1335 // PrevBB->updateTerminator();
1336 // Cond.clear();
1337 // TBB = FBB = nullptr;
1338 // if (TII->AnalyzeBranch(*PrevBB, TBB, FBB, Cond)) {
1339 // // FIXME: This should never take place.
1340 // TBB = FBB = nullptr;
1341 // }
1342 // }
1343 if (!TII->AnalyzeBranch(*PrevBB, TBB, FBB, Cond))
1344 PrevBB->updateTerminator();
Chandler Carruth10281422011-10-21 06:46:38 +00001345 }
Chandler Carruth8d150782011-11-13 11:20:44 +00001346
1347 // Fixup the last block.
1348 Cond.clear();
Craig Topperc0196b12014-04-14 00:51:57 +00001349 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
Chandler Carruth8d150782011-11-13 11:20:44 +00001350 if (!TII->AnalyzeBranch(F.back(), TBB, FBB, Cond))
1351 F.back().updateTerminator();
Haicheng Wu90a55652016-05-24 22:16:14 +00001352}
1353
1354void MachineBlockPlacement::optimizeBranches(MachineFunction &F) {
1355 BlockChain &FunctionChain = *BlockToChain[&F.front()];
1356 SmallVector<MachineOperand, 4> Cond; // For AnalyzeBranch.
Quentin Colombet776e6de2016-05-02 22:58:59 +00001357
1358 // Now that all the basic blocks in the chain have the proper layout,
1359 // make a final call to AnalyzeBranch with AllowModify set.
1360 // Indeed, the target may be able to optimize the branches in a way we
1361 // cannot because all branches may not be analyzable.
1362 // E.g., the target may be able to remove an unconditional branch to
1363 // a fallthrough when it occurs after predicated terminators.
1364 for (MachineBasicBlock *ChainBB : FunctionChain) {
1365 Cond.clear();
Haicheng Wu90a55652016-05-24 22:16:14 +00001366 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
1367 if (!TII->AnalyzeBranch(*ChainBB, TBB, FBB, Cond, /*AllowModify*/ true)) {
1368 // If PrevBB has a two-way branch, try to re-order the branches
1369 // such that we branch to the successor with higher probability first.
1370 if (TBB && !Cond.empty() && FBB &&
1371 MBPI->getEdgeProbability(ChainBB, FBB) >
1372 MBPI->getEdgeProbability(ChainBB, TBB) &&
1373 !TII->ReverseBranchCondition(Cond)) {
1374 DEBUG(dbgs() << "Reverse order of the two branches: "
1375 << getBlockName(ChainBB) << "\n");
1376 DEBUG(dbgs() << " Edge probability: "
1377 << MBPI->getEdgeProbability(ChainBB, FBB) << " vs "
1378 << MBPI->getEdgeProbability(ChainBB, TBB) << "\n");
1379 DebugLoc dl; // FIXME: this is nowhere
1380 TII->RemoveBranch(*ChainBB);
1381 TII->InsertBranch(*ChainBB, FBB, TBB, Cond, dl);
1382 ChainBB->updateTerminator();
1383 }
1384 }
Quentin Colombet776e6de2016-05-02 22:58:59 +00001385 }
Haicheng Wue749ce52016-04-29 17:06:44 +00001386}
Chandler Carruth10281422011-10-21 06:46:38 +00001387
Haicheng Wue749ce52016-04-29 17:06:44 +00001388void MachineBlockPlacement::alignBlocks(MachineFunction &F) {
Chandler Carruthccc7e422012-04-16 01:12:56 +00001389 // Walk through the backedges of the function now that we have fully laid out
1390 // the basic blocks and align the destination of each backedge. We don't rely
Chandler Carruth881d0a72012-08-07 09:45:24 +00001391 // exclusively on the loop info here so that we can align backedges in
1392 // unnatural CFGs and backedges that were introduced purely because of the
1393 // loop rotations done during this layout pass.
Haicheng Wu4afe0422016-04-29 22:01:10 +00001394 if (F.getFunction()->optForSize())
Chandler Carruth8b9737c2011-10-21 08:57:37 +00001395 return;
Haicheng Wue749ce52016-04-29 17:06:44 +00001396 BlockChain &FunctionChain = *BlockToChain[&F.front()];
Chandler Carruth881d0a72012-08-07 09:45:24 +00001397 if (FunctionChain.begin() == FunctionChain.end())
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001398 return; // Empty chain.
Chandler Carruth8b9737c2011-10-21 08:57:37 +00001399
Chandler Carruth881d0a72012-08-07 09:45:24 +00001400 const BranchProbability ColdProb(1, 5); // 20%
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +00001401 BlockFrequency EntryFreq = MBFI->getBlockFreq(&F.front());
Chandler Carruth881d0a72012-08-07 09:45:24 +00001402 BlockFrequency WeightedEntryFreq = EntryFreq * ColdProb;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001403 for (MachineBasicBlock *ChainBB : FunctionChain) {
1404 if (ChainBB == *FunctionChain.begin())
1405 continue;
1406
Chandler Carruth881d0a72012-08-07 09:45:24 +00001407 // Don't align non-looping basic blocks. These are unlikely to execute
1408 // enough times to matter in practice. Note that we'll still handle
1409 // unnatural CFGs inside of a natural outer loop (the common case) and
1410 // rotated loops.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001411 MachineLoop *L = MLI->getLoopFor(ChainBB);
Chandler Carruth881d0a72012-08-07 09:45:24 +00001412 if (!L)
1413 continue;
1414
Hal Finkel57725662015-01-03 17:58:24 +00001415 unsigned Align = TLI->getPrefLoopAlignment(L);
1416 if (!Align)
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001417 continue; // Don't care about loop alignment.
Hal Finkel57725662015-01-03 17:58:24 +00001418
Chandler Carruth881d0a72012-08-07 09:45:24 +00001419 // If the block is cold relative to the function entry don't waste space
1420 // aligning it.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001421 BlockFrequency Freq = MBFI->getBlockFreq(ChainBB);
Chandler Carruth881d0a72012-08-07 09:45:24 +00001422 if (Freq < WeightedEntryFreq)
1423 continue;
1424
1425 // If the block is cold relative to its loop header, don't align it
1426 // regardless of what edges into the block exist.
1427 MachineBasicBlock *LoopHeader = L->getHeader();
1428 BlockFrequency LoopHeaderFreq = MBFI->getBlockFreq(LoopHeader);
1429 if (Freq < (LoopHeaderFreq * ColdProb))
1430 continue;
1431
1432 // Check for the existence of a non-layout predecessor which would benefit
1433 // from aligning this block.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001434 MachineBasicBlock *LayoutPred =
1435 &*std::prev(MachineFunction::iterator(ChainBB));
Chandler Carruth881d0a72012-08-07 09:45:24 +00001436
1437 // Force alignment if all the predecessors are jumps. We already checked
1438 // that the block isn't cold above.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001439 if (!LayoutPred->isSuccessor(ChainBB)) {
1440 ChainBB->setAlignment(Align);
Chandler Carruth881d0a72012-08-07 09:45:24 +00001441 continue;
1442 }
1443
1444 // Align this block if the layout predecessor's edge into this block is
Nadav Rotem6036f582013-03-29 16:34:23 +00001445 // cold relative to the block. When this is true, other predecessors make up
Chandler Carruth881d0a72012-08-07 09:45:24 +00001446 // all of the hot entries into the block and thus alignment is likely to be
1447 // important.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001448 BranchProbability LayoutProb =
1449 MBPI->getEdgeProbability(LayoutPred, ChainBB);
Chandler Carruth881d0a72012-08-07 09:45:24 +00001450 BlockFrequency LayoutEdgeFreq = MBFI->getBlockFreq(LayoutPred) * LayoutProb;
1451 if (LayoutEdgeFreq <= (Freq * ColdProb))
Chandler Carruth7a715da2015-03-05 03:19:05 +00001452 ChainBB->setAlignment(Align);
Chandler Carruthccc7e422012-04-16 01:12:56 +00001453 }
Chandler Carruth8b9737c2011-10-21 08:57:37 +00001454}
1455
Chandler Carruth10281422011-10-21 06:46:38 +00001456bool MachineBlockPlacement::runOnMachineFunction(MachineFunction &F) {
Andrew Kaylor50271f72016-05-03 22:32:30 +00001457 if (skipFunction(*F.getFunction()))
1458 return false;
1459
Chandler Carruth10281422011-10-21 06:46:38 +00001460 // Check for single-block functions and skip them.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001461 if (std::next(F.begin()) == F.end())
Chandler Carruth10281422011-10-21 06:46:38 +00001462 return false;
1463
1464 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
1465 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
Chandler Carruth8b9737c2011-10-21 08:57:37 +00001466 MLI = &getAnalysis<MachineLoopInfo>();
Eric Christopherfc6de422014-08-05 02:39:49 +00001467 TII = F.getSubtarget().getInstrInfo();
1468 TLI = F.getSubtarget().getTargetLowering();
Daniel Jasper471e8562015-03-04 11:05:34 +00001469 MDT = &getAnalysis<MachineDominatorTree>();
Chandler Carruth10281422011-10-21 06:46:38 +00001470 assert(BlockToChain.empty());
Chandler Carruth10281422011-10-21 06:46:38 +00001471
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00001472 buildCFGChains(F);
Haicheng Wu90a55652016-05-24 22:16:14 +00001473 optimizeBranches(F);
Haicheng Wue749ce52016-04-29 17:06:44 +00001474 alignBlocks(F);
Chandler Carruth10281422011-10-21 06:46:38 +00001475
Chandler Carruth10281422011-10-21 06:46:38 +00001476 BlockToChain.clear();
Chandler Carruthfd9b4d92011-11-14 10:57:23 +00001477 ChainAllocator.DestroyAll();
Chandler Carruth10281422011-10-21 06:46:38 +00001478
Nadav Rotemc0adc9f2013-04-12 01:24:16 +00001479 if (AlignAllBlock)
1480 // Align all of the blocks in the function to a specific alignment.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001481 for (MachineBasicBlock &MBB : F)
1482 MBB.setAlignment(AlignAllBlock);
Geoff Berry10494ac2016-01-21 17:25:52 +00001483 else if (AlignAllNonFallThruBlocks) {
1484 // Align all of the blocks that have no fall-through predecessors to a
1485 // specific alignment.
1486 for (auto MBI = std::next(F.begin()), MBE = F.end(); MBI != MBE; ++MBI) {
1487 auto LayoutPred = std::prev(MBI);
1488 if (!LayoutPred->isSuccessor(&*MBI))
1489 MBI->setAlignment(AlignAllNonFallThruBlocks);
1490 }
1491 }
Nadav Rotemc0adc9f2013-04-12 01:24:16 +00001492
Chandler Carruth10281422011-10-21 06:46:38 +00001493 // We always return true as we have no way to track whether the final order
1494 // differs from the original order.
1495 return true;
1496}
Chandler Carruthae4e8002011-11-02 07:17:12 +00001497
1498namespace {
1499/// \brief A pass to compute block placement statistics.
1500///
1501/// A separate pass to compute interesting statistics for evaluating block
1502/// placement. This is separate from the actual placement pass so that they can
Benjamin Kramerbde91762012-06-02 10:20:22 +00001503/// be computed in the absence of any placement transformations or when using
Chandler Carruthae4e8002011-11-02 07:17:12 +00001504/// alternative placement strategies.
1505class MachineBlockPlacementStats : public MachineFunctionPass {
1506 /// \brief A handle to the branch probability pass.
1507 const MachineBranchProbabilityInfo *MBPI;
1508
1509 /// \brief A handle to the function-wide block frequency pass.
1510 const MachineBlockFrequencyInfo *MBFI;
1511
1512public:
1513 static char ID; // Pass identification, replacement for typeid
1514 MachineBlockPlacementStats() : MachineFunctionPass(ID) {
1515 initializeMachineBlockPlacementStatsPass(*PassRegistry::getPassRegistry());
1516 }
1517
Craig Topper4584cd52014-03-07 09:26:03 +00001518 bool runOnMachineFunction(MachineFunction &F) override;
Chandler Carruthae4e8002011-11-02 07:17:12 +00001519
Craig Topper4584cd52014-03-07 09:26:03 +00001520 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruthae4e8002011-11-02 07:17:12 +00001521 AU.addRequired<MachineBranchProbabilityInfo>();
1522 AU.addRequired<MachineBlockFrequencyInfo>();
1523 AU.setPreservesAll();
1524 MachineFunctionPass::getAnalysisUsage(AU);
1525 }
Chandler Carruthae4e8002011-11-02 07:17:12 +00001526};
Alexander Kornienkof00654e2015-06-23 09:49:53 +00001527}
Chandler Carruthae4e8002011-11-02 07:17:12 +00001528
1529char MachineBlockPlacementStats::ID = 0;
Andrew Trick1fa5bcb2012-02-08 21:23:13 +00001530char &llvm::MachineBlockPlacementStatsID = MachineBlockPlacementStats::ID;
Chandler Carruthae4e8002011-11-02 07:17:12 +00001531INITIALIZE_PASS_BEGIN(MachineBlockPlacementStats, "block-placement-stats",
1532 "Basic Block Placement Stats", false, false)
1533INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
1534INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
1535INITIALIZE_PASS_END(MachineBlockPlacementStats, "block-placement-stats",
1536 "Basic Block Placement Stats", false, false)
1537
Chandler Carruthae4e8002011-11-02 07:17:12 +00001538bool MachineBlockPlacementStats::runOnMachineFunction(MachineFunction &F) {
1539 // Check for single-block functions and skip them.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001540 if (std::next(F.begin()) == F.end())
Chandler Carruthae4e8002011-11-02 07:17:12 +00001541 return false;
1542
1543 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
1544 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
1545
Chandler Carruth7a715da2015-03-05 03:19:05 +00001546 for (MachineBasicBlock &MBB : F) {
1547 BlockFrequency BlockFreq = MBFI->getBlockFreq(&MBB);
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001548 Statistic &NumBranches =
Chandler Carruth7a715da2015-03-05 03:19:05 +00001549 (MBB.succ_size() > 1) ? NumCondBranches : NumUncondBranches;
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001550 Statistic &BranchTakenFreq =
Chandler Carruth7a715da2015-03-05 03:19:05 +00001551 (MBB.succ_size() > 1) ? CondBranchTakenFreq : UncondBranchTakenFreq;
1552 for (MachineBasicBlock *Succ : MBB.successors()) {
Chandler Carruthae4e8002011-11-02 07:17:12 +00001553 // Skip if this successor is a fallthrough.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001554 if (MBB.isLayoutSuccessor(Succ))
Chandler Carruthae4e8002011-11-02 07:17:12 +00001555 continue;
1556
Chandler Carruth7a715da2015-03-05 03:19:05 +00001557 BlockFrequency EdgeFreq =
1558 BlockFreq * MBPI->getEdgeProbability(&MBB, Succ);
Chandler Carruthae4e8002011-11-02 07:17:12 +00001559 ++NumBranches;
1560 BranchTakenFreq += EdgeFreq.getFrequency();
1561 }
1562 }
1563
1564 return false;
1565}