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