1 //===- MachineBlockPlacement.cpp - Basic Block Code Layout optimization ---===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements basic block placement transformations using the CFG
10 // structure and branch probability estimates.
11 //
12 // The pass strives to preserve the structure of the CFG (that is, retain
13 // a topological ordering of basic blocks) in the absence of a *strong* signal
14 // to the contrary from probabilities. However, within the CFG structure, it
15 // attempts to choose an ordering which favors placing more likely sequences of
16 // blocks adjacent to each other.
17 //
18 // The algorithm works from the inner-most loop within a function outward, and
19 // at each stage walks through the basic blocks, trying to coalesce them into
20 // sequential chains where allowed by the CFG (or demanded by heavy
21 // probabilities). Finally, it walks the blocks in topological order, and the
22 // first time it reaches a chain of basic blocks, it schedules them in the
23 // function in-order.
24 //
25 //===----------------------------------------------------------------------===//
26
27 #include "BranchFolding.h"
28 #include "llvm/ADT/ArrayRef.h"
29 #include "llvm/ADT/DenseMap.h"
30 #include "llvm/ADT/STLExtras.h"
31 #include "llvm/ADT/SetVector.h"
32 #include "llvm/ADT/SmallPtrSet.h"
33 #include "llvm/ADT/SmallVector.h"
34 #include "llvm/ADT/Statistic.h"
35 #include "llvm/Analysis/BlockFrequencyInfoImpl.h"
36 #include "llvm/Analysis/ProfileSummaryInfo.h"
37 #include "llvm/CodeGen/MBFIWrapper.h"
38 #include "llvm/CodeGen/MachineBasicBlock.h"
39 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
40 #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
41 #include "llvm/CodeGen/MachineFunction.h"
42 #include "llvm/CodeGen/MachineFunctionPass.h"
43 #include "llvm/CodeGen/MachineLoopInfo.h"
44 #include "llvm/CodeGen/MachinePostDominators.h"
45 #include "llvm/CodeGen/MachineSizeOpts.h"
46 #include "llvm/CodeGen/TailDuplicator.h"
47 #include "llvm/CodeGen/TargetInstrInfo.h"
48 #include "llvm/CodeGen/TargetLowering.h"
49 #include "llvm/CodeGen/TargetPassConfig.h"
50 #include "llvm/CodeGen/TargetSubtargetInfo.h"
51 #include "llvm/IR/DebugLoc.h"
52 #include "llvm/IR/Function.h"
53 #include "llvm/IR/PrintPasses.h"
54 #include "llvm/InitializePasses.h"
55 #include "llvm/Pass.h"
56 #include "llvm/Support/Allocator.h"
57 #include "llvm/Support/BlockFrequency.h"
58 #include "llvm/Support/BranchProbability.h"
59 #include "llvm/Support/CodeGen.h"
60 #include "llvm/Support/CommandLine.h"
61 #include "llvm/Support/Compiler.h"
62 #include "llvm/Support/Debug.h"
63 #include "llvm/Support/raw_ostream.h"
64 #include "llvm/Target/TargetMachine.h"
65 #include "llvm/Transforms/Utils/CodeLayout.h"
66 #include <algorithm>
67 #include <cassert>
68 #include <cstdint>
69 #include <iterator>
70 #include <memory>
71 #include <string>
72 #include <tuple>
73 #include <utility>
74 #include <vector>
75
76 using namespace llvm;
77
78 #define DEBUG_TYPE "block-placement"
79
80 STATISTIC(NumCondBranches, "Number of conditional branches");
81 STATISTIC(NumUncondBranches, "Number of unconditional branches");
82 STATISTIC(CondBranchTakenFreq,
83 "Potential frequency of taking conditional branches");
84 STATISTIC(UncondBranchTakenFreq,
85 "Potential frequency of taking unconditional branches");
86
87 static cl::opt<unsigned> AlignAllBlock(
88 "align-all-blocks",
89 cl::desc("Force the alignment of all blocks in the function in log2 format "
90 "(e.g 4 means align on 16B boundaries)."),
91 cl::init(0), cl::Hidden);
92
93 static cl::opt<unsigned> AlignAllNonFallThruBlocks(
94 "align-all-nofallthru-blocks",
95 cl::desc("Force the alignment of all blocks that have no fall-through "
96 "predecessors (i.e. don't add nops that are executed). In log2 "
97 "format (e.g 4 means align on 16B boundaries)."),
98 cl::init(0), cl::Hidden);
99
100 static cl::opt<unsigned> MaxBytesForAlignmentOverride(
101 "max-bytes-for-alignment",
102 cl::desc("Forces the maximum bytes allowed to be emitted when padding for "
103 "alignment"),
104 cl::init(0), cl::Hidden);
105
106 // FIXME: Find a good default for this flag and remove the flag.
107 static cl::opt<unsigned> ExitBlockBias(
108 "block-placement-exit-block-bias",
109 cl::desc("Block frequency percentage a loop exit block needs "
110 "over the original exit to be considered the new exit."),
111 cl::init(0), cl::Hidden);
112
113 // Definition:
114 // - Outlining: placement of a basic block outside the chain or hot path.
115
116 static cl::opt<unsigned> LoopToColdBlockRatio(
117 "loop-to-cold-block-ratio",
118 cl::desc("Outline loop blocks from loop chain if (frequency of loop) / "
119 "(frequency of block) is greater than this ratio"),
120 cl::init(5), cl::Hidden);
121
122 static cl::opt<bool> ForceLoopColdBlock(
123 "force-loop-cold-block",
124 cl::desc("Force outlining cold blocks from loops."),
125 cl::init(false), cl::Hidden);
126
127 static cl::opt<bool>
128 PreciseRotationCost("precise-rotation-cost",
129 cl::desc("Model the cost of loop rotation more "
130 "precisely by using profile data."),
131 cl::init(false), cl::Hidden);
132
133 static cl::opt<bool>
134 ForcePreciseRotationCost("force-precise-rotation-cost",
135 cl::desc("Force the use of precise cost "
136 "loop rotation strategy."),
137 cl::init(false), cl::Hidden);
138
139 static cl::opt<unsigned> MisfetchCost(
140 "misfetch-cost",
141 cl::desc("Cost that models the probabilistic risk of an instruction "
142 "misfetch due to a jump comparing to falling through, whose cost "
143 "is zero."),
144 cl::init(1), cl::Hidden);
145
146 static cl::opt<unsigned> JumpInstCost("jump-inst-cost",
147 cl::desc("Cost of jump instructions."),
148 cl::init(1), cl::Hidden);
149 static cl::opt<bool>
150 TailDupPlacement("tail-dup-placement",
151 cl::desc("Perform tail duplication during placement. "
152 "Creates more fallthrough opportunites in "
153 "outline branches."),
154 cl::init(true), cl::Hidden);
155
156 static cl::opt<bool>
157 BranchFoldPlacement("branch-fold-placement",
158 cl::desc("Perform branch folding during placement. "
159 "Reduces code size."),
160 cl::init(true), cl::Hidden);
161
162 // Heuristic for tail duplication.
163 static cl::opt<unsigned> TailDupPlacementThreshold(
164 "tail-dup-placement-threshold",
165 cl::desc("Instruction cutoff for tail duplication during layout. "
166 "Tail merging during layout is forced to have a threshold "
167 "that won't conflict."), cl::init(2),
168 cl::Hidden);
169
170 // Heuristic for aggressive tail duplication.
171 static cl::opt<unsigned> TailDupPlacementAggressiveThreshold(
172 "tail-dup-placement-aggressive-threshold",
173 cl::desc("Instruction cutoff for aggressive tail duplication during "
174 "layout. Used at -O3. Tail merging during layout is forced to "
175 "have a threshold that won't conflict."), cl::init(4),
176 cl::Hidden);
177
178 // Heuristic for tail duplication.
179 static cl::opt<unsigned> TailDupPlacementPenalty(
180 "tail-dup-placement-penalty",
181 cl::desc("Cost penalty for blocks that can avoid breaking CFG by copying. "
182 "Copying can increase fallthrough, but it also increases icache "
183 "pressure. This parameter controls the penalty to account for that. "
184 "Percent as integer."),
185 cl::init(2),
186 cl::Hidden);
187
188 // Heuristic for tail duplication if profile count is used in cost model.
189 static cl::opt<unsigned> TailDupProfilePercentThreshold(
190 "tail-dup-profile-percent-threshold",
191 cl::desc("If profile count information is used in tail duplication cost "
192 "model, the gained fall through number from tail duplication "
193 "should be at least this percent of hot count."),
194 cl::init(50), cl::Hidden);
195
196 // Heuristic for triangle chains.
197 static cl::opt<unsigned> TriangleChainCount(
198 "triangle-chain-count",
199 cl::desc("Number of triangle-shaped-CFG's that need to be in a row for the "
200 "triangle tail duplication heuristic to kick in. 0 to disable."),
201 cl::init(2),
202 cl::Hidden);
203
204 extern cl::opt<bool> EnableExtTspBlockPlacement;
205 extern cl::opt<bool> ApplyExtTspWithoutProfile;
206
207 namespace llvm {
208 extern cl::opt<unsigned> StaticLikelyProb;
209 extern cl::opt<unsigned> ProfileLikelyProb;
210
211 // Internal option used to control BFI display only after MBP pass.
212 // Defined in CodeGen/MachineBlockFrequencyInfo.cpp:
213 // -view-block-layout-with-bfi=
214 extern cl::opt<GVDAGType> ViewBlockLayoutWithBFI;
215
216 // Command line option to specify the name of the function for CFG dump
217 // Defined in Analysis/BlockFrequencyInfo.cpp: -view-bfi-func-name=
218 extern cl::opt<std::string> ViewBlockFreqFuncName;
219 } // namespace llvm
220
221 namespace {
222
223 class BlockChain;
224
225 /// Type for our function-wide basic block -> block chain mapping.
226 using BlockToChainMapType = DenseMap<const MachineBasicBlock *, BlockChain *>;
227
228 /// A chain of blocks which will be laid out contiguously.
229 ///
230 /// This is the datastructure representing a chain of consecutive blocks that
231 /// are profitable to layout together in order to maximize fallthrough
232 /// probabilities and code locality. We also can use a block chain to represent
233 /// a sequence of basic blocks which have some external (correctness)
234 /// requirement for sequential layout.
235 ///
236 /// Chains can be built around a single basic block and can be merged to grow
237 /// them. They participate in a block-to-chain mapping, which is updated
238 /// automatically as chains are merged together.
239 class BlockChain {
240 /// The sequence of blocks belonging to this chain.
241 ///
242 /// This is the sequence of blocks for a particular chain. These will be laid
243 /// out in-order within the function.
244 SmallVector<MachineBasicBlock *, 4> Blocks;
245
246 /// A handle to the function-wide basic block to block chain mapping.
247 ///
248 /// This is retained in each block chain to simplify the computation of child
249 /// block chains for SCC-formation and iteration. We store the edges to child
250 /// basic blocks, and map them back to their associated chains using this
251 /// structure.
252 BlockToChainMapType &BlockToChain;
253
254 public:
255 /// Construct a new BlockChain.
256 ///
257 /// This builds a new block chain representing a single basic block in the
258 /// function. It also registers itself as the chain that block participates
259 /// in with the BlockToChain mapping.
BlockChain(BlockToChainMapType & BlockToChain,MachineBasicBlock * BB)260 BlockChain(BlockToChainMapType &BlockToChain, MachineBasicBlock *BB)
261 : Blocks(1, BB), BlockToChain(BlockToChain) {
262 assert(BB && "Cannot create a chain with a null basic block");
263 BlockToChain[BB] = this;
264 }
265
266 /// Iterator over blocks within the chain.
267 using iterator = SmallVectorImpl<MachineBasicBlock *>::iterator;
268 using const_iterator = SmallVectorImpl<MachineBasicBlock *>::const_iterator;
269
270 /// Beginning of blocks within the chain.
begin()271 iterator begin() { return Blocks.begin(); }
begin() const272 const_iterator begin() const { return Blocks.begin(); }
273
274 /// End of blocks within the chain.
end()275 iterator end() { return Blocks.end(); }
end() const276 const_iterator end() const { return Blocks.end(); }
277
remove(MachineBasicBlock * BB)278 bool remove(MachineBasicBlock* BB) {
279 for(iterator i = begin(); i != end(); ++i) {
280 if (*i == BB) {
281 Blocks.erase(i);
282 return true;
283 }
284 }
285 return false;
286 }
287
288 /// Merge a block chain into this one.
289 ///
290 /// This routine merges a block chain into this one. It takes care of forming
291 /// a contiguous sequence of basic blocks, updating the edge list, and
292 /// updating the block -> chain mapping. It does not free or tear down the
293 /// old chain, but the old chain's block list is no longer valid.
merge(MachineBasicBlock * BB,BlockChain * Chain)294 void merge(MachineBasicBlock *BB, BlockChain *Chain) {
295 assert(BB && "Can't merge a null block.");
296 assert(!Blocks.empty() && "Can't merge into an empty chain.");
297
298 // Fast path in case we don't have a chain already.
299 if (!Chain) {
300 assert(!BlockToChain[BB] &&
301 "Passed chain is null, but BB has entry in BlockToChain.");
302 Blocks.push_back(BB);
303 BlockToChain[BB] = this;
304 return;
305 }
306
307 assert(BB == *Chain->begin() && "Passed BB is not head of Chain.");
308 assert(Chain->begin() != Chain->end());
309
310 // Update the incoming blocks to point to this chain, and add them to the
311 // chain structure.
312 for (MachineBasicBlock *ChainBB : *Chain) {
313 Blocks.push_back(ChainBB);
314 assert(BlockToChain[ChainBB] == Chain && "Incoming blocks not in chain.");
315 BlockToChain[ChainBB] = this;
316 }
317 }
318
319 #ifndef NDEBUG
320 /// Dump the blocks in this chain.
dump()321 LLVM_DUMP_METHOD void dump() {
322 for (MachineBasicBlock *MBB : *this)
323 MBB->dump();
324 }
325 #endif // NDEBUG
326
327 /// Count of predecessors of any block within the chain which have not
328 /// yet been scheduled. In general, we will delay scheduling this chain
329 /// until those predecessors are scheduled (or we find a sufficiently good
330 /// reason to override this heuristic.) Note that when forming loop chains,
331 /// blocks outside the loop are ignored and treated as if they were already
332 /// scheduled.
333 ///
334 /// Note: This field is reinitialized multiple times - once for each loop,
335 /// and then once for the function as a whole.
336 unsigned UnscheduledPredecessors = 0;
337 };
338
339 class MachineBlockPlacement : public MachineFunctionPass {
340 /// A type for a block filter set.
341 using BlockFilterSet = SmallSetVector<const MachineBasicBlock *, 16>;
342
343 /// Pair struct containing basic block and taildup profitability
344 struct BlockAndTailDupResult {
345 MachineBasicBlock *BB;
346 bool ShouldTailDup;
347 };
348
349 /// Triple struct containing edge weight and the edge.
350 struct WeightedEdge {
351 BlockFrequency Weight;
352 MachineBasicBlock *Src;
353 MachineBasicBlock *Dest;
354 };
355
356 /// work lists of blocks that are ready to be laid out
357 SmallVector<MachineBasicBlock *, 16> BlockWorkList;
358 SmallVector<MachineBasicBlock *, 16> EHPadWorkList;
359
360 /// Edges that have already been computed as optimal.
361 DenseMap<const MachineBasicBlock *, BlockAndTailDupResult> ComputedEdges;
362
363 /// Machine Function
364 MachineFunction *F;
365
366 /// A handle to the branch probability pass.
367 const MachineBranchProbabilityInfo *MBPI;
368
369 /// A handle to the function-wide block frequency pass.
370 std::unique_ptr<MBFIWrapper> MBFI;
371
372 /// A handle to the loop info.
373 MachineLoopInfo *MLI;
374
375 /// Preferred loop exit.
376 /// Member variable for convenience. It may be removed by duplication deep
377 /// in the call stack.
378 MachineBasicBlock *PreferredLoopExit;
379
380 /// A handle to the target's instruction info.
381 const TargetInstrInfo *TII;
382
383 /// A handle to the target's lowering info.
384 const TargetLoweringBase *TLI;
385
386 /// A handle to the post dominator tree.
387 MachinePostDominatorTree *MPDT;
388
389 ProfileSummaryInfo *PSI;
390
391 /// Duplicator used to duplicate tails during placement.
392 ///
393 /// Placement decisions can open up new tail duplication opportunities, but
394 /// since tail duplication affects placement decisions of later blocks, it
395 /// must be done inline.
396 TailDuplicator TailDup;
397
398 /// Partial tail duplication threshold.
399 BlockFrequency DupThreshold;
400
401 /// True: use block profile count to compute tail duplication cost.
402 /// False: use block frequency to compute tail duplication cost.
403 bool UseProfileCount;
404
405 /// Allocator and owner of BlockChain structures.
406 ///
407 /// We build BlockChains lazily while processing the loop structure of
408 /// a function. To reduce malloc traffic, we allocate them using this
409 /// slab-like allocator, and destroy them after the pass completes. An
410 /// important guarantee is that this allocator produces stable pointers to
411 /// the chains.
412 SpecificBumpPtrAllocator<BlockChain> ChainAllocator;
413
414 /// Function wide BasicBlock to BlockChain mapping.
415 ///
416 /// This mapping allows efficiently moving from any given basic block to the
417 /// BlockChain it participates in, if any. We use it to, among other things,
418 /// allow implicitly defining edges between chains as the existing edges
419 /// between basic blocks.
420 DenseMap<const MachineBasicBlock *, BlockChain *> BlockToChain;
421
422 #ifndef NDEBUG
423 /// The set of basic blocks that have terminators that cannot be fully
424 /// analyzed. These basic blocks cannot be re-ordered safely by
425 /// MachineBlockPlacement, and we must preserve physical layout of these
426 /// blocks and their successors through the pass.
427 SmallPtrSet<MachineBasicBlock *, 4> BlocksWithUnanalyzableExits;
428 #endif
429
430 /// Get block profile count or frequency according to UseProfileCount.
431 /// The return value is used to model tail duplication cost.
getBlockCountOrFrequency(const MachineBasicBlock * BB)432 BlockFrequency getBlockCountOrFrequency(const MachineBasicBlock *BB) {
433 if (UseProfileCount) {
434 auto Count = MBFI->getBlockProfileCount(BB);
435 if (Count)
436 return *Count;
437 else
438 return 0;
439 } else
440 return MBFI->getBlockFreq(BB);
441 }
442
443 /// Scale the DupThreshold according to basic block size.
444 BlockFrequency scaleThreshold(MachineBasicBlock *BB);
445 void initDupThreshold();
446
447 /// Decrease the UnscheduledPredecessors count for all blocks in chain, and
448 /// if the count goes to 0, add them to the appropriate work list.
449 void markChainSuccessors(
450 const BlockChain &Chain, const MachineBasicBlock *LoopHeaderBB,
451 const BlockFilterSet *BlockFilter = nullptr);
452
453 /// Decrease the UnscheduledPredecessors count for a single block, and
454 /// if the count goes to 0, add them to the appropriate work list.
455 void markBlockSuccessors(
456 const BlockChain &Chain, const MachineBasicBlock *BB,
457 const MachineBasicBlock *LoopHeaderBB,
458 const BlockFilterSet *BlockFilter = nullptr);
459
460 BranchProbability
461 collectViableSuccessors(
462 const MachineBasicBlock *BB, const BlockChain &Chain,
463 const BlockFilterSet *BlockFilter,
464 SmallVector<MachineBasicBlock *, 4> &Successors);
465 bool isBestSuccessor(MachineBasicBlock *BB, MachineBasicBlock *Pred,
466 BlockFilterSet *BlockFilter);
467 void findDuplicateCandidates(SmallVectorImpl<MachineBasicBlock *> &Candidates,
468 MachineBasicBlock *BB,
469 BlockFilterSet *BlockFilter);
470 bool repeatedlyTailDuplicateBlock(
471 MachineBasicBlock *BB, MachineBasicBlock *&LPred,
472 const MachineBasicBlock *LoopHeaderBB,
473 BlockChain &Chain, BlockFilterSet *BlockFilter,
474 MachineFunction::iterator &PrevUnplacedBlockIt);
475 bool maybeTailDuplicateBlock(
476 MachineBasicBlock *BB, MachineBasicBlock *LPred,
477 BlockChain &Chain, BlockFilterSet *BlockFilter,
478 MachineFunction::iterator &PrevUnplacedBlockIt,
479 bool &DuplicatedToLPred);
480 bool hasBetterLayoutPredecessor(
481 const MachineBasicBlock *BB, const MachineBasicBlock *Succ,
482 const BlockChain &SuccChain, BranchProbability SuccProb,
483 BranchProbability RealSuccProb, const BlockChain &Chain,
484 const BlockFilterSet *BlockFilter);
485 BlockAndTailDupResult selectBestSuccessor(
486 const MachineBasicBlock *BB, const BlockChain &Chain,
487 const BlockFilterSet *BlockFilter);
488 MachineBasicBlock *selectBestCandidateBlock(
489 const BlockChain &Chain, SmallVectorImpl<MachineBasicBlock *> &WorkList);
490 MachineBasicBlock *getFirstUnplacedBlock(
491 const BlockChain &PlacedChain,
492 MachineFunction::iterator &PrevUnplacedBlockIt,
493 const BlockFilterSet *BlockFilter);
494
495 /// Add a basic block to the work list if it is appropriate.
496 ///
497 /// If the optional parameter BlockFilter is provided, only MBB
498 /// present in the set will be added to the worklist. If nullptr
499 /// is provided, no filtering occurs.
500 void fillWorkLists(const MachineBasicBlock *MBB,
501 SmallPtrSetImpl<BlockChain *> &UpdatedPreds,
502 const BlockFilterSet *BlockFilter);
503
504 void buildChain(const MachineBasicBlock *BB, BlockChain &Chain,
505 BlockFilterSet *BlockFilter = nullptr);
506 bool canMoveBottomBlockToTop(const MachineBasicBlock *BottomBlock,
507 const MachineBasicBlock *OldTop);
508 bool hasViableTopFallthrough(const MachineBasicBlock *Top,
509 const BlockFilterSet &LoopBlockSet);
510 BlockFrequency TopFallThroughFreq(const MachineBasicBlock *Top,
511 const BlockFilterSet &LoopBlockSet);
512 BlockFrequency FallThroughGains(const MachineBasicBlock *NewTop,
513 const MachineBasicBlock *OldTop,
514 const MachineBasicBlock *ExitBB,
515 const BlockFilterSet &LoopBlockSet);
516 MachineBasicBlock *findBestLoopTopHelper(MachineBasicBlock *OldTop,
517 const MachineLoop &L, const BlockFilterSet &LoopBlockSet);
518 MachineBasicBlock *findBestLoopTop(
519 const MachineLoop &L, const BlockFilterSet &LoopBlockSet);
520 MachineBasicBlock *findBestLoopExit(
521 const MachineLoop &L, const BlockFilterSet &LoopBlockSet,
522 BlockFrequency &ExitFreq);
523 BlockFilterSet collectLoopBlockSet(const MachineLoop &L);
524 void buildLoopChains(const MachineLoop &L);
525 void rotateLoop(
526 BlockChain &LoopChain, const MachineBasicBlock *ExitingBB,
527 BlockFrequency ExitFreq, const BlockFilterSet &LoopBlockSet);
528 void rotateLoopWithProfile(
529 BlockChain &LoopChain, const MachineLoop &L,
530 const BlockFilterSet &LoopBlockSet);
531 void buildCFGChains();
532 void optimizeBranches();
533 void alignBlocks();
534 /// Returns true if a block should be tail-duplicated to increase fallthrough
535 /// opportunities.
536 bool shouldTailDuplicate(MachineBasicBlock *BB);
537 /// Check the edge frequencies to see if tail duplication will increase
538 /// fallthroughs.
539 bool isProfitableToTailDup(
540 const MachineBasicBlock *BB, const MachineBasicBlock *Succ,
541 BranchProbability QProb,
542 const BlockChain &Chain, const BlockFilterSet *BlockFilter);
543
544 /// Check for a trellis layout.
545 bool isTrellis(const MachineBasicBlock *BB,
546 const SmallVectorImpl<MachineBasicBlock *> &ViableSuccs,
547 const BlockChain &Chain, const BlockFilterSet *BlockFilter);
548
549 /// Get the best successor given a trellis layout.
550 BlockAndTailDupResult getBestTrellisSuccessor(
551 const MachineBasicBlock *BB,
552 const SmallVectorImpl<MachineBasicBlock *> &ViableSuccs,
553 BranchProbability AdjustedSumProb, const BlockChain &Chain,
554 const BlockFilterSet *BlockFilter);
555
556 /// Get the best pair of non-conflicting edges.
557 static std::pair<WeightedEdge, WeightedEdge> getBestNonConflictingEdges(
558 const MachineBasicBlock *BB,
559 MutableArrayRef<SmallVector<WeightedEdge, 8>> Edges);
560
561 /// Returns true if a block can tail duplicate into all unplaced
562 /// predecessors. Filters based on loop.
563 bool canTailDuplicateUnplacedPreds(
564 const MachineBasicBlock *BB, MachineBasicBlock *Succ,
565 const BlockChain &Chain, const BlockFilterSet *BlockFilter);
566
567 /// Find chains of triangles to tail-duplicate where a global analysis works,
568 /// but a local analysis would not find them.
569 void precomputeTriangleChains();
570
571 /// Apply a post-processing step optimizing block placement.
572 void applyExtTsp();
573
574 /// Modify the existing block placement in the function and adjust all jumps.
575 void assignBlockOrder(const std::vector<const MachineBasicBlock *> &NewOrder);
576
577 /// Create a single CFG chain from the current block order.
578 void createCFGChainExtTsp();
579
580 public:
581 static char ID; // Pass identification, replacement for typeid
582
MachineBlockPlacement()583 MachineBlockPlacement() : MachineFunctionPass(ID) {
584 initializeMachineBlockPlacementPass(*PassRegistry::getPassRegistry());
585 }
586
587 bool runOnMachineFunction(MachineFunction &F) override;
588
allowTailDupPlacement() const589 bool allowTailDupPlacement() const {
590 assert(F);
591 return TailDupPlacement && !F->getTarget().requiresStructuredCFG();
592 }
593
getAnalysisUsage(AnalysisUsage & AU) const594 void getAnalysisUsage(AnalysisUsage &AU) const override {
595 AU.addRequired<MachineBranchProbabilityInfo>();
596 AU.addRequired<MachineBlockFrequencyInfo>();
597 if (TailDupPlacement)
598 AU.addRequired<MachinePostDominatorTree>();
599 AU.addRequired<MachineLoopInfo>();
600 AU.addRequired<ProfileSummaryInfoWrapperPass>();
601 AU.addRequired<TargetPassConfig>();
602 MachineFunctionPass::getAnalysisUsage(AU);
603 }
604 };
605
606 } // end anonymous namespace
607
608 char MachineBlockPlacement::ID = 0;
609
610 char &llvm::MachineBlockPlacementID = MachineBlockPlacement::ID;
611
612 INITIALIZE_PASS_BEGIN(MachineBlockPlacement, DEBUG_TYPE,
613 "Branch Probability Basic Block Placement", false, false)
INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)614 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
615 INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
616 INITIALIZE_PASS_DEPENDENCY(MachinePostDominatorTree)
617 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
618 INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
619 INITIALIZE_PASS_END(MachineBlockPlacement, DEBUG_TYPE,
620 "Branch Probability Basic Block Placement", false, false)
621
622 #ifndef NDEBUG
623 /// Helper to print the name of a MBB.
624 ///
625 /// Only used by debug logging.
626 static std::string getBlockName(const MachineBasicBlock *BB) {
627 std::string Result;
628 raw_string_ostream OS(Result);
629 OS << printMBBReference(*BB);
630 OS << " ('" << BB->getName() << "')";
631 OS.flush();
632 return Result;
633 }
634 #endif
635
636 /// Mark a chain's successors as having one fewer preds.
637 ///
638 /// When a chain is being merged into the "placed" chain, this routine will
639 /// quickly walk the successors of each block in the chain and mark them as
640 /// having one fewer active predecessor. It also adds any successors of this
641 /// chain which reach the zero-predecessor state to the appropriate worklist.
markChainSuccessors(const BlockChain & Chain,const MachineBasicBlock * LoopHeaderBB,const BlockFilterSet * BlockFilter)642 void MachineBlockPlacement::markChainSuccessors(
643 const BlockChain &Chain, const MachineBasicBlock *LoopHeaderBB,
644 const BlockFilterSet *BlockFilter) {
645 // Walk all the blocks in this chain, marking their successors as having
646 // a predecessor placed.
647 for (MachineBasicBlock *MBB : Chain) {
648 markBlockSuccessors(Chain, MBB, LoopHeaderBB, BlockFilter);
649 }
650 }
651
652 /// Mark a single block's successors as having one fewer preds.
653 ///
654 /// Under normal circumstances, this is only called by markChainSuccessors,
655 /// but if a block that was to be placed is completely tail-duplicated away,
656 /// and was duplicated into the chain end, we need to redo markBlockSuccessors
657 /// for just that block.
markBlockSuccessors(const BlockChain & Chain,const MachineBasicBlock * MBB,const MachineBasicBlock * LoopHeaderBB,const BlockFilterSet * BlockFilter)658 void MachineBlockPlacement::markBlockSuccessors(
659 const BlockChain &Chain, const MachineBasicBlock *MBB,
660 const MachineBasicBlock *LoopHeaderBB, const BlockFilterSet *BlockFilter) {
661 // Add any successors for which this is the only un-placed in-loop
662 // predecessor to the worklist as a viable candidate for CFG-neutral
663 // placement. No subsequent placement of this block will violate the CFG
664 // shape, so we get to use heuristics to choose a favorable placement.
665 for (MachineBasicBlock *Succ : MBB->successors()) {
666 if (BlockFilter && !BlockFilter->count(Succ))
667 continue;
668 BlockChain &SuccChain = *BlockToChain[Succ];
669 // Disregard edges within a fixed chain, or edges to the loop header.
670 if (&Chain == &SuccChain || Succ == LoopHeaderBB)
671 continue;
672
673 // This is a cross-chain edge that is within the loop, so decrement the
674 // loop predecessor count of the destination chain.
675 if (SuccChain.UnscheduledPredecessors == 0 ||
676 --SuccChain.UnscheduledPredecessors > 0)
677 continue;
678
679 auto *NewBB = *SuccChain.begin();
680 if (NewBB->isEHPad())
681 EHPadWorkList.push_back(NewBB);
682 else
683 BlockWorkList.push_back(NewBB);
684 }
685 }
686
687 /// This helper function collects the set of successors of block
688 /// \p BB that are allowed to be its layout successors, and return
689 /// the total branch probability of edges from \p BB to those
690 /// blocks.
collectViableSuccessors(const MachineBasicBlock * BB,const BlockChain & Chain,const BlockFilterSet * BlockFilter,SmallVector<MachineBasicBlock *,4> & Successors)691 BranchProbability MachineBlockPlacement::collectViableSuccessors(
692 const MachineBasicBlock *BB, const BlockChain &Chain,
693 const BlockFilterSet *BlockFilter,
694 SmallVector<MachineBasicBlock *, 4> &Successors) {
695 // Adjust edge probabilities by excluding edges pointing to blocks that is
696 // either not in BlockFilter or is already in the current chain. Consider the
697 // following CFG:
698 //
699 // --->A
700 // | / \
701 // | B C
702 // | \ / \
703 // ----D E
704 //
705 // Assume A->C is very hot (>90%), and C->D has a 50% probability, then after
706 // A->C is chosen as a fall-through, D won't be selected as a successor of C
707 // due to CFG constraint (the probability of C->D is not greater than
708 // HotProb to break topo-order). If we exclude E that is not in BlockFilter
709 // when calculating the probability of C->D, D will be selected and we
710 // will get A C D B as the layout of this loop.
711 auto AdjustedSumProb = BranchProbability::getOne();
712 for (MachineBasicBlock *Succ : BB->successors()) {
713 bool SkipSucc = false;
714 if (Succ->isEHPad() || (BlockFilter && !BlockFilter->count(Succ))) {
715 SkipSucc = true;
716 } else {
717 BlockChain *SuccChain = BlockToChain[Succ];
718 if (SuccChain == &Chain) {
719 SkipSucc = true;
720 } else if (Succ != *SuccChain->begin()) {
721 LLVM_DEBUG(dbgs() << " " << getBlockName(Succ)
722 << " -> Mid chain!\n");
723 continue;
724 }
725 }
726 if (SkipSucc)
727 AdjustedSumProb -= MBPI->getEdgeProbability(BB, Succ);
728 else
729 Successors.push_back(Succ);
730 }
731
732 return AdjustedSumProb;
733 }
734
735 /// The helper function returns the branch probability that is adjusted
736 /// or normalized over the new total \p AdjustedSumProb.
737 static BranchProbability
getAdjustedProbability(BranchProbability OrigProb,BranchProbability AdjustedSumProb)738 getAdjustedProbability(BranchProbability OrigProb,
739 BranchProbability AdjustedSumProb) {
740 BranchProbability SuccProb;
741 uint32_t SuccProbN = OrigProb.getNumerator();
742 uint32_t SuccProbD = AdjustedSumProb.getNumerator();
743 if (SuccProbN >= SuccProbD)
744 SuccProb = BranchProbability::getOne();
745 else
746 SuccProb = BranchProbability(SuccProbN, SuccProbD);
747
748 return SuccProb;
749 }
750
751 /// Check if \p BB has exactly the successors in \p Successors.
752 static bool
hasSameSuccessors(MachineBasicBlock & BB,SmallPtrSetImpl<const MachineBasicBlock * > & Successors)753 hasSameSuccessors(MachineBasicBlock &BB,
754 SmallPtrSetImpl<const MachineBasicBlock *> &Successors) {
755 if (BB.succ_size() != Successors.size())
756 return false;
757 // We don't want to count self-loops
758 if (Successors.count(&BB))
759 return false;
760 for (MachineBasicBlock *Succ : BB.successors())
761 if (!Successors.count(Succ))
762 return false;
763 return true;
764 }
765
766 /// Check if a block should be tail duplicated to increase fallthrough
767 /// opportunities.
768 /// \p BB Block to check.
shouldTailDuplicate(MachineBasicBlock * BB)769 bool MachineBlockPlacement::shouldTailDuplicate(MachineBasicBlock *BB) {
770 // Blocks with single successors don't create additional fallthrough
771 // opportunities. Don't duplicate them. TODO: When conditional exits are
772 // analyzable, allow them to be duplicated.
773 bool IsSimple = TailDup.isSimpleBB(BB);
774
775 if (BB->succ_size() == 1)
776 return false;
777 return TailDup.shouldTailDuplicate(IsSimple, *BB);
778 }
779
780 /// Compare 2 BlockFrequency's with a small penalty for \p A.
781 /// In order to be conservative, we apply a X% penalty to account for
782 /// increased icache pressure and static heuristics. For small frequencies
783 /// we use only the numerators to improve accuracy. For simplicity, we assume the
784 /// penalty is less than 100%
785 /// TODO(iteratee): Use 64-bit fixed point edge frequencies everywhere.
greaterWithBias(BlockFrequency A,BlockFrequency B,uint64_t EntryFreq)786 static bool greaterWithBias(BlockFrequency A, BlockFrequency B,
787 uint64_t EntryFreq) {
788 BranchProbability ThresholdProb(TailDupPlacementPenalty, 100);
789 BlockFrequency Gain = A - B;
790 return (Gain / ThresholdProb).getFrequency() >= EntryFreq;
791 }
792
793 /// Check the edge frequencies to see if tail duplication will increase
794 /// fallthroughs. It only makes sense to call this function when
795 /// \p Succ would not be chosen otherwise. Tail duplication of \p Succ is
796 /// always locally profitable if we would have picked \p Succ without
797 /// considering duplication.
isProfitableToTailDup(const MachineBasicBlock * BB,const MachineBasicBlock * Succ,BranchProbability QProb,const BlockChain & Chain,const BlockFilterSet * BlockFilter)798 bool MachineBlockPlacement::isProfitableToTailDup(
799 const MachineBasicBlock *BB, const MachineBasicBlock *Succ,
800 BranchProbability QProb,
801 const BlockChain &Chain, const BlockFilterSet *BlockFilter) {
802 // We need to do a probability calculation to make sure this is profitable.
803 // First: does succ have a successor that post-dominates? This affects the
804 // calculation. The 2 relevant cases are:
805 // BB BB
806 // | \Qout | \Qout
807 // P| C |P C
808 // = C' = C'
809 // | /Qin | /Qin
810 // | / | /
811 // Succ Succ
812 // / \ | \ V
813 // U/ =V |U \
814 // / \ = D
815 // D E | /
816 // | /
817 // |/
818 // PDom
819 // '=' : Branch taken for that CFG edge
820 // In the second case, Placing Succ while duplicating it into C prevents the
821 // fallthrough of Succ into either D or PDom, because they now have C as an
822 // unplaced predecessor
823
824 // Start by figuring out which case we fall into
825 MachineBasicBlock *PDom = nullptr;
826 SmallVector<MachineBasicBlock *, 4> SuccSuccs;
827 // Only scan the relevant successors
828 auto AdjustedSuccSumProb =
829 collectViableSuccessors(Succ, Chain, BlockFilter, SuccSuccs);
830 BranchProbability PProb = MBPI->getEdgeProbability(BB, Succ);
831 auto BBFreq = MBFI->getBlockFreq(BB);
832 auto SuccFreq = MBFI->getBlockFreq(Succ);
833 BlockFrequency P = BBFreq * PProb;
834 BlockFrequency Qout = BBFreq * QProb;
835 uint64_t EntryFreq = MBFI->getEntryFreq();
836 // If there are no more successors, it is profitable to copy, as it strictly
837 // increases fallthrough.
838 if (SuccSuccs.size() == 0)
839 return greaterWithBias(P, Qout, EntryFreq);
840
841 auto BestSuccSucc = BranchProbability::getZero();
842 // Find the PDom or the best Succ if no PDom exists.
843 for (MachineBasicBlock *SuccSucc : SuccSuccs) {
844 auto Prob = MBPI->getEdgeProbability(Succ, SuccSucc);
845 if (Prob > BestSuccSucc)
846 BestSuccSucc = Prob;
847 if (PDom == nullptr)
848 if (MPDT->dominates(SuccSucc, Succ)) {
849 PDom = SuccSucc;
850 break;
851 }
852 }
853 // For the comparisons, we need to know Succ's best incoming edge that isn't
854 // from BB.
855 auto SuccBestPred = BlockFrequency(0);
856 for (MachineBasicBlock *SuccPred : Succ->predecessors()) {
857 if (SuccPred == Succ || SuccPred == BB
858 || BlockToChain[SuccPred] == &Chain
859 || (BlockFilter && !BlockFilter->count(SuccPred)))
860 continue;
861 auto Freq = MBFI->getBlockFreq(SuccPred)
862 * MBPI->getEdgeProbability(SuccPred, Succ);
863 if (Freq > SuccBestPred)
864 SuccBestPred = Freq;
865 }
866 // Qin is Succ's best unplaced incoming edge that isn't BB
867 BlockFrequency Qin = SuccBestPred;
868 // If it doesn't have a post-dominating successor, here is the calculation:
869 // BB BB
870 // | \Qout | \
871 // P| C | =
872 // = C' | C
873 // | /Qin | |
874 // | / | C' (+Succ)
875 // Succ Succ /|
876 // / \ | \/ |
877 // U/ =V | == |
878 // / \ | / \|
879 // D E D E
880 // '=' : Branch taken for that CFG edge
881 // Cost in the first case is: P + V
882 // For this calculation, we always assume P > Qout. If Qout > P
883 // The result of this function will be ignored at the caller.
884 // Let F = SuccFreq - Qin
885 // Cost in the second case is: Qout + min(Qin, F) * U + max(Qin, F) * V
886
887 if (PDom == nullptr || !Succ->isSuccessor(PDom)) {
888 BranchProbability UProb = BestSuccSucc;
889 BranchProbability VProb = AdjustedSuccSumProb - UProb;
890 BlockFrequency F = SuccFreq - Qin;
891 BlockFrequency V = SuccFreq * VProb;
892 BlockFrequency QinU = std::min(Qin, F) * UProb;
893 BlockFrequency BaseCost = P + V;
894 BlockFrequency DupCost = Qout + QinU + std::max(Qin, F) * VProb;
895 return greaterWithBias(BaseCost, DupCost, EntryFreq);
896 }
897 BranchProbability UProb = MBPI->getEdgeProbability(Succ, PDom);
898 BranchProbability VProb = AdjustedSuccSumProb - UProb;
899 BlockFrequency U = SuccFreq * UProb;
900 BlockFrequency V = SuccFreq * VProb;
901 BlockFrequency F = SuccFreq - Qin;
902 // If there is a post-dominating successor, here is the calculation:
903 // BB BB BB BB
904 // | \Qout | \ | \Qout | \
905 // |P C | = |P C | =
906 // = C' |P C = C' |P C
907 // | /Qin | | | /Qin | |
908 // | / | C' (+Succ) | / | C' (+Succ)
909 // Succ Succ /| Succ Succ /|
910 // | \ V | \/ | | \ V | \/ |
911 // |U \ |U /\ =? |U = |U /\ |
912 // = D = = =?| | D | = =|
913 // | / |/ D | / |/ D
914 // | / | / | = | /
915 // |/ | / |/ | =
916 // Dom Dom Dom Dom
917 // '=' : Branch taken for that CFG edge
918 // The cost for taken branches in the first case is P + U
919 // Let F = SuccFreq - Qin
920 // The cost in the second case (assuming independence), given the layout:
921 // BB, Succ, (C+Succ), D, Dom or the layout:
922 // BB, Succ, D, Dom, (C+Succ)
923 // is Qout + max(F, Qin) * U + min(F, Qin)
924 // compare P + U vs Qout + P * U + Qin.
925 //
926 // The 3rd and 4th cases cover when Dom would be chosen to follow Succ.
927 //
928 // For the 3rd case, the cost is P + 2 * V
929 // For the 4th case, the cost is Qout + min(Qin, F) * U + max(Qin, F) * V + V
930 // We choose 4 over 3 when (P + V) > Qout + min(Qin, F) * U + max(Qin, F) * V
931 if (UProb > AdjustedSuccSumProb / 2 &&
932 !hasBetterLayoutPredecessor(Succ, PDom, *BlockToChain[PDom], UProb, UProb,
933 Chain, BlockFilter))
934 // Cases 3 & 4
935 return greaterWithBias(
936 (P + V), (Qout + std::max(Qin, F) * VProb + std::min(Qin, F) * UProb),
937 EntryFreq);
938 // Cases 1 & 2
939 return greaterWithBias((P + U),
940 (Qout + std::min(Qin, F) * AdjustedSuccSumProb +
941 std::max(Qin, F) * UProb),
942 EntryFreq);
943 }
944
945 /// Check for a trellis layout. \p BB is the upper part of a trellis if its
946 /// successors form the lower part of a trellis. A successor set S forms the
947 /// lower part of a trellis if all of the predecessors of S are either in S or
948 /// have all of S as successors. We ignore trellises where BB doesn't have 2
949 /// successors because for fewer than 2, it's trivial, and for 3 or greater they
950 /// are very uncommon and complex to compute optimally. Allowing edges within S
951 /// is not strictly a trellis, but the same algorithm works, so we allow it.
isTrellis(const MachineBasicBlock * BB,const SmallVectorImpl<MachineBasicBlock * > & ViableSuccs,const BlockChain & Chain,const BlockFilterSet * BlockFilter)952 bool MachineBlockPlacement::isTrellis(
953 const MachineBasicBlock *BB,
954 const SmallVectorImpl<MachineBasicBlock *> &ViableSuccs,
955 const BlockChain &Chain, const BlockFilterSet *BlockFilter) {
956 // Technically BB could form a trellis with branching factor higher than 2.
957 // But that's extremely uncommon.
958 if (BB->succ_size() != 2 || ViableSuccs.size() != 2)
959 return false;
960
961 SmallPtrSet<const MachineBasicBlock *, 2> Successors(BB->succ_begin(),
962 BB->succ_end());
963 // To avoid reviewing the same predecessors twice.
964 SmallPtrSet<const MachineBasicBlock *, 8> SeenPreds;
965
966 for (MachineBasicBlock *Succ : ViableSuccs) {
967 int PredCount = 0;
968 for (auto *SuccPred : Succ->predecessors()) {
969 // Allow triangle successors, but don't count them.
970 if (Successors.count(SuccPred)) {
971 // Make sure that it is actually a triangle.
972 for (MachineBasicBlock *CheckSucc : SuccPred->successors())
973 if (!Successors.count(CheckSucc))
974 return false;
975 continue;
976 }
977 const BlockChain *PredChain = BlockToChain[SuccPred];
978 if (SuccPred == BB || (BlockFilter && !BlockFilter->count(SuccPred)) ||
979 PredChain == &Chain || PredChain == BlockToChain[Succ])
980 continue;
981 ++PredCount;
982 // Perform the successor check only once.
983 if (!SeenPreds.insert(SuccPred).second)
984 continue;
985 if (!hasSameSuccessors(*SuccPred, Successors))
986 return false;
987 }
988 // If one of the successors has only BB as a predecessor, it is not a
989 // trellis.
990 if (PredCount < 1)
991 return false;
992 }
993 return true;
994 }
995
996 /// Pick the highest total weight pair of edges that can both be laid out.
997 /// The edges in \p Edges[0] are assumed to have a different destination than
998 /// the edges in \p Edges[1]. Simple counting shows that the best pair is either
999 /// the individual highest weight edges to the 2 different destinations, or in
1000 /// case of a conflict, one of them should be replaced with a 2nd best edge.
1001 std::pair<MachineBlockPlacement::WeightedEdge,
1002 MachineBlockPlacement::WeightedEdge>
getBestNonConflictingEdges(const MachineBasicBlock * BB,MutableArrayRef<SmallVector<MachineBlockPlacement::WeightedEdge,8>> Edges)1003 MachineBlockPlacement::getBestNonConflictingEdges(
1004 const MachineBasicBlock *BB,
1005 MutableArrayRef<SmallVector<MachineBlockPlacement::WeightedEdge, 8>>
1006 Edges) {
1007 // Sort the edges, and then for each successor, find the best incoming
1008 // predecessor. If the best incoming predecessors aren't the same,
1009 // then that is clearly the best layout. If there is a conflict, one of the
1010 // successors will have to fallthrough from the second best predecessor. We
1011 // compare which combination is better overall.
1012
1013 // Sort for highest frequency.
1014 auto Cmp = [](WeightedEdge A, WeightedEdge B) { return A.Weight > B.Weight; };
1015
1016 llvm::stable_sort(Edges[0], Cmp);
1017 llvm::stable_sort(Edges[1], Cmp);
1018 auto BestA = Edges[0].begin();
1019 auto BestB = Edges[1].begin();
1020 // Arrange for the correct answer to be in BestA and BestB
1021 // If the 2 best edges don't conflict, the answer is already there.
1022 if (BestA->Src == BestB->Src) {
1023 // Compare the total fallthrough of (Best + Second Best) for both pairs
1024 auto SecondBestA = std::next(BestA);
1025 auto SecondBestB = std::next(BestB);
1026 BlockFrequency BestAScore = BestA->Weight + SecondBestB->Weight;
1027 BlockFrequency BestBScore = BestB->Weight + SecondBestA->Weight;
1028 if (BestAScore < BestBScore)
1029 BestA = SecondBestA;
1030 else
1031 BestB = SecondBestB;
1032 }
1033 // Arrange for the BB edge to be in BestA if it exists.
1034 if (BestB->Src == BB)
1035 std::swap(BestA, BestB);
1036 return std::make_pair(*BestA, *BestB);
1037 }
1038
1039 /// Get the best successor from \p BB based on \p BB being part of a trellis.
1040 /// We only handle trellises with 2 successors, so the algorithm is
1041 /// straightforward: Find the best pair of edges that don't conflict. We find
1042 /// the best incoming edge for each successor in the trellis. If those conflict,
1043 /// we consider which of them should be replaced with the second best.
1044 /// Upon return the two best edges will be in \p BestEdges. If one of the edges
1045 /// comes from \p BB, it will be in \p BestEdges[0]
1046 MachineBlockPlacement::BlockAndTailDupResult
getBestTrellisSuccessor(const MachineBasicBlock * BB,const SmallVectorImpl<MachineBasicBlock * > & ViableSuccs,BranchProbability AdjustedSumProb,const BlockChain & Chain,const BlockFilterSet * BlockFilter)1047 MachineBlockPlacement::getBestTrellisSuccessor(
1048 const MachineBasicBlock *BB,
1049 const SmallVectorImpl<MachineBasicBlock *> &ViableSuccs,
1050 BranchProbability AdjustedSumProb, const BlockChain &Chain,
1051 const BlockFilterSet *BlockFilter) {
1052
1053 BlockAndTailDupResult Result = {nullptr, false};
1054 SmallPtrSet<const MachineBasicBlock *, 4> Successors(BB->succ_begin(),
1055 BB->succ_end());
1056
1057 // We assume size 2 because it's common. For general n, we would have to do
1058 // the Hungarian algorithm, but it's not worth the complexity because more
1059 // than 2 successors is fairly uncommon, and a trellis even more so.
1060 if (Successors.size() != 2 || ViableSuccs.size() != 2)
1061 return Result;
1062
1063 // Collect the edge frequencies of all edges that form the trellis.
1064 SmallVector<WeightedEdge, 8> Edges[2];
1065 int SuccIndex = 0;
1066 for (auto *Succ : ViableSuccs) {
1067 for (MachineBasicBlock *SuccPred : Succ->predecessors()) {
1068 // Skip any placed predecessors that are not BB
1069 if (SuccPred != BB)
1070 if ((BlockFilter && !BlockFilter->count(SuccPred)) ||
1071 BlockToChain[SuccPred] == &Chain ||
1072 BlockToChain[SuccPred] == BlockToChain[Succ])
1073 continue;
1074 BlockFrequency EdgeFreq = MBFI->getBlockFreq(SuccPred) *
1075 MBPI->getEdgeProbability(SuccPred, Succ);
1076 Edges[SuccIndex].push_back({EdgeFreq, SuccPred, Succ});
1077 }
1078 ++SuccIndex;
1079 }
1080
1081 // Pick the best combination of 2 edges from all the edges in the trellis.
1082 WeightedEdge BestA, BestB;
1083 std::tie(BestA, BestB) = getBestNonConflictingEdges(BB, Edges);
1084
1085 if (BestA.Src != BB) {
1086 // If we have a trellis, and BB doesn't have the best fallthrough edges,
1087 // we shouldn't choose any successor. We've already looked and there's a
1088 // better fallthrough edge for all the successors.
1089 LLVM_DEBUG(dbgs() << "Trellis, but not one of the chosen edges.\n");
1090 return Result;
1091 }
1092
1093 // Did we pick the triangle edge? If tail-duplication is profitable, do
1094 // that instead. Otherwise merge the triangle edge now while we know it is
1095 // optimal.
1096 if (BestA.Dest == BestB.Src) {
1097 // The edges are BB->Succ1->Succ2, and we're looking to see if BB->Succ2
1098 // would be better.
1099 MachineBasicBlock *Succ1 = BestA.Dest;
1100 MachineBasicBlock *Succ2 = BestB.Dest;
1101 // Check to see if tail-duplication would be profitable.
1102 if (allowTailDupPlacement() && shouldTailDuplicate(Succ2) &&
1103 canTailDuplicateUnplacedPreds(BB, Succ2, Chain, BlockFilter) &&
1104 isProfitableToTailDup(BB, Succ2, MBPI->getEdgeProbability(BB, Succ1),
1105 Chain, BlockFilter)) {
1106 LLVM_DEBUG(BranchProbability Succ2Prob = getAdjustedProbability(
1107 MBPI->getEdgeProbability(BB, Succ2), AdjustedSumProb);
1108 dbgs() << " Selected: " << getBlockName(Succ2)
1109 << ", probability: " << Succ2Prob
1110 << " (Tail Duplicate)\n");
1111 Result.BB = Succ2;
1112 Result.ShouldTailDup = true;
1113 return Result;
1114 }
1115 }
1116 // We have already computed the optimal edge for the other side of the
1117 // trellis.
1118 ComputedEdges[BestB.Src] = { BestB.Dest, false };
1119
1120 auto TrellisSucc = BestA.Dest;
1121 LLVM_DEBUG(BranchProbability SuccProb = getAdjustedProbability(
1122 MBPI->getEdgeProbability(BB, TrellisSucc), AdjustedSumProb);
1123 dbgs() << " Selected: " << getBlockName(TrellisSucc)
1124 << ", probability: " << SuccProb << " (Trellis)\n");
1125 Result.BB = TrellisSucc;
1126 return Result;
1127 }
1128
1129 /// When the option allowTailDupPlacement() is on, this method checks if the
1130 /// fallthrough candidate block \p Succ (of block \p BB) can be tail-duplicated
1131 /// into all of its unplaced, unfiltered predecessors, that are not BB.
canTailDuplicateUnplacedPreds(const MachineBasicBlock * BB,MachineBasicBlock * Succ,const BlockChain & Chain,const BlockFilterSet * BlockFilter)1132 bool MachineBlockPlacement::canTailDuplicateUnplacedPreds(
1133 const MachineBasicBlock *BB, MachineBasicBlock *Succ,
1134 const BlockChain &Chain, const BlockFilterSet *BlockFilter) {
1135 if (!shouldTailDuplicate(Succ))
1136 return false;
1137
1138 // The result of canTailDuplicate.
1139 bool Duplicate = true;
1140 // Number of possible duplication.
1141 unsigned int NumDup = 0;
1142
1143 // For CFG checking.
1144 SmallPtrSet<const MachineBasicBlock *, 4> Successors(BB->succ_begin(),
1145 BB->succ_end());
1146 for (MachineBasicBlock *Pred : Succ->predecessors()) {
1147 // Make sure all unplaced and unfiltered predecessors can be
1148 // tail-duplicated into.
1149 // Skip any blocks that are already placed or not in this loop.
1150 if (Pred == BB || (BlockFilter && !BlockFilter->count(Pred))
1151 || BlockToChain[Pred] == &Chain)
1152 continue;
1153 if (!TailDup.canTailDuplicate(Succ, Pred)) {
1154 if (Successors.size() > 1 && hasSameSuccessors(*Pred, Successors))
1155 // This will result in a trellis after tail duplication, so we don't
1156 // need to copy Succ into this predecessor. In the presence
1157 // of a trellis tail duplication can continue to be profitable.
1158 // For example:
1159 // A A
1160 // |\ |\
1161 // | \ | \
1162 // | C | C+BB
1163 // | / | |
1164 // |/ | |
1165 // BB => BB |
1166 // |\ |\/|
1167 // | \ |/\|
1168 // | D | D
1169 // | / | /
1170 // |/ |/
1171 // Succ Succ
1172 //
1173 // After BB was duplicated into C, the layout looks like the one on the
1174 // right. BB and C now have the same successors. When considering
1175 // whether Succ can be duplicated into all its unplaced predecessors, we
1176 // ignore C.
1177 // We can do this because C already has a profitable fallthrough, namely
1178 // D. TODO(iteratee): ignore sufficiently cold predecessors for
1179 // duplication and for this test.
1180 //
1181 // This allows trellises to be laid out in 2 separate chains
1182 // (A,B,Succ,...) and later (C,D,...) This is a reasonable heuristic
1183 // because it allows the creation of 2 fallthrough paths with links
1184 // between them, and we correctly identify the best layout for these
1185 // CFGs. We want to extend trellises that the user created in addition
1186 // to trellises created by tail-duplication, so we just look for the
1187 // CFG.
1188 continue;
1189 Duplicate = false;
1190 continue;
1191 }
1192 NumDup++;
1193 }
1194
1195 // No possible duplication in current filter set.
1196 if (NumDup == 0)
1197 return false;
1198
1199 // If profile information is available, findDuplicateCandidates can do more
1200 // precise benefit analysis.
1201 if (F->getFunction().hasProfileData())
1202 return true;
1203
1204 // This is mainly for function exit BB.
1205 // The integrated tail duplication is really designed for increasing
1206 // fallthrough from predecessors from Succ to its successors. We may need
1207 // other machanism to handle different cases.
1208 if (Succ->succ_empty())
1209 return true;
1210
1211 // Plus the already placed predecessor.
1212 NumDup++;
1213
1214 // If the duplication candidate has more unplaced predecessors than
1215 // successors, the extra duplication can't bring more fallthrough.
1216 //
1217 // Pred1 Pred2 Pred3
1218 // \ | /
1219 // \ | /
1220 // \ | /
1221 // Dup
1222 // / \
1223 // / \
1224 // Succ1 Succ2
1225 //
1226 // In this example Dup has 2 successors and 3 predecessors, duplication of Dup
1227 // can increase the fallthrough from Pred1 to Succ1 and from Pred2 to Succ2,
1228 // but the duplication into Pred3 can't increase fallthrough.
1229 //
1230 // A small number of extra duplication may not hurt too much. We need a better
1231 // heuristic to handle it.
1232 if ((NumDup > Succ->succ_size()) || !Duplicate)
1233 return false;
1234
1235 return true;
1236 }
1237
1238 /// Find chains of triangles where we believe it would be profitable to
1239 /// tail-duplicate them all, but a local analysis would not find them.
1240 /// There are 3 ways this can be profitable:
1241 /// 1) The post-dominators marked 50% are actually taken 55% (This shrinks with
1242 /// longer chains)
1243 /// 2) The chains are statically correlated. Branch probabilities have a very
1244 /// U-shaped distribution.
1245 /// [http://nrs.harvard.edu/urn-3:HUL.InstRepos:24015805]
1246 /// If the branches in a chain are likely to be from the same side of the
1247 /// distribution as their predecessor, but are independent at runtime, this
1248 /// transformation is profitable. (Because the cost of being wrong is a small
1249 /// fixed cost, unlike the standard triangle layout where the cost of being
1250 /// wrong scales with the # of triangles.)
1251 /// 3) The chains are dynamically correlated. If the probability that a previous
1252 /// branch was taken positively influences whether the next branch will be
1253 /// taken
1254 /// We believe that 2 and 3 are common enough to justify the small margin in 1.
precomputeTriangleChains()1255 void MachineBlockPlacement::precomputeTriangleChains() {
1256 struct TriangleChain {
1257 std::vector<MachineBasicBlock *> Edges;
1258
1259 TriangleChain(MachineBasicBlock *src, MachineBasicBlock *dst)
1260 : Edges({src, dst}) {}
1261
1262 void append(MachineBasicBlock *dst) {
1263 assert(getKey()->isSuccessor(dst) &&
1264 "Attempting to append a block that is not a successor.");
1265 Edges.push_back(dst);
1266 }
1267
1268 unsigned count() const { return Edges.size() - 1; }
1269
1270 MachineBasicBlock *getKey() const {
1271 return Edges.back();
1272 }
1273 };
1274
1275 if (TriangleChainCount == 0)
1276 return;
1277
1278 LLVM_DEBUG(dbgs() << "Pre-computing triangle chains.\n");
1279 // Map from last block to the chain that contains it. This allows us to extend
1280 // chains as we find new triangles.
1281 DenseMap<const MachineBasicBlock *, TriangleChain> TriangleChainMap;
1282 for (MachineBasicBlock &BB : *F) {
1283 // If BB doesn't have 2 successors, it doesn't start a triangle.
1284 if (BB.succ_size() != 2)
1285 continue;
1286 MachineBasicBlock *PDom = nullptr;
1287 for (MachineBasicBlock *Succ : BB.successors()) {
1288 if (!MPDT->dominates(Succ, &BB))
1289 continue;
1290 PDom = Succ;
1291 break;
1292 }
1293 // If BB doesn't have a post-dominating successor, it doesn't form a
1294 // triangle.
1295 if (PDom == nullptr)
1296 continue;
1297 // If PDom has a hint that it is low probability, skip this triangle.
1298 if (MBPI->getEdgeProbability(&BB, PDom) < BranchProbability(50, 100))
1299 continue;
1300 // If PDom isn't eligible for duplication, this isn't the kind of triangle
1301 // we're looking for.
1302 if (!shouldTailDuplicate(PDom))
1303 continue;
1304 bool CanTailDuplicate = true;
1305 // If PDom can't tail-duplicate into it's non-BB predecessors, then this
1306 // isn't the kind of triangle we're looking for.
1307 for (MachineBasicBlock* Pred : PDom->predecessors()) {
1308 if (Pred == &BB)
1309 continue;
1310 if (!TailDup.canTailDuplicate(PDom, Pred)) {
1311 CanTailDuplicate = false;
1312 break;
1313 }
1314 }
1315 // If we can't tail-duplicate PDom to its predecessors, then skip this
1316 // triangle.
1317 if (!CanTailDuplicate)
1318 continue;
1319
1320 // Now we have an interesting triangle. Insert it if it's not part of an
1321 // existing chain.
1322 // Note: This cannot be replaced with a call insert() or emplace() because
1323 // the find key is BB, but the insert/emplace key is PDom.
1324 auto Found = TriangleChainMap.find(&BB);
1325 // If it is, remove the chain from the map, grow it, and put it back in the
1326 // map with the end as the new key.
1327 if (Found != TriangleChainMap.end()) {
1328 TriangleChain Chain = std::move(Found->second);
1329 TriangleChainMap.erase(Found);
1330 Chain.append(PDom);
1331 TriangleChainMap.insert(std::make_pair(Chain.getKey(), std::move(Chain)));
1332 } else {
1333 auto InsertResult = TriangleChainMap.try_emplace(PDom, &BB, PDom);
1334 assert(InsertResult.second && "Block seen twice.");
1335 (void)InsertResult;
1336 }
1337 }
1338
1339 // Iterating over a DenseMap is safe here, because the only thing in the body
1340 // of the loop is inserting into another DenseMap (ComputedEdges).
1341 // ComputedEdges is never iterated, so this doesn't lead to non-determinism.
1342 for (auto &ChainPair : TriangleChainMap) {
1343 TriangleChain &Chain = ChainPair.second;
1344 // Benchmarking has shown that due to branch correlation duplicating 2 or
1345 // more triangles is profitable, despite the calculations assuming
1346 // independence.
1347 if (Chain.count() < TriangleChainCount)
1348 continue;
1349 MachineBasicBlock *dst = Chain.Edges.back();
1350 Chain.Edges.pop_back();
1351 for (MachineBasicBlock *src : reverse(Chain.Edges)) {
1352 LLVM_DEBUG(dbgs() << "Marking edge: " << getBlockName(src) << "->"
1353 << getBlockName(dst)
1354 << " as pre-computed based on triangles.\n");
1355
1356 auto InsertResult = ComputedEdges.insert({src, {dst, true}});
1357 assert(InsertResult.second && "Block seen twice.");
1358 (void)InsertResult;
1359
1360 dst = src;
1361 }
1362 }
1363 }
1364
1365 // When profile is not present, return the StaticLikelyProb.
1366 // When profile is available, we need to handle the triangle-shape CFG.
getLayoutSuccessorProbThreshold(const MachineBasicBlock * BB)1367 static BranchProbability getLayoutSuccessorProbThreshold(
1368 const MachineBasicBlock *BB) {
1369 if (!BB->getParent()->getFunction().hasProfileData())
1370 return BranchProbability(StaticLikelyProb, 100);
1371 if (BB->succ_size() == 2) {
1372 const MachineBasicBlock *Succ1 = *BB->succ_begin();
1373 const MachineBasicBlock *Succ2 = *(BB->succ_begin() + 1);
1374 if (Succ1->isSuccessor(Succ2) || Succ2->isSuccessor(Succ1)) {
1375 /* See case 1 below for the cost analysis. For BB->Succ to
1376 * be taken with smaller cost, the following needs to hold:
1377 * Prob(BB->Succ) > 2 * Prob(BB->Pred)
1378 * So the threshold T in the calculation below
1379 * (1-T) * Prob(BB->Succ) > T * Prob(BB->Pred)
1380 * So T / (1 - T) = 2, Yielding T = 2/3
1381 * Also adding user specified branch bias, we have
1382 * T = (2/3)*(ProfileLikelyProb/50)
1383 * = (2*ProfileLikelyProb)/150)
1384 */
1385 return BranchProbability(2 * ProfileLikelyProb, 150);
1386 }
1387 }
1388 return BranchProbability(ProfileLikelyProb, 100);
1389 }
1390
1391 /// Checks to see if the layout candidate block \p Succ has a better layout
1392 /// predecessor than \c BB. If yes, returns true.
1393 /// \p SuccProb: The probability adjusted for only remaining blocks.
1394 /// Only used for logging
1395 /// \p RealSuccProb: The un-adjusted probability.
1396 /// \p Chain: The chain that BB belongs to and Succ is being considered for.
1397 /// \p BlockFilter: if non-null, the set of blocks that make up the loop being
1398 /// considered
hasBetterLayoutPredecessor(const MachineBasicBlock * BB,const MachineBasicBlock * Succ,const BlockChain & SuccChain,BranchProbability SuccProb,BranchProbability RealSuccProb,const BlockChain & Chain,const BlockFilterSet * BlockFilter)1399 bool MachineBlockPlacement::hasBetterLayoutPredecessor(
1400 const MachineBasicBlock *BB, const MachineBasicBlock *Succ,
1401 const BlockChain &SuccChain, BranchProbability SuccProb,
1402 BranchProbability RealSuccProb, const BlockChain &Chain,
1403 const BlockFilterSet *BlockFilter) {
1404
1405 // There isn't a better layout when there are no unscheduled predecessors.
1406 if (SuccChain.UnscheduledPredecessors == 0)
1407 return false;
1408
1409 // There are two basic scenarios here:
1410 // -------------------------------------
1411 // Case 1: triangular shape CFG (if-then):
1412 // BB
1413 // | \
1414 // | \
1415 // | Pred
1416 // | /
1417 // Succ
1418 // In this case, we are evaluating whether to select edge -> Succ, e.g.
1419 // set Succ as the layout successor of BB. Picking Succ as BB's
1420 // successor breaks the CFG constraints (FIXME: define these constraints).
1421 // With this layout, Pred BB
1422 // is forced to be outlined, so the overall cost will be cost of the
1423 // branch taken from BB to Pred, plus the cost of back taken branch
1424 // from Pred to Succ, as well as the additional cost associated
1425 // with the needed unconditional jump instruction from Pred To Succ.
1426
1427 // The cost of the topological order layout is the taken branch cost
1428 // from BB to Succ, so to make BB->Succ a viable candidate, the following
1429 // must hold:
1430 // 2 * freq(BB->Pred) * taken_branch_cost + unconditional_jump_cost
1431 // < freq(BB->Succ) * taken_branch_cost.
1432 // Ignoring unconditional jump cost, we get
1433 // freq(BB->Succ) > 2 * freq(BB->Pred), i.e.,
1434 // prob(BB->Succ) > 2 * prob(BB->Pred)
1435 //
1436 // When real profile data is available, we can precisely compute the
1437 // probability threshold that is needed for edge BB->Succ to be considered.
1438 // Without profile data, the heuristic requires the branch bias to be
1439 // a lot larger to make sure the signal is very strong (e.g. 80% default).
1440 // -----------------------------------------------------------------
1441 // Case 2: diamond like CFG (if-then-else):
1442 // S
1443 // / \
1444 // | \
1445 // BB Pred
1446 // \ /
1447 // Succ
1448 // ..
1449 //
1450 // The current block is BB and edge BB->Succ is now being evaluated.
1451 // Note that edge S->BB was previously already selected because
1452 // prob(S->BB) > prob(S->Pred).
1453 // At this point, 2 blocks can be placed after BB: Pred or Succ. If we
1454 // choose Pred, we will have a topological ordering as shown on the left
1455 // in the picture below. If we choose Succ, we have the solution as shown
1456 // on the right:
1457 //
1458 // topo-order:
1459 //
1460 // S----- ---S
1461 // | | | |
1462 // ---BB | | BB
1463 // | | | |
1464 // | Pred-- | Succ--
1465 // | | | |
1466 // ---Succ ---Pred--
1467 //
1468 // cost = freq(S->Pred) + freq(BB->Succ) cost = 2 * freq (S->Pred)
1469 // = freq(S->Pred) + freq(S->BB)
1470 //
1471 // If we have profile data (i.e, branch probabilities can be trusted), the
1472 // cost (number of taken branches) with layout S->BB->Succ->Pred is 2 *
1473 // freq(S->Pred) while the cost of topo order is freq(S->Pred) + freq(S->BB).
1474 // We know Prob(S->BB) > Prob(S->Pred), so freq(S->BB) > freq(S->Pred), which
1475 // means the cost of topological order is greater.
1476 // When profile data is not available, however, we need to be more
1477 // conservative. If the branch prediction is wrong, breaking the topo-order
1478 // will actually yield a layout with large cost. For this reason, we need
1479 // strong biased branch at block S with Prob(S->BB) in order to select
1480 // BB->Succ. This is equivalent to looking the CFG backward with backward
1481 // edge: Prob(Succ->BB) needs to >= HotProb in order to be selected (without
1482 // profile data).
1483 // --------------------------------------------------------------------------
1484 // Case 3: forked diamond
1485 // S
1486 // / \
1487 // / \
1488 // BB Pred
1489 // | \ / |
1490 // | \ / |
1491 // | X |
1492 // | / \ |
1493 // | / \ |
1494 // S1 S2
1495 //
1496 // The current block is BB and edge BB->S1 is now being evaluated.
1497 // As above S->BB was already selected because
1498 // prob(S->BB) > prob(S->Pred). Assume that prob(BB->S1) >= prob(BB->S2).
1499 //
1500 // topo-order:
1501 //
1502 // S-------| ---S
1503 // | | | |
1504 // ---BB | | BB
1505 // | | | |
1506 // | Pred----| | S1----
1507 // | | | |
1508 // --(S1 or S2) ---Pred--
1509 // |
1510 // S2
1511 //
1512 // topo-cost = freq(S->Pred) + freq(BB->S1) + freq(BB->S2)
1513 // + min(freq(Pred->S1), freq(Pred->S2))
1514 // Non-topo-order cost:
1515 // non-topo-cost = 2 * freq(S->Pred) + freq(BB->S2).
1516 // To be conservative, we can assume that min(freq(Pred->S1), freq(Pred->S2))
1517 // is 0. Then the non topo layout is better when
1518 // freq(S->Pred) < freq(BB->S1).
1519 // This is exactly what is checked below.
1520 // Note there are other shapes that apply (Pred may not be a single block,
1521 // but they all fit this general pattern.)
1522 BranchProbability HotProb = getLayoutSuccessorProbThreshold(BB);
1523
1524 // Make sure that a hot successor doesn't have a globally more
1525 // important predecessor.
1526 BlockFrequency CandidateEdgeFreq = MBFI->getBlockFreq(BB) * RealSuccProb;
1527 bool BadCFGConflict = false;
1528
1529 for (MachineBasicBlock *Pred : Succ->predecessors()) {
1530 BlockChain *PredChain = BlockToChain[Pred];
1531 if (Pred == Succ || PredChain == &SuccChain ||
1532 (BlockFilter && !BlockFilter->count(Pred)) ||
1533 PredChain == &Chain || Pred != *std::prev(PredChain->end()) ||
1534 // This check is redundant except for look ahead. This function is
1535 // called for lookahead by isProfitableToTailDup when BB hasn't been
1536 // placed yet.
1537 (Pred == BB))
1538 continue;
1539 // Do backward checking.
1540 // For all cases above, we need a backward checking to filter out edges that
1541 // are not 'strongly' biased.
1542 // BB Pred
1543 // \ /
1544 // Succ
1545 // We select edge BB->Succ if
1546 // freq(BB->Succ) > freq(Succ) * HotProb
1547 // i.e. freq(BB->Succ) > freq(BB->Succ) * HotProb + freq(Pred->Succ) *
1548 // HotProb
1549 // i.e. freq((BB->Succ) * (1 - HotProb) > freq(Pred->Succ) * HotProb
1550 // Case 1 is covered too, because the first equation reduces to:
1551 // prob(BB->Succ) > HotProb. (freq(Succ) = freq(BB) for a triangle)
1552 BlockFrequency PredEdgeFreq =
1553 MBFI->getBlockFreq(Pred) * MBPI->getEdgeProbability(Pred, Succ);
1554 if (PredEdgeFreq * HotProb >= CandidateEdgeFreq * HotProb.getCompl()) {
1555 BadCFGConflict = true;
1556 break;
1557 }
1558 }
1559
1560 if (BadCFGConflict) {
1561 LLVM_DEBUG(dbgs() << " Not a candidate: " << getBlockName(Succ) << " -> "
1562 << SuccProb << " (prob) (non-cold CFG conflict)\n");
1563 return true;
1564 }
1565
1566 return false;
1567 }
1568
1569 /// Select the best successor for a block.
1570 ///
1571 /// This looks across all successors of a particular block and attempts to
1572 /// select the "best" one to be the layout successor. It only considers direct
1573 /// successors which also pass the block filter. It will attempt to avoid
1574 /// breaking CFG structure, but cave and break such structures in the case of
1575 /// very hot successor edges.
1576 ///
1577 /// \returns The best successor block found, or null if none are viable, along
1578 /// with a boolean indicating if tail duplication is necessary.
1579 MachineBlockPlacement::BlockAndTailDupResult
selectBestSuccessor(const MachineBasicBlock * BB,const BlockChain & Chain,const BlockFilterSet * BlockFilter)1580 MachineBlockPlacement::selectBestSuccessor(
1581 const MachineBasicBlock *BB, const BlockChain &Chain,
1582 const BlockFilterSet *BlockFilter) {
1583 const BranchProbability HotProb(StaticLikelyProb, 100);
1584
1585 BlockAndTailDupResult BestSucc = { nullptr, false };
1586 auto BestProb = BranchProbability::getZero();
1587
1588 SmallVector<MachineBasicBlock *, 4> Successors;
1589 auto AdjustedSumProb =
1590 collectViableSuccessors(BB, Chain, BlockFilter, Successors);
1591
1592 LLVM_DEBUG(dbgs() << "Selecting best successor for: " << getBlockName(BB)
1593 << "\n");
1594
1595 // if we already precomputed the best successor for BB, return that if still
1596 // applicable.
1597 auto FoundEdge = ComputedEdges.find(BB);
1598 if (FoundEdge != ComputedEdges.end()) {
1599 MachineBasicBlock *Succ = FoundEdge->second.BB;
1600 ComputedEdges.erase(FoundEdge);
1601 BlockChain *SuccChain = BlockToChain[Succ];
1602 if (BB->isSuccessor(Succ) && (!BlockFilter || BlockFilter->count(Succ)) &&
1603 SuccChain != &Chain && Succ == *SuccChain->begin())
1604 return FoundEdge->second;
1605 }
1606
1607 // if BB is part of a trellis, Use the trellis to determine the optimal
1608 // fallthrough edges
1609 if (isTrellis(BB, Successors, Chain, BlockFilter))
1610 return getBestTrellisSuccessor(BB, Successors, AdjustedSumProb, Chain,
1611 BlockFilter);
1612
1613 // For blocks with CFG violations, we may be able to lay them out anyway with
1614 // tail-duplication. We keep this vector so we can perform the probability
1615 // calculations the minimum number of times.
1616 SmallVector<std::pair<BranchProbability, MachineBasicBlock *>, 4>
1617 DupCandidates;
1618 for (MachineBasicBlock *Succ : Successors) {
1619 auto RealSuccProb = MBPI->getEdgeProbability(BB, Succ);
1620 BranchProbability SuccProb =
1621 getAdjustedProbability(RealSuccProb, AdjustedSumProb);
1622
1623 BlockChain &SuccChain = *BlockToChain[Succ];
1624 // Skip the edge \c BB->Succ if block \c Succ has a better layout
1625 // predecessor that yields lower global cost.
1626 if (hasBetterLayoutPredecessor(BB, Succ, SuccChain, SuccProb, RealSuccProb,
1627 Chain, BlockFilter)) {
1628 // If tail duplication would make Succ profitable, place it.
1629 if (allowTailDupPlacement() && shouldTailDuplicate(Succ))
1630 DupCandidates.emplace_back(SuccProb, Succ);
1631 continue;
1632 }
1633
1634 LLVM_DEBUG(
1635 dbgs() << " Candidate: " << getBlockName(Succ)
1636 << ", probability: " << SuccProb
1637 << (SuccChain.UnscheduledPredecessors != 0 ? " (CFG break)" : "")
1638 << "\n");
1639
1640 if (BestSucc.BB && BestProb >= SuccProb) {
1641 LLVM_DEBUG(dbgs() << " Not the best candidate, continuing\n");
1642 continue;
1643 }
1644
1645 LLVM_DEBUG(dbgs() << " Setting it as best candidate\n");
1646 BestSucc.BB = Succ;
1647 BestProb = SuccProb;
1648 }
1649 // Handle the tail duplication candidates in order of decreasing probability.
1650 // Stop at the first one that is profitable. Also stop if they are less
1651 // profitable than BestSucc. Position is important because we preserve it and
1652 // prefer first best match. Here we aren't comparing in order, so we capture
1653 // the position instead.
1654 llvm::stable_sort(DupCandidates,
1655 [](std::tuple<BranchProbability, MachineBasicBlock *> L,
1656 std::tuple<BranchProbability, MachineBasicBlock *> R) {
1657 return std::get<0>(L) > std::get<0>(R);
1658 });
1659 for (auto &Tup : DupCandidates) {
1660 BranchProbability DupProb;
1661 MachineBasicBlock *Succ;
1662 std::tie(DupProb, Succ) = Tup;
1663 if (DupProb < BestProb)
1664 break;
1665 if (canTailDuplicateUnplacedPreds(BB, Succ, Chain, BlockFilter)
1666 && (isProfitableToTailDup(BB, Succ, BestProb, Chain, BlockFilter))) {
1667 LLVM_DEBUG(dbgs() << " Candidate: " << getBlockName(Succ)
1668 << ", probability: " << DupProb
1669 << " (Tail Duplicate)\n");
1670 BestSucc.BB = Succ;
1671 BestSucc.ShouldTailDup = true;
1672 break;
1673 }
1674 }
1675
1676 if (BestSucc.BB)
1677 LLVM_DEBUG(dbgs() << " Selected: " << getBlockName(BestSucc.BB) << "\n");
1678
1679 return BestSucc;
1680 }
1681
1682 /// Select the best block from a worklist.
1683 ///
1684 /// This looks through the provided worklist as a list of candidate basic
1685 /// blocks and select the most profitable one to place. The definition of
1686 /// profitable only really makes sense in the context of a loop. This returns
1687 /// the most frequently visited block in the worklist, which in the case of
1688 /// a loop, is the one most desirable to be physically close to the rest of the
1689 /// loop body in order to improve i-cache behavior.
1690 ///
1691 /// \returns The best block found, or null if none are viable.
selectBestCandidateBlock(const BlockChain & Chain,SmallVectorImpl<MachineBasicBlock * > & WorkList)1692 MachineBasicBlock *MachineBlockPlacement::selectBestCandidateBlock(
1693 const BlockChain &Chain, SmallVectorImpl<MachineBasicBlock *> &WorkList) {
1694 // Once we need to walk the worklist looking for a candidate, cleanup the
1695 // worklist of already placed entries.
1696 // FIXME: If this shows up on profiles, it could be folded (at the cost of
1697 // some code complexity) into the loop below.
1698 llvm::erase_if(WorkList, [&](MachineBasicBlock *BB) {
1699 return BlockToChain.lookup(BB) == &Chain;
1700 });
1701
1702 if (WorkList.empty())
1703 return nullptr;
1704
1705 bool IsEHPad = WorkList[0]->isEHPad();
1706
1707 MachineBasicBlock *BestBlock = nullptr;
1708 BlockFrequency BestFreq;
1709 for (MachineBasicBlock *MBB : WorkList) {
1710 assert(MBB->isEHPad() == IsEHPad &&
1711 "EHPad mismatch between block and work list.");
1712
1713 BlockChain &SuccChain = *BlockToChain[MBB];
1714 if (&SuccChain == &Chain)
1715 continue;
1716
1717 assert(SuccChain.UnscheduledPredecessors == 0 &&
1718 "Found CFG-violating block");
1719
1720 BlockFrequency CandidateFreq = MBFI->getBlockFreq(MBB);
1721 LLVM_DEBUG(dbgs() << " " << getBlockName(MBB) << " -> ";
1722 MBFI->printBlockFreq(dbgs(), CandidateFreq) << " (freq)\n");
1723
1724 // For ehpad, we layout the least probable first as to avoid jumping back
1725 // from least probable landingpads to more probable ones.
1726 //
1727 // FIXME: Using probability is probably (!) not the best way to achieve
1728 // this. We should probably have a more principled approach to layout
1729 // cleanup code.
1730 //
1731 // The goal is to get:
1732 //
1733 // +--------------------------+
1734 // | V
1735 // InnerLp -> InnerCleanup OuterLp -> OuterCleanup -> Resume
1736 //
1737 // Rather than:
1738 //
1739 // +-------------------------------------+
1740 // V |
1741 // OuterLp -> OuterCleanup -> Resume InnerLp -> InnerCleanup
1742 if (BestBlock && (IsEHPad ^ (BestFreq >= CandidateFreq)))
1743 continue;
1744
1745 BestBlock = MBB;
1746 BestFreq = CandidateFreq;
1747 }
1748
1749 return BestBlock;
1750 }
1751
1752 /// Retrieve the first unplaced basic block.
1753 ///
1754 /// This routine is called when we are unable to use the CFG to walk through
1755 /// all of the basic blocks and form a chain due to unnatural loops in the CFG.
1756 /// We walk through the function's blocks in order, starting from the
1757 /// LastUnplacedBlockIt. We update this iterator on each call to avoid
1758 /// re-scanning the entire sequence on repeated calls to this routine.
getFirstUnplacedBlock(const BlockChain & PlacedChain,MachineFunction::iterator & PrevUnplacedBlockIt,const BlockFilterSet * BlockFilter)1759 MachineBasicBlock *MachineBlockPlacement::getFirstUnplacedBlock(
1760 const BlockChain &PlacedChain,
1761 MachineFunction::iterator &PrevUnplacedBlockIt,
1762 const BlockFilterSet *BlockFilter) {
1763 for (MachineFunction::iterator I = PrevUnplacedBlockIt, E = F->end(); I != E;
1764 ++I) {
1765 if (BlockFilter && !BlockFilter->count(&*I))
1766 continue;
1767 if (BlockToChain[&*I] != &PlacedChain) {
1768 PrevUnplacedBlockIt = I;
1769 // Now select the head of the chain to which the unplaced block belongs
1770 // as the block to place. This will force the entire chain to be placed,
1771 // and satisfies the requirements of merging chains.
1772 return *BlockToChain[&*I]->begin();
1773 }
1774 }
1775 return nullptr;
1776 }
1777
fillWorkLists(const MachineBasicBlock * MBB,SmallPtrSetImpl<BlockChain * > & UpdatedPreds,const BlockFilterSet * BlockFilter=nullptr)1778 void MachineBlockPlacement::fillWorkLists(
1779 const MachineBasicBlock *MBB,
1780 SmallPtrSetImpl<BlockChain *> &UpdatedPreds,
1781 const BlockFilterSet *BlockFilter = nullptr) {
1782 BlockChain &Chain = *BlockToChain[MBB];
1783 if (!UpdatedPreds.insert(&Chain).second)
1784 return;
1785
1786 assert(
1787 Chain.UnscheduledPredecessors == 0 &&
1788 "Attempting to place block with unscheduled predecessors in worklist.");
1789 for (MachineBasicBlock *ChainBB : Chain) {
1790 assert(BlockToChain[ChainBB] == &Chain &&
1791 "Block in chain doesn't match BlockToChain map.");
1792 for (MachineBasicBlock *Pred : ChainBB->predecessors()) {
1793 if (BlockFilter && !BlockFilter->count(Pred))
1794 continue;
1795 if (BlockToChain[Pred] == &Chain)
1796 continue;
1797 ++Chain.UnscheduledPredecessors;
1798 }
1799 }
1800
1801 if (Chain.UnscheduledPredecessors != 0)
1802 return;
1803
1804 MachineBasicBlock *BB = *Chain.begin();
1805 if (BB->isEHPad())
1806 EHPadWorkList.push_back(BB);
1807 else
1808 BlockWorkList.push_back(BB);
1809 }
1810
buildChain(const MachineBasicBlock * HeadBB,BlockChain & Chain,BlockFilterSet * BlockFilter)1811 void MachineBlockPlacement::buildChain(
1812 const MachineBasicBlock *HeadBB, BlockChain &Chain,
1813 BlockFilterSet *BlockFilter) {
1814 assert(HeadBB && "BB must not be null.\n");
1815 assert(BlockToChain[HeadBB] == &Chain && "BlockToChainMap mis-match.\n");
1816 MachineFunction::iterator PrevUnplacedBlockIt = F->begin();
1817
1818 const MachineBasicBlock *LoopHeaderBB = HeadBB;
1819 markChainSuccessors(Chain, LoopHeaderBB, BlockFilter);
1820 MachineBasicBlock *BB = *std::prev(Chain.end());
1821 while (true) {
1822 assert(BB && "null block found at end of chain in loop.");
1823 assert(BlockToChain[BB] == &Chain && "BlockToChainMap mis-match in loop.");
1824 assert(*std::prev(Chain.end()) == BB && "BB Not found at end of chain.");
1825
1826
1827 // Look for the best viable successor if there is one to place immediately
1828 // after this block.
1829 auto Result = selectBestSuccessor(BB, Chain, BlockFilter);
1830 MachineBasicBlock* BestSucc = Result.BB;
1831 bool ShouldTailDup = Result.ShouldTailDup;
1832 if (allowTailDupPlacement())
1833 ShouldTailDup |= (BestSucc && canTailDuplicateUnplacedPreds(BB, BestSucc,
1834 Chain,
1835 BlockFilter));
1836
1837 // If an immediate successor isn't available, look for the best viable
1838 // block among those we've identified as not violating the loop's CFG at
1839 // this point. This won't be a fallthrough, but it will increase locality.
1840 if (!BestSucc)
1841 BestSucc = selectBestCandidateBlock(Chain, BlockWorkList);
1842 if (!BestSucc)
1843 BestSucc = selectBestCandidateBlock(Chain, EHPadWorkList);
1844
1845 if (!BestSucc) {
1846 BestSucc = getFirstUnplacedBlock(Chain, PrevUnplacedBlockIt, BlockFilter);
1847 if (!BestSucc)
1848 break;
1849
1850 LLVM_DEBUG(dbgs() << "Unnatural loop CFG detected, forcibly merging the "
1851 "layout successor until the CFG reduces\n");
1852 }
1853
1854 // Placement may have changed tail duplication opportunities.
1855 // Check for that now.
1856 if (allowTailDupPlacement() && BestSucc && ShouldTailDup) {
1857 repeatedlyTailDuplicateBlock(BestSucc, BB, LoopHeaderBB, Chain,
1858 BlockFilter, PrevUnplacedBlockIt);
1859 // If the chosen successor was duplicated into BB, don't bother laying
1860 // it out, just go round the loop again with BB as the chain end.
1861 if (!BB->isSuccessor(BestSucc))
1862 continue;
1863 }
1864
1865 // Place this block, updating the datastructures to reflect its placement.
1866 BlockChain &SuccChain = *BlockToChain[BestSucc];
1867 // Zero out UnscheduledPredecessors for the successor we're about to merge in case
1868 // we selected a successor that didn't fit naturally into the CFG.
1869 SuccChain.UnscheduledPredecessors = 0;
1870 LLVM_DEBUG(dbgs() << "Merging from " << getBlockName(BB) << " to "
1871 << getBlockName(BestSucc) << "\n");
1872 markChainSuccessors(SuccChain, LoopHeaderBB, BlockFilter);
1873 Chain.merge(BestSucc, &SuccChain);
1874 BB = *std::prev(Chain.end());
1875 }
1876
1877 LLVM_DEBUG(dbgs() << "Finished forming chain for header block "
1878 << getBlockName(*Chain.begin()) << "\n");
1879 }
1880
1881 // If bottom of block BB has only one successor OldTop, in most cases it is
1882 // profitable to move it before OldTop, except the following case:
1883 //
1884 // -->OldTop<-
1885 // | . |
1886 // | . |
1887 // | . |
1888 // ---Pred |
1889 // | |
1890 // BB-----
1891 //
1892 // If BB is moved before OldTop, Pred needs a taken branch to BB, and it can't
1893 // layout the other successor below it, so it can't reduce taken branch.
1894 // In this case we keep its original layout.
1895 bool
canMoveBottomBlockToTop(const MachineBasicBlock * BottomBlock,const MachineBasicBlock * OldTop)1896 MachineBlockPlacement::canMoveBottomBlockToTop(
1897 const MachineBasicBlock *BottomBlock,
1898 const MachineBasicBlock *OldTop) {
1899 if (BottomBlock->pred_size() != 1)
1900 return true;
1901 MachineBasicBlock *Pred = *BottomBlock->pred_begin();
1902 if (Pred->succ_size() != 2)
1903 return true;
1904
1905 MachineBasicBlock *OtherBB = *Pred->succ_begin();
1906 if (OtherBB == BottomBlock)
1907 OtherBB = *Pred->succ_rbegin();
1908 if (OtherBB == OldTop)
1909 return false;
1910
1911 return true;
1912 }
1913
1914 // Find out the possible fall through frequence to the top of a loop.
1915 BlockFrequency
TopFallThroughFreq(const MachineBasicBlock * Top,const BlockFilterSet & LoopBlockSet)1916 MachineBlockPlacement::TopFallThroughFreq(
1917 const MachineBasicBlock *Top,
1918 const BlockFilterSet &LoopBlockSet) {
1919 BlockFrequency MaxFreq = 0;
1920 for (MachineBasicBlock *Pred : Top->predecessors()) {
1921 BlockChain *PredChain = BlockToChain[Pred];
1922 if (!LoopBlockSet.count(Pred) &&
1923 (!PredChain || Pred == *std::prev(PredChain->end()))) {
1924 // Found a Pred block can be placed before Top.
1925 // Check if Top is the best successor of Pred.
1926 auto TopProb = MBPI->getEdgeProbability(Pred, Top);
1927 bool TopOK = true;
1928 for (MachineBasicBlock *Succ : Pred->successors()) {
1929 auto SuccProb = MBPI->getEdgeProbability(Pred, Succ);
1930 BlockChain *SuccChain = BlockToChain[Succ];
1931 // Check if Succ can be placed after Pred.
1932 // Succ should not be in any chain, or it is the head of some chain.
1933 if (!LoopBlockSet.count(Succ) && (SuccProb > TopProb) &&
1934 (!SuccChain || Succ == *SuccChain->begin())) {
1935 TopOK = false;
1936 break;
1937 }
1938 }
1939 if (TopOK) {
1940 BlockFrequency EdgeFreq = MBFI->getBlockFreq(Pred) *
1941 MBPI->getEdgeProbability(Pred, Top);
1942 if (EdgeFreq > MaxFreq)
1943 MaxFreq = EdgeFreq;
1944 }
1945 }
1946 }
1947 return MaxFreq;
1948 }
1949
1950 // Compute the fall through gains when move NewTop before OldTop.
1951 //
1952 // In following diagram, edges marked as "-" are reduced fallthrough, edges
1953 // marked as "+" are increased fallthrough, this function computes
1954 //
1955 // SUM(increased fallthrough) - SUM(decreased fallthrough)
1956 //
1957 // |
1958 // | -
1959 // V
1960 // --->OldTop
1961 // | .
1962 // | .
1963 // +| . +
1964 // | Pred --->
1965 // | |-
1966 // | V
1967 // --- NewTop <---
1968 // |-
1969 // V
1970 //
1971 BlockFrequency
FallThroughGains(const MachineBasicBlock * NewTop,const MachineBasicBlock * OldTop,const MachineBasicBlock * ExitBB,const BlockFilterSet & LoopBlockSet)1972 MachineBlockPlacement::FallThroughGains(
1973 const MachineBasicBlock *NewTop,
1974 const MachineBasicBlock *OldTop,
1975 const MachineBasicBlock *ExitBB,
1976 const BlockFilterSet &LoopBlockSet) {
1977 BlockFrequency FallThrough2Top = TopFallThroughFreq(OldTop, LoopBlockSet);
1978 BlockFrequency FallThrough2Exit = 0;
1979 if (ExitBB)
1980 FallThrough2Exit = MBFI->getBlockFreq(NewTop) *
1981 MBPI->getEdgeProbability(NewTop, ExitBB);
1982 BlockFrequency BackEdgeFreq = MBFI->getBlockFreq(NewTop) *
1983 MBPI->getEdgeProbability(NewTop, OldTop);
1984
1985 // Find the best Pred of NewTop.
1986 MachineBasicBlock *BestPred = nullptr;
1987 BlockFrequency FallThroughFromPred = 0;
1988 for (MachineBasicBlock *Pred : NewTop->predecessors()) {
1989 if (!LoopBlockSet.count(Pred))
1990 continue;
1991 BlockChain *PredChain = BlockToChain[Pred];
1992 if (!PredChain || Pred == *std::prev(PredChain->end())) {
1993 BlockFrequency EdgeFreq = MBFI->getBlockFreq(Pred) *
1994 MBPI->getEdgeProbability(Pred, NewTop);
1995 if (EdgeFreq > FallThroughFromPred) {
1996 FallThroughFromPred = EdgeFreq;
1997 BestPred = Pred;
1998 }
1999 }
2000 }
2001
2002 // If NewTop is not placed after Pred, another successor can be placed
2003 // after Pred.
2004 BlockFrequency NewFreq = 0;
2005 if (BestPred) {
2006 for (MachineBasicBlock *Succ : BestPred->successors()) {
2007 if ((Succ == NewTop) || (Succ == BestPred) || !LoopBlockSet.count(Succ))
2008 continue;
2009 if (ComputedEdges.find(Succ) != ComputedEdges.end())
2010 continue;
2011 BlockChain *SuccChain = BlockToChain[Succ];
2012 if ((SuccChain && (Succ != *SuccChain->begin())) ||
2013 (SuccChain == BlockToChain[BestPred]))
2014 continue;
2015 BlockFrequency EdgeFreq = MBFI->getBlockFreq(BestPred) *
2016 MBPI->getEdgeProbability(BestPred, Succ);
2017 if (EdgeFreq > NewFreq)
2018 NewFreq = EdgeFreq;
2019 }
2020 BlockFrequency OrigEdgeFreq = MBFI->getBlockFreq(BestPred) *
2021 MBPI->getEdgeProbability(BestPred, NewTop);
2022 if (NewFreq > OrigEdgeFreq) {
2023 // If NewTop is not the best successor of Pred, then Pred doesn't
2024 // fallthrough to NewTop. So there is no FallThroughFromPred and
2025 // NewFreq.
2026 NewFreq = 0;
2027 FallThroughFromPred = 0;
2028 }
2029 }
2030
2031 BlockFrequency Result = 0;
2032 BlockFrequency Gains = BackEdgeFreq + NewFreq;
2033 BlockFrequency Lost = FallThrough2Top + FallThrough2Exit +
2034 FallThroughFromPred;
2035 if (Gains > Lost)
2036 Result = Gains - Lost;
2037 return Result;
2038 }
2039
2040 /// Helper function of findBestLoopTop. Find the best loop top block
2041 /// from predecessors of old top.
2042 ///
2043 /// Look for a block which is strictly better than the old top for laying
2044 /// out before the old top of the loop. This looks for only two patterns:
2045 ///
2046 /// 1. a block has only one successor, the old loop top
2047 ///
2048 /// Because such a block will always result in an unconditional jump,
2049 /// rotating it in front of the old top is always profitable.
2050 ///
2051 /// 2. a block has two successors, one is old top, another is exit
2052 /// and it has more than one predecessors
2053 ///
2054 /// If it is below one of its predecessors P, only P can fall through to
2055 /// it, all other predecessors need a jump to it, and another conditional
2056 /// jump to loop header. If it is moved before loop header, all its
2057 /// predecessors jump to it, then fall through to loop header. So all its
2058 /// predecessors except P can reduce one taken branch.
2059 /// At the same time, move it before old top increases the taken branch
2060 /// to loop exit block, so the reduced taken branch will be compared with
2061 /// the increased taken branch to the loop exit block.
2062 MachineBasicBlock *
findBestLoopTopHelper(MachineBasicBlock * OldTop,const MachineLoop & L,const BlockFilterSet & LoopBlockSet)2063 MachineBlockPlacement::findBestLoopTopHelper(
2064 MachineBasicBlock *OldTop,
2065 const MachineLoop &L,
2066 const BlockFilterSet &LoopBlockSet) {
2067 // Check that the header hasn't been fused with a preheader block due to
2068 // crazy branches. If it has, we need to start with the header at the top to
2069 // prevent pulling the preheader into the loop body.
2070 BlockChain &HeaderChain = *BlockToChain[OldTop];
2071 if (!LoopBlockSet.count(*HeaderChain.begin()))
2072 return OldTop;
2073 if (OldTop != *HeaderChain.begin())
2074 return OldTop;
2075
2076 LLVM_DEBUG(dbgs() << "Finding best loop top for: " << getBlockName(OldTop)
2077 << "\n");
2078
2079 BlockFrequency BestGains = 0;
2080 MachineBasicBlock *BestPred = nullptr;
2081 for (MachineBasicBlock *Pred : OldTop->predecessors()) {
2082 if (!LoopBlockSet.count(Pred))
2083 continue;
2084 if (Pred == L.getHeader())
2085 continue;
2086 LLVM_DEBUG(dbgs() << " old top pred: " << getBlockName(Pred) << ", has "
2087 << Pred->succ_size() << " successors, ";
2088 MBFI->printBlockFreq(dbgs(), Pred) << " freq\n");
2089 if (Pred->succ_size() > 2)
2090 continue;
2091
2092 MachineBasicBlock *OtherBB = nullptr;
2093 if (Pred->succ_size() == 2) {
2094 OtherBB = *Pred->succ_begin();
2095 if (OtherBB == OldTop)
2096 OtherBB = *Pred->succ_rbegin();
2097 }
2098
2099 if (!canMoveBottomBlockToTop(Pred, OldTop))
2100 continue;
2101
2102 BlockFrequency Gains = FallThroughGains(Pred, OldTop, OtherBB,
2103 LoopBlockSet);
2104 if ((Gains > 0) && (Gains > BestGains ||
2105 ((Gains == BestGains) && Pred->isLayoutSuccessor(OldTop)))) {
2106 BestPred = Pred;
2107 BestGains = Gains;
2108 }
2109 }
2110
2111 // If no direct predecessor is fine, just use the loop header.
2112 if (!BestPred) {
2113 LLVM_DEBUG(dbgs() << " final top unchanged\n");
2114 return OldTop;
2115 }
2116
2117 // Walk backwards through any straight line of predecessors.
2118 while (BestPred->pred_size() == 1 &&
2119 (*BestPred->pred_begin())->succ_size() == 1 &&
2120 *BestPred->pred_begin() != L.getHeader())
2121 BestPred = *BestPred->pred_begin();
2122
2123 LLVM_DEBUG(dbgs() << " final top: " << getBlockName(BestPred) << "\n");
2124 return BestPred;
2125 }
2126
2127 /// Find the best loop top block for layout.
2128 ///
2129 /// This function iteratively calls findBestLoopTopHelper, until no new better
2130 /// BB can be found.
2131 MachineBasicBlock *
findBestLoopTop(const MachineLoop & L,const BlockFilterSet & LoopBlockSet)2132 MachineBlockPlacement::findBestLoopTop(const MachineLoop &L,
2133 const BlockFilterSet &LoopBlockSet) {
2134 // Placing the latch block before the header may introduce an extra branch
2135 // that skips this block the first time the loop is executed, which we want
2136 // to avoid when optimising for size.
2137 // FIXME: in theory there is a case that does not introduce a new branch,
2138 // i.e. when the layout predecessor does not fallthrough to the loop header.
2139 // In practice this never happens though: there always seems to be a preheader
2140 // that can fallthrough and that is also placed before the header.
2141 bool OptForSize = F->getFunction().hasOptSize() ||
2142 llvm::shouldOptimizeForSize(L.getHeader(), PSI, MBFI.get());
2143 if (OptForSize)
2144 return L.getHeader();
2145
2146 MachineBasicBlock *OldTop = nullptr;
2147 MachineBasicBlock *NewTop = L.getHeader();
2148 while (NewTop != OldTop) {
2149 OldTop = NewTop;
2150 NewTop = findBestLoopTopHelper(OldTop, L, LoopBlockSet);
2151 if (NewTop != OldTop)
2152 ComputedEdges[NewTop] = { OldTop, false };
2153 }
2154 return NewTop;
2155 }
2156
2157 /// Find the best loop exiting block for layout.
2158 ///
2159 /// This routine implements the logic to analyze the loop looking for the best
2160 /// block to layout at the top of the loop. Typically this is done to maximize
2161 /// fallthrough opportunities.
2162 MachineBasicBlock *
findBestLoopExit(const MachineLoop & L,const BlockFilterSet & LoopBlockSet,BlockFrequency & ExitFreq)2163 MachineBlockPlacement::findBestLoopExit(const MachineLoop &L,
2164 const BlockFilterSet &LoopBlockSet,
2165 BlockFrequency &ExitFreq) {
2166 // We don't want to layout the loop linearly in all cases. If the loop header
2167 // is just a normal basic block in the loop, we want to look for what block
2168 // within the loop is the best one to layout at the top. However, if the loop
2169 // header has be pre-merged into a chain due to predecessors not having
2170 // analyzable branches, *and* the predecessor it is merged with is *not* part
2171 // of the loop, rotating the header into the middle of the loop will create
2172 // a non-contiguous range of blocks which is Very Bad. So start with the
2173 // header and only rotate if safe.
2174 BlockChain &HeaderChain = *BlockToChain[L.getHeader()];
2175 if (!LoopBlockSet.count(*HeaderChain.begin()))
2176 return nullptr;
2177
2178 BlockFrequency BestExitEdgeFreq;
2179 unsigned BestExitLoopDepth = 0;
2180 MachineBasicBlock *ExitingBB = nullptr;
2181 // If there are exits to outer loops, loop rotation can severely limit
2182 // fallthrough opportunities unless it selects such an exit. Keep a set of
2183 // blocks where rotating to exit with that block will reach an outer loop.
2184 SmallPtrSet<MachineBasicBlock *, 4> BlocksExitingToOuterLoop;
2185
2186 LLVM_DEBUG(dbgs() << "Finding best loop exit for: "
2187 << getBlockName(L.getHeader()) << "\n");
2188 for (MachineBasicBlock *MBB : L.getBlocks()) {
2189 BlockChain &Chain = *BlockToChain[MBB];
2190 // Ensure that this block is at the end of a chain; otherwise it could be
2191 // mid-way through an inner loop or a successor of an unanalyzable branch.
2192 if (MBB != *std::prev(Chain.end()))
2193 continue;
2194
2195 // Now walk the successors. We need to establish whether this has a viable
2196 // exiting successor and whether it has a viable non-exiting successor.
2197 // We store the old exiting state and restore it if a viable looping
2198 // successor isn't found.
2199 MachineBasicBlock *OldExitingBB = ExitingBB;
2200 BlockFrequency OldBestExitEdgeFreq = BestExitEdgeFreq;
2201 bool HasLoopingSucc = false;
2202 for (MachineBasicBlock *Succ : MBB->successors()) {
2203 if (Succ->isEHPad())
2204 continue;
2205 if (Succ == MBB)
2206 continue;
2207 BlockChain &SuccChain = *BlockToChain[Succ];
2208 // Don't split chains, either this chain or the successor's chain.
2209 if (&Chain == &SuccChain) {
2210 LLVM_DEBUG(dbgs() << " exiting: " << getBlockName(MBB) << " -> "
2211 << getBlockName(Succ) << " (chain conflict)\n");
2212 continue;
2213 }
2214
2215 auto SuccProb = MBPI->getEdgeProbability(MBB, Succ);
2216 if (LoopBlockSet.count(Succ)) {
2217 LLVM_DEBUG(dbgs() << " looping: " << getBlockName(MBB) << " -> "
2218 << getBlockName(Succ) << " (" << SuccProb << ")\n");
2219 HasLoopingSucc = true;
2220 continue;
2221 }
2222
2223 unsigned SuccLoopDepth = 0;
2224 if (MachineLoop *ExitLoop = MLI->getLoopFor(Succ)) {
2225 SuccLoopDepth = ExitLoop->getLoopDepth();
2226 if (ExitLoop->contains(&L))
2227 BlocksExitingToOuterLoop.insert(MBB);
2228 }
2229
2230 BlockFrequency ExitEdgeFreq = MBFI->getBlockFreq(MBB) * SuccProb;
2231 LLVM_DEBUG(dbgs() << " exiting: " << getBlockName(MBB) << " -> "
2232 << getBlockName(Succ) << " [L:" << SuccLoopDepth
2233 << "] (";
2234 MBFI->printBlockFreq(dbgs(), ExitEdgeFreq) << ")\n");
2235 // Note that we bias this toward an existing layout successor to retain
2236 // incoming order in the absence of better information. The exit must have
2237 // a frequency higher than the current exit before we consider breaking
2238 // the layout.
2239 BranchProbability Bias(100 - ExitBlockBias, 100);
2240 if (!ExitingBB || SuccLoopDepth > BestExitLoopDepth ||
2241 ExitEdgeFreq > BestExitEdgeFreq ||
2242 (MBB->isLayoutSuccessor(Succ) &&
2243 !(ExitEdgeFreq < BestExitEdgeFreq * Bias))) {
2244 BestExitEdgeFreq = ExitEdgeFreq;
2245 ExitingBB = MBB;
2246 }
2247 }
2248
2249 if (!HasLoopingSucc) {
2250 // Restore the old exiting state, no viable looping successor was found.
2251 ExitingBB = OldExitingBB;
2252 BestExitEdgeFreq = OldBestExitEdgeFreq;
2253 }
2254 }
2255 // Without a candidate exiting block or with only a single block in the
2256 // loop, just use the loop header to layout the loop.
2257 if (!ExitingBB) {
2258 LLVM_DEBUG(
2259 dbgs() << " No other candidate exit blocks, using loop header\n");
2260 return nullptr;
2261 }
2262 if (L.getNumBlocks() == 1) {
2263 LLVM_DEBUG(dbgs() << " Loop has 1 block, using loop header as exit\n");
2264 return nullptr;
2265 }
2266
2267 // Also, if we have exit blocks which lead to outer loops but didn't select
2268 // one of them as the exiting block we are rotating toward, disable loop
2269 // rotation altogether.
2270 if (!BlocksExitingToOuterLoop.empty() &&
2271 !BlocksExitingToOuterLoop.count(ExitingBB))
2272 return nullptr;
2273
2274 LLVM_DEBUG(dbgs() << " Best exiting block: " << getBlockName(ExitingBB)
2275 << "\n");
2276 ExitFreq = BestExitEdgeFreq;
2277 return ExitingBB;
2278 }
2279
2280 /// Check if there is a fallthrough to loop header Top.
2281 ///
2282 /// 1. Look for a Pred that can be layout before Top.
2283 /// 2. Check if Top is the most possible successor of Pred.
2284 bool
hasViableTopFallthrough(const MachineBasicBlock * Top,const BlockFilterSet & LoopBlockSet)2285 MachineBlockPlacement::hasViableTopFallthrough(
2286 const MachineBasicBlock *Top,
2287 const BlockFilterSet &LoopBlockSet) {
2288 for (MachineBasicBlock *Pred : Top->predecessors()) {
2289 BlockChain *PredChain = BlockToChain[Pred];
2290 if (!LoopBlockSet.count(Pred) &&
2291 (!PredChain || Pred == *std::prev(PredChain->end()))) {
2292 // Found a Pred block can be placed before Top.
2293 // Check if Top is the best successor of Pred.
2294 auto TopProb = MBPI->getEdgeProbability(Pred, Top);
2295 bool TopOK = true;
2296 for (MachineBasicBlock *Succ : Pred->successors()) {
2297 auto SuccProb = MBPI->getEdgeProbability(Pred, Succ);
2298 BlockChain *SuccChain = BlockToChain[Succ];
2299 // Check if Succ can be placed after Pred.
2300 // Succ should not be in any chain, or it is the head of some chain.
2301 if ((!SuccChain || Succ == *SuccChain->begin()) && SuccProb > TopProb) {
2302 TopOK = false;
2303 break;
2304 }
2305 }
2306 if (TopOK)
2307 return true;
2308 }
2309 }
2310 return false;
2311 }
2312
2313 /// Attempt to rotate an exiting block to the bottom of the loop.
2314 ///
2315 /// Once we have built a chain, try to rotate it to line up the hot exit block
2316 /// with fallthrough out of the loop if doing so doesn't introduce unnecessary
2317 /// branches. For example, if the loop has fallthrough into its header and out
2318 /// of its bottom already, don't rotate it.
rotateLoop(BlockChain & LoopChain,const MachineBasicBlock * ExitingBB,BlockFrequency ExitFreq,const BlockFilterSet & LoopBlockSet)2319 void MachineBlockPlacement::rotateLoop(BlockChain &LoopChain,
2320 const MachineBasicBlock *ExitingBB,
2321 BlockFrequency ExitFreq,
2322 const BlockFilterSet &LoopBlockSet) {
2323 if (!ExitingBB)
2324 return;
2325
2326 MachineBasicBlock *Top = *LoopChain.begin();
2327 MachineBasicBlock *Bottom = *std::prev(LoopChain.end());
2328
2329 // If ExitingBB is already the last one in a chain then nothing to do.
2330 if (Bottom == ExitingBB)
2331 return;
2332
2333 // The entry block should always be the first BB in a function.
2334 if (Top->isEntryBlock())
2335 return;
2336
2337 bool ViableTopFallthrough = hasViableTopFallthrough(Top, LoopBlockSet);
2338
2339 // If the header has viable fallthrough, check whether the current loop
2340 // bottom is a viable exiting block. If so, bail out as rotating will
2341 // introduce an unnecessary branch.
2342 if (ViableTopFallthrough) {
2343 for (MachineBasicBlock *Succ : Bottom->successors()) {
2344 BlockChain *SuccChain = BlockToChain[Succ];
2345 if (!LoopBlockSet.count(Succ) &&
2346 (!SuccChain || Succ == *SuccChain->begin()))
2347 return;
2348 }
2349
2350 // Rotate will destroy the top fallthrough, we need to ensure the new exit
2351 // frequency is larger than top fallthrough.
2352 BlockFrequency FallThrough2Top = TopFallThroughFreq(Top, LoopBlockSet);
2353 if (FallThrough2Top >= ExitFreq)
2354 return;
2355 }
2356
2357 BlockChain::iterator ExitIt = llvm::find(LoopChain, ExitingBB);
2358 if (ExitIt == LoopChain.end())
2359 return;
2360
2361 // Rotating a loop exit to the bottom when there is a fallthrough to top
2362 // trades the entry fallthrough for an exit fallthrough.
2363 // If there is no bottom->top edge, but the chosen exit block does have
2364 // a fallthrough, we break that fallthrough for nothing in return.
2365
2366 // Let's consider an example. We have a built chain of basic blocks
2367 // B1, B2, ..., Bn, where Bk is a ExitingBB - chosen exit block.
2368 // By doing a rotation we get
2369 // Bk+1, ..., Bn, B1, ..., Bk
2370 // Break of fallthrough to B1 is compensated by a fallthrough from Bk.
2371 // If we had a fallthrough Bk -> Bk+1 it is broken now.
2372 // It might be compensated by fallthrough Bn -> B1.
2373 // So we have a condition to avoid creation of extra branch by loop rotation.
2374 // All below must be true to avoid loop rotation:
2375 // If there is a fallthrough to top (B1)
2376 // There was fallthrough from chosen exit block (Bk) to next one (Bk+1)
2377 // There is no fallthrough from bottom (Bn) to top (B1).
2378 // Please note that there is no exit fallthrough from Bn because we checked it
2379 // above.
2380 if (ViableTopFallthrough) {
2381 assert(std::next(ExitIt) != LoopChain.end() &&
2382 "Exit should not be last BB");
2383 MachineBasicBlock *NextBlockInChain = *std::next(ExitIt);
2384 if (ExitingBB->isSuccessor(NextBlockInChain))
2385 if (!Bottom->isSuccessor(Top))
2386 return;
2387 }
2388
2389 LLVM_DEBUG(dbgs() << "Rotating loop to put exit " << getBlockName(ExitingBB)
2390 << " at bottom\n");
2391 std::rotate(LoopChain.begin(), std::next(ExitIt), LoopChain.end());
2392 }
2393
2394 /// Attempt to rotate a loop based on profile data to reduce branch cost.
2395 ///
2396 /// With profile data, we can determine the cost in terms of missed fall through
2397 /// opportunities when rotating a loop chain and select the best rotation.
2398 /// Basically, there are three kinds of cost to consider for each rotation:
2399 /// 1. The possibly missed fall through edge (if it exists) from BB out of
2400 /// the loop to the loop header.
2401 /// 2. The possibly missed fall through edges (if they exist) from the loop
2402 /// exits to BB out of the loop.
2403 /// 3. The missed fall through edge (if it exists) from the last BB to the
2404 /// first BB in the loop chain.
2405 /// Therefore, the cost for a given rotation is the sum of costs listed above.
2406 /// We select the best rotation with the smallest cost.
rotateLoopWithProfile(BlockChain & LoopChain,const MachineLoop & L,const BlockFilterSet & LoopBlockSet)2407 void MachineBlockPlacement::rotateLoopWithProfile(
2408 BlockChain &LoopChain, const MachineLoop &L,
2409 const BlockFilterSet &LoopBlockSet) {
2410 auto RotationPos = LoopChain.end();
2411 MachineBasicBlock *ChainHeaderBB = *LoopChain.begin();
2412
2413 // The entry block should always be the first BB in a function.
2414 if (ChainHeaderBB->isEntryBlock())
2415 return;
2416
2417 BlockFrequency SmallestRotationCost = BlockFrequency::getMaxFrequency();
2418
2419 // A utility lambda that scales up a block frequency by dividing it by a
2420 // branch probability which is the reciprocal of the scale.
2421 auto ScaleBlockFrequency = [](BlockFrequency Freq,
2422 unsigned Scale) -> BlockFrequency {
2423 if (Scale == 0)
2424 return 0;
2425 // Use operator / between BlockFrequency and BranchProbability to implement
2426 // saturating multiplication.
2427 return Freq / BranchProbability(1, Scale);
2428 };
2429
2430 // Compute the cost of the missed fall-through edge to the loop header if the
2431 // chain head is not the loop header. As we only consider natural loops with
2432 // single header, this computation can be done only once.
2433 BlockFrequency HeaderFallThroughCost(0);
2434 for (auto *Pred : ChainHeaderBB->predecessors()) {
2435 BlockChain *PredChain = BlockToChain[Pred];
2436 if (!LoopBlockSet.count(Pred) &&
2437 (!PredChain || Pred == *std::prev(PredChain->end()))) {
2438 auto EdgeFreq = MBFI->getBlockFreq(Pred) *
2439 MBPI->getEdgeProbability(Pred, ChainHeaderBB);
2440 auto FallThruCost = ScaleBlockFrequency(EdgeFreq, MisfetchCost);
2441 // If the predecessor has only an unconditional jump to the header, we
2442 // need to consider the cost of this jump.
2443 if (Pred->succ_size() == 1)
2444 FallThruCost += ScaleBlockFrequency(EdgeFreq, JumpInstCost);
2445 HeaderFallThroughCost = std::max(HeaderFallThroughCost, FallThruCost);
2446 }
2447 }
2448
2449 // Here we collect all exit blocks in the loop, and for each exit we find out
2450 // its hottest exit edge. For each loop rotation, we define the loop exit cost
2451 // as the sum of frequencies of exit edges we collect here, excluding the exit
2452 // edge from the tail of the loop chain.
2453 SmallVector<std::pair<MachineBasicBlock *, BlockFrequency>, 4> ExitsWithFreq;
2454 for (auto *BB : LoopChain) {
2455 auto LargestExitEdgeProb = BranchProbability::getZero();
2456 for (auto *Succ : BB->successors()) {
2457 BlockChain *SuccChain = BlockToChain[Succ];
2458 if (!LoopBlockSet.count(Succ) &&
2459 (!SuccChain || Succ == *SuccChain->begin())) {
2460 auto SuccProb = MBPI->getEdgeProbability(BB, Succ);
2461 LargestExitEdgeProb = std::max(LargestExitEdgeProb, SuccProb);
2462 }
2463 }
2464 if (LargestExitEdgeProb > BranchProbability::getZero()) {
2465 auto ExitFreq = MBFI->getBlockFreq(BB) * LargestExitEdgeProb;
2466 ExitsWithFreq.emplace_back(BB, ExitFreq);
2467 }
2468 }
2469
2470 // In this loop we iterate every block in the loop chain and calculate the
2471 // cost assuming the block is the head of the loop chain. When the loop ends,
2472 // we should have found the best candidate as the loop chain's head.
2473 for (auto Iter = LoopChain.begin(), TailIter = std::prev(LoopChain.end()),
2474 EndIter = LoopChain.end();
2475 Iter != EndIter; Iter++, TailIter++) {
2476 // TailIter is used to track the tail of the loop chain if the block we are
2477 // checking (pointed by Iter) is the head of the chain.
2478 if (TailIter == LoopChain.end())
2479 TailIter = LoopChain.begin();
2480
2481 auto TailBB = *TailIter;
2482
2483 // Calculate the cost by putting this BB to the top.
2484 BlockFrequency Cost = 0;
2485
2486 // If the current BB is the loop header, we need to take into account the
2487 // cost of the missed fall through edge from outside of the loop to the
2488 // header.
2489 if (Iter != LoopChain.begin())
2490 Cost += HeaderFallThroughCost;
2491
2492 // Collect the loop exit cost by summing up frequencies of all exit edges
2493 // except the one from the chain tail.
2494 for (auto &ExitWithFreq : ExitsWithFreq)
2495 if (TailBB != ExitWithFreq.first)
2496 Cost += ExitWithFreq.second;
2497
2498 // The cost of breaking the once fall-through edge from the tail to the top
2499 // of the loop chain. Here we need to consider three cases:
2500 // 1. If the tail node has only one successor, then we will get an
2501 // additional jmp instruction. So the cost here is (MisfetchCost +
2502 // JumpInstCost) * tail node frequency.
2503 // 2. If the tail node has two successors, then we may still get an
2504 // additional jmp instruction if the layout successor after the loop
2505 // chain is not its CFG successor. Note that the more frequently executed
2506 // jmp instruction will be put ahead of the other one. Assume the
2507 // frequency of those two branches are x and y, where x is the frequency
2508 // of the edge to the chain head, then the cost will be
2509 // (x * MisfetechCost + min(x, y) * JumpInstCost) * tail node frequency.
2510 // 3. If the tail node has more than two successors (this rarely happens),
2511 // we won't consider any additional cost.
2512 if (TailBB->isSuccessor(*Iter)) {
2513 auto TailBBFreq = MBFI->getBlockFreq(TailBB);
2514 if (TailBB->succ_size() == 1)
2515 Cost += ScaleBlockFrequency(TailBBFreq.getFrequency(),
2516 MisfetchCost + JumpInstCost);
2517 else if (TailBB->succ_size() == 2) {
2518 auto TailToHeadProb = MBPI->getEdgeProbability(TailBB, *Iter);
2519 auto TailToHeadFreq = TailBBFreq * TailToHeadProb;
2520 auto ColderEdgeFreq = TailToHeadProb > BranchProbability(1, 2)
2521 ? TailBBFreq * TailToHeadProb.getCompl()
2522 : TailToHeadFreq;
2523 Cost += ScaleBlockFrequency(TailToHeadFreq, MisfetchCost) +
2524 ScaleBlockFrequency(ColderEdgeFreq, JumpInstCost);
2525 }
2526 }
2527
2528 LLVM_DEBUG(dbgs() << "The cost of loop rotation by making "
2529 << getBlockName(*Iter)
2530 << " to the top: " << Cost.getFrequency() << "\n");
2531
2532 if (Cost < SmallestRotationCost) {
2533 SmallestRotationCost = Cost;
2534 RotationPos = Iter;
2535 }
2536 }
2537
2538 if (RotationPos != LoopChain.end()) {
2539 LLVM_DEBUG(dbgs() << "Rotate loop by making " << getBlockName(*RotationPos)
2540 << " to the top\n");
2541 std::rotate(LoopChain.begin(), RotationPos, LoopChain.end());
2542 }
2543 }
2544
2545 /// Collect blocks in the given loop that are to be placed.
2546 ///
2547 /// When profile data is available, exclude cold blocks from the returned set;
2548 /// otherwise, collect all blocks in the loop.
2549 MachineBlockPlacement::BlockFilterSet
collectLoopBlockSet(const MachineLoop & L)2550 MachineBlockPlacement::collectLoopBlockSet(const MachineLoop &L) {
2551 BlockFilterSet LoopBlockSet;
2552
2553 // Filter cold blocks off from LoopBlockSet when profile data is available.
2554 // Collect the sum of frequencies of incoming edges to the loop header from
2555 // outside. If we treat the loop as a super block, this is the frequency of
2556 // the loop. Then for each block in the loop, we calculate the ratio between
2557 // its frequency and the frequency of the loop block. When it is too small,
2558 // don't add it to the loop chain. If there are outer loops, then this block
2559 // will be merged into the first outer loop chain for which this block is not
2560 // cold anymore. This needs precise profile data and we only do this when
2561 // profile data is available.
2562 if (F->getFunction().hasProfileData() || ForceLoopColdBlock) {
2563 BlockFrequency LoopFreq(0);
2564 for (auto *LoopPred : L.getHeader()->predecessors())
2565 if (!L.contains(LoopPred))
2566 LoopFreq += MBFI->getBlockFreq(LoopPred) *
2567 MBPI->getEdgeProbability(LoopPred, L.getHeader());
2568
2569 for (MachineBasicBlock *LoopBB : L.getBlocks()) {
2570 if (LoopBlockSet.count(LoopBB))
2571 continue;
2572 auto Freq = MBFI->getBlockFreq(LoopBB).getFrequency();
2573 if (Freq == 0 || LoopFreq.getFrequency() / Freq > LoopToColdBlockRatio)
2574 continue;
2575 BlockChain *Chain = BlockToChain[LoopBB];
2576 for (MachineBasicBlock *ChainBB : *Chain)
2577 LoopBlockSet.insert(ChainBB);
2578 }
2579 } else
2580 LoopBlockSet.insert(L.block_begin(), L.block_end());
2581
2582 return LoopBlockSet;
2583 }
2584
2585 /// Forms basic block chains from the natural loop structures.
2586 ///
2587 /// These chains are designed to preserve the existing *structure* of the code
2588 /// as much as possible. We can then stitch the chains together in a way which
2589 /// both preserves the topological structure and minimizes taken conditional
2590 /// branches.
buildLoopChains(const MachineLoop & L)2591 void MachineBlockPlacement::buildLoopChains(const MachineLoop &L) {
2592 // First recurse through any nested loops, building chains for those inner
2593 // loops.
2594 for (const MachineLoop *InnerLoop : L)
2595 buildLoopChains(*InnerLoop);
2596
2597 assert(BlockWorkList.empty() &&
2598 "BlockWorkList not empty when starting to build loop chains.");
2599 assert(EHPadWorkList.empty() &&
2600 "EHPadWorkList not empty when starting to build loop chains.");
2601 BlockFilterSet LoopBlockSet = collectLoopBlockSet(L);
2602
2603 // Check if we have profile data for this function. If yes, we will rotate
2604 // this loop by modeling costs more precisely which requires the profile data
2605 // for better layout.
2606 bool RotateLoopWithProfile =
2607 ForcePreciseRotationCost ||
2608 (PreciseRotationCost && F->getFunction().hasProfileData());
2609
2610 // First check to see if there is an obviously preferable top block for the
2611 // loop. This will default to the header, but may end up as one of the
2612 // predecessors to the header if there is one which will result in strictly
2613 // fewer branches in the loop body.
2614 MachineBasicBlock *LoopTop = findBestLoopTop(L, LoopBlockSet);
2615
2616 // If we selected just the header for the loop top, look for a potentially
2617 // profitable exit block in the event that rotating the loop can eliminate
2618 // branches by placing an exit edge at the bottom.
2619 //
2620 // Loops are processed innermost to uttermost, make sure we clear
2621 // PreferredLoopExit before processing a new loop.
2622 PreferredLoopExit = nullptr;
2623 BlockFrequency ExitFreq;
2624 if (!RotateLoopWithProfile && LoopTop == L.getHeader())
2625 PreferredLoopExit = findBestLoopExit(L, LoopBlockSet, ExitFreq);
2626
2627 BlockChain &LoopChain = *BlockToChain[LoopTop];
2628
2629 // FIXME: This is a really lame way of walking the chains in the loop: we
2630 // walk the blocks, and use a set to prevent visiting a particular chain
2631 // twice.
2632 SmallPtrSet<BlockChain *, 4> UpdatedPreds;
2633 assert(LoopChain.UnscheduledPredecessors == 0 &&
2634 "LoopChain should not have unscheduled predecessors.");
2635 UpdatedPreds.insert(&LoopChain);
2636
2637 for (const MachineBasicBlock *LoopBB : LoopBlockSet)
2638 fillWorkLists(LoopBB, UpdatedPreds, &LoopBlockSet);
2639
2640 buildChain(LoopTop, LoopChain, &LoopBlockSet);
2641
2642 if (RotateLoopWithProfile)
2643 rotateLoopWithProfile(LoopChain, L, LoopBlockSet);
2644 else
2645 rotateLoop(LoopChain, PreferredLoopExit, ExitFreq, LoopBlockSet);
2646
2647 LLVM_DEBUG({
2648 // Crash at the end so we get all of the debugging output first.
2649 bool BadLoop = false;
2650 if (LoopChain.UnscheduledPredecessors) {
2651 BadLoop = true;
2652 dbgs() << "Loop chain contains a block without its preds placed!\n"
2653 << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
2654 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n";
2655 }
2656 for (MachineBasicBlock *ChainBB : LoopChain) {
2657 dbgs() << " ... " << getBlockName(ChainBB) << "\n";
2658 if (!LoopBlockSet.remove(ChainBB)) {
2659 // We don't mark the loop as bad here because there are real situations
2660 // where this can occur. For example, with an unanalyzable fallthrough
2661 // from a loop block to a non-loop block or vice versa.
2662 dbgs() << "Loop chain contains a block not contained by the loop!\n"
2663 << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
2664 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
2665 << " Bad block: " << getBlockName(ChainBB) << "\n";
2666 }
2667 }
2668
2669 if (!LoopBlockSet.empty()) {
2670 BadLoop = true;
2671 for (const MachineBasicBlock *LoopBB : LoopBlockSet)
2672 dbgs() << "Loop contains blocks never placed into a chain!\n"
2673 << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
2674 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
2675 << " Bad block: " << getBlockName(LoopBB) << "\n";
2676 }
2677 assert(!BadLoop && "Detected problems with the placement of this loop.");
2678 });
2679
2680 BlockWorkList.clear();
2681 EHPadWorkList.clear();
2682 }
2683
buildCFGChains()2684 void MachineBlockPlacement::buildCFGChains() {
2685 // Ensure that every BB in the function has an associated chain to simplify
2686 // the assumptions of the remaining algorithm.
2687 SmallVector<MachineOperand, 4> Cond; // For analyzeBranch.
2688 for (MachineFunction::iterator FI = F->begin(), FE = F->end(); FI != FE;
2689 ++FI) {
2690 MachineBasicBlock *BB = &*FI;
2691 BlockChain *Chain =
2692 new (ChainAllocator.Allocate()) BlockChain(BlockToChain, BB);
2693 // Also, merge any blocks which we cannot reason about and must preserve
2694 // the exact fallthrough behavior for.
2695 while (true) {
2696 Cond.clear();
2697 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For analyzeBranch.
2698 if (!TII->analyzeBranch(*BB, TBB, FBB, Cond) || !FI->canFallThrough())
2699 break;
2700
2701 MachineFunction::iterator NextFI = std::next(FI);
2702 MachineBasicBlock *NextBB = &*NextFI;
2703 // Ensure that the layout successor is a viable block, as we know that
2704 // fallthrough is a possibility.
2705 assert(NextFI != FE && "Can't fallthrough past the last block.");
2706 LLVM_DEBUG(dbgs() << "Pre-merging due to unanalyzable fallthrough: "
2707 << getBlockName(BB) << " -> " << getBlockName(NextBB)
2708 << "\n");
2709 Chain->merge(NextBB, nullptr);
2710 #ifndef NDEBUG
2711 BlocksWithUnanalyzableExits.insert(&*BB);
2712 #endif
2713 FI = NextFI;
2714 BB = NextBB;
2715 }
2716 }
2717
2718 // Build any loop-based chains.
2719 PreferredLoopExit = nullptr;
2720 for (MachineLoop *L : *MLI)
2721 buildLoopChains(*L);
2722
2723 assert(BlockWorkList.empty() &&
2724 "BlockWorkList should be empty before building final chain.");
2725 assert(EHPadWorkList.empty() &&
2726 "EHPadWorkList should be empty before building final chain.");
2727
2728 SmallPtrSet<BlockChain *, 4> UpdatedPreds;
2729 for (MachineBasicBlock &MBB : *F)
2730 fillWorkLists(&MBB, UpdatedPreds);
2731
2732 BlockChain &FunctionChain = *BlockToChain[&F->front()];
2733 buildChain(&F->front(), FunctionChain);
2734
2735 #ifndef NDEBUG
2736 using FunctionBlockSetType = SmallPtrSet<MachineBasicBlock *, 16>;
2737 #endif
2738 LLVM_DEBUG({
2739 // Crash at the end so we get all of the debugging output first.
2740 bool BadFunc = false;
2741 FunctionBlockSetType FunctionBlockSet;
2742 for (MachineBasicBlock &MBB : *F)
2743 FunctionBlockSet.insert(&MBB);
2744
2745 for (MachineBasicBlock *ChainBB : FunctionChain)
2746 if (!FunctionBlockSet.erase(ChainBB)) {
2747 BadFunc = true;
2748 dbgs() << "Function chain contains a block not in the function!\n"
2749 << " Bad block: " << getBlockName(ChainBB) << "\n";
2750 }
2751
2752 if (!FunctionBlockSet.empty()) {
2753 BadFunc = true;
2754 for (MachineBasicBlock *RemainingBB : FunctionBlockSet)
2755 dbgs() << "Function contains blocks never placed into a chain!\n"
2756 << " Bad block: " << getBlockName(RemainingBB) << "\n";
2757 }
2758 assert(!BadFunc && "Detected problems with the block placement.");
2759 });
2760
2761 // Remember original layout ordering, so we can update terminators after
2762 // reordering to point to the original layout successor.
2763 SmallVector<MachineBasicBlock *, 4> OriginalLayoutSuccessors(
2764 F->getNumBlockIDs());
2765 {
2766 MachineBasicBlock *LastMBB = nullptr;
2767 for (auto &MBB : *F) {
2768 if (LastMBB != nullptr)
2769 OriginalLayoutSuccessors[LastMBB->getNumber()] = &MBB;
2770 LastMBB = &MBB;
2771 }
2772 OriginalLayoutSuccessors[F->back().getNumber()] = nullptr;
2773 }
2774
2775 // Splice the blocks into place.
2776 MachineFunction::iterator InsertPos = F->begin();
2777 LLVM_DEBUG(dbgs() << "[MBP] Function: " << F->getName() << "\n");
2778 for (MachineBasicBlock *ChainBB : FunctionChain) {
2779 LLVM_DEBUG(dbgs() << (ChainBB == *FunctionChain.begin() ? "Placing chain "
2780 : " ... ")
2781 << getBlockName(ChainBB) << "\n");
2782 if (InsertPos != MachineFunction::iterator(ChainBB))
2783 F->splice(InsertPos, ChainBB);
2784 else
2785 ++InsertPos;
2786
2787 // Update the terminator of the previous block.
2788 if (ChainBB == *FunctionChain.begin())
2789 continue;
2790 MachineBasicBlock *PrevBB = &*std::prev(MachineFunction::iterator(ChainBB));
2791
2792 // FIXME: It would be awesome of updateTerminator would just return rather
2793 // than assert when the branch cannot be analyzed in order to remove this
2794 // boiler plate.
2795 Cond.clear();
2796 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For analyzeBranch.
2797
2798 #ifndef NDEBUG
2799 if (!BlocksWithUnanalyzableExits.count(PrevBB)) {
2800 // Given the exact block placement we chose, we may actually not _need_ to
2801 // be able to edit PrevBB's terminator sequence, but not being _able_ to
2802 // do that at this point is a bug.
2803 assert((!TII->analyzeBranch(*PrevBB, TBB, FBB, Cond) ||
2804 !PrevBB->canFallThrough()) &&
2805 "Unexpected block with un-analyzable fallthrough!");
2806 Cond.clear();
2807 TBB = FBB = nullptr;
2808 }
2809 #endif
2810
2811 // The "PrevBB" is not yet updated to reflect current code layout, so,
2812 // o. it may fall-through to a block without explicit "goto" instruction
2813 // before layout, and no longer fall-through it after layout; or
2814 // o. just opposite.
2815 //
2816 // analyzeBranch() may return erroneous value for FBB when these two
2817 // situations take place. For the first scenario FBB is mistakenly set NULL;
2818 // for the 2nd scenario, the FBB, which is expected to be NULL, is
2819 // mistakenly pointing to "*BI".
2820 // Thus, if the future change needs to use FBB before the layout is set, it
2821 // has to correct FBB first by using the code similar to the following:
2822 //
2823 // if (!Cond.empty() && (!FBB || FBB == ChainBB)) {
2824 // PrevBB->updateTerminator();
2825 // Cond.clear();
2826 // TBB = FBB = nullptr;
2827 // if (TII->analyzeBranch(*PrevBB, TBB, FBB, Cond)) {
2828 // // FIXME: This should never take place.
2829 // TBB = FBB = nullptr;
2830 // }
2831 // }
2832 if (!TII->analyzeBranch(*PrevBB, TBB, FBB, Cond)) {
2833 PrevBB->updateTerminator(OriginalLayoutSuccessors[PrevBB->getNumber()]);
2834 }
2835 }
2836
2837 // Fixup the last block.
2838 Cond.clear();
2839 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For analyzeBranch.
2840 if (!TII->analyzeBranch(F->back(), TBB, FBB, Cond)) {
2841 MachineBasicBlock *PrevBB = &F->back();
2842 PrevBB->updateTerminator(OriginalLayoutSuccessors[PrevBB->getNumber()]);
2843 }
2844
2845 BlockWorkList.clear();
2846 EHPadWorkList.clear();
2847 }
2848
optimizeBranches()2849 void MachineBlockPlacement::optimizeBranches() {
2850 BlockChain &FunctionChain = *BlockToChain[&F->front()];
2851 SmallVector<MachineOperand, 4> Cond; // For analyzeBranch.
2852
2853 // Now that all the basic blocks in the chain have the proper layout,
2854 // make a final call to analyzeBranch with AllowModify set.
2855 // Indeed, the target may be able to optimize the branches in a way we
2856 // cannot because all branches may not be analyzable.
2857 // E.g., the target may be able to remove an unconditional branch to
2858 // a fallthrough when it occurs after predicated terminators.
2859 for (MachineBasicBlock *ChainBB : FunctionChain) {
2860 Cond.clear();
2861 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For analyzeBranch.
2862 if (!TII->analyzeBranch(*ChainBB, TBB, FBB, Cond, /*AllowModify*/ true)) {
2863 // If PrevBB has a two-way branch, try to re-order the branches
2864 // such that we branch to the successor with higher probability first.
2865 if (TBB && !Cond.empty() && FBB &&
2866 MBPI->getEdgeProbability(ChainBB, FBB) >
2867 MBPI->getEdgeProbability(ChainBB, TBB) &&
2868 !TII->reverseBranchCondition(Cond)) {
2869 LLVM_DEBUG(dbgs() << "Reverse order of the two branches: "
2870 << getBlockName(ChainBB) << "\n");
2871 LLVM_DEBUG(dbgs() << " Edge probability: "
2872 << MBPI->getEdgeProbability(ChainBB, FBB) << " vs "
2873 << MBPI->getEdgeProbability(ChainBB, TBB) << "\n");
2874 DebugLoc dl; // FIXME: this is nowhere
2875 TII->removeBranch(*ChainBB);
2876 TII->insertBranch(*ChainBB, FBB, TBB, Cond, dl);
2877 }
2878 }
2879 }
2880 }
2881
alignBlocks()2882 void MachineBlockPlacement::alignBlocks() {
2883 // Walk through the backedges of the function now that we have fully laid out
2884 // the basic blocks and align the destination of each backedge. We don't rely
2885 // exclusively on the loop info here so that we can align backedges in
2886 // unnatural CFGs and backedges that were introduced purely because of the
2887 // loop rotations done during this layout pass.
2888 if (F->getFunction().hasMinSize() ||
2889 (F->getFunction().hasOptSize() && !TLI->alignLoopsWithOptSize()))
2890 return;
2891 BlockChain &FunctionChain = *BlockToChain[&F->front()];
2892 if (FunctionChain.begin() == FunctionChain.end())
2893 return; // Empty chain.
2894
2895 const BranchProbability ColdProb(1, 5); // 20%
2896 BlockFrequency EntryFreq = MBFI->getBlockFreq(&F->front());
2897 BlockFrequency WeightedEntryFreq = EntryFreq * ColdProb;
2898 for (MachineBasicBlock *ChainBB : FunctionChain) {
2899 if (ChainBB == *FunctionChain.begin())
2900 continue;
2901
2902 // Don't align non-looping basic blocks. These are unlikely to execute
2903 // enough times to matter in practice. Note that we'll still handle
2904 // unnatural CFGs inside of a natural outer loop (the common case) and
2905 // rotated loops.
2906 MachineLoop *L = MLI->getLoopFor(ChainBB);
2907 if (!L)
2908 continue;
2909
2910 const Align Align = TLI->getPrefLoopAlignment(L);
2911 if (Align == 1)
2912 continue; // Don't care about loop alignment.
2913
2914 // If the block is cold relative to the function entry don't waste space
2915 // aligning it.
2916 BlockFrequency Freq = MBFI->getBlockFreq(ChainBB);
2917 if (Freq < WeightedEntryFreq)
2918 continue;
2919
2920 // If the block is cold relative to its loop header, don't align it
2921 // regardless of what edges into the block exist.
2922 MachineBasicBlock *LoopHeader = L->getHeader();
2923 BlockFrequency LoopHeaderFreq = MBFI->getBlockFreq(LoopHeader);
2924 if (Freq < (LoopHeaderFreq * ColdProb))
2925 continue;
2926
2927 // If the global profiles indicates so, don't align it.
2928 if (llvm::shouldOptimizeForSize(ChainBB, PSI, MBFI.get()) &&
2929 !TLI->alignLoopsWithOptSize())
2930 continue;
2931
2932 // Check for the existence of a non-layout predecessor which would benefit
2933 // from aligning this block.
2934 MachineBasicBlock *LayoutPred =
2935 &*std::prev(MachineFunction::iterator(ChainBB));
2936
2937 auto DetermineMaxAlignmentPadding = [&]() {
2938 // Set the maximum bytes allowed to be emitted for alignment.
2939 unsigned MaxBytes;
2940 if (MaxBytesForAlignmentOverride.getNumOccurrences() > 0)
2941 MaxBytes = MaxBytesForAlignmentOverride;
2942 else
2943 MaxBytes = TLI->getMaxPermittedBytesForAlignment(ChainBB);
2944 ChainBB->setMaxBytesForAlignment(MaxBytes);
2945 };
2946
2947 // Force alignment if all the predecessors are jumps. We already checked
2948 // that the block isn't cold above.
2949 if (!LayoutPred->isSuccessor(ChainBB)) {
2950 ChainBB->setAlignment(Align);
2951 DetermineMaxAlignmentPadding();
2952 continue;
2953 }
2954
2955 // Align this block if the layout predecessor's edge into this block is
2956 // cold relative to the block. When this is true, other predecessors make up
2957 // all of the hot entries into the block and thus alignment is likely to be
2958 // important.
2959 BranchProbability LayoutProb =
2960 MBPI->getEdgeProbability(LayoutPred, ChainBB);
2961 BlockFrequency LayoutEdgeFreq = MBFI->getBlockFreq(LayoutPred) * LayoutProb;
2962 if (LayoutEdgeFreq <= (Freq * ColdProb)) {
2963 ChainBB->setAlignment(Align);
2964 DetermineMaxAlignmentPadding();
2965 }
2966 }
2967 }
2968
2969 /// Tail duplicate \p BB into (some) predecessors if profitable, repeating if
2970 /// it was duplicated into its chain predecessor and removed.
2971 /// \p BB - Basic block that may be duplicated.
2972 ///
2973 /// \p LPred - Chosen layout predecessor of \p BB.
2974 /// Updated to be the chain end if LPred is removed.
2975 /// \p Chain - Chain to which \p LPred belongs, and \p BB will belong.
2976 /// \p BlockFilter - Set of blocks that belong to the loop being laid out.
2977 /// Used to identify which blocks to update predecessor
2978 /// counts.
2979 /// \p PrevUnplacedBlockIt - Iterator pointing to the last block that was
2980 /// chosen in the given order due to unnatural CFG
2981 /// only needed if \p BB is removed and
2982 /// \p PrevUnplacedBlockIt pointed to \p BB.
2983 /// @return true if \p BB was removed.
repeatedlyTailDuplicateBlock(MachineBasicBlock * BB,MachineBasicBlock * & LPred,const MachineBasicBlock * LoopHeaderBB,BlockChain & Chain,BlockFilterSet * BlockFilter,MachineFunction::iterator & PrevUnplacedBlockIt)2984 bool MachineBlockPlacement::repeatedlyTailDuplicateBlock(
2985 MachineBasicBlock *BB, MachineBasicBlock *&LPred,
2986 const MachineBasicBlock *LoopHeaderBB,
2987 BlockChain &Chain, BlockFilterSet *BlockFilter,
2988 MachineFunction::iterator &PrevUnplacedBlockIt) {
2989 bool Removed, DuplicatedToLPred;
2990 bool DuplicatedToOriginalLPred;
2991 Removed = maybeTailDuplicateBlock(BB, LPred, Chain, BlockFilter,
2992 PrevUnplacedBlockIt,
2993 DuplicatedToLPred);
2994 if (!Removed)
2995 return false;
2996 DuplicatedToOriginalLPred = DuplicatedToLPred;
2997 // Iteratively try to duplicate again. It can happen that a block that is
2998 // duplicated into is still small enough to be duplicated again.
2999 // No need to call markBlockSuccessors in this case, as the blocks being
3000 // duplicated from here on are already scheduled.
3001 while (DuplicatedToLPred && Removed) {
3002 MachineBasicBlock *DupBB, *DupPred;
3003 // The removal callback causes Chain.end() to be updated when a block is
3004 // removed. On the first pass through the loop, the chain end should be the
3005 // same as it was on function entry. On subsequent passes, because we are
3006 // duplicating the block at the end of the chain, if it is removed the
3007 // chain will have shrunk by one block.
3008 BlockChain::iterator ChainEnd = Chain.end();
3009 DupBB = *(--ChainEnd);
3010 // Now try to duplicate again.
3011 if (ChainEnd == Chain.begin())
3012 break;
3013 DupPred = *std::prev(ChainEnd);
3014 Removed = maybeTailDuplicateBlock(DupBB, DupPred, Chain, BlockFilter,
3015 PrevUnplacedBlockIt,
3016 DuplicatedToLPred);
3017 }
3018 // If BB was duplicated into LPred, it is now scheduled. But because it was
3019 // removed, markChainSuccessors won't be called for its chain. Instead we
3020 // call markBlockSuccessors for LPred to achieve the same effect. This must go
3021 // at the end because repeating the tail duplication can increase the number
3022 // of unscheduled predecessors.
3023 LPred = *std::prev(Chain.end());
3024 if (DuplicatedToOriginalLPred)
3025 markBlockSuccessors(Chain, LPred, LoopHeaderBB, BlockFilter);
3026 return true;
3027 }
3028
3029 /// Tail duplicate \p BB into (some) predecessors if profitable.
3030 /// \p BB - Basic block that may be duplicated
3031 /// \p LPred - Chosen layout predecessor of \p BB
3032 /// \p Chain - Chain to which \p LPred belongs, and \p BB will belong.
3033 /// \p BlockFilter - Set of blocks that belong to the loop being laid out.
3034 /// Used to identify which blocks to update predecessor
3035 /// counts.
3036 /// \p PrevUnplacedBlockIt - Iterator pointing to the last block that was
3037 /// chosen in the given order due to unnatural CFG
3038 /// only needed if \p BB is removed and
3039 /// \p PrevUnplacedBlockIt pointed to \p BB.
3040 /// \p DuplicatedToLPred - True if the block was duplicated into LPred.
3041 /// \return - True if the block was duplicated into all preds and removed.
maybeTailDuplicateBlock(MachineBasicBlock * BB,MachineBasicBlock * LPred,BlockChain & Chain,BlockFilterSet * BlockFilter,MachineFunction::iterator & PrevUnplacedBlockIt,bool & DuplicatedToLPred)3042 bool MachineBlockPlacement::maybeTailDuplicateBlock(
3043 MachineBasicBlock *BB, MachineBasicBlock *LPred,
3044 BlockChain &Chain, BlockFilterSet *BlockFilter,
3045 MachineFunction::iterator &PrevUnplacedBlockIt,
3046 bool &DuplicatedToLPred) {
3047 DuplicatedToLPred = false;
3048 if (!shouldTailDuplicate(BB))
3049 return false;
3050
3051 LLVM_DEBUG(dbgs() << "Redoing tail duplication for Succ#" << BB->getNumber()
3052 << "\n");
3053
3054 // This has to be a callback because none of it can be done after
3055 // BB is deleted.
3056 bool Removed = false;
3057 auto RemovalCallback =
3058 [&](MachineBasicBlock *RemBB) {
3059 // Signal to outer function
3060 Removed = true;
3061
3062 // Conservative default.
3063 bool InWorkList = true;
3064 // Remove from the Chain and Chain Map
3065 if (BlockToChain.count(RemBB)) {
3066 BlockChain *Chain = BlockToChain[RemBB];
3067 InWorkList = Chain->UnscheduledPredecessors == 0;
3068 Chain->remove(RemBB);
3069 BlockToChain.erase(RemBB);
3070 }
3071
3072 // Handle the unplaced block iterator
3073 if (&(*PrevUnplacedBlockIt) == RemBB) {
3074 PrevUnplacedBlockIt++;
3075 }
3076
3077 // Handle the Work Lists
3078 if (InWorkList) {
3079 SmallVectorImpl<MachineBasicBlock *> &RemoveList = BlockWorkList;
3080 if (RemBB->isEHPad())
3081 RemoveList = EHPadWorkList;
3082 llvm::erase_value(RemoveList, RemBB);
3083 }
3084
3085 // Handle the filter set
3086 if (BlockFilter) {
3087 BlockFilter->remove(RemBB);
3088 }
3089
3090 // Remove the block from loop info.
3091 MLI->removeBlock(RemBB);
3092 if (RemBB == PreferredLoopExit)
3093 PreferredLoopExit = nullptr;
3094
3095 LLVM_DEBUG(dbgs() << "TailDuplicator deleted block: "
3096 << getBlockName(RemBB) << "\n");
3097 };
3098 auto RemovalCallbackRef =
3099 function_ref<void(MachineBasicBlock*)>(RemovalCallback);
3100
3101 SmallVector<MachineBasicBlock *, 8> DuplicatedPreds;
3102 bool IsSimple = TailDup.isSimpleBB(BB);
3103 SmallVector<MachineBasicBlock *, 8> CandidatePreds;
3104 SmallVectorImpl<MachineBasicBlock *> *CandidatePtr = nullptr;
3105 if (F->getFunction().hasProfileData()) {
3106 // We can do partial duplication with precise profile information.
3107 findDuplicateCandidates(CandidatePreds, BB, BlockFilter);
3108 if (CandidatePreds.size() == 0)
3109 return false;
3110 if (CandidatePreds.size() < BB->pred_size())
3111 CandidatePtr = &CandidatePreds;
3112 }
3113 TailDup.tailDuplicateAndUpdate(IsSimple, BB, LPred, &DuplicatedPreds,
3114 &RemovalCallbackRef, CandidatePtr);
3115
3116 // Update UnscheduledPredecessors to reflect tail-duplication.
3117 DuplicatedToLPred = false;
3118 for (MachineBasicBlock *Pred : DuplicatedPreds) {
3119 // We're only looking for unscheduled predecessors that match the filter.
3120 BlockChain* PredChain = BlockToChain[Pred];
3121 if (Pred == LPred)
3122 DuplicatedToLPred = true;
3123 if (Pred == LPred || (BlockFilter && !BlockFilter->count(Pred))
3124 || PredChain == &Chain)
3125 continue;
3126 for (MachineBasicBlock *NewSucc : Pred->successors()) {
3127 if (BlockFilter && !BlockFilter->count(NewSucc))
3128 continue;
3129 BlockChain *NewChain = BlockToChain[NewSucc];
3130 if (NewChain != &Chain && NewChain != PredChain)
3131 NewChain->UnscheduledPredecessors++;
3132 }
3133 }
3134 return Removed;
3135 }
3136
3137 // Count the number of actual machine instructions.
countMBBInstruction(MachineBasicBlock * MBB)3138 static uint64_t countMBBInstruction(MachineBasicBlock *MBB) {
3139 uint64_t InstrCount = 0;
3140 for (MachineInstr &MI : *MBB) {
3141 if (!MI.isPHI() && !MI.isMetaInstruction())
3142 InstrCount += 1;
3143 }
3144 return InstrCount;
3145 }
3146
3147 // The size cost of duplication is the instruction size of the duplicated block.
3148 // So we should scale the threshold accordingly. But the instruction size is not
3149 // available on all targets, so we use the number of instructions instead.
scaleThreshold(MachineBasicBlock * BB)3150 BlockFrequency MachineBlockPlacement::scaleThreshold(MachineBasicBlock *BB) {
3151 return DupThreshold.getFrequency() * countMBBInstruction(BB);
3152 }
3153
3154 // Returns true if BB is Pred's best successor.
isBestSuccessor(MachineBasicBlock * BB,MachineBasicBlock * Pred,BlockFilterSet * BlockFilter)3155 bool MachineBlockPlacement::isBestSuccessor(MachineBasicBlock *BB,
3156 MachineBasicBlock *Pred,
3157 BlockFilterSet *BlockFilter) {
3158 if (BB == Pred)
3159 return false;
3160 if (BlockFilter && !BlockFilter->count(Pred))
3161 return false;
3162 BlockChain *PredChain = BlockToChain[Pred];
3163 if (PredChain && (Pred != *std::prev(PredChain->end())))
3164 return false;
3165
3166 // Find the successor with largest probability excluding BB.
3167 BranchProbability BestProb = BranchProbability::getZero();
3168 for (MachineBasicBlock *Succ : Pred->successors())
3169 if (Succ != BB) {
3170 if (BlockFilter && !BlockFilter->count(Succ))
3171 continue;
3172 BlockChain *SuccChain = BlockToChain[Succ];
3173 if (SuccChain && (Succ != *SuccChain->begin()))
3174 continue;
3175 BranchProbability SuccProb = MBPI->getEdgeProbability(Pred, Succ);
3176 if (SuccProb > BestProb)
3177 BestProb = SuccProb;
3178 }
3179
3180 BranchProbability BBProb = MBPI->getEdgeProbability(Pred, BB);
3181 if (BBProb <= BestProb)
3182 return false;
3183
3184 // Compute the number of reduced taken branches if Pred falls through to BB
3185 // instead of another successor. Then compare it with threshold.
3186 BlockFrequency PredFreq = getBlockCountOrFrequency(Pred);
3187 BlockFrequency Gain = PredFreq * (BBProb - BestProb);
3188 return Gain > scaleThreshold(BB);
3189 }
3190
3191 // Find out the predecessors of BB and BB can be beneficially duplicated into
3192 // them.
findDuplicateCandidates(SmallVectorImpl<MachineBasicBlock * > & Candidates,MachineBasicBlock * BB,BlockFilterSet * BlockFilter)3193 void MachineBlockPlacement::findDuplicateCandidates(
3194 SmallVectorImpl<MachineBasicBlock *> &Candidates,
3195 MachineBasicBlock *BB,
3196 BlockFilterSet *BlockFilter) {
3197 MachineBasicBlock *Fallthrough = nullptr;
3198 BranchProbability DefaultBranchProb = BranchProbability::getZero();
3199 BlockFrequency BBDupThreshold(scaleThreshold(BB));
3200 SmallVector<MachineBasicBlock *, 8> Preds(BB->predecessors());
3201 SmallVector<MachineBasicBlock *, 8> Succs(BB->successors());
3202
3203 // Sort for highest frequency.
3204 auto CmpSucc = [&](MachineBasicBlock *A, MachineBasicBlock *B) {
3205 return MBPI->getEdgeProbability(BB, A) > MBPI->getEdgeProbability(BB, B);
3206 };
3207 auto CmpPred = [&](MachineBasicBlock *A, MachineBasicBlock *B) {
3208 return MBFI->getBlockFreq(A) > MBFI->getBlockFreq(B);
3209 };
3210 llvm::stable_sort(Succs, CmpSucc);
3211 llvm::stable_sort(Preds, CmpPred);
3212
3213 auto SuccIt = Succs.begin();
3214 if (SuccIt != Succs.end()) {
3215 DefaultBranchProb = MBPI->getEdgeProbability(BB, *SuccIt).getCompl();
3216 }
3217
3218 // For each predecessors of BB, compute the benefit of duplicating BB,
3219 // if it is larger than the threshold, add it into Candidates.
3220 //
3221 // If we have following control flow.
3222 //
3223 // PB1 PB2 PB3 PB4
3224 // \ | / /\
3225 // \ | / / \
3226 // \ |/ / \
3227 // BB----/ OB
3228 // /\
3229 // / \
3230 // SB1 SB2
3231 //
3232 // And it can be partially duplicated as
3233 //
3234 // PB2+BB
3235 // | PB1 PB3 PB4
3236 // | | / /\
3237 // | | / / \
3238 // | |/ / \
3239 // | BB----/ OB
3240 // |\ /|
3241 // | X |
3242 // |/ \|
3243 // SB2 SB1
3244 //
3245 // The benefit of duplicating into a predecessor is defined as
3246 // Orig_taken_branch - Duplicated_taken_branch
3247 //
3248 // The Orig_taken_branch is computed with the assumption that predecessor
3249 // jumps to BB and the most possible successor is laid out after BB.
3250 //
3251 // The Duplicated_taken_branch is computed with the assumption that BB is
3252 // duplicated into PB, and one successor is layout after it (SB1 for PB1 and
3253 // SB2 for PB2 in our case). If there is no available successor, the combined
3254 // block jumps to all BB's successor, like PB3 in this example.
3255 //
3256 // If a predecessor has multiple successors, so BB can't be duplicated into
3257 // it. But it can beneficially fall through to BB, and duplicate BB into other
3258 // predecessors.
3259 for (MachineBasicBlock *Pred : Preds) {
3260 BlockFrequency PredFreq = getBlockCountOrFrequency(Pred);
3261
3262 if (!TailDup.canTailDuplicate(BB, Pred)) {
3263 // BB can't be duplicated into Pred, but it is possible to be layout
3264 // below Pred.
3265 if (!Fallthrough && isBestSuccessor(BB, Pred, BlockFilter)) {
3266 Fallthrough = Pred;
3267 if (SuccIt != Succs.end())
3268 SuccIt++;
3269 }
3270 continue;
3271 }
3272
3273 BlockFrequency OrigCost = PredFreq + PredFreq * DefaultBranchProb;
3274 BlockFrequency DupCost;
3275 if (SuccIt == Succs.end()) {
3276 // Jump to all successors;
3277 if (Succs.size() > 0)
3278 DupCost += PredFreq;
3279 } else {
3280 // Fallthrough to *SuccIt, jump to all other successors;
3281 DupCost += PredFreq;
3282 DupCost -= PredFreq * MBPI->getEdgeProbability(BB, *SuccIt);
3283 }
3284
3285 assert(OrigCost >= DupCost);
3286 OrigCost -= DupCost;
3287 if (OrigCost > BBDupThreshold) {
3288 Candidates.push_back(Pred);
3289 if (SuccIt != Succs.end())
3290 SuccIt++;
3291 }
3292 }
3293
3294 // No predecessors can optimally fallthrough to BB.
3295 // So we can change one duplication into fallthrough.
3296 if (!Fallthrough) {
3297 if ((Candidates.size() < Preds.size()) && (Candidates.size() > 0)) {
3298 Candidates[0] = Candidates.back();
3299 Candidates.pop_back();
3300 }
3301 }
3302 }
3303
initDupThreshold()3304 void MachineBlockPlacement::initDupThreshold() {
3305 DupThreshold = 0;
3306 if (!F->getFunction().hasProfileData())
3307 return;
3308
3309 // We prefer to use prifile count.
3310 uint64_t HotThreshold = PSI->getOrCompHotCountThreshold();
3311 if (HotThreshold != UINT64_MAX) {
3312 UseProfileCount = true;
3313 DupThreshold = HotThreshold * TailDupProfilePercentThreshold / 100;
3314 return;
3315 }
3316
3317 // Profile count is not available, we can use block frequency instead.
3318 BlockFrequency MaxFreq = 0;
3319 for (MachineBasicBlock &MBB : *F) {
3320 BlockFrequency Freq = MBFI->getBlockFreq(&MBB);
3321 if (Freq > MaxFreq)
3322 MaxFreq = Freq;
3323 }
3324
3325 BranchProbability ThresholdProb(TailDupPlacementPenalty, 100);
3326 DupThreshold = MaxFreq * ThresholdProb;
3327 UseProfileCount = false;
3328 }
3329
runOnMachineFunction(MachineFunction & MF)3330 bool MachineBlockPlacement::runOnMachineFunction(MachineFunction &MF) {
3331 if (skipFunction(MF.getFunction()))
3332 return false;
3333
3334 // Check for single-block functions and skip them.
3335 if (std::next(MF.begin()) == MF.end())
3336 return false;
3337
3338 F = &MF;
3339 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
3340 MBFI = std::make_unique<MBFIWrapper>(
3341 getAnalysis<MachineBlockFrequencyInfo>());
3342 MLI = &getAnalysis<MachineLoopInfo>();
3343 TII = MF.getSubtarget().getInstrInfo();
3344 TLI = MF.getSubtarget().getTargetLowering();
3345 MPDT = nullptr;
3346 PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
3347
3348 initDupThreshold();
3349
3350 // Initialize PreferredLoopExit to nullptr here since it may never be set if
3351 // there are no MachineLoops.
3352 PreferredLoopExit = nullptr;
3353
3354 assert(BlockToChain.empty() &&
3355 "BlockToChain map should be empty before starting placement.");
3356 assert(ComputedEdges.empty() &&
3357 "Computed Edge map should be empty before starting placement.");
3358
3359 unsigned TailDupSize = TailDupPlacementThreshold;
3360 // If only the aggressive threshold is explicitly set, use it.
3361 if (TailDupPlacementAggressiveThreshold.getNumOccurrences() != 0 &&
3362 TailDupPlacementThreshold.getNumOccurrences() == 0)
3363 TailDupSize = TailDupPlacementAggressiveThreshold;
3364
3365 TargetPassConfig *PassConfig = &getAnalysis<TargetPassConfig>();
3366 // For aggressive optimization, we can adjust some thresholds to be less
3367 // conservative.
3368 if (PassConfig->getOptLevel() >= CodeGenOpt::Aggressive) {
3369 // At O3 we should be more willing to copy blocks for tail duplication. This
3370 // increases size pressure, so we only do it at O3
3371 // Do this unless only the regular threshold is explicitly set.
3372 if (TailDupPlacementThreshold.getNumOccurrences() == 0 ||
3373 TailDupPlacementAggressiveThreshold.getNumOccurrences() != 0)
3374 TailDupSize = TailDupPlacementAggressiveThreshold;
3375 }
3376
3377 // If there's no threshold provided through options, query the target
3378 // information for a threshold instead.
3379 if (TailDupPlacementThreshold.getNumOccurrences() == 0 &&
3380 (PassConfig->getOptLevel() < CodeGenOpt::Aggressive ||
3381 TailDupPlacementAggressiveThreshold.getNumOccurrences() == 0))
3382 TailDupSize = TII->getTailDuplicateSize(PassConfig->getOptLevel());
3383
3384 if (allowTailDupPlacement()) {
3385 MPDT = &getAnalysis<MachinePostDominatorTree>();
3386 bool OptForSize = MF.getFunction().hasOptSize() ||
3387 llvm::shouldOptimizeForSize(&MF, PSI, &MBFI->getMBFI());
3388 if (OptForSize)
3389 TailDupSize = 1;
3390 bool PreRegAlloc = false;
3391 TailDup.initMF(MF, PreRegAlloc, MBPI, MBFI.get(), PSI,
3392 /* LayoutMode */ true, TailDupSize);
3393 precomputeTriangleChains();
3394 }
3395
3396 buildCFGChains();
3397
3398 // Changing the layout can create new tail merging opportunities.
3399 // TailMerge can create jump into if branches that make CFG irreducible for
3400 // HW that requires structured CFG.
3401 bool EnableTailMerge = !MF.getTarget().requiresStructuredCFG() &&
3402 PassConfig->getEnableTailMerge() &&
3403 BranchFoldPlacement;
3404 // No tail merging opportunities if the block number is less than four.
3405 if (MF.size() > 3 && EnableTailMerge) {
3406 unsigned TailMergeSize = TailDupSize + 1;
3407 BranchFolder BF(/*DefaultEnableTailMerge=*/true, /*CommonHoist=*/false,
3408 *MBFI, *MBPI, PSI, TailMergeSize);
3409
3410 if (BF.OptimizeFunction(MF, TII, MF.getSubtarget().getRegisterInfo(), MLI,
3411 /*AfterPlacement=*/true)) {
3412 // Redo the layout if tail merging creates/removes/moves blocks.
3413 BlockToChain.clear();
3414 ComputedEdges.clear();
3415 // Must redo the post-dominator tree if blocks were changed.
3416 if (MPDT)
3417 MPDT->runOnMachineFunction(MF);
3418 ChainAllocator.DestroyAll();
3419 buildCFGChains();
3420 }
3421 }
3422
3423 // Apply a post-processing optimizing block placement.
3424 if (MF.size() >= 3 && EnableExtTspBlockPlacement &&
3425 (ApplyExtTspWithoutProfile || MF.getFunction().hasProfileData())) {
3426 // Find a new placement and modify the layout of the blocks in the function.
3427 applyExtTsp();
3428
3429 // Re-create CFG chain so that we can optimizeBranches and alignBlocks.
3430 createCFGChainExtTsp();
3431 }
3432
3433 optimizeBranches();
3434 alignBlocks();
3435
3436 BlockToChain.clear();
3437 ComputedEdges.clear();
3438 ChainAllocator.DestroyAll();
3439
3440 bool HasMaxBytesOverride =
3441 MaxBytesForAlignmentOverride.getNumOccurrences() > 0;
3442
3443 if (AlignAllBlock)
3444 // Align all of the blocks in the function to a specific alignment.
3445 for (MachineBasicBlock &MBB : MF) {
3446 if (HasMaxBytesOverride)
3447 MBB.setAlignment(Align(1ULL << AlignAllBlock),
3448 MaxBytesForAlignmentOverride);
3449 else
3450 MBB.setAlignment(Align(1ULL << AlignAllBlock));
3451 }
3452 else if (AlignAllNonFallThruBlocks) {
3453 // Align all of the blocks that have no fall-through predecessors to a
3454 // specific alignment.
3455 for (auto MBI = std::next(MF.begin()), MBE = MF.end(); MBI != MBE; ++MBI) {
3456 auto LayoutPred = std::prev(MBI);
3457 if (!LayoutPred->isSuccessor(&*MBI)) {
3458 if (HasMaxBytesOverride)
3459 MBI->setAlignment(Align(1ULL << AlignAllNonFallThruBlocks),
3460 MaxBytesForAlignmentOverride);
3461 else
3462 MBI->setAlignment(Align(1ULL << AlignAllNonFallThruBlocks));
3463 }
3464 }
3465 }
3466 if (ViewBlockLayoutWithBFI != GVDT_None &&
3467 (ViewBlockFreqFuncName.empty() ||
3468 F->getFunction().getName().equals(ViewBlockFreqFuncName))) {
3469 MBFI->view("MBP." + MF.getName(), false);
3470 }
3471
3472 // We always return true as we have no way to track whether the final order
3473 // differs from the original order.
3474 return true;
3475 }
3476
applyExtTsp()3477 void MachineBlockPlacement::applyExtTsp() {
3478 // Prepare data; blocks are indexed by their index in the current ordering.
3479 DenseMap<const MachineBasicBlock *, uint64_t> BlockIndex;
3480 BlockIndex.reserve(F->size());
3481 std::vector<const MachineBasicBlock *> CurrentBlockOrder;
3482 CurrentBlockOrder.reserve(F->size());
3483 size_t NumBlocks = 0;
3484 for (const MachineBasicBlock &MBB : *F) {
3485 BlockIndex[&MBB] = NumBlocks++;
3486 CurrentBlockOrder.push_back(&MBB);
3487 }
3488
3489 auto BlockSizes = std::vector<uint64_t>(F->size());
3490 auto BlockCounts = std::vector<uint64_t>(F->size());
3491 DenseMap<std::pair<uint64_t, uint64_t>, uint64_t> JumpCounts;
3492 for (MachineBasicBlock &MBB : *F) {
3493 // Getting the block frequency.
3494 BlockFrequency BlockFreq = MBFI->getBlockFreq(&MBB);
3495 BlockCounts[BlockIndex[&MBB]] = BlockFreq.getFrequency();
3496 // Getting the block size:
3497 // - approximate the size of an instruction by 4 bytes, and
3498 // - ignore debug instructions.
3499 // Note: getting the exact size of each block is target-dependent and can be
3500 // done by extending the interface of MCCodeEmitter. Experimentally we do
3501 // not see a perf improvement with the exact block sizes.
3502 auto NonDbgInsts =
3503 instructionsWithoutDebug(MBB.instr_begin(), MBB.instr_end());
3504 int NumInsts = std::distance(NonDbgInsts.begin(), NonDbgInsts.end());
3505 BlockSizes[BlockIndex[&MBB]] = 4 * NumInsts;
3506 // Getting jump frequencies.
3507 for (MachineBasicBlock *Succ : MBB.successors()) {
3508 auto EP = MBPI->getEdgeProbability(&MBB, Succ);
3509 BlockFrequency EdgeFreq = BlockFreq * EP;
3510 auto Edge = std::make_pair(BlockIndex[&MBB], BlockIndex[Succ]);
3511 JumpCounts[Edge] = EdgeFreq.getFrequency();
3512 }
3513 }
3514
3515 LLVM_DEBUG(dbgs() << "Applying ext-tsp layout for |V| = " << F->size()
3516 << " with profile = " << F->getFunction().hasProfileData()
3517 << " (" << F->getName().str() << ")"
3518 << "\n");
3519 LLVM_DEBUG(
3520 dbgs() << format(" original layout score: %0.2f\n",
3521 calcExtTspScore(BlockSizes, BlockCounts, JumpCounts)));
3522
3523 // Run the layout algorithm.
3524 auto NewOrder = applyExtTspLayout(BlockSizes, BlockCounts, JumpCounts);
3525 std::vector<const MachineBasicBlock *> NewBlockOrder;
3526 NewBlockOrder.reserve(F->size());
3527 for (uint64_t Node : NewOrder) {
3528 NewBlockOrder.push_back(CurrentBlockOrder[Node]);
3529 }
3530 LLVM_DEBUG(dbgs() << format(" optimized layout score: %0.2f\n",
3531 calcExtTspScore(NewOrder, BlockSizes, BlockCounts,
3532 JumpCounts)));
3533
3534 // Assign new block order.
3535 assignBlockOrder(NewBlockOrder);
3536 }
3537
assignBlockOrder(const std::vector<const MachineBasicBlock * > & NewBlockOrder)3538 void MachineBlockPlacement::assignBlockOrder(
3539 const std::vector<const MachineBasicBlock *> &NewBlockOrder) {
3540 assert(F->size() == NewBlockOrder.size() && "Incorrect size of block order");
3541 F->RenumberBlocks();
3542
3543 bool HasChanges = false;
3544 for (size_t I = 0; I < NewBlockOrder.size(); I++) {
3545 if (NewBlockOrder[I] != F->getBlockNumbered(I)) {
3546 HasChanges = true;
3547 break;
3548 }
3549 }
3550 // Stop early if the new block order is identical to the existing one.
3551 if (!HasChanges)
3552 return;
3553
3554 SmallVector<MachineBasicBlock *, 4> PrevFallThroughs(F->getNumBlockIDs());
3555 for (auto &MBB : *F) {
3556 PrevFallThroughs[MBB.getNumber()] = MBB.getFallThrough();
3557 }
3558
3559 // Sort basic blocks in the function according to the computed order.
3560 DenseMap<const MachineBasicBlock *, size_t> NewIndex;
3561 for (const MachineBasicBlock *MBB : NewBlockOrder) {
3562 NewIndex[MBB] = NewIndex.size();
3563 }
3564 F->sort([&](MachineBasicBlock &L, MachineBasicBlock &R) {
3565 return NewIndex[&L] < NewIndex[&R];
3566 });
3567
3568 // Update basic block branches by inserting explicit fallthrough branches
3569 // when required and re-optimize branches when possible.
3570 const TargetInstrInfo *TII = F->getSubtarget().getInstrInfo();
3571 SmallVector<MachineOperand, 4> Cond;
3572 for (auto &MBB : *F) {
3573 MachineFunction::iterator NextMBB = std::next(MBB.getIterator());
3574 MachineFunction::iterator EndIt = MBB.getParent()->end();
3575 auto *FTMBB = PrevFallThroughs[MBB.getNumber()];
3576 // If this block had a fallthrough before we need an explicit unconditional
3577 // branch to that block if the fallthrough block is not adjacent to the
3578 // block in the new order.
3579 if (FTMBB && (NextMBB == EndIt || &*NextMBB != FTMBB)) {
3580 TII->insertUnconditionalBranch(MBB, FTMBB, MBB.findBranchDebugLoc());
3581 }
3582
3583 // It might be possible to optimize branches by flipping the condition.
3584 Cond.clear();
3585 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
3586 if (TII->analyzeBranch(MBB, TBB, FBB, Cond))
3587 continue;
3588 MBB.updateTerminator(FTMBB);
3589 }
3590
3591 #ifndef NDEBUG
3592 // Make sure we correctly constructed all branches.
3593 F->verify(this, "After optimized block reordering");
3594 #endif
3595 }
3596
createCFGChainExtTsp()3597 void MachineBlockPlacement::createCFGChainExtTsp() {
3598 BlockToChain.clear();
3599 ComputedEdges.clear();
3600 ChainAllocator.DestroyAll();
3601
3602 MachineBasicBlock *HeadBB = &F->front();
3603 BlockChain *FunctionChain =
3604 new (ChainAllocator.Allocate()) BlockChain(BlockToChain, HeadBB);
3605
3606 for (MachineBasicBlock &MBB : *F) {
3607 if (HeadBB == &MBB)
3608 continue; // Ignore head of the chain
3609 FunctionChain->merge(&MBB, nullptr);
3610 }
3611 }
3612
3613 namespace {
3614
3615 /// A pass to compute block placement statistics.
3616 ///
3617 /// A separate pass to compute interesting statistics for evaluating block
3618 /// placement. This is separate from the actual placement pass so that they can
3619 /// be computed in the absence of any placement transformations or when using
3620 /// alternative placement strategies.
3621 class MachineBlockPlacementStats : public MachineFunctionPass {
3622 /// A handle to the branch probability pass.
3623 const MachineBranchProbabilityInfo *MBPI;
3624
3625 /// A handle to the function-wide block frequency pass.
3626 const MachineBlockFrequencyInfo *MBFI;
3627
3628 public:
3629 static char ID; // Pass identification, replacement for typeid
3630
MachineBlockPlacementStats()3631 MachineBlockPlacementStats() : MachineFunctionPass(ID) {
3632 initializeMachineBlockPlacementStatsPass(*PassRegistry::getPassRegistry());
3633 }
3634
3635 bool runOnMachineFunction(MachineFunction &F) override;
3636
getAnalysisUsage(AnalysisUsage & AU) const3637 void getAnalysisUsage(AnalysisUsage &AU) const override {
3638 AU.addRequired<MachineBranchProbabilityInfo>();
3639 AU.addRequired<MachineBlockFrequencyInfo>();
3640 AU.setPreservesAll();
3641 MachineFunctionPass::getAnalysisUsage(AU);
3642 }
3643 };
3644
3645 } // end anonymous namespace
3646
3647 char MachineBlockPlacementStats::ID = 0;
3648
3649 char &llvm::MachineBlockPlacementStatsID = MachineBlockPlacementStats::ID;
3650
3651 INITIALIZE_PASS_BEGIN(MachineBlockPlacementStats, "block-placement-stats",
3652 "Basic Block Placement Stats", false, false)
INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)3653 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
3654 INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
3655 INITIALIZE_PASS_END(MachineBlockPlacementStats, "block-placement-stats",
3656 "Basic Block Placement Stats", false, false)
3657
3658 bool MachineBlockPlacementStats::runOnMachineFunction(MachineFunction &F) {
3659 // Check for single-block functions and skip them.
3660 if (std::next(F.begin()) == F.end())
3661 return false;
3662
3663 if (!isFunctionInPrintList(F.getName()))
3664 return false;
3665
3666 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
3667 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
3668
3669 for (MachineBasicBlock &MBB : F) {
3670 BlockFrequency BlockFreq = MBFI->getBlockFreq(&MBB);
3671 Statistic &NumBranches =
3672 (MBB.succ_size() > 1) ? NumCondBranches : NumUncondBranches;
3673 Statistic &BranchTakenFreq =
3674 (MBB.succ_size() > 1) ? CondBranchTakenFreq : UncondBranchTakenFreq;
3675 for (MachineBasicBlock *Succ : MBB.successors()) {
3676 // Skip if this successor is a fallthrough.
3677 if (MBB.isLayoutSuccessor(Succ))
3678 continue;
3679
3680 BlockFrequency EdgeFreq =
3681 BlockFreq * MBPI->getEdgeProbability(&MBB, Succ);
3682 ++NumBranches;
3683 BranchTakenFreq += EdgeFreq.getFrequency();
3684 }
3685 }
3686
3687 return false;
3688 }
3689