Record whether the weights on out-edges from a MBB are normalized.
[oota-llvm.git] / lib / CodeGen / MachineBlockPlacement.cpp
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 uncondittional 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 // FIXME: Find a good default for this flag and remove the flag.
66 static cl::opt<unsigned> ExitBlockBias(
67     "block-placement-exit-block-bias",
68     cl::desc("Block frequency percentage a loop exit block needs "
69              "over the original exit to be considered the new exit."),
70     cl::init(0), cl::Hidden);
71
72 static cl::opt<bool> OutlineOptionalBranches(
73     "outline-optional-branches",
74     cl::desc("Put completely optional branches, i.e. branches with a common "
75              "post dominator, out of line."),
76     cl::init(false), cl::Hidden);
77
78 static cl::opt<unsigned> OutlineOptionalThreshold(
79     "outline-optional-threshold",
80     cl::desc("Don't outline optional branches that are a single block with an "
81              "instruction count below this threshold"),
82     cl::init(4), cl::Hidden);
83
84 namespace {
85 class BlockChain;
86 /// \brief Type for our function-wide basic block -> block chain mapping.
87 typedef DenseMap<MachineBasicBlock *, BlockChain *> BlockToChainMapType;
88 }
89
90 namespace {
91 /// \brief A chain of blocks which will be laid out contiguously.
92 ///
93 /// This is the datastructure representing a chain of consecutive blocks that
94 /// are profitable to layout together in order to maximize fallthrough
95 /// probabilities and code locality. We also can use a block chain to represent
96 /// a sequence of basic blocks which have some external (correctness)
97 /// requirement for sequential layout.
98 ///
99 /// Chains can be built around a single basic block and can be merged to grow
100 /// them. They participate in a block-to-chain mapping, which is updated
101 /// automatically as chains are merged together.
102 class BlockChain {
103   /// \brief The sequence of blocks belonging to this chain.
104   ///
105   /// This is the sequence of blocks for a particular chain. These will be laid
106   /// out in-order within the function.
107   SmallVector<MachineBasicBlock *, 4> Blocks;
108
109   /// \brief A handle to the function-wide basic block to block chain mapping.
110   ///
111   /// This is retained in each block chain to simplify the computation of child
112   /// block chains for SCC-formation and iteration. We store the edges to child
113   /// basic blocks, and map them back to their associated chains using this
114   /// structure.
115   BlockToChainMapType &BlockToChain;
116
117 public:
118   /// \brief Construct a new BlockChain.
119   ///
120   /// This builds a new block chain representing a single basic block in the
121   /// function. It also registers itself as the chain that block participates
122   /// in with the BlockToChain mapping.
123   BlockChain(BlockToChainMapType &BlockToChain, MachineBasicBlock *BB)
124       : Blocks(1, BB), BlockToChain(BlockToChain), LoopPredecessors(0) {
125     assert(BB && "Cannot create a chain with a null basic block");
126     BlockToChain[BB] = this;
127   }
128
129   /// \brief Iterator over blocks within the chain.
130   typedef SmallVectorImpl<MachineBasicBlock *>::iterator iterator;
131
132   /// \brief Beginning of blocks within the chain.
133   iterator begin() { return Blocks.begin(); }
134
135   /// \brief End of blocks within the chain.
136   iterator end() { return Blocks.end(); }
137
138   /// \brief Merge a block chain into this one.
139   ///
140   /// This routine merges a block chain into this one. It takes care of forming
141   /// a contiguous sequence of basic blocks, updating the edge list, and
142   /// updating the block -> chain mapping. It does not free or tear down the
143   /// old chain, but the old chain's block list is no longer valid.
144   void merge(MachineBasicBlock *BB, BlockChain *Chain) {
145     assert(BB);
146     assert(!Blocks.empty());
147
148     // Fast path in case we don't have a chain already.
149     if (!Chain) {
150       assert(!BlockToChain[BB]);
151       Blocks.push_back(BB);
152       BlockToChain[BB] = this;
153       return;
154     }
155
156     assert(BB == *Chain->begin());
157     assert(Chain->begin() != Chain->end());
158
159     // Update the incoming blocks to point to this chain, and add them to the
160     // chain structure.
161     for (MachineBasicBlock *ChainBB : *Chain) {
162       Blocks.push_back(ChainBB);
163       assert(BlockToChain[ChainBB] == Chain && "Incoming blocks not in chain");
164       BlockToChain[ChainBB] = this;
165     }
166   }
167
168 #ifndef NDEBUG
169   /// \brief Dump the blocks in this chain.
170   LLVM_DUMP_METHOD void dump() {
171     for (MachineBasicBlock *MBB : *this)
172       MBB->dump();
173   }
174 #endif // NDEBUG
175
176   /// \brief Count of predecessors within the loop currently being processed.
177   ///
178   /// This count is updated at each loop we process to represent the number of
179   /// in-loop predecessors of this chain.
180   unsigned LoopPredecessors;
181 };
182 }
183
184 namespace {
185 class MachineBlockPlacement : public MachineFunctionPass {
186   /// \brief A typedef for a block filter set.
187   typedef SmallPtrSet<MachineBasicBlock *, 16> BlockFilterSet;
188
189   /// \brief A handle to the branch probability pass.
190   const MachineBranchProbabilityInfo *MBPI;
191
192   /// \brief A handle to the function-wide block frequency pass.
193   const MachineBlockFrequencyInfo *MBFI;
194
195   /// \brief A handle to the loop info.
196   const MachineLoopInfo *MLI;
197
198   /// \brief A handle to the target's instruction info.
199   const TargetInstrInfo *TII;
200
201   /// \brief A handle to the target's lowering info.
202   const TargetLoweringBase *TLI;
203
204   /// \brief A handle to the post dominator tree.
205   MachineDominatorTree *MDT;
206
207   /// \brief A set of blocks that are unavoidably execute, i.e. they dominate
208   /// all terminators of the MachineFunction.
209   SmallPtrSet<MachineBasicBlock *, 4> UnavoidableBlocks;
210
211   /// \brief Allocator and owner of BlockChain structures.
212   ///
213   /// We build BlockChains lazily while processing the loop structure of
214   /// a function. To reduce malloc traffic, we allocate them using this
215   /// slab-like allocator, and destroy them after the pass completes. An
216   /// important guarantee is that this allocator produces stable pointers to
217   /// the chains.
218   SpecificBumpPtrAllocator<BlockChain> ChainAllocator;
219
220   /// \brief Function wide BasicBlock to BlockChain mapping.
221   ///
222   /// This mapping allows efficiently moving from any given basic block to the
223   /// BlockChain it participates in, if any. We use it to, among other things,
224   /// allow implicitly defining edges between chains as the existing edges
225   /// between basic blocks.
226   DenseMap<MachineBasicBlock *, BlockChain *> BlockToChain;
227
228   void markChainSuccessors(BlockChain &Chain, MachineBasicBlock *LoopHeaderBB,
229                            SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
230                            const BlockFilterSet *BlockFilter = nullptr);
231   MachineBasicBlock *selectBestSuccessor(MachineBasicBlock *BB,
232                                          BlockChain &Chain,
233                                          const BlockFilterSet *BlockFilter);
234   MachineBasicBlock *
235   selectBestCandidateBlock(BlockChain &Chain,
236                            SmallVectorImpl<MachineBasicBlock *> &WorkList,
237                            const BlockFilterSet *BlockFilter);
238   MachineBasicBlock *
239   getFirstUnplacedBlock(MachineFunction &F, const BlockChain &PlacedChain,
240                         MachineFunction::iterator &PrevUnplacedBlockIt,
241                         const BlockFilterSet *BlockFilter);
242   void buildChain(MachineBasicBlock *BB, BlockChain &Chain,
243                   SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
244                   const BlockFilterSet *BlockFilter = nullptr);
245   MachineBasicBlock *findBestLoopTop(MachineLoop &L,
246                                      const BlockFilterSet &LoopBlockSet);
247   MachineBasicBlock *findBestLoopExit(MachineFunction &F, MachineLoop &L,
248                                       const BlockFilterSet &LoopBlockSet);
249   void buildLoopChains(MachineFunction &F, MachineLoop &L);
250   void rotateLoop(BlockChain &LoopChain, MachineBasicBlock *ExitingBB,
251                   const BlockFilterSet &LoopBlockSet);
252   void buildCFGChains(MachineFunction &F);
253
254 public:
255   static char ID; // Pass identification, replacement for typeid
256   MachineBlockPlacement() : MachineFunctionPass(ID) {
257     initializeMachineBlockPlacementPass(*PassRegistry::getPassRegistry());
258   }
259
260   bool runOnMachineFunction(MachineFunction &F) override;
261
262   void getAnalysisUsage(AnalysisUsage &AU) const override {
263     AU.addRequired<MachineBranchProbabilityInfo>();
264     AU.addRequired<MachineBlockFrequencyInfo>();
265     AU.addRequired<MachineDominatorTree>();
266     AU.addRequired<MachineLoopInfo>();
267     MachineFunctionPass::getAnalysisUsage(AU);
268   }
269 };
270 }
271
272 char MachineBlockPlacement::ID = 0;
273 char &llvm::MachineBlockPlacementID = MachineBlockPlacement::ID;
274 INITIALIZE_PASS_BEGIN(MachineBlockPlacement, "block-placement",
275                       "Branch Probability Basic Block Placement", false, false)
276 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
277 INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
278 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
279 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
280 INITIALIZE_PASS_END(MachineBlockPlacement, "block-placement",
281                     "Branch Probability Basic Block Placement", false, false)
282
283 #ifndef NDEBUG
284 /// \brief Helper to print the name of a MBB.
285 ///
286 /// Only used by debug logging.
287 static std::string getBlockName(MachineBasicBlock *BB) {
288   std::string Result;
289   raw_string_ostream OS(Result);
290   OS << "BB#" << BB->getNumber();
291   OS << " (derived from LLVM BB '" << BB->getName() << "')";
292   OS.flush();
293   return Result;
294 }
295
296 /// \brief Helper to print the number of a MBB.
297 ///
298 /// Only used by debug logging.
299 static std::string getBlockNum(MachineBasicBlock *BB) {
300   std::string Result;
301   raw_string_ostream OS(Result);
302   OS << "BB#" << BB->getNumber();
303   OS.flush();
304   return Result;
305 }
306 #endif
307
308 /// \brief Mark a chain's successors as having one fewer preds.
309 ///
310 /// When a chain is being merged into the "placed" chain, this routine will
311 /// quickly walk the successors of each block in the chain and mark them as
312 /// having one fewer active predecessor. It also adds any successors of this
313 /// chain which reach the zero-predecessor state to the worklist passed in.
314 void MachineBlockPlacement::markChainSuccessors(
315     BlockChain &Chain, MachineBasicBlock *LoopHeaderBB,
316     SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
317     const BlockFilterSet *BlockFilter) {
318   // Walk all the blocks in this chain, marking their successors as having
319   // a predecessor placed.
320   for (MachineBasicBlock *MBB : Chain) {
321     // Add any successors for which this is the only un-placed in-loop
322     // predecessor to the worklist as a viable candidate for CFG-neutral
323     // placement. No subsequent placement of this block will violate the CFG
324     // shape, so we get to use heuristics to choose a favorable placement.
325     for (MachineBasicBlock *Succ : MBB->successors()) {
326       if (BlockFilter && !BlockFilter->count(Succ))
327         continue;
328       BlockChain &SuccChain = *BlockToChain[Succ];
329       // Disregard edges within a fixed chain, or edges to the loop header.
330       if (&Chain == &SuccChain || Succ == LoopHeaderBB)
331         continue;
332
333       // This is a cross-chain edge that is within the loop, so decrement the
334       // loop predecessor count of the destination chain.
335       if (SuccChain.LoopPredecessors > 0 && --SuccChain.LoopPredecessors == 0)
336         BlockWorkList.push_back(*SuccChain.begin());
337     }
338   }
339 }
340
341 /// \brief Select the best successor for a block.
342 ///
343 /// This looks across all successors of a particular block and attempts to
344 /// select the "best" one to be the layout successor. It only considers direct
345 /// successors which also pass the block filter. It will attempt to avoid
346 /// breaking CFG structure, but cave and break such structures in the case of
347 /// very hot successor edges.
348 ///
349 /// \returns The best successor block found, or null if none are viable.
350 MachineBasicBlock *
351 MachineBlockPlacement::selectBestSuccessor(MachineBasicBlock *BB,
352                                            BlockChain &Chain,
353                                            const BlockFilterSet *BlockFilter) {
354   const BranchProbability HotProb(4, 5); // 80%
355
356   MachineBasicBlock *BestSucc = nullptr;
357   // FIXME: Due to the performance of the probability and weight routines in
358   // the MBPI analysis, we manually compute probabilities using the edge
359   // weights. This is suboptimal as it means that the somewhat subtle
360   // definition of edge weight semantics is encoded here as well. We should
361   // improve the MBPI interface to efficiently support query patterns such as
362   // this.
363   uint32_t BestWeight = 0;
364   uint32_t SumWeight = MBPI->getSumForBlock(BB);
365   DEBUG(dbgs() << "Attempting merge from: " << getBlockName(BB) << "\n");
366   for (MachineBasicBlock *Succ : BB->successors()) {
367     if (BlockFilter && !BlockFilter->count(Succ))
368       continue;
369     BlockChain &SuccChain = *BlockToChain[Succ];
370     if (&SuccChain == &Chain) {
371       DEBUG(dbgs() << "    " << getBlockName(Succ) << " -> Already merged!\n");
372       continue;
373     }
374     if (Succ != *SuccChain.begin()) {
375       DEBUG(dbgs() << "    " << getBlockName(Succ) << " -> Mid chain!\n");
376       continue;
377     }
378
379     uint32_t SuccWeight = MBPI->getEdgeWeight(BB, Succ);
380     BranchProbability SuccProb(SuccWeight, SumWeight);
381
382     // If we outline optional branches, look whether Succ is unavoidable, i.e.
383     // dominates all terminators of the MachineFunction. If it does, other
384     // successors must be optional. Don't do this for cold branches.
385     if (OutlineOptionalBranches && SuccProb > HotProb.getCompl() &&
386         UnavoidableBlocks.count(Succ) > 0) {
387       auto HasShortOptionalBranch = [&]() {
388         for (MachineBasicBlock *Pred : Succ->predecessors()) {
389           // Check whether there is an unplaced optional branch.
390           if (Pred == Succ || (BlockFilter && !BlockFilter->count(Pred)) ||
391               BlockToChain[Pred] == &Chain)
392             continue;
393           // Check whether the optional branch has exactly one BB.
394           if (Pred->pred_size() > 1 || *Pred->pred_begin() != BB)
395             continue;
396           // Check whether the optional branch is small.
397           if (Pred->size() < OutlineOptionalThreshold)
398             return true;
399         }
400         return false;
401       };
402       if (!HasShortOptionalBranch())
403         return Succ;
404     }
405
406     // Only consider successors which are either "hot", or wouldn't violate
407     // any CFG constraints.
408     if (SuccChain.LoopPredecessors != 0) {
409       if (SuccProb < HotProb) {
410         DEBUG(dbgs() << "    " << getBlockName(Succ) << " -> " << SuccProb
411                      << " (prob) (CFG conflict)\n");
412         continue;
413       }
414
415       // Make sure that a hot successor doesn't have a globally more
416       // important predecessor.
417       BlockFrequency CandidateEdgeFreq =
418           MBFI->getBlockFreq(BB) * SuccProb * HotProb.getCompl();
419       bool BadCFGConflict = false;
420       for (MachineBasicBlock *Pred : Succ->predecessors()) {
421         if (Pred == Succ || (BlockFilter && !BlockFilter->count(Pred)) ||
422             BlockToChain[Pred] == &Chain)
423           continue;
424         BlockFrequency PredEdgeFreq =
425             MBFI->getBlockFreq(Pred) * MBPI->getEdgeProbability(Pred, Succ);
426         if (PredEdgeFreq >= CandidateEdgeFreq) {
427           BadCFGConflict = true;
428           break;
429         }
430       }
431       if (BadCFGConflict) {
432         DEBUG(dbgs() << "    " << getBlockName(Succ) << " -> " << SuccProb
433                      << " (prob) (non-cold CFG conflict)\n");
434         continue;
435       }
436     }
437
438     DEBUG(dbgs() << "    " << getBlockName(Succ) << " -> " << SuccProb
439                  << " (prob)"
440                  << (SuccChain.LoopPredecessors != 0 ? " (CFG break)" : "")
441                  << "\n");
442     if (BestSucc && BestWeight >= SuccWeight)
443       continue;
444     BestSucc = Succ;
445     BestWeight = SuccWeight;
446   }
447   return BestSucc;
448 }
449
450 /// \brief Select the best block from a worklist.
451 ///
452 /// This looks through the provided worklist as a list of candidate basic
453 /// blocks and select the most profitable one to place. The definition of
454 /// profitable only really makes sense in the context of a loop. This returns
455 /// the most frequently visited block in the worklist, which in the case of
456 /// a loop, is the one most desirable to be physically close to the rest of the
457 /// loop body in order to improve icache behavior.
458 ///
459 /// \returns The best block found, or null if none are viable.
460 MachineBasicBlock *MachineBlockPlacement::selectBestCandidateBlock(
461     BlockChain &Chain, SmallVectorImpl<MachineBasicBlock *> &WorkList,
462     const BlockFilterSet *BlockFilter) {
463   // Once we need to walk the worklist looking for a candidate, cleanup the
464   // worklist of already placed entries.
465   // FIXME: If this shows up on profiles, it could be folded (at the cost of
466   // some code complexity) into the loop below.
467   WorkList.erase(std::remove_if(WorkList.begin(), WorkList.end(),
468                                 [&](MachineBasicBlock *BB) {
469                                   return BlockToChain.lookup(BB) == &Chain;
470                                 }),
471                  WorkList.end());
472
473   MachineBasicBlock *BestBlock = nullptr;
474   BlockFrequency BestFreq;
475   for (MachineBasicBlock *MBB : WorkList) {
476     BlockChain &SuccChain = *BlockToChain[MBB];
477     if (&SuccChain == &Chain) {
478       DEBUG(dbgs() << "    " << getBlockName(MBB) << " -> Already merged!\n");
479       continue;
480     }
481     assert(SuccChain.LoopPredecessors == 0 && "Found CFG-violating block");
482
483     BlockFrequency CandidateFreq = MBFI->getBlockFreq(MBB);
484     DEBUG(dbgs() << "    " << getBlockName(MBB) << " -> ";
485           MBFI->printBlockFreq(dbgs(), CandidateFreq) << " (freq)\n");
486     if (BestBlock && BestFreq >= CandidateFreq)
487       continue;
488     BestBlock = MBB;
489     BestFreq = CandidateFreq;
490   }
491   return BestBlock;
492 }
493
494 /// \brief Retrieve the first unplaced basic block.
495 ///
496 /// This routine is called when we are unable to use the CFG to walk through
497 /// all of the basic blocks and form a chain due to unnatural loops in the CFG.
498 /// We walk through the function's blocks in order, starting from the
499 /// LastUnplacedBlockIt. We update this iterator on each call to avoid
500 /// re-scanning the entire sequence on repeated calls to this routine.
501 MachineBasicBlock *MachineBlockPlacement::getFirstUnplacedBlock(
502     MachineFunction &F, const BlockChain &PlacedChain,
503     MachineFunction::iterator &PrevUnplacedBlockIt,
504     const BlockFilterSet *BlockFilter) {
505   for (MachineFunction::iterator I = PrevUnplacedBlockIt, E = F.end(); I != E;
506        ++I) {
507     if (BlockFilter && !BlockFilter->count(I))
508       continue;
509     if (BlockToChain[I] != &PlacedChain) {
510       PrevUnplacedBlockIt = I;
511       // Now select the head of the chain to which the unplaced block belongs
512       // as the block to place. This will force the entire chain to be placed,
513       // and satisfies the requirements of merging chains.
514       return *BlockToChain[I]->begin();
515     }
516   }
517   return nullptr;
518 }
519
520 void MachineBlockPlacement::buildChain(
521     MachineBasicBlock *BB, BlockChain &Chain,
522     SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
523     const BlockFilterSet *BlockFilter) {
524   assert(BB);
525   assert(BlockToChain[BB] == &Chain);
526   MachineFunction &F = *BB->getParent();
527   MachineFunction::iterator PrevUnplacedBlockIt = F.begin();
528
529   MachineBasicBlock *LoopHeaderBB = BB;
530   markChainSuccessors(Chain, LoopHeaderBB, BlockWorkList, BlockFilter);
531   BB = *std::prev(Chain.end());
532   for (;;) {
533     assert(BB);
534     assert(BlockToChain[BB] == &Chain);
535     assert(*std::prev(Chain.end()) == BB);
536
537     // Look for the best viable successor if there is one to place immediately
538     // after this block.
539     MachineBasicBlock *BestSucc = selectBestSuccessor(BB, Chain, BlockFilter);
540
541     // If an immediate successor isn't available, look for the best viable
542     // block among those we've identified as not violating the loop's CFG at
543     // this point. This won't be a fallthrough, but it will increase locality.
544     if (!BestSucc)
545       BestSucc = selectBestCandidateBlock(Chain, BlockWorkList, BlockFilter);
546
547     if (!BestSucc) {
548       BestSucc =
549           getFirstUnplacedBlock(F, Chain, PrevUnplacedBlockIt, BlockFilter);
550       if (!BestSucc)
551         break;
552
553       DEBUG(dbgs() << "Unnatural loop CFG detected, forcibly merging the "
554                       "layout successor until the CFG reduces\n");
555     }
556
557     // Place this block, updating the datastructures to reflect its placement.
558     BlockChain &SuccChain = *BlockToChain[BestSucc];
559     // Zero out LoopPredecessors for the successor we're about to merge in case
560     // we selected a successor that didn't fit naturally into the CFG.
561     SuccChain.LoopPredecessors = 0;
562     DEBUG(dbgs() << "Merging from " << getBlockNum(BB) << " to "
563                  << getBlockNum(BestSucc) << "\n");
564     markChainSuccessors(SuccChain, LoopHeaderBB, BlockWorkList, BlockFilter);
565     Chain.merge(BestSucc, &SuccChain);
566     BB = *std::prev(Chain.end());
567   }
568
569   DEBUG(dbgs() << "Finished forming chain for header block "
570                << getBlockNum(*Chain.begin()) << "\n");
571 }
572
573 /// \brief Find the best loop top block for layout.
574 ///
575 /// Look for a block which is strictly better than the loop header for laying
576 /// out at the top of the loop. This looks for one and only one pattern:
577 /// a latch block with no conditional exit. This block will cause a conditional
578 /// jump around it or will be the bottom of the loop if we lay it out in place,
579 /// but if it it doesn't end up at the bottom of the loop for any reason,
580 /// rotation alone won't fix it. Because such a block will always result in an
581 /// unconditional jump (for the backedge) rotating it in front of the loop
582 /// header is always profitable.
583 MachineBasicBlock *
584 MachineBlockPlacement::findBestLoopTop(MachineLoop &L,
585                                        const BlockFilterSet &LoopBlockSet) {
586   // Check that the header hasn't been fused with a preheader block due to
587   // crazy branches. If it has, we need to start with the header at the top to
588   // prevent pulling the preheader into the loop body.
589   BlockChain &HeaderChain = *BlockToChain[L.getHeader()];
590   if (!LoopBlockSet.count(*HeaderChain.begin()))
591     return L.getHeader();
592
593   DEBUG(dbgs() << "Finding best loop top for: " << getBlockName(L.getHeader())
594                << "\n");
595
596   BlockFrequency BestPredFreq;
597   MachineBasicBlock *BestPred = nullptr;
598   for (MachineBasicBlock *Pred : L.getHeader()->predecessors()) {
599     if (!LoopBlockSet.count(Pred))
600       continue;
601     DEBUG(dbgs() << "    header pred: " << getBlockName(Pred) << ", "
602                  << Pred->succ_size() << " successors, ";
603           MBFI->printBlockFreq(dbgs(), Pred) << " freq\n");
604     if (Pred->succ_size() > 1)
605       continue;
606
607     BlockFrequency PredFreq = MBFI->getBlockFreq(Pred);
608     if (!BestPred || PredFreq > BestPredFreq ||
609         (!(PredFreq < BestPredFreq) &&
610          Pred->isLayoutSuccessor(L.getHeader()))) {
611       BestPred = Pred;
612       BestPredFreq = PredFreq;
613     }
614   }
615
616   // If no direct predecessor is fine, just use the loop header.
617   if (!BestPred)
618     return L.getHeader();
619
620   // Walk backwards through any straight line of predecessors.
621   while (BestPred->pred_size() == 1 &&
622          (*BestPred->pred_begin())->succ_size() == 1 &&
623          *BestPred->pred_begin() != L.getHeader())
624     BestPred = *BestPred->pred_begin();
625
626   DEBUG(dbgs() << "    final top: " << getBlockName(BestPred) << "\n");
627   return BestPred;
628 }
629
630 /// \brief Find the best loop exiting block for layout.
631 ///
632 /// This routine implements the logic to analyze the loop looking for the best
633 /// block to layout at the top of the loop. Typically this is done to maximize
634 /// fallthrough opportunities.
635 MachineBasicBlock *
636 MachineBlockPlacement::findBestLoopExit(MachineFunction &F, MachineLoop &L,
637                                         const BlockFilterSet &LoopBlockSet) {
638   // We don't want to layout the loop linearly in all cases. If the loop header
639   // is just a normal basic block in the loop, we want to look for what block
640   // within the loop is the best one to layout at the top. However, if the loop
641   // header has be pre-merged into a chain due to predecessors not having
642   // analyzable branches, *and* the predecessor it is merged with is *not* part
643   // of the loop, rotating the header into the middle of the loop will create
644   // a non-contiguous range of blocks which is Very Bad. So start with the
645   // header and only rotate if safe.
646   BlockChain &HeaderChain = *BlockToChain[L.getHeader()];
647   if (!LoopBlockSet.count(*HeaderChain.begin()))
648     return nullptr;
649
650   BlockFrequency BestExitEdgeFreq;
651   unsigned BestExitLoopDepth = 0;
652   MachineBasicBlock *ExitingBB = nullptr;
653   // If there are exits to outer loops, loop rotation can severely limit
654   // fallthrough opportunites unless it selects such an exit. Keep a set of
655   // blocks where rotating to exit with that block will reach an outer loop.
656   SmallPtrSet<MachineBasicBlock *, 4> BlocksExitingToOuterLoop;
657
658   DEBUG(dbgs() << "Finding best loop exit for: " << getBlockName(L.getHeader())
659                << "\n");
660   for (MachineBasicBlock *MBB : L.getBlocks()) {
661     BlockChain &Chain = *BlockToChain[MBB];
662     // Ensure that this block is at the end of a chain; otherwise it could be
663     // mid-way through an inner loop or a successor of an unanalyzable branch.
664     if (MBB != *std::prev(Chain.end()))
665       continue;
666
667     // Now walk the successors. We need to establish whether this has a viable
668     // exiting successor and whether it has a viable non-exiting successor.
669     // We store the old exiting state and restore it if a viable looping
670     // successor isn't found.
671     MachineBasicBlock *OldExitingBB = ExitingBB;
672     BlockFrequency OldBestExitEdgeFreq = BestExitEdgeFreq;
673     bool HasLoopingSucc = false;
674     // FIXME: Due to the performance of the probability and weight routines in
675     // the MBPI analysis, we use the internal weights and manually compute the
676     // probabilities to avoid quadratic behavior.
677     uint32_t SumWeight = MBPI->getSumForBlock(MBB);
678     for (MachineBasicBlock *Succ : MBB->successors()) {
679       if (Succ->isLandingPad())
680         continue;
681       if (Succ == MBB)
682         continue;
683       BlockChain &SuccChain = *BlockToChain[Succ];
684       // Don't split chains, either this chain or the successor's chain.
685       if (&Chain == &SuccChain) {
686         DEBUG(dbgs() << "    exiting: " << getBlockName(MBB) << " -> "
687                      << getBlockName(Succ) << " (chain conflict)\n");
688         continue;
689       }
690
691       uint32_t SuccWeight = MBPI->getEdgeWeight(MBB, Succ);
692       if (LoopBlockSet.count(Succ)) {
693         DEBUG(dbgs() << "    looping: " << getBlockName(MBB) << " -> "
694                      << getBlockName(Succ) << " (" << SuccWeight << ")\n");
695         HasLoopingSucc = true;
696         continue;
697       }
698
699       unsigned SuccLoopDepth = 0;
700       if (MachineLoop *ExitLoop = MLI->getLoopFor(Succ)) {
701         SuccLoopDepth = ExitLoop->getLoopDepth();
702         if (ExitLoop->contains(&L))
703           BlocksExitingToOuterLoop.insert(MBB);
704       }
705
706       BranchProbability SuccProb(SuccWeight, SumWeight);
707       BlockFrequency ExitEdgeFreq = MBFI->getBlockFreq(MBB) * SuccProb;
708       DEBUG(dbgs() << "    exiting: " << getBlockName(MBB) << " -> "
709                    << getBlockName(Succ) << " [L:" << SuccLoopDepth << "] (";
710             MBFI->printBlockFreq(dbgs(), ExitEdgeFreq) << ")\n");
711       // Note that we bias this toward an existing layout successor to retain
712       // incoming order in the absence of better information. The exit must have
713       // a frequency higher than the current exit before we consider breaking
714       // the layout.
715       BranchProbability Bias(100 - ExitBlockBias, 100);
716       if (!ExitingBB || SuccLoopDepth > BestExitLoopDepth ||
717           ExitEdgeFreq > BestExitEdgeFreq ||
718           (MBB->isLayoutSuccessor(Succ) &&
719            !(ExitEdgeFreq < BestExitEdgeFreq * Bias))) {
720         BestExitEdgeFreq = ExitEdgeFreq;
721         ExitingBB = MBB;
722       }
723     }
724
725     if (!HasLoopingSucc) {
726       // Restore the old exiting state, no viable looping successor was found.
727       ExitingBB = OldExitingBB;
728       BestExitEdgeFreq = OldBestExitEdgeFreq;
729       continue;
730     }
731   }
732   // Without a candidate exiting block or with only a single block in the
733   // loop, just use the loop header to layout the loop.
734   if (!ExitingBB || L.getNumBlocks() == 1)
735     return nullptr;
736
737   // Also, if we have exit blocks which lead to outer loops but didn't select
738   // one of them as the exiting block we are rotating toward, disable loop
739   // rotation altogether.
740   if (!BlocksExitingToOuterLoop.empty() &&
741       !BlocksExitingToOuterLoop.count(ExitingBB))
742     return nullptr;
743
744   DEBUG(dbgs() << "  Best exiting block: " << getBlockName(ExitingBB) << "\n");
745   return ExitingBB;
746 }
747
748 /// \brief Attempt to rotate an exiting block to the bottom of the loop.
749 ///
750 /// Once we have built a chain, try to rotate it to line up the hot exit block
751 /// with fallthrough out of the loop if doing so doesn't introduce unnecessary
752 /// branches. For example, if the loop has fallthrough into its header and out
753 /// of its bottom already, don't rotate it.
754 void MachineBlockPlacement::rotateLoop(BlockChain &LoopChain,
755                                        MachineBasicBlock *ExitingBB,
756                                        const BlockFilterSet &LoopBlockSet) {
757   if (!ExitingBB)
758     return;
759
760   MachineBasicBlock *Top = *LoopChain.begin();
761   bool ViableTopFallthrough = false;
762   for (MachineBasicBlock *Pred : Top->predecessors()) {
763     BlockChain *PredChain = BlockToChain[Pred];
764     if (!LoopBlockSet.count(Pred) &&
765         (!PredChain || Pred == *std::prev(PredChain->end()))) {
766       ViableTopFallthrough = true;
767       break;
768     }
769   }
770
771   // If the header has viable fallthrough, check whether the current loop
772   // bottom is a viable exiting block. If so, bail out as rotating will
773   // introduce an unnecessary branch.
774   if (ViableTopFallthrough) {
775     MachineBasicBlock *Bottom = *std::prev(LoopChain.end());
776     for (MachineBasicBlock *Succ : Bottom->successors()) {
777       BlockChain *SuccChain = BlockToChain[Succ];
778       if (!LoopBlockSet.count(Succ) &&
779           (!SuccChain || Succ == *SuccChain->begin()))
780         return;
781     }
782   }
783
784   BlockChain::iterator ExitIt =
785       std::find(LoopChain.begin(), LoopChain.end(), ExitingBB);
786   if (ExitIt == LoopChain.end())
787     return;
788
789   std::rotate(LoopChain.begin(), std::next(ExitIt), LoopChain.end());
790 }
791
792 /// \brief Forms basic block chains from the natural loop structures.
793 ///
794 /// These chains are designed to preserve the existing *structure* of the code
795 /// as much as possible. We can then stitch the chains together in a way which
796 /// both preserves the topological structure and minimizes taken conditional
797 /// branches.
798 void MachineBlockPlacement::buildLoopChains(MachineFunction &F,
799                                             MachineLoop &L) {
800   // First recurse through any nested loops, building chains for those inner
801   // loops.
802   for (MachineLoop *InnerLoop : L)
803     buildLoopChains(F, *InnerLoop);
804
805   SmallVector<MachineBasicBlock *, 16> BlockWorkList;
806   BlockFilterSet LoopBlockSet(L.block_begin(), L.block_end());
807
808   // First check to see if there is an obviously preferable top block for the
809   // loop. This will default to the header, but may end up as one of the
810   // predecessors to the header if there is one which will result in strictly
811   // fewer branches in the loop body.
812   MachineBasicBlock *LoopTop = findBestLoopTop(L, LoopBlockSet);
813
814   // If we selected just the header for the loop top, look for a potentially
815   // profitable exit block in the event that rotating the loop can eliminate
816   // branches by placing an exit edge at the bottom.
817   MachineBasicBlock *ExitingBB = nullptr;
818   if (LoopTop == L.getHeader())
819     ExitingBB = findBestLoopExit(F, L, LoopBlockSet);
820
821   BlockChain &LoopChain = *BlockToChain[LoopTop];
822
823   // FIXME: This is a really lame way of walking the chains in the loop: we
824   // walk the blocks, and use a set to prevent visiting a particular chain
825   // twice.
826   SmallPtrSet<BlockChain *, 4> UpdatedPreds;
827   assert(LoopChain.LoopPredecessors == 0);
828   UpdatedPreds.insert(&LoopChain);
829   for (MachineBasicBlock *LoopBB : L.getBlocks()) {
830     BlockChain &Chain = *BlockToChain[LoopBB];
831     if (!UpdatedPreds.insert(&Chain).second)
832       continue;
833
834     assert(Chain.LoopPredecessors == 0);
835     for (MachineBasicBlock *ChainBB : Chain) {
836       assert(BlockToChain[ChainBB] == &Chain);
837       for (MachineBasicBlock *Pred : ChainBB->predecessors()) {
838         if (BlockToChain[Pred] == &Chain || !LoopBlockSet.count(Pred))
839           continue;
840         ++Chain.LoopPredecessors;
841       }
842     }
843
844     if (Chain.LoopPredecessors == 0)
845       BlockWorkList.push_back(*Chain.begin());
846   }
847
848   buildChain(LoopTop, LoopChain, BlockWorkList, &LoopBlockSet);
849   rotateLoop(LoopChain, ExitingBB, LoopBlockSet);
850
851   DEBUG({
852     // Crash at the end so we get all of the debugging output first.
853     bool BadLoop = false;
854     if (LoopChain.LoopPredecessors) {
855       BadLoop = true;
856       dbgs() << "Loop chain contains a block without its preds placed!\n"
857              << "  Loop header:  " << getBlockName(*L.block_begin()) << "\n"
858              << "  Chain header: " << getBlockName(*LoopChain.begin()) << "\n";
859     }
860     for (MachineBasicBlock *ChainBB : LoopChain) {
861       dbgs() << "          ... " << getBlockName(ChainBB) << "\n";
862       if (!LoopBlockSet.erase(ChainBB)) {
863         // We don't mark the loop as bad here because there are real situations
864         // where this can occur. For example, with an unanalyzable fallthrough
865         // from a loop block to a non-loop block or vice versa.
866         dbgs() << "Loop chain contains a block not contained by the loop!\n"
867                << "  Loop header:  " << getBlockName(*L.block_begin()) << "\n"
868                << "  Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
869                << "  Bad block:    " << getBlockName(ChainBB) << "\n";
870       }
871     }
872
873     if (!LoopBlockSet.empty()) {
874       BadLoop = true;
875       for (MachineBasicBlock *LoopBB : LoopBlockSet)
876         dbgs() << "Loop contains blocks never placed into a chain!\n"
877                << "  Loop header:  " << getBlockName(*L.block_begin()) << "\n"
878                << "  Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
879                << "  Bad block:    " << getBlockName(LoopBB) << "\n";
880     }
881     assert(!BadLoop && "Detected problems with the placement of this loop.");
882   });
883 }
884
885 void MachineBlockPlacement::buildCFGChains(MachineFunction &F) {
886   // Ensure that every BB in the function has an associated chain to simplify
887   // the assumptions of the remaining algorithm.
888   SmallVector<MachineOperand, 4> Cond; // For AnalyzeBranch.
889   for (MachineFunction::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
890     MachineBasicBlock *BB = FI;
891     BlockChain *Chain =
892         new (ChainAllocator.Allocate()) BlockChain(BlockToChain, BB);
893     // Also, merge any blocks which we cannot reason about and must preserve
894     // the exact fallthrough behavior for.
895     for (;;) {
896       Cond.clear();
897       MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
898       if (!TII->AnalyzeBranch(*BB, TBB, FBB, Cond) || !FI->canFallThrough())
899         break;
900
901       MachineFunction::iterator NextFI(std::next(FI));
902       MachineBasicBlock *NextBB = NextFI;
903       // Ensure that the layout successor is a viable block, as we know that
904       // fallthrough is a possibility.
905       assert(NextFI != FE && "Can't fallthrough past the last block.");
906       DEBUG(dbgs() << "Pre-merging due to unanalyzable fallthrough: "
907                    << getBlockName(BB) << " -> " << getBlockName(NextBB)
908                    << "\n");
909       Chain->merge(NextBB, nullptr);
910       FI = NextFI;
911       BB = NextBB;
912     }
913   }
914
915   if (OutlineOptionalBranches) {
916     // Find the nearest common dominator of all of F's terminators.
917     MachineBasicBlock *Terminator = nullptr;
918     for (MachineBasicBlock &MBB : F) {
919       if (MBB.succ_size() == 0) {
920         if (Terminator == nullptr)
921           Terminator = &MBB;
922         else
923           Terminator = MDT->findNearestCommonDominator(Terminator, &MBB);
924       }
925     }
926
927     // MBBs dominating this common dominator are unavoidable.
928     UnavoidableBlocks.clear();
929     for (MachineBasicBlock &MBB : F) {
930       if (MDT->dominates(&MBB, Terminator)) {
931         UnavoidableBlocks.insert(&MBB);
932       }
933     }
934   }
935
936   // Build any loop-based chains.
937   for (MachineLoop *L : *MLI)
938     buildLoopChains(F, *L);
939
940   SmallVector<MachineBasicBlock *, 16> BlockWorkList;
941
942   SmallPtrSet<BlockChain *, 4> UpdatedPreds;
943   for (MachineBasicBlock &MBB : F) {
944     BlockChain &Chain = *BlockToChain[&MBB];
945     if (!UpdatedPreds.insert(&Chain).second)
946       continue;
947
948     assert(Chain.LoopPredecessors == 0);
949     for (MachineBasicBlock *ChainBB : Chain) {
950       assert(BlockToChain[ChainBB] == &Chain);
951       for (MachineBasicBlock *Pred : ChainBB->predecessors()) {
952         if (BlockToChain[Pred] == &Chain)
953           continue;
954         ++Chain.LoopPredecessors;
955       }
956     }
957
958     if (Chain.LoopPredecessors == 0)
959       BlockWorkList.push_back(*Chain.begin());
960   }
961
962   BlockChain &FunctionChain = *BlockToChain[&F.front()];
963   buildChain(&F.front(), FunctionChain, BlockWorkList);
964
965 #ifndef NDEBUG
966   typedef SmallPtrSet<MachineBasicBlock *, 16> FunctionBlockSetType;
967 #endif
968   DEBUG({
969     // Crash at the end so we get all of the debugging output first.
970     bool BadFunc = false;
971     FunctionBlockSetType FunctionBlockSet;
972     for (MachineBasicBlock &MBB : F)
973       FunctionBlockSet.insert(&MBB);
974
975     for (MachineBasicBlock *ChainBB : FunctionChain)
976       if (!FunctionBlockSet.erase(ChainBB)) {
977         BadFunc = true;
978         dbgs() << "Function chain contains a block not in the function!\n"
979                << "  Bad block:    " << getBlockName(ChainBB) << "\n";
980       }
981
982     if (!FunctionBlockSet.empty()) {
983       BadFunc = true;
984       for (MachineBasicBlock *RemainingBB : FunctionBlockSet)
985         dbgs() << "Function contains blocks never placed into a chain!\n"
986                << "  Bad block:    " << getBlockName(RemainingBB) << "\n";
987     }
988     assert(!BadFunc && "Detected problems with the block placement.");
989   });
990
991   // Splice the blocks into place.
992   MachineFunction::iterator InsertPos = F.begin();
993   for (MachineBasicBlock *ChainBB : FunctionChain) {
994     DEBUG(dbgs() << (ChainBB == *FunctionChain.begin() ? "Placing chain "
995                                                        : "          ... ")
996                  << getBlockName(ChainBB) << "\n");
997     if (InsertPos != MachineFunction::iterator(ChainBB))
998       F.splice(InsertPos, ChainBB);
999     else
1000       ++InsertPos;
1001
1002     // Update the terminator of the previous block.
1003     if (ChainBB == *FunctionChain.begin())
1004       continue;
1005     MachineBasicBlock *PrevBB = std::prev(MachineFunction::iterator(ChainBB));
1006
1007     // FIXME: It would be awesome of updateTerminator would just return rather
1008     // than assert when the branch cannot be analyzed in order to remove this
1009     // boiler plate.
1010     Cond.clear();
1011     MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
1012     if (!TII->AnalyzeBranch(*PrevBB, TBB, FBB, Cond)) {
1013       // The "PrevBB" is not yet updated to reflect current code layout, so,
1014       //   o. it may fall-through to a block without explict "goto" instruction
1015       //      before layout, and no longer fall-through it after layout; or
1016       //   o. just opposite.
1017       //
1018       // AnalyzeBranch() may return erroneous value for FBB when these two
1019       // situations take place. For the first scenario FBB is mistakenly set
1020       // NULL; for the 2nd scenario, the FBB, which is expected to be NULL,
1021       // is mistakenly pointing to "*BI".
1022       //
1023       bool needUpdateBr = true;
1024       if (!Cond.empty() && (!FBB || FBB == ChainBB)) {
1025         PrevBB->updateTerminator();
1026         needUpdateBr = false;
1027         Cond.clear();
1028         TBB = FBB = nullptr;
1029         if (TII->AnalyzeBranch(*PrevBB, TBB, FBB, Cond)) {
1030           // FIXME: This should never take place.
1031           TBB = FBB = nullptr;
1032         }
1033       }
1034
1035       // If PrevBB has a two-way branch, try to re-order the branches
1036       // such that we branch to the successor with higher weight first.
1037       if (TBB && !Cond.empty() && FBB &&
1038           MBPI->getEdgeWeight(PrevBB, FBB) > MBPI->getEdgeWeight(PrevBB, TBB) &&
1039           !TII->ReverseBranchCondition(Cond)) {
1040         DEBUG(dbgs() << "Reverse order of the two branches: "
1041                      << getBlockName(PrevBB) << "\n");
1042         DEBUG(dbgs() << "    Edge weight: " << MBPI->getEdgeWeight(PrevBB, FBB)
1043                      << " vs " << MBPI->getEdgeWeight(PrevBB, TBB) << "\n");
1044         DebugLoc dl; // FIXME: this is nowhere
1045         TII->RemoveBranch(*PrevBB);
1046         TII->InsertBranch(*PrevBB, FBB, TBB, Cond, dl);
1047         needUpdateBr = true;
1048       }
1049       if (needUpdateBr)
1050         PrevBB->updateTerminator();
1051     }
1052   }
1053
1054   // Fixup the last block.
1055   Cond.clear();
1056   MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
1057   if (!TII->AnalyzeBranch(F.back(), TBB, FBB, Cond))
1058     F.back().updateTerminator();
1059
1060   // Walk through the backedges of the function now that we have fully laid out
1061   // the basic blocks and align the destination of each backedge. We don't rely
1062   // exclusively on the loop info here so that we can align backedges in
1063   // unnatural CFGs and backedges that were introduced purely because of the
1064   // loop rotations done during this layout pass.
1065   // FIXME: Use Function::optForSize().
1066   if (F.getFunction()->hasFnAttribute(Attribute::OptimizeForSize))
1067     return;
1068   if (FunctionChain.begin() == FunctionChain.end())
1069     return; // Empty chain.
1070
1071   const BranchProbability ColdProb(1, 5); // 20%
1072   BlockFrequency EntryFreq = MBFI->getBlockFreq(F.begin());
1073   BlockFrequency WeightedEntryFreq = EntryFreq * ColdProb;
1074   for (MachineBasicBlock *ChainBB : FunctionChain) {
1075     if (ChainBB == *FunctionChain.begin())
1076       continue;
1077
1078     // Don't align non-looping basic blocks. These are unlikely to execute
1079     // enough times to matter in practice. Note that we'll still handle
1080     // unnatural CFGs inside of a natural outer loop (the common case) and
1081     // rotated loops.
1082     MachineLoop *L = MLI->getLoopFor(ChainBB);
1083     if (!L)
1084       continue;
1085
1086     unsigned Align = TLI->getPrefLoopAlignment(L);
1087     if (!Align)
1088       continue; // Don't care about loop alignment.
1089
1090     // If the block is cold relative to the function entry don't waste space
1091     // aligning it.
1092     BlockFrequency Freq = MBFI->getBlockFreq(ChainBB);
1093     if (Freq < WeightedEntryFreq)
1094       continue;
1095
1096     // If the block is cold relative to its loop header, don't align it
1097     // regardless of what edges into the block exist.
1098     MachineBasicBlock *LoopHeader = L->getHeader();
1099     BlockFrequency LoopHeaderFreq = MBFI->getBlockFreq(LoopHeader);
1100     if (Freq < (LoopHeaderFreq * ColdProb))
1101       continue;
1102
1103     // Check for the existence of a non-layout predecessor which would benefit
1104     // from aligning this block.
1105     MachineBasicBlock *LayoutPred =
1106         &*std::prev(MachineFunction::iterator(ChainBB));
1107
1108     // Force alignment if all the predecessors are jumps. We already checked
1109     // that the block isn't cold above.
1110     if (!LayoutPred->isSuccessor(ChainBB)) {
1111       ChainBB->setAlignment(Align);
1112       continue;
1113     }
1114
1115     // Align this block if the layout predecessor's edge into this block is
1116     // cold relative to the block. When this is true, other predecessors make up
1117     // all of the hot entries into the block and thus alignment is likely to be
1118     // important.
1119     BranchProbability LayoutProb =
1120         MBPI->getEdgeProbability(LayoutPred, ChainBB);
1121     BlockFrequency LayoutEdgeFreq = MBFI->getBlockFreq(LayoutPred) * LayoutProb;
1122     if (LayoutEdgeFreq <= (Freq * ColdProb))
1123       ChainBB->setAlignment(Align);
1124   }
1125 }
1126
1127 bool MachineBlockPlacement::runOnMachineFunction(MachineFunction &F) {
1128   // Check for single-block functions and skip them.
1129   if (std::next(F.begin()) == F.end())
1130     return false;
1131
1132   if (skipOptnoneFunction(*F.getFunction()))
1133     return false;
1134
1135   MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
1136   MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
1137   MLI = &getAnalysis<MachineLoopInfo>();
1138   TII = F.getSubtarget().getInstrInfo();
1139   TLI = F.getSubtarget().getTargetLowering();
1140   MDT = &getAnalysis<MachineDominatorTree>();
1141   assert(BlockToChain.empty());
1142
1143   buildCFGChains(F);
1144
1145   BlockToChain.clear();
1146   ChainAllocator.DestroyAll();
1147
1148   if (AlignAllBlock)
1149     // Align all of the blocks in the function to a specific alignment.
1150     for (MachineBasicBlock &MBB : F)
1151       MBB.setAlignment(AlignAllBlock);
1152
1153   // We always return true as we have no way to track whether the final order
1154   // differs from the original order.
1155   return true;
1156 }
1157
1158 namespace {
1159 /// \brief A pass to compute block placement statistics.
1160 ///
1161 /// A separate pass to compute interesting statistics for evaluating block
1162 /// placement. This is separate from the actual placement pass so that they can
1163 /// be computed in the absence of any placement transformations or when using
1164 /// alternative placement strategies.
1165 class MachineBlockPlacementStats : public MachineFunctionPass {
1166   /// \brief A handle to the branch probability pass.
1167   const MachineBranchProbabilityInfo *MBPI;
1168
1169   /// \brief A handle to the function-wide block frequency pass.
1170   const MachineBlockFrequencyInfo *MBFI;
1171
1172 public:
1173   static char ID; // Pass identification, replacement for typeid
1174   MachineBlockPlacementStats() : MachineFunctionPass(ID) {
1175     initializeMachineBlockPlacementStatsPass(*PassRegistry::getPassRegistry());
1176   }
1177
1178   bool runOnMachineFunction(MachineFunction &F) override;
1179
1180   void getAnalysisUsage(AnalysisUsage &AU) const override {
1181     AU.addRequired<MachineBranchProbabilityInfo>();
1182     AU.addRequired<MachineBlockFrequencyInfo>();
1183     AU.setPreservesAll();
1184     MachineFunctionPass::getAnalysisUsage(AU);
1185   }
1186 };
1187 }
1188
1189 char MachineBlockPlacementStats::ID = 0;
1190 char &llvm::MachineBlockPlacementStatsID = MachineBlockPlacementStats::ID;
1191 INITIALIZE_PASS_BEGIN(MachineBlockPlacementStats, "block-placement-stats",
1192                       "Basic Block Placement Stats", false, false)
1193 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
1194 INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
1195 INITIALIZE_PASS_END(MachineBlockPlacementStats, "block-placement-stats",
1196                     "Basic Block Placement Stats", false, false)
1197
1198 bool MachineBlockPlacementStats::runOnMachineFunction(MachineFunction &F) {
1199   // Check for single-block functions and skip them.
1200   if (std::next(F.begin()) == F.end())
1201     return false;
1202
1203   MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
1204   MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
1205
1206   for (MachineBasicBlock &MBB : F) {
1207     BlockFrequency BlockFreq = MBFI->getBlockFreq(&MBB);
1208     Statistic &NumBranches =
1209         (MBB.succ_size() > 1) ? NumCondBranches : NumUncondBranches;
1210     Statistic &BranchTakenFreq =
1211         (MBB.succ_size() > 1) ? CondBranchTakenFreq : UncondBranchTakenFreq;
1212     for (MachineBasicBlock *Succ : MBB.successors()) {
1213       // Skip if this successor is a fallthrough.
1214       if (MBB.isLayoutSuccessor(Succ))
1215         continue;
1216
1217       BlockFrequency EdgeFreq =
1218           BlockFreq * MBPI->getEdgeProbability(&MBB, Succ);
1219       ++NumBranches;
1220       BranchTakenFreq += EdgeFreq.getFrequency();
1221     }
1222   }
1223
1224   return false;
1225 }