xref: /llvm-project/llvm/lib/CodeGen/MachineBlockPlacement.cpp (revision 36cd84bdd9a7bca22b04341aa6abbf4d6b6e86d2)
1 //===- MachineBlockPlacement.cpp - Basic Block Code Layout optimization ---===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements basic block placement transformations using the CFG
10 // structure and branch probability estimates.
11 //
12 // The pass strives to preserve the structure of the CFG (that is, retain
13 // a topological ordering of basic blocks) in the absence of a *strong* signal
14 // to the contrary from probabilities. However, within the CFG structure, it
15 // attempts to choose an ordering which favors placing more likely sequences of
16 // blocks adjacent to each other.
17 //
18 // The algorithm works from the inner-most loop within a function outward, and
19 // at each stage walks through the basic blocks, trying to coalesce them into
20 // sequential chains where allowed by the CFG (or demanded by heavy
21 // probabilities). Finally, it walks the blocks in topological order, and the
22 // first time it reaches a chain of basic blocks, it schedules them in the
23 // function in-order.
24 //
25 //===----------------------------------------------------------------------===//
26 
27 #include "BranchFolding.h"
28 #include "llvm/ADT/ArrayRef.h"
29 #include "llvm/ADT/DenseMap.h"
30 #include "llvm/ADT/STLExtras.h"
31 #include "llvm/ADT/SetVector.h"
32 #include "llvm/ADT/SmallPtrSet.h"
33 #include "llvm/ADT/SmallVector.h"
34 #include "llvm/ADT/Statistic.h"
35 #include "llvm/Analysis/BlockFrequencyInfoImpl.h"
36 #include "llvm/CodeGen/MachineBasicBlock.h"
37 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
38 #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
39 #include "llvm/CodeGen/MachineFunction.h"
40 #include "llvm/CodeGen/MachineFunctionPass.h"
41 #include "llvm/CodeGen/MachineLoopInfo.h"
42 #include "llvm/CodeGen/MachineModuleInfo.h"
43 #include "llvm/CodeGen/MachinePostDominators.h"
44 #include "llvm/CodeGen/TailDuplicator.h"
45 #include "llvm/CodeGen/TargetInstrInfo.h"
46 #include "llvm/CodeGen/TargetLowering.h"
47 #include "llvm/CodeGen/TargetPassConfig.h"
48 #include "llvm/CodeGen/TargetSubtargetInfo.h"
49 #include "llvm/IR/DebugLoc.h"
50 #include "llvm/IR/Function.h"
51 #include "llvm/Pass.h"
52 #include "llvm/Support/Allocator.h"
53 #include "llvm/Support/BlockFrequency.h"
54 #include "llvm/Support/BranchProbability.h"
55 #include "llvm/Support/CodeGen.h"
56 #include "llvm/Support/CommandLine.h"
57 #include "llvm/Support/Compiler.h"
58 #include "llvm/Support/Debug.h"
59 #include "llvm/Support/raw_ostream.h"
60 #include "llvm/Target/TargetMachine.h"
61 #include <algorithm>
62 #include <cassert>
63 #include <cstdint>
64 #include <iterator>
65 #include <memory>
66 #include <string>
67 #include <tuple>
68 #include <utility>
69 #include <vector>
70 
71 using namespace llvm;
72 
73 #define DEBUG_TYPE "block-placement"
74 
75 STATISTIC(NumCondBranches, "Number of conditional branches");
76 STATISTIC(NumUncondBranches, "Number of unconditional branches");
77 STATISTIC(CondBranchTakenFreq,
78           "Potential frequency of taking conditional branches");
79 STATISTIC(UncondBranchTakenFreq,
80           "Potential frequency of taking unconditional branches");
81 
82 static cl::opt<unsigned> AlignAllBlock("align-all-blocks",
83                                        cl::desc("Force the alignment of all "
84                                                 "blocks in the function."),
85                                        cl::init(0), cl::Hidden);
86 
87 static cl::opt<unsigned> AlignAllNonFallThruBlocks(
88     "align-all-nofallthru-blocks",
89     cl::desc("Force the alignment of all "
90              "blocks that have no fall-through predecessors (i.e. don't add "
91              "nops that are executed)."),
92     cl::init(0), cl::Hidden);
93 
94 // FIXME: Find a good default for this flag and remove the flag.
95 static cl::opt<unsigned> ExitBlockBias(
96     "block-placement-exit-block-bias",
97     cl::desc("Block frequency percentage a loop exit block needs "
98              "over the original exit to be considered the new exit."),
99     cl::init(0), cl::Hidden);
100 
101 // Definition:
102 // - Outlining: placement of a basic block outside the chain or hot path.
103 
104 static cl::opt<unsigned> LoopToColdBlockRatio(
105     "loop-to-cold-block-ratio",
106     cl::desc("Outline loop blocks from loop chain if (frequency of loop) / "
107              "(frequency of block) is greater than this ratio"),
108     cl::init(5), cl::Hidden);
109 
110 static cl::opt<bool> ForceLoopColdBlock(
111     "force-loop-cold-block",
112     cl::desc("Force outlining cold blocks from loops."),
113     cl::init(false), cl::Hidden);
114 
115 static cl::opt<bool>
116     PreciseRotationCost("precise-rotation-cost",
117                         cl::desc("Model the cost of loop rotation more "
118                                  "precisely by using profile data."),
119                         cl::init(false), cl::Hidden);
120 
121 static cl::opt<bool>
122     ForcePreciseRotationCost("force-precise-rotation-cost",
123                              cl::desc("Force the use of precise cost "
124                                       "loop rotation strategy."),
125                              cl::init(false), cl::Hidden);
126 
127 static cl::opt<unsigned> MisfetchCost(
128     "misfetch-cost",
129     cl::desc("Cost that models the probabilistic risk of an instruction "
130              "misfetch due to a jump comparing to falling through, whose cost "
131              "is zero."),
132     cl::init(1), cl::Hidden);
133 
134 static cl::opt<unsigned> JumpInstCost("jump-inst-cost",
135                                       cl::desc("Cost of jump instructions."),
136                                       cl::init(1), cl::Hidden);
137 static cl::opt<bool>
138 TailDupPlacement("tail-dup-placement",
139               cl::desc("Perform tail duplication during placement. "
140                        "Creates more fallthrough opportunites in "
141                        "outline branches."),
142               cl::init(true), cl::Hidden);
143 
144 static cl::opt<bool>
145 BranchFoldPlacement("branch-fold-placement",
146               cl::desc("Perform branch folding during placement. "
147                        "Reduces code size."),
148               cl::init(true), cl::Hidden);
149 
150 // Heuristic for tail duplication.
151 static cl::opt<unsigned> TailDupPlacementThreshold(
152     "tail-dup-placement-threshold",
153     cl::desc("Instruction cutoff for tail duplication during layout. "
154              "Tail merging during layout is forced to have a threshold "
155              "that won't conflict."), cl::init(2),
156     cl::Hidden);
157 
158 // Heuristic for aggressive tail duplication.
159 static cl::opt<unsigned> TailDupPlacementAggressiveThreshold(
160     "tail-dup-placement-aggressive-threshold",
161     cl::desc("Instruction cutoff for aggressive tail duplication during "
162              "layout. Used at -O3. Tail merging during layout is forced to "
163              "have a threshold that won't conflict."), cl::init(4),
164     cl::Hidden);
165 
166 // Heuristic for tail duplication.
167 static cl::opt<unsigned> TailDupPlacementPenalty(
168     "tail-dup-placement-penalty",
169     cl::desc("Cost penalty for blocks that can avoid breaking CFG by copying. "
170              "Copying can increase fallthrough, but it also increases icache "
171              "pressure. This parameter controls the penalty to account for that. "
172              "Percent as integer."),
173     cl::init(2),
174     cl::Hidden);
175 
176 // Heuristic for triangle chains.
177 static cl::opt<unsigned> TriangleChainCount(
178     "triangle-chain-count",
179     cl::desc("Number of triangle-shaped-CFG's that need to be in a row for the "
180              "triangle tail duplication heuristic to kick in. 0 to disable."),
181     cl::init(2),
182     cl::Hidden);
183 
184 extern cl::opt<unsigned> StaticLikelyProb;
185 extern cl::opt<unsigned> ProfileLikelyProb;
186 
187 // Internal option used to control BFI display only after MBP pass.
188 // Defined in CodeGen/MachineBlockFrequencyInfo.cpp:
189 // -view-block-layout-with-bfi=
190 extern cl::opt<GVDAGType> ViewBlockLayoutWithBFI;
191 
192 // Command line option to specify the name of the function for CFG dump
193 // Defined in Analysis/BlockFrequencyInfo.cpp:  -view-bfi-func-name=
194 extern cl::opt<std::string> ViewBlockFreqFuncName;
195 
196 namespace {
197 
198 class BlockChain;
199 
200 /// Type for our function-wide basic block -> block chain mapping.
201 using BlockToChainMapType = DenseMap<const MachineBasicBlock *, BlockChain *>;
202 
203 /// A chain of blocks which will be laid out contiguously.
204 ///
205 /// This is the datastructure representing a chain of consecutive blocks that
206 /// are profitable to layout together in order to maximize fallthrough
207 /// probabilities and code locality. We also can use a block chain to represent
208 /// a sequence of basic blocks which have some external (correctness)
209 /// requirement for sequential layout.
210 ///
211 /// Chains can be built around a single basic block and can be merged to grow
212 /// them. They participate in a block-to-chain mapping, which is updated
213 /// automatically as chains are merged together.
214 class BlockChain {
215   /// The sequence of blocks belonging to this chain.
216   ///
217   /// This is the sequence of blocks for a particular chain. These will be laid
218   /// out in-order within the function.
219   SmallVector<MachineBasicBlock *, 4> Blocks;
220 
221   /// A handle to the function-wide basic block to block chain mapping.
222   ///
223   /// This is retained in each block chain to simplify the computation of child
224   /// block chains for SCC-formation and iteration. We store the edges to child
225   /// basic blocks, and map them back to their associated chains using this
226   /// structure.
227   BlockToChainMapType &BlockToChain;
228 
229 public:
230   /// Construct a new BlockChain.
231   ///
232   /// This builds a new block chain representing a single basic block in the
233   /// function. It also registers itself as the chain that block participates
234   /// in with the BlockToChain mapping.
235   BlockChain(BlockToChainMapType &BlockToChain, MachineBasicBlock *BB)
236       : Blocks(1, BB), BlockToChain(BlockToChain) {
237     assert(BB && "Cannot create a chain with a null basic block");
238     BlockToChain[BB] = this;
239   }
240 
241   /// Iterator over blocks within the chain.
242   using iterator = SmallVectorImpl<MachineBasicBlock *>::iterator;
243   using const_iterator = SmallVectorImpl<MachineBasicBlock *>::const_iterator;
244 
245   /// Beginning of blocks within the chain.
246   iterator begin() { return Blocks.begin(); }
247   const_iterator begin() const { return Blocks.begin(); }
248 
249   /// End of blocks within the chain.
250   iterator end() { return Blocks.end(); }
251   const_iterator end() const { return Blocks.end(); }
252 
253   bool remove(MachineBasicBlock* BB) {
254     for(iterator i = begin(); i != end(); ++i) {
255       if (*i == BB) {
256         Blocks.erase(i);
257         return true;
258       }
259     }
260     return false;
261   }
262 
263   /// Merge a block chain into this one.
264   ///
265   /// This routine merges a block chain into this one. It takes care of forming
266   /// a contiguous sequence of basic blocks, updating the edge list, and
267   /// updating the block -> chain mapping. It does not free or tear down the
268   /// old chain, but the old chain's block list is no longer valid.
269   void merge(MachineBasicBlock *BB, BlockChain *Chain) {
270     assert(BB && "Can't merge a null block.");
271     assert(!Blocks.empty() && "Can't merge into an empty chain.");
272 
273     // Fast path in case we don't have a chain already.
274     if (!Chain) {
275       assert(!BlockToChain[BB] &&
276              "Passed chain is null, but BB has entry in BlockToChain.");
277       Blocks.push_back(BB);
278       BlockToChain[BB] = this;
279       return;
280     }
281 
282     assert(BB == *Chain->begin() && "Passed BB is not head of Chain.");
283     assert(Chain->begin() != Chain->end());
284 
285     // Update the incoming blocks to point to this chain, and add them to the
286     // chain structure.
287     for (MachineBasicBlock *ChainBB : *Chain) {
288       Blocks.push_back(ChainBB);
289       assert(BlockToChain[ChainBB] == Chain && "Incoming blocks not in chain.");
290       BlockToChain[ChainBB] = this;
291     }
292   }
293 
294 #ifndef NDEBUG
295   /// Dump the blocks in this chain.
296   LLVM_DUMP_METHOD void dump() {
297     for (MachineBasicBlock *MBB : *this)
298       MBB->dump();
299   }
300 #endif // NDEBUG
301 
302   /// Count of predecessors of any block within the chain which have not
303   /// yet been scheduled.  In general, we will delay scheduling this chain
304   /// until those predecessors are scheduled (or we find a sufficiently good
305   /// reason to override this heuristic.)  Note that when forming loop chains,
306   /// blocks outside the loop are ignored and treated as if they were already
307   /// scheduled.
308   ///
309   /// Note: This field is reinitialized multiple times - once for each loop,
310   /// and then once for the function as a whole.
311   unsigned UnscheduledPredecessors = 0;
312 };
313 
314 class MachineBlockPlacement : public MachineFunctionPass {
315   /// A type for a block filter set.
316   using BlockFilterSet = SmallSetVector<const MachineBasicBlock *, 16>;
317 
318   /// Pair struct containing basic block and taildup profitability
319   struct BlockAndTailDupResult {
320     MachineBasicBlock *BB;
321     bool ShouldTailDup;
322   };
323 
324   /// Triple struct containing edge weight and the edge.
325   struct WeightedEdge {
326     BlockFrequency Weight;
327     MachineBasicBlock *Src;
328     MachineBasicBlock *Dest;
329   };
330 
331   /// work lists of blocks that are ready to be laid out
332   SmallVector<MachineBasicBlock *, 16> BlockWorkList;
333   SmallVector<MachineBasicBlock *, 16> EHPadWorkList;
334 
335   /// Edges that have already been computed as optimal.
336   DenseMap<const MachineBasicBlock *, BlockAndTailDupResult> ComputedEdges;
337 
338   /// Machine Function
339   MachineFunction *F;
340 
341   /// A handle to the branch probability pass.
342   const MachineBranchProbabilityInfo *MBPI;
343 
344   /// A handle to the function-wide block frequency pass.
345   std::unique_ptr<BranchFolder::MBFIWrapper> MBFI;
346 
347   /// A handle to the loop info.
348   MachineLoopInfo *MLI;
349 
350   /// Preferred loop exit.
351   /// Member variable for convenience. It may be removed by duplication deep
352   /// in the call stack.
353   MachineBasicBlock *PreferredLoopExit;
354 
355   /// A handle to the target's instruction info.
356   const TargetInstrInfo *TII;
357 
358   /// A handle to the target's lowering info.
359   const TargetLoweringBase *TLI;
360 
361   /// A handle to the post dominator tree.
362   MachinePostDominatorTree *MPDT;
363 
364   /// Duplicator used to duplicate tails during placement.
365   ///
366   /// Placement decisions can open up new tail duplication opportunities, but
367   /// since tail duplication affects placement decisions of later blocks, it
368   /// must be done inline.
369   TailDuplicator TailDup;
370 
371   /// Allocator and owner of BlockChain structures.
372   ///
373   /// We build BlockChains lazily while processing the loop structure of
374   /// a function. To reduce malloc traffic, we allocate them using this
375   /// slab-like allocator, and destroy them after the pass completes. An
376   /// important guarantee is that this allocator produces stable pointers to
377   /// the chains.
378   SpecificBumpPtrAllocator<BlockChain> ChainAllocator;
379 
380   /// Function wide BasicBlock to BlockChain mapping.
381   ///
382   /// This mapping allows efficiently moving from any given basic block to the
383   /// BlockChain it participates in, if any. We use it to, among other things,
384   /// allow implicitly defining edges between chains as the existing edges
385   /// between basic blocks.
386   DenseMap<const MachineBasicBlock *, BlockChain *> BlockToChain;
387 
388 #ifndef NDEBUG
389   /// The set of basic blocks that have terminators that cannot be fully
390   /// analyzed.  These basic blocks cannot be re-ordered safely by
391   /// MachineBlockPlacement, and we must preserve physical layout of these
392   /// blocks and their successors through the pass.
393   SmallPtrSet<MachineBasicBlock *, 4> BlocksWithUnanalyzableExits;
394 #endif
395 
396   /// Decrease the UnscheduledPredecessors count for all blocks in chain, and
397   /// if the count goes to 0, add them to the appropriate work list.
398   void markChainSuccessors(
399       const BlockChain &Chain, const MachineBasicBlock *LoopHeaderBB,
400       const BlockFilterSet *BlockFilter = nullptr);
401 
402   /// Decrease the UnscheduledPredecessors count for a single block, and
403   /// if the count goes to 0, add them to the appropriate work list.
404   void markBlockSuccessors(
405       const BlockChain &Chain, const MachineBasicBlock *BB,
406       const MachineBasicBlock *LoopHeaderBB,
407       const BlockFilterSet *BlockFilter = nullptr);
408 
409   BranchProbability
410   collectViableSuccessors(
411       const MachineBasicBlock *BB, const BlockChain &Chain,
412       const BlockFilterSet *BlockFilter,
413       SmallVector<MachineBasicBlock *, 4> &Successors);
414   bool shouldPredBlockBeOutlined(
415       const MachineBasicBlock *BB, const MachineBasicBlock *Succ,
416       const BlockChain &Chain, const BlockFilterSet *BlockFilter,
417       BranchProbability SuccProb, BranchProbability HotProb);
418   bool repeatedlyTailDuplicateBlock(
419       MachineBasicBlock *BB, MachineBasicBlock *&LPred,
420       const MachineBasicBlock *LoopHeaderBB,
421       BlockChain &Chain, BlockFilterSet *BlockFilter,
422       MachineFunction::iterator &PrevUnplacedBlockIt);
423   bool maybeTailDuplicateBlock(
424       MachineBasicBlock *BB, MachineBasicBlock *LPred,
425       BlockChain &Chain, BlockFilterSet *BlockFilter,
426       MachineFunction::iterator &PrevUnplacedBlockIt,
427       bool &DuplicatedToLPred);
428   bool hasBetterLayoutPredecessor(
429       const MachineBasicBlock *BB, const MachineBasicBlock *Succ,
430       const BlockChain &SuccChain, BranchProbability SuccProb,
431       BranchProbability RealSuccProb, const BlockChain &Chain,
432       const BlockFilterSet *BlockFilter);
433   BlockAndTailDupResult selectBestSuccessor(
434       const MachineBasicBlock *BB, const BlockChain &Chain,
435       const BlockFilterSet *BlockFilter);
436   MachineBasicBlock *selectBestCandidateBlock(
437       const BlockChain &Chain, SmallVectorImpl<MachineBasicBlock *> &WorkList);
438   MachineBasicBlock *getFirstUnplacedBlock(
439       const BlockChain &PlacedChain,
440       MachineFunction::iterator &PrevUnplacedBlockIt,
441       const BlockFilterSet *BlockFilter);
442 
443   /// Add a basic block to the work list if it is appropriate.
444   ///
445   /// If the optional parameter BlockFilter is provided, only MBB
446   /// present in the set will be added to the worklist. If nullptr
447   /// is provided, no filtering occurs.
448   void fillWorkLists(const MachineBasicBlock *MBB,
449                      SmallPtrSetImpl<BlockChain *> &UpdatedPreds,
450                      const BlockFilterSet *BlockFilter);
451 
452   void buildChain(const MachineBasicBlock *BB, BlockChain &Chain,
453                   BlockFilterSet *BlockFilter = nullptr);
454   bool canMoveBottomBlockToTop(const MachineBasicBlock *BottomBlock,
455                                const MachineBasicBlock *OldTop);
456   bool hasViableTopFallthrough(const MachineBasicBlock *Top,
457                                const BlockFilterSet &LoopBlockSet);
458   BlockFrequency TopFallThroughFreq(const MachineBasicBlock *Top,
459                                     const BlockFilterSet &LoopBlockSet);
460   BlockFrequency FallThroughGains(const MachineBasicBlock *NewTop,
461                                   const MachineBasicBlock *OldTop,
462                                   const MachineBasicBlock *ExitBB,
463                                   const BlockFilterSet &LoopBlockSet);
464   MachineBasicBlock *findBestLoopTopHelper(MachineBasicBlock *OldTop,
465                                            const MachineLoop &L,
466                                            const BlockFilterSet &LoopBlockSet,
467                                            bool HasStaticProfileOnly = false);
468   MachineBasicBlock *findBestLoopTop(
469       const MachineLoop &L, const BlockFilterSet &LoopBlockSet);
470   MachineBasicBlock *findBestLoopTopNoProfile(
471       const MachineLoop &L, const BlockFilterSet &LoopBlockSet);
472   MachineBasicBlock *findBestLoopExit(
473       const MachineLoop &L, const BlockFilterSet &LoopBlockSet);
474   BlockFilterSet collectLoopBlockSet(const MachineLoop &L);
475   void buildLoopChains(const MachineLoop &L);
476   void rotateLoop(
477       BlockChain &LoopChain, const MachineBasicBlock *ExitingBB,
478       const BlockFilterSet &LoopBlockSet);
479   void rotateLoopWithProfile(
480       BlockChain &LoopChain, const MachineLoop &L,
481       const BlockFilterSet &LoopBlockSet);
482   void buildCFGChains();
483   void optimizeBranches();
484   void alignBlocks();
485   /// Returns true if a block should be tail-duplicated to increase fallthrough
486   /// opportunities.
487   bool shouldTailDuplicate(MachineBasicBlock *BB);
488   /// Check the edge frequencies to see if tail duplication will increase
489   /// fallthroughs.
490   bool isProfitableToTailDup(
491     const MachineBasicBlock *BB, const MachineBasicBlock *Succ,
492     BranchProbability QProb,
493     const BlockChain &Chain, const BlockFilterSet *BlockFilter);
494 
495   /// Check for a trellis layout.
496   bool isTrellis(const MachineBasicBlock *BB,
497                  const SmallVectorImpl<MachineBasicBlock *> &ViableSuccs,
498                  const BlockChain &Chain, const BlockFilterSet *BlockFilter);
499 
500   /// Get the best successor given a trellis layout.
501   BlockAndTailDupResult getBestTrellisSuccessor(
502       const MachineBasicBlock *BB,
503       const SmallVectorImpl<MachineBasicBlock *> &ViableSuccs,
504       BranchProbability AdjustedSumProb, const BlockChain &Chain,
505       const BlockFilterSet *BlockFilter);
506 
507   /// Get the best pair of non-conflicting edges.
508   static std::pair<WeightedEdge, WeightedEdge> getBestNonConflictingEdges(
509       const MachineBasicBlock *BB,
510       MutableArrayRef<SmallVector<WeightedEdge, 8>> Edges);
511 
512   /// Returns true if a block can tail duplicate into all unplaced
513   /// predecessors. Filters based on loop.
514   bool canTailDuplicateUnplacedPreds(
515       const MachineBasicBlock *BB, MachineBasicBlock *Succ,
516       const BlockChain &Chain, const BlockFilterSet *BlockFilter);
517 
518   /// Find chains of triangles to tail-duplicate where a global analysis works,
519   /// but a local analysis would not find them.
520   void precomputeTriangleChains();
521 
522 public:
523   static char ID; // Pass identification, replacement for typeid
524 
525   MachineBlockPlacement() : MachineFunctionPass(ID) {
526     initializeMachineBlockPlacementPass(*PassRegistry::getPassRegistry());
527   }
528 
529   bool runOnMachineFunction(MachineFunction &F) override;
530 
531   bool allowTailDupPlacement() const {
532     assert(F);
533     return TailDupPlacement && !F->getTarget().requiresStructuredCFG();
534   }
535 
536   void getAnalysisUsage(AnalysisUsage &AU) const override {
537     AU.addRequired<MachineBranchProbabilityInfo>();
538     AU.addRequired<MachineBlockFrequencyInfo>();
539     if (TailDupPlacement)
540       AU.addRequired<MachinePostDominatorTree>();
541     AU.addRequired<MachineLoopInfo>();
542     AU.addRequired<TargetPassConfig>();
543     MachineFunctionPass::getAnalysisUsage(AU);
544   }
545 };
546 
547 } // end anonymous namespace
548 
549 char MachineBlockPlacement::ID = 0;
550 
551 char &llvm::MachineBlockPlacementID = MachineBlockPlacement::ID;
552 
553 INITIALIZE_PASS_BEGIN(MachineBlockPlacement, DEBUG_TYPE,
554                       "Branch Probability Basic Block Placement", false, false)
555 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
556 INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
557 INITIALIZE_PASS_DEPENDENCY(MachinePostDominatorTree)
558 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
559 INITIALIZE_PASS_END(MachineBlockPlacement, DEBUG_TYPE,
560                     "Branch Probability Basic Block Placement", false, false)
561 
562 #ifndef NDEBUG
563 /// Helper to print the name of a MBB.
564 ///
565 /// Only used by debug logging.
566 static std::string getBlockName(const MachineBasicBlock *BB) {
567   std::string Result;
568   raw_string_ostream OS(Result);
569   OS << printMBBReference(*BB);
570   OS << " ('" << BB->getName() << "')";
571   OS.flush();
572   return Result;
573 }
574 #endif
575 
576 /// Mark a chain's successors as having one fewer preds.
577 ///
578 /// When a chain is being merged into the "placed" chain, this routine will
579 /// quickly walk the successors of each block in the chain and mark them as
580 /// having one fewer active predecessor. It also adds any successors of this
581 /// chain which reach the zero-predecessor state to the appropriate worklist.
582 void MachineBlockPlacement::markChainSuccessors(
583     const BlockChain &Chain, const MachineBasicBlock *LoopHeaderBB,
584     const BlockFilterSet *BlockFilter) {
585   // Walk all the blocks in this chain, marking their successors as having
586   // a predecessor placed.
587   for (MachineBasicBlock *MBB : Chain) {
588     markBlockSuccessors(Chain, MBB, LoopHeaderBB, BlockFilter);
589   }
590 }
591 
592 /// Mark a single block's successors as having one fewer preds.
593 ///
594 /// Under normal circumstances, this is only called by markChainSuccessors,
595 /// but if a block that was to be placed is completely tail-duplicated away,
596 /// and was duplicated into the chain end, we need to redo markBlockSuccessors
597 /// for just that block.
598 void MachineBlockPlacement::markBlockSuccessors(
599     const BlockChain &Chain, const MachineBasicBlock *MBB,
600     const MachineBasicBlock *LoopHeaderBB, const BlockFilterSet *BlockFilter) {
601   // Add any successors for which this is the only un-placed in-loop
602   // predecessor to the worklist as a viable candidate for CFG-neutral
603   // placement. No subsequent placement of this block will violate the CFG
604   // shape, so we get to use heuristics to choose a favorable placement.
605   for (MachineBasicBlock *Succ : MBB->successors()) {
606     if (BlockFilter && !BlockFilter->count(Succ))
607       continue;
608     BlockChain &SuccChain = *BlockToChain[Succ];
609     // Disregard edges within a fixed chain, or edges to the loop header.
610     if (&Chain == &SuccChain || Succ == LoopHeaderBB)
611       continue;
612 
613     // This is a cross-chain edge that is within the loop, so decrement the
614     // loop predecessor count of the destination chain.
615     if (SuccChain.UnscheduledPredecessors == 0 ||
616         --SuccChain.UnscheduledPredecessors > 0)
617       continue;
618 
619     auto *NewBB = *SuccChain.begin();
620     if (NewBB->isEHPad())
621       EHPadWorkList.push_back(NewBB);
622     else
623       BlockWorkList.push_back(NewBB);
624   }
625 }
626 
627 /// This helper function collects the set of successors of block
628 /// \p BB that are allowed to be its layout successors, and return
629 /// the total branch probability of edges from \p BB to those
630 /// blocks.
631 BranchProbability MachineBlockPlacement::collectViableSuccessors(
632     const MachineBasicBlock *BB, const BlockChain &Chain,
633     const BlockFilterSet *BlockFilter,
634     SmallVector<MachineBasicBlock *, 4> &Successors) {
635   // Adjust edge probabilities by excluding edges pointing to blocks that is
636   // either not in BlockFilter or is already in the current chain. Consider the
637   // following CFG:
638   //
639   //     --->A
640   //     |  / \
641   //     | B   C
642   //     |  \ / \
643   //     ----D   E
644   //
645   // Assume A->C is very hot (>90%), and C->D has a 50% probability, then after
646   // A->C is chosen as a fall-through, D won't be selected as a successor of C
647   // due to CFG constraint (the probability of C->D is not greater than
648   // HotProb to break topo-order). If we exclude E that is not in BlockFilter
649   // when calculating the probability of C->D, D will be selected and we
650   // will get A C D B as the layout of this loop.
651   auto AdjustedSumProb = BranchProbability::getOne();
652   for (MachineBasicBlock *Succ : BB->successors()) {
653     bool SkipSucc = false;
654     if (Succ->isEHPad() || (BlockFilter && !BlockFilter->count(Succ))) {
655       SkipSucc = true;
656     } else {
657       BlockChain *SuccChain = BlockToChain[Succ];
658       if (SuccChain == &Chain) {
659         SkipSucc = true;
660       } else if (Succ != *SuccChain->begin()) {
661         LLVM_DEBUG(dbgs() << "    " << getBlockName(Succ)
662                           << " -> Mid chain!\n");
663         continue;
664       }
665     }
666     if (SkipSucc)
667       AdjustedSumProb -= MBPI->getEdgeProbability(BB, Succ);
668     else
669       Successors.push_back(Succ);
670   }
671 
672   return AdjustedSumProb;
673 }
674 
675 /// The helper function returns the branch probability that is adjusted
676 /// or normalized over the new total \p AdjustedSumProb.
677 static BranchProbability
678 getAdjustedProbability(BranchProbability OrigProb,
679                        BranchProbability AdjustedSumProb) {
680   BranchProbability SuccProb;
681   uint32_t SuccProbN = OrigProb.getNumerator();
682   uint32_t SuccProbD = AdjustedSumProb.getNumerator();
683   if (SuccProbN >= SuccProbD)
684     SuccProb = BranchProbability::getOne();
685   else
686     SuccProb = BranchProbability(SuccProbN, SuccProbD);
687 
688   return SuccProb;
689 }
690 
691 /// Check if \p BB has exactly the successors in \p Successors.
692 static bool
693 hasSameSuccessors(MachineBasicBlock &BB,
694                   SmallPtrSetImpl<const MachineBasicBlock *> &Successors) {
695   if (BB.succ_size() != Successors.size())
696     return false;
697   // We don't want to count self-loops
698   if (Successors.count(&BB))
699     return false;
700   for (MachineBasicBlock *Succ : BB.successors())
701     if (!Successors.count(Succ))
702       return false;
703   return true;
704 }
705 
706 /// Check if a block should be tail duplicated to increase fallthrough
707 /// opportunities.
708 /// \p BB Block to check.
709 bool MachineBlockPlacement::shouldTailDuplicate(MachineBasicBlock *BB) {
710   // Blocks with single successors don't create additional fallthrough
711   // opportunities. Don't duplicate them. TODO: When conditional exits are
712   // analyzable, allow them to be duplicated.
713   bool IsSimple = TailDup.isSimpleBB(BB);
714 
715   if (BB->succ_size() == 1)
716     return false;
717   return TailDup.shouldTailDuplicate(IsSimple, *BB);
718 }
719 
720 /// Compare 2 BlockFrequency's with a small penalty for \p A.
721 /// In order to be conservative, we apply a X% penalty to account for
722 /// increased icache pressure and static heuristics. For small frequencies
723 /// we use only the numerators to improve accuracy. For simplicity, we assume the
724 /// penalty is less than 100%
725 /// TODO(iteratee): Use 64-bit fixed point edge frequencies everywhere.
726 static bool greaterWithBias(BlockFrequency A, BlockFrequency B,
727                             uint64_t EntryFreq) {
728   BranchProbability ThresholdProb(TailDupPlacementPenalty, 100);
729   BlockFrequency Gain = A - B;
730   return (Gain / ThresholdProb).getFrequency() >= EntryFreq;
731 }
732 
733 /// Check the edge frequencies to see if tail duplication will increase
734 /// fallthroughs. It only makes sense to call this function when
735 /// \p Succ would not be chosen otherwise. Tail duplication of \p Succ is
736 /// always locally profitable if we would have picked \p Succ without
737 /// considering duplication.
738 bool MachineBlockPlacement::isProfitableToTailDup(
739     const MachineBasicBlock *BB, const MachineBasicBlock *Succ,
740     BranchProbability QProb,
741     const BlockChain &Chain, const BlockFilterSet *BlockFilter) {
742   // We need to do a probability calculation to make sure this is profitable.
743   // First: does succ have a successor that post-dominates? This affects the
744   // calculation. The 2 relevant cases are:
745   //    BB         BB
746   //    | \Qout    | \Qout
747   //   P|  C       |P C
748   //    =   C'     =   C'
749   //    |  /Qin    |  /Qin
750   //    | /        | /
751   //    Succ       Succ
752   //    / \        | \  V
753   //  U/   =V      |U \
754   //  /     \      =   D
755   //  D      E     |  /
756   //               | /
757   //               |/
758   //               PDom
759   //  '=' : Branch taken for that CFG edge
760   // In the second case, Placing Succ while duplicating it into C prevents the
761   // fallthrough of Succ into either D or PDom, because they now have C as an
762   // unplaced predecessor
763 
764   // Start by figuring out which case we fall into
765   MachineBasicBlock *PDom = nullptr;
766   SmallVector<MachineBasicBlock *, 4> SuccSuccs;
767   // Only scan the relevant successors
768   auto AdjustedSuccSumProb =
769       collectViableSuccessors(Succ, Chain, BlockFilter, SuccSuccs);
770   BranchProbability PProb = MBPI->getEdgeProbability(BB, Succ);
771   auto BBFreq = MBFI->getBlockFreq(BB);
772   auto SuccFreq = MBFI->getBlockFreq(Succ);
773   BlockFrequency P = BBFreq * PProb;
774   BlockFrequency Qout = BBFreq * QProb;
775   uint64_t EntryFreq = MBFI->getEntryFreq();
776   // If there are no more successors, it is profitable to copy, as it strictly
777   // increases fallthrough.
778   if (SuccSuccs.size() == 0)
779     return greaterWithBias(P, Qout, EntryFreq);
780 
781   auto BestSuccSucc = BranchProbability::getZero();
782   // Find the PDom or the best Succ if no PDom exists.
783   for (MachineBasicBlock *SuccSucc : SuccSuccs) {
784     auto Prob = MBPI->getEdgeProbability(Succ, SuccSucc);
785     if (Prob > BestSuccSucc)
786       BestSuccSucc = Prob;
787     if (PDom == nullptr)
788       if (MPDT->dominates(SuccSucc, Succ)) {
789         PDom = SuccSucc;
790         break;
791       }
792   }
793   // For the comparisons, we need to know Succ's best incoming edge that isn't
794   // from BB.
795   auto SuccBestPred = BlockFrequency(0);
796   for (MachineBasicBlock *SuccPred : Succ->predecessors()) {
797     if (SuccPred == Succ || SuccPred == BB
798         || BlockToChain[SuccPred] == &Chain
799         || (BlockFilter && !BlockFilter->count(SuccPred)))
800       continue;
801     auto Freq = MBFI->getBlockFreq(SuccPred)
802         * MBPI->getEdgeProbability(SuccPred, Succ);
803     if (Freq > SuccBestPred)
804       SuccBestPred = Freq;
805   }
806   // Qin is Succ's best unplaced incoming edge that isn't BB
807   BlockFrequency Qin = SuccBestPred;
808   // If it doesn't have a post-dominating successor, here is the calculation:
809   //    BB        BB
810   //    | \Qout   |  \
811   //   P|  C      |   =
812   //    =   C'    |    C
813   //    |  /Qin   |     |
814   //    | /       |     C' (+Succ)
815   //    Succ      Succ /|
816   //    / \       |  \/ |
817   //  U/   =V     |  == |
818   //  /     \     | /  \|
819   //  D      E    D     E
820   //  '=' : Branch taken for that CFG edge
821   //  Cost in the first case is: P + V
822   //  For this calculation, we always assume P > Qout. If Qout > P
823   //  The result of this function will be ignored at the caller.
824   //  Let F = SuccFreq - Qin
825   //  Cost in the second case is: Qout + min(Qin, F) * U + max(Qin, F) * V
826 
827   if (PDom == nullptr || !Succ->isSuccessor(PDom)) {
828     BranchProbability UProb = BestSuccSucc;
829     BranchProbability VProb = AdjustedSuccSumProb - UProb;
830     BlockFrequency F = SuccFreq - Qin;
831     BlockFrequency V = SuccFreq * VProb;
832     BlockFrequency QinU = std::min(Qin, F) * UProb;
833     BlockFrequency BaseCost = P + V;
834     BlockFrequency DupCost = Qout + QinU + std::max(Qin, F) * VProb;
835     return greaterWithBias(BaseCost, DupCost, EntryFreq);
836   }
837   BranchProbability UProb = MBPI->getEdgeProbability(Succ, PDom);
838   BranchProbability VProb = AdjustedSuccSumProb - UProb;
839   BlockFrequency U = SuccFreq * UProb;
840   BlockFrequency V = SuccFreq * VProb;
841   BlockFrequency F = SuccFreq - Qin;
842   // If there is a post-dominating successor, here is the calculation:
843   // BB         BB                 BB          BB
844   // | \Qout    |   \               | \Qout     |  \
845   // |P C       |    =              |P C        |   =
846   // =   C'     |P    C             =   C'      |P   C
847   // |  /Qin    |      |            |  /Qin     |     |
848   // | /        |      C' (+Succ)   | /         |     C' (+Succ)
849   // Succ       Succ  /|            Succ        Succ /|
850   // | \  V     |   \/ |            | \  V      |  \/ |
851   // |U \       |U  /\ =?           |U =        |U /\ |
852   // =   D      = =  =?|            |   D       | =  =|
853   // |  /       |/     D            |  /        |/    D
854   // | /        |     /             | =         |    /
855   // |/         |    /              |/          |   =
856   // Dom         Dom                Dom         Dom
857   //  '=' : Branch taken for that CFG edge
858   // The cost for taken branches in the first case is P + U
859   // Let F = SuccFreq - Qin
860   // The cost in the second case (assuming independence), given the layout:
861   // BB, Succ, (C+Succ), D, Dom or the layout:
862   // BB, Succ, D, Dom, (C+Succ)
863   // is Qout + max(F, Qin) * U + min(F, Qin)
864   // compare P + U vs Qout + P * U + Qin.
865   //
866   // The 3rd and 4th cases cover when Dom would be chosen to follow Succ.
867   //
868   // For the 3rd case, the cost is P + 2 * V
869   // For the 4th case, the cost is Qout + min(Qin, F) * U + max(Qin, F) * V + V
870   // We choose 4 over 3 when (P + V) > Qout + min(Qin, F) * U + max(Qin, F) * V
871   if (UProb > AdjustedSuccSumProb / 2 &&
872       !hasBetterLayoutPredecessor(Succ, PDom, *BlockToChain[PDom], UProb, UProb,
873                                   Chain, BlockFilter))
874     // Cases 3 & 4
875     return greaterWithBias(
876         (P + V), (Qout + std::max(Qin, F) * VProb + std::min(Qin, F) * UProb),
877         EntryFreq);
878   // Cases 1 & 2
879   return greaterWithBias((P + U),
880                          (Qout + std::min(Qin, F) * AdjustedSuccSumProb +
881                           std::max(Qin, F) * UProb),
882                          EntryFreq);
883 }
884 
885 /// Check for a trellis layout. \p BB is the upper part of a trellis if its
886 /// successors form the lower part of a trellis. A successor set S forms the
887 /// lower part of a trellis if all of the predecessors of S are either in S or
888 /// have all of S as successors. We ignore trellises where BB doesn't have 2
889 /// successors because for fewer than 2, it's trivial, and for 3 or greater they
890 /// are very uncommon and complex to compute optimally. Allowing edges within S
891 /// is not strictly a trellis, but the same algorithm works, so we allow it.
892 bool MachineBlockPlacement::isTrellis(
893     const MachineBasicBlock *BB,
894     const SmallVectorImpl<MachineBasicBlock *> &ViableSuccs,
895     const BlockChain &Chain, const BlockFilterSet *BlockFilter) {
896   // Technically BB could form a trellis with branching factor higher than 2.
897   // But that's extremely uncommon.
898   if (BB->succ_size() != 2 || ViableSuccs.size() != 2)
899     return false;
900 
901   SmallPtrSet<const MachineBasicBlock *, 2> Successors(BB->succ_begin(),
902                                                        BB->succ_end());
903   // To avoid reviewing the same predecessors twice.
904   SmallPtrSet<const MachineBasicBlock *, 8> SeenPreds;
905 
906   for (MachineBasicBlock *Succ : ViableSuccs) {
907     int PredCount = 0;
908     for (auto SuccPred : Succ->predecessors()) {
909       // Allow triangle successors, but don't count them.
910       if (Successors.count(SuccPred)) {
911         // Make sure that it is actually a triangle.
912         for (MachineBasicBlock *CheckSucc : SuccPred->successors())
913           if (!Successors.count(CheckSucc))
914             return false;
915         continue;
916       }
917       const BlockChain *PredChain = BlockToChain[SuccPred];
918       if (SuccPred == BB || (BlockFilter && !BlockFilter->count(SuccPred)) ||
919           PredChain == &Chain || PredChain == BlockToChain[Succ])
920         continue;
921       ++PredCount;
922       // Perform the successor check only once.
923       if (!SeenPreds.insert(SuccPred).second)
924         continue;
925       if (!hasSameSuccessors(*SuccPred, Successors))
926         return false;
927     }
928     // If one of the successors has only BB as a predecessor, it is not a
929     // trellis.
930     if (PredCount < 1)
931       return false;
932   }
933   return true;
934 }
935 
936 /// Pick the highest total weight pair of edges that can both be laid out.
937 /// The edges in \p Edges[0] are assumed to have a different destination than
938 /// the edges in \p Edges[1]. Simple counting shows that the best pair is either
939 /// the individual highest weight edges to the 2 different destinations, or in
940 /// case of a conflict, one of them should be replaced with a 2nd best edge.
941 std::pair<MachineBlockPlacement::WeightedEdge,
942           MachineBlockPlacement::WeightedEdge>
943 MachineBlockPlacement::getBestNonConflictingEdges(
944     const MachineBasicBlock *BB,
945     MutableArrayRef<SmallVector<MachineBlockPlacement::WeightedEdge, 8>>
946         Edges) {
947   // Sort the edges, and then for each successor, find the best incoming
948   // predecessor. If the best incoming predecessors aren't the same,
949   // then that is clearly the best layout. If there is a conflict, one of the
950   // successors will have to fallthrough from the second best predecessor. We
951   // compare which combination is better overall.
952 
953   // Sort for highest frequency.
954   auto Cmp = [](WeightedEdge A, WeightedEdge B) { return A.Weight > B.Weight; };
955 
956   llvm::stable_sort(Edges[0], Cmp);
957   llvm::stable_sort(Edges[1], Cmp);
958   auto BestA = Edges[0].begin();
959   auto BestB = Edges[1].begin();
960   // Arrange for the correct answer to be in BestA and BestB
961   // If the 2 best edges don't conflict, the answer is already there.
962   if (BestA->Src == BestB->Src) {
963     // Compare the total fallthrough of (Best + Second Best) for both pairs
964     auto SecondBestA = std::next(BestA);
965     auto SecondBestB = std::next(BestB);
966     BlockFrequency BestAScore = BestA->Weight + SecondBestB->Weight;
967     BlockFrequency BestBScore = BestB->Weight + SecondBestA->Weight;
968     if (BestAScore < BestBScore)
969       BestA = SecondBestA;
970     else
971       BestB = SecondBestB;
972   }
973   // Arrange for the BB edge to be in BestA if it exists.
974   if (BestB->Src == BB)
975     std::swap(BestA, BestB);
976   return std::make_pair(*BestA, *BestB);
977 }
978 
979 /// Get the best successor from \p BB based on \p BB being part of a trellis.
980 /// We only handle trellises with 2 successors, so the algorithm is
981 /// straightforward: Find the best pair of edges that don't conflict. We find
982 /// the best incoming edge for each successor in the trellis. If those conflict,
983 /// we consider which of them should be replaced with the second best.
984 /// Upon return the two best edges will be in \p BestEdges. If one of the edges
985 /// comes from \p BB, it will be in \p BestEdges[0]
986 MachineBlockPlacement::BlockAndTailDupResult
987 MachineBlockPlacement::getBestTrellisSuccessor(
988     const MachineBasicBlock *BB,
989     const SmallVectorImpl<MachineBasicBlock *> &ViableSuccs,
990     BranchProbability AdjustedSumProb, const BlockChain &Chain,
991     const BlockFilterSet *BlockFilter) {
992 
993   BlockAndTailDupResult Result = {nullptr, false};
994   SmallPtrSet<const MachineBasicBlock *, 4> Successors(BB->succ_begin(),
995                                                        BB->succ_end());
996 
997   // We assume size 2 because it's common. For general n, we would have to do
998   // the Hungarian algorithm, but it's not worth the complexity because more
999   // than 2 successors is fairly uncommon, and a trellis even more so.
1000   if (Successors.size() != 2 || ViableSuccs.size() != 2)
1001     return Result;
1002 
1003   // Collect the edge frequencies of all edges that form the trellis.
1004   SmallVector<WeightedEdge, 8> Edges[2];
1005   int SuccIndex = 0;
1006   for (auto Succ : ViableSuccs) {
1007     for (MachineBasicBlock *SuccPred : Succ->predecessors()) {
1008       // Skip any placed predecessors that are not BB
1009       if (SuccPred != BB)
1010         if ((BlockFilter && !BlockFilter->count(SuccPred)) ||
1011             BlockToChain[SuccPred] == &Chain ||
1012             BlockToChain[SuccPred] == BlockToChain[Succ])
1013           continue;
1014       BlockFrequency EdgeFreq = MBFI->getBlockFreq(SuccPred) *
1015                                 MBPI->getEdgeProbability(SuccPred, Succ);
1016       Edges[SuccIndex].push_back({EdgeFreq, SuccPred, Succ});
1017     }
1018     ++SuccIndex;
1019   }
1020 
1021   // Pick the best combination of 2 edges from all the edges in the trellis.
1022   WeightedEdge BestA, BestB;
1023   std::tie(BestA, BestB) = getBestNonConflictingEdges(BB, Edges);
1024 
1025   if (BestA.Src != BB) {
1026     // If we have a trellis, and BB doesn't have the best fallthrough edges,
1027     // we shouldn't choose any successor. We've already looked and there's a
1028     // better fallthrough edge for all the successors.
1029     LLVM_DEBUG(dbgs() << "Trellis, but not one of the chosen edges.\n");
1030     return Result;
1031   }
1032 
1033   // Did we pick the triangle edge? If tail-duplication is profitable, do
1034   // that instead. Otherwise merge the triangle edge now while we know it is
1035   // optimal.
1036   if (BestA.Dest == BestB.Src) {
1037     // The edges are BB->Succ1->Succ2, and we're looking to see if BB->Succ2
1038     // would be better.
1039     MachineBasicBlock *Succ1 = BestA.Dest;
1040     MachineBasicBlock *Succ2 = BestB.Dest;
1041     // Check to see if tail-duplication would be profitable.
1042     if (allowTailDupPlacement() && shouldTailDuplicate(Succ2) &&
1043         canTailDuplicateUnplacedPreds(BB, Succ2, Chain, BlockFilter) &&
1044         isProfitableToTailDup(BB, Succ2, MBPI->getEdgeProbability(BB, Succ1),
1045                               Chain, BlockFilter)) {
1046       LLVM_DEBUG(BranchProbability Succ2Prob = getAdjustedProbability(
1047                      MBPI->getEdgeProbability(BB, Succ2), AdjustedSumProb);
1048                  dbgs() << "    Selected: " << getBlockName(Succ2)
1049                         << ", probability: " << Succ2Prob
1050                         << " (Tail Duplicate)\n");
1051       Result.BB = Succ2;
1052       Result.ShouldTailDup = true;
1053       return Result;
1054     }
1055   }
1056   // We have already computed the optimal edge for the other side of the
1057   // trellis.
1058   ComputedEdges[BestB.Src] = { BestB.Dest, false };
1059 
1060   auto TrellisSucc = BestA.Dest;
1061   LLVM_DEBUG(BranchProbability SuccProb = getAdjustedProbability(
1062                  MBPI->getEdgeProbability(BB, TrellisSucc), AdjustedSumProb);
1063              dbgs() << "    Selected: " << getBlockName(TrellisSucc)
1064                     << ", probability: " << SuccProb << " (Trellis)\n");
1065   Result.BB = TrellisSucc;
1066   return Result;
1067 }
1068 
1069 /// When the option allowTailDupPlacement() is on, this method checks if the
1070 /// fallthrough candidate block \p Succ (of block \p BB) can be tail-duplicated
1071 /// into all of its unplaced, unfiltered predecessors, that are not BB.
1072 bool MachineBlockPlacement::canTailDuplicateUnplacedPreds(
1073     const MachineBasicBlock *BB, MachineBasicBlock *Succ,
1074     const BlockChain &Chain, const BlockFilterSet *BlockFilter) {
1075   if (!shouldTailDuplicate(Succ))
1076     return false;
1077 
1078   // For CFG checking.
1079   SmallPtrSet<const MachineBasicBlock *, 4> Successors(BB->succ_begin(),
1080                                                        BB->succ_end());
1081   for (MachineBasicBlock *Pred : Succ->predecessors()) {
1082     // Make sure all unplaced and unfiltered predecessors can be
1083     // tail-duplicated into.
1084     // Skip any blocks that are already placed or not in this loop.
1085     if (Pred == BB || (BlockFilter && !BlockFilter->count(Pred))
1086         || BlockToChain[Pred] == &Chain)
1087       continue;
1088     if (!TailDup.canTailDuplicate(Succ, Pred)) {
1089       if (Successors.size() > 1 && hasSameSuccessors(*Pred, Successors))
1090         // This will result in a trellis after tail duplication, so we don't
1091         // need to copy Succ into this predecessor. In the presence
1092         // of a trellis tail duplication can continue to be profitable.
1093         // For example:
1094         // A            A
1095         // |\           |\
1096         // | \          | \
1097         // |  C         |  C+BB
1098         // | /          |  |
1099         // |/           |  |
1100         // BB    =>     BB |
1101         // |\           |\/|
1102         // | \          |/\|
1103         // |  D         |  D
1104         // | /          | /
1105         // |/           |/
1106         // Succ         Succ
1107         //
1108         // After BB was duplicated into C, the layout looks like the one on the
1109         // right. BB and C now have the same successors. When considering
1110         // whether Succ can be duplicated into all its unplaced predecessors, we
1111         // ignore C.
1112         // We can do this because C already has a profitable fallthrough, namely
1113         // D. TODO(iteratee): ignore sufficiently cold predecessors for
1114         // duplication and for this test.
1115         //
1116         // This allows trellises to be laid out in 2 separate chains
1117         // (A,B,Succ,...) and later (C,D,...) This is a reasonable heuristic
1118         // because it allows the creation of 2 fallthrough paths with links
1119         // between them, and we correctly identify the best layout for these
1120         // CFGs. We want to extend trellises that the user created in addition
1121         // to trellises created by tail-duplication, so we just look for the
1122         // CFG.
1123         continue;
1124       return false;
1125     }
1126   }
1127   return true;
1128 }
1129 
1130 /// Find chains of triangles where we believe it would be profitable to
1131 /// tail-duplicate them all, but a local analysis would not find them.
1132 /// There are 3 ways this can be profitable:
1133 /// 1) The post-dominators marked 50% are actually taken 55% (This shrinks with
1134 ///    longer chains)
1135 /// 2) The chains are statically correlated. Branch probabilities have a very
1136 ///    U-shaped distribution.
1137 ///    [http://nrs.harvard.edu/urn-3:HUL.InstRepos:24015805]
1138 ///    If the branches in a chain are likely to be from the same side of the
1139 ///    distribution as their predecessor, but are independent at runtime, this
1140 ///    transformation is profitable. (Because the cost of being wrong is a small
1141 ///    fixed cost, unlike the standard triangle layout where the cost of being
1142 ///    wrong scales with the # of triangles.)
1143 /// 3) The chains are dynamically correlated. If the probability that a previous
1144 ///    branch was taken positively influences whether the next branch will be
1145 ///    taken
1146 /// We believe that 2 and 3 are common enough to justify the small margin in 1.
1147 void MachineBlockPlacement::precomputeTriangleChains() {
1148   struct TriangleChain {
1149     std::vector<MachineBasicBlock *> Edges;
1150 
1151     TriangleChain(MachineBasicBlock *src, MachineBasicBlock *dst)
1152         : Edges({src, dst}) {}
1153 
1154     void append(MachineBasicBlock *dst) {
1155       assert(getKey()->isSuccessor(dst) &&
1156              "Attempting to append a block that is not a successor.");
1157       Edges.push_back(dst);
1158     }
1159 
1160     unsigned count() const { return Edges.size() - 1; }
1161 
1162     MachineBasicBlock *getKey() const {
1163       return Edges.back();
1164     }
1165   };
1166 
1167   if (TriangleChainCount == 0)
1168     return;
1169 
1170   LLVM_DEBUG(dbgs() << "Pre-computing triangle chains.\n");
1171   // Map from last block to the chain that contains it. This allows us to extend
1172   // chains as we find new triangles.
1173   DenseMap<const MachineBasicBlock *, TriangleChain> TriangleChainMap;
1174   for (MachineBasicBlock &BB : *F) {
1175     // If BB doesn't have 2 successors, it doesn't start a triangle.
1176     if (BB.succ_size() != 2)
1177       continue;
1178     MachineBasicBlock *PDom = nullptr;
1179     for (MachineBasicBlock *Succ : BB.successors()) {
1180       if (!MPDT->dominates(Succ, &BB))
1181         continue;
1182       PDom = Succ;
1183       break;
1184     }
1185     // If BB doesn't have a post-dominating successor, it doesn't form a
1186     // triangle.
1187     if (PDom == nullptr)
1188       continue;
1189     // If PDom has a hint that it is low probability, skip this triangle.
1190     if (MBPI->getEdgeProbability(&BB, PDom) < BranchProbability(50, 100))
1191       continue;
1192     // If PDom isn't eligible for duplication, this isn't the kind of triangle
1193     // we're looking for.
1194     if (!shouldTailDuplicate(PDom))
1195       continue;
1196     bool CanTailDuplicate = true;
1197     // If PDom can't tail-duplicate into it's non-BB predecessors, then this
1198     // isn't the kind of triangle we're looking for.
1199     for (MachineBasicBlock* Pred : PDom->predecessors()) {
1200       if (Pred == &BB)
1201         continue;
1202       if (!TailDup.canTailDuplicate(PDom, Pred)) {
1203         CanTailDuplicate = false;
1204         break;
1205       }
1206     }
1207     // If we can't tail-duplicate PDom to its predecessors, then skip this
1208     // triangle.
1209     if (!CanTailDuplicate)
1210       continue;
1211 
1212     // Now we have an interesting triangle. Insert it if it's not part of an
1213     // existing chain.
1214     // Note: This cannot be replaced with a call insert() or emplace() because
1215     // the find key is BB, but the insert/emplace key is PDom.
1216     auto Found = TriangleChainMap.find(&BB);
1217     // If it is, remove the chain from the map, grow it, and put it back in the
1218     // map with the end as the new key.
1219     if (Found != TriangleChainMap.end()) {
1220       TriangleChain Chain = std::move(Found->second);
1221       TriangleChainMap.erase(Found);
1222       Chain.append(PDom);
1223       TriangleChainMap.insert(std::make_pair(Chain.getKey(), std::move(Chain)));
1224     } else {
1225       auto InsertResult = TriangleChainMap.try_emplace(PDom, &BB, PDom);
1226       assert(InsertResult.second && "Block seen twice.");
1227       (void)InsertResult;
1228     }
1229   }
1230 
1231   // Iterating over a DenseMap is safe here, because the only thing in the body
1232   // of the loop is inserting into another DenseMap (ComputedEdges).
1233   // ComputedEdges is never iterated, so this doesn't lead to non-determinism.
1234   for (auto &ChainPair : TriangleChainMap) {
1235     TriangleChain &Chain = ChainPair.second;
1236     // Benchmarking has shown that due to branch correlation duplicating 2 or
1237     // more triangles is profitable, despite the calculations assuming
1238     // independence.
1239     if (Chain.count() < TriangleChainCount)
1240       continue;
1241     MachineBasicBlock *dst = Chain.Edges.back();
1242     Chain.Edges.pop_back();
1243     for (MachineBasicBlock *src : reverse(Chain.Edges)) {
1244       LLVM_DEBUG(dbgs() << "Marking edge: " << getBlockName(src) << "->"
1245                         << getBlockName(dst)
1246                         << " as pre-computed based on triangles.\n");
1247 
1248       auto InsertResult = ComputedEdges.insert({src, {dst, true}});
1249       assert(InsertResult.second && "Block seen twice.");
1250       (void)InsertResult;
1251 
1252       dst = src;
1253     }
1254   }
1255 }
1256 
1257 // When profile is not present, return the StaticLikelyProb.
1258 // When profile is available, we need to handle the triangle-shape CFG.
1259 static BranchProbability getLayoutSuccessorProbThreshold(
1260       const MachineBasicBlock *BB) {
1261   if (!BB->getParent()->getFunction().hasProfileData())
1262     return BranchProbability(StaticLikelyProb, 100);
1263   if (BB->succ_size() == 2) {
1264     const MachineBasicBlock *Succ1 = *BB->succ_begin();
1265     const MachineBasicBlock *Succ2 = *(BB->succ_begin() + 1);
1266     if (Succ1->isSuccessor(Succ2) || Succ2->isSuccessor(Succ1)) {
1267       /* See case 1 below for the cost analysis. For BB->Succ to
1268        * be taken with smaller cost, the following needs to hold:
1269        *   Prob(BB->Succ) > 2 * Prob(BB->Pred)
1270        *   So the threshold T in the calculation below
1271        *   (1-T) * Prob(BB->Succ) > T * Prob(BB->Pred)
1272        *   So T / (1 - T) = 2, Yielding T = 2/3
1273        * Also adding user specified branch bias, we have
1274        *   T = (2/3)*(ProfileLikelyProb/50)
1275        *     = (2*ProfileLikelyProb)/150)
1276        */
1277       return BranchProbability(2 * ProfileLikelyProb, 150);
1278     }
1279   }
1280   return BranchProbability(ProfileLikelyProb, 100);
1281 }
1282 
1283 /// Checks to see if the layout candidate block \p Succ has a better layout
1284 /// predecessor than \c BB. If yes, returns true.
1285 /// \p SuccProb: The probability adjusted for only remaining blocks.
1286 ///   Only used for logging
1287 /// \p RealSuccProb: The un-adjusted probability.
1288 /// \p Chain: The chain that BB belongs to and Succ is being considered for.
1289 /// \p BlockFilter: if non-null, the set of blocks that make up the loop being
1290 ///    considered
1291 bool MachineBlockPlacement::hasBetterLayoutPredecessor(
1292     const MachineBasicBlock *BB, const MachineBasicBlock *Succ,
1293     const BlockChain &SuccChain, BranchProbability SuccProb,
1294     BranchProbability RealSuccProb, const BlockChain &Chain,
1295     const BlockFilterSet *BlockFilter) {
1296 
1297   // There isn't a better layout when there are no unscheduled predecessors.
1298   if (SuccChain.UnscheduledPredecessors == 0)
1299     return false;
1300 
1301   // There are two basic scenarios here:
1302   // -------------------------------------
1303   // Case 1: triangular shape CFG (if-then):
1304   //     BB
1305   //     | \
1306   //     |  \
1307   //     |   Pred
1308   //     |   /
1309   //     Succ
1310   // In this case, we are evaluating whether to select edge -> Succ, e.g.
1311   // set Succ as the layout successor of BB. Picking Succ as BB's
1312   // successor breaks the CFG constraints (FIXME: define these constraints).
1313   // With this layout, Pred BB
1314   // is forced to be outlined, so the overall cost will be cost of the
1315   // branch taken from BB to Pred, plus the cost of back taken branch
1316   // from Pred to Succ, as well as the additional cost associated
1317   // with the needed unconditional jump instruction from Pred To Succ.
1318 
1319   // The cost of the topological order layout is the taken branch cost
1320   // from BB to Succ, so to make BB->Succ a viable candidate, the following
1321   // must hold:
1322   //     2 * freq(BB->Pred) * taken_branch_cost + unconditional_jump_cost
1323   //      < freq(BB->Succ) *  taken_branch_cost.
1324   // Ignoring unconditional jump cost, we get
1325   //    freq(BB->Succ) > 2 * freq(BB->Pred), i.e.,
1326   //    prob(BB->Succ) > 2 * prob(BB->Pred)
1327   //
1328   // When real profile data is available, we can precisely compute the
1329   // probability threshold that is needed for edge BB->Succ to be considered.
1330   // Without profile data, the heuristic requires the branch bias to be
1331   // a lot larger to make sure the signal is very strong (e.g. 80% default).
1332   // -----------------------------------------------------------------
1333   // Case 2: diamond like CFG (if-then-else):
1334   //     S
1335   //    / \
1336   //   |   \
1337   //  BB    Pred
1338   //   \    /
1339   //    Succ
1340   //    ..
1341   //
1342   // The current block is BB and edge BB->Succ is now being evaluated.
1343   // Note that edge S->BB was previously already selected because
1344   // prob(S->BB) > prob(S->Pred).
1345   // At this point, 2 blocks can be placed after BB: Pred or Succ. If we
1346   // choose Pred, we will have a topological ordering as shown on the left
1347   // in the picture below. If we choose Succ, we have the solution as shown
1348   // on the right:
1349   //
1350   //   topo-order:
1351   //
1352   //       S-----                             ---S
1353   //       |    |                             |  |
1354   //    ---BB   |                             |  BB
1355   //    |       |                             |  |
1356   //    |  Pred--                             |  Succ--
1357   //    |  |                                  |       |
1358   //    ---Succ                               ---Pred--
1359   //
1360   // cost = freq(S->Pred) + freq(BB->Succ)    cost = 2 * freq (S->Pred)
1361   //      = freq(S->Pred) + freq(S->BB)
1362   //
1363   // If we have profile data (i.e, branch probabilities can be trusted), the
1364   // cost (number of taken branches) with layout S->BB->Succ->Pred is 2 *
1365   // freq(S->Pred) while the cost of topo order is freq(S->Pred) + freq(S->BB).
1366   // We know Prob(S->BB) > Prob(S->Pred), so freq(S->BB) > freq(S->Pred), which
1367   // means the cost of topological order is greater.
1368   // When profile data is not available, however, we need to be more
1369   // conservative. If the branch prediction is wrong, breaking the topo-order
1370   // will actually yield a layout with large cost. For this reason, we need
1371   // strong biased branch at block S with Prob(S->BB) in order to select
1372   // BB->Succ. This is equivalent to looking the CFG backward with backward
1373   // edge: Prob(Succ->BB) needs to >= HotProb in order to be selected (without
1374   // profile data).
1375   // --------------------------------------------------------------------------
1376   // Case 3: forked diamond
1377   //       S
1378   //      / \
1379   //     /   \
1380   //   BB    Pred
1381   //   | \   / |
1382   //   |  \ /  |
1383   //   |   X   |
1384   //   |  / \  |
1385   //   | /   \ |
1386   //   S1     S2
1387   //
1388   // The current block is BB and edge BB->S1 is now being evaluated.
1389   // As above S->BB was already selected because
1390   // prob(S->BB) > prob(S->Pred). Assume that prob(BB->S1) >= prob(BB->S2).
1391   //
1392   // topo-order:
1393   //
1394   //     S-------|                     ---S
1395   //     |       |                     |  |
1396   //  ---BB      |                     |  BB
1397   //  |          |                     |  |
1398   //  |  Pred----|                     |  S1----
1399   //  |  |                             |       |
1400   //  --(S1 or S2)                     ---Pred--
1401   //                                        |
1402   //                                       S2
1403   //
1404   // topo-cost = freq(S->Pred) + freq(BB->S1) + freq(BB->S2)
1405   //    + min(freq(Pred->S1), freq(Pred->S2))
1406   // Non-topo-order cost:
1407   // non-topo-cost = 2 * freq(S->Pred) + freq(BB->S2).
1408   // To be conservative, we can assume that min(freq(Pred->S1), freq(Pred->S2))
1409   // is 0. Then the non topo layout is better when
1410   // freq(S->Pred) < freq(BB->S1).
1411   // This is exactly what is checked below.
1412   // Note there are other shapes that apply (Pred may not be a single block,
1413   // but they all fit this general pattern.)
1414   BranchProbability HotProb = getLayoutSuccessorProbThreshold(BB);
1415 
1416   // Make sure that a hot successor doesn't have a globally more
1417   // important predecessor.
1418   BlockFrequency CandidateEdgeFreq = MBFI->getBlockFreq(BB) * RealSuccProb;
1419   bool BadCFGConflict = false;
1420 
1421   for (MachineBasicBlock *Pred : Succ->predecessors()) {
1422     if (Pred == Succ || BlockToChain[Pred] == &SuccChain ||
1423         (BlockFilter && !BlockFilter->count(Pred)) ||
1424         BlockToChain[Pred] == &Chain ||
1425         // This check is redundant except for look ahead. This function is
1426         // called for lookahead by isProfitableToTailDup when BB hasn't been
1427         // placed yet.
1428         (Pred == BB))
1429       continue;
1430     // Do backward checking.
1431     // For all cases above, we need a backward checking to filter out edges that
1432     // are not 'strongly' biased.
1433     // BB  Pred
1434     //  \ /
1435     //  Succ
1436     // We select edge BB->Succ if
1437     //      freq(BB->Succ) > freq(Succ) * HotProb
1438     //      i.e. freq(BB->Succ) > freq(BB->Succ) * HotProb + freq(Pred->Succ) *
1439     //      HotProb
1440     //      i.e. freq((BB->Succ) * (1 - HotProb) > freq(Pred->Succ) * HotProb
1441     // Case 1 is covered too, because the first equation reduces to:
1442     // prob(BB->Succ) > HotProb. (freq(Succ) = freq(BB) for a triangle)
1443     BlockFrequency PredEdgeFreq =
1444         MBFI->getBlockFreq(Pred) * MBPI->getEdgeProbability(Pred, Succ);
1445     if (PredEdgeFreq * HotProb >= CandidateEdgeFreq * HotProb.getCompl()) {
1446       BadCFGConflict = true;
1447       break;
1448     }
1449   }
1450 
1451   if (BadCFGConflict) {
1452     LLVM_DEBUG(dbgs() << "    Not a candidate: " << getBlockName(Succ) << " -> "
1453                       << SuccProb << " (prob) (non-cold CFG conflict)\n");
1454     return true;
1455   }
1456 
1457   return false;
1458 }
1459 
1460 /// Select the best successor for a block.
1461 ///
1462 /// This looks across all successors of a particular block and attempts to
1463 /// select the "best" one to be the layout successor. It only considers direct
1464 /// successors which also pass the block filter. It will attempt to avoid
1465 /// breaking CFG structure, but cave and break such structures in the case of
1466 /// very hot successor edges.
1467 ///
1468 /// \returns The best successor block found, or null if none are viable, along
1469 /// with a boolean indicating if tail duplication is necessary.
1470 MachineBlockPlacement::BlockAndTailDupResult
1471 MachineBlockPlacement::selectBestSuccessor(
1472     const MachineBasicBlock *BB, const BlockChain &Chain,
1473     const BlockFilterSet *BlockFilter) {
1474   const BranchProbability HotProb(StaticLikelyProb, 100);
1475 
1476   BlockAndTailDupResult BestSucc = { nullptr, false };
1477   auto BestProb = BranchProbability::getZero();
1478 
1479   SmallVector<MachineBasicBlock *, 4> Successors;
1480   auto AdjustedSumProb =
1481       collectViableSuccessors(BB, Chain, BlockFilter, Successors);
1482 
1483   LLVM_DEBUG(dbgs() << "Selecting best successor for: " << getBlockName(BB)
1484                     << "\n");
1485 
1486   // if we already precomputed the best successor for BB, return that if still
1487   // applicable.
1488   auto FoundEdge = ComputedEdges.find(BB);
1489   if (FoundEdge != ComputedEdges.end()) {
1490     MachineBasicBlock *Succ = FoundEdge->second.BB;
1491     ComputedEdges.erase(FoundEdge);
1492     BlockChain *SuccChain = BlockToChain[Succ];
1493     if (BB->isSuccessor(Succ) && (!BlockFilter || BlockFilter->count(Succ)) &&
1494         SuccChain != &Chain && Succ == *SuccChain->begin())
1495       return FoundEdge->second;
1496   }
1497 
1498   // if BB is part of a trellis, Use the trellis to determine the optimal
1499   // fallthrough edges
1500   if (isTrellis(BB, Successors, Chain, BlockFilter))
1501     return getBestTrellisSuccessor(BB, Successors, AdjustedSumProb, Chain,
1502                                    BlockFilter);
1503 
1504   // For blocks with CFG violations, we may be able to lay them out anyway with
1505   // tail-duplication. We keep this vector so we can perform the probability
1506   // calculations the minimum number of times.
1507   SmallVector<std::tuple<BranchProbability, MachineBasicBlock *>, 4>
1508       DupCandidates;
1509   for (MachineBasicBlock *Succ : Successors) {
1510     auto RealSuccProb = MBPI->getEdgeProbability(BB, Succ);
1511     BranchProbability SuccProb =
1512         getAdjustedProbability(RealSuccProb, AdjustedSumProb);
1513 
1514     BlockChain &SuccChain = *BlockToChain[Succ];
1515     // Skip the edge \c BB->Succ if block \c Succ has a better layout
1516     // predecessor that yields lower global cost.
1517     if (hasBetterLayoutPredecessor(BB, Succ, SuccChain, SuccProb, RealSuccProb,
1518                                    Chain, BlockFilter)) {
1519       // If tail duplication would make Succ profitable, place it.
1520       if (allowTailDupPlacement() && shouldTailDuplicate(Succ))
1521         DupCandidates.push_back(std::make_tuple(SuccProb, Succ));
1522       continue;
1523     }
1524 
1525     LLVM_DEBUG(
1526         dbgs() << "    Candidate: " << getBlockName(Succ)
1527                << ", probability: " << SuccProb
1528                << (SuccChain.UnscheduledPredecessors != 0 ? " (CFG break)" : "")
1529                << "\n");
1530 
1531     if (BestSucc.BB && BestProb >= SuccProb) {
1532       LLVM_DEBUG(dbgs() << "    Not the best candidate, continuing\n");
1533       continue;
1534     }
1535 
1536     LLVM_DEBUG(dbgs() << "    Setting it as best candidate\n");
1537     BestSucc.BB = Succ;
1538     BestProb = SuccProb;
1539   }
1540   // Handle the tail duplication candidates in order of decreasing probability.
1541   // Stop at the first one that is profitable. Also stop if they are less
1542   // profitable than BestSucc. Position is important because we preserve it and
1543   // prefer first best match. Here we aren't comparing in order, so we capture
1544   // the position instead.
1545   llvm::stable_sort(DupCandidates,
1546                     [](std::tuple<BranchProbability, MachineBasicBlock *> L,
1547                        std::tuple<BranchProbability, MachineBasicBlock *> R) {
1548                       return std::get<0>(L) > std::get<0>(R);
1549                     });
1550   for (auto &Tup : DupCandidates) {
1551     BranchProbability DupProb;
1552     MachineBasicBlock *Succ;
1553     std::tie(DupProb, Succ) = Tup;
1554     if (DupProb < BestProb)
1555       break;
1556     if (canTailDuplicateUnplacedPreds(BB, Succ, Chain, BlockFilter)
1557         && (isProfitableToTailDup(BB, Succ, BestProb, Chain, BlockFilter))) {
1558       LLVM_DEBUG(dbgs() << "    Candidate: " << getBlockName(Succ)
1559                         << ", probability: " << DupProb
1560                         << " (Tail Duplicate)\n");
1561       BestSucc.BB = Succ;
1562       BestSucc.ShouldTailDup = true;
1563       break;
1564     }
1565   }
1566 
1567   if (BestSucc.BB)
1568     LLVM_DEBUG(dbgs() << "    Selected: " << getBlockName(BestSucc.BB) << "\n");
1569 
1570   return BestSucc;
1571 }
1572 
1573 /// Select the best block from a worklist.
1574 ///
1575 /// This looks through the provided worklist as a list of candidate basic
1576 /// blocks and select the most profitable one to place. The definition of
1577 /// profitable only really makes sense in the context of a loop. This returns
1578 /// the most frequently visited block in the worklist, which in the case of
1579 /// a loop, is the one most desirable to be physically close to the rest of the
1580 /// loop body in order to improve i-cache behavior.
1581 ///
1582 /// \returns The best block found, or null if none are viable.
1583 MachineBasicBlock *MachineBlockPlacement::selectBestCandidateBlock(
1584     const BlockChain &Chain, SmallVectorImpl<MachineBasicBlock *> &WorkList) {
1585   // Once we need to walk the worklist looking for a candidate, cleanup the
1586   // worklist of already placed entries.
1587   // FIXME: If this shows up on profiles, it could be folded (at the cost of
1588   // some code complexity) into the loop below.
1589   WorkList.erase(llvm::remove_if(WorkList,
1590                                  [&](MachineBasicBlock *BB) {
1591                                    return BlockToChain.lookup(BB) == &Chain;
1592                                  }),
1593                  WorkList.end());
1594 
1595   if (WorkList.empty())
1596     return nullptr;
1597 
1598   bool IsEHPad = WorkList[0]->isEHPad();
1599 
1600   MachineBasicBlock *BestBlock = nullptr;
1601   BlockFrequency BestFreq;
1602   for (MachineBasicBlock *MBB : WorkList) {
1603     assert(MBB->isEHPad() == IsEHPad &&
1604            "EHPad mismatch between block and work list.");
1605 
1606     BlockChain &SuccChain = *BlockToChain[MBB];
1607     if (&SuccChain == &Chain)
1608       continue;
1609 
1610     assert(SuccChain.UnscheduledPredecessors == 0 &&
1611            "Found CFG-violating block");
1612 
1613     BlockFrequency CandidateFreq = MBFI->getBlockFreq(MBB);
1614     LLVM_DEBUG(dbgs() << "    " << getBlockName(MBB) << " -> ";
1615                MBFI->printBlockFreq(dbgs(), CandidateFreq) << " (freq)\n");
1616 
1617     // For ehpad, we layout the least probable first as to avoid jumping back
1618     // from least probable landingpads to more probable ones.
1619     //
1620     // FIXME: Using probability is probably (!) not the best way to achieve
1621     // this. We should probably have a more principled approach to layout
1622     // cleanup code.
1623     //
1624     // The goal is to get:
1625     //
1626     //                 +--------------------------+
1627     //                 |                          V
1628     // InnerLp -> InnerCleanup    OuterLp -> OuterCleanup -> Resume
1629     //
1630     // Rather than:
1631     //
1632     //                 +-------------------------------------+
1633     //                 V                                     |
1634     // OuterLp -> OuterCleanup -> Resume     InnerLp -> InnerCleanup
1635     if (BestBlock && (IsEHPad ^ (BestFreq >= CandidateFreq)))
1636       continue;
1637 
1638     BestBlock = MBB;
1639     BestFreq = CandidateFreq;
1640   }
1641 
1642   return BestBlock;
1643 }
1644 
1645 /// Retrieve the first unplaced basic block.
1646 ///
1647 /// This routine is called when we are unable to use the CFG to walk through
1648 /// all of the basic blocks and form a chain due to unnatural loops in the CFG.
1649 /// We walk through the function's blocks in order, starting from the
1650 /// LastUnplacedBlockIt. We update this iterator on each call to avoid
1651 /// re-scanning the entire sequence on repeated calls to this routine.
1652 MachineBasicBlock *MachineBlockPlacement::getFirstUnplacedBlock(
1653     const BlockChain &PlacedChain,
1654     MachineFunction::iterator &PrevUnplacedBlockIt,
1655     const BlockFilterSet *BlockFilter) {
1656   for (MachineFunction::iterator I = PrevUnplacedBlockIt, E = F->end(); I != E;
1657        ++I) {
1658     if (BlockFilter && !BlockFilter->count(&*I))
1659       continue;
1660     if (BlockToChain[&*I] != &PlacedChain) {
1661       PrevUnplacedBlockIt = I;
1662       // Now select the head of the chain to which the unplaced block belongs
1663       // as the block to place. This will force the entire chain to be placed,
1664       // and satisfies the requirements of merging chains.
1665       return *BlockToChain[&*I]->begin();
1666     }
1667   }
1668   return nullptr;
1669 }
1670 
1671 void MachineBlockPlacement::fillWorkLists(
1672     const MachineBasicBlock *MBB,
1673     SmallPtrSetImpl<BlockChain *> &UpdatedPreds,
1674     const BlockFilterSet *BlockFilter = nullptr) {
1675   BlockChain &Chain = *BlockToChain[MBB];
1676   if (!UpdatedPreds.insert(&Chain).second)
1677     return;
1678 
1679   assert(
1680       Chain.UnscheduledPredecessors == 0 &&
1681       "Attempting to place block with unscheduled predecessors in worklist.");
1682   for (MachineBasicBlock *ChainBB : Chain) {
1683     assert(BlockToChain[ChainBB] == &Chain &&
1684            "Block in chain doesn't match BlockToChain map.");
1685     for (MachineBasicBlock *Pred : ChainBB->predecessors()) {
1686       if (BlockFilter && !BlockFilter->count(Pred))
1687         continue;
1688       if (BlockToChain[Pred] == &Chain)
1689         continue;
1690       ++Chain.UnscheduledPredecessors;
1691     }
1692   }
1693 
1694   if (Chain.UnscheduledPredecessors != 0)
1695     return;
1696 
1697   MachineBasicBlock *BB = *Chain.begin();
1698   if (BB->isEHPad())
1699     EHPadWorkList.push_back(BB);
1700   else
1701     BlockWorkList.push_back(BB);
1702 }
1703 
1704 void MachineBlockPlacement::buildChain(
1705     const MachineBasicBlock *HeadBB, BlockChain &Chain,
1706     BlockFilterSet *BlockFilter) {
1707   assert(HeadBB && "BB must not be null.\n");
1708   assert(BlockToChain[HeadBB] == &Chain && "BlockToChainMap mis-match.\n");
1709   MachineFunction::iterator PrevUnplacedBlockIt = F->begin();
1710 
1711   const MachineBasicBlock *LoopHeaderBB = HeadBB;
1712   markChainSuccessors(Chain, LoopHeaderBB, BlockFilter);
1713   MachineBasicBlock *BB = *std::prev(Chain.end());
1714   while (true) {
1715     assert(BB && "null block found at end of chain in loop.");
1716     assert(BlockToChain[BB] == &Chain && "BlockToChainMap mis-match in loop.");
1717     assert(*std::prev(Chain.end()) == BB && "BB Not found at end of chain.");
1718 
1719 
1720     // Look for the best viable successor if there is one to place immediately
1721     // after this block.
1722     auto Result = selectBestSuccessor(BB, Chain, BlockFilter);
1723     MachineBasicBlock* BestSucc = Result.BB;
1724     bool ShouldTailDup = Result.ShouldTailDup;
1725     if (allowTailDupPlacement())
1726       ShouldTailDup |= (BestSucc && shouldTailDuplicate(BestSucc));
1727 
1728     // If an immediate successor isn't available, look for the best viable
1729     // block among those we've identified as not violating the loop's CFG at
1730     // this point. This won't be a fallthrough, but it will increase locality.
1731     if (!BestSucc)
1732       BestSucc = selectBestCandidateBlock(Chain, BlockWorkList);
1733     if (!BestSucc)
1734       BestSucc = selectBestCandidateBlock(Chain, EHPadWorkList);
1735 
1736     if (!BestSucc) {
1737       BestSucc = getFirstUnplacedBlock(Chain, PrevUnplacedBlockIt, BlockFilter);
1738       if (!BestSucc)
1739         break;
1740 
1741       LLVM_DEBUG(dbgs() << "Unnatural loop CFG detected, forcibly merging the "
1742                            "layout successor until the CFG reduces\n");
1743     }
1744 
1745     // Placement may have changed tail duplication opportunities.
1746     // Check for that now.
1747     if (allowTailDupPlacement() && BestSucc && ShouldTailDup) {
1748       // If the chosen successor was duplicated into all its predecessors,
1749       // don't bother laying it out, just go round the loop again with BB as
1750       // the chain end.
1751       if (repeatedlyTailDuplicateBlock(BestSucc, BB, LoopHeaderBB, Chain,
1752                                        BlockFilter, PrevUnplacedBlockIt))
1753         continue;
1754     }
1755 
1756     // Place this block, updating the datastructures to reflect its placement.
1757     BlockChain &SuccChain = *BlockToChain[BestSucc];
1758     // Zero out UnscheduledPredecessors for the successor we're about to merge in case
1759     // we selected a successor that didn't fit naturally into the CFG.
1760     SuccChain.UnscheduledPredecessors = 0;
1761     LLVM_DEBUG(dbgs() << "Merging from " << getBlockName(BB) << " to "
1762                       << getBlockName(BestSucc) << "\n");
1763     markChainSuccessors(SuccChain, LoopHeaderBB, BlockFilter);
1764     Chain.merge(BestSucc, &SuccChain);
1765     BB = *std::prev(Chain.end());
1766   }
1767 
1768   LLVM_DEBUG(dbgs() << "Finished forming chain for header block "
1769                     << getBlockName(*Chain.begin()) << "\n");
1770 }
1771 
1772 // If bottom of block BB has only one successor OldTop, in most cases it is
1773 // profitable to move it before OldTop, except the following case:
1774 //
1775 //     -->OldTop<-
1776 //     |    .    |
1777 //     |    .    |
1778 //     |    .    |
1779 //     ---Pred   |
1780 //          |    |
1781 //         BB-----
1782 //
1783 // If BB is moved before OldTop, Pred needs a taken branch to BB, and it can't
1784 // layout the other successor below it, so it can't reduce taken branch.
1785 // In this case we keep its original layout.
1786 bool
1787 MachineBlockPlacement::canMoveBottomBlockToTop(
1788     const MachineBasicBlock *BottomBlock,
1789     const MachineBasicBlock *OldTop) {
1790   if (BottomBlock->pred_size() != 1)
1791     return true;
1792   MachineBasicBlock *Pred = *BottomBlock->pred_begin();
1793   if (Pred->succ_size() != 2)
1794     return true;
1795 
1796   MachineBasicBlock *OtherBB = *Pred->succ_begin();
1797   if (OtherBB == BottomBlock)
1798     OtherBB = *Pred->succ_rbegin();
1799   if (OtherBB == OldTop)
1800     return false;
1801 
1802   return true;
1803 }
1804 
1805 // Find out the possible fall through frequence to the top of a loop.
1806 BlockFrequency
1807 MachineBlockPlacement::TopFallThroughFreq(
1808     const MachineBasicBlock *Top,
1809     const BlockFilterSet &LoopBlockSet) {
1810   BlockFrequency MaxFreq = 0;
1811   for (MachineBasicBlock *Pred : Top->predecessors()) {
1812     BlockChain *PredChain = BlockToChain[Pred];
1813     if (!LoopBlockSet.count(Pred) &&
1814         (!PredChain || Pred == *std::prev(PredChain->end()))) {
1815       // Found a Pred block can be placed before Top.
1816       // Check if Top is the best successor of Pred.
1817       auto TopProb = MBPI->getEdgeProbability(Pred, Top);
1818       bool TopOK = true;
1819       for (MachineBasicBlock *Succ : Pred->successors()) {
1820         auto SuccProb = MBPI->getEdgeProbability(Pred, Succ);
1821         BlockChain *SuccChain = BlockToChain[Succ];
1822         // Check if Succ can be placed after Pred.
1823         // Succ should not be in any chain, or it is the head of some chain.
1824         if (!LoopBlockSet.count(Succ) && (SuccProb > TopProb) &&
1825             (!SuccChain || Succ == *SuccChain->begin())) {
1826           TopOK = false;
1827           break;
1828         }
1829       }
1830       if (TopOK) {
1831         BlockFrequency EdgeFreq = MBFI->getBlockFreq(Pred) *
1832                                   MBPI->getEdgeProbability(Pred, Top);
1833         if (EdgeFreq > MaxFreq)
1834           MaxFreq = EdgeFreq;
1835       }
1836     }
1837   }
1838   return MaxFreq;
1839 }
1840 
1841 // Compute the fall through gains when move NewTop before OldTop.
1842 //
1843 // In following diagram, edges marked as "-" are reduced fallthrough, edges
1844 // marked as "+" are increased fallthrough, this function computes
1845 //
1846 //      SUM(increased fallthrough) - SUM(decreased fallthrough)
1847 //
1848 //              |
1849 //              | -
1850 //              V
1851 //        --->OldTop
1852 //        |     .
1853 //        |     .
1854 //       +|     .    +
1855 //        |   Pred --->
1856 //        |     |-
1857 //        |     V
1858 //        --- NewTop <---
1859 //              |-
1860 //              V
1861 //
1862 BlockFrequency
1863 MachineBlockPlacement::FallThroughGains(
1864     const MachineBasicBlock *NewTop,
1865     const MachineBasicBlock *OldTop,
1866     const MachineBasicBlock *ExitBB,
1867     const BlockFilterSet &LoopBlockSet) {
1868   BlockFrequency FallThrough2Top = TopFallThroughFreq(OldTop, LoopBlockSet);
1869   BlockFrequency FallThrough2Exit = 0;
1870   if (ExitBB)
1871     FallThrough2Exit = MBFI->getBlockFreq(NewTop) *
1872         MBPI->getEdgeProbability(NewTop, ExitBB);
1873   BlockFrequency BackEdgeFreq = MBFI->getBlockFreq(NewTop) *
1874       MBPI->getEdgeProbability(NewTop, OldTop);
1875 
1876   // Find the best Pred of NewTop.
1877    MachineBasicBlock *BestPred = nullptr;
1878    BlockFrequency FallThroughFromPred = 0;
1879    for (MachineBasicBlock *Pred : NewTop->predecessors()) {
1880      if (!LoopBlockSet.count(Pred))
1881        continue;
1882      BlockChain *PredChain = BlockToChain[Pred];
1883      if (!PredChain || Pred == *std::prev(PredChain->end())) {
1884        BlockFrequency EdgeFreq = MBFI->getBlockFreq(Pred) *
1885            MBPI->getEdgeProbability(Pred, NewTop);
1886        if (EdgeFreq > FallThroughFromPred) {
1887          FallThroughFromPred = EdgeFreq;
1888          BestPred = Pred;
1889        }
1890      }
1891    }
1892 
1893    // If NewTop is not placed after Pred, another successor can be placed
1894    // after Pred.
1895    BlockFrequency NewFreq = 0;
1896    if (BestPred) {
1897      for (MachineBasicBlock *Succ : BestPred->successors()) {
1898        if ((Succ == NewTop) || (Succ == BestPred) || !LoopBlockSet.count(Succ))
1899          continue;
1900        if (ComputedEdges.find(Succ) != ComputedEdges.end())
1901          continue;
1902        BlockChain *SuccChain = BlockToChain[Succ];
1903        if ((SuccChain && (Succ != *SuccChain->begin())) ||
1904            (SuccChain == BlockToChain[BestPred]))
1905          continue;
1906        BlockFrequency EdgeFreq = MBFI->getBlockFreq(BestPred) *
1907            MBPI->getEdgeProbability(BestPred, Succ);
1908        if (EdgeFreq > NewFreq)
1909          NewFreq = EdgeFreq;
1910      }
1911      BlockFrequency OrigEdgeFreq = MBFI->getBlockFreq(BestPred) *
1912          MBPI->getEdgeProbability(BestPred, NewTop);
1913      if (NewFreq > OrigEdgeFreq) {
1914        // If NewTop is not the best successor of Pred, then Pred doesn't
1915        // fallthrough to NewTop. So there is no FallThroughFromPred and
1916        // NewFreq.
1917        NewFreq = 0;
1918        FallThroughFromPred = 0;
1919      }
1920    }
1921 
1922    BlockFrequency Result = 0;
1923    BlockFrequency Gains = BackEdgeFreq + NewFreq;
1924    BlockFrequency Lost = FallThrough2Top + FallThrough2Exit +
1925        FallThroughFromPred;
1926    if (Gains > Lost)
1927      Result = Gains - Lost;
1928    return Result;
1929 }
1930 
1931 /// Helper function of findBestLoopTop. Find the best loop top block
1932 /// from predecessors of old top.
1933 ///
1934 /// Look for a block which is strictly better than the old top for laying
1935 /// out before the old top of the loop. This looks for only two patterns:
1936 ///
1937 ///     1. a block has only one successor, the old loop top
1938 ///
1939 ///        Because such a block will always result in an unconditional jump,
1940 ///        rotating it in front of the old top is always profitable.
1941 ///
1942 ///     2. a block has two successors, one is old top, another is exit
1943 ///        and it has more than one predecessors
1944 ///
1945 ///        If it is below one of its predecessors P, only P can fall through to
1946 ///        it, all other predecessors need a jump to it, and another conditional
1947 ///        jump to loop header. If it is moved before loop header, all its
1948 ///        predecessors jump to it, then fall through to loop header. So all its
1949 ///        predecessors except P can reduce one taken branch.
1950 ///        At the same time, move it before old top increases the taken branch
1951 ///        to loop exit block, so the reduced taken branch will be compared with
1952 ///        the increased taken branch to the loop exit block.
1953 ///
1954 ///        This pattern is enabled only when PlainMode is false.
1955 MachineBasicBlock *
1956 MachineBlockPlacement::findBestLoopTopHelper(
1957     MachineBasicBlock *OldTop,
1958     const MachineLoop &L,
1959     const BlockFilterSet &LoopBlockSet,
1960     bool HasStaticProfileOnly) {
1961   // Check that the header hasn't been fused with a preheader block due to
1962   // crazy branches. If it has, we need to start with the header at the top to
1963   // prevent pulling the preheader into the loop body.
1964   BlockChain &HeaderChain = *BlockToChain[OldTop];
1965   if (!LoopBlockSet.count(*HeaderChain.begin()))
1966     return OldTop;
1967 
1968   LLVM_DEBUG(dbgs() << "Finding best loop top for: " << getBlockName(OldTop)
1969                     << "\n");
1970 
1971   BlockFrequency BestGains = 0;
1972   MachineBasicBlock *BestPred = nullptr;
1973   for (MachineBasicBlock *Pred : OldTop->predecessors()) {
1974     if (!LoopBlockSet.count(Pred))
1975       continue;
1976     if (Pred == L.getHeader())
1977       continue;
1978     LLVM_DEBUG(dbgs() << "   old top pred: " << getBlockName(Pred) << ", has "
1979                       << Pred->succ_size() << " successors, ";
1980                MBFI->printBlockFreq(dbgs(), Pred) << " freq\n");
1981     if (Pred->succ_size() > 2)
1982       continue;
1983 
1984     if (!canMoveBottomBlockToTop(Pred, OldTop))
1985       continue;
1986 
1987     if (HasStaticProfileOnly) {
1988       // In plain mode we consider pattern 1 only.
1989       if (Pred->succ_size() > 1)
1990         continue;
1991 
1992       BlockFrequency PredFreq = MBFI->getBlockFreq(Pred);
1993       if (!BestPred || PredFreq > BestGains ||
1994           (!(PredFreq < BestGains) &&
1995            Pred->isLayoutSuccessor(OldTop))) {
1996         BestPred = Pred;
1997         BestGains = PredFreq;
1998       }
1999     } else {
2000       // With profile information we also consider pattern 2.
2001       MachineBasicBlock *OtherBB = nullptr;
2002       if (Pred->succ_size() == 2) {
2003         OtherBB = *Pred->succ_begin();
2004         if (OtherBB == OldTop)
2005           OtherBB = *Pred->succ_rbegin();
2006       }
2007 
2008       // And more sophisticated cost model.
2009       BlockFrequency Gains = FallThroughGains(Pred, OldTop, OtherBB,
2010                                               LoopBlockSet);
2011       if ((Gains > 0) && (Gains > BestGains ||
2012           ((Gains == BestGains) && Pred->isLayoutSuccessor(OldTop)))) {
2013         BestPred = Pred;
2014         BestGains = Gains;
2015       }
2016     }
2017   }
2018 
2019   // If no direct predecessor is fine, just use the loop header.
2020   if (!BestPred) {
2021     LLVM_DEBUG(dbgs() << "    final top unchanged\n");
2022     return OldTop;
2023   }
2024 
2025   // Walk backwards through any straight line of predecessors.
2026   while (BestPred->pred_size() == 1 &&
2027          (*BestPred->pred_begin())->succ_size() == 1 &&
2028          *BestPred->pred_begin() != L.getHeader())
2029     BestPred = *BestPred->pred_begin();
2030 
2031   LLVM_DEBUG(dbgs() << "    final top: " << getBlockName(BestPred) << "\n");
2032   return BestPred;
2033 }
2034 
2035 /// Find the best loop top block for layout in FDO mode.
2036 ///
2037 /// This function iteratively calls findBestLoopTopHelper, until no new better
2038 /// BB can be found.
2039 MachineBasicBlock *
2040 MachineBlockPlacement::findBestLoopTop(const MachineLoop &L,
2041                                        const BlockFilterSet &LoopBlockSet) {
2042   // Placing the latch block before the header may introduce an extra branch
2043   // that skips this block the first time the loop is executed, which we want
2044   // to avoid when optimising for size.
2045   // FIXME: in theory there is a case that does not introduce a new branch,
2046   // i.e. when the layout predecessor does not fallthrough to the loop header.
2047   // In practice this never happens though: there always seems to be a preheader
2048   // that can fallthrough and that is also placed before the header.
2049   if (F->getFunction().hasOptSize())
2050     return L.getHeader();
2051 
2052   MachineBasicBlock *OldTop = nullptr;
2053   MachineBasicBlock *NewTop = L.getHeader();
2054   while (NewTop != OldTop) {
2055     OldTop = NewTop;
2056     NewTop = findBestLoopTopHelper(OldTop, L, LoopBlockSet);
2057     if (NewTop != OldTop)
2058       ComputedEdges[NewTop] = { OldTop, false };
2059   }
2060   return NewTop;
2061 }
2062 
2063 /// Find the best loop top block for layout in plain mode. It is less agressive
2064 /// than findBestLoopTop.
2065 ///
2066 /// Look for a block which is strictly better than the loop header for laying
2067 /// out at the top of the loop. This looks for one and only one pattern:
2068 /// a latch block with no conditional exit. This block will cause a conditional
2069 /// jump around it or will be the bottom of the loop if we lay it out in place,
2070 /// but if it doesn't end up at the bottom of the loop for any reason,
2071 /// rotation alone won't fix it. Because such a block will always result in an
2072 /// unconditional jump (for the backedge) rotating it in front of the loop
2073 /// header is always profitable.
2074 MachineBasicBlock *
2075 MachineBlockPlacement::findBestLoopTopNoProfile(
2076     const MachineLoop &L,
2077     const BlockFilterSet &LoopBlockSet) {
2078   // Placing the latch block before the header may introduce an extra branch
2079   // that skips this block the first time the loop is executed, which we want
2080   // to avoid when optimising for size.
2081   // FIXME: in theory there is a case that does not introduce a new branch,
2082   // i.e. when the layout predecessor does not fallthrough to the loop header.
2083   // In practice this never happens though: there always seems to be a preheader
2084   // that can fallthrough and that is also placed before the header.
2085   if (F->getFunction().hasOptSize())
2086     return L.getHeader();
2087 
2088   return findBestLoopTopHelper(L.getHeader(), L, LoopBlockSet, true);
2089 }
2090 
2091 /// Find the best loop exiting block for layout.
2092 ///
2093 /// This routine implements the logic to analyze the loop looking for the best
2094 /// block to layout at the top of the loop. Typically this is done to maximize
2095 /// fallthrough opportunities.
2096 MachineBasicBlock *
2097 MachineBlockPlacement::findBestLoopExit(const MachineLoop &L,
2098                                         const BlockFilterSet &LoopBlockSet) {
2099   // We don't want to layout the loop linearly in all cases. If the loop header
2100   // is just a normal basic block in the loop, we want to look for what block
2101   // within the loop is the best one to layout at the top. However, if the loop
2102   // header has be pre-merged into a chain due to predecessors not having
2103   // analyzable branches, *and* the predecessor it is merged with is *not* part
2104   // of the loop, rotating the header into the middle of the loop will create
2105   // a non-contiguous range of blocks which is Very Bad. So start with the
2106   // header and only rotate if safe.
2107   BlockChain &HeaderChain = *BlockToChain[L.getHeader()];
2108   if (!LoopBlockSet.count(*HeaderChain.begin()))
2109     return nullptr;
2110 
2111   BlockFrequency BestExitEdgeFreq;
2112   unsigned BestExitLoopDepth = 0;
2113   MachineBasicBlock *ExitingBB = nullptr;
2114   // If there are exits to outer loops, loop rotation can severely limit
2115   // fallthrough opportunities unless it selects such an exit. Keep a set of
2116   // blocks where rotating to exit with that block will reach an outer loop.
2117   SmallPtrSet<MachineBasicBlock *, 4> BlocksExitingToOuterLoop;
2118 
2119   LLVM_DEBUG(dbgs() << "Finding best loop exit for: "
2120                     << getBlockName(L.getHeader()) << "\n");
2121   for (MachineBasicBlock *MBB : L.getBlocks()) {
2122     BlockChain &Chain = *BlockToChain[MBB];
2123     // Ensure that this block is at the end of a chain; otherwise it could be
2124     // mid-way through an inner loop or a successor of an unanalyzable branch.
2125     if (MBB != *std::prev(Chain.end()))
2126       continue;
2127 
2128     // Now walk the successors. We need to establish whether this has a viable
2129     // exiting successor and whether it has a viable non-exiting successor.
2130     // We store the old exiting state and restore it if a viable looping
2131     // successor isn't found.
2132     MachineBasicBlock *OldExitingBB = ExitingBB;
2133     BlockFrequency OldBestExitEdgeFreq = BestExitEdgeFreq;
2134     bool HasLoopingSucc = false;
2135     for (MachineBasicBlock *Succ : MBB->successors()) {
2136       if (Succ->isEHPad())
2137         continue;
2138       if (Succ == MBB)
2139         continue;
2140       BlockChain &SuccChain = *BlockToChain[Succ];
2141       // Don't split chains, either this chain or the successor's chain.
2142       if (&Chain == &SuccChain) {
2143         LLVM_DEBUG(dbgs() << "    exiting: " << getBlockName(MBB) << " -> "
2144                           << getBlockName(Succ) << " (chain conflict)\n");
2145         continue;
2146       }
2147 
2148       auto SuccProb = MBPI->getEdgeProbability(MBB, Succ);
2149       if (LoopBlockSet.count(Succ)) {
2150         LLVM_DEBUG(dbgs() << "    looping: " << getBlockName(MBB) << " -> "
2151                           << getBlockName(Succ) << " (" << SuccProb << ")\n");
2152         HasLoopingSucc = true;
2153         continue;
2154       }
2155 
2156       unsigned SuccLoopDepth = 0;
2157       if (MachineLoop *ExitLoop = MLI->getLoopFor(Succ)) {
2158         SuccLoopDepth = ExitLoop->getLoopDepth();
2159         if (ExitLoop->contains(&L))
2160           BlocksExitingToOuterLoop.insert(MBB);
2161       }
2162 
2163       BlockFrequency ExitEdgeFreq = MBFI->getBlockFreq(MBB) * SuccProb;
2164       LLVM_DEBUG(dbgs() << "    exiting: " << getBlockName(MBB) << " -> "
2165                         << getBlockName(Succ) << " [L:" << SuccLoopDepth
2166                         << "] (";
2167                  MBFI->printBlockFreq(dbgs(), ExitEdgeFreq) << ")\n");
2168       // Note that we bias this toward an existing layout successor to retain
2169       // incoming order in the absence of better information. The exit must have
2170       // a frequency higher than the current exit before we consider breaking
2171       // the layout.
2172       BranchProbability Bias(100 - ExitBlockBias, 100);
2173       if (!ExitingBB || SuccLoopDepth > BestExitLoopDepth ||
2174           ExitEdgeFreq > BestExitEdgeFreq ||
2175           (MBB->isLayoutSuccessor(Succ) &&
2176            !(ExitEdgeFreq < BestExitEdgeFreq * Bias))) {
2177         BestExitEdgeFreq = ExitEdgeFreq;
2178         ExitingBB = MBB;
2179       }
2180     }
2181 
2182     if (!HasLoopingSucc) {
2183       // Restore the old exiting state, no viable looping successor was found.
2184       ExitingBB = OldExitingBB;
2185       BestExitEdgeFreq = OldBestExitEdgeFreq;
2186     }
2187   }
2188   // Without a candidate exiting block or with only a single block in the
2189   // loop, just use the loop header to layout the loop.
2190   if (!ExitingBB) {
2191     LLVM_DEBUG(
2192         dbgs() << "    No other candidate exit blocks, using loop header\n");
2193     return nullptr;
2194   }
2195   if (L.getNumBlocks() == 1) {
2196     LLVM_DEBUG(dbgs() << "    Loop has 1 block, using loop header as exit\n");
2197     return nullptr;
2198   }
2199 
2200   // Also, if we have exit blocks which lead to outer loops but didn't select
2201   // one of them as the exiting block we are rotating toward, disable loop
2202   // rotation altogether.
2203   if (!BlocksExitingToOuterLoop.empty() &&
2204       !BlocksExitingToOuterLoop.count(ExitingBB))
2205     return nullptr;
2206 
2207   LLVM_DEBUG(dbgs() << "  Best exiting block: " << getBlockName(ExitingBB)
2208                     << "\n");
2209   return ExitingBB;
2210 }
2211 
2212 /// Check if there is a fallthrough to loop header Top.
2213 ///
2214 ///   1. Look for a Pred that can be layout before Top.
2215 ///   2. Check if Top is the most possible successor of Pred.
2216 bool
2217 MachineBlockPlacement::hasViableTopFallthrough(
2218     const MachineBasicBlock *Top,
2219     const BlockFilterSet &LoopBlockSet) {
2220   for (MachineBasicBlock *Pred : Top->predecessors()) {
2221     BlockChain *PredChain = BlockToChain[Pred];
2222     if (!LoopBlockSet.count(Pred) &&
2223         (!PredChain || Pred == *std::prev(PredChain->end()))) {
2224       // Found a Pred block can be placed before Top.
2225       // Check if Top is the best successor of Pred.
2226       auto TopProb = MBPI->getEdgeProbability(Pred, Top);
2227       bool TopOK = true;
2228       for (MachineBasicBlock *Succ : Pred->successors()) {
2229         auto SuccProb = MBPI->getEdgeProbability(Pred, Succ);
2230         BlockChain *SuccChain = BlockToChain[Succ];
2231         // Check if Succ can be placed after Pred.
2232         // Succ should not be in any chain, or it is the head of some chain.
2233         if ((!SuccChain || Succ == *SuccChain->begin()) && SuccProb > TopProb) {
2234           TopOK = false;
2235           break;
2236         }
2237       }
2238       if (TopOK)
2239         return true;
2240     }
2241   }
2242   return false;
2243 }
2244 
2245 /// Attempt to rotate an exiting block to the bottom of the loop.
2246 ///
2247 /// Once we have built a chain, try to rotate it to line up the hot exit block
2248 /// with fallthrough out of the loop if doing so doesn't introduce unnecessary
2249 /// branches. For example, if the loop has fallthrough into its header and out
2250 /// of its bottom already, don't rotate it.
2251 void MachineBlockPlacement::rotateLoop(BlockChain &LoopChain,
2252                                        const MachineBasicBlock *ExitingBB,
2253                                        const BlockFilterSet &LoopBlockSet) {
2254   if (!ExitingBB)
2255     return;
2256 
2257   MachineBasicBlock *Top = *LoopChain.begin();
2258   MachineBasicBlock *Bottom = *std::prev(LoopChain.end());
2259 
2260   // If ExitingBB is already the last one in a chain then nothing to do.
2261   if (Bottom == ExitingBB)
2262     return;
2263 
2264   bool ViableTopFallthrough = hasViableTopFallthrough(Top, LoopBlockSet);
2265 
2266   // If the header has viable fallthrough, check whether the current loop
2267   // bottom is a viable exiting block. If so, bail out as rotating will
2268   // introduce an unnecessary branch.
2269   if (ViableTopFallthrough) {
2270     for (MachineBasicBlock *Succ : Bottom->successors()) {
2271       BlockChain *SuccChain = BlockToChain[Succ];
2272       if (!LoopBlockSet.count(Succ) &&
2273           (!SuccChain || Succ == *SuccChain->begin()))
2274         return;
2275     }
2276   }
2277 
2278   BlockChain::iterator ExitIt = llvm::find(LoopChain, ExitingBB);
2279   if (ExitIt == LoopChain.end())
2280     return;
2281 
2282   // Rotating a loop exit to the bottom when there is a fallthrough to top
2283   // trades the entry fallthrough for an exit fallthrough.
2284   // If there is no bottom->top edge, but the chosen exit block does have
2285   // a fallthrough, we break that fallthrough for nothing in return.
2286 
2287   // Let's consider an example. We have a built chain of basic blocks
2288   // B1, B2, ..., Bn, where Bk is a ExitingBB - chosen exit block.
2289   // By doing a rotation we get
2290   // Bk+1, ..., Bn, B1, ..., Bk
2291   // Break of fallthrough to B1 is compensated by a fallthrough from Bk.
2292   // If we had a fallthrough Bk -> Bk+1 it is broken now.
2293   // It might be compensated by fallthrough Bn -> B1.
2294   // So we have a condition to avoid creation of extra branch by loop rotation.
2295   // All below must be true to avoid loop rotation:
2296   //   If there is a fallthrough to top (B1)
2297   //   There was fallthrough from chosen exit block (Bk) to next one (Bk+1)
2298   //   There is no fallthrough from bottom (Bn) to top (B1).
2299   // Please note that there is no exit fallthrough from Bn because we checked it
2300   // above.
2301   if (ViableTopFallthrough) {
2302     assert(std::next(ExitIt) != LoopChain.end() &&
2303            "Exit should not be last BB");
2304     MachineBasicBlock *NextBlockInChain = *std::next(ExitIt);
2305     if (ExitingBB->isSuccessor(NextBlockInChain))
2306       if (!Bottom->isSuccessor(Top))
2307         return;
2308   }
2309 
2310   LLVM_DEBUG(dbgs() << "Rotating loop to put exit " << getBlockName(ExitingBB)
2311                     << " at bottom\n");
2312   std::rotate(LoopChain.begin(), std::next(ExitIt), LoopChain.end());
2313 }
2314 
2315 /// Attempt to rotate a loop based on profile data to reduce branch cost.
2316 ///
2317 /// With profile data, we can determine the cost in terms of missed fall through
2318 /// opportunities when rotating a loop chain and select the best rotation.
2319 /// Basically, there are three kinds of cost to consider for each rotation:
2320 ///    1. The possibly missed fall through edge (if it exists) from BB out of
2321 ///    the loop to the loop header.
2322 ///    2. The possibly missed fall through edges (if they exist) from the loop
2323 ///    exits to BB out of the loop.
2324 ///    3. The missed fall through edge (if it exists) from the last BB to the
2325 ///    first BB in the loop chain.
2326 ///  Therefore, the cost for a given rotation is the sum of costs listed above.
2327 ///  We select the best rotation with the smallest cost.
2328 void MachineBlockPlacement::rotateLoopWithProfile(
2329     BlockChain &LoopChain, const MachineLoop &L,
2330     const BlockFilterSet &LoopBlockSet) {
2331   auto RotationPos = LoopChain.end();
2332 
2333   BlockFrequency SmallestRotationCost = BlockFrequency::getMaxFrequency();
2334 
2335   // A utility lambda that scales up a block frequency by dividing it by a
2336   // branch probability which is the reciprocal of the scale.
2337   auto ScaleBlockFrequency = [](BlockFrequency Freq,
2338                                 unsigned Scale) -> BlockFrequency {
2339     if (Scale == 0)
2340       return 0;
2341     // Use operator / between BlockFrequency and BranchProbability to implement
2342     // saturating multiplication.
2343     return Freq / BranchProbability(1, Scale);
2344   };
2345 
2346   // Compute the cost of the missed fall-through edge to the loop header if the
2347   // chain head is not the loop header. As we only consider natural loops with
2348   // single header, this computation can be done only once.
2349   BlockFrequency HeaderFallThroughCost(0);
2350   MachineBasicBlock *ChainHeaderBB = *LoopChain.begin();
2351   for (auto *Pred : ChainHeaderBB->predecessors()) {
2352     BlockChain *PredChain = BlockToChain[Pred];
2353     if (!LoopBlockSet.count(Pred) &&
2354         (!PredChain || Pred == *std::prev(PredChain->end()))) {
2355       auto EdgeFreq = MBFI->getBlockFreq(Pred) *
2356           MBPI->getEdgeProbability(Pred, ChainHeaderBB);
2357       auto FallThruCost = ScaleBlockFrequency(EdgeFreq, MisfetchCost);
2358       // If the predecessor has only an unconditional jump to the header, we
2359       // need to consider the cost of this jump.
2360       if (Pred->succ_size() == 1)
2361         FallThruCost += ScaleBlockFrequency(EdgeFreq, JumpInstCost);
2362       HeaderFallThroughCost = std::max(HeaderFallThroughCost, FallThruCost);
2363     }
2364   }
2365 
2366   // Here we collect all exit blocks in the loop, and for each exit we find out
2367   // its hottest exit edge. For each loop rotation, we define the loop exit cost
2368   // as the sum of frequencies of exit edges we collect here, excluding the exit
2369   // edge from the tail of the loop chain.
2370   SmallVector<std::pair<MachineBasicBlock *, BlockFrequency>, 4> ExitsWithFreq;
2371   for (auto BB : LoopChain) {
2372     auto LargestExitEdgeProb = BranchProbability::getZero();
2373     for (auto *Succ : BB->successors()) {
2374       BlockChain *SuccChain = BlockToChain[Succ];
2375       if (!LoopBlockSet.count(Succ) &&
2376           (!SuccChain || Succ == *SuccChain->begin())) {
2377         auto SuccProb = MBPI->getEdgeProbability(BB, Succ);
2378         LargestExitEdgeProb = std::max(LargestExitEdgeProb, SuccProb);
2379       }
2380     }
2381     if (LargestExitEdgeProb > BranchProbability::getZero()) {
2382       auto ExitFreq = MBFI->getBlockFreq(BB) * LargestExitEdgeProb;
2383       ExitsWithFreq.emplace_back(BB, ExitFreq);
2384     }
2385   }
2386 
2387   // In this loop we iterate every block in the loop chain and calculate the
2388   // cost assuming the block is the head of the loop chain. When the loop ends,
2389   // we should have found the best candidate as the loop chain's head.
2390   for (auto Iter = LoopChain.begin(), TailIter = std::prev(LoopChain.end()),
2391             EndIter = LoopChain.end();
2392        Iter != EndIter; Iter++, TailIter++) {
2393     // TailIter is used to track the tail of the loop chain if the block we are
2394     // checking (pointed by Iter) is the head of the chain.
2395     if (TailIter == LoopChain.end())
2396       TailIter = LoopChain.begin();
2397 
2398     auto TailBB = *TailIter;
2399 
2400     // Calculate the cost by putting this BB to the top.
2401     BlockFrequency Cost = 0;
2402 
2403     // If the current BB is the loop header, we need to take into account the
2404     // cost of the missed fall through edge from outside of the loop to the
2405     // header.
2406     if (Iter != LoopChain.begin())
2407       Cost += HeaderFallThroughCost;
2408 
2409     // Collect the loop exit cost by summing up frequencies of all exit edges
2410     // except the one from the chain tail.
2411     for (auto &ExitWithFreq : ExitsWithFreq)
2412       if (TailBB != ExitWithFreq.first)
2413         Cost += ExitWithFreq.second;
2414 
2415     // The cost of breaking the once fall-through edge from the tail to the top
2416     // of the loop chain. Here we need to consider three cases:
2417     // 1. If the tail node has only one successor, then we will get an
2418     //    additional jmp instruction. So the cost here is (MisfetchCost +
2419     //    JumpInstCost) * tail node frequency.
2420     // 2. If the tail node has two successors, then we may still get an
2421     //    additional jmp instruction if the layout successor after the loop
2422     //    chain is not its CFG successor. Note that the more frequently executed
2423     //    jmp instruction will be put ahead of the other one. Assume the
2424     //    frequency of those two branches are x and y, where x is the frequency
2425     //    of the edge to the chain head, then the cost will be
2426     //    (x * MisfetechCost + min(x, y) * JumpInstCost) * tail node frequency.
2427     // 3. If the tail node has more than two successors (this rarely happens),
2428     //    we won't consider any additional cost.
2429     if (TailBB->isSuccessor(*Iter)) {
2430       auto TailBBFreq = MBFI->getBlockFreq(TailBB);
2431       if (TailBB->succ_size() == 1)
2432         Cost += ScaleBlockFrequency(TailBBFreq.getFrequency(),
2433                                     MisfetchCost + JumpInstCost);
2434       else if (TailBB->succ_size() == 2) {
2435         auto TailToHeadProb = MBPI->getEdgeProbability(TailBB, *Iter);
2436         auto TailToHeadFreq = TailBBFreq * TailToHeadProb;
2437         auto ColderEdgeFreq = TailToHeadProb > BranchProbability(1, 2)
2438                                   ? TailBBFreq * TailToHeadProb.getCompl()
2439                                   : TailToHeadFreq;
2440         Cost += ScaleBlockFrequency(TailToHeadFreq, MisfetchCost) +
2441                 ScaleBlockFrequency(ColderEdgeFreq, JumpInstCost);
2442       }
2443     }
2444 
2445     LLVM_DEBUG(dbgs() << "The cost of loop rotation by making "
2446                       << getBlockName(*Iter)
2447                       << " to the top: " << Cost.getFrequency() << "\n");
2448 
2449     if (Cost < SmallestRotationCost) {
2450       SmallestRotationCost = Cost;
2451       RotationPos = Iter;
2452     }
2453   }
2454 
2455   if (RotationPos != LoopChain.end()) {
2456     LLVM_DEBUG(dbgs() << "Rotate loop by making " << getBlockName(*RotationPos)
2457                       << " to the top\n");
2458     std::rotate(LoopChain.begin(), RotationPos, LoopChain.end());
2459   }
2460 }
2461 
2462 /// Collect blocks in the given loop that are to be placed.
2463 ///
2464 /// When profile data is available, exclude cold blocks from the returned set;
2465 /// otherwise, collect all blocks in the loop.
2466 MachineBlockPlacement::BlockFilterSet
2467 MachineBlockPlacement::collectLoopBlockSet(const MachineLoop &L) {
2468   BlockFilterSet LoopBlockSet;
2469 
2470   // Filter cold blocks off from LoopBlockSet when profile data is available.
2471   // Collect the sum of frequencies of incoming edges to the loop header from
2472   // outside. If we treat the loop as a super block, this is the frequency of
2473   // the loop. Then for each block in the loop, we calculate the ratio between
2474   // its frequency and the frequency of the loop block. When it is too small,
2475   // don't add it to the loop chain. If there are outer loops, then this block
2476   // will be merged into the first outer loop chain for which this block is not
2477   // cold anymore. This needs precise profile data and we only do this when
2478   // profile data is available.
2479   if (F->getFunction().hasProfileData() || ForceLoopColdBlock) {
2480     BlockFrequency LoopFreq(0);
2481     for (auto LoopPred : L.getHeader()->predecessors())
2482       if (!L.contains(LoopPred))
2483         LoopFreq += MBFI->getBlockFreq(LoopPred) *
2484                     MBPI->getEdgeProbability(LoopPred, L.getHeader());
2485 
2486     for (MachineBasicBlock *LoopBB : L.getBlocks()) {
2487       auto Freq = MBFI->getBlockFreq(LoopBB).getFrequency();
2488       if (Freq == 0 || LoopFreq.getFrequency() / Freq > LoopToColdBlockRatio)
2489         continue;
2490       LoopBlockSet.insert(LoopBB);
2491     }
2492   } else
2493     LoopBlockSet.insert(L.block_begin(), L.block_end());
2494 
2495   return LoopBlockSet;
2496 }
2497 
2498 /// Forms basic block chains from the natural loop structures.
2499 ///
2500 /// These chains are designed to preserve the existing *structure* of the code
2501 /// as much as possible. We can then stitch the chains together in a way which
2502 /// both preserves the topological structure and minimizes taken conditional
2503 /// branches.
2504 void MachineBlockPlacement::buildLoopChains(const MachineLoop &L) {
2505   // First recurse through any nested loops, building chains for those inner
2506   // loops.
2507   for (const MachineLoop *InnerLoop : L)
2508     buildLoopChains(*InnerLoop);
2509 
2510   assert(BlockWorkList.empty() &&
2511          "BlockWorkList not empty when starting to build loop chains.");
2512   assert(EHPadWorkList.empty() &&
2513          "EHPadWorkList not empty when starting to build loop chains.");
2514   BlockFilterSet LoopBlockSet = collectLoopBlockSet(L);
2515 
2516   // Check if we have profile data for this function. If yes, we will rotate
2517   // this loop by modeling costs more precisely which requires the profile data
2518   // for better layout.
2519   bool RotateLoopWithProfile =
2520       ForcePreciseRotationCost ||
2521       (PreciseRotationCost && F->getFunction().hasProfileData());
2522 
2523   // First check to see if there is an obviously preferable top block for the
2524   // loop. This will default to the header, but may end up as one of the
2525   // predecessors to the header if there is one which will result in strictly
2526   // fewer branches in the loop body.
2527   MachineBasicBlock *LoopTop =
2528       (RotateLoopWithProfile || F->getFunction().hasProfileData()) ?
2529           findBestLoopTop(L, LoopBlockSet) :
2530           findBestLoopTopNoProfile(L, LoopBlockSet);
2531 
2532   // If we selected just the header for the loop top, look for a potentially
2533   // profitable exit block in the event that rotating the loop can eliminate
2534   // branches by placing an exit edge at the bottom.
2535   //
2536   // Loops are processed innermost to uttermost, make sure we clear
2537   // PreferredLoopExit before processing a new loop.
2538   PreferredLoopExit = nullptr;
2539   if (!RotateLoopWithProfile && LoopTop == L.getHeader())
2540     PreferredLoopExit = findBestLoopExit(L, LoopBlockSet);
2541 
2542   BlockChain &LoopChain = *BlockToChain[LoopTop];
2543 
2544   // FIXME: This is a really lame way of walking the chains in the loop: we
2545   // walk the blocks, and use a set to prevent visiting a particular chain
2546   // twice.
2547   SmallPtrSet<BlockChain *, 4> UpdatedPreds;
2548   assert(LoopChain.UnscheduledPredecessors == 0 &&
2549          "LoopChain should not have unscheduled predecessors.");
2550   UpdatedPreds.insert(&LoopChain);
2551 
2552   for (const MachineBasicBlock *LoopBB : LoopBlockSet)
2553     fillWorkLists(LoopBB, UpdatedPreds, &LoopBlockSet);
2554 
2555   buildChain(LoopTop, LoopChain, &LoopBlockSet);
2556 
2557   if (RotateLoopWithProfile) {
2558     if (LoopTop == L.getHeader())
2559       rotateLoopWithProfile(LoopChain, L, LoopBlockSet);
2560   } else
2561     rotateLoop(LoopChain, PreferredLoopExit, LoopBlockSet);
2562 
2563   LLVM_DEBUG({
2564     // Crash at the end so we get all of the debugging output first.
2565     bool BadLoop = false;
2566     if (LoopChain.UnscheduledPredecessors) {
2567       BadLoop = true;
2568       dbgs() << "Loop chain contains a block without its preds placed!\n"
2569              << "  Loop header:  " << getBlockName(*L.block_begin()) << "\n"
2570              << "  Chain header: " << getBlockName(*LoopChain.begin()) << "\n";
2571     }
2572     for (MachineBasicBlock *ChainBB : LoopChain) {
2573       dbgs() << "          ... " << getBlockName(ChainBB) << "\n";
2574       if (!LoopBlockSet.remove(ChainBB)) {
2575         // We don't mark the loop as bad here because there are real situations
2576         // where this can occur. For example, with an unanalyzable fallthrough
2577         // from a loop block to a non-loop block or vice versa.
2578         dbgs() << "Loop chain contains a block not contained by the loop!\n"
2579                << "  Loop header:  " << getBlockName(*L.block_begin()) << "\n"
2580                << "  Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
2581                << "  Bad block:    " << getBlockName(ChainBB) << "\n";
2582       }
2583     }
2584 
2585     if (!LoopBlockSet.empty()) {
2586       BadLoop = true;
2587       for (const MachineBasicBlock *LoopBB : LoopBlockSet)
2588         dbgs() << "Loop contains blocks never placed into a chain!\n"
2589                << "  Loop header:  " << getBlockName(*L.block_begin()) << "\n"
2590                << "  Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
2591                << "  Bad block:    " << getBlockName(LoopBB) << "\n";
2592     }
2593     assert(!BadLoop && "Detected problems with the placement of this loop.");
2594   });
2595 
2596   BlockWorkList.clear();
2597   EHPadWorkList.clear();
2598 }
2599 
2600 void MachineBlockPlacement::buildCFGChains() {
2601   // Ensure that every BB in the function has an associated chain to simplify
2602   // the assumptions of the remaining algorithm.
2603   SmallVector<MachineOperand, 4> Cond; // For AnalyzeBranch.
2604   for (MachineFunction::iterator FI = F->begin(), FE = F->end(); FI != FE;
2605        ++FI) {
2606     MachineBasicBlock *BB = &*FI;
2607     BlockChain *Chain =
2608         new (ChainAllocator.Allocate()) BlockChain(BlockToChain, BB);
2609     // Also, merge any blocks which we cannot reason about and must preserve
2610     // the exact fallthrough behavior for.
2611     while (true) {
2612       Cond.clear();
2613       MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
2614       if (!TII->analyzeBranch(*BB, TBB, FBB, Cond) || !FI->canFallThrough())
2615         break;
2616 
2617       MachineFunction::iterator NextFI = std::next(FI);
2618       MachineBasicBlock *NextBB = &*NextFI;
2619       // Ensure that the layout successor is a viable block, as we know that
2620       // fallthrough is a possibility.
2621       assert(NextFI != FE && "Can't fallthrough past the last block.");
2622       LLVM_DEBUG(dbgs() << "Pre-merging due to unanalyzable fallthrough: "
2623                         << getBlockName(BB) << " -> " << getBlockName(NextBB)
2624                         << "\n");
2625       Chain->merge(NextBB, nullptr);
2626 #ifndef NDEBUG
2627       BlocksWithUnanalyzableExits.insert(&*BB);
2628 #endif
2629       FI = NextFI;
2630       BB = NextBB;
2631     }
2632   }
2633 
2634   // Build any loop-based chains.
2635   PreferredLoopExit = nullptr;
2636   for (MachineLoop *L : *MLI)
2637     buildLoopChains(*L);
2638 
2639   assert(BlockWorkList.empty() &&
2640          "BlockWorkList should be empty before building final chain.");
2641   assert(EHPadWorkList.empty() &&
2642          "EHPadWorkList should be empty before building final chain.");
2643 
2644   SmallPtrSet<BlockChain *, 4> UpdatedPreds;
2645   for (MachineBasicBlock &MBB : *F)
2646     fillWorkLists(&MBB, UpdatedPreds);
2647 
2648   BlockChain &FunctionChain = *BlockToChain[&F->front()];
2649   buildChain(&F->front(), FunctionChain);
2650 
2651 #ifndef NDEBUG
2652   using FunctionBlockSetType = SmallPtrSet<MachineBasicBlock *, 16>;
2653 #endif
2654   LLVM_DEBUG({
2655     // Crash at the end so we get all of the debugging output first.
2656     bool BadFunc = false;
2657     FunctionBlockSetType FunctionBlockSet;
2658     for (MachineBasicBlock &MBB : *F)
2659       FunctionBlockSet.insert(&MBB);
2660 
2661     for (MachineBasicBlock *ChainBB : FunctionChain)
2662       if (!FunctionBlockSet.erase(ChainBB)) {
2663         BadFunc = true;
2664         dbgs() << "Function chain contains a block not in the function!\n"
2665                << "  Bad block:    " << getBlockName(ChainBB) << "\n";
2666       }
2667 
2668     if (!FunctionBlockSet.empty()) {
2669       BadFunc = true;
2670       for (MachineBasicBlock *RemainingBB : FunctionBlockSet)
2671         dbgs() << "Function contains blocks never placed into a chain!\n"
2672                << "  Bad block:    " << getBlockName(RemainingBB) << "\n";
2673     }
2674     assert(!BadFunc && "Detected problems with the block placement.");
2675   });
2676 
2677   // Splice the blocks into place.
2678   MachineFunction::iterator InsertPos = F->begin();
2679   LLVM_DEBUG(dbgs() << "[MBP] Function: " << F->getName() << "\n");
2680   for (MachineBasicBlock *ChainBB : FunctionChain) {
2681     LLVM_DEBUG(dbgs() << (ChainBB == *FunctionChain.begin() ? "Placing chain "
2682                                                             : "          ... ")
2683                       << getBlockName(ChainBB) << "\n");
2684     if (InsertPos != MachineFunction::iterator(ChainBB))
2685       F->splice(InsertPos, ChainBB);
2686     else
2687       ++InsertPos;
2688 
2689     // Update the terminator of the previous block.
2690     if (ChainBB == *FunctionChain.begin())
2691       continue;
2692     MachineBasicBlock *PrevBB = &*std::prev(MachineFunction::iterator(ChainBB));
2693 
2694     // FIXME: It would be awesome of updateTerminator would just return rather
2695     // than assert when the branch cannot be analyzed in order to remove this
2696     // boiler plate.
2697     Cond.clear();
2698     MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
2699 
2700 #ifndef NDEBUG
2701     if (!BlocksWithUnanalyzableExits.count(PrevBB)) {
2702       // Given the exact block placement we chose, we may actually not _need_ to
2703       // be able to edit PrevBB's terminator sequence, but not being _able_ to
2704       // do that at this point is a bug.
2705       assert((!TII->analyzeBranch(*PrevBB, TBB, FBB, Cond) ||
2706               !PrevBB->canFallThrough()) &&
2707              "Unexpected block with un-analyzable fallthrough!");
2708       Cond.clear();
2709       TBB = FBB = nullptr;
2710     }
2711 #endif
2712 
2713     // The "PrevBB" is not yet updated to reflect current code layout, so,
2714     //   o. it may fall-through to a block without explicit "goto" instruction
2715     //      before layout, and no longer fall-through it after layout; or
2716     //   o. just opposite.
2717     //
2718     // analyzeBranch() may return erroneous value for FBB when these two
2719     // situations take place. For the first scenario FBB is mistakenly set NULL;
2720     // for the 2nd scenario, the FBB, which is expected to be NULL, is
2721     // mistakenly pointing to "*BI".
2722     // Thus, if the future change needs to use FBB before the layout is set, it
2723     // has to correct FBB first by using the code similar to the following:
2724     //
2725     // if (!Cond.empty() && (!FBB || FBB == ChainBB)) {
2726     //   PrevBB->updateTerminator();
2727     //   Cond.clear();
2728     //   TBB = FBB = nullptr;
2729     //   if (TII->analyzeBranch(*PrevBB, TBB, FBB, Cond)) {
2730     //     // FIXME: This should never take place.
2731     //     TBB = FBB = nullptr;
2732     //   }
2733     // }
2734     if (!TII->analyzeBranch(*PrevBB, TBB, FBB, Cond))
2735       PrevBB->updateTerminator();
2736   }
2737 
2738   // Fixup the last block.
2739   Cond.clear();
2740   MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
2741   if (!TII->analyzeBranch(F->back(), TBB, FBB, Cond))
2742     F->back().updateTerminator();
2743 
2744   BlockWorkList.clear();
2745   EHPadWorkList.clear();
2746 }
2747 
2748 void MachineBlockPlacement::optimizeBranches() {
2749   BlockChain &FunctionChain = *BlockToChain[&F->front()];
2750   SmallVector<MachineOperand, 4> Cond; // For AnalyzeBranch.
2751 
2752   // Now that all the basic blocks in the chain have the proper layout,
2753   // make a final call to AnalyzeBranch with AllowModify set.
2754   // Indeed, the target may be able to optimize the branches in a way we
2755   // cannot because all branches may not be analyzable.
2756   // E.g., the target may be able to remove an unconditional branch to
2757   // a fallthrough when it occurs after predicated terminators.
2758   SmallVector<MachineBasicBlock*, 4> EmptyBB;
2759   for (MachineBasicBlock *ChainBB : FunctionChain) {
2760     Cond.clear();
2761     MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
2762     if (!TII->analyzeBranch(*ChainBB, TBB, FBB, Cond, /*AllowModify*/ true)) {
2763       // If PrevBB has a two-way branch, try to re-order the branches
2764       // such that we branch to the successor with higher probability first.
2765       if (TBB && !Cond.empty() && FBB &&
2766           MBPI->getEdgeProbability(ChainBB, FBB) >
2767               MBPI->getEdgeProbability(ChainBB, TBB) &&
2768           !TII->reverseBranchCondition(Cond)) {
2769         LLVM_DEBUG(dbgs() << "Reverse order of the two branches: "
2770                           << getBlockName(ChainBB) << "\n");
2771         LLVM_DEBUG(dbgs() << "    Edge probability: "
2772                           << MBPI->getEdgeProbability(ChainBB, FBB) << " vs "
2773                           << MBPI->getEdgeProbability(ChainBB, TBB) << "\n");
2774         DebugLoc dl; // FIXME: this is nowhere
2775         TII->removeBranch(*ChainBB);
2776         TII->insertBranch(*ChainBB, FBB, TBB, Cond, dl);
2777         ChainBB->updateTerminator();
2778       } else if (Cond.empty() && TBB && ChainBB != TBB &&
2779                  !TBB->canFallThrough()) {
2780         // When ChainBB is unconditional branch to the TBB, and TBB has no
2781         // fallthrough predecessor and fallthrough successor, try to merge
2782         // ChainBB and TBB. This is legal under the one of following conditions:
2783         // 1. ChainBB is empty except for an unconditional branch.
2784         // 2. TBB has only one predecessor.
2785         MachineFunction::iterator I(TBB);
2786         if (((TBB == &*F->begin()) || !std::prev(I)->canFallThrough()) &&
2787              (TailDup.isSimpleBB(ChainBB) || (TBB->pred_size() == 1))) {
2788           TII->removeBranch(*ChainBB);
2789           ChainBB->removeSuccessor(TBB);
2790 
2791           // Update the CFG.
2792           for (MachineBasicBlock::pred_iterator PI = TBB->pred_begin(),
2793                PE = TBB->pred_end(); PI != PE; PI++)
2794             (*PI)->ReplaceUsesOfBlockWith(TBB, ChainBB);
2795 
2796           for (MachineBasicBlock *Succ : TBB->successors())
2797             ChainBB->addSuccessor(Succ, MBPI->getEdgeProbability(TBB, Succ));
2798 
2799           // Move all the instructions of TBB to ChainBB.
2800           ChainBB->splice(ChainBB->end(), TBB, TBB->begin(), TBB->end());
2801           EmptyBB.push_back(TBB);
2802         }
2803       }
2804     }
2805   }
2806 
2807   for (auto BB: EmptyBB) {
2808     MLI->removeBlock(BB);
2809     FunctionChain.remove(BB);
2810     BlockToChain.erase(BB);
2811     F->erase(BB);
2812   }
2813 }
2814 
2815 void MachineBlockPlacement::alignBlocks() {
2816   // Walk through the backedges of the function now that we have fully laid out
2817   // the basic blocks and align the destination of each backedge. We don't rely
2818   // exclusively on the loop info here so that we can align backedges in
2819   // unnatural CFGs and backedges that were introduced purely because of the
2820   // loop rotations done during this layout pass.
2821   if (F->getFunction().hasMinSize() ||
2822       (F->getFunction().hasOptSize() && !TLI->alignLoopsWithOptSize()))
2823     return;
2824   BlockChain &FunctionChain = *BlockToChain[&F->front()];
2825   if (FunctionChain.begin() == FunctionChain.end())
2826     return; // Empty chain.
2827 
2828   const BranchProbability ColdProb(1, 5); // 20%
2829   BlockFrequency EntryFreq = MBFI->getBlockFreq(&F->front());
2830   BlockFrequency WeightedEntryFreq = EntryFreq * ColdProb;
2831   for (MachineBasicBlock *ChainBB : FunctionChain) {
2832     if (ChainBB == *FunctionChain.begin())
2833       continue;
2834 
2835     // Don't align non-looping basic blocks. These are unlikely to execute
2836     // enough times to matter in practice. Note that we'll still handle
2837     // unnatural CFGs inside of a natural outer loop (the common case) and
2838     // rotated loops.
2839     MachineLoop *L = MLI->getLoopFor(ChainBB);
2840     if (!L)
2841       continue;
2842 
2843     unsigned Align = TLI->getPrefLoopAlignment(L);
2844     if (!Align)
2845       continue; // Don't care about loop alignment.
2846 
2847     // If the block is cold relative to the function entry don't waste space
2848     // aligning it.
2849     BlockFrequency Freq = MBFI->getBlockFreq(ChainBB);
2850     if (Freq < WeightedEntryFreq)
2851       continue;
2852 
2853     // If the block is cold relative to its loop header, don't align it
2854     // regardless of what edges into the block exist.
2855     MachineBasicBlock *LoopHeader = L->getHeader();
2856     BlockFrequency LoopHeaderFreq = MBFI->getBlockFreq(LoopHeader);
2857     if (Freq < (LoopHeaderFreq * ColdProb))
2858       continue;
2859 
2860     // Check for the existence of a non-layout predecessor which would benefit
2861     // from aligning this block.
2862     MachineBasicBlock *LayoutPred =
2863         &*std::prev(MachineFunction::iterator(ChainBB));
2864 
2865     // Force alignment if all the predecessors are jumps. We already checked
2866     // that the block isn't cold above.
2867     if (!LayoutPred->isSuccessor(ChainBB)) {
2868       ChainBB->setAlignment(Align);
2869       continue;
2870     }
2871 
2872     // Align this block if the layout predecessor's edge into this block is
2873     // cold relative to the block. When this is true, other predecessors make up
2874     // all of the hot entries into the block and thus alignment is likely to be
2875     // important.
2876     BranchProbability LayoutProb =
2877         MBPI->getEdgeProbability(LayoutPred, ChainBB);
2878     BlockFrequency LayoutEdgeFreq = MBFI->getBlockFreq(LayoutPred) * LayoutProb;
2879     if (LayoutEdgeFreq <= (Freq * ColdProb))
2880       ChainBB->setAlignment(Align);
2881   }
2882 }
2883 
2884 /// Tail duplicate \p BB into (some) predecessors if profitable, repeating if
2885 /// it was duplicated into its chain predecessor and removed.
2886 /// \p BB    - Basic block that may be duplicated.
2887 ///
2888 /// \p LPred - Chosen layout predecessor of \p BB.
2889 ///            Updated to be the chain end if LPred is removed.
2890 /// \p Chain - Chain to which \p LPred belongs, and \p BB will belong.
2891 /// \p BlockFilter - Set of blocks that belong to the loop being laid out.
2892 ///                  Used to identify which blocks to update predecessor
2893 ///                  counts.
2894 /// \p PrevUnplacedBlockIt - Iterator pointing to the last block that was
2895 ///                          chosen in the given order due to unnatural CFG
2896 ///                          only needed if \p BB is removed and
2897 ///                          \p PrevUnplacedBlockIt pointed to \p BB.
2898 /// @return true if \p BB was removed.
2899 bool MachineBlockPlacement::repeatedlyTailDuplicateBlock(
2900     MachineBasicBlock *BB, MachineBasicBlock *&LPred,
2901     const MachineBasicBlock *LoopHeaderBB,
2902     BlockChain &Chain, BlockFilterSet *BlockFilter,
2903     MachineFunction::iterator &PrevUnplacedBlockIt) {
2904   bool Removed, DuplicatedToLPred;
2905   bool DuplicatedToOriginalLPred;
2906   Removed = maybeTailDuplicateBlock(BB, LPred, Chain, BlockFilter,
2907                                     PrevUnplacedBlockIt,
2908                                     DuplicatedToLPred);
2909   if (!Removed)
2910     return false;
2911   DuplicatedToOriginalLPred = DuplicatedToLPred;
2912   // Iteratively try to duplicate again. It can happen that a block that is
2913   // duplicated into is still small enough to be duplicated again.
2914   // No need to call markBlockSuccessors in this case, as the blocks being
2915   // duplicated from here on are already scheduled.
2916   // Note that DuplicatedToLPred always implies Removed.
2917   while (DuplicatedToLPred) {
2918     assert(Removed && "Block must have been removed to be duplicated into its "
2919            "layout predecessor.");
2920     MachineBasicBlock *DupBB, *DupPred;
2921     // The removal callback causes Chain.end() to be updated when a block is
2922     // removed. On the first pass through the loop, the chain end should be the
2923     // same as it was on function entry. On subsequent passes, because we are
2924     // duplicating the block at the end of the chain, if it is removed the
2925     // chain will have shrunk by one block.
2926     BlockChain::iterator ChainEnd = Chain.end();
2927     DupBB = *(--ChainEnd);
2928     // Now try to duplicate again.
2929     if (ChainEnd == Chain.begin())
2930       break;
2931     DupPred = *std::prev(ChainEnd);
2932     Removed = maybeTailDuplicateBlock(DupBB, DupPred, Chain, BlockFilter,
2933                                       PrevUnplacedBlockIt,
2934                                       DuplicatedToLPred);
2935   }
2936   // If BB was duplicated into LPred, it is now scheduled. But because it was
2937   // removed, markChainSuccessors won't be called for its chain. Instead we
2938   // call markBlockSuccessors for LPred to achieve the same effect. This must go
2939   // at the end because repeating the tail duplication can increase the number
2940   // of unscheduled predecessors.
2941   LPred = *std::prev(Chain.end());
2942   if (DuplicatedToOriginalLPred)
2943     markBlockSuccessors(Chain, LPred, LoopHeaderBB, BlockFilter);
2944   return true;
2945 }
2946 
2947 /// Tail duplicate \p BB into (some) predecessors if profitable.
2948 /// \p BB    - Basic block that may be duplicated
2949 /// \p LPred - Chosen layout predecessor of \p BB
2950 /// \p Chain - Chain to which \p LPred belongs, and \p BB will belong.
2951 /// \p BlockFilter - Set of blocks that belong to the loop being laid out.
2952 ///                  Used to identify which blocks to update predecessor
2953 ///                  counts.
2954 /// \p PrevUnplacedBlockIt - Iterator pointing to the last block that was
2955 ///                          chosen in the given order due to unnatural CFG
2956 ///                          only needed if \p BB is removed and
2957 ///                          \p PrevUnplacedBlockIt pointed to \p BB.
2958 /// \p DuplicatedToLPred - True if the block was duplicated into LPred. Will
2959 ///                        only be true if the block was removed.
2960 /// \return  - True if the block was duplicated into all preds and removed.
2961 bool MachineBlockPlacement::maybeTailDuplicateBlock(
2962     MachineBasicBlock *BB, MachineBasicBlock *LPred,
2963     BlockChain &Chain, BlockFilterSet *BlockFilter,
2964     MachineFunction::iterator &PrevUnplacedBlockIt,
2965     bool &DuplicatedToLPred) {
2966   DuplicatedToLPred = false;
2967   if (!shouldTailDuplicate(BB))
2968     return false;
2969 
2970   LLVM_DEBUG(dbgs() << "Redoing tail duplication for Succ#" << BB->getNumber()
2971                     << "\n");
2972 
2973   // This has to be a callback because none of it can be done after
2974   // BB is deleted.
2975   bool Removed = false;
2976   auto RemovalCallback =
2977       [&](MachineBasicBlock *RemBB) {
2978         // Signal to outer function
2979         Removed = true;
2980 
2981         // Conservative default.
2982         bool InWorkList = true;
2983         // Remove from the Chain and Chain Map
2984         if (BlockToChain.count(RemBB)) {
2985           BlockChain *Chain = BlockToChain[RemBB];
2986           InWorkList = Chain->UnscheduledPredecessors == 0;
2987           Chain->remove(RemBB);
2988           BlockToChain.erase(RemBB);
2989         }
2990 
2991         // Handle the unplaced block iterator
2992         if (&(*PrevUnplacedBlockIt) == RemBB) {
2993           PrevUnplacedBlockIt++;
2994         }
2995 
2996         // Handle the Work Lists
2997         if (InWorkList) {
2998           SmallVectorImpl<MachineBasicBlock *> &RemoveList = BlockWorkList;
2999           if (RemBB->isEHPad())
3000             RemoveList = EHPadWorkList;
3001           RemoveList.erase(
3002               llvm::remove_if(RemoveList,
3003                               [RemBB](MachineBasicBlock *BB) {
3004                                 return BB == RemBB;
3005                               }),
3006               RemoveList.end());
3007         }
3008 
3009         // Handle the filter set
3010         if (BlockFilter) {
3011           BlockFilter->remove(RemBB);
3012         }
3013 
3014         // Remove the block from loop info.
3015         MLI->removeBlock(RemBB);
3016         if (RemBB == PreferredLoopExit)
3017           PreferredLoopExit = nullptr;
3018 
3019         LLVM_DEBUG(dbgs() << "TailDuplicator deleted block: "
3020                           << getBlockName(RemBB) << "\n");
3021       };
3022   auto RemovalCallbackRef =
3023       function_ref<void(MachineBasicBlock*)>(RemovalCallback);
3024 
3025   SmallVector<MachineBasicBlock *, 8> DuplicatedPreds;
3026   bool IsSimple = TailDup.isSimpleBB(BB);
3027   TailDup.tailDuplicateAndUpdate(IsSimple, BB, LPred,
3028                                  &DuplicatedPreds, &RemovalCallbackRef);
3029 
3030   // Update UnscheduledPredecessors to reflect tail-duplication.
3031   DuplicatedToLPred = false;
3032   for (MachineBasicBlock *Pred : DuplicatedPreds) {
3033     // We're only looking for unscheduled predecessors that match the filter.
3034     BlockChain* PredChain = BlockToChain[Pred];
3035     if (Pred == LPred)
3036       DuplicatedToLPred = true;
3037     if (Pred == LPred || (BlockFilter && !BlockFilter->count(Pred))
3038         || PredChain == &Chain)
3039       continue;
3040     for (MachineBasicBlock *NewSucc : Pred->successors()) {
3041       if (BlockFilter && !BlockFilter->count(NewSucc))
3042         continue;
3043       BlockChain *NewChain = BlockToChain[NewSucc];
3044       if (NewChain != &Chain && NewChain != PredChain)
3045         NewChain->UnscheduledPredecessors++;
3046     }
3047   }
3048   return Removed;
3049 }
3050 
3051 bool MachineBlockPlacement::runOnMachineFunction(MachineFunction &MF) {
3052   if (skipFunction(MF.getFunction()))
3053     return false;
3054 
3055   // Check for single-block functions and skip them.
3056   if (std::next(MF.begin()) == MF.end())
3057     return false;
3058 
3059   F = &MF;
3060   MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
3061   MBFI = llvm::make_unique<BranchFolder::MBFIWrapper>(
3062       getAnalysis<MachineBlockFrequencyInfo>());
3063   MLI = &getAnalysis<MachineLoopInfo>();
3064   TII = MF.getSubtarget().getInstrInfo();
3065   TLI = MF.getSubtarget().getTargetLowering();
3066   MPDT = nullptr;
3067 
3068   // Initialize PreferredLoopExit to nullptr here since it may never be set if
3069   // there are no MachineLoops.
3070   PreferredLoopExit = nullptr;
3071 
3072   assert(BlockToChain.empty() &&
3073          "BlockToChain map should be empty before starting placement.");
3074   assert(ComputedEdges.empty() &&
3075          "Computed Edge map should be empty before starting placement.");
3076 
3077   unsigned TailDupSize = TailDupPlacementThreshold;
3078   // If only the aggressive threshold is explicitly set, use it.
3079   if (TailDupPlacementAggressiveThreshold.getNumOccurrences() != 0 &&
3080       TailDupPlacementThreshold.getNumOccurrences() == 0)
3081     TailDupSize = TailDupPlacementAggressiveThreshold;
3082 
3083   TargetPassConfig *PassConfig = &getAnalysis<TargetPassConfig>();
3084   // For aggressive optimization, we can adjust some thresholds to be less
3085   // conservative.
3086   if (PassConfig->getOptLevel() >= CodeGenOpt::Aggressive) {
3087     // At O3 we should be more willing to copy blocks for tail duplication. This
3088     // increases size pressure, so we only do it at O3
3089     // Do this unless only the regular threshold is explicitly set.
3090     if (TailDupPlacementThreshold.getNumOccurrences() == 0 ||
3091         TailDupPlacementAggressiveThreshold.getNumOccurrences() != 0)
3092       TailDupSize = TailDupPlacementAggressiveThreshold;
3093   }
3094 
3095   if (allowTailDupPlacement()) {
3096     MPDT = &getAnalysis<MachinePostDominatorTree>();
3097     if (MF.getFunction().hasOptSize())
3098       TailDupSize = 1;
3099     bool PreRegAlloc = false;
3100     TailDup.initMF(MF, PreRegAlloc, MBPI, /* LayoutMode */ true, TailDupSize);
3101     precomputeTriangleChains();
3102   }
3103 
3104   buildCFGChains();
3105 
3106   // Changing the layout can create new tail merging opportunities.
3107   // TailMerge can create jump into if branches that make CFG irreducible for
3108   // HW that requires structured CFG.
3109   bool EnableTailMerge = !MF.getTarget().requiresStructuredCFG() &&
3110                          PassConfig->getEnableTailMerge() &&
3111                          BranchFoldPlacement;
3112   // No tail merging opportunities if the block number is less than four.
3113   if (MF.size() > 3 && EnableTailMerge) {
3114     unsigned TailMergeSize = TailDupSize + 1;
3115     BranchFolder BF(/*EnableTailMerge=*/true, /*CommonHoist=*/false, *MBFI,
3116                     *MBPI, TailMergeSize);
3117 
3118     if (BF.OptimizeFunction(MF, TII, MF.getSubtarget().getRegisterInfo(),
3119                             getAnalysisIfAvailable<MachineModuleInfo>(), MLI,
3120                             /*AfterPlacement=*/true)) {
3121       // Redo the layout if tail merging creates/removes/moves blocks.
3122       BlockToChain.clear();
3123       ComputedEdges.clear();
3124       // Must redo the post-dominator tree if blocks were changed.
3125       if (MPDT)
3126         MPDT->runOnMachineFunction(MF);
3127       ChainAllocator.DestroyAll();
3128       buildCFGChains();
3129     }
3130   }
3131 
3132   // optimizeBranches() may change the blocks, but we haven't updated the
3133   // post-dominator tree. Because the post-dominator tree won't be used after
3134   // this function and this pass don't preserve the post-dominator tree.
3135   optimizeBranches();
3136   alignBlocks();
3137 
3138   BlockToChain.clear();
3139   ComputedEdges.clear();
3140   ChainAllocator.DestroyAll();
3141 
3142   if (AlignAllBlock)
3143     // Align all of the blocks in the function to a specific alignment.
3144     for (MachineBasicBlock &MBB : MF)
3145       MBB.setAlignment(AlignAllBlock);
3146   else if (AlignAllNonFallThruBlocks) {
3147     // Align all of the blocks that have no fall-through predecessors to a
3148     // specific alignment.
3149     for (auto MBI = std::next(MF.begin()), MBE = MF.end(); MBI != MBE; ++MBI) {
3150       auto LayoutPred = std::prev(MBI);
3151       if (!LayoutPred->isSuccessor(&*MBI))
3152         MBI->setAlignment(AlignAllNonFallThruBlocks);
3153     }
3154   }
3155   if (ViewBlockLayoutWithBFI != GVDT_None &&
3156       (ViewBlockFreqFuncName.empty() ||
3157        F->getFunction().getName().equals(ViewBlockFreqFuncName))) {
3158     MBFI->view("MBP." + MF.getName(), false);
3159   }
3160 
3161 
3162   // We always return true as we have no way to track whether the final order
3163   // differs from the original order.
3164   return true;
3165 }
3166 
3167 namespace {
3168 
3169 /// A pass to compute block placement statistics.
3170 ///
3171 /// A separate pass to compute interesting statistics for evaluating block
3172 /// placement. This is separate from the actual placement pass so that they can
3173 /// be computed in the absence of any placement transformations or when using
3174 /// alternative placement strategies.
3175 class MachineBlockPlacementStats : public MachineFunctionPass {
3176   /// A handle to the branch probability pass.
3177   const MachineBranchProbabilityInfo *MBPI;
3178 
3179   /// A handle to the function-wide block frequency pass.
3180   const MachineBlockFrequencyInfo *MBFI;
3181 
3182 public:
3183   static char ID; // Pass identification, replacement for typeid
3184 
3185   MachineBlockPlacementStats() : MachineFunctionPass(ID) {
3186     initializeMachineBlockPlacementStatsPass(*PassRegistry::getPassRegistry());
3187   }
3188 
3189   bool runOnMachineFunction(MachineFunction &F) override;
3190 
3191   void getAnalysisUsage(AnalysisUsage &AU) const override {
3192     AU.addRequired<MachineBranchProbabilityInfo>();
3193     AU.addRequired<MachineBlockFrequencyInfo>();
3194     AU.setPreservesAll();
3195     MachineFunctionPass::getAnalysisUsage(AU);
3196   }
3197 };
3198 
3199 } // end anonymous namespace
3200 
3201 char MachineBlockPlacementStats::ID = 0;
3202 
3203 char &llvm::MachineBlockPlacementStatsID = MachineBlockPlacementStats::ID;
3204 
3205 INITIALIZE_PASS_BEGIN(MachineBlockPlacementStats, "block-placement-stats",
3206                       "Basic Block Placement Stats", false, false)
3207 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
3208 INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
3209 INITIALIZE_PASS_END(MachineBlockPlacementStats, "block-placement-stats",
3210                     "Basic Block Placement Stats", false, false)
3211 
3212 bool MachineBlockPlacementStats::runOnMachineFunction(MachineFunction &F) {
3213   // Check for single-block functions and skip them.
3214   if (std::next(F.begin()) == F.end())
3215     return false;
3216 
3217   MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
3218   MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
3219 
3220   for (MachineBasicBlock &MBB : F) {
3221     BlockFrequency BlockFreq = MBFI->getBlockFreq(&MBB);
3222     Statistic &NumBranches =
3223         (MBB.succ_size() > 1) ? NumCondBranches : NumUncondBranches;
3224     Statistic &BranchTakenFreq =
3225         (MBB.succ_size() > 1) ? CondBranchTakenFreq : UncondBranchTakenFreq;
3226     for (MachineBasicBlock *Succ : MBB.successors()) {
3227       // Skip if this successor is a fallthrough.
3228       if (MBB.isLayoutSuccessor(Succ))
3229         continue;
3230 
3231       BlockFrequency EdgeFreq =
3232           BlockFreq * MBPI->getEdgeProbability(&MBB, Succ);
3233       ++NumBranches;
3234       BranchTakenFreq += EdgeFreq.getFrequency();
3235     }
3236   }
3237 
3238   return false;
3239 }
3240