blob: c6766f48a39641c2f7560c436f3f15179b16ebdf [file] [log] [blame]
Eugene Zelenko5df3d892017-08-24 21:21:39 +00001//===- MachineBlockPlacement.cpp - Basic Block Code Layout optimization ---===//
Chandler Carruth10281422011-10-21 06:46:38 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Chandler Carruth10281422011-10-21 06:46:38 +00006//
7//===----------------------------------------------------------------------===//
8//
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00009// This file implements basic block placement transformations using the CFG
10// structure and branch probability estimates.
Chandler Carruth10281422011-10-21 06:46:38 +000011//
Chandler Carruthbd1be4d2011-10-23 09:18:45 +000012// The pass strives to preserve the structure of the CFG (that is, retain
Benjamin Kramerbde91762012-06-02 10:20:22 +000013// a topological ordering of basic blocks) in the absence of a *strong* signal
Chandler Carruthbd1be4d2011-10-23 09:18:45 +000014// to the contrary from probabilities. However, within the CFG structure, it
15// attempts to choose an ordering which favors placing more likely sequences of
16// blocks adjacent to each other.
17//
18// The algorithm works from the inner-most loop within a function outward, and
19// at each stage walks through the basic blocks, trying to coalesce them into
20// sequential chains where allowed by the CFG (or demanded by heavy
21// probabilities). Finally, it walks the blocks in topological order, and the
22// first time it reaches a chain of basic blocks, it schedules them in the
23// function in-order.
Chandler Carruth10281422011-10-21 06:46:38 +000024//
25//===----------------------------------------------------------------------===//
26
Haicheng Wu5b458cc2016-06-09 15:24:29 +000027#include "BranchFolding.h"
Eugene Zelenko5df3d892017-08-24 21:21:39 +000028#include "llvm/ADT/ArrayRef.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000029#include "llvm/ADT/DenseMap.h"
Eugene Zelenko5df3d892017-08-24 21:21:39 +000030#include "llvm/ADT/STLExtras.h"
31#include "llvm/ADT/SetVector.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000032#include "llvm/ADT/SmallPtrSet.h"
33#include "llvm/ADT/SmallVector.h"
34#include "llvm/ADT/Statistic.h"
Xinliang David Lifd3f6452017-01-29 01:57:02 +000035#include "llvm/Analysis/BlockFrequencyInfoImpl.h"
Chandler Carruth8b9737c2011-10-21 08:57:37 +000036#include "llvm/CodeGen/MachineBasicBlock.h"
Chandler Carruth10281422011-10-21 06:46:38 +000037#include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
38#include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
39#include "llvm/CodeGen/MachineFunction.h"
Chandler Carruth10281422011-10-21 06:46:38 +000040#include "llvm/CodeGen/MachineFunctionPass.h"
Chandler Carruth8b9737c2011-10-21 08:57:37 +000041#include "llvm/CodeGen/MachineLoopInfo.h"
42#include "llvm/CodeGen/MachineModuleInfo.h"
Kyle Buttb15c0662017-01-31 23:48:32 +000043#include "llvm/CodeGen/MachinePostDominators.h"
Kyle Butt0846e562016-10-11 20:36:43 +000044#include "llvm/CodeGen/TailDuplicator.h"
David Blaikie3f833ed2017-11-08 01:01:31 +000045#include "llvm/CodeGen/TargetInstrInfo.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000046#include "llvm/CodeGen/TargetLowering.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000047#include "llvm/CodeGen/TargetPassConfig.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000048#include "llvm/CodeGen/TargetSubtargetInfo.h"
Eugene Zelenko5df3d892017-08-24 21:21:39 +000049#include "llvm/IR/DebugLoc.h"
50#include "llvm/IR/Function.h"
51#include "llvm/Pass.h"
Chandler Carruth10281422011-10-21 06:46:38 +000052#include "llvm/Support/Allocator.h"
Eugene Zelenko5df3d892017-08-24 21:21:39 +000053#include "llvm/Support/BlockFrequency.h"
54#include "llvm/Support/BranchProbability.h"
55#include "llvm/Support/CodeGen.h"
Nadav Rotemc3b0f502013-04-12 00:48:32 +000056#include "llvm/Support/CommandLine.h"
Eugene Zelenko5df3d892017-08-24 21:21:39 +000057#include "llvm/Support/Compiler.h"
Chandler Carruthbd1be4d2011-10-23 09:18:45 +000058#include "llvm/Support/Debug.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000059#include "llvm/Support/raw_ostream.h"
Eugene Zelenko5df3d892017-08-24 21:21:39 +000060#include "llvm/Target/TargetMachine.h"
Chandler Carruth10281422011-10-21 06:46:38 +000061#include <algorithm>
Eugene Zelenko5df3d892017-08-24 21:21:39 +000062#include <cassert>
63#include <cstdint>
64#include <iterator>
65#include <memory>
66#include <string>
67#include <tuple>
Kyle Buttb15c0662017-01-31 23:48:32 +000068#include <utility>
Eugene Zelenko5df3d892017-08-24 21:21:39 +000069#include <vector>
70
Chandler Carruth10281422011-10-21 06:46:38 +000071using namespace llvm;
72
Chandler Carruthd0dced52015-03-05 02:28:25 +000073#define DEBUG_TYPE "block-placement"
Chandler Carruth1b9dde02014-04-22 02:02:50 +000074
Chandler Carruthae4e8002011-11-02 07:17:12 +000075STATISTIC(NumCondBranches, "Number of conditional branches");
Craig Topper77ec0772015-09-16 03:52:32 +000076STATISTIC(NumUncondBranches, "Number of unconditional branches");
Chandler Carruthae4e8002011-11-02 07:17:12 +000077STATISTIC(CondBranchTakenFreq,
78 "Potential frequency of taking conditional branches");
79STATISTIC(UncondBranchTakenFreq,
80 "Potential frequency of taking unconditional branches");
81
Nadav Rotemc3b0f502013-04-12 00:48:32 +000082static cl::opt<unsigned> AlignAllBlock("align-all-blocks",
83 cl::desc("Force the alignment of all "
84 "blocks in the function."),
85 cl::init(0), cl::Hidden);
86
Geoff Berry10494ac2016-01-21 17:25:52 +000087static cl::opt<unsigned> AlignAllNonFallThruBlocks(
88 "align-all-nofallthru-blocks",
89 cl::desc("Force the alignment of all "
90 "blocks that have no fall-through predecessors (i.e. don't add "
91 "nops that are executed)."),
92 cl::init(0), cl::Hidden);
93
Benjamin Kramerc8160d62013-11-20 19:08:44 +000094// FIXME: Find a good default for this flag and remove the flag.
Chandler Carruth2fc3fe12015-03-05 02:35:31 +000095static cl::opt<unsigned> ExitBlockBias(
96 "block-placement-exit-block-bias",
97 cl::desc("Block frequency percentage a loop exit block needs "
98 "over the original exit to be considered the new exit."),
99 cl::init(0), cl::Hidden);
Benjamin Kramerc8160d62013-11-20 19:08:44 +0000100
Sjoerd Meijer5e11a182016-07-27 08:49:23 +0000101// Definition:
102// - Outlining: placement of a basic block outside the chain or hot path.
103
Cong Houb90b9e02015-11-02 21:24:00 +0000104static cl::opt<unsigned> LoopToColdBlockRatio(
105 "loop-to-cold-block-ratio",
106 cl::desc("Outline loop blocks from loop chain if (frequency of loop) / "
107 "(frequency of block) is greater than this ratio"),
108 cl::init(5), cl::Hidden);
109
Kyle Butt74f61dd2017-08-04 21:13:41 +0000110static cl::opt<bool> ForceLoopColdBlock(
111 "force-loop-cold-block",
112 cl::desc("Force outlining cold blocks from loops."),
113 cl::init(false), cl::Hidden);
114
Cong Hou7745dbc2015-10-19 23:16:40 +0000115static cl::opt<bool>
116 PreciseRotationCost("precise-rotation-cost",
117 cl::desc("Model the cost of loop rotation more "
118 "precisely by using profile data."),
119 cl::init(false), cl::Hidden);
Eugene Zelenko5df3d892017-08-24 21:21:39 +0000120
Xinliang David Lif0ab6df2016-05-12 02:04:41 +0000121static cl::opt<bool>
122 ForcePreciseRotationCost("force-precise-rotation-cost",
Xinliang David Lib840bb82016-05-12 16:39:02 +0000123 cl::desc("Force the use of precise cost "
124 "loop rotation strategy."),
Xinliang David Lif0ab6df2016-05-12 02:04:41 +0000125 cl::init(false), cl::Hidden);
Cong Hou7745dbc2015-10-19 23:16:40 +0000126
127static cl::opt<unsigned> MisfetchCost(
128 "misfetch-cost",
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +0000129 cl::desc("Cost that models the probabilistic risk of an instruction "
Cong Hou7745dbc2015-10-19 23:16:40 +0000130 "misfetch due to a jump comparing to falling through, whose cost "
131 "is zero."),
132 cl::init(1), cl::Hidden);
133
134static cl::opt<unsigned> JumpInstCost("jump-inst-cost",
135 cl::desc("Cost of jump instructions."),
136 cl::init(1), cl::Hidden);
Kyle Butt0846e562016-10-11 20:36:43 +0000137static cl::opt<bool>
138TailDupPlacement("tail-dup-placement",
139 cl::desc("Perform tail duplication during placement. "
140 "Creates more fallthrough opportunites in "
141 "outline branches."),
142 cl::init(true), cl::Hidden);
Cong Hou7745dbc2015-10-19 23:16:40 +0000143
Haicheng Wu5b458cc2016-06-09 15:24:29 +0000144static cl::opt<bool>
145BranchFoldPlacement("branch-fold-placement",
146 cl::desc("Perform branch folding during placement. "
147 "Reduces code size."),
148 cl::init(true), cl::Hidden);
149
Kyle Butt0846e562016-10-11 20:36:43 +0000150// Heuristic for tail duplication.
Kyle Buttb15c0662017-01-31 23:48:32 +0000151static cl::opt<unsigned> TailDupPlacementThreshold(
Kyle Butt0846e562016-10-11 20:36:43 +0000152 "tail-dup-placement-threshold",
153 cl::desc("Instruction cutoff for tail duplication during layout. "
154 "Tail merging during layout is forced to have a threshold "
155 "that won't conflict."), cl::init(2),
156 cl::Hidden);
157
Kyle Butt7d531da2017-05-15 17:30:47 +0000158// Heuristic for aggressive tail duplication.
159static cl::opt<unsigned> TailDupPlacementAggressiveThreshold(
160 "tail-dup-placement-aggressive-threshold",
161 cl::desc("Instruction cutoff for aggressive tail duplication during "
162 "layout. Used at -O3. Tail merging during layout is forced to "
Richard Smithc0541df2017-08-17 23:38:41 +0000163 "have a threshold that won't conflict."), cl::init(4),
Kyle Butt7d531da2017-05-15 17:30:47 +0000164 cl::Hidden);
165
Kyle Buttb15c0662017-01-31 23:48:32 +0000166// Heuristic for tail duplication.
167static cl::opt<unsigned> TailDupPlacementPenalty(
168 "tail-dup-placement-penalty",
169 cl::desc("Cost penalty for blocks that can avoid breaking CFG by copying. "
170 "Copying can increase fallthrough, but it also increases icache "
171 "pressure. This parameter controls the penalty to account for that. "
172 "Percent as integer."),
173 cl::init(2),
174 cl::Hidden);
175
Kyle Butt1fa60302017-03-03 01:00:22 +0000176// Heuristic for triangle chains.
177static cl::opt<unsigned> TriangleChainCount(
178 "triangle-chain-count",
179 cl::desc("Number of triangle-shaped-CFG's that need to be in a row for the "
180 "triangle tail duplication heuristic to kick in. 0 to disable."),
Kyle Butt08655992017-03-16 01:32:29 +0000181 cl::init(2),
Kyle Butt1fa60302017-03-03 01:00:22 +0000182 cl::Hidden);
183
Xinliang David Liff287372016-06-03 23:48:36 +0000184extern cl::opt<unsigned> StaticLikelyProb;
Dehao Chen9f2bdfb2016-06-14 22:27:17 +0000185extern cl::opt<unsigned> ProfileLikelyProb;
Xinliang David Liff287372016-06-03 23:48:36 +0000186
Xinliang David Li58fcc9b2017-02-02 21:29:17 +0000187// Internal option used to control BFI display only after MBP pass.
188// Defined in CodeGen/MachineBlockFrequencyInfo.cpp:
189// -view-block-layout-with-bfi=
Xinliang David Lifd3f6452017-01-29 01:57:02 +0000190extern cl::opt<GVDAGType> ViewBlockLayoutWithBFI;
Xinliang David Li58fcc9b2017-02-02 21:29:17 +0000191
192// Command line option to specify the name of the function for CFG dump
193// Defined in Analysis/BlockFrequencyInfo.cpp: -view-bfi-func-name=
Xinliang David Lifd3f6452017-01-29 01:57:02 +0000194extern cl::opt<std::string> ViewBlockFreqFuncName;
Xinliang David Lifd3f6452017-01-29 01:57:02 +0000195
Chandler Carruth10281422011-10-21 06:46:38 +0000196namespace {
Chandler Carruth10281422011-10-21 06:46:38 +0000197
Eugene Zelenko5df3d892017-08-24 21:21:39 +0000198class BlockChain;
199
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000200/// Type for our function-wide basic block -> block chain mapping.
Eugene Zelenko5df3d892017-08-24 21:21:39 +0000201using BlockToChainMapType = DenseMap<const MachineBasicBlock *, BlockChain *>;
202
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000203/// A chain of blocks which will be laid out contiguously.
Chandler Carruth10281422011-10-21 06:46:38 +0000204///
205/// This is the datastructure representing a chain of consecutive blocks that
206/// are profitable to layout together in order to maximize fallthrough
Chandler Carruth9139f442012-06-26 05:16:37 +0000207/// probabilities and code locality. We also can use a block chain to represent
208/// a sequence of basic blocks which have some external (correctness)
209/// requirement for sequential layout.
Chandler Carruth10281422011-10-21 06:46:38 +0000210///
Chandler Carruth9139f442012-06-26 05:16:37 +0000211/// Chains can be built around a single basic block and can be merged to grow
212/// them. They participate in a block-to-chain mapping, which is updated
213/// automatically as chains are merged together.
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000214class BlockChain {
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000215 /// The sequence of blocks belonging to this chain.
Chandler Carruth10281422011-10-21 06:46:38 +0000216 ///
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000217 /// This is the sequence of blocks for a particular chain. These will be laid
218 /// out in-order within the function.
219 SmallVector<MachineBasicBlock *, 4> Blocks;
Chandler Carruth10281422011-10-21 06:46:38 +0000220
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000221 /// A handle to the function-wide basic block to block chain mapping.
Chandler Carruth10281422011-10-21 06:46:38 +0000222 ///
223 /// This is retained in each block chain to simplify the computation of child
224 /// block chains for SCC-formation and iteration. We store the edges to child
225 /// basic blocks, and map them back to their associated chains using this
226 /// structure.
227 BlockToChainMapType &BlockToChain;
228
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000229public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000230 /// Construct a new BlockChain.
Chandler Carruth10281422011-10-21 06:46:38 +0000231 ///
232 /// This builds a new block chain representing a single basic block in the
233 /// function. It also registers itself as the chain that block participates
234 /// in with the BlockToChain mapping.
235 BlockChain(BlockToChainMapType &BlockToChain, MachineBasicBlock *BB)
Eugene Zelenko5df3d892017-08-24 21:21:39 +0000236 : Blocks(1, BB), BlockToChain(BlockToChain) {
Chandler Carruth10281422011-10-21 06:46:38 +0000237 assert(BB && "Cannot create a chain with a null basic block");
238 BlockToChain[BB] = this;
239 }
240
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000241 /// Iterator over blocks within the chain.
Eugene Zelenko5df3d892017-08-24 21:21:39 +0000242 using iterator = SmallVectorImpl<MachineBasicBlock *>::iterator;
243 using const_iterator = SmallVectorImpl<MachineBasicBlock *>::const_iterator;
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000244
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000245 /// Beginning of blocks within the chain.
Chandler Carruthccc7e422012-04-16 01:12:56 +0000246 iterator begin() { return Blocks.begin(); }
Kyle Butte9425c4f2017-02-04 02:26:32 +0000247 const_iterator begin() const { return Blocks.begin(); }
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000248
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000249 /// End of blocks within the chain.
Chandler Carruthccc7e422012-04-16 01:12:56 +0000250 iterator end() { return Blocks.end(); }
Kyle Butte9425c4f2017-02-04 02:26:32 +0000251 const_iterator end() const { return Blocks.end(); }
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000252
Kyle Butt0846e562016-10-11 20:36:43 +0000253 bool remove(MachineBasicBlock* BB) {
254 for(iterator i = begin(); i != end(); ++i) {
255 if (*i == BB) {
256 Blocks.erase(i);
257 return true;
258 }
259 }
260 return false;
261 }
262
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000263 /// Merge a block chain into this one.
Chandler Carruth10281422011-10-21 06:46:38 +0000264 ///
265 /// This routine merges a block chain into this one. It takes care of forming
266 /// a contiguous sequence of basic blocks, updating the edge list, and
267 /// updating the block -> chain mapping. It does not free or tear down the
268 /// old chain, but the old chain's block list is no longer valid.
Jakub Staszak90616162011-12-21 23:02:08 +0000269 void merge(MachineBasicBlock *BB, BlockChain *Chain) {
Kyle Butt0cf5b2f2017-05-17 23:44:41 +0000270 assert(BB && "Can't merge a null block.");
271 assert(!Blocks.empty() && "Can't merge into an empty chain.");
Chandler Carruth10281422011-10-21 06:46:38 +0000272
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000273 // Fast path in case we don't have a chain already.
274 if (!Chain) {
Kyle Butt0cf5b2f2017-05-17 23:44:41 +0000275 assert(!BlockToChain[BB] &&
276 "Passed chain is null, but BB has entry in BlockToChain.");
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000277 Blocks.push_back(BB);
278 BlockToChain[BB] = this;
279 return;
Chandler Carruth10281422011-10-21 06:46:38 +0000280 }
281
Kyle Butt0cf5b2f2017-05-17 23:44:41 +0000282 assert(BB == *Chain->begin() && "Passed BB is not head of Chain.");
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000283 assert(Chain->begin() != Chain->end());
Chandler Carruth10281422011-10-21 06:46:38 +0000284
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000285 // Update the incoming blocks to point to this chain, and add them to the
286 // chain structure.
Chandler Carruth7a715da2015-03-05 03:19:05 +0000287 for (MachineBasicBlock *ChainBB : *Chain) {
288 Blocks.push_back(ChainBB);
Kyle Butt0cf5b2f2017-05-17 23:44:41 +0000289 assert(BlockToChain[ChainBB] == Chain && "Incoming blocks not in chain.");
Chandler Carruth7a715da2015-03-05 03:19:05 +0000290 BlockToChain[ChainBB] = this;
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000291 }
Chandler Carruth10281422011-10-21 06:46:38 +0000292 }
Chandler Carruth8d150782011-11-13 11:20:44 +0000293
Chandler Carruth49158902012-04-08 14:37:01 +0000294#ifndef NDEBUG
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000295 /// Dump the blocks in this chain.
Nico Weber7408c702014-01-03 22:53:37 +0000296 LLVM_DUMP_METHOD void dump() {
Chandler Carruth7a715da2015-03-05 03:19:05 +0000297 for (MachineBasicBlock *MBB : *this)
298 MBB->dump();
Chandler Carruth49158902012-04-08 14:37:01 +0000299 }
300#endif // NDEBUG
301
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000302 /// Count of predecessors of any block within the chain which have not
Philip Reamesae27b232016-03-03 00:58:43 +0000303 /// yet been scheduled. In general, we will delay scheduling this chain
304 /// until those predecessors are scheduled (or we find a sufficiently good
305 /// reason to override this heuristic.) Note that when forming loop chains,
306 /// blocks outside the loop are ignored and treated as if they were already
307 /// scheduled.
Chandler Carruth8d150782011-11-13 11:20:44 +0000308 ///
Philip Reamesae27b232016-03-03 00:58:43 +0000309 /// Note: This field is reinitialized multiple times - once for each loop,
310 /// and then once for the function as a whole.
Eugene Zelenko5df3d892017-08-24 21:21:39 +0000311 unsigned UnscheduledPredecessors = 0;
Chandler Carruth10281422011-10-21 06:46:38 +0000312};
Chandler Carruth10281422011-10-21 06:46:38 +0000313
Chandler Carruth10281422011-10-21 06:46:38 +0000314class MachineBlockPlacement : public MachineFunctionPass {
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000315 /// A type for a block filter set.
Eugene Zelenko5df3d892017-08-24 21:21:39 +0000316 using BlockFilterSet = SmallSetVector<const MachineBasicBlock *, 16>;
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000317
Hiroshi Inouedad8c6a2019-01-09 05:11:10 +0000318 /// Pair struct containing basic block and taildup profitability
Kyle Buttb15c0662017-01-31 23:48:32 +0000319 struct BlockAndTailDupResult {
Kyle Butt7fbec9b2017-02-15 19:49:14 +0000320 MachineBasicBlock *BB;
Kyle Buttb15c0662017-01-31 23:48:32 +0000321 bool ShouldTailDup;
322 };
323
Kyle Butt7fbec9b2017-02-15 19:49:14 +0000324 /// Triple struct containing edge weight and the edge.
325 struct WeightedEdge {
326 BlockFrequency Weight;
327 MachineBasicBlock *Src;
328 MachineBasicBlock *Dest;
329 };
330
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000331 /// work lists of blocks that are ready to be laid out
Xinliang David Li93926ac2016-07-01 05:46:48 +0000332 SmallVector<MachineBasicBlock *, 16> BlockWorkList;
333 SmallVector<MachineBasicBlock *, 16> EHPadWorkList;
334
Kyle Buttebe6cc42017-02-23 21:22:24 +0000335 /// Edges that have already been computed as optimal.
336 DenseMap<const MachineBasicBlock *, BlockAndTailDupResult> ComputedEdges;
Kyle Butt7fbec9b2017-02-15 19:49:14 +0000337
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000338 /// Machine Function
Xinliang David Li52530a72016-06-13 22:23:44 +0000339 MachineFunction *F;
340
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000341 /// A handle to the branch probability pass.
Chandler Carruth10281422011-10-21 06:46:38 +0000342 const MachineBranchProbabilityInfo *MBPI;
343
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000344 /// A handle to the function-wide block frequency pass.
Haicheng Wu5b458cc2016-06-09 15:24:29 +0000345 std::unique_ptr<BranchFolder::MBFIWrapper> MBFI;
Chandler Carruth10281422011-10-21 06:46:38 +0000346
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000347 /// A handle to the loop info.
Haicheng Wu5b458cc2016-06-09 15:24:29 +0000348 MachineLoopInfo *MLI;
Chandler Carruth8b9737c2011-10-21 08:57:37 +0000349
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000350 /// Preferred loop exit.
Kyle Buttab9cca72016-10-27 21:37:20 +0000351 /// Member variable for convenience. It may be removed by duplication deep
352 /// in the call stack.
353 MachineBasicBlock *PreferredLoopExit;
354
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000355 /// A handle to the target's instruction info.
Chandler Carruth10281422011-10-21 06:46:38 +0000356 const TargetInstrInfo *TII;
357
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000358 /// A handle to the target's lowering info.
Benjamin Kramer56b31bd2013-01-11 20:05:37 +0000359 const TargetLoweringBase *TLI;
Chandler Carruth8b9737c2011-10-21 08:57:37 +0000360
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000361 /// A handle to the post dominator tree.
Kyle Buttb15c0662017-01-31 23:48:32 +0000362 MachinePostDominatorTree *MPDT;
363
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000364 /// Duplicator used to duplicate tails during placement.
Kyle Butt0846e562016-10-11 20:36:43 +0000365 ///
366 /// Placement decisions can open up new tail duplication opportunities, but
367 /// since tail duplication affects placement decisions of later blocks, it
368 /// must be done inline.
369 TailDuplicator TailDup;
370
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000371 /// Allocator and owner of BlockChain structures.
Chandler Carruth10281422011-10-21 06:46:38 +0000372 ///
Chandler Carruth9139f442012-06-26 05:16:37 +0000373 /// We build BlockChains lazily while processing the loop structure of
374 /// a function. To reduce malloc traffic, we allocate them using this
375 /// slab-like allocator, and destroy them after the pass completes. An
376 /// important guarantee is that this allocator produces stable pointers to
377 /// the chains.
Chandler Carruth10281422011-10-21 06:46:38 +0000378 SpecificBumpPtrAllocator<BlockChain> ChainAllocator;
379
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000380 /// Function wide BasicBlock to BlockChain mapping.
Chandler Carruth10281422011-10-21 06:46:38 +0000381 ///
382 /// This mapping allows efficiently moving from any given basic block to the
383 /// BlockChain it participates in, if any. We use it to, among other things,
384 /// allow implicitly defining edges between chains as the existing edges
385 /// between basic blocks.
Kyle Butte9425c4f2017-02-04 02:26:32 +0000386 DenseMap<const MachineBasicBlock *, BlockChain *> BlockToChain;
Chandler Carruth10281422011-10-21 06:46:38 +0000387
Sanjoy Dasd7389d62016-12-15 05:08:57 +0000388#ifndef NDEBUG
389 /// The set of basic blocks that have terminators that cannot be fully
390 /// analyzed. These basic blocks cannot be re-ordered safely by
391 /// MachineBlockPlacement, and we must preserve physical layout of these
392 /// blocks and their successors through the pass.
393 SmallPtrSet<MachineBasicBlock *, 4> BlocksWithUnanalyzableExits;
394#endif
395
Kyle Butt0846e562016-10-11 20:36:43 +0000396 /// Decrease the UnscheduledPredecessors count for all blocks in chain, and
397 /// if the count goes to 0, add them to the appropriate work list.
Kyle Butte9425c4f2017-02-04 02:26:32 +0000398 void markChainSuccessors(
399 const BlockChain &Chain, const MachineBasicBlock *LoopHeaderBB,
400 const BlockFilterSet *BlockFilter = nullptr);
Kyle Butt0846e562016-10-11 20:36:43 +0000401
402 /// Decrease the UnscheduledPredecessors count for a single block, and
403 /// if the count goes to 0, add them to the appropriate work list.
404 void markBlockSuccessors(
Kyle Butte9425c4f2017-02-04 02:26:32 +0000405 const BlockChain &Chain, const MachineBasicBlock *BB,
406 const MachineBasicBlock *LoopHeaderBB,
Kyle Butt0846e562016-10-11 20:36:43 +0000407 const BlockFilterSet *BlockFilter = nullptr);
408
Xinliang David Li594ffa32016-06-11 18:35:40 +0000409 BranchProbability
Kyle Butte9425c4f2017-02-04 02:26:32 +0000410 collectViableSuccessors(
411 const MachineBasicBlock *BB, const BlockChain &Chain,
412 const BlockFilterSet *BlockFilter,
413 SmallVector<MachineBasicBlock *, 4> &Successors);
414 bool shouldPredBlockBeOutlined(
415 const MachineBasicBlock *BB, const MachineBasicBlock *Succ,
416 const BlockChain &Chain, const BlockFilterSet *BlockFilter,
417 BranchProbability SuccProb, BranchProbability HotProb);
Kyle Butt0846e562016-10-11 20:36:43 +0000418 bool repeatedlyTailDuplicateBlock(
419 MachineBasicBlock *BB, MachineBasicBlock *&LPred,
Kyle Butte9425c4f2017-02-04 02:26:32 +0000420 const MachineBasicBlock *LoopHeaderBB,
Kyle Butt0846e562016-10-11 20:36:43 +0000421 BlockChain &Chain, BlockFilterSet *BlockFilter,
422 MachineFunction::iterator &PrevUnplacedBlockIt);
Kyle Butte9425c4f2017-02-04 02:26:32 +0000423 bool maybeTailDuplicateBlock(
424 MachineBasicBlock *BB, MachineBasicBlock *LPred,
425 BlockChain &Chain, BlockFilterSet *BlockFilter,
426 MachineFunction::iterator &PrevUnplacedBlockIt,
Fangrui Songcb0bab82018-07-16 18:51:40 +0000427 bool &DuplicatedToLPred);
Kyle Butte9425c4f2017-02-04 02:26:32 +0000428 bool hasBetterLayoutPredecessor(
429 const MachineBasicBlock *BB, const MachineBasicBlock *Succ,
430 const BlockChain &SuccChain, BranchProbability SuccProb,
431 BranchProbability RealSuccProb, const BlockChain &Chain,
432 const BlockFilterSet *BlockFilter);
433 BlockAndTailDupResult selectBestSuccessor(
434 const MachineBasicBlock *BB, const BlockChain &Chain,
435 const BlockFilterSet *BlockFilter);
436 MachineBasicBlock *selectBestCandidateBlock(
437 const BlockChain &Chain, SmallVectorImpl<MachineBasicBlock *> &WorkList);
438 MachineBasicBlock *getFirstUnplacedBlock(
439 const BlockChain &PlacedChain,
440 MachineFunction::iterator &PrevUnplacedBlockIt,
441 const BlockFilterSet *BlockFilter);
Amaury Secheteae09c22016-03-14 21:24:11 +0000442
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000443 /// Add a basic block to the work list if it is appropriate.
Amaury Secheteae09c22016-03-14 21:24:11 +0000444 ///
445 /// If the optional parameter BlockFilter is provided, only MBB
446 /// present in the set will be added to the worklist. If nullptr
447 /// is provided, no filtering occurs.
Kyle Butte9425c4f2017-02-04 02:26:32 +0000448 void fillWorkLists(const MachineBasicBlock *MBB,
Amaury Secheteae09c22016-03-14 21:24:11 +0000449 SmallPtrSetImpl<BlockChain *> &UpdatedPreds,
Amaury Secheteae09c22016-03-14 21:24:11 +0000450 const BlockFilterSet *BlockFilter);
Eugene Zelenko5df3d892017-08-24 21:21:39 +0000451
Kyle Butte9425c4f2017-02-04 02:26:32 +0000452 void buildChain(const MachineBasicBlock *BB, BlockChain &Chain,
Kyle Butt0846e562016-10-11 20:36:43 +0000453 BlockFilterSet *BlockFilter = nullptr);
Guozhi Wei81f3fd42019-01-25 19:45:13 +0000454 bool canMoveBottomBlockToTop(const MachineBasicBlock *BottomBlock,
455 const MachineBasicBlock *OldTop);
Guozhi Wei4c8e4802019-02-22 18:04:37 +0000456 bool hasViableTopFallthrough(const MachineBasicBlock *Top,
457 const BlockFilterSet &LoopBlockSet);
Kyle Butte9425c4f2017-02-04 02:26:32 +0000458 MachineBasicBlock *findBestLoopTop(
459 const MachineLoop &L, const BlockFilterSet &LoopBlockSet);
460 MachineBasicBlock *findBestLoopExit(
461 const MachineLoop &L, const BlockFilterSet &LoopBlockSet);
462 BlockFilterSet collectLoopBlockSet(const MachineLoop &L);
463 void buildLoopChains(const MachineLoop &L);
464 void rotateLoop(
465 BlockChain &LoopChain, const MachineBasicBlock *ExitingBB,
466 const BlockFilterSet &LoopBlockSet);
467 void rotateLoopWithProfile(
468 BlockChain &LoopChain, const MachineLoop &L,
469 const BlockFilterSet &LoopBlockSet);
Xinliang David Li52530a72016-06-13 22:23:44 +0000470 void buildCFGChains();
471 void optimizeBranches();
472 void alignBlocks();
Kyle Butt7fbec9b2017-02-15 19:49:14 +0000473 /// Returns true if a block should be tail-duplicated to increase fallthrough
474 /// opportunities.
Kyle Buttb15c0662017-01-31 23:48:32 +0000475 bool shouldTailDuplicate(MachineBasicBlock *BB);
476 /// Check the edge frequencies to see if tail duplication will increase
477 /// fallthroughs.
478 bool isProfitableToTailDup(
Kyle Butte9425c4f2017-02-04 02:26:32 +0000479 const MachineBasicBlock *BB, const MachineBasicBlock *Succ,
Fangrui Songcb0bab82018-07-16 18:51:40 +0000480 BranchProbability QProb,
Kyle Butte9425c4f2017-02-04 02:26:32 +0000481 const BlockChain &Chain, const BlockFilterSet *BlockFilter);
Eugene Zelenko5df3d892017-08-24 21:21:39 +0000482
Kyle Butt7fbec9b2017-02-15 19:49:14 +0000483 /// Check for a trellis layout.
484 bool isTrellis(const MachineBasicBlock *BB,
485 const SmallVectorImpl<MachineBasicBlock *> &ViableSuccs,
486 const BlockChain &Chain, const BlockFilterSet *BlockFilter);
Eugene Zelenko5df3d892017-08-24 21:21:39 +0000487
Kyle Butt7fbec9b2017-02-15 19:49:14 +0000488 /// Get the best successor given a trellis layout.
489 BlockAndTailDupResult getBestTrellisSuccessor(
490 const MachineBasicBlock *BB,
491 const SmallVectorImpl<MachineBasicBlock *> &ViableSuccs,
492 BranchProbability AdjustedSumProb, const BlockChain &Chain,
493 const BlockFilterSet *BlockFilter);
Eugene Zelenko5df3d892017-08-24 21:21:39 +0000494
Kyle Butt7fbec9b2017-02-15 19:49:14 +0000495 /// Get the best pair of non-conflicting edges.
496 static std::pair<WeightedEdge, WeightedEdge> getBestNonConflictingEdges(
497 const MachineBasicBlock *BB,
Benjamin Kramerd71461c2017-04-12 13:26:28 +0000498 MutableArrayRef<SmallVector<WeightedEdge, 8>> Edges);
Eugene Zelenko5df3d892017-08-24 21:21:39 +0000499
Kyle Buttb15c0662017-01-31 23:48:32 +0000500 /// Returns true if a block can tail duplicate into all unplaced
501 /// predecessors. Filters based on loop.
502 bool canTailDuplicateUnplacedPreds(
Kyle Butte9425c4f2017-02-04 02:26:32 +0000503 const MachineBasicBlock *BB, MachineBasicBlock *Succ,
504 const BlockChain &Chain, const BlockFilterSet *BlockFilter);
Eugene Zelenko5df3d892017-08-24 21:21:39 +0000505
Kyle Butt1fa60302017-03-03 01:00:22 +0000506 /// Find chains of triangles to tail-duplicate where a global analysis works,
507 /// but a local analysis would not find them.
508 void precomputeTriangleChains();
Chandler Carruth10281422011-10-21 06:46:38 +0000509
510public:
511 static char ID; // Pass identification, replacement for typeid
Eugene Zelenko5df3d892017-08-24 21:21:39 +0000512
Chandler Carruth10281422011-10-21 06:46:38 +0000513 MachineBlockPlacement() : MachineFunctionPass(ID) {
514 initializeMachineBlockPlacementPass(*PassRegistry::getPassRegistry());
515 }
516
Craig Topper4584cd52014-03-07 09:26:03 +0000517 bool runOnMachineFunction(MachineFunction &F) override;
Chandler Carruth10281422011-10-21 06:46:38 +0000518
Tim Shen1a8c6772018-03-30 17:51:00 +0000519 bool allowTailDupPlacement() const {
520 assert(F);
521 return TailDupPlacement && !F->getTarget().requiresStructuredCFG();
522 }
523
Craig Topper4584cd52014-03-07 09:26:03 +0000524 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruth10281422011-10-21 06:46:38 +0000525 AU.addRequired<MachineBranchProbabilityInfo>();
526 AU.addRequired<MachineBlockFrequencyInfo>();
Kyle Buttb15c0662017-01-31 23:48:32 +0000527 if (TailDupPlacement)
528 AU.addRequired<MachinePostDominatorTree>();
Chandler Carruth8b9737c2011-10-21 08:57:37 +0000529 AU.addRequired<MachineLoopInfo>();
Haicheng Wu5b458cc2016-06-09 15:24:29 +0000530 AU.addRequired<TargetPassConfig>();
Chandler Carruth10281422011-10-21 06:46:38 +0000531 MachineFunctionPass::getAnalysisUsage(AU);
532 }
Chandler Carruth10281422011-10-21 06:46:38 +0000533};
Eugene Zelenko5df3d892017-08-24 21:21:39 +0000534
535} // end anonymous namespace
Chandler Carruth10281422011-10-21 06:46:38 +0000536
537char MachineBlockPlacement::ID = 0;
Eugene Zelenko5df3d892017-08-24 21:21:39 +0000538
Andrew Trick1fa5bcb2012-02-08 21:23:13 +0000539char &llvm::MachineBlockPlacementID = MachineBlockPlacement::ID;
Eugene Zelenko5df3d892017-08-24 21:21:39 +0000540
Matthias Braun1527baa2017-05-25 21:26:32 +0000541INITIALIZE_PASS_BEGIN(MachineBlockPlacement, DEBUG_TYPE,
Chandler Carruth10281422011-10-21 06:46:38 +0000542 "Branch Probability Basic Block Placement", false, false)
543INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
544INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
Kyle Buttb15c0662017-01-31 23:48:32 +0000545INITIALIZE_PASS_DEPENDENCY(MachinePostDominatorTree)
Chandler Carruth8b9737c2011-10-21 08:57:37 +0000546INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
Matthias Braun1527baa2017-05-25 21:26:32 +0000547INITIALIZE_PASS_END(MachineBlockPlacement, DEBUG_TYPE,
Chandler Carruth10281422011-10-21 06:46:38 +0000548 "Branch Probability Basic Block Placement", false, false)
549
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000550#ifndef NDEBUG
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000551/// Helper to print the name of a MBB.
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000552///
553/// Only used by debug logging.
Kyle Butte9425c4f2017-02-04 02:26:32 +0000554static std::string getBlockName(const MachineBasicBlock *BB) {
Alp Tokere69170a2014-06-26 22:52:05 +0000555 std::string Result;
556 raw_string_ostream OS(Result);
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +0000557 OS << printMBBReference(*BB);
Philip Reamesb9688f42016-03-02 21:45:13 +0000558 OS << " ('" << BB->getName() << "')";
Alp Tokere69170a2014-06-26 22:52:05 +0000559 OS.flush();
560 return Result;
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000561}
562#endif
563
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000564/// Mark a chain's successors as having one fewer preds.
Chandler Carrutheb4ec3a2011-11-13 11:34:55 +0000565///
566/// When a chain is being merged into the "placed" chain, this routine will
567/// quickly walk the successors of each block in the chain and mark them as
568/// having one fewer active predecessor. It also adds any successors of this
Kyle Butt0846e562016-10-11 20:36:43 +0000569/// chain which reach the zero-predecessor state to the appropriate worklist.
Chandler Carruth8d150782011-11-13 11:20:44 +0000570void MachineBlockPlacement::markChainSuccessors(
Kyle Butte9425c4f2017-02-04 02:26:32 +0000571 const BlockChain &Chain, const MachineBasicBlock *LoopHeaderBB,
Jakub Staszak90616162011-12-21 23:02:08 +0000572 const BlockFilterSet *BlockFilter) {
Chandler Carruth8d150782011-11-13 11:20:44 +0000573 // Walk all the blocks in this chain, marking their successors as having
574 // a predecessor placed.
Chandler Carruth7a715da2015-03-05 03:19:05 +0000575 for (MachineBasicBlock *MBB : Chain) {
Kyle Butt0846e562016-10-11 20:36:43 +0000576 markBlockSuccessors(Chain, MBB, LoopHeaderBB, BlockFilter);
577 }
578}
Chandler Carruth10281422011-10-21 06:46:38 +0000579
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000580/// Mark a single block's successors as having one fewer preds.
Kyle Butt0846e562016-10-11 20:36:43 +0000581///
582/// Under normal circumstances, this is only called by markChainSuccessors,
583/// but if a block that was to be placed is completely tail-duplicated away,
584/// and was duplicated into the chain end, we need to redo markBlockSuccessors
585/// for just that block.
586void MachineBlockPlacement::markBlockSuccessors(
Kyle Butte9425c4f2017-02-04 02:26:32 +0000587 const BlockChain &Chain, const MachineBasicBlock *MBB,
588 const MachineBasicBlock *LoopHeaderBB, const BlockFilterSet *BlockFilter) {
Kyle Butt0846e562016-10-11 20:36:43 +0000589 // Add any successors for which this is the only un-placed in-loop
590 // predecessor to the worklist as a viable candidate for CFG-neutral
591 // placement. No subsequent placement of this block will violate the CFG
592 // shape, so we get to use heuristics to choose a favorable placement.
593 for (MachineBasicBlock *Succ : MBB->successors()) {
594 if (BlockFilter && !BlockFilter->count(Succ))
595 continue;
596 BlockChain &SuccChain = *BlockToChain[Succ];
597 // Disregard edges within a fixed chain, or edges to the loop header.
598 if (&Chain == &SuccChain || Succ == LoopHeaderBB)
599 continue;
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000600
Kyle Butt0846e562016-10-11 20:36:43 +0000601 // This is a cross-chain edge that is within the loop, so decrement the
602 // loop predecessor count of the destination chain.
603 if (SuccChain.UnscheduledPredecessors == 0 ||
604 --SuccChain.UnscheduledPredecessors > 0)
605 continue;
606
607 auto *NewBB = *SuccChain.begin();
608 if (NewBB->isEHPad())
609 EHPadWorkList.push_back(NewBB);
610 else
611 BlockWorkList.push_back(NewBB);
Chandler Carruth10281422011-10-21 06:46:38 +0000612 }
Chandler Carruth8d150782011-11-13 11:20:44 +0000613}
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000614
Xinliang David Li594ffa32016-06-11 18:35:40 +0000615/// This helper function collects the set of successors of block
616/// \p BB that are allowed to be its layout successors, and return
617/// the total branch probability of edges from \p BB to those
618/// blocks.
619BranchProbability MachineBlockPlacement::collectViableSuccessors(
Kyle Butte9425c4f2017-02-04 02:26:32 +0000620 const MachineBasicBlock *BB, const BlockChain &Chain,
621 const BlockFilterSet *BlockFilter,
Xinliang David Li594ffa32016-06-11 18:35:40 +0000622 SmallVector<MachineBasicBlock *, 4> &Successors) {
Cong Houd97c1002015-12-01 05:29:22 +0000623 // Adjust edge probabilities by excluding edges pointing to blocks that is
624 // either not in BlockFilter or is already in the current chain. Consider the
625 // following CFG:
Cong Hou41cf1a52015-11-18 00:52:52 +0000626 //
627 // --->A
628 // | / \
629 // | B C
630 // | \ / \
631 // ----D E
632 //
633 // Assume A->C is very hot (>90%), and C->D has a 50% probability, then after
634 // A->C is chosen as a fall-through, D won't be selected as a successor of C
635 // due to CFG constraint (the probability of C->D is not greater than
Hiroshi Inoue3c358f82017-06-16 12:23:04 +0000636 // HotProb to break topo-order). If we exclude E that is not in BlockFilter
637 // when calculating the probability of C->D, D will be selected and we
Xinliang David Li594ffa32016-06-11 18:35:40 +0000638 // will get A C D B as the layout of this loop.
Cong Houd97c1002015-12-01 05:29:22 +0000639 auto AdjustedSumProb = BranchProbability::getOne();
Cong Hou41cf1a52015-11-18 00:52:52 +0000640 for (MachineBasicBlock *Succ : BB->successors()) {
641 bool SkipSucc = false;
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000642 if (Succ->isEHPad() || (BlockFilter && !BlockFilter->count(Succ))) {
Cong Hou41cf1a52015-11-18 00:52:52 +0000643 SkipSucc = true;
644 } else {
645 BlockChain *SuccChain = BlockToChain[Succ];
646 if (SuccChain == &Chain) {
Cong Hou41cf1a52015-11-18 00:52:52 +0000647 SkipSucc = true;
648 } else if (Succ != *SuccChain->begin()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000649 LLVM_DEBUG(dbgs() << " " << getBlockName(Succ)
650 << " -> Mid chain!\n");
Cong Hou41cf1a52015-11-18 00:52:52 +0000651 continue;
652 }
653 }
654 if (SkipSucc)
Cong Houd97c1002015-12-01 05:29:22 +0000655 AdjustedSumProb -= MBPI->getEdgeProbability(BB, Succ);
Cong Hou41cf1a52015-11-18 00:52:52 +0000656 else
657 Successors.push_back(Succ);
658 }
659
Xinliang David Li594ffa32016-06-11 18:35:40 +0000660 return AdjustedSumProb;
661}
662
663/// The helper function returns the branch probability that is adjusted
664/// or normalized over the new total \p AdjustedSumProb.
Xinliang David Li594ffa32016-06-11 18:35:40 +0000665static BranchProbability
666getAdjustedProbability(BranchProbability OrigProb,
667 BranchProbability AdjustedSumProb) {
668 BranchProbability SuccProb;
669 uint32_t SuccProbN = OrigProb.getNumerator();
670 uint32_t SuccProbD = AdjustedSumProb.getNumerator();
671 if (SuccProbN >= SuccProbD)
672 SuccProb = BranchProbability::getOne();
673 else
674 SuccProb = BranchProbability(SuccProbN, SuccProbD);
675
676 return SuccProb;
677}
678
Kyle Butt7fbec9b2017-02-15 19:49:14 +0000679/// Check if \p BB has exactly the successors in \p Successors.
680static bool
681hasSameSuccessors(MachineBasicBlock &BB,
682 SmallPtrSetImpl<const MachineBasicBlock *> &Successors) {
683 if (BB.succ_size() != Successors.size())
684 return false;
685 // We don't want to count self-loops
686 if (Successors.count(&BB))
687 return false;
688 for (MachineBasicBlock *Succ : BB.successors())
689 if (!Successors.count(Succ))
690 return false;
691 return true;
692}
693
694/// Check if a block should be tail duplicated to increase fallthrough
695/// opportunities.
Kyle Buttb15c0662017-01-31 23:48:32 +0000696/// \p BB Block to check.
697bool MachineBlockPlacement::shouldTailDuplicate(MachineBasicBlock *BB) {
698 // Blocks with single successors don't create additional fallthrough
699 // opportunities. Don't duplicate them. TODO: When conditional exits are
700 // analyzable, allow them to be duplicated.
701 bool IsSimple = TailDup.isSimpleBB(BB);
702
703 if (BB->succ_size() == 1)
704 return false;
705 return TailDup.shouldTailDuplicate(IsSimple, *BB);
706}
707
708/// Compare 2 BlockFrequency's with a small penalty for \p A.
709/// In order to be conservative, we apply a X% penalty to account for
710/// increased icache pressure and static heuristics. For small frequencies
711/// we use only the numerators to improve accuracy. For simplicity, we assume the
712/// penalty is less than 100%
713/// TODO(iteratee): Use 64-bit fixed point edge frequencies everywhere.
714static bool greaterWithBias(BlockFrequency A, BlockFrequency B,
715 uint64_t EntryFreq) {
716 BranchProbability ThresholdProb(TailDupPlacementPenalty, 100);
717 BlockFrequency Gain = A - B;
718 return (Gain / ThresholdProb).getFrequency() >= EntryFreq;
719}
720
721/// Check the edge frequencies to see if tail duplication will increase
722/// fallthroughs. It only makes sense to call this function when
723/// \p Succ would not be chosen otherwise. Tail duplication of \p Succ is
724/// always locally profitable if we would have picked \p Succ without
725/// considering duplication.
726bool MachineBlockPlacement::isProfitableToTailDup(
Kyle Butte9425c4f2017-02-04 02:26:32 +0000727 const MachineBasicBlock *BB, const MachineBasicBlock *Succ,
Kyle Buttb15c0662017-01-31 23:48:32 +0000728 BranchProbability QProb,
Kyle Butte9425c4f2017-02-04 02:26:32 +0000729 const BlockChain &Chain, const BlockFilterSet *BlockFilter) {
Kyle Buttb15c0662017-01-31 23:48:32 +0000730 // We need to do a probability calculation to make sure this is profitable.
731 // First: does succ have a successor that post-dominates? This affects the
732 // calculation. The 2 relevant cases are:
733 // BB BB
734 // | \Qout | \Qout
735 // P| C |P C
736 // = C' = C'
737 // | /Qin | /Qin
738 // | / | /
739 // Succ Succ
740 // / \ | \ V
741 // U/ =V |U \
742 // / \ = D
743 // D E | /
744 // | /
745 // |/
746 // PDom
747 // '=' : Branch taken for that CFG edge
748 // In the second case, Placing Succ while duplicating it into C prevents the
749 // fallthrough of Succ into either D or PDom, because they now have C as an
750 // unplaced predecessor
751
752 // Start by figuring out which case we fall into
753 MachineBasicBlock *PDom = nullptr;
754 SmallVector<MachineBasicBlock *, 4> SuccSuccs;
755 // Only scan the relevant successors
756 auto AdjustedSuccSumProb =
757 collectViableSuccessors(Succ, Chain, BlockFilter, SuccSuccs);
758 BranchProbability PProb = MBPI->getEdgeProbability(BB, Succ);
759 auto BBFreq = MBFI->getBlockFreq(BB);
760 auto SuccFreq = MBFI->getBlockFreq(Succ);
761 BlockFrequency P = BBFreq * PProb;
762 BlockFrequency Qout = BBFreq * QProb;
763 uint64_t EntryFreq = MBFI->getEntryFreq();
764 // If there are no more successors, it is profitable to copy, as it strictly
765 // increases fallthrough.
766 if (SuccSuccs.size() == 0)
767 return greaterWithBias(P, Qout, EntryFreq);
768
769 auto BestSuccSucc = BranchProbability::getZero();
770 // Find the PDom or the best Succ if no PDom exists.
771 for (MachineBasicBlock *SuccSucc : SuccSuccs) {
772 auto Prob = MBPI->getEdgeProbability(Succ, SuccSucc);
773 if (Prob > BestSuccSucc)
774 BestSuccSucc = Prob;
775 if (PDom == nullptr)
776 if (MPDT->dominates(SuccSucc, Succ)) {
777 PDom = SuccSucc;
778 break;
779 }
780 }
781 // For the comparisons, we need to know Succ's best incoming edge that isn't
782 // from BB.
783 auto SuccBestPred = BlockFrequency(0);
784 for (MachineBasicBlock *SuccPred : Succ->predecessors()) {
785 if (SuccPred == Succ || SuccPred == BB
786 || BlockToChain[SuccPred] == &Chain
787 || (BlockFilter && !BlockFilter->count(SuccPred)))
788 continue;
789 auto Freq = MBFI->getBlockFreq(SuccPred)
790 * MBPI->getEdgeProbability(SuccPred, Succ);
791 if (Freq > SuccBestPred)
792 SuccBestPred = Freq;
793 }
794 // Qin is Succ's best unplaced incoming edge that isn't BB
795 BlockFrequency Qin = SuccBestPred;
796 // If it doesn't have a post-dominating successor, here is the calculation:
797 // BB BB
798 // | \Qout | \
799 // P| C | =
800 // = C' | C
801 // | /Qin | |
802 // | / | C' (+Succ)
803 // Succ Succ /|
804 // / \ | \/ |
Kyle Butt7fbec9b2017-02-15 19:49:14 +0000805 // U/ =V | == |
Kyle Buttb15c0662017-01-31 23:48:32 +0000806 // / \ | / \|
807 // D E D E
808 // '=' : Branch taken for that CFG edge
809 // Cost in the first case is: P + V
810 // For this calculation, we always assume P > Qout. If Qout > P
811 // The result of this function will be ignored at the caller.
Kyle Buttee51a202017-04-10 22:28:18 +0000812 // Let F = SuccFreq - Qin
813 // Cost in the second case is: Qout + min(Qin, F) * U + max(Qin, F) * V
Kyle Buttb15c0662017-01-31 23:48:32 +0000814
815 if (PDom == nullptr || !Succ->isSuccessor(PDom)) {
816 BranchProbability UProb = BestSuccSucc;
817 BranchProbability VProb = AdjustedSuccSumProb - UProb;
Kyle Buttee51a202017-04-10 22:28:18 +0000818 BlockFrequency F = SuccFreq - Qin;
Kyle Buttb15c0662017-01-31 23:48:32 +0000819 BlockFrequency V = SuccFreq * VProb;
Kyle Buttee51a202017-04-10 22:28:18 +0000820 BlockFrequency QinU = std::min(Qin, F) * UProb;
Kyle Buttb15c0662017-01-31 23:48:32 +0000821 BlockFrequency BaseCost = P + V;
Kyle Buttee51a202017-04-10 22:28:18 +0000822 BlockFrequency DupCost = Qout + QinU + std::max(Qin, F) * VProb;
Kyle Buttb15c0662017-01-31 23:48:32 +0000823 return greaterWithBias(BaseCost, DupCost, EntryFreq);
824 }
825 BranchProbability UProb = MBPI->getEdgeProbability(Succ, PDom);
826 BranchProbability VProb = AdjustedSuccSumProb - UProb;
827 BlockFrequency U = SuccFreq * UProb;
828 BlockFrequency V = SuccFreq * VProb;
Kyle Buttee51a202017-04-10 22:28:18 +0000829 BlockFrequency F = SuccFreq - Qin;
Kyle Buttb15c0662017-01-31 23:48:32 +0000830 // If there is a post-dominating successor, here is the calculation:
831 // BB BB BB BB
Kyle Buttee51a202017-04-10 22:28:18 +0000832 // | \Qout | \ | \Qout | \
833 // |P C | = |P C | =
834 // = C' |P C = C' |P C
835 // | /Qin | | | /Qin | |
836 // | / | C' (+Succ) | / | C' (+Succ)
837 // Succ Succ /| Succ Succ /|
838 // | \ V | \/ | | \ V | \/ |
839 // |U \ |U /\ =? |U = |U /\ |
840 // = D = = =?| | D | = =|
841 // | / |/ D | / |/ D
842 // | / | / | = | /
843 // |/ | / |/ | =
844 // Dom Dom Dom Dom
Kyle Buttb15c0662017-01-31 23:48:32 +0000845 // '=' : Branch taken for that CFG edge
846 // The cost for taken branches in the first case is P + U
Kyle Buttee51a202017-04-10 22:28:18 +0000847 // Let F = SuccFreq - Qin
Kyle Buttb15c0662017-01-31 23:48:32 +0000848 // The cost in the second case (assuming independence), given the layout:
Kyle Buttee51a202017-04-10 22:28:18 +0000849 // BB, Succ, (C+Succ), D, Dom or the layout:
850 // BB, Succ, D, Dom, (C+Succ)
851 // is Qout + max(F, Qin) * U + min(F, Qin)
Kyle Butt7fbec9b2017-02-15 19:49:14 +0000852 // compare P + U vs Qout + P * U + Qin.
Kyle Buttb15c0662017-01-31 23:48:32 +0000853 //
854 // The 3rd and 4th cases cover when Dom would be chosen to follow Succ.
855 //
856 // For the 3rd case, the cost is P + 2 * V
Kyle Buttee51a202017-04-10 22:28:18 +0000857 // For the 4th case, the cost is Qout + min(Qin, F) * U + max(Qin, F) * V + V
858 // We choose 4 over 3 when (P + V) > Qout + min(Qin, F) * U + max(Qin, F) * V
Kyle Butt7fbec9b2017-02-15 19:49:14 +0000859 if (UProb > AdjustedSuccSumProb / 2 &&
860 !hasBetterLayoutPredecessor(Succ, PDom, *BlockToChain[PDom], UProb, UProb,
861 Chain, BlockFilter))
Kyle Buttb15c0662017-01-31 23:48:32 +0000862 // Cases 3 & 4
Kyle Buttee51a202017-04-10 22:28:18 +0000863 return greaterWithBias(
864 (P + V), (Qout + std::max(Qin, F) * VProb + std::min(Qin, F) * UProb),
865 EntryFreq);
Kyle Buttb15c0662017-01-31 23:48:32 +0000866 // Cases 1 & 2
Kyle Buttee51a202017-04-10 22:28:18 +0000867 return greaterWithBias((P + U),
868 (Qout + std::min(Qin, F) * AdjustedSuccSumProb +
869 std::max(Qin, F) * UProb),
870 EntryFreq);
Kyle Buttb15c0662017-01-31 23:48:32 +0000871}
872
Kyle Butt7fbec9b2017-02-15 19:49:14 +0000873/// Check for a trellis layout. \p BB is the upper part of a trellis if its
874/// successors form the lower part of a trellis. A successor set S forms the
875/// lower part of a trellis if all of the predecessors of S are either in S or
876/// have all of S as successors. We ignore trellises where BB doesn't have 2
877/// successors because for fewer than 2, it's trivial, and for 3 or greater they
878/// are very uncommon and complex to compute optimally. Allowing edges within S
879/// is not strictly a trellis, but the same algorithm works, so we allow it.
880bool MachineBlockPlacement::isTrellis(
881 const MachineBasicBlock *BB,
882 const SmallVectorImpl<MachineBasicBlock *> &ViableSuccs,
883 const BlockChain &Chain, const BlockFilterSet *BlockFilter) {
884 // Technically BB could form a trellis with branching factor higher than 2.
885 // But that's extremely uncommon.
886 if (BB->succ_size() != 2 || ViableSuccs.size() != 2)
887 return false;
888
889 SmallPtrSet<const MachineBasicBlock *, 2> Successors(BB->succ_begin(),
890 BB->succ_end());
891 // To avoid reviewing the same predecessors twice.
892 SmallPtrSet<const MachineBasicBlock *, 8> SeenPreds;
893
894 for (MachineBasicBlock *Succ : ViableSuccs) {
895 int PredCount = 0;
896 for (auto SuccPred : Succ->predecessors()) {
897 // Allow triangle successors, but don't count them.
Dehao Chenb197d5b2017-03-23 23:28:09 +0000898 if (Successors.count(SuccPred)) {
899 // Make sure that it is actually a triangle.
900 for (MachineBasicBlock *CheckSucc : SuccPred->successors())
901 if (!Successors.count(CheckSucc))
902 return false;
Kyle Butt7fbec9b2017-02-15 19:49:14 +0000903 continue;
Dehao Chenb197d5b2017-03-23 23:28:09 +0000904 }
Kyle Butt7fbec9b2017-02-15 19:49:14 +0000905 const BlockChain *PredChain = BlockToChain[SuccPred];
906 if (SuccPred == BB || (BlockFilter && !BlockFilter->count(SuccPred)) ||
907 PredChain == &Chain || PredChain == BlockToChain[Succ])
908 continue;
909 ++PredCount;
910 // Perform the successor check only once.
911 if (!SeenPreds.insert(SuccPred).second)
912 continue;
913 if (!hasSameSuccessors(*SuccPred, Successors))
914 return false;
915 }
916 // If one of the successors has only BB as a predecessor, it is not a
917 // trellis.
918 if (PredCount < 1)
919 return false;
920 }
921 return true;
922}
923
924/// Pick the highest total weight pair of edges that can both be laid out.
925/// The edges in \p Edges[0] are assumed to have a different destination than
926/// the edges in \p Edges[1]. Simple counting shows that the best pair is either
927/// the individual highest weight edges to the 2 different destinations, or in
928/// case of a conflict, one of them should be replaced with a 2nd best edge.
929std::pair<MachineBlockPlacement::WeightedEdge,
930 MachineBlockPlacement::WeightedEdge>
931MachineBlockPlacement::getBestNonConflictingEdges(
932 const MachineBasicBlock *BB,
Benjamin Kramerd71461c2017-04-12 13:26:28 +0000933 MutableArrayRef<SmallVector<MachineBlockPlacement::WeightedEdge, 8>>
934 Edges) {
Kyle Butt7fbec9b2017-02-15 19:49:14 +0000935 // Sort the edges, and then for each successor, find the best incoming
936 // predecessor. If the best incoming predecessors aren't the same,
937 // then that is clearly the best layout. If there is a conflict, one of the
938 // successors will have to fallthrough from the second best predecessor. We
939 // compare which combination is better overall.
940
941 // Sort for highest frequency.
942 auto Cmp = [](WeightedEdge A, WeightedEdge B) { return A.Weight > B.Weight; };
943
Fangrui Songefd94c52019-04-23 14:51:27 +0000944 llvm::stable_sort(Edges[0], Cmp);
945 llvm::stable_sort(Edges[1], Cmp);
Kyle Butt7fbec9b2017-02-15 19:49:14 +0000946 auto BestA = Edges[0].begin();
947 auto BestB = Edges[1].begin();
948 // Arrange for the correct answer to be in BestA and BestB
949 // If the 2 best edges don't conflict, the answer is already there.
950 if (BestA->Src == BestB->Src) {
951 // Compare the total fallthrough of (Best + Second Best) for both pairs
952 auto SecondBestA = std::next(BestA);
953 auto SecondBestB = std::next(BestB);
954 BlockFrequency BestAScore = BestA->Weight + SecondBestB->Weight;
955 BlockFrequency BestBScore = BestB->Weight + SecondBestA->Weight;
956 if (BestAScore < BestBScore)
957 BestA = SecondBestA;
958 else
959 BestB = SecondBestB;
960 }
961 // Arrange for the BB edge to be in BestA if it exists.
962 if (BestB->Src == BB)
963 std::swap(BestA, BestB);
964 return std::make_pair(*BestA, *BestB);
965}
966
967/// Get the best successor from \p BB based on \p BB being part of a trellis.
968/// We only handle trellises with 2 successors, so the algorithm is
969/// straightforward: Find the best pair of edges that don't conflict. We find
970/// the best incoming edge for each successor in the trellis. If those conflict,
971/// we consider which of them should be replaced with the second best.
972/// Upon return the two best edges will be in \p BestEdges. If one of the edges
973/// comes from \p BB, it will be in \p BestEdges[0]
974MachineBlockPlacement::BlockAndTailDupResult
975MachineBlockPlacement::getBestTrellisSuccessor(
976 const MachineBasicBlock *BB,
977 const SmallVectorImpl<MachineBasicBlock *> &ViableSuccs,
978 BranchProbability AdjustedSumProb, const BlockChain &Chain,
979 const BlockFilterSet *BlockFilter) {
980
981 BlockAndTailDupResult Result = {nullptr, false};
982 SmallPtrSet<const MachineBasicBlock *, 4> Successors(BB->succ_begin(),
983 BB->succ_end());
984
985 // We assume size 2 because it's common. For general n, we would have to do
986 // the Hungarian algorithm, but it's not worth the complexity because more
987 // than 2 successors is fairly uncommon, and a trellis even more so.
988 if (Successors.size() != 2 || ViableSuccs.size() != 2)
989 return Result;
990
991 // Collect the edge frequencies of all edges that form the trellis.
Benjamin Kramerd71461c2017-04-12 13:26:28 +0000992 SmallVector<WeightedEdge, 8> Edges[2];
Kyle Butt7fbec9b2017-02-15 19:49:14 +0000993 int SuccIndex = 0;
994 for (auto Succ : ViableSuccs) {
995 for (MachineBasicBlock *SuccPred : Succ->predecessors()) {
996 // Skip any placed predecessors that are not BB
997 if (SuccPred != BB)
998 if ((BlockFilter && !BlockFilter->count(SuccPred)) ||
999 BlockToChain[SuccPred] == &Chain ||
1000 BlockToChain[SuccPred] == BlockToChain[Succ])
1001 continue;
1002 BlockFrequency EdgeFreq = MBFI->getBlockFreq(SuccPred) *
1003 MBPI->getEdgeProbability(SuccPred, Succ);
1004 Edges[SuccIndex].push_back({EdgeFreq, SuccPred, Succ});
1005 }
1006 ++SuccIndex;
1007 }
1008
1009 // Pick the best combination of 2 edges from all the edges in the trellis.
1010 WeightedEdge BestA, BestB;
1011 std::tie(BestA, BestB) = getBestNonConflictingEdges(BB, Edges);
1012
1013 if (BestA.Src != BB) {
1014 // If we have a trellis, and BB doesn't have the best fallthrough edges,
1015 // we shouldn't choose any successor. We've already looked and there's a
1016 // better fallthrough edge for all the successors.
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001017 LLVM_DEBUG(dbgs() << "Trellis, but not one of the chosen edges.\n");
Kyle Butt7fbec9b2017-02-15 19:49:14 +00001018 return Result;
1019 }
1020
1021 // Did we pick the triangle edge? If tail-duplication is profitable, do
1022 // that instead. Otherwise merge the triangle edge now while we know it is
1023 // optimal.
1024 if (BestA.Dest == BestB.Src) {
1025 // The edges are BB->Succ1->Succ2, and we're looking to see if BB->Succ2
1026 // would be better.
1027 MachineBasicBlock *Succ1 = BestA.Dest;
1028 MachineBasicBlock *Succ2 = BestB.Dest;
1029 // Check to see if tail-duplication would be profitable.
Tim Shen1a8c6772018-03-30 17:51:00 +00001030 if (allowTailDupPlacement() && shouldTailDuplicate(Succ2) &&
Kyle Butt7fbec9b2017-02-15 19:49:14 +00001031 canTailDuplicateUnplacedPreds(BB, Succ2, Chain, BlockFilter) &&
1032 isProfitableToTailDup(BB, Succ2, MBPI->getEdgeProbability(BB, Succ1),
1033 Chain, BlockFilter)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001034 LLVM_DEBUG(BranchProbability Succ2Prob = getAdjustedProbability(
1035 MBPI->getEdgeProbability(BB, Succ2), AdjustedSumProb);
1036 dbgs() << " Selected: " << getBlockName(Succ2)
1037 << ", probability: " << Succ2Prob
1038 << " (Tail Duplicate)\n");
Kyle Butt7fbec9b2017-02-15 19:49:14 +00001039 Result.BB = Succ2;
1040 Result.ShouldTailDup = true;
1041 return Result;
1042 }
1043 }
1044 // We have already computed the optimal edge for the other side of the
1045 // trellis.
Kyle Buttebe6cc42017-02-23 21:22:24 +00001046 ComputedEdges[BestB.Src] = { BestB.Dest, false };
Kyle Butt7fbec9b2017-02-15 19:49:14 +00001047
1048 auto TrellisSucc = BestA.Dest;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001049 LLVM_DEBUG(BranchProbability SuccProb = getAdjustedProbability(
1050 MBPI->getEdgeProbability(BB, TrellisSucc), AdjustedSumProb);
1051 dbgs() << " Selected: " << getBlockName(TrellisSucc)
1052 << ", probability: " << SuccProb << " (Trellis)\n");
Kyle Butt7fbec9b2017-02-15 19:49:14 +00001053 Result.BB = TrellisSucc;
1054 return Result;
1055}
Kyle Buttb15c0662017-01-31 23:48:32 +00001056
Tim Shen1a8c6772018-03-30 17:51:00 +00001057/// When the option allowTailDupPlacement() is on, this method checks if the
Kyle Buttb15c0662017-01-31 23:48:32 +00001058/// fallthrough candidate block \p Succ (of block \p BB) can be tail-duplicated
1059/// into all of its unplaced, unfiltered predecessors, that are not BB.
1060bool MachineBlockPlacement::canTailDuplicateUnplacedPreds(
Kyle Butte9425c4f2017-02-04 02:26:32 +00001061 const MachineBasicBlock *BB, MachineBasicBlock *Succ,
1062 const BlockChain &Chain, const BlockFilterSet *BlockFilter) {
Kyle Buttb15c0662017-01-31 23:48:32 +00001063 if (!shouldTailDuplicate(Succ))
1064 return false;
1065
Kyle Butt7fbec9b2017-02-15 19:49:14 +00001066 // For CFG checking.
1067 SmallPtrSet<const MachineBasicBlock *, 4> Successors(BB->succ_begin(),
1068 BB->succ_end());
Kyle Buttb15c0662017-01-31 23:48:32 +00001069 for (MachineBasicBlock *Pred : Succ->predecessors()) {
1070 // Make sure all unplaced and unfiltered predecessors can be
1071 // tail-duplicated into.
Kyle Butte9425c4f2017-02-04 02:26:32 +00001072 // Skip any blocks that are already placed or not in this loop.
Kyle Buttb15c0662017-01-31 23:48:32 +00001073 if (Pred == BB || (BlockFilter && !BlockFilter->count(Pred))
1074 || BlockToChain[Pred] == &Chain)
1075 continue;
Kyle Butt7fbec9b2017-02-15 19:49:14 +00001076 if (!TailDup.canTailDuplicate(Succ, Pred)) {
1077 if (Successors.size() > 1 && hasSameSuccessors(*Pred, Successors))
1078 // This will result in a trellis after tail duplication, so we don't
1079 // need to copy Succ into this predecessor. In the presence
1080 // of a trellis tail duplication can continue to be profitable.
1081 // For example:
1082 // A A
1083 // |\ |\
1084 // | \ | \
1085 // | C | C+BB
1086 // | / | |
1087 // |/ | |
1088 // BB => BB |
1089 // |\ |\/|
1090 // | \ |/\|
1091 // | D | D
1092 // | / | /
1093 // |/ |/
1094 // Succ Succ
1095 //
1096 // After BB was duplicated into C, the layout looks like the one on the
1097 // right. BB and C now have the same successors. When considering
1098 // whether Succ can be duplicated into all its unplaced predecessors, we
1099 // ignore C.
1100 // We can do this because C already has a profitable fallthrough, namely
1101 // D. TODO(iteratee): ignore sufficiently cold predecessors for
1102 // duplication and for this test.
1103 //
1104 // This allows trellises to be laid out in 2 separate chains
1105 // (A,B,Succ,...) and later (C,D,...) This is a reasonable heuristic
1106 // because it allows the creation of 2 fallthrough paths with links
1107 // between them, and we correctly identify the best layout for these
1108 // CFGs. We want to extend trellises that the user created in addition
1109 // to trellises created by tail-duplication, so we just look for the
1110 // CFG.
1111 continue;
Kyle Buttb15c0662017-01-31 23:48:32 +00001112 return false;
Kyle Butt7fbec9b2017-02-15 19:49:14 +00001113 }
Kyle Buttb15c0662017-01-31 23:48:32 +00001114 }
1115 return true;
1116}
1117
Kyle Butt1fa60302017-03-03 01:00:22 +00001118/// Find chains of triangles where we believe it would be profitable to
1119/// tail-duplicate them all, but a local analysis would not find them.
1120/// There are 3 ways this can be profitable:
1121/// 1) The post-dominators marked 50% are actually taken 55% (This shrinks with
1122/// longer chains)
1123/// 2) The chains are statically correlated. Branch probabilities have a very
1124/// U-shaped distribution.
1125/// [http://nrs.harvard.edu/urn-3:HUL.InstRepos:24015805]
1126/// If the branches in a chain are likely to be from the same side of the
1127/// distribution as their predecessor, but are independent at runtime, this
1128/// transformation is profitable. (Because the cost of being wrong is a small
1129/// fixed cost, unlike the standard triangle layout where the cost of being
1130/// wrong scales with the # of triangles.)
1131/// 3) The chains are dynamically correlated. If the probability that a previous
1132/// branch was taken positively influences whether the next branch will be
1133/// taken
1134/// We believe that 2 and 3 are common enough to justify the small margin in 1.
1135void MachineBlockPlacement::precomputeTriangleChains() {
1136 struct TriangleChain {
Benjamin Kramerd71461c2017-04-12 13:26:28 +00001137 std::vector<MachineBasicBlock *> Edges;
Eugene Zelenko5df3d892017-08-24 21:21:39 +00001138
Benjamin Kramerd71461c2017-04-12 13:26:28 +00001139 TriangleChain(MachineBasicBlock *src, MachineBasicBlock *dst)
1140 : Edges({src, dst}) {}
Kyle Butt1fa60302017-03-03 01:00:22 +00001141
1142 void append(MachineBasicBlock *dst) {
Benjamin Kramerd71461c2017-04-12 13:26:28 +00001143 assert(getKey()->isSuccessor(dst) &&
Kyle Butt1fa60302017-03-03 01:00:22 +00001144 "Attempting to append a block that is not a successor.");
Benjamin Kramerd71461c2017-04-12 13:26:28 +00001145 Edges.push_back(dst);
Kyle Butt1fa60302017-03-03 01:00:22 +00001146 }
1147
Benjamin Kramerd71461c2017-04-12 13:26:28 +00001148 unsigned count() const { return Edges.size() - 1; }
1149
1150 MachineBasicBlock *getKey() const {
1151 return Edges.back();
Kyle Butt1fa60302017-03-03 01:00:22 +00001152 }
1153 };
1154
1155 if (TriangleChainCount == 0)
1156 return;
1157
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001158 LLVM_DEBUG(dbgs() << "Pre-computing triangle chains.\n");
Kyle Butt1fa60302017-03-03 01:00:22 +00001159 // Map from last block to the chain that contains it. This allows us to extend
1160 // chains as we find new triangles.
1161 DenseMap<const MachineBasicBlock *, TriangleChain> TriangleChainMap;
1162 for (MachineBasicBlock &BB : *F) {
1163 // If BB doesn't have 2 successors, it doesn't start a triangle.
1164 if (BB.succ_size() != 2)
1165 continue;
1166 MachineBasicBlock *PDom = nullptr;
1167 for (MachineBasicBlock *Succ : BB.successors()) {
1168 if (!MPDT->dominates(Succ, &BB))
1169 continue;
1170 PDom = Succ;
1171 break;
1172 }
1173 // If BB doesn't have a post-dominating successor, it doesn't form a
1174 // triangle.
1175 if (PDom == nullptr)
1176 continue;
1177 // If PDom has a hint that it is low probability, skip this triangle.
1178 if (MBPI->getEdgeProbability(&BB, PDom) < BranchProbability(50, 100))
1179 continue;
1180 // If PDom isn't eligible for duplication, this isn't the kind of triangle
1181 // we're looking for.
1182 if (!shouldTailDuplicate(PDom))
1183 continue;
1184 bool CanTailDuplicate = true;
1185 // If PDom can't tail-duplicate into it's non-BB predecessors, then this
1186 // isn't the kind of triangle we're looking for.
1187 for (MachineBasicBlock* Pred : PDom->predecessors()) {
1188 if (Pred == &BB)
1189 continue;
1190 if (!TailDup.canTailDuplicate(PDom, Pred)) {
1191 CanTailDuplicate = false;
1192 break;
1193 }
1194 }
1195 // If we can't tail-duplicate PDom to its predecessors, then skip this
1196 // triangle.
1197 if (!CanTailDuplicate)
1198 continue;
1199
1200 // Now we have an interesting triangle. Insert it if it's not part of an
Hiroshi Inoue3c358f82017-06-16 12:23:04 +00001201 // existing chain.
Kyle Butt1fa60302017-03-03 01:00:22 +00001202 // Note: This cannot be replaced with a call insert() or emplace() because
1203 // the find key is BB, but the insert/emplace key is PDom.
1204 auto Found = TriangleChainMap.find(&BB);
1205 // If it is, remove the chain from the map, grow it, and put it back in the
1206 // map with the end as the new key.
1207 if (Found != TriangleChainMap.end()) {
1208 TriangleChain Chain = std::move(Found->second);
1209 TriangleChainMap.erase(Found);
1210 Chain.append(PDom);
1211 TriangleChainMap.insert(std::make_pair(Chain.getKey(), std::move(Chain)));
1212 } else {
1213 auto InsertResult = TriangleChainMap.try_emplace(PDom, &BB, PDom);
Benjamin Kramer33580692017-04-12 13:26:31 +00001214 assert(InsertResult.second && "Block seen twice.");
1215 (void)InsertResult;
Kyle Butt1fa60302017-03-03 01:00:22 +00001216 }
1217 }
1218
Kyle Butt336c78f2017-04-12 18:30:32 +00001219 // Iterating over a DenseMap is safe here, because the only thing in the body
1220 // of the loop is inserting into another DenseMap (ComputedEdges).
1221 // ComputedEdges is never iterated, so this doesn't lead to non-determinism.
Kyle Butt1fa60302017-03-03 01:00:22 +00001222 for (auto &ChainPair : TriangleChainMap) {
1223 TriangleChain &Chain = ChainPair.second;
1224 // Benchmarking has shown that due to branch correlation duplicating 2 or
1225 // more triangles is profitable, despite the calculations assuming
1226 // independence.
Benjamin Kramerd71461c2017-04-12 13:26:28 +00001227 if (Chain.count() < TriangleChainCount)
Kyle Butt1fa60302017-03-03 01:00:22 +00001228 continue;
Benjamin Kramerd71461c2017-04-12 13:26:28 +00001229 MachineBasicBlock *dst = Chain.Edges.back();
1230 Chain.Edges.pop_back();
1231 for (MachineBasicBlock *src : reverse(Chain.Edges)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001232 LLVM_DEBUG(dbgs() << "Marking edge: " << getBlockName(src) << "->"
1233 << getBlockName(dst)
1234 << " as pre-computed based on triangles.\n");
Benjamin Kramer33580692017-04-12 13:26:31 +00001235
1236 auto InsertResult = ComputedEdges.insert({src, {dst, true}});
1237 assert(InsertResult.second && "Block seen twice.");
1238 (void)InsertResult;
1239
Kyle Butt1fa60302017-03-03 01:00:22 +00001240 dst = src;
1241 }
1242 }
1243}
1244
Dehao Chen9f2bdfb2016-06-14 22:27:17 +00001245// When profile is not present, return the StaticLikelyProb.
1246// When profile is available, we need to handle the triangle-shape CFG.
1247static BranchProbability getLayoutSuccessorProbThreshold(
Kyle Butte9425c4f2017-02-04 02:26:32 +00001248 const MachineBasicBlock *BB) {
Easwaran Ramana17f2202017-12-22 01:33:52 +00001249 if (!BB->getParent()->getFunction().hasProfileData())
Dehao Chen9f2bdfb2016-06-14 22:27:17 +00001250 return BranchProbability(StaticLikelyProb, 100);
1251 if (BB->succ_size() == 2) {
1252 const MachineBasicBlock *Succ1 = *BB->succ_begin();
1253 const MachineBasicBlock *Succ2 = *(BB->succ_begin() + 1);
Xinliang David Lie34ed832016-06-15 03:03:30 +00001254 if (Succ1->isSuccessor(Succ2) || Succ2->isSuccessor(Succ1)) {
1255 /* See case 1 below for the cost analysis. For BB->Succ to
1256 * be taken with smaller cost, the following needs to hold:
Kyle Buttb15c0662017-01-31 23:48:32 +00001257 * Prob(BB->Succ) > 2 * Prob(BB->Pred)
1258 * So the threshold T in the calculation below
1259 * (1-T) * Prob(BB->Succ) > T * Prob(BB->Pred)
1260 * So T / (1 - T) = 2, Yielding T = 2/3
1261 * Also adding user specified branch bias, we have
Xinliang David Lie34ed832016-06-15 03:03:30 +00001262 * T = (2/3)*(ProfileLikelyProb/50)
1263 * = (2*ProfileLikelyProb)/150)
1264 */
1265 return BranchProbability(2 * ProfileLikelyProb, 150);
1266 }
Dehao Chen9f2bdfb2016-06-14 22:27:17 +00001267 }
1268 return BranchProbability(ProfileLikelyProb, 100);
Xinliang David Licbf12142016-06-13 20:24:19 +00001269}
1270
1271/// Checks to see if the layout candidate block \p Succ has a better layout
1272/// predecessor than \c BB. If yes, returns true.
Kyle Buttb15c0662017-01-31 23:48:32 +00001273/// \p SuccProb: The probability adjusted for only remaining blocks.
1274/// Only used for logging
1275/// \p RealSuccProb: The un-adjusted probability.
1276/// \p Chain: The chain that BB belongs to and Succ is being considered for.
1277/// \p BlockFilter: if non-null, the set of blocks that make up the loop being
1278/// considered
Xinliang David Licbf12142016-06-13 20:24:19 +00001279bool MachineBlockPlacement::hasBetterLayoutPredecessor(
Kyle Butte9425c4f2017-02-04 02:26:32 +00001280 const MachineBasicBlock *BB, const MachineBasicBlock *Succ,
1281 const BlockChain &SuccChain, BranchProbability SuccProb,
1282 BranchProbability RealSuccProb, const BlockChain &Chain,
1283 const BlockFilterSet *BlockFilter) {
Xinliang David Licbf12142016-06-13 20:24:19 +00001284
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00001285 // There isn't a better layout when there are no unscheduled predecessors.
Xinliang David Licbf12142016-06-13 20:24:19 +00001286 if (SuccChain.UnscheduledPredecessors == 0)
1287 return false;
1288
1289 // There are two basic scenarios here:
1290 // -------------------------------------
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00001291 // Case 1: triangular shape CFG (if-then):
Xinliang David Licbf12142016-06-13 20:24:19 +00001292 // BB
1293 // | \
1294 // | \
1295 // | Pred
1296 // | /
1297 // Succ
1298 // In this case, we are evaluating whether to select edge -> Succ, e.g.
1299 // set Succ as the layout successor of BB. Picking Succ as BB's
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00001300 // successor breaks the CFG constraints (FIXME: define these constraints).
1301 // With this layout, Pred BB
Xinliang David Licbf12142016-06-13 20:24:19 +00001302 // is forced to be outlined, so the overall cost will be cost of the
1303 // branch taken from BB to Pred, plus the cost of back taken branch
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00001304 // from Pred to Succ, as well as the additional cost associated
Xinliang David Licbf12142016-06-13 20:24:19 +00001305 // with the needed unconditional jump instruction from Pred To Succ.
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00001306
Xinliang David Licbf12142016-06-13 20:24:19 +00001307 // The cost of the topological order layout is the taken branch cost
1308 // from BB to Succ, so to make BB->Succ a viable candidate, the following
1309 // must hold:
1310 // 2 * freq(BB->Pred) * taken_branch_cost + unconditional_jump_cost
1311 // < freq(BB->Succ) * taken_branch_cost.
1312 // Ignoring unconditional jump cost, we get
1313 // freq(BB->Succ) > 2 * freq(BB->Pred), i.e.,
1314 // prob(BB->Succ) > 2 * prob(BB->Pred)
1315 //
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00001316 // When real profile data is available, we can precisely compute the
1317 // probability threshold that is needed for edge BB->Succ to be considered.
1318 // Without profile data, the heuristic requires the branch bias to be
Xinliang David Licbf12142016-06-13 20:24:19 +00001319 // a lot larger to make sure the signal is very strong (e.g. 80% default).
1320 // -----------------------------------------------------------------
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00001321 // Case 2: diamond like CFG (if-then-else):
Xinliang David Licbf12142016-06-13 20:24:19 +00001322 // S
1323 // / \
1324 // | \
1325 // BB Pred
1326 // \ /
1327 // Succ
1328 // ..
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00001329 //
1330 // The current block is BB and edge BB->Succ is now being evaluated.
1331 // Note that edge S->BB was previously already selected because
1332 // prob(S->BB) > prob(S->Pred).
1333 // At this point, 2 blocks can be placed after BB: Pred or Succ. If we
1334 // choose Pred, we will have a topological ordering as shown on the left
1335 // in the picture below. If we choose Succ, we have the solution as shown
1336 // on the right:
1337 //
1338 // topo-order:
1339 //
1340 // S----- ---S
1341 // | | | |
1342 // ---BB | | BB
1343 // | | | |
Hiroshi Inoue3c358f82017-06-16 12:23:04 +00001344 // | Pred-- | Succ--
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00001345 // | | | |
Hiroshi Inoue3c358f82017-06-16 12:23:04 +00001346 // ---Succ ---Pred--
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00001347 //
1348 // cost = freq(S->Pred) + freq(BB->Succ) cost = 2 * freq (S->Pred)
1349 // = freq(S->Pred) + freq(S->BB)
1350 //
1351 // If we have profile data (i.e, branch probabilities can be trusted), the
1352 // cost (number of taken branches) with layout S->BB->Succ->Pred is 2 *
1353 // freq(S->Pred) while the cost of topo order is freq(S->Pred) + freq(S->BB).
1354 // We know Prob(S->BB) > Prob(S->Pred), so freq(S->BB) > freq(S->Pred), which
1355 // means the cost of topological order is greater.
Xinliang David Licbf12142016-06-13 20:24:19 +00001356 // When profile data is not available, however, we need to be more
1357 // conservative. If the branch prediction is wrong, breaking the topo-order
1358 // will actually yield a layout with large cost. For this reason, we need
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00001359 // strong biased branch at block S with Prob(S->BB) in order to select
1360 // BB->Succ. This is equivalent to looking the CFG backward with backward
Xinliang David Licbf12142016-06-13 20:24:19 +00001361 // edge: Prob(Succ->BB) needs to >= HotProb in order to be selected (without
1362 // profile data).
Kyle Butt02d8d052016-07-29 18:09:28 +00001363 // --------------------------------------------------------------------------
1364 // Case 3: forked diamond
1365 // S
1366 // / \
1367 // / \
1368 // BB Pred
1369 // | \ / |
1370 // | \ / |
1371 // | X |
1372 // | / \ |
1373 // | / \ |
1374 // S1 S2
1375 //
1376 // The current block is BB and edge BB->S1 is now being evaluated.
1377 // As above S->BB was already selected because
1378 // prob(S->BB) > prob(S->Pred). Assume that prob(BB->S1) >= prob(BB->S2).
1379 //
1380 // topo-order:
1381 //
1382 // S-------| ---S
1383 // | | | |
1384 // ---BB | | BB
1385 // | | | |
1386 // | Pred----| | S1----
1387 // | | | |
1388 // --(S1 or S2) ---Pred--
Kyle Butt7fbec9b2017-02-15 19:49:14 +00001389 // |
1390 // S2
Kyle Butt02d8d052016-07-29 18:09:28 +00001391 //
1392 // topo-cost = freq(S->Pred) + freq(BB->S1) + freq(BB->S2)
1393 // + min(freq(Pred->S1), freq(Pred->S2))
1394 // Non-topo-order cost:
Kyle Butt02d8d052016-07-29 18:09:28 +00001395 // non-topo-cost = 2 * freq(S->Pred) + freq(BB->S2).
1396 // To be conservative, we can assume that min(freq(Pred->S1), freq(Pred->S2))
1397 // is 0. Then the non topo layout is better when
1398 // freq(S->Pred) < freq(BB->S1).
1399 // This is exactly what is checked below.
1400 // Note there are other shapes that apply (Pred may not be a single block,
1401 // but they all fit this general pattern.)
Dehao Chen9f2bdfb2016-06-14 22:27:17 +00001402 BranchProbability HotProb = getLayoutSuccessorProbThreshold(BB);
Xinliang David Licbf12142016-06-13 20:24:19 +00001403
Xinliang David Licbf12142016-06-13 20:24:19 +00001404 // Make sure that a hot successor doesn't have a globally more
1405 // important predecessor.
1406 BlockFrequency CandidateEdgeFreq = MBFI->getBlockFreq(BB) * RealSuccProb;
1407 bool BadCFGConflict = false;
1408
1409 for (MachineBasicBlock *Pred : Succ->predecessors()) {
1410 if (Pred == Succ || BlockToChain[Pred] == &SuccChain ||
1411 (BlockFilter && !BlockFilter->count(Pred)) ||
Kyle Buttb15c0662017-01-31 23:48:32 +00001412 BlockToChain[Pred] == &Chain ||
1413 // This check is redundant except for look ahead. This function is
1414 // called for lookahead by isProfitableToTailDup when BB hasn't been
1415 // placed yet.
1416 (Pred == BB))
Xinliang David Licbf12142016-06-13 20:24:19 +00001417 continue;
Kyle Butt02d8d052016-07-29 18:09:28 +00001418 // Do backward checking.
1419 // For all cases above, we need a backward checking to filter out edges that
Kyle Buttb15c0662017-01-31 23:48:32 +00001420 // are not 'strongly' biased.
Xinliang David Licbf12142016-06-13 20:24:19 +00001421 // BB Pred
1422 // \ /
1423 // Succ
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00001424 // We select edge BB->Succ if
Xinliang David Licbf12142016-06-13 20:24:19 +00001425 // freq(BB->Succ) > freq(Succ) * HotProb
1426 // i.e. freq(BB->Succ) > freq(BB->Succ) * HotProb + freq(Pred->Succ) *
1427 // HotProb
1428 // i.e. freq((BB->Succ) * (1 - HotProb) > freq(Pred->Succ) * HotProb
Kyle Butt02d8d052016-07-29 18:09:28 +00001429 // Case 1 is covered too, because the first equation reduces to:
1430 // prob(BB->Succ) > HotProb. (freq(Succ) = freq(BB) for a triangle)
Xinliang David Licbf12142016-06-13 20:24:19 +00001431 BlockFrequency PredEdgeFreq =
1432 MBFI->getBlockFreq(Pred) * MBPI->getEdgeProbability(Pred, Succ);
1433 if (PredEdgeFreq * HotProb >= CandidateEdgeFreq * HotProb.getCompl()) {
1434 BadCFGConflict = true;
1435 break;
1436 }
1437 }
1438
1439 if (BadCFGConflict) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001440 LLVM_DEBUG(dbgs() << " Not a candidate: " << getBlockName(Succ) << " -> "
1441 << SuccProb << " (prob) (non-cold CFG conflict)\n");
Xinliang David Licbf12142016-06-13 20:24:19 +00001442 return true;
1443 }
1444
1445 return false;
1446}
1447
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001448/// Select the best successor for a block.
Xinliang David Li594ffa32016-06-11 18:35:40 +00001449///
1450/// This looks across all successors of a particular block and attempts to
1451/// select the "best" one to be the layout successor. It only considers direct
1452/// successors which also pass the block filter. It will attempt to avoid
1453/// breaking CFG structure, but cave and break such structures in the case of
1454/// very hot successor edges.
1455///
Kyle Buttb15c0662017-01-31 23:48:32 +00001456/// \returns The best successor block found, or null if none are viable, along
1457/// with a boolean indicating if tail duplication is necessary.
1458MachineBlockPlacement::BlockAndTailDupResult
Kyle Butte9425c4f2017-02-04 02:26:32 +00001459MachineBlockPlacement::selectBestSuccessor(
1460 const MachineBasicBlock *BB, const BlockChain &Chain,
1461 const BlockFilterSet *BlockFilter) {
Xinliang David Li594ffa32016-06-11 18:35:40 +00001462 const BranchProbability HotProb(StaticLikelyProb, 100);
1463
Kyle Buttb15c0662017-01-31 23:48:32 +00001464 BlockAndTailDupResult BestSucc = { nullptr, false };
Xinliang David Li594ffa32016-06-11 18:35:40 +00001465 auto BestProb = BranchProbability::getZero();
1466
1467 SmallVector<MachineBasicBlock *, 4> Successors;
1468 auto AdjustedSumProb =
1469 collectViableSuccessors(BB, Chain, BlockFilter, Successors);
1470
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001471 LLVM_DEBUG(dbgs() << "Selecting best successor for: " << getBlockName(BB)
1472 << "\n");
Kyle Buttb15c0662017-01-31 23:48:32 +00001473
Kyle Buttebe6cc42017-02-23 21:22:24 +00001474 // if we already precomputed the best successor for BB, return that if still
1475 // applicable.
1476 auto FoundEdge = ComputedEdges.find(BB);
1477 if (FoundEdge != ComputedEdges.end()) {
1478 MachineBasicBlock *Succ = FoundEdge->second.BB;
1479 ComputedEdges.erase(FoundEdge);
Kyle Butt7fbec9b2017-02-15 19:49:14 +00001480 BlockChain *SuccChain = BlockToChain[Succ];
1481 if (BB->isSuccessor(Succ) && (!BlockFilter || BlockFilter->count(Succ)) &&
Kyle Buttebe6cc42017-02-23 21:22:24 +00001482 SuccChain != &Chain && Succ == *SuccChain->begin())
1483 return FoundEdge->second;
Kyle Butt7fbec9b2017-02-15 19:49:14 +00001484 }
1485
1486 // if BB is part of a trellis, Use the trellis to determine the optimal
1487 // fallthrough edges
1488 if (isTrellis(BB, Successors, Chain, BlockFilter))
1489 return getBestTrellisSuccessor(BB, Successors, AdjustedSumProb, Chain,
1490 BlockFilter);
1491
Kyle Buttb15c0662017-01-31 23:48:32 +00001492 // For blocks with CFG violations, we may be able to lay them out anyway with
1493 // tail-duplication. We keep this vector so we can perform the probability
1494 // calculations the minimum number of times.
1495 SmallVector<std::tuple<BranchProbability, MachineBasicBlock *>, 4>
1496 DupCandidates;
Cong Hou41cf1a52015-11-18 00:52:52 +00001497 for (MachineBasicBlock *Succ : Successors) {
Xinliang David Li594ffa32016-06-11 18:35:40 +00001498 auto RealSuccProb = MBPI->getEdgeProbability(BB, Succ);
1499 BranchProbability SuccProb =
1500 getAdjustedProbability(RealSuccProb, AdjustedSumProb);
Chandler Carruthb3361722011-11-13 11:34:53 +00001501
Cong Hou41cf1a52015-11-18 00:52:52 +00001502 BlockChain &SuccChain = *BlockToChain[Succ];
Xinliang David Licbf12142016-06-13 20:24:19 +00001503 // Skip the edge \c BB->Succ if block \c Succ has a better layout
1504 // predecessor that yields lower global cost.
1505 if (hasBetterLayoutPredecessor(BB, Succ, SuccChain, SuccProb, RealSuccProb,
Kyle Buttb15c0662017-01-31 23:48:32 +00001506 Chain, BlockFilter)) {
1507 // If tail duplication would make Succ profitable, place it.
Tim Shen1a8c6772018-03-30 17:51:00 +00001508 if (allowTailDupPlacement() && shouldTailDuplicate(Succ))
Kyle Buttb15c0662017-01-31 23:48:32 +00001509 DupCandidates.push_back(std::make_tuple(SuccProb, Succ));
Xinliang David Licbf12142016-06-13 20:24:19 +00001510 continue;
Kyle Buttb15c0662017-01-31 23:48:32 +00001511 }
Chandler Carruth18dfac32011-11-20 11:22:06 +00001512
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001513 LLVM_DEBUG(
1514 dbgs() << " Candidate: " << getBlockName(Succ)
1515 << ", probability: " << SuccProb
Xinliang David Licbf12142016-06-13 20:24:19 +00001516 << (SuccChain.UnscheduledPredecessors != 0 ? " (CFG break)" : "")
1517 << "\n");
Sjoerd Meijer5e11a182016-07-27 08:49:23 +00001518
Kyle Buttb15c0662017-01-31 23:48:32 +00001519 if (BestSucc.BB && BestProb >= SuccProb) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001520 LLVM_DEBUG(dbgs() << " Not the best candidate, continuing\n");
Chandler Carruthb3361722011-11-13 11:34:53 +00001521 continue;
Sjoerd Meijer5e11a182016-07-27 08:49:23 +00001522 }
1523
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001524 LLVM_DEBUG(dbgs() << " Setting it as best candidate\n");
Kyle Buttb15c0662017-01-31 23:48:32 +00001525 BestSucc.BB = Succ;
Cong Houd97c1002015-12-01 05:29:22 +00001526 BestProb = SuccProb;
Chandler Carruthb3361722011-11-13 11:34:53 +00001527 }
Kyle Buttb15c0662017-01-31 23:48:32 +00001528 // Handle the tail duplication candidates in order of decreasing probability.
1529 // Stop at the first one that is profitable. Also stop if they are less
1530 // profitable than BestSucc. Position is important because we preserve it and
1531 // prefer first best match. Here we aren't comparing in order, so we capture
1532 // the position instead.
Fangrui Songefd94c52019-04-23 14:51:27 +00001533 llvm::stable_sort(DupCandidates,
1534 [](std::tuple<BranchProbability, MachineBasicBlock *> L,
1535 std::tuple<BranchProbability, MachineBasicBlock *> R) {
1536 return std::get<0>(L) > std::get<0>(R);
1537 });
1538 for (auto &Tup : DupCandidates) {
Kyle Buttb15c0662017-01-31 23:48:32 +00001539 BranchProbability DupProb;
1540 MachineBasicBlock *Succ;
1541 std::tie(DupProb, Succ) = Tup;
1542 if (DupProb < BestProb)
1543 break;
1544 if (canTailDuplicateUnplacedPreds(BB, Succ, Chain, BlockFilter)
Kyle Butt7e8be282017-04-10 22:28:22 +00001545 && (isProfitableToTailDup(BB, Succ, BestProb, Chain, BlockFilter))) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001546 LLVM_DEBUG(dbgs() << " Candidate: " << getBlockName(Succ)
1547 << ", probability: " << DupProb
1548 << " (Tail Duplicate)\n");
Kyle Buttb15c0662017-01-31 23:48:32 +00001549 BestSucc.BB = Succ;
1550 BestSucc.ShouldTailDup = true;
1551 break;
1552 }
1553 }
1554
1555 if (BestSucc.BB)
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001556 LLVM_DEBUG(dbgs() << " Selected: " << getBlockName(BestSucc.BB) << "\n");
Sjoerd Meijer5e11a182016-07-27 08:49:23 +00001557
Chandler Carruthb3361722011-11-13 11:34:53 +00001558 return BestSucc;
1559}
1560
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001561/// Select the best block from a worklist.
Chandler Carruthf9213fe2011-11-13 11:42:26 +00001562///
1563/// This looks through the provided worklist as a list of candidate basic
1564/// blocks and select the most profitable one to place. The definition of
1565/// profitable only really makes sense in the context of a loop. This returns
1566/// the most frequently visited block in the worklist, which in the case of
1567/// a loop, is the one most desirable to be physically close to the rest of the
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00001568/// loop body in order to improve i-cache behavior.
Chandler Carruthf9213fe2011-11-13 11:42:26 +00001569///
1570/// \returns The best block found, or null if none are viable.
1571MachineBasicBlock *MachineBlockPlacement::selectBestCandidateBlock(
Kyle Butte9425c4f2017-02-04 02:26:32 +00001572 const BlockChain &Chain, SmallVectorImpl<MachineBasicBlock *> &WorkList) {
Chandler Carruth0af6a0b2011-11-14 09:46:33 +00001573 // Once we need to walk the worklist looking for a candidate, cleanup the
1574 // worklist of already placed entries.
1575 // FIXME: If this shows up on profiles, it could be folded (at the cost of
1576 // some code complexity) into the loop below.
Eugene Zelenko5df3d892017-08-24 21:21:39 +00001577 WorkList.erase(llvm::remove_if(WorkList,
1578 [&](MachineBasicBlock *BB) {
1579 return BlockToChain.lookup(BB) == &Chain;
1580 }),
Chandler Carruth0af6a0b2011-11-14 09:46:33 +00001581 WorkList.end());
1582
Amaury Sechetc53ad4f2016-04-07 21:29:39 +00001583 if (WorkList.empty())
1584 return nullptr;
1585
1586 bool IsEHPad = WorkList[0]->isEHPad();
1587
Craig Topperc0196b12014-04-14 00:51:57 +00001588 MachineBasicBlock *BestBlock = nullptr;
Chandler Carruthf9213fe2011-11-13 11:42:26 +00001589 BlockFrequency BestFreq;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001590 for (MachineBasicBlock *MBB : WorkList) {
Kyle Butt0cf5b2f2017-05-17 23:44:41 +00001591 assert(MBB->isEHPad() == IsEHPad &&
1592 "EHPad mismatch between block and work list.");
Amaury Sechetc53ad4f2016-04-07 21:29:39 +00001593
Chandler Carruth7a715da2015-03-05 03:19:05 +00001594 BlockChain &SuccChain = *BlockToChain[MBB];
Philip Reames02e11322016-03-02 22:40:51 +00001595 if (&SuccChain == &Chain)
Chandler Carruthf9213fe2011-11-13 11:42:26 +00001596 continue;
Junmo Park4ba6cf62016-03-11 05:07:07 +00001597
Kyle Butt0cf5b2f2017-05-17 23:44:41 +00001598 assert(SuccChain.UnscheduledPredecessors == 0 &&
1599 "Found CFG-violating block");
Chandler Carruthf9213fe2011-11-13 11:42:26 +00001600
Chandler Carruth7a715da2015-03-05 03:19:05 +00001601 BlockFrequency CandidateFreq = MBFI->getBlockFreq(MBB);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001602 LLVM_DEBUG(dbgs() << " " << getBlockName(MBB) << " -> ";
1603 MBFI->printBlockFreq(dbgs(), CandidateFreq) << " (freq)\n");
Amaury Sechetc53ad4f2016-04-07 21:29:39 +00001604
1605 // For ehpad, we layout the least probable first as to avoid jumping back
1606 // from least probable landingpads to more probable ones.
1607 //
1608 // FIXME: Using probability is probably (!) not the best way to achieve
1609 // this. We should probably have a more principled approach to layout
1610 // cleanup code.
1611 //
1612 // The goal is to get:
1613 //
1614 // +--------------------------+
1615 // | V
1616 // InnerLp -> InnerCleanup OuterLp -> OuterCleanup -> Resume
1617 //
1618 // Rather than:
1619 //
1620 // +-------------------------------------+
1621 // V |
1622 // OuterLp -> OuterCleanup -> Resume InnerLp -> InnerCleanup
1623 if (BestBlock && (IsEHPad ^ (BestFreq >= CandidateFreq)))
Chandler Carruthf9213fe2011-11-13 11:42:26 +00001624 continue;
Amaury Sechetc53ad4f2016-04-07 21:29:39 +00001625
Chandler Carruth7a715da2015-03-05 03:19:05 +00001626 BestBlock = MBB;
Chandler Carruthf9213fe2011-11-13 11:42:26 +00001627 BestFreq = CandidateFreq;
1628 }
Amaury Sechetc53ad4f2016-04-07 21:29:39 +00001629
Chandler Carruthf9213fe2011-11-13 11:42:26 +00001630 return BestBlock;
1631}
1632
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001633/// Retrieve the first unplaced basic block.
Chandler Carruth1071cfa2011-11-14 00:00:35 +00001634///
1635/// This routine is called when we are unable to use the CFG to walk through
1636/// all of the basic blocks and form a chain due to unnatural loops in the CFG.
Chandler Carruth9b548a7f2011-11-15 06:26:43 +00001637/// We walk through the function's blocks in order, starting from the
1638/// LastUnplacedBlockIt. We update this iterator on each call to avoid
1639/// re-scanning the entire sequence on repeated calls to this routine.
Chandler Carruth1071cfa2011-11-14 00:00:35 +00001640MachineBasicBlock *MachineBlockPlacement::getFirstUnplacedBlock(
Xinliang David Li52530a72016-06-13 22:23:44 +00001641 const BlockChain &PlacedChain,
Chandler Carruth9b548a7f2011-11-15 06:26:43 +00001642 MachineFunction::iterator &PrevUnplacedBlockIt,
Jakub Staszak90616162011-12-21 23:02:08 +00001643 const BlockFilterSet *BlockFilter) {
Xinliang David Li52530a72016-06-13 22:23:44 +00001644 for (MachineFunction::iterator I = PrevUnplacedBlockIt, E = F->end(); I != E;
Chandler Carruth9b548a7f2011-11-15 06:26:43 +00001645 ++I) {
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +00001646 if (BlockFilter && !BlockFilter->count(&*I))
Chandler Carruth9b548a7f2011-11-15 06:26:43 +00001647 continue;
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +00001648 if (BlockToChain[&*I] != &PlacedChain) {
Chandler Carruth9b548a7f2011-11-15 06:26:43 +00001649 PrevUnplacedBlockIt = I;
Chandler Carruth4a87aa02011-11-23 03:03:21 +00001650 // Now select the head of the chain to which the unplaced block belongs
1651 // as the block to place. This will force the entire chain to be placed,
1652 // and satisfies the requirements of merging chains.
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +00001653 return *BlockToChain[&*I]->begin();
Chandler Carruth1071cfa2011-11-14 00:00:35 +00001654 }
1655 }
Craig Topperc0196b12014-04-14 00:51:57 +00001656 return nullptr;
Chandler Carruth1071cfa2011-11-14 00:00:35 +00001657}
1658
Amaury Secheteae09c22016-03-14 21:24:11 +00001659void MachineBlockPlacement::fillWorkLists(
Kyle Butte9425c4f2017-02-04 02:26:32 +00001660 const MachineBasicBlock *MBB,
Amaury Secheteae09c22016-03-14 21:24:11 +00001661 SmallPtrSetImpl<BlockChain *> &UpdatedPreds,
Amaury Secheteae09c22016-03-14 21:24:11 +00001662 const BlockFilterSet *BlockFilter = nullptr) {
1663 BlockChain &Chain = *BlockToChain[MBB];
1664 if (!UpdatedPreds.insert(&Chain).second)
1665 return;
1666
Kyle Butt0cf5b2f2017-05-17 23:44:41 +00001667 assert(
1668 Chain.UnscheduledPredecessors == 0 &&
1669 "Attempting to place block with unscheduled predecessors in worklist.");
Amaury Secheteae09c22016-03-14 21:24:11 +00001670 for (MachineBasicBlock *ChainBB : Chain) {
Kyle Butt0cf5b2f2017-05-17 23:44:41 +00001671 assert(BlockToChain[ChainBB] == &Chain &&
1672 "Block in chain doesn't match BlockToChain map.");
Amaury Secheteae09c22016-03-14 21:24:11 +00001673 for (MachineBasicBlock *Pred : ChainBB->predecessors()) {
1674 if (BlockFilter && !BlockFilter->count(Pred))
1675 continue;
1676 if (BlockToChain[Pred] == &Chain)
1677 continue;
1678 ++Chain.UnscheduledPredecessors;
1679 }
1680 }
1681
Amaury Sechetc53ad4f2016-04-07 21:29:39 +00001682 if (Chain.UnscheduledPredecessors != 0)
1683 return;
1684
Kyle Butte9425c4f2017-02-04 02:26:32 +00001685 MachineBasicBlock *BB = *Chain.begin();
1686 if (BB->isEHPad())
1687 EHPadWorkList.push_back(BB);
Amaury Sechetc53ad4f2016-04-07 21:29:39 +00001688 else
Kyle Butte9425c4f2017-02-04 02:26:32 +00001689 BlockWorkList.push_back(BB);
Amaury Secheteae09c22016-03-14 21:24:11 +00001690}
1691
Chandler Carruth8d150782011-11-13 11:20:44 +00001692void MachineBlockPlacement::buildChain(
Kyle Butte9425c4f2017-02-04 02:26:32 +00001693 const MachineBasicBlock *HeadBB, BlockChain &Chain,
Kyle Butt0846e562016-10-11 20:36:43 +00001694 BlockFilterSet *BlockFilter) {
Kyle Butte9425c4f2017-02-04 02:26:32 +00001695 assert(HeadBB && "BB must not be null.\n");
1696 assert(BlockToChain[HeadBB] == &Chain && "BlockToChainMap mis-match.\n");
Xinliang David Li52530a72016-06-13 22:23:44 +00001697 MachineFunction::iterator PrevUnplacedBlockIt = F->begin();
Chandler Carruth1071cfa2011-11-14 00:00:35 +00001698
Kyle Butte9425c4f2017-02-04 02:26:32 +00001699 const MachineBasicBlock *LoopHeaderBB = HeadBB;
Xinliang David Li93926ac2016-07-01 05:46:48 +00001700 markChainSuccessors(Chain, LoopHeaderBB, BlockFilter);
Kyle Butte9425c4f2017-02-04 02:26:32 +00001701 MachineBasicBlock *BB = *std::prev(Chain.end());
Eugene Zelenko5df3d892017-08-24 21:21:39 +00001702 while (true) {
Kyle Butt82c22902016-06-28 22:50:54 +00001703 assert(BB && "null block found at end of chain in loop.");
1704 assert(BlockToChain[BB] == &Chain && "BlockToChainMap mis-match in loop.");
1705 assert(*std::prev(Chain.end()) == BB && "BB Not found at end of chain.");
1706
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00001707
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +00001708 // Look for the best viable successor if there is one to place immediately
1709 // after this block.
Kyle Buttb15c0662017-01-31 23:48:32 +00001710 auto Result = selectBestSuccessor(BB, Chain, BlockFilter);
1711 MachineBasicBlock* BestSucc = Result.BB;
1712 bool ShouldTailDup = Result.ShouldTailDup;
Tim Shen1a8c6772018-03-30 17:51:00 +00001713 if (allowTailDupPlacement())
Kyle Buttb15c0662017-01-31 23:48:32 +00001714 ShouldTailDup |= (BestSucc && shouldTailDuplicate(BestSucc));
Chandler Carruth8d150782011-11-13 11:20:44 +00001715
1716 // If an immediate successor isn't available, look for the best viable
1717 // block among those we've identified as not violating the loop's CFG at
1718 // this point. This won't be a fallthrough, but it will increase locality.
Chandler Carruthf9213fe2011-11-13 11:42:26 +00001719 if (!BestSucc)
Amaury Sechet9ee4ddd2016-04-07 06:34:47 +00001720 BestSucc = selectBestCandidateBlock(Chain, BlockWorkList);
Amaury Sechetc53ad4f2016-04-07 21:29:39 +00001721 if (!BestSucc)
1722 BestSucc = selectBestCandidateBlock(Chain, EHPadWorkList);
Chandler Carruth8d150782011-11-13 11:20:44 +00001723
Chandler Carruth8d150782011-11-13 11:20:44 +00001724 if (!BestSucc) {
Xinliang David Li52530a72016-06-13 22:23:44 +00001725 BestSucc = getFirstUnplacedBlock(Chain, PrevUnplacedBlockIt, BlockFilter);
Chandler Carruth1071cfa2011-11-14 00:00:35 +00001726 if (!BestSucc)
1727 break;
1728
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001729 LLVM_DEBUG(dbgs() << "Unnatural loop CFG detected, forcibly merging the "
1730 "layout successor until the CFG reduces\n");
Chandler Carruth8d150782011-11-13 11:20:44 +00001731 }
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00001732
Kyle Butt0846e562016-10-11 20:36:43 +00001733 // Placement may have changed tail duplication opportunities.
1734 // Check for that now.
Tim Shen1a8c6772018-03-30 17:51:00 +00001735 if (allowTailDupPlacement() && BestSucc && ShouldTailDup) {
Kyle Butt0846e562016-10-11 20:36:43 +00001736 // If the chosen successor was duplicated into all its predecessors,
1737 // don't bother laying it out, just go round the loop again with BB as
1738 // the chain end.
1739 if (repeatedlyTailDuplicateBlock(BestSucc, BB, LoopHeaderBB, Chain,
1740 BlockFilter, PrevUnplacedBlockIt))
1741 continue;
1742 }
1743
Chandler Carruth8d150782011-11-13 11:20:44 +00001744 // Place this block, updating the datastructures to reflect its placement.
Jakub Staszak90616162011-12-21 23:02:08 +00001745 BlockChain &SuccChain = *BlockToChain[BestSucc];
Philip Reamesae27b232016-03-03 00:58:43 +00001746 // Zero out UnscheduledPredecessors for the successor we're about to merge in case
Chandler Carruth1071cfa2011-11-14 00:00:35 +00001747 // we selected a successor that didn't fit naturally into the CFG.
Philip Reamesae27b232016-03-03 00:58:43 +00001748 SuccChain.UnscheduledPredecessors = 0;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001749 LLVM_DEBUG(dbgs() << "Merging from " << getBlockName(BB) << " to "
1750 << getBlockName(BestSucc) << "\n");
Xinliang David Li93926ac2016-07-01 05:46:48 +00001751 markChainSuccessors(SuccChain, LoopHeaderBB, BlockFilter);
Chandler Carruth8d150782011-11-13 11:20:44 +00001752 Chain.merge(BestSucc, &SuccChain);
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001753 BB = *std::prev(Chain.end());
Jakub Staszak190c7122011-12-07 19:46:10 +00001754 }
Chandler Carruth1071cfa2011-11-14 00:00:35 +00001755
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001756 LLVM_DEBUG(dbgs() << "Finished forming chain for header block "
1757 << getBlockName(*Chain.begin()) << "\n");
Chandler Carruth10281422011-10-21 06:46:38 +00001758}
1759
Guozhi Wei81f3fd42019-01-25 19:45:13 +00001760// If bottom of block BB has only one successor OldTop, in most cases it is
1761// profitable to move it before OldTop, except the following case:
1762//
1763// -->OldTop<-
1764// | . |
1765// | . |
1766// | . |
1767// ---Pred |
1768// | |
1769// BB-----
1770//
1771// If BB is moved before OldTop, Pred needs a taken branch to BB, and it can't
1772// layout the other successor below it, so it can't reduce taken branch.
1773// In this case we keep its original layout.
1774bool
1775MachineBlockPlacement::canMoveBottomBlockToTop(
1776 const MachineBasicBlock *BottomBlock,
1777 const MachineBasicBlock *OldTop) {
1778 if (BottomBlock->pred_size() != 1)
1779 return true;
1780 MachineBasicBlock *Pred = *BottomBlock->pred_begin();
1781 if (Pred->succ_size() != 2)
1782 return true;
1783
1784 MachineBasicBlock *OtherBB = *Pred->succ_begin();
1785 if (OtherBB == BottomBlock)
1786 OtherBB = *Pred->succ_rbegin();
1787 if (OtherBB == OldTop)
1788 return false;
1789
1790 return true;
1791}
1792
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001793/// Find the best loop top block for layout.
Chandler Carruth9ffb97e2011-11-27 00:38:03 +00001794///
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001795/// Look for a block which is strictly better than the loop header for laying
1796/// out at the top of the loop. This looks for one and only one pattern:
1797/// a latch block with no conditional exit. This block will cause a conditional
1798/// jump around it or will be the bottom of the loop if we lay it out in place,
1799/// but if it it doesn't end up at the bottom of the loop for any reason,
1800/// rotation alone won't fix it. Because such a block will always result in an
1801/// unconditional jump (for the backedge) rotating it in front of the loop
1802/// header is always profitable.
1803MachineBasicBlock *
Kyle Butte9425c4f2017-02-04 02:26:32 +00001804MachineBlockPlacement::findBestLoopTop(const MachineLoop &L,
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001805 const BlockFilterSet &LoopBlockSet) {
Sjoerd Meijer15c81b02016-08-16 19:50:33 +00001806 // Placing the latch block before the header may introduce an extra branch
1807 // that skips this block the first time the loop is executed, which we want
1808 // to avoid when optimising for size.
1809 // FIXME: in theory there is a case that does not introduce a new branch,
1810 // i.e. when the layout predecessor does not fallthrough to the loop header.
1811 // In practice this never happens though: there always seems to be a preheader
1812 // that can fallthrough and that is also placed before the header.
Evandro Menezes85bd3972019-04-04 22:40:06 +00001813 if (F->getFunction().hasOptSize())
Sjoerd Meijer15c81b02016-08-16 19:50:33 +00001814 return L.getHeader();
1815
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001816 // Check that the header hasn't been fused with a preheader block due to
1817 // crazy branches. If it has, we need to start with the header at the top to
1818 // prevent pulling the preheader into the loop body.
1819 BlockChain &HeaderChain = *BlockToChain[L.getHeader()];
1820 if (!LoopBlockSet.count(*HeaderChain.begin()))
1821 return L.getHeader();
1822
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001823 LLVM_DEBUG(dbgs() << "Finding best loop top for: "
1824 << getBlockName(L.getHeader()) << "\n");
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001825
1826 BlockFrequency BestPredFreq;
Craig Topperc0196b12014-04-14 00:51:57 +00001827 MachineBasicBlock *BestPred = nullptr;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001828 for (MachineBasicBlock *Pred : L.getHeader()->predecessors()) {
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001829 if (!LoopBlockSet.count(Pred))
1830 continue;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001831 LLVM_DEBUG(dbgs() << " header pred: " << getBlockName(Pred) << ", has "
1832 << Pred->succ_size() << " successors, ";
1833 MBFI->printBlockFreq(dbgs(), Pred) << " freq\n");
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001834 if (Pred->succ_size() > 1)
1835 continue;
1836
Guozhi Wei81f3fd42019-01-25 19:45:13 +00001837 if (!canMoveBottomBlockToTop(Pred, L.getHeader()))
1838 continue;
1839
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001840 BlockFrequency PredFreq = MBFI->getBlockFreq(Pred);
1841 if (!BestPred || PredFreq > BestPredFreq ||
1842 (!(PredFreq < BestPredFreq) &&
1843 Pred->isLayoutSuccessor(L.getHeader()))) {
1844 BestPred = Pred;
1845 BestPredFreq = PredFreq;
1846 }
1847 }
1848
1849 // If no direct predecessor is fine, just use the loop header.
Philip Reamesb9688f42016-03-02 21:45:13 +00001850 if (!BestPred) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001851 LLVM_DEBUG(dbgs() << " final top unchanged\n");
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001852 return L.getHeader();
Philip Reamesb9688f42016-03-02 21:45:13 +00001853 }
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001854
1855 // Walk backwards through any straight line of predecessors.
1856 while (BestPred->pred_size() == 1 &&
1857 (*BestPred->pred_begin())->succ_size() == 1 &&
1858 *BestPred->pred_begin() != L.getHeader())
1859 BestPred = *BestPred->pred_begin();
1860
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001861 LLVM_DEBUG(dbgs() << " final top: " << getBlockName(BestPred) << "\n");
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001862 return BestPred;
1863}
1864
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001865/// Find the best loop exiting block for layout.
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001866///
Chandler Carruth03adbd42011-11-27 13:34:33 +00001867/// This routine implements the logic to analyze the loop looking for the best
1868/// block to layout at the top of the loop. Typically this is done to maximize
1869/// fallthrough opportunities.
1870MachineBasicBlock *
Kyle Butte9425c4f2017-02-04 02:26:32 +00001871MachineBlockPlacement::findBestLoopExit(const MachineLoop &L,
Chandler Carruthccc7e422012-04-16 01:12:56 +00001872 const BlockFilterSet &LoopBlockSet) {
Chandler Carruth68062612012-04-10 13:35:57 +00001873 // We don't want to layout the loop linearly in all cases. If the loop header
1874 // is just a normal basic block in the loop, we want to look for what block
1875 // within the loop is the best one to layout at the top. However, if the loop
1876 // header has be pre-merged into a chain due to predecessors not having
1877 // analyzable branches, *and* the predecessor it is merged with is *not* part
1878 // of the loop, rotating the header into the middle of the loop will create
1879 // a non-contiguous range of blocks which is Very Bad. So start with the
1880 // header and only rotate if safe.
1881 BlockChain &HeaderChain = *BlockToChain[L.getHeader()];
1882 if (!LoopBlockSet.count(*HeaderChain.begin()))
Craig Topperc0196b12014-04-14 00:51:57 +00001883 return nullptr;
Chandler Carruth68062612012-04-10 13:35:57 +00001884
Chandler Carruth03adbd42011-11-27 13:34:33 +00001885 BlockFrequency BestExitEdgeFreq;
Chandler Carruthccc7e422012-04-16 01:12:56 +00001886 unsigned BestExitLoopDepth = 0;
Craig Topperc0196b12014-04-14 00:51:57 +00001887 MachineBasicBlock *ExitingBB = nullptr;
Chandler Carruth4f567202011-11-27 20:18:00 +00001888 // If there are exits to outer loops, loop rotation can severely limit
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00001889 // fallthrough opportunities unless it selects such an exit. Keep a set of
Chandler Carruth4f567202011-11-27 20:18:00 +00001890 // blocks where rotating to exit with that block will reach an outer loop.
1891 SmallPtrSet<MachineBasicBlock *, 4> BlocksExitingToOuterLoop;
1892
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001893 LLVM_DEBUG(dbgs() << "Finding best loop exit for: "
1894 << getBlockName(L.getHeader()) << "\n");
Chandler Carruth7a715da2015-03-05 03:19:05 +00001895 for (MachineBasicBlock *MBB : L.getBlocks()) {
1896 BlockChain &Chain = *BlockToChain[MBB];
Chandler Carruth03adbd42011-11-27 13:34:33 +00001897 // Ensure that this block is at the end of a chain; otherwise it could be
Chandler Carruth9a512a42015-04-15 13:19:54 +00001898 // mid-way through an inner loop or a successor of an unanalyzable branch.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001899 if (MBB != *std::prev(Chain.end()))
Chandler Carruth9ffb97e2011-11-27 00:38:03 +00001900 continue;
Chandler Carruth9ffb97e2011-11-27 00:38:03 +00001901
Chandler Carruth03adbd42011-11-27 13:34:33 +00001902 // Now walk the successors. We need to establish whether this has a viable
1903 // exiting successor and whether it has a viable non-exiting successor.
1904 // We store the old exiting state and restore it if a viable looping
1905 // successor isn't found.
1906 MachineBasicBlock *OldExitingBB = ExitingBB;
1907 BlockFrequency OldBestExitEdgeFreq = BestExitEdgeFreq;
Chandler Carruthccc7e422012-04-16 01:12:56 +00001908 bool HasLoopingSucc = false;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001909 for (MachineBasicBlock *Succ : MBB->successors()) {
Reid Kleckner0e288232015-08-27 23:27:47 +00001910 if (Succ->isEHPad())
Chandler Carruth03adbd42011-11-27 13:34:33 +00001911 continue;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001912 if (Succ == MBB)
Chandler Carruth03adbd42011-11-27 13:34:33 +00001913 continue;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001914 BlockChain &SuccChain = *BlockToChain[Succ];
Chandler Carruth03adbd42011-11-27 13:34:33 +00001915 // Don't split chains, either this chain or the successor's chain.
Chandler Carruthccc7e422012-04-16 01:12:56 +00001916 if (&Chain == &SuccChain) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001917 LLVM_DEBUG(dbgs() << " exiting: " << getBlockName(MBB) << " -> "
1918 << getBlockName(Succ) << " (chain conflict)\n");
Chandler Carruth03adbd42011-11-27 13:34:33 +00001919 continue;
1920 }
1921
Cong Houd97c1002015-12-01 05:29:22 +00001922 auto SuccProb = MBPI->getEdgeProbability(MBB, Succ);
Chandler Carruth7a715da2015-03-05 03:19:05 +00001923 if (LoopBlockSet.count(Succ)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001924 LLVM_DEBUG(dbgs() << " looping: " << getBlockName(MBB) << " -> "
1925 << getBlockName(Succ) << " (" << SuccProb << ")\n");
Chandler Carruthccc7e422012-04-16 01:12:56 +00001926 HasLoopingSucc = true;
Chandler Carruth03adbd42011-11-27 13:34:33 +00001927 continue;
1928 }
1929
Chandler Carruthccc7e422012-04-16 01:12:56 +00001930 unsigned SuccLoopDepth = 0;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001931 if (MachineLoop *ExitLoop = MLI->getLoopFor(Succ)) {
Chandler Carruthccc7e422012-04-16 01:12:56 +00001932 SuccLoopDepth = ExitLoop->getLoopDepth();
1933 if (ExitLoop->contains(&L))
Chandler Carruth7a715da2015-03-05 03:19:05 +00001934 BlocksExitingToOuterLoop.insert(MBB);
Chandler Carruthccc7e422012-04-16 01:12:56 +00001935 }
1936
Chandler Carruth7a715da2015-03-05 03:19:05 +00001937 BlockFrequency ExitEdgeFreq = MBFI->getBlockFreq(MBB) * SuccProb;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001938 LLVM_DEBUG(dbgs() << " exiting: " << getBlockName(MBB) << " -> "
1939 << getBlockName(Succ) << " [L:" << SuccLoopDepth
1940 << "] (";
1941 MBFI->printBlockFreq(dbgs(), ExitEdgeFreq) << ")\n");
Benjamin Kramerc8160d62013-11-20 19:08:44 +00001942 // Note that we bias this toward an existing layout successor to retain
1943 // incoming order in the absence of better information. The exit must have
1944 // a frequency higher than the current exit before we consider breaking
1945 // the layout.
1946 BranchProbability Bias(100 - ExitBlockBias, 100);
Chandler Carruth26d30172015-04-15 13:39:42 +00001947 if (!ExitingBB || SuccLoopDepth > BestExitLoopDepth ||
Chandler Carruthccc7e422012-04-16 01:12:56 +00001948 ExitEdgeFreq > BestExitEdgeFreq ||
Chandler Carruth7a715da2015-03-05 03:19:05 +00001949 (MBB->isLayoutSuccessor(Succ) &&
Benjamin Kramerc8160d62013-11-20 19:08:44 +00001950 !(ExitEdgeFreq < BestExitEdgeFreq * Bias))) {
Chandler Carruth03adbd42011-11-27 13:34:33 +00001951 BestExitEdgeFreq = ExitEdgeFreq;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001952 ExitingBB = MBB;
Chandler Carrutha0545802011-11-27 09:22:53 +00001953 }
Chandler Carruth9ffb97e2011-11-27 00:38:03 +00001954 }
Chandler Carruth03adbd42011-11-27 13:34:33 +00001955
Chandler Carruthccc7e422012-04-16 01:12:56 +00001956 if (!HasLoopingSucc) {
Chandler Carruthcfb2b9d2015-04-15 13:26:41 +00001957 // Restore the old exiting state, no viable looping successor was found.
Chandler Carruth03adbd42011-11-27 13:34:33 +00001958 ExitingBB = OldExitingBB;
1959 BestExitEdgeFreq = OldBestExitEdgeFreq;
Chandler Carruth03adbd42011-11-27 13:34:33 +00001960 }
Chandler Carruth9ffb97e2011-11-27 00:38:03 +00001961 }
Chandler Carruthccc7e422012-04-16 01:12:56 +00001962 // Without a candidate exiting block or with only a single block in the
Chandler Carruth03adbd42011-11-27 13:34:33 +00001963 // loop, just use the loop header to layout the loop.
Sjoerd Meijer5e11a182016-07-27 08:49:23 +00001964 if (!ExitingBB) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001965 LLVM_DEBUG(
1966 dbgs() << " No other candidate exit blocks, using loop header\n");
Craig Topperc0196b12014-04-14 00:51:57 +00001967 return nullptr;
Sjoerd Meijer5e11a182016-07-27 08:49:23 +00001968 }
1969 if (L.getNumBlocks() == 1) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001970 LLVM_DEBUG(dbgs() << " Loop has 1 block, using loop header as exit\n");
Sjoerd Meijer5e11a182016-07-27 08:49:23 +00001971 return nullptr;
1972 }
Chandler Carruth9ffb97e2011-11-27 00:38:03 +00001973
Chandler Carruth4f567202011-11-27 20:18:00 +00001974 // Also, if we have exit blocks which lead to outer loops but didn't select
1975 // one of them as the exiting block we are rotating toward, disable loop
1976 // rotation altogether.
1977 if (!BlocksExitingToOuterLoop.empty() &&
1978 !BlocksExitingToOuterLoop.count(ExitingBB))
Craig Topperc0196b12014-04-14 00:51:57 +00001979 return nullptr;
Chandler Carruth4f567202011-11-27 20:18:00 +00001980
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001981 LLVM_DEBUG(dbgs() << " Best exiting block: " << getBlockName(ExitingBB)
1982 << "\n");
Chandler Carruthccc7e422012-04-16 01:12:56 +00001983 return ExitingBB;
Chandler Carruth9ffb97e2011-11-27 00:38:03 +00001984}
1985
Guozhi Wei4c8e4802019-02-22 18:04:37 +00001986/// Check if there is a fallthrough to loop header Top.
1987///
1988/// 1. Look for a Pred that can be layout before Top.
1989/// 2. Check if Top is the most possible successor of Pred.
1990bool
1991MachineBlockPlacement::hasViableTopFallthrough(
1992 const MachineBasicBlock *Top,
1993 const BlockFilterSet &LoopBlockSet) {
1994 for (MachineBasicBlock *Pred : Top->predecessors()) {
1995 BlockChain *PredChain = BlockToChain[Pred];
1996 if (!LoopBlockSet.count(Pred) &&
1997 (!PredChain || Pred == *std::prev(PredChain->end()))) {
1998 // Found a Pred block can be placed before Top.
1999 // Check if Top is the best successor of Pred.
2000 auto TopProb = MBPI->getEdgeProbability(Pred, Top);
2001 bool TopOK = true;
2002 for (MachineBasicBlock *Succ : Pred->successors()) {
2003 auto SuccProb = MBPI->getEdgeProbability(Pred, Succ);
2004 BlockChain *SuccChain = BlockToChain[Succ];
2005 // Check if Succ can be placed after Pred.
2006 // Succ should not be in any chain, or it is the head of some chain.
2007 if ((!SuccChain || Succ == *SuccChain->begin()) && SuccProb > TopProb) {
2008 TopOK = false;
2009 break;
2010 }
2011 }
2012 if (TopOK)
2013 return true;
2014 }
2015 }
2016 return false;
2017}
2018
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002019/// Attempt to rotate an exiting block to the bottom of the loop.
Chandler Carruth8c74c7b2012-04-16 09:31:23 +00002020///
2021/// Once we have built a chain, try to rotate it to line up the hot exit block
2022/// with fallthrough out of the loop if doing so doesn't introduce unnecessary
2023/// branches. For example, if the loop has fallthrough into its header and out
2024/// of its bottom already, don't rotate it.
2025void MachineBlockPlacement::rotateLoop(BlockChain &LoopChain,
Kyle Butte9425c4f2017-02-04 02:26:32 +00002026 const MachineBasicBlock *ExitingBB,
Chandler Carruth8c74c7b2012-04-16 09:31:23 +00002027 const BlockFilterSet &LoopBlockSet) {
2028 if (!ExitingBB)
2029 return;
2030
2031 MachineBasicBlock *Top = *LoopChain.begin();
Serguei Katkov0e831c92017-07-11 08:34:58 +00002032 MachineBasicBlock *Bottom = *std::prev(LoopChain.end());
2033
2034 // If ExitingBB is already the last one in a chain then nothing to do.
2035 if (Bottom == ExitingBB)
2036 return;
2037
Guozhi Wei4c8e4802019-02-22 18:04:37 +00002038 bool ViableTopFallthrough = hasViableTopFallthrough(Top, LoopBlockSet);
Chandler Carruth8c74c7b2012-04-16 09:31:23 +00002039
2040 // If the header has viable fallthrough, check whether the current loop
2041 // bottom is a viable exiting block. If so, bail out as rotating will
2042 // introduce an unnecessary branch.
2043 if (ViableTopFallthrough) {
Chandler Carruth7a715da2015-03-05 03:19:05 +00002044 for (MachineBasicBlock *Succ : Bottom->successors()) {
2045 BlockChain *SuccChain = BlockToChain[Succ];
2046 if (!LoopBlockSet.count(Succ) &&
2047 (!SuccChain || Succ == *SuccChain->begin()))
Chandler Carruth8c74c7b2012-04-16 09:31:23 +00002048 return;
2049 }
2050 }
2051
Eugene Zelenko5df3d892017-08-24 21:21:39 +00002052 BlockChain::iterator ExitIt = llvm::find(LoopChain, ExitingBB);
Chandler Carruth8c74c7b2012-04-16 09:31:23 +00002053 if (ExitIt == LoopChain.end())
2054 return;
2055
Serguei Katkov0e831c92017-07-11 08:34:58 +00002056 // Rotating a loop exit to the bottom when there is a fallthrough to top
2057 // trades the entry fallthrough for an exit fallthrough.
2058 // If there is no bottom->top edge, but the chosen exit block does have
2059 // a fallthrough, we break that fallthrough for nothing in return.
2060
2061 // Let's consider an example. We have a built chain of basic blocks
2062 // B1, B2, ..., Bn, where Bk is a ExitingBB - chosen exit block.
2063 // By doing a rotation we get
2064 // Bk+1, ..., Bn, B1, ..., Bk
2065 // Break of fallthrough to B1 is compensated by a fallthrough from Bk.
2066 // If we had a fallthrough Bk -> Bk+1 it is broken now.
2067 // It might be compensated by fallthrough Bn -> B1.
2068 // So we have a condition to avoid creation of extra branch by loop rotation.
2069 // All below must be true to avoid loop rotation:
2070 // If there is a fallthrough to top (B1)
2071 // There was fallthrough from chosen exit block (Bk) to next one (Bk+1)
2072 // There is no fallthrough from bottom (Bn) to top (B1).
2073 // Please note that there is no exit fallthrough from Bn because we checked it
2074 // above.
2075 if (ViableTopFallthrough) {
2076 assert(std::next(ExitIt) != LoopChain.end() &&
2077 "Exit should not be last BB");
2078 MachineBasicBlock *NextBlockInChain = *std::next(ExitIt);
2079 if (ExitingBB->isSuccessor(NextBlockInChain))
2080 if (!Bottom->isSuccessor(Top))
2081 return;
2082 }
2083
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002084 LLVM_DEBUG(dbgs() << "Rotating loop to put exit " << getBlockName(ExitingBB)
2085 << " at bottom\n");
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00002086 std::rotate(LoopChain.begin(), std::next(ExitIt), LoopChain.end());
Chandler Carruth8c74c7b2012-04-16 09:31:23 +00002087}
2088
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002089/// Attempt to rotate a loop based on profile data to reduce branch cost.
Cong Hou7745dbc2015-10-19 23:16:40 +00002090///
2091/// With profile data, we can determine the cost in terms of missed fall through
2092/// opportunities when rotating a loop chain and select the best rotation.
2093/// Basically, there are three kinds of cost to consider for each rotation:
2094/// 1. The possibly missed fall through edge (if it exists) from BB out of
2095/// the loop to the loop header.
2096/// 2. The possibly missed fall through edges (if they exist) from the loop
2097/// exits to BB out of the loop.
2098/// 3. The missed fall through edge (if it exists) from the last BB to the
2099/// first BB in the loop chain.
2100/// Therefore, the cost for a given rotation is the sum of costs listed above.
2101/// We select the best rotation with the smallest cost.
2102void MachineBlockPlacement::rotateLoopWithProfile(
Kyle Butte9425c4f2017-02-04 02:26:32 +00002103 BlockChain &LoopChain, const MachineLoop &L,
2104 const BlockFilterSet &LoopBlockSet) {
Cong Hou7745dbc2015-10-19 23:16:40 +00002105 auto HeaderBB = L.getHeader();
Eugene Zelenko5df3d892017-08-24 21:21:39 +00002106 auto HeaderIter = llvm::find(LoopChain, HeaderBB);
Cong Hou7745dbc2015-10-19 23:16:40 +00002107 auto RotationPos = LoopChain.end();
2108
2109 BlockFrequency SmallestRotationCost = BlockFrequency::getMaxFrequency();
2110
2111 // A utility lambda that scales up a block frequency by dividing it by a
2112 // branch probability which is the reciprocal of the scale.
2113 auto ScaleBlockFrequency = [](BlockFrequency Freq,
2114 unsigned Scale) -> BlockFrequency {
2115 if (Scale == 0)
2116 return 0;
2117 // Use operator / between BlockFrequency and BranchProbability to implement
2118 // saturating multiplication.
2119 return Freq / BranchProbability(1, Scale);
2120 };
2121
2122 // Compute the cost of the missed fall-through edge to the loop header if the
2123 // chain head is not the loop header. As we only consider natural loops with
2124 // single header, this computation can be done only once.
2125 BlockFrequency HeaderFallThroughCost(0);
2126 for (auto *Pred : HeaderBB->predecessors()) {
2127 BlockChain *PredChain = BlockToChain[Pred];
2128 if (!LoopBlockSet.count(Pred) &&
2129 (!PredChain || Pred == *std::prev(PredChain->end()))) {
2130 auto EdgeFreq =
2131 MBFI->getBlockFreq(Pred) * MBPI->getEdgeProbability(Pred, HeaderBB);
2132 auto FallThruCost = ScaleBlockFrequency(EdgeFreq, MisfetchCost);
2133 // If the predecessor has only an unconditional jump to the header, we
2134 // need to consider the cost of this jump.
2135 if (Pred->succ_size() == 1)
2136 FallThruCost += ScaleBlockFrequency(EdgeFreq, JumpInstCost);
2137 HeaderFallThroughCost = std::max(HeaderFallThroughCost, FallThruCost);
2138 }
2139 }
2140
2141 // Here we collect all exit blocks in the loop, and for each exit we find out
2142 // its hottest exit edge. For each loop rotation, we define the loop exit cost
2143 // as the sum of frequencies of exit edges we collect here, excluding the exit
2144 // edge from the tail of the loop chain.
2145 SmallVector<std::pair<MachineBasicBlock *, BlockFrequency>, 4> ExitsWithFreq;
2146 for (auto BB : LoopChain) {
Cong Houd97c1002015-12-01 05:29:22 +00002147 auto LargestExitEdgeProb = BranchProbability::getZero();
Cong Hou7745dbc2015-10-19 23:16:40 +00002148 for (auto *Succ : BB->successors()) {
2149 BlockChain *SuccChain = BlockToChain[Succ];
2150 if (!LoopBlockSet.count(Succ) &&
2151 (!SuccChain || Succ == *SuccChain->begin())) {
Cong Houd97c1002015-12-01 05:29:22 +00002152 auto SuccProb = MBPI->getEdgeProbability(BB, Succ);
2153 LargestExitEdgeProb = std::max(LargestExitEdgeProb, SuccProb);
Cong Hou7745dbc2015-10-19 23:16:40 +00002154 }
2155 }
Cong Houd97c1002015-12-01 05:29:22 +00002156 if (LargestExitEdgeProb > BranchProbability::getZero()) {
2157 auto ExitFreq = MBFI->getBlockFreq(BB) * LargestExitEdgeProb;
Cong Hou7745dbc2015-10-19 23:16:40 +00002158 ExitsWithFreq.emplace_back(BB, ExitFreq);
2159 }
2160 }
2161
2162 // In this loop we iterate every block in the loop chain and calculate the
2163 // cost assuming the block is the head of the loop chain. When the loop ends,
2164 // we should have found the best candidate as the loop chain's head.
2165 for (auto Iter = LoopChain.begin(), TailIter = std::prev(LoopChain.end()),
2166 EndIter = LoopChain.end();
2167 Iter != EndIter; Iter++, TailIter++) {
2168 // TailIter is used to track the tail of the loop chain if the block we are
2169 // checking (pointed by Iter) is the head of the chain.
2170 if (TailIter == LoopChain.end())
2171 TailIter = LoopChain.begin();
2172
2173 auto TailBB = *TailIter;
2174
2175 // Calculate the cost by putting this BB to the top.
2176 BlockFrequency Cost = 0;
2177
2178 // If the current BB is the loop header, we need to take into account the
2179 // cost of the missed fall through edge from outside of the loop to the
2180 // header.
2181 if (Iter != HeaderIter)
2182 Cost += HeaderFallThroughCost;
2183
2184 // Collect the loop exit cost by summing up frequencies of all exit edges
2185 // except the one from the chain tail.
2186 for (auto &ExitWithFreq : ExitsWithFreq)
2187 if (TailBB != ExitWithFreq.first)
2188 Cost += ExitWithFreq.second;
2189
2190 // The cost of breaking the once fall-through edge from the tail to the top
2191 // of the loop chain. Here we need to consider three cases:
2192 // 1. If the tail node has only one successor, then we will get an
2193 // additional jmp instruction. So the cost here is (MisfetchCost +
2194 // JumpInstCost) * tail node frequency.
2195 // 2. If the tail node has two successors, then we may still get an
2196 // additional jmp instruction if the layout successor after the loop
2197 // chain is not its CFG successor. Note that the more frequently executed
2198 // jmp instruction will be put ahead of the other one. Assume the
2199 // frequency of those two branches are x and y, where x is the frequency
2200 // of the edge to the chain head, then the cost will be
2201 // (x * MisfetechCost + min(x, y) * JumpInstCost) * tail node frequency.
2202 // 3. If the tail node has more than two successors (this rarely happens),
2203 // we won't consider any additional cost.
2204 if (TailBB->isSuccessor(*Iter)) {
2205 auto TailBBFreq = MBFI->getBlockFreq(TailBB);
2206 if (TailBB->succ_size() == 1)
2207 Cost += ScaleBlockFrequency(TailBBFreq.getFrequency(),
2208 MisfetchCost + JumpInstCost);
2209 else if (TailBB->succ_size() == 2) {
2210 auto TailToHeadProb = MBPI->getEdgeProbability(TailBB, *Iter);
2211 auto TailToHeadFreq = TailBBFreq * TailToHeadProb;
2212 auto ColderEdgeFreq = TailToHeadProb > BranchProbability(1, 2)
2213 ? TailBBFreq * TailToHeadProb.getCompl()
2214 : TailToHeadFreq;
2215 Cost += ScaleBlockFrequency(TailToHeadFreq, MisfetchCost) +
2216 ScaleBlockFrequency(ColderEdgeFreq, JumpInstCost);
2217 }
2218 }
2219
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002220 LLVM_DEBUG(dbgs() << "The cost of loop rotation by making "
2221 << getBlockName(*Iter)
2222 << " to the top: " << Cost.getFrequency() << "\n");
Cong Hou7745dbc2015-10-19 23:16:40 +00002223
2224 if (Cost < SmallestRotationCost) {
2225 SmallestRotationCost = Cost;
2226 RotationPos = Iter;
2227 }
2228 }
2229
2230 if (RotationPos != LoopChain.end()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002231 LLVM_DEBUG(dbgs() << "Rotate loop by making " << getBlockName(*RotationPos)
2232 << " to the top\n");
Cong Hou7745dbc2015-10-19 23:16:40 +00002233 std::rotate(LoopChain.begin(), RotationPos, LoopChain.end());
2234 }
2235}
2236
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002237/// Collect blocks in the given loop that are to be placed.
Cong Houb90b9e02015-11-02 21:24:00 +00002238///
2239/// When profile data is available, exclude cold blocks from the returned set;
2240/// otherwise, collect all blocks in the loop.
2241MachineBlockPlacement::BlockFilterSet
Kyle Butte9425c4f2017-02-04 02:26:32 +00002242MachineBlockPlacement::collectLoopBlockSet(const MachineLoop &L) {
Cong Houb90b9e02015-11-02 21:24:00 +00002243 BlockFilterSet LoopBlockSet;
2244
2245 // Filter cold blocks off from LoopBlockSet when profile data is available.
2246 // Collect the sum of frequencies of incoming edges to the loop header from
2247 // outside. If we treat the loop as a super block, this is the frequency of
2248 // the loop. Then for each block in the loop, we calculate the ratio between
2249 // its frequency and the frequency of the loop block. When it is too small,
2250 // don't add it to the loop chain. If there are outer loops, then this block
2251 // will be merged into the first outer loop chain for which this block is not
2252 // cold anymore. This needs precise profile data and we only do this when
2253 // profile data is available.
Easwaran Ramana17f2202017-12-22 01:33:52 +00002254 if (F->getFunction().hasProfileData() || ForceLoopColdBlock) {
Cong Houb90b9e02015-11-02 21:24:00 +00002255 BlockFrequency LoopFreq(0);
2256 for (auto LoopPred : L.getHeader()->predecessors())
2257 if (!L.contains(LoopPred))
2258 LoopFreq += MBFI->getBlockFreq(LoopPred) *
2259 MBPI->getEdgeProbability(LoopPred, L.getHeader());
2260
2261 for (MachineBasicBlock *LoopBB : L.getBlocks()) {
2262 auto Freq = MBFI->getBlockFreq(LoopBB).getFrequency();
2263 if (Freq == 0 || LoopFreq.getFrequency() / Freq > LoopToColdBlockRatio)
2264 continue;
2265 LoopBlockSet.insert(LoopBB);
2266 }
2267 } else
2268 LoopBlockSet.insert(L.block_begin(), L.block_end());
2269
2270 return LoopBlockSet;
2271}
2272
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002273/// Forms basic block chains from the natural loop structures.
Chandler Carruth10281422011-10-21 06:46:38 +00002274///
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00002275/// These chains are designed to preserve the existing *structure* of the code
2276/// as much as possible. We can then stitch the chains together in a way which
2277/// both preserves the topological structure and minimizes taken conditional
2278/// branches.
Kyle Butte9425c4f2017-02-04 02:26:32 +00002279void MachineBlockPlacement::buildLoopChains(const MachineLoop &L) {
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00002280 // First recurse through any nested loops, building chains for those inner
2281 // loops.
Kyle Butte9425c4f2017-02-04 02:26:32 +00002282 for (const MachineLoop *InnerLoop : L)
Xinliang David Li52530a72016-06-13 22:23:44 +00002283 buildLoopChains(*InnerLoop);
Chandler Carruth10281422011-10-21 06:46:38 +00002284
Kyle Butt0cf5b2f2017-05-17 23:44:41 +00002285 assert(BlockWorkList.empty() &&
2286 "BlockWorkList not empty when starting to build loop chains.");
2287 assert(EHPadWorkList.empty() &&
2288 "EHPadWorkList not empty when starting to build loop chains.");
Xinliang David Li52530a72016-06-13 22:23:44 +00002289 BlockFilterSet LoopBlockSet = collectLoopBlockSet(L);
Chandler Carruth03adbd42011-11-27 13:34:33 +00002290
Cong Hou7745dbc2015-10-19 23:16:40 +00002291 // Check if we have profile data for this function. If yes, we will rotate
2292 // this loop by modeling costs more precisely which requires the profile data
2293 // for better layout.
2294 bool RotateLoopWithProfile =
Xinliang David Lif0ab6df2016-05-12 02:04:41 +00002295 ForcePreciseRotationCost ||
Easwaran Ramana17f2202017-12-22 01:33:52 +00002296 (PreciseRotationCost && F->getFunction().hasProfileData());
Cong Hou7745dbc2015-10-19 23:16:40 +00002297
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00002298 // First check to see if there is an obviously preferable top block for the
2299 // loop. This will default to the header, but may end up as one of the
2300 // predecessors to the header if there is one which will result in strictly
2301 // fewer branches in the loop body.
Cong Hou7745dbc2015-10-19 23:16:40 +00002302 // When we use profile data to rotate the loop, this is unnecessary.
2303 MachineBasicBlock *LoopTop =
2304 RotateLoopWithProfile ? L.getHeader() : findBestLoopTop(L, LoopBlockSet);
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00002305
2306 // If we selected just the header for the loop top, look for a potentially
2307 // profitable exit block in the event that rotating the loop can eliminate
2308 // branches by placing an exit edge at the bottom.
Xin Tongd8d97972017-10-04 21:39:25 +00002309 //
2310 // Loops are processed innermost to uttermost, make sure we clear
2311 // PreferredLoopExit before processing a new loop.
2312 PreferredLoopExit = nullptr;
Cong Hou7745dbc2015-10-19 23:16:40 +00002313 if (!RotateLoopWithProfile && LoopTop == L.getHeader())
Kyle Buttab9cca72016-10-27 21:37:20 +00002314 PreferredLoopExit = findBestLoopExit(L, LoopBlockSet);
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00002315
2316 BlockChain &LoopChain = *BlockToChain[LoopTop];
Chandler Carruth10281422011-10-21 06:46:38 +00002317
Chandler Carruth8d150782011-11-13 11:20:44 +00002318 // FIXME: This is a really lame way of walking the chains in the loop: we
2319 // walk the blocks, and use a set to prevent visiting a particular chain
2320 // twice.
Jakub Staszak90616162011-12-21 23:02:08 +00002321 SmallPtrSet<BlockChain *, 4> UpdatedPreds;
Kyle Butt0cf5b2f2017-05-17 23:44:41 +00002322 assert(LoopChain.UnscheduledPredecessors == 0 &&
2323 "LoopChain should not have unscheduled predecessors.");
Jakub Staszak190c7122011-12-07 19:46:10 +00002324 UpdatedPreds.insert(&LoopChain);
Cong Houb90b9e02015-11-02 21:24:00 +00002325
Kyle Butte9425c4f2017-02-04 02:26:32 +00002326 for (const MachineBasicBlock *LoopBB : LoopBlockSet)
Xinliang David Li93926ac2016-07-01 05:46:48 +00002327 fillWorkLists(LoopBB, UpdatedPreds, &LoopBlockSet);
Chandler Carruth8d150782011-11-13 11:20:44 +00002328
Xinliang David Li93926ac2016-07-01 05:46:48 +00002329 buildChain(LoopTop, LoopChain, &LoopBlockSet);
Cong Hou7745dbc2015-10-19 23:16:40 +00002330
2331 if (RotateLoopWithProfile)
2332 rotateLoopWithProfile(LoopChain, L, LoopBlockSet);
2333 else
Kyle Buttab9cca72016-10-27 21:37:20 +00002334 rotateLoop(LoopChain, PreferredLoopExit, LoopBlockSet);
Chandler Carruth8d150782011-11-13 11:20:44 +00002335
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002336 LLVM_DEBUG({
Chandler Carruth8e1d9062011-11-13 21:39:51 +00002337 // Crash at the end so we get all of the debugging output first.
2338 bool BadLoop = false;
Philip Reamesae27b232016-03-03 00:58:43 +00002339 if (LoopChain.UnscheduledPredecessors) {
Chandler Carruth8e1d9062011-11-13 21:39:51 +00002340 BadLoop = true;
Chandler Carruth8d150782011-11-13 11:20:44 +00002341 dbgs() << "Loop chain contains a block without its preds placed!\n"
2342 << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
2343 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n";
Chandler Carruth8e1d9062011-11-13 21:39:51 +00002344 }
Chandler Carruth7a715da2015-03-05 03:19:05 +00002345 for (MachineBasicBlock *ChainBB : LoopChain) {
2346 dbgs() << " ... " << getBlockName(ChainBB) << "\n";
Rong Xu66827422016-11-16 20:50:06 +00002347 if (!LoopBlockSet.remove(ChainBB)) {
Chandler Carruth0a31d142011-11-14 10:55:53 +00002348 // We don't mark the loop as bad here because there are real situations
2349 // where this can occur. For example, with an unanalyzable fallthrough
Chandler Carruth99fe42f2011-11-23 10:35:36 +00002350 // from a loop block to a non-loop block or vice versa.
Chandler Carruth8d150782011-11-13 11:20:44 +00002351 dbgs() << "Loop chain contains a block not contained by the loop!\n"
2352 << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
2353 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
Chandler Carruth7a715da2015-03-05 03:19:05 +00002354 << " Bad block: " << getBlockName(ChainBB) << "\n";
Chandler Carruth8e1d9062011-11-13 21:39:51 +00002355 }
Chandler Carruthccc7e422012-04-16 01:12:56 +00002356 }
Chandler Carruth8d150782011-11-13 11:20:44 +00002357
Chandler Carruth8e1d9062011-11-13 21:39:51 +00002358 if (!LoopBlockSet.empty()) {
2359 BadLoop = true;
Kyle Butte9425c4f2017-02-04 02:26:32 +00002360 for (const MachineBasicBlock *LoopBB : LoopBlockSet)
Chandler Carruth8d150782011-11-13 11:20:44 +00002361 dbgs() << "Loop contains blocks never placed into a chain!\n"
2362 << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
2363 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
Chandler Carruth7a715da2015-03-05 03:19:05 +00002364 << " Bad block: " << getBlockName(LoopBB) << "\n";
Chandler Carruth8e1d9062011-11-13 21:39:51 +00002365 }
2366 assert(!BadLoop && "Detected problems with the placement of this loop.");
Chandler Carruth8d150782011-11-13 11:20:44 +00002367 });
Xinliang David Li93926ac2016-07-01 05:46:48 +00002368
2369 BlockWorkList.clear();
2370 EHPadWorkList.clear();
Chandler Carruth10281422011-10-21 06:46:38 +00002371}
2372
Xinliang David Li52530a72016-06-13 22:23:44 +00002373void MachineBlockPlacement::buildCFGChains() {
Chandler Carruth8d150782011-11-13 11:20:44 +00002374 // Ensure that every BB in the function has an associated chain to simplify
2375 // the assumptions of the remaining algorithm.
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +00002376 SmallVector<MachineOperand, 4> Cond; // For AnalyzeBranch.
Xinliang David Li52530a72016-06-13 22:23:44 +00002377 for (MachineFunction::iterator FI = F->begin(), FE = F->end(); FI != FE;
2378 ++FI) {
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +00002379 MachineBasicBlock *BB = &*FI;
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00002380 BlockChain *Chain =
2381 new (ChainAllocator.Allocate()) BlockChain(BlockToChain, BB);
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +00002382 // Also, merge any blocks which we cannot reason about and must preserve
2383 // the exact fallthrough behavior for.
Eugene Zelenko5df3d892017-08-24 21:21:39 +00002384 while (true) {
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +00002385 Cond.clear();
Craig Topperc0196b12014-04-14 00:51:57 +00002386 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
Jacques Pienaar71c30a12016-07-15 14:41:04 +00002387 if (!TII->analyzeBranch(*BB, TBB, FBB, Cond) || !FI->canFallThrough())
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +00002388 break;
2389
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +00002390 MachineFunction::iterator NextFI = std::next(FI);
2391 MachineBasicBlock *NextBB = &*NextFI;
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +00002392 // Ensure that the layout successor is a viable block, as we know that
2393 // fallthrough is a possibility.
2394 assert(NextFI != FE && "Can't fallthrough past the last block.");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002395 LLVM_DEBUG(dbgs() << "Pre-merging due to unanalyzable fallthrough: "
2396 << getBlockName(BB) << " -> " << getBlockName(NextBB)
2397 << "\n");
Craig Topperc0196b12014-04-14 00:51:57 +00002398 Chain->merge(NextBB, nullptr);
Hal Finkel34f9d6a2016-12-15 05:33:19 +00002399#ifndef NDEBUG
Sanjoy Dasd7389d62016-12-15 05:08:57 +00002400 BlocksWithUnanalyzableExits.insert(&*BB);
Hal Finkel34f9d6a2016-12-15 05:33:19 +00002401#endif
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +00002402 FI = NextFI;
2403 BB = NextBB;
2404 }
2405 }
Chandler Carruth8d150782011-11-13 11:20:44 +00002406
2407 // Build any loop-based chains.
Sam McCall2a36eee2016-11-01 22:02:14 +00002408 PreferredLoopExit = nullptr;
Chandler Carruth7a715da2015-03-05 03:19:05 +00002409 for (MachineLoop *L : *MLI)
Xinliang David Li52530a72016-06-13 22:23:44 +00002410 buildLoopChains(*L);
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00002411
Kyle Butt0cf5b2f2017-05-17 23:44:41 +00002412 assert(BlockWorkList.empty() &&
2413 "BlockWorkList should be empty before building final chain.");
2414 assert(EHPadWorkList.empty() &&
2415 "EHPadWorkList should be empty before building final chain.");
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00002416
Chandler Carruth8d150782011-11-13 11:20:44 +00002417 SmallPtrSet<BlockChain *, 4> UpdatedPreds;
Xinliang David Li52530a72016-06-13 22:23:44 +00002418 for (MachineBasicBlock &MBB : *F)
Xinliang David Li93926ac2016-07-01 05:46:48 +00002419 fillWorkLists(&MBB, UpdatedPreds);
Chandler Carruth8d150782011-11-13 11:20:44 +00002420
Xinliang David Li52530a72016-06-13 22:23:44 +00002421 BlockChain &FunctionChain = *BlockToChain[&F->front()];
Xinliang David Li93926ac2016-07-01 05:46:48 +00002422 buildChain(&F->front(), FunctionChain);
Chandler Carruth8d150782011-11-13 11:20:44 +00002423
Matt Arsenault0f5f0152013-12-10 18:55:37 +00002424#ifndef NDEBUG
Eugene Zelenko5df3d892017-08-24 21:21:39 +00002425 using FunctionBlockSetType = SmallPtrSet<MachineBasicBlock *, 16>;
Matt Arsenault0f5f0152013-12-10 18:55:37 +00002426#endif
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002427 LLVM_DEBUG({
Chandler Carruth8e1d9062011-11-13 21:39:51 +00002428 // Crash at the end so we get all of the debugging output first.
2429 bool BadFunc = false;
Chandler Carruth8d150782011-11-13 11:20:44 +00002430 FunctionBlockSetType FunctionBlockSet;
Xinliang David Li52530a72016-06-13 22:23:44 +00002431 for (MachineBasicBlock &MBB : *F)
Chandler Carruth7a715da2015-03-05 03:19:05 +00002432 FunctionBlockSet.insert(&MBB);
Chandler Carruth8d150782011-11-13 11:20:44 +00002433
Chandler Carruth7a715da2015-03-05 03:19:05 +00002434 for (MachineBasicBlock *ChainBB : FunctionChain)
2435 if (!FunctionBlockSet.erase(ChainBB)) {
Chandler Carruth8e1d9062011-11-13 21:39:51 +00002436 BadFunc = true;
Chandler Carruth8d150782011-11-13 11:20:44 +00002437 dbgs() << "Function chain contains a block not in the function!\n"
Chandler Carruth7a715da2015-03-05 03:19:05 +00002438 << " Bad block: " << getBlockName(ChainBB) << "\n";
Chandler Carruth8e1d9062011-11-13 21:39:51 +00002439 }
Chandler Carruth8d150782011-11-13 11:20:44 +00002440
Chandler Carruth8e1d9062011-11-13 21:39:51 +00002441 if (!FunctionBlockSet.empty()) {
2442 BadFunc = true;
Chandler Carruth7a715da2015-03-05 03:19:05 +00002443 for (MachineBasicBlock *RemainingBB : FunctionBlockSet)
Chandler Carruth8d150782011-11-13 11:20:44 +00002444 dbgs() << "Function contains blocks never placed into a chain!\n"
Chandler Carruth7a715da2015-03-05 03:19:05 +00002445 << " Bad block: " << getBlockName(RemainingBB) << "\n";
Chandler Carruth8e1d9062011-11-13 21:39:51 +00002446 }
2447 assert(!BadFunc && "Detected problems with the block placement.");
Chandler Carruth8d150782011-11-13 11:20:44 +00002448 });
2449
2450 // Splice the blocks into place.
Xinliang David Li52530a72016-06-13 22:23:44 +00002451 MachineFunction::iterator InsertPos = F->begin();
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002452 LLVM_DEBUG(dbgs() << "[MBP] Function: " << F->getName() << "\n");
Chandler Carruth7a715da2015-03-05 03:19:05 +00002453 for (MachineBasicBlock *ChainBB : FunctionChain) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002454 LLVM_DEBUG(dbgs() << (ChainBB == *FunctionChain.begin() ? "Placing chain "
2455 : " ... ")
2456 << getBlockName(ChainBB) << "\n");
Chandler Carruth7a715da2015-03-05 03:19:05 +00002457 if (InsertPos != MachineFunction::iterator(ChainBB))
Xinliang David Li52530a72016-06-13 22:23:44 +00002458 F->splice(InsertPos, ChainBB);
Chandler Carruth8d150782011-11-13 11:20:44 +00002459 else
2460 ++InsertPos;
2461
2462 // Update the terminator of the previous block.
Chandler Carruth7a715da2015-03-05 03:19:05 +00002463 if (ChainBB == *FunctionChain.begin())
Chandler Carruth8d150782011-11-13 11:20:44 +00002464 continue;
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +00002465 MachineBasicBlock *PrevBB = &*std::prev(MachineFunction::iterator(ChainBB));
Chandler Carruth8d150782011-11-13 11:20:44 +00002466
Chandler Carruth10281422011-10-21 06:46:38 +00002467 // FIXME: It would be awesome of updateTerminator would just return rather
2468 // than assert when the branch cannot be analyzed in order to remove this
2469 // boiler plate.
2470 Cond.clear();
Craig Topperc0196b12014-04-14 00:51:57 +00002471 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
Shuxin Yang8b8fd212013-06-04 01:00:57 +00002472
Sanjoy Dasd7389d62016-12-15 05:08:57 +00002473#ifndef NDEBUG
2474 if (!BlocksWithUnanalyzableExits.count(PrevBB)) {
2475 // Given the exact block placement we chose, we may actually not _need_ to
2476 // be able to edit PrevBB's terminator sequence, but not being _able_ to
2477 // do that at this point is a bug.
2478 assert((!TII->analyzeBranch(*PrevBB, TBB, FBB, Cond) ||
2479 !PrevBB->canFallThrough()) &&
2480 "Unexpected block with un-analyzable fallthrough!");
2481 Cond.clear();
2482 TBB = FBB = nullptr;
2483 }
2484#endif
2485
Haicheng Wu90a55652016-05-24 22:16:14 +00002486 // The "PrevBB" is not yet updated to reflect current code layout, so,
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00002487 // o. it may fall-through to a block without explicit "goto" instruction
Haicheng Wu90a55652016-05-24 22:16:14 +00002488 // before layout, and no longer fall-through it after layout; or
2489 // o. just opposite.
2490 //
Jacques Pienaar71c30a12016-07-15 14:41:04 +00002491 // analyzeBranch() may return erroneous value for FBB when these two
Haicheng Wu90a55652016-05-24 22:16:14 +00002492 // situations take place. For the first scenario FBB is mistakenly set NULL;
2493 // for the 2nd scenario, the FBB, which is expected to be NULL, is
2494 // mistakenly pointing to "*BI".
2495 // Thus, if the future change needs to use FBB before the layout is set, it
2496 // has to correct FBB first by using the code similar to the following:
2497 //
2498 // if (!Cond.empty() && (!FBB || FBB == ChainBB)) {
2499 // PrevBB->updateTerminator();
2500 // Cond.clear();
2501 // TBB = FBB = nullptr;
Jacques Pienaar71c30a12016-07-15 14:41:04 +00002502 // if (TII->analyzeBranch(*PrevBB, TBB, FBB, Cond)) {
Haicheng Wu90a55652016-05-24 22:16:14 +00002503 // // FIXME: This should never take place.
2504 // TBB = FBB = nullptr;
2505 // }
2506 // }
Jacques Pienaar71c30a12016-07-15 14:41:04 +00002507 if (!TII->analyzeBranch(*PrevBB, TBB, FBB, Cond))
Haicheng Wu90a55652016-05-24 22:16:14 +00002508 PrevBB->updateTerminator();
Chandler Carruth10281422011-10-21 06:46:38 +00002509 }
Chandler Carruth8d150782011-11-13 11:20:44 +00002510
2511 // Fixup the last block.
2512 Cond.clear();
Craig Topperc0196b12014-04-14 00:51:57 +00002513 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
Jacques Pienaar71c30a12016-07-15 14:41:04 +00002514 if (!TII->analyzeBranch(F->back(), TBB, FBB, Cond))
Xinliang David Li52530a72016-06-13 22:23:44 +00002515 F->back().updateTerminator();
Xinliang David Li93926ac2016-07-01 05:46:48 +00002516
2517 BlockWorkList.clear();
2518 EHPadWorkList.clear();
Haicheng Wu90a55652016-05-24 22:16:14 +00002519}
2520
Xinliang David Li52530a72016-06-13 22:23:44 +00002521void MachineBlockPlacement::optimizeBranches() {
2522 BlockChain &FunctionChain = *BlockToChain[&F->front()];
Haicheng Wu90a55652016-05-24 22:16:14 +00002523 SmallVector<MachineOperand, 4> Cond; // For AnalyzeBranch.
Quentin Colombet776e6de2016-05-02 22:58:59 +00002524
2525 // Now that all the basic blocks in the chain have the proper layout,
2526 // make a final call to AnalyzeBranch with AllowModify set.
2527 // Indeed, the target may be able to optimize the branches in a way we
2528 // cannot because all branches may not be analyzable.
2529 // E.g., the target may be able to remove an unconditional branch to
2530 // a fallthrough when it occurs after predicated terminators.
2531 for (MachineBasicBlock *ChainBB : FunctionChain) {
2532 Cond.clear();
Haicheng Wu90a55652016-05-24 22:16:14 +00002533 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
Jacques Pienaar71c30a12016-07-15 14:41:04 +00002534 if (!TII->analyzeBranch(*ChainBB, TBB, FBB, Cond, /*AllowModify*/ true)) {
Haicheng Wu90a55652016-05-24 22:16:14 +00002535 // If PrevBB has a two-way branch, try to re-order the branches
2536 // such that we branch to the successor with higher probability first.
2537 if (TBB && !Cond.empty() && FBB &&
2538 MBPI->getEdgeProbability(ChainBB, FBB) >
2539 MBPI->getEdgeProbability(ChainBB, TBB) &&
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +00002540 !TII->reverseBranchCondition(Cond)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002541 LLVM_DEBUG(dbgs() << "Reverse order of the two branches: "
2542 << getBlockName(ChainBB) << "\n");
2543 LLVM_DEBUG(dbgs() << " Edge probability: "
2544 << MBPI->getEdgeProbability(ChainBB, FBB) << " vs "
2545 << MBPI->getEdgeProbability(ChainBB, TBB) << "\n");
Haicheng Wu90a55652016-05-24 22:16:14 +00002546 DebugLoc dl; // FIXME: this is nowhere
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +00002547 TII->removeBranch(*ChainBB);
Matt Arsenaulte8e0f5c2016-09-14 17:24:15 +00002548 TII->insertBranch(*ChainBB, FBB, TBB, Cond, dl);
Haicheng Wu90a55652016-05-24 22:16:14 +00002549 ChainBB->updateTerminator();
2550 }
2551 }
Quentin Colombet776e6de2016-05-02 22:58:59 +00002552 }
Haicheng Wue749ce52016-04-29 17:06:44 +00002553}
Chandler Carruth10281422011-10-21 06:46:38 +00002554
Xinliang David Li52530a72016-06-13 22:23:44 +00002555void MachineBlockPlacement::alignBlocks() {
Chandler Carruthccc7e422012-04-16 01:12:56 +00002556 // Walk through the backedges of the function now that we have fully laid out
2557 // the basic blocks and align the destination of each backedge. We don't rely
Chandler Carruth881d0a72012-08-07 09:45:24 +00002558 // exclusively on the loop info here so that we can align backedges in
2559 // unnatural CFGs and backedges that were introduced purely because of the
2560 // loop rotations done during this layout pass.
Evandro Menezes85bd3972019-04-04 22:40:06 +00002561 if (F->getFunction().hasMinSize() ||
2562 (F->getFunction().hasOptSize() && !TLI->alignLoopsWithOptSize()))
Chandler Carruth8b9737c2011-10-21 08:57:37 +00002563 return;
Xinliang David Li52530a72016-06-13 22:23:44 +00002564 BlockChain &FunctionChain = *BlockToChain[&F->front()];
Chandler Carruth881d0a72012-08-07 09:45:24 +00002565 if (FunctionChain.begin() == FunctionChain.end())
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00002566 return; // Empty chain.
Chandler Carruth8b9737c2011-10-21 08:57:37 +00002567
Chandler Carruth881d0a72012-08-07 09:45:24 +00002568 const BranchProbability ColdProb(1, 5); // 20%
Xinliang David Li52530a72016-06-13 22:23:44 +00002569 BlockFrequency EntryFreq = MBFI->getBlockFreq(&F->front());
Chandler Carruth881d0a72012-08-07 09:45:24 +00002570 BlockFrequency WeightedEntryFreq = EntryFreq * ColdProb;
Chandler Carruth7a715da2015-03-05 03:19:05 +00002571 for (MachineBasicBlock *ChainBB : FunctionChain) {
2572 if (ChainBB == *FunctionChain.begin())
2573 continue;
2574
Chandler Carruth881d0a72012-08-07 09:45:24 +00002575 // Don't align non-looping basic blocks. These are unlikely to execute
2576 // enough times to matter in practice. Note that we'll still handle
2577 // unnatural CFGs inside of a natural outer loop (the common case) and
2578 // rotated loops.
Chandler Carruth7a715da2015-03-05 03:19:05 +00002579 MachineLoop *L = MLI->getLoopFor(ChainBB);
Chandler Carruth881d0a72012-08-07 09:45:24 +00002580 if (!L)
2581 continue;
2582
Hal Finkel57725662015-01-03 17:58:24 +00002583 unsigned Align = TLI->getPrefLoopAlignment(L);
2584 if (!Align)
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00002585 continue; // Don't care about loop alignment.
Hal Finkel57725662015-01-03 17:58:24 +00002586
Chandler Carruth881d0a72012-08-07 09:45:24 +00002587 // If the block is cold relative to the function entry don't waste space
2588 // aligning it.
Chandler Carruth7a715da2015-03-05 03:19:05 +00002589 BlockFrequency Freq = MBFI->getBlockFreq(ChainBB);
Chandler Carruth881d0a72012-08-07 09:45:24 +00002590 if (Freq < WeightedEntryFreq)
2591 continue;
2592
2593 // If the block is cold relative to its loop header, don't align it
2594 // regardless of what edges into the block exist.
2595 MachineBasicBlock *LoopHeader = L->getHeader();
2596 BlockFrequency LoopHeaderFreq = MBFI->getBlockFreq(LoopHeader);
2597 if (Freq < (LoopHeaderFreq * ColdProb))
2598 continue;
2599
2600 // Check for the existence of a non-layout predecessor which would benefit
2601 // from aligning this block.
Chandler Carruth7a715da2015-03-05 03:19:05 +00002602 MachineBasicBlock *LayoutPred =
2603 &*std::prev(MachineFunction::iterator(ChainBB));
Chandler Carruth881d0a72012-08-07 09:45:24 +00002604
2605 // Force alignment if all the predecessors are jumps. We already checked
2606 // that the block isn't cold above.
Chandler Carruth7a715da2015-03-05 03:19:05 +00002607 if (!LayoutPred->isSuccessor(ChainBB)) {
2608 ChainBB->setAlignment(Align);
Chandler Carruth881d0a72012-08-07 09:45:24 +00002609 continue;
2610 }
2611
2612 // Align this block if the layout predecessor's edge into this block is
Nadav Rotem6036f582013-03-29 16:34:23 +00002613 // cold relative to the block. When this is true, other predecessors make up
Chandler Carruth881d0a72012-08-07 09:45:24 +00002614 // all of the hot entries into the block and thus alignment is likely to be
2615 // important.
Chandler Carruth7a715da2015-03-05 03:19:05 +00002616 BranchProbability LayoutProb =
2617 MBPI->getEdgeProbability(LayoutPred, ChainBB);
Chandler Carruth881d0a72012-08-07 09:45:24 +00002618 BlockFrequency LayoutEdgeFreq = MBFI->getBlockFreq(LayoutPred) * LayoutProb;
2619 if (LayoutEdgeFreq <= (Freq * ColdProb))
Chandler Carruth7a715da2015-03-05 03:19:05 +00002620 ChainBB->setAlignment(Align);
Chandler Carruthccc7e422012-04-16 01:12:56 +00002621 }
Chandler Carruth8b9737c2011-10-21 08:57:37 +00002622}
2623
Kyle Butt0846e562016-10-11 20:36:43 +00002624/// Tail duplicate \p BB into (some) predecessors if profitable, repeating if
2625/// it was duplicated into its chain predecessor and removed.
2626/// \p BB - Basic block that may be duplicated.
2627///
2628/// \p LPred - Chosen layout predecessor of \p BB.
2629/// Updated to be the chain end if LPred is removed.
2630/// \p Chain - Chain to which \p LPred belongs, and \p BB will belong.
2631/// \p BlockFilter - Set of blocks that belong to the loop being laid out.
2632/// Used to identify which blocks to update predecessor
2633/// counts.
2634/// \p PrevUnplacedBlockIt - Iterator pointing to the last block that was
2635/// chosen in the given order due to unnatural CFG
2636/// only needed if \p BB is removed and
2637/// \p PrevUnplacedBlockIt pointed to \p BB.
2638/// @return true if \p BB was removed.
2639bool MachineBlockPlacement::repeatedlyTailDuplicateBlock(
2640 MachineBasicBlock *BB, MachineBasicBlock *&LPred,
Kyle Butte9425c4f2017-02-04 02:26:32 +00002641 const MachineBasicBlock *LoopHeaderBB,
Kyle Butt0846e562016-10-11 20:36:43 +00002642 BlockChain &Chain, BlockFilterSet *BlockFilter,
2643 MachineFunction::iterator &PrevUnplacedBlockIt) {
2644 bool Removed, DuplicatedToLPred;
2645 bool DuplicatedToOriginalLPred;
2646 Removed = maybeTailDuplicateBlock(BB, LPred, Chain, BlockFilter,
2647 PrevUnplacedBlockIt,
2648 DuplicatedToLPred);
2649 if (!Removed)
2650 return false;
2651 DuplicatedToOriginalLPred = DuplicatedToLPred;
2652 // Iteratively try to duplicate again. It can happen that a block that is
2653 // duplicated into is still small enough to be duplicated again.
2654 // No need to call markBlockSuccessors in this case, as the blocks being
2655 // duplicated from here on are already scheduled.
2656 // Note that DuplicatedToLPred always implies Removed.
2657 while (DuplicatedToLPred) {
Eugene Zelenko5df3d892017-08-24 21:21:39 +00002658 assert(Removed && "Block must have been removed to be duplicated into its "
2659 "layout predecessor.");
Kyle Butt0846e562016-10-11 20:36:43 +00002660 MachineBasicBlock *DupBB, *DupPred;
2661 // The removal callback causes Chain.end() to be updated when a block is
2662 // removed. On the first pass through the loop, the chain end should be the
2663 // same as it was on function entry. On subsequent passes, because we are
2664 // duplicating the block at the end of the chain, if it is removed the
2665 // chain will have shrunk by one block.
2666 BlockChain::iterator ChainEnd = Chain.end();
2667 DupBB = *(--ChainEnd);
2668 // Now try to duplicate again.
2669 if (ChainEnd == Chain.begin())
2670 break;
2671 DupPred = *std::prev(ChainEnd);
2672 Removed = maybeTailDuplicateBlock(DupBB, DupPred, Chain, BlockFilter,
2673 PrevUnplacedBlockIt,
2674 DuplicatedToLPred);
2675 }
2676 // If BB was duplicated into LPred, it is now scheduled. But because it was
2677 // removed, markChainSuccessors won't be called for its chain. Instead we
2678 // call markBlockSuccessors for LPred to achieve the same effect. This must go
2679 // at the end because repeating the tail duplication can increase the number
2680 // of unscheduled predecessors.
2681 LPred = *std::prev(Chain.end());
2682 if (DuplicatedToOriginalLPred)
2683 markBlockSuccessors(Chain, LPred, LoopHeaderBB, BlockFilter);
2684 return true;
2685}
2686
2687/// Tail duplicate \p BB into (some) predecessors if profitable.
2688/// \p BB - Basic block that may be duplicated
2689/// \p LPred - Chosen layout predecessor of \p BB
2690/// \p Chain - Chain to which \p LPred belongs, and \p BB will belong.
2691/// \p BlockFilter - Set of blocks that belong to the loop being laid out.
2692/// Used to identify which blocks to update predecessor
2693/// counts.
2694/// \p PrevUnplacedBlockIt - Iterator pointing to the last block that was
2695/// chosen in the given order due to unnatural CFG
2696/// only needed if \p BB is removed and
2697/// \p PrevUnplacedBlockIt pointed to \p BB.
2698/// \p DuplicatedToLPred - True if the block was duplicated into LPred. Will
2699/// only be true if the block was removed.
2700/// \return - True if the block was duplicated into all preds and removed.
2701bool MachineBlockPlacement::maybeTailDuplicateBlock(
2702 MachineBasicBlock *BB, MachineBasicBlock *LPred,
Kyle Butte9425c4f2017-02-04 02:26:32 +00002703 BlockChain &Chain, BlockFilterSet *BlockFilter,
Kyle Butt0846e562016-10-11 20:36:43 +00002704 MachineFunction::iterator &PrevUnplacedBlockIt,
2705 bool &DuplicatedToLPred) {
Kyle Butt0846e562016-10-11 20:36:43 +00002706 DuplicatedToLPred = false;
Kyle Buttc7d67eef2017-02-04 02:26:34 +00002707 if (!shouldTailDuplicate(BB))
2708 return false;
2709
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002710 LLVM_DEBUG(dbgs() << "Redoing tail duplication for Succ#" << BB->getNumber()
2711 << "\n");
Kyle Buttb15c0662017-01-31 23:48:32 +00002712
Kyle Butt0846e562016-10-11 20:36:43 +00002713 // This has to be a callback because none of it can be done after
2714 // BB is deleted.
2715 bool Removed = false;
2716 auto RemovalCallback =
2717 [&](MachineBasicBlock *RemBB) {
2718 // Signal to outer function
2719 Removed = true;
2720
2721 // Conservative default.
2722 bool InWorkList = true;
2723 // Remove from the Chain and Chain Map
2724 if (BlockToChain.count(RemBB)) {
2725 BlockChain *Chain = BlockToChain[RemBB];
2726 InWorkList = Chain->UnscheduledPredecessors == 0;
2727 Chain->remove(RemBB);
2728 BlockToChain.erase(RemBB);
2729 }
2730
2731 // Handle the unplaced block iterator
2732 if (&(*PrevUnplacedBlockIt) == RemBB) {
2733 PrevUnplacedBlockIt++;
2734 }
2735
2736 // Handle the Work Lists
2737 if (InWorkList) {
2738 SmallVectorImpl<MachineBasicBlock *> &RemoveList = BlockWorkList;
2739 if (RemBB->isEHPad())
2740 RemoveList = EHPadWorkList;
2741 RemoveList.erase(
Eugene Zelenko5df3d892017-08-24 21:21:39 +00002742 llvm::remove_if(RemoveList,
2743 [RemBB](MachineBasicBlock *BB) {
2744 return BB == RemBB;
2745 }),
Kyle Butt0846e562016-10-11 20:36:43 +00002746 RemoveList.end());
2747 }
2748
2749 // Handle the filter set
2750 if (BlockFilter) {
Rong Xu66827422016-11-16 20:50:06 +00002751 BlockFilter->remove(RemBB);
Kyle Butt0846e562016-10-11 20:36:43 +00002752 }
2753
2754 // Remove the block from loop info.
2755 MLI->removeBlock(RemBB);
Kyle Buttab9cca72016-10-27 21:37:20 +00002756 if (RemBB == PreferredLoopExit)
2757 PreferredLoopExit = nullptr;
Kyle Butt0846e562016-10-11 20:36:43 +00002758
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002759 LLVM_DEBUG(dbgs() << "TailDuplicator deleted block: "
2760 << getBlockName(RemBB) << "\n");
Kyle Butt0846e562016-10-11 20:36:43 +00002761 };
2762 auto RemovalCallbackRef =
Eugene Zelenko5df3d892017-08-24 21:21:39 +00002763 function_ref<void(MachineBasicBlock*)>(RemovalCallback);
Kyle Butt0846e562016-10-11 20:36:43 +00002764
2765 SmallVector<MachineBasicBlock *, 8> DuplicatedPreds;
Kyle Buttb15c0662017-01-31 23:48:32 +00002766 bool IsSimple = TailDup.isSimpleBB(BB);
Kyle Butt0846e562016-10-11 20:36:43 +00002767 TailDup.tailDuplicateAndUpdate(IsSimple, BB, LPred,
2768 &DuplicatedPreds, &RemovalCallbackRef);
2769
2770 // Update UnscheduledPredecessors to reflect tail-duplication.
2771 DuplicatedToLPred = false;
2772 for (MachineBasicBlock *Pred : DuplicatedPreds) {
2773 // We're only looking for unscheduled predecessors that match the filter.
2774 BlockChain* PredChain = BlockToChain[Pred];
2775 if (Pred == LPred)
2776 DuplicatedToLPred = true;
2777 if (Pred == LPred || (BlockFilter && !BlockFilter->count(Pred))
2778 || PredChain == &Chain)
2779 continue;
2780 for (MachineBasicBlock *NewSucc : Pred->successors()) {
2781 if (BlockFilter && !BlockFilter->count(NewSucc))
2782 continue;
2783 BlockChain *NewChain = BlockToChain[NewSucc];
2784 if (NewChain != &Chain && NewChain != PredChain)
2785 NewChain->UnscheduledPredecessors++;
2786 }
2787 }
2788 return Removed;
2789}
2790
Xinliang David Li52530a72016-06-13 22:23:44 +00002791bool MachineBlockPlacement::runOnMachineFunction(MachineFunction &MF) {
Matthias Braunf1caa282017-12-15 22:22:58 +00002792 if (skipFunction(MF.getFunction()))
Andrew Kaylor50271f72016-05-03 22:32:30 +00002793 return false;
2794
Chandler Carruth10281422011-10-21 06:46:38 +00002795 // Check for single-block functions and skip them.
Xinliang David Li52530a72016-06-13 22:23:44 +00002796 if (std::next(MF.begin()) == MF.end())
Chandler Carruth10281422011-10-21 06:46:38 +00002797 return false;
2798
Xinliang David Li52530a72016-06-13 22:23:44 +00002799 F = &MF;
Chandler Carruth10281422011-10-21 06:46:38 +00002800 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
Haicheng Wu5b458cc2016-06-09 15:24:29 +00002801 MBFI = llvm::make_unique<BranchFolder::MBFIWrapper>(
2802 getAnalysis<MachineBlockFrequencyInfo>());
Chandler Carruth8b9737c2011-10-21 08:57:37 +00002803 MLI = &getAnalysis<MachineLoopInfo>();
Xinliang David Li52530a72016-06-13 22:23:44 +00002804 TII = MF.getSubtarget().getInstrInfo();
2805 TLI = MF.getSubtarget().getTargetLowering();
Kyle Buttb15c0662017-01-31 23:48:32 +00002806 MPDT = nullptr;
Eric Christopher690f8e52016-11-01 22:15:50 +00002807
2808 // Initialize PreferredLoopExit to nullptr here since it may never be set if
2809 // there are no MachineLoops.
2810 PreferredLoopExit = nullptr;
2811
Kyle Butt0cf5b2f2017-05-17 23:44:41 +00002812 assert(BlockToChain.empty() &&
2813 "BlockToChain map should be empty before starting placement.");
2814 assert(ComputedEdges.empty() &&
2815 "Computed Edge map should be empty before starting placement.");
Kyle Butt04300b032017-04-12 03:18:20 +00002816
Kyle Butt7d531da2017-05-15 17:30:47 +00002817 unsigned TailDupSize = TailDupPlacementThreshold;
2818 // If only the aggressive threshold is explicitly set, use it.
2819 if (TailDupPlacementAggressiveThreshold.getNumOccurrences() != 0 &&
2820 TailDupPlacementThreshold.getNumOccurrences() == 0)
2821 TailDupSize = TailDupPlacementAggressiveThreshold;
2822
2823 TargetPassConfig *PassConfig = &getAnalysis<TargetPassConfig>();
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00002824 // For aggressive optimization, we can adjust some thresholds to be less
Kyle Butt7d531da2017-05-15 17:30:47 +00002825 // conservative.
2826 if (PassConfig->getOptLevel() >= CodeGenOpt::Aggressive) {
2827 // At O3 we should be more willing to copy blocks for tail duplication. This
2828 // increases size pressure, so we only do it at O3
2829 // Do this unless only the regular threshold is explicitly set.
2830 if (TailDupPlacementThreshold.getNumOccurrences() == 0 ||
2831 TailDupPlacementAggressiveThreshold.getNumOccurrences() != 0)
2832 TailDupSize = TailDupPlacementAggressiveThreshold;
2833 }
2834
Tim Shen1a8c6772018-03-30 17:51:00 +00002835 if (allowTailDupPlacement()) {
Kyle Buttb15c0662017-01-31 23:48:32 +00002836 MPDT = &getAnalysis<MachinePostDominatorTree>();
Evandro Menezes85bd3972019-04-04 22:40:06 +00002837 if (MF.getFunction().hasOptSize())
Kyle Butt0846e562016-10-11 20:36:43 +00002838 TailDupSize = 1;
Matthias Braun8426d132017-08-23 03:17:59 +00002839 bool PreRegAlloc = false;
2840 TailDup.initMF(MF, PreRegAlloc, MBPI, /* LayoutMode */ true, TailDupSize);
Kyle Butt1fa60302017-03-03 01:00:22 +00002841 precomputeTriangleChains();
Kyle Butt0846e562016-10-11 20:36:43 +00002842 }
2843
Xinliang David Li52530a72016-06-13 22:23:44 +00002844 buildCFGChains();
Haicheng Wu5b458cc2016-06-09 15:24:29 +00002845
2846 // Changing the layout can create new tail merging opportunities.
Haicheng Wu5b458cc2016-06-09 15:24:29 +00002847 // TailMerge can create jump into if branches that make CFG irreducible for
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00002848 // HW that requires structured CFG.
Xinliang David Li52530a72016-06-13 22:23:44 +00002849 bool EnableTailMerge = !MF.getTarget().requiresStructuredCFG() &&
Haicheng Wu5b458cc2016-06-09 15:24:29 +00002850 PassConfig->getEnableTailMerge() &&
2851 BranchFoldPlacement;
2852 // No tail merging opportunities if the block number is less than four.
Xinliang David Li52530a72016-06-13 22:23:44 +00002853 if (MF.size() > 3 && EnableTailMerge) {
Kyle Butt7d531da2017-05-15 17:30:47 +00002854 unsigned TailMergeSize = TailDupSize + 1;
Haicheng Wu5b458cc2016-06-09 15:24:29 +00002855 BranchFolder BF(/*EnableTailMerge=*/true, /*CommonHoist=*/false, *MBFI,
Kyle Butt64e42812016-08-18 18:57:29 +00002856 *MBPI, TailMergeSize);
Haicheng Wu5b458cc2016-06-09 15:24:29 +00002857
Xinliang David Li52530a72016-06-13 22:23:44 +00002858 if (BF.OptimizeFunction(MF, TII, MF.getSubtarget().getRegisterInfo(),
Haicheng Wu5b458cc2016-06-09 15:24:29 +00002859 getAnalysisIfAvailable<MachineModuleInfo>(), MLI,
2860 /*AfterBlockPlacement=*/true)) {
2861 // Redo the layout if tail merging creates/removes/moves blocks.
2862 BlockToChain.clear();
Kyle Butt04300b032017-04-12 03:18:20 +00002863 ComputedEdges.clear();
Kyle Butt13937612017-03-02 21:44:24 +00002864 // Must redo the post-dominator tree if blocks were changed.
Kyle Buttb15c0662017-01-31 23:48:32 +00002865 if (MPDT)
2866 MPDT->runOnMachineFunction(MF);
Haicheng Wu5b458cc2016-06-09 15:24:29 +00002867 ChainAllocator.DestroyAll();
Xinliang David Li52530a72016-06-13 22:23:44 +00002868 buildCFGChains();
Haicheng Wu5b458cc2016-06-09 15:24:29 +00002869 }
2870 }
2871
Xinliang David Li52530a72016-06-13 22:23:44 +00002872 optimizeBranches();
2873 alignBlocks();
Chandler Carruth10281422011-10-21 06:46:38 +00002874
Chandler Carruth10281422011-10-21 06:46:38 +00002875 BlockToChain.clear();
Kyle Butt04300b032017-04-12 03:18:20 +00002876 ComputedEdges.clear();
Chandler Carruthfd9b4d92011-11-14 10:57:23 +00002877 ChainAllocator.DestroyAll();
Chandler Carruth10281422011-10-21 06:46:38 +00002878
Nadav Rotemc0adc9f2013-04-12 01:24:16 +00002879 if (AlignAllBlock)
2880 // Align all of the blocks in the function to a specific alignment.
Xinliang David Li52530a72016-06-13 22:23:44 +00002881 for (MachineBasicBlock &MBB : MF)
Chandler Carruth7a715da2015-03-05 03:19:05 +00002882 MBB.setAlignment(AlignAllBlock);
Geoff Berry10494ac2016-01-21 17:25:52 +00002883 else if (AlignAllNonFallThruBlocks) {
2884 // Align all of the blocks that have no fall-through predecessors to a
2885 // specific alignment.
Xinliang David Li52530a72016-06-13 22:23:44 +00002886 for (auto MBI = std::next(MF.begin()), MBE = MF.end(); MBI != MBE; ++MBI) {
Geoff Berry10494ac2016-01-21 17:25:52 +00002887 auto LayoutPred = std::prev(MBI);
2888 if (!LayoutPred->isSuccessor(&*MBI))
2889 MBI->setAlignment(AlignAllNonFallThruBlocks);
2890 }
2891 }
Xinliang David Lifd3f6452017-01-29 01:57:02 +00002892 if (ViewBlockLayoutWithBFI != GVDT_None &&
2893 (ViewBlockFreqFuncName.empty() ||
Matthias Braunf1caa282017-12-15 22:22:58 +00002894 F->getFunction().getName().equals(ViewBlockFreqFuncName))) {
Xinliang David Li538d6662017-02-15 19:21:04 +00002895 MBFI->view("MBP." + MF.getName(), false);
Xinliang David Lifd3f6452017-01-29 01:57:02 +00002896 }
Xinliang David Lifd3f6452017-01-29 01:57:02 +00002897
Nadav Rotemc0adc9f2013-04-12 01:24:16 +00002898
Chandler Carruth10281422011-10-21 06:46:38 +00002899 // We always return true as we have no way to track whether the final order
2900 // differs from the original order.
2901 return true;
2902}
Chandler Carruthae4e8002011-11-02 07:17:12 +00002903
2904namespace {
Eugene Zelenko5df3d892017-08-24 21:21:39 +00002905
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002906/// A pass to compute block placement statistics.
Chandler Carruthae4e8002011-11-02 07:17:12 +00002907///
2908/// A separate pass to compute interesting statistics for evaluating block
2909/// placement. This is separate from the actual placement pass so that they can
Benjamin Kramerbde91762012-06-02 10:20:22 +00002910/// be computed in the absence of any placement transformations or when using
Chandler Carruthae4e8002011-11-02 07:17:12 +00002911/// alternative placement strategies.
2912class MachineBlockPlacementStats : public MachineFunctionPass {
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002913 /// A handle to the branch probability pass.
Chandler Carruthae4e8002011-11-02 07:17:12 +00002914 const MachineBranchProbabilityInfo *MBPI;
2915
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002916 /// A handle to the function-wide block frequency pass.
Chandler Carruthae4e8002011-11-02 07:17:12 +00002917 const MachineBlockFrequencyInfo *MBFI;
2918
2919public:
2920 static char ID; // Pass identification, replacement for typeid
Eugene Zelenko5df3d892017-08-24 21:21:39 +00002921
Chandler Carruthae4e8002011-11-02 07:17:12 +00002922 MachineBlockPlacementStats() : MachineFunctionPass(ID) {
2923 initializeMachineBlockPlacementStatsPass(*PassRegistry::getPassRegistry());
2924 }
2925
Craig Topper4584cd52014-03-07 09:26:03 +00002926 bool runOnMachineFunction(MachineFunction &F) override;
Chandler Carruthae4e8002011-11-02 07:17:12 +00002927
Craig Topper4584cd52014-03-07 09:26:03 +00002928 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruthae4e8002011-11-02 07:17:12 +00002929 AU.addRequired<MachineBranchProbabilityInfo>();
2930 AU.addRequired<MachineBlockFrequencyInfo>();
2931 AU.setPreservesAll();
2932 MachineFunctionPass::getAnalysisUsage(AU);
2933 }
Chandler Carruthae4e8002011-11-02 07:17:12 +00002934};
Eugene Zelenko5df3d892017-08-24 21:21:39 +00002935
2936} // end anonymous namespace
Chandler Carruthae4e8002011-11-02 07:17:12 +00002937
2938char MachineBlockPlacementStats::ID = 0;
Eugene Zelenko5df3d892017-08-24 21:21:39 +00002939
Andrew Trick1fa5bcb2012-02-08 21:23:13 +00002940char &llvm::MachineBlockPlacementStatsID = MachineBlockPlacementStats::ID;
Eugene Zelenko5df3d892017-08-24 21:21:39 +00002941
Chandler Carruthae4e8002011-11-02 07:17:12 +00002942INITIALIZE_PASS_BEGIN(MachineBlockPlacementStats, "block-placement-stats",
2943 "Basic Block Placement Stats", false, false)
2944INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
2945INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
2946INITIALIZE_PASS_END(MachineBlockPlacementStats, "block-placement-stats",
2947 "Basic Block Placement Stats", false, false)
2948
Chandler Carruthae4e8002011-11-02 07:17:12 +00002949bool MachineBlockPlacementStats::runOnMachineFunction(MachineFunction &F) {
2950 // Check for single-block functions and skip them.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00002951 if (std::next(F.begin()) == F.end())
Chandler Carruthae4e8002011-11-02 07:17:12 +00002952 return false;
2953
2954 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
2955 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
2956
Chandler Carruth7a715da2015-03-05 03:19:05 +00002957 for (MachineBasicBlock &MBB : F) {
2958 BlockFrequency BlockFreq = MBFI->getBlockFreq(&MBB);
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00002959 Statistic &NumBranches =
Chandler Carruth7a715da2015-03-05 03:19:05 +00002960 (MBB.succ_size() > 1) ? NumCondBranches : NumUncondBranches;
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00002961 Statistic &BranchTakenFreq =
Chandler Carruth7a715da2015-03-05 03:19:05 +00002962 (MBB.succ_size() > 1) ? CondBranchTakenFreq : UncondBranchTakenFreq;
2963 for (MachineBasicBlock *Succ : MBB.successors()) {
Chandler Carruthae4e8002011-11-02 07:17:12 +00002964 // Skip if this successor is a fallthrough.
Chandler Carruth7a715da2015-03-05 03:19:05 +00002965 if (MBB.isLayoutSuccessor(Succ))
Chandler Carruthae4e8002011-11-02 07:17:12 +00002966 continue;
2967
Chandler Carruth7a715da2015-03-05 03:19:05 +00002968 BlockFrequency EdgeFreq =
2969 BlockFreq * MBPI->getEdgeProbability(&MBB, Succ);
Chandler Carruthae4e8002011-11-02 07:17:12 +00002970 ++NumBranches;
2971 BranchTakenFreq += EdgeFreq.getFrequency();
2972 }
2973 }
2974
2975 return false;
2976}