blob: 4fee9c4ea027f079c9dc11acbf17a4afa9994bf9 [file] [log] [blame]
Eugene Zelenko2de563a2017-08-24 21:21:39 +00001//===- MachineBlockPlacement.cpp - Basic Block Code Layout optimization ---===//
Chandler Carruthdb350872011-10-21 06:46:38 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Chandler Carruth30713632011-10-23 09:18:45 +000010// This file implements basic block placement transformations using the CFG
11// structure and branch probability estimates.
Chandler Carruthdb350872011-10-21 06:46:38 +000012//
Chandler Carruth30713632011-10-23 09:18:45 +000013// The pass strives to preserve the structure of the CFG (that is, retain
Benjamin Kramerd9b0b022012-06-02 10:20:22 +000014// a topological ordering of basic blocks) in the absence of a *strong* signal
Chandler Carruth30713632011-10-23 09:18:45 +000015// to the contrary from probabilities. However, within the CFG structure, it
16// attempts to choose an ordering which favors placing more likely sequences of
17// blocks adjacent to each other.
18//
19// The algorithm works from the inner-most loop within a function outward, and
20// at each stage walks through the basic blocks, trying to coalesce them into
21// sequential chains where allowed by the CFG (or demanded by heavy
22// probabilities). Finally, it walks the blocks in topological order, and the
23// first time it reaches a chain of basic blocks, it schedules them in the
24// function in-order.
Chandler Carruthdb350872011-10-21 06:46:38 +000025//
26//===----------------------------------------------------------------------===//
27
Haicheng Wuc4f22582016-06-09 15:24:29 +000028#include "BranchFolding.h"
Eugene Zelenko2de563a2017-08-24 21:21:39 +000029#include "llvm/ADT/ArrayRef.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000030#include "llvm/ADT/DenseMap.h"
Eugene Zelenko2de563a2017-08-24 21:21:39 +000031#include "llvm/ADT/STLExtras.h"
32#include "llvm/ADT/SetVector.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000033#include "llvm/ADT/SmallPtrSet.h"
34#include "llvm/ADT/SmallVector.h"
35#include "llvm/ADT/Statistic.h"
Xinliang David Li828b3982017-01-29 01:57:02 +000036#include "llvm/Analysis/BlockFrequencyInfoImpl.h"
Chandler Carruth4a85cc92011-10-21 08:57:37 +000037#include "llvm/CodeGen/MachineBasicBlock.h"
Chandler Carruthdb350872011-10-21 06:46:38 +000038#include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
39#include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
40#include "llvm/CodeGen/MachineFunction.h"
Chandler Carruthdb350872011-10-21 06:46:38 +000041#include "llvm/CodeGen/MachineFunctionPass.h"
Chandler Carruth4a85cc92011-10-21 08:57:37 +000042#include "llvm/CodeGen/MachineLoopInfo.h"
43#include "llvm/CodeGen/MachineModuleInfo.h"
Kyle Butt5818a512017-01-31 23:48:32 +000044#include "llvm/CodeGen/MachinePostDominators.h"
Kyle Butt2a180182016-10-11 20:36:43 +000045#include "llvm/CodeGen/TailDuplicator.h"
David Blaikie48319232017-11-08 01:01:31 +000046#include "llvm/CodeGen/TargetInstrInfo.h"
David Blaikiee3a9b4c2017-11-17 01:07:10 +000047#include "llvm/CodeGen/TargetLowering.h"
Chandler Carruthe3e43d92017-06-06 11:49:48 +000048#include "llvm/CodeGen/TargetPassConfig.h"
David Blaikiee3a9b4c2017-11-17 01:07:10 +000049#include "llvm/CodeGen/TargetSubtargetInfo.h"
Eugene Zelenko2de563a2017-08-24 21:21:39 +000050#include "llvm/IR/DebugLoc.h"
51#include "llvm/IR/Function.h"
52#include "llvm/Pass.h"
Chandler Carruthdb350872011-10-21 06:46:38 +000053#include "llvm/Support/Allocator.h"
Eugene Zelenko2de563a2017-08-24 21:21:39 +000054#include "llvm/Support/BlockFrequency.h"
55#include "llvm/Support/BranchProbability.h"
56#include "llvm/Support/CodeGen.h"
Nadav Rotem07706e52013-04-12 00:48:32 +000057#include "llvm/Support/CommandLine.h"
Eugene Zelenko2de563a2017-08-24 21:21:39 +000058#include "llvm/Support/Compiler.h"
Chandler Carruth30713632011-10-23 09:18:45 +000059#include "llvm/Support/Debug.h"
Benjamin Kramer1bfcd1f2015-03-23 19:32:43 +000060#include "llvm/Support/raw_ostream.h"
Eugene Zelenko2de563a2017-08-24 21:21:39 +000061#include "llvm/Target/TargetMachine.h"
Chandler Carruthdb350872011-10-21 06:46:38 +000062#include <algorithm>
Eugene Zelenko2de563a2017-08-24 21:21:39 +000063#include <cassert>
64#include <cstdint>
65#include <iterator>
66#include <memory>
67#include <string>
68#include <tuple>
Kyle Butt5818a512017-01-31 23:48:32 +000069#include <utility>
Eugene Zelenko2de563a2017-08-24 21:21:39 +000070#include <vector>
71
Chandler Carruthdb350872011-10-21 06:46:38 +000072using namespace llvm;
73
Chandler Carruth559a3292015-03-05 02:28:25 +000074#define DEBUG_TYPE "block-placement"
Chandler Carruth8677f2f2014-04-22 02:02:50 +000075
Chandler Carruth37efc9f2011-11-02 07:17:12 +000076STATISTIC(NumCondBranches, "Number of conditional branches");
Craig Topper5e6c2d42015-09-16 03:52:32 +000077STATISTIC(NumUncondBranches, "Number of unconditional branches");
Chandler Carruth37efc9f2011-11-02 07:17:12 +000078STATISTIC(CondBranchTakenFreq,
79 "Potential frequency of taking conditional branches");
80STATISTIC(UncondBranchTakenFreq,
81 "Potential frequency of taking unconditional branches");
82
Nadav Rotem07706e52013-04-12 00:48:32 +000083static cl::opt<unsigned> AlignAllBlock("align-all-blocks",
84 cl::desc("Force the alignment of all "
85 "blocks in the function."),
86 cl::init(0), cl::Hidden);
87
Geoff Berry5e799862016-01-21 17:25:52 +000088static cl::opt<unsigned> AlignAllNonFallThruBlocks(
89 "align-all-nofallthru-blocks",
90 cl::desc("Force the alignment of all "
91 "blocks that have no fall-through predecessors (i.e. don't add "
92 "nops that are executed)."),
93 cl::init(0), cl::Hidden);
94
Benjamin Kramer16e2f0e2013-11-20 19:08:44 +000095// FIXME: Find a good default for this flag and remove the flag.
Chandler Carruth35742dd2015-03-05 02:35:31 +000096static cl::opt<unsigned> ExitBlockBias(
97 "block-placement-exit-block-bias",
98 cl::desc("Block frequency percentage a loop exit block needs "
99 "over the original exit to be considered the new exit."),
100 cl::init(0), cl::Hidden);
Benjamin Kramer16e2f0e2013-11-20 19:08:44 +0000101
Sjoerd Meijer23ce7972016-07-27 08:49:23 +0000102// Definition:
103// - Outlining: placement of a basic block outside the chain or hot path.
104
Cong Houb18412c2015-11-02 21:24:00 +0000105static cl::opt<unsigned> LoopToColdBlockRatio(
106 "loop-to-cold-block-ratio",
107 cl::desc("Outline loop blocks from loop chain if (frequency of loop) / "
108 "(frequency of block) is greater than this ratio"),
109 cl::init(5), cl::Hidden);
110
Kyle Buttd3a55a82017-08-04 21:13:41 +0000111static cl::opt<bool> ForceLoopColdBlock(
112 "force-loop-cold-block",
113 cl::desc("Force outlining cold blocks from loops."),
114 cl::init(false), cl::Hidden);
115
Cong Houf2558c22015-10-19 23:16:40 +0000116static cl::opt<bool>
117 PreciseRotationCost("precise-rotation-cost",
118 cl::desc("Model the cost of loop rotation more "
119 "precisely by using profile data."),
120 cl::init(false), cl::Hidden);
Eugene Zelenko2de563a2017-08-24 21:21:39 +0000121
Xinliang David Lid4e30ea2016-05-12 02:04:41 +0000122static cl::opt<bool>
123 ForcePreciseRotationCost("force-precise-rotation-cost",
Xinliang David Li8f150842016-05-12 16:39:02 +0000124 cl::desc("Force the use of precise cost "
125 "loop rotation strategy."),
Xinliang David Lid4e30ea2016-05-12 02:04:41 +0000126 cl::init(false), cl::Hidden);
Cong Houf2558c22015-10-19 23:16:40 +0000127
128static cl::opt<unsigned> MisfetchCost(
129 "misfetch-cost",
Sjoerd Meijeraafccf02016-07-15 18:41:56 +0000130 cl::desc("Cost that models the probabilistic risk of an instruction "
Cong Houf2558c22015-10-19 23:16:40 +0000131 "misfetch due to a jump comparing to falling through, whose cost "
132 "is zero."),
133 cl::init(1), cl::Hidden);
134
135static cl::opt<unsigned> JumpInstCost("jump-inst-cost",
136 cl::desc("Cost of jump instructions."),
137 cl::init(1), cl::Hidden);
Kyle Butt2a180182016-10-11 20:36:43 +0000138static cl::opt<bool>
139TailDupPlacement("tail-dup-placement",
140 cl::desc("Perform tail duplication during placement. "
141 "Creates more fallthrough opportunites in "
142 "outline branches."),
143 cl::init(true), cl::Hidden);
Cong Houf2558c22015-10-19 23:16:40 +0000144
Haicheng Wuc4f22582016-06-09 15:24:29 +0000145static cl::opt<bool>
146BranchFoldPlacement("branch-fold-placement",
147 cl::desc("Perform branch folding during placement. "
148 "Reduces code size."),
149 cl::init(true), cl::Hidden);
150
Kyle Butt2a180182016-10-11 20:36:43 +0000151// Heuristic for tail duplication.
Kyle Butt5818a512017-01-31 23:48:32 +0000152static cl::opt<unsigned> TailDupPlacementThreshold(
Kyle Butt2a180182016-10-11 20:36:43 +0000153 "tail-dup-placement-threshold",
154 cl::desc("Instruction cutoff for tail duplication during layout. "
155 "Tail merging during layout is forced to have a threshold "
156 "that won't conflict."), cl::init(2),
157 cl::Hidden);
158
Kyle Butte6202482017-05-15 17:30:47 +0000159// Heuristic for aggressive tail duplication.
160static cl::opt<unsigned> TailDupPlacementAggressiveThreshold(
161 "tail-dup-placement-aggressive-threshold",
162 cl::desc("Instruction cutoff for aggressive tail duplication during "
163 "layout. Used at -O3. Tail merging during layout is forced to "
Richard Smith11110e12017-08-17 23:38:41 +0000164 "have a threshold that won't conflict."), cl::init(4),
Kyle Butte6202482017-05-15 17:30:47 +0000165 cl::Hidden);
166
Kyle Butt5818a512017-01-31 23:48:32 +0000167// Heuristic for tail duplication.
168static cl::opt<unsigned> TailDupPlacementPenalty(
169 "tail-dup-placement-penalty",
170 cl::desc("Cost penalty for blocks that can avoid breaking CFG by copying. "
171 "Copying can increase fallthrough, but it also increases icache "
172 "pressure. This parameter controls the penalty to account for that. "
173 "Percent as integer."),
174 cl::init(2),
175 cl::Hidden);
176
Kyle Buttc160e2a2017-03-03 01:00:22 +0000177// Heuristic for triangle chains.
178static cl::opt<unsigned> TriangleChainCount(
179 "triangle-chain-count",
180 cl::desc("Number of triangle-shaped-CFG's that need to be in a row for the "
181 "triangle tail duplication heuristic to kick in. 0 to disable."),
Kyle Buttfef90ab2017-03-16 01:32:29 +0000182 cl::init(2),
Kyle Buttc160e2a2017-03-03 01:00:22 +0000183 cl::Hidden);
184
Xinliang David Li670f8e52016-06-03 23:48:36 +0000185extern cl::opt<unsigned> StaticLikelyProb;
Dehao Chen97615522016-06-14 22:27:17 +0000186extern cl::opt<unsigned> ProfileLikelyProb;
Xinliang David Li670f8e52016-06-03 23:48:36 +0000187
Xinliang David Li050d2a72017-02-02 21:29:17 +0000188// Internal option used to control BFI display only after MBP pass.
189// Defined in CodeGen/MachineBlockFrequencyInfo.cpp:
190// -view-block-layout-with-bfi=
Xinliang David Li828b3982017-01-29 01:57:02 +0000191extern cl::opt<GVDAGType> ViewBlockLayoutWithBFI;
Xinliang David Li050d2a72017-02-02 21:29:17 +0000192
193// Command line option to specify the name of the function for CFG dump
194// Defined in Analysis/BlockFrequencyInfo.cpp: -view-bfi-func-name=
Xinliang David Li828b3982017-01-29 01:57:02 +0000195extern cl::opt<std::string> ViewBlockFreqFuncName;
Xinliang David Li828b3982017-01-29 01:57:02 +0000196
Chandler Carruthdb350872011-10-21 06:46:38 +0000197namespace {
Chandler Carruthdb350872011-10-21 06:46:38 +0000198
Eugene Zelenko2de563a2017-08-24 21:21:39 +0000199class BlockChain;
200
Adrian Prantl26b584c2018-05-01 15:54:18 +0000201/// Type for our function-wide basic block -> block chain mapping.
Eugene Zelenko2de563a2017-08-24 21:21:39 +0000202using BlockToChainMapType = DenseMap<const MachineBasicBlock *, BlockChain *>;
203
Adrian Prantl26b584c2018-05-01 15:54:18 +0000204/// A chain of blocks which will be laid out contiguously.
Chandler Carruthdb350872011-10-21 06:46:38 +0000205///
206/// This is the datastructure representing a chain of consecutive blocks that
207/// are profitable to layout together in order to maximize fallthrough
Chandler Carruthc04f8162012-06-26 05:16:37 +0000208/// probabilities and code locality. We also can use a block chain to represent
209/// a sequence of basic blocks which have some external (correctness)
210/// requirement for sequential layout.
Chandler Carruthdb350872011-10-21 06:46:38 +0000211///
Chandler Carruthc04f8162012-06-26 05:16:37 +0000212/// Chains can be built around a single basic block and can be merged to grow
213/// them. They participate in a block-to-chain mapping, which is updated
214/// automatically as chains are merged together.
Chandler Carruth30713632011-10-23 09:18:45 +0000215class BlockChain {
Adrian Prantl26b584c2018-05-01 15:54:18 +0000216 /// The sequence of blocks belonging to this chain.
Chandler Carruthdb350872011-10-21 06:46:38 +0000217 ///
Chandler Carruth30713632011-10-23 09:18:45 +0000218 /// This is the sequence of blocks for a particular chain. These will be laid
219 /// out in-order within the function.
220 SmallVector<MachineBasicBlock *, 4> Blocks;
Chandler Carruthdb350872011-10-21 06:46:38 +0000221
Adrian Prantl26b584c2018-05-01 15:54:18 +0000222 /// A handle to the function-wide basic block to block chain mapping.
Chandler Carruthdb350872011-10-21 06:46:38 +0000223 ///
224 /// This is retained in each block chain to simplify the computation of child
225 /// block chains for SCC-formation and iteration. We store the edges to child
226 /// basic blocks, and map them back to their associated chains using this
227 /// structure.
228 BlockToChainMapType &BlockToChain;
229
Chandler Carruth30713632011-10-23 09:18:45 +0000230public:
Adrian Prantl26b584c2018-05-01 15:54:18 +0000231 /// Construct a new BlockChain.
Chandler Carruthdb350872011-10-21 06:46:38 +0000232 ///
233 /// This builds a new block chain representing a single basic block in the
234 /// function. It also registers itself as the chain that block participates
235 /// in with the BlockToChain mapping.
236 BlockChain(BlockToChainMapType &BlockToChain, MachineBasicBlock *BB)
Eugene Zelenko2de563a2017-08-24 21:21:39 +0000237 : Blocks(1, BB), BlockToChain(BlockToChain) {
Chandler Carruthdb350872011-10-21 06:46:38 +0000238 assert(BB && "Cannot create a chain with a null basic block");
239 BlockToChain[BB] = this;
240 }
241
Adrian Prantl26b584c2018-05-01 15:54:18 +0000242 /// Iterator over blocks within the chain.
Eugene Zelenko2de563a2017-08-24 21:21:39 +0000243 using iterator = SmallVectorImpl<MachineBasicBlock *>::iterator;
244 using const_iterator = SmallVectorImpl<MachineBasicBlock *>::const_iterator;
Chandler Carruth30713632011-10-23 09:18:45 +0000245
Adrian Prantl26b584c2018-05-01 15:54:18 +0000246 /// Beginning of blocks within the chain.
Chandler Carruth70daea92012-04-16 01:12:56 +0000247 iterator begin() { return Blocks.begin(); }
Kyle Butt7a252572017-02-04 02:26:32 +0000248 const_iterator begin() const { return Blocks.begin(); }
Chandler Carruth30713632011-10-23 09:18:45 +0000249
Adrian Prantl26b584c2018-05-01 15:54:18 +0000250 /// End of blocks within the chain.
Chandler Carruth70daea92012-04-16 01:12:56 +0000251 iterator end() { return Blocks.end(); }
Kyle Butt7a252572017-02-04 02:26:32 +0000252 const_iterator end() const { return Blocks.end(); }
Chandler Carruth30713632011-10-23 09:18:45 +0000253
Kyle Butt2a180182016-10-11 20:36:43 +0000254 bool remove(MachineBasicBlock* BB) {
255 for(iterator i = begin(); i != end(); ++i) {
256 if (*i == BB) {
257 Blocks.erase(i);
258 return true;
259 }
260 }
261 return false;
262 }
263
Adrian Prantl26b584c2018-05-01 15:54:18 +0000264 /// Merge a block chain into this one.
Chandler Carruthdb350872011-10-21 06:46:38 +0000265 ///
266 /// This routine merges a block chain into this one. It takes care of forming
267 /// a contiguous sequence of basic blocks, updating the edge list, and
268 /// updating the block -> chain mapping. It does not free or tear down the
269 /// old chain, but the old chain's block list is no longer valid.
Jakub Staszakd4895de2011-12-21 23:02:08 +0000270 void merge(MachineBasicBlock *BB, BlockChain *Chain) {
Kyle Butt25ccad82017-05-17 23:44:41 +0000271 assert(BB && "Can't merge a null block.");
272 assert(!Blocks.empty() && "Can't merge into an empty chain.");
Chandler Carruthdb350872011-10-21 06:46:38 +0000273
Chandler Carruth30713632011-10-23 09:18:45 +0000274 // Fast path in case we don't have a chain already.
275 if (!Chain) {
Kyle Butt25ccad82017-05-17 23:44:41 +0000276 assert(!BlockToChain[BB] &&
277 "Passed chain is null, but BB has entry in BlockToChain.");
Chandler Carruth30713632011-10-23 09:18:45 +0000278 Blocks.push_back(BB);
279 BlockToChain[BB] = this;
280 return;
Chandler Carruthdb350872011-10-21 06:46:38 +0000281 }
282
Kyle Butt25ccad82017-05-17 23:44:41 +0000283 assert(BB == *Chain->begin() && "Passed BB is not head of Chain.");
Chandler Carruth30713632011-10-23 09:18:45 +0000284 assert(Chain->begin() != Chain->end());
Chandler Carruthdb350872011-10-21 06:46:38 +0000285
Chandler Carruth30713632011-10-23 09:18:45 +0000286 // Update the incoming blocks to point to this chain, and add them to the
287 // chain structure.
Chandler Carruthbb535bc2015-03-05 03:19:05 +0000288 for (MachineBasicBlock *ChainBB : *Chain) {
289 Blocks.push_back(ChainBB);
Kyle Butt25ccad82017-05-17 23:44:41 +0000290 assert(BlockToChain[ChainBB] == Chain && "Incoming blocks not in chain.");
Chandler Carruthbb535bc2015-03-05 03:19:05 +0000291 BlockToChain[ChainBB] = this;
Chandler Carruth30713632011-10-23 09:18:45 +0000292 }
Chandler Carruthdb350872011-10-21 06:46:38 +0000293 }
Chandler Carruthdf234352011-11-13 11:20:44 +0000294
Chandler Carruth6313d942012-04-08 14:37:01 +0000295#ifndef NDEBUG
Adrian Prantl26b584c2018-05-01 15:54:18 +0000296 /// Dump the blocks in this chain.
Nico Weberc3d3f0c2014-01-03 22:53:37 +0000297 LLVM_DUMP_METHOD void dump() {
Chandler Carruthbb535bc2015-03-05 03:19:05 +0000298 for (MachineBasicBlock *MBB : *this)
299 MBB->dump();
Chandler Carruth6313d942012-04-08 14:37:01 +0000300 }
301#endif // NDEBUG
302
Adrian Prantl26b584c2018-05-01 15:54:18 +0000303 /// Count of predecessors of any block within the chain which have not
Philip Reames43605f82016-03-03 00:58:43 +0000304 /// yet been scheduled. In general, we will delay scheduling this chain
305 /// until those predecessors are scheduled (or we find a sufficiently good
306 /// reason to override this heuristic.) Note that when forming loop chains,
307 /// blocks outside the loop are ignored and treated as if they were already
308 /// scheduled.
Chandler Carruthdf234352011-11-13 11:20:44 +0000309 ///
Philip Reames43605f82016-03-03 00:58:43 +0000310 /// Note: This field is reinitialized multiple times - once for each loop,
311 /// and then once for the function as a whole.
Eugene Zelenko2de563a2017-08-24 21:21:39 +0000312 unsigned UnscheduledPredecessors = 0;
Chandler Carruthdb350872011-10-21 06:46:38 +0000313};
Chandler Carruthdb350872011-10-21 06:46:38 +0000314
Chandler Carruthdb350872011-10-21 06:46:38 +0000315class MachineBlockPlacement : public MachineFunctionPass {
Adrian Prantl26b584c2018-05-01 15:54:18 +0000316 /// A type for a block filter set.
Eugene Zelenko2de563a2017-08-24 21:21:39 +0000317 using BlockFilterSet = SmallSetVector<const MachineBasicBlock *, 16>;
Chandler Carruth30713632011-10-23 09:18:45 +0000318
Hiroshi Inoue7a9527e2019-01-09 05:11:10 +0000319 /// Pair struct containing basic block and taildup profitability
Kyle Butt5818a512017-01-31 23:48:32 +0000320 struct BlockAndTailDupResult {
Kyle Butta466b362017-02-15 19:49:14 +0000321 MachineBasicBlock *BB;
Kyle Butt5818a512017-01-31 23:48:32 +0000322 bool ShouldTailDup;
323 };
324
Kyle Butta466b362017-02-15 19:49:14 +0000325 /// Triple struct containing edge weight and the edge.
326 struct WeightedEdge {
327 BlockFrequency Weight;
328 MachineBasicBlock *Src;
329 MachineBasicBlock *Dest;
330 };
331
Adrian Prantl26b584c2018-05-01 15:54:18 +0000332 /// work lists of blocks that are ready to be laid out
Xinliang David Li036eb7c2016-07-01 05:46:48 +0000333 SmallVector<MachineBasicBlock *, 16> BlockWorkList;
334 SmallVector<MachineBasicBlock *, 16> EHPadWorkList;
335
Kyle Butt9e601a42017-02-23 21:22:24 +0000336 /// Edges that have already been computed as optimal.
337 DenseMap<const MachineBasicBlock *, BlockAndTailDupResult> ComputedEdges;
Kyle Butta466b362017-02-15 19:49:14 +0000338
Adrian Prantl26b584c2018-05-01 15:54:18 +0000339 /// Machine Function
Xinliang David Li121cd172016-06-13 22:23:44 +0000340 MachineFunction *F;
341
Adrian Prantl26b584c2018-05-01 15:54:18 +0000342 /// A handle to the branch probability pass.
Chandler Carruthdb350872011-10-21 06:46:38 +0000343 const MachineBranchProbabilityInfo *MBPI;
344
Adrian Prantl26b584c2018-05-01 15:54:18 +0000345 /// A handle to the function-wide block frequency pass.
Haicheng Wuc4f22582016-06-09 15:24:29 +0000346 std::unique_ptr<BranchFolder::MBFIWrapper> MBFI;
Chandler Carruthdb350872011-10-21 06:46:38 +0000347
Adrian Prantl26b584c2018-05-01 15:54:18 +0000348 /// A handle to the loop info.
Haicheng Wuc4f22582016-06-09 15:24:29 +0000349 MachineLoopInfo *MLI;
Chandler Carruth4a85cc92011-10-21 08:57:37 +0000350
Adrian Prantl26b584c2018-05-01 15:54:18 +0000351 /// Preferred loop exit.
Kyle Buttbf977932016-10-27 21:37:20 +0000352 /// Member variable for convenience. It may be removed by duplication deep
353 /// in the call stack.
354 MachineBasicBlock *PreferredLoopExit;
355
Adrian Prantl26b584c2018-05-01 15:54:18 +0000356 /// A handle to the target's instruction info.
Chandler Carruthdb350872011-10-21 06:46:38 +0000357 const TargetInstrInfo *TII;
358
Adrian Prantl26b584c2018-05-01 15:54:18 +0000359 /// A handle to the target's lowering info.
Benjamin Kramer69e42db2013-01-11 20:05:37 +0000360 const TargetLoweringBase *TLI;
Chandler Carruth4a85cc92011-10-21 08:57:37 +0000361
Adrian Prantl26b584c2018-05-01 15:54:18 +0000362 /// A handle to the post dominator tree.
Kyle Butt5818a512017-01-31 23:48:32 +0000363 MachinePostDominatorTree *MPDT;
364
Adrian Prantl26b584c2018-05-01 15:54:18 +0000365 /// Duplicator used to duplicate tails during placement.
Kyle Butt2a180182016-10-11 20:36:43 +0000366 ///
367 /// Placement decisions can open up new tail duplication opportunities, but
368 /// since tail duplication affects placement decisions of later blocks, it
369 /// must be done inline.
370 TailDuplicator TailDup;
371
Adrian Prantl26b584c2018-05-01 15:54:18 +0000372 /// Allocator and owner of BlockChain structures.
Chandler Carruthdb350872011-10-21 06:46:38 +0000373 ///
Chandler Carruthc04f8162012-06-26 05:16:37 +0000374 /// We build BlockChains lazily while processing the loop structure of
375 /// a function. To reduce malloc traffic, we allocate them using this
376 /// slab-like allocator, and destroy them after the pass completes. An
377 /// important guarantee is that this allocator produces stable pointers to
378 /// the chains.
Chandler Carruthdb350872011-10-21 06:46:38 +0000379 SpecificBumpPtrAllocator<BlockChain> ChainAllocator;
380
Adrian Prantl26b584c2018-05-01 15:54:18 +0000381 /// Function wide BasicBlock to BlockChain mapping.
Chandler Carruthdb350872011-10-21 06:46:38 +0000382 ///
383 /// This mapping allows efficiently moving from any given basic block to the
384 /// BlockChain it participates in, if any. We use it to, among other things,
385 /// allow implicitly defining edges between chains as the existing edges
386 /// between basic blocks.
Kyle Butt7a252572017-02-04 02:26:32 +0000387 DenseMap<const MachineBasicBlock *, BlockChain *> BlockToChain;
Chandler Carruthdb350872011-10-21 06:46:38 +0000388
Sanjoy Dasd0f66422016-12-15 05:08:57 +0000389#ifndef NDEBUG
390 /// The set of basic blocks that have terminators that cannot be fully
391 /// analyzed. These basic blocks cannot be re-ordered safely by
392 /// MachineBlockPlacement, and we must preserve physical layout of these
393 /// blocks and their successors through the pass.
394 SmallPtrSet<MachineBasicBlock *, 4> BlocksWithUnanalyzableExits;
395#endif
396
Kyle Butt2a180182016-10-11 20:36:43 +0000397 /// Decrease the UnscheduledPredecessors count for all blocks in chain, and
398 /// if the count goes to 0, add them to the appropriate work list.
Kyle Butt7a252572017-02-04 02:26:32 +0000399 void markChainSuccessors(
400 const BlockChain &Chain, const MachineBasicBlock *LoopHeaderBB,
401 const BlockFilterSet *BlockFilter = nullptr);
Kyle Butt2a180182016-10-11 20:36:43 +0000402
403 /// Decrease the UnscheduledPredecessors count for a single block, and
404 /// if the count goes to 0, add them to the appropriate work list.
405 void markBlockSuccessors(
Kyle Butt7a252572017-02-04 02:26:32 +0000406 const BlockChain &Chain, const MachineBasicBlock *BB,
407 const MachineBasicBlock *LoopHeaderBB,
Kyle Butt2a180182016-10-11 20:36:43 +0000408 const BlockFilterSet *BlockFilter = nullptr);
409
Xinliang David Li2e5514a2016-06-11 18:35:40 +0000410 BranchProbability
Kyle Butt7a252572017-02-04 02:26:32 +0000411 collectViableSuccessors(
412 const MachineBasicBlock *BB, const BlockChain &Chain,
413 const BlockFilterSet *BlockFilter,
414 SmallVector<MachineBasicBlock *, 4> &Successors);
415 bool shouldPredBlockBeOutlined(
416 const MachineBasicBlock *BB, const MachineBasicBlock *Succ,
417 const BlockChain &Chain, const BlockFilterSet *BlockFilter,
418 BranchProbability SuccProb, BranchProbability HotProb);
Kyle Butt2a180182016-10-11 20:36:43 +0000419 bool repeatedlyTailDuplicateBlock(
420 MachineBasicBlock *BB, MachineBasicBlock *&LPred,
Kyle Butt7a252572017-02-04 02:26:32 +0000421 const MachineBasicBlock *LoopHeaderBB,
Kyle Butt2a180182016-10-11 20:36:43 +0000422 BlockChain &Chain, BlockFilterSet *BlockFilter,
423 MachineFunction::iterator &PrevUnplacedBlockIt);
Kyle Butt7a252572017-02-04 02:26:32 +0000424 bool maybeTailDuplicateBlock(
425 MachineBasicBlock *BB, MachineBasicBlock *LPred,
426 BlockChain &Chain, BlockFilterSet *BlockFilter,
427 MachineFunction::iterator &PrevUnplacedBlockIt,
Fangrui Song7d882862018-07-16 18:51:40 +0000428 bool &DuplicatedToLPred);
Kyle Butt7a252572017-02-04 02:26:32 +0000429 bool hasBetterLayoutPredecessor(
430 const MachineBasicBlock *BB, const MachineBasicBlock *Succ,
431 const BlockChain &SuccChain, BranchProbability SuccProb,
432 BranchProbability RealSuccProb, const BlockChain &Chain,
433 const BlockFilterSet *BlockFilter);
434 BlockAndTailDupResult selectBestSuccessor(
435 const MachineBasicBlock *BB, const BlockChain &Chain,
436 const BlockFilterSet *BlockFilter);
437 MachineBasicBlock *selectBestCandidateBlock(
438 const BlockChain &Chain, SmallVectorImpl<MachineBasicBlock *> &WorkList);
439 MachineBasicBlock *getFirstUnplacedBlock(
440 const BlockChain &PlacedChain,
441 MachineFunction::iterator &PrevUnplacedBlockIt,
442 const BlockFilterSet *BlockFilter);
Amaury Sechetce1afcc2016-03-14 21:24:11 +0000443
Adrian Prantl26b584c2018-05-01 15:54:18 +0000444 /// Add a basic block to the work list if it is appropriate.
Amaury Sechetce1afcc2016-03-14 21:24:11 +0000445 ///
446 /// If the optional parameter BlockFilter is provided, only MBB
447 /// present in the set will be added to the worklist. If nullptr
448 /// is provided, no filtering occurs.
Kyle Butt7a252572017-02-04 02:26:32 +0000449 void fillWorkLists(const MachineBasicBlock *MBB,
Amaury Sechetce1afcc2016-03-14 21:24:11 +0000450 SmallPtrSetImpl<BlockChain *> &UpdatedPreds,
Amaury Sechetce1afcc2016-03-14 21:24:11 +0000451 const BlockFilterSet *BlockFilter);
Eugene Zelenko2de563a2017-08-24 21:21:39 +0000452
Kyle Butt7a252572017-02-04 02:26:32 +0000453 void buildChain(const MachineBasicBlock *BB, BlockChain &Chain,
Kyle Butt2a180182016-10-11 20:36:43 +0000454 BlockFilterSet *BlockFilter = nullptr);
Kyle Butt7a252572017-02-04 02:26:32 +0000455 MachineBasicBlock *findBestLoopTop(
456 const MachineLoop &L, const BlockFilterSet &LoopBlockSet);
457 MachineBasicBlock *findBestLoopExit(
458 const MachineLoop &L, const BlockFilterSet &LoopBlockSet);
459 BlockFilterSet collectLoopBlockSet(const MachineLoop &L);
460 void buildLoopChains(const MachineLoop &L);
461 void rotateLoop(
462 BlockChain &LoopChain, const MachineBasicBlock *ExitingBB,
463 const BlockFilterSet &LoopBlockSet);
464 void rotateLoopWithProfile(
465 BlockChain &LoopChain, const MachineLoop &L,
466 const BlockFilterSet &LoopBlockSet);
Xinliang David Li121cd172016-06-13 22:23:44 +0000467 void buildCFGChains();
468 void optimizeBranches();
469 void alignBlocks();
Kyle Butta466b362017-02-15 19:49:14 +0000470 /// Returns true if a block should be tail-duplicated to increase fallthrough
471 /// opportunities.
Kyle Butt5818a512017-01-31 23:48:32 +0000472 bool shouldTailDuplicate(MachineBasicBlock *BB);
473 /// Check the edge frequencies to see if tail duplication will increase
474 /// fallthroughs.
475 bool isProfitableToTailDup(
Kyle Butt7a252572017-02-04 02:26:32 +0000476 const MachineBasicBlock *BB, const MachineBasicBlock *Succ,
Fangrui Song7d882862018-07-16 18:51:40 +0000477 BranchProbability QProb,
Kyle Butt7a252572017-02-04 02:26:32 +0000478 const BlockChain &Chain, const BlockFilterSet *BlockFilter);
Eugene Zelenko2de563a2017-08-24 21:21:39 +0000479
Kyle Butta466b362017-02-15 19:49:14 +0000480 /// Check for a trellis layout.
481 bool isTrellis(const MachineBasicBlock *BB,
482 const SmallVectorImpl<MachineBasicBlock *> &ViableSuccs,
483 const BlockChain &Chain, const BlockFilterSet *BlockFilter);
Eugene Zelenko2de563a2017-08-24 21:21:39 +0000484
Kyle Butta466b362017-02-15 19:49:14 +0000485 /// Get the best successor given a trellis layout.
486 BlockAndTailDupResult getBestTrellisSuccessor(
487 const MachineBasicBlock *BB,
488 const SmallVectorImpl<MachineBasicBlock *> &ViableSuccs,
489 BranchProbability AdjustedSumProb, const BlockChain &Chain,
490 const BlockFilterSet *BlockFilter);
Eugene Zelenko2de563a2017-08-24 21:21:39 +0000491
Kyle Butta466b362017-02-15 19:49:14 +0000492 /// Get the best pair of non-conflicting edges.
493 static std::pair<WeightedEdge, WeightedEdge> getBestNonConflictingEdges(
494 const MachineBasicBlock *BB,
Benjamin Kramer2b371752017-04-12 13:26:28 +0000495 MutableArrayRef<SmallVector<WeightedEdge, 8>> Edges);
Eugene Zelenko2de563a2017-08-24 21:21:39 +0000496
Kyle Butt5818a512017-01-31 23:48:32 +0000497 /// Returns true if a block can tail duplicate into all unplaced
498 /// predecessors. Filters based on loop.
499 bool canTailDuplicateUnplacedPreds(
Kyle Butt7a252572017-02-04 02:26:32 +0000500 const MachineBasicBlock *BB, MachineBasicBlock *Succ,
501 const BlockChain &Chain, const BlockFilterSet *BlockFilter);
Eugene Zelenko2de563a2017-08-24 21:21:39 +0000502
Kyle Buttc160e2a2017-03-03 01:00:22 +0000503 /// Find chains of triangles to tail-duplicate where a global analysis works,
504 /// but a local analysis would not find them.
505 void precomputeTriangleChains();
Chandler Carruthdb350872011-10-21 06:46:38 +0000506
507public:
508 static char ID; // Pass identification, replacement for typeid
Eugene Zelenko2de563a2017-08-24 21:21:39 +0000509
Chandler Carruthdb350872011-10-21 06:46:38 +0000510 MachineBlockPlacement() : MachineFunctionPass(ID) {
511 initializeMachineBlockPlacementPass(*PassRegistry::getPassRegistry());
512 }
513
Craig Topper9f998de2014-03-07 09:26:03 +0000514 bool runOnMachineFunction(MachineFunction &F) override;
Chandler Carruthdb350872011-10-21 06:46:38 +0000515
Tim Shene1a4b172018-03-30 17:51:00 +0000516 bool allowTailDupPlacement() const {
517 assert(F);
518 return TailDupPlacement && !F->getTarget().requiresStructuredCFG();
519 }
520
Craig Topper9f998de2014-03-07 09:26:03 +0000521 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruthdb350872011-10-21 06:46:38 +0000522 AU.addRequired<MachineBranchProbabilityInfo>();
523 AU.addRequired<MachineBlockFrequencyInfo>();
Kyle Butt5818a512017-01-31 23:48:32 +0000524 if (TailDupPlacement)
525 AU.addRequired<MachinePostDominatorTree>();
Chandler Carruth4a85cc92011-10-21 08:57:37 +0000526 AU.addRequired<MachineLoopInfo>();
Haicheng Wuc4f22582016-06-09 15:24:29 +0000527 AU.addRequired<TargetPassConfig>();
Chandler Carruthdb350872011-10-21 06:46:38 +0000528 MachineFunctionPass::getAnalysisUsage(AU);
529 }
Chandler Carruthdb350872011-10-21 06:46:38 +0000530};
Eugene Zelenko2de563a2017-08-24 21:21:39 +0000531
532} // end anonymous namespace
Chandler Carruthdb350872011-10-21 06:46:38 +0000533
534char MachineBlockPlacement::ID = 0;
Eugene Zelenko2de563a2017-08-24 21:21:39 +0000535
Andrew Trick1dd8c852012-02-08 21:23:13 +0000536char &llvm::MachineBlockPlacementID = MachineBlockPlacement::ID;
Eugene Zelenko2de563a2017-08-24 21:21:39 +0000537
Matthias Braun94c49042017-05-25 21:26:32 +0000538INITIALIZE_PASS_BEGIN(MachineBlockPlacement, DEBUG_TYPE,
Chandler Carruthdb350872011-10-21 06:46:38 +0000539 "Branch Probability Basic Block Placement", false, false)
540INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
541INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
Kyle Butt5818a512017-01-31 23:48:32 +0000542INITIALIZE_PASS_DEPENDENCY(MachinePostDominatorTree)
Chandler Carruth4a85cc92011-10-21 08:57:37 +0000543INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
Matthias Braun94c49042017-05-25 21:26:32 +0000544INITIALIZE_PASS_END(MachineBlockPlacement, DEBUG_TYPE,
Chandler Carruthdb350872011-10-21 06:46:38 +0000545 "Branch Probability Basic Block Placement", false, false)
546
Chandler Carruth30713632011-10-23 09:18:45 +0000547#ifndef NDEBUG
Adrian Prantl26b584c2018-05-01 15:54:18 +0000548/// Helper to print the name of a MBB.
Chandler Carruth30713632011-10-23 09:18:45 +0000549///
550/// Only used by debug logging.
Kyle Butt7a252572017-02-04 02:26:32 +0000551static std::string getBlockName(const MachineBasicBlock *BB) {
Alp Toker8dd8d5c2014-06-26 22:52:05 +0000552 std::string Result;
553 raw_string_ostream OS(Result);
Francis Visoiu Mistrihca0df552017-12-04 17:18:51 +0000554 OS << printMBBReference(*BB);
Philip Reames0dadb952016-03-02 21:45:13 +0000555 OS << " ('" << BB->getName() << "')";
Alp Toker8dd8d5c2014-06-26 22:52:05 +0000556 OS.flush();
557 return Result;
Chandler Carruth30713632011-10-23 09:18:45 +0000558}
559#endif
560
Adrian Prantl26b584c2018-05-01 15:54:18 +0000561/// Mark a chain's successors as having one fewer preds.
Chandler Carruth729bec82011-11-13 11:34:55 +0000562///
563/// When a chain is being merged into the "placed" chain, this routine will
564/// quickly walk the successors of each block in the chain and mark them as
565/// having one fewer active predecessor. It also adds any successors of this
Kyle Butt2a180182016-10-11 20:36:43 +0000566/// chain which reach the zero-predecessor state to the appropriate worklist.
Chandler Carruthdf234352011-11-13 11:20:44 +0000567void MachineBlockPlacement::markChainSuccessors(
Kyle Butt7a252572017-02-04 02:26:32 +0000568 const BlockChain &Chain, const MachineBasicBlock *LoopHeaderBB,
Jakub Staszakd4895de2011-12-21 23:02:08 +0000569 const BlockFilterSet *BlockFilter) {
Chandler Carruthdf234352011-11-13 11:20:44 +0000570 // Walk all the blocks in this chain, marking their successors as having
571 // a predecessor placed.
Chandler Carruthbb535bc2015-03-05 03:19:05 +0000572 for (MachineBasicBlock *MBB : Chain) {
Kyle Butt2a180182016-10-11 20:36:43 +0000573 markBlockSuccessors(Chain, MBB, LoopHeaderBB, BlockFilter);
574 }
575}
Chandler Carruthdb350872011-10-21 06:46:38 +0000576
Adrian Prantl26b584c2018-05-01 15:54:18 +0000577/// Mark a single block's successors as having one fewer preds.
Kyle Butt2a180182016-10-11 20:36:43 +0000578///
579/// Under normal circumstances, this is only called by markChainSuccessors,
580/// but if a block that was to be placed is completely tail-duplicated away,
581/// and was duplicated into the chain end, we need to redo markBlockSuccessors
582/// for just that block.
583void MachineBlockPlacement::markBlockSuccessors(
Kyle Butt7a252572017-02-04 02:26:32 +0000584 const BlockChain &Chain, const MachineBasicBlock *MBB,
585 const MachineBasicBlock *LoopHeaderBB, const BlockFilterSet *BlockFilter) {
Kyle Butt2a180182016-10-11 20:36:43 +0000586 // Add any successors for which this is the only un-placed in-loop
587 // predecessor to the worklist as a viable candidate for CFG-neutral
588 // placement. No subsequent placement of this block will violate the CFG
589 // shape, so we get to use heuristics to choose a favorable placement.
590 for (MachineBasicBlock *Succ : MBB->successors()) {
591 if (BlockFilter && !BlockFilter->count(Succ))
592 continue;
593 BlockChain &SuccChain = *BlockToChain[Succ];
594 // Disregard edges within a fixed chain, or edges to the loop header.
595 if (&Chain == &SuccChain || Succ == LoopHeaderBB)
596 continue;
Amaury Secheta5bbcb52016-04-07 21:29:39 +0000597
Kyle Butt2a180182016-10-11 20:36:43 +0000598 // This is a cross-chain edge that is within the loop, so decrement the
599 // loop predecessor count of the destination chain.
600 if (SuccChain.UnscheduledPredecessors == 0 ||
601 --SuccChain.UnscheduledPredecessors > 0)
602 continue;
603
604 auto *NewBB = *SuccChain.begin();
605 if (NewBB->isEHPad())
606 EHPadWorkList.push_back(NewBB);
607 else
608 BlockWorkList.push_back(NewBB);
Chandler Carruthdb350872011-10-21 06:46:38 +0000609 }
Chandler Carruthdf234352011-11-13 11:20:44 +0000610}
Chandler Carruth30713632011-10-23 09:18:45 +0000611
Xinliang David Li2e5514a2016-06-11 18:35:40 +0000612/// This helper function collects the set of successors of block
613/// \p BB that are allowed to be its layout successors, and return
614/// the total branch probability of edges from \p BB to those
615/// blocks.
616BranchProbability MachineBlockPlacement::collectViableSuccessors(
Kyle Butt7a252572017-02-04 02:26:32 +0000617 const MachineBasicBlock *BB, const BlockChain &Chain,
618 const BlockFilterSet *BlockFilter,
Xinliang David Li2e5514a2016-06-11 18:35:40 +0000619 SmallVector<MachineBasicBlock *, 4> &Successors) {
Cong Hou51550212015-12-01 05:29:22 +0000620 // Adjust edge probabilities by excluding edges pointing to blocks that is
621 // either not in BlockFilter or is already in the current chain. Consider the
622 // following CFG:
Cong Houd6634262015-11-18 00:52:52 +0000623 //
624 // --->A
625 // | / \
626 // | B C
627 // | \ / \
628 // ----D E
629 //
630 // Assume A->C is very hot (>90%), and C->D has a 50% probability, then after
631 // A->C is chosen as a fall-through, D won't be selected as a successor of C
632 // due to CFG constraint (the probability of C->D is not greater than
Hiroshi Inoue0a8e8962017-06-16 12:23:04 +0000633 // HotProb to break topo-order). If we exclude E that is not in BlockFilter
634 // when calculating the probability of C->D, D will be selected and we
Xinliang David Li2e5514a2016-06-11 18:35:40 +0000635 // will get A C D B as the layout of this loop.
Cong Hou51550212015-12-01 05:29:22 +0000636 auto AdjustedSumProb = BranchProbability::getOne();
Cong Houd6634262015-11-18 00:52:52 +0000637 for (MachineBasicBlock *Succ : BB->successors()) {
638 bool SkipSucc = false;
Amaury Secheta5bbcb52016-04-07 21:29:39 +0000639 if (Succ->isEHPad() || (BlockFilter && !BlockFilter->count(Succ))) {
Cong Houd6634262015-11-18 00:52:52 +0000640 SkipSucc = true;
641 } else {
642 BlockChain *SuccChain = BlockToChain[Succ];
643 if (SuccChain == &Chain) {
Cong Houd6634262015-11-18 00:52:52 +0000644 SkipSucc = true;
645 } else if (Succ != *SuccChain->begin()) {
Nicola Zaghen0818e782018-05-14 12:53:11 +0000646 LLVM_DEBUG(dbgs() << " " << getBlockName(Succ)
647 << " -> Mid chain!\n");
Cong Houd6634262015-11-18 00:52:52 +0000648 continue;
649 }
650 }
651 if (SkipSucc)
Cong Hou51550212015-12-01 05:29:22 +0000652 AdjustedSumProb -= MBPI->getEdgeProbability(BB, Succ);
Cong Houd6634262015-11-18 00:52:52 +0000653 else
654 Successors.push_back(Succ);
655 }
656
Xinliang David Li2e5514a2016-06-11 18:35:40 +0000657 return AdjustedSumProb;
658}
659
660/// The helper function returns the branch probability that is adjusted
661/// or normalized over the new total \p AdjustedSumProb.
Xinliang David Li2e5514a2016-06-11 18:35:40 +0000662static BranchProbability
663getAdjustedProbability(BranchProbability OrigProb,
664 BranchProbability AdjustedSumProb) {
665 BranchProbability SuccProb;
666 uint32_t SuccProbN = OrigProb.getNumerator();
667 uint32_t SuccProbD = AdjustedSumProb.getNumerator();
668 if (SuccProbN >= SuccProbD)
669 SuccProb = BranchProbability::getOne();
670 else
671 SuccProb = BranchProbability(SuccProbN, SuccProbD);
672
673 return SuccProb;
674}
675
Kyle Butta466b362017-02-15 19:49:14 +0000676/// Check if \p BB has exactly the successors in \p Successors.
677static bool
678hasSameSuccessors(MachineBasicBlock &BB,
679 SmallPtrSetImpl<const MachineBasicBlock *> &Successors) {
680 if (BB.succ_size() != Successors.size())
681 return false;
682 // We don't want to count self-loops
683 if (Successors.count(&BB))
684 return false;
685 for (MachineBasicBlock *Succ : BB.successors())
686 if (!Successors.count(Succ))
687 return false;
688 return true;
689}
690
691/// Check if a block should be tail duplicated to increase fallthrough
692/// opportunities.
Kyle Butt5818a512017-01-31 23:48:32 +0000693/// \p BB Block to check.
694bool MachineBlockPlacement::shouldTailDuplicate(MachineBasicBlock *BB) {
695 // Blocks with single successors don't create additional fallthrough
696 // opportunities. Don't duplicate them. TODO: When conditional exits are
697 // analyzable, allow them to be duplicated.
698 bool IsSimple = TailDup.isSimpleBB(BB);
699
700 if (BB->succ_size() == 1)
701 return false;
702 return TailDup.shouldTailDuplicate(IsSimple, *BB);
703}
704
705/// Compare 2 BlockFrequency's with a small penalty for \p A.
706/// In order to be conservative, we apply a X% penalty to account for
707/// increased icache pressure and static heuristics. For small frequencies
708/// we use only the numerators to improve accuracy. For simplicity, we assume the
709/// penalty is less than 100%
710/// TODO(iteratee): Use 64-bit fixed point edge frequencies everywhere.
711static bool greaterWithBias(BlockFrequency A, BlockFrequency B,
712 uint64_t EntryFreq) {
713 BranchProbability ThresholdProb(TailDupPlacementPenalty, 100);
714 BlockFrequency Gain = A - B;
715 return (Gain / ThresholdProb).getFrequency() >= EntryFreq;
716}
717
718/// Check the edge frequencies to see if tail duplication will increase
719/// fallthroughs. It only makes sense to call this function when
720/// \p Succ would not be chosen otherwise. Tail duplication of \p Succ is
721/// always locally profitable if we would have picked \p Succ without
722/// considering duplication.
723bool MachineBlockPlacement::isProfitableToTailDup(
Kyle Butt7a252572017-02-04 02:26:32 +0000724 const MachineBasicBlock *BB, const MachineBasicBlock *Succ,
Kyle Butt5818a512017-01-31 23:48:32 +0000725 BranchProbability QProb,
Kyle Butt7a252572017-02-04 02:26:32 +0000726 const BlockChain &Chain, const BlockFilterSet *BlockFilter) {
Kyle Butt5818a512017-01-31 23:48:32 +0000727 // We need to do a probability calculation to make sure this is profitable.
728 // First: does succ have a successor that post-dominates? This affects the
729 // calculation. The 2 relevant cases are:
730 // BB BB
731 // | \Qout | \Qout
732 // P| C |P C
733 // = C' = C'
734 // | /Qin | /Qin
735 // | / | /
736 // Succ Succ
737 // / \ | \ V
738 // U/ =V |U \
739 // / \ = D
740 // D E | /
741 // | /
742 // |/
743 // PDom
744 // '=' : Branch taken for that CFG edge
745 // In the second case, Placing Succ while duplicating it into C prevents the
746 // fallthrough of Succ into either D or PDom, because they now have C as an
747 // unplaced predecessor
748
749 // Start by figuring out which case we fall into
750 MachineBasicBlock *PDom = nullptr;
751 SmallVector<MachineBasicBlock *, 4> SuccSuccs;
752 // Only scan the relevant successors
753 auto AdjustedSuccSumProb =
754 collectViableSuccessors(Succ, Chain, BlockFilter, SuccSuccs);
755 BranchProbability PProb = MBPI->getEdgeProbability(BB, Succ);
756 auto BBFreq = MBFI->getBlockFreq(BB);
757 auto SuccFreq = MBFI->getBlockFreq(Succ);
758 BlockFrequency P = BBFreq * PProb;
759 BlockFrequency Qout = BBFreq * QProb;
760 uint64_t EntryFreq = MBFI->getEntryFreq();
761 // If there are no more successors, it is profitable to copy, as it strictly
762 // increases fallthrough.
763 if (SuccSuccs.size() == 0)
764 return greaterWithBias(P, Qout, EntryFreq);
765
766 auto BestSuccSucc = BranchProbability::getZero();
767 // Find the PDom or the best Succ if no PDom exists.
768 for (MachineBasicBlock *SuccSucc : SuccSuccs) {
769 auto Prob = MBPI->getEdgeProbability(Succ, SuccSucc);
770 if (Prob > BestSuccSucc)
771 BestSuccSucc = Prob;
772 if (PDom == nullptr)
773 if (MPDT->dominates(SuccSucc, Succ)) {
774 PDom = SuccSucc;
775 break;
776 }
777 }
778 // For the comparisons, we need to know Succ's best incoming edge that isn't
779 // from BB.
780 auto SuccBestPred = BlockFrequency(0);
781 for (MachineBasicBlock *SuccPred : Succ->predecessors()) {
782 if (SuccPred == Succ || SuccPred == BB
783 || BlockToChain[SuccPred] == &Chain
784 || (BlockFilter && !BlockFilter->count(SuccPred)))
785 continue;
786 auto Freq = MBFI->getBlockFreq(SuccPred)
787 * MBPI->getEdgeProbability(SuccPred, Succ);
788 if (Freq > SuccBestPred)
789 SuccBestPred = Freq;
790 }
791 // Qin is Succ's best unplaced incoming edge that isn't BB
792 BlockFrequency Qin = SuccBestPred;
793 // If it doesn't have a post-dominating successor, here is the calculation:
794 // BB BB
795 // | \Qout | \
796 // P| C | =
797 // = C' | C
798 // | /Qin | |
799 // | / | C' (+Succ)
800 // Succ Succ /|
801 // / \ | \/ |
Kyle Butta466b362017-02-15 19:49:14 +0000802 // U/ =V | == |
Kyle Butt5818a512017-01-31 23:48:32 +0000803 // / \ | / \|
804 // D E D E
805 // '=' : Branch taken for that CFG edge
806 // Cost in the first case is: P + V
807 // For this calculation, we always assume P > Qout. If Qout > P
808 // The result of this function will be ignored at the caller.
Kyle Butt132e8442017-04-10 22:28:18 +0000809 // Let F = SuccFreq - Qin
810 // Cost in the second case is: Qout + min(Qin, F) * U + max(Qin, F) * V
Kyle Butt5818a512017-01-31 23:48:32 +0000811
812 if (PDom == nullptr || !Succ->isSuccessor(PDom)) {
813 BranchProbability UProb = BestSuccSucc;
814 BranchProbability VProb = AdjustedSuccSumProb - UProb;
Kyle Butt132e8442017-04-10 22:28:18 +0000815 BlockFrequency F = SuccFreq - Qin;
Kyle Butt5818a512017-01-31 23:48:32 +0000816 BlockFrequency V = SuccFreq * VProb;
Kyle Butt132e8442017-04-10 22:28:18 +0000817 BlockFrequency QinU = std::min(Qin, F) * UProb;
Kyle Butt5818a512017-01-31 23:48:32 +0000818 BlockFrequency BaseCost = P + V;
Kyle Butt132e8442017-04-10 22:28:18 +0000819 BlockFrequency DupCost = Qout + QinU + std::max(Qin, F) * VProb;
Kyle Butt5818a512017-01-31 23:48:32 +0000820 return greaterWithBias(BaseCost, DupCost, EntryFreq);
821 }
822 BranchProbability UProb = MBPI->getEdgeProbability(Succ, PDom);
823 BranchProbability VProb = AdjustedSuccSumProb - UProb;
824 BlockFrequency U = SuccFreq * UProb;
825 BlockFrequency V = SuccFreq * VProb;
Kyle Butt132e8442017-04-10 22:28:18 +0000826 BlockFrequency F = SuccFreq - Qin;
Kyle Butt5818a512017-01-31 23:48:32 +0000827 // If there is a post-dominating successor, here is the calculation:
828 // BB BB BB BB
Kyle Butt132e8442017-04-10 22:28:18 +0000829 // | \Qout | \ | \Qout | \
830 // |P C | = |P C | =
831 // = C' |P C = C' |P C
832 // | /Qin | | | /Qin | |
833 // | / | C' (+Succ) | / | C' (+Succ)
834 // Succ Succ /| Succ Succ /|
835 // | \ V | \/ | | \ V | \/ |
836 // |U \ |U /\ =? |U = |U /\ |
837 // = D = = =?| | D | = =|
838 // | / |/ D | / |/ D
839 // | / | / | = | /
840 // |/ | / |/ | =
841 // Dom Dom Dom Dom
Kyle Butt5818a512017-01-31 23:48:32 +0000842 // '=' : Branch taken for that CFG edge
843 // The cost for taken branches in the first case is P + U
Kyle Butt132e8442017-04-10 22:28:18 +0000844 // Let F = SuccFreq - Qin
Kyle Butt5818a512017-01-31 23:48:32 +0000845 // The cost in the second case (assuming independence), given the layout:
Kyle Butt132e8442017-04-10 22:28:18 +0000846 // BB, Succ, (C+Succ), D, Dom or the layout:
847 // BB, Succ, D, Dom, (C+Succ)
848 // is Qout + max(F, Qin) * U + min(F, Qin)
Kyle Butta466b362017-02-15 19:49:14 +0000849 // compare P + U vs Qout + P * U + Qin.
Kyle Butt5818a512017-01-31 23:48:32 +0000850 //
851 // The 3rd and 4th cases cover when Dom would be chosen to follow Succ.
852 //
853 // For the 3rd case, the cost is P + 2 * V
Kyle Butt132e8442017-04-10 22:28:18 +0000854 // For the 4th case, the cost is Qout + min(Qin, F) * U + max(Qin, F) * V + V
855 // We choose 4 over 3 when (P + V) > Qout + min(Qin, F) * U + max(Qin, F) * V
Kyle Butta466b362017-02-15 19:49:14 +0000856 if (UProb > AdjustedSuccSumProb / 2 &&
857 !hasBetterLayoutPredecessor(Succ, PDom, *BlockToChain[PDom], UProb, UProb,
858 Chain, BlockFilter))
Kyle Butt5818a512017-01-31 23:48:32 +0000859 // Cases 3 & 4
Kyle Butt132e8442017-04-10 22:28:18 +0000860 return greaterWithBias(
861 (P + V), (Qout + std::max(Qin, F) * VProb + std::min(Qin, F) * UProb),
862 EntryFreq);
Kyle Butt5818a512017-01-31 23:48:32 +0000863 // Cases 1 & 2
Kyle Butt132e8442017-04-10 22:28:18 +0000864 return greaterWithBias((P + U),
865 (Qout + std::min(Qin, F) * AdjustedSuccSumProb +
866 std::max(Qin, F) * UProb),
867 EntryFreq);
Kyle Butt5818a512017-01-31 23:48:32 +0000868}
869
Kyle Butta466b362017-02-15 19:49:14 +0000870/// Check for a trellis layout. \p BB is the upper part of a trellis if its
871/// successors form the lower part of a trellis. A successor set S forms the
872/// lower part of a trellis if all of the predecessors of S are either in S or
873/// have all of S as successors. We ignore trellises where BB doesn't have 2
874/// successors because for fewer than 2, it's trivial, and for 3 or greater they
875/// are very uncommon and complex to compute optimally. Allowing edges within S
876/// is not strictly a trellis, but the same algorithm works, so we allow it.
877bool MachineBlockPlacement::isTrellis(
878 const MachineBasicBlock *BB,
879 const SmallVectorImpl<MachineBasicBlock *> &ViableSuccs,
880 const BlockChain &Chain, const BlockFilterSet *BlockFilter) {
881 // Technically BB could form a trellis with branching factor higher than 2.
882 // But that's extremely uncommon.
883 if (BB->succ_size() != 2 || ViableSuccs.size() != 2)
884 return false;
885
886 SmallPtrSet<const MachineBasicBlock *, 2> Successors(BB->succ_begin(),
887 BB->succ_end());
888 // To avoid reviewing the same predecessors twice.
889 SmallPtrSet<const MachineBasicBlock *, 8> SeenPreds;
890
891 for (MachineBasicBlock *Succ : ViableSuccs) {
892 int PredCount = 0;
893 for (auto SuccPred : Succ->predecessors()) {
894 // Allow triangle successors, but don't count them.
Dehao Chena68ea002017-03-23 23:28:09 +0000895 if (Successors.count(SuccPred)) {
896 // Make sure that it is actually a triangle.
897 for (MachineBasicBlock *CheckSucc : SuccPred->successors())
898 if (!Successors.count(CheckSucc))
899 return false;
Kyle Butta466b362017-02-15 19:49:14 +0000900 continue;
Dehao Chena68ea002017-03-23 23:28:09 +0000901 }
Kyle Butta466b362017-02-15 19:49:14 +0000902 const BlockChain *PredChain = BlockToChain[SuccPred];
903 if (SuccPred == BB || (BlockFilter && !BlockFilter->count(SuccPred)) ||
904 PredChain == &Chain || PredChain == BlockToChain[Succ])
905 continue;
906 ++PredCount;
907 // Perform the successor check only once.
908 if (!SeenPreds.insert(SuccPred).second)
909 continue;
910 if (!hasSameSuccessors(*SuccPred, Successors))
911 return false;
912 }
913 // If one of the successors has only BB as a predecessor, it is not a
914 // trellis.
915 if (PredCount < 1)
916 return false;
917 }
918 return true;
919}
920
921/// Pick the highest total weight pair of edges that can both be laid out.
922/// The edges in \p Edges[0] are assumed to have a different destination than
923/// the edges in \p Edges[1]. Simple counting shows that the best pair is either
924/// the individual highest weight edges to the 2 different destinations, or in
925/// case of a conflict, one of them should be replaced with a 2nd best edge.
926std::pair<MachineBlockPlacement::WeightedEdge,
927 MachineBlockPlacement::WeightedEdge>
928MachineBlockPlacement::getBestNonConflictingEdges(
929 const MachineBasicBlock *BB,
Benjamin Kramer2b371752017-04-12 13:26:28 +0000930 MutableArrayRef<SmallVector<MachineBlockPlacement::WeightedEdge, 8>>
931 Edges) {
Kyle Butta466b362017-02-15 19:49:14 +0000932 // Sort the edges, and then for each successor, find the best incoming
933 // predecessor. If the best incoming predecessors aren't the same,
934 // then that is clearly the best layout. If there is a conflict, one of the
935 // successors will have to fallthrough from the second best predecessor. We
936 // compare which combination is better overall.
937
938 // Sort for highest frequency.
939 auto Cmp = [](WeightedEdge A, WeightedEdge B) { return A.Weight > B.Weight; };
940
941 std::stable_sort(Edges[0].begin(), Edges[0].end(), Cmp);
942 std::stable_sort(Edges[1].begin(), Edges[1].end(), Cmp);
943 auto BestA = Edges[0].begin();
944 auto BestB = Edges[1].begin();
945 // Arrange for the correct answer to be in BestA and BestB
946 // If the 2 best edges don't conflict, the answer is already there.
947 if (BestA->Src == BestB->Src) {
948 // Compare the total fallthrough of (Best + Second Best) for both pairs
949 auto SecondBestA = std::next(BestA);
950 auto SecondBestB = std::next(BestB);
951 BlockFrequency BestAScore = BestA->Weight + SecondBestB->Weight;
952 BlockFrequency BestBScore = BestB->Weight + SecondBestA->Weight;
953 if (BestAScore < BestBScore)
954 BestA = SecondBestA;
955 else
956 BestB = SecondBestB;
957 }
958 // Arrange for the BB edge to be in BestA if it exists.
959 if (BestB->Src == BB)
960 std::swap(BestA, BestB);
961 return std::make_pair(*BestA, *BestB);
962}
963
964/// Get the best successor from \p BB based on \p BB being part of a trellis.
965/// We only handle trellises with 2 successors, so the algorithm is
966/// straightforward: Find the best pair of edges that don't conflict. We find
967/// the best incoming edge for each successor in the trellis. If those conflict,
968/// we consider which of them should be replaced with the second best.
969/// Upon return the two best edges will be in \p BestEdges. If one of the edges
970/// comes from \p BB, it will be in \p BestEdges[0]
971MachineBlockPlacement::BlockAndTailDupResult
972MachineBlockPlacement::getBestTrellisSuccessor(
973 const MachineBasicBlock *BB,
974 const SmallVectorImpl<MachineBasicBlock *> &ViableSuccs,
975 BranchProbability AdjustedSumProb, const BlockChain &Chain,
976 const BlockFilterSet *BlockFilter) {
977
978 BlockAndTailDupResult Result = {nullptr, false};
979 SmallPtrSet<const MachineBasicBlock *, 4> Successors(BB->succ_begin(),
980 BB->succ_end());
981
982 // We assume size 2 because it's common. For general n, we would have to do
983 // the Hungarian algorithm, but it's not worth the complexity because more
984 // than 2 successors is fairly uncommon, and a trellis even more so.
985 if (Successors.size() != 2 || ViableSuccs.size() != 2)
986 return Result;
987
988 // Collect the edge frequencies of all edges that form the trellis.
Benjamin Kramer2b371752017-04-12 13:26:28 +0000989 SmallVector<WeightedEdge, 8> Edges[2];
Kyle Butta466b362017-02-15 19:49:14 +0000990 int SuccIndex = 0;
991 for (auto Succ : ViableSuccs) {
992 for (MachineBasicBlock *SuccPred : Succ->predecessors()) {
993 // Skip any placed predecessors that are not BB
994 if (SuccPred != BB)
995 if ((BlockFilter && !BlockFilter->count(SuccPred)) ||
996 BlockToChain[SuccPred] == &Chain ||
997 BlockToChain[SuccPred] == BlockToChain[Succ])
998 continue;
999 BlockFrequency EdgeFreq = MBFI->getBlockFreq(SuccPred) *
1000 MBPI->getEdgeProbability(SuccPred, Succ);
1001 Edges[SuccIndex].push_back({EdgeFreq, SuccPred, Succ});
1002 }
1003 ++SuccIndex;
1004 }
1005
1006 // Pick the best combination of 2 edges from all the edges in the trellis.
1007 WeightedEdge BestA, BestB;
1008 std::tie(BestA, BestB) = getBestNonConflictingEdges(BB, Edges);
1009
1010 if (BestA.Src != BB) {
1011 // If we have a trellis, and BB doesn't have the best fallthrough edges,
1012 // we shouldn't choose any successor. We've already looked and there's a
1013 // better fallthrough edge for all the successors.
Nicola Zaghen0818e782018-05-14 12:53:11 +00001014 LLVM_DEBUG(dbgs() << "Trellis, but not one of the chosen edges.\n");
Kyle Butta466b362017-02-15 19:49:14 +00001015 return Result;
1016 }
1017
1018 // Did we pick the triangle edge? If tail-duplication is profitable, do
1019 // that instead. Otherwise merge the triangle edge now while we know it is
1020 // optimal.
1021 if (BestA.Dest == BestB.Src) {
1022 // The edges are BB->Succ1->Succ2, and we're looking to see if BB->Succ2
1023 // would be better.
1024 MachineBasicBlock *Succ1 = BestA.Dest;
1025 MachineBasicBlock *Succ2 = BestB.Dest;
1026 // Check to see if tail-duplication would be profitable.
Tim Shene1a4b172018-03-30 17:51:00 +00001027 if (allowTailDupPlacement() && shouldTailDuplicate(Succ2) &&
Kyle Butta466b362017-02-15 19:49:14 +00001028 canTailDuplicateUnplacedPreds(BB, Succ2, Chain, BlockFilter) &&
1029 isProfitableToTailDup(BB, Succ2, MBPI->getEdgeProbability(BB, Succ1),
1030 Chain, BlockFilter)) {
Nicola Zaghen0818e782018-05-14 12:53:11 +00001031 LLVM_DEBUG(BranchProbability Succ2Prob = getAdjustedProbability(
1032 MBPI->getEdgeProbability(BB, Succ2), AdjustedSumProb);
1033 dbgs() << " Selected: " << getBlockName(Succ2)
1034 << ", probability: " << Succ2Prob
1035 << " (Tail Duplicate)\n");
Kyle Butta466b362017-02-15 19:49:14 +00001036 Result.BB = Succ2;
1037 Result.ShouldTailDup = true;
1038 return Result;
1039 }
1040 }
1041 // We have already computed the optimal edge for the other side of the
1042 // trellis.
Kyle Butt9e601a42017-02-23 21:22:24 +00001043 ComputedEdges[BestB.Src] = { BestB.Dest, false };
Kyle Butta466b362017-02-15 19:49:14 +00001044
1045 auto TrellisSucc = BestA.Dest;
Nicola Zaghen0818e782018-05-14 12:53:11 +00001046 LLVM_DEBUG(BranchProbability SuccProb = getAdjustedProbability(
1047 MBPI->getEdgeProbability(BB, TrellisSucc), AdjustedSumProb);
1048 dbgs() << " Selected: " << getBlockName(TrellisSucc)
1049 << ", probability: " << SuccProb << " (Trellis)\n");
Kyle Butta466b362017-02-15 19:49:14 +00001050 Result.BB = TrellisSucc;
1051 return Result;
1052}
Kyle Butt5818a512017-01-31 23:48:32 +00001053
Tim Shene1a4b172018-03-30 17:51:00 +00001054/// When the option allowTailDupPlacement() is on, this method checks if the
Kyle Butt5818a512017-01-31 23:48:32 +00001055/// fallthrough candidate block \p Succ (of block \p BB) can be tail-duplicated
1056/// into all of its unplaced, unfiltered predecessors, that are not BB.
1057bool MachineBlockPlacement::canTailDuplicateUnplacedPreds(
Kyle Butt7a252572017-02-04 02:26:32 +00001058 const MachineBasicBlock *BB, MachineBasicBlock *Succ,
1059 const BlockChain &Chain, const BlockFilterSet *BlockFilter) {
Kyle Butt5818a512017-01-31 23:48:32 +00001060 if (!shouldTailDuplicate(Succ))
1061 return false;
1062
Kyle Butta466b362017-02-15 19:49:14 +00001063 // For CFG checking.
1064 SmallPtrSet<const MachineBasicBlock *, 4> Successors(BB->succ_begin(),
1065 BB->succ_end());
Kyle Butt5818a512017-01-31 23:48:32 +00001066 for (MachineBasicBlock *Pred : Succ->predecessors()) {
1067 // Make sure all unplaced and unfiltered predecessors can be
1068 // tail-duplicated into.
Kyle Butt7a252572017-02-04 02:26:32 +00001069 // Skip any blocks that are already placed or not in this loop.
Kyle Butt5818a512017-01-31 23:48:32 +00001070 if (Pred == BB || (BlockFilter && !BlockFilter->count(Pred))
1071 || BlockToChain[Pred] == &Chain)
1072 continue;
Kyle Butta466b362017-02-15 19:49:14 +00001073 if (!TailDup.canTailDuplicate(Succ, Pred)) {
1074 if (Successors.size() > 1 && hasSameSuccessors(*Pred, Successors))
1075 // This will result in a trellis after tail duplication, so we don't
1076 // need to copy Succ into this predecessor. In the presence
1077 // of a trellis tail duplication can continue to be profitable.
1078 // For example:
1079 // A A
1080 // |\ |\
1081 // | \ | \
1082 // | C | C+BB
1083 // | / | |
1084 // |/ | |
1085 // BB => BB |
1086 // |\ |\/|
1087 // | \ |/\|
1088 // | D | D
1089 // | / | /
1090 // |/ |/
1091 // Succ Succ
1092 //
1093 // After BB was duplicated into C, the layout looks like the one on the
1094 // right. BB and C now have the same successors. When considering
1095 // whether Succ can be duplicated into all its unplaced predecessors, we
1096 // ignore C.
1097 // We can do this because C already has a profitable fallthrough, namely
1098 // D. TODO(iteratee): ignore sufficiently cold predecessors for
1099 // duplication and for this test.
1100 //
1101 // This allows trellises to be laid out in 2 separate chains
1102 // (A,B,Succ,...) and later (C,D,...) This is a reasonable heuristic
1103 // because it allows the creation of 2 fallthrough paths with links
1104 // between them, and we correctly identify the best layout for these
1105 // CFGs. We want to extend trellises that the user created in addition
1106 // to trellises created by tail-duplication, so we just look for the
1107 // CFG.
1108 continue;
Kyle Butt5818a512017-01-31 23:48:32 +00001109 return false;
Kyle Butta466b362017-02-15 19:49:14 +00001110 }
Kyle Butt5818a512017-01-31 23:48:32 +00001111 }
1112 return true;
1113}
1114
Kyle Buttc160e2a2017-03-03 01:00:22 +00001115/// Find chains of triangles where we believe it would be profitable to
1116/// tail-duplicate them all, but a local analysis would not find them.
1117/// There are 3 ways this can be profitable:
1118/// 1) The post-dominators marked 50% are actually taken 55% (This shrinks with
1119/// longer chains)
1120/// 2) The chains are statically correlated. Branch probabilities have a very
1121/// U-shaped distribution.
1122/// [http://nrs.harvard.edu/urn-3:HUL.InstRepos:24015805]
1123/// If the branches in a chain are likely to be from the same side of the
1124/// distribution as their predecessor, but are independent at runtime, this
1125/// transformation is profitable. (Because the cost of being wrong is a small
1126/// fixed cost, unlike the standard triangle layout where the cost of being
1127/// wrong scales with the # of triangles.)
1128/// 3) The chains are dynamically correlated. If the probability that a previous
1129/// branch was taken positively influences whether the next branch will be
1130/// taken
1131/// We believe that 2 and 3 are common enough to justify the small margin in 1.
1132void MachineBlockPlacement::precomputeTriangleChains() {
1133 struct TriangleChain {
Benjamin Kramer2b371752017-04-12 13:26:28 +00001134 std::vector<MachineBasicBlock *> Edges;
Eugene Zelenko2de563a2017-08-24 21:21:39 +00001135
Benjamin Kramer2b371752017-04-12 13:26:28 +00001136 TriangleChain(MachineBasicBlock *src, MachineBasicBlock *dst)
1137 : Edges({src, dst}) {}
Kyle Buttc160e2a2017-03-03 01:00:22 +00001138
1139 void append(MachineBasicBlock *dst) {
Benjamin Kramer2b371752017-04-12 13:26:28 +00001140 assert(getKey()->isSuccessor(dst) &&
Kyle Buttc160e2a2017-03-03 01:00:22 +00001141 "Attempting to append a block that is not a successor.");
Benjamin Kramer2b371752017-04-12 13:26:28 +00001142 Edges.push_back(dst);
Kyle Buttc160e2a2017-03-03 01:00:22 +00001143 }
1144
Benjamin Kramer2b371752017-04-12 13:26:28 +00001145 unsigned count() const { return Edges.size() - 1; }
1146
1147 MachineBasicBlock *getKey() const {
1148 return Edges.back();
Kyle Buttc160e2a2017-03-03 01:00:22 +00001149 }
1150 };
1151
1152 if (TriangleChainCount == 0)
1153 return;
1154
Nicola Zaghen0818e782018-05-14 12:53:11 +00001155 LLVM_DEBUG(dbgs() << "Pre-computing triangle chains.\n");
Kyle Buttc160e2a2017-03-03 01:00:22 +00001156 // Map from last block to the chain that contains it. This allows us to extend
1157 // chains as we find new triangles.
1158 DenseMap<const MachineBasicBlock *, TriangleChain> TriangleChainMap;
1159 for (MachineBasicBlock &BB : *F) {
1160 // If BB doesn't have 2 successors, it doesn't start a triangle.
1161 if (BB.succ_size() != 2)
1162 continue;
1163 MachineBasicBlock *PDom = nullptr;
1164 for (MachineBasicBlock *Succ : BB.successors()) {
1165 if (!MPDT->dominates(Succ, &BB))
1166 continue;
1167 PDom = Succ;
1168 break;
1169 }
1170 // If BB doesn't have a post-dominating successor, it doesn't form a
1171 // triangle.
1172 if (PDom == nullptr)
1173 continue;
1174 // If PDom has a hint that it is low probability, skip this triangle.
1175 if (MBPI->getEdgeProbability(&BB, PDom) < BranchProbability(50, 100))
1176 continue;
1177 // If PDom isn't eligible for duplication, this isn't the kind of triangle
1178 // we're looking for.
1179 if (!shouldTailDuplicate(PDom))
1180 continue;
1181 bool CanTailDuplicate = true;
1182 // If PDom can't tail-duplicate into it's non-BB predecessors, then this
1183 // isn't the kind of triangle we're looking for.
1184 for (MachineBasicBlock* Pred : PDom->predecessors()) {
1185 if (Pred == &BB)
1186 continue;
1187 if (!TailDup.canTailDuplicate(PDom, Pred)) {
1188 CanTailDuplicate = false;
1189 break;
1190 }
1191 }
1192 // If we can't tail-duplicate PDom to its predecessors, then skip this
1193 // triangle.
1194 if (!CanTailDuplicate)
1195 continue;
1196
1197 // Now we have an interesting triangle. Insert it if it's not part of an
Hiroshi Inoue0a8e8962017-06-16 12:23:04 +00001198 // existing chain.
Kyle Buttc160e2a2017-03-03 01:00:22 +00001199 // Note: This cannot be replaced with a call insert() or emplace() because
1200 // the find key is BB, but the insert/emplace key is PDom.
1201 auto Found = TriangleChainMap.find(&BB);
1202 // If it is, remove the chain from the map, grow it, and put it back in the
1203 // map with the end as the new key.
1204 if (Found != TriangleChainMap.end()) {
1205 TriangleChain Chain = std::move(Found->second);
1206 TriangleChainMap.erase(Found);
1207 Chain.append(PDom);
1208 TriangleChainMap.insert(std::make_pair(Chain.getKey(), std::move(Chain)));
1209 } else {
1210 auto InsertResult = TriangleChainMap.try_emplace(PDom, &BB, PDom);
Benjamin Kramer4e5abdf2017-04-12 13:26:31 +00001211 assert(InsertResult.second && "Block seen twice.");
1212 (void)InsertResult;
Kyle Buttc160e2a2017-03-03 01:00:22 +00001213 }
1214 }
1215
Kyle Butt718593b2017-04-12 18:30:32 +00001216 // Iterating over a DenseMap is safe here, because the only thing in the body
1217 // of the loop is inserting into another DenseMap (ComputedEdges).
1218 // ComputedEdges is never iterated, so this doesn't lead to non-determinism.
Kyle Buttc160e2a2017-03-03 01:00:22 +00001219 for (auto &ChainPair : TriangleChainMap) {
1220 TriangleChain &Chain = ChainPair.second;
1221 // Benchmarking has shown that due to branch correlation duplicating 2 or
1222 // more triangles is profitable, despite the calculations assuming
1223 // independence.
Benjamin Kramer2b371752017-04-12 13:26:28 +00001224 if (Chain.count() < TriangleChainCount)
Kyle Buttc160e2a2017-03-03 01:00:22 +00001225 continue;
Benjamin Kramer2b371752017-04-12 13:26:28 +00001226 MachineBasicBlock *dst = Chain.Edges.back();
1227 Chain.Edges.pop_back();
1228 for (MachineBasicBlock *src : reverse(Chain.Edges)) {
Nicola Zaghen0818e782018-05-14 12:53:11 +00001229 LLVM_DEBUG(dbgs() << "Marking edge: " << getBlockName(src) << "->"
1230 << getBlockName(dst)
1231 << " as pre-computed based on triangles.\n");
Benjamin Kramer4e5abdf2017-04-12 13:26:31 +00001232
1233 auto InsertResult = ComputedEdges.insert({src, {dst, true}});
1234 assert(InsertResult.second && "Block seen twice.");
1235 (void)InsertResult;
1236
Kyle Buttc160e2a2017-03-03 01:00:22 +00001237 dst = src;
1238 }
1239 }
1240}
1241
Dehao Chen97615522016-06-14 22:27:17 +00001242// When profile is not present, return the StaticLikelyProb.
1243// When profile is available, we need to handle the triangle-shape CFG.
1244static BranchProbability getLayoutSuccessorProbThreshold(
Kyle Butt7a252572017-02-04 02:26:32 +00001245 const MachineBasicBlock *BB) {
Easwaran Ramanfe7b9dc2017-12-22 01:33:52 +00001246 if (!BB->getParent()->getFunction().hasProfileData())
Dehao Chen97615522016-06-14 22:27:17 +00001247 return BranchProbability(StaticLikelyProb, 100);
1248 if (BB->succ_size() == 2) {
1249 const MachineBasicBlock *Succ1 = *BB->succ_begin();
1250 const MachineBasicBlock *Succ2 = *(BB->succ_begin() + 1);
Xinliang David Lib2ccb9b2016-06-15 03:03:30 +00001251 if (Succ1->isSuccessor(Succ2) || Succ2->isSuccessor(Succ1)) {
1252 /* See case 1 below for the cost analysis. For BB->Succ to
1253 * be taken with smaller cost, the following needs to hold:
Kyle Butt5818a512017-01-31 23:48:32 +00001254 * Prob(BB->Succ) > 2 * Prob(BB->Pred)
1255 * So the threshold T in the calculation below
1256 * (1-T) * Prob(BB->Succ) > T * Prob(BB->Pred)
1257 * So T / (1 - T) = 2, Yielding T = 2/3
1258 * Also adding user specified branch bias, we have
Xinliang David Lib2ccb9b2016-06-15 03:03:30 +00001259 * T = (2/3)*(ProfileLikelyProb/50)
1260 * = (2*ProfileLikelyProb)/150)
1261 */
1262 return BranchProbability(2 * ProfileLikelyProb, 150);
1263 }
Dehao Chen97615522016-06-14 22:27:17 +00001264 }
1265 return BranchProbability(ProfileLikelyProb, 100);
Xinliang David Lifa405a62016-06-13 20:24:19 +00001266}
1267
1268/// Checks to see if the layout candidate block \p Succ has a better layout
1269/// predecessor than \c BB. If yes, returns true.
Kyle Butt5818a512017-01-31 23:48:32 +00001270/// \p SuccProb: The probability adjusted for only remaining blocks.
1271/// Only used for logging
1272/// \p RealSuccProb: The un-adjusted probability.
1273/// \p Chain: The chain that BB belongs to and Succ is being considered for.
1274/// \p BlockFilter: if non-null, the set of blocks that make up the loop being
1275/// considered
Xinliang David Lifa405a62016-06-13 20:24:19 +00001276bool MachineBlockPlacement::hasBetterLayoutPredecessor(
Kyle Butt7a252572017-02-04 02:26:32 +00001277 const MachineBasicBlock *BB, const MachineBasicBlock *Succ,
1278 const BlockChain &SuccChain, BranchProbability SuccProb,
1279 BranchProbability RealSuccProb, const BlockChain &Chain,
1280 const BlockFilterSet *BlockFilter) {
Xinliang David Lifa405a62016-06-13 20:24:19 +00001281
Sjoerd Meijeraafccf02016-07-15 18:41:56 +00001282 // There isn't a better layout when there are no unscheduled predecessors.
Xinliang David Lifa405a62016-06-13 20:24:19 +00001283 if (SuccChain.UnscheduledPredecessors == 0)
1284 return false;
1285
1286 // There are two basic scenarios here:
1287 // -------------------------------------
Sjoerd Meijeraafccf02016-07-15 18:41:56 +00001288 // Case 1: triangular shape CFG (if-then):
Xinliang David Lifa405a62016-06-13 20:24:19 +00001289 // BB
1290 // | \
1291 // | \
1292 // | Pred
1293 // | /
1294 // Succ
1295 // In this case, we are evaluating whether to select edge -> Succ, e.g.
1296 // set Succ as the layout successor of BB. Picking Succ as BB's
Sjoerd Meijeraafccf02016-07-15 18:41:56 +00001297 // successor breaks the CFG constraints (FIXME: define these constraints).
1298 // With this layout, Pred BB
Xinliang David Lifa405a62016-06-13 20:24:19 +00001299 // is forced to be outlined, so the overall cost will be cost of the
1300 // branch taken from BB to Pred, plus the cost of back taken branch
Sjoerd Meijeraafccf02016-07-15 18:41:56 +00001301 // from Pred to Succ, as well as the additional cost associated
Xinliang David Lifa405a62016-06-13 20:24:19 +00001302 // with the needed unconditional jump instruction from Pred To Succ.
Sjoerd Meijeraafccf02016-07-15 18:41:56 +00001303
Xinliang David Lifa405a62016-06-13 20:24:19 +00001304 // The cost of the topological order layout is the taken branch cost
1305 // from BB to Succ, so to make BB->Succ a viable candidate, the following
1306 // must hold:
1307 // 2 * freq(BB->Pred) * taken_branch_cost + unconditional_jump_cost
1308 // < freq(BB->Succ) * taken_branch_cost.
1309 // Ignoring unconditional jump cost, we get
1310 // freq(BB->Succ) > 2 * freq(BB->Pred), i.e.,
1311 // prob(BB->Succ) > 2 * prob(BB->Pred)
1312 //
Sjoerd Meijeraafccf02016-07-15 18:41:56 +00001313 // When real profile data is available, we can precisely compute the
1314 // probability threshold that is needed for edge BB->Succ to be considered.
1315 // Without profile data, the heuristic requires the branch bias to be
Xinliang David Lifa405a62016-06-13 20:24:19 +00001316 // a lot larger to make sure the signal is very strong (e.g. 80% default).
1317 // -----------------------------------------------------------------
Sjoerd Meijeraafccf02016-07-15 18:41:56 +00001318 // Case 2: diamond like CFG (if-then-else):
Xinliang David Lifa405a62016-06-13 20:24:19 +00001319 // S
1320 // / \
1321 // | \
1322 // BB Pred
1323 // \ /
1324 // Succ
1325 // ..
Sjoerd Meijeraafccf02016-07-15 18:41:56 +00001326 //
1327 // The current block is BB and edge BB->Succ is now being evaluated.
1328 // Note that edge S->BB was previously already selected because
1329 // prob(S->BB) > prob(S->Pred).
1330 // At this point, 2 blocks can be placed after BB: Pred or Succ. If we
1331 // choose Pred, we will have a topological ordering as shown on the left
1332 // in the picture below. If we choose Succ, we have the solution as shown
1333 // on the right:
1334 //
1335 // topo-order:
1336 //
1337 // S----- ---S
1338 // | | | |
1339 // ---BB | | BB
1340 // | | | |
Hiroshi Inoue0a8e8962017-06-16 12:23:04 +00001341 // | Pred-- | Succ--
Sjoerd Meijeraafccf02016-07-15 18:41:56 +00001342 // | | | |
Hiroshi Inoue0a8e8962017-06-16 12:23:04 +00001343 // ---Succ ---Pred--
Sjoerd Meijeraafccf02016-07-15 18:41:56 +00001344 //
1345 // cost = freq(S->Pred) + freq(BB->Succ) cost = 2 * freq (S->Pred)
1346 // = freq(S->Pred) + freq(S->BB)
1347 //
1348 // If we have profile data (i.e, branch probabilities can be trusted), the
1349 // cost (number of taken branches) with layout S->BB->Succ->Pred is 2 *
1350 // freq(S->Pred) while the cost of topo order is freq(S->Pred) + freq(S->BB).
1351 // We know Prob(S->BB) > Prob(S->Pred), so freq(S->BB) > freq(S->Pred), which
1352 // means the cost of topological order is greater.
Xinliang David Lifa405a62016-06-13 20:24:19 +00001353 // When profile data is not available, however, we need to be more
1354 // conservative. If the branch prediction is wrong, breaking the topo-order
1355 // will actually yield a layout with large cost. For this reason, we need
Sjoerd Meijeraafccf02016-07-15 18:41:56 +00001356 // strong biased branch at block S with Prob(S->BB) in order to select
1357 // BB->Succ. This is equivalent to looking the CFG backward with backward
Xinliang David Lifa405a62016-06-13 20:24:19 +00001358 // edge: Prob(Succ->BB) needs to >= HotProb in order to be selected (without
1359 // profile data).
Kyle Butt9f1f15e2016-07-29 18:09:28 +00001360 // --------------------------------------------------------------------------
1361 // Case 3: forked diamond
1362 // S
1363 // / \
1364 // / \
1365 // BB Pred
1366 // | \ / |
1367 // | \ / |
1368 // | X |
1369 // | / \ |
1370 // | / \ |
1371 // S1 S2
1372 //
1373 // The current block is BB and edge BB->S1 is now being evaluated.
1374 // As above S->BB was already selected because
1375 // prob(S->BB) > prob(S->Pred). Assume that prob(BB->S1) >= prob(BB->S2).
1376 //
1377 // topo-order:
1378 //
1379 // S-------| ---S
1380 // | | | |
1381 // ---BB | | BB
1382 // | | | |
1383 // | Pred----| | S1----
1384 // | | | |
1385 // --(S1 or S2) ---Pred--
Kyle Butta466b362017-02-15 19:49:14 +00001386 // |
1387 // S2
Kyle Butt9f1f15e2016-07-29 18:09:28 +00001388 //
1389 // topo-cost = freq(S->Pred) + freq(BB->S1) + freq(BB->S2)
1390 // + min(freq(Pred->S1), freq(Pred->S2))
1391 // Non-topo-order cost:
Kyle Butt9f1f15e2016-07-29 18:09:28 +00001392 // non-topo-cost = 2 * freq(S->Pred) + freq(BB->S2).
1393 // To be conservative, we can assume that min(freq(Pred->S1), freq(Pred->S2))
1394 // is 0. Then the non topo layout is better when
1395 // freq(S->Pred) < freq(BB->S1).
1396 // This is exactly what is checked below.
1397 // Note there are other shapes that apply (Pred may not be a single block,
1398 // but they all fit this general pattern.)
Dehao Chen97615522016-06-14 22:27:17 +00001399 BranchProbability HotProb = getLayoutSuccessorProbThreshold(BB);
Xinliang David Lifa405a62016-06-13 20:24:19 +00001400
Xinliang David Lifa405a62016-06-13 20:24:19 +00001401 // Make sure that a hot successor doesn't have a globally more
1402 // important predecessor.
1403 BlockFrequency CandidateEdgeFreq = MBFI->getBlockFreq(BB) * RealSuccProb;
1404 bool BadCFGConflict = false;
1405
1406 for (MachineBasicBlock *Pred : Succ->predecessors()) {
1407 if (Pred == Succ || BlockToChain[Pred] == &SuccChain ||
1408 (BlockFilter && !BlockFilter->count(Pred)) ||
Kyle Butt5818a512017-01-31 23:48:32 +00001409 BlockToChain[Pred] == &Chain ||
1410 // This check is redundant except for look ahead. This function is
1411 // called for lookahead by isProfitableToTailDup when BB hasn't been
1412 // placed yet.
1413 (Pred == BB))
Xinliang David Lifa405a62016-06-13 20:24:19 +00001414 continue;
Kyle Butt9f1f15e2016-07-29 18:09:28 +00001415 // Do backward checking.
1416 // For all cases above, we need a backward checking to filter out edges that
Kyle Butt5818a512017-01-31 23:48:32 +00001417 // are not 'strongly' biased.
Xinliang David Lifa405a62016-06-13 20:24:19 +00001418 // BB Pred
1419 // \ /
1420 // Succ
Sjoerd Meijeraafccf02016-07-15 18:41:56 +00001421 // We select edge BB->Succ if
Xinliang David Lifa405a62016-06-13 20:24:19 +00001422 // freq(BB->Succ) > freq(Succ) * HotProb
1423 // i.e. freq(BB->Succ) > freq(BB->Succ) * HotProb + freq(Pred->Succ) *
1424 // HotProb
1425 // i.e. freq((BB->Succ) * (1 - HotProb) > freq(Pred->Succ) * HotProb
Kyle Butt9f1f15e2016-07-29 18:09:28 +00001426 // Case 1 is covered too, because the first equation reduces to:
1427 // prob(BB->Succ) > HotProb. (freq(Succ) = freq(BB) for a triangle)
Xinliang David Lifa405a62016-06-13 20:24:19 +00001428 BlockFrequency PredEdgeFreq =
1429 MBFI->getBlockFreq(Pred) * MBPI->getEdgeProbability(Pred, Succ);
1430 if (PredEdgeFreq * HotProb >= CandidateEdgeFreq * HotProb.getCompl()) {
1431 BadCFGConflict = true;
1432 break;
1433 }
1434 }
1435
1436 if (BadCFGConflict) {
Nicola Zaghen0818e782018-05-14 12:53:11 +00001437 LLVM_DEBUG(dbgs() << " Not a candidate: " << getBlockName(Succ) << " -> "
1438 << SuccProb << " (prob) (non-cold CFG conflict)\n");
Xinliang David Lifa405a62016-06-13 20:24:19 +00001439 return true;
1440 }
1441
1442 return false;
1443}
1444
Adrian Prantl26b584c2018-05-01 15:54:18 +00001445/// Select the best successor for a block.
Xinliang David Li2e5514a2016-06-11 18:35:40 +00001446///
1447/// This looks across all successors of a particular block and attempts to
1448/// select the "best" one to be the layout successor. It only considers direct
1449/// successors which also pass the block filter. It will attempt to avoid
1450/// breaking CFG structure, but cave and break such structures in the case of
1451/// very hot successor edges.
1452///
Kyle Butt5818a512017-01-31 23:48:32 +00001453/// \returns The best successor block found, or null if none are viable, along
1454/// with a boolean indicating if tail duplication is necessary.
1455MachineBlockPlacement::BlockAndTailDupResult
Kyle Butt7a252572017-02-04 02:26:32 +00001456MachineBlockPlacement::selectBestSuccessor(
1457 const MachineBasicBlock *BB, const BlockChain &Chain,
1458 const BlockFilterSet *BlockFilter) {
Xinliang David Li2e5514a2016-06-11 18:35:40 +00001459 const BranchProbability HotProb(StaticLikelyProb, 100);
1460
Kyle Butt5818a512017-01-31 23:48:32 +00001461 BlockAndTailDupResult BestSucc = { nullptr, false };
Xinliang David Li2e5514a2016-06-11 18:35:40 +00001462 auto BestProb = BranchProbability::getZero();
1463
1464 SmallVector<MachineBasicBlock *, 4> Successors;
1465 auto AdjustedSumProb =
1466 collectViableSuccessors(BB, Chain, BlockFilter, Successors);
1467
Nicola Zaghen0818e782018-05-14 12:53:11 +00001468 LLVM_DEBUG(dbgs() << "Selecting best successor for: " << getBlockName(BB)
1469 << "\n");
Kyle Butt5818a512017-01-31 23:48:32 +00001470
Kyle Butt9e601a42017-02-23 21:22:24 +00001471 // if we already precomputed the best successor for BB, return that if still
1472 // applicable.
1473 auto FoundEdge = ComputedEdges.find(BB);
1474 if (FoundEdge != ComputedEdges.end()) {
1475 MachineBasicBlock *Succ = FoundEdge->second.BB;
1476 ComputedEdges.erase(FoundEdge);
Kyle Butta466b362017-02-15 19:49:14 +00001477 BlockChain *SuccChain = BlockToChain[Succ];
1478 if (BB->isSuccessor(Succ) && (!BlockFilter || BlockFilter->count(Succ)) &&
Kyle Butt9e601a42017-02-23 21:22:24 +00001479 SuccChain != &Chain && Succ == *SuccChain->begin())
1480 return FoundEdge->second;
Kyle Butta466b362017-02-15 19:49:14 +00001481 }
1482
1483 // if BB is part of a trellis, Use the trellis to determine the optimal
1484 // fallthrough edges
1485 if (isTrellis(BB, Successors, Chain, BlockFilter))
1486 return getBestTrellisSuccessor(BB, Successors, AdjustedSumProb, Chain,
1487 BlockFilter);
1488
Kyle Butt5818a512017-01-31 23:48:32 +00001489 // For blocks with CFG violations, we may be able to lay them out anyway with
1490 // tail-duplication. We keep this vector so we can perform the probability
1491 // calculations the minimum number of times.
1492 SmallVector<std::tuple<BranchProbability, MachineBasicBlock *>, 4>
1493 DupCandidates;
Cong Houd6634262015-11-18 00:52:52 +00001494 for (MachineBasicBlock *Succ : Successors) {
Xinliang David Li2e5514a2016-06-11 18:35:40 +00001495 auto RealSuccProb = MBPI->getEdgeProbability(BB, Succ);
1496 BranchProbability SuccProb =
1497 getAdjustedProbability(RealSuccProb, AdjustedSumProb);
Chandler Carruth9fd4e052011-11-13 11:34:53 +00001498
Cong Houd6634262015-11-18 00:52:52 +00001499 BlockChain &SuccChain = *BlockToChain[Succ];
Xinliang David Lifa405a62016-06-13 20:24:19 +00001500 // Skip the edge \c BB->Succ if block \c Succ has a better layout
1501 // predecessor that yields lower global cost.
1502 if (hasBetterLayoutPredecessor(BB, Succ, SuccChain, SuccProb, RealSuccProb,
Kyle Butt5818a512017-01-31 23:48:32 +00001503 Chain, BlockFilter)) {
1504 // If tail duplication would make Succ profitable, place it.
Tim Shene1a4b172018-03-30 17:51:00 +00001505 if (allowTailDupPlacement() && shouldTailDuplicate(Succ))
Kyle Butt5818a512017-01-31 23:48:32 +00001506 DupCandidates.push_back(std::make_tuple(SuccProb, Succ));
Xinliang David Lifa405a62016-06-13 20:24:19 +00001507 continue;
Kyle Butt5818a512017-01-31 23:48:32 +00001508 }
Chandler Carruthb0dadb92011-11-20 11:22:06 +00001509
Nicola Zaghen0818e782018-05-14 12:53:11 +00001510 LLVM_DEBUG(
1511 dbgs() << " Candidate: " << getBlockName(Succ)
1512 << ", probability: " << SuccProb
Xinliang David Lifa405a62016-06-13 20:24:19 +00001513 << (SuccChain.UnscheduledPredecessors != 0 ? " (CFG break)" : "")
1514 << "\n");
Sjoerd Meijer23ce7972016-07-27 08:49:23 +00001515
Kyle Butt5818a512017-01-31 23:48:32 +00001516 if (BestSucc.BB && BestProb >= SuccProb) {
Nicola Zaghen0818e782018-05-14 12:53:11 +00001517 LLVM_DEBUG(dbgs() << " Not the best candidate, continuing\n");
Chandler Carruth9fd4e052011-11-13 11:34:53 +00001518 continue;
Sjoerd Meijer23ce7972016-07-27 08:49:23 +00001519 }
1520
Nicola Zaghen0818e782018-05-14 12:53:11 +00001521 LLVM_DEBUG(dbgs() << " Setting it as best candidate\n");
Kyle Butt5818a512017-01-31 23:48:32 +00001522 BestSucc.BB = Succ;
Cong Hou51550212015-12-01 05:29:22 +00001523 BestProb = SuccProb;
Chandler Carruth9fd4e052011-11-13 11:34:53 +00001524 }
Kyle Butt5818a512017-01-31 23:48:32 +00001525 // Handle the tail duplication candidates in order of decreasing probability.
1526 // Stop at the first one that is profitable. Also stop if they are less
1527 // profitable than BestSucc. Position is important because we preserve it and
1528 // prefer first best match. Here we aren't comparing in order, so we capture
1529 // the position instead.
1530 if (DupCandidates.size() != 0) {
1531 auto cmp =
1532 [](const std::tuple<BranchProbability, MachineBasicBlock *> &a,
1533 const std::tuple<BranchProbability, MachineBasicBlock *> &b) {
1534 return std::get<0>(a) > std::get<0>(b);
1535 };
1536 std::stable_sort(DupCandidates.begin(), DupCandidates.end(), cmp);
1537 }
1538 for(auto &Tup : DupCandidates) {
1539 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 Butt663903f2017-04-10 22:28:22 +00001545 && (isProfitableToTailDup(BB, Succ, BestProb, Chain, BlockFilter))) {
Nicola Zaghen0818e782018-05-14 12:53:11 +00001546 LLVM_DEBUG(dbgs() << " Candidate: " << getBlockName(Succ)
1547 << ", probability: " << DupProb
1548 << " (Tail Duplicate)\n");
Kyle Butt5818a512017-01-31 23:48:32 +00001549 BestSucc.BB = Succ;
1550 BestSucc.ShouldTailDup = true;
1551 break;
1552 }
1553 }
1554
1555 if (BestSucc.BB)
Nicola Zaghen0818e782018-05-14 12:53:11 +00001556 LLVM_DEBUG(dbgs() << " Selected: " << getBlockName(BestSucc.BB) << "\n");
Sjoerd Meijer23ce7972016-07-27 08:49:23 +00001557
Chandler Carruth9fd4e052011-11-13 11:34:53 +00001558 return BestSucc;
1559}
1560
Adrian Prantl26b584c2018-05-01 15:54:18 +00001561/// Select the best block from a worklist.
Chandler Carruthf3fc0052011-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 Meijeraafccf02016-07-15 18:41:56 +00001568/// loop body in order to improve i-cache behavior.
Chandler Carruthf3fc0052011-11-13 11:42:26 +00001569///
1570/// \returns The best block found, or null if none are viable.
1571MachineBasicBlock *MachineBlockPlacement::selectBestCandidateBlock(
Kyle Butt7a252572017-02-04 02:26:32 +00001572 const BlockChain &Chain, SmallVectorImpl<MachineBasicBlock *> &WorkList) {
Chandler Carruthfa976582011-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 Zelenko2de563a2017-08-24 21:21:39 +00001577 WorkList.erase(llvm::remove_if(WorkList,
1578 [&](MachineBasicBlock *BB) {
1579 return BlockToChain.lookup(BB) == &Chain;
1580 }),
Chandler Carruthfa976582011-11-14 09:46:33 +00001581 WorkList.end());
1582
Amaury Secheta5bbcb52016-04-07 21:29:39 +00001583 if (WorkList.empty())
1584 return nullptr;
1585
1586 bool IsEHPad = WorkList[0]->isEHPad();
1587
Craig Topper4ba84432014-04-14 00:51:57 +00001588 MachineBasicBlock *BestBlock = nullptr;
Chandler Carruthf3fc0052011-11-13 11:42:26 +00001589 BlockFrequency BestFreq;
Chandler Carruthbb535bc2015-03-05 03:19:05 +00001590 for (MachineBasicBlock *MBB : WorkList) {
Kyle Butt25ccad82017-05-17 23:44:41 +00001591 assert(MBB->isEHPad() == IsEHPad &&
1592 "EHPad mismatch between block and work list.");
Amaury Secheta5bbcb52016-04-07 21:29:39 +00001593
Chandler Carruthbb535bc2015-03-05 03:19:05 +00001594 BlockChain &SuccChain = *BlockToChain[MBB];
Philip Reames3dee4be2016-03-02 22:40:51 +00001595 if (&SuccChain == &Chain)
Chandler Carruthf3fc0052011-11-13 11:42:26 +00001596 continue;
Junmo Parkc1b22fa2016-03-11 05:07:07 +00001597
Kyle Butt25ccad82017-05-17 23:44:41 +00001598 assert(SuccChain.UnscheduledPredecessors == 0 &&
1599 "Found CFG-violating block");
Chandler Carruthf3fc0052011-11-13 11:42:26 +00001600
Chandler Carruthbb535bc2015-03-05 03:19:05 +00001601 BlockFrequency CandidateFreq = MBFI->getBlockFreq(MBB);
Nicola Zaghen0818e782018-05-14 12:53:11 +00001602 LLVM_DEBUG(dbgs() << " " << getBlockName(MBB) << " -> ";
1603 MBFI->printBlockFreq(dbgs(), CandidateFreq) << " (freq)\n");
Amaury Secheta5bbcb52016-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 Carruthf3fc0052011-11-13 11:42:26 +00001624 continue;
Amaury Secheta5bbcb52016-04-07 21:29:39 +00001625
Chandler Carruthbb535bc2015-03-05 03:19:05 +00001626 BestBlock = MBB;
Chandler Carruthf3fc0052011-11-13 11:42:26 +00001627 BestFreq = CandidateFreq;
1628 }
Amaury Secheta5bbcb52016-04-07 21:29:39 +00001629
Chandler Carruthf3fc0052011-11-13 11:42:26 +00001630 return BestBlock;
1631}
1632
Adrian Prantl26b584c2018-05-01 15:54:18 +00001633/// Retrieve the first unplaced basic block.
Chandler Carruthb5856c82011-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 Carruth3273c892011-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 Carruthb5856c82011-11-14 00:00:35 +00001640MachineBasicBlock *MachineBlockPlacement::getFirstUnplacedBlock(
Xinliang David Li121cd172016-06-13 22:23:44 +00001641 const BlockChain &PlacedChain,
Chandler Carruth3273c892011-11-15 06:26:43 +00001642 MachineFunction::iterator &PrevUnplacedBlockIt,
Jakub Staszakd4895de2011-12-21 23:02:08 +00001643 const BlockFilterSet *BlockFilter) {
Xinliang David Li121cd172016-06-13 22:23:44 +00001644 for (MachineFunction::iterator I = PrevUnplacedBlockIt, E = F->end(); I != E;
Chandler Carruth3273c892011-11-15 06:26:43 +00001645 ++I) {
Duncan P. N. Exon Smith1b44cbf2015-10-09 19:36:12 +00001646 if (BlockFilter && !BlockFilter->count(&*I))
Chandler Carruth3273c892011-11-15 06:26:43 +00001647 continue;
Duncan P. N. Exon Smith1b44cbf2015-10-09 19:36:12 +00001648 if (BlockToChain[&*I] != &PlacedChain) {
Chandler Carruth3273c892011-11-15 06:26:43 +00001649 PrevUnplacedBlockIt = I;
Chandler Carruth47fb9542011-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 Smith1b44cbf2015-10-09 19:36:12 +00001653 return *BlockToChain[&*I]->begin();
Chandler Carruthb5856c82011-11-14 00:00:35 +00001654 }
1655 }
Craig Topper4ba84432014-04-14 00:51:57 +00001656 return nullptr;
Chandler Carruthb5856c82011-11-14 00:00:35 +00001657}
1658
Amaury Sechetce1afcc2016-03-14 21:24:11 +00001659void MachineBlockPlacement::fillWorkLists(
Kyle Butt7a252572017-02-04 02:26:32 +00001660 const MachineBasicBlock *MBB,
Amaury Sechetce1afcc2016-03-14 21:24:11 +00001661 SmallPtrSetImpl<BlockChain *> &UpdatedPreds,
Amaury Sechetce1afcc2016-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 Butt25ccad82017-05-17 23:44:41 +00001667 assert(
1668 Chain.UnscheduledPredecessors == 0 &&
1669 "Attempting to place block with unscheduled predecessors in worklist.");
Amaury Sechetce1afcc2016-03-14 21:24:11 +00001670 for (MachineBasicBlock *ChainBB : Chain) {
Kyle Butt25ccad82017-05-17 23:44:41 +00001671 assert(BlockToChain[ChainBB] == &Chain &&
1672 "Block in chain doesn't match BlockToChain map.");
Amaury Sechetce1afcc2016-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 Secheta5bbcb52016-04-07 21:29:39 +00001682 if (Chain.UnscheduledPredecessors != 0)
1683 return;
1684
Kyle Butt7a252572017-02-04 02:26:32 +00001685 MachineBasicBlock *BB = *Chain.begin();
1686 if (BB->isEHPad())
1687 EHPadWorkList.push_back(BB);
Amaury Secheta5bbcb52016-04-07 21:29:39 +00001688 else
Kyle Butt7a252572017-02-04 02:26:32 +00001689 BlockWorkList.push_back(BB);
Amaury Sechetce1afcc2016-03-14 21:24:11 +00001690}
1691
Chandler Carruthdf234352011-11-13 11:20:44 +00001692void MachineBlockPlacement::buildChain(
Kyle Butt7a252572017-02-04 02:26:32 +00001693 const MachineBasicBlock *HeadBB, BlockChain &Chain,
Kyle Butt2a180182016-10-11 20:36:43 +00001694 BlockFilterSet *BlockFilter) {
Kyle Butt7a252572017-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 Li121cd172016-06-13 22:23:44 +00001697 MachineFunction::iterator PrevUnplacedBlockIt = F->begin();
Chandler Carruthb5856c82011-11-14 00:00:35 +00001698
Kyle Butt7a252572017-02-04 02:26:32 +00001699 const MachineBasicBlock *LoopHeaderBB = HeadBB;
Xinliang David Li036eb7c2016-07-01 05:46:48 +00001700 markChainSuccessors(Chain, LoopHeaderBB, BlockFilter);
Kyle Butt7a252572017-02-04 02:26:32 +00001701 MachineBasicBlock *BB = *std::prev(Chain.end());
Eugene Zelenko2de563a2017-08-24 21:21:39 +00001702 while (true) {
Kyle Buttbaaf6e52016-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 Carruth30713632011-10-23 09:18:45 +00001707
Chandler Carruth03300ec2011-11-19 10:26:02 +00001708 // Look for the best viable successor if there is one to place immediately
1709 // after this block.
Kyle Butt5818a512017-01-31 23:48:32 +00001710 auto Result = selectBestSuccessor(BB, Chain, BlockFilter);
1711 MachineBasicBlock* BestSucc = Result.BB;
1712 bool ShouldTailDup = Result.ShouldTailDup;
Tim Shene1a4b172018-03-30 17:51:00 +00001713 if (allowTailDupPlacement())
Kyle Butt5818a512017-01-31 23:48:32 +00001714 ShouldTailDup |= (BestSucc && shouldTailDuplicate(BestSucc));
Chandler Carruthdf234352011-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 Carruthf3fc0052011-11-13 11:42:26 +00001719 if (!BestSucc)
Amaury Sechetb1788182016-04-07 06:34:47 +00001720 BestSucc = selectBestCandidateBlock(Chain, BlockWorkList);
Amaury Secheta5bbcb52016-04-07 21:29:39 +00001721 if (!BestSucc)
1722 BestSucc = selectBestCandidateBlock(Chain, EHPadWorkList);
Chandler Carruthdf234352011-11-13 11:20:44 +00001723
Chandler Carruthdf234352011-11-13 11:20:44 +00001724 if (!BestSucc) {
Xinliang David Li121cd172016-06-13 22:23:44 +00001725 BestSucc = getFirstUnplacedBlock(Chain, PrevUnplacedBlockIt, BlockFilter);
Chandler Carruthb5856c82011-11-14 00:00:35 +00001726 if (!BestSucc)
1727 break;
1728
Nicola Zaghen0818e782018-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 Carruthdf234352011-11-13 11:20:44 +00001731 }
Chandler Carruth30713632011-10-23 09:18:45 +00001732
Kyle Butt2a180182016-10-11 20:36:43 +00001733 // Placement may have changed tail duplication opportunities.
1734 // Check for that now.
Tim Shene1a4b172018-03-30 17:51:00 +00001735 if (allowTailDupPlacement() && BestSucc && ShouldTailDup) {
Kyle Butt2a180182016-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 Carruthdf234352011-11-13 11:20:44 +00001744 // Place this block, updating the datastructures to reflect its placement.
Jakub Staszakd4895de2011-12-21 23:02:08 +00001745 BlockChain &SuccChain = *BlockToChain[BestSucc];
Philip Reames43605f82016-03-03 00:58:43 +00001746 // Zero out UnscheduledPredecessors for the successor we're about to merge in case
Chandler Carruthb5856c82011-11-14 00:00:35 +00001747 // we selected a successor that didn't fit naturally into the CFG.
Philip Reames43605f82016-03-03 00:58:43 +00001748 SuccChain.UnscheduledPredecessors = 0;
Nicola Zaghen0818e782018-05-14 12:53:11 +00001749 LLVM_DEBUG(dbgs() << "Merging from " << getBlockName(BB) << " to "
1750 << getBlockName(BestSucc) << "\n");
Xinliang David Li036eb7c2016-07-01 05:46:48 +00001751 markChainSuccessors(SuccChain, LoopHeaderBB, BlockFilter);
Chandler Carruthdf234352011-11-13 11:20:44 +00001752 Chain.merge(BestSucc, &SuccChain);
Benjamin Kramerd628f192014-03-02 12:27:27 +00001753 BB = *std::prev(Chain.end());
Jakub Staszakfeb468a2011-12-07 19:46:10 +00001754 }
Chandler Carruthb5856c82011-11-14 00:00:35 +00001755
Nicola Zaghen0818e782018-05-14 12:53:11 +00001756 LLVM_DEBUG(dbgs() << "Finished forming chain for header block "
1757 << getBlockName(*Chain.begin()) << "\n");
Chandler Carruthdb350872011-10-21 06:46:38 +00001758}
1759
Adrian Prantl26b584c2018-05-01 15:54:18 +00001760/// Find the best loop top block for layout.
Chandler Carruth2e38cf92011-11-27 00:38:03 +00001761///
Chandler Carruthe773e8c2012-04-16 13:33:36 +00001762/// Look for a block which is strictly better than the loop header for laying
1763/// out at the top of the loop. This looks for one and only one pattern:
1764/// a latch block with no conditional exit. This block will cause a conditional
1765/// jump around it or will be the bottom of the loop if we lay it out in place,
1766/// but if it it doesn't end up at the bottom of the loop for any reason,
1767/// rotation alone won't fix it. Because such a block will always result in an
1768/// unconditional jump (for the backedge) rotating it in front of the loop
1769/// header is always profitable.
1770MachineBasicBlock *
Kyle Butt7a252572017-02-04 02:26:32 +00001771MachineBlockPlacement::findBestLoopTop(const MachineLoop &L,
Chandler Carruthe773e8c2012-04-16 13:33:36 +00001772 const BlockFilterSet &LoopBlockSet) {
Sjoerd Meijerf8505d62016-08-16 19:50:33 +00001773 // Placing the latch block before the header may introduce an extra branch
1774 // that skips this block the first time the loop is executed, which we want
1775 // to avoid when optimising for size.
1776 // FIXME: in theory there is a case that does not introduce a new branch,
1777 // i.e. when the layout predecessor does not fallthrough to the loop header.
1778 // In practice this never happens though: there always seems to be a preheader
1779 // that can fallthrough and that is also placed before the header.
Matthias Braund3181392017-12-15 22:22:58 +00001780 if (F->getFunction().optForSize())
Sjoerd Meijerf8505d62016-08-16 19:50:33 +00001781 return L.getHeader();
1782
Chandler Carruthe773e8c2012-04-16 13:33:36 +00001783 // Check that the header hasn't been fused with a preheader block due to
1784 // crazy branches. If it has, we need to start with the header at the top to
1785 // prevent pulling the preheader into the loop body.
1786 BlockChain &HeaderChain = *BlockToChain[L.getHeader()];
1787 if (!LoopBlockSet.count(*HeaderChain.begin()))
1788 return L.getHeader();
1789
Nicola Zaghen0818e782018-05-14 12:53:11 +00001790 LLVM_DEBUG(dbgs() << "Finding best loop top for: "
1791 << getBlockName(L.getHeader()) << "\n");
Chandler Carruthe773e8c2012-04-16 13:33:36 +00001792
1793 BlockFrequency BestPredFreq;
Craig Topper4ba84432014-04-14 00:51:57 +00001794 MachineBasicBlock *BestPred = nullptr;
Chandler Carruthbb535bc2015-03-05 03:19:05 +00001795 for (MachineBasicBlock *Pred : L.getHeader()->predecessors()) {
Chandler Carruthe773e8c2012-04-16 13:33:36 +00001796 if (!LoopBlockSet.count(Pred))
1797 continue;
Nicola Zaghen0818e782018-05-14 12:53:11 +00001798 LLVM_DEBUG(dbgs() << " header pred: " << getBlockName(Pred) << ", has "
1799 << Pred->succ_size() << " successors, ";
1800 MBFI->printBlockFreq(dbgs(), Pred) << " freq\n");
Chandler Carruthe773e8c2012-04-16 13:33:36 +00001801 if (Pred->succ_size() > 1)
1802 continue;
1803
1804 BlockFrequency PredFreq = MBFI->getBlockFreq(Pred);
1805 if (!BestPred || PredFreq > BestPredFreq ||
1806 (!(PredFreq < BestPredFreq) &&
1807 Pred->isLayoutSuccessor(L.getHeader()))) {
1808 BestPred = Pred;
1809 BestPredFreq = PredFreq;
1810 }
1811 }
1812
1813 // If no direct predecessor is fine, just use the loop header.
Philip Reames0dadb952016-03-02 21:45:13 +00001814 if (!BestPred) {
Nicola Zaghen0818e782018-05-14 12:53:11 +00001815 LLVM_DEBUG(dbgs() << " final top unchanged\n");
Chandler Carruthe773e8c2012-04-16 13:33:36 +00001816 return L.getHeader();
Philip Reames0dadb952016-03-02 21:45:13 +00001817 }
Chandler Carruthe773e8c2012-04-16 13:33:36 +00001818
1819 // Walk backwards through any straight line of predecessors.
1820 while (BestPred->pred_size() == 1 &&
1821 (*BestPred->pred_begin())->succ_size() == 1 &&
1822 *BestPred->pred_begin() != L.getHeader())
1823 BestPred = *BestPred->pred_begin();
1824
Nicola Zaghen0818e782018-05-14 12:53:11 +00001825 LLVM_DEBUG(dbgs() << " final top: " << getBlockName(BestPred) << "\n");
Chandler Carruthe773e8c2012-04-16 13:33:36 +00001826 return BestPred;
1827}
1828
Adrian Prantl26b584c2018-05-01 15:54:18 +00001829/// Find the best loop exiting block for layout.
Chandler Carruthe773e8c2012-04-16 13:33:36 +00001830///
Chandler Carruthfac13052011-11-27 13:34:33 +00001831/// This routine implements the logic to analyze the loop looking for the best
1832/// block to layout at the top of the loop. Typically this is done to maximize
1833/// fallthrough opportunities.
1834MachineBasicBlock *
Kyle Butt7a252572017-02-04 02:26:32 +00001835MachineBlockPlacement::findBestLoopExit(const MachineLoop &L,
Chandler Carruth70daea92012-04-16 01:12:56 +00001836 const BlockFilterSet &LoopBlockSet) {
Chandler Carruth45fb79b2012-04-10 13:35:57 +00001837 // We don't want to layout the loop linearly in all cases. If the loop header
1838 // is just a normal basic block in the loop, we want to look for what block
1839 // within the loop is the best one to layout at the top. However, if the loop
1840 // header has be pre-merged into a chain due to predecessors not having
1841 // analyzable branches, *and* the predecessor it is merged with is *not* part
1842 // of the loop, rotating the header into the middle of the loop will create
1843 // a non-contiguous range of blocks which is Very Bad. So start with the
1844 // header and only rotate if safe.
1845 BlockChain &HeaderChain = *BlockToChain[L.getHeader()];
1846 if (!LoopBlockSet.count(*HeaderChain.begin()))
Craig Topper4ba84432014-04-14 00:51:57 +00001847 return nullptr;
Chandler Carruth45fb79b2012-04-10 13:35:57 +00001848
Chandler Carruthfac13052011-11-27 13:34:33 +00001849 BlockFrequency BestExitEdgeFreq;
Chandler Carruth70daea92012-04-16 01:12:56 +00001850 unsigned BestExitLoopDepth = 0;
Craig Topper4ba84432014-04-14 00:51:57 +00001851 MachineBasicBlock *ExitingBB = nullptr;
Chandler Carruth51901d82011-11-27 20:18:00 +00001852 // If there are exits to outer loops, loop rotation can severely limit
Sjoerd Meijeraafccf02016-07-15 18:41:56 +00001853 // fallthrough opportunities unless it selects such an exit. Keep a set of
Chandler Carruth51901d82011-11-27 20:18:00 +00001854 // blocks where rotating to exit with that block will reach an outer loop.
1855 SmallPtrSet<MachineBasicBlock *, 4> BlocksExitingToOuterLoop;
1856
Nicola Zaghen0818e782018-05-14 12:53:11 +00001857 LLVM_DEBUG(dbgs() << "Finding best loop exit for: "
1858 << getBlockName(L.getHeader()) << "\n");
Chandler Carruthbb535bc2015-03-05 03:19:05 +00001859 for (MachineBasicBlock *MBB : L.getBlocks()) {
1860 BlockChain &Chain = *BlockToChain[MBB];
Chandler Carruthfac13052011-11-27 13:34:33 +00001861 // Ensure that this block is at the end of a chain; otherwise it could be
Chandler Carruthec07ff52015-04-15 13:19:54 +00001862 // mid-way through an inner loop or a successor of an unanalyzable branch.
Chandler Carruthbb535bc2015-03-05 03:19:05 +00001863 if (MBB != *std::prev(Chain.end()))
Chandler Carruth2e38cf92011-11-27 00:38:03 +00001864 continue;
Chandler Carruth2e38cf92011-11-27 00:38:03 +00001865
Chandler Carruthfac13052011-11-27 13:34:33 +00001866 // Now walk the successors. We need to establish whether this has a viable
1867 // exiting successor and whether it has a viable non-exiting successor.
1868 // We store the old exiting state and restore it if a viable looping
1869 // successor isn't found.
1870 MachineBasicBlock *OldExitingBB = ExitingBB;
1871 BlockFrequency OldBestExitEdgeFreq = BestExitEdgeFreq;
Chandler Carruth70daea92012-04-16 01:12:56 +00001872 bool HasLoopingSucc = false;
Chandler Carruthbb535bc2015-03-05 03:19:05 +00001873 for (MachineBasicBlock *Succ : MBB->successors()) {
Reid Klecknerc0e64ad2015-08-27 23:27:47 +00001874 if (Succ->isEHPad())
Chandler Carruthfac13052011-11-27 13:34:33 +00001875 continue;
Chandler Carruthbb535bc2015-03-05 03:19:05 +00001876 if (Succ == MBB)
Chandler Carruthfac13052011-11-27 13:34:33 +00001877 continue;
Chandler Carruthbb535bc2015-03-05 03:19:05 +00001878 BlockChain &SuccChain = *BlockToChain[Succ];
Chandler Carruthfac13052011-11-27 13:34:33 +00001879 // Don't split chains, either this chain or the successor's chain.
Chandler Carruth70daea92012-04-16 01:12:56 +00001880 if (&Chain == &SuccChain) {
Nicola Zaghen0818e782018-05-14 12:53:11 +00001881 LLVM_DEBUG(dbgs() << " exiting: " << getBlockName(MBB) << " -> "
1882 << getBlockName(Succ) << " (chain conflict)\n");
Chandler Carruthfac13052011-11-27 13:34:33 +00001883 continue;
1884 }
1885
Cong Hou51550212015-12-01 05:29:22 +00001886 auto SuccProb = MBPI->getEdgeProbability(MBB, Succ);
Chandler Carruthbb535bc2015-03-05 03:19:05 +00001887 if (LoopBlockSet.count(Succ)) {
Nicola Zaghen0818e782018-05-14 12:53:11 +00001888 LLVM_DEBUG(dbgs() << " looping: " << getBlockName(MBB) << " -> "
1889 << getBlockName(Succ) << " (" << SuccProb << ")\n");
Chandler Carruth70daea92012-04-16 01:12:56 +00001890 HasLoopingSucc = true;
Chandler Carruthfac13052011-11-27 13:34:33 +00001891 continue;
1892 }
1893
Chandler Carruth70daea92012-04-16 01:12:56 +00001894 unsigned SuccLoopDepth = 0;
Chandler Carruthbb535bc2015-03-05 03:19:05 +00001895 if (MachineLoop *ExitLoop = MLI->getLoopFor(Succ)) {
Chandler Carruth70daea92012-04-16 01:12:56 +00001896 SuccLoopDepth = ExitLoop->getLoopDepth();
1897 if (ExitLoop->contains(&L))
Chandler Carruthbb535bc2015-03-05 03:19:05 +00001898 BlocksExitingToOuterLoop.insert(MBB);
Chandler Carruth70daea92012-04-16 01:12:56 +00001899 }
1900
Chandler Carruthbb535bc2015-03-05 03:19:05 +00001901 BlockFrequency ExitEdgeFreq = MBFI->getBlockFreq(MBB) * SuccProb;
Nicola Zaghen0818e782018-05-14 12:53:11 +00001902 LLVM_DEBUG(dbgs() << " exiting: " << getBlockName(MBB) << " -> "
1903 << getBlockName(Succ) << " [L:" << SuccLoopDepth
1904 << "] (";
1905 MBFI->printBlockFreq(dbgs(), ExitEdgeFreq) << ")\n");
Benjamin Kramer16e2f0e2013-11-20 19:08:44 +00001906 // Note that we bias this toward an existing layout successor to retain
1907 // incoming order in the absence of better information. The exit must have
1908 // a frequency higher than the current exit before we consider breaking
1909 // the layout.
1910 BranchProbability Bias(100 - ExitBlockBias, 100);
Chandler Carruthea604d92015-04-15 13:39:42 +00001911 if (!ExitingBB || SuccLoopDepth > BestExitLoopDepth ||
Chandler Carruth70daea92012-04-16 01:12:56 +00001912 ExitEdgeFreq > BestExitEdgeFreq ||
Chandler Carruthbb535bc2015-03-05 03:19:05 +00001913 (MBB->isLayoutSuccessor(Succ) &&
Benjamin Kramer16e2f0e2013-11-20 19:08:44 +00001914 !(ExitEdgeFreq < BestExitEdgeFreq * Bias))) {
Chandler Carruthfac13052011-11-27 13:34:33 +00001915 BestExitEdgeFreq = ExitEdgeFreq;
Chandler Carruthbb535bc2015-03-05 03:19:05 +00001916 ExitingBB = MBB;
Chandler Carruth2eb5a742011-11-27 09:22:53 +00001917 }
Chandler Carruth2e38cf92011-11-27 00:38:03 +00001918 }
Chandler Carruthfac13052011-11-27 13:34:33 +00001919
Chandler Carruth70daea92012-04-16 01:12:56 +00001920 if (!HasLoopingSucc) {
Chandler Carruth016e9772015-04-15 13:26:41 +00001921 // Restore the old exiting state, no viable looping successor was found.
Chandler Carruthfac13052011-11-27 13:34:33 +00001922 ExitingBB = OldExitingBB;
1923 BestExitEdgeFreq = OldBestExitEdgeFreq;
Chandler Carruthfac13052011-11-27 13:34:33 +00001924 }
Chandler Carruth2e38cf92011-11-27 00:38:03 +00001925 }
Chandler Carruth70daea92012-04-16 01:12:56 +00001926 // Without a candidate exiting block or with only a single block in the
Chandler Carruthfac13052011-11-27 13:34:33 +00001927 // loop, just use the loop header to layout the loop.
Sjoerd Meijer23ce7972016-07-27 08:49:23 +00001928 if (!ExitingBB) {
Nicola Zaghen0818e782018-05-14 12:53:11 +00001929 LLVM_DEBUG(
1930 dbgs() << " No other candidate exit blocks, using loop header\n");
Craig Topper4ba84432014-04-14 00:51:57 +00001931 return nullptr;
Sjoerd Meijer23ce7972016-07-27 08:49:23 +00001932 }
1933 if (L.getNumBlocks() == 1) {
Nicola Zaghen0818e782018-05-14 12:53:11 +00001934 LLVM_DEBUG(dbgs() << " Loop has 1 block, using loop header as exit\n");
Sjoerd Meijer23ce7972016-07-27 08:49:23 +00001935 return nullptr;
1936 }
Chandler Carruth2e38cf92011-11-27 00:38:03 +00001937
Chandler Carruth51901d82011-11-27 20:18:00 +00001938 // Also, if we have exit blocks which lead to outer loops but didn't select
1939 // one of them as the exiting block we are rotating toward, disable loop
1940 // rotation altogether.
1941 if (!BlocksExitingToOuterLoop.empty() &&
1942 !BlocksExitingToOuterLoop.count(ExitingBB))
Craig Topper4ba84432014-04-14 00:51:57 +00001943 return nullptr;
Chandler Carruth51901d82011-11-27 20:18:00 +00001944
Nicola Zaghen0818e782018-05-14 12:53:11 +00001945 LLVM_DEBUG(dbgs() << " Best exiting block: " << getBlockName(ExitingBB)
1946 << "\n");
Chandler Carruth70daea92012-04-16 01:12:56 +00001947 return ExitingBB;
Chandler Carruth2e38cf92011-11-27 00:38:03 +00001948}
1949
Adrian Prantl26b584c2018-05-01 15:54:18 +00001950/// Attempt to rotate an exiting block to the bottom of the loop.
Chandler Carruth16295fc2012-04-16 09:31:23 +00001951///
1952/// Once we have built a chain, try to rotate it to line up the hot exit block
1953/// with fallthrough out of the loop if doing so doesn't introduce unnecessary
1954/// branches. For example, if the loop has fallthrough into its header and out
1955/// of its bottom already, don't rotate it.
1956void MachineBlockPlacement::rotateLoop(BlockChain &LoopChain,
Kyle Butt7a252572017-02-04 02:26:32 +00001957 const MachineBasicBlock *ExitingBB,
Chandler Carruth16295fc2012-04-16 09:31:23 +00001958 const BlockFilterSet &LoopBlockSet) {
1959 if (!ExitingBB)
1960 return;
1961
1962 MachineBasicBlock *Top = *LoopChain.begin();
Serguei Katkova1602eb2017-07-11 08:34:58 +00001963 MachineBasicBlock *Bottom = *std::prev(LoopChain.end());
1964
1965 // If ExitingBB is already the last one in a chain then nothing to do.
1966 if (Bottom == ExitingBB)
1967 return;
1968
Chandler Carruth16295fc2012-04-16 09:31:23 +00001969 bool ViableTopFallthrough = false;
Chandler Carruthbb535bc2015-03-05 03:19:05 +00001970 for (MachineBasicBlock *Pred : Top->predecessors()) {
1971 BlockChain *PredChain = BlockToChain[Pred];
1972 if (!LoopBlockSet.count(Pred) &&
1973 (!PredChain || Pred == *std::prev(PredChain->end()))) {
Chandler Carruth16295fc2012-04-16 09:31:23 +00001974 ViableTopFallthrough = true;
1975 break;
1976 }
1977 }
1978
1979 // If the header has viable fallthrough, check whether the current loop
1980 // bottom is a viable exiting block. If so, bail out as rotating will
1981 // introduce an unnecessary branch.
1982 if (ViableTopFallthrough) {
Chandler Carruthbb535bc2015-03-05 03:19:05 +00001983 for (MachineBasicBlock *Succ : Bottom->successors()) {
1984 BlockChain *SuccChain = BlockToChain[Succ];
1985 if (!LoopBlockSet.count(Succ) &&
1986 (!SuccChain || Succ == *SuccChain->begin()))
Chandler Carruth16295fc2012-04-16 09:31:23 +00001987 return;
1988 }
1989 }
1990
Eugene Zelenko2de563a2017-08-24 21:21:39 +00001991 BlockChain::iterator ExitIt = llvm::find(LoopChain, ExitingBB);
Chandler Carruth16295fc2012-04-16 09:31:23 +00001992 if (ExitIt == LoopChain.end())
1993 return;
1994
Serguei Katkova1602eb2017-07-11 08:34:58 +00001995 // Rotating a loop exit to the bottom when there is a fallthrough to top
1996 // trades the entry fallthrough for an exit fallthrough.
1997 // If there is no bottom->top edge, but the chosen exit block does have
1998 // a fallthrough, we break that fallthrough for nothing in return.
1999
2000 // Let's consider an example. We have a built chain of basic blocks
2001 // B1, B2, ..., Bn, where Bk is a ExitingBB - chosen exit block.
2002 // By doing a rotation we get
2003 // Bk+1, ..., Bn, B1, ..., Bk
2004 // Break of fallthrough to B1 is compensated by a fallthrough from Bk.
2005 // If we had a fallthrough Bk -> Bk+1 it is broken now.
2006 // It might be compensated by fallthrough Bn -> B1.
2007 // So we have a condition to avoid creation of extra branch by loop rotation.
2008 // All below must be true to avoid loop rotation:
2009 // If there is a fallthrough to top (B1)
2010 // There was fallthrough from chosen exit block (Bk) to next one (Bk+1)
2011 // There is no fallthrough from bottom (Bn) to top (B1).
2012 // Please note that there is no exit fallthrough from Bn because we checked it
2013 // above.
2014 if (ViableTopFallthrough) {
2015 assert(std::next(ExitIt) != LoopChain.end() &&
2016 "Exit should not be last BB");
2017 MachineBasicBlock *NextBlockInChain = *std::next(ExitIt);
2018 if (ExitingBB->isSuccessor(NextBlockInChain))
2019 if (!Bottom->isSuccessor(Top))
2020 return;
2021 }
2022
Nicola Zaghen0818e782018-05-14 12:53:11 +00002023 LLVM_DEBUG(dbgs() << "Rotating loop to put exit " << getBlockName(ExitingBB)
2024 << " at bottom\n");
Benjamin Kramerd628f192014-03-02 12:27:27 +00002025 std::rotate(LoopChain.begin(), std::next(ExitIt), LoopChain.end());
Chandler Carruth16295fc2012-04-16 09:31:23 +00002026}
2027
Adrian Prantl26b584c2018-05-01 15:54:18 +00002028/// Attempt to rotate a loop based on profile data to reduce branch cost.
Cong Houf2558c22015-10-19 23:16:40 +00002029///
2030/// With profile data, we can determine the cost in terms of missed fall through
2031/// opportunities when rotating a loop chain and select the best rotation.
2032/// Basically, there are three kinds of cost to consider for each rotation:
2033/// 1. The possibly missed fall through edge (if it exists) from BB out of
2034/// the loop to the loop header.
2035/// 2. The possibly missed fall through edges (if they exist) from the loop
2036/// exits to BB out of the loop.
2037/// 3. The missed fall through edge (if it exists) from the last BB to the
2038/// first BB in the loop chain.
2039/// Therefore, the cost for a given rotation is the sum of costs listed above.
2040/// We select the best rotation with the smallest cost.
2041void MachineBlockPlacement::rotateLoopWithProfile(
Kyle Butt7a252572017-02-04 02:26:32 +00002042 BlockChain &LoopChain, const MachineLoop &L,
2043 const BlockFilterSet &LoopBlockSet) {
Cong Houf2558c22015-10-19 23:16:40 +00002044 auto HeaderBB = L.getHeader();
Eugene Zelenko2de563a2017-08-24 21:21:39 +00002045 auto HeaderIter = llvm::find(LoopChain, HeaderBB);
Cong Houf2558c22015-10-19 23:16:40 +00002046 auto RotationPos = LoopChain.end();
2047
2048 BlockFrequency SmallestRotationCost = BlockFrequency::getMaxFrequency();
2049
2050 // A utility lambda that scales up a block frequency by dividing it by a
2051 // branch probability which is the reciprocal of the scale.
2052 auto ScaleBlockFrequency = [](BlockFrequency Freq,
2053 unsigned Scale) -> BlockFrequency {
2054 if (Scale == 0)
2055 return 0;
2056 // Use operator / between BlockFrequency and BranchProbability to implement
2057 // saturating multiplication.
2058 return Freq / BranchProbability(1, Scale);
2059 };
2060
2061 // Compute the cost of the missed fall-through edge to the loop header if the
2062 // chain head is not the loop header. As we only consider natural loops with
2063 // single header, this computation can be done only once.
2064 BlockFrequency HeaderFallThroughCost(0);
2065 for (auto *Pred : HeaderBB->predecessors()) {
2066 BlockChain *PredChain = BlockToChain[Pred];
2067 if (!LoopBlockSet.count(Pred) &&
2068 (!PredChain || Pred == *std::prev(PredChain->end()))) {
2069 auto EdgeFreq =
2070 MBFI->getBlockFreq(Pred) * MBPI->getEdgeProbability(Pred, HeaderBB);
2071 auto FallThruCost = ScaleBlockFrequency(EdgeFreq, MisfetchCost);
2072 // If the predecessor has only an unconditional jump to the header, we
2073 // need to consider the cost of this jump.
2074 if (Pred->succ_size() == 1)
2075 FallThruCost += ScaleBlockFrequency(EdgeFreq, JumpInstCost);
2076 HeaderFallThroughCost = std::max(HeaderFallThroughCost, FallThruCost);
2077 }
2078 }
2079
2080 // Here we collect all exit blocks in the loop, and for each exit we find out
2081 // its hottest exit edge. For each loop rotation, we define the loop exit cost
2082 // as the sum of frequencies of exit edges we collect here, excluding the exit
2083 // edge from the tail of the loop chain.
2084 SmallVector<std::pair<MachineBasicBlock *, BlockFrequency>, 4> ExitsWithFreq;
2085 for (auto BB : LoopChain) {
Cong Hou51550212015-12-01 05:29:22 +00002086 auto LargestExitEdgeProb = BranchProbability::getZero();
Cong Houf2558c22015-10-19 23:16:40 +00002087 for (auto *Succ : BB->successors()) {
2088 BlockChain *SuccChain = BlockToChain[Succ];
2089 if (!LoopBlockSet.count(Succ) &&
2090 (!SuccChain || Succ == *SuccChain->begin())) {
Cong Hou51550212015-12-01 05:29:22 +00002091 auto SuccProb = MBPI->getEdgeProbability(BB, Succ);
2092 LargestExitEdgeProb = std::max(LargestExitEdgeProb, SuccProb);
Cong Houf2558c22015-10-19 23:16:40 +00002093 }
2094 }
Cong Hou51550212015-12-01 05:29:22 +00002095 if (LargestExitEdgeProb > BranchProbability::getZero()) {
2096 auto ExitFreq = MBFI->getBlockFreq(BB) * LargestExitEdgeProb;
Cong Houf2558c22015-10-19 23:16:40 +00002097 ExitsWithFreq.emplace_back(BB, ExitFreq);
2098 }
2099 }
2100
2101 // In this loop we iterate every block in the loop chain and calculate the
2102 // cost assuming the block is the head of the loop chain. When the loop ends,
2103 // we should have found the best candidate as the loop chain's head.
2104 for (auto Iter = LoopChain.begin(), TailIter = std::prev(LoopChain.end()),
2105 EndIter = LoopChain.end();
2106 Iter != EndIter; Iter++, TailIter++) {
2107 // TailIter is used to track the tail of the loop chain if the block we are
2108 // checking (pointed by Iter) is the head of the chain.
2109 if (TailIter == LoopChain.end())
2110 TailIter = LoopChain.begin();
2111
2112 auto TailBB = *TailIter;
2113
2114 // Calculate the cost by putting this BB to the top.
2115 BlockFrequency Cost = 0;
2116
2117 // If the current BB is the loop header, we need to take into account the
2118 // cost of the missed fall through edge from outside of the loop to the
2119 // header.
2120 if (Iter != HeaderIter)
2121 Cost += HeaderFallThroughCost;
2122
2123 // Collect the loop exit cost by summing up frequencies of all exit edges
2124 // except the one from the chain tail.
2125 for (auto &ExitWithFreq : ExitsWithFreq)
2126 if (TailBB != ExitWithFreq.first)
2127 Cost += ExitWithFreq.second;
2128
2129 // The cost of breaking the once fall-through edge from the tail to the top
2130 // of the loop chain. Here we need to consider three cases:
2131 // 1. If the tail node has only one successor, then we will get an
2132 // additional jmp instruction. So the cost here is (MisfetchCost +
2133 // JumpInstCost) * tail node frequency.
2134 // 2. If the tail node has two successors, then we may still get an
2135 // additional jmp instruction if the layout successor after the loop
2136 // chain is not its CFG successor. Note that the more frequently executed
2137 // jmp instruction will be put ahead of the other one. Assume the
2138 // frequency of those two branches are x and y, where x is the frequency
2139 // of the edge to the chain head, then the cost will be
2140 // (x * MisfetechCost + min(x, y) * JumpInstCost) * tail node frequency.
2141 // 3. If the tail node has more than two successors (this rarely happens),
2142 // we won't consider any additional cost.
2143 if (TailBB->isSuccessor(*Iter)) {
2144 auto TailBBFreq = MBFI->getBlockFreq(TailBB);
2145 if (TailBB->succ_size() == 1)
2146 Cost += ScaleBlockFrequency(TailBBFreq.getFrequency(),
2147 MisfetchCost + JumpInstCost);
2148 else if (TailBB->succ_size() == 2) {
2149 auto TailToHeadProb = MBPI->getEdgeProbability(TailBB, *Iter);
2150 auto TailToHeadFreq = TailBBFreq * TailToHeadProb;
2151 auto ColderEdgeFreq = TailToHeadProb > BranchProbability(1, 2)
2152 ? TailBBFreq * TailToHeadProb.getCompl()
2153 : TailToHeadFreq;
2154 Cost += ScaleBlockFrequency(TailToHeadFreq, MisfetchCost) +
2155 ScaleBlockFrequency(ColderEdgeFreq, JumpInstCost);
2156 }
2157 }
2158
Nicola Zaghen0818e782018-05-14 12:53:11 +00002159 LLVM_DEBUG(dbgs() << "The cost of loop rotation by making "
2160 << getBlockName(*Iter)
2161 << " to the top: " << Cost.getFrequency() << "\n");
Cong Houf2558c22015-10-19 23:16:40 +00002162
2163 if (Cost < SmallestRotationCost) {
2164 SmallestRotationCost = Cost;
2165 RotationPos = Iter;
2166 }
2167 }
2168
2169 if (RotationPos != LoopChain.end()) {
Nicola Zaghen0818e782018-05-14 12:53:11 +00002170 LLVM_DEBUG(dbgs() << "Rotate loop by making " << getBlockName(*RotationPos)
2171 << " to the top\n");
Cong Houf2558c22015-10-19 23:16:40 +00002172 std::rotate(LoopChain.begin(), RotationPos, LoopChain.end());
2173 }
2174}
2175
Adrian Prantl26b584c2018-05-01 15:54:18 +00002176/// Collect blocks in the given loop that are to be placed.
Cong Houb18412c2015-11-02 21:24:00 +00002177///
2178/// When profile data is available, exclude cold blocks from the returned set;
2179/// otherwise, collect all blocks in the loop.
2180MachineBlockPlacement::BlockFilterSet
Kyle Butt7a252572017-02-04 02:26:32 +00002181MachineBlockPlacement::collectLoopBlockSet(const MachineLoop &L) {
Cong Houb18412c2015-11-02 21:24:00 +00002182 BlockFilterSet LoopBlockSet;
2183
2184 // Filter cold blocks off from LoopBlockSet when profile data is available.
2185 // Collect the sum of frequencies of incoming edges to the loop header from
2186 // outside. If we treat the loop as a super block, this is the frequency of
2187 // the loop. Then for each block in the loop, we calculate the ratio between
2188 // its frequency and the frequency of the loop block. When it is too small,
2189 // don't add it to the loop chain. If there are outer loops, then this block
2190 // will be merged into the first outer loop chain for which this block is not
2191 // cold anymore. This needs precise profile data and we only do this when
2192 // profile data is available.
Easwaran Ramanfe7b9dc2017-12-22 01:33:52 +00002193 if (F->getFunction().hasProfileData() || ForceLoopColdBlock) {
Cong Houb18412c2015-11-02 21:24:00 +00002194 BlockFrequency LoopFreq(0);
2195 for (auto LoopPred : L.getHeader()->predecessors())
2196 if (!L.contains(LoopPred))
2197 LoopFreq += MBFI->getBlockFreq(LoopPred) *
2198 MBPI->getEdgeProbability(LoopPred, L.getHeader());
2199
2200 for (MachineBasicBlock *LoopBB : L.getBlocks()) {
2201 auto Freq = MBFI->getBlockFreq(LoopBB).getFrequency();
2202 if (Freq == 0 || LoopFreq.getFrequency() / Freq > LoopToColdBlockRatio)
2203 continue;
2204 LoopBlockSet.insert(LoopBB);
2205 }
2206 } else
2207 LoopBlockSet.insert(L.block_begin(), L.block_end());
2208
2209 return LoopBlockSet;
2210}
2211
Adrian Prantl26b584c2018-05-01 15:54:18 +00002212/// Forms basic block chains from the natural loop structures.
Chandler Carruthdb350872011-10-21 06:46:38 +00002213///
Chandler Carruth30713632011-10-23 09:18:45 +00002214/// These chains are designed to preserve the existing *structure* of the code
2215/// as much as possible. We can then stitch the chains together in a way which
2216/// both preserves the topological structure and minimizes taken conditional
2217/// branches.
Kyle Butt7a252572017-02-04 02:26:32 +00002218void MachineBlockPlacement::buildLoopChains(const MachineLoop &L) {
Chandler Carruth30713632011-10-23 09:18:45 +00002219 // First recurse through any nested loops, building chains for those inner
2220 // loops.
Kyle Butt7a252572017-02-04 02:26:32 +00002221 for (const MachineLoop *InnerLoop : L)
Xinliang David Li121cd172016-06-13 22:23:44 +00002222 buildLoopChains(*InnerLoop);
Chandler Carruthdb350872011-10-21 06:46:38 +00002223
Kyle Butt25ccad82017-05-17 23:44:41 +00002224 assert(BlockWorkList.empty() &&
2225 "BlockWorkList not empty when starting to build loop chains.");
2226 assert(EHPadWorkList.empty() &&
2227 "EHPadWorkList not empty when starting to build loop chains.");
Xinliang David Li121cd172016-06-13 22:23:44 +00002228 BlockFilterSet LoopBlockSet = collectLoopBlockSet(L);
Chandler Carruthfac13052011-11-27 13:34:33 +00002229
Cong Houf2558c22015-10-19 23:16:40 +00002230 // Check if we have profile data for this function. If yes, we will rotate
2231 // this loop by modeling costs more precisely which requires the profile data
2232 // for better layout.
2233 bool RotateLoopWithProfile =
Xinliang David Lid4e30ea2016-05-12 02:04:41 +00002234 ForcePreciseRotationCost ||
Easwaran Ramanfe7b9dc2017-12-22 01:33:52 +00002235 (PreciseRotationCost && F->getFunction().hasProfileData());
Cong Houf2558c22015-10-19 23:16:40 +00002236
Chandler Carruthe773e8c2012-04-16 13:33:36 +00002237 // First check to see if there is an obviously preferable top block for the
2238 // loop. This will default to the header, but may end up as one of the
2239 // predecessors to the header if there is one which will result in strictly
2240 // fewer branches in the loop body.
Cong Houf2558c22015-10-19 23:16:40 +00002241 // When we use profile data to rotate the loop, this is unnecessary.
2242 MachineBasicBlock *LoopTop =
2243 RotateLoopWithProfile ? L.getHeader() : findBestLoopTop(L, LoopBlockSet);
Chandler Carruthe773e8c2012-04-16 13:33:36 +00002244
2245 // If we selected just the header for the loop top, look for a potentially
2246 // profitable exit block in the event that rotating the loop can eliminate
2247 // branches by placing an exit edge at the bottom.
Xin Tong587a4b02017-10-04 21:39:25 +00002248 //
2249 // Loops are processed innermost to uttermost, make sure we clear
2250 // PreferredLoopExit before processing a new loop.
2251 PreferredLoopExit = nullptr;
Cong Houf2558c22015-10-19 23:16:40 +00002252 if (!RotateLoopWithProfile && LoopTop == L.getHeader())
Kyle Buttbf977932016-10-27 21:37:20 +00002253 PreferredLoopExit = findBestLoopExit(L, LoopBlockSet);
Chandler Carruthe773e8c2012-04-16 13:33:36 +00002254
2255 BlockChain &LoopChain = *BlockToChain[LoopTop];
Chandler Carruthdb350872011-10-21 06:46:38 +00002256
Chandler Carruthdf234352011-11-13 11:20:44 +00002257 // FIXME: This is a really lame way of walking the chains in the loop: we
2258 // walk the blocks, and use a set to prevent visiting a particular chain
2259 // twice.
Jakub Staszakd4895de2011-12-21 23:02:08 +00002260 SmallPtrSet<BlockChain *, 4> UpdatedPreds;
Kyle Butt25ccad82017-05-17 23:44:41 +00002261 assert(LoopChain.UnscheduledPredecessors == 0 &&
2262 "LoopChain should not have unscheduled predecessors.");
Jakub Staszakfeb468a2011-12-07 19:46:10 +00002263 UpdatedPreds.insert(&LoopChain);
Cong Houb18412c2015-11-02 21:24:00 +00002264
Kyle Butt7a252572017-02-04 02:26:32 +00002265 for (const MachineBasicBlock *LoopBB : LoopBlockSet)
Xinliang David Li036eb7c2016-07-01 05:46:48 +00002266 fillWorkLists(LoopBB, UpdatedPreds, &LoopBlockSet);
Chandler Carruthdf234352011-11-13 11:20:44 +00002267
Xinliang David Li036eb7c2016-07-01 05:46:48 +00002268 buildChain(LoopTop, LoopChain, &LoopBlockSet);
Cong Houf2558c22015-10-19 23:16:40 +00002269
2270 if (RotateLoopWithProfile)
2271 rotateLoopWithProfile(LoopChain, L, LoopBlockSet);
2272 else
Kyle Buttbf977932016-10-27 21:37:20 +00002273 rotateLoop(LoopChain, PreferredLoopExit, LoopBlockSet);
Chandler Carruthdf234352011-11-13 11:20:44 +00002274
Nicola Zaghen0818e782018-05-14 12:53:11 +00002275 LLVM_DEBUG({
Chandler Carruth10252db2011-11-13 21:39:51 +00002276 // Crash at the end so we get all of the debugging output first.
2277 bool BadLoop = false;
Philip Reames43605f82016-03-03 00:58:43 +00002278 if (LoopChain.UnscheduledPredecessors) {
Chandler Carruth10252db2011-11-13 21:39:51 +00002279 BadLoop = true;
Chandler Carruthdf234352011-11-13 11:20:44 +00002280 dbgs() << "Loop chain contains a block without its preds placed!\n"
2281 << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
2282 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n";
Chandler Carruth10252db2011-11-13 21:39:51 +00002283 }
Chandler Carruthbb535bc2015-03-05 03:19:05 +00002284 for (MachineBasicBlock *ChainBB : LoopChain) {
2285 dbgs() << " ... " << getBlockName(ChainBB) << "\n";
Rong Xu4146fdb2016-11-16 20:50:06 +00002286 if (!LoopBlockSet.remove(ChainBB)) {
Chandler Carruthbc83fcd2011-11-14 10:55:53 +00002287 // We don't mark the loop as bad here because there are real situations
2288 // where this can occur. For example, with an unanalyzable fallthrough
Chandler Carruth598894f2011-11-23 10:35:36 +00002289 // from a loop block to a non-loop block or vice versa.
Chandler Carruthdf234352011-11-13 11:20:44 +00002290 dbgs() << "Loop chain contains a block not contained by the loop!\n"
2291 << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
2292 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
Chandler Carruthbb535bc2015-03-05 03:19:05 +00002293 << " Bad block: " << getBlockName(ChainBB) << "\n";
Chandler Carruth10252db2011-11-13 21:39:51 +00002294 }
Chandler Carruth70daea92012-04-16 01:12:56 +00002295 }
Chandler Carruthdf234352011-11-13 11:20:44 +00002296
Chandler Carruth10252db2011-11-13 21:39:51 +00002297 if (!LoopBlockSet.empty()) {
2298 BadLoop = true;
Kyle Butt7a252572017-02-04 02:26:32 +00002299 for (const MachineBasicBlock *LoopBB : LoopBlockSet)
Chandler Carruthdf234352011-11-13 11:20:44 +00002300 dbgs() << "Loop contains blocks never placed into a chain!\n"
2301 << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
2302 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
Chandler Carruthbb535bc2015-03-05 03:19:05 +00002303 << " Bad block: " << getBlockName(LoopBB) << "\n";
Chandler Carruth10252db2011-11-13 21:39:51 +00002304 }
2305 assert(!BadLoop && "Detected problems with the placement of this loop.");
Chandler Carruthdf234352011-11-13 11:20:44 +00002306 });
Xinliang David Li036eb7c2016-07-01 05:46:48 +00002307
2308 BlockWorkList.clear();
2309 EHPadWorkList.clear();
Chandler Carruthdb350872011-10-21 06:46:38 +00002310}
2311
Xinliang David Li121cd172016-06-13 22:23:44 +00002312void MachineBlockPlacement::buildCFGChains() {
Chandler Carruthdf234352011-11-13 11:20:44 +00002313 // Ensure that every BB in the function has an associated chain to simplify
2314 // the assumptions of the remaining algorithm.
Chandler Carruth03300ec2011-11-19 10:26:02 +00002315 SmallVector<MachineOperand, 4> Cond; // For AnalyzeBranch.
Xinliang David Li121cd172016-06-13 22:23:44 +00002316 for (MachineFunction::iterator FI = F->begin(), FE = F->end(); FI != FE;
2317 ++FI) {
Duncan P. N. Exon Smith1b44cbf2015-10-09 19:36:12 +00002318 MachineBasicBlock *BB = &*FI;
Chandler Carruth35742dd2015-03-05 02:35:31 +00002319 BlockChain *Chain =
2320 new (ChainAllocator.Allocate()) BlockChain(BlockToChain, BB);
Chandler Carruth03300ec2011-11-19 10:26:02 +00002321 // Also, merge any blocks which we cannot reason about and must preserve
2322 // the exact fallthrough behavior for.
Eugene Zelenko2de563a2017-08-24 21:21:39 +00002323 while (true) {
Chandler Carruth03300ec2011-11-19 10:26:02 +00002324 Cond.clear();
Craig Topper4ba84432014-04-14 00:51:57 +00002325 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
Jacques Pienaar48ed4ab2016-07-15 14:41:04 +00002326 if (!TII->analyzeBranch(*BB, TBB, FBB, Cond) || !FI->canFallThrough())
Chandler Carruth03300ec2011-11-19 10:26:02 +00002327 break;
2328
Duncan P. N. Exon Smith1b44cbf2015-10-09 19:36:12 +00002329 MachineFunction::iterator NextFI = std::next(FI);
2330 MachineBasicBlock *NextBB = &*NextFI;
Chandler Carruth03300ec2011-11-19 10:26:02 +00002331 // Ensure that the layout successor is a viable block, as we know that
2332 // fallthrough is a possibility.
2333 assert(NextFI != FE && "Can't fallthrough past the last block.");
Nicola Zaghen0818e782018-05-14 12:53:11 +00002334 LLVM_DEBUG(dbgs() << "Pre-merging due to unanalyzable fallthrough: "
2335 << getBlockName(BB) << " -> " << getBlockName(NextBB)
2336 << "\n");
Craig Topper4ba84432014-04-14 00:51:57 +00002337 Chain->merge(NextBB, nullptr);
Hal Finkel954db622016-12-15 05:33:19 +00002338#ifndef NDEBUG
Sanjoy Dasd0f66422016-12-15 05:08:57 +00002339 BlocksWithUnanalyzableExits.insert(&*BB);
Hal Finkel954db622016-12-15 05:33:19 +00002340#endif
Chandler Carruth03300ec2011-11-19 10:26:02 +00002341 FI = NextFI;
2342 BB = NextBB;
2343 }
2344 }
Chandler Carruthdf234352011-11-13 11:20:44 +00002345
2346 // Build any loop-based chains.
Sam McCall456b2622016-11-01 22:02:14 +00002347 PreferredLoopExit = nullptr;
Chandler Carruthbb535bc2015-03-05 03:19:05 +00002348 for (MachineLoop *L : *MLI)
Xinliang David Li121cd172016-06-13 22:23:44 +00002349 buildLoopChains(*L);
Chandler Carruth30713632011-10-23 09:18:45 +00002350
Kyle Butt25ccad82017-05-17 23:44:41 +00002351 assert(BlockWorkList.empty() &&
2352 "BlockWorkList should be empty before building final chain.");
2353 assert(EHPadWorkList.empty() &&
2354 "EHPadWorkList should be empty before building final chain.");
Chandler Carruth30713632011-10-23 09:18:45 +00002355
Chandler Carruthdf234352011-11-13 11:20:44 +00002356 SmallPtrSet<BlockChain *, 4> UpdatedPreds;
Xinliang David Li121cd172016-06-13 22:23:44 +00002357 for (MachineBasicBlock &MBB : *F)
Xinliang David Li036eb7c2016-07-01 05:46:48 +00002358 fillWorkLists(&MBB, UpdatedPreds);
Chandler Carruthdf234352011-11-13 11:20:44 +00002359
Xinliang David Li121cd172016-06-13 22:23:44 +00002360 BlockChain &FunctionChain = *BlockToChain[&F->front()];
Xinliang David Li036eb7c2016-07-01 05:46:48 +00002361 buildChain(&F->front(), FunctionChain);
Chandler Carruthdf234352011-11-13 11:20:44 +00002362
Matt Arsenaultc5019a32013-12-10 18:55:37 +00002363#ifndef NDEBUG
Eugene Zelenko2de563a2017-08-24 21:21:39 +00002364 using FunctionBlockSetType = SmallPtrSet<MachineBasicBlock *, 16>;
Matt Arsenaultc5019a32013-12-10 18:55:37 +00002365#endif
Nicola Zaghen0818e782018-05-14 12:53:11 +00002366 LLVM_DEBUG({
Chandler Carruth10252db2011-11-13 21:39:51 +00002367 // Crash at the end so we get all of the debugging output first.
2368 bool BadFunc = false;
Chandler Carruthdf234352011-11-13 11:20:44 +00002369 FunctionBlockSetType FunctionBlockSet;
Xinliang David Li121cd172016-06-13 22:23:44 +00002370 for (MachineBasicBlock &MBB : *F)
Chandler Carruthbb535bc2015-03-05 03:19:05 +00002371 FunctionBlockSet.insert(&MBB);
Chandler Carruthdf234352011-11-13 11:20:44 +00002372
Chandler Carruthbb535bc2015-03-05 03:19:05 +00002373 for (MachineBasicBlock *ChainBB : FunctionChain)
2374 if (!FunctionBlockSet.erase(ChainBB)) {
Chandler Carruth10252db2011-11-13 21:39:51 +00002375 BadFunc = true;
Chandler Carruthdf234352011-11-13 11:20:44 +00002376 dbgs() << "Function chain contains a block not in the function!\n"
Chandler Carruthbb535bc2015-03-05 03:19:05 +00002377 << " Bad block: " << getBlockName(ChainBB) << "\n";
Chandler Carruth10252db2011-11-13 21:39:51 +00002378 }
Chandler Carruthdf234352011-11-13 11:20:44 +00002379
Chandler Carruth10252db2011-11-13 21:39:51 +00002380 if (!FunctionBlockSet.empty()) {
2381 BadFunc = true;
Chandler Carruthbb535bc2015-03-05 03:19:05 +00002382 for (MachineBasicBlock *RemainingBB : FunctionBlockSet)
Chandler Carruthdf234352011-11-13 11:20:44 +00002383 dbgs() << "Function contains blocks never placed into a chain!\n"
Chandler Carruthbb535bc2015-03-05 03:19:05 +00002384 << " Bad block: " << getBlockName(RemainingBB) << "\n";
Chandler Carruth10252db2011-11-13 21:39:51 +00002385 }
2386 assert(!BadFunc && "Detected problems with the block placement.");
Chandler Carruthdf234352011-11-13 11:20:44 +00002387 });
2388
2389 // Splice the blocks into place.
Xinliang David Li121cd172016-06-13 22:23:44 +00002390 MachineFunction::iterator InsertPos = F->begin();
Nicola Zaghen0818e782018-05-14 12:53:11 +00002391 LLVM_DEBUG(dbgs() << "[MBP] Function: " << F->getName() << "\n");
Chandler Carruthbb535bc2015-03-05 03:19:05 +00002392 for (MachineBasicBlock *ChainBB : FunctionChain) {
Nicola Zaghen0818e782018-05-14 12:53:11 +00002393 LLVM_DEBUG(dbgs() << (ChainBB == *FunctionChain.begin() ? "Placing chain "
2394 : " ... ")
2395 << getBlockName(ChainBB) << "\n");
Chandler Carruthbb535bc2015-03-05 03:19:05 +00002396 if (InsertPos != MachineFunction::iterator(ChainBB))
Xinliang David Li121cd172016-06-13 22:23:44 +00002397 F->splice(InsertPos, ChainBB);
Chandler Carruthdf234352011-11-13 11:20:44 +00002398 else
2399 ++InsertPos;
2400
2401 // Update the terminator of the previous block.
Chandler Carruthbb535bc2015-03-05 03:19:05 +00002402 if (ChainBB == *FunctionChain.begin())
Chandler Carruthdf234352011-11-13 11:20:44 +00002403 continue;
Duncan P. N. Exon Smith1b44cbf2015-10-09 19:36:12 +00002404 MachineBasicBlock *PrevBB = &*std::prev(MachineFunction::iterator(ChainBB));
Chandler Carruthdf234352011-11-13 11:20:44 +00002405
Chandler Carruthdb350872011-10-21 06:46:38 +00002406 // FIXME: It would be awesome of updateTerminator would just return rather
2407 // than assert when the branch cannot be analyzed in order to remove this
2408 // boiler plate.
2409 Cond.clear();
Craig Topper4ba84432014-04-14 00:51:57 +00002410 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
Shuxin Yang45c75442013-06-04 01:00:57 +00002411
Sanjoy Dasd0f66422016-12-15 05:08:57 +00002412#ifndef NDEBUG
2413 if (!BlocksWithUnanalyzableExits.count(PrevBB)) {
2414 // Given the exact block placement we chose, we may actually not _need_ to
2415 // be able to edit PrevBB's terminator sequence, but not being _able_ to
2416 // do that at this point is a bug.
2417 assert((!TII->analyzeBranch(*PrevBB, TBB, FBB, Cond) ||
2418 !PrevBB->canFallThrough()) &&
2419 "Unexpected block with un-analyzable fallthrough!");
2420 Cond.clear();
2421 TBB = FBB = nullptr;
2422 }
2423#endif
2424
Haicheng Wuba658042016-05-24 22:16:14 +00002425 // The "PrevBB" is not yet updated to reflect current code layout, so,
Sjoerd Meijeraafccf02016-07-15 18:41:56 +00002426 // o. it may fall-through to a block without explicit "goto" instruction
Haicheng Wuba658042016-05-24 22:16:14 +00002427 // before layout, and no longer fall-through it after layout; or
2428 // o. just opposite.
2429 //
Jacques Pienaar48ed4ab2016-07-15 14:41:04 +00002430 // analyzeBranch() may return erroneous value for FBB when these two
Haicheng Wuba658042016-05-24 22:16:14 +00002431 // situations take place. For the first scenario FBB is mistakenly set NULL;
2432 // for the 2nd scenario, the FBB, which is expected to be NULL, is
2433 // mistakenly pointing to "*BI".
2434 // Thus, if the future change needs to use FBB before the layout is set, it
2435 // has to correct FBB first by using the code similar to the following:
2436 //
2437 // if (!Cond.empty() && (!FBB || FBB == ChainBB)) {
2438 // PrevBB->updateTerminator();
2439 // Cond.clear();
2440 // TBB = FBB = nullptr;
Jacques Pienaar48ed4ab2016-07-15 14:41:04 +00002441 // if (TII->analyzeBranch(*PrevBB, TBB, FBB, Cond)) {
Haicheng Wuba658042016-05-24 22:16:14 +00002442 // // FIXME: This should never take place.
2443 // TBB = FBB = nullptr;
2444 // }
2445 // }
Jacques Pienaar48ed4ab2016-07-15 14:41:04 +00002446 if (!TII->analyzeBranch(*PrevBB, TBB, FBB, Cond))
Haicheng Wuba658042016-05-24 22:16:14 +00002447 PrevBB->updateTerminator();
Chandler Carruthdb350872011-10-21 06:46:38 +00002448 }
Chandler Carruthdf234352011-11-13 11:20:44 +00002449
2450 // Fixup the last block.
2451 Cond.clear();
Craig Topper4ba84432014-04-14 00:51:57 +00002452 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
Jacques Pienaar48ed4ab2016-07-15 14:41:04 +00002453 if (!TII->analyzeBranch(F->back(), TBB, FBB, Cond))
Xinliang David Li121cd172016-06-13 22:23:44 +00002454 F->back().updateTerminator();
Xinliang David Li036eb7c2016-07-01 05:46:48 +00002455
2456 BlockWorkList.clear();
2457 EHPadWorkList.clear();
Haicheng Wuba658042016-05-24 22:16:14 +00002458}
2459
Xinliang David Li121cd172016-06-13 22:23:44 +00002460void MachineBlockPlacement::optimizeBranches() {
2461 BlockChain &FunctionChain = *BlockToChain[&F->front()];
Haicheng Wuba658042016-05-24 22:16:14 +00002462 SmallVector<MachineOperand, 4> Cond; // For AnalyzeBranch.
Quentin Colombet1b867752016-05-02 22:58:59 +00002463
2464 // Now that all the basic blocks in the chain have the proper layout,
2465 // make a final call to AnalyzeBranch with AllowModify set.
2466 // Indeed, the target may be able to optimize the branches in a way we
2467 // cannot because all branches may not be analyzable.
2468 // E.g., the target may be able to remove an unconditional branch to
2469 // a fallthrough when it occurs after predicated terminators.
2470 for (MachineBasicBlock *ChainBB : FunctionChain) {
2471 Cond.clear();
Haicheng Wuba658042016-05-24 22:16:14 +00002472 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
Jacques Pienaar48ed4ab2016-07-15 14:41:04 +00002473 if (!TII->analyzeBranch(*ChainBB, TBB, FBB, Cond, /*AllowModify*/ true)) {
Haicheng Wuba658042016-05-24 22:16:14 +00002474 // If PrevBB has a two-way branch, try to re-order the branches
2475 // such that we branch to the successor with higher probability first.
2476 if (TBB && !Cond.empty() && FBB &&
2477 MBPI->getEdgeProbability(ChainBB, FBB) >
2478 MBPI->getEdgeProbability(ChainBB, TBB) &&
Matt Arsenault93e6e542016-09-14 20:43:16 +00002479 !TII->reverseBranchCondition(Cond)) {
Nicola Zaghen0818e782018-05-14 12:53:11 +00002480 LLVM_DEBUG(dbgs() << "Reverse order of the two branches: "
2481 << getBlockName(ChainBB) << "\n");
2482 LLVM_DEBUG(dbgs() << " Edge probability: "
2483 << MBPI->getEdgeProbability(ChainBB, FBB) << " vs "
2484 << MBPI->getEdgeProbability(ChainBB, TBB) << "\n");
Haicheng Wuba658042016-05-24 22:16:14 +00002485 DebugLoc dl; // FIXME: this is nowhere
Matt Arsenault93e6e542016-09-14 20:43:16 +00002486 TII->removeBranch(*ChainBB);
Matt Arsenaultb1a710d2016-09-14 17:24:15 +00002487 TII->insertBranch(*ChainBB, FBB, TBB, Cond, dl);
Haicheng Wuba658042016-05-24 22:16:14 +00002488 ChainBB->updateTerminator();
2489 }
2490 }
Quentin Colombet1b867752016-05-02 22:58:59 +00002491 }
Haicheng Wuc4cd8172016-04-29 17:06:44 +00002492}
Chandler Carruthdb350872011-10-21 06:46:38 +00002493
Xinliang David Li121cd172016-06-13 22:23:44 +00002494void MachineBlockPlacement::alignBlocks() {
Chandler Carruth70daea92012-04-16 01:12:56 +00002495 // Walk through the backedges of the function now that we have fully laid out
2496 // the basic blocks and align the destination of each backedge. We don't rely
Chandler Carruthe6450dc2012-08-07 09:45:24 +00002497 // exclusively on the loop info here so that we can align backedges in
2498 // unnatural CFGs and backedges that were introduced purely because of the
2499 // loop rotations done during this layout pass.
Tim Northover29369e82018-09-13 10:28:05 +00002500 if (F->getFunction().optForMinSize() ||
2501 (F->getFunction().optForSize() && !TLI->alignLoopsWithOptSize()))
Chandler Carruth4a85cc92011-10-21 08:57:37 +00002502 return;
Xinliang David Li121cd172016-06-13 22:23:44 +00002503 BlockChain &FunctionChain = *BlockToChain[&F->front()];
Chandler Carruthe6450dc2012-08-07 09:45:24 +00002504 if (FunctionChain.begin() == FunctionChain.end())
Chandler Carruth35742dd2015-03-05 02:35:31 +00002505 return; // Empty chain.
Chandler Carruth4a85cc92011-10-21 08:57:37 +00002506
Chandler Carruthe6450dc2012-08-07 09:45:24 +00002507 const BranchProbability ColdProb(1, 5); // 20%
Xinliang David Li121cd172016-06-13 22:23:44 +00002508 BlockFrequency EntryFreq = MBFI->getBlockFreq(&F->front());
Chandler Carruthe6450dc2012-08-07 09:45:24 +00002509 BlockFrequency WeightedEntryFreq = EntryFreq * ColdProb;
Chandler Carruthbb535bc2015-03-05 03:19:05 +00002510 for (MachineBasicBlock *ChainBB : FunctionChain) {
2511 if (ChainBB == *FunctionChain.begin())
2512 continue;
2513
Chandler Carruthe6450dc2012-08-07 09:45:24 +00002514 // Don't align non-looping basic blocks. These are unlikely to execute
2515 // enough times to matter in practice. Note that we'll still handle
2516 // unnatural CFGs inside of a natural outer loop (the common case) and
2517 // rotated loops.
Chandler Carruthbb535bc2015-03-05 03:19:05 +00002518 MachineLoop *L = MLI->getLoopFor(ChainBB);
Chandler Carruthe6450dc2012-08-07 09:45:24 +00002519 if (!L)
2520 continue;
2521
Hal Finkele05b2322015-01-03 17:58:24 +00002522 unsigned Align = TLI->getPrefLoopAlignment(L);
2523 if (!Align)
Chandler Carruth35742dd2015-03-05 02:35:31 +00002524 continue; // Don't care about loop alignment.
Hal Finkele05b2322015-01-03 17:58:24 +00002525
Chandler Carruthe6450dc2012-08-07 09:45:24 +00002526 // If the block is cold relative to the function entry don't waste space
2527 // aligning it.
Chandler Carruthbb535bc2015-03-05 03:19:05 +00002528 BlockFrequency Freq = MBFI->getBlockFreq(ChainBB);
Chandler Carruthe6450dc2012-08-07 09:45:24 +00002529 if (Freq < WeightedEntryFreq)
2530 continue;
2531
2532 // If the block is cold relative to its loop header, don't align it
2533 // regardless of what edges into the block exist.
2534 MachineBasicBlock *LoopHeader = L->getHeader();
2535 BlockFrequency LoopHeaderFreq = MBFI->getBlockFreq(LoopHeader);
2536 if (Freq < (LoopHeaderFreq * ColdProb))
2537 continue;
2538
2539 // Check for the existence of a non-layout predecessor which would benefit
2540 // from aligning this block.
Chandler Carruthbb535bc2015-03-05 03:19:05 +00002541 MachineBasicBlock *LayoutPred =
2542 &*std::prev(MachineFunction::iterator(ChainBB));
Chandler Carruthe6450dc2012-08-07 09:45:24 +00002543
2544 // Force alignment if all the predecessors are jumps. We already checked
2545 // that the block isn't cold above.
Chandler Carruthbb535bc2015-03-05 03:19:05 +00002546 if (!LayoutPred->isSuccessor(ChainBB)) {
2547 ChainBB->setAlignment(Align);
Chandler Carruthe6450dc2012-08-07 09:45:24 +00002548 continue;
2549 }
2550
2551 // Align this block if the layout predecessor's edge into this block is
Nadav Rotem975ee542013-03-29 16:34:23 +00002552 // cold relative to the block. When this is true, other predecessors make up
Chandler Carruthe6450dc2012-08-07 09:45:24 +00002553 // all of the hot entries into the block and thus alignment is likely to be
2554 // important.
Chandler Carruthbb535bc2015-03-05 03:19:05 +00002555 BranchProbability LayoutProb =
2556 MBPI->getEdgeProbability(LayoutPred, ChainBB);
Chandler Carruthe6450dc2012-08-07 09:45:24 +00002557 BlockFrequency LayoutEdgeFreq = MBFI->getBlockFreq(LayoutPred) * LayoutProb;
2558 if (LayoutEdgeFreq <= (Freq * ColdProb))
Chandler Carruthbb535bc2015-03-05 03:19:05 +00002559 ChainBB->setAlignment(Align);
Chandler Carruth70daea92012-04-16 01:12:56 +00002560 }
Chandler Carruth4a85cc92011-10-21 08:57:37 +00002561}
2562
Kyle Butt2a180182016-10-11 20:36:43 +00002563/// Tail duplicate \p BB into (some) predecessors if profitable, repeating if
2564/// it was duplicated into its chain predecessor and removed.
2565/// \p BB - Basic block that may be duplicated.
2566///
2567/// \p LPred - Chosen layout predecessor of \p BB.
2568/// Updated to be the chain end if LPred is removed.
2569/// \p Chain - Chain to which \p LPred belongs, and \p BB will belong.
2570/// \p BlockFilter - Set of blocks that belong to the loop being laid out.
2571/// Used to identify which blocks to update predecessor
2572/// counts.
2573/// \p PrevUnplacedBlockIt - Iterator pointing to the last block that was
2574/// chosen in the given order due to unnatural CFG
2575/// only needed if \p BB is removed and
2576/// \p PrevUnplacedBlockIt pointed to \p BB.
2577/// @return true if \p BB was removed.
2578bool MachineBlockPlacement::repeatedlyTailDuplicateBlock(
2579 MachineBasicBlock *BB, MachineBasicBlock *&LPred,
Kyle Butt7a252572017-02-04 02:26:32 +00002580 const MachineBasicBlock *LoopHeaderBB,
Kyle Butt2a180182016-10-11 20:36:43 +00002581 BlockChain &Chain, BlockFilterSet *BlockFilter,
2582 MachineFunction::iterator &PrevUnplacedBlockIt) {
2583 bool Removed, DuplicatedToLPred;
2584 bool DuplicatedToOriginalLPred;
2585 Removed = maybeTailDuplicateBlock(BB, LPred, Chain, BlockFilter,
2586 PrevUnplacedBlockIt,
2587 DuplicatedToLPred);
2588 if (!Removed)
2589 return false;
2590 DuplicatedToOriginalLPred = DuplicatedToLPred;
2591 // Iteratively try to duplicate again. It can happen that a block that is
2592 // duplicated into is still small enough to be duplicated again.
2593 // No need to call markBlockSuccessors in this case, as the blocks being
2594 // duplicated from here on are already scheduled.
2595 // Note that DuplicatedToLPred always implies Removed.
2596 while (DuplicatedToLPred) {
Eugene Zelenko2de563a2017-08-24 21:21:39 +00002597 assert(Removed && "Block must have been removed to be duplicated into its "
2598 "layout predecessor.");
Kyle Butt2a180182016-10-11 20:36:43 +00002599 MachineBasicBlock *DupBB, *DupPred;
2600 // The removal callback causes Chain.end() to be updated when a block is
2601 // removed. On the first pass through the loop, the chain end should be the
2602 // same as it was on function entry. On subsequent passes, because we are
2603 // duplicating the block at the end of the chain, if it is removed the
2604 // chain will have shrunk by one block.
2605 BlockChain::iterator ChainEnd = Chain.end();
2606 DupBB = *(--ChainEnd);
2607 // Now try to duplicate again.
2608 if (ChainEnd == Chain.begin())
2609 break;
2610 DupPred = *std::prev(ChainEnd);
2611 Removed = maybeTailDuplicateBlock(DupBB, DupPred, Chain, BlockFilter,
2612 PrevUnplacedBlockIt,
2613 DuplicatedToLPred);
2614 }
2615 // If BB was duplicated into LPred, it is now scheduled. But because it was
2616 // removed, markChainSuccessors won't be called for its chain. Instead we
2617 // call markBlockSuccessors for LPred to achieve the same effect. This must go
2618 // at the end because repeating the tail duplication can increase the number
2619 // of unscheduled predecessors.
2620 LPred = *std::prev(Chain.end());
2621 if (DuplicatedToOriginalLPred)
2622 markBlockSuccessors(Chain, LPred, LoopHeaderBB, BlockFilter);
2623 return true;
2624}
2625
2626/// Tail duplicate \p BB into (some) predecessors if profitable.
2627/// \p BB - Basic block that may be duplicated
2628/// \p LPred - Chosen layout predecessor of \p BB
2629/// \p Chain - Chain to which \p LPred belongs, and \p BB will belong.
2630/// \p BlockFilter - Set of blocks that belong to the loop being laid out.
2631/// Used to identify which blocks to update predecessor
2632/// counts.
2633/// \p PrevUnplacedBlockIt - Iterator pointing to the last block that was
2634/// chosen in the given order due to unnatural CFG
2635/// only needed if \p BB is removed and
2636/// \p PrevUnplacedBlockIt pointed to \p BB.
2637/// \p DuplicatedToLPred - True if the block was duplicated into LPred. Will
2638/// only be true if the block was removed.
2639/// \return - True if the block was duplicated into all preds and removed.
2640bool MachineBlockPlacement::maybeTailDuplicateBlock(
2641 MachineBasicBlock *BB, MachineBasicBlock *LPred,
Kyle Butt7a252572017-02-04 02:26:32 +00002642 BlockChain &Chain, BlockFilterSet *BlockFilter,
Kyle Butt2a180182016-10-11 20:36:43 +00002643 MachineFunction::iterator &PrevUnplacedBlockIt,
2644 bool &DuplicatedToLPred) {
Kyle Butt2a180182016-10-11 20:36:43 +00002645 DuplicatedToLPred = false;
Kyle Butt286f20b2017-02-04 02:26:34 +00002646 if (!shouldTailDuplicate(BB))
2647 return false;
2648
Nicola Zaghen0818e782018-05-14 12:53:11 +00002649 LLVM_DEBUG(dbgs() << "Redoing tail duplication for Succ#" << BB->getNumber()
2650 << "\n");
Kyle Butt5818a512017-01-31 23:48:32 +00002651
Kyle Butt2a180182016-10-11 20:36:43 +00002652 // This has to be a callback because none of it can be done after
2653 // BB is deleted.
2654 bool Removed = false;
2655 auto RemovalCallback =
2656 [&](MachineBasicBlock *RemBB) {
2657 // Signal to outer function
2658 Removed = true;
2659
2660 // Conservative default.
2661 bool InWorkList = true;
2662 // Remove from the Chain and Chain Map
2663 if (BlockToChain.count(RemBB)) {
2664 BlockChain *Chain = BlockToChain[RemBB];
2665 InWorkList = Chain->UnscheduledPredecessors == 0;
2666 Chain->remove(RemBB);
2667 BlockToChain.erase(RemBB);
2668 }
2669
2670 // Handle the unplaced block iterator
2671 if (&(*PrevUnplacedBlockIt) == RemBB) {
2672 PrevUnplacedBlockIt++;
2673 }
2674
2675 // Handle the Work Lists
2676 if (InWorkList) {
2677 SmallVectorImpl<MachineBasicBlock *> &RemoveList = BlockWorkList;
2678 if (RemBB->isEHPad())
2679 RemoveList = EHPadWorkList;
2680 RemoveList.erase(
Eugene Zelenko2de563a2017-08-24 21:21:39 +00002681 llvm::remove_if(RemoveList,
2682 [RemBB](MachineBasicBlock *BB) {
2683 return BB == RemBB;
2684 }),
Kyle Butt2a180182016-10-11 20:36:43 +00002685 RemoveList.end());
2686 }
2687
2688 // Handle the filter set
2689 if (BlockFilter) {
Rong Xu4146fdb2016-11-16 20:50:06 +00002690 BlockFilter->remove(RemBB);
Kyle Butt2a180182016-10-11 20:36:43 +00002691 }
2692
2693 // Remove the block from loop info.
2694 MLI->removeBlock(RemBB);
Kyle Buttbf977932016-10-27 21:37:20 +00002695 if (RemBB == PreferredLoopExit)
2696 PreferredLoopExit = nullptr;
Kyle Butt2a180182016-10-11 20:36:43 +00002697
Nicola Zaghen0818e782018-05-14 12:53:11 +00002698 LLVM_DEBUG(dbgs() << "TailDuplicator deleted block: "
2699 << getBlockName(RemBB) << "\n");
Kyle Butt2a180182016-10-11 20:36:43 +00002700 };
2701 auto RemovalCallbackRef =
Eugene Zelenko2de563a2017-08-24 21:21:39 +00002702 function_ref<void(MachineBasicBlock*)>(RemovalCallback);
Kyle Butt2a180182016-10-11 20:36:43 +00002703
2704 SmallVector<MachineBasicBlock *, 8> DuplicatedPreds;
Kyle Butt5818a512017-01-31 23:48:32 +00002705 bool IsSimple = TailDup.isSimpleBB(BB);
Kyle Butt2a180182016-10-11 20:36:43 +00002706 TailDup.tailDuplicateAndUpdate(IsSimple, BB, LPred,
2707 &DuplicatedPreds, &RemovalCallbackRef);
2708
2709 // Update UnscheduledPredecessors to reflect tail-duplication.
2710 DuplicatedToLPred = false;
2711 for (MachineBasicBlock *Pred : DuplicatedPreds) {
2712 // We're only looking for unscheduled predecessors that match the filter.
2713 BlockChain* PredChain = BlockToChain[Pred];
2714 if (Pred == LPred)
2715 DuplicatedToLPred = true;
2716 if (Pred == LPred || (BlockFilter && !BlockFilter->count(Pred))
2717 || PredChain == &Chain)
2718 continue;
2719 for (MachineBasicBlock *NewSucc : Pred->successors()) {
2720 if (BlockFilter && !BlockFilter->count(NewSucc))
2721 continue;
2722 BlockChain *NewChain = BlockToChain[NewSucc];
2723 if (NewChain != &Chain && NewChain != PredChain)
2724 NewChain->UnscheduledPredecessors++;
2725 }
2726 }
2727 return Removed;
2728}
2729
Xinliang David Li121cd172016-06-13 22:23:44 +00002730bool MachineBlockPlacement::runOnMachineFunction(MachineFunction &MF) {
Matthias Braund3181392017-12-15 22:22:58 +00002731 if (skipFunction(MF.getFunction()))
Andrew Kaylor7b7e9c72016-05-03 22:32:30 +00002732 return false;
2733
Chandler Carruthdb350872011-10-21 06:46:38 +00002734 // Check for single-block functions and skip them.
Xinliang David Li121cd172016-06-13 22:23:44 +00002735 if (std::next(MF.begin()) == MF.end())
Chandler Carruthdb350872011-10-21 06:46:38 +00002736 return false;
2737
Xinliang David Li121cd172016-06-13 22:23:44 +00002738 F = &MF;
Chandler Carruthdb350872011-10-21 06:46:38 +00002739 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
Haicheng Wuc4f22582016-06-09 15:24:29 +00002740 MBFI = llvm::make_unique<BranchFolder::MBFIWrapper>(
2741 getAnalysis<MachineBlockFrequencyInfo>());
Chandler Carruth4a85cc92011-10-21 08:57:37 +00002742 MLI = &getAnalysis<MachineLoopInfo>();
Xinliang David Li121cd172016-06-13 22:23:44 +00002743 TII = MF.getSubtarget().getInstrInfo();
2744 TLI = MF.getSubtarget().getTargetLowering();
Kyle Butt5818a512017-01-31 23:48:32 +00002745 MPDT = nullptr;
Eric Christopherfd64fad2016-11-01 22:15:50 +00002746
2747 // Initialize PreferredLoopExit to nullptr here since it may never be set if
2748 // there are no MachineLoops.
2749 PreferredLoopExit = nullptr;
2750
Kyle Butt25ccad82017-05-17 23:44:41 +00002751 assert(BlockToChain.empty() &&
2752 "BlockToChain map should be empty before starting placement.");
2753 assert(ComputedEdges.empty() &&
2754 "Computed Edge map should be empty before starting placement.");
Kyle Butt92625cf2017-04-12 03:18:20 +00002755
Kyle Butte6202482017-05-15 17:30:47 +00002756 unsigned TailDupSize = TailDupPlacementThreshold;
2757 // If only the aggressive threshold is explicitly set, use it.
2758 if (TailDupPlacementAggressiveThreshold.getNumOccurrences() != 0 &&
2759 TailDupPlacementThreshold.getNumOccurrences() == 0)
2760 TailDupSize = TailDupPlacementAggressiveThreshold;
2761
2762 TargetPassConfig *PassConfig = &getAnalysis<TargetPassConfig>();
Hiroshi Inoue73d058a2018-06-20 05:29:26 +00002763 // For aggressive optimization, we can adjust some thresholds to be less
Kyle Butte6202482017-05-15 17:30:47 +00002764 // conservative.
2765 if (PassConfig->getOptLevel() >= CodeGenOpt::Aggressive) {
2766 // At O3 we should be more willing to copy blocks for tail duplication. This
2767 // increases size pressure, so we only do it at O3
2768 // Do this unless only the regular threshold is explicitly set.
2769 if (TailDupPlacementThreshold.getNumOccurrences() == 0 ||
2770 TailDupPlacementAggressiveThreshold.getNumOccurrences() != 0)
2771 TailDupSize = TailDupPlacementAggressiveThreshold;
2772 }
2773
Tim Shene1a4b172018-03-30 17:51:00 +00002774 if (allowTailDupPlacement()) {
Kyle Butt5818a512017-01-31 23:48:32 +00002775 MPDT = &getAnalysis<MachinePostDominatorTree>();
Matthias Braund3181392017-12-15 22:22:58 +00002776 if (MF.getFunction().optForSize())
Kyle Butt2a180182016-10-11 20:36:43 +00002777 TailDupSize = 1;
Matthias Braund44f0242017-08-23 03:17:59 +00002778 bool PreRegAlloc = false;
2779 TailDup.initMF(MF, PreRegAlloc, MBPI, /* LayoutMode */ true, TailDupSize);
Kyle Buttc160e2a2017-03-03 01:00:22 +00002780 precomputeTriangleChains();
Kyle Butt2a180182016-10-11 20:36:43 +00002781 }
2782
Xinliang David Li121cd172016-06-13 22:23:44 +00002783 buildCFGChains();
Haicheng Wuc4f22582016-06-09 15:24:29 +00002784
2785 // Changing the layout can create new tail merging opportunities.
Haicheng Wuc4f22582016-06-09 15:24:29 +00002786 // TailMerge can create jump into if branches that make CFG irreducible for
Sjoerd Meijeraafccf02016-07-15 18:41:56 +00002787 // HW that requires structured CFG.
Xinliang David Li121cd172016-06-13 22:23:44 +00002788 bool EnableTailMerge = !MF.getTarget().requiresStructuredCFG() &&
Haicheng Wuc4f22582016-06-09 15:24:29 +00002789 PassConfig->getEnableTailMerge() &&
2790 BranchFoldPlacement;
2791 // No tail merging opportunities if the block number is less than four.
Xinliang David Li121cd172016-06-13 22:23:44 +00002792 if (MF.size() > 3 && EnableTailMerge) {
Kyle Butte6202482017-05-15 17:30:47 +00002793 unsigned TailMergeSize = TailDupSize + 1;
Haicheng Wuc4f22582016-06-09 15:24:29 +00002794 BranchFolder BF(/*EnableTailMerge=*/true, /*CommonHoist=*/false, *MBFI,
Kyle Buttb1ee91e2016-08-18 18:57:29 +00002795 *MBPI, TailMergeSize);
Haicheng Wuc4f22582016-06-09 15:24:29 +00002796
Xinliang David Li121cd172016-06-13 22:23:44 +00002797 if (BF.OptimizeFunction(MF, TII, MF.getSubtarget().getRegisterInfo(),
Haicheng Wuc4f22582016-06-09 15:24:29 +00002798 getAnalysisIfAvailable<MachineModuleInfo>(), MLI,
2799 /*AfterBlockPlacement=*/true)) {
2800 // Redo the layout if tail merging creates/removes/moves blocks.
2801 BlockToChain.clear();
Kyle Butt92625cf2017-04-12 03:18:20 +00002802 ComputedEdges.clear();
Kyle Buttce9b88e2017-03-02 21:44:24 +00002803 // Must redo the post-dominator tree if blocks were changed.
Kyle Butt5818a512017-01-31 23:48:32 +00002804 if (MPDT)
2805 MPDT->runOnMachineFunction(MF);
Haicheng Wuc4f22582016-06-09 15:24:29 +00002806 ChainAllocator.DestroyAll();
Xinliang David Li121cd172016-06-13 22:23:44 +00002807 buildCFGChains();
Haicheng Wuc4f22582016-06-09 15:24:29 +00002808 }
2809 }
2810
Xinliang David Li121cd172016-06-13 22:23:44 +00002811 optimizeBranches();
2812 alignBlocks();
Chandler Carruthdb350872011-10-21 06:46:38 +00002813
Chandler Carruthdb350872011-10-21 06:46:38 +00002814 BlockToChain.clear();
Kyle Butt92625cf2017-04-12 03:18:20 +00002815 ComputedEdges.clear();
Chandler Carruthf5e47ac2011-11-14 10:57:23 +00002816 ChainAllocator.DestroyAll();
Chandler Carruthdb350872011-10-21 06:46:38 +00002817
Nadav Rotem33a47d62013-04-12 01:24:16 +00002818 if (AlignAllBlock)
2819 // Align all of the blocks in the function to a specific alignment.
Xinliang David Li121cd172016-06-13 22:23:44 +00002820 for (MachineBasicBlock &MBB : MF)
Chandler Carruthbb535bc2015-03-05 03:19:05 +00002821 MBB.setAlignment(AlignAllBlock);
Geoff Berry5e799862016-01-21 17:25:52 +00002822 else if (AlignAllNonFallThruBlocks) {
2823 // Align all of the blocks that have no fall-through predecessors to a
2824 // specific alignment.
Xinliang David Li121cd172016-06-13 22:23:44 +00002825 for (auto MBI = std::next(MF.begin()), MBE = MF.end(); MBI != MBE; ++MBI) {
Geoff Berry5e799862016-01-21 17:25:52 +00002826 auto LayoutPred = std::prev(MBI);
2827 if (!LayoutPred->isSuccessor(&*MBI))
2828 MBI->setAlignment(AlignAllNonFallThruBlocks);
2829 }
2830 }
Xinliang David Li828b3982017-01-29 01:57:02 +00002831 if (ViewBlockLayoutWithBFI != GVDT_None &&
2832 (ViewBlockFreqFuncName.empty() ||
Matthias Braund3181392017-12-15 22:22:58 +00002833 F->getFunction().getName().equals(ViewBlockFreqFuncName))) {
Xinliang David Li210c6902017-02-15 19:21:04 +00002834 MBFI->view("MBP." + MF.getName(), false);
Xinliang David Li828b3982017-01-29 01:57:02 +00002835 }
Xinliang David Li828b3982017-01-29 01:57:02 +00002836
Nadav Rotem33a47d62013-04-12 01:24:16 +00002837
Chandler Carruthdb350872011-10-21 06:46:38 +00002838 // We always return true as we have no way to track whether the final order
2839 // differs from the original order.
2840 return true;
2841}
Chandler Carruth37efc9f2011-11-02 07:17:12 +00002842
2843namespace {
Eugene Zelenko2de563a2017-08-24 21:21:39 +00002844
Adrian Prantl26b584c2018-05-01 15:54:18 +00002845/// A pass to compute block placement statistics.
Chandler Carruth37efc9f2011-11-02 07:17:12 +00002846///
2847/// A separate pass to compute interesting statistics for evaluating block
2848/// placement. This is separate from the actual placement pass so that they can
Benjamin Kramerd9b0b022012-06-02 10:20:22 +00002849/// be computed in the absence of any placement transformations or when using
Chandler Carruth37efc9f2011-11-02 07:17:12 +00002850/// alternative placement strategies.
2851class MachineBlockPlacementStats : public MachineFunctionPass {
Adrian Prantl26b584c2018-05-01 15:54:18 +00002852 /// A handle to the branch probability pass.
Chandler Carruth37efc9f2011-11-02 07:17:12 +00002853 const MachineBranchProbabilityInfo *MBPI;
2854
Adrian Prantl26b584c2018-05-01 15:54:18 +00002855 /// A handle to the function-wide block frequency pass.
Chandler Carruth37efc9f2011-11-02 07:17:12 +00002856 const MachineBlockFrequencyInfo *MBFI;
2857
2858public:
2859 static char ID; // Pass identification, replacement for typeid
Eugene Zelenko2de563a2017-08-24 21:21:39 +00002860
Chandler Carruth37efc9f2011-11-02 07:17:12 +00002861 MachineBlockPlacementStats() : MachineFunctionPass(ID) {
2862 initializeMachineBlockPlacementStatsPass(*PassRegistry::getPassRegistry());
2863 }
2864
Craig Topper9f998de2014-03-07 09:26:03 +00002865 bool runOnMachineFunction(MachineFunction &F) override;
Chandler Carruth37efc9f2011-11-02 07:17:12 +00002866
Craig Topper9f998de2014-03-07 09:26:03 +00002867 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruth37efc9f2011-11-02 07:17:12 +00002868 AU.addRequired<MachineBranchProbabilityInfo>();
2869 AU.addRequired<MachineBlockFrequencyInfo>();
2870 AU.setPreservesAll();
2871 MachineFunctionPass::getAnalysisUsage(AU);
2872 }
Chandler Carruth37efc9f2011-11-02 07:17:12 +00002873};
Eugene Zelenko2de563a2017-08-24 21:21:39 +00002874
2875} // end anonymous namespace
Chandler Carruth37efc9f2011-11-02 07:17:12 +00002876
2877char MachineBlockPlacementStats::ID = 0;
Eugene Zelenko2de563a2017-08-24 21:21:39 +00002878
Andrew Trick1dd8c852012-02-08 21:23:13 +00002879char &llvm::MachineBlockPlacementStatsID = MachineBlockPlacementStats::ID;
Eugene Zelenko2de563a2017-08-24 21:21:39 +00002880
Chandler Carruth37efc9f2011-11-02 07:17:12 +00002881INITIALIZE_PASS_BEGIN(MachineBlockPlacementStats, "block-placement-stats",
2882 "Basic Block Placement Stats", false, false)
2883INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
2884INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
2885INITIALIZE_PASS_END(MachineBlockPlacementStats, "block-placement-stats",
2886 "Basic Block Placement Stats", false, false)
2887
Chandler Carruth37efc9f2011-11-02 07:17:12 +00002888bool MachineBlockPlacementStats::runOnMachineFunction(MachineFunction &F) {
2889 // Check for single-block functions and skip them.
Benjamin Kramerd628f192014-03-02 12:27:27 +00002890 if (std::next(F.begin()) == F.end())
Chandler Carruth37efc9f2011-11-02 07:17:12 +00002891 return false;
2892
2893 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
2894 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
2895
Chandler Carruthbb535bc2015-03-05 03:19:05 +00002896 for (MachineBasicBlock &MBB : F) {
2897 BlockFrequency BlockFreq = MBFI->getBlockFreq(&MBB);
Chandler Carruth35742dd2015-03-05 02:35:31 +00002898 Statistic &NumBranches =
Chandler Carruthbb535bc2015-03-05 03:19:05 +00002899 (MBB.succ_size() > 1) ? NumCondBranches : NumUncondBranches;
Chandler Carruth35742dd2015-03-05 02:35:31 +00002900 Statistic &BranchTakenFreq =
Chandler Carruthbb535bc2015-03-05 03:19:05 +00002901 (MBB.succ_size() > 1) ? CondBranchTakenFreq : UncondBranchTakenFreq;
2902 for (MachineBasicBlock *Succ : MBB.successors()) {
Chandler Carruth37efc9f2011-11-02 07:17:12 +00002903 // Skip if this successor is a fallthrough.
Chandler Carruthbb535bc2015-03-05 03:19:05 +00002904 if (MBB.isLayoutSuccessor(Succ))
Chandler Carruth37efc9f2011-11-02 07:17:12 +00002905 continue;
2906
Chandler Carruthbb535bc2015-03-05 03:19:05 +00002907 BlockFrequency EdgeFreq =
2908 BlockFreq * MBPI->getEdgeProbability(&MBB, Succ);
Chandler Carruth37efc9f2011-11-02 07:17:12 +00002909 ++NumBranches;
2910 BranchTakenFreq += EdgeFreq.getFrequency();
2911 }
2912 }
2913
2914 return false;
2915}