1 //===-- MachineBlockPlacement.cpp - Basic Block Code Layout optimization --===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements basic block placement transformations using the CFG
11 // structure and branch probability estimates.
13 // The pass strives to preserve the structure of the CFG (that is, retain
14 // a topological ordering of basic blocks) in the absence of a *strong* signal
15 // to the contrary from probabilities. However, within the CFG structure, it
16 // attempts to choose an ordering which favors placing more likely sequences of
17 // blocks adjacent to each other.
19 // The algorithm works from the inner-most loop within a function outward, and
20 // at each stage walks through the basic blocks, trying to coalesce them into
21 // sequential chains where allowed by the CFG (or demanded by heavy
22 // probabilities). Finally, it walks the blocks in topological order, and the
23 // first time it reaches a chain of basic blocks, it schedules them in the
26 //===----------------------------------------------------------------------===//
28 #include "llvm/CodeGen/Passes.h"
29 #include "llvm/ADT/DenseMap.h"
30 #include "llvm/ADT/SmallPtrSet.h"
31 #include "llvm/ADT/SmallVector.h"
32 #include "llvm/ADT/Statistic.h"
33 #include "llvm/CodeGen/MachineBasicBlock.h"
34 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
35 #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
36 #include "llvm/CodeGen/MachineDominators.h"
37 #include "llvm/CodeGen/MachineFunction.h"
38 #include "llvm/CodeGen/MachineFunctionPass.h"
39 #include "llvm/CodeGen/MachineLoopInfo.h"
40 #include "llvm/CodeGen/MachineModuleInfo.h"
41 #include "llvm/Support/Allocator.h"
42 #include "llvm/Support/CommandLine.h"
43 #include "llvm/Support/Debug.h"
44 #include "llvm/Support/raw_ostream.h"
45 #include "llvm/Target/TargetInstrInfo.h"
46 #include "llvm/Target/TargetLowering.h"
47 #include "llvm/Target/TargetSubtargetInfo.h"
51 #define DEBUG_TYPE "block-placement"
53 STATISTIC(NumCondBranches, "Number of conditional branches");
54 STATISTIC(NumUncondBranches, "Number of unconditional branches");
55 STATISTIC(CondBranchTakenFreq,
56 "Potential frequency of taking conditional branches");
57 STATISTIC(UncondBranchTakenFreq,
58 "Potential frequency of taking unconditional branches");
60 static cl::opt<unsigned> AlignAllBlock("align-all-blocks",
61 cl::desc("Force the alignment of all "
62 "blocks in the function."),
63 cl::init(0), cl::Hidden);
65 static cl::opt<unsigned>
66 AlignAllLoops("align-all-loops",
67 cl::desc("Force the alignment of all loops in the function."),
68 cl::init(0), cl::Hidden);
70 // FIXME: Find a good default for this flag and remove the flag.
71 static cl::opt<unsigned> ExitBlockBias(
72 "block-placement-exit-block-bias",
73 cl::desc("Block frequency percentage a loop exit block needs "
74 "over the original exit to be considered the new exit."),
75 cl::init(0), cl::Hidden);
77 static cl::opt<bool> OutlineOptionalBranches(
78 "outline-optional-branches",
79 cl::desc("Put completely optional branches, i.e. branches with a common "
80 "post dominator, out of line."),
81 cl::init(false), cl::Hidden);
83 static cl::opt<unsigned> OutlineOptionalThreshold(
84 "outline-optional-threshold",
85 cl::desc("Don't outline optional branches that are a single block with an "
86 "instruction count below this threshold"),
87 cl::init(4), cl::Hidden);
89 static cl::opt<unsigned> LoopToColdBlockRatio(
90 "loop-to-cold-block-ratio",
91 cl::desc("Outline loop blocks from loop chain if (frequency of loop) / "
92 "(frequency of block) is greater than this ratio"),
93 cl::init(5), cl::Hidden);
96 PreciseRotationCost("precise-rotation-cost",
97 cl::desc("Model the cost of loop rotation more "
98 "precisely by using profile data."),
99 cl::init(false), cl::Hidden);
101 static cl::opt<unsigned> MisfetchCost(
103 cl::desc("Cost that models the probablistic risk of an instruction "
104 "misfetch due to a jump comparing to falling through, whose cost "
106 cl::init(1), cl::Hidden);
108 static cl::opt<unsigned> JumpInstCost("jump-inst-cost",
109 cl::desc("Cost of jump instructions."),
110 cl::init(1), cl::Hidden);
114 /// \brief Type for our function-wide basic block -> block chain mapping.
115 typedef DenseMap<MachineBasicBlock *, BlockChain *> BlockToChainMapType;
119 /// \brief A chain of blocks which will be laid out contiguously.
121 /// This is the datastructure representing a chain of consecutive blocks that
122 /// are profitable to layout together in order to maximize fallthrough
123 /// probabilities and code locality. We also can use a block chain to represent
124 /// a sequence of basic blocks which have some external (correctness)
125 /// requirement for sequential layout.
127 /// Chains can be built around a single basic block and can be merged to grow
128 /// them. They participate in a block-to-chain mapping, which is updated
129 /// automatically as chains are merged together.
131 /// \brief The sequence of blocks belonging to this chain.
133 /// This is the sequence of blocks for a particular chain. These will be laid
134 /// out in-order within the function.
135 SmallVector<MachineBasicBlock *, 4> Blocks;
137 /// \brief A handle to the function-wide basic block to block chain mapping.
139 /// This is retained in each block chain to simplify the computation of child
140 /// block chains for SCC-formation and iteration. We store the edges to child
141 /// basic blocks, and map them back to their associated chains using this
143 BlockToChainMapType &BlockToChain;
146 /// \brief Construct a new BlockChain.
148 /// This builds a new block chain representing a single basic block in the
149 /// function. It also registers itself as the chain that block participates
150 /// in with the BlockToChain mapping.
151 BlockChain(BlockToChainMapType &BlockToChain, MachineBasicBlock *BB)
152 : Blocks(1, BB), BlockToChain(BlockToChain), LoopPredecessors(0) {
153 assert(BB && "Cannot create a chain with a null basic block");
154 BlockToChain[BB] = this;
157 /// \brief Iterator over blocks within the chain.
158 typedef SmallVectorImpl<MachineBasicBlock *>::iterator iterator;
160 /// \brief Beginning of blocks within the chain.
161 iterator begin() { return Blocks.begin(); }
163 /// \brief End of blocks within the chain.
164 iterator end() { return Blocks.end(); }
166 /// \brief Merge a block chain into this one.
168 /// This routine merges a block chain into this one. It takes care of forming
169 /// a contiguous sequence of basic blocks, updating the edge list, and
170 /// updating the block -> chain mapping. It does not free or tear down the
171 /// old chain, but the old chain's block list is no longer valid.
172 void merge(MachineBasicBlock *BB, BlockChain *Chain) {
174 assert(!Blocks.empty());
176 // Fast path in case we don't have a chain already.
178 assert(!BlockToChain[BB]);
179 Blocks.push_back(BB);
180 BlockToChain[BB] = this;
184 assert(BB == *Chain->begin());
185 assert(Chain->begin() != Chain->end());
187 // Update the incoming blocks to point to this chain, and add them to the
189 for (MachineBasicBlock *ChainBB : *Chain) {
190 Blocks.push_back(ChainBB);
191 assert(BlockToChain[ChainBB] == Chain && "Incoming blocks not in chain");
192 BlockToChain[ChainBB] = this;
197 /// \brief Dump the blocks in this chain.
198 LLVM_DUMP_METHOD void dump() {
199 for (MachineBasicBlock *MBB : *this)
204 /// \brief Count of predecessors within the loop currently being processed.
206 /// This count is updated at each loop we process to represent the number of
207 /// in-loop predecessors of this chain.
208 unsigned LoopPredecessors;
213 class MachineBlockPlacement : public MachineFunctionPass {
214 /// \brief A typedef for a block filter set.
215 typedef SmallPtrSet<MachineBasicBlock *, 16> BlockFilterSet;
217 /// \brief A handle to the branch probability pass.
218 const MachineBranchProbabilityInfo *MBPI;
220 /// \brief A handle to the function-wide block frequency pass.
221 const MachineBlockFrequencyInfo *MBFI;
223 /// \brief A handle to the loop info.
224 const MachineLoopInfo *MLI;
226 /// \brief A handle to the target's instruction info.
227 const TargetInstrInfo *TII;
229 /// \brief A handle to the target's lowering info.
230 const TargetLoweringBase *TLI;
232 /// \brief A handle to the post dominator tree.
233 MachineDominatorTree *MDT;
235 /// \brief A set of blocks that are unavoidably execute, i.e. they dominate
236 /// all terminators of the MachineFunction.
237 SmallPtrSet<MachineBasicBlock *, 4> UnavoidableBlocks;
239 /// \brief Allocator and owner of BlockChain structures.
241 /// We build BlockChains lazily while processing the loop structure of
242 /// a function. To reduce malloc traffic, we allocate them using this
243 /// slab-like allocator, and destroy them after the pass completes. An
244 /// important guarantee is that this allocator produces stable pointers to
246 SpecificBumpPtrAllocator<BlockChain> ChainAllocator;
248 /// \brief Function wide BasicBlock to BlockChain mapping.
250 /// This mapping allows efficiently moving from any given basic block to the
251 /// BlockChain it participates in, if any. We use it to, among other things,
252 /// allow implicitly defining edges between chains as the existing edges
253 /// between basic blocks.
254 DenseMap<MachineBasicBlock *, BlockChain *> BlockToChain;
256 void markChainSuccessors(BlockChain &Chain, MachineBasicBlock *LoopHeaderBB,
257 SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
258 const BlockFilterSet *BlockFilter = nullptr);
259 MachineBasicBlock *selectBestSuccessor(MachineBasicBlock *BB,
261 const BlockFilterSet *BlockFilter);
263 selectBestCandidateBlock(BlockChain &Chain,
264 SmallVectorImpl<MachineBasicBlock *> &WorkList,
265 const BlockFilterSet *BlockFilter);
267 getFirstUnplacedBlock(MachineFunction &F, const BlockChain &PlacedChain,
268 MachineFunction::iterator &PrevUnplacedBlockIt,
269 const BlockFilterSet *BlockFilter);
270 void buildChain(MachineBasicBlock *BB, BlockChain &Chain,
271 SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
272 const BlockFilterSet *BlockFilter = nullptr);
273 MachineBasicBlock *findBestLoopTop(MachineLoop &L,
274 const BlockFilterSet &LoopBlockSet);
275 MachineBasicBlock *findBestLoopExit(MachineFunction &F, MachineLoop &L,
276 const BlockFilterSet &LoopBlockSet);
277 BlockFilterSet collectLoopBlockSet(MachineFunction &F, MachineLoop &L);
278 void buildLoopChains(MachineFunction &F, MachineLoop &L);
279 void rotateLoop(BlockChain &LoopChain, MachineBasicBlock *ExitingBB,
280 const BlockFilterSet &LoopBlockSet);
281 void rotateLoopWithProfile(BlockChain &LoopChain, MachineLoop &L,
282 const BlockFilterSet &LoopBlockSet);
283 void buildCFGChains(MachineFunction &F);
286 static char ID; // Pass identification, replacement for typeid
287 MachineBlockPlacement() : MachineFunctionPass(ID) {
288 initializeMachineBlockPlacementPass(*PassRegistry::getPassRegistry());
291 bool runOnMachineFunction(MachineFunction &F) override;
293 void getAnalysisUsage(AnalysisUsage &AU) const override {
294 AU.addRequired<MachineBranchProbabilityInfo>();
295 AU.addRequired<MachineBlockFrequencyInfo>();
296 AU.addRequired<MachineDominatorTree>();
297 AU.addRequired<MachineLoopInfo>();
298 MachineFunctionPass::getAnalysisUsage(AU);
303 char MachineBlockPlacement::ID = 0;
304 char &llvm::MachineBlockPlacementID = MachineBlockPlacement::ID;
305 INITIALIZE_PASS_BEGIN(MachineBlockPlacement, "block-placement",
306 "Branch Probability Basic Block Placement", false, false)
307 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
308 INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
309 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
310 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
311 INITIALIZE_PASS_END(MachineBlockPlacement, "block-placement",
312 "Branch Probability Basic Block Placement", false, false)
315 /// \brief Helper to print the name of a MBB.
317 /// Only used by debug logging.
318 static std::string getBlockName(MachineBasicBlock *BB) {
320 raw_string_ostream OS(Result);
321 OS << "BB#" << BB->getNumber();
322 OS << " (derived from LLVM BB '" << BB->getName() << "')";
327 /// \brief Helper to print the number of a MBB.
329 /// Only used by debug logging.
330 static std::string getBlockNum(MachineBasicBlock *BB) {
332 raw_string_ostream OS(Result);
333 OS << "BB#" << BB->getNumber();
339 /// \brief Mark a chain's successors as having one fewer preds.
341 /// When a chain is being merged into the "placed" chain, this routine will
342 /// quickly walk the successors of each block in the chain and mark them as
343 /// having one fewer active predecessor. It also adds any successors of this
344 /// chain which reach the zero-predecessor state to the worklist passed in.
345 void MachineBlockPlacement::markChainSuccessors(
346 BlockChain &Chain, MachineBasicBlock *LoopHeaderBB,
347 SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
348 const BlockFilterSet *BlockFilter) {
349 // Walk all the blocks in this chain, marking their successors as having
350 // a predecessor placed.
351 for (MachineBasicBlock *MBB : Chain) {
352 // Add any successors for which this is the only un-placed in-loop
353 // predecessor to the worklist as a viable candidate for CFG-neutral
354 // placement. No subsequent placement of this block will violate the CFG
355 // shape, so we get to use heuristics to choose a favorable placement.
356 for (MachineBasicBlock *Succ : MBB->successors()) {
357 if (BlockFilter && !BlockFilter->count(Succ))
359 BlockChain &SuccChain = *BlockToChain[Succ];
360 // Disregard edges within a fixed chain, or edges to the loop header.
361 if (&Chain == &SuccChain || Succ == LoopHeaderBB)
364 // This is a cross-chain edge that is within the loop, so decrement the
365 // loop predecessor count of the destination chain.
366 if (SuccChain.LoopPredecessors > 0 && --SuccChain.LoopPredecessors == 0)
367 BlockWorkList.push_back(*SuccChain.begin());
372 /// \brief Select the best successor for a block.
374 /// This looks across all successors of a particular block and attempts to
375 /// select the "best" one to be the layout successor. It only considers direct
376 /// successors which also pass the block filter. It will attempt to avoid
377 /// breaking CFG structure, but cave and break such structures in the case of
378 /// very hot successor edges.
380 /// \returns The best successor block found, or null if none are viable.
382 MachineBlockPlacement::selectBestSuccessor(MachineBasicBlock *BB,
384 const BlockFilterSet *BlockFilter) {
385 const BranchProbability HotProb(4, 5); // 80%
387 MachineBasicBlock *BestSucc = nullptr;
388 auto BestProb = BranchProbability::getZero();
390 // Adjust edge probabilities by excluding edges pointing to blocks that is
391 // either not in BlockFilter or is already in the current chain. Consider the
400 // Assume A->C is very hot (>90%), and C->D has a 50% probability, then after
401 // A->C is chosen as a fall-through, D won't be selected as a successor of C
402 // due to CFG constraint (the probability of C->D is not greater than
403 // HotProb). If we exclude E that is not in BlockFilter when calculating the
404 // probability of C->D, D will be selected and we will get A C D B as the
405 // layout of this loop.
406 auto AdjustedSumProb = BranchProbability::getOne();
407 SmallVector<MachineBasicBlock *, 4> Successors;
408 for (MachineBasicBlock *Succ : BB->successors()) {
409 bool SkipSucc = false;
410 if (BlockFilter && !BlockFilter->count(Succ)) {
413 BlockChain *SuccChain = BlockToChain[Succ];
414 if (SuccChain == &Chain) {
415 DEBUG(dbgs() << " " << getBlockName(Succ)
416 << " -> Already merged!\n");
418 } else if (Succ != *SuccChain->begin()) {
419 DEBUG(dbgs() << " " << getBlockName(Succ) << " -> Mid chain!\n");
424 AdjustedSumProb -= MBPI->getEdgeProbability(BB, Succ);
426 Successors.push_back(Succ);
429 DEBUG(dbgs() << "Attempting merge from: " << getBlockName(BB) << "\n");
430 for (MachineBasicBlock *Succ : Successors) {
431 BranchProbability SuccProb;
432 uint32_t SuccProbN = MBPI->getEdgeProbability(BB, Succ).getNumerator();
433 uint32_t SuccProbD = AdjustedSumProb.getNumerator();
434 if (SuccProbN >= SuccProbD)
435 SuccProb = BranchProbability::getOne();
437 SuccProb = BranchProbability(SuccProbN, SuccProbD);
439 // If we outline optional branches, look whether Succ is unavoidable, i.e.
440 // dominates all terminators of the MachineFunction. If it does, other
441 // successors must be optional. Don't do this for cold branches.
442 if (OutlineOptionalBranches && SuccProb > HotProb.getCompl() &&
443 UnavoidableBlocks.count(Succ) > 0) {
444 auto HasShortOptionalBranch = [&]() {
445 for (MachineBasicBlock *Pred : Succ->predecessors()) {
446 // Check whether there is an unplaced optional branch.
447 if (Pred == Succ || (BlockFilter && !BlockFilter->count(Pred)) ||
448 BlockToChain[Pred] == &Chain)
450 // Check whether the optional branch has exactly one BB.
451 if (Pred->pred_size() > 1 || *Pred->pred_begin() != BB)
453 // Check whether the optional branch is small.
454 if (Pred->size() < OutlineOptionalThreshold)
459 if (!HasShortOptionalBranch())
463 // Only consider successors which are either "hot", or wouldn't violate
464 // any CFG constraints.
465 BlockChain &SuccChain = *BlockToChain[Succ];
466 if (SuccChain.LoopPredecessors != 0) {
467 if (SuccProb < HotProb) {
468 DEBUG(dbgs() << " " << getBlockName(Succ) << " -> " << SuccProb
469 << " (prob) (CFG conflict)\n");
473 // Make sure that a hot successor doesn't have a globally more
474 // important predecessor.
475 auto RealSuccProb = MBPI->getEdgeProbability(BB, Succ);
476 BlockFrequency CandidateEdgeFreq =
477 MBFI->getBlockFreq(BB) * RealSuccProb * HotProb.getCompl();
478 bool BadCFGConflict = false;
479 for (MachineBasicBlock *Pred : Succ->predecessors()) {
480 if (Pred == Succ || (BlockFilter && !BlockFilter->count(Pred)) ||
481 BlockToChain[Pred] == &Chain)
483 BlockFrequency PredEdgeFreq =
484 MBFI->getBlockFreq(Pred) * MBPI->getEdgeProbability(Pred, Succ);
485 if (PredEdgeFreq >= CandidateEdgeFreq) {
486 BadCFGConflict = true;
490 if (BadCFGConflict) {
491 DEBUG(dbgs() << " " << getBlockName(Succ) << " -> " << SuccProb
492 << " (prob) (non-cold CFG conflict)\n");
497 DEBUG(dbgs() << " " << getBlockName(Succ) << " -> " << SuccProb
499 << (SuccChain.LoopPredecessors != 0 ? " (CFG break)" : "")
501 if (BestSucc && BestProb >= SuccProb)
509 /// \brief Select the best block from a worklist.
511 /// This looks through the provided worklist as a list of candidate basic
512 /// blocks and select the most profitable one to place. The definition of
513 /// profitable only really makes sense in the context of a loop. This returns
514 /// the most frequently visited block in the worklist, which in the case of
515 /// a loop, is the one most desirable to be physically close to the rest of the
516 /// loop body in order to improve icache behavior.
518 /// \returns The best block found, or null if none are viable.
519 MachineBasicBlock *MachineBlockPlacement::selectBestCandidateBlock(
520 BlockChain &Chain, SmallVectorImpl<MachineBasicBlock *> &WorkList,
521 const BlockFilterSet *BlockFilter) {
522 // Once we need to walk the worklist looking for a candidate, cleanup the
523 // worklist of already placed entries.
524 // FIXME: If this shows up on profiles, it could be folded (at the cost of
525 // some code complexity) into the loop below.
526 WorkList.erase(std::remove_if(WorkList.begin(), WorkList.end(),
527 [&](MachineBasicBlock *BB) {
528 return BlockToChain.lookup(BB) == &Chain;
532 MachineBasicBlock *BestBlock = nullptr;
533 BlockFrequency BestFreq;
534 for (MachineBasicBlock *MBB : WorkList) {
535 BlockChain &SuccChain = *BlockToChain[MBB];
536 if (&SuccChain == &Chain) {
537 DEBUG(dbgs() << " " << getBlockName(MBB) << " -> Already merged!\n");
540 assert(SuccChain.LoopPredecessors == 0 && "Found CFG-violating block");
542 BlockFrequency CandidateFreq = MBFI->getBlockFreq(MBB);
543 DEBUG(dbgs() << " " << getBlockName(MBB) << " -> ";
544 MBFI->printBlockFreq(dbgs(), CandidateFreq) << " (freq)\n");
545 if (BestBlock && BestFreq >= CandidateFreq)
548 BestFreq = CandidateFreq;
553 /// \brief Retrieve the first unplaced basic block.
555 /// This routine is called when we are unable to use the CFG to walk through
556 /// all of the basic blocks and form a chain due to unnatural loops in the CFG.
557 /// We walk through the function's blocks in order, starting from the
558 /// LastUnplacedBlockIt. We update this iterator on each call to avoid
559 /// re-scanning the entire sequence on repeated calls to this routine.
560 MachineBasicBlock *MachineBlockPlacement::getFirstUnplacedBlock(
561 MachineFunction &F, const BlockChain &PlacedChain,
562 MachineFunction::iterator &PrevUnplacedBlockIt,
563 const BlockFilterSet *BlockFilter) {
564 for (MachineFunction::iterator I = PrevUnplacedBlockIt, E = F.end(); I != E;
566 if (BlockFilter && !BlockFilter->count(&*I))
568 if (BlockToChain[&*I] != &PlacedChain) {
569 PrevUnplacedBlockIt = I;
570 // Now select the head of the chain to which the unplaced block belongs
571 // as the block to place. This will force the entire chain to be placed,
572 // and satisfies the requirements of merging chains.
573 return *BlockToChain[&*I]->begin();
579 void MachineBlockPlacement::buildChain(
580 MachineBasicBlock *BB, BlockChain &Chain,
581 SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
582 const BlockFilterSet *BlockFilter) {
584 assert(BlockToChain[BB] == &Chain);
585 MachineFunction &F = *BB->getParent();
586 MachineFunction::iterator PrevUnplacedBlockIt = F.begin();
588 MachineBasicBlock *LoopHeaderBB = BB;
589 markChainSuccessors(Chain, LoopHeaderBB, BlockWorkList, BlockFilter);
590 BB = *std::prev(Chain.end());
593 assert(BlockToChain[BB] == &Chain);
594 assert(*std::prev(Chain.end()) == BB);
596 // Look for the best viable successor if there is one to place immediately
598 MachineBasicBlock *BestSucc = selectBestSuccessor(BB, Chain, BlockFilter);
600 // If an immediate successor isn't available, look for the best viable
601 // block among those we've identified as not violating the loop's CFG at
602 // this point. This won't be a fallthrough, but it will increase locality.
604 BestSucc = selectBestCandidateBlock(Chain, BlockWorkList, BlockFilter);
608 getFirstUnplacedBlock(F, Chain, PrevUnplacedBlockIt, BlockFilter);
612 DEBUG(dbgs() << "Unnatural loop CFG detected, forcibly merging the "
613 "layout successor until the CFG reduces\n");
616 // Place this block, updating the datastructures to reflect its placement.
617 BlockChain &SuccChain = *BlockToChain[BestSucc];
618 // Zero out LoopPredecessors for the successor we're about to merge in case
619 // we selected a successor that didn't fit naturally into the CFG.
620 SuccChain.LoopPredecessors = 0;
621 DEBUG(dbgs() << "Merging from " << getBlockNum(BB) << " to "
622 << getBlockNum(BestSucc) << "\n");
623 markChainSuccessors(SuccChain, LoopHeaderBB, BlockWorkList, BlockFilter);
624 Chain.merge(BestSucc, &SuccChain);
625 BB = *std::prev(Chain.end());
628 DEBUG(dbgs() << "Finished forming chain for header block "
629 << getBlockNum(*Chain.begin()) << "\n");
632 /// \brief Find the best loop top block for layout.
634 /// Look for a block which is strictly better than the loop header for laying
635 /// out at the top of the loop. This looks for one and only one pattern:
636 /// a latch block with no conditional exit. This block will cause a conditional
637 /// jump around it or will be the bottom of the loop if we lay it out in place,
638 /// but if it it doesn't end up at the bottom of the loop for any reason,
639 /// rotation alone won't fix it. Because such a block will always result in an
640 /// unconditional jump (for the backedge) rotating it in front of the loop
641 /// header is always profitable.
643 MachineBlockPlacement::findBestLoopTop(MachineLoop &L,
644 const BlockFilterSet &LoopBlockSet) {
645 // Check that the header hasn't been fused with a preheader block due to
646 // crazy branches. If it has, we need to start with the header at the top to
647 // prevent pulling the preheader into the loop body.
648 BlockChain &HeaderChain = *BlockToChain[L.getHeader()];
649 if (!LoopBlockSet.count(*HeaderChain.begin()))
650 return L.getHeader();
652 DEBUG(dbgs() << "Finding best loop top for: " << getBlockName(L.getHeader())
655 BlockFrequency BestPredFreq;
656 MachineBasicBlock *BestPred = nullptr;
657 for (MachineBasicBlock *Pred : L.getHeader()->predecessors()) {
658 if (!LoopBlockSet.count(Pred))
660 DEBUG(dbgs() << " header pred: " << getBlockName(Pred) << ", "
661 << Pred->succ_size() << " successors, ";
662 MBFI->printBlockFreq(dbgs(), Pred) << " freq\n");
663 if (Pred->succ_size() > 1)
666 BlockFrequency PredFreq = MBFI->getBlockFreq(Pred);
667 if (!BestPred || PredFreq > BestPredFreq ||
668 (!(PredFreq < BestPredFreq) &&
669 Pred->isLayoutSuccessor(L.getHeader()))) {
671 BestPredFreq = PredFreq;
675 // If no direct predecessor is fine, just use the loop header.
677 return L.getHeader();
679 // Walk backwards through any straight line of predecessors.
680 while (BestPred->pred_size() == 1 &&
681 (*BestPred->pred_begin())->succ_size() == 1 &&
682 *BestPred->pred_begin() != L.getHeader())
683 BestPred = *BestPred->pred_begin();
685 DEBUG(dbgs() << " final top: " << getBlockName(BestPred) << "\n");
689 /// \brief Find the best loop exiting block for layout.
691 /// This routine implements the logic to analyze the loop looking for the best
692 /// block to layout at the top of the loop. Typically this is done to maximize
693 /// fallthrough opportunities.
695 MachineBlockPlacement::findBestLoopExit(MachineFunction &F, MachineLoop &L,
696 const BlockFilterSet &LoopBlockSet) {
697 // We don't want to layout the loop linearly in all cases. If the loop header
698 // is just a normal basic block in the loop, we want to look for what block
699 // within the loop is the best one to layout at the top. However, if the loop
700 // header has be pre-merged into a chain due to predecessors not having
701 // analyzable branches, *and* the predecessor it is merged with is *not* part
702 // of the loop, rotating the header into the middle of the loop will create
703 // a non-contiguous range of blocks which is Very Bad. So start with the
704 // header and only rotate if safe.
705 BlockChain &HeaderChain = *BlockToChain[L.getHeader()];
706 if (!LoopBlockSet.count(*HeaderChain.begin()))
709 BlockFrequency BestExitEdgeFreq;
710 unsigned BestExitLoopDepth = 0;
711 MachineBasicBlock *ExitingBB = nullptr;
712 // If there are exits to outer loops, loop rotation can severely limit
713 // fallthrough opportunites unless it selects such an exit. Keep a set of
714 // blocks where rotating to exit with that block will reach an outer loop.
715 SmallPtrSet<MachineBasicBlock *, 4> BlocksExitingToOuterLoop;
717 DEBUG(dbgs() << "Finding best loop exit for: " << getBlockName(L.getHeader())
719 for (MachineBasicBlock *MBB : L.getBlocks()) {
720 BlockChain &Chain = *BlockToChain[MBB];
721 // Ensure that this block is at the end of a chain; otherwise it could be
722 // mid-way through an inner loop or a successor of an unanalyzable branch.
723 if (MBB != *std::prev(Chain.end()))
726 // Now walk the successors. We need to establish whether this has a viable
727 // exiting successor and whether it has a viable non-exiting successor.
728 // We store the old exiting state and restore it if a viable looping
729 // successor isn't found.
730 MachineBasicBlock *OldExitingBB = ExitingBB;
731 BlockFrequency OldBestExitEdgeFreq = BestExitEdgeFreq;
732 bool HasLoopingSucc = false;
733 for (MachineBasicBlock *Succ : MBB->successors()) {
738 BlockChain &SuccChain = *BlockToChain[Succ];
739 // Don't split chains, either this chain or the successor's chain.
740 if (&Chain == &SuccChain) {
741 DEBUG(dbgs() << " exiting: " << getBlockName(MBB) << " -> "
742 << getBlockName(Succ) << " (chain conflict)\n");
746 auto SuccProb = MBPI->getEdgeProbability(MBB, Succ);
747 if (LoopBlockSet.count(Succ)) {
748 DEBUG(dbgs() << " looping: " << getBlockName(MBB) << " -> "
749 << getBlockName(Succ) << " (" << SuccProb << ")\n");
750 HasLoopingSucc = true;
754 unsigned SuccLoopDepth = 0;
755 if (MachineLoop *ExitLoop = MLI->getLoopFor(Succ)) {
756 SuccLoopDepth = ExitLoop->getLoopDepth();
757 if (ExitLoop->contains(&L))
758 BlocksExitingToOuterLoop.insert(MBB);
761 BlockFrequency ExitEdgeFreq = MBFI->getBlockFreq(MBB) * SuccProb;
762 DEBUG(dbgs() << " exiting: " << getBlockName(MBB) << " -> "
763 << getBlockName(Succ) << " [L:" << SuccLoopDepth << "] (";
764 MBFI->printBlockFreq(dbgs(), ExitEdgeFreq) << ")\n");
765 // Note that we bias this toward an existing layout successor to retain
766 // incoming order in the absence of better information. The exit must have
767 // a frequency higher than the current exit before we consider breaking
769 BranchProbability Bias(100 - ExitBlockBias, 100);
770 if (!ExitingBB || SuccLoopDepth > BestExitLoopDepth ||
771 ExitEdgeFreq > BestExitEdgeFreq ||
772 (MBB->isLayoutSuccessor(Succ) &&
773 !(ExitEdgeFreq < BestExitEdgeFreq * Bias))) {
774 BestExitEdgeFreq = ExitEdgeFreq;
779 if (!HasLoopingSucc) {
780 // Restore the old exiting state, no viable looping successor was found.
781 ExitingBB = OldExitingBB;
782 BestExitEdgeFreq = OldBestExitEdgeFreq;
786 // Without a candidate exiting block or with only a single block in the
787 // loop, just use the loop header to layout the loop.
788 if (!ExitingBB || L.getNumBlocks() == 1)
791 // Also, if we have exit blocks which lead to outer loops but didn't select
792 // one of them as the exiting block we are rotating toward, disable loop
793 // rotation altogether.
794 if (!BlocksExitingToOuterLoop.empty() &&
795 !BlocksExitingToOuterLoop.count(ExitingBB))
798 DEBUG(dbgs() << " Best exiting block: " << getBlockName(ExitingBB) << "\n");
802 /// \brief Attempt to rotate an exiting block to the bottom of the loop.
804 /// Once we have built a chain, try to rotate it to line up the hot exit block
805 /// with fallthrough out of the loop if doing so doesn't introduce unnecessary
806 /// branches. For example, if the loop has fallthrough into its header and out
807 /// of its bottom already, don't rotate it.
808 void MachineBlockPlacement::rotateLoop(BlockChain &LoopChain,
809 MachineBasicBlock *ExitingBB,
810 const BlockFilterSet &LoopBlockSet) {
814 MachineBasicBlock *Top = *LoopChain.begin();
815 bool ViableTopFallthrough = false;
816 for (MachineBasicBlock *Pred : Top->predecessors()) {
817 BlockChain *PredChain = BlockToChain[Pred];
818 if (!LoopBlockSet.count(Pred) &&
819 (!PredChain || Pred == *std::prev(PredChain->end()))) {
820 ViableTopFallthrough = true;
825 // If the header has viable fallthrough, check whether the current loop
826 // bottom is a viable exiting block. If so, bail out as rotating will
827 // introduce an unnecessary branch.
828 if (ViableTopFallthrough) {
829 MachineBasicBlock *Bottom = *std::prev(LoopChain.end());
830 for (MachineBasicBlock *Succ : Bottom->successors()) {
831 BlockChain *SuccChain = BlockToChain[Succ];
832 if (!LoopBlockSet.count(Succ) &&
833 (!SuccChain || Succ == *SuccChain->begin()))
838 BlockChain::iterator ExitIt =
839 std::find(LoopChain.begin(), LoopChain.end(), ExitingBB);
840 if (ExitIt == LoopChain.end())
843 std::rotate(LoopChain.begin(), std::next(ExitIt), LoopChain.end());
846 /// \brief Attempt to rotate a loop based on profile data to reduce branch cost.
848 /// With profile data, we can determine the cost in terms of missed fall through
849 /// opportunities when rotating a loop chain and select the best rotation.
850 /// Basically, there are three kinds of cost to consider for each rotation:
851 /// 1. The possibly missed fall through edge (if it exists) from BB out of
852 /// the loop to the loop header.
853 /// 2. The possibly missed fall through edges (if they exist) from the loop
854 /// exits to BB out of the loop.
855 /// 3. The missed fall through edge (if it exists) from the last BB to the
856 /// first BB in the loop chain.
857 /// Therefore, the cost for a given rotation is the sum of costs listed above.
858 /// We select the best rotation with the smallest cost.
859 void MachineBlockPlacement::rotateLoopWithProfile(
860 BlockChain &LoopChain, MachineLoop &L, const BlockFilterSet &LoopBlockSet) {
861 auto HeaderBB = L.getHeader();
862 auto HeaderIter = std::find(LoopChain.begin(), LoopChain.end(), HeaderBB);
863 auto RotationPos = LoopChain.end();
865 BlockFrequency SmallestRotationCost = BlockFrequency::getMaxFrequency();
867 // A utility lambda that scales up a block frequency by dividing it by a
868 // branch probability which is the reciprocal of the scale.
869 auto ScaleBlockFrequency = [](BlockFrequency Freq,
870 unsigned Scale) -> BlockFrequency {
873 // Use operator / between BlockFrequency and BranchProbability to implement
874 // saturating multiplication.
875 return Freq / BranchProbability(1, Scale);
878 // Compute the cost of the missed fall-through edge to the loop header if the
879 // chain head is not the loop header. As we only consider natural loops with
880 // single header, this computation can be done only once.
881 BlockFrequency HeaderFallThroughCost(0);
882 for (auto *Pred : HeaderBB->predecessors()) {
883 BlockChain *PredChain = BlockToChain[Pred];
884 if (!LoopBlockSet.count(Pred) &&
885 (!PredChain || Pred == *std::prev(PredChain->end()))) {
887 MBFI->getBlockFreq(Pred) * MBPI->getEdgeProbability(Pred, HeaderBB);
888 auto FallThruCost = ScaleBlockFrequency(EdgeFreq, MisfetchCost);
889 // If the predecessor has only an unconditional jump to the header, we
890 // need to consider the cost of this jump.
891 if (Pred->succ_size() == 1)
892 FallThruCost += ScaleBlockFrequency(EdgeFreq, JumpInstCost);
893 HeaderFallThroughCost = std::max(HeaderFallThroughCost, FallThruCost);
897 // Here we collect all exit blocks in the loop, and for each exit we find out
898 // its hottest exit edge. For each loop rotation, we define the loop exit cost
899 // as the sum of frequencies of exit edges we collect here, excluding the exit
900 // edge from the tail of the loop chain.
901 SmallVector<std::pair<MachineBasicBlock *, BlockFrequency>, 4> ExitsWithFreq;
902 for (auto BB : LoopChain) {
903 auto LargestExitEdgeProb = BranchProbability::getZero();
904 for (auto *Succ : BB->successors()) {
905 BlockChain *SuccChain = BlockToChain[Succ];
906 if (!LoopBlockSet.count(Succ) &&
907 (!SuccChain || Succ == *SuccChain->begin())) {
908 auto SuccProb = MBPI->getEdgeProbability(BB, Succ);
909 LargestExitEdgeProb = std::max(LargestExitEdgeProb, SuccProb);
912 if (LargestExitEdgeProb > BranchProbability::getZero()) {
913 auto ExitFreq = MBFI->getBlockFreq(BB) * LargestExitEdgeProb;
914 ExitsWithFreq.emplace_back(BB, ExitFreq);
918 // In this loop we iterate every block in the loop chain and calculate the
919 // cost assuming the block is the head of the loop chain. When the loop ends,
920 // we should have found the best candidate as the loop chain's head.
921 for (auto Iter = LoopChain.begin(), TailIter = std::prev(LoopChain.end()),
922 EndIter = LoopChain.end();
923 Iter != EndIter; Iter++, TailIter++) {
924 // TailIter is used to track the tail of the loop chain if the block we are
925 // checking (pointed by Iter) is the head of the chain.
926 if (TailIter == LoopChain.end())
927 TailIter = LoopChain.begin();
929 auto TailBB = *TailIter;
931 // Calculate the cost by putting this BB to the top.
932 BlockFrequency Cost = 0;
934 // If the current BB is the loop header, we need to take into account the
935 // cost of the missed fall through edge from outside of the loop to the
937 if (Iter != HeaderIter)
938 Cost += HeaderFallThroughCost;
940 // Collect the loop exit cost by summing up frequencies of all exit edges
941 // except the one from the chain tail.
942 for (auto &ExitWithFreq : ExitsWithFreq)
943 if (TailBB != ExitWithFreq.first)
944 Cost += ExitWithFreq.second;
946 // The cost of breaking the once fall-through edge from the tail to the top
947 // of the loop chain. Here we need to consider three cases:
948 // 1. If the tail node has only one successor, then we will get an
949 // additional jmp instruction. So the cost here is (MisfetchCost +
950 // JumpInstCost) * tail node frequency.
951 // 2. If the tail node has two successors, then we may still get an
952 // additional jmp instruction if the layout successor after the loop
953 // chain is not its CFG successor. Note that the more frequently executed
954 // jmp instruction will be put ahead of the other one. Assume the
955 // frequency of those two branches are x and y, where x is the frequency
956 // of the edge to the chain head, then the cost will be
957 // (x * MisfetechCost + min(x, y) * JumpInstCost) * tail node frequency.
958 // 3. If the tail node has more than two successors (this rarely happens),
959 // we won't consider any additional cost.
960 if (TailBB->isSuccessor(*Iter)) {
961 auto TailBBFreq = MBFI->getBlockFreq(TailBB);
962 if (TailBB->succ_size() == 1)
963 Cost += ScaleBlockFrequency(TailBBFreq.getFrequency(),
964 MisfetchCost + JumpInstCost);
965 else if (TailBB->succ_size() == 2) {
966 auto TailToHeadProb = MBPI->getEdgeProbability(TailBB, *Iter);
967 auto TailToHeadFreq = TailBBFreq * TailToHeadProb;
968 auto ColderEdgeFreq = TailToHeadProb > BranchProbability(1, 2)
969 ? TailBBFreq * TailToHeadProb.getCompl()
971 Cost += ScaleBlockFrequency(TailToHeadFreq, MisfetchCost) +
972 ScaleBlockFrequency(ColderEdgeFreq, JumpInstCost);
976 DEBUG(dbgs() << "The cost of loop rotation by making " << getBlockNum(*Iter)
977 << " to the top: " << Cost.getFrequency() << "\n");
979 if (Cost < SmallestRotationCost) {
980 SmallestRotationCost = Cost;
985 if (RotationPos != LoopChain.end()) {
986 DEBUG(dbgs() << "Rotate loop by making " << getBlockNum(*RotationPos)
988 std::rotate(LoopChain.begin(), RotationPos, LoopChain.end());
992 /// \brief Collect blocks in the given loop that are to be placed.
994 /// When profile data is available, exclude cold blocks from the returned set;
995 /// otherwise, collect all blocks in the loop.
996 MachineBlockPlacement::BlockFilterSet
997 MachineBlockPlacement::collectLoopBlockSet(MachineFunction &F, MachineLoop &L) {
998 BlockFilterSet LoopBlockSet;
1000 // Filter cold blocks off from LoopBlockSet when profile data is available.
1001 // Collect the sum of frequencies of incoming edges to the loop header from
1002 // outside. If we treat the loop as a super block, this is the frequency of
1003 // the loop. Then for each block in the loop, we calculate the ratio between
1004 // its frequency and the frequency of the loop block. When it is too small,
1005 // don't add it to the loop chain. If there are outer loops, then this block
1006 // will be merged into the first outer loop chain for which this block is not
1007 // cold anymore. This needs precise profile data and we only do this when
1008 // profile data is available.
1009 if (F.getFunction()->getEntryCount()) {
1010 BlockFrequency LoopFreq(0);
1011 for (auto LoopPred : L.getHeader()->predecessors())
1012 if (!L.contains(LoopPred))
1013 LoopFreq += MBFI->getBlockFreq(LoopPred) *
1014 MBPI->getEdgeProbability(LoopPred, L.getHeader());
1016 for (MachineBasicBlock *LoopBB : L.getBlocks()) {
1017 auto Freq = MBFI->getBlockFreq(LoopBB).getFrequency();
1018 if (Freq == 0 || LoopFreq.getFrequency() / Freq > LoopToColdBlockRatio)
1020 LoopBlockSet.insert(LoopBB);
1023 LoopBlockSet.insert(L.block_begin(), L.block_end());
1025 return LoopBlockSet;
1028 /// \brief Forms basic block chains from the natural loop structures.
1030 /// These chains are designed to preserve the existing *structure* of the code
1031 /// as much as possible. We can then stitch the chains together in a way which
1032 /// both preserves the topological structure and minimizes taken conditional
1034 void MachineBlockPlacement::buildLoopChains(MachineFunction &F,
1036 // First recurse through any nested loops, building chains for those inner
1038 for (MachineLoop *InnerLoop : L)
1039 buildLoopChains(F, *InnerLoop);
1041 SmallVector<MachineBasicBlock *, 16> BlockWorkList;
1042 BlockFilterSet LoopBlockSet = collectLoopBlockSet(F, L);
1044 // Check if we have profile data for this function. If yes, we will rotate
1045 // this loop by modeling costs more precisely which requires the profile data
1046 // for better layout.
1047 bool RotateLoopWithProfile =
1048 PreciseRotationCost && F.getFunction()->getEntryCount();
1050 // First check to see if there is an obviously preferable top block for the
1051 // loop. This will default to the header, but may end up as one of the
1052 // predecessors to the header if there is one which will result in strictly
1053 // fewer branches in the loop body.
1054 // When we use profile data to rotate the loop, this is unnecessary.
1055 MachineBasicBlock *LoopTop =
1056 RotateLoopWithProfile ? L.getHeader() : findBestLoopTop(L, LoopBlockSet);
1058 // If we selected just the header for the loop top, look for a potentially
1059 // profitable exit block in the event that rotating the loop can eliminate
1060 // branches by placing an exit edge at the bottom.
1061 MachineBasicBlock *ExitingBB = nullptr;
1062 if (!RotateLoopWithProfile && LoopTop == L.getHeader())
1063 ExitingBB = findBestLoopExit(F, L, LoopBlockSet);
1065 BlockChain &LoopChain = *BlockToChain[LoopTop];
1067 // FIXME: This is a really lame way of walking the chains in the loop: we
1068 // walk the blocks, and use a set to prevent visiting a particular chain
1070 SmallPtrSet<BlockChain *, 4> UpdatedPreds;
1071 assert(LoopChain.LoopPredecessors == 0);
1072 UpdatedPreds.insert(&LoopChain);
1074 for (MachineBasicBlock *LoopBB : LoopBlockSet) {
1075 BlockChain &Chain = *BlockToChain[LoopBB];
1076 if (!UpdatedPreds.insert(&Chain).second)
1079 assert(Chain.LoopPredecessors == 0);
1080 for (MachineBasicBlock *ChainBB : Chain) {
1081 assert(BlockToChain[ChainBB] == &Chain);
1082 for (MachineBasicBlock *Pred : ChainBB->predecessors()) {
1083 if (BlockToChain[Pred] == &Chain || !LoopBlockSet.count(Pred))
1085 ++Chain.LoopPredecessors;
1089 if (Chain.LoopPredecessors == 0)
1090 BlockWorkList.push_back(*Chain.begin());
1093 buildChain(LoopTop, LoopChain, BlockWorkList, &LoopBlockSet);
1095 if (RotateLoopWithProfile)
1096 rotateLoopWithProfile(LoopChain, L, LoopBlockSet);
1098 rotateLoop(LoopChain, ExitingBB, LoopBlockSet);
1101 // Crash at the end so we get all of the debugging output first.
1102 bool BadLoop = false;
1103 if (LoopChain.LoopPredecessors) {
1105 dbgs() << "Loop chain contains a block without its preds placed!\n"
1106 << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
1107 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n";
1109 for (MachineBasicBlock *ChainBB : LoopChain) {
1110 dbgs() << " ... " << getBlockName(ChainBB) << "\n";
1111 if (!LoopBlockSet.erase(ChainBB)) {
1112 // We don't mark the loop as bad here because there are real situations
1113 // where this can occur. For example, with an unanalyzable fallthrough
1114 // from a loop block to a non-loop block or vice versa.
1115 dbgs() << "Loop chain contains a block not contained by the loop!\n"
1116 << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
1117 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
1118 << " Bad block: " << getBlockName(ChainBB) << "\n";
1122 if (!LoopBlockSet.empty()) {
1124 for (MachineBasicBlock *LoopBB : LoopBlockSet)
1125 dbgs() << "Loop contains blocks never placed into a chain!\n"
1126 << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
1127 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
1128 << " Bad block: " << getBlockName(LoopBB) << "\n";
1130 assert(!BadLoop && "Detected problems with the placement of this loop.");
1134 void MachineBlockPlacement::buildCFGChains(MachineFunction &F) {
1135 // Ensure that every BB in the function has an associated chain to simplify
1136 // the assumptions of the remaining algorithm.
1137 SmallVector<MachineOperand, 4> Cond; // For AnalyzeBranch.
1138 for (MachineFunction::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
1139 MachineBasicBlock *BB = &*FI;
1141 new (ChainAllocator.Allocate()) BlockChain(BlockToChain, BB);
1142 // Also, merge any blocks which we cannot reason about and must preserve
1143 // the exact fallthrough behavior for.
1146 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
1147 if (!TII->AnalyzeBranch(*BB, TBB, FBB, Cond) || !FI->canFallThrough())
1150 MachineFunction::iterator NextFI = std::next(FI);
1151 MachineBasicBlock *NextBB = &*NextFI;
1152 // Ensure that the layout successor is a viable block, as we know that
1153 // fallthrough is a possibility.
1154 assert(NextFI != FE && "Can't fallthrough past the last block.");
1155 DEBUG(dbgs() << "Pre-merging due to unanalyzable fallthrough: "
1156 << getBlockName(BB) << " -> " << getBlockName(NextBB)
1158 Chain->merge(NextBB, nullptr);
1164 if (OutlineOptionalBranches) {
1165 // Find the nearest common dominator of all of F's terminators.
1166 MachineBasicBlock *Terminator = nullptr;
1167 for (MachineBasicBlock &MBB : F) {
1168 if (MBB.succ_size() == 0) {
1169 if (Terminator == nullptr)
1172 Terminator = MDT->findNearestCommonDominator(Terminator, &MBB);
1176 // MBBs dominating this common dominator are unavoidable.
1177 UnavoidableBlocks.clear();
1178 for (MachineBasicBlock &MBB : F) {
1179 if (MDT->dominates(&MBB, Terminator)) {
1180 UnavoidableBlocks.insert(&MBB);
1185 // Build any loop-based chains.
1186 for (MachineLoop *L : *MLI)
1187 buildLoopChains(F, *L);
1189 SmallVector<MachineBasicBlock *, 16> BlockWorkList;
1191 SmallPtrSet<BlockChain *, 4> UpdatedPreds;
1192 for (MachineBasicBlock &MBB : F) {
1193 BlockChain &Chain = *BlockToChain[&MBB];
1194 if (!UpdatedPreds.insert(&Chain).second)
1197 assert(Chain.LoopPredecessors == 0);
1198 for (MachineBasicBlock *ChainBB : Chain) {
1199 assert(BlockToChain[ChainBB] == &Chain);
1200 for (MachineBasicBlock *Pred : ChainBB->predecessors()) {
1201 if (BlockToChain[Pred] == &Chain)
1203 ++Chain.LoopPredecessors;
1207 if (Chain.LoopPredecessors == 0)
1208 BlockWorkList.push_back(*Chain.begin());
1211 BlockChain &FunctionChain = *BlockToChain[&F.front()];
1212 buildChain(&F.front(), FunctionChain, BlockWorkList);
1215 typedef SmallPtrSet<MachineBasicBlock *, 16> FunctionBlockSetType;
1218 // Crash at the end so we get all of the debugging output first.
1219 bool BadFunc = false;
1220 FunctionBlockSetType FunctionBlockSet;
1221 for (MachineBasicBlock &MBB : F)
1222 FunctionBlockSet.insert(&MBB);
1224 for (MachineBasicBlock *ChainBB : FunctionChain)
1225 if (!FunctionBlockSet.erase(ChainBB)) {
1227 dbgs() << "Function chain contains a block not in the function!\n"
1228 << " Bad block: " << getBlockName(ChainBB) << "\n";
1231 if (!FunctionBlockSet.empty()) {
1233 for (MachineBasicBlock *RemainingBB : FunctionBlockSet)
1234 dbgs() << "Function contains blocks never placed into a chain!\n"
1235 << " Bad block: " << getBlockName(RemainingBB) << "\n";
1237 assert(!BadFunc && "Detected problems with the block placement.");
1240 // Splice the blocks into place.
1241 MachineFunction::iterator InsertPos = F.begin();
1242 for (MachineBasicBlock *ChainBB : FunctionChain) {
1243 DEBUG(dbgs() << (ChainBB == *FunctionChain.begin() ? "Placing chain "
1245 << getBlockName(ChainBB) << "\n");
1246 if (InsertPos != MachineFunction::iterator(ChainBB))
1247 F.splice(InsertPos, ChainBB);
1251 // Update the terminator of the previous block.
1252 if (ChainBB == *FunctionChain.begin())
1254 MachineBasicBlock *PrevBB = &*std::prev(MachineFunction::iterator(ChainBB));
1256 // FIXME: It would be awesome of updateTerminator would just return rather
1257 // than assert when the branch cannot be analyzed in order to remove this
1260 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
1261 if (!TII->AnalyzeBranch(*PrevBB, TBB, FBB, Cond)) {
1262 // The "PrevBB" is not yet updated to reflect current code layout, so,
1263 // o. it may fall-through to a block without explict "goto" instruction
1264 // before layout, and no longer fall-through it after layout; or
1265 // o. just opposite.
1267 // AnalyzeBranch() may return erroneous value for FBB when these two
1268 // situations take place. For the first scenario FBB is mistakenly set
1269 // NULL; for the 2nd scenario, the FBB, which is expected to be NULL,
1270 // is mistakenly pointing to "*BI".
1272 bool needUpdateBr = true;
1273 if (!Cond.empty() && (!FBB || FBB == ChainBB)) {
1274 PrevBB->updateTerminator();
1275 needUpdateBr = false;
1277 TBB = FBB = nullptr;
1278 if (TII->AnalyzeBranch(*PrevBB, TBB, FBB, Cond)) {
1279 // FIXME: This should never take place.
1280 TBB = FBB = nullptr;
1284 // If PrevBB has a two-way branch, try to re-order the branches
1285 // such that we branch to the successor with higher probability first.
1286 if (TBB && !Cond.empty() && FBB &&
1287 MBPI->getEdgeProbability(PrevBB, FBB) >
1288 MBPI->getEdgeProbability(PrevBB, TBB) &&
1289 !TII->ReverseBranchCondition(Cond)) {
1290 DEBUG(dbgs() << "Reverse order of the two branches: "
1291 << getBlockName(PrevBB) << "\n");
1292 DEBUG(dbgs() << " Edge probability: "
1293 << MBPI->getEdgeProbability(PrevBB, FBB) << " vs "
1294 << MBPI->getEdgeProbability(PrevBB, TBB) << "\n");
1295 DebugLoc dl; // FIXME: this is nowhere
1296 TII->RemoveBranch(*PrevBB);
1297 TII->InsertBranch(*PrevBB, FBB, TBB, Cond, dl);
1298 needUpdateBr = true;
1301 PrevBB->updateTerminator();
1305 // Fixup the last block.
1307 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
1308 if (!TII->AnalyzeBranch(F.back(), TBB, FBB, Cond))
1309 F.back().updateTerminator();
1311 // Walk through the backedges of the function now that we have fully laid out
1312 // the basic blocks and align the destination of each backedge. We don't rely
1313 // exclusively on the loop info here so that we can align backedges in
1314 // unnatural CFGs and backedges that were introduced purely because of the
1315 // loop rotations done during this layout pass.
1316 // FIXME: Use Function::optForSize().
1317 if (F.getFunction()->hasFnAttribute(Attribute::OptimizeForSize))
1319 if (FunctionChain.begin() == FunctionChain.end())
1320 return; // Empty chain.
1322 const BranchProbability ColdProb(1, 5); // 20%
1323 BlockFrequency EntryFreq = MBFI->getBlockFreq(&F.front());
1324 BlockFrequency WeightedEntryFreq = EntryFreq * ColdProb;
1325 for (MachineBasicBlock *ChainBB : FunctionChain) {
1326 if (ChainBB == *FunctionChain.begin())
1329 // Don't align non-looping basic blocks. These are unlikely to execute
1330 // enough times to matter in practice. Note that we'll still handle
1331 // unnatural CFGs inside of a natural outer loop (the common case) and
1333 MachineLoop *L = MLI->getLoopFor(ChainBB);
1337 if (AlignAllLoops) {
1338 ChainBB->setAlignment(AlignAllLoops);
1342 unsigned Align = TLI->getPrefLoopAlignment(L);
1344 continue; // Don't care about loop alignment.
1346 // If the block is cold relative to the function entry don't waste space
1348 BlockFrequency Freq = MBFI->getBlockFreq(ChainBB);
1349 if (Freq < WeightedEntryFreq)
1352 // If the block is cold relative to its loop header, don't align it
1353 // regardless of what edges into the block exist.
1354 MachineBasicBlock *LoopHeader = L->getHeader();
1355 BlockFrequency LoopHeaderFreq = MBFI->getBlockFreq(LoopHeader);
1356 if (Freq < (LoopHeaderFreq * ColdProb))
1359 // Check for the existence of a non-layout predecessor which would benefit
1360 // from aligning this block.
1361 MachineBasicBlock *LayoutPred =
1362 &*std::prev(MachineFunction::iterator(ChainBB));
1364 // Force alignment if all the predecessors are jumps. We already checked
1365 // that the block isn't cold above.
1366 if (!LayoutPred->isSuccessor(ChainBB)) {
1367 ChainBB->setAlignment(Align);
1371 // Align this block if the layout predecessor's edge into this block is
1372 // cold relative to the block. When this is true, other predecessors make up
1373 // all of the hot entries into the block and thus alignment is likely to be
1375 BranchProbability LayoutProb =
1376 MBPI->getEdgeProbability(LayoutPred, ChainBB);
1377 BlockFrequency LayoutEdgeFreq = MBFI->getBlockFreq(LayoutPred) * LayoutProb;
1378 if (LayoutEdgeFreq <= (Freq * ColdProb))
1379 ChainBB->setAlignment(Align);
1383 bool MachineBlockPlacement::runOnMachineFunction(MachineFunction &F) {
1384 // Check for single-block functions and skip them.
1385 if (std::next(F.begin()) == F.end())
1388 if (skipOptnoneFunction(*F.getFunction()))
1391 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
1392 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
1393 MLI = &getAnalysis<MachineLoopInfo>();
1394 TII = F.getSubtarget().getInstrInfo();
1395 TLI = F.getSubtarget().getTargetLowering();
1396 MDT = &getAnalysis<MachineDominatorTree>();
1397 assert(BlockToChain.empty());
1401 BlockToChain.clear();
1402 ChainAllocator.DestroyAll();
1405 // Align all of the blocks in the function to a specific alignment.
1406 for (MachineBasicBlock &MBB : F)
1407 MBB.setAlignment(AlignAllBlock);
1409 // We always return true as we have no way to track whether the final order
1410 // differs from the original order.
1415 /// \brief A pass to compute block placement statistics.
1417 /// A separate pass to compute interesting statistics for evaluating block
1418 /// placement. This is separate from the actual placement pass so that they can
1419 /// be computed in the absence of any placement transformations or when using
1420 /// alternative placement strategies.
1421 class MachineBlockPlacementStats : public MachineFunctionPass {
1422 /// \brief A handle to the branch probability pass.
1423 const MachineBranchProbabilityInfo *MBPI;
1425 /// \brief A handle to the function-wide block frequency pass.
1426 const MachineBlockFrequencyInfo *MBFI;
1429 static char ID; // Pass identification, replacement for typeid
1430 MachineBlockPlacementStats() : MachineFunctionPass(ID) {
1431 initializeMachineBlockPlacementStatsPass(*PassRegistry::getPassRegistry());
1434 bool runOnMachineFunction(MachineFunction &F) override;
1436 void getAnalysisUsage(AnalysisUsage &AU) const override {
1437 AU.addRequired<MachineBranchProbabilityInfo>();
1438 AU.addRequired<MachineBlockFrequencyInfo>();
1439 AU.setPreservesAll();
1440 MachineFunctionPass::getAnalysisUsage(AU);
1445 char MachineBlockPlacementStats::ID = 0;
1446 char &llvm::MachineBlockPlacementStatsID = MachineBlockPlacementStats::ID;
1447 INITIALIZE_PASS_BEGIN(MachineBlockPlacementStats, "block-placement-stats",
1448 "Basic Block Placement Stats", false, false)
1449 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
1450 INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
1451 INITIALIZE_PASS_END(MachineBlockPlacementStats, "block-placement-stats",
1452 "Basic Block Placement Stats", false, false)
1454 bool MachineBlockPlacementStats::runOnMachineFunction(MachineFunction &F) {
1455 // Check for single-block functions and skip them.
1456 if (std::next(F.begin()) == F.end())
1459 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
1460 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
1462 for (MachineBasicBlock &MBB : F) {
1463 BlockFrequency BlockFreq = MBFI->getBlockFreq(&MBB);
1464 Statistic &NumBranches =
1465 (MBB.succ_size() > 1) ? NumCondBranches : NumUncondBranches;
1466 Statistic &BranchTakenFreq =
1467 (MBB.succ_size() > 1) ? CondBranchTakenFreq : UncondBranchTakenFreq;
1468 for (MachineBasicBlock *Succ : MBB.successors()) {
1469 // Skip if this successor is a fallthrough.
1470 if (MBB.isLayoutSuccessor(Succ))
1473 BlockFrequency EdgeFreq =
1474 BlockFreq * MBPI->getEdgeProbability(&MBB, Succ);
1476 BranchTakenFreq += EdgeFreq.getFrequency();