xref: /freebsd/contrib/llvm-project/llvm/lib/CodeGen/MachineBlockPlacement.cpp (revision e8d8bef961a50d4dc22501cde4fb9fb0be1b2532)
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   llvm::erase_if(WorkList, [&](MachineBasicBlock *BB) {
1677     return BlockToChain.lookup(BB) == &Chain;
1678   });
1679 
1680   if (WorkList.empty())
1681     return nullptr;
1682 
1683   bool IsEHPad = WorkList[0]->isEHPad();
1684 
1685   MachineBasicBlock *BestBlock = nullptr;
1686   BlockFrequency BestFreq;
1687   for (MachineBasicBlock *MBB : WorkList) {
1688     assert(MBB->isEHPad() == IsEHPad &&
1689            "EHPad mismatch between block and work list.");
1690 
1691     BlockChain &SuccChain = *BlockToChain[MBB];
1692     if (&SuccChain == &Chain)
1693       continue;
1694 
1695     assert(SuccChain.UnscheduledPredecessors == 0 &&
1696            "Found CFG-violating block");
1697 
1698     BlockFrequency CandidateFreq = MBFI->getBlockFreq(MBB);
1699     LLVM_DEBUG(dbgs() << "    " << getBlockName(MBB) << " -> ";
1700                MBFI->printBlockFreq(dbgs(), CandidateFreq) << " (freq)\n");
1701 
1702     // For ehpad, we layout the least probable first as to avoid jumping back
1703     // from least probable landingpads to more probable ones.
1704     //
1705     // FIXME: Using probability is probably (!) not the best way to achieve
1706     // this. We should probably have a more principled approach to layout
1707     // cleanup code.
1708     //
1709     // The goal is to get:
1710     //
1711     //                 +--------------------------+
1712     //                 |                          V
1713     // InnerLp -> InnerCleanup    OuterLp -> OuterCleanup -> Resume
1714     //
1715     // Rather than:
1716     //
1717     //                 +-------------------------------------+
1718     //                 V                                     |
1719     // OuterLp -> OuterCleanup -> Resume     InnerLp -> InnerCleanup
1720     if (BestBlock && (IsEHPad ^ (BestFreq >= CandidateFreq)))
1721       continue;
1722 
1723     BestBlock = MBB;
1724     BestFreq = CandidateFreq;
1725   }
1726 
1727   return BestBlock;
1728 }
1729 
1730 /// Retrieve the first unplaced basic block.
1731 ///
1732 /// This routine is called when we are unable to use the CFG to walk through
1733 /// all of the basic blocks and form a chain due to unnatural loops in the CFG.
1734 /// We walk through the function's blocks in order, starting from the
1735 /// LastUnplacedBlockIt. We update this iterator on each call to avoid
1736 /// re-scanning the entire sequence on repeated calls to this routine.
1737 MachineBasicBlock *MachineBlockPlacement::getFirstUnplacedBlock(
1738     const BlockChain &PlacedChain,
1739     MachineFunction::iterator &PrevUnplacedBlockIt,
1740     const BlockFilterSet *BlockFilter) {
1741   for (MachineFunction::iterator I = PrevUnplacedBlockIt, E = F->end(); I != E;
1742        ++I) {
1743     if (BlockFilter && !BlockFilter->count(&*I))
1744       continue;
1745     if (BlockToChain[&*I] != &PlacedChain) {
1746       PrevUnplacedBlockIt = I;
1747       // Now select the head of the chain to which the unplaced block belongs
1748       // as the block to place. This will force the entire chain to be placed,
1749       // and satisfies the requirements of merging chains.
1750       return *BlockToChain[&*I]->begin();
1751     }
1752   }
1753   return nullptr;
1754 }
1755 
1756 void MachineBlockPlacement::fillWorkLists(
1757     const MachineBasicBlock *MBB,
1758     SmallPtrSetImpl<BlockChain *> &UpdatedPreds,
1759     const BlockFilterSet *BlockFilter = nullptr) {
1760   BlockChain &Chain = *BlockToChain[MBB];
1761   if (!UpdatedPreds.insert(&Chain).second)
1762     return;
1763 
1764   assert(
1765       Chain.UnscheduledPredecessors == 0 &&
1766       "Attempting to place block with unscheduled predecessors in worklist.");
1767   for (MachineBasicBlock *ChainBB : Chain) {
1768     assert(BlockToChain[ChainBB] == &Chain &&
1769            "Block in chain doesn't match BlockToChain map.");
1770     for (MachineBasicBlock *Pred : ChainBB->predecessors()) {
1771       if (BlockFilter && !BlockFilter->count(Pred))
1772         continue;
1773       if (BlockToChain[Pred] == &Chain)
1774         continue;
1775       ++Chain.UnscheduledPredecessors;
1776     }
1777   }
1778 
1779   if (Chain.UnscheduledPredecessors != 0)
1780     return;
1781 
1782   MachineBasicBlock *BB = *Chain.begin();
1783   if (BB->isEHPad())
1784     EHPadWorkList.push_back(BB);
1785   else
1786     BlockWorkList.push_back(BB);
1787 }
1788 
1789 void MachineBlockPlacement::buildChain(
1790     const MachineBasicBlock *HeadBB, BlockChain &Chain,
1791     BlockFilterSet *BlockFilter) {
1792   assert(HeadBB && "BB must not be null.\n");
1793   assert(BlockToChain[HeadBB] == &Chain && "BlockToChainMap mis-match.\n");
1794   MachineFunction::iterator PrevUnplacedBlockIt = F->begin();
1795 
1796   const MachineBasicBlock *LoopHeaderBB = HeadBB;
1797   markChainSuccessors(Chain, LoopHeaderBB, BlockFilter);
1798   MachineBasicBlock *BB = *std::prev(Chain.end());
1799   while (true) {
1800     assert(BB && "null block found at end of chain in loop.");
1801     assert(BlockToChain[BB] == &Chain && "BlockToChainMap mis-match in loop.");
1802     assert(*std::prev(Chain.end()) == BB && "BB Not found at end of chain.");
1803 
1804 
1805     // Look for the best viable successor if there is one to place immediately
1806     // after this block.
1807     auto Result = selectBestSuccessor(BB, Chain, BlockFilter);
1808     MachineBasicBlock* BestSucc = Result.BB;
1809     bool ShouldTailDup = Result.ShouldTailDup;
1810     if (allowTailDupPlacement())
1811       ShouldTailDup |= (BestSucc && canTailDuplicateUnplacedPreds(BB, BestSucc,
1812                                                                   Chain,
1813                                                                   BlockFilter));
1814 
1815     // If an immediate successor isn't available, look for the best viable
1816     // block among those we've identified as not violating the loop's CFG at
1817     // this point. This won't be a fallthrough, but it will increase locality.
1818     if (!BestSucc)
1819       BestSucc = selectBestCandidateBlock(Chain, BlockWorkList);
1820     if (!BestSucc)
1821       BestSucc = selectBestCandidateBlock(Chain, EHPadWorkList);
1822 
1823     if (!BestSucc) {
1824       BestSucc = getFirstUnplacedBlock(Chain, PrevUnplacedBlockIt, BlockFilter);
1825       if (!BestSucc)
1826         break;
1827 
1828       LLVM_DEBUG(dbgs() << "Unnatural loop CFG detected, forcibly merging the "
1829                            "layout successor until the CFG reduces\n");
1830     }
1831 
1832     // Placement may have changed tail duplication opportunities.
1833     // Check for that now.
1834     if (allowTailDupPlacement() && BestSucc && ShouldTailDup) {
1835       repeatedlyTailDuplicateBlock(BestSucc, BB, LoopHeaderBB, Chain,
1836                                        BlockFilter, PrevUnplacedBlockIt);
1837       // If the chosen successor was duplicated into BB, don't bother laying
1838       // it out, just go round the loop again with BB as the chain end.
1839       if (!BB->isSuccessor(BestSucc))
1840         continue;
1841     }
1842 
1843     // Place this block, updating the datastructures to reflect its placement.
1844     BlockChain &SuccChain = *BlockToChain[BestSucc];
1845     // Zero out UnscheduledPredecessors for the successor we're about to merge in case
1846     // we selected a successor that didn't fit naturally into the CFG.
1847     SuccChain.UnscheduledPredecessors = 0;
1848     LLVM_DEBUG(dbgs() << "Merging from " << getBlockName(BB) << " to "
1849                       << getBlockName(BestSucc) << "\n");
1850     markChainSuccessors(SuccChain, LoopHeaderBB, BlockFilter);
1851     Chain.merge(BestSucc, &SuccChain);
1852     BB = *std::prev(Chain.end());
1853   }
1854 
1855   LLVM_DEBUG(dbgs() << "Finished forming chain for header block "
1856                     << getBlockName(*Chain.begin()) << "\n");
1857 }
1858 
1859 // If bottom of block BB has only one successor OldTop, in most cases it is
1860 // profitable to move it before OldTop, except the following case:
1861 //
1862 //     -->OldTop<-
1863 //     |    .    |
1864 //     |    .    |
1865 //     |    .    |
1866 //     ---Pred   |
1867 //          |    |
1868 //         BB-----
1869 //
1870 // If BB is moved before OldTop, Pred needs a taken branch to BB, and it can't
1871 // layout the other successor below it, so it can't reduce taken branch.
1872 // In this case we keep its original layout.
1873 bool
1874 MachineBlockPlacement::canMoveBottomBlockToTop(
1875     const MachineBasicBlock *BottomBlock,
1876     const MachineBasicBlock *OldTop) {
1877   if (BottomBlock->pred_size() != 1)
1878     return true;
1879   MachineBasicBlock *Pred = *BottomBlock->pred_begin();
1880   if (Pred->succ_size() != 2)
1881     return true;
1882 
1883   MachineBasicBlock *OtherBB = *Pred->succ_begin();
1884   if (OtherBB == BottomBlock)
1885     OtherBB = *Pred->succ_rbegin();
1886   if (OtherBB == OldTop)
1887     return false;
1888 
1889   return true;
1890 }
1891 
1892 // Find out the possible fall through frequence to the top of a loop.
1893 BlockFrequency
1894 MachineBlockPlacement::TopFallThroughFreq(
1895     const MachineBasicBlock *Top,
1896     const BlockFilterSet &LoopBlockSet) {
1897   BlockFrequency MaxFreq = 0;
1898   for (MachineBasicBlock *Pred : Top->predecessors()) {
1899     BlockChain *PredChain = BlockToChain[Pred];
1900     if (!LoopBlockSet.count(Pred) &&
1901         (!PredChain || Pred == *std::prev(PredChain->end()))) {
1902       // Found a Pred block can be placed before Top.
1903       // Check if Top is the best successor of Pred.
1904       auto TopProb = MBPI->getEdgeProbability(Pred, Top);
1905       bool TopOK = true;
1906       for (MachineBasicBlock *Succ : Pred->successors()) {
1907         auto SuccProb = MBPI->getEdgeProbability(Pred, Succ);
1908         BlockChain *SuccChain = BlockToChain[Succ];
1909         // Check if Succ can be placed after Pred.
1910         // Succ should not be in any chain, or it is the head of some chain.
1911         if (!LoopBlockSet.count(Succ) && (SuccProb > TopProb) &&
1912             (!SuccChain || Succ == *SuccChain->begin())) {
1913           TopOK = false;
1914           break;
1915         }
1916       }
1917       if (TopOK) {
1918         BlockFrequency EdgeFreq = MBFI->getBlockFreq(Pred) *
1919                                   MBPI->getEdgeProbability(Pred, Top);
1920         if (EdgeFreq > MaxFreq)
1921           MaxFreq = EdgeFreq;
1922       }
1923     }
1924   }
1925   return MaxFreq;
1926 }
1927 
1928 // Compute the fall through gains when move NewTop before OldTop.
1929 //
1930 // In following diagram, edges marked as "-" are reduced fallthrough, edges
1931 // marked as "+" are increased fallthrough, this function computes
1932 //
1933 //      SUM(increased fallthrough) - SUM(decreased fallthrough)
1934 //
1935 //              |
1936 //              | -
1937 //              V
1938 //        --->OldTop
1939 //        |     .
1940 //        |     .
1941 //       +|     .    +
1942 //        |   Pred --->
1943 //        |     |-
1944 //        |     V
1945 //        --- NewTop <---
1946 //              |-
1947 //              V
1948 //
1949 BlockFrequency
1950 MachineBlockPlacement::FallThroughGains(
1951     const MachineBasicBlock *NewTop,
1952     const MachineBasicBlock *OldTop,
1953     const MachineBasicBlock *ExitBB,
1954     const BlockFilterSet &LoopBlockSet) {
1955   BlockFrequency FallThrough2Top = TopFallThroughFreq(OldTop, LoopBlockSet);
1956   BlockFrequency FallThrough2Exit = 0;
1957   if (ExitBB)
1958     FallThrough2Exit = MBFI->getBlockFreq(NewTop) *
1959         MBPI->getEdgeProbability(NewTop, ExitBB);
1960   BlockFrequency BackEdgeFreq = MBFI->getBlockFreq(NewTop) *
1961       MBPI->getEdgeProbability(NewTop, OldTop);
1962 
1963   // Find the best Pred of NewTop.
1964    MachineBasicBlock *BestPred = nullptr;
1965    BlockFrequency FallThroughFromPred = 0;
1966    for (MachineBasicBlock *Pred : NewTop->predecessors()) {
1967      if (!LoopBlockSet.count(Pred))
1968        continue;
1969      BlockChain *PredChain = BlockToChain[Pred];
1970      if (!PredChain || Pred == *std::prev(PredChain->end())) {
1971        BlockFrequency EdgeFreq = MBFI->getBlockFreq(Pred) *
1972            MBPI->getEdgeProbability(Pred, NewTop);
1973        if (EdgeFreq > FallThroughFromPred) {
1974          FallThroughFromPred = EdgeFreq;
1975          BestPred = Pred;
1976        }
1977      }
1978    }
1979 
1980    // If NewTop is not placed after Pred, another successor can be placed
1981    // after Pred.
1982    BlockFrequency NewFreq = 0;
1983    if (BestPred) {
1984      for (MachineBasicBlock *Succ : BestPred->successors()) {
1985        if ((Succ == NewTop) || (Succ == BestPred) || !LoopBlockSet.count(Succ))
1986          continue;
1987        if (ComputedEdges.find(Succ) != ComputedEdges.end())
1988          continue;
1989        BlockChain *SuccChain = BlockToChain[Succ];
1990        if ((SuccChain && (Succ != *SuccChain->begin())) ||
1991            (SuccChain == BlockToChain[BestPred]))
1992          continue;
1993        BlockFrequency EdgeFreq = MBFI->getBlockFreq(BestPred) *
1994            MBPI->getEdgeProbability(BestPred, Succ);
1995        if (EdgeFreq > NewFreq)
1996          NewFreq = EdgeFreq;
1997      }
1998      BlockFrequency OrigEdgeFreq = MBFI->getBlockFreq(BestPred) *
1999          MBPI->getEdgeProbability(BestPred, NewTop);
2000      if (NewFreq > OrigEdgeFreq) {
2001        // If NewTop is not the best successor of Pred, then Pred doesn't
2002        // fallthrough to NewTop. So there is no FallThroughFromPred and
2003        // NewFreq.
2004        NewFreq = 0;
2005        FallThroughFromPred = 0;
2006      }
2007    }
2008 
2009    BlockFrequency Result = 0;
2010    BlockFrequency Gains = BackEdgeFreq + NewFreq;
2011    BlockFrequency Lost = FallThrough2Top + FallThrough2Exit +
2012        FallThroughFromPred;
2013    if (Gains > Lost)
2014      Result = Gains - Lost;
2015    return Result;
2016 }
2017 
2018 /// Helper function of findBestLoopTop. Find the best loop top block
2019 /// from predecessors of old top.
2020 ///
2021 /// Look for a block which is strictly better than the old top for laying
2022 /// out before the old top of the loop. This looks for only two patterns:
2023 ///
2024 ///     1. a block has only one successor, the old loop top
2025 ///
2026 ///        Because such a block will always result in an unconditional jump,
2027 ///        rotating it in front of the old top is always profitable.
2028 ///
2029 ///     2. a block has two successors, one is old top, another is exit
2030 ///        and it has more than one predecessors
2031 ///
2032 ///        If it is below one of its predecessors P, only P can fall through to
2033 ///        it, all other predecessors need a jump to it, and another conditional
2034 ///        jump to loop header. If it is moved before loop header, all its
2035 ///        predecessors jump to it, then fall through to loop header. So all its
2036 ///        predecessors except P can reduce one taken branch.
2037 ///        At the same time, move it before old top increases the taken branch
2038 ///        to loop exit block, so the reduced taken branch will be compared with
2039 ///        the increased taken branch to the loop exit block.
2040 MachineBasicBlock *
2041 MachineBlockPlacement::findBestLoopTopHelper(
2042     MachineBasicBlock *OldTop,
2043     const MachineLoop &L,
2044     const BlockFilterSet &LoopBlockSet) {
2045   // Check that the header hasn't been fused with a preheader block due to
2046   // crazy branches. If it has, we need to start with the header at the top to
2047   // prevent pulling the preheader into the loop body.
2048   BlockChain &HeaderChain = *BlockToChain[OldTop];
2049   if (!LoopBlockSet.count(*HeaderChain.begin()))
2050     return OldTop;
2051 
2052   LLVM_DEBUG(dbgs() << "Finding best loop top for: " << getBlockName(OldTop)
2053                     << "\n");
2054 
2055   BlockFrequency BestGains = 0;
2056   MachineBasicBlock *BestPred = nullptr;
2057   for (MachineBasicBlock *Pred : OldTop->predecessors()) {
2058     if (!LoopBlockSet.count(Pred))
2059       continue;
2060     if (Pred == L.getHeader())
2061       continue;
2062     LLVM_DEBUG(dbgs() << "   old top pred: " << getBlockName(Pred) << ", has "
2063                       << Pred->succ_size() << " successors, ";
2064                MBFI->printBlockFreq(dbgs(), Pred) << " freq\n");
2065     if (Pred->succ_size() > 2)
2066       continue;
2067 
2068     MachineBasicBlock *OtherBB = nullptr;
2069     if (Pred->succ_size() == 2) {
2070       OtherBB = *Pred->succ_begin();
2071       if (OtherBB == OldTop)
2072         OtherBB = *Pred->succ_rbegin();
2073     }
2074 
2075     if (!canMoveBottomBlockToTop(Pred, OldTop))
2076       continue;
2077 
2078     BlockFrequency Gains = FallThroughGains(Pred, OldTop, OtherBB,
2079                                             LoopBlockSet);
2080     if ((Gains > 0) && (Gains > BestGains ||
2081         ((Gains == BestGains) && Pred->isLayoutSuccessor(OldTop)))) {
2082       BestPred = Pred;
2083       BestGains = Gains;
2084     }
2085   }
2086 
2087   // If no direct predecessor is fine, just use the loop header.
2088   if (!BestPred) {
2089     LLVM_DEBUG(dbgs() << "    final top unchanged\n");
2090     return OldTop;
2091   }
2092 
2093   // Walk backwards through any straight line of predecessors.
2094   while (BestPred->pred_size() == 1 &&
2095          (*BestPred->pred_begin())->succ_size() == 1 &&
2096          *BestPred->pred_begin() != L.getHeader())
2097     BestPred = *BestPred->pred_begin();
2098 
2099   LLVM_DEBUG(dbgs() << "    final top: " << getBlockName(BestPred) << "\n");
2100   return BestPred;
2101 }
2102 
2103 /// Find the best loop top block for layout.
2104 ///
2105 /// This function iteratively calls findBestLoopTopHelper, until no new better
2106 /// BB can be found.
2107 MachineBasicBlock *
2108 MachineBlockPlacement::findBestLoopTop(const MachineLoop &L,
2109                                        const BlockFilterSet &LoopBlockSet) {
2110   // Placing the latch block before the header may introduce an extra branch
2111   // that skips this block the first time the loop is executed, which we want
2112   // to avoid when optimising for size.
2113   // FIXME: in theory there is a case that does not introduce a new branch,
2114   // i.e. when the layout predecessor does not fallthrough to the loop header.
2115   // In practice this never happens though: there always seems to be a preheader
2116   // that can fallthrough and that is also placed before the header.
2117   bool OptForSize = F->getFunction().hasOptSize() ||
2118                     llvm::shouldOptimizeForSize(L.getHeader(), PSI, MBFI.get());
2119   if (OptForSize)
2120     return L.getHeader();
2121 
2122   MachineBasicBlock *OldTop = nullptr;
2123   MachineBasicBlock *NewTop = L.getHeader();
2124   while (NewTop != OldTop) {
2125     OldTop = NewTop;
2126     NewTop = findBestLoopTopHelper(OldTop, L, LoopBlockSet);
2127     if (NewTop != OldTop)
2128       ComputedEdges[NewTop] = { OldTop, false };
2129   }
2130   return NewTop;
2131 }
2132 
2133 /// Find the best loop exiting block for layout.
2134 ///
2135 /// This routine implements the logic to analyze the loop looking for the best
2136 /// block to layout at the top of the loop. Typically this is done to maximize
2137 /// fallthrough opportunities.
2138 MachineBasicBlock *
2139 MachineBlockPlacement::findBestLoopExit(const MachineLoop &L,
2140                                         const BlockFilterSet &LoopBlockSet,
2141                                         BlockFrequency &ExitFreq) {
2142   // We don't want to layout the loop linearly in all cases. If the loop header
2143   // is just a normal basic block in the loop, we want to look for what block
2144   // within the loop is the best one to layout at the top. However, if the loop
2145   // header has be pre-merged into a chain due to predecessors not having
2146   // analyzable branches, *and* the predecessor it is merged with is *not* part
2147   // of the loop, rotating the header into the middle of the loop will create
2148   // a non-contiguous range of blocks which is Very Bad. So start with the
2149   // header and only rotate if safe.
2150   BlockChain &HeaderChain = *BlockToChain[L.getHeader()];
2151   if (!LoopBlockSet.count(*HeaderChain.begin()))
2152     return nullptr;
2153 
2154   BlockFrequency BestExitEdgeFreq;
2155   unsigned BestExitLoopDepth = 0;
2156   MachineBasicBlock *ExitingBB = nullptr;
2157   // If there are exits to outer loops, loop rotation can severely limit
2158   // fallthrough opportunities unless it selects such an exit. Keep a set of
2159   // blocks where rotating to exit with that block will reach an outer loop.
2160   SmallPtrSet<MachineBasicBlock *, 4> BlocksExitingToOuterLoop;
2161 
2162   LLVM_DEBUG(dbgs() << "Finding best loop exit for: "
2163                     << getBlockName(L.getHeader()) << "\n");
2164   for (MachineBasicBlock *MBB : L.getBlocks()) {
2165     BlockChain &Chain = *BlockToChain[MBB];
2166     // Ensure that this block is at the end of a chain; otherwise it could be
2167     // mid-way through an inner loop or a successor of an unanalyzable branch.
2168     if (MBB != *std::prev(Chain.end()))
2169       continue;
2170 
2171     // Now walk the successors. We need to establish whether this has a viable
2172     // exiting successor and whether it has a viable non-exiting successor.
2173     // We store the old exiting state and restore it if a viable looping
2174     // successor isn't found.
2175     MachineBasicBlock *OldExitingBB = ExitingBB;
2176     BlockFrequency OldBestExitEdgeFreq = BestExitEdgeFreq;
2177     bool HasLoopingSucc = false;
2178     for (MachineBasicBlock *Succ : MBB->successors()) {
2179       if (Succ->isEHPad())
2180         continue;
2181       if (Succ == MBB)
2182         continue;
2183       BlockChain &SuccChain = *BlockToChain[Succ];
2184       // Don't split chains, either this chain or the successor's chain.
2185       if (&Chain == &SuccChain) {
2186         LLVM_DEBUG(dbgs() << "    exiting: " << getBlockName(MBB) << " -> "
2187                           << getBlockName(Succ) << " (chain conflict)\n");
2188         continue;
2189       }
2190 
2191       auto SuccProb = MBPI->getEdgeProbability(MBB, Succ);
2192       if (LoopBlockSet.count(Succ)) {
2193         LLVM_DEBUG(dbgs() << "    looping: " << getBlockName(MBB) << " -> "
2194                           << getBlockName(Succ) << " (" << SuccProb << ")\n");
2195         HasLoopingSucc = true;
2196         continue;
2197       }
2198 
2199       unsigned SuccLoopDepth = 0;
2200       if (MachineLoop *ExitLoop = MLI->getLoopFor(Succ)) {
2201         SuccLoopDepth = ExitLoop->getLoopDepth();
2202         if (ExitLoop->contains(&L))
2203           BlocksExitingToOuterLoop.insert(MBB);
2204       }
2205 
2206       BlockFrequency ExitEdgeFreq = MBFI->getBlockFreq(MBB) * SuccProb;
2207       LLVM_DEBUG(dbgs() << "    exiting: " << getBlockName(MBB) << " -> "
2208                         << getBlockName(Succ) << " [L:" << SuccLoopDepth
2209                         << "] (";
2210                  MBFI->printBlockFreq(dbgs(), ExitEdgeFreq) << ")\n");
2211       // Note that we bias this toward an existing layout successor to retain
2212       // incoming order in the absence of better information. The exit must have
2213       // a frequency higher than the current exit before we consider breaking
2214       // the layout.
2215       BranchProbability Bias(100 - ExitBlockBias, 100);
2216       if (!ExitingBB || SuccLoopDepth > BestExitLoopDepth ||
2217           ExitEdgeFreq > BestExitEdgeFreq ||
2218           (MBB->isLayoutSuccessor(Succ) &&
2219            !(ExitEdgeFreq < BestExitEdgeFreq * Bias))) {
2220         BestExitEdgeFreq = ExitEdgeFreq;
2221         ExitingBB = MBB;
2222       }
2223     }
2224 
2225     if (!HasLoopingSucc) {
2226       // Restore the old exiting state, no viable looping successor was found.
2227       ExitingBB = OldExitingBB;
2228       BestExitEdgeFreq = OldBestExitEdgeFreq;
2229     }
2230   }
2231   // Without a candidate exiting block or with only a single block in the
2232   // loop, just use the loop header to layout the loop.
2233   if (!ExitingBB) {
2234     LLVM_DEBUG(
2235         dbgs() << "    No other candidate exit blocks, using loop header\n");
2236     return nullptr;
2237   }
2238   if (L.getNumBlocks() == 1) {
2239     LLVM_DEBUG(dbgs() << "    Loop has 1 block, using loop header as exit\n");
2240     return nullptr;
2241   }
2242 
2243   // Also, if we have exit blocks which lead to outer loops but didn't select
2244   // one of them as the exiting block we are rotating toward, disable loop
2245   // rotation altogether.
2246   if (!BlocksExitingToOuterLoop.empty() &&
2247       !BlocksExitingToOuterLoop.count(ExitingBB))
2248     return nullptr;
2249 
2250   LLVM_DEBUG(dbgs() << "  Best exiting block: " << getBlockName(ExitingBB)
2251                     << "\n");
2252   ExitFreq = BestExitEdgeFreq;
2253   return ExitingBB;
2254 }
2255 
2256 /// Check if there is a fallthrough to loop header Top.
2257 ///
2258 ///   1. Look for a Pred that can be layout before Top.
2259 ///   2. Check if Top is the most possible successor of Pred.
2260 bool
2261 MachineBlockPlacement::hasViableTopFallthrough(
2262     const MachineBasicBlock *Top,
2263     const BlockFilterSet &LoopBlockSet) {
2264   for (MachineBasicBlock *Pred : Top->predecessors()) {
2265     BlockChain *PredChain = BlockToChain[Pred];
2266     if (!LoopBlockSet.count(Pred) &&
2267         (!PredChain || Pred == *std::prev(PredChain->end()))) {
2268       // Found a Pred block can be placed before Top.
2269       // Check if Top is the best successor of Pred.
2270       auto TopProb = MBPI->getEdgeProbability(Pred, Top);
2271       bool TopOK = true;
2272       for (MachineBasicBlock *Succ : Pred->successors()) {
2273         auto SuccProb = MBPI->getEdgeProbability(Pred, Succ);
2274         BlockChain *SuccChain = BlockToChain[Succ];
2275         // Check if Succ can be placed after Pred.
2276         // Succ should not be in any chain, or it is the head of some chain.
2277         if ((!SuccChain || Succ == *SuccChain->begin()) && SuccProb > TopProb) {
2278           TopOK = false;
2279           break;
2280         }
2281       }
2282       if (TopOK)
2283         return true;
2284     }
2285   }
2286   return false;
2287 }
2288 
2289 /// Attempt to rotate an exiting block to the bottom of the loop.
2290 ///
2291 /// Once we have built a chain, try to rotate it to line up the hot exit block
2292 /// with fallthrough out of the loop if doing so doesn't introduce unnecessary
2293 /// branches. For example, if the loop has fallthrough into its header and out
2294 /// of its bottom already, don't rotate it.
2295 void MachineBlockPlacement::rotateLoop(BlockChain &LoopChain,
2296                                        const MachineBasicBlock *ExitingBB,
2297                                        BlockFrequency ExitFreq,
2298                                        const BlockFilterSet &LoopBlockSet) {
2299   if (!ExitingBB)
2300     return;
2301 
2302   MachineBasicBlock *Top = *LoopChain.begin();
2303   MachineBasicBlock *Bottom = *std::prev(LoopChain.end());
2304 
2305   // If ExitingBB is already the last one in a chain then nothing to do.
2306   if (Bottom == ExitingBB)
2307     return;
2308 
2309   // The entry block should always be the first BB in a function.
2310   if (Top->isEntryBlock())
2311     return;
2312 
2313   bool ViableTopFallthrough = hasViableTopFallthrough(Top, LoopBlockSet);
2314 
2315   // If the header has viable fallthrough, check whether the current loop
2316   // bottom is a viable exiting block. If so, bail out as rotating will
2317   // introduce an unnecessary branch.
2318   if (ViableTopFallthrough) {
2319     for (MachineBasicBlock *Succ : Bottom->successors()) {
2320       BlockChain *SuccChain = BlockToChain[Succ];
2321       if (!LoopBlockSet.count(Succ) &&
2322           (!SuccChain || Succ == *SuccChain->begin()))
2323         return;
2324     }
2325 
2326     // Rotate will destroy the top fallthrough, we need to ensure the new exit
2327     // frequency is larger than top fallthrough.
2328     BlockFrequency FallThrough2Top = TopFallThroughFreq(Top, LoopBlockSet);
2329     if (FallThrough2Top >= ExitFreq)
2330       return;
2331   }
2332 
2333   BlockChain::iterator ExitIt = llvm::find(LoopChain, ExitingBB);
2334   if (ExitIt == LoopChain.end())
2335     return;
2336 
2337   // Rotating a loop exit to the bottom when there is a fallthrough to top
2338   // trades the entry fallthrough for an exit fallthrough.
2339   // If there is no bottom->top edge, but the chosen exit block does have
2340   // a fallthrough, we break that fallthrough for nothing in return.
2341 
2342   // Let's consider an example. We have a built chain of basic blocks
2343   // B1, B2, ..., Bn, where Bk is a ExitingBB - chosen exit block.
2344   // By doing a rotation we get
2345   // Bk+1, ..., Bn, B1, ..., Bk
2346   // Break of fallthrough to B1 is compensated by a fallthrough from Bk.
2347   // If we had a fallthrough Bk -> Bk+1 it is broken now.
2348   // It might be compensated by fallthrough Bn -> B1.
2349   // So we have a condition to avoid creation of extra branch by loop rotation.
2350   // All below must be true to avoid loop rotation:
2351   //   If there is a fallthrough to top (B1)
2352   //   There was fallthrough from chosen exit block (Bk) to next one (Bk+1)
2353   //   There is no fallthrough from bottom (Bn) to top (B1).
2354   // Please note that there is no exit fallthrough from Bn because we checked it
2355   // above.
2356   if (ViableTopFallthrough) {
2357     assert(std::next(ExitIt) != LoopChain.end() &&
2358            "Exit should not be last BB");
2359     MachineBasicBlock *NextBlockInChain = *std::next(ExitIt);
2360     if (ExitingBB->isSuccessor(NextBlockInChain))
2361       if (!Bottom->isSuccessor(Top))
2362         return;
2363   }
2364 
2365   LLVM_DEBUG(dbgs() << "Rotating loop to put exit " << getBlockName(ExitingBB)
2366                     << " at bottom\n");
2367   std::rotate(LoopChain.begin(), std::next(ExitIt), LoopChain.end());
2368 }
2369 
2370 /// Attempt to rotate a loop based on profile data to reduce branch cost.
2371 ///
2372 /// With profile data, we can determine the cost in terms of missed fall through
2373 /// opportunities when rotating a loop chain and select the best rotation.
2374 /// Basically, there are three kinds of cost to consider for each rotation:
2375 ///    1. The possibly missed fall through edge (if it exists) from BB out of
2376 ///    the loop to the loop header.
2377 ///    2. The possibly missed fall through edges (if they exist) from the loop
2378 ///    exits to BB out of the loop.
2379 ///    3. The missed fall through edge (if it exists) from the last BB to the
2380 ///    first BB in the loop chain.
2381 ///  Therefore, the cost for a given rotation is the sum of costs listed above.
2382 ///  We select the best rotation with the smallest cost.
2383 void MachineBlockPlacement::rotateLoopWithProfile(
2384     BlockChain &LoopChain, const MachineLoop &L,
2385     const BlockFilterSet &LoopBlockSet) {
2386   auto RotationPos = LoopChain.end();
2387   MachineBasicBlock *ChainHeaderBB = *LoopChain.begin();
2388 
2389   // The entry block should always be the first BB in a function.
2390   if (ChainHeaderBB->isEntryBlock())
2391     return;
2392 
2393   BlockFrequency SmallestRotationCost = BlockFrequency::getMaxFrequency();
2394 
2395   // A utility lambda that scales up a block frequency by dividing it by a
2396   // branch probability which is the reciprocal of the scale.
2397   auto ScaleBlockFrequency = [](BlockFrequency Freq,
2398                                 unsigned Scale) -> BlockFrequency {
2399     if (Scale == 0)
2400       return 0;
2401     // Use operator / between BlockFrequency and BranchProbability to implement
2402     // saturating multiplication.
2403     return Freq / BranchProbability(1, Scale);
2404   };
2405 
2406   // Compute the cost of the missed fall-through edge to the loop header if the
2407   // chain head is not the loop header. As we only consider natural loops with
2408   // single header, this computation can be done only once.
2409   BlockFrequency HeaderFallThroughCost(0);
2410   for (auto *Pred : ChainHeaderBB->predecessors()) {
2411     BlockChain *PredChain = BlockToChain[Pred];
2412     if (!LoopBlockSet.count(Pred) &&
2413         (!PredChain || Pred == *std::prev(PredChain->end()))) {
2414       auto EdgeFreq = MBFI->getBlockFreq(Pred) *
2415           MBPI->getEdgeProbability(Pred, ChainHeaderBB);
2416       auto FallThruCost = ScaleBlockFrequency(EdgeFreq, MisfetchCost);
2417       // If the predecessor has only an unconditional jump to the header, we
2418       // need to consider the cost of this jump.
2419       if (Pred->succ_size() == 1)
2420         FallThruCost += ScaleBlockFrequency(EdgeFreq, JumpInstCost);
2421       HeaderFallThroughCost = std::max(HeaderFallThroughCost, FallThruCost);
2422     }
2423   }
2424 
2425   // Here we collect all exit blocks in the loop, and for each exit we find out
2426   // its hottest exit edge. For each loop rotation, we define the loop exit cost
2427   // as the sum of frequencies of exit edges we collect here, excluding the exit
2428   // edge from the tail of the loop chain.
2429   SmallVector<std::pair<MachineBasicBlock *, BlockFrequency>, 4> ExitsWithFreq;
2430   for (auto BB : LoopChain) {
2431     auto LargestExitEdgeProb = BranchProbability::getZero();
2432     for (auto *Succ : BB->successors()) {
2433       BlockChain *SuccChain = BlockToChain[Succ];
2434       if (!LoopBlockSet.count(Succ) &&
2435           (!SuccChain || Succ == *SuccChain->begin())) {
2436         auto SuccProb = MBPI->getEdgeProbability(BB, Succ);
2437         LargestExitEdgeProb = std::max(LargestExitEdgeProb, SuccProb);
2438       }
2439     }
2440     if (LargestExitEdgeProb > BranchProbability::getZero()) {
2441       auto ExitFreq = MBFI->getBlockFreq(BB) * LargestExitEdgeProb;
2442       ExitsWithFreq.emplace_back(BB, ExitFreq);
2443     }
2444   }
2445 
2446   // In this loop we iterate every block in the loop chain and calculate the
2447   // cost assuming the block is the head of the loop chain. When the loop ends,
2448   // we should have found the best candidate as the loop chain's head.
2449   for (auto Iter = LoopChain.begin(), TailIter = std::prev(LoopChain.end()),
2450             EndIter = LoopChain.end();
2451        Iter != EndIter; Iter++, TailIter++) {
2452     // TailIter is used to track the tail of the loop chain if the block we are
2453     // checking (pointed by Iter) is the head of the chain.
2454     if (TailIter == LoopChain.end())
2455       TailIter = LoopChain.begin();
2456 
2457     auto TailBB = *TailIter;
2458 
2459     // Calculate the cost by putting this BB to the top.
2460     BlockFrequency Cost = 0;
2461 
2462     // If the current BB is the loop header, we need to take into account the
2463     // cost of the missed fall through edge from outside of the loop to the
2464     // header.
2465     if (Iter != LoopChain.begin())
2466       Cost += HeaderFallThroughCost;
2467 
2468     // Collect the loop exit cost by summing up frequencies of all exit edges
2469     // except the one from the chain tail.
2470     for (auto &ExitWithFreq : ExitsWithFreq)
2471       if (TailBB != ExitWithFreq.first)
2472         Cost += ExitWithFreq.second;
2473 
2474     // The cost of breaking the once fall-through edge from the tail to the top
2475     // of the loop chain. Here we need to consider three cases:
2476     // 1. If the tail node has only one successor, then we will get an
2477     //    additional jmp instruction. So the cost here is (MisfetchCost +
2478     //    JumpInstCost) * tail node frequency.
2479     // 2. If the tail node has two successors, then we may still get an
2480     //    additional jmp instruction if the layout successor after the loop
2481     //    chain is not its CFG successor. Note that the more frequently executed
2482     //    jmp instruction will be put ahead of the other one. Assume the
2483     //    frequency of those two branches are x and y, where x is the frequency
2484     //    of the edge to the chain head, then the cost will be
2485     //    (x * MisfetechCost + min(x, y) * JumpInstCost) * tail node frequency.
2486     // 3. If the tail node has more than two successors (this rarely happens),
2487     //    we won't consider any additional cost.
2488     if (TailBB->isSuccessor(*Iter)) {
2489       auto TailBBFreq = MBFI->getBlockFreq(TailBB);
2490       if (TailBB->succ_size() == 1)
2491         Cost += ScaleBlockFrequency(TailBBFreq.getFrequency(),
2492                                     MisfetchCost + JumpInstCost);
2493       else if (TailBB->succ_size() == 2) {
2494         auto TailToHeadProb = MBPI->getEdgeProbability(TailBB, *Iter);
2495         auto TailToHeadFreq = TailBBFreq * TailToHeadProb;
2496         auto ColderEdgeFreq = TailToHeadProb > BranchProbability(1, 2)
2497                                   ? TailBBFreq * TailToHeadProb.getCompl()
2498                                   : TailToHeadFreq;
2499         Cost += ScaleBlockFrequency(TailToHeadFreq, MisfetchCost) +
2500                 ScaleBlockFrequency(ColderEdgeFreq, JumpInstCost);
2501       }
2502     }
2503 
2504     LLVM_DEBUG(dbgs() << "The cost of loop rotation by making "
2505                       << getBlockName(*Iter)
2506                       << " to the top: " << Cost.getFrequency() << "\n");
2507 
2508     if (Cost < SmallestRotationCost) {
2509       SmallestRotationCost = Cost;
2510       RotationPos = Iter;
2511     }
2512   }
2513 
2514   if (RotationPos != LoopChain.end()) {
2515     LLVM_DEBUG(dbgs() << "Rotate loop by making " << getBlockName(*RotationPos)
2516                       << " to the top\n");
2517     std::rotate(LoopChain.begin(), RotationPos, LoopChain.end());
2518   }
2519 }
2520 
2521 /// Collect blocks in the given loop that are to be placed.
2522 ///
2523 /// When profile data is available, exclude cold blocks from the returned set;
2524 /// otherwise, collect all blocks in the loop.
2525 MachineBlockPlacement::BlockFilterSet
2526 MachineBlockPlacement::collectLoopBlockSet(const MachineLoop &L) {
2527   BlockFilterSet LoopBlockSet;
2528 
2529   // Filter cold blocks off from LoopBlockSet when profile data is available.
2530   // Collect the sum of frequencies of incoming edges to the loop header from
2531   // outside. If we treat the loop as a super block, this is the frequency of
2532   // the loop. Then for each block in the loop, we calculate the ratio between
2533   // its frequency and the frequency of the loop block. When it is too small,
2534   // don't add it to the loop chain. If there are outer loops, then this block
2535   // will be merged into the first outer loop chain for which this block is not
2536   // cold anymore. This needs precise profile data and we only do this when
2537   // profile data is available.
2538   if (F->getFunction().hasProfileData() || ForceLoopColdBlock) {
2539     BlockFrequency LoopFreq(0);
2540     for (auto LoopPred : L.getHeader()->predecessors())
2541       if (!L.contains(LoopPred))
2542         LoopFreq += MBFI->getBlockFreq(LoopPred) *
2543                     MBPI->getEdgeProbability(LoopPred, L.getHeader());
2544 
2545     for (MachineBasicBlock *LoopBB : L.getBlocks()) {
2546       if (LoopBlockSet.count(LoopBB))
2547         continue;
2548       auto Freq = MBFI->getBlockFreq(LoopBB).getFrequency();
2549       if (Freq == 0 || LoopFreq.getFrequency() / Freq > LoopToColdBlockRatio)
2550         continue;
2551       BlockChain *Chain = BlockToChain[LoopBB];
2552       for (MachineBasicBlock *ChainBB : *Chain)
2553         LoopBlockSet.insert(ChainBB);
2554     }
2555   } else
2556     LoopBlockSet.insert(L.block_begin(), L.block_end());
2557 
2558   return LoopBlockSet;
2559 }
2560 
2561 /// Forms basic block chains from the natural loop structures.
2562 ///
2563 /// These chains are designed to preserve the existing *structure* of the code
2564 /// as much as possible. We can then stitch the chains together in a way which
2565 /// both preserves the topological structure and minimizes taken conditional
2566 /// branches.
2567 void MachineBlockPlacement::buildLoopChains(const MachineLoop &L) {
2568   // First recurse through any nested loops, building chains for those inner
2569   // loops.
2570   for (const MachineLoop *InnerLoop : L)
2571     buildLoopChains(*InnerLoop);
2572 
2573   assert(BlockWorkList.empty() &&
2574          "BlockWorkList not empty when starting to build loop chains.");
2575   assert(EHPadWorkList.empty() &&
2576          "EHPadWorkList not empty when starting to build loop chains.");
2577   BlockFilterSet LoopBlockSet = collectLoopBlockSet(L);
2578 
2579   // Check if we have profile data for this function. If yes, we will rotate
2580   // this loop by modeling costs more precisely which requires the profile data
2581   // for better layout.
2582   bool RotateLoopWithProfile =
2583       ForcePreciseRotationCost ||
2584       (PreciseRotationCost && F->getFunction().hasProfileData());
2585 
2586   // First check to see if there is an obviously preferable top block for the
2587   // loop. This will default to the header, but may end up as one of the
2588   // predecessors to the header if there is one which will result in strictly
2589   // fewer branches in the loop body.
2590   MachineBasicBlock *LoopTop = findBestLoopTop(L, LoopBlockSet);
2591 
2592   // If we selected just the header for the loop top, look for a potentially
2593   // profitable exit block in the event that rotating the loop can eliminate
2594   // branches by placing an exit edge at the bottom.
2595   //
2596   // Loops are processed innermost to uttermost, make sure we clear
2597   // PreferredLoopExit before processing a new loop.
2598   PreferredLoopExit = nullptr;
2599   BlockFrequency ExitFreq;
2600   if (!RotateLoopWithProfile && LoopTop == L.getHeader())
2601     PreferredLoopExit = findBestLoopExit(L, LoopBlockSet, ExitFreq);
2602 
2603   BlockChain &LoopChain = *BlockToChain[LoopTop];
2604 
2605   // FIXME: This is a really lame way of walking the chains in the loop: we
2606   // walk the blocks, and use a set to prevent visiting a particular chain
2607   // twice.
2608   SmallPtrSet<BlockChain *, 4> UpdatedPreds;
2609   assert(LoopChain.UnscheduledPredecessors == 0 &&
2610          "LoopChain should not have unscheduled predecessors.");
2611   UpdatedPreds.insert(&LoopChain);
2612 
2613   for (const MachineBasicBlock *LoopBB : LoopBlockSet)
2614     fillWorkLists(LoopBB, UpdatedPreds, &LoopBlockSet);
2615 
2616   buildChain(LoopTop, LoopChain, &LoopBlockSet);
2617 
2618   if (RotateLoopWithProfile)
2619     rotateLoopWithProfile(LoopChain, L, LoopBlockSet);
2620   else
2621     rotateLoop(LoopChain, PreferredLoopExit, ExitFreq, LoopBlockSet);
2622 
2623   LLVM_DEBUG({
2624     // Crash at the end so we get all of the debugging output first.
2625     bool BadLoop = false;
2626     if (LoopChain.UnscheduledPredecessors) {
2627       BadLoop = true;
2628       dbgs() << "Loop chain contains a block without its preds placed!\n"
2629              << "  Loop header:  " << getBlockName(*L.block_begin()) << "\n"
2630              << "  Chain header: " << getBlockName(*LoopChain.begin()) << "\n";
2631     }
2632     for (MachineBasicBlock *ChainBB : LoopChain) {
2633       dbgs() << "          ... " << getBlockName(ChainBB) << "\n";
2634       if (!LoopBlockSet.remove(ChainBB)) {
2635         // We don't mark the loop as bad here because there are real situations
2636         // where this can occur. For example, with an unanalyzable fallthrough
2637         // from a loop block to a non-loop block or vice versa.
2638         dbgs() << "Loop chain contains a block not contained by the loop!\n"
2639                << "  Loop header:  " << getBlockName(*L.block_begin()) << "\n"
2640                << "  Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
2641                << "  Bad block:    " << getBlockName(ChainBB) << "\n";
2642       }
2643     }
2644 
2645     if (!LoopBlockSet.empty()) {
2646       BadLoop = true;
2647       for (const MachineBasicBlock *LoopBB : LoopBlockSet)
2648         dbgs() << "Loop contains blocks never placed into a chain!\n"
2649                << "  Loop header:  " << getBlockName(*L.block_begin()) << "\n"
2650                << "  Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
2651                << "  Bad block:    " << getBlockName(LoopBB) << "\n";
2652     }
2653     assert(!BadLoop && "Detected problems with the placement of this loop.");
2654   });
2655 
2656   BlockWorkList.clear();
2657   EHPadWorkList.clear();
2658 }
2659 
2660 void MachineBlockPlacement::buildCFGChains() {
2661   // Ensure that every BB in the function has an associated chain to simplify
2662   // the assumptions of the remaining algorithm.
2663   SmallVector<MachineOperand, 4> Cond; // For analyzeBranch.
2664   for (MachineFunction::iterator FI = F->begin(), FE = F->end(); FI != FE;
2665        ++FI) {
2666     MachineBasicBlock *BB = &*FI;
2667     BlockChain *Chain =
2668         new (ChainAllocator.Allocate()) BlockChain(BlockToChain, BB);
2669     // Also, merge any blocks which we cannot reason about and must preserve
2670     // the exact fallthrough behavior for.
2671     while (true) {
2672       Cond.clear();
2673       MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For analyzeBranch.
2674       if (!TII->analyzeBranch(*BB, TBB, FBB, Cond) || !FI->canFallThrough())
2675         break;
2676 
2677       MachineFunction::iterator NextFI = std::next(FI);
2678       MachineBasicBlock *NextBB = &*NextFI;
2679       // Ensure that the layout successor is a viable block, as we know that
2680       // fallthrough is a possibility.
2681       assert(NextFI != FE && "Can't fallthrough past the last block.");
2682       LLVM_DEBUG(dbgs() << "Pre-merging due to unanalyzable fallthrough: "
2683                         << getBlockName(BB) << " -> " << getBlockName(NextBB)
2684                         << "\n");
2685       Chain->merge(NextBB, nullptr);
2686 #ifndef NDEBUG
2687       BlocksWithUnanalyzableExits.insert(&*BB);
2688 #endif
2689       FI = NextFI;
2690       BB = NextBB;
2691     }
2692   }
2693 
2694   // Build any loop-based chains.
2695   PreferredLoopExit = nullptr;
2696   for (MachineLoop *L : *MLI)
2697     buildLoopChains(*L);
2698 
2699   assert(BlockWorkList.empty() &&
2700          "BlockWorkList should be empty before building final chain.");
2701   assert(EHPadWorkList.empty() &&
2702          "EHPadWorkList should be empty before building final chain.");
2703 
2704   SmallPtrSet<BlockChain *, 4> UpdatedPreds;
2705   for (MachineBasicBlock &MBB : *F)
2706     fillWorkLists(&MBB, UpdatedPreds);
2707 
2708   BlockChain &FunctionChain = *BlockToChain[&F->front()];
2709   buildChain(&F->front(), FunctionChain);
2710 
2711 #ifndef NDEBUG
2712   using FunctionBlockSetType = SmallPtrSet<MachineBasicBlock *, 16>;
2713 #endif
2714   LLVM_DEBUG({
2715     // Crash at the end so we get all of the debugging output first.
2716     bool BadFunc = false;
2717     FunctionBlockSetType FunctionBlockSet;
2718     for (MachineBasicBlock &MBB : *F)
2719       FunctionBlockSet.insert(&MBB);
2720 
2721     for (MachineBasicBlock *ChainBB : FunctionChain)
2722       if (!FunctionBlockSet.erase(ChainBB)) {
2723         BadFunc = true;
2724         dbgs() << "Function chain contains a block not in the function!\n"
2725                << "  Bad block:    " << getBlockName(ChainBB) << "\n";
2726       }
2727 
2728     if (!FunctionBlockSet.empty()) {
2729       BadFunc = true;
2730       for (MachineBasicBlock *RemainingBB : FunctionBlockSet)
2731         dbgs() << "Function contains blocks never placed into a chain!\n"
2732                << "  Bad block:    " << getBlockName(RemainingBB) << "\n";
2733     }
2734     assert(!BadFunc && "Detected problems with the block placement.");
2735   });
2736 
2737   // Remember original layout ordering, so we can update terminators after
2738   // reordering to point to the original layout successor.
2739   SmallVector<MachineBasicBlock *, 4> OriginalLayoutSuccessors(
2740       F->getNumBlockIDs());
2741   {
2742     MachineBasicBlock *LastMBB = nullptr;
2743     for (auto &MBB : *F) {
2744       if (LastMBB != nullptr)
2745         OriginalLayoutSuccessors[LastMBB->getNumber()] = &MBB;
2746       LastMBB = &MBB;
2747     }
2748     OriginalLayoutSuccessors[F->back().getNumber()] = nullptr;
2749   }
2750 
2751   // Splice the blocks into place.
2752   MachineFunction::iterator InsertPos = F->begin();
2753   LLVM_DEBUG(dbgs() << "[MBP] Function: " << F->getName() << "\n");
2754   for (MachineBasicBlock *ChainBB : FunctionChain) {
2755     LLVM_DEBUG(dbgs() << (ChainBB == *FunctionChain.begin() ? "Placing chain "
2756                                                             : "          ... ")
2757                       << getBlockName(ChainBB) << "\n");
2758     if (InsertPos != MachineFunction::iterator(ChainBB))
2759       F->splice(InsertPos, ChainBB);
2760     else
2761       ++InsertPos;
2762 
2763     // Update the terminator of the previous block.
2764     if (ChainBB == *FunctionChain.begin())
2765       continue;
2766     MachineBasicBlock *PrevBB = &*std::prev(MachineFunction::iterator(ChainBB));
2767 
2768     // FIXME: It would be awesome of updateTerminator would just return rather
2769     // than assert when the branch cannot be analyzed in order to remove this
2770     // boiler plate.
2771     Cond.clear();
2772     MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For analyzeBranch.
2773 
2774 #ifndef NDEBUG
2775     if (!BlocksWithUnanalyzableExits.count(PrevBB)) {
2776       // Given the exact block placement we chose, we may actually not _need_ to
2777       // be able to edit PrevBB's terminator sequence, but not being _able_ to
2778       // do that at this point is a bug.
2779       assert((!TII->analyzeBranch(*PrevBB, TBB, FBB, Cond) ||
2780               !PrevBB->canFallThrough()) &&
2781              "Unexpected block with un-analyzable fallthrough!");
2782       Cond.clear();
2783       TBB = FBB = nullptr;
2784     }
2785 #endif
2786 
2787     // The "PrevBB" is not yet updated to reflect current code layout, so,
2788     //   o. it may fall-through to a block without explicit "goto" instruction
2789     //      before layout, and no longer fall-through it after layout; or
2790     //   o. just opposite.
2791     //
2792     // analyzeBranch() may return erroneous value for FBB when these two
2793     // situations take place. For the first scenario FBB is mistakenly set NULL;
2794     // for the 2nd scenario, the FBB, which is expected to be NULL, is
2795     // mistakenly pointing to "*BI".
2796     // Thus, if the future change needs to use FBB before the layout is set, it
2797     // has to correct FBB first by using the code similar to the following:
2798     //
2799     // if (!Cond.empty() && (!FBB || FBB == ChainBB)) {
2800     //   PrevBB->updateTerminator();
2801     //   Cond.clear();
2802     //   TBB = FBB = nullptr;
2803     //   if (TII->analyzeBranch(*PrevBB, TBB, FBB, Cond)) {
2804     //     // FIXME: This should never take place.
2805     //     TBB = FBB = nullptr;
2806     //   }
2807     // }
2808     if (!TII->analyzeBranch(*PrevBB, TBB, FBB, Cond)) {
2809       PrevBB->updateTerminator(OriginalLayoutSuccessors[PrevBB->getNumber()]);
2810     }
2811   }
2812 
2813   // Fixup the last block.
2814   Cond.clear();
2815   MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For analyzeBranch.
2816   if (!TII->analyzeBranch(F->back(), TBB, FBB, Cond)) {
2817     MachineBasicBlock *PrevBB = &F->back();
2818     PrevBB->updateTerminator(OriginalLayoutSuccessors[PrevBB->getNumber()]);
2819   }
2820 
2821   BlockWorkList.clear();
2822   EHPadWorkList.clear();
2823 }
2824 
2825 void MachineBlockPlacement::optimizeBranches() {
2826   BlockChain &FunctionChain = *BlockToChain[&F->front()];
2827   SmallVector<MachineOperand, 4> Cond; // For analyzeBranch.
2828 
2829   // Now that all the basic blocks in the chain have the proper layout,
2830   // make a final call to analyzeBranch with AllowModify set.
2831   // Indeed, the target may be able to optimize the branches in a way we
2832   // cannot because all branches may not be analyzable.
2833   // E.g., the target may be able to remove an unconditional branch to
2834   // a fallthrough when it occurs after predicated terminators.
2835   for (MachineBasicBlock *ChainBB : FunctionChain) {
2836     Cond.clear();
2837     MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For analyzeBranch.
2838     if (!TII->analyzeBranch(*ChainBB, TBB, FBB, Cond, /*AllowModify*/ true)) {
2839       // If PrevBB has a two-way branch, try to re-order the branches
2840       // such that we branch to the successor with higher probability first.
2841       if (TBB && !Cond.empty() && FBB &&
2842           MBPI->getEdgeProbability(ChainBB, FBB) >
2843               MBPI->getEdgeProbability(ChainBB, TBB) &&
2844           !TII->reverseBranchCondition(Cond)) {
2845         LLVM_DEBUG(dbgs() << "Reverse order of the two branches: "
2846                           << getBlockName(ChainBB) << "\n");
2847         LLVM_DEBUG(dbgs() << "    Edge probability: "
2848                           << MBPI->getEdgeProbability(ChainBB, FBB) << " vs "
2849                           << MBPI->getEdgeProbability(ChainBB, TBB) << "\n");
2850         DebugLoc dl; // FIXME: this is nowhere
2851         TII->removeBranch(*ChainBB);
2852         TII->insertBranch(*ChainBB, FBB, TBB, Cond, dl);
2853       }
2854     }
2855   }
2856 }
2857 
2858 void MachineBlockPlacement::alignBlocks() {
2859   // Walk through the backedges of the function now that we have fully laid out
2860   // the basic blocks and align the destination of each backedge. We don't rely
2861   // exclusively on the loop info here so that we can align backedges in
2862   // unnatural CFGs and backedges that were introduced purely because of the
2863   // loop rotations done during this layout pass.
2864   if (F->getFunction().hasMinSize() ||
2865       (F->getFunction().hasOptSize() && !TLI->alignLoopsWithOptSize()))
2866     return;
2867   BlockChain &FunctionChain = *BlockToChain[&F->front()];
2868   if (FunctionChain.begin() == FunctionChain.end())
2869     return; // Empty chain.
2870 
2871   const BranchProbability ColdProb(1, 5); // 20%
2872   BlockFrequency EntryFreq = MBFI->getBlockFreq(&F->front());
2873   BlockFrequency WeightedEntryFreq = EntryFreq * ColdProb;
2874   for (MachineBasicBlock *ChainBB : FunctionChain) {
2875     if (ChainBB == *FunctionChain.begin())
2876       continue;
2877 
2878     // Don't align non-looping basic blocks. These are unlikely to execute
2879     // enough times to matter in practice. Note that we'll still handle
2880     // unnatural CFGs inside of a natural outer loop (the common case) and
2881     // rotated loops.
2882     MachineLoop *L = MLI->getLoopFor(ChainBB);
2883     if (!L)
2884       continue;
2885 
2886     const Align Align = TLI->getPrefLoopAlignment(L);
2887     if (Align == 1)
2888       continue; // Don't care about loop alignment.
2889 
2890     // If the block is cold relative to the function entry don't waste space
2891     // aligning it.
2892     BlockFrequency Freq = MBFI->getBlockFreq(ChainBB);
2893     if (Freq < WeightedEntryFreq)
2894       continue;
2895 
2896     // If the block is cold relative to its loop header, don't align it
2897     // regardless of what edges into the block exist.
2898     MachineBasicBlock *LoopHeader = L->getHeader();
2899     BlockFrequency LoopHeaderFreq = MBFI->getBlockFreq(LoopHeader);
2900     if (Freq < (LoopHeaderFreq * ColdProb))
2901       continue;
2902 
2903     // If the global profiles indicates so, don't align it.
2904     if (llvm::shouldOptimizeForSize(ChainBB, PSI, MBFI.get()) &&
2905         !TLI->alignLoopsWithOptSize())
2906       continue;
2907 
2908     // Check for the existence of a non-layout predecessor which would benefit
2909     // from aligning this block.
2910     MachineBasicBlock *LayoutPred =
2911         &*std::prev(MachineFunction::iterator(ChainBB));
2912 
2913     // Force alignment if all the predecessors are jumps. We already checked
2914     // that the block isn't cold above.
2915     if (!LayoutPred->isSuccessor(ChainBB)) {
2916       ChainBB->setAlignment(Align);
2917       continue;
2918     }
2919 
2920     // Align this block if the layout predecessor's edge into this block is
2921     // cold relative to the block. When this is true, other predecessors make up
2922     // all of the hot entries into the block and thus alignment is likely to be
2923     // important.
2924     BranchProbability LayoutProb =
2925         MBPI->getEdgeProbability(LayoutPred, ChainBB);
2926     BlockFrequency LayoutEdgeFreq = MBFI->getBlockFreq(LayoutPred) * LayoutProb;
2927     if (LayoutEdgeFreq <= (Freq * ColdProb))
2928       ChainBB->setAlignment(Align);
2929   }
2930 }
2931 
2932 /// Tail duplicate \p BB into (some) predecessors if profitable, repeating if
2933 /// it was duplicated into its chain predecessor and removed.
2934 /// \p BB    - Basic block that may be duplicated.
2935 ///
2936 /// \p LPred - Chosen layout predecessor of \p BB.
2937 ///            Updated to be the chain end if LPred is removed.
2938 /// \p Chain - Chain to which \p LPred belongs, and \p BB will belong.
2939 /// \p BlockFilter - Set of blocks that belong to the loop being laid out.
2940 ///                  Used to identify which blocks to update predecessor
2941 ///                  counts.
2942 /// \p PrevUnplacedBlockIt - Iterator pointing to the last block that was
2943 ///                          chosen in the given order due to unnatural CFG
2944 ///                          only needed if \p BB is removed and
2945 ///                          \p PrevUnplacedBlockIt pointed to \p BB.
2946 /// @return true if \p BB was removed.
2947 bool MachineBlockPlacement::repeatedlyTailDuplicateBlock(
2948     MachineBasicBlock *BB, MachineBasicBlock *&LPred,
2949     const MachineBasicBlock *LoopHeaderBB,
2950     BlockChain &Chain, BlockFilterSet *BlockFilter,
2951     MachineFunction::iterator &PrevUnplacedBlockIt) {
2952   bool Removed, DuplicatedToLPred;
2953   bool DuplicatedToOriginalLPred;
2954   Removed = maybeTailDuplicateBlock(BB, LPred, Chain, BlockFilter,
2955                                     PrevUnplacedBlockIt,
2956                                     DuplicatedToLPred);
2957   if (!Removed)
2958     return false;
2959   DuplicatedToOriginalLPred = DuplicatedToLPred;
2960   // Iteratively try to duplicate again. It can happen that a block that is
2961   // duplicated into is still small enough to be duplicated again.
2962   // No need to call markBlockSuccessors in this case, as the blocks being
2963   // duplicated from here on are already scheduled.
2964   while (DuplicatedToLPred && Removed) {
2965     MachineBasicBlock *DupBB, *DupPred;
2966     // The removal callback causes Chain.end() to be updated when a block is
2967     // removed. On the first pass through the loop, the chain end should be the
2968     // same as it was on function entry. On subsequent passes, because we are
2969     // duplicating the block at the end of the chain, if it is removed the
2970     // chain will have shrunk by one block.
2971     BlockChain::iterator ChainEnd = Chain.end();
2972     DupBB = *(--ChainEnd);
2973     // Now try to duplicate again.
2974     if (ChainEnd == Chain.begin())
2975       break;
2976     DupPred = *std::prev(ChainEnd);
2977     Removed = maybeTailDuplicateBlock(DupBB, DupPred, Chain, BlockFilter,
2978                                       PrevUnplacedBlockIt,
2979                                       DuplicatedToLPred);
2980   }
2981   // If BB was duplicated into LPred, it is now scheduled. But because it was
2982   // removed, markChainSuccessors won't be called for its chain. Instead we
2983   // call markBlockSuccessors for LPred to achieve the same effect. This must go
2984   // at the end because repeating the tail duplication can increase the number
2985   // of unscheduled predecessors.
2986   LPred = *std::prev(Chain.end());
2987   if (DuplicatedToOriginalLPred)
2988     markBlockSuccessors(Chain, LPred, LoopHeaderBB, BlockFilter);
2989   return true;
2990 }
2991 
2992 /// Tail duplicate \p BB into (some) predecessors if profitable.
2993 /// \p BB    - Basic block that may be duplicated
2994 /// \p LPred - Chosen layout predecessor of \p BB
2995 /// \p Chain - Chain to which \p LPred belongs, and \p BB will belong.
2996 /// \p BlockFilter - Set of blocks that belong to the loop being laid out.
2997 ///                  Used to identify which blocks to update predecessor
2998 ///                  counts.
2999 /// \p PrevUnplacedBlockIt - Iterator pointing to the last block that was
3000 ///                          chosen in the given order due to unnatural CFG
3001 ///                          only needed if \p BB is removed and
3002 ///                          \p PrevUnplacedBlockIt pointed to \p BB.
3003 /// \p DuplicatedToLPred - True if the block was duplicated into LPred.
3004 /// \return  - True if the block was duplicated into all preds and removed.
3005 bool MachineBlockPlacement::maybeTailDuplicateBlock(
3006     MachineBasicBlock *BB, MachineBasicBlock *LPred,
3007     BlockChain &Chain, BlockFilterSet *BlockFilter,
3008     MachineFunction::iterator &PrevUnplacedBlockIt,
3009     bool &DuplicatedToLPred) {
3010   DuplicatedToLPred = false;
3011   if (!shouldTailDuplicate(BB))
3012     return false;
3013 
3014   LLVM_DEBUG(dbgs() << "Redoing tail duplication for Succ#" << BB->getNumber()
3015                     << "\n");
3016 
3017   // This has to be a callback because none of it can be done after
3018   // BB is deleted.
3019   bool Removed = false;
3020   auto RemovalCallback =
3021       [&](MachineBasicBlock *RemBB) {
3022         // Signal to outer function
3023         Removed = true;
3024 
3025         // Conservative default.
3026         bool InWorkList = true;
3027         // Remove from the Chain and Chain Map
3028         if (BlockToChain.count(RemBB)) {
3029           BlockChain *Chain = BlockToChain[RemBB];
3030           InWorkList = Chain->UnscheduledPredecessors == 0;
3031           Chain->remove(RemBB);
3032           BlockToChain.erase(RemBB);
3033         }
3034 
3035         // Handle the unplaced block iterator
3036         if (&(*PrevUnplacedBlockIt) == RemBB) {
3037           PrevUnplacedBlockIt++;
3038         }
3039 
3040         // Handle the Work Lists
3041         if (InWorkList) {
3042           SmallVectorImpl<MachineBasicBlock *> &RemoveList = BlockWorkList;
3043           if (RemBB->isEHPad())
3044             RemoveList = EHPadWorkList;
3045           llvm::erase_value(RemoveList, RemBB);
3046         }
3047 
3048         // Handle the filter set
3049         if (BlockFilter) {
3050           BlockFilter->remove(RemBB);
3051         }
3052 
3053         // Remove the block from loop info.
3054         MLI->removeBlock(RemBB);
3055         if (RemBB == PreferredLoopExit)
3056           PreferredLoopExit = nullptr;
3057 
3058         LLVM_DEBUG(dbgs() << "TailDuplicator deleted block: "
3059                           << getBlockName(RemBB) << "\n");
3060       };
3061   auto RemovalCallbackRef =
3062       function_ref<void(MachineBasicBlock*)>(RemovalCallback);
3063 
3064   SmallVector<MachineBasicBlock *, 8> DuplicatedPreds;
3065   bool IsSimple = TailDup.isSimpleBB(BB);
3066   SmallVector<MachineBasicBlock *, 8> CandidatePreds;
3067   SmallVectorImpl<MachineBasicBlock *> *CandidatePtr = nullptr;
3068   if (F->getFunction().hasProfileData()) {
3069     // We can do partial duplication with precise profile information.
3070     findDuplicateCandidates(CandidatePreds, BB, BlockFilter);
3071     if (CandidatePreds.size() == 0)
3072       return false;
3073     if (CandidatePreds.size() < BB->pred_size())
3074       CandidatePtr = &CandidatePreds;
3075   }
3076   TailDup.tailDuplicateAndUpdate(IsSimple, BB, LPred, &DuplicatedPreds,
3077                                  &RemovalCallbackRef, CandidatePtr);
3078 
3079   // Update UnscheduledPredecessors to reflect tail-duplication.
3080   DuplicatedToLPred = false;
3081   for (MachineBasicBlock *Pred : DuplicatedPreds) {
3082     // We're only looking for unscheduled predecessors that match the filter.
3083     BlockChain* PredChain = BlockToChain[Pred];
3084     if (Pred == LPred)
3085       DuplicatedToLPred = true;
3086     if (Pred == LPred || (BlockFilter && !BlockFilter->count(Pred))
3087         || PredChain == &Chain)
3088       continue;
3089     for (MachineBasicBlock *NewSucc : Pred->successors()) {
3090       if (BlockFilter && !BlockFilter->count(NewSucc))
3091         continue;
3092       BlockChain *NewChain = BlockToChain[NewSucc];
3093       if (NewChain != &Chain && NewChain != PredChain)
3094         NewChain->UnscheduledPredecessors++;
3095     }
3096   }
3097   return Removed;
3098 }
3099 
3100 // Count the number of actual machine instructions.
3101 static uint64_t countMBBInstruction(MachineBasicBlock *MBB) {
3102   uint64_t InstrCount = 0;
3103   for (MachineInstr &MI : *MBB) {
3104     if (!MI.isPHI() && !MI.isMetaInstruction())
3105       InstrCount += 1;
3106   }
3107   return InstrCount;
3108 }
3109 
3110 // The size cost of duplication is the instruction size of the duplicated block.
3111 // So we should scale the threshold accordingly. But the instruction size is not
3112 // available on all targets, so we use the number of instructions instead.
3113 BlockFrequency MachineBlockPlacement::scaleThreshold(MachineBasicBlock *BB) {
3114   return DupThreshold.getFrequency() * countMBBInstruction(BB);
3115 }
3116 
3117 // Returns true if BB is Pred's best successor.
3118 bool MachineBlockPlacement::isBestSuccessor(MachineBasicBlock *BB,
3119                                             MachineBasicBlock *Pred,
3120                                             BlockFilterSet *BlockFilter) {
3121   if (BB == Pred)
3122     return false;
3123   if (BlockFilter && !BlockFilter->count(Pred))
3124     return false;
3125   BlockChain *PredChain = BlockToChain[Pred];
3126   if (PredChain && (Pred != *std::prev(PredChain->end())))
3127     return false;
3128 
3129   // Find the successor with largest probability excluding BB.
3130   BranchProbability BestProb = BranchProbability::getZero();
3131   for (MachineBasicBlock *Succ : Pred->successors())
3132     if (Succ != BB) {
3133       if (BlockFilter && !BlockFilter->count(Succ))
3134         continue;
3135       BlockChain *SuccChain = BlockToChain[Succ];
3136       if (SuccChain && (Succ != *SuccChain->begin()))
3137         continue;
3138       BranchProbability SuccProb = MBPI->getEdgeProbability(Pred, Succ);
3139       if (SuccProb > BestProb)
3140         BestProb = SuccProb;
3141     }
3142 
3143   BranchProbability BBProb = MBPI->getEdgeProbability(Pred, BB);
3144   if (BBProb <= BestProb)
3145     return false;
3146 
3147   // Compute the number of reduced taken branches if Pred falls through to BB
3148   // instead of another successor. Then compare it with threshold.
3149   BlockFrequency PredFreq = getBlockCountOrFrequency(Pred);
3150   BlockFrequency Gain = PredFreq * (BBProb - BestProb);
3151   return Gain > scaleThreshold(BB);
3152 }
3153 
3154 // Find out the predecessors of BB and BB can be beneficially duplicated into
3155 // them.
3156 void MachineBlockPlacement::findDuplicateCandidates(
3157     SmallVectorImpl<MachineBasicBlock *> &Candidates,
3158     MachineBasicBlock *BB,
3159     BlockFilterSet *BlockFilter) {
3160   MachineBasicBlock *Fallthrough = nullptr;
3161   BranchProbability DefaultBranchProb = BranchProbability::getZero();
3162   BlockFrequency BBDupThreshold(scaleThreshold(BB));
3163   SmallVector<MachineBasicBlock *, 8> Preds(BB->predecessors());
3164   SmallVector<MachineBasicBlock *, 8> Succs(BB->successors());
3165 
3166   // Sort for highest frequency.
3167   auto CmpSucc = [&](MachineBasicBlock *A, MachineBasicBlock *B) {
3168     return MBPI->getEdgeProbability(BB, A) > MBPI->getEdgeProbability(BB, B);
3169   };
3170   auto CmpPred = [&](MachineBasicBlock *A, MachineBasicBlock *B) {
3171     return MBFI->getBlockFreq(A) > MBFI->getBlockFreq(B);
3172   };
3173   llvm::stable_sort(Succs, CmpSucc);
3174   llvm::stable_sort(Preds, CmpPred);
3175 
3176   auto SuccIt = Succs.begin();
3177   if (SuccIt != Succs.end()) {
3178     DefaultBranchProb = MBPI->getEdgeProbability(BB, *SuccIt).getCompl();
3179   }
3180 
3181   // For each predecessors of BB, compute the benefit of duplicating BB,
3182   // if it is larger than the threshold, add it into Candidates.
3183   //
3184   // If we have following control flow.
3185   //
3186   //     PB1 PB2 PB3 PB4
3187   //      \   |  /    /\
3188   //       \  | /    /  \
3189   //        \ |/    /    \
3190   //         BB----/     OB
3191   //         /\
3192   //        /  \
3193   //      SB1 SB2
3194   //
3195   // And it can be partially duplicated as
3196   //
3197   //   PB2+BB
3198   //      |  PB1 PB3 PB4
3199   //      |   |  /    /\
3200   //      |   | /    /  \
3201   //      |   |/    /    \
3202   //      |  BB----/     OB
3203   //      |\ /|
3204   //      | X |
3205   //      |/ \|
3206   //     SB2 SB1
3207   //
3208   // The benefit of duplicating into a predecessor is defined as
3209   //         Orig_taken_branch - Duplicated_taken_branch
3210   //
3211   // The Orig_taken_branch is computed with the assumption that predecessor
3212   // jumps to BB and the most possible successor is laid out after BB.
3213   //
3214   // The Duplicated_taken_branch is computed with the assumption that BB is
3215   // duplicated into PB, and one successor is layout after it (SB1 for PB1 and
3216   // SB2 for PB2 in our case). If there is no available successor, the combined
3217   // block jumps to all BB's successor, like PB3 in this example.
3218   //
3219   // If a predecessor has multiple successors, so BB can't be duplicated into
3220   // it. But it can beneficially fall through to BB, and duplicate BB into other
3221   // predecessors.
3222   for (MachineBasicBlock *Pred : Preds) {
3223     BlockFrequency PredFreq = getBlockCountOrFrequency(Pred);
3224 
3225     if (!TailDup.canTailDuplicate(BB, Pred)) {
3226       // BB can't be duplicated into Pred, but it is possible to be layout
3227       // below Pred.
3228       if (!Fallthrough && isBestSuccessor(BB, Pred, BlockFilter)) {
3229         Fallthrough = Pred;
3230         if (SuccIt != Succs.end())
3231           SuccIt++;
3232       }
3233       continue;
3234     }
3235 
3236     BlockFrequency OrigCost = PredFreq + PredFreq * DefaultBranchProb;
3237     BlockFrequency DupCost;
3238     if (SuccIt == Succs.end()) {
3239       // Jump to all successors;
3240       if (Succs.size() > 0)
3241         DupCost += PredFreq;
3242     } else {
3243       // Fallthrough to *SuccIt, jump to all other successors;
3244       DupCost += PredFreq;
3245       DupCost -= PredFreq * MBPI->getEdgeProbability(BB, *SuccIt);
3246     }
3247 
3248     assert(OrigCost >= DupCost);
3249     OrigCost -= DupCost;
3250     if (OrigCost > BBDupThreshold) {
3251       Candidates.push_back(Pred);
3252       if (SuccIt != Succs.end())
3253         SuccIt++;
3254     }
3255   }
3256 
3257   // No predecessors can optimally fallthrough to BB.
3258   // So we can change one duplication into fallthrough.
3259   if (!Fallthrough) {
3260     if ((Candidates.size() < Preds.size()) && (Candidates.size() > 0)) {
3261       Candidates[0] = Candidates.back();
3262       Candidates.pop_back();
3263     }
3264   }
3265 }
3266 
3267 void MachineBlockPlacement::initDupThreshold() {
3268   DupThreshold = 0;
3269   if (!F->getFunction().hasProfileData())
3270     return;
3271 
3272   // We prefer to use prifile count.
3273   uint64_t HotThreshold = PSI->getOrCompHotCountThreshold();
3274   if (HotThreshold != UINT64_MAX) {
3275     UseProfileCount = true;
3276     DupThreshold = HotThreshold * TailDupProfilePercentThreshold / 100;
3277     return;
3278   }
3279 
3280   // Profile count is not available, we can use block frequency instead.
3281   BlockFrequency MaxFreq = 0;
3282   for (MachineBasicBlock &MBB : *F) {
3283     BlockFrequency Freq = MBFI->getBlockFreq(&MBB);
3284     if (Freq > MaxFreq)
3285       MaxFreq = Freq;
3286   }
3287 
3288   BranchProbability ThresholdProb(TailDupPlacementPenalty, 100);
3289   DupThreshold = MaxFreq * ThresholdProb;
3290   UseProfileCount = false;
3291 }
3292 
3293 bool MachineBlockPlacement::runOnMachineFunction(MachineFunction &MF) {
3294   if (skipFunction(MF.getFunction()))
3295     return false;
3296 
3297   // Check for single-block functions and skip them.
3298   if (std::next(MF.begin()) == MF.end())
3299     return false;
3300 
3301   F = &MF;
3302   MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
3303   MBFI = std::make_unique<MBFIWrapper>(
3304       getAnalysis<MachineBlockFrequencyInfo>());
3305   MLI = &getAnalysis<MachineLoopInfo>();
3306   TII = MF.getSubtarget().getInstrInfo();
3307   TLI = MF.getSubtarget().getTargetLowering();
3308   MPDT = nullptr;
3309   PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
3310 
3311   initDupThreshold();
3312 
3313   // Initialize PreferredLoopExit to nullptr here since it may never be set if
3314   // there are no MachineLoops.
3315   PreferredLoopExit = nullptr;
3316 
3317   assert(BlockToChain.empty() &&
3318          "BlockToChain map should be empty before starting placement.");
3319   assert(ComputedEdges.empty() &&
3320          "Computed Edge map should be empty before starting placement.");
3321 
3322   unsigned TailDupSize = TailDupPlacementThreshold;
3323   // If only the aggressive threshold is explicitly set, use it.
3324   if (TailDupPlacementAggressiveThreshold.getNumOccurrences() != 0 &&
3325       TailDupPlacementThreshold.getNumOccurrences() == 0)
3326     TailDupSize = TailDupPlacementAggressiveThreshold;
3327 
3328   TargetPassConfig *PassConfig = &getAnalysis<TargetPassConfig>();
3329   // For aggressive optimization, we can adjust some thresholds to be less
3330   // conservative.
3331   if (PassConfig->getOptLevel() >= CodeGenOpt::Aggressive) {
3332     // At O3 we should be more willing to copy blocks for tail duplication. This
3333     // increases size pressure, so we only do it at O3
3334     // Do this unless only the regular threshold is explicitly set.
3335     if (TailDupPlacementThreshold.getNumOccurrences() == 0 ||
3336         TailDupPlacementAggressiveThreshold.getNumOccurrences() != 0)
3337       TailDupSize = TailDupPlacementAggressiveThreshold;
3338   }
3339 
3340   if (allowTailDupPlacement()) {
3341     MPDT = &getAnalysis<MachinePostDominatorTree>();
3342     bool OptForSize = MF.getFunction().hasOptSize() ||
3343                       llvm::shouldOptimizeForSize(&MF, PSI, &MBFI->getMBFI());
3344     if (OptForSize)
3345       TailDupSize = 1;
3346     bool PreRegAlloc = false;
3347     TailDup.initMF(MF, PreRegAlloc, MBPI, MBFI.get(), PSI,
3348                    /* LayoutMode */ true, TailDupSize);
3349     precomputeTriangleChains();
3350   }
3351 
3352   buildCFGChains();
3353 
3354   // Changing the layout can create new tail merging opportunities.
3355   // TailMerge can create jump into if branches that make CFG irreducible for
3356   // HW that requires structured CFG.
3357   bool EnableTailMerge = !MF.getTarget().requiresStructuredCFG() &&
3358                          PassConfig->getEnableTailMerge() &&
3359                          BranchFoldPlacement;
3360   // No tail merging opportunities if the block number is less than four.
3361   if (MF.size() > 3 && EnableTailMerge) {
3362     unsigned TailMergeSize = TailDupSize + 1;
3363     BranchFolder BF(/*DefaultEnableTailMerge=*/true, /*CommonHoist=*/false,
3364                     *MBFI, *MBPI, PSI, TailMergeSize);
3365 
3366     if (BF.OptimizeFunction(MF, TII, MF.getSubtarget().getRegisterInfo(), MLI,
3367                             /*AfterPlacement=*/true)) {
3368       // Redo the layout if tail merging creates/removes/moves blocks.
3369       BlockToChain.clear();
3370       ComputedEdges.clear();
3371       // Must redo the post-dominator tree if blocks were changed.
3372       if (MPDT)
3373         MPDT->runOnMachineFunction(MF);
3374       ChainAllocator.DestroyAll();
3375       buildCFGChains();
3376     }
3377   }
3378 
3379   optimizeBranches();
3380   alignBlocks();
3381 
3382   BlockToChain.clear();
3383   ComputedEdges.clear();
3384   ChainAllocator.DestroyAll();
3385 
3386   if (AlignAllBlock)
3387     // Align all of the blocks in the function to a specific alignment.
3388     for (MachineBasicBlock &MBB : MF)
3389       MBB.setAlignment(Align(1ULL << AlignAllBlock));
3390   else if (AlignAllNonFallThruBlocks) {
3391     // Align all of the blocks that have no fall-through predecessors to a
3392     // specific alignment.
3393     for (auto MBI = std::next(MF.begin()), MBE = MF.end(); MBI != MBE; ++MBI) {
3394       auto LayoutPred = std::prev(MBI);
3395       if (!LayoutPred->isSuccessor(&*MBI))
3396         MBI->setAlignment(Align(1ULL << AlignAllNonFallThruBlocks));
3397     }
3398   }
3399   if (ViewBlockLayoutWithBFI != GVDT_None &&
3400       (ViewBlockFreqFuncName.empty() ||
3401        F->getFunction().getName().equals(ViewBlockFreqFuncName))) {
3402     MBFI->view("MBP." + MF.getName(), false);
3403   }
3404 
3405 
3406   // We always return true as we have no way to track whether the final order
3407   // differs from the original order.
3408   return true;
3409 }
3410 
3411 namespace {
3412 
3413 /// A pass to compute block placement statistics.
3414 ///
3415 /// A separate pass to compute interesting statistics for evaluating block
3416 /// placement. This is separate from the actual placement pass so that they can
3417 /// be computed in the absence of any placement transformations or when using
3418 /// alternative placement strategies.
3419 class MachineBlockPlacementStats : public MachineFunctionPass {
3420   /// A handle to the branch probability pass.
3421   const MachineBranchProbabilityInfo *MBPI;
3422 
3423   /// A handle to the function-wide block frequency pass.
3424   const MachineBlockFrequencyInfo *MBFI;
3425 
3426 public:
3427   static char ID; // Pass identification, replacement for typeid
3428 
3429   MachineBlockPlacementStats() : MachineFunctionPass(ID) {
3430     initializeMachineBlockPlacementStatsPass(*PassRegistry::getPassRegistry());
3431   }
3432 
3433   bool runOnMachineFunction(MachineFunction &F) override;
3434 
3435   void getAnalysisUsage(AnalysisUsage &AU) const override {
3436     AU.addRequired<MachineBranchProbabilityInfo>();
3437     AU.addRequired<MachineBlockFrequencyInfo>();
3438     AU.setPreservesAll();
3439     MachineFunctionPass::getAnalysisUsage(AU);
3440   }
3441 };
3442 
3443 } // end anonymous namespace
3444 
3445 char MachineBlockPlacementStats::ID = 0;
3446 
3447 char &llvm::MachineBlockPlacementStatsID = MachineBlockPlacementStats::ID;
3448 
3449 INITIALIZE_PASS_BEGIN(MachineBlockPlacementStats, "block-placement-stats",
3450                       "Basic Block Placement Stats", false, false)
3451 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
3452 INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
3453 INITIALIZE_PASS_END(MachineBlockPlacementStats, "block-placement-stats",
3454                     "Basic Block Placement Stats", false, false)
3455 
3456 bool MachineBlockPlacementStats::runOnMachineFunction(MachineFunction &F) {
3457   // Check for single-block functions and skip them.
3458   if (std::next(F.begin()) == F.end())
3459     return false;
3460 
3461   MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
3462   MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
3463 
3464   for (MachineBasicBlock &MBB : F) {
3465     BlockFrequency BlockFreq = MBFI->getBlockFreq(&MBB);
3466     Statistic &NumBranches =
3467         (MBB.succ_size() > 1) ? NumCondBranches : NumUncondBranches;
3468     Statistic &BranchTakenFreq =
3469         (MBB.succ_size() > 1) ? CondBranchTakenFreq : UncondBranchTakenFreq;
3470     for (MachineBasicBlock *Succ : MBB.successors()) {
3471       // Skip if this successor is a fallthrough.
3472       if (MBB.isLayoutSuccessor(Succ))
3473         continue;
3474 
3475       BlockFrequency EdgeFreq =
3476           BlockFreq * MBPI->getEdgeProbability(&MBB, Succ);
3477       ++NumBranches;
3478       BranchTakenFreq += EdgeFreq.getFrequency();
3479     }
3480   }
3481 
3482   return false;
3483 }
3484