xref: /llvm-project/llvm/lib/CodeGen/MachineBlockPlacement.cpp (revision 071d0f180794f7819c44026815614ce8fa00a3bd)
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/CodeGen/MachineBasicBlock.h"
36 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
37 #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
38 #include "llvm/CodeGen/MachineDominators.h"
39 #include "llvm/CodeGen/MachineFunction.h"
40 #include "llvm/CodeGen/MachineFunctionPass.h"
41 #include "llvm/CodeGen/MachineLoopInfo.h"
42 #include "llvm/CodeGen/MachineModuleInfo.h"
43 #include "llvm/Support/Allocator.h"
44 #include "llvm/Support/CommandLine.h"
45 #include "llvm/Support/Debug.h"
46 #include "llvm/Support/raw_ostream.h"
47 #include "llvm/Target/TargetInstrInfo.h"
48 #include "llvm/Target/TargetLowering.h"
49 #include "llvm/Target/TargetSubtargetInfo.h"
50 #include <algorithm>
51 using namespace llvm;
52 
53 #define DEBUG_TYPE "block-placement"
54 
55 STATISTIC(NumCondBranches, "Number of conditional branches");
56 STATISTIC(NumUncondBranches, "Number of unconditional branches");
57 STATISTIC(CondBranchTakenFreq,
58           "Potential frequency of taking conditional branches");
59 STATISTIC(UncondBranchTakenFreq,
60           "Potential frequency of taking unconditional branches");
61 
62 static cl::opt<unsigned> AlignAllBlock("align-all-blocks",
63                                        cl::desc("Force the alignment of all "
64                                                 "blocks in the function."),
65                                        cl::init(0), cl::Hidden);
66 
67 static cl::opt<unsigned> AlignAllNonFallThruBlocks(
68     "align-all-nofallthru-blocks",
69     cl::desc("Force the alignment of all "
70              "blocks that have no fall-through predecessors (i.e. don't add "
71              "nops that are executed)."),
72     cl::init(0), cl::Hidden);
73 
74 // FIXME: Find a good default for this flag and remove the flag.
75 static cl::opt<unsigned> ExitBlockBias(
76     "block-placement-exit-block-bias",
77     cl::desc("Block frequency percentage a loop exit block needs "
78              "over the original exit to be considered the new exit."),
79     cl::init(0), cl::Hidden);
80 
81 static cl::opt<bool> OutlineOptionalBranches(
82     "outline-optional-branches",
83     cl::desc("Put completely optional branches, i.e. branches with a common "
84              "post dominator, out of line."),
85     cl::init(false), cl::Hidden);
86 
87 static cl::opt<unsigned> OutlineOptionalThreshold(
88     "outline-optional-threshold",
89     cl::desc("Don't outline optional branches that are a single block with an "
90              "instruction count below this threshold"),
91     cl::init(4), cl::Hidden);
92 
93 static cl::opt<unsigned> LoopToColdBlockRatio(
94     "loop-to-cold-block-ratio",
95     cl::desc("Outline loop blocks from loop chain if (frequency of loop) / "
96              "(frequency of block) is greater than this ratio"),
97     cl::init(5), cl::Hidden);
98 
99 static cl::opt<bool>
100     PreciseRotationCost("precise-rotation-cost",
101                         cl::desc("Model the cost of loop rotation more "
102                                  "precisely by using profile data."),
103                         cl::init(false), cl::Hidden);
104 static cl::opt<bool>
105     ForcePreciseRotationCost("force-precise-rotation-cost",
106                              cl::desc("Force the use of precise cost "
107                                       "loop rotation strategy."),
108                              cl::init(false), cl::Hidden);
109 
110 static cl::opt<unsigned> MisfetchCost(
111     "misfetch-cost",
112     cl::desc("Cost that models the probablistic risk of an instruction "
113              "misfetch due to a jump comparing to falling through, whose cost "
114              "is zero."),
115     cl::init(1), cl::Hidden);
116 
117 static cl::opt<unsigned> JumpInstCost("jump-inst-cost",
118                                       cl::desc("Cost of jump instructions."),
119                                       cl::init(1), cl::Hidden);
120 
121 static cl::opt<bool>
122 BranchFoldPlacement("branch-fold-placement",
123               cl::desc("Perform branch folding during placement. "
124                        "Reduces code size."),
125               cl::init(true), cl::Hidden);
126 
127 extern cl::opt<unsigned> StaticLikelyProb;
128 
129 namespace {
130 class BlockChain;
131 /// \brief Type for our function-wide basic block -> block chain mapping.
132 typedef DenseMap<MachineBasicBlock *, BlockChain *> BlockToChainMapType;
133 }
134 
135 namespace {
136 /// \brief A chain of blocks which will be laid out contiguously.
137 ///
138 /// This is the datastructure representing a chain of consecutive blocks that
139 /// are profitable to layout together in order to maximize fallthrough
140 /// probabilities and code locality. We also can use a block chain to represent
141 /// a sequence of basic blocks which have some external (correctness)
142 /// requirement for sequential layout.
143 ///
144 /// Chains can be built around a single basic block and can be merged to grow
145 /// them. They participate in a block-to-chain mapping, which is updated
146 /// automatically as chains are merged together.
147 class BlockChain {
148   /// \brief The sequence of blocks belonging to this chain.
149   ///
150   /// This is the sequence of blocks for a particular chain. These will be laid
151   /// out in-order within the function.
152   SmallVector<MachineBasicBlock *, 4> Blocks;
153 
154   /// \brief A handle to the function-wide basic block to block chain mapping.
155   ///
156   /// This is retained in each block chain to simplify the computation of child
157   /// block chains for SCC-formation and iteration. We store the edges to child
158   /// basic blocks, and map them back to their associated chains using this
159   /// structure.
160   BlockToChainMapType &BlockToChain;
161 
162 public:
163   /// \brief Construct a new BlockChain.
164   ///
165   /// This builds a new block chain representing a single basic block in the
166   /// function. It also registers itself as the chain that block participates
167   /// in with the BlockToChain mapping.
168   BlockChain(BlockToChainMapType &BlockToChain, MachineBasicBlock *BB)
169       : Blocks(1, BB), BlockToChain(BlockToChain), UnscheduledPredecessors(0) {
170     assert(BB && "Cannot create a chain with a null basic block");
171     BlockToChain[BB] = this;
172   }
173 
174   /// \brief Iterator over blocks within the chain.
175   typedef SmallVectorImpl<MachineBasicBlock *>::iterator iterator;
176 
177   /// \brief Beginning of blocks within the chain.
178   iterator begin() { return Blocks.begin(); }
179 
180   /// \brief End of blocks within the chain.
181   iterator end() { return Blocks.end(); }
182 
183   /// \brief Merge a block chain into this one.
184   ///
185   /// This routine merges a block chain into this one. It takes care of forming
186   /// a contiguous sequence of basic blocks, updating the edge list, and
187   /// updating the block -> chain mapping. It does not free or tear down the
188   /// old chain, but the old chain's block list is no longer valid.
189   void merge(MachineBasicBlock *BB, BlockChain *Chain) {
190     assert(BB);
191     assert(!Blocks.empty());
192 
193     // Fast path in case we don't have a chain already.
194     if (!Chain) {
195       assert(!BlockToChain[BB]);
196       Blocks.push_back(BB);
197       BlockToChain[BB] = this;
198       return;
199     }
200 
201     assert(BB == *Chain->begin());
202     assert(Chain->begin() != Chain->end());
203 
204     // Update the incoming blocks to point to this chain, and add them to the
205     // chain structure.
206     for (MachineBasicBlock *ChainBB : *Chain) {
207       Blocks.push_back(ChainBB);
208       assert(BlockToChain[ChainBB] == Chain && "Incoming blocks not in chain");
209       BlockToChain[ChainBB] = this;
210     }
211   }
212 
213 #ifndef NDEBUG
214   /// \brief Dump the blocks in this chain.
215   LLVM_DUMP_METHOD void dump() {
216     for (MachineBasicBlock *MBB : *this)
217       MBB->dump();
218   }
219 #endif // NDEBUG
220 
221   /// \brief Count of predecessors of any block within the chain which have not
222   /// yet been scheduled.  In general, we will delay scheduling this chain
223   /// until those predecessors are scheduled (or we find a sufficiently good
224   /// reason to override this heuristic.)  Note that when forming loop chains,
225   /// blocks outside the loop are ignored and treated as if they were already
226   /// scheduled.
227   ///
228   /// Note: This field is reinitialized multiple times - once for each loop,
229   /// and then once for the function as a whole.
230   unsigned UnscheduledPredecessors;
231 };
232 }
233 
234 namespace {
235 class MachineBlockPlacement : public MachineFunctionPass {
236   /// \brief A typedef for a block filter set.
237   typedef SmallPtrSet<MachineBasicBlock *, 16> BlockFilterSet;
238 
239   /// \brief A handle to the branch probability pass.
240   const MachineBranchProbabilityInfo *MBPI;
241 
242   /// \brief A handle to the function-wide block frequency pass.
243   std::unique_ptr<BranchFolder::MBFIWrapper> MBFI;
244 
245   /// \brief A handle to the loop info.
246   MachineLoopInfo *MLI;
247 
248   /// \brief A handle to the target's instruction info.
249   const TargetInstrInfo *TII;
250 
251   /// \brief A handle to the target's lowering info.
252   const TargetLoweringBase *TLI;
253 
254   /// \brief A handle to the post dominator tree.
255   MachineDominatorTree *MDT;
256 
257   /// \brief A set of blocks that are unavoidably execute, i.e. they dominate
258   /// all terminators of the MachineFunction.
259   SmallPtrSet<MachineBasicBlock *, 4> UnavoidableBlocks;
260 
261   /// \brief Allocator and owner of BlockChain structures.
262   ///
263   /// We build BlockChains lazily while processing the loop structure of
264   /// a function. To reduce malloc traffic, we allocate them using this
265   /// slab-like allocator, and destroy them after the pass completes. An
266   /// important guarantee is that this allocator produces stable pointers to
267   /// the chains.
268   SpecificBumpPtrAllocator<BlockChain> ChainAllocator;
269 
270   /// \brief Function wide BasicBlock to BlockChain mapping.
271   ///
272   /// This mapping allows efficiently moving from any given basic block to the
273   /// BlockChain it participates in, if any. We use it to, among other things,
274   /// allow implicitly defining edges between chains as the existing edges
275   /// between basic blocks.
276   DenseMap<MachineBasicBlock *, BlockChain *> BlockToChain;
277 
278   void markChainSuccessors(BlockChain &Chain, MachineBasicBlock *LoopHeaderBB,
279                            SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
280                            SmallVectorImpl<MachineBasicBlock *> &EHPadWorkList,
281                            const BlockFilterSet *BlockFilter = nullptr);
282   BranchProbability
283   collectViableSuccessors(MachineBasicBlock *BB, BlockChain &Chain,
284                           const BlockFilterSet *BlockFilter,
285                           SmallVector<MachineBasicBlock *, 4> &Successors);
286   bool shouldPredBlockBeOutlined(MachineBasicBlock *BB, MachineBasicBlock *Succ,
287                                  BlockChain &Chain,
288                                  const BlockFilterSet *BlockFilter,
289                                  BranchProbability SuccProb,
290                                  BranchProbability HotProb);
291   MachineBasicBlock *selectBestSuccessor(MachineBasicBlock *BB,
292                                          BlockChain &Chain,
293                                          const BlockFilterSet *BlockFilter);
294   MachineBasicBlock *
295   selectBestCandidateBlock(BlockChain &Chain,
296                            SmallVectorImpl<MachineBasicBlock *> &WorkList);
297   MachineBasicBlock *
298   getFirstUnplacedBlock(MachineFunction &F, const BlockChain &PlacedChain,
299                         MachineFunction::iterator &PrevUnplacedBlockIt,
300                         const BlockFilterSet *BlockFilter);
301 
302   /// \brief Add a basic block to the work list if it is apropriate.
303   ///
304   /// If the optional parameter BlockFilter is provided, only MBB
305   /// present in the set will be added to the worklist. If nullptr
306   /// is provided, no filtering occurs.
307   void fillWorkLists(MachineBasicBlock *MBB,
308                      SmallPtrSetImpl<BlockChain *> &UpdatedPreds,
309                      SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
310                      SmallVectorImpl<MachineBasicBlock *> &EHPadWorkList,
311                      const BlockFilterSet *BlockFilter);
312   void buildChain(MachineBasicBlock *BB, BlockChain &Chain,
313                   SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
314                   SmallVectorImpl<MachineBasicBlock *> &EHPadWorkList,
315                   const BlockFilterSet *BlockFilter = nullptr);
316   MachineBasicBlock *findBestLoopTop(MachineLoop &L,
317                                      const BlockFilterSet &LoopBlockSet);
318   MachineBasicBlock *findBestLoopExit(MachineFunction &F, MachineLoop &L,
319                                       const BlockFilterSet &LoopBlockSet);
320   BlockFilterSet collectLoopBlockSet(MachineFunction &F, MachineLoop &L);
321   void buildLoopChains(MachineFunction &F, MachineLoop &L);
322   void rotateLoop(BlockChain &LoopChain, MachineBasicBlock *ExitingBB,
323                   const BlockFilterSet &LoopBlockSet);
324   void rotateLoopWithProfile(BlockChain &LoopChain, MachineLoop &L,
325                              const BlockFilterSet &LoopBlockSet);
326   void collectMustExecuteBBs(MachineFunction &F);
327   void buildCFGChains(MachineFunction &F);
328   void optimizeBranches(MachineFunction &F);
329   void alignBlocks(MachineFunction &F);
330 
331 public:
332   static char ID; // Pass identification, replacement for typeid
333   MachineBlockPlacement() : MachineFunctionPass(ID) {
334     initializeMachineBlockPlacementPass(*PassRegistry::getPassRegistry());
335   }
336 
337   bool runOnMachineFunction(MachineFunction &F) override;
338 
339   void getAnalysisUsage(AnalysisUsage &AU) const override {
340     AU.addRequired<MachineBranchProbabilityInfo>();
341     AU.addRequired<MachineBlockFrequencyInfo>();
342     AU.addRequired<MachineDominatorTree>();
343     AU.addRequired<MachineLoopInfo>();
344     AU.addRequired<TargetPassConfig>();
345     MachineFunctionPass::getAnalysisUsage(AU);
346   }
347 };
348 }
349 
350 char MachineBlockPlacement::ID = 0;
351 char &llvm::MachineBlockPlacementID = MachineBlockPlacement::ID;
352 INITIALIZE_PASS_BEGIN(MachineBlockPlacement, "block-placement",
353                       "Branch Probability Basic Block Placement", false, false)
354 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
355 INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
356 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
357 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
358 INITIALIZE_PASS_END(MachineBlockPlacement, "block-placement",
359                     "Branch Probability Basic Block Placement", false, false)
360 
361 #ifndef NDEBUG
362 /// \brief Helper to print the name of a MBB.
363 ///
364 /// Only used by debug logging.
365 static std::string getBlockName(MachineBasicBlock *BB) {
366   std::string Result;
367   raw_string_ostream OS(Result);
368   OS << "BB#" << BB->getNumber();
369   OS << " ('" << BB->getName() << "')";
370   OS.flush();
371   return Result;
372 }
373 #endif
374 
375 /// \brief Mark a chain's successors as having one fewer preds.
376 ///
377 /// When a chain is being merged into the "placed" chain, this routine will
378 /// quickly walk the successors of each block in the chain and mark them as
379 /// having one fewer active predecessor. It also adds any successors of this
380 /// chain which reach the zero-predecessor state to the worklist passed in.
381 void MachineBlockPlacement::markChainSuccessors(
382     BlockChain &Chain, MachineBasicBlock *LoopHeaderBB,
383     SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
384     SmallVectorImpl<MachineBasicBlock *> &EHPadWorkList,
385     const BlockFilterSet *BlockFilter) {
386   // Walk all the blocks in this chain, marking their successors as having
387   // a predecessor placed.
388   for (MachineBasicBlock *MBB : Chain) {
389     // Add any successors for which this is the only un-placed in-loop
390     // predecessor to the worklist as a viable candidate for CFG-neutral
391     // placement. No subsequent placement of this block will violate the CFG
392     // shape, so we get to use heuristics to choose a favorable placement.
393     for (MachineBasicBlock *Succ : MBB->successors()) {
394       if (BlockFilter && !BlockFilter->count(Succ))
395         continue;
396       BlockChain &SuccChain = *BlockToChain[Succ];
397       // Disregard edges within a fixed chain, or edges to the loop header.
398       if (&Chain == &SuccChain || Succ == LoopHeaderBB)
399         continue;
400 
401       // This is a cross-chain edge that is within the loop, so decrement the
402       // loop predecessor count of the destination chain.
403       if (SuccChain.UnscheduledPredecessors == 0 ||
404           --SuccChain.UnscheduledPredecessors > 0)
405         continue;
406 
407       auto *MBB = *SuccChain.begin();
408       if (MBB->isEHPad())
409         EHPadWorkList.push_back(MBB);
410       else
411         BlockWorkList.push_back(MBB);
412     }
413   }
414 }
415 
416 /// This helper function collects the set of successors of block
417 /// \p BB that are allowed to be its layout successors, and return
418 /// the total branch probability of edges from \p BB to those
419 /// blocks.
420 BranchProbability MachineBlockPlacement::collectViableSuccessors(
421     MachineBasicBlock *BB, BlockChain &Chain, const BlockFilterSet *BlockFilter,
422     SmallVector<MachineBasicBlock *, 4> &Successors) {
423   // Adjust edge probabilities by excluding edges pointing to blocks that is
424   // either not in BlockFilter or is already in the current chain. Consider the
425   // following CFG:
426   //
427   //     --->A
428   //     |  / \
429   //     | B   C
430   //     |  \ / \
431   //     ----D   E
432   //
433   // Assume A->C is very hot (>90%), and C->D has a 50% probability, then after
434   // A->C is chosen as a fall-through, D won't be selected as a successor of C
435   // due to CFG constraint (the probability of C->D is not greater than
436   // HotProb to break top-oorder). If we exclude E that is not in BlockFilter
437   // when calculating the  probability of C->D, D will be selected and we
438   // will get A C D B as the layout of this loop.
439   auto AdjustedSumProb = BranchProbability::getOne();
440   for (MachineBasicBlock *Succ : BB->successors()) {
441     bool SkipSucc = false;
442     if (Succ->isEHPad() || (BlockFilter && !BlockFilter->count(Succ))) {
443       SkipSucc = true;
444     } else {
445       BlockChain *SuccChain = BlockToChain[Succ];
446       if (SuccChain == &Chain) {
447         SkipSucc = true;
448       } else if (Succ != *SuccChain->begin()) {
449         DEBUG(dbgs() << "    " << getBlockName(Succ) << " -> Mid chain!\n");
450         continue;
451       }
452     }
453     if (SkipSucc)
454       AdjustedSumProb -= MBPI->getEdgeProbability(BB, Succ);
455     else
456       Successors.push_back(Succ);
457   }
458 
459   return AdjustedSumProb;
460 }
461 
462 /// The helper function returns the branch probability that is adjusted
463 /// or normalized over the new total \p AdjustedSumProb.
464 
465 static BranchProbability
466 getAdjustedProbability(BranchProbability OrigProb,
467                        BranchProbability AdjustedSumProb) {
468   BranchProbability SuccProb;
469   uint32_t SuccProbN = OrigProb.getNumerator();
470   uint32_t SuccProbD = AdjustedSumProb.getNumerator();
471   if (SuccProbN >= SuccProbD)
472     SuccProb = BranchProbability::getOne();
473   else
474     SuccProb = BranchProbability(SuccProbN, SuccProbD);
475 
476   return SuccProb;
477 }
478 
479 /// When the option OutlineOptionalBranches is on, this method
480 /// checks if the fallthrough candidate block \p Succ (of block
481 /// \p BB) also has other unscheduled predecessor blocks which
482 /// are also successors of \p BB (forming triagular shape CFG).
483 /// If none of such predecessors are small, it returns true.
484 /// The caller can choose to select \p Succ as the layout successors
485 /// so that \p Succ's predecessors (optional branches) can be
486 /// outlined.
487 /// FIXME: fold this with more general layout cost analysis.
488 bool MachineBlockPlacement::shouldPredBlockBeOutlined(
489     MachineBasicBlock *BB, MachineBasicBlock *Succ, BlockChain &Chain,
490     const BlockFilterSet *BlockFilter, BranchProbability SuccProb,
491     BranchProbability HotProb) {
492   if (!OutlineOptionalBranches)
493     return false;
494   // If we outline optional branches, look whether Succ is unavoidable, i.e.
495   // dominates all terminators of the MachineFunction. If it does, other
496   // successors must be optional. Don't do this for cold branches.
497   if (SuccProb > HotProb.getCompl() && UnavoidableBlocks.count(Succ) > 0) {
498     for (MachineBasicBlock *Pred : Succ->predecessors()) {
499       // Check whether there is an unplaced optional branch.
500       if (Pred == Succ || (BlockFilter && !BlockFilter->count(Pred)) ||
501           BlockToChain[Pred] == &Chain)
502         continue;
503       // Check whether the optional branch has exactly one BB.
504       if (Pred->pred_size() > 1 || *Pred->pred_begin() != BB)
505         continue;
506       // Check whether the optional branch is small.
507       if (Pred->size() < OutlineOptionalThreshold)
508         return false;
509     }
510     return true;
511   } else
512     return false;
513 }
514 
515 /// \brief Select the best successor for a block.
516 ///
517 /// This looks across all successors of a particular block and attempts to
518 /// select the "best" one to be the layout successor. It only considers direct
519 /// successors which also pass the block filter. It will attempt to avoid
520 /// breaking CFG structure, but cave and break such structures in the case of
521 /// very hot successor edges.
522 ///
523 /// \returns The best successor block found, or null if none are viable.
524 MachineBasicBlock *
525 MachineBlockPlacement::selectBestSuccessor(MachineBasicBlock *BB,
526                                            BlockChain &Chain,
527                                            const BlockFilterSet *BlockFilter) {
528   const BranchProbability HotProb(StaticLikelyProb, 100);
529 
530   MachineBasicBlock *BestSucc = nullptr;
531   auto BestProb = BranchProbability::getZero();
532 
533   SmallVector<MachineBasicBlock *, 4> Successors;
534   auto AdjustedSumProb =
535       collectViableSuccessors(BB, Chain, BlockFilter, Successors);
536 
537   DEBUG(dbgs() << "Attempting merge from: " << getBlockName(BB) << "\n");
538   for (MachineBasicBlock *Succ : Successors) {
539     auto RealSuccProb = MBPI->getEdgeProbability(BB, Succ);
540     BranchProbability SuccProb =
541         getAdjustedProbability(RealSuccProb, AdjustedSumProb);
542 
543     // This heuristic is off by default.
544     if (shouldPredBlockBeOutlined(BB, Succ, Chain, BlockFilter, SuccProb,
545                                   HotProb))
546       return Succ;
547 
548     // Only consider successors which are either "hot", or wouldn't violate
549     // any CFG constraints.
550     BlockChain &SuccChain = *BlockToChain[Succ];
551     if (SuccChain.UnscheduledPredecessors != 0) {
552       if (SuccProb < HotProb) {
553         DEBUG(dbgs() << "    " << getBlockName(Succ) << " -> " << SuccProb
554                      << " (prob) (CFG conflict)\n");
555         continue;
556       }
557 
558       // Make sure that a hot successor doesn't have a globally more
559       // important predecessor.
560       BlockFrequency CandidateEdgeFreq = MBFI->getBlockFreq(BB) * RealSuccProb;
561       bool BadCFGConflict = false;
562       for (MachineBasicBlock *Pred : Succ->predecessors()) {
563         if (Pred == Succ || BlockToChain[Pred] == &SuccChain ||
564             (BlockFilter && !BlockFilter->count(Pred)) ||
565             BlockToChain[Pred] == &Chain)
566           continue;
567         BlockFrequency PredEdgeFreq =
568             MBFI->getBlockFreq(Pred) * MBPI->getEdgeProbability(Pred, Succ);
569         // A   B
570         //  \ /
571         //   C
572         // We layout ACB iff  A.freq > C.freq * HotProb
573         //               i.e. A.freq > A.freq * HotProb + B.freq * HotProb
574         //               i.e. A.freq * (1 - HotProb) > B.freq * HotProb
575         // A: CandidateEdge
576         // B: PredEdge
577         if (PredEdgeFreq * HotProb >= CandidateEdgeFreq * HotProb.getCompl()) {
578           BadCFGConflict = true;
579           break;
580         }
581       }
582       if (BadCFGConflict) {
583         DEBUG(dbgs() << "    " << getBlockName(Succ) << " -> " << SuccProb
584                      << " (prob) (non-cold CFG conflict)\n");
585         continue;
586       }
587     }
588 
589     DEBUG(dbgs() << "    " << getBlockName(Succ) << " -> " << SuccProb
590                  << " (prob)"
591                  << (SuccChain.UnscheduledPredecessors != 0 ? " (CFG break)" : "")
592                  << "\n");
593     if (BestSucc && BestProb >= SuccProb)
594       continue;
595     BestSucc = Succ;
596     BestProb = SuccProb;
597   }
598   return BestSucc;
599 }
600 
601 /// \brief Select the best block from a worklist.
602 ///
603 /// This looks through the provided worklist as a list of candidate basic
604 /// blocks and select the most profitable one to place. The definition of
605 /// profitable only really makes sense in the context of a loop. This returns
606 /// the most frequently visited block in the worklist, which in the case of
607 /// a loop, is the one most desirable to be physically close to the rest of the
608 /// loop body in order to improve icache behavior.
609 ///
610 /// \returns The best block found, or null if none are viable.
611 MachineBasicBlock *MachineBlockPlacement::selectBestCandidateBlock(
612     BlockChain &Chain, SmallVectorImpl<MachineBasicBlock *> &WorkList) {
613   // Once we need to walk the worklist looking for a candidate, cleanup the
614   // worklist of already placed entries.
615   // FIXME: If this shows up on profiles, it could be folded (at the cost of
616   // some code complexity) into the loop below.
617   WorkList.erase(std::remove_if(WorkList.begin(), WorkList.end(),
618                                 [&](MachineBasicBlock *BB) {
619                                   return BlockToChain.lookup(BB) == &Chain;
620                                 }),
621                  WorkList.end());
622 
623   if (WorkList.empty())
624     return nullptr;
625 
626   bool IsEHPad = WorkList[0]->isEHPad();
627 
628   MachineBasicBlock *BestBlock = nullptr;
629   BlockFrequency BestFreq;
630   for (MachineBasicBlock *MBB : WorkList) {
631     assert(MBB->isEHPad() == IsEHPad);
632 
633     BlockChain &SuccChain = *BlockToChain[MBB];
634     if (&SuccChain == &Chain)
635       continue;
636 
637     assert(SuccChain.UnscheduledPredecessors == 0 && "Found CFG-violating block");
638 
639     BlockFrequency CandidateFreq = MBFI->getBlockFreq(MBB);
640     DEBUG(dbgs() << "    " << getBlockName(MBB) << " -> ";
641           MBFI->printBlockFreq(dbgs(), CandidateFreq) << " (freq)\n");
642 
643     // For ehpad, we layout the least probable first as to avoid jumping back
644     // from least probable landingpads to more probable ones.
645     //
646     // FIXME: Using probability is probably (!) not the best way to achieve
647     // this. We should probably have a more principled approach to layout
648     // cleanup code.
649     //
650     // The goal is to get:
651     //
652     //                 +--------------------------+
653     //                 |                          V
654     // InnerLp -> InnerCleanup    OuterLp -> OuterCleanup -> Resume
655     //
656     // Rather than:
657     //
658     //                 +-------------------------------------+
659     //                 V                                     |
660     // OuterLp -> OuterCleanup -> Resume     InnerLp -> InnerCleanup
661     if (BestBlock && (IsEHPad ^ (BestFreq >= CandidateFreq)))
662       continue;
663 
664     BestBlock = MBB;
665     BestFreq = CandidateFreq;
666   }
667 
668   return BestBlock;
669 }
670 
671 /// \brief Retrieve the first unplaced basic block.
672 ///
673 /// This routine is called when we are unable to use the CFG to walk through
674 /// all of the basic blocks and form a chain due to unnatural loops in the CFG.
675 /// We walk through the function's blocks in order, starting from the
676 /// LastUnplacedBlockIt. We update this iterator on each call to avoid
677 /// re-scanning the entire sequence on repeated calls to this routine.
678 MachineBasicBlock *MachineBlockPlacement::getFirstUnplacedBlock(
679     MachineFunction &F, const BlockChain &PlacedChain,
680     MachineFunction::iterator &PrevUnplacedBlockIt,
681     const BlockFilterSet *BlockFilter) {
682   for (MachineFunction::iterator I = PrevUnplacedBlockIt, E = F.end(); I != E;
683        ++I) {
684     if (BlockFilter && !BlockFilter->count(&*I))
685       continue;
686     if (BlockToChain[&*I] != &PlacedChain) {
687       PrevUnplacedBlockIt = I;
688       // Now select the head of the chain to which the unplaced block belongs
689       // as the block to place. This will force the entire chain to be placed,
690       // and satisfies the requirements of merging chains.
691       return *BlockToChain[&*I]->begin();
692     }
693   }
694   return nullptr;
695 }
696 
697 void MachineBlockPlacement::fillWorkLists(
698     MachineBasicBlock *MBB,
699     SmallPtrSetImpl<BlockChain *> &UpdatedPreds,
700     SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
701     SmallVectorImpl<MachineBasicBlock *> &EHPadWorkList,
702     const BlockFilterSet *BlockFilter = nullptr) {
703   BlockChain &Chain = *BlockToChain[MBB];
704   if (!UpdatedPreds.insert(&Chain).second)
705     return;
706 
707   assert(Chain.UnscheduledPredecessors == 0);
708   for (MachineBasicBlock *ChainBB : Chain) {
709     assert(BlockToChain[ChainBB] == &Chain);
710     for (MachineBasicBlock *Pred : ChainBB->predecessors()) {
711       if (BlockFilter && !BlockFilter->count(Pred))
712         continue;
713       if (BlockToChain[Pred] == &Chain)
714         continue;
715       ++Chain.UnscheduledPredecessors;
716     }
717   }
718 
719   if (Chain.UnscheduledPredecessors != 0)
720     return;
721 
722   MBB = *Chain.begin();
723   if (MBB->isEHPad())
724     EHPadWorkList.push_back(MBB);
725   else
726     BlockWorkList.push_back(MBB);
727 }
728 
729 void MachineBlockPlacement::buildChain(
730     MachineBasicBlock *BB, BlockChain &Chain,
731     SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
732     SmallVectorImpl<MachineBasicBlock *> &EHPadWorkList,
733     const BlockFilterSet *BlockFilter) {
734   assert(BB);
735   assert(BlockToChain[BB] == &Chain);
736   MachineFunction &F = *BB->getParent();
737   MachineFunction::iterator PrevUnplacedBlockIt = F.begin();
738 
739   MachineBasicBlock *LoopHeaderBB = BB;
740   markChainSuccessors(Chain, LoopHeaderBB, BlockWorkList, EHPadWorkList,
741                       BlockFilter);
742   BB = *std::prev(Chain.end());
743   for (;;) {
744     assert(BB);
745     assert(BlockToChain[BB] == &Chain);
746     assert(*std::prev(Chain.end()) == BB);
747 
748     // Look for the best viable successor if there is one to place immediately
749     // after this block.
750     MachineBasicBlock *BestSucc = selectBestSuccessor(BB, Chain, BlockFilter);
751 
752     // If an immediate successor isn't available, look for the best viable
753     // block among those we've identified as not violating the loop's CFG at
754     // this point. This won't be a fallthrough, but it will increase locality.
755     if (!BestSucc)
756       BestSucc = selectBestCandidateBlock(Chain, BlockWorkList);
757     if (!BestSucc)
758       BestSucc = selectBestCandidateBlock(Chain, EHPadWorkList);
759 
760     if (!BestSucc) {
761       BestSucc =
762           getFirstUnplacedBlock(F, Chain, PrevUnplacedBlockIt, BlockFilter);
763       if (!BestSucc)
764         break;
765 
766       DEBUG(dbgs() << "Unnatural loop CFG detected, forcibly merging the "
767                       "layout successor until the CFG reduces\n");
768     }
769 
770     // Place this block, updating the datastructures to reflect its placement.
771     BlockChain &SuccChain = *BlockToChain[BestSucc];
772     // Zero out UnscheduledPredecessors for the successor we're about to merge in case
773     // we selected a successor that didn't fit naturally into the CFG.
774     SuccChain.UnscheduledPredecessors = 0;
775     DEBUG(dbgs() << "Merging from " << getBlockName(BB) << " to "
776                  << getBlockName(BestSucc) << "\n");
777     markChainSuccessors(SuccChain, LoopHeaderBB, BlockWorkList, EHPadWorkList,
778                         BlockFilter);
779     Chain.merge(BestSucc, &SuccChain);
780     BB = *std::prev(Chain.end());
781   }
782 
783   DEBUG(dbgs() << "Finished forming chain for header block "
784                << getBlockName(*Chain.begin()) << "\n");
785 }
786 
787 /// \brief Find the best loop top block for layout.
788 ///
789 /// Look for a block which is strictly better than the loop header for laying
790 /// out at the top of the loop. This looks for one and only one pattern:
791 /// a latch block with no conditional exit. This block will cause a conditional
792 /// jump around it or will be the bottom of the loop if we lay it out in place,
793 /// but if it it doesn't end up at the bottom of the loop for any reason,
794 /// rotation alone won't fix it. Because such a block will always result in an
795 /// unconditional jump (for the backedge) rotating it in front of the loop
796 /// header is always profitable.
797 MachineBasicBlock *
798 MachineBlockPlacement::findBestLoopTop(MachineLoop &L,
799                                        const BlockFilterSet &LoopBlockSet) {
800   // Check that the header hasn't been fused with a preheader block due to
801   // crazy branches. If it has, we need to start with the header at the top to
802   // prevent pulling the preheader into the loop body.
803   BlockChain &HeaderChain = *BlockToChain[L.getHeader()];
804   if (!LoopBlockSet.count(*HeaderChain.begin()))
805     return L.getHeader();
806 
807   DEBUG(dbgs() << "Finding best loop top for: " << getBlockName(L.getHeader())
808                << "\n");
809 
810   BlockFrequency BestPredFreq;
811   MachineBasicBlock *BestPred = nullptr;
812   for (MachineBasicBlock *Pred : L.getHeader()->predecessors()) {
813     if (!LoopBlockSet.count(Pred))
814       continue;
815     DEBUG(dbgs() << "    header pred: " << getBlockName(Pred) << ", "
816                  << Pred->succ_size() << " successors, ";
817           MBFI->printBlockFreq(dbgs(), Pred) << " freq\n");
818     if (Pred->succ_size() > 1)
819       continue;
820 
821     BlockFrequency PredFreq = MBFI->getBlockFreq(Pred);
822     if (!BestPred || PredFreq > BestPredFreq ||
823         (!(PredFreq < BestPredFreq) &&
824          Pred->isLayoutSuccessor(L.getHeader()))) {
825       BestPred = Pred;
826       BestPredFreq = PredFreq;
827     }
828   }
829 
830   // If no direct predecessor is fine, just use the loop header.
831   if (!BestPred) {
832     DEBUG(dbgs() << "    final top unchanged\n");
833     return L.getHeader();
834   }
835 
836   // Walk backwards through any straight line of predecessors.
837   while (BestPred->pred_size() == 1 &&
838          (*BestPred->pred_begin())->succ_size() == 1 &&
839          *BestPred->pred_begin() != L.getHeader())
840     BestPred = *BestPred->pred_begin();
841 
842   DEBUG(dbgs() << "    final top: " << getBlockName(BestPred) << "\n");
843   return BestPred;
844 }
845 
846 /// \brief Find the best loop exiting block for layout.
847 ///
848 /// This routine implements the logic to analyze the loop looking for the best
849 /// block to layout at the top of the loop. Typically this is done to maximize
850 /// fallthrough opportunities.
851 MachineBasicBlock *
852 MachineBlockPlacement::findBestLoopExit(MachineFunction &F, MachineLoop &L,
853                                         const BlockFilterSet &LoopBlockSet) {
854   // We don't want to layout the loop linearly in all cases. If the loop header
855   // is just a normal basic block in the loop, we want to look for what block
856   // within the loop is the best one to layout at the top. However, if the loop
857   // header has be pre-merged into a chain due to predecessors not having
858   // analyzable branches, *and* the predecessor it is merged with is *not* part
859   // of the loop, rotating the header into the middle of the loop will create
860   // a non-contiguous range of blocks which is Very Bad. So start with the
861   // header and only rotate if safe.
862   BlockChain &HeaderChain = *BlockToChain[L.getHeader()];
863   if (!LoopBlockSet.count(*HeaderChain.begin()))
864     return nullptr;
865 
866   BlockFrequency BestExitEdgeFreq;
867   unsigned BestExitLoopDepth = 0;
868   MachineBasicBlock *ExitingBB = nullptr;
869   // If there are exits to outer loops, loop rotation can severely limit
870   // fallthrough opportunites unless it selects such an exit. Keep a set of
871   // blocks where rotating to exit with that block will reach an outer loop.
872   SmallPtrSet<MachineBasicBlock *, 4> BlocksExitingToOuterLoop;
873 
874   DEBUG(dbgs() << "Finding best loop exit for: " << getBlockName(L.getHeader())
875                << "\n");
876   for (MachineBasicBlock *MBB : L.getBlocks()) {
877     BlockChain &Chain = *BlockToChain[MBB];
878     // Ensure that this block is at the end of a chain; otherwise it could be
879     // mid-way through an inner loop or a successor of an unanalyzable branch.
880     if (MBB != *std::prev(Chain.end()))
881       continue;
882 
883     // Now walk the successors. We need to establish whether this has a viable
884     // exiting successor and whether it has a viable non-exiting successor.
885     // We store the old exiting state and restore it if a viable looping
886     // successor isn't found.
887     MachineBasicBlock *OldExitingBB = ExitingBB;
888     BlockFrequency OldBestExitEdgeFreq = BestExitEdgeFreq;
889     bool HasLoopingSucc = false;
890     for (MachineBasicBlock *Succ : MBB->successors()) {
891       if (Succ->isEHPad())
892         continue;
893       if (Succ == MBB)
894         continue;
895       BlockChain &SuccChain = *BlockToChain[Succ];
896       // Don't split chains, either this chain or the successor's chain.
897       if (&Chain == &SuccChain) {
898         DEBUG(dbgs() << "    exiting: " << getBlockName(MBB) << " -> "
899                      << getBlockName(Succ) << " (chain conflict)\n");
900         continue;
901       }
902 
903       auto SuccProb = MBPI->getEdgeProbability(MBB, Succ);
904       if (LoopBlockSet.count(Succ)) {
905         DEBUG(dbgs() << "    looping: " << getBlockName(MBB) << " -> "
906                      << getBlockName(Succ) << " (" << SuccProb << ")\n");
907         HasLoopingSucc = true;
908         continue;
909       }
910 
911       unsigned SuccLoopDepth = 0;
912       if (MachineLoop *ExitLoop = MLI->getLoopFor(Succ)) {
913         SuccLoopDepth = ExitLoop->getLoopDepth();
914         if (ExitLoop->contains(&L))
915           BlocksExitingToOuterLoop.insert(MBB);
916       }
917 
918       BlockFrequency ExitEdgeFreq = MBFI->getBlockFreq(MBB) * SuccProb;
919       DEBUG(dbgs() << "    exiting: " << getBlockName(MBB) << " -> "
920                    << getBlockName(Succ) << " [L:" << SuccLoopDepth << "] (";
921             MBFI->printBlockFreq(dbgs(), ExitEdgeFreq) << ")\n");
922       // Note that we bias this toward an existing layout successor to retain
923       // incoming order in the absence of better information. The exit must have
924       // a frequency higher than the current exit before we consider breaking
925       // the layout.
926       BranchProbability Bias(100 - ExitBlockBias, 100);
927       if (!ExitingBB || SuccLoopDepth > BestExitLoopDepth ||
928           ExitEdgeFreq > BestExitEdgeFreq ||
929           (MBB->isLayoutSuccessor(Succ) &&
930            !(ExitEdgeFreq < BestExitEdgeFreq * Bias))) {
931         BestExitEdgeFreq = ExitEdgeFreq;
932         ExitingBB = MBB;
933       }
934     }
935 
936     if (!HasLoopingSucc) {
937       // Restore the old exiting state, no viable looping successor was found.
938       ExitingBB = OldExitingBB;
939       BestExitEdgeFreq = OldBestExitEdgeFreq;
940     }
941   }
942   // Without a candidate exiting block or with only a single block in the
943   // loop, just use the loop header to layout the loop.
944   if (!ExitingBB || L.getNumBlocks() == 1)
945     return nullptr;
946 
947   // Also, if we have exit blocks which lead to outer loops but didn't select
948   // one of them as the exiting block we are rotating toward, disable loop
949   // rotation altogether.
950   if (!BlocksExitingToOuterLoop.empty() &&
951       !BlocksExitingToOuterLoop.count(ExitingBB))
952     return nullptr;
953 
954   DEBUG(dbgs() << "  Best exiting block: " << getBlockName(ExitingBB) << "\n");
955   return ExitingBB;
956 }
957 
958 /// \brief Attempt to rotate an exiting block to the bottom of the loop.
959 ///
960 /// Once we have built a chain, try to rotate it to line up the hot exit block
961 /// with fallthrough out of the loop if doing so doesn't introduce unnecessary
962 /// branches. For example, if the loop has fallthrough into its header and out
963 /// of its bottom already, don't rotate it.
964 void MachineBlockPlacement::rotateLoop(BlockChain &LoopChain,
965                                        MachineBasicBlock *ExitingBB,
966                                        const BlockFilterSet &LoopBlockSet) {
967   if (!ExitingBB)
968     return;
969 
970   MachineBasicBlock *Top = *LoopChain.begin();
971   bool ViableTopFallthrough = false;
972   for (MachineBasicBlock *Pred : Top->predecessors()) {
973     BlockChain *PredChain = BlockToChain[Pred];
974     if (!LoopBlockSet.count(Pred) &&
975         (!PredChain || Pred == *std::prev(PredChain->end()))) {
976       ViableTopFallthrough = true;
977       break;
978     }
979   }
980 
981   // If the header has viable fallthrough, check whether the current loop
982   // bottom is a viable exiting block. If so, bail out as rotating will
983   // introduce an unnecessary branch.
984   if (ViableTopFallthrough) {
985     MachineBasicBlock *Bottom = *std::prev(LoopChain.end());
986     for (MachineBasicBlock *Succ : Bottom->successors()) {
987       BlockChain *SuccChain = BlockToChain[Succ];
988       if (!LoopBlockSet.count(Succ) &&
989           (!SuccChain || Succ == *SuccChain->begin()))
990         return;
991     }
992   }
993 
994   BlockChain::iterator ExitIt =
995       std::find(LoopChain.begin(), LoopChain.end(), ExitingBB);
996   if (ExitIt == LoopChain.end())
997     return;
998 
999   std::rotate(LoopChain.begin(), std::next(ExitIt), LoopChain.end());
1000 }
1001 
1002 /// \brief Attempt to rotate a loop based on profile data to reduce branch cost.
1003 ///
1004 /// With profile data, we can determine the cost in terms of missed fall through
1005 /// opportunities when rotating a loop chain and select the best rotation.
1006 /// Basically, there are three kinds of cost to consider for each rotation:
1007 ///    1. The possibly missed fall through edge (if it exists) from BB out of
1008 ///    the loop to the loop header.
1009 ///    2. The possibly missed fall through edges (if they exist) from the loop
1010 ///    exits to BB out of the loop.
1011 ///    3. The missed fall through edge (if it exists) from the last BB to the
1012 ///    first BB in the loop chain.
1013 ///  Therefore, the cost for a given rotation is the sum of costs listed above.
1014 ///  We select the best rotation with the smallest cost.
1015 void MachineBlockPlacement::rotateLoopWithProfile(
1016     BlockChain &LoopChain, MachineLoop &L, const BlockFilterSet &LoopBlockSet) {
1017   auto HeaderBB = L.getHeader();
1018   auto HeaderIter = std::find(LoopChain.begin(), LoopChain.end(), HeaderBB);
1019   auto RotationPos = LoopChain.end();
1020 
1021   BlockFrequency SmallestRotationCost = BlockFrequency::getMaxFrequency();
1022 
1023   // A utility lambda that scales up a block frequency by dividing it by a
1024   // branch probability which is the reciprocal of the scale.
1025   auto ScaleBlockFrequency = [](BlockFrequency Freq,
1026                                 unsigned Scale) -> BlockFrequency {
1027     if (Scale == 0)
1028       return 0;
1029     // Use operator / between BlockFrequency and BranchProbability to implement
1030     // saturating multiplication.
1031     return Freq / BranchProbability(1, Scale);
1032   };
1033 
1034   // Compute the cost of the missed fall-through edge to the loop header if the
1035   // chain head is not the loop header. As we only consider natural loops with
1036   // single header, this computation can be done only once.
1037   BlockFrequency HeaderFallThroughCost(0);
1038   for (auto *Pred : HeaderBB->predecessors()) {
1039     BlockChain *PredChain = BlockToChain[Pred];
1040     if (!LoopBlockSet.count(Pred) &&
1041         (!PredChain || Pred == *std::prev(PredChain->end()))) {
1042       auto EdgeFreq =
1043           MBFI->getBlockFreq(Pred) * MBPI->getEdgeProbability(Pred, HeaderBB);
1044       auto FallThruCost = ScaleBlockFrequency(EdgeFreq, MisfetchCost);
1045       // If the predecessor has only an unconditional jump to the header, we
1046       // need to consider the cost of this jump.
1047       if (Pred->succ_size() == 1)
1048         FallThruCost += ScaleBlockFrequency(EdgeFreq, JumpInstCost);
1049       HeaderFallThroughCost = std::max(HeaderFallThroughCost, FallThruCost);
1050     }
1051   }
1052 
1053   // Here we collect all exit blocks in the loop, and for each exit we find out
1054   // its hottest exit edge. For each loop rotation, we define the loop exit cost
1055   // as the sum of frequencies of exit edges we collect here, excluding the exit
1056   // edge from the tail of the loop chain.
1057   SmallVector<std::pair<MachineBasicBlock *, BlockFrequency>, 4> ExitsWithFreq;
1058   for (auto BB : LoopChain) {
1059     auto LargestExitEdgeProb = BranchProbability::getZero();
1060     for (auto *Succ : BB->successors()) {
1061       BlockChain *SuccChain = BlockToChain[Succ];
1062       if (!LoopBlockSet.count(Succ) &&
1063           (!SuccChain || Succ == *SuccChain->begin())) {
1064         auto SuccProb = MBPI->getEdgeProbability(BB, Succ);
1065         LargestExitEdgeProb = std::max(LargestExitEdgeProb, SuccProb);
1066       }
1067     }
1068     if (LargestExitEdgeProb > BranchProbability::getZero()) {
1069       auto ExitFreq = MBFI->getBlockFreq(BB) * LargestExitEdgeProb;
1070       ExitsWithFreq.emplace_back(BB, ExitFreq);
1071     }
1072   }
1073 
1074   // In this loop we iterate every block in the loop chain and calculate the
1075   // cost assuming the block is the head of the loop chain. When the loop ends,
1076   // we should have found the best candidate as the loop chain's head.
1077   for (auto Iter = LoopChain.begin(), TailIter = std::prev(LoopChain.end()),
1078             EndIter = LoopChain.end();
1079        Iter != EndIter; Iter++, TailIter++) {
1080     // TailIter is used to track the tail of the loop chain if the block we are
1081     // checking (pointed by Iter) is the head of the chain.
1082     if (TailIter == LoopChain.end())
1083       TailIter = LoopChain.begin();
1084 
1085     auto TailBB = *TailIter;
1086 
1087     // Calculate the cost by putting this BB to the top.
1088     BlockFrequency Cost = 0;
1089 
1090     // If the current BB is the loop header, we need to take into account the
1091     // cost of the missed fall through edge from outside of the loop to the
1092     // header.
1093     if (Iter != HeaderIter)
1094       Cost += HeaderFallThroughCost;
1095 
1096     // Collect the loop exit cost by summing up frequencies of all exit edges
1097     // except the one from the chain tail.
1098     for (auto &ExitWithFreq : ExitsWithFreq)
1099       if (TailBB != ExitWithFreq.first)
1100         Cost += ExitWithFreq.second;
1101 
1102     // The cost of breaking the once fall-through edge from the tail to the top
1103     // of the loop chain. Here we need to consider three cases:
1104     // 1. If the tail node has only one successor, then we will get an
1105     //    additional jmp instruction. So the cost here is (MisfetchCost +
1106     //    JumpInstCost) * tail node frequency.
1107     // 2. If the tail node has two successors, then we may still get an
1108     //    additional jmp instruction if the layout successor after the loop
1109     //    chain is not its CFG successor. Note that the more frequently executed
1110     //    jmp instruction will be put ahead of the other one. Assume the
1111     //    frequency of those two branches are x and y, where x is the frequency
1112     //    of the edge to the chain head, then the cost will be
1113     //    (x * MisfetechCost + min(x, y) * JumpInstCost) * tail node frequency.
1114     // 3. If the tail node has more than two successors (this rarely happens),
1115     //    we won't consider any additional cost.
1116     if (TailBB->isSuccessor(*Iter)) {
1117       auto TailBBFreq = MBFI->getBlockFreq(TailBB);
1118       if (TailBB->succ_size() == 1)
1119         Cost += ScaleBlockFrequency(TailBBFreq.getFrequency(),
1120                                     MisfetchCost + JumpInstCost);
1121       else if (TailBB->succ_size() == 2) {
1122         auto TailToHeadProb = MBPI->getEdgeProbability(TailBB, *Iter);
1123         auto TailToHeadFreq = TailBBFreq * TailToHeadProb;
1124         auto ColderEdgeFreq = TailToHeadProb > BranchProbability(1, 2)
1125                                   ? TailBBFreq * TailToHeadProb.getCompl()
1126                                   : TailToHeadFreq;
1127         Cost += ScaleBlockFrequency(TailToHeadFreq, MisfetchCost) +
1128                 ScaleBlockFrequency(ColderEdgeFreq, JumpInstCost);
1129       }
1130     }
1131 
1132     DEBUG(dbgs() << "The cost of loop rotation by making " << getBlockName(*Iter)
1133                  << " to the top: " << Cost.getFrequency() << "\n");
1134 
1135     if (Cost < SmallestRotationCost) {
1136       SmallestRotationCost = Cost;
1137       RotationPos = Iter;
1138     }
1139   }
1140 
1141   if (RotationPos != LoopChain.end()) {
1142     DEBUG(dbgs() << "Rotate loop by making " << getBlockName(*RotationPos)
1143                  << " to the top\n");
1144     std::rotate(LoopChain.begin(), RotationPos, LoopChain.end());
1145   }
1146 }
1147 
1148 /// \brief Collect blocks in the given loop that are to be placed.
1149 ///
1150 /// When profile data is available, exclude cold blocks from the returned set;
1151 /// otherwise, collect all blocks in the loop.
1152 MachineBlockPlacement::BlockFilterSet
1153 MachineBlockPlacement::collectLoopBlockSet(MachineFunction &F, MachineLoop &L) {
1154   BlockFilterSet LoopBlockSet;
1155 
1156   // Filter cold blocks off from LoopBlockSet when profile data is available.
1157   // Collect the sum of frequencies of incoming edges to the loop header from
1158   // outside. If we treat the loop as a super block, this is the frequency of
1159   // the loop. Then for each block in the loop, we calculate the ratio between
1160   // its frequency and the frequency of the loop block. When it is too small,
1161   // don't add it to the loop chain. If there are outer loops, then this block
1162   // will be merged into the first outer loop chain for which this block is not
1163   // cold anymore. This needs precise profile data and we only do this when
1164   // profile data is available.
1165   if (F.getFunction()->getEntryCount()) {
1166     BlockFrequency LoopFreq(0);
1167     for (auto LoopPred : L.getHeader()->predecessors())
1168       if (!L.contains(LoopPred))
1169         LoopFreq += MBFI->getBlockFreq(LoopPred) *
1170                     MBPI->getEdgeProbability(LoopPred, L.getHeader());
1171 
1172     for (MachineBasicBlock *LoopBB : L.getBlocks()) {
1173       auto Freq = MBFI->getBlockFreq(LoopBB).getFrequency();
1174       if (Freq == 0 || LoopFreq.getFrequency() / Freq > LoopToColdBlockRatio)
1175         continue;
1176       LoopBlockSet.insert(LoopBB);
1177     }
1178   } else
1179     LoopBlockSet.insert(L.block_begin(), L.block_end());
1180 
1181   return LoopBlockSet;
1182 }
1183 
1184 /// \brief Forms basic block chains from the natural loop structures.
1185 ///
1186 /// These chains are designed to preserve the existing *structure* of the code
1187 /// as much as possible. We can then stitch the chains together in a way which
1188 /// both preserves the topological structure and minimizes taken conditional
1189 /// branches.
1190 void MachineBlockPlacement::buildLoopChains(MachineFunction &F,
1191                                             MachineLoop &L) {
1192   // First recurse through any nested loops, building chains for those inner
1193   // loops.
1194   for (MachineLoop *InnerLoop : L)
1195     buildLoopChains(F, *InnerLoop);
1196 
1197   SmallVector<MachineBasicBlock *, 16> BlockWorkList;
1198   SmallVector<MachineBasicBlock *, 16> EHPadWorkList;
1199   BlockFilterSet LoopBlockSet = collectLoopBlockSet(F, L);
1200 
1201   // Check if we have profile data for this function. If yes, we will rotate
1202   // this loop by modeling costs more precisely which requires the profile data
1203   // for better layout.
1204   bool RotateLoopWithProfile =
1205       ForcePreciseRotationCost ||
1206       (PreciseRotationCost && F.getFunction()->getEntryCount());
1207 
1208   // First check to see if there is an obviously preferable top block for the
1209   // loop. This will default to the header, but may end up as one of the
1210   // predecessors to the header if there is one which will result in strictly
1211   // fewer branches in the loop body.
1212   // When we use profile data to rotate the loop, this is unnecessary.
1213   MachineBasicBlock *LoopTop =
1214       RotateLoopWithProfile ? L.getHeader() : findBestLoopTop(L, LoopBlockSet);
1215 
1216   // If we selected just the header for the loop top, look for a potentially
1217   // profitable exit block in the event that rotating the loop can eliminate
1218   // branches by placing an exit edge at the bottom.
1219   MachineBasicBlock *ExitingBB = nullptr;
1220   if (!RotateLoopWithProfile && LoopTop == L.getHeader())
1221     ExitingBB = findBestLoopExit(F, L, LoopBlockSet);
1222 
1223   BlockChain &LoopChain = *BlockToChain[LoopTop];
1224 
1225   // FIXME: This is a really lame way of walking the chains in the loop: we
1226   // walk the blocks, and use a set to prevent visiting a particular chain
1227   // twice.
1228   SmallPtrSet<BlockChain *, 4> UpdatedPreds;
1229   assert(LoopChain.UnscheduledPredecessors == 0);
1230   UpdatedPreds.insert(&LoopChain);
1231 
1232   for (MachineBasicBlock *LoopBB : LoopBlockSet)
1233     fillWorkLists(LoopBB, UpdatedPreds, BlockWorkList, EHPadWorkList,
1234                   &LoopBlockSet);
1235 
1236   buildChain(LoopTop, LoopChain, BlockWorkList, EHPadWorkList, &LoopBlockSet);
1237 
1238   if (RotateLoopWithProfile)
1239     rotateLoopWithProfile(LoopChain, L, LoopBlockSet);
1240   else
1241     rotateLoop(LoopChain, ExitingBB, LoopBlockSet);
1242 
1243   DEBUG({
1244     // Crash at the end so we get all of the debugging output first.
1245     bool BadLoop = false;
1246     if (LoopChain.UnscheduledPredecessors) {
1247       BadLoop = true;
1248       dbgs() << "Loop chain contains a block without its preds placed!\n"
1249              << "  Loop header:  " << getBlockName(*L.block_begin()) << "\n"
1250              << "  Chain header: " << getBlockName(*LoopChain.begin()) << "\n";
1251     }
1252     for (MachineBasicBlock *ChainBB : LoopChain) {
1253       dbgs() << "          ... " << getBlockName(ChainBB) << "\n";
1254       if (!LoopBlockSet.erase(ChainBB)) {
1255         // We don't mark the loop as bad here because there are real situations
1256         // where this can occur. For example, with an unanalyzable fallthrough
1257         // from a loop block to a non-loop block or vice versa.
1258         dbgs() << "Loop chain contains a block not contained by the loop!\n"
1259                << "  Loop header:  " << getBlockName(*L.block_begin()) << "\n"
1260                << "  Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
1261                << "  Bad block:    " << getBlockName(ChainBB) << "\n";
1262       }
1263     }
1264 
1265     if (!LoopBlockSet.empty()) {
1266       BadLoop = true;
1267       for (MachineBasicBlock *LoopBB : LoopBlockSet)
1268         dbgs() << "Loop contains blocks never placed into a chain!\n"
1269                << "  Loop header:  " << getBlockName(*L.block_begin()) << "\n"
1270                << "  Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
1271                << "  Bad block:    " << getBlockName(LoopBB) << "\n";
1272     }
1273     assert(!BadLoop && "Detected problems with the placement of this loop.");
1274   });
1275 }
1276 
1277 /// When OutlineOpitonalBranches is on, this method colects BBs that
1278 /// dominates all terminator blocks of the function \p F.
1279 void MachineBlockPlacement::collectMustExecuteBBs(MachineFunction &F) {
1280   if (OutlineOptionalBranches) {
1281     // Find the nearest common dominator of all of F's terminators.
1282     MachineBasicBlock *Terminator = nullptr;
1283     for (MachineBasicBlock &MBB : F) {
1284       if (MBB.succ_size() == 0) {
1285         if (Terminator == nullptr)
1286           Terminator = &MBB;
1287         else
1288           Terminator = MDT->findNearestCommonDominator(Terminator, &MBB);
1289       }
1290     }
1291 
1292     // MBBs dominating this common dominator are unavoidable.
1293     UnavoidableBlocks.clear();
1294     for (MachineBasicBlock &MBB : F) {
1295       if (MDT->dominates(&MBB, Terminator)) {
1296         UnavoidableBlocks.insert(&MBB);
1297       }
1298     }
1299   }
1300 }
1301 
1302 void MachineBlockPlacement::buildCFGChains(MachineFunction &F) {
1303   // Ensure that every BB in the function has an associated chain to simplify
1304   // the assumptions of the remaining algorithm.
1305   SmallVector<MachineOperand, 4> Cond; // For AnalyzeBranch.
1306   for (MachineFunction::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
1307     MachineBasicBlock *BB = &*FI;
1308     BlockChain *Chain =
1309         new (ChainAllocator.Allocate()) BlockChain(BlockToChain, BB);
1310     // Also, merge any blocks which we cannot reason about and must preserve
1311     // the exact fallthrough behavior for.
1312     for (;;) {
1313       Cond.clear();
1314       MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
1315       if (!TII->AnalyzeBranch(*BB, TBB, FBB, Cond) || !FI->canFallThrough())
1316         break;
1317 
1318       MachineFunction::iterator NextFI = std::next(FI);
1319       MachineBasicBlock *NextBB = &*NextFI;
1320       // Ensure that the layout successor is a viable block, as we know that
1321       // fallthrough is a possibility.
1322       assert(NextFI != FE && "Can't fallthrough past the last block.");
1323       DEBUG(dbgs() << "Pre-merging due to unanalyzable fallthrough: "
1324                    << getBlockName(BB) << " -> " << getBlockName(NextBB)
1325                    << "\n");
1326       Chain->merge(NextBB, nullptr);
1327       FI = NextFI;
1328       BB = NextBB;
1329     }
1330   }
1331 
1332   // Turned on with OutlineOptionalBranches option
1333   collectMustExecuteBBs(F);
1334 
1335   // Build any loop-based chains.
1336   for (MachineLoop *L : *MLI)
1337     buildLoopChains(F, *L);
1338 
1339   SmallVector<MachineBasicBlock *, 16> BlockWorkList;
1340   SmallVector<MachineBasicBlock *, 16> EHPadWorkList;
1341 
1342   SmallPtrSet<BlockChain *, 4> UpdatedPreds;
1343   for (MachineBasicBlock &MBB : F)
1344     fillWorkLists(&MBB, UpdatedPreds, BlockWorkList, EHPadWorkList);
1345 
1346   BlockChain &FunctionChain = *BlockToChain[&F.front()];
1347   buildChain(&F.front(), FunctionChain, BlockWorkList, EHPadWorkList);
1348 
1349 #ifndef NDEBUG
1350   typedef SmallPtrSet<MachineBasicBlock *, 16> FunctionBlockSetType;
1351 #endif
1352   DEBUG({
1353     // Crash at the end so we get all of the debugging output first.
1354     bool BadFunc = false;
1355     FunctionBlockSetType FunctionBlockSet;
1356     for (MachineBasicBlock &MBB : F)
1357       FunctionBlockSet.insert(&MBB);
1358 
1359     for (MachineBasicBlock *ChainBB : FunctionChain)
1360       if (!FunctionBlockSet.erase(ChainBB)) {
1361         BadFunc = true;
1362         dbgs() << "Function chain contains a block not in the function!\n"
1363                << "  Bad block:    " << getBlockName(ChainBB) << "\n";
1364       }
1365 
1366     if (!FunctionBlockSet.empty()) {
1367       BadFunc = true;
1368       for (MachineBasicBlock *RemainingBB : FunctionBlockSet)
1369         dbgs() << "Function contains blocks never placed into a chain!\n"
1370                << "  Bad block:    " << getBlockName(RemainingBB) << "\n";
1371     }
1372     assert(!BadFunc && "Detected problems with the block placement.");
1373   });
1374 
1375   // Splice the blocks into place.
1376   MachineFunction::iterator InsertPos = F.begin();
1377   for (MachineBasicBlock *ChainBB : FunctionChain) {
1378     DEBUG(dbgs() << (ChainBB == *FunctionChain.begin() ? "Placing chain "
1379                                                        : "          ... ")
1380                  << getBlockName(ChainBB) << "\n");
1381     if (InsertPos != MachineFunction::iterator(ChainBB))
1382       F.splice(InsertPos, ChainBB);
1383     else
1384       ++InsertPos;
1385 
1386     // Update the terminator of the previous block.
1387     if (ChainBB == *FunctionChain.begin())
1388       continue;
1389     MachineBasicBlock *PrevBB = &*std::prev(MachineFunction::iterator(ChainBB));
1390 
1391     // FIXME: It would be awesome of updateTerminator would just return rather
1392     // than assert when the branch cannot be analyzed in order to remove this
1393     // boiler plate.
1394     Cond.clear();
1395     MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
1396 
1397     // The "PrevBB" is not yet updated to reflect current code layout, so,
1398     //   o. it may fall-through to a block without explict "goto" instruction
1399     //      before layout, and no longer fall-through it after layout; or
1400     //   o. just opposite.
1401     //
1402     // AnalyzeBranch() may return erroneous value for FBB when these two
1403     // situations take place. For the first scenario FBB is mistakenly set NULL;
1404     // for the 2nd scenario, the FBB, which is expected to be NULL, is
1405     // mistakenly pointing to "*BI".
1406     // Thus, if the future change needs to use FBB before the layout is set, it
1407     // has to correct FBB first by using the code similar to the following:
1408     //
1409     // if (!Cond.empty() && (!FBB || FBB == ChainBB)) {
1410     //   PrevBB->updateTerminator();
1411     //   Cond.clear();
1412     //   TBB = FBB = nullptr;
1413     //   if (TII->AnalyzeBranch(*PrevBB, TBB, FBB, Cond)) {
1414     //     // FIXME: This should never take place.
1415     //     TBB = FBB = nullptr;
1416     //   }
1417     // }
1418     if (!TII->AnalyzeBranch(*PrevBB, TBB, FBB, Cond))
1419       PrevBB->updateTerminator();
1420   }
1421 
1422   // Fixup the last block.
1423   Cond.clear();
1424   MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
1425   if (!TII->AnalyzeBranch(F.back(), TBB, FBB, Cond))
1426     F.back().updateTerminator();
1427 }
1428 
1429 void MachineBlockPlacement::optimizeBranches(MachineFunction &F) {
1430   BlockChain &FunctionChain = *BlockToChain[&F.front()];
1431   SmallVector<MachineOperand, 4> Cond; // For AnalyzeBranch.
1432 
1433   // Now that all the basic blocks in the chain have the proper layout,
1434   // make a final call to AnalyzeBranch with AllowModify set.
1435   // Indeed, the target may be able to optimize the branches in a way we
1436   // cannot because all branches may not be analyzable.
1437   // E.g., the target may be able to remove an unconditional branch to
1438   // a fallthrough when it occurs after predicated terminators.
1439   for (MachineBasicBlock *ChainBB : FunctionChain) {
1440     Cond.clear();
1441     MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
1442     if (!TII->AnalyzeBranch(*ChainBB, TBB, FBB, Cond, /*AllowModify*/ true)) {
1443       // If PrevBB has a two-way branch, try to re-order the branches
1444       // such that we branch to the successor with higher probability first.
1445       if (TBB && !Cond.empty() && FBB &&
1446           MBPI->getEdgeProbability(ChainBB, FBB) >
1447               MBPI->getEdgeProbability(ChainBB, TBB) &&
1448           !TII->ReverseBranchCondition(Cond)) {
1449         DEBUG(dbgs() << "Reverse order of the two branches: "
1450                      << getBlockName(ChainBB) << "\n");
1451         DEBUG(dbgs() << "    Edge probability: "
1452                      << MBPI->getEdgeProbability(ChainBB, FBB) << " vs "
1453                      << MBPI->getEdgeProbability(ChainBB, TBB) << "\n");
1454         DebugLoc dl; // FIXME: this is nowhere
1455         TII->RemoveBranch(*ChainBB);
1456         TII->InsertBranch(*ChainBB, FBB, TBB, Cond, dl);
1457         ChainBB->updateTerminator();
1458       }
1459     }
1460   }
1461 }
1462 
1463 void MachineBlockPlacement::alignBlocks(MachineFunction &F) {
1464   // Walk through the backedges of the function now that we have fully laid out
1465   // the basic blocks and align the destination of each backedge. We don't rely
1466   // exclusively on the loop info here so that we can align backedges in
1467   // unnatural CFGs and backedges that were introduced purely because of the
1468   // loop rotations done during this layout pass.
1469   if (F.getFunction()->optForSize())
1470     return;
1471   BlockChain &FunctionChain = *BlockToChain[&F.front()];
1472   if (FunctionChain.begin() == FunctionChain.end())
1473     return; // Empty chain.
1474 
1475   const BranchProbability ColdProb(1, 5); // 20%
1476   BlockFrequency EntryFreq = MBFI->getBlockFreq(&F.front());
1477   BlockFrequency WeightedEntryFreq = EntryFreq * ColdProb;
1478   for (MachineBasicBlock *ChainBB : FunctionChain) {
1479     if (ChainBB == *FunctionChain.begin())
1480       continue;
1481 
1482     // Don't align non-looping basic blocks. These are unlikely to execute
1483     // enough times to matter in practice. Note that we'll still handle
1484     // unnatural CFGs inside of a natural outer loop (the common case) and
1485     // rotated loops.
1486     MachineLoop *L = MLI->getLoopFor(ChainBB);
1487     if (!L)
1488       continue;
1489 
1490     unsigned Align = TLI->getPrefLoopAlignment(L);
1491     if (!Align)
1492       continue; // Don't care about loop alignment.
1493 
1494     // If the block is cold relative to the function entry don't waste space
1495     // aligning it.
1496     BlockFrequency Freq = MBFI->getBlockFreq(ChainBB);
1497     if (Freq < WeightedEntryFreq)
1498       continue;
1499 
1500     // If the block is cold relative to its loop header, don't align it
1501     // regardless of what edges into the block exist.
1502     MachineBasicBlock *LoopHeader = L->getHeader();
1503     BlockFrequency LoopHeaderFreq = MBFI->getBlockFreq(LoopHeader);
1504     if (Freq < (LoopHeaderFreq * ColdProb))
1505       continue;
1506 
1507     // Check for the existence of a non-layout predecessor which would benefit
1508     // from aligning this block.
1509     MachineBasicBlock *LayoutPred =
1510         &*std::prev(MachineFunction::iterator(ChainBB));
1511 
1512     // Force alignment if all the predecessors are jumps. We already checked
1513     // that the block isn't cold above.
1514     if (!LayoutPred->isSuccessor(ChainBB)) {
1515       ChainBB->setAlignment(Align);
1516       continue;
1517     }
1518 
1519     // Align this block if the layout predecessor's edge into this block is
1520     // cold relative to the block. When this is true, other predecessors make up
1521     // all of the hot entries into the block and thus alignment is likely to be
1522     // important.
1523     BranchProbability LayoutProb =
1524         MBPI->getEdgeProbability(LayoutPred, ChainBB);
1525     BlockFrequency LayoutEdgeFreq = MBFI->getBlockFreq(LayoutPred) * LayoutProb;
1526     if (LayoutEdgeFreq <= (Freq * ColdProb))
1527       ChainBB->setAlignment(Align);
1528   }
1529 }
1530 
1531 bool MachineBlockPlacement::runOnMachineFunction(MachineFunction &F) {
1532   if (skipFunction(*F.getFunction()))
1533     return false;
1534 
1535   // Check for single-block functions and skip them.
1536   if (std::next(F.begin()) == F.end())
1537     return false;
1538 
1539   MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
1540   MBFI = llvm::make_unique<BranchFolder::MBFIWrapper>(
1541       getAnalysis<MachineBlockFrequencyInfo>());
1542   MLI = &getAnalysis<MachineLoopInfo>();
1543   TII = F.getSubtarget().getInstrInfo();
1544   TLI = F.getSubtarget().getTargetLowering();
1545   MDT = &getAnalysis<MachineDominatorTree>();
1546   assert(BlockToChain.empty());
1547 
1548   buildCFGChains(F);
1549 
1550   // Changing the layout can create new tail merging opportunities.
1551   TargetPassConfig *PassConfig = &getAnalysis<TargetPassConfig>();
1552   // TailMerge can create jump into if branches that make CFG irreducible for
1553   // HW that requires structurized CFG.
1554   bool EnableTailMerge = !F.getTarget().requiresStructuredCFG() &&
1555                          PassConfig->getEnableTailMerge() &&
1556                          BranchFoldPlacement;
1557   // No tail merging opportunities if the block number is less than four.
1558   if (F.size() > 3 && EnableTailMerge) {
1559     BranchFolder BF(/*EnableTailMerge=*/true, /*CommonHoist=*/false, *MBFI,
1560                     *MBPI);
1561 
1562     if (BF.OptimizeFunction(F, TII, F.getSubtarget().getRegisterInfo(),
1563                             getAnalysisIfAvailable<MachineModuleInfo>(), MLI,
1564                             /*AfterBlockPlacement=*/true)) {
1565       // Redo the layout if tail merging creates/removes/moves blocks.
1566       BlockToChain.clear();
1567       ChainAllocator.DestroyAll();
1568       buildCFGChains(F);
1569     }
1570   }
1571 
1572   optimizeBranches(F);
1573   alignBlocks(F);
1574 
1575   BlockToChain.clear();
1576   ChainAllocator.DestroyAll();
1577 
1578   if (AlignAllBlock)
1579     // Align all of the blocks in the function to a specific alignment.
1580     for (MachineBasicBlock &MBB : F)
1581       MBB.setAlignment(AlignAllBlock);
1582   else if (AlignAllNonFallThruBlocks) {
1583     // Align all of the blocks that have no fall-through predecessors to a
1584     // specific alignment.
1585     for (auto MBI = std::next(F.begin()), MBE = F.end(); MBI != MBE; ++MBI) {
1586       auto LayoutPred = std::prev(MBI);
1587       if (!LayoutPred->isSuccessor(&*MBI))
1588         MBI->setAlignment(AlignAllNonFallThruBlocks);
1589     }
1590   }
1591 
1592   // We always return true as we have no way to track whether the final order
1593   // differs from the original order.
1594   return true;
1595 }
1596 
1597 namespace {
1598 /// \brief A pass to compute block placement statistics.
1599 ///
1600 /// A separate pass to compute interesting statistics for evaluating block
1601 /// placement. This is separate from the actual placement pass so that they can
1602 /// be computed in the absence of any placement transformations or when using
1603 /// alternative placement strategies.
1604 class MachineBlockPlacementStats : public MachineFunctionPass {
1605   /// \brief A handle to the branch probability pass.
1606   const MachineBranchProbabilityInfo *MBPI;
1607 
1608   /// \brief A handle to the function-wide block frequency pass.
1609   const MachineBlockFrequencyInfo *MBFI;
1610 
1611 public:
1612   static char ID; // Pass identification, replacement for typeid
1613   MachineBlockPlacementStats() : MachineFunctionPass(ID) {
1614     initializeMachineBlockPlacementStatsPass(*PassRegistry::getPassRegistry());
1615   }
1616 
1617   bool runOnMachineFunction(MachineFunction &F) override;
1618 
1619   void getAnalysisUsage(AnalysisUsage &AU) const override {
1620     AU.addRequired<MachineBranchProbabilityInfo>();
1621     AU.addRequired<MachineBlockFrequencyInfo>();
1622     AU.setPreservesAll();
1623     MachineFunctionPass::getAnalysisUsage(AU);
1624   }
1625 };
1626 }
1627 
1628 char MachineBlockPlacementStats::ID = 0;
1629 char &llvm::MachineBlockPlacementStatsID = MachineBlockPlacementStats::ID;
1630 INITIALIZE_PASS_BEGIN(MachineBlockPlacementStats, "block-placement-stats",
1631                       "Basic Block Placement Stats", false, false)
1632 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
1633 INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
1634 INITIALIZE_PASS_END(MachineBlockPlacementStats, "block-placement-stats",
1635                     "Basic Block Placement Stats", false, false)
1636 
1637 bool MachineBlockPlacementStats::runOnMachineFunction(MachineFunction &F) {
1638   // Check for single-block functions and skip them.
1639   if (std::next(F.begin()) == F.end())
1640     return false;
1641 
1642   MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
1643   MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
1644 
1645   for (MachineBasicBlock &MBB : F) {
1646     BlockFrequency BlockFreq = MBFI->getBlockFreq(&MBB);
1647     Statistic &NumBranches =
1648         (MBB.succ_size() > 1) ? NumCondBranches : NumUncondBranches;
1649     Statistic &BranchTakenFreq =
1650         (MBB.succ_size() > 1) ? CondBranchTakenFreq : UncondBranchTakenFreq;
1651     for (MachineBasicBlock *Succ : MBB.successors()) {
1652       // Skip if this successor is a fallthrough.
1653       if (MBB.isLayoutSuccessor(Succ))
1654         continue;
1655 
1656       BlockFrequency EdgeFreq =
1657           BlockFreq * MBPI->getEdgeProbability(&MBB, Succ);
1658       ++NumBranches;
1659       BranchTakenFreq += EdgeFreq.getFrequency();
1660     }
1661   }
1662 
1663   return false;
1664 }
1665