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 // FIXME: Find a good default for this flag and remove the flag.
66 static cl::opt<unsigned> ExitBlockBias(
67 "block-placement-exit-block-bias",
68 cl::desc("Block frequency percentage a loop exit block needs "
69 "over the original exit to be considered the new exit."),
70 cl::init(0), cl::Hidden);
72 static cl::opt<bool> OutlineOptionalBranches(
73 "outline-optional-branches",
74 cl::desc("Put completely optional branches, i.e. branches with a common "
75 "post dominator, out of line."),
76 cl::init(false), cl::Hidden);
78 static cl::opt<unsigned> OutlineOptionalThreshold(
79 "outline-optional-threshold",
80 cl::desc("Don't outline optional branches that are a single block with an "
81 "instruction count below this threshold"),
82 cl::init(4), cl::Hidden);
84 static cl::opt<unsigned> LoopToColdBlockRatio(
85 "loop-to-cold-block-ratio",
86 cl::desc("Outline loop blocks from loop chain if (frequency of loop) / "
87 "(frequency of block) is greater than this ratio"),
88 cl::init(5), cl::Hidden);
91 PreciseRotationCost("precise-rotation-cost",
92 cl::desc("Model the cost of loop rotation more "
93 "precisely by using profile data."),
94 cl::init(false), cl::Hidden);
96 static cl::opt<unsigned> MisfetchCost(
98 cl::desc("Cost that models the probablistic risk of an instruction "
99 "misfetch due to a jump comparing to falling through, whose cost "
101 cl::init(1), cl::Hidden);
103 static cl::opt<unsigned> JumpInstCost("jump-inst-cost",
104 cl::desc("Cost of jump instructions."),
105 cl::init(1), cl::Hidden);
109 /// \brief Type for our function-wide basic block -> block chain mapping.
110 typedef DenseMap<MachineBasicBlock *, BlockChain *> BlockToChainMapType;
114 /// \brief A chain of blocks which will be laid out contiguously.
116 /// This is the datastructure representing a chain of consecutive blocks that
117 /// are profitable to layout together in order to maximize fallthrough
118 /// probabilities and code locality. We also can use a block chain to represent
119 /// a sequence of basic blocks which have some external (correctness)
120 /// requirement for sequential layout.
122 /// Chains can be built around a single basic block and can be merged to grow
123 /// them. They participate in a block-to-chain mapping, which is updated
124 /// automatically as chains are merged together.
126 /// \brief The sequence of blocks belonging to this chain.
128 /// This is the sequence of blocks for a particular chain. These will be laid
129 /// out in-order within the function.
130 SmallVector<MachineBasicBlock *, 4> Blocks;
132 /// \brief A handle to the function-wide basic block to block chain mapping.
134 /// This is retained in each block chain to simplify the computation of child
135 /// block chains for SCC-formation and iteration. We store the edges to child
136 /// basic blocks, and map them back to their associated chains using this
138 BlockToChainMapType &BlockToChain;
141 /// \brief Construct a new BlockChain.
143 /// This builds a new block chain representing a single basic block in the
144 /// function. It also registers itself as the chain that block participates
145 /// in with the BlockToChain mapping.
146 BlockChain(BlockToChainMapType &BlockToChain, MachineBasicBlock *BB)
147 : Blocks(1, BB), BlockToChain(BlockToChain), LoopPredecessors(0) {
148 assert(BB && "Cannot create a chain with a null basic block");
149 BlockToChain[BB] = this;
152 /// \brief Iterator over blocks within the chain.
153 typedef SmallVectorImpl<MachineBasicBlock *>::iterator iterator;
155 /// \brief Beginning of blocks within the chain.
156 iterator begin() { return Blocks.begin(); }
158 /// \brief End of blocks within the chain.
159 iterator end() { return Blocks.end(); }
161 /// \brief Merge a block chain into this one.
163 /// This routine merges a block chain into this one. It takes care of forming
164 /// a contiguous sequence of basic blocks, updating the edge list, and
165 /// updating the block -> chain mapping. It does not free or tear down the
166 /// old chain, but the old chain's block list is no longer valid.
167 void merge(MachineBasicBlock *BB, BlockChain *Chain) {
169 assert(!Blocks.empty());
171 // Fast path in case we don't have a chain already.
173 assert(!BlockToChain[BB]);
174 Blocks.push_back(BB);
175 BlockToChain[BB] = this;
179 assert(BB == *Chain->begin());
180 assert(Chain->begin() != Chain->end());
182 // Update the incoming blocks to point to this chain, and add them to the
184 for (MachineBasicBlock *ChainBB : *Chain) {
185 Blocks.push_back(ChainBB);
186 assert(BlockToChain[ChainBB] == Chain && "Incoming blocks not in chain");
187 BlockToChain[ChainBB] = this;
192 /// \brief Dump the blocks in this chain.
193 LLVM_DUMP_METHOD void dump() {
194 for (MachineBasicBlock *MBB : *this)
199 /// \brief Count of predecessors within the loop currently being processed.
201 /// This count is updated at each loop we process to represent the number of
202 /// in-loop predecessors of this chain.
203 unsigned LoopPredecessors;
208 class MachineBlockPlacement : public MachineFunctionPass {
209 /// \brief A typedef for a block filter set.
210 typedef SmallPtrSet<MachineBasicBlock *, 16> BlockFilterSet;
212 /// \brief A handle to the branch probability pass.
213 const MachineBranchProbabilityInfo *MBPI;
215 /// \brief A handle to the function-wide block frequency pass.
216 const MachineBlockFrequencyInfo *MBFI;
218 /// \brief A handle to the loop info.
219 const MachineLoopInfo *MLI;
221 /// \brief A handle to the target's instruction info.
222 const TargetInstrInfo *TII;
224 /// \brief A handle to the target's lowering info.
225 const TargetLoweringBase *TLI;
227 /// \brief A handle to the post dominator tree.
228 MachineDominatorTree *MDT;
230 /// \brief A set of blocks that are unavoidably execute, i.e. they dominate
231 /// all terminators of the MachineFunction.
232 SmallPtrSet<MachineBasicBlock *, 4> UnavoidableBlocks;
234 /// \brief Allocator and owner of BlockChain structures.
236 /// We build BlockChains lazily while processing the loop structure of
237 /// a function. To reduce malloc traffic, we allocate them using this
238 /// slab-like allocator, and destroy them after the pass completes. An
239 /// important guarantee is that this allocator produces stable pointers to
241 SpecificBumpPtrAllocator<BlockChain> ChainAllocator;
243 /// \brief Function wide BasicBlock to BlockChain mapping.
245 /// This mapping allows efficiently moving from any given basic block to the
246 /// BlockChain it participates in, if any. We use it to, among other things,
247 /// allow implicitly defining edges between chains as the existing edges
248 /// between basic blocks.
249 DenseMap<MachineBasicBlock *, BlockChain *> BlockToChain;
251 void markChainSuccessors(BlockChain &Chain, MachineBasicBlock *LoopHeaderBB,
252 SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
253 const BlockFilterSet *BlockFilter = nullptr);
254 MachineBasicBlock *selectBestSuccessor(MachineBasicBlock *BB,
256 const BlockFilterSet *BlockFilter);
258 selectBestCandidateBlock(BlockChain &Chain,
259 SmallVectorImpl<MachineBasicBlock *> &WorkList,
260 const BlockFilterSet *BlockFilter);
262 getFirstUnplacedBlock(MachineFunction &F, const BlockChain &PlacedChain,
263 MachineFunction::iterator &PrevUnplacedBlockIt,
264 const BlockFilterSet *BlockFilter);
265 void buildChain(MachineBasicBlock *BB, BlockChain &Chain,
266 SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
267 const BlockFilterSet *BlockFilter = nullptr);
268 MachineBasicBlock *findBestLoopTop(MachineLoop &L,
269 const BlockFilterSet &LoopBlockSet);
270 MachineBasicBlock *findBestLoopExit(MachineFunction &F, MachineLoop &L,
271 const BlockFilterSet &LoopBlockSet);
272 BlockFilterSet collectLoopBlockSet(MachineFunction &F, MachineLoop &L);
273 void buildLoopChains(MachineFunction &F, MachineLoop &L);
274 void rotateLoop(BlockChain &LoopChain, MachineBasicBlock *ExitingBB,
275 const BlockFilterSet &LoopBlockSet);
276 void rotateLoopWithProfile(BlockChain &LoopChain, MachineLoop &L,
277 const BlockFilterSet &LoopBlockSet);
278 void buildCFGChains(MachineFunction &F);
281 static char ID; // Pass identification, replacement for typeid
282 MachineBlockPlacement() : MachineFunctionPass(ID) {
283 initializeMachineBlockPlacementPass(*PassRegistry::getPassRegistry());
286 bool runOnMachineFunction(MachineFunction &F) override;
288 void getAnalysisUsage(AnalysisUsage &AU) const override {
289 AU.addRequired<MachineBranchProbabilityInfo>();
290 AU.addRequired<MachineBlockFrequencyInfo>();
291 AU.addRequired<MachineDominatorTree>();
292 AU.addRequired<MachineLoopInfo>();
293 MachineFunctionPass::getAnalysisUsage(AU);
298 char MachineBlockPlacement::ID = 0;
299 char &llvm::MachineBlockPlacementID = MachineBlockPlacement::ID;
300 INITIALIZE_PASS_BEGIN(MachineBlockPlacement, "block-placement",
301 "Branch Probability Basic Block Placement", false, false)
302 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
303 INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
304 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
305 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
306 INITIALIZE_PASS_END(MachineBlockPlacement, "block-placement",
307 "Branch Probability Basic Block Placement", false, false)
310 /// \brief Helper to print the name of a MBB.
312 /// Only used by debug logging.
313 static std::string getBlockName(MachineBasicBlock *BB) {
315 raw_string_ostream OS(Result);
316 OS << "BB#" << BB->getNumber();
317 OS << " (derived from LLVM BB '" << BB->getName() << "')";
322 /// \brief Helper to print the number of a MBB.
324 /// Only used by debug logging.
325 static std::string getBlockNum(MachineBasicBlock *BB) {
327 raw_string_ostream OS(Result);
328 OS << "BB#" << BB->getNumber();
334 /// \brief Mark a chain's successors as having one fewer preds.
336 /// When a chain is being merged into the "placed" chain, this routine will
337 /// quickly walk the successors of each block in the chain and mark them as
338 /// having one fewer active predecessor. It also adds any successors of this
339 /// chain which reach the zero-predecessor state to the worklist passed in.
340 void MachineBlockPlacement::markChainSuccessors(
341 BlockChain &Chain, MachineBasicBlock *LoopHeaderBB,
342 SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
343 const BlockFilterSet *BlockFilter) {
344 // Walk all the blocks in this chain, marking their successors as having
345 // a predecessor placed.
346 for (MachineBasicBlock *MBB : Chain) {
347 // Add any successors for which this is the only un-placed in-loop
348 // predecessor to the worklist as a viable candidate for CFG-neutral
349 // placement. No subsequent placement of this block will violate the CFG
350 // shape, so we get to use heuristics to choose a favorable placement.
351 for (MachineBasicBlock *Succ : MBB->successors()) {
352 if (BlockFilter && !BlockFilter->count(Succ))
354 BlockChain &SuccChain = *BlockToChain[Succ];
355 // Disregard edges within a fixed chain, or edges to the loop header.
356 if (&Chain == &SuccChain || Succ == LoopHeaderBB)
359 // This is a cross-chain edge that is within the loop, so decrement the
360 // loop predecessor count of the destination chain.
361 if (SuccChain.LoopPredecessors > 0 && --SuccChain.LoopPredecessors == 0)
362 BlockWorkList.push_back(*SuccChain.begin());
367 /// \brief Select the best successor for a block.
369 /// This looks across all successors of a particular block and attempts to
370 /// select the "best" one to be the layout successor. It only considers direct
371 /// successors which also pass the block filter. It will attempt to avoid
372 /// breaking CFG structure, but cave and break such structures in the case of
373 /// very hot successor edges.
375 /// \returns The best successor block found, or null if none are viable.
377 MachineBlockPlacement::selectBestSuccessor(MachineBasicBlock *BB,
379 const BlockFilterSet *BlockFilter) {
380 const BranchProbability HotProb(4, 5); // 80%
382 MachineBasicBlock *BestSucc = nullptr;
383 // FIXME: Due to the performance of the probability and weight routines in
384 // the MBPI analysis, we manually compute probabilities using the edge
385 // weights. This is suboptimal as it means that the somewhat subtle
386 // definition of edge weight semantics is encoded here as well. We should
387 // improve the MBPI interface to efficiently support query patterns such as
389 uint32_t BestWeight = 0;
390 uint32_t WeightScale = 0;
391 uint32_t SumWeight = MBPI->getSumForBlock(BB, WeightScale);
393 // Adjust sum of weights by excluding weights on edges pointing to blocks that
394 // is either not in BlockFilter or is already in the current chain. Consider
395 // the following CFG:
403 // Assume A->C is very hot (>90%), and C->D has a 50% probability, then after
404 // A->C is chosen as a fall-through, D won't be selected as a successor of C
405 // due to CFG constraint (the probability of C->D is not greater than
406 // HotProb). If we exclude E that is not in BlockFilter when calculating the
407 // probability of C->D, D will be selected and we will get A C D B as the
408 // layout of this loop.
409 uint32_t AdjustedSumWeight = SumWeight;
410 SmallVector<MachineBasicBlock *, 4> Successors;
411 for (MachineBasicBlock *Succ : BB->successors()) {
412 bool SkipSucc = false;
413 if (BlockFilter && !BlockFilter->count(Succ)) {
416 BlockChain *SuccChain = BlockToChain[Succ];
417 if (SuccChain == &Chain) {
418 DEBUG(dbgs() << " " << getBlockName(Succ)
419 << " -> Already merged!\n");
421 } else if (Succ != *SuccChain->begin()) {
422 DEBUG(dbgs() << " " << getBlockName(Succ) << " -> Mid chain!\n");
427 AdjustedSumWeight -= MBPI->getEdgeWeight(BB, Succ) / WeightScale;
429 Successors.push_back(Succ);
432 DEBUG(dbgs() << "Attempting merge from: " << getBlockName(BB) << "\n");
433 for (MachineBasicBlock *Succ : Successors) {
434 uint32_t SuccWeight = MBPI->getEdgeWeight(BB, Succ);
435 BranchProbability SuccProb(SuccWeight / WeightScale, AdjustedSumWeight);
437 // If we outline optional branches, look whether Succ is unavoidable, i.e.
438 // dominates all terminators of the MachineFunction. If it does, other
439 // successors must be optional. Don't do this for cold branches.
440 if (OutlineOptionalBranches && SuccProb > HotProb.getCompl() &&
441 UnavoidableBlocks.count(Succ) > 0) {
442 auto HasShortOptionalBranch = [&]() {
443 for (MachineBasicBlock *Pred : Succ->predecessors()) {
444 // Check whether there is an unplaced optional branch.
445 if (Pred == Succ || (BlockFilter && !BlockFilter->count(Pred)) ||
446 BlockToChain[Pred] == &Chain)
448 // Check whether the optional branch has exactly one BB.
449 if (Pred->pred_size() > 1 || *Pred->pred_begin() != BB)
451 // Check whether the optional branch is small.
452 if (Pred->size() < OutlineOptionalThreshold)
457 if (!HasShortOptionalBranch())
461 // Only consider successors which are either "hot", or wouldn't violate
462 // any CFG constraints.
463 BlockChain &SuccChain = *BlockToChain[Succ];
464 if (SuccChain.LoopPredecessors != 0) {
465 if (SuccProb < HotProb) {
466 DEBUG(dbgs() << " " << getBlockName(Succ) << " -> " << SuccProb
467 << " (prob) (CFG conflict)\n");
471 // Make sure that a hot successor doesn't have a globally more
472 // important predecessor.
473 BranchProbability RealSuccProb(SuccWeight / WeightScale, SumWeight);
474 BlockFrequency CandidateEdgeFreq =
475 MBFI->getBlockFreq(BB) * RealSuccProb * HotProb.getCompl();
476 bool BadCFGConflict = false;
477 for (MachineBasicBlock *Pred : Succ->predecessors()) {
478 if (Pred == Succ || (BlockFilter && !BlockFilter->count(Pred)) ||
479 BlockToChain[Pred] == &Chain)
481 BlockFrequency PredEdgeFreq =
482 MBFI->getBlockFreq(Pred) * MBPI->getEdgeProbability(Pred, Succ);
483 if (PredEdgeFreq >= CandidateEdgeFreq) {
484 BadCFGConflict = true;
488 if (BadCFGConflict) {
489 DEBUG(dbgs() << " " << getBlockName(Succ) << " -> " << SuccProb
490 << " (prob) (non-cold CFG conflict)\n");
495 DEBUG(dbgs() << " " << getBlockName(Succ) << " -> " << SuccProb
497 << (SuccChain.LoopPredecessors != 0 ? " (CFG break)" : "")
499 if (BestSucc && BestWeight >= SuccWeight)
502 BestWeight = SuccWeight;
507 /// \brief Select the best block from a worklist.
509 /// This looks through the provided worklist as a list of candidate basic
510 /// blocks and select the most profitable one to place. The definition of
511 /// profitable only really makes sense in the context of a loop. This returns
512 /// the most frequently visited block in the worklist, which in the case of
513 /// a loop, is the one most desirable to be physically close to the rest of the
514 /// loop body in order to improve icache behavior.
516 /// \returns The best block found, or null if none are viable.
517 MachineBasicBlock *MachineBlockPlacement::selectBestCandidateBlock(
518 BlockChain &Chain, SmallVectorImpl<MachineBasicBlock *> &WorkList,
519 const BlockFilterSet *BlockFilter) {
520 // Once we need to walk the worklist looking for a candidate, cleanup the
521 // worklist of already placed entries.
522 // FIXME: If this shows up on profiles, it could be folded (at the cost of
523 // some code complexity) into the loop below.
524 WorkList.erase(std::remove_if(WorkList.begin(), WorkList.end(),
525 [&](MachineBasicBlock *BB) {
526 return BlockToChain.lookup(BB) == &Chain;
530 MachineBasicBlock *BestBlock = nullptr;
531 BlockFrequency BestFreq;
532 for (MachineBasicBlock *MBB : WorkList) {
533 BlockChain &SuccChain = *BlockToChain[MBB];
534 if (&SuccChain == &Chain) {
535 DEBUG(dbgs() << " " << getBlockName(MBB) << " -> Already merged!\n");
538 assert(SuccChain.LoopPredecessors == 0 && "Found CFG-violating block");
540 BlockFrequency CandidateFreq = MBFI->getBlockFreq(MBB);
541 DEBUG(dbgs() << " " << getBlockName(MBB) << " -> ";
542 MBFI->printBlockFreq(dbgs(), CandidateFreq) << " (freq)\n");
543 if (BestBlock && BestFreq >= CandidateFreq)
546 BestFreq = CandidateFreq;
551 /// \brief Retrieve the first unplaced basic block.
553 /// This routine is called when we are unable to use the CFG to walk through
554 /// all of the basic blocks and form a chain due to unnatural loops in the CFG.
555 /// We walk through the function's blocks in order, starting from the
556 /// LastUnplacedBlockIt. We update this iterator on each call to avoid
557 /// re-scanning the entire sequence on repeated calls to this routine.
558 MachineBasicBlock *MachineBlockPlacement::getFirstUnplacedBlock(
559 MachineFunction &F, const BlockChain &PlacedChain,
560 MachineFunction::iterator &PrevUnplacedBlockIt,
561 const BlockFilterSet *BlockFilter) {
562 for (MachineFunction::iterator I = PrevUnplacedBlockIt, E = F.end(); I != E;
564 if (BlockFilter && !BlockFilter->count(&*I))
566 if (BlockToChain[&*I] != &PlacedChain) {
567 PrevUnplacedBlockIt = I;
568 // Now select the head of the chain to which the unplaced block belongs
569 // as the block to place. This will force the entire chain to be placed,
570 // and satisfies the requirements of merging chains.
571 return *BlockToChain[&*I]->begin();
577 void MachineBlockPlacement::buildChain(
578 MachineBasicBlock *BB, BlockChain &Chain,
579 SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
580 const BlockFilterSet *BlockFilter) {
582 assert(BlockToChain[BB] == &Chain);
583 MachineFunction &F = *BB->getParent();
584 MachineFunction::iterator PrevUnplacedBlockIt = F.begin();
586 MachineBasicBlock *LoopHeaderBB = BB;
587 markChainSuccessors(Chain, LoopHeaderBB, BlockWorkList, BlockFilter);
588 BB = *std::prev(Chain.end());
591 assert(BlockToChain[BB] == &Chain);
592 assert(*std::prev(Chain.end()) == BB);
594 // Look for the best viable successor if there is one to place immediately
596 MachineBasicBlock *BestSucc = selectBestSuccessor(BB, Chain, BlockFilter);
598 // If an immediate successor isn't available, look for the best viable
599 // block among those we've identified as not violating the loop's CFG at
600 // this point. This won't be a fallthrough, but it will increase locality.
602 BestSucc = selectBestCandidateBlock(Chain, BlockWorkList, BlockFilter);
606 getFirstUnplacedBlock(F, Chain, PrevUnplacedBlockIt, BlockFilter);
610 DEBUG(dbgs() << "Unnatural loop CFG detected, forcibly merging the "
611 "layout successor until the CFG reduces\n");
614 // Place this block, updating the datastructures to reflect its placement.
615 BlockChain &SuccChain = *BlockToChain[BestSucc];
616 // Zero out LoopPredecessors for the successor we're about to merge in case
617 // we selected a successor that didn't fit naturally into the CFG.
618 SuccChain.LoopPredecessors = 0;
619 DEBUG(dbgs() << "Merging from " << getBlockNum(BB) << " to "
620 << getBlockNum(BestSucc) << "\n");
621 markChainSuccessors(SuccChain, LoopHeaderBB, BlockWorkList, BlockFilter);
622 Chain.merge(BestSucc, &SuccChain);
623 BB = *std::prev(Chain.end());
626 DEBUG(dbgs() << "Finished forming chain for header block "
627 << getBlockNum(*Chain.begin()) << "\n");
630 /// \brief Find the best loop top block for layout.
632 /// Look for a block which is strictly better than the loop header for laying
633 /// out at the top of the loop. This looks for one and only one pattern:
634 /// a latch block with no conditional exit. This block will cause a conditional
635 /// jump around it or will be the bottom of the loop if we lay it out in place,
636 /// but if it it doesn't end up at the bottom of the loop for any reason,
637 /// rotation alone won't fix it. Because such a block will always result in an
638 /// unconditional jump (for the backedge) rotating it in front of the loop
639 /// header is always profitable.
641 MachineBlockPlacement::findBestLoopTop(MachineLoop &L,
642 const BlockFilterSet &LoopBlockSet) {
643 // Check that the header hasn't been fused with a preheader block due to
644 // crazy branches. If it has, we need to start with the header at the top to
645 // prevent pulling the preheader into the loop body.
646 BlockChain &HeaderChain = *BlockToChain[L.getHeader()];
647 if (!LoopBlockSet.count(*HeaderChain.begin()))
648 return L.getHeader();
650 DEBUG(dbgs() << "Finding best loop top for: " << getBlockName(L.getHeader())
653 BlockFrequency BestPredFreq;
654 MachineBasicBlock *BestPred = nullptr;
655 for (MachineBasicBlock *Pred : L.getHeader()->predecessors()) {
656 if (!LoopBlockSet.count(Pred))
658 DEBUG(dbgs() << " header pred: " << getBlockName(Pred) << ", "
659 << Pred->succ_size() << " successors, ";
660 MBFI->printBlockFreq(dbgs(), Pred) << " freq\n");
661 if (Pred->succ_size() > 1)
664 BlockFrequency PredFreq = MBFI->getBlockFreq(Pred);
665 if (!BestPred || PredFreq > BestPredFreq ||
666 (!(PredFreq < BestPredFreq) &&
667 Pred->isLayoutSuccessor(L.getHeader()))) {
669 BestPredFreq = PredFreq;
673 // If no direct predecessor is fine, just use the loop header.
675 return L.getHeader();
677 // Walk backwards through any straight line of predecessors.
678 while (BestPred->pred_size() == 1 &&
679 (*BestPred->pred_begin())->succ_size() == 1 &&
680 *BestPred->pred_begin() != L.getHeader())
681 BestPred = *BestPred->pred_begin();
683 DEBUG(dbgs() << " final top: " << getBlockName(BestPred) << "\n");
687 /// \brief Find the best loop exiting block for layout.
689 /// This routine implements the logic to analyze the loop looking for the best
690 /// block to layout at the top of the loop. Typically this is done to maximize
691 /// fallthrough opportunities.
693 MachineBlockPlacement::findBestLoopExit(MachineFunction &F, MachineLoop &L,
694 const BlockFilterSet &LoopBlockSet) {
695 // We don't want to layout the loop linearly in all cases. If the loop header
696 // is just a normal basic block in the loop, we want to look for what block
697 // within the loop is the best one to layout at the top. However, if the loop
698 // header has be pre-merged into a chain due to predecessors not having
699 // analyzable branches, *and* the predecessor it is merged with is *not* part
700 // of the loop, rotating the header into the middle of the loop will create
701 // a non-contiguous range of blocks which is Very Bad. So start with the
702 // header and only rotate if safe.
703 BlockChain &HeaderChain = *BlockToChain[L.getHeader()];
704 if (!LoopBlockSet.count(*HeaderChain.begin()))
707 BlockFrequency BestExitEdgeFreq;
708 unsigned BestExitLoopDepth = 0;
709 MachineBasicBlock *ExitingBB = nullptr;
710 // If there are exits to outer loops, loop rotation can severely limit
711 // fallthrough opportunites unless it selects such an exit. Keep a set of
712 // blocks where rotating to exit with that block will reach an outer loop.
713 SmallPtrSet<MachineBasicBlock *, 4> BlocksExitingToOuterLoop;
715 DEBUG(dbgs() << "Finding best loop exit for: " << getBlockName(L.getHeader())
717 for (MachineBasicBlock *MBB : L.getBlocks()) {
718 BlockChain &Chain = *BlockToChain[MBB];
719 // Ensure that this block is at the end of a chain; otherwise it could be
720 // mid-way through an inner loop or a successor of an unanalyzable branch.
721 if (MBB != *std::prev(Chain.end()))
724 // Now walk the successors. We need to establish whether this has a viable
725 // exiting successor and whether it has a viable non-exiting successor.
726 // We store the old exiting state and restore it if a viable looping
727 // successor isn't found.
728 MachineBasicBlock *OldExitingBB = ExitingBB;
729 BlockFrequency OldBestExitEdgeFreq = BestExitEdgeFreq;
730 bool HasLoopingSucc = false;
731 // FIXME: Due to the performance of the probability and weight routines in
732 // the MBPI analysis, we use the internal weights and manually compute the
733 // probabilities to avoid quadratic behavior.
734 uint32_t WeightScale = 0;
735 uint32_t SumWeight = MBPI->getSumForBlock(MBB, WeightScale);
736 for (MachineBasicBlock *Succ : MBB->successors()) {
741 BlockChain &SuccChain = *BlockToChain[Succ];
742 // Don't split chains, either this chain or the successor's chain.
743 if (&Chain == &SuccChain) {
744 DEBUG(dbgs() << " exiting: " << getBlockName(MBB) << " -> "
745 << getBlockName(Succ) << " (chain conflict)\n");
749 uint32_t SuccWeight = MBPI->getEdgeWeight(MBB, Succ);
750 if (LoopBlockSet.count(Succ)) {
751 DEBUG(dbgs() << " looping: " << getBlockName(MBB) << " -> "
752 << getBlockName(Succ) << " (" << SuccWeight << ")\n");
753 HasLoopingSucc = true;
757 unsigned SuccLoopDepth = 0;
758 if (MachineLoop *ExitLoop = MLI->getLoopFor(Succ)) {
759 SuccLoopDepth = ExitLoop->getLoopDepth();
760 if (ExitLoop->contains(&L))
761 BlocksExitingToOuterLoop.insert(MBB);
764 BranchProbability SuccProb(SuccWeight / WeightScale, SumWeight);
765 BlockFrequency ExitEdgeFreq = MBFI->getBlockFreq(MBB) * SuccProb;
766 DEBUG(dbgs() << " exiting: " << getBlockName(MBB) << " -> "
767 << getBlockName(Succ) << " [L:" << SuccLoopDepth << "] (";
768 MBFI->printBlockFreq(dbgs(), ExitEdgeFreq) << ")\n");
769 // Note that we bias this toward an existing layout successor to retain
770 // incoming order in the absence of better information. The exit must have
771 // a frequency higher than the current exit before we consider breaking
773 BranchProbability Bias(100 - ExitBlockBias, 100);
774 if (!ExitingBB || SuccLoopDepth > BestExitLoopDepth ||
775 ExitEdgeFreq > BestExitEdgeFreq ||
776 (MBB->isLayoutSuccessor(Succ) &&
777 !(ExitEdgeFreq < BestExitEdgeFreq * Bias))) {
778 BestExitEdgeFreq = ExitEdgeFreq;
783 if (!HasLoopingSucc) {
784 // Restore the old exiting state, no viable looping successor was found.
785 ExitingBB = OldExitingBB;
786 BestExitEdgeFreq = OldBestExitEdgeFreq;
790 // Without a candidate exiting block or with only a single block in the
791 // loop, just use the loop header to layout the loop.
792 if (!ExitingBB || L.getNumBlocks() == 1)
795 // Also, if we have exit blocks which lead to outer loops but didn't select
796 // one of them as the exiting block we are rotating toward, disable loop
797 // rotation altogether.
798 if (!BlocksExitingToOuterLoop.empty() &&
799 !BlocksExitingToOuterLoop.count(ExitingBB))
802 DEBUG(dbgs() << " Best exiting block: " << getBlockName(ExitingBB) << "\n");
806 /// \brief Attempt to rotate an exiting block to the bottom of the loop.
808 /// Once we have built a chain, try to rotate it to line up the hot exit block
809 /// with fallthrough out of the loop if doing so doesn't introduce unnecessary
810 /// branches. For example, if the loop has fallthrough into its header and out
811 /// of its bottom already, don't rotate it.
812 void MachineBlockPlacement::rotateLoop(BlockChain &LoopChain,
813 MachineBasicBlock *ExitingBB,
814 const BlockFilterSet &LoopBlockSet) {
818 MachineBasicBlock *Top = *LoopChain.begin();
819 bool ViableTopFallthrough = false;
820 for (MachineBasicBlock *Pred : Top->predecessors()) {
821 BlockChain *PredChain = BlockToChain[Pred];
822 if (!LoopBlockSet.count(Pred) &&
823 (!PredChain || Pred == *std::prev(PredChain->end()))) {
824 ViableTopFallthrough = true;
829 // If the header has viable fallthrough, check whether the current loop
830 // bottom is a viable exiting block. If so, bail out as rotating will
831 // introduce an unnecessary branch.
832 if (ViableTopFallthrough) {
833 MachineBasicBlock *Bottom = *std::prev(LoopChain.end());
834 for (MachineBasicBlock *Succ : Bottom->successors()) {
835 BlockChain *SuccChain = BlockToChain[Succ];
836 if (!LoopBlockSet.count(Succ) &&
837 (!SuccChain || Succ == *SuccChain->begin()))
842 BlockChain::iterator ExitIt =
843 std::find(LoopChain.begin(), LoopChain.end(), ExitingBB);
844 if (ExitIt == LoopChain.end())
847 std::rotate(LoopChain.begin(), std::next(ExitIt), LoopChain.end());
850 /// \brief Attempt to rotate a loop based on profile data to reduce branch cost.
852 /// With profile data, we can determine the cost in terms of missed fall through
853 /// opportunities when rotating a loop chain and select the best rotation.
854 /// Basically, there are three kinds of cost to consider for each rotation:
855 /// 1. The possibly missed fall through edge (if it exists) from BB out of
856 /// the loop to the loop header.
857 /// 2. The possibly missed fall through edges (if they exist) from the loop
858 /// exits to BB out of the loop.
859 /// 3. The missed fall through edge (if it exists) from the last BB to the
860 /// first BB in the loop chain.
861 /// Therefore, the cost for a given rotation is the sum of costs listed above.
862 /// We select the best rotation with the smallest cost.
863 void MachineBlockPlacement::rotateLoopWithProfile(
864 BlockChain &LoopChain, MachineLoop &L, const BlockFilterSet &LoopBlockSet) {
865 auto HeaderBB = L.getHeader();
866 auto HeaderIter = std::find(LoopChain.begin(), LoopChain.end(), HeaderBB);
867 auto RotationPos = LoopChain.end();
869 BlockFrequency SmallestRotationCost = BlockFrequency::getMaxFrequency();
871 // A utility lambda that scales up a block frequency by dividing it by a
872 // branch probability which is the reciprocal of the scale.
873 auto ScaleBlockFrequency = [](BlockFrequency Freq,
874 unsigned Scale) -> BlockFrequency {
877 // Use operator / between BlockFrequency and BranchProbability to implement
878 // saturating multiplication.
879 return Freq / BranchProbability(1, Scale);
882 // Compute the cost of the missed fall-through edge to the loop header if the
883 // chain head is not the loop header. As we only consider natural loops with
884 // single header, this computation can be done only once.
885 BlockFrequency HeaderFallThroughCost(0);
886 for (auto *Pred : HeaderBB->predecessors()) {
887 BlockChain *PredChain = BlockToChain[Pred];
888 if (!LoopBlockSet.count(Pred) &&
889 (!PredChain || Pred == *std::prev(PredChain->end()))) {
891 MBFI->getBlockFreq(Pred) * MBPI->getEdgeProbability(Pred, HeaderBB);
892 auto FallThruCost = ScaleBlockFrequency(EdgeFreq, MisfetchCost);
893 // If the predecessor has only an unconditional jump to the header, we
894 // need to consider the cost of this jump.
895 if (Pred->succ_size() == 1)
896 FallThruCost += ScaleBlockFrequency(EdgeFreq, JumpInstCost);
897 HeaderFallThroughCost = std::max(HeaderFallThroughCost, FallThruCost);
901 // Here we collect all exit blocks in the loop, and for each exit we find out
902 // its hottest exit edge. For each loop rotation, we define the loop exit cost
903 // as the sum of frequencies of exit edges we collect here, excluding the exit
904 // edge from the tail of the loop chain.
905 SmallVector<std::pair<MachineBasicBlock *, BlockFrequency>, 4> ExitsWithFreq;
906 for (auto BB : LoopChain) {
907 uint32_t LargestExitEdgeWeight = 0;
908 for (auto *Succ : BB->successors()) {
909 BlockChain *SuccChain = BlockToChain[Succ];
910 if (!LoopBlockSet.count(Succ) &&
911 (!SuccChain || Succ == *SuccChain->begin())) {
912 uint32_t SuccWeight = MBPI->getEdgeWeight(BB, Succ);
913 LargestExitEdgeWeight = std::max(LargestExitEdgeWeight, SuccWeight);
916 if (LargestExitEdgeWeight > 0) {
917 uint32_t WeightScale = 0;
918 uint32_t SumWeight = MBPI->getSumForBlock(BB, WeightScale);
920 MBFI->getBlockFreq(BB) *
921 BranchProbability(LargestExitEdgeWeight / WeightScale, SumWeight);
922 ExitsWithFreq.emplace_back(BB, ExitFreq);
926 // In this loop we iterate every block in the loop chain and calculate the
927 // cost assuming the block is the head of the loop chain. When the loop ends,
928 // we should have found the best candidate as the loop chain's head.
929 for (auto Iter = LoopChain.begin(), TailIter = std::prev(LoopChain.end()),
930 EndIter = LoopChain.end();
931 Iter != EndIter; Iter++, TailIter++) {
932 // TailIter is used to track the tail of the loop chain if the block we are
933 // checking (pointed by Iter) is the head of the chain.
934 if (TailIter == LoopChain.end())
935 TailIter = LoopChain.begin();
937 auto TailBB = *TailIter;
939 // Calculate the cost by putting this BB to the top.
940 BlockFrequency Cost = 0;
942 // If the current BB is the loop header, we need to take into account the
943 // cost of the missed fall through edge from outside of the loop to the
945 if (Iter != HeaderIter)
946 Cost += HeaderFallThroughCost;
948 // Collect the loop exit cost by summing up frequencies of all exit edges
949 // except the one from the chain tail.
950 for (auto &ExitWithFreq : ExitsWithFreq)
951 if (TailBB != ExitWithFreq.first)
952 Cost += ExitWithFreq.second;
954 // The cost of breaking the once fall-through edge from the tail to the top
955 // of the loop chain. Here we need to consider three cases:
956 // 1. If the tail node has only one successor, then we will get an
957 // additional jmp instruction. So the cost here is (MisfetchCost +
958 // JumpInstCost) * tail node frequency.
959 // 2. If the tail node has two successors, then we may still get an
960 // additional jmp instruction if the layout successor after the loop
961 // chain is not its CFG successor. Note that the more frequently executed
962 // jmp instruction will be put ahead of the other one. Assume the
963 // frequency of those two branches are x and y, where x is the frequency
964 // of the edge to the chain head, then the cost will be
965 // (x * MisfetechCost + min(x, y) * JumpInstCost) * tail node frequency.
966 // 3. If the tail node has more than two successors (this rarely happens),
967 // we won't consider any additional cost.
968 if (TailBB->isSuccessor(*Iter)) {
969 auto TailBBFreq = MBFI->getBlockFreq(TailBB);
970 if (TailBB->succ_size() == 1)
971 Cost += ScaleBlockFrequency(TailBBFreq.getFrequency(),
972 MisfetchCost + JumpInstCost);
973 else if (TailBB->succ_size() == 2) {
974 auto TailToHeadProb = MBPI->getEdgeProbability(TailBB, *Iter);
975 auto TailToHeadFreq = TailBBFreq * TailToHeadProb;
976 auto ColderEdgeFreq = TailToHeadProb > BranchProbability(1, 2)
977 ? TailBBFreq * TailToHeadProb.getCompl()
979 Cost += ScaleBlockFrequency(TailToHeadFreq, MisfetchCost) +
980 ScaleBlockFrequency(ColderEdgeFreq, JumpInstCost);
984 DEBUG(dbgs() << "The cost of loop rotation by making " << getBlockNum(*Iter)
985 << " to the top: " << Cost.getFrequency() << "\n");
987 if (Cost < SmallestRotationCost) {
988 SmallestRotationCost = Cost;
993 if (RotationPos != LoopChain.end()) {
994 DEBUG(dbgs() << "Rotate loop by making " << getBlockNum(*RotationPos)
996 std::rotate(LoopChain.begin(), RotationPos, LoopChain.end());
1000 /// \brief Collect blocks in the given loop that are to be placed.
1002 /// When profile data is available, exclude cold blocks from the returned set;
1003 /// otherwise, collect all blocks in the loop.
1004 MachineBlockPlacement::BlockFilterSet
1005 MachineBlockPlacement::collectLoopBlockSet(MachineFunction &F, MachineLoop &L) {
1006 BlockFilterSet LoopBlockSet;
1008 // Filter cold blocks off from LoopBlockSet when profile data is available.
1009 // Collect the sum of frequencies of incoming edges to the loop header from
1010 // outside. If we treat the loop as a super block, this is the frequency of
1011 // the loop. Then for each block in the loop, we calculate the ratio between
1012 // its frequency and the frequency of the loop block. When it is too small,
1013 // don't add it to the loop chain. If there are outer loops, then this block
1014 // will be merged into the first outer loop chain for which this block is not
1015 // cold anymore. This needs precise profile data and we only do this when
1016 // profile data is available.
1017 if (F.getFunction()->getEntryCount()) {
1018 BlockFrequency LoopFreq(0);
1019 for (auto LoopPred : L.getHeader()->predecessors())
1020 if (!L.contains(LoopPred))
1021 LoopFreq += MBFI->getBlockFreq(LoopPred) *
1022 MBPI->getEdgeProbability(LoopPred, L.getHeader());
1024 for (MachineBasicBlock *LoopBB : L.getBlocks()) {
1025 auto Freq = MBFI->getBlockFreq(LoopBB).getFrequency();
1026 if (Freq == 0 || LoopFreq.getFrequency() / Freq > LoopToColdBlockRatio)
1028 LoopBlockSet.insert(LoopBB);
1031 LoopBlockSet.insert(L.block_begin(), L.block_end());
1033 return LoopBlockSet;
1036 /// \brief Forms basic block chains from the natural loop structures.
1038 /// These chains are designed to preserve the existing *structure* of the code
1039 /// as much as possible. We can then stitch the chains together in a way which
1040 /// both preserves the topological structure and minimizes taken conditional
1042 void MachineBlockPlacement::buildLoopChains(MachineFunction &F,
1044 // First recurse through any nested loops, building chains for those inner
1046 for (MachineLoop *InnerLoop : L)
1047 buildLoopChains(F, *InnerLoop);
1049 SmallVector<MachineBasicBlock *, 16> BlockWorkList;
1050 BlockFilterSet LoopBlockSet = collectLoopBlockSet(F, L);
1052 // Check if we have profile data for this function. If yes, we will rotate
1053 // this loop by modeling costs more precisely which requires the profile data
1054 // for better layout.
1055 bool RotateLoopWithProfile =
1056 PreciseRotationCost && F.getFunction()->getEntryCount();
1058 // First check to see if there is an obviously preferable top block for the
1059 // loop. This will default to the header, but may end up as one of the
1060 // predecessors to the header if there is one which will result in strictly
1061 // fewer branches in the loop body.
1062 // When we use profile data to rotate the loop, this is unnecessary.
1063 MachineBasicBlock *LoopTop =
1064 RotateLoopWithProfile ? L.getHeader() : findBestLoopTop(L, LoopBlockSet);
1066 // If we selected just the header for the loop top, look for a potentially
1067 // profitable exit block in the event that rotating the loop can eliminate
1068 // branches by placing an exit edge at the bottom.
1069 MachineBasicBlock *ExitingBB = nullptr;
1070 if (!RotateLoopWithProfile && LoopTop == L.getHeader())
1071 ExitingBB = findBestLoopExit(F, L, LoopBlockSet);
1073 BlockChain &LoopChain = *BlockToChain[LoopTop];
1075 // FIXME: This is a really lame way of walking the chains in the loop: we
1076 // walk the blocks, and use a set to prevent visiting a particular chain
1078 SmallPtrSet<BlockChain *, 4> UpdatedPreds;
1079 assert(LoopChain.LoopPredecessors == 0);
1080 UpdatedPreds.insert(&LoopChain);
1082 for (MachineBasicBlock *LoopBB : LoopBlockSet) {
1083 BlockChain &Chain = *BlockToChain[LoopBB];
1084 if (!UpdatedPreds.insert(&Chain).second)
1087 assert(Chain.LoopPredecessors == 0);
1088 for (MachineBasicBlock *ChainBB : Chain) {
1089 assert(BlockToChain[ChainBB] == &Chain);
1090 for (MachineBasicBlock *Pred : ChainBB->predecessors()) {
1091 if (BlockToChain[Pred] == &Chain || !LoopBlockSet.count(Pred))
1093 ++Chain.LoopPredecessors;
1097 if (Chain.LoopPredecessors == 0)
1098 BlockWorkList.push_back(*Chain.begin());
1101 buildChain(LoopTop, LoopChain, BlockWorkList, &LoopBlockSet);
1103 if (RotateLoopWithProfile)
1104 rotateLoopWithProfile(LoopChain, L, LoopBlockSet);
1106 rotateLoop(LoopChain, ExitingBB, LoopBlockSet);
1109 // Crash at the end so we get all of the debugging output first.
1110 bool BadLoop = false;
1111 if (LoopChain.LoopPredecessors) {
1113 dbgs() << "Loop chain contains a block without its preds placed!\n"
1114 << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
1115 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n";
1117 for (MachineBasicBlock *ChainBB : LoopChain) {
1118 dbgs() << " ... " << getBlockName(ChainBB) << "\n";
1119 if (!LoopBlockSet.erase(ChainBB)) {
1120 // We don't mark the loop as bad here because there are real situations
1121 // where this can occur. For example, with an unanalyzable fallthrough
1122 // from a loop block to a non-loop block or vice versa.
1123 dbgs() << "Loop chain contains a block not contained by the loop!\n"
1124 << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
1125 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
1126 << " Bad block: " << getBlockName(ChainBB) << "\n";
1130 if (!LoopBlockSet.empty()) {
1132 for (MachineBasicBlock *LoopBB : LoopBlockSet)
1133 dbgs() << "Loop contains blocks never placed into a chain!\n"
1134 << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
1135 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
1136 << " Bad block: " << getBlockName(LoopBB) << "\n";
1138 assert(!BadLoop && "Detected problems with the placement of this loop.");
1142 void MachineBlockPlacement::buildCFGChains(MachineFunction &F) {
1143 // Ensure that every BB in the function has an associated chain to simplify
1144 // the assumptions of the remaining algorithm.
1145 SmallVector<MachineOperand, 4> Cond; // For AnalyzeBranch.
1146 for (MachineFunction::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
1147 MachineBasicBlock *BB = &*FI;
1149 new (ChainAllocator.Allocate()) BlockChain(BlockToChain, BB);
1150 // Also, merge any blocks which we cannot reason about and must preserve
1151 // the exact fallthrough behavior for.
1154 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
1155 if (!TII->AnalyzeBranch(*BB, TBB, FBB, Cond) || !FI->canFallThrough())
1158 MachineFunction::iterator NextFI = std::next(FI);
1159 MachineBasicBlock *NextBB = &*NextFI;
1160 // Ensure that the layout successor is a viable block, as we know that
1161 // fallthrough is a possibility.
1162 assert(NextFI != FE && "Can't fallthrough past the last block.");
1163 DEBUG(dbgs() << "Pre-merging due to unanalyzable fallthrough: "
1164 << getBlockName(BB) << " -> " << getBlockName(NextBB)
1166 Chain->merge(NextBB, nullptr);
1172 if (OutlineOptionalBranches) {
1173 // Find the nearest common dominator of all of F's terminators.
1174 MachineBasicBlock *Terminator = nullptr;
1175 for (MachineBasicBlock &MBB : F) {
1176 if (MBB.succ_size() == 0) {
1177 if (Terminator == nullptr)
1180 Terminator = MDT->findNearestCommonDominator(Terminator, &MBB);
1184 // MBBs dominating this common dominator are unavoidable.
1185 UnavoidableBlocks.clear();
1186 for (MachineBasicBlock &MBB : F) {
1187 if (MDT->dominates(&MBB, Terminator)) {
1188 UnavoidableBlocks.insert(&MBB);
1193 // Build any loop-based chains.
1194 for (MachineLoop *L : *MLI)
1195 buildLoopChains(F, *L);
1197 SmallVector<MachineBasicBlock *, 16> BlockWorkList;
1199 SmallPtrSet<BlockChain *, 4> UpdatedPreds;
1200 for (MachineBasicBlock &MBB : F) {
1201 BlockChain &Chain = *BlockToChain[&MBB];
1202 if (!UpdatedPreds.insert(&Chain).second)
1205 assert(Chain.LoopPredecessors == 0);
1206 for (MachineBasicBlock *ChainBB : Chain) {
1207 assert(BlockToChain[ChainBB] == &Chain);
1208 for (MachineBasicBlock *Pred : ChainBB->predecessors()) {
1209 if (BlockToChain[Pred] == &Chain)
1211 ++Chain.LoopPredecessors;
1215 if (Chain.LoopPredecessors == 0)
1216 BlockWorkList.push_back(*Chain.begin());
1219 BlockChain &FunctionChain = *BlockToChain[&F.front()];
1220 buildChain(&F.front(), FunctionChain, BlockWorkList);
1223 typedef SmallPtrSet<MachineBasicBlock *, 16> FunctionBlockSetType;
1226 // Crash at the end so we get all of the debugging output first.
1227 bool BadFunc = false;
1228 FunctionBlockSetType FunctionBlockSet;
1229 for (MachineBasicBlock &MBB : F)
1230 FunctionBlockSet.insert(&MBB);
1232 for (MachineBasicBlock *ChainBB : FunctionChain)
1233 if (!FunctionBlockSet.erase(ChainBB)) {
1235 dbgs() << "Function chain contains a block not in the function!\n"
1236 << " Bad block: " << getBlockName(ChainBB) << "\n";
1239 if (!FunctionBlockSet.empty()) {
1241 for (MachineBasicBlock *RemainingBB : FunctionBlockSet)
1242 dbgs() << "Function contains blocks never placed into a chain!\n"
1243 << " Bad block: " << getBlockName(RemainingBB) << "\n";
1245 assert(!BadFunc && "Detected problems with the block placement.");
1248 // Splice the blocks into place.
1249 MachineFunction::iterator InsertPos = F.begin();
1250 for (MachineBasicBlock *ChainBB : FunctionChain) {
1251 DEBUG(dbgs() << (ChainBB == *FunctionChain.begin() ? "Placing chain "
1253 << getBlockName(ChainBB) << "\n");
1254 if (InsertPos != MachineFunction::iterator(ChainBB))
1255 F.splice(InsertPos, ChainBB);
1259 // Update the terminator of the previous block.
1260 if (ChainBB == *FunctionChain.begin())
1262 MachineBasicBlock *PrevBB = &*std::prev(MachineFunction::iterator(ChainBB));
1264 // FIXME: It would be awesome of updateTerminator would just return rather
1265 // than assert when the branch cannot be analyzed in order to remove this
1268 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
1269 if (!TII->AnalyzeBranch(*PrevBB, TBB, FBB, Cond)) {
1270 // The "PrevBB" is not yet updated to reflect current code layout, so,
1271 // o. it may fall-through to a block without explict "goto" instruction
1272 // before layout, and no longer fall-through it after layout; or
1273 // o. just opposite.
1275 // AnalyzeBranch() may return erroneous value for FBB when these two
1276 // situations take place. For the first scenario FBB is mistakenly set
1277 // NULL; for the 2nd scenario, the FBB, which is expected to be NULL,
1278 // is mistakenly pointing to "*BI".
1280 bool needUpdateBr = true;
1281 if (!Cond.empty() && (!FBB || FBB == ChainBB)) {
1282 PrevBB->updateTerminator();
1283 needUpdateBr = false;
1285 TBB = FBB = nullptr;
1286 if (TII->AnalyzeBranch(*PrevBB, TBB, FBB, Cond)) {
1287 // FIXME: This should never take place.
1288 TBB = FBB = nullptr;
1292 // If PrevBB has a two-way branch, try to re-order the branches
1293 // such that we branch to the successor with higher weight first.
1294 if (TBB && !Cond.empty() && FBB &&
1295 MBPI->getEdgeWeight(PrevBB, FBB) > MBPI->getEdgeWeight(PrevBB, TBB) &&
1296 !TII->ReverseBranchCondition(Cond)) {
1297 DEBUG(dbgs() << "Reverse order of the two branches: "
1298 << getBlockName(PrevBB) << "\n");
1299 DEBUG(dbgs() << " Edge weight: " << MBPI->getEdgeWeight(PrevBB, FBB)
1300 << " vs " << MBPI->getEdgeWeight(PrevBB, TBB) << "\n");
1301 DebugLoc dl; // FIXME: this is nowhere
1302 TII->RemoveBranch(*PrevBB);
1303 TII->InsertBranch(*PrevBB, FBB, TBB, Cond, dl);
1304 needUpdateBr = true;
1307 PrevBB->updateTerminator();
1311 // Fixup the last block.
1313 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
1314 if (!TII->AnalyzeBranch(F.back(), TBB, FBB, Cond))
1315 F.back().updateTerminator();
1317 // Walk through the backedges of the function now that we have fully laid out
1318 // the basic blocks and align the destination of each backedge. We don't rely
1319 // exclusively on the loop info here so that we can align backedges in
1320 // unnatural CFGs and backedges that were introduced purely because of the
1321 // loop rotations done during this layout pass.
1322 // FIXME: Use Function::optForSize().
1323 if (F.getFunction()->hasFnAttribute(Attribute::OptimizeForSize))
1325 if (FunctionChain.begin() == FunctionChain.end())
1326 return; // Empty chain.
1328 const BranchProbability ColdProb(1, 5); // 20%
1329 BlockFrequency EntryFreq = MBFI->getBlockFreq(&F.front());
1330 BlockFrequency WeightedEntryFreq = EntryFreq * ColdProb;
1331 for (MachineBasicBlock *ChainBB : FunctionChain) {
1332 if (ChainBB == *FunctionChain.begin())
1335 // Don't align non-looping basic blocks. These are unlikely to execute
1336 // enough times to matter in practice. Note that we'll still handle
1337 // unnatural CFGs inside of a natural outer loop (the common case) and
1339 MachineLoop *L = MLI->getLoopFor(ChainBB);
1343 unsigned Align = TLI->getPrefLoopAlignment(L);
1345 continue; // Don't care about loop alignment.
1347 // If the block is cold relative to the function entry don't waste space
1349 BlockFrequency Freq = MBFI->getBlockFreq(ChainBB);
1350 if (Freq < WeightedEntryFreq)
1353 // If the block is cold relative to its loop header, don't align it
1354 // regardless of what edges into the block exist.
1355 MachineBasicBlock *LoopHeader = L->getHeader();
1356 BlockFrequency LoopHeaderFreq = MBFI->getBlockFreq(LoopHeader);
1357 if (Freq < (LoopHeaderFreq * ColdProb))
1360 // Check for the existence of a non-layout predecessor which would benefit
1361 // from aligning this block.
1362 MachineBasicBlock *LayoutPred =
1363 &*std::prev(MachineFunction::iterator(ChainBB));
1365 // Force alignment if all the predecessors are jumps. We already checked
1366 // that the block isn't cold above.
1367 if (!LayoutPred->isSuccessor(ChainBB)) {
1368 ChainBB->setAlignment(Align);
1372 // Align this block if the layout predecessor's edge into this block is
1373 // cold relative to the block. When this is true, other predecessors make up
1374 // all of the hot entries into the block and thus alignment is likely to be
1376 BranchProbability LayoutProb =
1377 MBPI->getEdgeProbability(LayoutPred, ChainBB);
1378 BlockFrequency LayoutEdgeFreq = MBFI->getBlockFreq(LayoutPred) * LayoutProb;
1379 if (LayoutEdgeFreq <= (Freq * ColdProb))
1380 ChainBB->setAlignment(Align);
1384 bool MachineBlockPlacement::runOnMachineFunction(MachineFunction &F) {
1385 // Check for single-block functions and skip them.
1386 if (std::next(F.begin()) == F.end())
1389 if (skipOptnoneFunction(*F.getFunction()))
1392 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
1393 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
1394 MLI = &getAnalysis<MachineLoopInfo>();
1395 TII = F.getSubtarget().getInstrInfo();
1396 TLI = F.getSubtarget().getTargetLowering();
1397 MDT = &getAnalysis<MachineDominatorTree>();
1398 assert(BlockToChain.empty());
1402 BlockToChain.clear();
1403 ChainAllocator.DestroyAll();
1406 // Align all of the blocks in the function to a specific alignment.
1407 for (MachineBasicBlock &MBB : F)
1408 MBB.setAlignment(AlignAllBlock);
1410 // We always return true as we have no way to track whether the final order
1411 // differs from the original order.
1416 /// \brief A pass to compute block placement statistics.
1418 /// A separate pass to compute interesting statistics for evaluating block
1419 /// placement. This is separate from the actual placement pass so that they can
1420 /// be computed in the absence of any placement transformations or when using
1421 /// alternative placement strategies.
1422 class MachineBlockPlacementStats : public MachineFunctionPass {
1423 /// \brief A handle to the branch probability pass.
1424 const MachineBranchProbabilityInfo *MBPI;
1426 /// \brief A handle to the function-wide block frequency pass.
1427 const MachineBlockFrequencyInfo *MBFI;
1430 static char ID; // Pass identification, replacement for typeid
1431 MachineBlockPlacementStats() : MachineFunctionPass(ID) {
1432 initializeMachineBlockPlacementStatsPass(*PassRegistry::getPassRegistry());
1435 bool runOnMachineFunction(MachineFunction &F) override;
1437 void getAnalysisUsage(AnalysisUsage &AU) const override {
1438 AU.addRequired<MachineBranchProbabilityInfo>();
1439 AU.addRequired<MachineBlockFrequencyInfo>();
1440 AU.setPreservesAll();
1441 MachineFunctionPass::getAnalysisUsage(AU);
1446 char MachineBlockPlacementStats::ID = 0;
1447 char &llvm::MachineBlockPlacementStatsID = MachineBlockPlacementStats::ID;
1448 INITIALIZE_PASS_BEGIN(MachineBlockPlacementStats, "block-placement-stats",
1449 "Basic Block Placement Stats", false, false)
1450 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
1451 INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
1452 INITIALIZE_PASS_END(MachineBlockPlacementStats, "block-placement-stats",
1453 "Basic Block Placement Stats", false, false)
1455 bool MachineBlockPlacementStats::runOnMachineFunction(MachineFunction &F) {
1456 // Check for single-block functions and skip them.
1457 if (std::next(F.begin()) == F.end())
1460 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
1461 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
1463 for (MachineBasicBlock &MBB : F) {
1464 BlockFrequency BlockFreq = MBFI->getBlockFreq(&MBB);
1465 Statistic &NumBranches =
1466 (MBB.succ_size() > 1) ? NumCondBranches : NumUncondBranches;
1467 Statistic &BranchTakenFreq =
1468 (MBB.succ_size() > 1) ? CondBranchTakenFreq : UncondBranchTakenFreq;
1469 for (MachineBasicBlock *Succ : MBB.successors()) {
1470 // Skip if this successor is a fallthrough.
1471 if (MBB.isLayoutSuccessor(Succ))
1474 BlockFrequency EdgeFreq =
1475 BlockFreq * MBPI->getEdgeProbability(&MBB, Succ);
1477 BranchTakenFreq += EdgeFreq.getFrequency();