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