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