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