1 //===-- MachineBlockPlacement.cpp - Basic Block Code Layout optimization --===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements basic block placement transformations using the CFG
11 // structure and branch probability estimates.
12 //
13 // The pass strives to preserve the structure of the CFG (that is, retain
14 // a topological ordering of basic blocks) in the absence of a *strong* signal
15 // to the contrary from probabilities. However, within the CFG structure, it
16 // attempts to choose an ordering which favors placing more likely sequences of
17 // blocks adjacent to each other.
18 //
19 // The algorithm works from the inner-most loop within a function outward, and
20 // at each stage walks through the basic blocks, trying to coalesce them into
21 // sequential chains where allowed by the CFG (or demanded by heavy
22 // probabilities). Finally, it walks the blocks in topological order, and the
23 // first time it reaches a chain of basic blocks, it schedules them in the
24 // function in-order.
25 //
26 //===----------------------------------------------------------------------===//
27 
28 #include "llvm/CodeGen/Passes.h"
29 #include "llvm/ADT/DenseMap.h"
30 #include "llvm/ADT/SmallPtrSet.h"
31 #include "llvm/ADT/SmallVector.h"
32 #include "llvm/ADT/Statistic.h"
33 #include "llvm/CodeGen/MachineBasicBlock.h"
34 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
35 #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
36 #include "llvm/CodeGen/MachineDominators.h"
37 #include "llvm/CodeGen/MachineFunction.h"
38 #include "llvm/CodeGen/MachineFunctionPass.h"
39 #include "llvm/CodeGen/MachineLoopInfo.h"
40 #include "llvm/CodeGen/MachineModuleInfo.h"
41 #include "llvm/Support/Allocator.h"
42 #include "llvm/Support/CommandLine.h"
43 #include "llvm/Support/Debug.h"
44 #include "llvm/Support/raw_ostream.h"
45 #include "llvm/Target/TargetInstrInfo.h"
46 #include "llvm/Target/TargetLowering.h"
47 #include "llvm/Target/TargetSubtargetInfo.h"
48 #include <algorithm>
49 using namespace llvm;
50 
51 #define DEBUG_TYPE "block-placement"
52 
53 STATISTIC(NumCondBranches, "Number of conditional branches");
54 STATISTIC(NumUncondBranches, "Number of unconditional branches");
55 STATISTIC(CondBranchTakenFreq,
56           "Potential frequency of taking conditional branches");
57 STATISTIC(UncondBranchTakenFreq,
58           "Potential frequency of taking unconditional branches");
59 
60 static cl::opt<unsigned> AlignAllBlock("align-all-blocks",
61                                        cl::desc("Force the alignment of all "
62                                                 "blocks in the function."),
63                                        cl::init(0), cl::Hidden);
64 
65 static cl::opt<unsigned> AlignAllNonFallThruBlocks(
66     "align-all-nofallthru-blocks",
67     cl::desc("Force the alignment of all "
68              "blocks that have no fall-through predecessors (i.e. don't add "
69              "nops that are executed)."),
70     cl::init(0), cl::Hidden);
71 
72 // FIXME: Find a good default for this flag and remove the flag.
73 static cl::opt<unsigned> ExitBlockBias(
74     "block-placement-exit-block-bias",
75     cl::desc("Block frequency percentage a loop exit block needs "
76              "over the original exit to be considered the new exit."),
77     cl::init(0), cl::Hidden);
78 
79 static cl::opt<bool> OutlineOptionalBranches(
80     "outline-optional-branches",
81     cl::desc("Put completely optional branches, i.e. branches with a common "
82              "post dominator, out of line."),
83     cl::init(false), cl::Hidden);
84 
85 static cl::opt<unsigned> OutlineOptionalThreshold(
86     "outline-optional-threshold",
87     cl::desc("Don't outline optional branches that are a single block with an "
88              "instruction count below this threshold"),
89     cl::init(4), cl::Hidden);
90 
91 static cl::opt<unsigned> LoopToColdBlockRatio(
92     "loop-to-cold-block-ratio",
93     cl::desc("Outline loop blocks from loop chain if (frequency of loop) / "
94              "(frequency of block) is greater than this ratio"),
95     cl::init(5), cl::Hidden);
96 
97 static cl::opt<bool>
98     PreciseRotationCost("precise-rotation-cost",
99                         cl::desc("Model the cost of loop rotation more "
100                                  "precisely by using profile data."),
101                         cl::init(false), cl::Hidden);
102 
103 static cl::opt<unsigned> MisfetchCost(
104     "misfetch-cost",
105     cl::desc("Cost that models the probablistic risk of an instruction "
106              "misfetch due to a jump comparing to falling through, whose cost "
107              "is zero."),
108     cl::init(1), cl::Hidden);
109 
110 static cl::opt<unsigned> JumpInstCost("jump-inst-cost",
111                                       cl::desc("Cost of jump instructions."),
112                                       cl::init(1), cl::Hidden);
113 
114 namespace {
115 class BlockChain;
116 /// \brief Type for our function-wide basic block -> block chain mapping.
117 typedef DenseMap<MachineBasicBlock *, BlockChain *> BlockToChainMapType;
118 }
119 
120 namespace {
121 /// \brief A chain of blocks which will be laid out contiguously.
122 ///
123 /// This is the datastructure representing a chain of consecutive blocks that
124 /// are profitable to layout together in order to maximize fallthrough
125 /// probabilities and code locality. We also can use a block chain to represent
126 /// a sequence of basic blocks which have some external (correctness)
127 /// requirement for sequential layout.
128 ///
129 /// Chains can be built around a single basic block and can be merged to grow
130 /// them. They participate in a block-to-chain mapping, which is updated
131 /// automatically as chains are merged together.
132 class BlockChain {
133   /// \brief The sequence of blocks belonging to this chain.
134   ///
135   /// This is the sequence of blocks for a particular chain. These will be laid
136   /// out in-order within the function.
137   SmallVector<MachineBasicBlock *, 4> Blocks;
138 
139   /// \brief A handle to the function-wide basic block to block chain mapping.
140   ///
141   /// This is retained in each block chain to simplify the computation of child
142   /// block chains for SCC-formation and iteration. We store the edges to child
143   /// basic blocks, and map them back to their associated chains using this
144   /// structure.
145   BlockToChainMapType &BlockToChain;
146 
147 public:
148   /// \brief Construct a new BlockChain.
149   ///
150   /// This builds a new block chain representing a single basic block in the
151   /// function. It also registers itself as the chain that block participates
152   /// in with the BlockToChain mapping.
153   BlockChain(BlockToChainMapType &BlockToChain, MachineBasicBlock *BB)
154       : Blocks(1, BB), BlockToChain(BlockToChain), UnscheduledPredecessors(0) {
155     assert(BB && "Cannot create a chain with a null basic block");
156     BlockToChain[BB] = this;
157   }
158 
159   /// \brief Iterator over blocks within the chain.
160   typedef SmallVectorImpl<MachineBasicBlock *>::iterator iterator;
161 
162   /// \brief Beginning of blocks within the chain.
163   iterator begin() { return Blocks.begin(); }
164 
165   /// \brief End of blocks within the chain.
166   iterator end() { return Blocks.end(); }
167 
168   /// \brief Merge a block chain into this one.
169   ///
170   /// This routine merges a block chain into this one. It takes care of forming
171   /// a contiguous sequence of basic blocks, updating the edge list, and
172   /// updating the block -> chain mapping. It does not free or tear down the
173   /// old chain, but the old chain's block list is no longer valid.
174   void merge(MachineBasicBlock *BB, BlockChain *Chain) {
175     assert(BB);
176     assert(!Blocks.empty());
177 
178     // Fast path in case we don't have a chain already.
179     if (!Chain) {
180       assert(!BlockToChain[BB]);
181       Blocks.push_back(BB);
182       BlockToChain[BB] = this;
183       return;
184     }
185 
186     assert(BB == *Chain->begin());
187     assert(Chain->begin() != Chain->end());
188 
189     // Update the incoming blocks to point to this chain, and add them to the
190     // chain structure.
191     for (MachineBasicBlock *ChainBB : *Chain) {
192       Blocks.push_back(ChainBB);
193       assert(BlockToChain[ChainBB] == Chain && "Incoming blocks not in chain");
194       BlockToChain[ChainBB] = this;
195     }
196   }
197 
198 #ifndef NDEBUG
199   /// \brief Dump the blocks in this chain.
200   LLVM_DUMP_METHOD void dump() {
201     for (MachineBasicBlock *MBB : *this)
202       MBB->dump();
203   }
204 #endif // NDEBUG
205 
206   /// \brief Count of predecessors of any block within the chain which have not
207   /// yet been scheduled.  In general, we will delay scheduling this chain
208   /// until those predecessors are scheduled (or we find a sufficiently good
209   /// reason to override this heuristic.)  Note that when forming loop chains,
210   /// blocks outside the loop are ignored and treated as if they were already
211   /// scheduled.
212   ///
213   /// Note: This field is reinitialized multiple times - once for each loop,
214   /// and then once for the function as a whole.
215   unsigned UnscheduledPredecessors;
216 };
217 }
218 
219 namespace {
220 class MachineBlockPlacement : public MachineFunctionPass {
221   /// \brief A typedef for a block filter set.
222   typedef SmallPtrSet<MachineBasicBlock *, 16> BlockFilterSet;
223 
224   /// \brief A handle to the branch probability pass.
225   const MachineBranchProbabilityInfo *MBPI;
226 
227   /// \brief A handle to the function-wide block frequency pass.
228   const MachineBlockFrequencyInfo *MBFI;
229 
230   /// \brief A handle to the loop info.
231   const MachineLoopInfo *MLI;
232 
233   /// \brief A handle to the target's instruction info.
234   const TargetInstrInfo *TII;
235 
236   /// \brief A handle to the target's lowering info.
237   const TargetLoweringBase *TLI;
238 
239   /// \brief A handle to the post dominator tree.
240   MachineDominatorTree *MDT;
241 
242   /// \brief A set of blocks that are unavoidably execute, i.e. they dominate
243   /// all terminators of the MachineFunction.
244   SmallPtrSet<MachineBasicBlock *, 4> UnavoidableBlocks;
245 
246   /// \brief Allocator and owner of BlockChain structures.
247   ///
248   /// We build BlockChains lazily while processing the loop structure of
249   /// a function. To reduce malloc traffic, we allocate them using this
250   /// slab-like allocator, and destroy them after the pass completes. An
251   /// important guarantee is that this allocator produces stable pointers to
252   /// the chains.
253   SpecificBumpPtrAllocator<BlockChain> ChainAllocator;
254 
255   /// \brief Function wide BasicBlock to BlockChain mapping.
256   ///
257   /// This mapping allows efficiently moving from any given basic block to the
258   /// BlockChain it participates in, if any. We use it to, among other things,
259   /// allow implicitly defining edges between chains as the existing edges
260   /// between basic blocks.
261   DenseMap<MachineBasicBlock *, BlockChain *> BlockToChain;
262 
263   void markChainSuccessors(BlockChain &Chain, MachineBasicBlock *LoopHeaderBB,
264                            SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
265                            const BlockFilterSet *BlockFilter = nullptr);
266   MachineBasicBlock *selectBestSuccessor(MachineBasicBlock *BB,
267                                          BlockChain &Chain,
268                                          const BlockFilterSet *BlockFilter);
269   MachineBasicBlock *
270   selectBestCandidateBlock(BlockChain &Chain,
271                            SmallVectorImpl<MachineBasicBlock *> &WorkList,
272                            const BlockFilterSet *BlockFilter);
273   MachineBasicBlock *
274   getFirstUnplacedBlock(MachineFunction &F, const BlockChain &PlacedChain,
275                         MachineFunction::iterator &PrevUnplacedBlockIt,
276                         const BlockFilterSet *BlockFilter);
277   void buildChain(MachineBasicBlock *BB, BlockChain &Chain,
278                   SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
279                   const BlockFilterSet *BlockFilter = nullptr);
280   MachineBasicBlock *findBestLoopTop(MachineLoop &L,
281                                      const BlockFilterSet &LoopBlockSet);
282   MachineBasicBlock *findBestLoopExit(MachineFunction &F, MachineLoop &L,
283                                       const BlockFilterSet &LoopBlockSet);
284   BlockFilterSet collectLoopBlockSet(MachineFunction &F, MachineLoop &L);
285   void buildLoopChains(MachineFunction &F, MachineLoop &L);
286   void rotateLoop(BlockChain &LoopChain, MachineBasicBlock *ExitingBB,
287                   const BlockFilterSet &LoopBlockSet);
288   void rotateLoopWithProfile(BlockChain &LoopChain, MachineLoop &L,
289                              const BlockFilterSet &LoopBlockSet);
290   void buildCFGChains(MachineFunction &F);
291 
292 public:
293   static char ID; // Pass identification, replacement for typeid
294   MachineBlockPlacement() : MachineFunctionPass(ID) {
295     initializeMachineBlockPlacementPass(*PassRegistry::getPassRegistry());
296   }
297 
298   bool runOnMachineFunction(MachineFunction &F) override;
299 
300   void getAnalysisUsage(AnalysisUsage &AU) const override {
301     AU.addRequired<MachineBranchProbabilityInfo>();
302     AU.addRequired<MachineBlockFrequencyInfo>();
303     AU.addRequired<MachineDominatorTree>();
304     AU.addRequired<MachineLoopInfo>();
305     MachineFunctionPass::getAnalysisUsage(AU);
306   }
307 };
308 }
309 
310 char MachineBlockPlacement::ID = 0;
311 char &llvm::MachineBlockPlacementID = MachineBlockPlacement::ID;
312 INITIALIZE_PASS_BEGIN(MachineBlockPlacement, "block-placement",
313                       "Branch Probability Basic Block Placement", false, false)
314 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
315 INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
316 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
317 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
318 INITIALIZE_PASS_END(MachineBlockPlacement, "block-placement",
319                     "Branch Probability Basic Block Placement", false, false)
320 
321 #ifndef NDEBUG
322 /// \brief Helper to print the name of a MBB.
323 ///
324 /// Only used by debug logging.
325 static std::string getBlockName(MachineBasicBlock *BB) {
326   std::string Result;
327   raw_string_ostream OS(Result);
328   OS << "BB#" << BB->getNumber();
329   OS << " ('" << BB->getName() << "')";
330   OS.flush();
331   return Result;
332 }
333 #endif
334 
335 /// \brief Mark a chain's successors as having one fewer preds.
336 ///
337 /// When a chain is being merged into the "placed" chain, this routine will
338 /// quickly walk the successors of each block in the chain and mark them as
339 /// having one fewer active predecessor. It also adds any successors of this
340 /// chain which reach the zero-predecessor state to the worklist passed in.
341 void MachineBlockPlacement::markChainSuccessors(
342     BlockChain &Chain, MachineBasicBlock *LoopHeaderBB,
343     SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
344     const BlockFilterSet *BlockFilter) {
345   // Walk all the blocks in this chain, marking their successors as having
346   // a predecessor placed.
347   for (MachineBasicBlock *MBB : Chain) {
348     // Add any successors for which this is the only un-placed in-loop
349     // predecessor to the worklist as a viable candidate for CFG-neutral
350     // placement. No subsequent placement of this block will violate the CFG
351     // shape, so we get to use heuristics to choose a favorable placement.
352     for (MachineBasicBlock *Succ : MBB->successors()) {
353       if (BlockFilter && !BlockFilter->count(Succ))
354         continue;
355       BlockChain &SuccChain = *BlockToChain[Succ];
356       // Disregard edges within a fixed chain, or edges to the loop header.
357       if (&Chain == &SuccChain || Succ == LoopHeaderBB)
358         continue;
359 
360       // This is a cross-chain edge that is within the loop, so decrement the
361       // loop predecessor count of the destination chain.
362       if (SuccChain.UnscheduledPredecessors > 0 && --SuccChain.UnscheduledPredecessors == 0)
363         BlockWorkList.push_back(*SuccChain.begin());
364     }
365   }
366 }
367 
368 /// \brief Select the best successor for a block.
369 ///
370 /// This looks across all successors of a particular block and attempts to
371 /// select the "best" one to be the layout successor. It only considers direct
372 /// successors which also pass the block filter. It will attempt to avoid
373 /// breaking CFG structure, but cave and break such structures in the case of
374 /// very hot successor edges.
375 ///
376 /// \returns The best successor block found, or null if none are viable.
377 MachineBasicBlock *
378 MachineBlockPlacement::selectBestSuccessor(MachineBasicBlock *BB,
379                                            BlockChain &Chain,
380                                            const BlockFilterSet *BlockFilter) {
381   const BranchProbability HotProb(4, 5); // 80%
382 
383   MachineBasicBlock *BestSucc = nullptr;
384   auto BestProb = BranchProbability::getZero();
385 
386   // Adjust edge probabilities by excluding edges pointing to blocks that is
387   // either not in BlockFilter or is already in the current chain. Consider the
388   // following CFG:
389   //
390   //     --->A
391   //     |  / \
392   //     | B   C
393   //     |  \ / \
394   //     ----D   E
395   //
396   // Assume A->C is very hot (>90%), and C->D has a 50% probability, then after
397   // A->C is chosen as a fall-through, D won't be selected as a successor of C
398   // due to CFG constraint (the probability of C->D is not greater than
399   // HotProb). If we exclude E that is not in BlockFilter when calculating the
400   // probability of C->D, D will be selected and we will get A C D B as the
401   // layout of this loop.
402   auto AdjustedSumProb = BranchProbability::getOne();
403   SmallVector<MachineBasicBlock *, 4> Successors;
404   for (MachineBasicBlock *Succ : BB->successors()) {
405     bool SkipSucc = false;
406     if (BlockFilter && !BlockFilter->count(Succ)) {
407       SkipSucc = true;
408     } else {
409       BlockChain *SuccChain = BlockToChain[Succ];
410       if (SuccChain == &Chain) {
411         SkipSucc = true;
412       } else if (Succ != *SuccChain->begin()) {
413         DEBUG(dbgs() << "    " << getBlockName(Succ) << " -> Mid chain!\n");
414         continue;
415       }
416     }
417     if (SkipSucc)
418       AdjustedSumProb -= MBPI->getEdgeProbability(BB, Succ);
419     else
420       Successors.push_back(Succ);
421   }
422 
423   DEBUG(dbgs() << "Attempting merge from: " << getBlockName(BB) << "\n");
424   for (MachineBasicBlock *Succ : Successors) {
425     BranchProbability SuccProb;
426     uint32_t SuccProbN = MBPI->getEdgeProbability(BB, Succ).getNumerator();
427     uint32_t SuccProbD = AdjustedSumProb.getNumerator();
428     if (SuccProbN >= SuccProbD)
429       SuccProb = BranchProbability::getOne();
430     else
431       SuccProb = BranchProbability(SuccProbN, SuccProbD);
432 
433     // If we outline optional branches, look whether Succ is unavoidable, i.e.
434     // dominates all terminators of the MachineFunction. If it does, other
435     // successors must be optional. Don't do this for cold branches.
436     if (OutlineOptionalBranches && SuccProb > HotProb.getCompl() &&
437         UnavoidableBlocks.count(Succ) > 0) {
438       auto HasShortOptionalBranch = [&]() {
439         for (MachineBasicBlock *Pred : Succ->predecessors()) {
440           // Check whether there is an unplaced optional branch.
441           if (Pred == Succ || (BlockFilter && !BlockFilter->count(Pred)) ||
442               BlockToChain[Pred] == &Chain)
443             continue;
444           // Check whether the optional branch has exactly one BB.
445           if (Pred->pred_size() > 1 || *Pred->pred_begin() != BB)
446             continue;
447           // Check whether the optional branch is small.
448           if (Pred->size() < OutlineOptionalThreshold)
449             return true;
450         }
451         return false;
452       };
453       if (!HasShortOptionalBranch())
454         return Succ;
455     }
456 
457     // Only consider successors which are either "hot", or wouldn't violate
458     // any CFG constraints.
459     BlockChain &SuccChain = *BlockToChain[Succ];
460     if (SuccChain.UnscheduledPredecessors != 0) {
461       if (SuccProb < HotProb) {
462         DEBUG(dbgs() << "    " << getBlockName(Succ) << " -> " << SuccProb
463                      << " (prob) (CFG conflict)\n");
464         continue;
465       }
466 
467       // Make sure that a hot successor doesn't have a globally more
468       // important predecessor.
469       auto RealSuccProb = MBPI->getEdgeProbability(BB, Succ);
470       BlockFrequency CandidateEdgeFreq =
471           MBFI->getBlockFreq(BB) * RealSuccProb * HotProb.getCompl();
472       bool BadCFGConflict = false;
473       for (MachineBasicBlock *Pred : Succ->predecessors()) {
474         if (Pred == Succ || BlockToChain[Pred] == &SuccChain ||
475             (BlockFilter && !BlockFilter->count(Pred)) ||
476             BlockToChain[Pred] == &Chain)
477           continue;
478         BlockFrequency PredEdgeFreq =
479             MBFI->getBlockFreq(Pred) * MBPI->getEdgeProbability(Pred, Succ);
480         if (PredEdgeFreq >= CandidateEdgeFreq) {
481           BadCFGConflict = true;
482           break;
483         }
484       }
485       if (BadCFGConflict) {
486         DEBUG(dbgs() << "    " << getBlockName(Succ) << " -> " << SuccProb
487                      << " (prob) (non-cold CFG conflict)\n");
488         continue;
489       }
490     }
491 
492     DEBUG(dbgs() << "    " << getBlockName(Succ) << " -> " << SuccProb
493                  << " (prob)"
494                  << (SuccChain.UnscheduledPredecessors != 0 ? " (CFG break)" : "")
495                  << "\n");
496     if (BestSucc && BestProb >= SuccProb)
497       continue;
498     BestSucc = Succ;
499     BestProb = SuccProb;
500   }
501   return BestSucc;
502 }
503 
504 /// \brief Select the best block from a worklist.
505 ///
506 /// This looks through the provided worklist as a list of candidate basic
507 /// blocks and select the most profitable one to place. The definition of
508 /// profitable only really makes sense in the context of a loop. This returns
509 /// the most frequently visited block in the worklist, which in the case of
510 /// a loop, is the one most desirable to be physically close to the rest of the
511 /// loop body in order to improve icache behavior.
512 ///
513 /// \returns The best block found, or null if none are viable.
514 MachineBasicBlock *MachineBlockPlacement::selectBestCandidateBlock(
515     BlockChain &Chain, SmallVectorImpl<MachineBasicBlock *> &WorkList,
516     const BlockFilterSet *BlockFilter) {
517   // Once we need to walk the worklist looking for a candidate, cleanup the
518   // worklist of already placed entries.
519   // FIXME: If this shows up on profiles, it could be folded (at the cost of
520   // some code complexity) into the loop below.
521   WorkList.erase(std::remove_if(WorkList.begin(), WorkList.end(),
522                                 [&](MachineBasicBlock *BB) {
523                                   return BlockToChain.lookup(BB) == &Chain;
524                                 }),
525                  WorkList.end());
526 
527   MachineBasicBlock *BestBlock = nullptr;
528   BlockFrequency BestFreq;
529   for (MachineBasicBlock *MBB : WorkList) {
530     BlockChain &SuccChain = *BlockToChain[MBB];
531     if (&SuccChain == &Chain)
532       continue;
533 
534     assert(SuccChain.UnscheduledPredecessors == 0 && "Found CFG-violating block");
535 
536     BlockFrequency CandidateFreq = MBFI->getBlockFreq(MBB);
537     DEBUG(dbgs() << "    " << getBlockName(MBB) << " -> ";
538           MBFI->printBlockFreq(dbgs(), CandidateFreq) << " (freq)\n");
539     if (BestBlock && BestFreq >= CandidateFreq)
540       continue;
541     BestBlock = MBB;
542     BestFreq = CandidateFreq;
543   }
544   return BestBlock;
545 }
546 
547 /// \brief Retrieve the first unplaced basic block.
548 ///
549 /// This routine is called when we are unable to use the CFG to walk through
550 /// all of the basic blocks and form a chain due to unnatural loops in the CFG.
551 /// We walk through the function's blocks in order, starting from the
552 /// LastUnplacedBlockIt. We update this iterator on each call to avoid
553 /// re-scanning the entire sequence on repeated calls to this routine.
554 MachineBasicBlock *MachineBlockPlacement::getFirstUnplacedBlock(
555     MachineFunction &F, const BlockChain &PlacedChain,
556     MachineFunction::iterator &PrevUnplacedBlockIt,
557     const BlockFilterSet *BlockFilter) {
558   for (MachineFunction::iterator I = PrevUnplacedBlockIt, E = F.end(); I != E;
559        ++I) {
560     if (BlockFilter && !BlockFilter->count(&*I))
561       continue;
562     if (BlockToChain[&*I] != &PlacedChain) {
563       PrevUnplacedBlockIt = I;
564       // Now select the head of the chain to which the unplaced block belongs
565       // as the block to place. This will force the entire chain to be placed,
566       // and satisfies the requirements of merging chains.
567       return *BlockToChain[&*I]->begin();
568     }
569   }
570   return nullptr;
571 }
572 
573 void MachineBlockPlacement::buildChain(
574     MachineBasicBlock *BB, BlockChain &Chain,
575     SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
576     const BlockFilterSet *BlockFilter) {
577   assert(BB);
578   assert(BlockToChain[BB] == &Chain);
579   MachineFunction &F = *BB->getParent();
580   MachineFunction::iterator PrevUnplacedBlockIt = F.begin();
581 
582   MachineBasicBlock *LoopHeaderBB = BB;
583   markChainSuccessors(Chain, LoopHeaderBB, BlockWorkList, BlockFilter);
584   BB = *std::prev(Chain.end());
585   for (;;) {
586     assert(BB);
587     assert(BlockToChain[BB] == &Chain);
588     assert(*std::prev(Chain.end()) == BB);
589 
590     // Look for the best viable successor if there is one to place immediately
591     // after this block.
592     MachineBasicBlock *BestSucc = selectBestSuccessor(BB, Chain, BlockFilter);
593 
594     // If an immediate successor isn't available, look for the best viable
595     // block among those we've identified as not violating the loop's CFG at
596     // this point. This won't be a fallthrough, but it will increase locality.
597     if (!BestSucc)
598       BestSucc = selectBestCandidateBlock(Chain, BlockWorkList, BlockFilter);
599 
600     if (!BestSucc) {
601       BestSucc =
602           getFirstUnplacedBlock(F, Chain, PrevUnplacedBlockIt, BlockFilter);
603       if (!BestSucc)
604         break;
605 
606       DEBUG(dbgs() << "Unnatural loop CFG detected, forcibly merging the "
607                       "layout successor until the CFG reduces\n");
608     }
609 
610     // Place this block, updating the datastructures to reflect its placement.
611     BlockChain &SuccChain = *BlockToChain[BestSucc];
612     // Zero out UnscheduledPredecessors for the successor we're about to merge in case
613     // we selected a successor that didn't fit naturally into the CFG.
614     SuccChain.UnscheduledPredecessors = 0;
615     DEBUG(dbgs() << "Merging from " << getBlockName(BB) << " to "
616                  << getBlockName(BestSucc) << "\n");
617     markChainSuccessors(SuccChain, LoopHeaderBB, BlockWorkList, BlockFilter);
618     Chain.merge(BestSucc, &SuccChain);
619     BB = *std::prev(Chain.end());
620   }
621 
622   DEBUG(dbgs() << "Finished forming chain for header block "
623                << getBlockName(*Chain.begin()) << "\n");
624 }
625 
626 /// \brief Find the best loop top block for layout.
627 ///
628 /// Look for a block which is strictly better than the loop header for laying
629 /// out at the top of the loop. This looks for one and only one pattern:
630 /// a latch block with no conditional exit. This block will cause a conditional
631 /// jump around it or will be the bottom of the loop if we lay it out in place,
632 /// but if it it doesn't end up at the bottom of the loop for any reason,
633 /// rotation alone won't fix it. Because such a block will always result in an
634 /// unconditional jump (for the backedge) rotating it in front of the loop
635 /// header is always profitable.
636 MachineBasicBlock *
637 MachineBlockPlacement::findBestLoopTop(MachineLoop &L,
638                                        const BlockFilterSet &LoopBlockSet) {
639   // Check that the header hasn't been fused with a preheader block due to
640   // crazy branches. If it has, we need to start with the header at the top to
641   // prevent pulling the preheader into the loop body.
642   BlockChain &HeaderChain = *BlockToChain[L.getHeader()];
643   if (!LoopBlockSet.count(*HeaderChain.begin()))
644     return L.getHeader();
645 
646   DEBUG(dbgs() << "Finding best loop top for: " << getBlockName(L.getHeader())
647                << "\n");
648 
649   BlockFrequency BestPredFreq;
650   MachineBasicBlock *BestPred = nullptr;
651   for (MachineBasicBlock *Pred : L.getHeader()->predecessors()) {
652     if (!LoopBlockSet.count(Pred))
653       continue;
654     DEBUG(dbgs() << "    header pred: " << getBlockName(Pred) << ", "
655                  << Pred->succ_size() << " successors, ";
656           MBFI->printBlockFreq(dbgs(), Pred) << " freq\n");
657     if (Pred->succ_size() > 1)
658       continue;
659 
660     BlockFrequency PredFreq = MBFI->getBlockFreq(Pred);
661     if (!BestPred || PredFreq > BestPredFreq ||
662         (!(PredFreq < BestPredFreq) &&
663          Pred->isLayoutSuccessor(L.getHeader()))) {
664       BestPred = Pred;
665       BestPredFreq = PredFreq;
666     }
667   }
668 
669   // If no direct predecessor is fine, just use the loop header.
670   if (!BestPred) {
671     DEBUG(dbgs() << "    final top unchanged\n");
672     return L.getHeader();
673   }
674 
675   // Walk backwards through any straight line of predecessors.
676   while (BestPred->pred_size() == 1 &&
677          (*BestPred->pred_begin())->succ_size() == 1 &&
678          *BestPred->pred_begin() != L.getHeader())
679     BestPred = *BestPred->pred_begin();
680 
681   DEBUG(dbgs() << "    final top: " << getBlockName(BestPred) << "\n");
682   return BestPred;
683 }
684 
685 /// \brief Find the best loop exiting block for layout.
686 ///
687 /// This routine implements the logic to analyze the loop looking for the best
688 /// block to layout at the top of the loop. Typically this is done to maximize
689 /// fallthrough opportunities.
690 MachineBasicBlock *
691 MachineBlockPlacement::findBestLoopExit(MachineFunction &F, MachineLoop &L,
692                                         const BlockFilterSet &LoopBlockSet) {
693   // We don't want to layout the loop linearly in all cases. If the loop header
694   // is just a normal basic block in the loop, we want to look for what block
695   // within the loop is the best one to layout at the top. However, if the loop
696   // header has be pre-merged into a chain due to predecessors not having
697   // analyzable branches, *and* the predecessor it is merged with is *not* part
698   // of the loop, rotating the header into the middle of the loop will create
699   // a non-contiguous range of blocks which is Very Bad. So start with the
700   // header and only rotate if safe.
701   BlockChain &HeaderChain = *BlockToChain[L.getHeader()];
702   if (!LoopBlockSet.count(*HeaderChain.begin()))
703     return nullptr;
704 
705   BlockFrequency BestExitEdgeFreq;
706   unsigned BestExitLoopDepth = 0;
707   MachineBasicBlock *ExitingBB = nullptr;
708   // If there are exits to outer loops, loop rotation can severely limit
709   // fallthrough opportunites unless it selects such an exit. Keep a set of
710   // blocks where rotating to exit with that block will reach an outer loop.
711   SmallPtrSet<MachineBasicBlock *, 4> BlocksExitingToOuterLoop;
712 
713   DEBUG(dbgs() << "Finding best loop exit for: " << getBlockName(L.getHeader())
714                << "\n");
715   for (MachineBasicBlock *MBB : L.getBlocks()) {
716     BlockChain &Chain = *BlockToChain[MBB];
717     // Ensure that this block is at the end of a chain; otherwise it could be
718     // mid-way through an inner loop or a successor of an unanalyzable branch.
719     if (MBB != *std::prev(Chain.end()))
720       continue;
721 
722     // Now walk the successors. We need to establish whether this has a viable
723     // exiting successor and whether it has a viable non-exiting successor.
724     // We store the old exiting state and restore it if a viable looping
725     // successor isn't found.
726     MachineBasicBlock *OldExitingBB = ExitingBB;
727     BlockFrequency OldBestExitEdgeFreq = BestExitEdgeFreq;
728     bool HasLoopingSucc = false;
729     for (MachineBasicBlock *Succ : MBB->successors()) {
730       if (Succ->isEHPad())
731         continue;
732       if (Succ == MBB)
733         continue;
734       BlockChain &SuccChain = *BlockToChain[Succ];
735       // Don't split chains, either this chain or the successor's chain.
736       if (&Chain == &SuccChain) {
737         DEBUG(dbgs() << "    exiting: " << getBlockName(MBB) << " -> "
738                      << getBlockName(Succ) << " (chain conflict)\n");
739         continue;
740       }
741 
742       auto SuccProb = MBPI->getEdgeProbability(MBB, Succ);
743       if (LoopBlockSet.count(Succ)) {
744         DEBUG(dbgs() << "    looping: " << getBlockName(MBB) << " -> "
745                      << getBlockName(Succ) << " (" << SuccProb << ")\n");
746         HasLoopingSucc = true;
747         continue;
748       }
749 
750       unsigned SuccLoopDepth = 0;
751       if (MachineLoop *ExitLoop = MLI->getLoopFor(Succ)) {
752         SuccLoopDepth = ExitLoop->getLoopDepth();
753         if (ExitLoop->contains(&L))
754           BlocksExitingToOuterLoop.insert(MBB);
755       }
756 
757       BlockFrequency ExitEdgeFreq = MBFI->getBlockFreq(MBB) * SuccProb;
758       DEBUG(dbgs() << "    exiting: " << getBlockName(MBB) << " -> "
759                    << getBlockName(Succ) << " [L:" << SuccLoopDepth << "] (";
760             MBFI->printBlockFreq(dbgs(), ExitEdgeFreq) << ")\n");
761       // Note that we bias this toward an existing layout successor to retain
762       // incoming order in the absence of better information. The exit must have
763       // a frequency higher than the current exit before we consider breaking
764       // the layout.
765       BranchProbability Bias(100 - ExitBlockBias, 100);
766       if (!ExitingBB || SuccLoopDepth > BestExitLoopDepth ||
767           ExitEdgeFreq > BestExitEdgeFreq ||
768           (MBB->isLayoutSuccessor(Succ) &&
769            !(ExitEdgeFreq < BestExitEdgeFreq * Bias))) {
770         BestExitEdgeFreq = ExitEdgeFreq;
771         ExitingBB = MBB;
772       }
773     }
774 
775     if (!HasLoopingSucc) {
776       // Restore the old exiting state, no viable looping successor was found.
777       ExitingBB = OldExitingBB;
778       BestExitEdgeFreq = OldBestExitEdgeFreq;
779       continue;
780     }
781   }
782   // Without a candidate exiting block or with only a single block in the
783   // loop, just use the loop header to layout the loop.
784   if (!ExitingBB || L.getNumBlocks() == 1)
785     return nullptr;
786 
787   // Also, if we have exit blocks which lead to outer loops but didn't select
788   // one of them as the exiting block we are rotating toward, disable loop
789   // rotation altogether.
790   if (!BlocksExitingToOuterLoop.empty() &&
791       !BlocksExitingToOuterLoop.count(ExitingBB))
792     return nullptr;
793 
794   DEBUG(dbgs() << "  Best exiting block: " << getBlockName(ExitingBB) << "\n");
795   return ExitingBB;
796 }
797 
798 /// \brief Attempt to rotate an exiting block to the bottom of the loop.
799 ///
800 /// Once we have built a chain, try to rotate it to line up the hot exit block
801 /// with fallthrough out of the loop if doing so doesn't introduce unnecessary
802 /// branches. For example, if the loop has fallthrough into its header and out
803 /// of its bottom already, don't rotate it.
804 void MachineBlockPlacement::rotateLoop(BlockChain &LoopChain,
805                                        MachineBasicBlock *ExitingBB,
806                                        const BlockFilterSet &LoopBlockSet) {
807   if (!ExitingBB)
808     return;
809 
810   MachineBasicBlock *Top = *LoopChain.begin();
811   bool ViableTopFallthrough = false;
812   for (MachineBasicBlock *Pred : Top->predecessors()) {
813     BlockChain *PredChain = BlockToChain[Pred];
814     if (!LoopBlockSet.count(Pred) &&
815         (!PredChain || Pred == *std::prev(PredChain->end()))) {
816       ViableTopFallthrough = true;
817       break;
818     }
819   }
820 
821   // If the header has viable fallthrough, check whether the current loop
822   // bottom is a viable exiting block. If so, bail out as rotating will
823   // introduce an unnecessary branch.
824   if (ViableTopFallthrough) {
825     MachineBasicBlock *Bottom = *std::prev(LoopChain.end());
826     for (MachineBasicBlock *Succ : Bottom->successors()) {
827       BlockChain *SuccChain = BlockToChain[Succ];
828       if (!LoopBlockSet.count(Succ) &&
829           (!SuccChain || Succ == *SuccChain->begin()))
830         return;
831     }
832   }
833 
834   BlockChain::iterator ExitIt =
835       std::find(LoopChain.begin(), LoopChain.end(), ExitingBB);
836   if (ExitIt == LoopChain.end())
837     return;
838 
839   std::rotate(LoopChain.begin(), std::next(ExitIt), LoopChain.end());
840 }
841 
842 /// \brief Attempt to rotate a loop based on profile data to reduce branch cost.
843 ///
844 /// With profile data, we can determine the cost in terms of missed fall through
845 /// opportunities when rotating a loop chain and select the best rotation.
846 /// Basically, there are three kinds of cost to consider for each rotation:
847 ///    1. The possibly missed fall through edge (if it exists) from BB out of
848 ///    the loop to the loop header.
849 ///    2. The possibly missed fall through edges (if they exist) from the loop
850 ///    exits to BB out of the loop.
851 ///    3. The missed fall through edge (if it exists) from the last BB to the
852 ///    first BB in the loop chain.
853 ///  Therefore, the cost for a given rotation is the sum of costs listed above.
854 ///  We select the best rotation with the smallest cost.
855 void MachineBlockPlacement::rotateLoopWithProfile(
856     BlockChain &LoopChain, MachineLoop &L, const BlockFilterSet &LoopBlockSet) {
857   auto HeaderBB = L.getHeader();
858   auto HeaderIter = std::find(LoopChain.begin(), LoopChain.end(), HeaderBB);
859   auto RotationPos = LoopChain.end();
860 
861   BlockFrequency SmallestRotationCost = BlockFrequency::getMaxFrequency();
862 
863   // A utility lambda that scales up a block frequency by dividing it by a
864   // branch probability which is the reciprocal of the scale.
865   auto ScaleBlockFrequency = [](BlockFrequency Freq,
866                                 unsigned Scale) -> BlockFrequency {
867     if (Scale == 0)
868       return 0;
869     // Use operator / between BlockFrequency and BranchProbability to implement
870     // saturating multiplication.
871     return Freq / BranchProbability(1, Scale);
872   };
873 
874   // Compute the cost of the missed fall-through edge to the loop header if the
875   // chain head is not the loop header. As we only consider natural loops with
876   // single header, this computation can be done only once.
877   BlockFrequency HeaderFallThroughCost(0);
878   for (auto *Pred : HeaderBB->predecessors()) {
879     BlockChain *PredChain = BlockToChain[Pred];
880     if (!LoopBlockSet.count(Pred) &&
881         (!PredChain || Pred == *std::prev(PredChain->end()))) {
882       auto EdgeFreq =
883           MBFI->getBlockFreq(Pred) * MBPI->getEdgeProbability(Pred, HeaderBB);
884       auto FallThruCost = ScaleBlockFrequency(EdgeFreq, MisfetchCost);
885       // If the predecessor has only an unconditional jump to the header, we
886       // need to consider the cost of this jump.
887       if (Pred->succ_size() == 1)
888         FallThruCost += ScaleBlockFrequency(EdgeFreq, JumpInstCost);
889       HeaderFallThroughCost = std::max(HeaderFallThroughCost, FallThruCost);
890     }
891   }
892 
893   // Here we collect all exit blocks in the loop, and for each exit we find out
894   // its hottest exit edge. For each loop rotation, we define the loop exit cost
895   // as the sum of frequencies of exit edges we collect here, excluding the exit
896   // edge from the tail of the loop chain.
897   SmallVector<std::pair<MachineBasicBlock *, BlockFrequency>, 4> ExitsWithFreq;
898   for (auto BB : LoopChain) {
899     auto LargestExitEdgeProb = BranchProbability::getZero();
900     for (auto *Succ : BB->successors()) {
901       BlockChain *SuccChain = BlockToChain[Succ];
902       if (!LoopBlockSet.count(Succ) &&
903           (!SuccChain || Succ == *SuccChain->begin())) {
904         auto SuccProb = MBPI->getEdgeProbability(BB, Succ);
905         LargestExitEdgeProb = std::max(LargestExitEdgeProb, SuccProb);
906       }
907     }
908     if (LargestExitEdgeProb > BranchProbability::getZero()) {
909       auto ExitFreq = MBFI->getBlockFreq(BB) * LargestExitEdgeProb;
910       ExitsWithFreq.emplace_back(BB, ExitFreq);
911     }
912   }
913 
914   // In this loop we iterate every block in the loop chain and calculate the
915   // cost assuming the block is the head of the loop chain. When the loop ends,
916   // we should have found the best candidate as the loop chain's head.
917   for (auto Iter = LoopChain.begin(), TailIter = std::prev(LoopChain.end()),
918             EndIter = LoopChain.end();
919        Iter != EndIter; Iter++, TailIter++) {
920     // TailIter is used to track the tail of the loop chain if the block we are
921     // checking (pointed by Iter) is the head of the chain.
922     if (TailIter == LoopChain.end())
923       TailIter = LoopChain.begin();
924 
925     auto TailBB = *TailIter;
926 
927     // Calculate the cost by putting this BB to the top.
928     BlockFrequency Cost = 0;
929 
930     // If the current BB is the loop header, we need to take into account the
931     // cost of the missed fall through edge from outside of the loop to the
932     // header.
933     if (Iter != HeaderIter)
934       Cost += HeaderFallThroughCost;
935 
936     // Collect the loop exit cost by summing up frequencies of all exit edges
937     // except the one from the chain tail.
938     for (auto &ExitWithFreq : ExitsWithFreq)
939       if (TailBB != ExitWithFreq.first)
940         Cost += ExitWithFreq.second;
941 
942     // The cost of breaking the once fall-through edge from the tail to the top
943     // of the loop chain. Here we need to consider three cases:
944     // 1. If the tail node has only one successor, then we will get an
945     //    additional jmp instruction. So the cost here is (MisfetchCost +
946     //    JumpInstCost) * tail node frequency.
947     // 2. If the tail node has two successors, then we may still get an
948     //    additional jmp instruction if the layout successor after the loop
949     //    chain is not its CFG successor. Note that the more frequently executed
950     //    jmp instruction will be put ahead of the other one. Assume the
951     //    frequency of those two branches are x and y, where x is the frequency
952     //    of the edge to the chain head, then the cost will be
953     //    (x * MisfetechCost + min(x, y) * JumpInstCost) * tail node frequency.
954     // 3. If the tail node has more than two successors (this rarely happens),
955     //    we won't consider any additional cost.
956     if (TailBB->isSuccessor(*Iter)) {
957       auto TailBBFreq = MBFI->getBlockFreq(TailBB);
958       if (TailBB->succ_size() == 1)
959         Cost += ScaleBlockFrequency(TailBBFreq.getFrequency(),
960                                     MisfetchCost + JumpInstCost);
961       else if (TailBB->succ_size() == 2) {
962         auto TailToHeadProb = MBPI->getEdgeProbability(TailBB, *Iter);
963         auto TailToHeadFreq = TailBBFreq * TailToHeadProb;
964         auto ColderEdgeFreq = TailToHeadProb > BranchProbability(1, 2)
965                                   ? TailBBFreq * TailToHeadProb.getCompl()
966                                   : TailToHeadFreq;
967         Cost += ScaleBlockFrequency(TailToHeadFreq, MisfetchCost) +
968                 ScaleBlockFrequency(ColderEdgeFreq, JumpInstCost);
969       }
970     }
971 
972     DEBUG(dbgs() << "The cost of loop rotation by making " << getBlockName(*Iter)
973                  << " to the top: " << Cost.getFrequency() << "\n");
974 
975     if (Cost < SmallestRotationCost) {
976       SmallestRotationCost = Cost;
977       RotationPos = Iter;
978     }
979   }
980 
981   if (RotationPos != LoopChain.end()) {
982     DEBUG(dbgs() << "Rotate loop by making " << getBlockName(*RotationPos)
983                  << " to the top\n");
984     std::rotate(LoopChain.begin(), RotationPos, LoopChain.end());
985   }
986 }
987 
988 /// \brief Collect blocks in the given loop that are to be placed.
989 ///
990 /// When profile data is available, exclude cold blocks from the returned set;
991 /// otherwise, collect all blocks in the loop.
992 MachineBlockPlacement::BlockFilterSet
993 MachineBlockPlacement::collectLoopBlockSet(MachineFunction &F, MachineLoop &L) {
994   BlockFilterSet LoopBlockSet;
995 
996   // Filter cold blocks off from LoopBlockSet when profile data is available.
997   // Collect the sum of frequencies of incoming edges to the loop header from
998   // outside. If we treat the loop as a super block, this is the frequency of
999   // the loop. Then for each block in the loop, we calculate the ratio between
1000   // its frequency and the frequency of the loop block. When it is too small,
1001   // don't add it to the loop chain. If there are outer loops, then this block
1002   // will be merged into the first outer loop chain for which this block is not
1003   // cold anymore. This needs precise profile data and we only do this when
1004   // profile data is available.
1005   if (F.getFunction()->getEntryCount()) {
1006     BlockFrequency LoopFreq(0);
1007     for (auto LoopPred : L.getHeader()->predecessors())
1008       if (!L.contains(LoopPred))
1009         LoopFreq += MBFI->getBlockFreq(LoopPred) *
1010                     MBPI->getEdgeProbability(LoopPred, L.getHeader());
1011 
1012     for (MachineBasicBlock *LoopBB : L.getBlocks()) {
1013       auto Freq = MBFI->getBlockFreq(LoopBB).getFrequency();
1014       if (Freq == 0 || LoopFreq.getFrequency() / Freq > LoopToColdBlockRatio)
1015         continue;
1016       LoopBlockSet.insert(LoopBB);
1017     }
1018   } else
1019     LoopBlockSet.insert(L.block_begin(), L.block_end());
1020 
1021   return LoopBlockSet;
1022 }
1023 
1024 /// \brief Forms basic block chains from the natural loop structures.
1025 ///
1026 /// These chains are designed to preserve the existing *structure* of the code
1027 /// as much as possible. We can then stitch the chains together in a way which
1028 /// both preserves the topological structure and minimizes taken conditional
1029 /// branches.
1030 void MachineBlockPlacement::buildLoopChains(MachineFunction &F,
1031                                             MachineLoop &L) {
1032   // First recurse through any nested loops, building chains for those inner
1033   // loops.
1034   for (MachineLoop *InnerLoop : L)
1035     buildLoopChains(F, *InnerLoop);
1036 
1037   SmallVector<MachineBasicBlock *, 16> BlockWorkList;
1038   BlockFilterSet LoopBlockSet = collectLoopBlockSet(F, L);
1039 
1040   // Check if we have profile data for this function. If yes, we will rotate
1041   // this loop by modeling costs more precisely which requires the profile data
1042   // for better layout.
1043   bool RotateLoopWithProfile =
1044       PreciseRotationCost && F.getFunction()->getEntryCount();
1045 
1046   // First check to see if there is an obviously preferable top block for the
1047   // loop. This will default to the header, but may end up as one of the
1048   // predecessors to the header if there is one which will result in strictly
1049   // fewer branches in the loop body.
1050   // When we use profile data to rotate the loop, this is unnecessary.
1051   MachineBasicBlock *LoopTop =
1052       RotateLoopWithProfile ? L.getHeader() : findBestLoopTop(L, LoopBlockSet);
1053 
1054   // If we selected just the header for the loop top, look for a potentially
1055   // profitable exit block in the event that rotating the loop can eliminate
1056   // branches by placing an exit edge at the bottom.
1057   MachineBasicBlock *ExitingBB = nullptr;
1058   if (!RotateLoopWithProfile && LoopTop == L.getHeader())
1059     ExitingBB = findBestLoopExit(F, L, LoopBlockSet);
1060 
1061   BlockChain &LoopChain = *BlockToChain[LoopTop];
1062 
1063   // FIXME: This is a really lame way of walking the chains in the loop: we
1064   // walk the blocks, and use a set to prevent visiting a particular chain
1065   // twice.
1066   SmallPtrSet<BlockChain *, 4> UpdatedPreds;
1067   assert(LoopChain.UnscheduledPredecessors == 0);
1068   UpdatedPreds.insert(&LoopChain);
1069 
1070   for (MachineBasicBlock *LoopBB : LoopBlockSet) {
1071     BlockChain &Chain = *BlockToChain[LoopBB];
1072     if (!UpdatedPreds.insert(&Chain).second)
1073       continue;
1074 
1075     assert(Chain.UnscheduledPredecessors == 0);
1076     for (MachineBasicBlock *ChainBB : Chain) {
1077       assert(BlockToChain[ChainBB] == &Chain);
1078       for (MachineBasicBlock *Pred : ChainBB->predecessors()) {
1079         if (BlockToChain[Pred] == &Chain || !LoopBlockSet.count(Pred))
1080           continue;
1081         ++Chain.UnscheduledPredecessors;
1082       }
1083     }
1084 
1085     if (Chain.UnscheduledPredecessors == 0)
1086       BlockWorkList.push_back(*Chain.begin());
1087   }
1088 
1089   buildChain(LoopTop, LoopChain, BlockWorkList, &LoopBlockSet);
1090 
1091   if (RotateLoopWithProfile)
1092     rotateLoopWithProfile(LoopChain, L, LoopBlockSet);
1093   else
1094     rotateLoop(LoopChain, ExitingBB, LoopBlockSet);
1095 
1096   DEBUG({
1097     // Crash at the end so we get all of the debugging output first.
1098     bool BadLoop = false;
1099     if (LoopChain.UnscheduledPredecessors) {
1100       BadLoop = true;
1101       dbgs() << "Loop chain contains a block without its preds placed!\n"
1102              << "  Loop header:  " << getBlockName(*L.block_begin()) << "\n"
1103              << "  Chain header: " << getBlockName(*LoopChain.begin()) << "\n";
1104     }
1105     for (MachineBasicBlock *ChainBB : LoopChain) {
1106       dbgs() << "          ... " << getBlockName(ChainBB) << "\n";
1107       if (!LoopBlockSet.erase(ChainBB)) {
1108         // We don't mark the loop as bad here because there are real situations
1109         // where this can occur. For example, with an unanalyzable fallthrough
1110         // from a loop block to a non-loop block or vice versa.
1111         dbgs() << "Loop chain contains a block not contained by the loop!\n"
1112                << "  Loop header:  " << getBlockName(*L.block_begin()) << "\n"
1113                << "  Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
1114                << "  Bad block:    " << getBlockName(ChainBB) << "\n";
1115       }
1116     }
1117 
1118     if (!LoopBlockSet.empty()) {
1119       BadLoop = true;
1120       for (MachineBasicBlock *LoopBB : LoopBlockSet)
1121         dbgs() << "Loop contains blocks never placed into a chain!\n"
1122                << "  Loop header:  " << getBlockName(*L.block_begin()) << "\n"
1123                << "  Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
1124                << "  Bad block:    " << getBlockName(LoopBB) << "\n";
1125     }
1126     assert(!BadLoop && "Detected problems with the placement of this loop.");
1127   });
1128 }
1129 
1130 void MachineBlockPlacement::buildCFGChains(MachineFunction &F) {
1131   // Ensure that every BB in the function has an associated chain to simplify
1132   // the assumptions of the remaining algorithm.
1133   SmallVector<MachineOperand, 4> Cond; // For AnalyzeBranch.
1134   for (MachineFunction::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
1135     MachineBasicBlock *BB = &*FI;
1136     BlockChain *Chain =
1137         new (ChainAllocator.Allocate()) BlockChain(BlockToChain, BB);
1138     // Also, merge any blocks which we cannot reason about and must preserve
1139     // the exact fallthrough behavior for.
1140     for (;;) {
1141       Cond.clear();
1142       MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
1143       if (!TII->AnalyzeBranch(*BB, TBB, FBB, Cond) || !FI->canFallThrough())
1144         break;
1145 
1146       MachineFunction::iterator NextFI = std::next(FI);
1147       MachineBasicBlock *NextBB = &*NextFI;
1148       // Ensure that the layout successor is a viable block, as we know that
1149       // fallthrough is a possibility.
1150       assert(NextFI != FE && "Can't fallthrough past the last block.");
1151       DEBUG(dbgs() << "Pre-merging due to unanalyzable fallthrough: "
1152                    << getBlockName(BB) << " -> " << getBlockName(NextBB)
1153                    << "\n");
1154       Chain->merge(NextBB, nullptr);
1155       FI = NextFI;
1156       BB = NextBB;
1157     }
1158   }
1159 
1160   if (OutlineOptionalBranches) {
1161     // Find the nearest common dominator of all of F's terminators.
1162     MachineBasicBlock *Terminator = nullptr;
1163     for (MachineBasicBlock &MBB : F) {
1164       if (MBB.succ_size() == 0) {
1165         if (Terminator == nullptr)
1166           Terminator = &MBB;
1167         else
1168           Terminator = MDT->findNearestCommonDominator(Terminator, &MBB);
1169       }
1170     }
1171 
1172     // MBBs dominating this common dominator are unavoidable.
1173     UnavoidableBlocks.clear();
1174     for (MachineBasicBlock &MBB : F) {
1175       if (MDT->dominates(&MBB, Terminator)) {
1176         UnavoidableBlocks.insert(&MBB);
1177       }
1178     }
1179   }
1180 
1181   // Build any loop-based chains.
1182   for (MachineLoop *L : *MLI)
1183     buildLoopChains(F, *L);
1184 
1185   SmallVector<MachineBasicBlock *, 16> BlockWorkList;
1186 
1187   SmallPtrSet<BlockChain *, 4> UpdatedPreds;
1188   for (MachineBasicBlock &MBB : F) {
1189     BlockChain &Chain = *BlockToChain[&MBB];
1190     if (!UpdatedPreds.insert(&Chain).second)
1191       continue;
1192 
1193     assert(Chain.UnscheduledPredecessors == 0);
1194     for (MachineBasicBlock *ChainBB : Chain) {
1195       assert(BlockToChain[ChainBB] == &Chain);
1196       for (MachineBasicBlock *Pred : ChainBB->predecessors()) {
1197         if (BlockToChain[Pred] == &Chain)
1198           continue;
1199         ++Chain.UnscheduledPredecessors;
1200       }
1201     }
1202 
1203     if (Chain.UnscheduledPredecessors == 0)
1204       BlockWorkList.push_back(*Chain.begin());
1205   }
1206 
1207   BlockChain &FunctionChain = *BlockToChain[&F.front()];
1208   buildChain(&F.front(), FunctionChain, BlockWorkList);
1209 
1210 #ifndef NDEBUG
1211   typedef SmallPtrSet<MachineBasicBlock *, 16> FunctionBlockSetType;
1212 #endif
1213   DEBUG({
1214     // Crash at the end so we get all of the debugging output first.
1215     bool BadFunc = false;
1216     FunctionBlockSetType FunctionBlockSet;
1217     for (MachineBasicBlock &MBB : F)
1218       FunctionBlockSet.insert(&MBB);
1219 
1220     for (MachineBasicBlock *ChainBB : FunctionChain)
1221       if (!FunctionBlockSet.erase(ChainBB)) {
1222         BadFunc = true;
1223         dbgs() << "Function chain contains a block not in the function!\n"
1224                << "  Bad block:    " << getBlockName(ChainBB) << "\n";
1225       }
1226 
1227     if (!FunctionBlockSet.empty()) {
1228       BadFunc = true;
1229       for (MachineBasicBlock *RemainingBB : FunctionBlockSet)
1230         dbgs() << "Function contains blocks never placed into a chain!\n"
1231                << "  Bad block:    " << getBlockName(RemainingBB) << "\n";
1232     }
1233     assert(!BadFunc && "Detected problems with the block placement.");
1234   });
1235 
1236   // Splice the blocks into place.
1237   MachineFunction::iterator InsertPos = F.begin();
1238   for (MachineBasicBlock *ChainBB : FunctionChain) {
1239     DEBUG(dbgs() << (ChainBB == *FunctionChain.begin() ? "Placing chain "
1240                                                        : "          ... ")
1241                  << getBlockName(ChainBB) << "\n");
1242     if (InsertPos != MachineFunction::iterator(ChainBB))
1243       F.splice(InsertPos, ChainBB);
1244     else
1245       ++InsertPos;
1246 
1247     // Update the terminator of the previous block.
1248     if (ChainBB == *FunctionChain.begin())
1249       continue;
1250     MachineBasicBlock *PrevBB = &*std::prev(MachineFunction::iterator(ChainBB));
1251 
1252     // FIXME: It would be awesome of updateTerminator would just return rather
1253     // than assert when the branch cannot be analyzed in order to remove this
1254     // boiler plate.
1255     Cond.clear();
1256     MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
1257     if (!TII->AnalyzeBranch(*PrevBB, TBB, FBB, Cond)) {
1258       // The "PrevBB" is not yet updated to reflect current code layout, so,
1259       //   o. it may fall-through to a block without explict "goto" instruction
1260       //      before layout, and no longer fall-through it after layout; or
1261       //   o. just opposite.
1262       //
1263       // AnalyzeBranch() may return erroneous value for FBB when these two
1264       // situations take place. For the first scenario FBB is mistakenly set
1265       // NULL; for the 2nd scenario, the FBB, which is expected to be NULL,
1266       // is mistakenly pointing to "*BI".
1267       //
1268       bool needUpdateBr = true;
1269       if (!Cond.empty() && (!FBB || FBB == ChainBB)) {
1270         PrevBB->updateTerminator();
1271         needUpdateBr = false;
1272         Cond.clear();
1273         TBB = FBB = nullptr;
1274         if (TII->AnalyzeBranch(*PrevBB, TBB, FBB, Cond)) {
1275           // FIXME: This should never take place.
1276           TBB = FBB = nullptr;
1277         }
1278       }
1279 
1280       // If PrevBB has a two-way branch, try to re-order the branches
1281       // such that we branch to the successor with higher probability first.
1282       if (TBB && !Cond.empty() && FBB &&
1283           MBPI->getEdgeProbability(PrevBB, FBB) >
1284               MBPI->getEdgeProbability(PrevBB, TBB) &&
1285           !TII->ReverseBranchCondition(Cond)) {
1286         DEBUG(dbgs() << "Reverse order of the two branches: "
1287                      << getBlockName(PrevBB) << "\n");
1288         DEBUG(dbgs() << "    Edge probability: "
1289                      << MBPI->getEdgeProbability(PrevBB, FBB) << " vs "
1290                      << MBPI->getEdgeProbability(PrevBB, TBB) << "\n");
1291         DebugLoc dl; // FIXME: this is nowhere
1292         TII->RemoveBranch(*PrevBB);
1293         TII->InsertBranch(*PrevBB, FBB, TBB, Cond, dl);
1294         needUpdateBr = true;
1295       }
1296       if (needUpdateBr)
1297         PrevBB->updateTerminator();
1298     }
1299   }
1300 
1301   // Fixup the last block.
1302   Cond.clear();
1303   MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
1304   if (!TII->AnalyzeBranch(F.back(), TBB, FBB, Cond))
1305     F.back().updateTerminator();
1306 
1307   // Walk through the backedges of the function now that we have fully laid out
1308   // the basic blocks and align the destination of each backedge. We don't rely
1309   // exclusively on the loop info here so that we can align backedges in
1310   // unnatural CFGs and backedges that were introduced purely because of the
1311   // loop rotations done during this layout pass.
1312   // FIXME: Use Function::optForSize().
1313   if (F.getFunction()->hasFnAttribute(Attribute::OptimizeForSize))
1314     return;
1315   if (FunctionChain.begin() == FunctionChain.end())
1316     return; // Empty chain.
1317 
1318   const BranchProbability ColdProb(1, 5); // 20%
1319   BlockFrequency EntryFreq = MBFI->getBlockFreq(&F.front());
1320   BlockFrequency WeightedEntryFreq = EntryFreq * ColdProb;
1321   for (MachineBasicBlock *ChainBB : FunctionChain) {
1322     if (ChainBB == *FunctionChain.begin())
1323       continue;
1324 
1325     // Don't align non-looping basic blocks. These are unlikely to execute
1326     // enough times to matter in practice. Note that we'll still handle
1327     // unnatural CFGs inside of a natural outer loop (the common case) and
1328     // rotated loops.
1329     MachineLoop *L = MLI->getLoopFor(ChainBB);
1330     if (!L)
1331       continue;
1332 
1333     unsigned Align = TLI->getPrefLoopAlignment(L);
1334     if (!Align)
1335       continue; // Don't care about loop alignment.
1336 
1337     // If the block is cold relative to the function entry don't waste space
1338     // aligning it.
1339     BlockFrequency Freq = MBFI->getBlockFreq(ChainBB);
1340     if (Freq < WeightedEntryFreq)
1341       continue;
1342 
1343     // If the block is cold relative to its loop header, don't align it
1344     // regardless of what edges into the block exist.
1345     MachineBasicBlock *LoopHeader = L->getHeader();
1346     BlockFrequency LoopHeaderFreq = MBFI->getBlockFreq(LoopHeader);
1347     if (Freq < (LoopHeaderFreq * ColdProb))
1348       continue;
1349 
1350     // Check for the existence of a non-layout predecessor which would benefit
1351     // from aligning this block.
1352     MachineBasicBlock *LayoutPred =
1353         &*std::prev(MachineFunction::iterator(ChainBB));
1354 
1355     // Force alignment if all the predecessors are jumps. We already checked
1356     // that the block isn't cold above.
1357     if (!LayoutPred->isSuccessor(ChainBB)) {
1358       ChainBB->setAlignment(Align);
1359       continue;
1360     }
1361 
1362     // Align this block if the layout predecessor's edge into this block is
1363     // cold relative to the block. When this is true, other predecessors make up
1364     // all of the hot entries into the block and thus alignment is likely to be
1365     // important.
1366     BranchProbability LayoutProb =
1367         MBPI->getEdgeProbability(LayoutPred, ChainBB);
1368     BlockFrequency LayoutEdgeFreq = MBFI->getBlockFreq(LayoutPred) * LayoutProb;
1369     if (LayoutEdgeFreq <= (Freq * ColdProb))
1370       ChainBB->setAlignment(Align);
1371   }
1372 }
1373 
1374 bool MachineBlockPlacement::runOnMachineFunction(MachineFunction &F) {
1375   // Check for single-block functions and skip them.
1376   if (std::next(F.begin()) == F.end())
1377     return false;
1378 
1379   if (skipOptnoneFunction(*F.getFunction()))
1380     return false;
1381 
1382   MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
1383   MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
1384   MLI = &getAnalysis<MachineLoopInfo>();
1385   TII = F.getSubtarget().getInstrInfo();
1386   TLI = F.getSubtarget().getTargetLowering();
1387   MDT = &getAnalysis<MachineDominatorTree>();
1388   assert(BlockToChain.empty());
1389 
1390   buildCFGChains(F);
1391 
1392   BlockToChain.clear();
1393   ChainAllocator.DestroyAll();
1394 
1395   if (AlignAllBlock)
1396     // Align all of the blocks in the function to a specific alignment.
1397     for (MachineBasicBlock &MBB : F)
1398       MBB.setAlignment(AlignAllBlock);
1399   else if (AlignAllNonFallThruBlocks) {
1400     // Align all of the blocks that have no fall-through predecessors to a
1401     // specific alignment.
1402     for (auto MBI = std::next(F.begin()), MBE = F.end(); MBI != MBE; ++MBI) {
1403       auto LayoutPred = std::prev(MBI);
1404       if (!LayoutPred->isSuccessor(&*MBI))
1405         MBI->setAlignment(AlignAllNonFallThruBlocks);
1406     }
1407   }
1408 
1409   // We always return true as we have no way to track whether the final order
1410   // differs from the original order.
1411   return true;
1412 }
1413 
1414 namespace {
1415 /// \brief A pass to compute block placement statistics.
1416 ///
1417 /// A separate pass to compute interesting statistics for evaluating block
1418 /// placement. This is separate from the actual placement pass so that they can
1419 /// be computed in the absence of any placement transformations or when using
1420 /// alternative placement strategies.
1421 class MachineBlockPlacementStats : public MachineFunctionPass {
1422   /// \brief A handle to the branch probability pass.
1423   const MachineBranchProbabilityInfo *MBPI;
1424 
1425   /// \brief A handle to the function-wide block frequency pass.
1426   const MachineBlockFrequencyInfo *MBFI;
1427 
1428 public:
1429   static char ID; // Pass identification, replacement for typeid
1430   MachineBlockPlacementStats() : MachineFunctionPass(ID) {
1431     initializeMachineBlockPlacementStatsPass(*PassRegistry::getPassRegistry());
1432   }
1433 
1434   bool runOnMachineFunction(MachineFunction &F) override;
1435 
1436   void getAnalysisUsage(AnalysisUsage &AU) const override {
1437     AU.addRequired<MachineBranchProbabilityInfo>();
1438     AU.addRequired<MachineBlockFrequencyInfo>();
1439     AU.setPreservesAll();
1440     MachineFunctionPass::getAnalysisUsage(AU);
1441   }
1442 };
1443 }
1444 
1445 char MachineBlockPlacementStats::ID = 0;
1446 char &llvm::MachineBlockPlacementStatsID = MachineBlockPlacementStats::ID;
1447 INITIALIZE_PASS_BEGIN(MachineBlockPlacementStats, "block-placement-stats",
1448                       "Basic Block Placement Stats", false, false)
1449 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
1450 INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
1451 INITIALIZE_PASS_END(MachineBlockPlacementStats, "block-placement-stats",
1452                     "Basic Block Placement Stats", false, false)
1453 
1454 bool MachineBlockPlacementStats::runOnMachineFunction(MachineFunction &F) {
1455   // Check for single-block functions and skip them.
1456   if (std::next(F.begin()) == F.end())
1457     return false;
1458 
1459   MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
1460   MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
1461 
1462   for (MachineBasicBlock &MBB : F) {
1463     BlockFrequency BlockFreq = MBFI->getBlockFreq(&MBB);
1464     Statistic &NumBranches =
1465         (MBB.succ_size() > 1) ? NumCondBranches : NumUncondBranches;
1466     Statistic &BranchTakenFreq =
1467         (MBB.succ_size() > 1) ? CondBranchTakenFreq : UncondBranchTakenFreq;
1468     for (MachineBasicBlock *Succ : MBB.successors()) {
1469       // Skip if this successor is a fallthrough.
1470       if (MBB.isLayoutSuccessor(Succ))
1471         continue;
1472 
1473       BlockFrequency EdgeFreq =
1474           BlockFreq * MBPI->getEdgeProbability(&MBB, Succ);
1475       ++NumBranches;
1476       BranchTakenFreq += EdgeFreq.getFrequency();
1477     }
1478   }
1479 
1480   return false;
1481 }
1482