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