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