blob: ec43097c23b2a3773f537c310ba935bfdbc88e30 [file] [log] [blame]
Eugene Zelenko5df3d892017-08-24 21:21:39 +00001//===- MachineBlockPlacement.cpp - Basic Block Code Layout optimization ---===//
Chandler Carruth10281422011-10-21 06:46:38 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Chandler Carruthbd1be4d2011-10-23 09:18:45 +000010// This file implements basic block placement transformations using the CFG
11// structure and branch probability estimates.
Chandler Carruth10281422011-10-21 06:46:38 +000012//
Chandler Carruthbd1be4d2011-10-23 09:18:45 +000013// The pass strives to preserve the structure of the CFG (that is, retain
Benjamin Kramerbde91762012-06-02 10:20:22 +000014// a topological ordering of basic blocks) in the absence of a *strong* signal
Chandler Carruthbd1be4d2011-10-23 09:18:45 +000015// to the contrary from probabilities. However, within the CFG structure, it
16// attempts to choose an ordering which favors placing more likely sequences of
17// blocks adjacent to each other.
18//
19// The algorithm works from the inner-most loop within a function outward, and
20// at each stage walks through the basic blocks, trying to coalesce them into
21// sequential chains where allowed by the CFG (or demanded by heavy
22// probabilities). Finally, it walks the blocks in topological order, and the
23// first time it reaches a chain of basic blocks, it schedules them in the
24// function in-order.
Chandler Carruth10281422011-10-21 06:46:38 +000025//
26//===----------------------------------------------------------------------===//
27
Haicheng Wu5b458cc2016-06-09 15:24:29 +000028#include "BranchFolding.h"
Eugene Zelenko5df3d892017-08-24 21:21:39 +000029#include "llvm/ADT/ArrayRef.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000030#include "llvm/ADT/DenseMap.h"
Eugene Zelenko5df3d892017-08-24 21:21:39 +000031#include "llvm/ADT/STLExtras.h"
32#include "llvm/ADT/SetVector.h"
Chandler Carruthed0881b2012-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 Lifd3f6452017-01-29 01:57:02 +000036#include "llvm/Analysis/BlockFrequencyInfoImpl.h"
Chandler Carruth8b9737c2011-10-21 08:57:37 +000037#include "llvm/CodeGen/MachineBasicBlock.h"
Chandler Carruth10281422011-10-21 06:46:38 +000038#include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
39#include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
40#include "llvm/CodeGen/MachineFunction.h"
Chandler Carruth10281422011-10-21 06:46:38 +000041#include "llvm/CodeGen/MachineFunctionPass.h"
Chandler Carruth8b9737c2011-10-21 08:57:37 +000042#include "llvm/CodeGen/MachineLoopInfo.h"
43#include "llvm/CodeGen/MachineModuleInfo.h"
Kyle Buttb15c0662017-01-31 23:48:32 +000044#include "llvm/CodeGen/MachinePostDominators.h"
Kyle Butt0846e562016-10-11 20:36:43 +000045#include "llvm/CodeGen/TailDuplicator.h"
David Blaikie3f833ed2017-11-08 01:01:31 +000046#include "llvm/CodeGen/TargetInstrInfo.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000047#include "llvm/CodeGen/TargetLowering.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000048#include "llvm/CodeGen/TargetPassConfig.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000049#include "llvm/CodeGen/TargetSubtargetInfo.h"
Eugene Zelenko5df3d892017-08-24 21:21:39 +000050#include "llvm/IR/DebugLoc.h"
51#include "llvm/IR/Function.h"
52#include "llvm/Pass.h"
Chandler Carruth10281422011-10-21 06:46:38 +000053#include "llvm/Support/Allocator.h"
Eugene Zelenko5df3d892017-08-24 21:21:39 +000054#include "llvm/Support/BlockFrequency.h"
55#include "llvm/Support/BranchProbability.h"
56#include "llvm/Support/CodeGen.h"
Nadav Rotemc3b0f502013-04-12 00:48:32 +000057#include "llvm/Support/CommandLine.h"
Eugene Zelenko5df3d892017-08-24 21:21:39 +000058#include "llvm/Support/Compiler.h"
Chandler Carruthbd1be4d2011-10-23 09:18:45 +000059#include "llvm/Support/Debug.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000060#include "llvm/Support/raw_ostream.h"
Eugene Zelenko5df3d892017-08-24 21:21:39 +000061#include "llvm/Target/TargetMachine.h"
Chandler Carruth10281422011-10-21 06:46:38 +000062#include <algorithm>
Eugene Zelenko5df3d892017-08-24 21:21:39 +000063#include <cassert>
64#include <cstdint>
65#include <iterator>
66#include <memory>
67#include <string>
68#include <tuple>
Kyle Buttb15c0662017-01-31 23:48:32 +000069#include <utility>
Eugene Zelenko5df3d892017-08-24 21:21:39 +000070#include <vector>
71
Chandler Carruth10281422011-10-21 06:46:38 +000072using namespace llvm;
73
Chandler Carruthd0dced52015-03-05 02:28:25 +000074#define DEBUG_TYPE "block-placement"
Chandler Carruth1b9dde02014-04-22 02:02:50 +000075
Chandler Carruthae4e8002011-11-02 07:17:12 +000076STATISTIC(NumCondBranches, "Number of conditional branches");
Craig Topper77ec0772015-09-16 03:52:32 +000077STATISTIC(NumUncondBranches, "Number of unconditional branches");
Chandler Carruthae4e8002011-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 Rotemc3b0f502013-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 Berry10494ac2016-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 Kramerc8160d62013-11-20 19:08:44 +000095// FIXME: Find a good default for this flag and remove the flag.
Chandler Carruth2fc3fe12015-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 Kramerc8160d62013-11-20 19:08:44 +0000101
Sjoerd Meijer5e11a182016-07-27 08:49:23 +0000102// Definition:
103// - Outlining: placement of a basic block outside the chain or hot path.
104
Cong Houb90b9e02015-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 Butt74f61dd2017-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 Hou7745dbc2015-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 Zelenko5df3d892017-08-24 21:21:39 +0000121
Xinliang David Lif0ab6df2016-05-12 02:04:41 +0000122static cl::opt<bool>
123 ForcePreciseRotationCost("force-precise-rotation-cost",
Xinliang David Lib840bb82016-05-12 16:39:02 +0000124 cl::desc("Force the use of precise cost "
125 "loop rotation strategy."),
Xinliang David Lif0ab6df2016-05-12 02:04:41 +0000126 cl::init(false), cl::Hidden);
Cong Hou7745dbc2015-10-19 23:16:40 +0000127
128static cl::opt<unsigned> MisfetchCost(
129 "misfetch-cost",
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +0000130 cl::desc("Cost that models the probabilistic risk of an instruction "
Cong Hou7745dbc2015-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 Butt0846e562016-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 Hou7745dbc2015-10-19 23:16:40 +0000144
Haicheng Wu5b458cc2016-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 Butt0846e562016-10-11 20:36:43 +0000151// Heuristic for tail duplication.
Kyle Buttb15c0662017-01-31 23:48:32 +0000152static cl::opt<unsigned> TailDupPlacementThreshold(
Kyle Butt0846e562016-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 Butt7d531da2017-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 Smithc0541df2017-08-17 23:38:41 +0000164 "have a threshold that won't conflict."), cl::init(4),
Kyle Butt7d531da2017-05-15 17:30:47 +0000165 cl::Hidden);
166
Kyle Buttb15c0662017-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 Butt1fa60302017-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 Butt08655992017-03-16 01:32:29 +0000182 cl::init(2),
Kyle Butt1fa60302017-03-03 01:00:22 +0000183 cl::Hidden);
184
Xinliang David Liff287372016-06-03 23:48:36 +0000185extern cl::opt<unsigned> StaticLikelyProb;
Dehao Chen9f2bdfb2016-06-14 22:27:17 +0000186extern cl::opt<unsigned> ProfileLikelyProb;
Xinliang David Liff287372016-06-03 23:48:36 +0000187
Xinliang David Li58fcc9b2017-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 Lifd3f6452017-01-29 01:57:02 +0000191extern cl::opt<GVDAGType> ViewBlockLayoutWithBFI;
Xinliang David Li58fcc9b2017-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 Lifd3f6452017-01-29 01:57:02 +0000195extern cl::opt<std::string> ViewBlockFreqFuncName;
Xinliang David Lifd3f6452017-01-29 01:57:02 +0000196
Chandler Carruth10281422011-10-21 06:46:38 +0000197namespace {
Chandler Carruth10281422011-10-21 06:46:38 +0000198
Eugene Zelenko5df3d892017-08-24 21:21:39 +0000199class BlockChain;
200
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000201/// Type for our function-wide basic block -> block chain mapping.
Eugene Zelenko5df3d892017-08-24 21:21:39 +0000202using BlockToChainMapType = DenseMap<const MachineBasicBlock *, BlockChain *>;
203
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000204/// A chain of blocks which will be laid out contiguously.
Chandler Carruth10281422011-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 Carruth9139f442012-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 Carruth10281422011-10-21 06:46:38 +0000211///
Chandler Carruth9139f442012-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 Carruthbd1be4d2011-10-23 09:18:45 +0000215class BlockChain {
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000216 /// The sequence of blocks belonging to this chain.
Chandler Carruth10281422011-10-21 06:46:38 +0000217 ///
Chandler Carruthbd1be4d2011-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 Carruth10281422011-10-21 06:46:38 +0000221
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000222 /// A handle to the function-wide basic block to block chain mapping.
Chandler Carruth10281422011-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 Carruthbd1be4d2011-10-23 09:18:45 +0000230public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000231 /// Construct a new BlockChain.
Chandler Carruth10281422011-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 Zelenko5df3d892017-08-24 21:21:39 +0000237 : Blocks(1, BB), BlockToChain(BlockToChain) {
Chandler Carruth10281422011-10-21 06:46:38 +0000238 assert(BB && "Cannot create a chain with a null basic block");
239 BlockToChain[BB] = this;
240 }
241
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000242 /// Iterator over blocks within the chain.
Eugene Zelenko5df3d892017-08-24 21:21:39 +0000243 using iterator = SmallVectorImpl<MachineBasicBlock *>::iterator;
244 using const_iterator = SmallVectorImpl<MachineBasicBlock *>::const_iterator;
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000245
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000246 /// Beginning of blocks within the chain.
Chandler Carruthccc7e422012-04-16 01:12:56 +0000247 iterator begin() { return Blocks.begin(); }
Kyle Butte9425c4f2017-02-04 02:26:32 +0000248 const_iterator begin() const { return Blocks.begin(); }
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000249
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000250 /// End of blocks within the chain.
Chandler Carruthccc7e422012-04-16 01:12:56 +0000251 iterator end() { return Blocks.end(); }
Kyle Butte9425c4f2017-02-04 02:26:32 +0000252 const_iterator end() const { return Blocks.end(); }
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000253
Kyle Butt0846e562016-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 Prantl5f8f34e42018-05-01 15:54:18 +0000264 /// Merge a block chain into this one.
Chandler Carruth10281422011-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 Staszak90616162011-12-21 23:02:08 +0000270 void merge(MachineBasicBlock *BB, BlockChain *Chain) {
Kyle Butt0cf5b2f2017-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 Carruth10281422011-10-21 06:46:38 +0000273
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000274 // Fast path in case we don't have a chain already.
275 if (!Chain) {
Kyle Butt0cf5b2f2017-05-17 23:44:41 +0000276 assert(!BlockToChain[BB] &&
277 "Passed chain is null, but BB has entry in BlockToChain.");
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000278 Blocks.push_back(BB);
279 BlockToChain[BB] = this;
280 return;
Chandler Carruth10281422011-10-21 06:46:38 +0000281 }
282
Kyle Butt0cf5b2f2017-05-17 23:44:41 +0000283 assert(BB == *Chain->begin() && "Passed BB is not head of Chain.");
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000284 assert(Chain->begin() != Chain->end());
Chandler Carruth10281422011-10-21 06:46:38 +0000285
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000286 // Update the incoming blocks to point to this chain, and add them to the
287 // chain structure.
Chandler Carruth7a715da2015-03-05 03:19:05 +0000288 for (MachineBasicBlock *ChainBB : *Chain) {
289 Blocks.push_back(ChainBB);
Kyle Butt0cf5b2f2017-05-17 23:44:41 +0000290 assert(BlockToChain[ChainBB] == Chain && "Incoming blocks not in chain.");
Chandler Carruth7a715da2015-03-05 03:19:05 +0000291 BlockToChain[ChainBB] = this;
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000292 }
Chandler Carruth10281422011-10-21 06:46:38 +0000293 }
Chandler Carruth8d150782011-11-13 11:20:44 +0000294
Chandler Carruth49158902012-04-08 14:37:01 +0000295#ifndef NDEBUG
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000296 /// Dump the blocks in this chain.
Nico Weber7408c702014-01-03 22:53:37 +0000297 LLVM_DUMP_METHOD void dump() {
Chandler Carruth7a715da2015-03-05 03:19:05 +0000298 for (MachineBasicBlock *MBB : *this)
299 MBB->dump();
Chandler Carruth49158902012-04-08 14:37:01 +0000300 }
301#endif // NDEBUG
302
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000303 /// Count of predecessors of any block within the chain which have not
Philip Reamesae27b232016-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 Carruth8d150782011-11-13 11:20:44 +0000309 ///
Philip Reamesae27b232016-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 Zelenko5df3d892017-08-24 21:21:39 +0000312 unsigned UnscheduledPredecessors = 0;
Chandler Carruth10281422011-10-21 06:46:38 +0000313};
Chandler Carruth10281422011-10-21 06:46:38 +0000314
Chandler Carruth10281422011-10-21 06:46:38 +0000315class MachineBlockPlacement : public MachineFunctionPass {
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000316 /// A type for a block filter set.
Eugene Zelenko5df3d892017-08-24 21:21:39 +0000317 using BlockFilterSet = SmallSetVector<const MachineBasicBlock *, 16>;
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000318
Kyle Buttb15c0662017-01-31 23:48:32 +0000319 /// Pair struct containing basic block and taildup profitiability
320 struct BlockAndTailDupResult {
Kyle Butt7fbec9b2017-02-15 19:49:14 +0000321 MachineBasicBlock *BB;
Kyle Buttb15c0662017-01-31 23:48:32 +0000322 bool ShouldTailDup;
323 };
324
Kyle Butt7fbec9b2017-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 Prantl5f8f34e42018-05-01 15:54:18 +0000332 /// work lists of blocks that are ready to be laid out
Xinliang David Li93926ac2016-07-01 05:46:48 +0000333 SmallVector<MachineBasicBlock *, 16> BlockWorkList;
334 SmallVector<MachineBasicBlock *, 16> EHPadWorkList;
335
Kyle Buttebe6cc42017-02-23 21:22:24 +0000336 /// Edges that have already been computed as optimal.
337 DenseMap<const MachineBasicBlock *, BlockAndTailDupResult> ComputedEdges;
Kyle Butt7fbec9b2017-02-15 19:49:14 +0000338
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000339 /// Machine Function
Xinliang David Li52530a72016-06-13 22:23:44 +0000340 MachineFunction *F;
341
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000342 /// A handle to the branch probability pass.
Chandler Carruth10281422011-10-21 06:46:38 +0000343 const MachineBranchProbabilityInfo *MBPI;
344
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000345 /// A handle to the function-wide block frequency pass.
Haicheng Wu5b458cc2016-06-09 15:24:29 +0000346 std::unique_ptr<BranchFolder::MBFIWrapper> MBFI;
Chandler Carruth10281422011-10-21 06:46:38 +0000347
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000348 /// A handle to the loop info.
Haicheng Wu5b458cc2016-06-09 15:24:29 +0000349 MachineLoopInfo *MLI;
Chandler Carruth8b9737c2011-10-21 08:57:37 +0000350
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000351 /// Preferred loop exit.
Kyle Buttab9cca72016-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 Prantl5f8f34e42018-05-01 15:54:18 +0000356 /// A handle to the target's instruction info.
Chandler Carruth10281422011-10-21 06:46:38 +0000357 const TargetInstrInfo *TII;
358
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000359 /// A handle to the target's lowering info.
Benjamin Kramer56b31bd2013-01-11 20:05:37 +0000360 const TargetLoweringBase *TLI;
Chandler Carruth8b9737c2011-10-21 08:57:37 +0000361
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000362 /// A handle to the post dominator tree.
Kyle Buttb15c0662017-01-31 23:48:32 +0000363 MachinePostDominatorTree *MPDT;
364
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000365 /// Duplicator used to duplicate tails during placement.
Kyle Butt0846e562016-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 Prantl5f8f34e42018-05-01 15:54:18 +0000372 /// Allocator and owner of BlockChain structures.
Chandler Carruth10281422011-10-21 06:46:38 +0000373 ///
Chandler Carruth9139f442012-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 Carruth10281422011-10-21 06:46:38 +0000379 SpecificBumpPtrAllocator<BlockChain> ChainAllocator;
380
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000381 /// Function wide BasicBlock to BlockChain mapping.
Chandler Carruth10281422011-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 Butte9425c4f2017-02-04 02:26:32 +0000387 DenseMap<const MachineBasicBlock *, BlockChain *> BlockToChain;
Chandler Carruth10281422011-10-21 06:46:38 +0000388
Sanjoy Dasd7389d62016-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 Butt0846e562016-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 Butte9425c4f2017-02-04 02:26:32 +0000399 void markChainSuccessors(
400 const BlockChain &Chain, const MachineBasicBlock *LoopHeaderBB,
401 const BlockFilterSet *BlockFilter = nullptr);
Kyle Butt0846e562016-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 Butte9425c4f2017-02-04 02:26:32 +0000406 const BlockChain &Chain, const MachineBasicBlock *BB,
407 const MachineBasicBlock *LoopHeaderBB,
Kyle Butt0846e562016-10-11 20:36:43 +0000408 const BlockFilterSet *BlockFilter = nullptr);
409
Xinliang David Li594ffa32016-06-11 18:35:40 +0000410 BranchProbability
Kyle Butte9425c4f2017-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 Butt0846e562016-10-11 20:36:43 +0000419 bool repeatedlyTailDuplicateBlock(
420 MachineBasicBlock *BB, MachineBasicBlock *&LPred,
Kyle Butte9425c4f2017-02-04 02:26:32 +0000421 const MachineBasicBlock *LoopHeaderBB,
Kyle Butt0846e562016-10-11 20:36:43 +0000422 BlockChain &Chain, BlockFilterSet *BlockFilter,
423 MachineFunction::iterator &PrevUnplacedBlockIt);
Kyle Butte9425c4f2017-02-04 02:26:32 +0000424 bool maybeTailDuplicateBlock(
425 MachineBasicBlock *BB, MachineBasicBlock *LPred,
426 BlockChain &Chain, BlockFilterSet *BlockFilter,
427 MachineFunction::iterator &PrevUnplacedBlockIt,
428 bool &DuplicatedToPred);
429 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 Secheteae09c22016-03-14 21:24:11 +0000443
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000444 /// Add a basic block to the work list if it is appropriate.
Amaury Secheteae09c22016-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 Butte9425c4f2017-02-04 02:26:32 +0000449 void fillWorkLists(const MachineBasicBlock *MBB,
Amaury Secheteae09c22016-03-14 21:24:11 +0000450 SmallPtrSetImpl<BlockChain *> &UpdatedPreds,
Amaury Secheteae09c22016-03-14 21:24:11 +0000451 const BlockFilterSet *BlockFilter);
Eugene Zelenko5df3d892017-08-24 21:21:39 +0000452
Kyle Butte9425c4f2017-02-04 02:26:32 +0000453 void buildChain(const MachineBasicBlock *BB, BlockChain &Chain,
Kyle Butt0846e562016-10-11 20:36:43 +0000454 BlockFilterSet *BlockFilter = nullptr);
Kyle Butte9425c4f2017-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 Li52530a72016-06-13 22:23:44 +0000467 void buildCFGChains();
468 void optimizeBranches();
469 void alignBlocks();
Kyle Butt7fbec9b2017-02-15 19:49:14 +0000470 /// Returns true if a block should be tail-duplicated to increase fallthrough
471 /// opportunities.
Kyle Buttb15c0662017-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 Butte9425c4f2017-02-04 02:26:32 +0000476 const MachineBasicBlock *BB, const MachineBasicBlock *Succ,
Kyle Buttb15c0662017-01-31 23:48:32 +0000477 BranchProbability AdjustedSumProb,
Kyle Butte9425c4f2017-02-04 02:26:32 +0000478 const BlockChain &Chain, const BlockFilterSet *BlockFilter);
Eugene Zelenko5df3d892017-08-24 21:21:39 +0000479
Kyle Butt7fbec9b2017-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 Zelenko5df3d892017-08-24 21:21:39 +0000484
Kyle Butt7fbec9b2017-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 Zelenko5df3d892017-08-24 21:21:39 +0000491
Kyle Butt7fbec9b2017-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 Kramerd71461c2017-04-12 13:26:28 +0000495 MutableArrayRef<SmallVector<WeightedEdge, 8>> Edges);
Eugene Zelenko5df3d892017-08-24 21:21:39 +0000496
Kyle Buttb15c0662017-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 Butte9425c4f2017-02-04 02:26:32 +0000500 const MachineBasicBlock *BB, MachineBasicBlock *Succ,
501 const BlockChain &Chain, const BlockFilterSet *BlockFilter);
Eugene Zelenko5df3d892017-08-24 21:21:39 +0000502
Kyle Butt1fa60302017-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 Carruth10281422011-10-21 06:46:38 +0000506
507public:
508 static char ID; // Pass identification, replacement for typeid
Eugene Zelenko5df3d892017-08-24 21:21:39 +0000509
Chandler Carruth10281422011-10-21 06:46:38 +0000510 MachineBlockPlacement() : MachineFunctionPass(ID) {
511 initializeMachineBlockPlacementPass(*PassRegistry::getPassRegistry());
512 }
513
Craig Topper4584cd52014-03-07 09:26:03 +0000514 bool runOnMachineFunction(MachineFunction &F) override;
Chandler Carruth10281422011-10-21 06:46:38 +0000515
Tim Shen1a8c6772018-03-30 17:51:00 +0000516 bool allowTailDupPlacement() const {
517 assert(F);
518 return TailDupPlacement && !F->getTarget().requiresStructuredCFG();
519 }
520
Craig Topper4584cd52014-03-07 09:26:03 +0000521 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruth10281422011-10-21 06:46:38 +0000522 AU.addRequired<MachineBranchProbabilityInfo>();
523 AU.addRequired<MachineBlockFrequencyInfo>();
Kyle Buttb15c0662017-01-31 23:48:32 +0000524 if (TailDupPlacement)
525 AU.addRequired<MachinePostDominatorTree>();
Chandler Carruth8b9737c2011-10-21 08:57:37 +0000526 AU.addRequired<MachineLoopInfo>();
Haicheng Wu5b458cc2016-06-09 15:24:29 +0000527 AU.addRequired<TargetPassConfig>();
Chandler Carruth10281422011-10-21 06:46:38 +0000528 MachineFunctionPass::getAnalysisUsage(AU);
529 }
Chandler Carruth10281422011-10-21 06:46:38 +0000530};
Eugene Zelenko5df3d892017-08-24 21:21:39 +0000531
532} // end anonymous namespace
Chandler Carruth10281422011-10-21 06:46:38 +0000533
534char MachineBlockPlacement::ID = 0;
Eugene Zelenko5df3d892017-08-24 21:21:39 +0000535
Andrew Trick1fa5bcb2012-02-08 21:23:13 +0000536char &llvm::MachineBlockPlacementID = MachineBlockPlacement::ID;
Eugene Zelenko5df3d892017-08-24 21:21:39 +0000537
Matthias Braun1527baa2017-05-25 21:26:32 +0000538INITIALIZE_PASS_BEGIN(MachineBlockPlacement, DEBUG_TYPE,
Chandler Carruth10281422011-10-21 06:46:38 +0000539 "Branch Probability Basic Block Placement", false, false)
540INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
541INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
Kyle Buttb15c0662017-01-31 23:48:32 +0000542INITIALIZE_PASS_DEPENDENCY(MachinePostDominatorTree)
Chandler Carruth8b9737c2011-10-21 08:57:37 +0000543INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
Matthias Braun1527baa2017-05-25 21:26:32 +0000544INITIALIZE_PASS_END(MachineBlockPlacement, DEBUG_TYPE,
Chandler Carruth10281422011-10-21 06:46:38 +0000545 "Branch Probability Basic Block Placement", false, false)
546
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000547#ifndef NDEBUG
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000548/// Helper to print the name of a MBB.
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000549///
550/// Only used by debug logging.
Kyle Butte9425c4f2017-02-04 02:26:32 +0000551static std::string getBlockName(const MachineBasicBlock *BB) {
Alp Tokere69170a2014-06-26 22:52:05 +0000552 std::string Result;
553 raw_string_ostream OS(Result);
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +0000554 OS << printMBBReference(*BB);
Philip Reamesb9688f42016-03-02 21:45:13 +0000555 OS << " ('" << BB->getName() << "')";
Alp Tokere69170a2014-06-26 22:52:05 +0000556 OS.flush();
557 return Result;
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000558}
559#endif
560
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000561/// Mark a chain's successors as having one fewer preds.
Chandler Carrutheb4ec3a2011-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 Butt0846e562016-10-11 20:36:43 +0000566/// chain which reach the zero-predecessor state to the appropriate worklist.
Chandler Carruth8d150782011-11-13 11:20:44 +0000567void MachineBlockPlacement::markChainSuccessors(
Kyle Butte9425c4f2017-02-04 02:26:32 +0000568 const BlockChain &Chain, const MachineBasicBlock *LoopHeaderBB,
Jakub Staszak90616162011-12-21 23:02:08 +0000569 const BlockFilterSet *BlockFilter) {
Chandler Carruth8d150782011-11-13 11:20:44 +0000570 // Walk all the blocks in this chain, marking their successors as having
571 // a predecessor placed.
Chandler Carruth7a715da2015-03-05 03:19:05 +0000572 for (MachineBasicBlock *MBB : Chain) {
Kyle Butt0846e562016-10-11 20:36:43 +0000573 markBlockSuccessors(Chain, MBB, LoopHeaderBB, BlockFilter);
574 }
575}
Chandler Carruth10281422011-10-21 06:46:38 +0000576
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000577/// Mark a single block's successors as having one fewer preds.
Kyle Butt0846e562016-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 Butte9425c4f2017-02-04 02:26:32 +0000584 const BlockChain &Chain, const MachineBasicBlock *MBB,
585 const MachineBasicBlock *LoopHeaderBB, const BlockFilterSet *BlockFilter) {
Kyle Butt0846e562016-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 Sechetc53ad4f2016-04-07 21:29:39 +0000597
Kyle Butt0846e562016-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 Carruth10281422011-10-21 06:46:38 +0000609 }
Chandler Carruth8d150782011-11-13 11:20:44 +0000610}
Chandler Carruthbd1be4d2011-10-23 09:18:45 +0000611
Xinliang David Li594ffa32016-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 Butte9425c4f2017-02-04 02:26:32 +0000617 const MachineBasicBlock *BB, const BlockChain &Chain,
618 const BlockFilterSet *BlockFilter,
Xinliang David Li594ffa32016-06-11 18:35:40 +0000619 SmallVector<MachineBasicBlock *, 4> &Successors) {
Cong Houd97c1002015-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 Hou41cf1a52015-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 Inoue3c358f82017-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 Li594ffa32016-06-11 18:35:40 +0000635 // will get A C D B as the layout of this loop.
Cong Houd97c1002015-12-01 05:29:22 +0000636 auto AdjustedSumProb = BranchProbability::getOne();
Cong Hou41cf1a52015-11-18 00:52:52 +0000637 for (MachineBasicBlock *Succ : BB->successors()) {
638 bool SkipSucc = false;
Amaury Sechetc53ad4f2016-04-07 21:29:39 +0000639 if (Succ->isEHPad() || (BlockFilter && !BlockFilter->count(Succ))) {
Cong Hou41cf1a52015-11-18 00:52:52 +0000640 SkipSucc = true;
641 } else {
642 BlockChain *SuccChain = BlockToChain[Succ];
643 if (SuccChain == &Chain) {
Cong Hou41cf1a52015-11-18 00:52:52 +0000644 SkipSucc = true;
645 } else if (Succ != *SuccChain->begin()) {
646 DEBUG(dbgs() << " " << getBlockName(Succ) << " -> Mid chain!\n");
647 continue;
648 }
649 }
650 if (SkipSucc)
Cong Houd97c1002015-12-01 05:29:22 +0000651 AdjustedSumProb -= MBPI->getEdgeProbability(BB, Succ);
Cong Hou41cf1a52015-11-18 00:52:52 +0000652 else
653 Successors.push_back(Succ);
654 }
655
Xinliang David Li594ffa32016-06-11 18:35:40 +0000656 return AdjustedSumProb;
657}
658
659/// The helper function returns the branch probability that is adjusted
660/// or normalized over the new total \p AdjustedSumProb.
Xinliang David Li594ffa32016-06-11 18:35:40 +0000661static BranchProbability
662getAdjustedProbability(BranchProbability OrigProb,
663 BranchProbability AdjustedSumProb) {
664 BranchProbability SuccProb;
665 uint32_t SuccProbN = OrigProb.getNumerator();
666 uint32_t SuccProbD = AdjustedSumProb.getNumerator();
667 if (SuccProbN >= SuccProbD)
668 SuccProb = BranchProbability::getOne();
669 else
670 SuccProb = BranchProbability(SuccProbN, SuccProbD);
671
672 return SuccProb;
673}
674
Kyle Butt7fbec9b2017-02-15 19:49:14 +0000675/// Check if \p BB has exactly the successors in \p Successors.
676static bool
677hasSameSuccessors(MachineBasicBlock &BB,
678 SmallPtrSetImpl<const MachineBasicBlock *> &Successors) {
679 if (BB.succ_size() != Successors.size())
680 return false;
681 // We don't want to count self-loops
682 if (Successors.count(&BB))
683 return false;
684 for (MachineBasicBlock *Succ : BB.successors())
685 if (!Successors.count(Succ))
686 return false;
687 return true;
688}
689
690/// Check if a block should be tail duplicated to increase fallthrough
691/// opportunities.
Kyle Buttb15c0662017-01-31 23:48:32 +0000692/// \p BB Block to check.
693bool MachineBlockPlacement::shouldTailDuplicate(MachineBasicBlock *BB) {
694 // Blocks with single successors don't create additional fallthrough
695 // opportunities. Don't duplicate them. TODO: When conditional exits are
696 // analyzable, allow them to be duplicated.
697 bool IsSimple = TailDup.isSimpleBB(BB);
698
699 if (BB->succ_size() == 1)
700 return false;
701 return TailDup.shouldTailDuplicate(IsSimple, *BB);
702}
703
704/// Compare 2 BlockFrequency's with a small penalty for \p A.
705/// In order to be conservative, we apply a X% penalty to account for
706/// increased icache pressure and static heuristics. For small frequencies
707/// we use only the numerators to improve accuracy. For simplicity, we assume the
708/// penalty is less than 100%
709/// TODO(iteratee): Use 64-bit fixed point edge frequencies everywhere.
710static bool greaterWithBias(BlockFrequency A, BlockFrequency B,
711 uint64_t EntryFreq) {
712 BranchProbability ThresholdProb(TailDupPlacementPenalty, 100);
713 BlockFrequency Gain = A - B;
714 return (Gain / ThresholdProb).getFrequency() >= EntryFreq;
715}
716
717/// Check the edge frequencies to see if tail duplication will increase
718/// fallthroughs. It only makes sense to call this function when
719/// \p Succ would not be chosen otherwise. Tail duplication of \p Succ is
720/// always locally profitable if we would have picked \p Succ without
721/// considering duplication.
722bool MachineBlockPlacement::isProfitableToTailDup(
Kyle Butte9425c4f2017-02-04 02:26:32 +0000723 const MachineBasicBlock *BB, const MachineBasicBlock *Succ,
Kyle Buttb15c0662017-01-31 23:48:32 +0000724 BranchProbability QProb,
Kyle Butte9425c4f2017-02-04 02:26:32 +0000725 const BlockChain &Chain, const BlockFilterSet *BlockFilter) {
Kyle Buttb15c0662017-01-31 23:48:32 +0000726 // We need to do a probability calculation to make sure this is profitable.
727 // First: does succ have a successor that post-dominates? This affects the
728 // calculation. The 2 relevant cases are:
729 // BB BB
730 // | \Qout | \Qout
731 // P| C |P C
732 // = C' = C'
733 // | /Qin | /Qin
734 // | / | /
735 // Succ Succ
736 // / \ | \ V
737 // U/ =V |U \
738 // / \ = D
739 // D E | /
740 // | /
741 // |/
742 // PDom
743 // '=' : Branch taken for that CFG edge
744 // In the second case, Placing Succ while duplicating it into C prevents the
745 // fallthrough of Succ into either D or PDom, because they now have C as an
746 // unplaced predecessor
747
748 // Start by figuring out which case we fall into
749 MachineBasicBlock *PDom = nullptr;
750 SmallVector<MachineBasicBlock *, 4> SuccSuccs;
751 // Only scan the relevant successors
752 auto AdjustedSuccSumProb =
753 collectViableSuccessors(Succ, Chain, BlockFilter, SuccSuccs);
754 BranchProbability PProb = MBPI->getEdgeProbability(BB, Succ);
755 auto BBFreq = MBFI->getBlockFreq(BB);
756 auto SuccFreq = MBFI->getBlockFreq(Succ);
757 BlockFrequency P = BBFreq * PProb;
758 BlockFrequency Qout = BBFreq * QProb;
759 uint64_t EntryFreq = MBFI->getEntryFreq();
760 // If there are no more successors, it is profitable to copy, as it strictly
761 // increases fallthrough.
762 if (SuccSuccs.size() == 0)
763 return greaterWithBias(P, Qout, EntryFreq);
764
765 auto BestSuccSucc = BranchProbability::getZero();
766 // Find the PDom or the best Succ if no PDom exists.
767 for (MachineBasicBlock *SuccSucc : SuccSuccs) {
768 auto Prob = MBPI->getEdgeProbability(Succ, SuccSucc);
769 if (Prob > BestSuccSucc)
770 BestSuccSucc = Prob;
771 if (PDom == nullptr)
772 if (MPDT->dominates(SuccSucc, Succ)) {
773 PDom = SuccSucc;
774 break;
775 }
776 }
777 // For the comparisons, we need to know Succ's best incoming edge that isn't
778 // from BB.
779 auto SuccBestPred = BlockFrequency(0);
780 for (MachineBasicBlock *SuccPred : Succ->predecessors()) {
781 if (SuccPred == Succ || SuccPred == BB
782 || BlockToChain[SuccPred] == &Chain
783 || (BlockFilter && !BlockFilter->count(SuccPred)))
784 continue;
785 auto Freq = MBFI->getBlockFreq(SuccPred)
786 * MBPI->getEdgeProbability(SuccPred, Succ);
787 if (Freq > SuccBestPred)
788 SuccBestPred = Freq;
789 }
790 // Qin is Succ's best unplaced incoming edge that isn't BB
791 BlockFrequency Qin = SuccBestPred;
792 // If it doesn't have a post-dominating successor, here is the calculation:
793 // BB BB
794 // | \Qout | \
795 // P| C | =
796 // = C' | C
797 // | /Qin | |
798 // | / | C' (+Succ)
799 // Succ Succ /|
800 // / \ | \/ |
Kyle Butt7fbec9b2017-02-15 19:49:14 +0000801 // U/ =V | == |
Kyle Buttb15c0662017-01-31 23:48:32 +0000802 // / \ | / \|
803 // D E D E
804 // '=' : Branch taken for that CFG edge
805 // Cost in the first case is: P + V
806 // For this calculation, we always assume P > Qout. If Qout > P
807 // The result of this function will be ignored at the caller.
Kyle Buttee51a202017-04-10 22:28:18 +0000808 // Let F = SuccFreq - Qin
809 // Cost in the second case is: Qout + min(Qin, F) * U + max(Qin, F) * V
Kyle Buttb15c0662017-01-31 23:48:32 +0000810
811 if (PDom == nullptr || !Succ->isSuccessor(PDom)) {
812 BranchProbability UProb = BestSuccSucc;
813 BranchProbability VProb = AdjustedSuccSumProb - UProb;
Kyle Buttee51a202017-04-10 22:28:18 +0000814 BlockFrequency F = SuccFreq - Qin;
Kyle Buttb15c0662017-01-31 23:48:32 +0000815 BlockFrequency V = SuccFreq * VProb;
Kyle Buttee51a202017-04-10 22:28:18 +0000816 BlockFrequency QinU = std::min(Qin, F) * UProb;
Kyle Buttb15c0662017-01-31 23:48:32 +0000817 BlockFrequency BaseCost = P + V;
Kyle Buttee51a202017-04-10 22:28:18 +0000818 BlockFrequency DupCost = Qout + QinU + std::max(Qin, F) * VProb;
Kyle Buttb15c0662017-01-31 23:48:32 +0000819 return greaterWithBias(BaseCost, DupCost, EntryFreq);
820 }
821 BranchProbability UProb = MBPI->getEdgeProbability(Succ, PDom);
822 BranchProbability VProb = AdjustedSuccSumProb - UProb;
823 BlockFrequency U = SuccFreq * UProb;
824 BlockFrequency V = SuccFreq * VProb;
Kyle Buttee51a202017-04-10 22:28:18 +0000825 BlockFrequency F = SuccFreq - Qin;
Kyle Buttb15c0662017-01-31 23:48:32 +0000826 // If there is a post-dominating successor, here is the calculation:
827 // BB BB BB BB
Kyle Buttee51a202017-04-10 22:28:18 +0000828 // | \Qout | \ | \Qout | \
829 // |P C | = |P C | =
830 // = C' |P C = C' |P C
831 // | /Qin | | | /Qin | |
832 // | / | C' (+Succ) | / | C' (+Succ)
833 // Succ Succ /| Succ Succ /|
834 // | \ V | \/ | | \ V | \/ |
835 // |U \ |U /\ =? |U = |U /\ |
836 // = D = = =?| | D | = =|
837 // | / |/ D | / |/ D
838 // | / | / | = | /
839 // |/ | / |/ | =
840 // Dom Dom Dom Dom
Kyle Buttb15c0662017-01-31 23:48:32 +0000841 // '=' : Branch taken for that CFG edge
842 // The cost for taken branches in the first case is P + U
Kyle Buttee51a202017-04-10 22:28:18 +0000843 // Let F = SuccFreq - Qin
Kyle Buttb15c0662017-01-31 23:48:32 +0000844 // The cost in the second case (assuming independence), given the layout:
Kyle Buttee51a202017-04-10 22:28:18 +0000845 // BB, Succ, (C+Succ), D, Dom or the layout:
846 // BB, Succ, D, Dom, (C+Succ)
847 // is Qout + max(F, Qin) * U + min(F, Qin)
Kyle Butt7fbec9b2017-02-15 19:49:14 +0000848 // compare P + U vs Qout + P * U + Qin.
Kyle Buttb15c0662017-01-31 23:48:32 +0000849 //
850 // The 3rd and 4th cases cover when Dom would be chosen to follow Succ.
851 //
852 // For the 3rd case, the cost is P + 2 * V
Kyle Buttee51a202017-04-10 22:28:18 +0000853 // For the 4th case, the cost is Qout + min(Qin, F) * U + max(Qin, F) * V + V
854 // We choose 4 over 3 when (P + V) > Qout + min(Qin, F) * U + max(Qin, F) * V
Kyle Butt7fbec9b2017-02-15 19:49:14 +0000855 if (UProb > AdjustedSuccSumProb / 2 &&
856 !hasBetterLayoutPredecessor(Succ, PDom, *BlockToChain[PDom], UProb, UProb,
857 Chain, BlockFilter))
Kyle Buttb15c0662017-01-31 23:48:32 +0000858 // Cases 3 & 4
Kyle Buttee51a202017-04-10 22:28:18 +0000859 return greaterWithBias(
860 (P + V), (Qout + std::max(Qin, F) * VProb + std::min(Qin, F) * UProb),
861 EntryFreq);
Kyle Buttb15c0662017-01-31 23:48:32 +0000862 // Cases 1 & 2
Kyle Buttee51a202017-04-10 22:28:18 +0000863 return greaterWithBias((P + U),
864 (Qout + std::min(Qin, F) * AdjustedSuccSumProb +
865 std::max(Qin, F) * UProb),
866 EntryFreq);
Kyle Buttb15c0662017-01-31 23:48:32 +0000867}
868
Kyle Butt7fbec9b2017-02-15 19:49:14 +0000869/// Check for a trellis layout. \p BB is the upper part of a trellis if its
870/// successors form the lower part of a trellis. A successor set S forms the
871/// lower part of a trellis if all of the predecessors of S are either in S or
872/// have all of S as successors. We ignore trellises where BB doesn't have 2
873/// successors because for fewer than 2, it's trivial, and for 3 or greater they
874/// are very uncommon and complex to compute optimally. Allowing edges within S
875/// is not strictly a trellis, but the same algorithm works, so we allow it.
876bool MachineBlockPlacement::isTrellis(
877 const MachineBasicBlock *BB,
878 const SmallVectorImpl<MachineBasicBlock *> &ViableSuccs,
879 const BlockChain &Chain, const BlockFilterSet *BlockFilter) {
880 // Technically BB could form a trellis with branching factor higher than 2.
881 // But that's extremely uncommon.
882 if (BB->succ_size() != 2 || ViableSuccs.size() != 2)
883 return false;
884
885 SmallPtrSet<const MachineBasicBlock *, 2> Successors(BB->succ_begin(),
886 BB->succ_end());
887 // To avoid reviewing the same predecessors twice.
888 SmallPtrSet<const MachineBasicBlock *, 8> SeenPreds;
889
890 for (MachineBasicBlock *Succ : ViableSuccs) {
891 int PredCount = 0;
892 for (auto SuccPred : Succ->predecessors()) {
893 // Allow triangle successors, but don't count them.
Dehao Chenb197d5b2017-03-23 23:28:09 +0000894 if (Successors.count(SuccPred)) {
895 // Make sure that it is actually a triangle.
896 for (MachineBasicBlock *CheckSucc : SuccPred->successors())
897 if (!Successors.count(CheckSucc))
898 return false;
Kyle Butt7fbec9b2017-02-15 19:49:14 +0000899 continue;
Dehao Chenb197d5b2017-03-23 23:28:09 +0000900 }
Kyle Butt7fbec9b2017-02-15 19:49:14 +0000901 const BlockChain *PredChain = BlockToChain[SuccPred];
902 if (SuccPred == BB || (BlockFilter && !BlockFilter->count(SuccPred)) ||
903 PredChain == &Chain || PredChain == BlockToChain[Succ])
904 continue;
905 ++PredCount;
906 // Perform the successor check only once.
907 if (!SeenPreds.insert(SuccPred).second)
908 continue;
909 if (!hasSameSuccessors(*SuccPred, Successors))
910 return false;
911 }
912 // If one of the successors has only BB as a predecessor, it is not a
913 // trellis.
914 if (PredCount < 1)
915 return false;
916 }
917 return true;
918}
919
920/// Pick the highest total weight pair of edges that can both be laid out.
921/// The edges in \p Edges[0] are assumed to have a different destination than
922/// the edges in \p Edges[1]. Simple counting shows that the best pair is either
923/// the individual highest weight edges to the 2 different destinations, or in
924/// case of a conflict, one of them should be replaced with a 2nd best edge.
925std::pair<MachineBlockPlacement::WeightedEdge,
926 MachineBlockPlacement::WeightedEdge>
927MachineBlockPlacement::getBestNonConflictingEdges(
928 const MachineBasicBlock *BB,
Benjamin Kramerd71461c2017-04-12 13:26:28 +0000929 MutableArrayRef<SmallVector<MachineBlockPlacement::WeightedEdge, 8>>
930 Edges) {
Kyle Butt7fbec9b2017-02-15 19:49:14 +0000931 // Sort the edges, and then for each successor, find the best incoming
932 // predecessor. If the best incoming predecessors aren't the same,
933 // then that is clearly the best layout. If there is a conflict, one of the
934 // successors will have to fallthrough from the second best predecessor. We
935 // compare which combination is better overall.
936
937 // Sort for highest frequency.
938 auto Cmp = [](WeightedEdge A, WeightedEdge B) { return A.Weight > B.Weight; };
939
940 std::stable_sort(Edges[0].begin(), Edges[0].end(), Cmp);
941 std::stable_sort(Edges[1].begin(), Edges[1].end(), Cmp);
942 auto BestA = Edges[0].begin();
943 auto BestB = Edges[1].begin();
944 // Arrange for the correct answer to be in BestA and BestB
945 // If the 2 best edges don't conflict, the answer is already there.
946 if (BestA->Src == BestB->Src) {
947 // Compare the total fallthrough of (Best + Second Best) for both pairs
948 auto SecondBestA = std::next(BestA);
949 auto SecondBestB = std::next(BestB);
950 BlockFrequency BestAScore = BestA->Weight + SecondBestB->Weight;
951 BlockFrequency BestBScore = BestB->Weight + SecondBestA->Weight;
952 if (BestAScore < BestBScore)
953 BestA = SecondBestA;
954 else
955 BestB = SecondBestB;
956 }
957 // Arrange for the BB edge to be in BestA if it exists.
958 if (BestB->Src == BB)
959 std::swap(BestA, BestB);
960 return std::make_pair(*BestA, *BestB);
961}
962
963/// Get the best successor from \p BB based on \p BB being part of a trellis.
964/// We only handle trellises with 2 successors, so the algorithm is
965/// straightforward: Find the best pair of edges that don't conflict. We find
966/// the best incoming edge for each successor in the trellis. If those conflict,
967/// we consider which of them should be replaced with the second best.
968/// Upon return the two best edges will be in \p BestEdges. If one of the edges
969/// comes from \p BB, it will be in \p BestEdges[0]
970MachineBlockPlacement::BlockAndTailDupResult
971MachineBlockPlacement::getBestTrellisSuccessor(
972 const MachineBasicBlock *BB,
973 const SmallVectorImpl<MachineBasicBlock *> &ViableSuccs,
974 BranchProbability AdjustedSumProb, const BlockChain &Chain,
975 const BlockFilterSet *BlockFilter) {
976
977 BlockAndTailDupResult Result = {nullptr, false};
978 SmallPtrSet<const MachineBasicBlock *, 4> Successors(BB->succ_begin(),
979 BB->succ_end());
980
981 // We assume size 2 because it's common. For general n, we would have to do
982 // the Hungarian algorithm, but it's not worth the complexity because more
983 // than 2 successors is fairly uncommon, and a trellis even more so.
984 if (Successors.size() != 2 || ViableSuccs.size() != 2)
985 return Result;
986
987 // Collect the edge frequencies of all edges that form the trellis.
Benjamin Kramerd71461c2017-04-12 13:26:28 +0000988 SmallVector<WeightedEdge, 8> Edges[2];
Kyle Butt7fbec9b2017-02-15 19:49:14 +0000989 int SuccIndex = 0;
990 for (auto Succ : ViableSuccs) {
991 for (MachineBasicBlock *SuccPred : Succ->predecessors()) {
992 // Skip any placed predecessors that are not BB
993 if (SuccPred != BB)
994 if ((BlockFilter && !BlockFilter->count(SuccPred)) ||
995 BlockToChain[SuccPred] == &Chain ||
996 BlockToChain[SuccPred] == BlockToChain[Succ])
997 continue;
998 BlockFrequency EdgeFreq = MBFI->getBlockFreq(SuccPred) *
999 MBPI->getEdgeProbability(SuccPred, Succ);
1000 Edges[SuccIndex].push_back({EdgeFreq, SuccPred, Succ});
1001 }
1002 ++SuccIndex;
1003 }
1004
1005 // Pick the best combination of 2 edges from all the edges in the trellis.
1006 WeightedEdge BestA, BestB;
1007 std::tie(BestA, BestB) = getBestNonConflictingEdges(BB, Edges);
1008
1009 if (BestA.Src != BB) {
1010 // If we have a trellis, and BB doesn't have the best fallthrough edges,
1011 // we shouldn't choose any successor. We've already looked and there's a
1012 // better fallthrough edge for all the successors.
1013 DEBUG(dbgs() << "Trellis, but not one of the chosen edges.\n");
1014 return Result;
1015 }
1016
1017 // Did we pick the triangle edge? If tail-duplication is profitable, do
1018 // that instead. Otherwise merge the triangle edge now while we know it is
1019 // optimal.
1020 if (BestA.Dest == BestB.Src) {
1021 // The edges are BB->Succ1->Succ2, and we're looking to see if BB->Succ2
1022 // would be better.
1023 MachineBasicBlock *Succ1 = BestA.Dest;
1024 MachineBasicBlock *Succ2 = BestB.Dest;
1025 // Check to see if tail-duplication would be profitable.
Tim Shen1a8c6772018-03-30 17:51:00 +00001026 if (allowTailDupPlacement() && shouldTailDuplicate(Succ2) &&
Kyle Butt7fbec9b2017-02-15 19:49:14 +00001027 canTailDuplicateUnplacedPreds(BB, Succ2, Chain, BlockFilter) &&
1028 isProfitableToTailDup(BB, Succ2, MBPI->getEdgeProbability(BB, Succ1),
1029 Chain, BlockFilter)) {
1030 DEBUG(BranchProbability Succ2Prob = getAdjustedProbability(
1031 MBPI->getEdgeProbability(BB, Succ2), AdjustedSumProb);
1032 dbgs() << " Selected: " << getBlockName(Succ2)
1033 << ", probability: " << Succ2Prob << " (Tail Duplicate)\n");
1034 Result.BB = Succ2;
1035 Result.ShouldTailDup = true;
1036 return Result;
1037 }
1038 }
1039 // We have already computed the optimal edge for the other side of the
1040 // trellis.
Kyle Buttebe6cc42017-02-23 21:22:24 +00001041 ComputedEdges[BestB.Src] = { BestB.Dest, false };
Kyle Butt7fbec9b2017-02-15 19:49:14 +00001042
1043 auto TrellisSucc = BestA.Dest;
1044 DEBUG(BranchProbability SuccProb = getAdjustedProbability(
1045 MBPI->getEdgeProbability(BB, TrellisSucc), AdjustedSumProb);
1046 dbgs() << " Selected: " << getBlockName(TrellisSucc)
1047 << ", probability: " << SuccProb << " (Trellis)\n");
1048 Result.BB = TrellisSucc;
1049 return Result;
1050}
Kyle Buttb15c0662017-01-31 23:48:32 +00001051
Tim Shen1a8c6772018-03-30 17:51:00 +00001052/// When the option allowTailDupPlacement() is on, this method checks if the
Kyle Buttb15c0662017-01-31 23:48:32 +00001053/// fallthrough candidate block \p Succ (of block \p BB) can be tail-duplicated
1054/// into all of its unplaced, unfiltered predecessors, that are not BB.
1055bool MachineBlockPlacement::canTailDuplicateUnplacedPreds(
Kyle Butte9425c4f2017-02-04 02:26:32 +00001056 const MachineBasicBlock *BB, MachineBasicBlock *Succ,
1057 const BlockChain &Chain, const BlockFilterSet *BlockFilter) {
Kyle Buttb15c0662017-01-31 23:48:32 +00001058 if (!shouldTailDuplicate(Succ))
1059 return false;
1060
Kyle Butt7fbec9b2017-02-15 19:49:14 +00001061 // For CFG checking.
1062 SmallPtrSet<const MachineBasicBlock *, 4> Successors(BB->succ_begin(),
1063 BB->succ_end());
Kyle Buttb15c0662017-01-31 23:48:32 +00001064 for (MachineBasicBlock *Pred : Succ->predecessors()) {
1065 // Make sure all unplaced and unfiltered predecessors can be
1066 // tail-duplicated into.
Kyle Butte9425c4f2017-02-04 02:26:32 +00001067 // Skip any blocks that are already placed or not in this loop.
Kyle Buttb15c0662017-01-31 23:48:32 +00001068 if (Pred == BB || (BlockFilter && !BlockFilter->count(Pred))
1069 || BlockToChain[Pred] == &Chain)
1070 continue;
Kyle Butt7fbec9b2017-02-15 19:49:14 +00001071 if (!TailDup.canTailDuplicate(Succ, Pred)) {
1072 if (Successors.size() > 1 && hasSameSuccessors(*Pred, Successors))
1073 // This will result in a trellis after tail duplication, so we don't
1074 // need to copy Succ into this predecessor. In the presence
1075 // of a trellis tail duplication can continue to be profitable.
1076 // For example:
1077 // A A
1078 // |\ |\
1079 // | \ | \
1080 // | C | C+BB
1081 // | / | |
1082 // |/ | |
1083 // BB => BB |
1084 // |\ |\/|
1085 // | \ |/\|
1086 // | D | D
1087 // | / | /
1088 // |/ |/
1089 // Succ Succ
1090 //
1091 // After BB was duplicated into C, the layout looks like the one on the
1092 // right. BB and C now have the same successors. When considering
1093 // whether Succ can be duplicated into all its unplaced predecessors, we
1094 // ignore C.
1095 // We can do this because C already has a profitable fallthrough, namely
1096 // D. TODO(iteratee): ignore sufficiently cold predecessors for
1097 // duplication and for this test.
1098 //
1099 // This allows trellises to be laid out in 2 separate chains
1100 // (A,B,Succ,...) and later (C,D,...) This is a reasonable heuristic
1101 // because it allows the creation of 2 fallthrough paths with links
1102 // between them, and we correctly identify the best layout for these
1103 // CFGs. We want to extend trellises that the user created in addition
1104 // to trellises created by tail-duplication, so we just look for the
1105 // CFG.
1106 continue;
Kyle Buttb15c0662017-01-31 23:48:32 +00001107 return false;
Kyle Butt7fbec9b2017-02-15 19:49:14 +00001108 }
Kyle Buttb15c0662017-01-31 23:48:32 +00001109 }
1110 return true;
1111}
1112
Kyle Butt1fa60302017-03-03 01:00:22 +00001113/// Find chains of triangles where we believe it would be profitable to
1114/// tail-duplicate them all, but a local analysis would not find them.
1115/// There are 3 ways this can be profitable:
1116/// 1) The post-dominators marked 50% are actually taken 55% (This shrinks with
1117/// longer chains)
1118/// 2) The chains are statically correlated. Branch probabilities have a very
1119/// U-shaped distribution.
1120/// [http://nrs.harvard.edu/urn-3:HUL.InstRepos:24015805]
1121/// If the branches in a chain are likely to be from the same side of the
1122/// distribution as their predecessor, but are independent at runtime, this
1123/// transformation is profitable. (Because the cost of being wrong is a small
1124/// fixed cost, unlike the standard triangle layout where the cost of being
1125/// wrong scales with the # of triangles.)
1126/// 3) The chains are dynamically correlated. If the probability that a previous
1127/// branch was taken positively influences whether the next branch will be
1128/// taken
1129/// We believe that 2 and 3 are common enough to justify the small margin in 1.
1130void MachineBlockPlacement::precomputeTriangleChains() {
1131 struct TriangleChain {
Benjamin Kramerd71461c2017-04-12 13:26:28 +00001132 std::vector<MachineBasicBlock *> Edges;
Eugene Zelenko5df3d892017-08-24 21:21:39 +00001133
Benjamin Kramerd71461c2017-04-12 13:26:28 +00001134 TriangleChain(MachineBasicBlock *src, MachineBasicBlock *dst)
1135 : Edges({src, dst}) {}
Kyle Butt1fa60302017-03-03 01:00:22 +00001136
1137 void append(MachineBasicBlock *dst) {
Benjamin Kramerd71461c2017-04-12 13:26:28 +00001138 assert(getKey()->isSuccessor(dst) &&
Kyle Butt1fa60302017-03-03 01:00:22 +00001139 "Attempting to append a block that is not a successor.");
Benjamin Kramerd71461c2017-04-12 13:26:28 +00001140 Edges.push_back(dst);
Kyle Butt1fa60302017-03-03 01:00:22 +00001141 }
1142
Benjamin Kramerd71461c2017-04-12 13:26:28 +00001143 unsigned count() const { return Edges.size() - 1; }
1144
1145 MachineBasicBlock *getKey() const {
1146 return Edges.back();
Kyle Butt1fa60302017-03-03 01:00:22 +00001147 }
1148 };
1149
1150 if (TriangleChainCount == 0)
1151 return;
1152
1153 DEBUG(dbgs() << "Pre-computing triangle chains.\n");
1154 // Map from last block to the chain that contains it. This allows us to extend
1155 // chains as we find new triangles.
1156 DenseMap<const MachineBasicBlock *, TriangleChain> TriangleChainMap;
1157 for (MachineBasicBlock &BB : *F) {
1158 // If BB doesn't have 2 successors, it doesn't start a triangle.
1159 if (BB.succ_size() != 2)
1160 continue;
1161 MachineBasicBlock *PDom = nullptr;
1162 for (MachineBasicBlock *Succ : BB.successors()) {
1163 if (!MPDT->dominates(Succ, &BB))
1164 continue;
1165 PDom = Succ;
1166 break;
1167 }
1168 // If BB doesn't have a post-dominating successor, it doesn't form a
1169 // triangle.
1170 if (PDom == nullptr)
1171 continue;
1172 // If PDom has a hint that it is low probability, skip this triangle.
1173 if (MBPI->getEdgeProbability(&BB, PDom) < BranchProbability(50, 100))
1174 continue;
1175 // If PDom isn't eligible for duplication, this isn't the kind of triangle
1176 // we're looking for.
1177 if (!shouldTailDuplicate(PDom))
1178 continue;
1179 bool CanTailDuplicate = true;
1180 // If PDom can't tail-duplicate into it's non-BB predecessors, then this
1181 // isn't the kind of triangle we're looking for.
1182 for (MachineBasicBlock* Pred : PDom->predecessors()) {
1183 if (Pred == &BB)
1184 continue;
1185 if (!TailDup.canTailDuplicate(PDom, Pred)) {
1186 CanTailDuplicate = false;
1187 break;
1188 }
1189 }
1190 // If we can't tail-duplicate PDom to its predecessors, then skip this
1191 // triangle.
1192 if (!CanTailDuplicate)
1193 continue;
1194
1195 // Now we have an interesting triangle. Insert it if it's not part of an
Hiroshi Inoue3c358f82017-06-16 12:23:04 +00001196 // existing chain.
Kyle Butt1fa60302017-03-03 01:00:22 +00001197 // Note: This cannot be replaced with a call insert() or emplace() because
1198 // the find key is BB, but the insert/emplace key is PDom.
1199 auto Found = TriangleChainMap.find(&BB);
1200 // If it is, remove the chain from the map, grow it, and put it back in the
1201 // map with the end as the new key.
1202 if (Found != TriangleChainMap.end()) {
1203 TriangleChain Chain = std::move(Found->second);
1204 TriangleChainMap.erase(Found);
1205 Chain.append(PDom);
1206 TriangleChainMap.insert(std::make_pair(Chain.getKey(), std::move(Chain)));
1207 } else {
1208 auto InsertResult = TriangleChainMap.try_emplace(PDom, &BB, PDom);
Benjamin Kramer33580692017-04-12 13:26:31 +00001209 assert(InsertResult.second && "Block seen twice.");
1210 (void)InsertResult;
Kyle Butt1fa60302017-03-03 01:00:22 +00001211 }
1212 }
1213
Kyle Butt336c78f2017-04-12 18:30:32 +00001214 // Iterating over a DenseMap is safe here, because the only thing in the body
1215 // of the loop is inserting into another DenseMap (ComputedEdges).
1216 // ComputedEdges is never iterated, so this doesn't lead to non-determinism.
Kyle Butt1fa60302017-03-03 01:00:22 +00001217 for (auto &ChainPair : TriangleChainMap) {
1218 TriangleChain &Chain = ChainPair.second;
1219 // Benchmarking has shown that due to branch correlation duplicating 2 or
1220 // more triangles is profitable, despite the calculations assuming
1221 // independence.
Benjamin Kramerd71461c2017-04-12 13:26:28 +00001222 if (Chain.count() < TriangleChainCount)
Kyle Butt1fa60302017-03-03 01:00:22 +00001223 continue;
Benjamin Kramerd71461c2017-04-12 13:26:28 +00001224 MachineBasicBlock *dst = Chain.Edges.back();
1225 Chain.Edges.pop_back();
1226 for (MachineBasicBlock *src : reverse(Chain.Edges)) {
Kyle Butt1fa60302017-03-03 01:00:22 +00001227 DEBUG(dbgs() << "Marking edge: " << getBlockName(src) << "->" <<
1228 getBlockName(dst) << " as pre-computed based on triangles.\n");
Benjamin Kramer33580692017-04-12 13:26:31 +00001229
1230 auto InsertResult = ComputedEdges.insert({src, {dst, true}});
1231 assert(InsertResult.second && "Block seen twice.");
1232 (void)InsertResult;
1233
Kyle Butt1fa60302017-03-03 01:00:22 +00001234 dst = src;
1235 }
1236 }
1237}
1238
Dehao Chen9f2bdfb2016-06-14 22:27:17 +00001239// When profile is not present, return the StaticLikelyProb.
1240// When profile is available, we need to handle the triangle-shape CFG.
1241static BranchProbability getLayoutSuccessorProbThreshold(
Kyle Butte9425c4f2017-02-04 02:26:32 +00001242 const MachineBasicBlock *BB) {
Easwaran Ramana17f2202017-12-22 01:33:52 +00001243 if (!BB->getParent()->getFunction().hasProfileData())
Dehao Chen9f2bdfb2016-06-14 22:27:17 +00001244 return BranchProbability(StaticLikelyProb, 100);
1245 if (BB->succ_size() == 2) {
1246 const MachineBasicBlock *Succ1 = *BB->succ_begin();
1247 const MachineBasicBlock *Succ2 = *(BB->succ_begin() + 1);
Xinliang David Lie34ed832016-06-15 03:03:30 +00001248 if (Succ1->isSuccessor(Succ2) || Succ2->isSuccessor(Succ1)) {
1249 /* See case 1 below for the cost analysis. For BB->Succ to
1250 * be taken with smaller cost, the following needs to hold:
Kyle Buttb15c0662017-01-31 23:48:32 +00001251 * Prob(BB->Succ) > 2 * Prob(BB->Pred)
1252 * So the threshold T in the calculation below
1253 * (1-T) * Prob(BB->Succ) > T * Prob(BB->Pred)
1254 * So T / (1 - T) = 2, Yielding T = 2/3
1255 * Also adding user specified branch bias, we have
Xinliang David Lie34ed832016-06-15 03:03:30 +00001256 * T = (2/3)*(ProfileLikelyProb/50)
1257 * = (2*ProfileLikelyProb)/150)
1258 */
1259 return BranchProbability(2 * ProfileLikelyProb, 150);
1260 }
Dehao Chen9f2bdfb2016-06-14 22:27:17 +00001261 }
1262 return BranchProbability(ProfileLikelyProb, 100);
Xinliang David Licbf12142016-06-13 20:24:19 +00001263}
1264
1265/// Checks to see if the layout candidate block \p Succ has a better layout
1266/// predecessor than \c BB. If yes, returns true.
Kyle Buttb15c0662017-01-31 23:48:32 +00001267/// \p SuccProb: The probability adjusted for only remaining blocks.
1268/// Only used for logging
1269/// \p RealSuccProb: The un-adjusted probability.
1270/// \p Chain: The chain that BB belongs to and Succ is being considered for.
1271/// \p BlockFilter: if non-null, the set of blocks that make up the loop being
1272/// considered
Xinliang David Licbf12142016-06-13 20:24:19 +00001273bool MachineBlockPlacement::hasBetterLayoutPredecessor(
Kyle Butte9425c4f2017-02-04 02:26:32 +00001274 const MachineBasicBlock *BB, const MachineBasicBlock *Succ,
1275 const BlockChain &SuccChain, BranchProbability SuccProb,
1276 BranchProbability RealSuccProb, const BlockChain &Chain,
1277 const BlockFilterSet *BlockFilter) {
Xinliang David Licbf12142016-06-13 20:24:19 +00001278
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00001279 // There isn't a better layout when there are no unscheduled predecessors.
Xinliang David Licbf12142016-06-13 20:24:19 +00001280 if (SuccChain.UnscheduledPredecessors == 0)
1281 return false;
1282
1283 // There are two basic scenarios here:
1284 // -------------------------------------
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00001285 // Case 1: triangular shape CFG (if-then):
Xinliang David Licbf12142016-06-13 20:24:19 +00001286 // BB
1287 // | \
1288 // | \
1289 // | Pred
1290 // | /
1291 // Succ
1292 // In this case, we are evaluating whether to select edge -> Succ, e.g.
1293 // set Succ as the layout successor of BB. Picking Succ as BB's
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00001294 // successor breaks the CFG constraints (FIXME: define these constraints).
1295 // With this layout, Pred BB
Xinliang David Licbf12142016-06-13 20:24:19 +00001296 // is forced to be outlined, so the overall cost will be cost of the
1297 // branch taken from BB to Pred, plus the cost of back taken branch
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00001298 // from Pred to Succ, as well as the additional cost associated
Xinliang David Licbf12142016-06-13 20:24:19 +00001299 // with the needed unconditional jump instruction from Pred To Succ.
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00001300
Xinliang David Licbf12142016-06-13 20:24:19 +00001301 // The cost of the topological order layout is the taken branch cost
1302 // from BB to Succ, so to make BB->Succ a viable candidate, the following
1303 // must hold:
1304 // 2 * freq(BB->Pred) * taken_branch_cost + unconditional_jump_cost
1305 // < freq(BB->Succ) * taken_branch_cost.
1306 // Ignoring unconditional jump cost, we get
1307 // freq(BB->Succ) > 2 * freq(BB->Pred), i.e.,
1308 // prob(BB->Succ) > 2 * prob(BB->Pred)
1309 //
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00001310 // When real profile data is available, we can precisely compute the
1311 // probability threshold that is needed for edge BB->Succ to be considered.
1312 // Without profile data, the heuristic requires the branch bias to be
Xinliang David Licbf12142016-06-13 20:24:19 +00001313 // a lot larger to make sure the signal is very strong (e.g. 80% default).
1314 // -----------------------------------------------------------------
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00001315 // Case 2: diamond like CFG (if-then-else):
Xinliang David Licbf12142016-06-13 20:24:19 +00001316 // S
1317 // / \
1318 // | \
1319 // BB Pred
1320 // \ /
1321 // Succ
1322 // ..
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00001323 //
1324 // The current block is BB and edge BB->Succ is now being evaluated.
1325 // Note that edge S->BB was previously already selected because
1326 // prob(S->BB) > prob(S->Pred).
1327 // At this point, 2 blocks can be placed after BB: Pred or Succ. If we
1328 // choose Pred, we will have a topological ordering as shown on the left
1329 // in the picture below. If we choose Succ, we have the solution as shown
1330 // on the right:
1331 //
1332 // topo-order:
1333 //
1334 // S----- ---S
1335 // | | | |
1336 // ---BB | | BB
1337 // | | | |
Hiroshi Inoue3c358f82017-06-16 12:23:04 +00001338 // | Pred-- | Succ--
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00001339 // | | | |
Hiroshi Inoue3c358f82017-06-16 12:23:04 +00001340 // ---Succ ---Pred--
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00001341 //
1342 // cost = freq(S->Pred) + freq(BB->Succ) cost = 2 * freq (S->Pred)
1343 // = freq(S->Pred) + freq(S->BB)
1344 //
1345 // If we have profile data (i.e, branch probabilities can be trusted), the
1346 // cost (number of taken branches) with layout S->BB->Succ->Pred is 2 *
1347 // freq(S->Pred) while the cost of topo order is freq(S->Pred) + freq(S->BB).
1348 // We know Prob(S->BB) > Prob(S->Pred), so freq(S->BB) > freq(S->Pred), which
1349 // means the cost of topological order is greater.
Xinliang David Licbf12142016-06-13 20:24:19 +00001350 // When profile data is not available, however, we need to be more
1351 // conservative. If the branch prediction is wrong, breaking the topo-order
1352 // will actually yield a layout with large cost. For this reason, we need
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00001353 // strong biased branch at block S with Prob(S->BB) in order to select
1354 // BB->Succ. This is equivalent to looking the CFG backward with backward
Xinliang David Licbf12142016-06-13 20:24:19 +00001355 // edge: Prob(Succ->BB) needs to >= HotProb in order to be selected (without
1356 // profile data).
Kyle Butt02d8d052016-07-29 18:09:28 +00001357 // --------------------------------------------------------------------------
1358 // Case 3: forked diamond
1359 // S
1360 // / \
1361 // / \
1362 // BB Pred
1363 // | \ / |
1364 // | \ / |
1365 // | X |
1366 // | / \ |
1367 // | / \ |
1368 // S1 S2
1369 //
1370 // The current block is BB and edge BB->S1 is now being evaluated.
1371 // As above S->BB was already selected because
1372 // prob(S->BB) > prob(S->Pred). Assume that prob(BB->S1) >= prob(BB->S2).
1373 //
1374 // topo-order:
1375 //
1376 // S-------| ---S
1377 // | | | |
1378 // ---BB | | BB
1379 // | | | |
1380 // | Pred----| | S1----
1381 // | | | |
1382 // --(S1 or S2) ---Pred--
Kyle Butt7fbec9b2017-02-15 19:49:14 +00001383 // |
1384 // S2
Kyle Butt02d8d052016-07-29 18:09:28 +00001385 //
1386 // topo-cost = freq(S->Pred) + freq(BB->S1) + freq(BB->S2)
1387 // + min(freq(Pred->S1), freq(Pred->S2))
1388 // Non-topo-order cost:
Kyle Butt02d8d052016-07-29 18:09:28 +00001389 // non-topo-cost = 2 * freq(S->Pred) + freq(BB->S2).
1390 // To be conservative, we can assume that min(freq(Pred->S1), freq(Pred->S2))
1391 // is 0. Then the non topo layout is better when
1392 // freq(S->Pred) < freq(BB->S1).
1393 // This is exactly what is checked below.
1394 // Note there are other shapes that apply (Pred may not be a single block,
1395 // but they all fit this general pattern.)
Dehao Chen9f2bdfb2016-06-14 22:27:17 +00001396 BranchProbability HotProb = getLayoutSuccessorProbThreshold(BB);
Xinliang David Licbf12142016-06-13 20:24:19 +00001397
Xinliang David Licbf12142016-06-13 20:24:19 +00001398 // Make sure that a hot successor doesn't have a globally more
1399 // important predecessor.
1400 BlockFrequency CandidateEdgeFreq = MBFI->getBlockFreq(BB) * RealSuccProb;
1401 bool BadCFGConflict = false;
1402
1403 for (MachineBasicBlock *Pred : Succ->predecessors()) {
1404 if (Pred == Succ || BlockToChain[Pred] == &SuccChain ||
1405 (BlockFilter && !BlockFilter->count(Pred)) ||
Kyle Buttb15c0662017-01-31 23:48:32 +00001406 BlockToChain[Pred] == &Chain ||
1407 // This check is redundant except for look ahead. This function is
1408 // called for lookahead by isProfitableToTailDup when BB hasn't been
1409 // placed yet.
1410 (Pred == BB))
Xinliang David Licbf12142016-06-13 20:24:19 +00001411 continue;
Kyle Butt02d8d052016-07-29 18:09:28 +00001412 // Do backward checking.
1413 // For all cases above, we need a backward checking to filter out edges that
Kyle Buttb15c0662017-01-31 23:48:32 +00001414 // are not 'strongly' biased.
Xinliang David Licbf12142016-06-13 20:24:19 +00001415 // BB Pred
1416 // \ /
1417 // Succ
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00001418 // We select edge BB->Succ if
Xinliang David Licbf12142016-06-13 20:24:19 +00001419 // freq(BB->Succ) > freq(Succ) * HotProb
1420 // i.e. freq(BB->Succ) > freq(BB->Succ) * HotProb + freq(Pred->Succ) *
1421 // HotProb
1422 // i.e. freq((BB->Succ) * (1 - HotProb) > freq(Pred->Succ) * HotProb
Kyle Butt02d8d052016-07-29 18:09:28 +00001423 // Case 1 is covered too, because the first equation reduces to:
1424 // prob(BB->Succ) > HotProb. (freq(Succ) = freq(BB) for a triangle)
Xinliang David Licbf12142016-06-13 20:24:19 +00001425 BlockFrequency PredEdgeFreq =
1426 MBFI->getBlockFreq(Pred) * MBPI->getEdgeProbability(Pred, Succ);
1427 if (PredEdgeFreq * HotProb >= CandidateEdgeFreq * HotProb.getCompl()) {
1428 BadCFGConflict = true;
1429 break;
1430 }
1431 }
1432
1433 if (BadCFGConflict) {
Sjoerd Meijer5e11a182016-07-27 08:49:23 +00001434 DEBUG(dbgs() << " Not a candidate: " << getBlockName(Succ) << " -> " << SuccProb
Xinliang David Licbf12142016-06-13 20:24:19 +00001435 << " (prob) (non-cold CFG conflict)\n");
1436 return true;
1437 }
1438
1439 return false;
1440}
1441
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001442/// Select the best successor for a block.
Xinliang David Li594ffa32016-06-11 18:35:40 +00001443///
1444/// This looks across all successors of a particular block and attempts to
1445/// select the "best" one to be the layout successor. It only considers direct
1446/// successors which also pass the block filter. It will attempt to avoid
1447/// breaking CFG structure, but cave and break such structures in the case of
1448/// very hot successor edges.
1449///
Kyle Buttb15c0662017-01-31 23:48:32 +00001450/// \returns The best successor block found, or null if none are viable, along
1451/// with a boolean indicating if tail duplication is necessary.
1452MachineBlockPlacement::BlockAndTailDupResult
Kyle Butte9425c4f2017-02-04 02:26:32 +00001453MachineBlockPlacement::selectBestSuccessor(
1454 const MachineBasicBlock *BB, const BlockChain &Chain,
1455 const BlockFilterSet *BlockFilter) {
Xinliang David Li594ffa32016-06-11 18:35:40 +00001456 const BranchProbability HotProb(StaticLikelyProb, 100);
1457
Kyle Buttb15c0662017-01-31 23:48:32 +00001458 BlockAndTailDupResult BestSucc = { nullptr, false };
Xinliang David Li594ffa32016-06-11 18:35:40 +00001459 auto BestProb = BranchProbability::getZero();
1460
1461 SmallVector<MachineBasicBlock *, 4> Successors;
1462 auto AdjustedSumProb =
1463 collectViableSuccessors(BB, Chain, BlockFilter, Successors);
1464
Sjoerd Meijer5e11a182016-07-27 08:49:23 +00001465 DEBUG(dbgs() << "Selecting best successor for: " << getBlockName(BB) << "\n");
Kyle Buttb15c0662017-01-31 23:48:32 +00001466
Kyle Buttebe6cc42017-02-23 21:22:24 +00001467 // if we already precomputed the best successor for BB, return that if still
1468 // applicable.
1469 auto FoundEdge = ComputedEdges.find(BB);
1470 if (FoundEdge != ComputedEdges.end()) {
1471 MachineBasicBlock *Succ = FoundEdge->second.BB;
1472 ComputedEdges.erase(FoundEdge);
Kyle Butt7fbec9b2017-02-15 19:49:14 +00001473 BlockChain *SuccChain = BlockToChain[Succ];
1474 if (BB->isSuccessor(Succ) && (!BlockFilter || BlockFilter->count(Succ)) &&
Kyle Buttebe6cc42017-02-23 21:22:24 +00001475 SuccChain != &Chain && Succ == *SuccChain->begin())
1476 return FoundEdge->second;
Kyle Butt7fbec9b2017-02-15 19:49:14 +00001477 }
1478
1479 // if BB is part of a trellis, Use the trellis to determine the optimal
1480 // fallthrough edges
1481 if (isTrellis(BB, Successors, Chain, BlockFilter))
1482 return getBestTrellisSuccessor(BB, Successors, AdjustedSumProb, Chain,
1483 BlockFilter);
1484
Kyle Buttb15c0662017-01-31 23:48:32 +00001485 // For blocks with CFG violations, we may be able to lay them out anyway with
1486 // tail-duplication. We keep this vector so we can perform the probability
1487 // calculations the minimum number of times.
1488 SmallVector<std::tuple<BranchProbability, MachineBasicBlock *>, 4>
1489 DupCandidates;
Cong Hou41cf1a52015-11-18 00:52:52 +00001490 for (MachineBasicBlock *Succ : Successors) {
Xinliang David Li594ffa32016-06-11 18:35:40 +00001491 auto RealSuccProb = MBPI->getEdgeProbability(BB, Succ);
1492 BranchProbability SuccProb =
1493 getAdjustedProbability(RealSuccProb, AdjustedSumProb);
Chandler Carruthb3361722011-11-13 11:34:53 +00001494
Cong Hou41cf1a52015-11-18 00:52:52 +00001495 BlockChain &SuccChain = *BlockToChain[Succ];
Xinliang David Licbf12142016-06-13 20:24:19 +00001496 // Skip the edge \c BB->Succ if block \c Succ has a better layout
1497 // predecessor that yields lower global cost.
1498 if (hasBetterLayoutPredecessor(BB, Succ, SuccChain, SuccProb, RealSuccProb,
Kyle Buttb15c0662017-01-31 23:48:32 +00001499 Chain, BlockFilter)) {
1500 // If tail duplication would make Succ profitable, place it.
Tim Shen1a8c6772018-03-30 17:51:00 +00001501 if (allowTailDupPlacement() && shouldTailDuplicate(Succ))
Kyle Buttb15c0662017-01-31 23:48:32 +00001502 DupCandidates.push_back(std::make_tuple(SuccProb, Succ));
Xinliang David Licbf12142016-06-13 20:24:19 +00001503 continue;
Kyle Buttb15c0662017-01-31 23:48:32 +00001504 }
Chandler Carruth18dfac32011-11-20 11:22:06 +00001505
Xinliang David Licbf12142016-06-13 20:24:19 +00001506 DEBUG(
Sjoerd Meijer5e11a182016-07-27 08:49:23 +00001507 dbgs() << " Candidate: " << getBlockName(Succ) << ", probability: "
1508 << SuccProb
Xinliang David Licbf12142016-06-13 20:24:19 +00001509 << (SuccChain.UnscheduledPredecessors != 0 ? " (CFG break)" : "")
1510 << "\n");
Sjoerd Meijer5e11a182016-07-27 08:49:23 +00001511
Kyle Buttb15c0662017-01-31 23:48:32 +00001512 if (BestSucc.BB && BestProb >= SuccProb) {
Sjoerd Meijer5e11a182016-07-27 08:49:23 +00001513 DEBUG(dbgs() << " Not the best candidate, continuing\n");
Chandler Carruthb3361722011-11-13 11:34:53 +00001514 continue;
Sjoerd Meijer5e11a182016-07-27 08:49:23 +00001515 }
1516
1517 DEBUG(dbgs() << " Setting it as best candidate\n");
Kyle Buttb15c0662017-01-31 23:48:32 +00001518 BestSucc.BB = Succ;
Cong Houd97c1002015-12-01 05:29:22 +00001519 BestProb = SuccProb;
Chandler Carruthb3361722011-11-13 11:34:53 +00001520 }
Kyle Buttb15c0662017-01-31 23:48:32 +00001521 // Handle the tail duplication candidates in order of decreasing probability.
1522 // Stop at the first one that is profitable. Also stop if they are less
1523 // profitable than BestSucc. Position is important because we preserve it and
1524 // prefer first best match. Here we aren't comparing in order, so we capture
1525 // the position instead.
1526 if (DupCandidates.size() != 0) {
1527 auto cmp =
1528 [](const std::tuple<BranchProbability, MachineBasicBlock *> &a,
1529 const std::tuple<BranchProbability, MachineBasicBlock *> &b) {
1530 return std::get<0>(a) > std::get<0>(b);
1531 };
1532 std::stable_sort(DupCandidates.begin(), DupCandidates.end(), cmp);
1533 }
1534 for(auto &Tup : DupCandidates) {
1535 BranchProbability DupProb;
1536 MachineBasicBlock *Succ;
1537 std::tie(DupProb, Succ) = Tup;
1538 if (DupProb < BestProb)
1539 break;
1540 if (canTailDuplicateUnplacedPreds(BB, Succ, Chain, BlockFilter)
Kyle Butt7e8be282017-04-10 22:28:22 +00001541 && (isProfitableToTailDup(BB, Succ, BestProb, Chain, BlockFilter))) {
Kyle Buttb15c0662017-01-31 23:48:32 +00001542 DEBUG(
1543 dbgs() << " Candidate: " << getBlockName(Succ) << ", probability: "
1544 << DupProb
1545 << " (Tail Duplicate)\n");
1546 BestSucc.BB = Succ;
1547 BestSucc.ShouldTailDup = true;
1548 break;
1549 }
1550 }
1551
1552 if (BestSucc.BB)
1553 DEBUG(dbgs() << " Selected: " << getBlockName(BestSucc.BB) << "\n");
Sjoerd Meijer5e11a182016-07-27 08:49:23 +00001554
Chandler Carruthb3361722011-11-13 11:34:53 +00001555 return BestSucc;
1556}
1557
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001558/// Select the best block from a worklist.
Chandler Carruthf9213fe2011-11-13 11:42:26 +00001559///
1560/// This looks through the provided worklist as a list of candidate basic
1561/// blocks and select the most profitable one to place. The definition of
1562/// profitable only really makes sense in the context of a loop. This returns
1563/// the most frequently visited block in the worklist, which in the case of
1564/// a loop, is the one most desirable to be physically close to the rest of the
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00001565/// loop body in order to improve i-cache behavior.
Chandler Carruthf9213fe2011-11-13 11:42:26 +00001566///
1567/// \returns The best block found, or null if none are viable.
1568MachineBasicBlock *MachineBlockPlacement::selectBestCandidateBlock(
Kyle Butte9425c4f2017-02-04 02:26:32 +00001569 const BlockChain &Chain, SmallVectorImpl<MachineBasicBlock *> &WorkList) {
Chandler Carruth0af6a0b2011-11-14 09:46:33 +00001570 // Once we need to walk the worklist looking for a candidate, cleanup the
1571 // worklist of already placed entries.
1572 // FIXME: If this shows up on profiles, it could be folded (at the cost of
1573 // some code complexity) into the loop below.
Eugene Zelenko5df3d892017-08-24 21:21:39 +00001574 WorkList.erase(llvm::remove_if(WorkList,
1575 [&](MachineBasicBlock *BB) {
1576 return BlockToChain.lookup(BB) == &Chain;
1577 }),
Chandler Carruth0af6a0b2011-11-14 09:46:33 +00001578 WorkList.end());
1579
Amaury Sechetc53ad4f2016-04-07 21:29:39 +00001580 if (WorkList.empty())
1581 return nullptr;
1582
1583 bool IsEHPad = WorkList[0]->isEHPad();
1584
Craig Topperc0196b12014-04-14 00:51:57 +00001585 MachineBasicBlock *BestBlock = nullptr;
Chandler Carruthf9213fe2011-11-13 11:42:26 +00001586 BlockFrequency BestFreq;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001587 for (MachineBasicBlock *MBB : WorkList) {
Kyle Butt0cf5b2f2017-05-17 23:44:41 +00001588 assert(MBB->isEHPad() == IsEHPad &&
1589 "EHPad mismatch between block and work list.");
Amaury Sechetc53ad4f2016-04-07 21:29:39 +00001590
Chandler Carruth7a715da2015-03-05 03:19:05 +00001591 BlockChain &SuccChain = *BlockToChain[MBB];
Philip Reames02e11322016-03-02 22:40:51 +00001592 if (&SuccChain == &Chain)
Chandler Carruthf9213fe2011-11-13 11:42:26 +00001593 continue;
Junmo Park4ba6cf62016-03-11 05:07:07 +00001594
Kyle Butt0cf5b2f2017-05-17 23:44:41 +00001595 assert(SuccChain.UnscheduledPredecessors == 0 &&
1596 "Found CFG-violating block");
Chandler Carruthf9213fe2011-11-13 11:42:26 +00001597
Chandler Carruth7a715da2015-03-05 03:19:05 +00001598 BlockFrequency CandidateFreq = MBFI->getBlockFreq(MBB);
1599 DEBUG(dbgs() << " " << getBlockName(MBB) << " -> ";
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001600 MBFI->printBlockFreq(dbgs(), CandidateFreq) << " (freq)\n");
Amaury Sechetc53ad4f2016-04-07 21:29:39 +00001601
1602 // For ehpad, we layout the least probable first as to avoid jumping back
1603 // from least probable landingpads to more probable ones.
1604 //
1605 // FIXME: Using probability is probably (!) not the best way to achieve
1606 // this. We should probably have a more principled approach to layout
1607 // cleanup code.
1608 //
1609 // The goal is to get:
1610 //
1611 // +--------------------------+
1612 // | V
1613 // InnerLp -> InnerCleanup OuterLp -> OuterCleanup -> Resume
1614 //
1615 // Rather than:
1616 //
1617 // +-------------------------------------+
1618 // V |
1619 // OuterLp -> OuterCleanup -> Resume InnerLp -> InnerCleanup
1620 if (BestBlock && (IsEHPad ^ (BestFreq >= CandidateFreq)))
Chandler Carruthf9213fe2011-11-13 11:42:26 +00001621 continue;
Amaury Sechetc53ad4f2016-04-07 21:29:39 +00001622
Chandler Carruth7a715da2015-03-05 03:19:05 +00001623 BestBlock = MBB;
Chandler Carruthf9213fe2011-11-13 11:42:26 +00001624 BestFreq = CandidateFreq;
1625 }
Amaury Sechetc53ad4f2016-04-07 21:29:39 +00001626
Chandler Carruthf9213fe2011-11-13 11:42:26 +00001627 return BestBlock;
1628}
1629
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001630/// Retrieve the first unplaced basic block.
Chandler Carruth1071cfa2011-11-14 00:00:35 +00001631///
1632/// This routine is called when we are unable to use the CFG to walk through
1633/// all of the basic blocks and form a chain due to unnatural loops in the CFG.
Chandler Carruth9b548a7f2011-11-15 06:26:43 +00001634/// We walk through the function's blocks in order, starting from the
1635/// LastUnplacedBlockIt. We update this iterator on each call to avoid
1636/// re-scanning the entire sequence on repeated calls to this routine.
Chandler Carruth1071cfa2011-11-14 00:00:35 +00001637MachineBasicBlock *MachineBlockPlacement::getFirstUnplacedBlock(
Xinliang David Li52530a72016-06-13 22:23:44 +00001638 const BlockChain &PlacedChain,
Chandler Carruth9b548a7f2011-11-15 06:26:43 +00001639 MachineFunction::iterator &PrevUnplacedBlockIt,
Jakub Staszak90616162011-12-21 23:02:08 +00001640 const BlockFilterSet *BlockFilter) {
Xinliang David Li52530a72016-06-13 22:23:44 +00001641 for (MachineFunction::iterator I = PrevUnplacedBlockIt, E = F->end(); I != E;
Chandler Carruth9b548a7f2011-11-15 06:26:43 +00001642 ++I) {
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +00001643 if (BlockFilter && !BlockFilter->count(&*I))
Chandler Carruth9b548a7f2011-11-15 06:26:43 +00001644 continue;
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +00001645 if (BlockToChain[&*I] != &PlacedChain) {
Chandler Carruth9b548a7f2011-11-15 06:26:43 +00001646 PrevUnplacedBlockIt = I;
Chandler Carruth4a87aa02011-11-23 03:03:21 +00001647 // Now select the head of the chain to which the unplaced block belongs
1648 // as the block to place. This will force the entire chain to be placed,
1649 // and satisfies the requirements of merging chains.
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +00001650 return *BlockToChain[&*I]->begin();
Chandler Carruth1071cfa2011-11-14 00:00:35 +00001651 }
1652 }
Craig Topperc0196b12014-04-14 00:51:57 +00001653 return nullptr;
Chandler Carruth1071cfa2011-11-14 00:00:35 +00001654}
1655
Amaury Secheteae09c22016-03-14 21:24:11 +00001656void MachineBlockPlacement::fillWorkLists(
Kyle Butte9425c4f2017-02-04 02:26:32 +00001657 const MachineBasicBlock *MBB,
Amaury Secheteae09c22016-03-14 21:24:11 +00001658 SmallPtrSetImpl<BlockChain *> &UpdatedPreds,
Amaury Secheteae09c22016-03-14 21:24:11 +00001659 const BlockFilterSet *BlockFilter = nullptr) {
1660 BlockChain &Chain = *BlockToChain[MBB];
1661 if (!UpdatedPreds.insert(&Chain).second)
1662 return;
1663
Kyle Butt0cf5b2f2017-05-17 23:44:41 +00001664 assert(
1665 Chain.UnscheduledPredecessors == 0 &&
1666 "Attempting to place block with unscheduled predecessors in worklist.");
Amaury Secheteae09c22016-03-14 21:24:11 +00001667 for (MachineBasicBlock *ChainBB : Chain) {
Kyle Butt0cf5b2f2017-05-17 23:44:41 +00001668 assert(BlockToChain[ChainBB] == &Chain &&
1669 "Block in chain doesn't match BlockToChain map.");
Amaury Secheteae09c22016-03-14 21:24:11 +00001670 for (MachineBasicBlock *Pred : ChainBB->predecessors()) {
1671 if (BlockFilter && !BlockFilter->count(Pred))
1672 continue;
1673 if (BlockToChain[Pred] == &Chain)
1674 continue;
1675 ++Chain.UnscheduledPredecessors;
1676 }
1677 }
1678
Amaury Sechetc53ad4f2016-04-07 21:29:39 +00001679 if (Chain.UnscheduledPredecessors != 0)
1680 return;
1681
Kyle Butte9425c4f2017-02-04 02:26:32 +00001682 MachineBasicBlock *BB = *Chain.begin();
1683 if (BB->isEHPad())
1684 EHPadWorkList.push_back(BB);
Amaury Sechetc53ad4f2016-04-07 21:29:39 +00001685 else
Kyle Butte9425c4f2017-02-04 02:26:32 +00001686 BlockWorkList.push_back(BB);
Amaury Secheteae09c22016-03-14 21:24:11 +00001687}
1688
Chandler Carruth8d150782011-11-13 11:20:44 +00001689void MachineBlockPlacement::buildChain(
Kyle Butte9425c4f2017-02-04 02:26:32 +00001690 const MachineBasicBlock *HeadBB, BlockChain &Chain,
Kyle Butt0846e562016-10-11 20:36:43 +00001691 BlockFilterSet *BlockFilter) {
Kyle Butte9425c4f2017-02-04 02:26:32 +00001692 assert(HeadBB && "BB must not be null.\n");
1693 assert(BlockToChain[HeadBB] == &Chain && "BlockToChainMap mis-match.\n");
Xinliang David Li52530a72016-06-13 22:23:44 +00001694 MachineFunction::iterator PrevUnplacedBlockIt = F->begin();
Chandler Carruth1071cfa2011-11-14 00:00:35 +00001695
Kyle Butte9425c4f2017-02-04 02:26:32 +00001696 const MachineBasicBlock *LoopHeaderBB = HeadBB;
Xinliang David Li93926ac2016-07-01 05:46:48 +00001697 markChainSuccessors(Chain, LoopHeaderBB, BlockFilter);
Kyle Butte9425c4f2017-02-04 02:26:32 +00001698 MachineBasicBlock *BB = *std::prev(Chain.end());
Eugene Zelenko5df3d892017-08-24 21:21:39 +00001699 while (true) {
Kyle Butt82c22902016-06-28 22:50:54 +00001700 assert(BB && "null block found at end of chain in loop.");
1701 assert(BlockToChain[BB] == &Chain && "BlockToChainMap mis-match in loop.");
1702 assert(*std::prev(Chain.end()) == BB && "BB Not found at end of chain.");
1703
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00001704
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +00001705 // Look for the best viable successor if there is one to place immediately
1706 // after this block.
Kyle Buttb15c0662017-01-31 23:48:32 +00001707 auto Result = selectBestSuccessor(BB, Chain, BlockFilter);
1708 MachineBasicBlock* BestSucc = Result.BB;
1709 bool ShouldTailDup = Result.ShouldTailDup;
Tim Shen1a8c6772018-03-30 17:51:00 +00001710 if (allowTailDupPlacement())
Kyle Buttb15c0662017-01-31 23:48:32 +00001711 ShouldTailDup |= (BestSucc && shouldTailDuplicate(BestSucc));
Chandler Carruth8d150782011-11-13 11:20:44 +00001712
1713 // If an immediate successor isn't available, look for the best viable
1714 // block among those we've identified as not violating the loop's CFG at
1715 // this point. This won't be a fallthrough, but it will increase locality.
Chandler Carruthf9213fe2011-11-13 11:42:26 +00001716 if (!BestSucc)
Amaury Sechet9ee4ddd2016-04-07 06:34:47 +00001717 BestSucc = selectBestCandidateBlock(Chain, BlockWorkList);
Amaury Sechetc53ad4f2016-04-07 21:29:39 +00001718 if (!BestSucc)
1719 BestSucc = selectBestCandidateBlock(Chain, EHPadWorkList);
Chandler Carruth8d150782011-11-13 11:20:44 +00001720
Chandler Carruth8d150782011-11-13 11:20:44 +00001721 if (!BestSucc) {
Xinliang David Li52530a72016-06-13 22:23:44 +00001722 BestSucc = getFirstUnplacedBlock(Chain, PrevUnplacedBlockIt, BlockFilter);
Chandler Carruth1071cfa2011-11-14 00:00:35 +00001723 if (!BestSucc)
1724 break;
1725
1726 DEBUG(dbgs() << "Unnatural loop CFG detected, forcibly merging the "
1727 "layout successor until the CFG reduces\n");
Chandler Carruth8d150782011-11-13 11:20:44 +00001728 }
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00001729
Kyle Butt0846e562016-10-11 20:36:43 +00001730 // Placement may have changed tail duplication opportunities.
1731 // Check for that now.
Tim Shen1a8c6772018-03-30 17:51:00 +00001732 if (allowTailDupPlacement() && BestSucc && ShouldTailDup) {
Kyle Butt0846e562016-10-11 20:36:43 +00001733 // If the chosen successor was duplicated into all its predecessors,
1734 // don't bother laying it out, just go round the loop again with BB as
1735 // the chain end.
1736 if (repeatedlyTailDuplicateBlock(BestSucc, BB, LoopHeaderBB, Chain,
1737 BlockFilter, PrevUnplacedBlockIt))
1738 continue;
1739 }
1740
Chandler Carruth8d150782011-11-13 11:20:44 +00001741 // Place this block, updating the datastructures to reflect its placement.
Jakub Staszak90616162011-12-21 23:02:08 +00001742 BlockChain &SuccChain = *BlockToChain[BestSucc];
Philip Reamesae27b232016-03-03 00:58:43 +00001743 // Zero out UnscheduledPredecessors for the successor we're about to merge in case
Chandler Carruth1071cfa2011-11-14 00:00:35 +00001744 // we selected a successor that didn't fit naturally into the CFG.
Philip Reamesae27b232016-03-03 00:58:43 +00001745 SuccChain.UnscheduledPredecessors = 0;
Philip Reamesb9688f42016-03-02 21:45:13 +00001746 DEBUG(dbgs() << "Merging from " << getBlockName(BB) << " to "
1747 << getBlockName(BestSucc) << "\n");
Xinliang David Li93926ac2016-07-01 05:46:48 +00001748 markChainSuccessors(SuccChain, LoopHeaderBB, BlockFilter);
Chandler Carruth8d150782011-11-13 11:20:44 +00001749 Chain.merge(BestSucc, &SuccChain);
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001750 BB = *std::prev(Chain.end());
Jakub Staszak190c7122011-12-07 19:46:10 +00001751 }
Chandler Carruth1071cfa2011-11-14 00:00:35 +00001752
1753 DEBUG(dbgs() << "Finished forming chain for header block "
Philip Reamesb9688f42016-03-02 21:45:13 +00001754 << getBlockName(*Chain.begin()) << "\n");
Chandler Carruth10281422011-10-21 06:46:38 +00001755}
1756
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001757/// Find the best loop top block for layout.
Chandler Carruth9ffb97e2011-11-27 00:38:03 +00001758///
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001759/// Look for a block which is strictly better than the loop header for laying
1760/// out at the top of the loop. This looks for one and only one pattern:
1761/// a latch block with no conditional exit. This block will cause a conditional
1762/// jump around it or will be the bottom of the loop if we lay it out in place,
1763/// but if it it doesn't end up at the bottom of the loop for any reason,
1764/// rotation alone won't fix it. Because such a block will always result in an
1765/// unconditional jump (for the backedge) rotating it in front of the loop
1766/// header is always profitable.
1767MachineBasicBlock *
Kyle Butte9425c4f2017-02-04 02:26:32 +00001768MachineBlockPlacement::findBestLoopTop(const MachineLoop &L,
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001769 const BlockFilterSet &LoopBlockSet) {
Sjoerd Meijer15c81b02016-08-16 19:50:33 +00001770 // Placing the latch block before the header may introduce an extra branch
1771 // that skips this block the first time the loop is executed, which we want
1772 // to avoid when optimising for size.
1773 // FIXME: in theory there is a case that does not introduce a new branch,
1774 // i.e. when the layout predecessor does not fallthrough to the loop header.
1775 // In practice this never happens though: there always seems to be a preheader
1776 // that can fallthrough and that is also placed before the header.
Matthias Braunf1caa282017-12-15 22:22:58 +00001777 if (F->getFunction().optForSize())
Sjoerd Meijer15c81b02016-08-16 19:50:33 +00001778 return L.getHeader();
1779
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001780 // Check that the header hasn't been fused with a preheader block due to
1781 // crazy branches. If it has, we need to start with the header at the top to
1782 // prevent pulling the preheader into the loop body.
1783 BlockChain &HeaderChain = *BlockToChain[L.getHeader()];
1784 if (!LoopBlockSet.count(*HeaderChain.begin()))
1785 return L.getHeader();
1786
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001787 DEBUG(dbgs() << "Finding best loop top for: " << getBlockName(L.getHeader())
1788 << "\n");
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001789
1790 BlockFrequency BestPredFreq;
Craig Topperc0196b12014-04-14 00:51:57 +00001791 MachineBasicBlock *BestPred = nullptr;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001792 for (MachineBasicBlock *Pred : L.getHeader()->predecessors()) {
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001793 if (!LoopBlockSet.count(Pred))
1794 continue;
Sjoerd Meijer5e11a182016-07-27 08:49:23 +00001795 DEBUG(dbgs() << " header pred: " << getBlockName(Pred) << ", has "
Michael Gottesmanb78dec82013-12-14 00:25:45 +00001796 << Pred->succ_size() << " successors, ";
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001797 MBFI->printBlockFreq(dbgs(), Pred) << " freq\n");
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001798 if (Pred->succ_size() > 1)
1799 continue;
1800
1801 BlockFrequency PredFreq = MBFI->getBlockFreq(Pred);
1802 if (!BestPred || PredFreq > BestPredFreq ||
1803 (!(PredFreq < BestPredFreq) &&
1804 Pred->isLayoutSuccessor(L.getHeader()))) {
1805 BestPred = Pred;
1806 BestPredFreq = PredFreq;
1807 }
1808 }
1809
1810 // If no direct predecessor is fine, just use the loop header.
Philip Reamesb9688f42016-03-02 21:45:13 +00001811 if (!BestPred) {
1812 DEBUG(dbgs() << " final top unchanged\n");
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001813 return L.getHeader();
Philip Reamesb9688f42016-03-02 21:45:13 +00001814 }
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001815
1816 // Walk backwards through any straight line of predecessors.
1817 while (BestPred->pred_size() == 1 &&
1818 (*BestPred->pred_begin())->succ_size() == 1 &&
1819 *BestPred->pred_begin() != L.getHeader())
1820 BestPred = *BestPred->pred_begin();
1821
1822 DEBUG(dbgs() << " final top: " << getBlockName(BestPred) << "\n");
1823 return BestPred;
1824}
1825
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001826/// Find the best loop exiting block for layout.
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00001827///
Chandler Carruth03adbd42011-11-27 13:34:33 +00001828/// This routine implements the logic to analyze the loop looking for the best
1829/// block to layout at the top of the loop. Typically this is done to maximize
1830/// fallthrough opportunities.
1831MachineBasicBlock *
Kyle Butte9425c4f2017-02-04 02:26:32 +00001832MachineBlockPlacement::findBestLoopExit(const MachineLoop &L,
Chandler Carruthccc7e422012-04-16 01:12:56 +00001833 const BlockFilterSet &LoopBlockSet) {
Chandler Carruth68062612012-04-10 13:35:57 +00001834 // We don't want to layout the loop linearly in all cases. If the loop header
1835 // is just a normal basic block in the loop, we want to look for what block
1836 // within the loop is the best one to layout at the top. However, if the loop
1837 // header has be pre-merged into a chain due to predecessors not having
1838 // analyzable branches, *and* the predecessor it is merged with is *not* part
1839 // of the loop, rotating the header into the middle of the loop will create
1840 // a non-contiguous range of blocks which is Very Bad. So start with the
1841 // header and only rotate if safe.
1842 BlockChain &HeaderChain = *BlockToChain[L.getHeader()];
1843 if (!LoopBlockSet.count(*HeaderChain.begin()))
Craig Topperc0196b12014-04-14 00:51:57 +00001844 return nullptr;
Chandler Carruth68062612012-04-10 13:35:57 +00001845
Chandler Carruth03adbd42011-11-27 13:34:33 +00001846 BlockFrequency BestExitEdgeFreq;
Chandler Carruthccc7e422012-04-16 01:12:56 +00001847 unsigned BestExitLoopDepth = 0;
Craig Topperc0196b12014-04-14 00:51:57 +00001848 MachineBasicBlock *ExitingBB = nullptr;
Chandler Carruth4f567202011-11-27 20:18:00 +00001849 // If there are exits to outer loops, loop rotation can severely limit
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00001850 // fallthrough opportunities unless it selects such an exit. Keep a set of
Chandler Carruth4f567202011-11-27 20:18:00 +00001851 // blocks where rotating to exit with that block will reach an outer loop.
1852 SmallPtrSet<MachineBasicBlock *, 4> BlocksExitingToOuterLoop;
1853
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001854 DEBUG(dbgs() << "Finding best loop exit for: " << getBlockName(L.getHeader())
1855 << "\n");
Chandler Carruth7a715da2015-03-05 03:19:05 +00001856 for (MachineBasicBlock *MBB : L.getBlocks()) {
1857 BlockChain &Chain = *BlockToChain[MBB];
Chandler Carruth03adbd42011-11-27 13:34:33 +00001858 // Ensure that this block is at the end of a chain; otherwise it could be
Chandler Carruth9a512a42015-04-15 13:19:54 +00001859 // mid-way through an inner loop or a successor of an unanalyzable branch.
Chandler Carruth7a715da2015-03-05 03:19:05 +00001860 if (MBB != *std::prev(Chain.end()))
Chandler Carruth9ffb97e2011-11-27 00:38:03 +00001861 continue;
Chandler Carruth9ffb97e2011-11-27 00:38:03 +00001862
Chandler Carruth03adbd42011-11-27 13:34:33 +00001863 // Now walk the successors. We need to establish whether this has a viable
1864 // exiting successor and whether it has a viable non-exiting successor.
1865 // We store the old exiting state and restore it if a viable looping
1866 // successor isn't found.
1867 MachineBasicBlock *OldExitingBB = ExitingBB;
1868 BlockFrequency OldBestExitEdgeFreq = BestExitEdgeFreq;
Chandler Carruthccc7e422012-04-16 01:12:56 +00001869 bool HasLoopingSucc = false;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001870 for (MachineBasicBlock *Succ : MBB->successors()) {
Reid Kleckner0e288232015-08-27 23:27:47 +00001871 if (Succ->isEHPad())
Chandler Carruth03adbd42011-11-27 13:34:33 +00001872 continue;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001873 if (Succ == MBB)
Chandler Carruth03adbd42011-11-27 13:34:33 +00001874 continue;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001875 BlockChain &SuccChain = *BlockToChain[Succ];
Chandler Carruth03adbd42011-11-27 13:34:33 +00001876 // Don't split chains, either this chain or the successor's chain.
Chandler Carruthccc7e422012-04-16 01:12:56 +00001877 if (&Chain == &SuccChain) {
Chandler Carruth7a715da2015-03-05 03:19:05 +00001878 DEBUG(dbgs() << " exiting: " << getBlockName(MBB) << " -> "
1879 << getBlockName(Succ) << " (chain conflict)\n");
Chandler Carruth03adbd42011-11-27 13:34:33 +00001880 continue;
1881 }
1882
Cong Houd97c1002015-12-01 05:29:22 +00001883 auto SuccProb = MBPI->getEdgeProbability(MBB, Succ);
Chandler Carruth7a715da2015-03-05 03:19:05 +00001884 if (LoopBlockSet.count(Succ)) {
1885 DEBUG(dbgs() << " looping: " << getBlockName(MBB) << " -> "
Cong Houd97c1002015-12-01 05:29:22 +00001886 << getBlockName(Succ) << " (" << SuccProb << ")\n");
Chandler Carruthccc7e422012-04-16 01:12:56 +00001887 HasLoopingSucc = true;
Chandler Carruth03adbd42011-11-27 13:34:33 +00001888 continue;
1889 }
1890
Chandler Carruthccc7e422012-04-16 01:12:56 +00001891 unsigned SuccLoopDepth = 0;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001892 if (MachineLoop *ExitLoop = MLI->getLoopFor(Succ)) {
Chandler Carruthccc7e422012-04-16 01:12:56 +00001893 SuccLoopDepth = ExitLoop->getLoopDepth();
1894 if (ExitLoop->contains(&L))
Chandler Carruth7a715da2015-03-05 03:19:05 +00001895 BlocksExitingToOuterLoop.insert(MBB);
Chandler Carruthccc7e422012-04-16 01:12:56 +00001896 }
1897
Chandler Carruth7a715da2015-03-05 03:19:05 +00001898 BlockFrequency ExitEdgeFreq = MBFI->getBlockFreq(MBB) * SuccProb;
1899 DEBUG(dbgs() << " exiting: " << getBlockName(MBB) << " -> "
1900 << getBlockName(Succ) << " [L:" << SuccLoopDepth << "] (";
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00001901 MBFI->printBlockFreq(dbgs(), ExitEdgeFreq) << ")\n");
Benjamin Kramerc8160d62013-11-20 19:08:44 +00001902 // Note that we bias this toward an existing layout successor to retain
1903 // incoming order in the absence of better information. The exit must have
1904 // a frequency higher than the current exit before we consider breaking
1905 // the layout.
1906 BranchProbability Bias(100 - ExitBlockBias, 100);
Chandler Carruth26d30172015-04-15 13:39:42 +00001907 if (!ExitingBB || SuccLoopDepth > BestExitLoopDepth ||
Chandler Carruthccc7e422012-04-16 01:12:56 +00001908 ExitEdgeFreq > BestExitEdgeFreq ||
Chandler Carruth7a715da2015-03-05 03:19:05 +00001909 (MBB->isLayoutSuccessor(Succ) &&
Benjamin Kramerc8160d62013-11-20 19:08:44 +00001910 !(ExitEdgeFreq < BestExitEdgeFreq * Bias))) {
Chandler Carruth03adbd42011-11-27 13:34:33 +00001911 BestExitEdgeFreq = ExitEdgeFreq;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001912 ExitingBB = MBB;
Chandler Carrutha0545802011-11-27 09:22:53 +00001913 }
Chandler Carruth9ffb97e2011-11-27 00:38:03 +00001914 }
Chandler Carruth03adbd42011-11-27 13:34:33 +00001915
Chandler Carruthccc7e422012-04-16 01:12:56 +00001916 if (!HasLoopingSucc) {
Chandler Carruthcfb2b9d2015-04-15 13:26:41 +00001917 // Restore the old exiting state, no viable looping successor was found.
Chandler Carruth03adbd42011-11-27 13:34:33 +00001918 ExitingBB = OldExitingBB;
1919 BestExitEdgeFreq = OldBestExitEdgeFreq;
Chandler Carruth03adbd42011-11-27 13:34:33 +00001920 }
Chandler Carruth9ffb97e2011-11-27 00:38:03 +00001921 }
Chandler Carruthccc7e422012-04-16 01:12:56 +00001922 // Without a candidate exiting block or with only a single block in the
Chandler Carruth03adbd42011-11-27 13:34:33 +00001923 // loop, just use the loop header to layout the loop.
Sjoerd Meijer5e11a182016-07-27 08:49:23 +00001924 if (!ExitingBB) {
1925 DEBUG(dbgs() << " No other candidate exit blocks, using loop header\n");
Craig Topperc0196b12014-04-14 00:51:57 +00001926 return nullptr;
Sjoerd Meijer5e11a182016-07-27 08:49:23 +00001927 }
1928 if (L.getNumBlocks() == 1) {
1929 DEBUG(dbgs() << " Loop has 1 block, using loop header as exit\n");
1930 return nullptr;
1931 }
Chandler Carruth9ffb97e2011-11-27 00:38:03 +00001932
Chandler Carruth4f567202011-11-27 20:18:00 +00001933 // Also, if we have exit blocks which lead to outer loops but didn't select
1934 // one of them as the exiting block we are rotating toward, disable loop
1935 // rotation altogether.
1936 if (!BlocksExitingToOuterLoop.empty() &&
1937 !BlocksExitingToOuterLoop.count(ExitingBB))
Craig Topperc0196b12014-04-14 00:51:57 +00001938 return nullptr;
Chandler Carruth4f567202011-11-27 20:18:00 +00001939
Chandler Carruth03adbd42011-11-27 13:34:33 +00001940 DEBUG(dbgs() << " Best exiting block: " << getBlockName(ExitingBB) << "\n");
Chandler Carruthccc7e422012-04-16 01:12:56 +00001941 return ExitingBB;
Chandler Carruth9ffb97e2011-11-27 00:38:03 +00001942}
1943
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001944/// Attempt to rotate an exiting block to the bottom of the loop.
Chandler Carruth8c74c7b2012-04-16 09:31:23 +00001945///
1946/// Once we have built a chain, try to rotate it to line up the hot exit block
1947/// with fallthrough out of the loop if doing so doesn't introduce unnecessary
1948/// branches. For example, if the loop has fallthrough into its header and out
1949/// of its bottom already, don't rotate it.
1950void MachineBlockPlacement::rotateLoop(BlockChain &LoopChain,
Kyle Butte9425c4f2017-02-04 02:26:32 +00001951 const MachineBasicBlock *ExitingBB,
Chandler Carruth8c74c7b2012-04-16 09:31:23 +00001952 const BlockFilterSet &LoopBlockSet) {
1953 if (!ExitingBB)
1954 return;
1955
1956 MachineBasicBlock *Top = *LoopChain.begin();
Serguei Katkov0e831c92017-07-11 08:34:58 +00001957 MachineBasicBlock *Bottom = *std::prev(LoopChain.end());
1958
1959 // If ExitingBB is already the last one in a chain then nothing to do.
1960 if (Bottom == ExitingBB)
1961 return;
1962
Chandler Carruth8c74c7b2012-04-16 09:31:23 +00001963 bool ViableTopFallthrough = false;
Chandler Carruth7a715da2015-03-05 03:19:05 +00001964 for (MachineBasicBlock *Pred : Top->predecessors()) {
1965 BlockChain *PredChain = BlockToChain[Pred];
1966 if (!LoopBlockSet.count(Pred) &&
1967 (!PredChain || Pred == *std::prev(PredChain->end()))) {
Chandler Carruth8c74c7b2012-04-16 09:31:23 +00001968 ViableTopFallthrough = true;
1969 break;
1970 }
1971 }
1972
1973 // If the header has viable fallthrough, check whether the current loop
1974 // bottom is a viable exiting block. If so, bail out as rotating will
1975 // introduce an unnecessary branch.
1976 if (ViableTopFallthrough) {
Chandler Carruth7a715da2015-03-05 03:19:05 +00001977 for (MachineBasicBlock *Succ : Bottom->successors()) {
1978 BlockChain *SuccChain = BlockToChain[Succ];
1979 if (!LoopBlockSet.count(Succ) &&
1980 (!SuccChain || Succ == *SuccChain->begin()))
Chandler Carruth8c74c7b2012-04-16 09:31:23 +00001981 return;
1982 }
1983 }
1984
Eugene Zelenko5df3d892017-08-24 21:21:39 +00001985 BlockChain::iterator ExitIt = llvm::find(LoopChain, ExitingBB);
Chandler Carruth8c74c7b2012-04-16 09:31:23 +00001986 if (ExitIt == LoopChain.end())
1987 return;
1988
Serguei Katkov0e831c92017-07-11 08:34:58 +00001989 // Rotating a loop exit to the bottom when there is a fallthrough to top
1990 // trades the entry fallthrough for an exit fallthrough.
1991 // If there is no bottom->top edge, but the chosen exit block does have
1992 // a fallthrough, we break that fallthrough for nothing in return.
1993
1994 // Let's consider an example. We have a built chain of basic blocks
1995 // B1, B2, ..., Bn, where Bk is a ExitingBB - chosen exit block.
1996 // By doing a rotation we get
1997 // Bk+1, ..., Bn, B1, ..., Bk
1998 // Break of fallthrough to B1 is compensated by a fallthrough from Bk.
1999 // If we had a fallthrough Bk -> Bk+1 it is broken now.
2000 // It might be compensated by fallthrough Bn -> B1.
2001 // So we have a condition to avoid creation of extra branch by loop rotation.
2002 // All below must be true to avoid loop rotation:
2003 // If there is a fallthrough to top (B1)
2004 // There was fallthrough from chosen exit block (Bk) to next one (Bk+1)
2005 // There is no fallthrough from bottom (Bn) to top (B1).
2006 // Please note that there is no exit fallthrough from Bn because we checked it
2007 // above.
2008 if (ViableTopFallthrough) {
2009 assert(std::next(ExitIt) != LoopChain.end() &&
2010 "Exit should not be last BB");
2011 MachineBasicBlock *NextBlockInChain = *std::next(ExitIt);
2012 if (ExitingBB->isSuccessor(NextBlockInChain))
2013 if (!Bottom->isSuccessor(Top))
2014 return;
2015 }
2016
2017 DEBUG(dbgs() << "Rotating loop to put exit " << getBlockName(ExitingBB)
2018 << " at bottom\n");
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00002019 std::rotate(LoopChain.begin(), std::next(ExitIt), LoopChain.end());
Chandler Carruth8c74c7b2012-04-16 09:31:23 +00002020}
2021
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002022/// Attempt to rotate a loop based on profile data to reduce branch cost.
Cong Hou7745dbc2015-10-19 23:16:40 +00002023///
2024/// With profile data, we can determine the cost in terms of missed fall through
2025/// opportunities when rotating a loop chain and select the best rotation.
2026/// Basically, there are three kinds of cost to consider for each rotation:
2027/// 1. The possibly missed fall through edge (if it exists) from BB out of
2028/// the loop to the loop header.
2029/// 2. The possibly missed fall through edges (if they exist) from the loop
2030/// exits to BB out of the loop.
2031/// 3. The missed fall through edge (if it exists) from the last BB to the
2032/// first BB in the loop chain.
2033/// Therefore, the cost for a given rotation is the sum of costs listed above.
2034/// We select the best rotation with the smallest cost.
2035void MachineBlockPlacement::rotateLoopWithProfile(
Kyle Butte9425c4f2017-02-04 02:26:32 +00002036 BlockChain &LoopChain, const MachineLoop &L,
2037 const BlockFilterSet &LoopBlockSet) {
Cong Hou7745dbc2015-10-19 23:16:40 +00002038 auto HeaderBB = L.getHeader();
Eugene Zelenko5df3d892017-08-24 21:21:39 +00002039 auto HeaderIter = llvm::find(LoopChain, HeaderBB);
Cong Hou7745dbc2015-10-19 23:16:40 +00002040 auto RotationPos = LoopChain.end();
2041
2042 BlockFrequency SmallestRotationCost = BlockFrequency::getMaxFrequency();
2043
2044 // A utility lambda that scales up a block frequency by dividing it by a
2045 // branch probability which is the reciprocal of the scale.
2046 auto ScaleBlockFrequency = [](BlockFrequency Freq,
2047 unsigned Scale) -> BlockFrequency {
2048 if (Scale == 0)
2049 return 0;
2050 // Use operator / between BlockFrequency and BranchProbability to implement
2051 // saturating multiplication.
2052 return Freq / BranchProbability(1, Scale);
2053 };
2054
2055 // Compute the cost of the missed fall-through edge to the loop header if the
2056 // chain head is not the loop header. As we only consider natural loops with
2057 // single header, this computation can be done only once.
2058 BlockFrequency HeaderFallThroughCost(0);
2059 for (auto *Pred : HeaderBB->predecessors()) {
2060 BlockChain *PredChain = BlockToChain[Pred];
2061 if (!LoopBlockSet.count(Pred) &&
2062 (!PredChain || Pred == *std::prev(PredChain->end()))) {
2063 auto EdgeFreq =
2064 MBFI->getBlockFreq(Pred) * MBPI->getEdgeProbability(Pred, HeaderBB);
2065 auto FallThruCost = ScaleBlockFrequency(EdgeFreq, MisfetchCost);
2066 // If the predecessor has only an unconditional jump to the header, we
2067 // need to consider the cost of this jump.
2068 if (Pred->succ_size() == 1)
2069 FallThruCost += ScaleBlockFrequency(EdgeFreq, JumpInstCost);
2070 HeaderFallThroughCost = std::max(HeaderFallThroughCost, FallThruCost);
2071 }
2072 }
2073
2074 // Here we collect all exit blocks in the loop, and for each exit we find out
2075 // its hottest exit edge. For each loop rotation, we define the loop exit cost
2076 // as the sum of frequencies of exit edges we collect here, excluding the exit
2077 // edge from the tail of the loop chain.
2078 SmallVector<std::pair<MachineBasicBlock *, BlockFrequency>, 4> ExitsWithFreq;
2079 for (auto BB : LoopChain) {
Cong Houd97c1002015-12-01 05:29:22 +00002080 auto LargestExitEdgeProb = BranchProbability::getZero();
Cong Hou7745dbc2015-10-19 23:16:40 +00002081 for (auto *Succ : BB->successors()) {
2082 BlockChain *SuccChain = BlockToChain[Succ];
2083 if (!LoopBlockSet.count(Succ) &&
2084 (!SuccChain || Succ == *SuccChain->begin())) {
Cong Houd97c1002015-12-01 05:29:22 +00002085 auto SuccProb = MBPI->getEdgeProbability(BB, Succ);
2086 LargestExitEdgeProb = std::max(LargestExitEdgeProb, SuccProb);
Cong Hou7745dbc2015-10-19 23:16:40 +00002087 }
2088 }
Cong Houd97c1002015-12-01 05:29:22 +00002089 if (LargestExitEdgeProb > BranchProbability::getZero()) {
2090 auto ExitFreq = MBFI->getBlockFreq(BB) * LargestExitEdgeProb;
Cong Hou7745dbc2015-10-19 23:16:40 +00002091 ExitsWithFreq.emplace_back(BB, ExitFreq);
2092 }
2093 }
2094
2095 // In this loop we iterate every block in the loop chain and calculate the
2096 // cost assuming the block is the head of the loop chain. When the loop ends,
2097 // we should have found the best candidate as the loop chain's head.
2098 for (auto Iter = LoopChain.begin(), TailIter = std::prev(LoopChain.end()),
2099 EndIter = LoopChain.end();
2100 Iter != EndIter; Iter++, TailIter++) {
2101 // TailIter is used to track the tail of the loop chain if the block we are
2102 // checking (pointed by Iter) is the head of the chain.
2103 if (TailIter == LoopChain.end())
2104 TailIter = LoopChain.begin();
2105
2106 auto TailBB = *TailIter;
2107
2108 // Calculate the cost by putting this BB to the top.
2109 BlockFrequency Cost = 0;
2110
2111 // If the current BB is the loop header, we need to take into account the
2112 // cost of the missed fall through edge from outside of the loop to the
2113 // header.
2114 if (Iter != HeaderIter)
2115 Cost += HeaderFallThroughCost;
2116
2117 // Collect the loop exit cost by summing up frequencies of all exit edges
2118 // except the one from the chain tail.
2119 for (auto &ExitWithFreq : ExitsWithFreq)
2120 if (TailBB != ExitWithFreq.first)
2121 Cost += ExitWithFreq.second;
2122
2123 // The cost of breaking the once fall-through edge from the tail to the top
2124 // of the loop chain. Here we need to consider three cases:
2125 // 1. If the tail node has only one successor, then we will get an
2126 // additional jmp instruction. So the cost here is (MisfetchCost +
2127 // JumpInstCost) * tail node frequency.
2128 // 2. If the tail node has two successors, then we may still get an
2129 // additional jmp instruction if the layout successor after the loop
2130 // chain is not its CFG successor. Note that the more frequently executed
2131 // jmp instruction will be put ahead of the other one. Assume the
2132 // frequency of those two branches are x and y, where x is the frequency
2133 // of the edge to the chain head, then the cost will be
2134 // (x * MisfetechCost + min(x, y) * JumpInstCost) * tail node frequency.
2135 // 3. If the tail node has more than two successors (this rarely happens),
2136 // we won't consider any additional cost.
2137 if (TailBB->isSuccessor(*Iter)) {
2138 auto TailBBFreq = MBFI->getBlockFreq(TailBB);
2139 if (TailBB->succ_size() == 1)
2140 Cost += ScaleBlockFrequency(TailBBFreq.getFrequency(),
2141 MisfetchCost + JumpInstCost);
2142 else if (TailBB->succ_size() == 2) {
2143 auto TailToHeadProb = MBPI->getEdgeProbability(TailBB, *Iter);
2144 auto TailToHeadFreq = TailBBFreq * TailToHeadProb;
2145 auto ColderEdgeFreq = TailToHeadProb > BranchProbability(1, 2)
2146 ? TailBBFreq * TailToHeadProb.getCompl()
2147 : TailToHeadFreq;
2148 Cost += ScaleBlockFrequency(TailToHeadFreq, MisfetchCost) +
2149 ScaleBlockFrequency(ColderEdgeFreq, JumpInstCost);
2150 }
2151 }
2152
Philip Reamesb9688f42016-03-02 21:45:13 +00002153 DEBUG(dbgs() << "The cost of loop rotation by making " << getBlockName(*Iter)
Cong Hou7745dbc2015-10-19 23:16:40 +00002154 << " to the top: " << Cost.getFrequency() << "\n");
2155
2156 if (Cost < SmallestRotationCost) {
2157 SmallestRotationCost = Cost;
2158 RotationPos = Iter;
2159 }
2160 }
2161
2162 if (RotationPos != LoopChain.end()) {
Philip Reamesb9688f42016-03-02 21:45:13 +00002163 DEBUG(dbgs() << "Rotate loop by making " << getBlockName(*RotationPos)
Cong Hou7745dbc2015-10-19 23:16:40 +00002164 << " to the top\n");
2165 std::rotate(LoopChain.begin(), RotationPos, LoopChain.end());
2166 }
2167}
2168
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002169/// Collect blocks in the given loop that are to be placed.
Cong Houb90b9e02015-11-02 21:24:00 +00002170///
2171/// When profile data is available, exclude cold blocks from the returned set;
2172/// otherwise, collect all blocks in the loop.
2173MachineBlockPlacement::BlockFilterSet
Kyle Butte9425c4f2017-02-04 02:26:32 +00002174MachineBlockPlacement::collectLoopBlockSet(const MachineLoop &L) {
Cong Houb90b9e02015-11-02 21:24:00 +00002175 BlockFilterSet LoopBlockSet;
2176
2177 // Filter cold blocks off from LoopBlockSet when profile data is available.
2178 // Collect the sum of frequencies of incoming edges to the loop header from
2179 // outside. If we treat the loop as a super block, this is the frequency of
2180 // the loop. Then for each block in the loop, we calculate the ratio between
2181 // its frequency and the frequency of the loop block. When it is too small,
2182 // don't add it to the loop chain. If there are outer loops, then this block
2183 // will be merged into the first outer loop chain for which this block is not
2184 // cold anymore. This needs precise profile data and we only do this when
2185 // profile data is available.
Easwaran Ramana17f2202017-12-22 01:33:52 +00002186 if (F->getFunction().hasProfileData() || ForceLoopColdBlock) {
Cong Houb90b9e02015-11-02 21:24:00 +00002187 BlockFrequency LoopFreq(0);
2188 for (auto LoopPred : L.getHeader()->predecessors())
2189 if (!L.contains(LoopPred))
2190 LoopFreq += MBFI->getBlockFreq(LoopPred) *
2191 MBPI->getEdgeProbability(LoopPred, L.getHeader());
2192
2193 for (MachineBasicBlock *LoopBB : L.getBlocks()) {
2194 auto Freq = MBFI->getBlockFreq(LoopBB).getFrequency();
2195 if (Freq == 0 || LoopFreq.getFrequency() / Freq > LoopToColdBlockRatio)
2196 continue;
2197 LoopBlockSet.insert(LoopBB);
2198 }
2199 } else
2200 LoopBlockSet.insert(L.block_begin(), L.block_end());
2201
2202 return LoopBlockSet;
2203}
2204
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002205/// Forms basic block chains from the natural loop structures.
Chandler Carruth10281422011-10-21 06:46:38 +00002206///
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00002207/// These chains are designed to preserve the existing *structure* of the code
2208/// as much as possible. We can then stitch the chains together in a way which
2209/// both preserves the topological structure and minimizes taken conditional
2210/// branches.
Kyle Butte9425c4f2017-02-04 02:26:32 +00002211void MachineBlockPlacement::buildLoopChains(const MachineLoop &L) {
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00002212 // First recurse through any nested loops, building chains for those inner
2213 // loops.
Kyle Butte9425c4f2017-02-04 02:26:32 +00002214 for (const MachineLoop *InnerLoop : L)
Xinliang David Li52530a72016-06-13 22:23:44 +00002215 buildLoopChains(*InnerLoop);
Chandler Carruth10281422011-10-21 06:46:38 +00002216
Kyle Butt0cf5b2f2017-05-17 23:44:41 +00002217 assert(BlockWorkList.empty() &&
2218 "BlockWorkList not empty when starting to build loop chains.");
2219 assert(EHPadWorkList.empty() &&
2220 "EHPadWorkList not empty when starting to build loop chains.");
Xinliang David Li52530a72016-06-13 22:23:44 +00002221 BlockFilterSet LoopBlockSet = collectLoopBlockSet(L);
Chandler Carruth03adbd42011-11-27 13:34:33 +00002222
Cong Hou7745dbc2015-10-19 23:16:40 +00002223 // Check if we have profile data for this function. If yes, we will rotate
2224 // this loop by modeling costs more precisely which requires the profile data
2225 // for better layout.
2226 bool RotateLoopWithProfile =
Xinliang David Lif0ab6df2016-05-12 02:04:41 +00002227 ForcePreciseRotationCost ||
Easwaran Ramana17f2202017-12-22 01:33:52 +00002228 (PreciseRotationCost && F->getFunction().hasProfileData());
Cong Hou7745dbc2015-10-19 23:16:40 +00002229
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00002230 // First check to see if there is an obviously preferable top block for the
2231 // loop. This will default to the header, but may end up as one of the
2232 // predecessors to the header if there is one which will result in strictly
2233 // fewer branches in the loop body.
Cong Hou7745dbc2015-10-19 23:16:40 +00002234 // When we use profile data to rotate the loop, this is unnecessary.
2235 MachineBasicBlock *LoopTop =
2236 RotateLoopWithProfile ? L.getHeader() : findBestLoopTop(L, LoopBlockSet);
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00002237
2238 // If we selected just the header for the loop top, look for a potentially
2239 // profitable exit block in the event that rotating the loop can eliminate
2240 // branches by placing an exit edge at the bottom.
Xin Tongd8d97972017-10-04 21:39:25 +00002241 //
2242 // Loops are processed innermost to uttermost, make sure we clear
2243 // PreferredLoopExit before processing a new loop.
2244 PreferredLoopExit = nullptr;
Cong Hou7745dbc2015-10-19 23:16:40 +00002245 if (!RotateLoopWithProfile && LoopTop == L.getHeader())
Kyle Buttab9cca72016-10-27 21:37:20 +00002246 PreferredLoopExit = findBestLoopExit(L, LoopBlockSet);
Chandler Carruth8c0b41d2012-04-16 13:33:36 +00002247
2248 BlockChain &LoopChain = *BlockToChain[LoopTop];
Chandler Carruth10281422011-10-21 06:46:38 +00002249
Chandler Carruth8d150782011-11-13 11:20:44 +00002250 // FIXME: This is a really lame way of walking the chains in the loop: we
2251 // walk the blocks, and use a set to prevent visiting a particular chain
2252 // twice.
Jakub Staszak90616162011-12-21 23:02:08 +00002253 SmallPtrSet<BlockChain *, 4> UpdatedPreds;
Kyle Butt0cf5b2f2017-05-17 23:44:41 +00002254 assert(LoopChain.UnscheduledPredecessors == 0 &&
2255 "LoopChain should not have unscheduled predecessors.");
Jakub Staszak190c7122011-12-07 19:46:10 +00002256 UpdatedPreds.insert(&LoopChain);
Cong Houb90b9e02015-11-02 21:24:00 +00002257
Kyle Butte9425c4f2017-02-04 02:26:32 +00002258 for (const MachineBasicBlock *LoopBB : LoopBlockSet)
Xinliang David Li93926ac2016-07-01 05:46:48 +00002259 fillWorkLists(LoopBB, UpdatedPreds, &LoopBlockSet);
Chandler Carruth8d150782011-11-13 11:20:44 +00002260
Xinliang David Li93926ac2016-07-01 05:46:48 +00002261 buildChain(LoopTop, LoopChain, &LoopBlockSet);
Cong Hou7745dbc2015-10-19 23:16:40 +00002262
2263 if (RotateLoopWithProfile)
2264 rotateLoopWithProfile(LoopChain, L, LoopBlockSet);
2265 else
Kyle Buttab9cca72016-10-27 21:37:20 +00002266 rotateLoop(LoopChain, PreferredLoopExit, LoopBlockSet);
Chandler Carruth8d150782011-11-13 11:20:44 +00002267
2268 DEBUG({
Chandler Carruth8e1d9062011-11-13 21:39:51 +00002269 // Crash at the end so we get all of the debugging output first.
2270 bool BadLoop = false;
Philip Reamesae27b232016-03-03 00:58:43 +00002271 if (LoopChain.UnscheduledPredecessors) {
Chandler Carruth8e1d9062011-11-13 21:39:51 +00002272 BadLoop = true;
Chandler Carruth8d150782011-11-13 11:20:44 +00002273 dbgs() << "Loop chain contains a block without its preds placed!\n"
2274 << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
2275 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n";
Chandler Carruth8e1d9062011-11-13 21:39:51 +00002276 }
Chandler Carruth7a715da2015-03-05 03:19:05 +00002277 for (MachineBasicBlock *ChainBB : LoopChain) {
2278 dbgs() << " ... " << getBlockName(ChainBB) << "\n";
Rong Xu66827422016-11-16 20:50:06 +00002279 if (!LoopBlockSet.remove(ChainBB)) {
Chandler Carruth0a31d142011-11-14 10:55:53 +00002280 // We don't mark the loop as bad here because there are real situations
2281 // where this can occur. For example, with an unanalyzable fallthrough
Chandler Carruth99fe42f2011-11-23 10:35:36 +00002282 // from a loop block to a non-loop block or vice versa.
Chandler Carruth8d150782011-11-13 11:20:44 +00002283 dbgs() << "Loop chain contains a block not contained by the loop!\n"
2284 << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
2285 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
Chandler Carruth7a715da2015-03-05 03:19:05 +00002286 << " Bad block: " << getBlockName(ChainBB) << "\n";
Chandler Carruth8e1d9062011-11-13 21:39:51 +00002287 }
Chandler Carruthccc7e422012-04-16 01:12:56 +00002288 }
Chandler Carruth8d150782011-11-13 11:20:44 +00002289
Chandler Carruth8e1d9062011-11-13 21:39:51 +00002290 if (!LoopBlockSet.empty()) {
2291 BadLoop = true;
Kyle Butte9425c4f2017-02-04 02:26:32 +00002292 for (const MachineBasicBlock *LoopBB : LoopBlockSet)
Chandler Carruth8d150782011-11-13 11:20:44 +00002293 dbgs() << "Loop contains blocks never placed into a chain!\n"
2294 << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
2295 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
Chandler Carruth7a715da2015-03-05 03:19:05 +00002296 << " Bad block: " << getBlockName(LoopBB) << "\n";
Chandler Carruth8e1d9062011-11-13 21:39:51 +00002297 }
2298 assert(!BadLoop && "Detected problems with the placement of this loop.");
Chandler Carruth8d150782011-11-13 11:20:44 +00002299 });
Xinliang David Li93926ac2016-07-01 05:46:48 +00002300
2301 BlockWorkList.clear();
2302 EHPadWorkList.clear();
Chandler Carruth10281422011-10-21 06:46:38 +00002303}
2304
Xinliang David Li52530a72016-06-13 22:23:44 +00002305void MachineBlockPlacement::buildCFGChains() {
Chandler Carruth8d150782011-11-13 11:20:44 +00002306 // Ensure that every BB in the function has an associated chain to simplify
2307 // the assumptions of the remaining algorithm.
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +00002308 SmallVector<MachineOperand, 4> Cond; // For AnalyzeBranch.
Xinliang David Li52530a72016-06-13 22:23:44 +00002309 for (MachineFunction::iterator FI = F->begin(), FE = F->end(); FI != FE;
2310 ++FI) {
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +00002311 MachineBasicBlock *BB = &*FI;
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00002312 BlockChain *Chain =
2313 new (ChainAllocator.Allocate()) BlockChain(BlockToChain, BB);
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +00002314 // Also, merge any blocks which we cannot reason about and must preserve
2315 // the exact fallthrough behavior for.
Eugene Zelenko5df3d892017-08-24 21:21:39 +00002316 while (true) {
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +00002317 Cond.clear();
Craig Topperc0196b12014-04-14 00:51:57 +00002318 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
Jacques Pienaar71c30a12016-07-15 14:41:04 +00002319 if (!TII->analyzeBranch(*BB, TBB, FBB, Cond) || !FI->canFallThrough())
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +00002320 break;
2321
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +00002322 MachineFunction::iterator NextFI = std::next(FI);
2323 MachineBasicBlock *NextBB = &*NextFI;
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +00002324 // Ensure that the layout successor is a viable block, as we know that
2325 // fallthrough is a possibility.
2326 assert(NextFI != FE && "Can't fallthrough past the last block.");
2327 DEBUG(dbgs() << "Pre-merging due to unanalyzable fallthrough: "
2328 << getBlockName(BB) << " -> " << getBlockName(NextBB)
2329 << "\n");
Craig Topperc0196b12014-04-14 00:51:57 +00002330 Chain->merge(NextBB, nullptr);
Hal Finkel34f9d6a2016-12-15 05:33:19 +00002331#ifndef NDEBUG
Sanjoy Dasd7389d62016-12-15 05:08:57 +00002332 BlocksWithUnanalyzableExits.insert(&*BB);
Hal Finkel34f9d6a2016-12-15 05:33:19 +00002333#endif
Chandler Carruthf3dc9ef2011-11-19 10:26:02 +00002334 FI = NextFI;
2335 BB = NextBB;
2336 }
2337 }
Chandler Carruth8d150782011-11-13 11:20:44 +00002338
2339 // Build any loop-based chains.
Sam McCall2a36eee2016-11-01 22:02:14 +00002340 PreferredLoopExit = nullptr;
Chandler Carruth7a715da2015-03-05 03:19:05 +00002341 for (MachineLoop *L : *MLI)
Xinliang David Li52530a72016-06-13 22:23:44 +00002342 buildLoopChains(*L);
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00002343
Kyle Butt0cf5b2f2017-05-17 23:44:41 +00002344 assert(BlockWorkList.empty() &&
2345 "BlockWorkList should be empty before building final chain.");
2346 assert(EHPadWorkList.empty() &&
2347 "EHPadWorkList should be empty before building final chain.");
Chandler Carruthbd1be4d2011-10-23 09:18:45 +00002348
Chandler Carruth8d150782011-11-13 11:20:44 +00002349 SmallPtrSet<BlockChain *, 4> UpdatedPreds;
Xinliang David Li52530a72016-06-13 22:23:44 +00002350 for (MachineBasicBlock &MBB : *F)
Xinliang David Li93926ac2016-07-01 05:46:48 +00002351 fillWorkLists(&MBB, UpdatedPreds);
Chandler Carruth8d150782011-11-13 11:20:44 +00002352
Xinliang David Li52530a72016-06-13 22:23:44 +00002353 BlockChain &FunctionChain = *BlockToChain[&F->front()];
Xinliang David Li93926ac2016-07-01 05:46:48 +00002354 buildChain(&F->front(), FunctionChain);
Chandler Carruth8d150782011-11-13 11:20:44 +00002355
Matt Arsenault0f5f0152013-12-10 18:55:37 +00002356#ifndef NDEBUG
Eugene Zelenko5df3d892017-08-24 21:21:39 +00002357 using FunctionBlockSetType = SmallPtrSet<MachineBasicBlock *, 16>;
Matt Arsenault0f5f0152013-12-10 18:55:37 +00002358#endif
Chandler Carruth8d150782011-11-13 11:20:44 +00002359 DEBUG({
Chandler Carruth8e1d9062011-11-13 21:39:51 +00002360 // Crash at the end so we get all of the debugging output first.
2361 bool BadFunc = false;
Chandler Carruth8d150782011-11-13 11:20:44 +00002362 FunctionBlockSetType FunctionBlockSet;
Xinliang David Li52530a72016-06-13 22:23:44 +00002363 for (MachineBasicBlock &MBB : *F)
Chandler Carruth7a715da2015-03-05 03:19:05 +00002364 FunctionBlockSet.insert(&MBB);
Chandler Carruth8d150782011-11-13 11:20:44 +00002365
Chandler Carruth7a715da2015-03-05 03:19:05 +00002366 for (MachineBasicBlock *ChainBB : FunctionChain)
2367 if (!FunctionBlockSet.erase(ChainBB)) {
Chandler Carruth8e1d9062011-11-13 21:39:51 +00002368 BadFunc = true;
Chandler Carruth8d150782011-11-13 11:20:44 +00002369 dbgs() << "Function chain contains a block not in the function!\n"
Chandler Carruth7a715da2015-03-05 03:19:05 +00002370 << " Bad block: " << getBlockName(ChainBB) << "\n";
Chandler Carruth8e1d9062011-11-13 21:39:51 +00002371 }
Chandler Carruth8d150782011-11-13 11:20:44 +00002372
Chandler Carruth8e1d9062011-11-13 21:39:51 +00002373 if (!FunctionBlockSet.empty()) {
2374 BadFunc = true;
Chandler Carruth7a715da2015-03-05 03:19:05 +00002375 for (MachineBasicBlock *RemainingBB : FunctionBlockSet)
Chandler Carruth8d150782011-11-13 11:20:44 +00002376 dbgs() << "Function contains blocks never placed into a chain!\n"
Chandler Carruth7a715da2015-03-05 03:19:05 +00002377 << " Bad block: " << getBlockName(RemainingBB) << "\n";
Chandler Carruth8e1d9062011-11-13 21:39:51 +00002378 }
2379 assert(!BadFunc && "Detected problems with the block placement.");
Chandler Carruth8d150782011-11-13 11:20:44 +00002380 });
2381
2382 // Splice the blocks into place.
Xinliang David Li52530a72016-06-13 22:23:44 +00002383 MachineFunction::iterator InsertPos = F->begin();
Xinliang David Li449cdfd2016-06-24 22:54:21 +00002384 DEBUG(dbgs() << "[MBP] Function: "<< F->getName() << "\n");
Chandler Carruth7a715da2015-03-05 03:19:05 +00002385 for (MachineBasicBlock *ChainBB : FunctionChain) {
2386 DEBUG(dbgs() << (ChainBB == *FunctionChain.begin() ? "Placing chain "
2387 : " ... ")
2388 << getBlockName(ChainBB) << "\n");
2389 if (InsertPos != MachineFunction::iterator(ChainBB))
Xinliang David Li52530a72016-06-13 22:23:44 +00002390 F->splice(InsertPos, ChainBB);
Chandler Carruth8d150782011-11-13 11:20:44 +00002391 else
2392 ++InsertPos;
2393
2394 // Update the terminator of the previous block.
Chandler Carruth7a715da2015-03-05 03:19:05 +00002395 if (ChainBB == *FunctionChain.begin())
Chandler Carruth8d150782011-11-13 11:20:44 +00002396 continue;
Duncan P. N. Exon Smith6ac07fd2015-10-09 19:36:12 +00002397 MachineBasicBlock *PrevBB = &*std::prev(MachineFunction::iterator(ChainBB));
Chandler Carruth8d150782011-11-13 11:20:44 +00002398
Chandler Carruth10281422011-10-21 06:46:38 +00002399 // FIXME: It would be awesome of updateTerminator would just return rather
2400 // than assert when the branch cannot be analyzed in order to remove this
2401 // boiler plate.
2402 Cond.clear();
Craig Topperc0196b12014-04-14 00:51:57 +00002403 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
Shuxin Yang8b8fd212013-06-04 01:00:57 +00002404
Sanjoy Dasd7389d62016-12-15 05:08:57 +00002405#ifndef NDEBUG
2406 if (!BlocksWithUnanalyzableExits.count(PrevBB)) {
2407 // Given the exact block placement we chose, we may actually not _need_ to
2408 // be able to edit PrevBB's terminator sequence, but not being _able_ to
2409 // do that at this point is a bug.
2410 assert((!TII->analyzeBranch(*PrevBB, TBB, FBB, Cond) ||
2411 !PrevBB->canFallThrough()) &&
2412 "Unexpected block with un-analyzable fallthrough!");
2413 Cond.clear();
2414 TBB = FBB = nullptr;
2415 }
2416#endif
2417
Haicheng Wu90a55652016-05-24 22:16:14 +00002418 // The "PrevBB" is not yet updated to reflect current code layout, so,
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00002419 // o. it may fall-through to a block without explicit "goto" instruction
Haicheng Wu90a55652016-05-24 22:16:14 +00002420 // before layout, and no longer fall-through it after layout; or
2421 // o. just opposite.
2422 //
Jacques Pienaar71c30a12016-07-15 14:41:04 +00002423 // analyzeBranch() may return erroneous value for FBB when these two
Haicheng Wu90a55652016-05-24 22:16:14 +00002424 // situations take place. For the first scenario FBB is mistakenly set NULL;
2425 // for the 2nd scenario, the FBB, which is expected to be NULL, is
2426 // mistakenly pointing to "*BI".
2427 // Thus, if the future change needs to use FBB before the layout is set, it
2428 // has to correct FBB first by using the code similar to the following:
2429 //
2430 // if (!Cond.empty() && (!FBB || FBB == ChainBB)) {
2431 // PrevBB->updateTerminator();
2432 // Cond.clear();
2433 // TBB = FBB = nullptr;
Jacques Pienaar71c30a12016-07-15 14:41:04 +00002434 // if (TII->analyzeBranch(*PrevBB, TBB, FBB, Cond)) {
Haicheng Wu90a55652016-05-24 22:16:14 +00002435 // // FIXME: This should never take place.
2436 // TBB = FBB = nullptr;
2437 // }
2438 // }
Jacques Pienaar71c30a12016-07-15 14:41:04 +00002439 if (!TII->analyzeBranch(*PrevBB, TBB, FBB, Cond))
Haicheng Wu90a55652016-05-24 22:16:14 +00002440 PrevBB->updateTerminator();
Chandler Carruth10281422011-10-21 06:46:38 +00002441 }
Chandler Carruth8d150782011-11-13 11:20:44 +00002442
2443 // Fixup the last block.
2444 Cond.clear();
Craig Topperc0196b12014-04-14 00:51:57 +00002445 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
Jacques Pienaar71c30a12016-07-15 14:41:04 +00002446 if (!TII->analyzeBranch(F->back(), TBB, FBB, Cond))
Xinliang David Li52530a72016-06-13 22:23:44 +00002447 F->back().updateTerminator();
Xinliang David Li93926ac2016-07-01 05:46:48 +00002448
2449 BlockWorkList.clear();
2450 EHPadWorkList.clear();
Haicheng Wu90a55652016-05-24 22:16:14 +00002451}
2452
Xinliang David Li52530a72016-06-13 22:23:44 +00002453void MachineBlockPlacement::optimizeBranches() {
2454 BlockChain &FunctionChain = *BlockToChain[&F->front()];
Haicheng Wu90a55652016-05-24 22:16:14 +00002455 SmallVector<MachineOperand, 4> Cond; // For AnalyzeBranch.
Quentin Colombet776e6de2016-05-02 22:58:59 +00002456
2457 // Now that all the basic blocks in the chain have the proper layout,
2458 // make a final call to AnalyzeBranch with AllowModify set.
2459 // Indeed, the target may be able to optimize the branches in a way we
2460 // cannot because all branches may not be analyzable.
2461 // E.g., the target may be able to remove an unconditional branch to
2462 // a fallthrough when it occurs after predicated terminators.
2463 for (MachineBasicBlock *ChainBB : FunctionChain) {
2464 Cond.clear();
Haicheng Wu90a55652016-05-24 22:16:14 +00002465 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
Jacques Pienaar71c30a12016-07-15 14:41:04 +00002466 if (!TII->analyzeBranch(*ChainBB, TBB, FBB, Cond, /*AllowModify*/ true)) {
Haicheng Wu90a55652016-05-24 22:16:14 +00002467 // If PrevBB has a two-way branch, try to re-order the branches
2468 // such that we branch to the successor with higher probability first.
2469 if (TBB && !Cond.empty() && FBB &&
2470 MBPI->getEdgeProbability(ChainBB, FBB) >
2471 MBPI->getEdgeProbability(ChainBB, TBB) &&
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +00002472 !TII->reverseBranchCondition(Cond)) {
Haicheng Wu90a55652016-05-24 22:16:14 +00002473 DEBUG(dbgs() << "Reverse order of the two branches: "
2474 << getBlockName(ChainBB) << "\n");
2475 DEBUG(dbgs() << " Edge probability: "
2476 << MBPI->getEdgeProbability(ChainBB, FBB) << " vs "
2477 << MBPI->getEdgeProbability(ChainBB, TBB) << "\n");
2478 DebugLoc dl; // FIXME: this is nowhere
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +00002479 TII->removeBranch(*ChainBB);
Matt Arsenaulte8e0f5c2016-09-14 17:24:15 +00002480 TII->insertBranch(*ChainBB, FBB, TBB, Cond, dl);
Haicheng Wu90a55652016-05-24 22:16:14 +00002481 ChainBB->updateTerminator();
2482 }
2483 }
Quentin Colombet776e6de2016-05-02 22:58:59 +00002484 }
Haicheng Wue749ce52016-04-29 17:06:44 +00002485}
Chandler Carruth10281422011-10-21 06:46:38 +00002486
Xinliang David Li52530a72016-06-13 22:23:44 +00002487void MachineBlockPlacement::alignBlocks() {
Chandler Carruthccc7e422012-04-16 01:12:56 +00002488 // Walk through the backedges of the function now that we have fully laid out
2489 // the basic blocks and align the destination of each backedge. We don't rely
Chandler Carruth881d0a72012-08-07 09:45:24 +00002490 // exclusively on the loop info here so that we can align backedges in
2491 // unnatural CFGs and backedges that were introduced purely because of the
2492 // loop rotations done during this layout pass.
Matthias Braunf1caa282017-12-15 22:22:58 +00002493 if (F->getFunction().optForSize())
Chandler Carruth8b9737c2011-10-21 08:57:37 +00002494 return;
Xinliang David Li52530a72016-06-13 22:23:44 +00002495 BlockChain &FunctionChain = *BlockToChain[&F->front()];
Chandler Carruth881d0a72012-08-07 09:45:24 +00002496 if (FunctionChain.begin() == FunctionChain.end())
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00002497 return; // Empty chain.
Chandler Carruth8b9737c2011-10-21 08:57:37 +00002498
Chandler Carruth881d0a72012-08-07 09:45:24 +00002499 const BranchProbability ColdProb(1, 5); // 20%
Xinliang David Li52530a72016-06-13 22:23:44 +00002500 BlockFrequency EntryFreq = MBFI->getBlockFreq(&F->front());
Chandler Carruth881d0a72012-08-07 09:45:24 +00002501 BlockFrequency WeightedEntryFreq = EntryFreq * ColdProb;
Chandler Carruth7a715da2015-03-05 03:19:05 +00002502 for (MachineBasicBlock *ChainBB : FunctionChain) {
2503 if (ChainBB == *FunctionChain.begin())
2504 continue;
2505
Chandler Carruth881d0a72012-08-07 09:45:24 +00002506 // Don't align non-looping basic blocks. These are unlikely to execute
2507 // enough times to matter in practice. Note that we'll still handle
2508 // unnatural CFGs inside of a natural outer loop (the common case) and
2509 // rotated loops.
Chandler Carruth7a715da2015-03-05 03:19:05 +00002510 MachineLoop *L = MLI->getLoopFor(ChainBB);
Chandler Carruth881d0a72012-08-07 09:45:24 +00002511 if (!L)
2512 continue;
2513
Hal Finkel57725662015-01-03 17:58:24 +00002514 unsigned Align = TLI->getPrefLoopAlignment(L);
2515 if (!Align)
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00002516 continue; // Don't care about loop alignment.
Hal Finkel57725662015-01-03 17:58:24 +00002517
Chandler Carruth881d0a72012-08-07 09:45:24 +00002518 // If the block is cold relative to the function entry don't waste space
2519 // aligning it.
Chandler Carruth7a715da2015-03-05 03:19:05 +00002520 BlockFrequency Freq = MBFI->getBlockFreq(ChainBB);
Chandler Carruth881d0a72012-08-07 09:45:24 +00002521 if (Freq < WeightedEntryFreq)
2522 continue;
2523
2524 // If the block is cold relative to its loop header, don't align it
2525 // regardless of what edges into the block exist.
2526 MachineBasicBlock *LoopHeader = L->getHeader();
2527 BlockFrequency LoopHeaderFreq = MBFI->getBlockFreq(LoopHeader);
2528 if (Freq < (LoopHeaderFreq * ColdProb))
2529 continue;
2530
2531 // Check for the existence of a non-layout predecessor which would benefit
2532 // from aligning this block.
Chandler Carruth7a715da2015-03-05 03:19:05 +00002533 MachineBasicBlock *LayoutPred =
2534 &*std::prev(MachineFunction::iterator(ChainBB));
Chandler Carruth881d0a72012-08-07 09:45:24 +00002535
2536 // Force alignment if all the predecessors are jumps. We already checked
2537 // that the block isn't cold above.
Chandler Carruth7a715da2015-03-05 03:19:05 +00002538 if (!LayoutPred->isSuccessor(ChainBB)) {
2539 ChainBB->setAlignment(Align);
Chandler Carruth881d0a72012-08-07 09:45:24 +00002540 continue;
2541 }
2542
2543 // Align this block if the layout predecessor's edge into this block is
Nadav Rotem6036f582013-03-29 16:34:23 +00002544 // cold relative to the block. When this is true, other predecessors make up
Chandler Carruth881d0a72012-08-07 09:45:24 +00002545 // all of the hot entries into the block and thus alignment is likely to be
2546 // important.
Chandler Carruth7a715da2015-03-05 03:19:05 +00002547 BranchProbability LayoutProb =
2548 MBPI->getEdgeProbability(LayoutPred, ChainBB);
Chandler Carruth881d0a72012-08-07 09:45:24 +00002549 BlockFrequency LayoutEdgeFreq = MBFI->getBlockFreq(LayoutPred) * LayoutProb;
2550 if (LayoutEdgeFreq <= (Freq * ColdProb))
Chandler Carruth7a715da2015-03-05 03:19:05 +00002551 ChainBB->setAlignment(Align);
Chandler Carruthccc7e422012-04-16 01:12:56 +00002552 }
Chandler Carruth8b9737c2011-10-21 08:57:37 +00002553}
2554
Kyle Butt0846e562016-10-11 20:36:43 +00002555/// Tail duplicate \p BB into (some) predecessors if profitable, repeating if
2556/// it was duplicated into its chain predecessor and removed.
2557/// \p BB - Basic block that may be duplicated.
2558///
2559/// \p LPred - Chosen layout predecessor of \p BB.
2560/// Updated to be the chain end if LPred is removed.
2561/// \p Chain - Chain to which \p LPred belongs, and \p BB will belong.
2562/// \p BlockFilter - Set of blocks that belong to the loop being laid out.
2563/// Used to identify which blocks to update predecessor
2564/// counts.
2565/// \p PrevUnplacedBlockIt - Iterator pointing to the last block that was
2566/// chosen in the given order due to unnatural CFG
2567/// only needed if \p BB is removed and
2568/// \p PrevUnplacedBlockIt pointed to \p BB.
2569/// @return true if \p BB was removed.
2570bool MachineBlockPlacement::repeatedlyTailDuplicateBlock(
2571 MachineBasicBlock *BB, MachineBasicBlock *&LPred,
Kyle Butte9425c4f2017-02-04 02:26:32 +00002572 const MachineBasicBlock *LoopHeaderBB,
Kyle Butt0846e562016-10-11 20:36:43 +00002573 BlockChain &Chain, BlockFilterSet *BlockFilter,
2574 MachineFunction::iterator &PrevUnplacedBlockIt) {
2575 bool Removed, DuplicatedToLPred;
2576 bool DuplicatedToOriginalLPred;
2577 Removed = maybeTailDuplicateBlock(BB, LPred, Chain, BlockFilter,
2578 PrevUnplacedBlockIt,
2579 DuplicatedToLPred);
2580 if (!Removed)
2581 return false;
2582 DuplicatedToOriginalLPred = DuplicatedToLPred;
2583 // Iteratively try to duplicate again. It can happen that a block that is
2584 // duplicated into is still small enough to be duplicated again.
2585 // No need to call markBlockSuccessors in this case, as the blocks being
2586 // duplicated from here on are already scheduled.
2587 // Note that DuplicatedToLPred always implies Removed.
2588 while (DuplicatedToLPred) {
Eugene Zelenko5df3d892017-08-24 21:21:39 +00002589 assert(Removed && "Block must have been removed to be duplicated into its "
2590 "layout predecessor.");
Kyle Butt0846e562016-10-11 20:36:43 +00002591 MachineBasicBlock *DupBB, *DupPred;
2592 // The removal callback causes Chain.end() to be updated when a block is
2593 // removed. On the first pass through the loop, the chain end should be the
2594 // same as it was on function entry. On subsequent passes, because we are
2595 // duplicating the block at the end of the chain, if it is removed the
2596 // chain will have shrunk by one block.
2597 BlockChain::iterator ChainEnd = Chain.end();
2598 DupBB = *(--ChainEnd);
2599 // Now try to duplicate again.
2600 if (ChainEnd == Chain.begin())
2601 break;
2602 DupPred = *std::prev(ChainEnd);
2603 Removed = maybeTailDuplicateBlock(DupBB, DupPred, Chain, BlockFilter,
2604 PrevUnplacedBlockIt,
2605 DuplicatedToLPred);
2606 }
2607 // If BB was duplicated into LPred, it is now scheduled. But because it was
2608 // removed, markChainSuccessors won't be called for its chain. Instead we
2609 // call markBlockSuccessors for LPred to achieve the same effect. This must go
2610 // at the end because repeating the tail duplication can increase the number
2611 // of unscheduled predecessors.
2612 LPred = *std::prev(Chain.end());
2613 if (DuplicatedToOriginalLPred)
2614 markBlockSuccessors(Chain, LPred, LoopHeaderBB, BlockFilter);
2615 return true;
2616}
2617
2618/// Tail duplicate \p BB into (some) predecessors if profitable.
2619/// \p BB - Basic block that may be duplicated
2620/// \p LPred - Chosen layout predecessor of \p BB
2621/// \p Chain - Chain to which \p LPred belongs, and \p BB will belong.
2622/// \p BlockFilter - Set of blocks that belong to the loop being laid out.
2623/// Used to identify which blocks to update predecessor
2624/// counts.
2625/// \p PrevUnplacedBlockIt - Iterator pointing to the last block that was
2626/// chosen in the given order due to unnatural CFG
2627/// only needed if \p BB is removed and
2628/// \p PrevUnplacedBlockIt pointed to \p BB.
2629/// \p DuplicatedToLPred - True if the block was duplicated into LPred. Will
2630/// only be true if the block was removed.
2631/// \return - True if the block was duplicated into all preds and removed.
2632bool MachineBlockPlacement::maybeTailDuplicateBlock(
2633 MachineBasicBlock *BB, MachineBasicBlock *LPred,
Kyle Butte9425c4f2017-02-04 02:26:32 +00002634 BlockChain &Chain, BlockFilterSet *BlockFilter,
Kyle Butt0846e562016-10-11 20:36:43 +00002635 MachineFunction::iterator &PrevUnplacedBlockIt,
2636 bool &DuplicatedToLPred) {
Kyle Butt0846e562016-10-11 20:36:43 +00002637 DuplicatedToLPred = false;
Kyle Buttc7d67eef2017-02-04 02:26:34 +00002638 if (!shouldTailDuplicate(BB))
2639 return false;
2640
Kyle Butt0846e562016-10-11 20:36:43 +00002641 DEBUG(dbgs() << "Redoing tail duplication for Succ#"
2642 << BB->getNumber() << "\n");
Kyle Buttb15c0662017-01-31 23:48:32 +00002643
Kyle Butt0846e562016-10-11 20:36:43 +00002644 // This has to be a callback because none of it can be done after
2645 // BB is deleted.
2646 bool Removed = false;
2647 auto RemovalCallback =
2648 [&](MachineBasicBlock *RemBB) {
2649 // Signal to outer function
2650 Removed = true;
2651
2652 // Conservative default.
2653 bool InWorkList = true;
2654 // Remove from the Chain and Chain Map
2655 if (BlockToChain.count(RemBB)) {
2656 BlockChain *Chain = BlockToChain[RemBB];
2657 InWorkList = Chain->UnscheduledPredecessors == 0;
2658 Chain->remove(RemBB);
2659 BlockToChain.erase(RemBB);
2660 }
2661
2662 // Handle the unplaced block iterator
2663 if (&(*PrevUnplacedBlockIt) == RemBB) {
2664 PrevUnplacedBlockIt++;
2665 }
2666
2667 // Handle the Work Lists
2668 if (InWorkList) {
2669 SmallVectorImpl<MachineBasicBlock *> &RemoveList = BlockWorkList;
2670 if (RemBB->isEHPad())
2671 RemoveList = EHPadWorkList;
2672 RemoveList.erase(
Eugene Zelenko5df3d892017-08-24 21:21:39 +00002673 llvm::remove_if(RemoveList,
2674 [RemBB](MachineBasicBlock *BB) {
2675 return BB == RemBB;
2676 }),
Kyle Butt0846e562016-10-11 20:36:43 +00002677 RemoveList.end());
2678 }
2679
2680 // Handle the filter set
2681 if (BlockFilter) {
Rong Xu66827422016-11-16 20:50:06 +00002682 BlockFilter->remove(RemBB);
Kyle Butt0846e562016-10-11 20:36:43 +00002683 }
2684
2685 // Remove the block from loop info.
2686 MLI->removeBlock(RemBB);
Kyle Buttab9cca72016-10-27 21:37:20 +00002687 if (RemBB == PreferredLoopExit)
2688 PreferredLoopExit = nullptr;
Kyle Butt0846e562016-10-11 20:36:43 +00002689
Kyle Butt0846e562016-10-11 20:36:43 +00002690 DEBUG(dbgs() << "TailDuplicator deleted block: "
2691 << getBlockName(RemBB) << "\n");
2692 };
2693 auto RemovalCallbackRef =
Eugene Zelenko5df3d892017-08-24 21:21:39 +00002694 function_ref<void(MachineBasicBlock*)>(RemovalCallback);
Kyle Butt0846e562016-10-11 20:36:43 +00002695
2696 SmallVector<MachineBasicBlock *, 8> DuplicatedPreds;
Kyle Buttb15c0662017-01-31 23:48:32 +00002697 bool IsSimple = TailDup.isSimpleBB(BB);
Kyle Butt0846e562016-10-11 20:36:43 +00002698 TailDup.tailDuplicateAndUpdate(IsSimple, BB, LPred,
2699 &DuplicatedPreds, &RemovalCallbackRef);
2700
2701 // Update UnscheduledPredecessors to reflect tail-duplication.
2702 DuplicatedToLPred = false;
2703 for (MachineBasicBlock *Pred : DuplicatedPreds) {
2704 // We're only looking for unscheduled predecessors that match the filter.
2705 BlockChain* PredChain = BlockToChain[Pred];
2706 if (Pred == LPred)
2707 DuplicatedToLPred = true;
2708 if (Pred == LPred || (BlockFilter && !BlockFilter->count(Pred))
2709 || PredChain == &Chain)
2710 continue;
2711 for (MachineBasicBlock *NewSucc : Pred->successors()) {
2712 if (BlockFilter && !BlockFilter->count(NewSucc))
2713 continue;
2714 BlockChain *NewChain = BlockToChain[NewSucc];
2715 if (NewChain != &Chain && NewChain != PredChain)
2716 NewChain->UnscheduledPredecessors++;
2717 }
2718 }
2719 return Removed;
2720}
2721
Xinliang David Li52530a72016-06-13 22:23:44 +00002722bool MachineBlockPlacement::runOnMachineFunction(MachineFunction &MF) {
Matthias Braunf1caa282017-12-15 22:22:58 +00002723 if (skipFunction(MF.getFunction()))
Andrew Kaylor50271f72016-05-03 22:32:30 +00002724 return false;
2725
Chandler Carruth10281422011-10-21 06:46:38 +00002726 // Check for single-block functions and skip them.
Xinliang David Li52530a72016-06-13 22:23:44 +00002727 if (std::next(MF.begin()) == MF.end())
Chandler Carruth10281422011-10-21 06:46:38 +00002728 return false;
2729
Xinliang David Li52530a72016-06-13 22:23:44 +00002730 F = &MF;
Chandler Carruth10281422011-10-21 06:46:38 +00002731 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
Haicheng Wu5b458cc2016-06-09 15:24:29 +00002732 MBFI = llvm::make_unique<BranchFolder::MBFIWrapper>(
2733 getAnalysis<MachineBlockFrequencyInfo>());
Chandler Carruth8b9737c2011-10-21 08:57:37 +00002734 MLI = &getAnalysis<MachineLoopInfo>();
Xinliang David Li52530a72016-06-13 22:23:44 +00002735 TII = MF.getSubtarget().getInstrInfo();
2736 TLI = MF.getSubtarget().getTargetLowering();
Kyle Buttb15c0662017-01-31 23:48:32 +00002737 MPDT = nullptr;
Eric Christopher690f8e52016-11-01 22:15:50 +00002738
2739 // Initialize PreferredLoopExit to nullptr here since it may never be set if
2740 // there are no MachineLoops.
2741 PreferredLoopExit = nullptr;
2742
Kyle Butt0cf5b2f2017-05-17 23:44:41 +00002743 assert(BlockToChain.empty() &&
2744 "BlockToChain map should be empty before starting placement.");
2745 assert(ComputedEdges.empty() &&
2746 "Computed Edge map should be empty before starting placement.");
Kyle Butt04300b032017-04-12 03:18:20 +00002747
Kyle Butt7d531da2017-05-15 17:30:47 +00002748 unsigned TailDupSize = TailDupPlacementThreshold;
2749 // If only the aggressive threshold is explicitly set, use it.
2750 if (TailDupPlacementAggressiveThreshold.getNumOccurrences() != 0 &&
2751 TailDupPlacementThreshold.getNumOccurrences() == 0)
2752 TailDupSize = TailDupPlacementAggressiveThreshold;
2753
2754 TargetPassConfig *PassConfig = &getAnalysis<TargetPassConfig>();
2755 // For agressive optimization, we can adjust some thresholds to be less
2756 // conservative.
2757 if (PassConfig->getOptLevel() >= CodeGenOpt::Aggressive) {
2758 // At O3 we should be more willing to copy blocks for tail duplication. This
2759 // increases size pressure, so we only do it at O3
2760 // Do this unless only the regular threshold is explicitly set.
2761 if (TailDupPlacementThreshold.getNumOccurrences() == 0 ||
2762 TailDupPlacementAggressiveThreshold.getNumOccurrences() != 0)
2763 TailDupSize = TailDupPlacementAggressiveThreshold;
2764 }
2765
Tim Shen1a8c6772018-03-30 17:51:00 +00002766 if (allowTailDupPlacement()) {
Kyle Buttb15c0662017-01-31 23:48:32 +00002767 MPDT = &getAnalysis<MachinePostDominatorTree>();
Matthias Braunf1caa282017-12-15 22:22:58 +00002768 if (MF.getFunction().optForSize())
Kyle Butt0846e562016-10-11 20:36:43 +00002769 TailDupSize = 1;
Matthias Braun8426d132017-08-23 03:17:59 +00002770 bool PreRegAlloc = false;
2771 TailDup.initMF(MF, PreRegAlloc, MBPI, /* LayoutMode */ true, TailDupSize);
Kyle Butt1fa60302017-03-03 01:00:22 +00002772 precomputeTriangleChains();
Kyle Butt0846e562016-10-11 20:36:43 +00002773 }
2774
Xinliang David Li52530a72016-06-13 22:23:44 +00002775 buildCFGChains();
Haicheng Wu5b458cc2016-06-09 15:24:29 +00002776
2777 // Changing the layout can create new tail merging opportunities.
Haicheng Wu5b458cc2016-06-09 15:24:29 +00002778 // TailMerge can create jump into if branches that make CFG irreducible for
Sjoerd Meijerfd0ad4e2016-07-15 18:41:56 +00002779 // HW that requires structured CFG.
Xinliang David Li52530a72016-06-13 22:23:44 +00002780 bool EnableTailMerge = !MF.getTarget().requiresStructuredCFG() &&
Haicheng Wu5b458cc2016-06-09 15:24:29 +00002781 PassConfig->getEnableTailMerge() &&
2782 BranchFoldPlacement;
2783 // No tail merging opportunities if the block number is less than four.
Xinliang David Li52530a72016-06-13 22:23:44 +00002784 if (MF.size() > 3 && EnableTailMerge) {
Kyle Butt7d531da2017-05-15 17:30:47 +00002785 unsigned TailMergeSize = TailDupSize + 1;
Haicheng Wu5b458cc2016-06-09 15:24:29 +00002786 BranchFolder BF(/*EnableTailMerge=*/true, /*CommonHoist=*/false, *MBFI,
Kyle Butt64e42812016-08-18 18:57:29 +00002787 *MBPI, TailMergeSize);
Haicheng Wu5b458cc2016-06-09 15:24:29 +00002788
Xinliang David Li52530a72016-06-13 22:23:44 +00002789 if (BF.OptimizeFunction(MF, TII, MF.getSubtarget().getRegisterInfo(),
Haicheng Wu5b458cc2016-06-09 15:24:29 +00002790 getAnalysisIfAvailable<MachineModuleInfo>(), MLI,
2791 /*AfterBlockPlacement=*/true)) {
2792 // Redo the layout if tail merging creates/removes/moves blocks.
2793 BlockToChain.clear();
Kyle Butt04300b032017-04-12 03:18:20 +00002794 ComputedEdges.clear();
Kyle Butt13937612017-03-02 21:44:24 +00002795 // Must redo the post-dominator tree if blocks were changed.
Kyle Buttb15c0662017-01-31 23:48:32 +00002796 if (MPDT)
2797 MPDT->runOnMachineFunction(MF);
Haicheng Wu5b458cc2016-06-09 15:24:29 +00002798 ChainAllocator.DestroyAll();
Xinliang David Li52530a72016-06-13 22:23:44 +00002799 buildCFGChains();
Haicheng Wu5b458cc2016-06-09 15:24:29 +00002800 }
2801 }
2802
Xinliang David Li52530a72016-06-13 22:23:44 +00002803 optimizeBranches();
2804 alignBlocks();
Chandler Carruth10281422011-10-21 06:46:38 +00002805
Chandler Carruth10281422011-10-21 06:46:38 +00002806 BlockToChain.clear();
Kyle Butt04300b032017-04-12 03:18:20 +00002807 ComputedEdges.clear();
Chandler Carruthfd9b4d92011-11-14 10:57:23 +00002808 ChainAllocator.DestroyAll();
Chandler Carruth10281422011-10-21 06:46:38 +00002809
Nadav Rotemc0adc9f2013-04-12 01:24:16 +00002810 if (AlignAllBlock)
2811 // Align all of the blocks in the function to a specific alignment.
Xinliang David Li52530a72016-06-13 22:23:44 +00002812 for (MachineBasicBlock &MBB : MF)
Chandler Carruth7a715da2015-03-05 03:19:05 +00002813 MBB.setAlignment(AlignAllBlock);
Geoff Berry10494ac2016-01-21 17:25:52 +00002814 else if (AlignAllNonFallThruBlocks) {
2815 // Align all of the blocks that have no fall-through predecessors to a
2816 // specific alignment.
Xinliang David Li52530a72016-06-13 22:23:44 +00002817 for (auto MBI = std::next(MF.begin()), MBE = MF.end(); MBI != MBE; ++MBI) {
Geoff Berry10494ac2016-01-21 17:25:52 +00002818 auto LayoutPred = std::prev(MBI);
2819 if (!LayoutPred->isSuccessor(&*MBI))
2820 MBI->setAlignment(AlignAllNonFallThruBlocks);
2821 }
2822 }
Xinliang David Lifd3f6452017-01-29 01:57:02 +00002823 if (ViewBlockLayoutWithBFI != GVDT_None &&
2824 (ViewBlockFreqFuncName.empty() ||
Matthias Braunf1caa282017-12-15 22:22:58 +00002825 F->getFunction().getName().equals(ViewBlockFreqFuncName))) {
Xinliang David Li538d6662017-02-15 19:21:04 +00002826 MBFI->view("MBP." + MF.getName(), false);
Xinliang David Lifd3f6452017-01-29 01:57:02 +00002827 }
Xinliang David Lifd3f6452017-01-29 01:57:02 +00002828
Nadav Rotemc0adc9f2013-04-12 01:24:16 +00002829
Chandler Carruth10281422011-10-21 06:46:38 +00002830 // We always return true as we have no way to track whether the final order
2831 // differs from the original order.
2832 return true;
2833}
Chandler Carruthae4e8002011-11-02 07:17:12 +00002834
2835namespace {
Eugene Zelenko5df3d892017-08-24 21:21:39 +00002836
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002837/// A pass to compute block placement statistics.
Chandler Carruthae4e8002011-11-02 07:17:12 +00002838///
2839/// A separate pass to compute interesting statistics for evaluating block
2840/// placement. This is separate from the actual placement pass so that they can
Benjamin Kramerbde91762012-06-02 10:20:22 +00002841/// be computed in the absence of any placement transformations or when using
Chandler Carruthae4e8002011-11-02 07:17:12 +00002842/// alternative placement strategies.
2843class MachineBlockPlacementStats : public MachineFunctionPass {
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002844 /// A handle to the branch probability pass.
Chandler Carruthae4e8002011-11-02 07:17:12 +00002845 const MachineBranchProbabilityInfo *MBPI;
2846
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002847 /// A handle to the function-wide block frequency pass.
Chandler Carruthae4e8002011-11-02 07:17:12 +00002848 const MachineBlockFrequencyInfo *MBFI;
2849
2850public:
2851 static char ID; // Pass identification, replacement for typeid
Eugene Zelenko5df3d892017-08-24 21:21:39 +00002852
Chandler Carruthae4e8002011-11-02 07:17:12 +00002853 MachineBlockPlacementStats() : MachineFunctionPass(ID) {
2854 initializeMachineBlockPlacementStatsPass(*PassRegistry::getPassRegistry());
2855 }
2856
Craig Topper4584cd52014-03-07 09:26:03 +00002857 bool runOnMachineFunction(MachineFunction &F) override;
Chandler Carruthae4e8002011-11-02 07:17:12 +00002858
Craig Topper4584cd52014-03-07 09:26:03 +00002859 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruthae4e8002011-11-02 07:17:12 +00002860 AU.addRequired<MachineBranchProbabilityInfo>();
2861 AU.addRequired<MachineBlockFrequencyInfo>();
2862 AU.setPreservesAll();
2863 MachineFunctionPass::getAnalysisUsage(AU);
2864 }
Chandler Carruthae4e8002011-11-02 07:17:12 +00002865};
Eugene Zelenko5df3d892017-08-24 21:21:39 +00002866
2867} // end anonymous namespace
Chandler Carruthae4e8002011-11-02 07:17:12 +00002868
2869char MachineBlockPlacementStats::ID = 0;
Eugene Zelenko5df3d892017-08-24 21:21:39 +00002870
Andrew Trick1fa5bcb2012-02-08 21:23:13 +00002871char &llvm::MachineBlockPlacementStatsID = MachineBlockPlacementStats::ID;
Eugene Zelenko5df3d892017-08-24 21:21:39 +00002872
Chandler Carruthae4e8002011-11-02 07:17:12 +00002873INITIALIZE_PASS_BEGIN(MachineBlockPlacementStats, "block-placement-stats",
2874 "Basic Block Placement Stats", false, false)
2875INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
2876INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
2877INITIALIZE_PASS_END(MachineBlockPlacementStats, "block-placement-stats",
2878 "Basic Block Placement Stats", false, false)
2879
Chandler Carruthae4e8002011-11-02 07:17:12 +00002880bool MachineBlockPlacementStats::runOnMachineFunction(MachineFunction &F) {
2881 // Check for single-block functions and skip them.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00002882 if (std::next(F.begin()) == F.end())
Chandler Carruthae4e8002011-11-02 07:17:12 +00002883 return false;
2884
2885 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
2886 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
2887
Chandler Carruth7a715da2015-03-05 03:19:05 +00002888 for (MachineBasicBlock &MBB : F) {
2889 BlockFrequency BlockFreq = MBFI->getBlockFreq(&MBB);
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00002890 Statistic &NumBranches =
Chandler Carruth7a715da2015-03-05 03:19:05 +00002891 (MBB.succ_size() > 1) ? NumCondBranches : NumUncondBranches;
Chandler Carruth2fc3fe12015-03-05 02:35:31 +00002892 Statistic &BranchTakenFreq =
Chandler Carruth7a715da2015-03-05 03:19:05 +00002893 (MBB.succ_size() > 1) ? CondBranchTakenFreq : UncondBranchTakenFreq;
2894 for (MachineBasicBlock *Succ : MBB.successors()) {
Chandler Carruthae4e8002011-11-02 07:17:12 +00002895 // Skip if this successor is a fallthrough.
Chandler Carruth7a715da2015-03-05 03:19:05 +00002896 if (MBB.isLayoutSuccessor(Succ))
Chandler Carruthae4e8002011-11-02 07:17:12 +00002897 continue;
2898
Chandler Carruth7a715da2015-03-05 03:19:05 +00002899 BlockFrequency EdgeFreq =
2900 BlockFreq * MBPI->getEdgeProbability(&MBB, Succ);
Chandler Carruthae4e8002011-11-02 07:17:12 +00002901 ++NumBranches;
2902 BranchTakenFreq += EdgeFreq.getFrequency();
2903 }
2904 }
2905
2906 return false;
2907}