xref: /llvm-project/llvm/lib/CodeGen/MachineBlockPlacement.cpp (revision fd3f645f9de1ac0461577c872162f5977abcc329)
1 //===-- MachineBlockPlacement.cpp - Basic Block Code Layout optimization --===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements basic block placement transformations using the CFG
11 // structure and branch probability estimates.
12 //
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.
18 //
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
24 // function in-order.
25 //
26 //===----------------------------------------------------------------------===//
27 
28 #include "llvm/CodeGen/Passes.h"
29 #include "llvm/CodeGen/TargetPassConfig.h"
30 #include "BranchFolding.h"
31 #include "llvm/ADT/DenseMap.h"
32 #include "llvm/ADT/SmallPtrSet.h"
33 #include "llvm/ADT/SmallVector.h"
34 #include "llvm/ADT/Statistic.h"
35 #include "llvm/Analysis/BlockFrequencyInfoImpl.h"
36 #include "llvm/CodeGen/MachineBasicBlock.h"
37 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
38 #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
39 #include "llvm/CodeGen/MachineDominators.h"
40 #include "llvm/CodeGen/MachineFunction.h"
41 #include "llvm/CodeGen/MachineFunctionPass.h"
42 #include "llvm/CodeGen/MachineLoopInfo.h"
43 #include "llvm/CodeGen/MachineModuleInfo.h"
44 #include "llvm/CodeGen/TailDuplicator.h"
45 #include "llvm/Support/Allocator.h"
46 #include "llvm/Support/CommandLine.h"
47 #include "llvm/Support/Debug.h"
48 #include "llvm/Support/raw_ostream.h"
49 #include "llvm/Target/TargetInstrInfo.h"
50 #include "llvm/Target/TargetLowering.h"
51 #include "llvm/Target/TargetSubtargetInfo.h"
52 #include <algorithm>
53 using namespace llvm;
54 
55 #define DEBUG_TYPE "block-placement"
56 
57 STATISTIC(NumCondBranches, "Number of conditional branches");
58 STATISTIC(NumUncondBranches, "Number of unconditional branches");
59 STATISTIC(CondBranchTakenFreq,
60           "Potential frequency of taking conditional branches");
61 STATISTIC(UncondBranchTakenFreq,
62           "Potential frequency of taking unconditional branches");
63 
64 static cl::opt<unsigned> AlignAllBlock("align-all-blocks",
65                                        cl::desc("Force the alignment of all "
66                                                 "blocks in the function."),
67                                        cl::init(0), cl::Hidden);
68 
69 static cl::opt<unsigned> AlignAllNonFallThruBlocks(
70     "align-all-nofallthru-blocks",
71     cl::desc("Force the alignment of all "
72              "blocks that have no fall-through predecessors (i.e. don't add "
73              "nops that are executed)."),
74     cl::init(0), cl::Hidden);
75 
76 // FIXME: Find a good default for this flag and remove the flag.
77 static cl::opt<unsigned> ExitBlockBias(
78     "block-placement-exit-block-bias",
79     cl::desc("Block frequency percentage a loop exit block needs "
80              "over the original exit to be considered the new exit."),
81     cl::init(0), cl::Hidden);
82 
83 // Definition:
84 // - Outlining: placement of a basic block outside the chain or hot path.
85 
86 static cl::opt<bool> OutlineOptionalBranches(
87     "outline-optional-branches",
88     cl::desc("Outlining optional branches will place blocks that are optional "
89               "branches, i.e. branches with a common post dominator, outside "
90               "the hot path or chain"),
91     cl::init(false), cl::Hidden);
92 
93 static cl::opt<unsigned> OutlineOptionalThreshold(
94     "outline-optional-threshold",
95     cl::desc("Don't outline optional branches that are a single block with an "
96              "instruction count below this threshold"),
97     cl::init(4), cl::Hidden);
98 
99 static cl::opt<unsigned> LoopToColdBlockRatio(
100     "loop-to-cold-block-ratio",
101     cl::desc("Outline loop blocks from loop chain if (frequency of loop) / "
102              "(frequency of block) is greater than this ratio"),
103     cl::init(5), cl::Hidden);
104 
105 static cl::opt<bool>
106     PreciseRotationCost("precise-rotation-cost",
107                         cl::desc("Model the cost of loop rotation more "
108                                  "precisely by using profile data."),
109                         cl::init(false), cl::Hidden);
110 static cl::opt<bool>
111     ForcePreciseRotationCost("force-precise-rotation-cost",
112                              cl::desc("Force the use of precise cost "
113                                       "loop rotation strategy."),
114                              cl::init(false), cl::Hidden);
115 
116 static cl::opt<unsigned> MisfetchCost(
117     "misfetch-cost",
118     cl::desc("Cost that models the probabilistic risk of an instruction "
119              "misfetch due to a jump comparing to falling through, whose cost "
120              "is zero."),
121     cl::init(1), cl::Hidden);
122 
123 static cl::opt<unsigned> JumpInstCost("jump-inst-cost",
124                                       cl::desc("Cost of jump instructions."),
125                                       cl::init(1), cl::Hidden);
126 static cl::opt<bool>
127 TailDupPlacement("tail-dup-placement",
128               cl::desc("Perform tail duplication during placement. "
129                        "Creates more fallthrough opportunites in "
130                        "outline branches."),
131               cl::init(true), cl::Hidden);
132 
133 static cl::opt<bool>
134 BranchFoldPlacement("branch-fold-placement",
135               cl::desc("Perform branch folding during placement. "
136                        "Reduces code size."),
137               cl::init(true), cl::Hidden);
138 
139 // Heuristic for tail duplication.
140 static cl::opt<unsigned> TailDuplicatePlacementThreshold(
141     "tail-dup-placement-threshold",
142     cl::desc("Instruction cutoff for tail duplication during layout. "
143              "Tail merging during layout is forced to have a threshold "
144              "that won't conflict."), cl::init(2),
145     cl::Hidden);
146 
147 extern cl::opt<unsigned> StaticLikelyProb;
148 extern cl::opt<unsigned> ProfileLikelyProb;
149 
150 #ifndef NDEBUG
151 extern cl::opt<GVDAGType> ViewBlockLayoutWithBFI;
152 extern cl::opt<std::string> ViewBlockFreqFuncName;
153 #endif
154 
155 namespace {
156 class BlockChain;
157 /// \brief Type for our function-wide basic block -> block chain mapping.
158 typedef DenseMap<MachineBasicBlock *, BlockChain *> BlockToChainMapType;
159 }
160 
161 namespace {
162 /// \brief A chain of blocks which will be laid out contiguously.
163 ///
164 /// This is the datastructure representing a chain of consecutive blocks that
165 /// are profitable to layout together in order to maximize fallthrough
166 /// probabilities and code locality. We also can use a block chain to represent
167 /// a sequence of basic blocks which have some external (correctness)
168 /// requirement for sequential layout.
169 ///
170 /// Chains can be built around a single basic block and can be merged to grow
171 /// them. They participate in a block-to-chain mapping, which is updated
172 /// automatically as chains are merged together.
173 class BlockChain {
174   /// \brief The sequence of blocks belonging to this chain.
175   ///
176   /// This is the sequence of blocks for a particular chain. These will be laid
177   /// out in-order within the function.
178   SmallVector<MachineBasicBlock *, 4> Blocks;
179 
180   /// \brief A handle to the function-wide basic block to block chain mapping.
181   ///
182   /// This is retained in each block chain to simplify the computation of child
183   /// block chains for SCC-formation and iteration. We store the edges to child
184   /// basic blocks, and map them back to their associated chains using this
185   /// structure.
186   BlockToChainMapType &BlockToChain;
187 
188 public:
189   /// \brief Construct a new BlockChain.
190   ///
191   /// This builds a new block chain representing a single basic block in the
192   /// function. It also registers itself as the chain that block participates
193   /// in with the BlockToChain mapping.
194   BlockChain(BlockToChainMapType &BlockToChain, MachineBasicBlock *BB)
195       : Blocks(1, BB), BlockToChain(BlockToChain), UnscheduledPredecessors(0) {
196     assert(BB && "Cannot create a chain with a null basic block");
197     BlockToChain[BB] = this;
198   }
199 
200   /// \brief Iterator over blocks within the chain.
201   typedef SmallVectorImpl<MachineBasicBlock *>::iterator iterator;
202 
203   /// \brief Beginning of blocks within the chain.
204   iterator begin() { return Blocks.begin(); }
205 
206   /// \brief End of blocks within the chain.
207   iterator end() { return Blocks.end(); }
208 
209   bool remove(MachineBasicBlock* BB) {
210     for(iterator i = begin(); i != end(); ++i) {
211       if (*i == BB) {
212         Blocks.erase(i);
213         return true;
214       }
215     }
216     return false;
217   }
218 
219   /// \brief Merge a block chain into this one.
220   ///
221   /// This routine merges a block chain into this one. It takes care of forming
222   /// a contiguous sequence of basic blocks, updating the edge list, and
223   /// updating the block -> chain mapping. It does not free or tear down the
224   /// old chain, but the old chain's block list is no longer valid.
225   void merge(MachineBasicBlock *BB, BlockChain *Chain) {
226     assert(BB);
227     assert(!Blocks.empty());
228 
229     // Fast path in case we don't have a chain already.
230     if (!Chain) {
231       assert(!BlockToChain[BB]);
232       Blocks.push_back(BB);
233       BlockToChain[BB] = this;
234       return;
235     }
236 
237     assert(BB == *Chain->begin());
238     assert(Chain->begin() != Chain->end());
239 
240     // Update the incoming blocks to point to this chain, and add them to the
241     // chain structure.
242     for (MachineBasicBlock *ChainBB : *Chain) {
243       Blocks.push_back(ChainBB);
244       assert(BlockToChain[ChainBB] == Chain && "Incoming blocks not in chain");
245       BlockToChain[ChainBB] = this;
246     }
247   }
248 
249 #ifndef NDEBUG
250   /// \brief Dump the blocks in this chain.
251   LLVM_DUMP_METHOD void dump() {
252     for (MachineBasicBlock *MBB : *this)
253       MBB->dump();
254   }
255 #endif // NDEBUG
256 
257   /// \brief Count of predecessors of any block within the chain which have not
258   /// yet been scheduled.  In general, we will delay scheduling this chain
259   /// until those predecessors are scheduled (or we find a sufficiently good
260   /// reason to override this heuristic.)  Note that when forming loop chains,
261   /// blocks outside the loop are ignored and treated as if they were already
262   /// scheduled.
263   ///
264   /// Note: This field is reinitialized multiple times - once for each loop,
265   /// and then once for the function as a whole.
266   unsigned UnscheduledPredecessors;
267 };
268 }
269 
270 namespace {
271 class MachineBlockPlacement : public MachineFunctionPass {
272   /// \brief A typedef for a block filter set.
273   typedef SmallSetVector<MachineBasicBlock *, 16> BlockFilterSet;
274 
275   /// \brief work lists of blocks that are ready to be laid out
276   SmallVector<MachineBasicBlock *, 16> BlockWorkList;
277   SmallVector<MachineBasicBlock *, 16> EHPadWorkList;
278 
279   /// \brief Machine Function
280   MachineFunction *F;
281 
282   /// \brief A handle to the branch probability pass.
283   const MachineBranchProbabilityInfo *MBPI;
284 
285   /// \brief A handle to the function-wide block frequency pass.
286   std::unique_ptr<BranchFolder::MBFIWrapper> MBFI;
287 
288   /// \brief A handle to the loop info.
289   MachineLoopInfo *MLI;
290 
291   /// \brief Preferred loop exit.
292   /// Member variable for convenience. It may be removed by duplication deep
293   /// in the call stack.
294   MachineBasicBlock *PreferredLoopExit;
295 
296   /// \brief A handle to the target's instruction info.
297   const TargetInstrInfo *TII;
298 
299   /// \brief A handle to the target's lowering info.
300   const TargetLoweringBase *TLI;
301 
302   /// \brief A handle to the post dominator tree.
303   MachineDominatorTree *MDT;
304 
305   /// \brief Duplicator used to duplicate tails during placement.
306   ///
307   /// Placement decisions can open up new tail duplication opportunities, but
308   /// since tail duplication affects placement decisions of later blocks, it
309   /// must be done inline.
310   TailDuplicator TailDup;
311 
312   /// \brief A set of blocks that are unavoidably execute, i.e. they dominate
313   /// all terminators of the MachineFunction.
314   SmallPtrSet<MachineBasicBlock *, 4> UnavoidableBlocks;
315 
316   /// \brief Allocator and owner of BlockChain structures.
317   ///
318   /// We build BlockChains lazily while processing the loop structure of
319   /// a function. To reduce malloc traffic, we allocate them using this
320   /// slab-like allocator, and destroy them after the pass completes. An
321   /// important guarantee is that this allocator produces stable pointers to
322   /// the chains.
323   SpecificBumpPtrAllocator<BlockChain> ChainAllocator;
324 
325   /// \brief Function wide BasicBlock to BlockChain mapping.
326   ///
327   /// This mapping allows efficiently moving from any given basic block to the
328   /// BlockChain it participates in, if any. We use it to, among other things,
329   /// allow implicitly defining edges between chains as the existing edges
330   /// between basic blocks.
331   DenseMap<MachineBasicBlock *, BlockChain *> BlockToChain;
332 
333 #ifndef NDEBUG
334   /// The set of basic blocks that have terminators that cannot be fully
335   /// analyzed.  These basic blocks cannot be re-ordered safely by
336   /// MachineBlockPlacement, and we must preserve physical layout of these
337   /// blocks and their successors through the pass.
338   SmallPtrSet<MachineBasicBlock *, 4> BlocksWithUnanalyzableExits;
339 #endif
340 
341   /// Decrease the UnscheduledPredecessors count for all blocks in chain, and
342   /// if the count goes to 0, add them to the appropriate work list.
343   void markChainSuccessors(BlockChain &Chain, MachineBasicBlock *LoopHeaderBB,
344                            const BlockFilterSet *BlockFilter = nullptr);
345 
346   /// Decrease the UnscheduledPredecessors count for a single block, and
347   /// if the count goes to 0, add them to the appropriate work list.
348   void markBlockSuccessors(
349       BlockChain &Chain, MachineBasicBlock *BB, MachineBasicBlock *LoopHeaderBB,
350       const BlockFilterSet *BlockFilter = nullptr);
351 
352 
353   BranchProbability
354   collectViableSuccessors(MachineBasicBlock *BB, BlockChain &Chain,
355                           const BlockFilterSet *BlockFilter,
356                           SmallVector<MachineBasicBlock *, 4> &Successors);
357   bool shouldPredBlockBeOutlined(MachineBasicBlock *BB, MachineBasicBlock *Succ,
358                                  BlockChain &Chain,
359                                  const BlockFilterSet *BlockFilter,
360                                  BranchProbability SuccProb,
361                                  BranchProbability HotProb);
362   bool repeatedlyTailDuplicateBlock(
363       MachineBasicBlock *BB, MachineBasicBlock *&LPred,
364       MachineBasicBlock *LoopHeaderBB,
365       BlockChain &Chain, BlockFilterSet *BlockFilter,
366       MachineFunction::iterator &PrevUnplacedBlockIt);
367   bool maybeTailDuplicateBlock(MachineBasicBlock *BB, MachineBasicBlock *LPred,
368                                const BlockChain &Chain,
369                                BlockFilterSet *BlockFilter,
370                                MachineFunction::iterator &PrevUnplacedBlockIt,
371                                bool &DuplicatedToPred);
372   bool
373   hasBetterLayoutPredecessor(MachineBasicBlock *BB, MachineBasicBlock *Succ,
374                              BlockChain &SuccChain, BranchProbability SuccProb,
375                              BranchProbability RealSuccProb, BlockChain &Chain,
376                              const BlockFilterSet *BlockFilter);
377   MachineBasicBlock *selectBestSuccessor(MachineBasicBlock *BB,
378                                          BlockChain &Chain,
379                                          const BlockFilterSet *BlockFilter);
380   MachineBasicBlock *
381   selectBestCandidateBlock(BlockChain &Chain,
382                            SmallVectorImpl<MachineBasicBlock *> &WorkList);
383   MachineBasicBlock *
384   getFirstUnplacedBlock(const BlockChain &PlacedChain,
385                         MachineFunction::iterator &PrevUnplacedBlockIt,
386                         const BlockFilterSet *BlockFilter);
387 
388   /// \brief Add a basic block to the work list if it is appropriate.
389   ///
390   /// If the optional parameter BlockFilter is provided, only MBB
391   /// present in the set will be added to the worklist. If nullptr
392   /// is provided, no filtering occurs.
393   void fillWorkLists(MachineBasicBlock *MBB,
394                      SmallPtrSetImpl<BlockChain *> &UpdatedPreds,
395                      const BlockFilterSet *BlockFilter);
396   void buildChain(MachineBasicBlock *BB, BlockChain &Chain,
397                   BlockFilterSet *BlockFilter = nullptr);
398   MachineBasicBlock *findBestLoopTop(MachineLoop &L,
399                                      const BlockFilterSet &LoopBlockSet);
400   MachineBasicBlock *findBestLoopExit(MachineLoop &L,
401                                       const BlockFilterSet &LoopBlockSet);
402   BlockFilterSet collectLoopBlockSet(MachineLoop &L);
403   void buildLoopChains(MachineLoop &L);
404   void rotateLoop(BlockChain &LoopChain, MachineBasicBlock *ExitingBB,
405                   const BlockFilterSet &LoopBlockSet);
406   void rotateLoopWithProfile(BlockChain &LoopChain, MachineLoop &L,
407                              const BlockFilterSet &LoopBlockSet);
408   void collectMustExecuteBBs();
409   void buildCFGChains();
410   void optimizeBranches();
411   void alignBlocks();
412 
413 public:
414   static char ID; // Pass identification, replacement for typeid
415   MachineBlockPlacement() : MachineFunctionPass(ID) {
416     initializeMachineBlockPlacementPass(*PassRegistry::getPassRegistry());
417   }
418 
419   bool runOnMachineFunction(MachineFunction &F) override;
420 
421   void getAnalysisUsage(AnalysisUsage &AU) const override {
422     AU.addRequired<MachineBranchProbabilityInfo>();
423     AU.addRequired<MachineBlockFrequencyInfo>();
424     AU.addRequired<MachineDominatorTree>();
425     AU.addRequired<MachineLoopInfo>();
426     AU.addRequired<TargetPassConfig>();
427     MachineFunctionPass::getAnalysisUsage(AU);
428   }
429 };
430 }
431 
432 char MachineBlockPlacement::ID = 0;
433 char &llvm::MachineBlockPlacementID = MachineBlockPlacement::ID;
434 INITIALIZE_PASS_BEGIN(MachineBlockPlacement, "block-placement",
435                       "Branch Probability Basic Block Placement", false, false)
436 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
437 INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
438 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
439 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
440 INITIALIZE_PASS_END(MachineBlockPlacement, "block-placement",
441                     "Branch Probability Basic Block Placement", false, false)
442 
443 #ifndef NDEBUG
444 /// \brief Helper to print the name of a MBB.
445 ///
446 /// Only used by debug logging.
447 static std::string getBlockName(MachineBasicBlock *BB) {
448   std::string Result;
449   raw_string_ostream OS(Result);
450   OS << "BB#" << BB->getNumber();
451   OS << " ('" << BB->getName() << "')";
452   OS.flush();
453   return Result;
454 }
455 #endif
456 
457 /// \brief Mark a chain's successors as having one fewer preds.
458 ///
459 /// When a chain is being merged into the "placed" chain, this routine will
460 /// quickly walk the successors of each block in the chain and mark them as
461 /// having one fewer active predecessor. It also adds any successors of this
462 /// chain which reach the zero-predecessor state to the appropriate worklist.
463 void MachineBlockPlacement::markChainSuccessors(
464     BlockChain &Chain, MachineBasicBlock *LoopHeaderBB,
465     const BlockFilterSet *BlockFilter) {
466   // Walk all the blocks in this chain, marking their successors as having
467   // a predecessor placed.
468   for (MachineBasicBlock *MBB : Chain) {
469     markBlockSuccessors(Chain, MBB, LoopHeaderBB, BlockFilter);
470   }
471 }
472 
473 /// \brief Mark a single block's successors as having one fewer preds.
474 ///
475 /// Under normal circumstances, this is only called by markChainSuccessors,
476 /// but if a block that was to be placed is completely tail-duplicated away,
477 /// and was duplicated into the chain end, we need to redo markBlockSuccessors
478 /// for just that block.
479 void MachineBlockPlacement::markBlockSuccessors(
480     BlockChain &Chain, MachineBasicBlock *MBB, MachineBasicBlock *LoopHeaderBB,
481     const BlockFilterSet *BlockFilter) {
482   // Add any successors for which this is the only un-placed in-loop
483   // predecessor to the worklist as a viable candidate for CFG-neutral
484   // placement. No subsequent placement of this block will violate the CFG
485   // shape, so we get to use heuristics to choose a favorable placement.
486   for (MachineBasicBlock *Succ : MBB->successors()) {
487     if (BlockFilter && !BlockFilter->count(Succ))
488       continue;
489     BlockChain &SuccChain = *BlockToChain[Succ];
490     // Disregard edges within a fixed chain, or edges to the loop header.
491     if (&Chain == &SuccChain || Succ == LoopHeaderBB)
492       continue;
493 
494     // This is a cross-chain edge that is within the loop, so decrement the
495     // loop predecessor count of the destination chain.
496     if (SuccChain.UnscheduledPredecessors == 0 ||
497         --SuccChain.UnscheduledPredecessors > 0)
498       continue;
499 
500     auto *NewBB = *SuccChain.begin();
501     if (NewBB->isEHPad())
502       EHPadWorkList.push_back(NewBB);
503     else
504       BlockWorkList.push_back(NewBB);
505   }
506 }
507 
508 /// This helper function collects the set of successors of block
509 /// \p BB that are allowed to be its layout successors, and return
510 /// the total branch probability of edges from \p BB to those
511 /// blocks.
512 BranchProbability MachineBlockPlacement::collectViableSuccessors(
513     MachineBasicBlock *BB, BlockChain &Chain, const BlockFilterSet *BlockFilter,
514     SmallVector<MachineBasicBlock *, 4> &Successors) {
515   // Adjust edge probabilities by excluding edges pointing to blocks that is
516   // either not in BlockFilter or is already in the current chain. Consider the
517   // following CFG:
518   //
519   //     --->A
520   //     |  / \
521   //     | B   C
522   //     |  \ / \
523   //     ----D   E
524   //
525   // Assume A->C is very hot (>90%), and C->D has a 50% probability, then after
526   // A->C is chosen as a fall-through, D won't be selected as a successor of C
527   // due to CFG constraint (the probability of C->D is not greater than
528   // HotProb to break top-order). If we exclude E that is not in BlockFilter
529   // when calculating the  probability of C->D, D will be selected and we
530   // will get A C D B as the layout of this loop.
531   auto AdjustedSumProb = BranchProbability::getOne();
532   for (MachineBasicBlock *Succ : BB->successors()) {
533     bool SkipSucc = false;
534     if (Succ->isEHPad() || (BlockFilter && !BlockFilter->count(Succ))) {
535       SkipSucc = true;
536     } else {
537       BlockChain *SuccChain = BlockToChain[Succ];
538       if (SuccChain == &Chain) {
539         SkipSucc = true;
540       } else if (Succ != *SuccChain->begin()) {
541         DEBUG(dbgs() << "    " << getBlockName(Succ) << " -> Mid chain!\n");
542         continue;
543       }
544     }
545     if (SkipSucc)
546       AdjustedSumProb -= MBPI->getEdgeProbability(BB, Succ);
547     else
548       Successors.push_back(Succ);
549   }
550 
551   return AdjustedSumProb;
552 }
553 
554 /// The helper function returns the branch probability that is adjusted
555 /// or normalized over the new total \p AdjustedSumProb.
556 static BranchProbability
557 getAdjustedProbability(BranchProbability OrigProb,
558                        BranchProbability AdjustedSumProb) {
559   BranchProbability SuccProb;
560   uint32_t SuccProbN = OrigProb.getNumerator();
561   uint32_t SuccProbD = AdjustedSumProb.getNumerator();
562   if (SuccProbN >= SuccProbD)
563     SuccProb = BranchProbability::getOne();
564   else
565     SuccProb = BranchProbability(SuccProbN, SuccProbD);
566 
567   return SuccProb;
568 }
569 
570 /// When the option OutlineOptionalBranches is on, this method
571 /// checks if the fallthrough candidate block \p Succ (of block
572 /// \p BB) also has other unscheduled predecessor blocks which
573 /// are also successors of \p BB (forming triangular shape CFG).
574 /// If none of such predecessors are small, it returns true.
575 /// The caller can choose to select \p Succ as the layout successors
576 /// so that \p Succ's predecessors (optional branches) can be
577 /// outlined.
578 /// FIXME: fold this with more general layout cost analysis.
579 bool MachineBlockPlacement::shouldPredBlockBeOutlined(
580     MachineBasicBlock *BB, MachineBasicBlock *Succ, BlockChain &Chain,
581     const BlockFilterSet *BlockFilter, BranchProbability SuccProb,
582     BranchProbability HotProb) {
583   if (!OutlineOptionalBranches)
584     return false;
585   // If we outline optional branches, look whether Succ is unavoidable, i.e.
586   // dominates all terminators of the MachineFunction. If it does, other
587   // successors must be optional. Don't do this for cold branches.
588   if (SuccProb > HotProb.getCompl() && UnavoidableBlocks.count(Succ) > 0) {
589     for (MachineBasicBlock *Pred : Succ->predecessors()) {
590       // Check whether there is an unplaced optional branch.
591       if (Pred == Succ || (BlockFilter && !BlockFilter->count(Pred)) ||
592           BlockToChain[Pred] == &Chain)
593         continue;
594       // Check whether the optional branch has exactly one BB.
595       if (Pred->pred_size() > 1 || *Pred->pred_begin() != BB)
596         continue;
597       // Check whether the optional branch is small.
598       if (Pred->size() < OutlineOptionalThreshold)
599         return false;
600     }
601     return true;
602   } else
603     return false;
604 }
605 
606 // When profile is not present, return the StaticLikelyProb.
607 // When profile is available, we need to handle the triangle-shape CFG.
608 static BranchProbability getLayoutSuccessorProbThreshold(
609       MachineBasicBlock *BB) {
610   if (!BB->getParent()->getFunction()->getEntryCount())
611     return BranchProbability(StaticLikelyProb, 100);
612   if (BB->succ_size() == 2) {
613     const MachineBasicBlock *Succ1 = *BB->succ_begin();
614     const MachineBasicBlock *Succ2 = *(BB->succ_begin() + 1);
615     if (Succ1->isSuccessor(Succ2) || Succ2->isSuccessor(Succ1)) {
616       /* See case 1 below for the cost analysis. For BB->Succ to
617        * be taken with smaller cost, the following needs to hold:
618        *   Prob(BB->Succ) > 2* Prob(BB->Pred)
619        *   So the threshold T
620        *   T = 2 * (1-Prob(BB->Pred). Since T + Prob(BB->Pred) == 1,
621        * We have  T + T/2 = 1, i.e. T = 2/3. Also adding user specified
622        * branch bias, we have
623        *   T = (2/3)*(ProfileLikelyProb/50)
624        *     = (2*ProfileLikelyProb)/150)
625        */
626       return BranchProbability(2 * ProfileLikelyProb, 150);
627     }
628   }
629   return BranchProbability(ProfileLikelyProb, 100);
630 }
631 
632 /// Checks to see if the layout candidate block \p Succ has a better layout
633 /// predecessor than \c BB. If yes, returns true.
634 bool MachineBlockPlacement::hasBetterLayoutPredecessor(
635     MachineBasicBlock *BB, MachineBasicBlock *Succ, BlockChain &SuccChain,
636     BranchProbability SuccProb, BranchProbability RealSuccProb,
637     BlockChain &Chain, const BlockFilterSet *BlockFilter) {
638 
639   // There isn't a better layout when there are no unscheduled predecessors.
640   if (SuccChain.UnscheduledPredecessors == 0)
641     return false;
642 
643   // There are two basic scenarios here:
644   // -------------------------------------
645   // Case 1: triangular shape CFG (if-then):
646   //     BB
647   //     | \
648   //     |  \
649   //     |   Pred
650   //     |   /
651   //     Succ
652   // In this case, we are evaluating whether to select edge -> Succ, e.g.
653   // set Succ as the layout successor of BB. Picking Succ as BB's
654   // successor breaks the CFG constraints (FIXME: define these constraints).
655   // With this layout, Pred BB
656   // is forced to be outlined, so the overall cost will be cost of the
657   // branch taken from BB to Pred, plus the cost of back taken branch
658   // from Pred to Succ, as well as the additional cost associated
659   // with the needed unconditional jump instruction from Pred To Succ.
660 
661   // The cost of the topological order layout is the taken branch cost
662   // from BB to Succ, so to make BB->Succ a viable candidate, the following
663   // must hold:
664   //     2 * freq(BB->Pred) * taken_branch_cost + unconditional_jump_cost
665   //      < freq(BB->Succ) *  taken_branch_cost.
666   // Ignoring unconditional jump cost, we get
667   //    freq(BB->Succ) > 2 * freq(BB->Pred), i.e.,
668   //    prob(BB->Succ) > 2 * prob(BB->Pred)
669   //
670   // When real profile data is available, we can precisely compute the
671   // probability threshold that is needed for edge BB->Succ to be considered.
672   // Without profile data, the heuristic requires the branch bias to be
673   // a lot larger to make sure the signal is very strong (e.g. 80% default).
674   // -----------------------------------------------------------------
675   // Case 2: diamond like CFG (if-then-else):
676   //     S
677   //    / \
678   //   |   \
679   //  BB    Pred
680   //   \    /
681   //    Succ
682   //    ..
683   //
684   // The current block is BB and edge BB->Succ is now being evaluated.
685   // Note that edge S->BB was previously already selected because
686   // prob(S->BB) > prob(S->Pred).
687   // At this point, 2 blocks can be placed after BB: Pred or Succ. If we
688   // choose Pred, we will have a topological ordering as shown on the left
689   // in the picture below. If we choose Succ, we have the solution as shown
690   // on the right:
691   //
692   //   topo-order:
693   //
694   //       S-----                             ---S
695   //       |    |                             |  |
696   //    ---BB   |                             |  BB
697   //    |       |                             |  |
698   //    |  pred--                             |  Succ--
699   //    |  |                                  |       |
700   //    ---succ                               ---pred--
701   //
702   // cost = freq(S->Pred) + freq(BB->Succ)    cost = 2 * freq (S->Pred)
703   //      = freq(S->Pred) + freq(S->BB)
704   //
705   // If we have profile data (i.e, branch probabilities can be trusted), the
706   // cost (number of taken branches) with layout S->BB->Succ->Pred is 2 *
707   // freq(S->Pred) while the cost of topo order is freq(S->Pred) + freq(S->BB).
708   // We know Prob(S->BB) > Prob(S->Pred), so freq(S->BB) > freq(S->Pred), which
709   // means the cost of topological order is greater.
710   // When profile data is not available, however, we need to be more
711   // conservative. If the branch prediction is wrong, breaking the topo-order
712   // will actually yield a layout with large cost. For this reason, we need
713   // strong biased branch at block S with Prob(S->BB) in order to select
714   // BB->Succ. This is equivalent to looking the CFG backward with backward
715   // edge: Prob(Succ->BB) needs to >= HotProb in order to be selected (without
716   // profile data).
717   // --------------------------------------------------------------------------
718   // Case 3: forked diamond
719   //       S
720   //      / \
721   //     /   \
722   //   BB    Pred
723   //   | \   / |
724   //   |  \ /  |
725   //   |   X   |
726   //   |  / \  |
727   //   | /   \ |
728   //   S1     S2
729   //
730   // The current block is BB and edge BB->S1 is now being evaluated.
731   // As above S->BB was already selected because
732   // prob(S->BB) > prob(S->Pred). Assume that prob(BB->S1) >= prob(BB->S2).
733   //
734   // topo-order:
735   //
736   //     S-------|                     ---S
737   //     |       |                     |  |
738   //  ---BB      |                     |  BB
739   //  |          |                     |  |
740   //  |  Pred----|                     |  S1----
741   //  |  |                             |       |
742   //  --(S1 or S2)                     ---Pred--
743   //
744   // topo-cost = freq(S->Pred) + freq(BB->S1) + freq(BB->S2)
745   //    + min(freq(Pred->S1), freq(Pred->S2))
746   // Non-topo-order cost:
747   // In the worst case, S2 will not get laid out after Pred.
748   // non-topo-cost = 2 * freq(S->Pred) + freq(BB->S2).
749   // To be conservative, we can assume that min(freq(Pred->S1), freq(Pred->S2))
750   // is 0. Then the non topo layout is better when
751   // freq(S->Pred) < freq(BB->S1).
752   // This is exactly what is checked below.
753   // Note there are other shapes that apply (Pred may not be a single block,
754   // but they all fit this general pattern.)
755   BranchProbability HotProb = getLayoutSuccessorProbThreshold(BB);
756 
757   // Make sure that a hot successor doesn't have a globally more
758   // important predecessor.
759   BlockFrequency CandidateEdgeFreq = MBFI->getBlockFreq(BB) * RealSuccProb;
760   bool BadCFGConflict = false;
761 
762   for (MachineBasicBlock *Pred : Succ->predecessors()) {
763     if (Pred == Succ || BlockToChain[Pred] == &SuccChain ||
764         (BlockFilter && !BlockFilter->count(Pred)) ||
765         BlockToChain[Pred] == &Chain)
766       continue;
767     // Do backward checking.
768     // For all cases above, we need a backward checking to filter out edges that
769     // are not 'strongly' biased. With profile data available, the check is
770     // mostly redundant for case 2 (when threshold prob is set at 50%) unless S
771     // has more than two successors.
772     // BB  Pred
773     //  \ /
774     //  Succ
775     // We select edge BB->Succ if
776     //      freq(BB->Succ) > freq(Succ) * HotProb
777     //      i.e. freq(BB->Succ) > freq(BB->Succ) * HotProb + freq(Pred->Succ) *
778     //      HotProb
779     //      i.e. freq((BB->Succ) * (1 - HotProb) > freq(Pred->Succ) * HotProb
780     // Case 1 is covered too, because the first equation reduces to:
781     // prob(BB->Succ) > HotProb. (freq(Succ) = freq(BB) for a triangle)
782     BlockFrequency PredEdgeFreq =
783         MBFI->getBlockFreq(Pred) * MBPI->getEdgeProbability(Pred, Succ);
784     if (PredEdgeFreq * HotProb >= CandidateEdgeFreq * HotProb.getCompl()) {
785       BadCFGConflict = true;
786       break;
787     }
788   }
789 
790   if (BadCFGConflict) {
791     DEBUG(dbgs() << "    Not a candidate: " << getBlockName(Succ) << " -> " << SuccProb
792                  << " (prob) (non-cold CFG conflict)\n");
793     return true;
794   }
795 
796   return false;
797 }
798 
799 /// \brief Select the best successor for a block.
800 ///
801 /// This looks across all successors of a particular block and attempts to
802 /// select the "best" one to be the layout successor. It only considers direct
803 /// successors which also pass the block filter. It will attempt to avoid
804 /// breaking CFG structure, but cave and break such structures in the case of
805 /// very hot successor edges.
806 ///
807 /// \returns The best successor block found, or null if none are viable.
808 MachineBasicBlock *
809 MachineBlockPlacement::selectBestSuccessor(MachineBasicBlock *BB,
810                                            BlockChain &Chain,
811                                            const BlockFilterSet *BlockFilter) {
812   const BranchProbability HotProb(StaticLikelyProb, 100);
813 
814   MachineBasicBlock *BestSucc = nullptr;
815   auto BestProb = BranchProbability::getZero();
816 
817   SmallVector<MachineBasicBlock *, 4> Successors;
818   auto AdjustedSumProb =
819       collectViableSuccessors(BB, Chain, BlockFilter, Successors);
820 
821   DEBUG(dbgs() << "Selecting best successor for: " << getBlockName(BB) << "\n");
822   for (MachineBasicBlock *Succ : Successors) {
823     auto RealSuccProb = MBPI->getEdgeProbability(BB, Succ);
824     BranchProbability SuccProb =
825         getAdjustedProbability(RealSuccProb, AdjustedSumProb);
826 
827     // This heuristic is off by default.
828     if (shouldPredBlockBeOutlined(BB, Succ, Chain, BlockFilter, SuccProb,
829                                   HotProb))
830       return Succ;
831 
832     BlockChain &SuccChain = *BlockToChain[Succ];
833     // Skip the edge \c BB->Succ if block \c Succ has a better layout
834     // predecessor that yields lower global cost.
835     if (hasBetterLayoutPredecessor(BB, Succ, SuccChain, SuccProb, RealSuccProb,
836                                    Chain, BlockFilter))
837       continue;
838 
839     DEBUG(
840         dbgs() << "    Candidate: " << getBlockName(Succ) << ", probability: "
841                << SuccProb
842                << (SuccChain.UnscheduledPredecessors != 0 ? " (CFG break)" : "")
843                << "\n");
844 
845     if (BestSucc && BestProb >= SuccProb) {
846       DEBUG(dbgs() << "    Not the best candidate, continuing\n");
847       continue;
848     }
849 
850     DEBUG(dbgs() << "    Setting it as best candidate\n");
851     BestSucc = Succ;
852     BestProb = SuccProb;
853   }
854   if (BestSucc)
855     DEBUG(dbgs() << "    Selected: " << getBlockName(BestSucc) << "\n");
856 
857   return BestSucc;
858 }
859 
860 /// \brief Select the best block from a worklist.
861 ///
862 /// This looks through the provided worklist as a list of candidate basic
863 /// blocks and select the most profitable one to place. The definition of
864 /// profitable only really makes sense in the context of a loop. This returns
865 /// the most frequently visited block in the worklist, which in the case of
866 /// a loop, is the one most desirable to be physically close to the rest of the
867 /// loop body in order to improve i-cache behavior.
868 ///
869 /// \returns The best block found, or null if none are viable.
870 MachineBasicBlock *MachineBlockPlacement::selectBestCandidateBlock(
871     BlockChain &Chain, SmallVectorImpl<MachineBasicBlock *> &WorkList) {
872   // Once we need to walk the worklist looking for a candidate, cleanup the
873   // worklist of already placed entries.
874   // FIXME: If this shows up on profiles, it could be folded (at the cost of
875   // some code complexity) into the loop below.
876   WorkList.erase(remove_if(WorkList,
877                            [&](MachineBasicBlock *BB) {
878                              return BlockToChain.lookup(BB) == &Chain;
879                            }),
880                  WorkList.end());
881 
882   if (WorkList.empty())
883     return nullptr;
884 
885   bool IsEHPad = WorkList[0]->isEHPad();
886 
887   MachineBasicBlock *BestBlock = nullptr;
888   BlockFrequency BestFreq;
889   for (MachineBasicBlock *MBB : WorkList) {
890     assert(MBB->isEHPad() == IsEHPad);
891 
892     BlockChain &SuccChain = *BlockToChain[MBB];
893     if (&SuccChain == &Chain)
894       continue;
895 
896     assert(SuccChain.UnscheduledPredecessors == 0 && "Found CFG-violating block");
897 
898     BlockFrequency CandidateFreq = MBFI->getBlockFreq(MBB);
899     DEBUG(dbgs() << "    " << getBlockName(MBB) << " -> ";
900           MBFI->printBlockFreq(dbgs(), CandidateFreq) << " (freq)\n");
901 
902     // For ehpad, we layout the least probable first as to avoid jumping back
903     // from least probable landingpads to more probable ones.
904     //
905     // FIXME: Using probability is probably (!) not the best way to achieve
906     // this. We should probably have a more principled approach to layout
907     // cleanup code.
908     //
909     // The goal is to get:
910     //
911     //                 +--------------------------+
912     //                 |                          V
913     // InnerLp -> InnerCleanup    OuterLp -> OuterCleanup -> Resume
914     //
915     // Rather than:
916     //
917     //                 +-------------------------------------+
918     //                 V                                     |
919     // OuterLp -> OuterCleanup -> Resume     InnerLp -> InnerCleanup
920     if (BestBlock && (IsEHPad ^ (BestFreq >= CandidateFreq)))
921       continue;
922 
923     BestBlock = MBB;
924     BestFreq = CandidateFreq;
925   }
926 
927   return BestBlock;
928 }
929 
930 /// \brief Retrieve the first unplaced basic block.
931 ///
932 /// This routine is called when we are unable to use the CFG to walk through
933 /// all of the basic blocks and form a chain due to unnatural loops in the CFG.
934 /// We walk through the function's blocks in order, starting from the
935 /// LastUnplacedBlockIt. We update this iterator on each call to avoid
936 /// re-scanning the entire sequence on repeated calls to this routine.
937 MachineBasicBlock *MachineBlockPlacement::getFirstUnplacedBlock(
938     const BlockChain &PlacedChain,
939     MachineFunction::iterator &PrevUnplacedBlockIt,
940     const BlockFilterSet *BlockFilter) {
941   for (MachineFunction::iterator I = PrevUnplacedBlockIt, E = F->end(); I != E;
942        ++I) {
943     if (BlockFilter && !BlockFilter->count(&*I))
944       continue;
945     if (BlockToChain[&*I] != &PlacedChain) {
946       PrevUnplacedBlockIt = I;
947       // Now select the head of the chain to which the unplaced block belongs
948       // as the block to place. This will force the entire chain to be placed,
949       // and satisfies the requirements of merging chains.
950       return *BlockToChain[&*I]->begin();
951     }
952   }
953   return nullptr;
954 }
955 
956 void MachineBlockPlacement::fillWorkLists(
957     MachineBasicBlock *MBB,
958     SmallPtrSetImpl<BlockChain *> &UpdatedPreds,
959     const BlockFilterSet *BlockFilter = nullptr) {
960   BlockChain &Chain = *BlockToChain[MBB];
961   if (!UpdatedPreds.insert(&Chain).second)
962     return;
963 
964   assert(Chain.UnscheduledPredecessors == 0);
965   for (MachineBasicBlock *ChainBB : Chain) {
966     assert(BlockToChain[ChainBB] == &Chain);
967     for (MachineBasicBlock *Pred : ChainBB->predecessors()) {
968       if (BlockFilter && !BlockFilter->count(Pred))
969         continue;
970       if (BlockToChain[Pred] == &Chain)
971         continue;
972       ++Chain.UnscheduledPredecessors;
973     }
974   }
975 
976   if (Chain.UnscheduledPredecessors != 0)
977     return;
978 
979   MBB = *Chain.begin();
980   if (MBB->isEHPad())
981     EHPadWorkList.push_back(MBB);
982   else
983     BlockWorkList.push_back(MBB);
984 }
985 
986 void MachineBlockPlacement::buildChain(
987     MachineBasicBlock *BB, BlockChain &Chain,
988     BlockFilterSet *BlockFilter) {
989   assert(BB && "BB must not be null.\n");
990   assert(BlockToChain[BB] == &Chain && "BlockToChainMap mis-match.\n");
991   MachineFunction::iterator PrevUnplacedBlockIt = F->begin();
992 
993   MachineBasicBlock *LoopHeaderBB = BB;
994   markChainSuccessors(Chain, LoopHeaderBB, BlockFilter);
995   BB = *std::prev(Chain.end());
996   for (;;) {
997     assert(BB && "null block found at end of chain in loop.");
998     assert(BlockToChain[BB] == &Chain && "BlockToChainMap mis-match in loop.");
999     assert(*std::prev(Chain.end()) == BB && "BB Not found at end of chain.");
1000 
1001 
1002     // Look for the best viable successor if there is one to place immediately
1003     // after this block.
1004     MachineBasicBlock *BestSucc = selectBestSuccessor(BB, Chain, BlockFilter);
1005 
1006     // If an immediate successor isn't available, look for the best viable
1007     // block among those we've identified as not violating the loop's CFG at
1008     // this point. This won't be a fallthrough, but it will increase locality.
1009     if (!BestSucc)
1010       BestSucc = selectBestCandidateBlock(Chain, BlockWorkList);
1011     if (!BestSucc)
1012       BestSucc = selectBestCandidateBlock(Chain, EHPadWorkList);
1013 
1014     if (!BestSucc) {
1015       BestSucc = getFirstUnplacedBlock(Chain, PrevUnplacedBlockIt, BlockFilter);
1016       if (!BestSucc)
1017         break;
1018 
1019       DEBUG(dbgs() << "Unnatural loop CFG detected, forcibly merging the "
1020                       "layout successor until the CFG reduces\n");
1021     }
1022 
1023     // Placement may have changed tail duplication opportunities.
1024     // Check for that now.
1025     if (TailDupPlacement && BestSucc) {
1026       // If the chosen successor was duplicated into all its predecessors,
1027       // don't bother laying it out, just go round the loop again with BB as
1028       // the chain end.
1029       if (repeatedlyTailDuplicateBlock(BestSucc, BB, LoopHeaderBB, Chain,
1030                                        BlockFilter, PrevUnplacedBlockIt))
1031         continue;
1032     }
1033 
1034     // Place this block, updating the datastructures to reflect its placement.
1035     BlockChain &SuccChain = *BlockToChain[BestSucc];
1036     // Zero out UnscheduledPredecessors for the successor we're about to merge in case
1037     // we selected a successor that didn't fit naturally into the CFG.
1038     SuccChain.UnscheduledPredecessors = 0;
1039     DEBUG(dbgs() << "Merging from " << getBlockName(BB) << " to "
1040                  << getBlockName(BestSucc) << "\n");
1041     markChainSuccessors(SuccChain, LoopHeaderBB, BlockFilter);
1042     Chain.merge(BestSucc, &SuccChain);
1043     BB = *std::prev(Chain.end());
1044   }
1045 
1046   DEBUG(dbgs() << "Finished forming chain for header block "
1047                << getBlockName(*Chain.begin()) << "\n");
1048 }
1049 
1050 /// \brief Find the best loop top block for layout.
1051 ///
1052 /// Look for a block which is strictly better than the loop header for laying
1053 /// out at the top of the loop. This looks for one and only one pattern:
1054 /// a latch block with no conditional exit. This block will cause a conditional
1055 /// jump around it or will be the bottom of the loop if we lay it out in place,
1056 /// but if it it doesn't end up at the bottom of the loop for any reason,
1057 /// rotation alone won't fix it. Because such a block will always result in an
1058 /// unconditional jump (for the backedge) rotating it in front of the loop
1059 /// header is always profitable.
1060 MachineBasicBlock *
1061 MachineBlockPlacement::findBestLoopTop(MachineLoop &L,
1062                                        const BlockFilterSet &LoopBlockSet) {
1063   // Placing the latch block before the header may introduce an extra branch
1064   // that skips this block the first time the loop is executed, which we want
1065   // to avoid when optimising for size.
1066   // FIXME: in theory there is a case that does not introduce a new branch,
1067   // i.e. when the layout predecessor does not fallthrough to the loop header.
1068   // In practice this never happens though: there always seems to be a preheader
1069   // that can fallthrough and that is also placed before the header.
1070   if (F->getFunction()->optForSize())
1071     return L.getHeader();
1072 
1073   // Check that the header hasn't been fused with a preheader block due to
1074   // crazy branches. If it has, we need to start with the header at the top to
1075   // prevent pulling the preheader into the loop body.
1076   BlockChain &HeaderChain = *BlockToChain[L.getHeader()];
1077   if (!LoopBlockSet.count(*HeaderChain.begin()))
1078     return L.getHeader();
1079 
1080   DEBUG(dbgs() << "Finding best loop top for: " << getBlockName(L.getHeader())
1081                << "\n");
1082 
1083   BlockFrequency BestPredFreq;
1084   MachineBasicBlock *BestPred = nullptr;
1085   for (MachineBasicBlock *Pred : L.getHeader()->predecessors()) {
1086     if (!LoopBlockSet.count(Pred))
1087       continue;
1088     DEBUG(dbgs() << "    header pred: " << getBlockName(Pred) << ", has "
1089                  << Pred->succ_size() << " successors, ";
1090           MBFI->printBlockFreq(dbgs(), Pred) << " freq\n");
1091     if (Pred->succ_size() > 1)
1092       continue;
1093 
1094     BlockFrequency PredFreq = MBFI->getBlockFreq(Pred);
1095     if (!BestPred || PredFreq > BestPredFreq ||
1096         (!(PredFreq < BestPredFreq) &&
1097          Pred->isLayoutSuccessor(L.getHeader()))) {
1098       BestPred = Pred;
1099       BestPredFreq = PredFreq;
1100     }
1101   }
1102 
1103   // If no direct predecessor is fine, just use the loop header.
1104   if (!BestPred) {
1105     DEBUG(dbgs() << "    final top unchanged\n");
1106     return L.getHeader();
1107   }
1108 
1109   // Walk backwards through any straight line of predecessors.
1110   while (BestPred->pred_size() == 1 &&
1111          (*BestPred->pred_begin())->succ_size() == 1 &&
1112          *BestPred->pred_begin() != L.getHeader())
1113     BestPred = *BestPred->pred_begin();
1114 
1115   DEBUG(dbgs() << "    final top: " << getBlockName(BestPred) << "\n");
1116   return BestPred;
1117 }
1118 
1119 /// \brief Find the best loop exiting block for layout.
1120 ///
1121 /// This routine implements the logic to analyze the loop looking for the best
1122 /// block to layout at the top of the loop. Typically this is done to maximize
1123 /// fallthrough opportunities.
1124 MachineBasicBlock *
1125 MachineBlockPlacement::findBestLoopExit(MachineLoop &L,
1126                                         const BlockFilterSet &LoopBlockSet) {
1127   // We don't want to layout the loop linearly in all cases. If the loop header
1128   // is just a normal basic block in the loop, we want to look for what block
1129   // within the loop is the best one to layout at the top. However, if the loop
1130   // header has be pre-merged into a chain due to predecessors not having
1131   // analyzable branches, *and* the predecessor it is merged with is *not* part
1132   // of the loop, rotating the header into the middle of the loop will create
1133   // a non-contiguous range of blocks which is Very Bad. So start with the
1134   // header and only rotate if safe.
1135   BlockChain &HeaderChain = *BlockToChain[L.getHeader()];
1136   if (!LoopBlockSet.count(*HeaderChain.begin()))
1137     return nullptr;
1138 
1139   BlockFrequency BestExitEdgeFreq;
1140   unsigned BestExitLoopDepth = 0;
1141   MachineBasicBlock *ExitingBB = nullptr;
1142   // If there are exits to outer loops, loop rotation can severely limit
1143   // fallthrough opportunities unless it selects such an exit. Keep a set of
1144   // blocks where rotating to exit with that block will reach an outer loop.
1145   SmallPtrSet<MachineBasicBlock *, 4> BlocksExitingToOuterLoop;
1146 
1147   DEBUG(dbgs() << "Finding best loop exit for: " << getBlockName(L.getHeader())
1148                << "\n");
1149   for (MachineBasicBlock *MBB : L.getBlocks()) {
1150     BlockChain &Chain = *BlockToChain[MBB];
1151     // Ensure that this block is at the end of a chain; otherwise it could be
1152     // mid-way through an inner loop or a successor of an unanalyzable branch.
1153     if (MBB != *std::prev(Chain.end()))
1154       continue;
1155 
1156     // Now walk the successors. We need to establish whether this has a viable
1157     // exiting successor and whether it has a viable non-exiting successor.
1158     // We store the old exiting state and restore it if a viable looping
1159     // successor isn't found.
1160     MachineBasicBlock *OldExitingBB = ExitingBB;
1161     BlockFrequency OldBestExitEdgeFreq = BestExitEdgeFreq;
1162     bool HasLoopingSucc = false;
1163     for (MachineBasicBlock *Succ : MBB->successors()) {
1164       if (Succ->isEHPad())
1165         continue;
1166       if (Succ == MBB)
1167         continue;
1168       BlockChain &SuccChain = *BlockToChain[Succ];
1169       // Don't split chains, either this chain or the successor's chain.
1170       if (&Chain == &SuccChain) {
1171         DEBUG(dbgs() << "    exiting: " << getBlockName(MBB) << " -> "
1172                      << getBlockName(Succ) << " (chain conflict)\n");
1173         continue;
1174       }
1175 
1176       auto SuccProb = MBPI->getEdgeProbability(MBB, Succ);
1177       if (LoopBlockSet.count(Succ)) {
1178         DEBUG(dbgs() << "    looping: " << getBlockName(MBB) << " -> "
1179                      << getBlockName(Succ) << " (" << SuccProb << ")\n");
1180         HasLoopingSucc = true;
1181         continue;
1182       }
1183 
1184       unsigned SuccLoopDepth = 0;
1185       if (MachineLoop *ExitLoop = MLI->getLoopFor(Succ)) {
1186         SuccLoopDepth = ExitLoop->getLoopDepth();
1187         if (ExitLoop->contains(&L))
1188           BlocksExitingToOuterLoop.insert(MBB);
1189       }
1190 
1191       BlockFrequency ExitEdgeFreq = MBFI->getBlockFreq(MBB) * SuccProb;
1192       DEBUG(dbgs() << "    exiting: " << getBlockName(MBB) << " -> "
1193                    << getBlockName(Succ) << " [L:" << SuccLoopDepth << "] (";
1194             MBFI->printBlockFreq(dbgs(), ExitEdgeFreq) << ")\n");
1195       // Note that we bias this toward an existing layout successor to retain
1196       // incoming order in the absence of better information. The exit must have
1197       // a frequency higher than the current exit before we consider breaking
1198       // the layout.
1199       BranchProbability Bias(100 - ExitBlockBias, 100);
1200       if (!ExitingBB || SuccLoopDepth > BestExitLoopDepth ||
1201           ExitEdgeFreq > BestExitEdgeFreq ||
1202           (MBB->isLayoutSuccessor(Succ) &&
1203            !(ExitEdgeFreq < BestExitEdgeFreq * Bias))) {
1204         BestExitEdgeFreq = ExitEdgeFreq;
1205         ExitingBB = MBB;
1206       }
1207     }
1208 
1209     if (!HasLoopingSucc) {
1210       // Restore the old exiting state, no viable looping successor was found.
1211       ExitingBB = OldExitingBB;
1212       BestExitEdgeFreq = OldBestExitEdgeFreq;
1213     }
1214   }
1215   // Without a candidate exiting block or with only a single block in the
1216   // loop, just use the loop header to layout the loop.
1217   if (!ExitingBB) {
1218     DEBUG(dbgs() << "    No other candidate exit blocks, using loop header\n");
1219     return nullptr;
1220   }
1221   if (L.getNumBlocks() == 1) {
1222     DEBUG(dbgs() << "    Loop has 1 block, using loop header as exit\n");
1223     return nullptr;
1224   }
1225 
1226   // Also, if we have exit blocks which lead to outer loops but didn't select
1227   // one of them as the exiting block we are rotating toward, disable loop
1228   // rotation altogether.
1229   if (!BlocksExitingToOuterLoop.empty() &&
1230       !BlocksExitingToOuterLoop.count(ExitingBB))
1231     return nullptr;
1232 
1233   DEBUG(dbgs() << "  Best exiting block: " << getBlockName(ExitingBB) << "\n");
1234   return ExitingBB;
1235 }
1236 
1237 /// \brief Attempt to rotate an exiting block to the bottom of the loop.
1238 ///
1239 /// Once we have built a chain, try to rotate it to line up the hot exit block
1240 /// with fallthrough out of the loop if doing so doesn't introduce unnecessary
1241 /// branches. For example, if the loop has fallthrough into its header and out
1242 /// of its bottom already, don't rotate it.
1243 void MachineBlockPlacement::rotateLoop(BlockChain &LoopChain,
1244                                        MachineBasicBlock *ExitingBB,
1245                                        const BlockFilterSet &LoopBlockSet) {
1246   if (!ExitingBB)
1247     return;
1248 
1249   MachineBasicBlock *Top = *LoopChain.begin();
1250   bool ViableTopFallthrough = false;
1251   for (MachineBasicBlock *Pred : Top->predecessors()) {
1252     BlockChain *PredChain = BlockToChain[Pred];
1253     if (!LoopBlockSet.count(Pred) &&
1254         (!PredChain || Pred == *std::prev(PredChain->end()))) {
1255       ViableTopFallthrough = true;
1256       break;
1257     }
1258   }
1259 
1260   // If the header has viable fallthrough, check whether the current loop
1261   // bottom is a viable exiting block. If so, bail out as rotating will
1262   // introduce an unnecessary branch.
1263   if (ViableTopFallthrough) {
1264     MachineBasicBlock *Bottom = *std::prev(LoopChain.end());
1265     for (MachineBasicBlock *Succ : Bottom->successors()) {
1266       BlockChain *SuccChain = BlockToChain[Succ];
1267       if (!LoopBlockSet.count(Succ) &&
1268           (!SuccChain || Succ == *SuccChain->begin()))
1269         return;
1270     }
1271   }
1272 
1273   BlockChain::iterator ExitIt = find(LoopChain, ExitingBB);
1274   if (ExitIt == LoopChain.end())
1275     return;
1276 
1277   std::rotate(LoopChain.begin(), std::next(ExitIt), LoopChain.end());
1278 }
1279 
1280 /// \brief Attempt to rotate a loop based on profile data to reduce branch cost.
1281 ///
1282 /// With profile data, we can determine the cost in terms of missed fall through
1283 /// opportunities when rotating a loop chain and select the best rotation.
1284 /// Basically, there are three kinds of cost to consider for each rotation:
1285 ///    1. The possibly missed fall through edge (if it exists) from BB out of
1286 ///    the loop to the loop header.
1287 ///    2. The possibly missed fall through edges (if they exist) from the loop
1288 ///    exits to BB out of the loop.
1289 ///    3. The missed fall through edge (if it exists) from the last BB to the
1290 ///    first BB in the loop chain.
1291 ///  Therefore, the cost for a given rotation is the sum of costs listed above.
1292 ///  We select the best rotation with the smallest cost.
1293 void MachineBlockPlacement::rotateLoopWithProfile(
1294     BlockChain &LoopChain, MachineLoop &L, const BlockFilterSet &LoopBlockSet) {
1295   auto HeaderBB = L.getHeader();
1296   auto HeaderIter = find(LoopChain, HeaderBB);
1297   auto RotationPos = LoopChain.end();
1298 
1299   BlockFrequency SmallestRotationCost = BlockFrequency::getMaxFrequency();
1300 
1301   // A utility lambda that scales up a block frequency by dividing it by a
1302   // branch probability which is the reciprocal of the scale.
1303   auto ScaleBlockFrequency = [](BlockFrequency Freq,
1304                                 unsigned Scale) -> BlockFrequency {
1305     if (Scale == 0)
1306       return 0;
1307     // Use operator / between BlockFrequency and BranchProbability to implement
1308     // saturating multiplication.
1309     return Freq / BranchProbability(1, Scale);
1310   };
1311 
1312   // Compute the cost of the missed fall-through edge to the loop header if the
1313   // chain head is not the loop header. As we only consider natural loops with
1314   // single header, this computation can be done only once.
1315   BlockFrequency HeaderFallThroughCost(0);
1316   for (auto *Pred : HeaderBB->predecessors()) {
1317     BlockChain *PredChain = BlockToChain[Pred];
1318     if (!LoopBlockSet.count(Pred) &&
1319         (!PredChain || Pred == *std::prev(PredChain->end()))) {
1320       auto EdgeFreq =
1321           MBFI->getBlockFreq(Pred) * MBPI->getEdgeProbability(Pred, HeaderBB);
1322       auto FallThruCost = ScaleBlockFrequency(EdgeFreq, MisfetchCost);
1323       // If the predecessor has only an unconditional jump to the header, we
1324       // need to consider the cost of this jump.
1325       if (Pred->succ_size() == 1)
1326         FallThruCost += ScaleBlockFrequency(EdgeFreq, JumpInstCost);
1327       HeaderFallThroughCost = std::max(HeaderFallThroughCost, FallThruCost);
1328     }
1329   }
1330 
1331   // Here we collect all exit blocks in the loop, and for each exit we find out
1332   // its hottest exit edge. For each loop rotation, we define the loop exit cost
1333   // as the sum of frequencies of exit edges we collect here, excluding the exit
1334   // edge from the tail of the loop chain.
1335   SmallVector<std::pair<MachineBasicBlock *, BlockFrequency>, 4> ExitsWithFreq;
1336   for (auto BB : LoopChain) {
1337     auto LargestExitEdgeProb = BranchProbability::getZero();
1338     for (auto *Succ : BB->successors()) {
1339       BlockChain *SuccChain = BlockToChain[Succ];
1340       if (!LoopBlockSet.count(Succ) &&
1341           (!SuccChain || Succ == *SuccChain->begin())) {
1342         auto SuccProb = MBPI->getEdgeProbability(BB, Succ);
1343         LargestExitEdgeProb = std::max(LargestExitEdgeProb, SuccProb);
1344       }
1345     }
1346     if (LargestExitEdgeProb > BranchProbability::getZero()) {
1347       auto ExitFreq = MBFI->getBlockFreq(BB) * LargestExitEdgeProb;
1348       ExitsWithFreq.emplace_back(BB, ExitFreq);
1349     }
1350   }
1351 
1352   // In this loop we iterate every block in the loop chain and calculate the
1353   // cost assuming the block is the head of the loop chain. When the loop ends,
1354   // we should have found the best candidate as the loop chain's head.
1355   for (auto Iter = LoopChain.begin(), TailIter = std::prev(LoopChain.end()),
1356             EndIter = LoopChain.end();
1357        Iter != EndIter; Iter++, TailIter++) {
1358     // TailIter is used to track the tail of the loop chain if the block we are
1359     // checking (pointed by Iter) is the head of the chain.
1360     if (TailIter == LoopChain.end())
1361       TailIter = LoopChain.begin();
1362 
1363     auto TailBB = *TailIter;
1364 
1365     // Calculate the cost by putting this BB to the top.
1366     BlockFrequency Cost = 0;
1367 
1368     // If the current BB is the loop header, we need to take into account the
1369     // cost of the missed fall through edge from outside of the loop to the
1370     // header.
1371     if (Iter != HeaderIter)
1372       Cost += HeaderFallThroughCost;
1373 
1374     // Collect the loop exit cost by summing up frequencies of all exit edges
1375     // except the one from the chain tail.
1376     for (auto &ExitWithFreq : ExitsWithFreq)
1377       if (TailBB != ExitWithFreq.first)
1378         Cost += ExitWithFreq.second;
1379 
1380     // The cost of breaking the once fall-through edge from the tail to the top
1381     // of the loop chain. Here we need to consider three cases:
1382     // 1. If the tail node has only one successor, then we will get an
1383     //    additional jmp instruction. So the cost here is (MisfetchCost +
1384     //    JumpInstCost) * tail node frequency.
1385     // 2. If the tail node has two successors, then we may still get an
1386     //    additional jmp instruction if the layout successor after the loop
1387     //    chain is not its CFG successor. Note that the more frequently executed
1388     //    jmp instruction will be put ahead of the other one. Assume the
1389     //    frequency of those two branches are x and y, where x is the frequency
1390     //    of the edge to the chain head, then the cost will be
1391     //    (x * MisfetechCost + min(x, y) * JumpInstCost) * tail node frequency.
1392     // 3. If the tail node has more than two successors (this rarely happens),
1393     //    we won't consider any additional cost.
1394     if (TailBB->isSuccessor(*Iter)) {
1395       auto TailBBFreq = MBFI->getBlockFreq(TailBB);
1396       if (TailBB->succ_size() == 1)
1397         Cost += ScaleBlockFrequency(TailBBFreq.getFrequency(),
1398                                     MisfetchCost + JumpInstCost);
1399       else if (TailBB->succ_size() == 2) {
1400         auto TailToHeadProb = MBPI->getEdgeProbability(TailBB, *Iter);
1401         auto TailToHeadFreq = TailBBFreq * TailToHeadProb;
1402         auto ColderEdgeFreq = TailToHeadProb > BranchProbability(1, 2)
1403                                   ? TailBBFreq * TailToHeadProb.getCompl()
1404                                   : TailToHeadFreq;
1405         Cost += ScaleBlockFrequency(TailToHeadFreq, MisfetchCost) +
1406                 ScaleBlockFrequency(ColderEdgeFreq, JumpInstCost);
1407       }
1408     }
1409 
1410     DEBUG(dbgs() << "The cost of loop rotation by making " << getBlockName(*Iter)
1411                  << " to the top: " << Cost.getFrequency() << "\n");
1412 
1413     if (Cost < SmallestRotationCost) {
1414       SmallestRotationCost = Cost;
1415       RotationPos = Iter;
1416     }
1417   }
1418 
1419   if (RotationPos != LoopChain.end()) {
1420     DEBUG(dbgs() << "Rotate loop by making " << getBlockName(*RotationPos)
1421                  << " to the top\n");
1422     std::rotate(LoopChain.begin(), RotationPos, LoopChain.end());
1423   }
1424 }
1425 
1426 /// \brief Collect blocks in the given loop that are to be placed.
1427 ///
1428 /// When profile data is available, exclude cold blocks from the returned set;
1429 /// otherwise, collect all blocks in the loop.
1430 MachineBlockPlacement::BlockFilterSet
1431 MachineBlockPlacement::collectLoopBlockSet(MachineLoop &L) {
1432   BlockFilterSet LoopBlockSet;
1433 
1434   // Filter cold blocks off from LoopBlockSet when profile data is available.
1435   // Collect the sum of frequencies of incoming edges to the loop header from
1436   // outside. If we treat the loop as a super block, this is the frequency of
1437   // the loop. Then for each block in the loop, we calculate the ratio between
1438   // its frequency and the frequency of the loop block. When it is too small,
1439   // don't add it to the loop chain. If there are outer loops, then this block
1440   // will be merged into the first outer loop chain for which this block is not
1441   // cold anymore. This needs precise profile data and we only do this when
1442   // profile data is available.
1443   if (F->getFunction()->getEntryCount()) {
1444     BlockFrequency LoopFreq(0);
1445     for (auto LoopPred : L.getHeader()->predecessors())
1446       if (!L.contains(LoopPred))
1447         LoopFreq += MBFI->getBlockFreq(LoopPred) *
1448                     MBPI->getEdgeProbability(LoopPred, L.getHeader());
1449 
1450     for (MachineBasicBlock *LoopBB : L.getBlocks()) {
1451       auto Freq = MBFI->getBlockFreq(LoopBB).getFrequency();
1452       if (Freq == 0 || LoopFreq.getFrequency() / Freq > LoopToColdBlockRatio)
1453         continue;
1454       LoopBlockSet.insert(LoopBB);
1455     }
1456   } else
1457     LoopBlockSet.insert(L.block_begin(), L.block_end());
1458 
1459   return LoopBlockSet;
1460 }
1461 
1462 /// \brief Forms basic block chains from the natural loop structures.
1463 ///
1464 /// These chains are designed to preserve the existing *structure* of the code
1465 /// as much as possible. We can then stitch the chains together in a way which
1466 /// both preserves the topological structure and minimizes taken conditional
1467 /// branches.
1468 void MachineBlockPlacement::buildLoopChains(MachineLoop &L) {
1469   // First recurse through any nested loops, building chains for those inner
1470   // loops.
1471   for (MachineLoop *InnerLoop : L)
1472     buildLoopChains(*InnerLoop);
1473 
1474   assert(BlockWorkList.empty());
1475   assert(EHPadWorkList.empty());
1476   BlockFilterSet LoopBlockSet = collectLoopBlockSet(L);
1477 
1478   // Check if we have profile data for this function. If yes, we will rotate
1479   // this loop by modeling costs more precisely which requires the profile data
1480   // for better layout.
1481   bool RotateLoopWithProfile =
1482       ForcePreciseRotationCost ||
1483       (PreciseRotationCost && F->getFunction()->getEntryCount());
1484 
1485   // First check to see if there is an obviously preferable top block for the
1486   // loop. This will default to the header, but may end up as one of the
1487   // predecessors to the header if there is one which will result in strictly
1488   // fewer branches in the loop body.
1489   // When we use profile data to rotate the loop, this is unnecessary.
1490   MachineBasicBlock *LoopTop =
1491       RotateLoopWithProfile ? L.getHeader() : findBestLoopTop(L, LoopBlockSet);
1492 
1493   // If we selected just the header for the loop top, look for a potentially
1494   // profitable exit block in the event that rotating the loop can eliminate
1495   // branches by placing an exit edge at the bottom.
1496   if (!RotateLoopWithProfile && LoopTop == L.getHeader())
1497     PreferredLoopExit = findBestLoopExit(L, LoopBlockSet);
1498 
1499   BlockChain &LoopChain = *BlockToChain[LoopTop];
1500 
1501   // FIXME: This is a really lame way of walking the chains in the loop: we
1502   // walk the blocks, and use a set to prevent visiting a particular chain
1503   // twice.
1504   SmallPtrSet<BlockChain *, 4> UpdatedPreds;
1505   assert(LoopChain.UnscheduledPredecessors == 0);
1506   UpdatedPreds.insert(&LoopChain);
1507 
1508   for (MachineBasicBlock *LoopBB : LoopBlockSet)
1509     fillWorkLists(LoopBB, UpdatedPreds, &LoopBlockSet);
1510 
1511   buildChain(LoopTop, LoopChain, &LoopBlockSet);
1512 
1513   if (RotateLoopWithProfile)
1514     rotateLoopWithProfile(LoopChain, L, LoopBlockSet);
1515   else
1516     rotateLoop(LoopChain, PreferredLoopExit, LoopBlockSet);
1517 
1518   DEBUG({
1519     // Crash at the end so we get all of the debugging output first.
1520     bool BadLoop = false;
1521     if (LoopChain.UnscheduledPredecessors) {
1522       BadLoop = true;
1523       dbgs() << "Loop chain contains a block without its preds placed!\n"
1524              << "  Loop header:  " << getBlockName(*L.block_begin()) << "\n"
1525              << "  Chain header: " << getBlockName(*LoopChain.begin()) << "\n";
1526     }
1527     for (MachineBasicBlock *ChainBB : LoopChain) {
1528       dbgs() << "          ... " << getBlockName(ChainBB) << "\n";
1529       if (!LoopBlockSet.remove(ChainBB)) {
1530         // We don't mark the loop as bad here because there are real situations
1531         // where this can occur. For example, with an unanalyzable fallthrough
1532         // from a loop block to a non-loop block or vice versa.
1533         dbgs() << "Loop chain contains a block not contained by the loop!\n"
1534                << "  Loop header:  " << getBlockName(*L.block_begin()) << "\n"
1535                << "  Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
1536                << "  Bad block:    " << getBlockName(ChainBB) << "\n";
1537       }
1538     }
1539 
1540     if (!LoopBlockSet.empty()) {
1541       BadLoop = true;
1542       for (MachineBasicBlock *LoopBB : LoopBlockSet)
1543         dbgs() << "Loop contains blocks never placed into a chain!\n"
1544                << "  Loop header:  " << getBlockName(*L.block_begin()) << "\n"
1545                << "  Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
1546                << "  Bad block:    " << getBlockName(LoopBB) << "\n";
1547     }
1548     assert(!BadLoop && "Detected problems with the placement of this loop.");
1549   });
1550 
1551   BlockWorkList.clear();
1552   EHPadWorkList.clear();
1553 }
1554 
1555 /// When OutlineOpitonalBranches is on, this method collects BBs that
1556 /// dominates all terminator blocks of the function \p F.
1557 void MachineBlockPlacement::collectMustExecuteBBs() {
1558   if (OutlineOptionalBranches) {
1559     // Find the nearest common dominator of all of F's terminators.
1560     MachineBasicBlock *Terminator = nullptr;
1561     for (MachineBasicBlock &MBB : *F) {
1562       if (MBB.succ_size() == 0) {
1563         if (Terminator == nullptr)
1564           Terminator = &MBB;
1565         else
1566           Terminator = MDT->findNearestCommonDominator(Terminator, &MBB);
1567       }
1568     }
1569 
1570     // MBBs dominating this common dominator are unavoidable.
1571     UnavoidableBlocks.clear();
1572     for (MachineBasicBlock &MBB : *F) {
1573       if (MDT->dominates(&MBB, Terminator)) {
1574         UnavoidableBlocks.insert(&MBB);
1575       }
1576     }
1577   }
1578 }
1579 
1580 void MachineBlockPlacement::buildCFGChains() {
1581   // Ensure that every BB in the function has an associated chain to simplify
1582   // the assumptions of the remaining algorithm.
1583   SmallVector<MachineOperand, 4> Cond; // For AnalyzeBranch.
1584   for (MachineFunction::iterator FI = F->begin(), FE = F->end(); FI != FE;
1585        ++FI) {
1586     MachineBasicBlock *BB = &*FI;
1587     BlockChain *Chain =
1588         new (ChainAllocator.Allocate()) BlockChain(BlockToChain, BB);
1589     // Also, merge any blocks which we cannot reason about and must preserve
1590     // the exact fallthrough behavior for.
1591     for (;;) {
1592       Cond.clear();
1593       MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
1594       if (!TII->analyzeBranch(*BB, TBB, FBB, Cond) || !FI->canFallThrough())
1595         break;
1596 
1597       MachineFunction::iterator NextFI = std::next(FI);
1598       MachineBasicBlock *NextBB = &*NextFI;
1599       // Ensure that the layout successor is a viable block, as we know that
1600       // fallthrough is a possibility.
1601       assert(NextFI != FE && "Can't fallthrough past the last block.");
1602       DEBUG(dbgs() << "Pre-merging due to unanalyzable fallthrough: "
1603                    << getBlockName(BB) << " -> " << getBlockName(NextBB)
1604                    << "\n");
1605       Chain->merge(NextBB, nullptr);
1606 #ifndef NDEBUG
1607       BlocksWithUnanalyzableExits.insert(&*BB);
1608 #endif
1609       FI = NextFI;
1610       BB = NextBB;
1611     }
1612   }
1613 
1614   // Turned on with OutlineOptionalBranches option
1615   collectMustExecuteBBs();
1616 
1617   // Build any loop-based chains.
1618   PreferredLoopExit = nullptr;
1619   for (MachineLoop *L : *MLI)
1620     buildLoopChains(*L);
1621 
1622   assert(BlockWorkList.empty());
1623   assert(EHPadWorkList.empty());
1624 
1625   SmallPtrSet<BlockChain *, 4> UpdatedPreds;
1626   for (MachineBasicBlock &MBB : *F)
1627     fillWorkLists(&MBB, UpdatedPreds);
1628 
1629   BlockChain &FunctionChain = *BlockToChain[&F->front()];
1630   buildChain(&F->front(), FunctionChain);
1631 
1632 #ifndef NDEBUG
1633   typedef SmallPtrSet<MachineBasicBlock *, 16> FunctionBlockSetType;
1634 #endif
1635   DEBUG({
1636     // Crash at the end so we get all of the debugging output first.
1637     bool BadFunc = false;
1638     FunctionBlockSetType FunctionBlockSet;
1639     for (MachineBasicBlock &MBB : *F)
1640       FunctionBlockSet.insert(&MBB);
1641 
1642     for (MachineBasicBlock *ChainBB : FunctionChain)
1643       if (!FunctionBlockSet.erase(ChainBB)) {
1644         BadFunc = true;
1645         dbgs() << "Function chain contains a block not in the function!\n"
1646                << "  Bad block:    " << getBlockName(ChainBB) << "\n";
1647       }
1648 
1649     if (!FunctionBlockSet.empty()) {
1650       BadFunc = true;
1651       for (MachineBasicBlock *RemainingBB : FunctionBlockSet)
1652         dbgs() << "Function contains blocks never placed into a chain!\n"
1653                << "  Bad block:    " << getBlockName(RemainingBB) << "\n";
1654     }
1655     assert(!BadFunc && "Detected problems with the block placement.");
1656   });
1657 
1658   // Splice the blocks into place.
1659   MachineFunction::iterator InsertPos = F->begin();
1660   DEBUG(dbgs() << "[MBP] Function: "<< F->getName() << "\n");
1661   for (MachineBasicBlock *ChainBB : FunctionChain) {
1662     DEBUG(dbgs() << (ChainBB == *FunctionChain.begin() ? "Placing chain "
1663                                                        : "          ... ")
1664                  << getBlockName(ChainBB) << "\n");
1665     if (InsertPos != MachineFunction::iterator(ChainBB))
1666       F->splice(InsertPos, ChainBB);
1667     else
1668       ++InsertPos;
1669 
1670     // Update the terminator of the previous block.
1671     if (ChainBB == *FunctionChain.begin())
1672       continue;
1673     MachineBasicBlock *PrevBB = &*std::prev(MachineFunction::iterator(ChainBB));
1674 
1675     // FIXME: It would be awesome of updateTerminator would just return rather
1676     // than assert when the branch cannot be analyzed in order to remove this
1677     // boiler plate.
1678     Cond.clear();
1679     MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
1680 
1681 #ifndef NDEBUG
1682     if (!BlocksWithUnanalyzableExits.count(PrevBB)) {
1683       // Given the exact block placement we chose, we may actually not _need_ to
1684       // be able to edit PrevBB's terminator sequence, but not being _able_ to
1685       // do that at this point is a bug.
1686       assert((!TII->analyzeBranch(*PrevBB, TBB, FBB, Cond) ||
1687               !PrevBB->canFallThrough()) &&
1688              "Unexpected block with un-analyzable fallthrough!");
1689       Cond.clear();
1690       TBB = FBB = nullptr;
1691     }
1692 #endif
1693 
1694     // The "PrevBB" is not yet updated to reflect current code layout, so,
1695     //   o. it may fall-through to a block without explicit "goto" instruction
1696     //      before layout, and no longer fall-through it after layout; or
1697     //   o. just opposite.
1698     //
1699     // analyzeBranch() may return erroneous value for FBB when these two
1700     // situations take place. For the first scenario FBB is mistakenly set NULL;
1701     // for the 2nd scenario, the FBB, which is expected to be NULL, is
1702     // mistakenly pointing to "*BI".
1703     // Thus, if the future change needs to use FBB before the layout is set, it
1704     // has to correct FBB first by using the code similar to the following:
1705     //
1706     // if (!Cond.empty() && (!FBB || FBB == ChainBB)) {
1707     //   PrevBB->updateTerminator();
1708     //   Cond.clear();
1709     //   TBB = FBB = nullptr;
1710     //   if (TII->analyzeBranch(*PrevBB, TBB, FBB, Cond)) {
1711     //     // FIXME: This should never take place.
1712     //     TBB = FBB = nullptr;
1713     //   }
1714     // }
1715     if (!TII->analyzeBranch(*PrevBB, TBB, FBB, Cond))
1716       PrevBB->updateTerminator();
1717   }
1718 
1719   // Fixup the last block.
1720   Cond.clear();
1721   MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
1722   if (!TII->analyzeBranch(F->back(), TBB, FBB, Cond))
1723     F->back().updateTerminator();
1724 
1725   BlockWorkList.clear();
1726   EHPadWorkList.clear();
1727 }
1728 
1729 void MachineBlockPlacement::optimizeBranches() {
1730   BlockChain &FunctionChain = *BlockToChain[&F->front()];
1731   SmallVector<MachineOperand, 4> Cond; // For AnalyzeBranch.
1732 
1733   // Now that all the basic blocks in the chain have the proper layout,
1734   // make a final call to AnalyzeBranch with AllowModify set.
1735   // Indeed, the target may be able to optimize the branches in a way we
1736   // cannot because all branches may not be analyzable.
1737   // E.g., the target may be able to remove an unconditional branch to
1738   // a fallthrough when it occurs after predicated terminators.
1739   for (MachineBasicBlock *ChainBB : FunctionChain) {
1740     Cond.clear();
1741     MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
1742     if (!TII->analyzeBranch(*ChainBB, TBB, FBB, Cond, /*AllowModify*/ true)) {
1743       // If PrevBB has a two-way branch, try to re-order the branches
1744       // such that we branch to the successor with higher probability first.
1745       if (TBB && !Cond.empty() && FBB &&
1746           MBPI->getEdgeProbability(ChainBB, FBB) >
1747               MBPI->getEdgeProbability(ChainBB, TBB) &&
1748           !TII->reverseBranchCondition(Cond)) {
1749         DEBUG(dbgs() << "Reverse order of the two branches: "
1750                      << getBlockName(ChainBB) << "\n");
1751         DEBUG(dbgs() << "    Edge probability: "
1752                      << MBPI->getEdgeProbability(ChainBB, FBB) << " vs "
1753                      << MBPI->getEdgeProbability(ChainBB, TBB) << "\n");
1754         DebugLoc dl; // FIXME: this is nowhere
1755         TII->removeBranch(*ChainBB);
1756         TII->insertBranch(*ChainBB, FBB, TBB, Cond, dl);
1757         ChainBB->updateTerminator();
1758       }
1759     }
1760   }
1761 }
1762 
1763 void MachineBlockPlacement::alignBlocks() {
1764   // Walk through the backedges of the function now that we have fully laid out
1765   // the basic blocks and align the destination of each backedge. We don't rely
1766   // exclusively on the loop info here so that we can align backedges in
1767   // unnatural CFGs and backedges that were introduced purely because of the
1768   // loop rotations done during this layout pass.
1769   if (F->getFunction()->optForSize())
1770     return;
1771   BlockChain &FunctionChain = *BlockToChain[&F->front()];
1772   if (FunctionChain.begin() == FunctionChain.end())
1773     return; // Empty chain.
1774 
1775   const BranchProbability ColdProb(1, 5); // 20%
1776   BlockFrequency EntryFreq = MBFI->getBlockFreq(&F->front());
1777   BlockFrequency WeightedEntryFreq = EntryFreq * ColdProb;
1778   for (MachineBasicBlock *ChainBB : FunctionChain) {
1779     if (ChainBB == *FunctionChain.begin())
1780       continue;
1781 
1782     // Don't align non-looping basic blocks. These are unlikely to execute
1783     // enough times to matter in practice. Note that we'll still handle
1784     // unnatural CFGs inside of a natural outer loop (the common case) and
1785     // rotated loops.
1786     MachineLoop *L = MLI->getLoopFor(ChainBB);
1787     if (!L)
1788       continue;
1789 
1790     unsigned Align = TLI->getPrefLoopAlignment(L);
1791     if (!Align)
1792       continue; // Don't care about loop alignment.
1793 
1794     // If the block is cold relative to the function entry don't waste space
1795     // aligning it.
1796     BlockFrequency Freq = MBFI->getBlockFreq(ChainBB);
1797     if (Freq < WeightedEntryFreq)
1798       continue;
1799 
1800     // If the block is cold relative to its loop header, don't align it
1801     // regardless of what edges into the block exist.
1802     MachineBasicBlock *LoopHeader = L->getHeader();
1803     BlockFrequency LoopHeaderFreq = MBFI->getBlockFreq(LoopHeader);
1804     if (Freq < (LoopHeaderFreq * ColdProb))
1805       continue;
1806 
1807     // Check for the existence of a non-layout predecessor which would benefit
1808     // from aligning this block.
1809     MachineBasicBlock *LayoutPred =
1810         &*std::prev(MachineFunction::iterator(ChainBB));
1811 
1812     // Force alignment if all the predecessors are jumps. We already checked
1813     // that the block isn't cold above.
1814     if (!LayoutPred->isSuccessor(ChainBB)) {
1815       ChainBB->setAlignment(Align);
1816       continue;
1817     }
1818 
1819     // Align this block if the layout predecessor's edge into this block is
1820     // cold relative to the block. When this is true, other predecessors make up
1821     // all of the hot entries into the block and thus alignment is likely to be
1822     // important.
1823     BranchProbability LayoutProb =
1824         MBPI->getEdgeProbability(LayoutPred, ChainBB);
1825     BlockFrequency LayoutEdgeFreq = MBFI->getBlockFreq(LayoutPred) * LayoutProb;
1826     if (LayoutEdgeFreq <= (Freq * ColdProb))
1827       ChainBB->setAlignment(Align);
1828   }
1829 }
1830 
1831 /// Tail duplicate \p BB into (some) predecessors if profitable, repeating if
1832 /// it was duplicated into its chain predecessor and removed.
1833 /// \p BB    - Basic block that may be duplicated.
1834 ///
1835 /// \p LPred - Chosen layout predecessor of \p BB.
1836 ///            Updated to be the chain end if LPred is removed.
1837 /// \p Chain - Chain to which \p LPred belongs, and \p BB will belong.
1838 /// \p BlockFilter - Set of blocks that belong to the loop being laid out.
1839 ///                  Used to identify which blocks to update predecessor
1840 ///                  counts.
1841 /// \p PrevUnplacedBlockIt - Iterator pointing to the last block that was
1842 ///                          chosen in the given order due to unnatural CFG
1843 ///                          only needed if \p BB is removed and
1844 ///                          \p PrevUnplacedBlockIt pointed to \p BB.
1845 /// @return true if \p BB was removed.
1846 bool MachineBlockPlacement::repeatedlyTailDuplicateBlock(
1847     MachineBasicBlock *BB, MachineBasicBlock *&LPred,
1848     MachineBasicBlock *LoopHeaderBB,
1849     BlockChain &Chain, BlockFilterSet *BlockFilter,
1850     MachineFunction::iterator &PrevUnplacedBlockIt) {
1851   bool Removed, DuplicatedToLPred;
1852   bool DuplicatedToOriginalLPred;
1853   Removed = maybeTailDuplicateBlock(BB, LPred, Chain, BlockFilter,
1854                                     PrevUnplacedBlockIt,
1855                                     DuplicatedToLPred);
1856   if (!Removed)
1857     return false;
1858   DuplicatedToOriginalLPred = DuplicatedToLPred;
1859   // Iteratively try to duplicate again. It can happen that a block that is
1860   // duplicated into is still small enough to be duplicated again.
1861   // No need to call markBlockSuccessors in this case, as the blocks being
1862   // duplicated from here on are already scheduled.
1863   // Note that DuplicatedToLPred always implies Removed.
1864   while (DuplicatedToLPred) {
1865     assert (Removed && "Block must have been removed to be duplicated into its "
1866             "layout predecessor.");
1867     MachineBasicBlock *DupBB, *DupPred;
1868     // The removal callback causes Chain.end() to be updated when a block is
1869     // removed. On the first pass through the loop, the chain end should be the
1870     // same as it was on function entry. On subsequent passes, because we are
1871     // duplicating the block at the end of the chain, if it is removed the
1872     // chain will have shrunk by one block.
1873     BlockChain::iterator ChainEnd = Chain.end();
1874     DupBB = *(--ChainEnd);
1875     // Now try to duplicate again.
1876     if (ChainEnd == Chain.begin())
1877       break;
1878     DupPred = *std::prev(ChainEnd);
1879     Removed = maybeTailDuplicateBlock(DupBB, DupPred, Chain, BlockFilter,
1880                                       PrevUnplacedBlockIt,
1881                                       DuplicatedToLPred);
1882   }
1883   // If BB was duplicated into LPred, it is now scheduled. But because it was
1884   // removed, markChainSuccessors won't be called for its chain. Instead we
1885   // call markBlockSuccessors for LPred to achieve the same effect. This must go
1886   // at the end because repeating the tail duplication can increase the number
1887   // of unscheduled predecessors.
1888   LPred = *std::prev(Chain.end());
1889   if (DuplicatedToOriginalLPred)
1890     markBlockSuccessors(Chain, LPred, LoopHeaderBB, BlockFilter);
1891   return true;
1892 }
1893 
1894 /// Tail duplicate \p BB into (some) predecessors if profitable.
1895 /// \p BB    - Basic block that may be duplicated
1896 /// \p LPred - Chosen layout predecessor of \p BB
1897 /// \p Chain - Chain to which \p LPred belongs, and \p BB will belong.
1898 /// \p BlockFilter - Set of blocks that belong to the loop being laid out.
1899 ///                  Used to identify which blocks to update predecessor
1900 ///                  counts.
1901 /// \p PrevUnplacedBlockIt - Iterator pointing to the last block that was
1902 ///                          chosen in the given order due to unnatural CFG
1903 ///                          only needed if \p BB is removed and
1904 ///                          \p PrevUnplacedBlockIt pointed to \p BB.
1905 /// \p DuplicatedToLPred - True if the block was duplicated into LPred. Will
1906 ///                        only be true if the block was removed.
1907 /// \return  - True if the block was duplicated into all preds and removed.
1908 bool MachineBlockPlacement::maybeTailDuplicateBlock(
1909     MachineBasicBlock *BB, MachineBasicBlock *LPred,
1910     const BlockChain &Chain, BlockFilterSet *BlockFilter,
1911     MachineFunction::iterator &PrevUnplacedBlockIt,
1912     bool &DuplicatedToLPred) {
1913 
1914   DuplicatedToLPred = false;
1915   DEBUG(dbgs() << "Redoing tail duplication for Succ#"
1916         << BB->getNumber() << "\n");
1917   bool IsSimple = TailDup.isSimpleBB(BB);
1918   // Blocks with single successors don't create additional fallthrough
1919   // opportunities. Don't duplicate them. TODO: When conditional exits are
1920   // analyzable, allow them to be duplicated.
1921   if (!IsSimple && BB->succ_size() == 1)
1922     return false;
1923   if (!TailDup.shouldTailDuplicate(IsSimple, *BB))
1924     return false;
1925   // This has to be a callback because none of it can be done after
1926   // BB is deleted.
1927   bool Removed = false;
1928   auto RemovalCallback =
1929       [&](MachineBasicBlock *RemBB) {
1930         // Signal to outer function
1931         Removed = true;
1932 
1933         // Conservative default.
1934         bool InWorkList = true;
1935         // Remove from the Chain and Chain Map
1936         if (BlockToChain.count(RemBB)) {
1937           BlockChain *Chain = BlockToChain[RemBB];
1938           InWorkList = Chain->UnscheduledPredecessors == 0;
1939           Chain->remove(RemBB);
1940           BlockToChain.erase(RemBB);
1941         }
1942 
1943         // Handle the unplaced block iterator
1944         if (&(*PrevUnplacedBlockIt) == RemBB) {
1945           PrevUnplacedBlockIt++;
1946         }
1947 
1948         // Handle the Work Lists
1949         if (InWorkList) {
1950           SmallVectorImpl<MachineBasicBlock *> &RemoveList = BlockWorkList;
1951           if (RemBB->isEHPad())
1952             RemoveList = EHPadWorkList;
1953           RemoveList.erase(
1954               remove_if(RemoveList,
1955                         [RemBB](MachineBasicBlock *BB) {return BB == RemBB;}),
1956               RemoveList.end());
1957         }
1958 
1959         // Handle the filter set
1960         if (BlockFilter) {
1961           BlockFilter->remove(RemBB);
1962         }
1963 
1964         // Remove the block from loop info.
1965         MLI->removeBlock(RemBB);
1966         if (RemBB == PreferredLoopExit)
1967           PreferredLoopExit = nullptr;
1968 
1969         DEBUG(dbgs() << "TailDuplicator deleted block: "
1970               << getBlockName(RemBB) << "\n");
1971       };
1972   auto RemovalCallbackRef =
1973       llvm::function_ref<void(MachineBasicBlock*)>(RemovalCallback);
1974 
1975   SmallVector<MachineBasicBlock *, 8> DuplicatedPreds;
1976   TailDup.tailDuplicateAndUpdate(IsSimple, BB, LPred,
1977                                  &DuplicatedPreds, &RemovalCallbackRef);
1978 
1979   // Update UnscheduledPredecessors to reflect tail-duplication.
1980   DuplicatedToLPred = false;
1981   for (MachineBasicBlock *Pred : DuplicatedPreds) {
1982     // We're only looking for unscheduled predecessors that match the filter.
1983     BlockChain* PredChain = BlockToChain[Pred];
1984     if (Pred == LPred)
1985       DuplicatedToLPred = true;
1986     if (Pred == LPred || (BlockFilter && !BlockFilter->count(Pred))
1987         || PredChain == &Chain)
1988       continue;
1989     for (MachineBasicBlock *NewSucc : Pred->successors()) {
1990       if (BlockFilter && !BlockFilter->count(NewSucc))
1991         continue;
1992       BlockChain *NewChain = BlockToChain[NewSucc];
1993       if (NewChain != &Chain && NewChain != PredChain)
1994         NewChain->UnscheduledPredecessors++;
1995     }
1996   }
1997   return Removed;
1998 }
1999 
2000 bool MachineBlockPlacement::runOnMachineFunction(MachineFunction &MF) {
2001   if (skipFunction(*MF.getFunction()))
2002     return false;
2003 
2004   // Check for single-block functions and skip them.
2005   if (std::next(MF.begin()) == MF.end())
2006     return false;
2007 
2008   F = &MF;
2009   MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
2010   MBFI = llvm::make_unique<BranchFolder::MBFIWrapper>(
2011       getAnalysis<MachineBlockFrequencyInfo>());
2012   MLI = &getAnalysis<MachineLoopInfo>();
2013   TII = MF.getSubtarget().getInstrInfo();
2014   TLI = MF.getSubtarget().getTargetLowering();
2015   MDT = &getAnalysis<MachineDominatorTree>();
2016 
2017   // Initialize PreferredLoopExit to nullptr here since it may never be set if
2018   // there are no MachineLoops.
2019   PreferredLoopExit = nullptr;
2020 
2021   if (TailDupPlacement) {
2022     unsigned TailDupSize = TailDuplicatePlacementThreshold;
2023     if (MF.getFunction()->optForSize())
2024       TailDupSize = 1;
2025     TailDup.initMF(MF, MBPI, /* LayoutMode */ true, TailDupSize);
2026   }
2027 
2028   assert(BlockToChain.empty());
2029 
2030   buildCFGChains();
2031 
2032   // Changing the layout can create new tail merging opportunities.
2033   TargetPassConfig *PassConfig = &getAnalysis<TargetPassConfig>();
2034   // TailMerge can create jump into if branches that make CFG irreducible for
2035   // HW that requires structured CFG.
2036   bool EnableTailMerge = !MF.getTarget().requiresStructuredCFG() &&
2037                          PassConfig->getEnableTailMerge() &&
2038                          BranchFoldPlacement;
2039   // No tail merging opportunities if the block number is less than four.
2040   if (MF.size() > 3 && EnableTailMerge) {
2041     unsigned TailMergeSize = TailDuplicatePlacementThreshold + 1;
2042     BranchFolder BF(/*EnableTailMerge=*/true, /*CommonHoist=*/false, *MBFI,
2043                     *MBPI, TailMergeSize);
2044 
2045     if (BF.OptimizeFunction(MF, TII, MF.getSubtarget().getRegisterInfo(),
2046                             getAnalysisIfAvailable<MachineModuleInfo>(), MLI,
2047                             /*AfterBlockPlacement=*/true)) {
2048       // Redo the layout if tail merging creates/removes/moves blocks.
2049       BlockToChain.clear();
2050       // Must redo the dominator tree if blocks were changed.
2051       MDT->runOnMachineFunction(MF);
2052       ChainAllocator.DestroyAll();
2053       buildCFGChains();
2054     }
2055   }
2056 
2057   optimizeBranches();
2058   alignBlocks();
2059 
2060   BlockToChain.clear();
2061   ChainAllocator.DestroyAll();
2062 
2063   if (AlignAllBlock)
2064     // Align all of the blocks in the function to a specific alignment.
2065     for (MachineBasicBlock &MBB : MF)
2066       MBB.setAlignment(AlignAllBlock);
2067   else if (AlignAllNonFallThruBlocks) {
2068     // Align all of the blocks that have no fall-through predecessors to a
2069     // specific alignment.
2070     for (auto MBI = std::next(MF.begin()), MBE = MF.end(); MBI != MBE; ++MBI) {
2071       auto LayoutPred = std::prev(MBI);
2072       if (!LayoutPred->isSuccessor(&*MBI))
2073         MBI->setAlignment(AlignAllNonFallThruBlocks);
2074     }
2075   }
2076 #ifndef NDEBUG
2077   if (ViewBlockLayoutWithBFI != GVDT_None &&
2078       (ViewBlockFreqFuncName.empty() ||
2079        F->getFunction()->getName().equals(ViewBlockFreqFuncName))) {
2080     MBFI->view(false);
2081   }
2082 #endif
2083 
2084 
2085   // We always return true as we have no way to track whether the final order
2086   // differs from the original order.
2087   return true;
2088 }
2089 
2090 namespace {
2091 /// \brief A pass to compute block placement statistics.
2092 ///
2093 /// A separate pass to compute interesting statistics for evaluating block
2094 /// placement. This is separate from the actual placement pass so that they can
2095 /// be computed in the absence of any placement transformations or when using
2096 /// alternative placement strategies.
2097 class MachineBlockPlacementStats : public MachineFunctionPass {
2098   /// \brief A handle to the branch probability pass.
2099   const MachineBranchProbabilityInfo *MBPI;
2100 
2101   /// \brief A handle to the function-wide block frequency pass.
2102   const MachineBlockFrequencyInfo *MBFI;
2103 
2104 public:
2105   static char ID; // Pass identification, replacement for typeid
2106   MachineBlockPlacementStats() : MachineFunctionPass(ID) {
2107     initializeMachineBlockPlacementStatsPass(*PassRegistry::getPassRegistry());
2108   }
2109 
2110   bool runOnMachineFunction(MachineFunction &F) override;
2111 
2112   void getAnalysisUsage(AnalysisUsage &AU) const override {
2113     AU.addRequired<MachineBranchProbabilityInfo>();
2114     AU.addRequired<MachineBlockFrequencyInfo>();
2115     AU.setPreservesAll();
2116     MachineFunctionPass::getAnalysisUsage(AU);
2117   }
2118 };
2119 }
2120 
2121 char MachineBlockPlacementStats::ID = 0;
2122 char &llvm::MachineBlockPlacementStatsID = MachineBlockPlacementStats::ID;
2123 INITIALIZE_PASS_BEGIN(MachineBlockPlacementStats, "block-placement-stats",
2124                       "Basic Block Placement Stats", false, false)
2125 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
2126 INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
2127 INITIALIZE_PASS_END(MachineBlockPlacementStats, "block-placement-stats",
2128                     "Basic Block Placement Stats", false, false)
2129 
2130 bool MachineBlockPlacementStats::runOnMachineFunction(MachineFunction &F) {
2131   // Check for single-block functions and skip them.
2132   if (std::next(F.begin()) == F.end())
2133     return false;
2134 
2135   MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
2136   MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
2137 
2138   for (MachineBasicBlock &MBB : F) {
2139     BlockFrequency BlockFreq = MBFI->getBlockFreq(&MBB);
2140     Statistic &NumBranches =
2141         (MBB.succ_size() > 1) ? NumCondBranches : NumUncondBranches;
2142     Statistic &BranchTakenFreq =
2143         (MBB.succ_size() > 1) ? CondBranchTakenFreq : UncondBranchTakenFreq;
2144     for (MachineBasicBlock *Succ : MBB.successors()) {
2145       // Skip if this successor is a fallthrough.
2146       if (MBB.isLayoutSuccessor(Succ))
2147         continue;
2148 
2149       BlockFrequency EdgeFreq =
2150           BlockFreq * MBPI->getEdgeProbability(&MBB, Succ);
2151       ++NumBranches;
2152       BranchTakenFreq += EdgeFreq.getFrequency();
2153     }
2154   }
2155 
2156   return false;
2157 }
2158