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 uncondittional 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);
86 /// \brief Type for our function-wide basic block -> block chain mapping.
87 typedef DenseMap<MachineBasicBlock *, BlockChain *> BlockToChainMapType;
91 /// \brief A chain of blocks which will be laid out contiguously.
93 /// This is the datastructure representing a chain of consecutive blocks that
94 /// are profitable to layout together in order to maximize fallthrough
95 /// probabilities and code locality. We also can use a block chain to represent
96 /// a sequence of basic blocks which have some external (correctness)
97 /// requirement for sequential layout.
99 /// Chains can be built around a single basic block and can be merged to grow
100 /// them. They participate in a block-to-chain mapping, which is updated
101 /// automatically as chains are merged together.
103 /// \brief The sequence of blocks belonging to this chain.
105 /// This is the sequence of blocks for a particular chain. These will be laid
106 /// out in-order within the function.
107 SmallVector<MachineBasicBlock *, 4> Blocks;
109 /// \brief A handle to the function-wide basic block to block chain mapping.
111 /// This is retained in each block chain to simplify the computation of child
112 /// block chains for SCC-formation and iteration. We store the edges to child
113 /// basic blocks, and map them back to their associated chains using this
115 BlockToChainMapType &BlockToChain;
118 /// \brief Construct a new BlockChain.
120 /// This builds a new block chain representing a single basic block in the
121 /// function. It also registers itself as the chain that block participates
122 /// in with the BlockToChain mapping.
123 BlockChain(BlockToChainMapType &BlockToChain, MachineBasicBlock *BB)
124 : Blocks(1, BB), BlockToChain(BlockToChain), LoopPredecessors(0) {
125 assert(BB && "Cannot create a chain with a null basic block");
126 BlockToChain[BB] = this;
129 /// \brief Iterator over blocks within the chain.
130 typedef SmallVectorImpl<MachineBasicBlock *>::iterator iterator;
132 /// \brief Beginning of blocks within the chain.
133 iterator begin() { return Blocks.begin(); }
135 /// \brief End of blocks within the chain.
136 iterator end() { return Blocks.end(); }
138 /// \brief Merge a block chain into this one.
140 /// This routine merges a block chain into this one. It takes care of forming
141 /// a contiguous sequence of basic blocks, updating the edge list, and
142 /// updating the block -> chain mapping. It does not free or tear down the
143 /// old chain, but the old chain's block list is no longer valid.
144 void merge(MachineBasicBlock *BB, BlockChain *Chain) {
146 assert(!Blocks.empty());
148 // Fast path in case we don't have a chain already.
150 assert(!BlockToChain[BB]);
151 Blocks.push_back(BB);
152 BlockToChain[BB] = this;
156 assert(BB == *Chain->begin());
157 assert(Chain->begin() != Chain->end());
159 // Update the incoming blocks to point to this chain, and add them to the
161 for (MachineBasicBlock *ChainBB : *Chain) {
162 Blocks.push_back(ChainBB);
163 assert(BlockToChain[ChainBB] == Chain && "Incoming blocks not in chain");
164 BlockToChain[ChainBB] = this;
169 /// \brief Dump the blocks in this chain.
170 LLVM_DUMP_METHOD void dump() {
171 for (MachineBasicBlock *MBB : *this)
176 /// \brief Count of predecessors within the loop currently being processed.
178 /// This count is updated at each loop we process to represent the number of
179 /// in-loop predecessors of this chain.
180 unsigned LoopPredecessors;
185 class MachineBlockPlacement : public MachineFunctionPass {
186 /// \brief A typedef for a block filter set.
187 typedef SmallPtrSet<MachineBasicBlock *, 16> BlockFilterSet;
189 /// \brief A handle to the branch probability pass.
190 const MachineBranchProbabilityInfo *MBPI;
192 /// \brief A handle to the function-wide block frequency pass.
193 const MachineBlockFrequencyInfo *MBFI;
195 /// \brief A handle to the loop info.
196 const MachineLoopInfo *MLI;
198 /// \brief A handle to the target's instruction info.
199 const TargetInstrInfo *TII;
201 /// \brief A handle to the target's lowering info.
202 const TargetLoweringBase *TLI;
204 /// \brief A handle to the post dominator tree.
205 MachineDominatorTree *MDT;
207 /// \brief A set of blocks that are unavoidably execute, i.e. they dominate
208 /// all terminators of the MachineFunction.
209 SmallPtrSet<MachineBasicBlock *, 4> UnavoidableBlocks;
211 /// \brief Allocator and owner of BlockChain structures.
213 /// We build BlockChains lazily while processing the loop structure of
214 /// a function. To reduce malloc traffic, we allocate them using this
215 /// slab-like allocator, and destroy them after the pass completes. An
216 /// important guarantee is that this allocator produces stable pointers to
218 SpecificBumpPtrAllocator<BlockChain> ChainAllocator;
220 /// \brief Function wide BasicBlock to BlockChain mapping.
222 /// This mapping allows efficiently moving from any given basic block to the
223 /// BlockChain it participates in, if any. We use it to, among other things,
224 /// allow implicitly defining edges between chains as the existing edges
225 /// between basic blocks.
226 DenseMap<MachineBasicBlock *, BlockChain *> BlockToChain;
228 void markChainSuccessors(BlockChain &Chain, MachineBasicBlock *LoopHeaderBB,
229 SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
230 const BlockFilterSet *BlockFilter = nullptr);
231 MachineBasicBlock *selectBestSuccessor(MachineBasicBlock *BB,
233 const BlockFilterSet *BlockFilter);
235 selectBestCandidateBlock(BlockChain &Chain,
236 SmallVectorImpl<MachineBasicBlock *> &WorkList,
237 const BlockFilterSet *BlockFilter);
239 getFirstUnplacedBlock(MachineFunction &F, const BlockChain &PlacedChain,
240 MachineFunction::iterator &PrevUnplacedBlockIt,
241 const BlockFilterSet *BlockFilter);
242 void buildChain(MachineBasicBlock *BB, BlockChain &Chain,
243 SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
244 const BlockFilterSet *BlockFilter = nullptr);
245 MachineBasicBlock *findBestLoopTop(MachineLoop &L,
246 const BlockFilterSet &LoopBlockSet);
247 MachineBasicBlock *findBestLoopExit(MachineFunction &F, MachineLoop &L,
248 const BlockFilterSet &LoopBlockSet);
249 void buildLoopChains(MachineFunction &F, MachineLoop &L);
250 void rotateLoop(BlockChain &LoopChain, MachineBasicBlock *ExitingBB,
251 const BlockFilterSet &LoopBlockSet);
252 void buildCFGChains(MachineFunction &F);
255 static char ID; // Pass identification, replacement for typeid
256 MachineBlockPlacement() : MachineFunctionPass(ID) {
257 initializeMachineBlockPlacementPass(*PassRegistry::getPassRegistry());
260 bool runOnMachineFunction(MachineFunction &F) override;
262 void getAnalysisUsage(AnalysisUsage &AU) const override {
263 AU.addRequired<MachineBranchProbabilityInfo>();
264 AU.addRequired<MachineBlockFrequencyInfo>();
265 AU.addRequired<MachineDominatorTree>();
266 AU.addRequired<MachineLoopInfo>();
267 MachineFunctionPass::getAnalysisUsage(AU);
272 char MachineBlockPlacement::ID = 0;
273 char &llvm::MachineBlockPlacementID = MachineBlockPlacement::ID;
274 INITIALIZE_PASS_BEGIN(MachineBlockPlacement, "block-placement",
275 "Branch Probability Basic Block Placement", false, false)
276 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
277 INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
278 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
279 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
280 INITIALIZE_PASS_END(MachineBlockPlacement, "block-placement",
281 "Branch Probability Basic Block Placement", false, false)
284 /// \brief Helper to print the name of a MBB.
286 /// Only used by debug logging.
287 static std::string getBlockName(MachineBasicBlock *BB) {
289 raw_string_ostream OS(Result);
290 OS << "BB#" << BB->getNumber();
291 OS << " (derived from LLVM BB '" << BB->getName() << "')";
296 /// \brief Helper to print the number of a MBB.
298 /// Only used by debug logging.
299 static std::string getBlockNum(MachineBasicBlock *BB) {
301 raw_string_ostream OS(Result);
302 OS << "BB#" << BB->getNumber();
308 /// \brief Mark a chain's successors as having one fewer preds.
310 /// When a chain is being merged into the "placed" chain, this routine will
311 /// quickly walk the successors of each block in the chain and mark them as
312 /// having one fewer active predecessor. It also adds any successors of this
313 /// chain which reach the zero-predecessor state to the worklist passed in.
314 void MachineBlockPlacement::markChainSuccessors(
315 BlockChain &Chain, MachineBasicBlock *LoopHeaderBB,
316 SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
317 const BlockFilterSet *BlockFilter) {
318 // Walk all the blocks in this chain, marking their successors as having
319 // a predecessor placed.
320 for (MachineBasicBlock *MBB : Chain) {
321 // Add any successors for which this is the only un-placed in-loop
322 // predecessor to the worklist as a viable candidate for CFG-neutral
323 // placement. No subsequent placement of this block will violate the CFG
324 // shape, so we get to use heuristics to choose a favorable placement.
325 for (MachineBasicBlock *Succ : MBB->successors()) {
326 if (BlockFilter && !BlockFilter->count(Succ))
328 BlockChain &SuccChain = *BlockToChain[Succ];
329 // Disregard edges within a fixed chain, or edges to the loop header.
330 if (&Chain == &SuccChain || Succ == LoopHeaderBB)
333 // This is a cross-chain edge that is within the loop, so decrement the
334 // loop predecessor count of the destination chain.
335 if (SuccChain.LoopPredecessors > 0 && --SuccChain.LoopPredecessors == 0)
336 BlockWorkList.push_back(*SuccChain.begin());
341 /// \brief Select the best successor for a block.
343 /// This looks across all successors of a particular block and attempts to
344 /// select the "best" one to be the layout successor. It only considers direct
345 /// successors which also pass the block filter. It will attempt to avoid
346 /// breaking CFG structure, but cave and break such structures in the case of
347 /// very hot successor edges.
349 /// \returns The best successor block found, or null if none are viable.
351 MachineBlockPlacement::selectBestSuccessor(MachineBasicBlock *BB,
353 const BlockFilterSet *BlockFilter) {
354 const BranchProbability HotProb(4, 5); // 80%
356 MachineBasicBlock *BestSucc = nullptr;
357 // FIXME: Due to the performance of the probability and weight routines in
358 // the MBPI analysis, we manually compute probabilities using the edge
359 // weights. This is suboptimal as it means that the somewhat subtle
360 // definition of edge weight semantics is encoded here as well. We should
361 // improve the MBPI interface to efficiently support query patterns such as
363 uint32_t BestWeight = 0;
364 uint32_t SumWeight = MBPI->getSumForBlock(BB);
365 DEBUG(dbgs() << "Attempting merge from: " << getBlockName(BB) << "\n");
366 for (MachineBasicBlock *Succ : BB->successors()) {
367 if (BlockFilter && !BlockFilter->count(Succ))
369 BlockChain &SuccChain = *BlockToChain[Succ];
370 if (&SuccChain == &Chain) {
371 DEBUG(dbgs() << " " << getBlockName(Succ) << " -> Already merged!\n");
374 if (Succ != *SuccChain.begin()) {
375 DEBUG(dbgs() << " " << getBlockName(Succ) << " -> Mid chain!\n");
379 uint32_t SuccWeight = MBPI->getEdgeWeight(BB, Succ);
380 BranchProbability SuccProb(SuccWeight, SumWeight);
382 // If we outline optional branches, look whether Succ is unavoidable, i.e.
383 // dominates all terminators of the MachineFunction. If it does, other
384 // successors must be optional. Don't do this for cold branches.
385 if (OutlineOptionalBranches && SuccProb > HotProb.getCompl() &&
386 UnavoidableBlocks.count(Succ) > 0) {
387 auto HasShortOptionalBranch = [&]() {
388 for (MachineBasicBlock *Pred : Succ->predecessors()) {
389 // Check whether there is an unplaced optional branch.
390 if (Pred == Succ || (BlockFilter && !BlockFilter->count(Pred)) ||
391 BlockToChain[Pred] == &Chain)
393 // Check whether the optional branch has exactly one BB.
394 if (Pred->pred_size() > 1 || *Pred->pred_begin() != BB)
396 // Check whether the optional branch is small.
397 if (Pred->size() < OutlineOptionalThreshold)
402 if (!HasShortOptionalBranch())
406 // Only consider successors which are either "hot", or wouldn't violate
407 // any CFG constraints.
408 if (SuccChain.LoopPredecessors != 0) {
409 if (SuccProb < HotProb) {
410 DEBUG(dbgs() << " " << getBlockName(Succ) << " -> " << SuccProb
411 << " (prob) (CFG conflict)\n");
415 // Make sure that a hot successor doesn't have a globally more
416 // important predecessor.
417 BlockFrequency CandidateEdgeFreq =
418 MBFI->getBlockFreq(BB) * SuccProb * HotProb.getCompl();
419 bool BadCFGConflict = false;
420 for (MachineBasicBlock *Pred : Succ->predecessors()) {
421 if (Pred == Succ || (BlockFilter && !BlockFilter->count(Pred)) ||
422 BlockToChain[Pred] == &Chain)
424 BlockFrequency PredEdgeFreq =
425 MBFI->getBlockFreq(Pred) * MBPI->getEdgeProbability(Pred, Succ);
426 if (PredEdgeFreq >= CandidateEdgeFreq) {
427 BadCFGConflict = true;
431 if (BadCFGConflict) {
432 DEBUG(dbgs() << " " << getBlockName(Succ) << " -> " << SuccProb
433 << " (prob) (non-cold CFG conflict)\n");
438 DEBUG(dbgs() << " " << getBlockName(Succ) << " -> " << SuccProb
440 << (SuccChain.LoopPredecessors != 0 ? " (CFG break)" : "")
442 if (BestSucc && BestWeight >= SuccWeight)
445 BestWeight = SuccWeight;
450 /// \brief Select the best block from a worklist.
452 /// This looks through the provided worklist as a list of candidate basic
453 /// blocks and select the most profitable one to place. The definition of
454 /// profitable only really makes sense in the context of a loop. This returns
455 /// the most frequently visited block in the worklist, which in the case of
456 /// a loop, is the one most desirable to be physically close to the rest of the
457 /// loop body in order to improve icache behavior.
459 /// \returns The best block found, or null if none are viable.
460 MachineBasicBlock *MachineBlockPlacement::selectBestCandidateBlock(
461 BlockChain &Chain, SmallVectorImpl<MachineBasicBlock *> &WorkList,
462 const BlockFilterSet *BlockFilter) {
463 // Once we need to walk the worklist looking for a candidate, cleanup the
464 // worklist of already placed entries.
465 // FIXME: If this shows up on profiles, it could be folded (at the cost of
466 // some code complexity) into the loop below.
467 WorkList.erase(std::remove_if(WorkList.begin(), WorkList.end(),
468 [&](MachineBasicBlock *BB) {
469 return BlockToChain.lookup(BB) == &Chain;
473 MachineBasicBlock *BestBlock = nullptr;
474 BlockFrequency BestFreq;
475 for (MachineBasicBlock *MBB : WorkList) {
476 BlockChain &SuccChain = *BlockToChain[MBB];
477 if (&SuccChain == &Chain) {
478 DEBUG(dbgs() << " " << getBlockName(MBB) << " -> Already merged!\n");
481 assert(SuccChain.LoopPredecessors == 0 && "Found CFG-violating block");
483 BlockFrequency CandidateFreq = MBFI->getBlockFreq(MBB);
484 DEBUG(dbgs() << " " << getBlockName(MBB) << " -> ";
485 MBFI->printBlockFreq(dbgs(), CandidateFreq) << " (freq)\n");
486 if (BestBlock && BestFreq >= CandidateFreq)
489 BestFreq = CandidateFreq;
494 /// \brief Retrieve the first unplaced basic block.
496 /// This routine is called when we are unable to use the CFG to walk through
497 /// all of the basic blocks and form a chain due to unnatural loops in the CFG.
498 /// We walk through the function's blocks in order, starting from the
499 /// LastUnplacedBlockIt. We update this iterator on each call to avoid
500 /// re-scanning the entire sequence on repeated calls to this routine.
501 MachineBasicBlock *MachineBlockPlacement::getFirstUnplacedBlock(
502 MachineFunction &F, const BlockChain &PlacedChain,
503 MachineFunction::iterator &PrevUnplacedBlockIt,
504 const BlockFilterSet *BlockFilter) {
505 for (MachineFunction::iterator I = PrevUnplacedBlockIt, E = F.end(); I != E;
507 if (BlockFilter && !BlockFilter->count(I))
509 if (BlockToChain[I] != &PlacedChain) {
510 PrevUnplacedBlockIt = I;
511 // Now select the head of the chain to which the unplaced block belongs
512 // as the block to place. This will force the entire chain to be placed,
513 // and satisfies the requirements of merging chains.
514 return *BlockToChain[I]->begin();
520 void MachineBlockPlacement::buildChain(
521 MachineBasicBlock *BB, BlockChain &Chain,
522 SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
523 const BlockFilterSet *BlockFilter) {
525 assert(BlockToChain[BB] == &Chain);
526 MachineFunction &F = *BB->getParent();
527 MachineFunction::iterator PrevUnplacedBlockIt = F.begin();
529 MachineBasicBlock *LoopHeaderBB = BB;
530 markChainSuccessors(Chain, LoopHeaderBB, BlockWorkList, BlockFilter);
531 BB = *std::prev(Chain.end());
534 assert(BlockToChain[BB] == &Chain);
535 assert(*std::prev(Chain.end()) == BB);
537 // Look for the best viable successor if there is one to place immediately
539 MachineBasicBlock *BestSucc = selectBestSuccessor(BB, Chain, BlockFilter);
541 // If an immediate successor isn't available, look for the best viable
542 // block among those we've identified as not violating the loop's CFG at
543 // this point. This won't be a fallthrough, but it will increase locality.
545 BestSucc = selectBestCandidateBlock(Chain, BlockWorkList, BlockFilter);
549 getFirstUnplacedBlock(F, Chain, PrevUnplacedBlockIt, BlockFilter);
553 DEBUG(dbgs() << "Unnatural loop CFG detected, forcibly merging the "
554 "layout successor until the CFG reduces\n");
557 // Place this block, updating the datastructures to reflect its placement.
558 BlockChain &SuccChain = *BlockToChain[BestSucc];
559 // Zero out LoopPredecessors for the successor we're about to merge in case
560 // we selected a successor that didn't fit naturally into the CFG.
561 SuccChain.LoopPredecessors = 0;
562 DEBUG(dbgs() << "Merging from " << getBlockNum(BB) << " to "
563 << getBlockNum(BestSucc) << "\n");
564 markChainSuccessors(SuccChain, LoopHeaderBB, BlockWorkList, BlockFilter);
565 Chain.merge(BestSucc, &SuccChain);
566 BB = *std::prev(Chain.end());
569 DEBUG(dbgs() << "Finished forming chain for header block "
570 << getBlockNum(*Chain.begin()) << "\n");
573 /// \brief Find the best loop top block for layout.
575 /// Look for a block which is strictly better than the loop header for laying
576 /// out at the top of the loop. This looks for one and only one pattern:
577 /// a latch block with no conditional exit. This block will cause a conditional
578 /// jump around it or will be the bottom of the loop if we lay it out in place,
579 /// but if it it doesn't end up at the bottom of the loop for any reason,
580 /// rotation alone won't fix it. Because such a block will always result in an
581 /// unconditional jump (for the backedge) rotating it in front of the loop
582 /// header is always profitable.
584 MachineBlockPlacement::findBestLoopTop(MachineLoop &L,
585 const BlockFilterSet &LoopBlockSet) {
586 // Check that the header hasn't been fused with a preheader block due to
587 // crazy branches. If it has, we need to start with the header at the top to
588 // prevent pulling the preheader into the loop body.
589 BlockChain &HeaderChain = *BlockToChain[L.getHeader()];
590 if (!LoopBlockSet.count(*HeaderChain.begin()))
591 return L.getHeader();
593 DEBUG(dbgs() << "Finding best loop top for: " << getBlockName(L.getHeader())
596 BlockFrequency BestPredFreq;
597 MachineBasicBlock *BestPred = nullptr;
598 for (MachineBasicBlock *Pred : L.getHeader()->predecessors()) {
599 if (!LoopBlockSet.count(Pred))
601 DEBUG(dbgs() << " header pred: " << getBlockName(Pred) << ", "
602 << Pred->succ_size() << " successors, ";
603 MBFI->printBlockFreq(dbgs(), Pred) << " freq\n");
604 if (Pred->succ_size() > 1)
607 BlockFrequency PredFreq = MBFI->getBlockFreq(Pred);
608 if (!BestPred || PredFreq > BestPredFreq ||
609 (!(PredFreq < BestPredFreq) &&
610 Pred->isLayoutSuccessor(L.getHeader()))) {
612 BestPredFreq = PredFreq;
616 // If no direct predecessor is fine, just use the loop header.
618 return L.getHeader();
620 // Walk backwards through any straight line of predecessors.
621 while (BestPred->pred_size() == 1 &&
622 (*BestPred->pred_begin())->succ_size() == 1 &&
623 *BestPred->pred_begin() != L.getHeader())
624 BestPred = *BestPred->pred_begin();
626 DEBUG(dbgs() << " final top: " << getBlockName(BestPred) << "\n");
630 /// \brief Find the best loop exiting block for layout.
632 /// This routine implements the logic to analyze the loop looking for the best
633 /// block to layout at the top of the loop. Typically this is done to maximize
634 /// fallthrough opportunities.
636 MachineBlockPlacement::findBestLoopExit(MachineFunction &F, MachineLoop &L,
637 const BlockFilterSet &LoopBlockSet) {
638 // We don't want to layout the loop linearly in all cases. If the loop header
639 // is just a normal basic block in the loop, we want to look for what block
640 // within the loop is the best one to layout at the top. However, if the loop
641 // header has be pre-merged into a chain due to predecessors not having
642 // analyzable branches, *and* the predecessor it is merged with is *not* part
643 // of the loop, rotating the header into the middle of the loop will create
644 // a non-contiguous range of blocks which is Very Bad. So start with the
645 // header and only rotate if safe.
646 BlockChain &HeaderChain = *BlockToChain[L.getHeader()];
647 if (!LoopBlockSet.count(*HeaderChain.begin()))
650 BlockFrequency BestExitEdgeFreq;
651 unsigned BestExitLoopDepth = 0;
652 MachineBasicBlock *ExitingBB = nullptr;
653 // If there are exits to outer loops, loop rotation can severely limit
654 // fallthrough opportunites unless it selects such an exit. Keep a set of
655 // blocks where rotating to exit with that block will reach an outer loop.
656 SmallPtrSet<MachineBasicBlock *, 4> BlocksExitingToOuterLoop;
658 DEBUG(dbgs() << "Finding best loop exit for: " << getBlockName(L.getHeader())
660 for (MachineBasicBlock *MBB : L.getBlocks()) {
661 BlockChain &Chain = *BlockToChain[MBB];
662 // Ensure that this block is at the end of a chain; otherwise it could be
663 // mid-way through an inner loop or a successor of an unanalyzable branch.
664 if (MBB != *std::prev(Chain.end()))
667 // Now walk the successors. We need to establish whether this has a viable
668 // exiting successor and whether it has a viable non-exiting successor.
669 // We store the old exiting state and restore it if a viable looping
670 // successor isn't found.
671 MachineBasicBlock *OldExitingBB = ExitingBB;
672 BlockFrequency OldBestExitEdgeFreq = BestExitEdgeFreq;
673 bool HasLoopingSucc = false;
674 // FIXME: Due to the performance of the probability and weight routines in
675 // the MBPI analysis, we use the internal weights and manually compute the
676 // probabilities to avoid quadratic behavior.
677 uint32_t SumWeight = MBPI->getSumForBlock(MBB);
678 for (MachineBasicBlock *Succ : MBB->successors()) {
679 if (Succ->isLandingPad())
683 BlockChain &SuccChain = *BlockToChain[Succ];
684 // Don't split chains, either this chain or the successor's chain.
685 if (&Chain == &SuccChain) {
686 DEBUG(dbgs() << " exiting: " << getBlockName(MBB) << " -> "
687 << getBlockName(Succ) << " (chain conflict)\n");
691 uint32_t SuccWeight = MBPI->getEdgeWeight(MBB, Succ);
692 if (LoopBlockSet.count(Succ)) {
693 DEBUG(dbgs() << " looping: " << getBlockName(MBB) << " -> "
694 << getBlockName(Succ) << " (" << SuccWeight << ")\n");
695 HasLoopingSucc = true;
699 unsigned SuccLoopDepth = 0;
700 if (MachineLoop *ExitLoop = MLI->getLoopFor(Succ)) {
701 SuccLoopDepth = ExitLoop->getLoopDepth();
702 if (ExitLoop->contains(&L))
703 BlocksExitingToOuterLoop.insert(MBB);
706 BranchProbability SuccProb(SuccWeight, SumWeight);
707 BlockFrequency ExitEdgeFreq = MBFI->getBlockFreq(MBB) * SuccProb;
708 DEBUG(dbgs() << " exiting: " << getBlockName(MBB) << " -> "
709 << getBlockName(Succ) << " [L:" << SuccLoopDepth << "] (";
710 MBFI->printBlockFreq(dbgs(), ExitEdgeFreq) << ")\n");
711 // Note that we bias this toward an existing layout successor to retain
712 // incoming order in the absence of better information. The exit must have
713 // a frequency higher than the current exit before we consider breaking
715 BranchProbability Bias(100 - ExitBlockBias, 100);
716 if (!ExitingBB || SuccLoopDepth > BestExitLoopDepth ||
717 ExitEdgeFreq > BestExitEdgeFreq ||
718 (MBB->isLayoutSuccessor(Succ) &&
719 !(ExitEdgeFreq < BestExitEdgeFreq * Bias))) {
720 BestExitEdgeFreq = ExitEdgeFreq;
725 if (!HasLoopingSucc) {
726 // Restore the old exiting state, no viable looping successor was found.
727 ExitingBB = OldExitingBB;
728 BestExitEdgeFreq = OldBestExitEdgeFreq;
732 // Without a candidate exiting block or with only a single block in the
733 // loop, just use the loop header to layout the loop.
734 if (!ExitingBB || L.getNumBlocks() == 1)
737 // Also, if we have exit blocks which lead to outer loops but didn't select
738 // one of them as the exiting block we are rotating toward, disable loop
739 // rotation altogether.
740 if (!BlocksExitingToOuterLoop.empty() &&
741 !BlocksExitingToOuterLoop.count(ExitingBB))
744 DEBUG(dbgs() << " Best exiting block: " << getBlockName(ExitingBB) << "\n");
748 /// \brief Attempt to rotate an exiting block to the bottom of the loop.
750 /// Once we have built a chain, try to rotate it to line up the hot exit block
751 /// with fallthrough out of the loop if doing so doesn't introduce unnecessary
752 /// branches. For example, if the loop has fallthrough into its header and out
753 /// of its bottom already, don't rotate it.
754 void MachineBlockPlacement::rotateLoop(BlockChain &LoopChain,
755 MachineBasicBlock *ExitingBB,
756 const BlockFilterSet &LoopBlockSet) {
760 MachineBasicBlock *Top = *LoopChain.begin();
761 bool ViableTopFallthrough = false;
762 for (MachineBasicBlock *Pred : Top->predecessors()) {
763 BlockChain *PredChain = BlockToChain[Pred];
764 if (!LoopBlockSet.count(Pred) &&
765 (!PredChain || Pred == *std::prev(PredChain->end()))) {
766 ViableTopFallthrough = true;
771 // If the header has viable fallthrough, check whether the current loop
772 // bottom is a viable exiting block. If so, bail out as rotating will
773 // introduce an unnecessary branch.
774 if (ViableTopFallthrough) {
775 MachineBasicBlock *Bottom = *std::prev(LoopChain.end());
776 for (MachineBasicBlock *Succ : Bottom->successors()) {
777 BlockChain *SuccChain = BlockToChain[Succ];
778 if (!LoopBlockSet.count(Succ) &&
779 (!SuccChain || Succ == *SuccChain->begin()))
784 BlockChain::iterator ExitIt =
785 std::find(LoopChain.begin(), LoopChain.end(), ExitingBB);
786 if (ExitIt == LoopChain.end())
789 std::rotate(LoopChain.begin(), std::next(ExitIt), LoopChain.end());
792 /// \brief Forms basic block chains from the natural loop structures.
794 /// These chains are designed to preserve the existing *structure* of the code
795 /// as much as possible. We can then stitch the chains together in a way which
796 /// both preserves the topological structure and minimizes taken conditional
798 void MachineBlockPlacement::buildLoopChains(MachineFunction &F,
800 // First recurse through any nested loops, building chains for those inner
802 for (MachineLoop *InnerLoop : L)
803 buildLoopChains(F, *InnerLoop);
805 SmallVector<MachineBasicBlock *, 16> BlockWorkList;
806 BlockFilterSet LoopBlockSet(L.block_begin(), L.block_end());
808 // First check to see if there is an obviously preferable top block for the
809 // loop. This will default to the header, but may end up as one of the
810 // predecessors to the header if there is one which will result in strictly
811 // fewer branches in the loop body.
812 MachineBasicBlock *LoopTop = findBestLoopTop(L, LoopBlockSet);
814 // If we selected just the header for the loop top, look for a potentially
815 // profitable exit block in the event that rotating the loop can eliminate
816 // branches by placing an exit edge at the bottom.
817 MachineBasicBlock *ExitingBB = nullptr;
818 if (LoopTop == L.getHeader())
819 ExitingBB = findBestLoopExit(F, L, LoopBlockSet);
821 BlockChain &LoopChain = *BlockToChain[LoopTop];
823 // FIXME: This is a really lame way of walking the chains in the loop: we
824 // walk the blocks, and use a set to prevent visiting a particular chain
826 SmallPtrSet<BlockChain *, 4> UpdatedPreds;
827 assert(LoopChain.LoopPredecessors == 0);
828 UpdatedPreds.insert(&LoopChain);
829 for (MachineBasicBlock *LoopBB : L.getBlocks()) {
830 BlockChain &Chain = *BlockToChain[LoopBB];
831 if (!UpdatedPreds.insert(&Chain).second)
834 assert(Chain.LoopPredecessors == 0);
835 for (MachineBasicBlock *ChainBB : Chain) {
836 assert(BlockToChain[ChainBB] == &Chain);
837 for (MachineBasicBlock *Pred : ChainBB->predecessors()) {
838 if (BlockToChain[Pred] == &Chain || !LoopBlockSet.count(Pred))
840 ++Chain.LoopPredecessors;
844 if (Chain.LoopPredecessors == 0)
845 BlockWorkList.push_back(*Chain.begin());
848 buildChain(LoopTop, LoopChain, BlockWorkList, &LoopBlockSet);
849 rotateLoop(LoopChain, ExitingBB, LoopBlockSet);
852 // Crash at the end so we get all of the debugging output first.
853 bool BadLoop = false;
854 if (LoopChain.LoopPredecessors) {
856 dbgs() << "Loop chain contains a block without its preds placed!\n"
857 << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
858 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n";
860 for (MachineBasicBlock *ChainBB : LoopChain) {
861 dbgs() << " ... " << getBlockName(ChainBB) << "\n";
862 if (!LoopBlockSet.erase(ChainBB)) {
863 // We don't mark the loop as bad here because there are real situations
864 // where this can occur. For example, with an unanalyzable fallthrough
865 // from a loop block to a non-loop block or vice versa.
866 dbgs() << "Loop chain contains a block not contained by the loop!\n"
867 << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
868 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
869 << " Bad block: " << getBlockName(ChainBB) << "\n";
873 if (!LoopBlockSet.empty()) {
875 for (MachineBasicBlock *LoopBB : LoopBlockSet)
876 dbgs() << "Loop contains blocks never placed into a chain!\n"
877 << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
878 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
879 << " Bad block: " << getBlockName(LoopBB) << "\n";
881 assert(!BadLoop && "Detected problems with the placement of this loop.");
885 void MachineBlockPlacement::buildCFGChains(MachineFunction &F) {
886 // Ensure that every BB in the function has an associated chain to simplify
887 // the assumptions of the remaining algorithm.
888 SmallVector<MachineOperand, 4> Cond; // For AnalyzeBranch.
889 for (MachineFunction::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
890 MachineBasicBlock *BB = FI;
892 new (ChainAllocator.Allocate()) BlockChain(BlockToChain, BB);
893 // Also, merge any blocks which we cannot reason about and must preserve
894 // the exact fallthrough behavior for.
897 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
898 if (!TII->AnalyzeBranch(*BB, TBB, FBB, Cond) || !FI->canFallThrough())
901 MachineFunction::iterator NextFI(std::next(FI));
902 MachineBasicBlock *NextBB = NextFI;
903 // Ensure that the layout successor is a viable block, as we know that
904 // fallthrough is a possibility.
905 assert(NextFI != FE && "Can't fallthrough past the last block.");
906 DEBUG(dbgs() << "Pre-merging due to unanalyzable fallthrough: "
907 << getBlockName(BB) << " -> " << getBlockName(NextBB)
909 Chain->merge(NextBB, nullptr);
915 if (OutlineOptionalBranches) {
916 // Find the nearest common dominator of all of F's terminators.
917 MachineBasicBlock *Terminator = nullptr;
918 for (MachineBasicBlock &MBB : F) {
919 if (MBB.succ_size() == 0) {
920 if (Terminator == nullptr)
923 Terminator = MDT->findNearestCommonDominator(Terminator, &MBB);
927 // MBBs dominating this common dominator are unavoidable.
928 UnavoidableBlocks.clear();
929 for (MachineBasicBlock &MBB : F) {
930 if (MDT->dominates(&MBB, Terminator)) {
931 UnavoidableBlocks.insert(&MBB);
936 // Build any loop-based chains.
937 for (MachineLoop *L : *MLI)
938 buildLoopChains(F, *L);
940 SmallVector<MachineBasicBlock *, 16> BlockWorkList;
942 SmallPtrSet<BlockChain *, 4> UpdatedPreds;
943 for (MachineBasicBlock &MBB : F) {
944 BlockChain &Chain = *BlockToChain[&MBB];
945 if (!UpdatedPreds.insert(&Chain).second)
948 assert(Chain.LoopPredecessors == 0);
949 for (MachineBasicBlock *ChainBB : Chain) {
950 assert(BlockToChain[ChainBB] == &Chain);
951 for (MachineBasicBlock *Pred : ChainBB->predecessors()) {
952 if (BlockToChain[Pred] == &Chain)
954 ++Chain.LoopPredecessors;
958 if (Chain.LoopPredecessors == 0)
959 BlockWorkList.push_back(*Chain.begin());
962 BlockChain &FunctionChain = *BlockToChain[&F.front()];
963 buildChain(&F.front(), FunctionChain, BlockWorkList);
966 typedef SmallPtrSet<MachineBasicBlock *, 16> FunctionBlockSetType;
969 // Crash at the end so we get all of the debugging output first.
970 bool BadFunc = false;
971 FunctionBlockSetType FunctionBlockSet;
972 for (MachineBasicBlock &MBB : F)
973 FunctionBlockSet.insert(&MBB);
975 for (MachineBasicBlock *ChainBB : FunctionChain)
976 if (!FunctionBlockSet.erase(ChainBB)) {
978 dbgs() << "Function chain contains a block not in the function!\n"
979 << " Bad block: " << getBlockName(ChainBB) << "\n";
982 if (!FunctionBlockSet.empty()) {
984 for (MachineBasicBlock *RemainingBB : FunctionBlockSet)
985 dbgs() << "Function contains blocks never placed into a chain!\n"
986 << " Bad block: " << getBlockName(RemainingBB) << "\n";
988 assert(!BadFunc && "Detected problems with the block placement.");
991 // Splice the blocks into place.
992 MachineFunction::iterator InsertPos = F.begin();
993 for (MachineBasicBlock *ChainBB : FunctionChain) {
994 DEBUG(dbgs() << (ChainBB == *FunctionChain.begin() ? "Placing chain "
996 << getBlockName(ChainBB) << "\n");
997 if (InsertPos != MachineFunction::iterator(ChainBB))
998 F.splice(InsertPos, ChainBB);
1002 // Update the terminator of the previous block.
1003 if (ChainBB == *FunctionChain.begin())
1005 MachineBasicBlock *PrevBB = std::prev(MachineFunction::iterator(ChainBB));
1007 // FIXME: It would be awesome of updateTerminator would just return rather
1008 // than assert when the branch cannot be analyzed in order to remove this
1011 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
1012 if (!TII->AnalyzeBranch(*PrevBB, TBB, FBB, Cond)) {
1013 // The "PrevBB" is not yet updated to reflect current code layout, so,
1014 // o. it may fall-through to a block without explict "goto" instruction
1015 // before layout, and no longer fall-through it after layout; or
1016 // o. just opposite.
1018 // AnalyzeBranch() may return erroneous value for FBB when these two
1019 // situations take place. For the first scenario FBB is mistakenly set
1020 // NULL; for the 2nd scenario, the FBB, which is expected to be NULL,
1021 // is mistakenly pointing to "*BI".
1023 bool needUpdateBr = true;
1024 if (!Cond.empty() && (!FBB || FBB == ChainBB)) {
1025 PrevBB->updateTerminator();
1026 needUpdateBr = false;
1028 TBB = FBB = nullptr;
1029 if (TII->AnalyzeBranch(*PrevBB, TBB, FBB, Cond)) {
1030 // FIXME: This should never take place.
1031 TBB = FBB = nullptr;
1035 // If PrevBB has a two-way branch, try to re-order the branches
1036 // such that we branch to the successor with higher weight first.
1037 if (TBB && !Cond.empty() && FBB &&
1038 MBPI->getEdgeWeight(PrevBB, FBB) > MBPI->getEdgeWeight(PrevBB, TBB) &&
1039 !TII->ReverseBranchCondition(Cond)) {
1040 DEBUG(dbgs() << "Reverse order of the two branches: "
1041 << getBlockName(PrevBB) << "\n");
1042 DEBUG(dbgs() << " Edge weight: " << MBPI->getEdgeWeight(PrevBB, FBB)
1043 << " vs " << MBPI->getEdgeWeight(PrevBB, TBB) << "\n");
1044 DebugLoc dl; // FIXME: this is nowhere
1045 TII->RemoveBranch(*PrevBB);
1046 TII->InsertBranch(*PrevBB, FBB, TBB, Cond, dl);
1047 needUpdateBr = true;
1050 PrevBB->updateTerminator();
1054 // Fixup the last block.
1056 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
1057 if (!TII->AnalyzeBranch(F.back(), TBB, FBB, Cond))
1058 F.back().updateTerminator();
1060 // Walk through the backedges of the function now that we have fully laid out
1061 // the basic blocks and align the destination of each backedge. We don't rely
1062 // exclusively on the loop info here so that we can align backedges in
1063 // unnatural CFGs and backedges that were introduced purely because of the
1064 // loop rotations done during this layout pass.
1065 // FIXME: Use Function::optForSize().
1066 if (F.getFunction()->hasFnAttribute(Attribute::OptimizeForSize))
1068 if (FunctionChain.begin() == FunctionChain.end())
1069 return; // Empty chain.
1071 const BranchProbability ColdProb(1, 5); // 20%
1072 BlockFrequency EntryFreq = MBFI->getBlockFreq(F.begin());
1073 BlockFrequency WeightedEntryFreq = EntryFreq * ColdProb;
1074 for (MachineBasicBlock *ChainBB : FunctionChain) {
1075 if (ChainBB == *FunctionChain.begin())
1078 // Don't align non-looping basic blocks. These are unlikely to execute
1079 // enough times to matter in practice. Note that we'll still handle
1080 // unnatural CFGs inside of a natural outer loop (the common case) and
1082 MachineLoop *L = MLI->getLoopFor(ChainBB);
1086 unsigned Align = TLI->getPrefLoopAlignment(L);
1088 continue; // Don't care about loop alignment.
1090 // If the block is cold relative to the function entry don't waste space
1092 BlockFrequency Freq = MBFI->getBlockFreq(ChainBB);
1093 if (Freq < WeightedEntryFreq)
1096 // If the block is cold relative to its loop header, don't align it
1097 // regardless of what edges into the block exist.
1098 MachineBasicBlock *LoopHeader = L->getHeader();
1099 BlockFrequency LoopHeaderFreq = MBFI->getBlockFreq(LoopHeader);
1100 if (Freq < (LoopHeaderFreq * ColdProb))
1103 // Check for the existence of a non-layout predecessor which would benefit
1104 // from aligning this block.
1105 MachineBasicBlock *LayoutPred =
1106 &*std::prev(MachineFunction::iterator(ChainBB));
1108 // Force alignment if all the predecessors are jumps. We already checked
1109 // that the block isn't cold above.
1110 if (!LayoutPred->isSuccessor(ChainBB)) {
1111 ChainBB->setAlignment(Align);
1115 // Align this block if the layout predecessor's edge into this block is
1116 // cold relative to the block. When this is true, other predecessors make up
1117 // all of the hot entries into the block and thus alignment is likely to be
1119 BranchProbability LayoutProb =
1120 MBPI->getEdgeProbability(LayoutPred, ChainBB);
1121 BlockFrequency LayoutEdgeFreq = MBFI->getBlockFreq(LayoutPred) * LayoutProb;
1122 if (LayoutEdgeFreq <= (Freq * ColdProb))
1123 ChainBB->setAlignment(Align);
1127 bool MachineBlockPlacement::runOnMachineFunction(MachineFunction &F) {
1128 // Check for single-block functions and skip them.
1129 if (std::next(F.begin()) == F.end())
1132 if (skipOptnoneFunction(*F.getFunction()))
1135 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
1136 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
1137 MLI = &getAnalysis<MachineLoopInfo>();
1138 TII = F.getSubtarget().getInstrInfo();
1139 TLI = F.getSubtarget().getTargetLowering();
1140 MDT = &getAnalysis<MachineDominatorTree>();
1141 assert(BlockToChain.empty());
1145 BlockToChain.clear();
1146 ChainAllocator.DestroyAll();
1149 // Align all of the blocks in the function to a specific alignment.
1150 for (MachineBasicBlock &MBB : F)
1151 MBB.setAlignment(AlignAllBlock);
1153 // We always return true as we have no way to track whether the final order
1154 // differs from the original order.
1159 /// \brief A pass to compute block placement statistics.
1161 /// A separate pass to compute interesting statistics for evaluating block
1162 /// placement. This is separate from the actual placement pass so that they can
1163 /// be computed in the absence of any placement transformations or when using
1164 /// alternative placement strategies.
1165 class MachineBlockPlacementStats : public MachineFunctionPass {
1166 /// \brief A handle to the branch probability pass.
1167 const MachineBranchProbabilityInfo *MBPI;
1169 /// \brief A handle to the function-wide block frequency pass.
1170 const MachineBlockFrequencyInfo *MBFI;
1173 static char ID; // Pass identification, replacement for typeid
1174 MachineBlockPlacementStats() : MachineFunctionPass(ID) {
1175 initializeMachineBlockPlacementStatsPass(*PassRegistry::getPassRegistry());
1178 bool runOnMachineFunction(MachineFunction &F) override;
1180 void getAnalysisUsage(AnalysisUsage &AU) const override {
1181 AU.addRequired<MachineBranchProbabilityInfo>();
1182 AU.addRequired<MachineBlockFrequencyInfo>();
1183 AU.setPreservesAll();
1184 MachineFunctionPass::getAnalysisUsage(AU);
1189 char MachineBlockPlacementStats::ID = 0;
1190 char &llvm::MachineBlockPlacementStatsID = MachineBlockPlacementStats::ID;
1191 INITIALIZE_PASS_BEGIN(MachineBlockPlacementStats, "block-placement-stats",
1192 "Basic Block Placement Stats", false, false)
1193 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
1194 INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
1195 INITIALIZE_PASS_END(MachineBlockPlacementStats, "block-placement-stats",
1196 "Basic Block Placement Stats", false, false)
1198 bool MachineBlockPlacementStats::runOnMachineFunction(MachineFunction &F) {
1199 // Check for single-block functions and skip them.
1200 if (std::next(F.begin()) == F.end())
1203 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
1204 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
1206 for (MachineBasicBlock &MBB : F) {
1207 BlockFrequency BlockFreq = MBFI->getBlockFreq(&MBB);
1208 Statistic &NumBranches =
1209 (MBB.succ_size() > 1) ? NumCondBranches : NumUncondBranches;
1210 Statistic &BranchTakenFreq =
1211 (MBB.succ_size() > 1) ? CondBranchTakenFreq : UncondBranchTakenFreq;
1212 for (MachineBasicBlock *Succ : MBB.successors()) {
1213 // Skip if this successor is a fallthrough.
1214 if (MBB.isLayoutSuccessor(Succ))
1217 BlockFrequency EdgeFreq =
1218 BlockFreq * MBPI->getEdgeProbability(&MBB, Succ);
1220 BranchTakenFreq += EdgeFreq.getFrequency();