e022c7bd0d0f5b97106e53dfbbddda0e206c40c7
[oota-llvm.git] / lib / CodeGen / MachineBlockPlacement.cpp
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/Target/TargetInstrInfo.h"
45 #include "llvm/Target/TargetLowering.h"
46 #include "llvm/Target/TargetSubtargetInfo.h"
47 #include <algorithm>
48 using namespace llvm;
49
50 #define DEBUG_TYPE "block-placement"
51
52 STATISTIC(NumCondBranches, "Number of conditional branches");
53 STATISTIC(NumUncondBranches, "Number of uncondittional branches");
54 STATISTIC(CondBranchTakenFreq,
55           "Potential frequency of taking conditional branches");
56 STATISTIC(UncondBranchTakenFreq,
57           "Potential frequency of taking unconditional branches");
58
59 static cl::opt<unsigned> AlignAllBlock("align-all-blocks",
60                                        cl::desc("Force the alignment of all "
61                                                 "blocks in the function."),
62                                        cl::init(0), cl::Hidden);
63
64 // FIXME: Find a good default for this flag and remove the flag.
65 static cl::opt<unsigned>
66 ExitBlockBias("block-placement-exit-block-bias",
67               cl::desc("Block frequency percentage a loop exit block needs "
68                        "over the original exit to be considered the new exit."),
69               cl::init(0), cl::Hidden);
70
71 static cl::opt<bool> OutlineOptionalBranches(
72     "outline-optional-branches",
73     cl::desc("Put completely optional branches, i.e. branches with a common "
74              "post dominator, out of line."),
75     cl::init(false), cl::Hidden);
76
77 namespace {
78 class BlockChain;
79 /// \brief Type for our function-wide basic block -> block chain mapping.
80 typedef DenseMap<MachineBasicBlock *, BlockChain *> BlockToChainMapType;
81 }
82
83 namespace {
84 /// \brief A chain of blocks which will be laid out contiguously.
85 ///
86 /// This is the datastructure representing a chain of consecutive blocks that
87 /// are profitable to layout together in order to maximize fallthrough
88 /// probabilities and code locality. We also can use a block chain to represent
89 /// a sequence of basic blocks which have some external (correctness)
90 /// requirement for sequential layout.
91 ///
92 /// Chains can be built around a single basic block and can be merged to grow
93 /// them. They participate in a block-to-chain mapping, which is updated
94 /// automatically as chains are merged together.
95 class BlockChain {
96   /// \brief The sequence of blocks belonging to this chain.
97   ///
98   /// This is the sequence of blocks for a particular chain. These will be laid
99   /// out in-order within the function.
100   SmallVector<MachineBasicBlock *, 4> Blocks;
101
102   /// \brief A handle to the function-wide basic block to block chain mapping.
103   ///
104   /// This is retained in each block chain to simplify the computation of child
105   /// block chains for SCC-formation and iteration. We store the edges to child
106   /// basic blocks, and map them back to their associated chains using this
107   /// structure.
108   BlockToChainMapType &BlockToChain;
109
110 public:
111   /// \brief Construct a new BlockChain.
112   ///
113   /// This builds a new block chain representing a single basic block in the
114   /// function. It also registers itself as the chain that block participates
115   /// in with the BlockToChain mapping.
116   BlockChain(BlockToChainMapType &BlockToChain, MachineBasicBlock *BB)
117     : Blocks(1, BB), BlockToChain(BlockToChain), LoopPredecessors(0) {
118     assert(BB && "Cannot create a chain with a null basic block");
119     BlockToChain[BB] = this;
120   }
121
122   /// \brief Iterator over blocks within the chain.
123   typedef SmallVectorImpl<MachineBasicBlock *>::iterator iterator;
124
125   /// \brief Beginning of blocks within the chain.
126   iterator begin() { return Blocks.begin(); }
127
128   /// \brief End of blocks within the chain.
129   iterator end() { return Blocks.end(); }
130
131   /// \brief Merge a block chain into this one.
132   ///
133   /// This routine merges a block chain into this one. It takes care of forming
134   /// a contiguous sequence of basic blocks, updating the edge list, and
135   /// updating the block -> chain mapping. It does not free or tear down the
136   /// old chain, but the old chain's block list is no longer valid.
137   void merge(MachineBasicBlock *BB, BlockChain *Chain) {
138     assert(BB);
139     assert(!Blocks.empty());
140
141     // Fast path in case we don't have a chain already.
142     if (!Chain) {
143       assert(!BlockToChain[BB]);
144       Blocks.push_back(BB);
145       BlockToChain[BB] = this;
146       return;
147     }
148
149     assert(BB == *Chain->begin());
150     assert(Chain->begin() != Chain->end());
151
152     // Update the incoming blocks to point to this chain, and add them to the
153     // chain structure.
154     for (BlockChain::iterator BI = Chain->begin(), BE = Chain->end();
155          BI != BE; ++BI) {
156       Blocks.push_back(*BI);
157       assert(BlockToChain[*BI] == Chain && "Incoming blocks not in chain");
158       BlockToChain[*BI] = this;
159     }
160   }
161
162 #ifndef NDEBUG
163   /// \brief Dump the blocks in this chain.
164   LLVM_DUMP_METHOD void dump() {
165     for (iterator I = begin(), E = end(); I != E; ++I)
166       (*I)->dump();
167   }
168 #endif // NDEBUG
169
170   /// \brief Count of predecessors within the loop currently being processed.
171   ///
172   /// This count is updated at each loop we process to represent the number of
173   /// in-loop predecessors of this chain.
174   unsigned LoopPredecessors;
175 };
176 }
177
178 namespace {
179 class MachineBlockPlacement : public MachineFunctionPass {
180   /// \brief A typedef for a block filter set.
181   typedef SmallPtrSet<MachineBasicBlock *, 16> BlockFilterSet;
182
183   /// \brief A handle to the branch probability pass.
184   const MachineBranchProbabilityInfo *MBPI;
185
186   /// \brief A handle to the function-wide block frequency pass.
187   const MachineBlockFrequencyInfo *MBFI;
188
189   /// \brief A handle to the loop info.
190   const MachineLoopInfo *MLI;
191
192   /// \brief A handle to the target's instruction info.
193   const TargetInstrInfo *TII;
194
195   /// \brief A handle to the target's lowering info.
196   const TargetLoweringBase *TLI;
197
198   /// \brief A handle to the post dominator tree.
199   MachineDominatorTree *MDT;
200
201   /// \brief A set of blocks that are unavoidably execute, i.e. they dominate
202   /// all terminators of the MachineFunction. 
203   SmallPtrSet<MachineBasicBlock *, 4> UnavoidableBlocks;
204
205   /// \brief Allocator and owner of BlockChain structures.
206   ///
207   /// We build BlockChains lazily while processing the loop structure of
208   /// a function. To reduce malloc traffic, we allocate them using this
209   /// slab-like allocator, and destroy them after the pass completes. An
210   /// important guarantee is that this allocator produces stable pointers to
211   /// the chains.
212   SpecificBumpPtrAllocator<BlockChain> ChainAllocator;
213
214   /// \brief Function wide BasicBlock to BlockChain mapping.
215   ///
216   /// This mapping allows efficiently moving from any given basic block to the
217   /// BlockChain it participates in, if any. We use it to, among other things,
218   /// allow implicitly defining edges between chains as the existing edges
219   /// between basic blocks.
220   DenseMap<MachineBasicBlock *, BlockChain *> BlockToChain;
221
222   void markChainSuccessors(BlockChain &Chain,
223                            MachineBasicBlock *LoopHeaderBB,
224                            SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
225                            const BlockFilterSet *BlockFilter = nullptr);
226   MachineBasicBlock *selectBestSuccessor(MachineBasicBlock *BB,
227                                          BlockChain &Chain,
228                                          const BlockFilterSet *BlockFilter);
229   MachineBasicBlock *selectBestCandidateBlock(
230       BlockChain &Chain, SmallVectorImpl<MachineBasicBlock *> &WorkList,
231       const BlockFilterSet *BlockFilter);
232   MachineBasicBlock *getFirstUnplacedBlock(
233       MachineFunction &F,
234       const BlockChain &PlacedChain,
235       MachineFunction::iterator &PrevUnplacedBlockIt,
236       const BlockFilterSet *BlockFilter);
237   void buildChain(MachineBasicBlock *BB, BlockChain &Chain,
238                   SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
239                   const BlockFilterSet *BlockFilter = nullptr);
240   MachineBasicBlock *findBestLoopTop(MachineLoop &L,
241                                      const BlockFilterSet &LoopBlockSet);
242   MachineBasicBlock *findBestLoopExit(MachineFunction &F,
243                                       MachineLoop &L,
244                                       const BlockFilterSet &LoopBlockSet);
245   void buildLoopChains(MachineFunction &F, MachineLoop &L);
246   void rotateLoop(BlockChain &LoopChain, MachineBasicBlock *ExitingBB,
247                   const BlockFilterSet &LoopBlockSet);
248   void buildCFGChains(MachineFunction &F);
249
250 public:
251   static char ID; // Pass identification, replacement for typeid
252   MachineBlockPlacement() : MachineFunctionPass(ID) {
253     initializeMachineBlockPlacementPass(*PassRegistry::getPassRegistry());
254   }
255
256   bool runOnMachineFunction(MachineFunction &F) override;
257
258   void getAnalysisUsage(AnalysisUsage &AU) const override {
259     AU.addRequired<MachineBranchProbabilityInfo>();
260     AU.addRequired<MachineBlockFrequencyInfo>();
261     AU.addRequired<MachineDominatorTree>();
262     AU.addRequired<MachineLoopInfo>();
263     MachineFunctionPass::getAnalysisUsage(AU);
264   }
265 };
266 }
267
268 char MachineBlockPlacement::ID = 0;
269 char &llvm::MachineBlockPlacementID = MachineBlockPlacement::ID;
270 INITIALIZE_PASS_BEGIN(MachineBlockPlacement, "block-placement",
271                       "Branch Probability Basic Block Placement", false, false)
272 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
273 INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
274 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
275 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
276 INITIALIZE_PASS_END(MachineBlockPlacement, "block-placement",
277                     "Branch Probability Basic Block Placement", false, false)
278
279 #ifndef NDEBUG
280 /// \brief Helper to print the name of a MBB.
281 ///
282 /// Only used by debug logging.
283 static std::string getBlockName(MachineBasicBlock *BB) {
284   std::string Result;
285   raw_string_ostream OS(Result);
286   OS << "BB#" << BB->getNumber()
287      << " (derived from LLVM BB '" << BB->getName() << "')";
288   OS.flush();
289   return Result;
290 }
291
292 /// \brief Helper to print the number of a MBB.
293 ///
294 /// Only used by debug logging.
295 static std::string getBlockNum(MachineBasicBlock *BB) {
296   std::string Result;
297   raw_string_ostream OS(Result);
298   OS << "BB#" << BB->getNumber();
299   OS.flush();
300   return Result;
301 }
302 #endif
303
304 /// \brief Mark a chain's successors as having one fewer preds.
305 ///
306 /// When a chain is being merged into the "placed" chain, this routine will
307 /// quickly walk the successors of each block in the chain and mark them as
308 /// having one fewer active predecessor. It also adds any successors of this
309 /// chain which reach the zero-predecessor state to the worklist passed in.
310 void MachineBlockPlacement::markChainSuccessors(
311     BlockChain &Chain,
312     MachineBasicBlock *LoopHeaderBB,
313     SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
314     const BlockFilterSet *BlockFilter) {
315   // Walk all the blocks in this chain, marking their successors as having
316   // a predecessor placed.
317   for (BlockChain::iterator CBI = Chain.begin(), CBE = Chain.end();
318        CBI != CBE; ++CBI) {
319     // Add any successors for which this is the only un-placed in-loop
320     // predecessor to the worklist as a viable candidate for CFG-neutral
321     // placement. No subsequent placement of this block will violate the CFG
322     // shape, so we get to use heuristics to choose a favorable placement.
323     for (MachineBasicBlock::succ_iterator SI = (*CBI)->succ_begin(),
324                                           SE = (*CBI)->succ_end();
325          SI != SE; ++SI) {
326       if (BlockFilter && !BlockFilter->count(*SI))
327         continue;
328       BlockChain &SuccChain = *BlockToChain[*SI];
329       // Disregard edges within a fixed chain, or edges to the loop header.
330       if (&Chain == &SuccChain || *SI == LoopHeaderBB)
331         continue;
332
333       // This is a cross-chain edge that is within the loop, so decrement the
334       // loop predecessor count of the destination chain.
335       if (SuccChain.LoopPredecessors > 0 && --SuccChain.LoopPredecessors == 0)
336         BlockWorkList.push_back(*SuccChain.begin());
337     }
338   }
339 }
340
341 /// \brief Select the best successor for a block.
342 ///
343 /// This looks across all successors of a particular block and attempts to
344 /// select the "best" one to be the layout successor. It only considers direct
345 /// successors which also pass the block filter. It will attempt to avoid
346 /// breaking CFG structure, but cave and break such structures in the case of
347 /// very hot successor edges.
348 ///
349 /// \returns The best successor block found, or null if none are viable.
350 MachineBasicBlock *MachineBlockPlacement::selectBestSuccessor(
351     MachineBasicBlock *BB, BlockChain &Chain,
352     const BlockFilterSet *BlockFilter) {
353   const BranchProbability HotProb(4, 5); // 80%
354
355   MachineBasicBlock *BestSucc = nullptr;
356   // FIXME: Due to the performance of the probability and weight routines in
357   // the MBPI analysis, we manually compute probabilities using the edge
358   // weights. This is suboptimal as it means that the somewhat subtle
359   // definition of edge weight semantics is encoded here as well. We should
360   // improve the MBPI interface to efficiently support query patterns such as
361   // this.
362   uint32_t BestWeight = 0;
363   uint32_t WeightScale = 0;
364   uint32_t SumWeight = MBPI->getSumForBlock(BB, WeightScale);
365   DEBUG(dbgs() << "Attempting merge from: " << getBlockName(BB) << "\n");
366   for (MachineBasicBlock *Succ : BB->successors()) {
367     if (BlockFilter && !BlockFilter->count(Succ))
368       continue;
369     BlockChain &SuccChain = *BlockToChain[Succ];
370     if (&SuccChain == &Chain) {
371       DEBUG(dbgs() << "    " << getBlockName(Succ) << " -> Already merged!\n");
372       continue;
373     }
374     if (Succ != *SuccChain.begin()) {
375       DEBUG(dbgs() << "    " << getBlockName(Succ) << " -> Mid chain!\n");
376       continue;
377     }
378
379     uint32_t SuccWeight = MBPI->getEdgeWeight(BB, Succ);
380     BranchProbability SuccProb(SuccWeight / WeightScale, SumWeight);
381
382     // If we outline optional branches, look whether Succ is unavoidable, i.e.
383     // dominates all terminators of the MachineFunction. If it does, other
384     // successors must be optional. Don't do this for cold branches.
385     if (OutlineOptionalBranches && SuccProb > HotProb.getCompl() &&
386         UnavoidableBlocks.count(Succ) > 0)
387       return Succ;
388
389     // Only consider successors which are either "hot", or wouldn't violate
390     // any CFG constraints.
391     if (SuccChain.LoopPredecessors != 0) {
392       if (SuccProb < HotProb) {
393         DEBUG(dbgs() << "    " << getBlockName(Succ) << " -> " << SuccProb
394                      << " (prob) (CFG conflict)\n");
395         continue;
396       }
397
398       // Make sure that a hot successor doesn't have a globally more
399       // important predecessor.
400       BlockFrequency CandidateEdgeFreq =
401           MBFI->getBlockFreq(BB) * SuccProb * HotProb.getCompl();
402       bool BadCFGConflict = false;
403       for (MachineBasicBlock *Pred : Succ->predecessors()) {
404         if (Pred == Succ || (BlockFilter && !BlockFilter->count(Pred)) ||
405             BlockToChain[Pred] == &Chain)
406           continue;
407         BlockFrequency PredEdgeFreq =
408             MBFI->getBlockFreq(Pred) * MBPI->getEdgeProbability(Pred, Succ);
409         if (PredEdgeFreq >= CandidateEdgeFreq) {
410           BadCFGConflict = true;
411           break;
412         }
413       }
414       if (BadCFGConflict) {
415         DEBUG(dbgs() << "    " << getBlockName(Succ) << " -> " << SuccProb
416                      << " (prob) (non-cold CFG conflict)\n");
417         continue;
418       }
419     }
420
421     DEBUG(dbgs() << "    " << getBlockName(Succ) << " -> " << SuccProb
422                  << " (prob)"
423                  << (SuccChain.LoopPredecessors != 0 ? " (CFG break)" : "")
424                  << "\n");
425     if (BestSucc && BestWeight >= SuccWeight)
426       continue;
427     BestSucc = Succ;
428     BestWeight = SuccWeight;
429   }
430   return BestSucc;
431 }
432
433 /// \brief Select the best block from a worklist.
434 ///
435 /// This looks through the provided worklist as a list of candidate basic
436 /// blocks and select the most profitable one to place. The definition of
437 /// profitable only really makes sense in the context of a loop. This returns
438 /// the most frequently visited block in the worklist, which in the case of
439 /// a loop, is the one most desirable to be physically close to the rest of the
440 /// loop body in order to improve icache behavior.
441 ///
442 /// \returns The best block found, or null if none are viable.
443 MachineBasicBlock *MachineBlockPlacement::selectBestCandidateBlock(
444     BlockChain &Chain, SmallVectorImpl<MachineBasicBlock *> &WorkList,
445     const BlockFilterSet *BlockFilter) {
446   // Once we need to walk the worklist looking for a candidate, cleanup the
447   // worklist of already placed entries.
448   // FIXME: If this shows up on profiles, it could be folded (at the cost of
449   // some code complexity) into the loop below.
450   WorkList.erase(std::remove_if(WorkList.begin(), WorkList.end(),
451                                 [&](MachineBasicBlock *BB) {
452                    return BlockToChain.lookup(BB) == &Chain;
453                  }),
454                  WorkList.end());
455
456   MachineBasicBlock *BestBlock = nullptr;
457   BlockFrequency BestFreq;
458   for (SmallVectorImpl<MachineBasicBlock *>::iterator WBI = WorkList.begin(),
459                                                       WBE = WorkList.end();
460        WBI != WBE; ++WBI) {
461     BlockChain &SuccChain = *BlockToChain[*WBI];
462     if (&SuccChain == &Chain) {
463       DEBUG(dbgs() << "    " << getBlockName(*WBI)
464                    << " -> Already merged!\n");
465       continue;
466     }
467     assert(SuccChain.LoopPredecessors == 0 && "Found CFG-violating block");
468
469     BlockFrequency CandidateFreq = MBFI->getBlockFreq(*WBI);
470     DEBUG(dbgs() << "    " << getBlockName(*WBI) << " -> ";
471                  MBFI->printBlockFreq(dbgs(), CandidateFreq) << " (freq)\n");
472     if (BestBlock && BestFreq >= CandidateFreq)
473       continue;
474     BestBlock = *WBI;
475     BestFreq = CandidateFreq;
476   }
477   return BestBlock;
478 }
479
480 /// \brief Retrieve the first unplaced basic block.
481 ///
482 /// This routine is called when we are unable to use the CFG to walk through
483 /// all of the basic blocks and form a chain due to unnatural loops in the CFG.
484 /// We walk through the function's blocks in order, starting from the
485 /// LastUnplacedBlockIt. We update this iterator on each call to avoid
486 /// re-scanning the entire sequence on repeated calls to this routine.
487 MachineBasicBlock *MachineBlockPlacement::getFirstUnplacedBlock(
488     MachineFunction &F, const BlockChain &PlacedChain,
489     MachineFunction::iterator &PrevUnplacedBlockIt,
490     const BlockFilterSet *BlockFilter) {
491   for (MachineFunction::iterator I = PrevUnplacedBlockIt, E = F.end(); I != E;
492        ++I) {
493     if (BlockFilter && !BlockFilter->count(I))
494       continue;
495     if (BlockToChain[I] != &PlacedChain) {
496       PrevUnplacedBlockIt = I;
497       // Now select the head of the chain to which the unplaced block belongs
498       // as the block to place. This will force the entire chain to be placed,
499       // and satisfies the requirements of merging chains.
500       return *BlockToChain[I]->begin();
501     }
502   }
503   return nullptr;
504 }
505
506 void MachineBlockPlacement::buildChain(
507     MachineBasicBlock *BB, BlockChain &Chain,
508     SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
509     const BlockFilterSet *BlockFilter) {
510   assert(BB);
511   assert(BlockToChain[BB] == &Chain);
512   MachineFunction &F = *BB->getParent();
513   MachineFunction::iterator PrevUnplacedBlockIt = F.begin();
514
515   MachineBasicBlock *LoopHeaderBB = BB;
516   markChainSuccessors(Chain, LoopHeaderBB, BlockWorkList, BlockFilter);
517   BB = *std::prev(Chain.end());
518   for (;;) {
519     assert(BB);
520     assert(BlockToChain[BB] == &Chain);
521     assert(*std::prev(Chain.end()) == BB);
522
523     // Look for the best viable successor if there is one to place immediately
524     // after this block.
525     MachineBasicBlock *BestSucc = selectBestSuccessor(BB, Chain, BlockFilter);
526
527     // If an immediate successor isn't available, look for the best viable
528     // block among those we've identified as not violating the loop's CFG at
529     // this point. This won't be a fallthrough, but it will increase locality.
530     if (!BestSucc)
531       BestSucc = selectBestCandidateBlock(Chain, BlockWorkList, BlockFilter);
532
533     if (!BestSucc) {
534       BestSucc = getFirstUnplacedBlock(F, Chain, PrevUnplacedBlockIt,
535                                        BlockFilter);
536       if (!BestSucc)
537         break;
538
539       DEBUG(dbgs() << "Unnatural loop CFG detected, forcibly merging the "
540                       "layout successor until the CFG reduces\n");
541     }
542
543     // Place this block, updating the datastructures to reflect its placement.
544     BlockChain &SuccChain = *BlockToChain[BestSucc];
545     // Zero out LoopPredecessors for the successor we're about to merge in case
546     // we selected a successor that didn't fit naturally into the CFG.
547     SuccChain.LoopPredecessors = 0;
548     DEBUG(dbgs() << "Merging from " << getBlockNum(BB)
549                  << " to " << getBlockNum(BestSucc) << "\n");
550     markChainSuccessors(SuccChain, LoopHeaderBB, BlockWorkList, BlockFilter);
551     Chain.merge(BestSucc, &SuccChain);
552     BB = *std::prev(Chain.end());
553   }
554
555   DEBUG(dbgs() << "Finished forming chain for header block "
556                << getBlockNum(*Chain.begin()) << "\n");
557 }
558
559 /// \brief Find the best loop top block for layout.
560 ///
561 /// Look for a block which is strictly better than the loop header for laying
562 /// out at the top of the loop. This looks for one and only one pattern:
563 /// a latch block with no conditional exit. This block will cause a conditional
564 /// jump around it or will be the bottom of the loop if we lay it out in place,
565 /// but if it it doesn't end up at the bottom of the loop for any reason,
566 /// rotation alone won't fix it. Because such a block will always result in an
567 /// unconditional jump (for the backedge) rotating it in front of the loop
568 /// header is always profitable.
569 MachineBasicBlock *
570 MachineBlockPlacement::findBestLoopTop(MachineLoop &L,
571                                        const BlockFilterSet &LoopBlockSet) {
572   // Check that the header hasn't been fused with a preheader block due to
573   // crazy branches. If it has, we need to start with the header at the top to
574   // prevent pulling the preheader into the loop body.
575   BlockChain &HeaderChain = *BlockToChain[L.getHeader()];
576   if (!LoopBlockSet.count(*HeaderChain.begin()))
577     return L.getHeader();
578
579   DEBUG(dbgs() << "Finding best loop top for: "
580                << getBlockName(L.getHeader()) << "\n");
581
582   BlockFrequency BestPredFreq;
583   MachineBasicBlock *BestPred = nullptr;
584   for (MachineBasicBlock::pred_iterator PI = L.getHeader()->pred_begin(),
585                                         PE = L.getHeader()->pred_end();
586        PI != PE; ++PI) {
587     MachineBasicBlock *Pred = *PI;
588     if (!LoopBlockSet.count(Pred))
589       continue;
590     DEBUG(dbgs() << "    header pred: " << getBlockName(Pred) << ", "
591                  << Pred->succ_size() << " successors, ";
592                  MBFI->printBlockFreq(dbgs(), Pred) << " freq\n");
593     if (Pred->succ_size() > 1)
594       continue;
595
596     BlockFrequency PredFreq = MBFI->getBlockFreq(Pred);
597     if (!BestPred || PredFreq > BestPredFreq ||
598         (!(PredFreq < BestPredFreq) &&
599          Pred->isLayoutSuccessor(L.getHeader()))) {
600       BestPred = Pred;
601       BestPredFreq = PredFreq;
602     }
603   }
604
605   // If no direct predecessor is fine, just use the loop header.
606   if (!BestPred)
607     return L.getHeader();
608
609   // Walk backwards through any straight line of predecessors.
610   while (BestPred->pred_size() == 1 &&
611          (*BestPred->pred_begin())->succ_size() == 1 &&
612          *BestPred->pred_begin() != L.getHeader())
613     BestPred = *BestPred->pred_begin();
614
615   DEBUG(dbgs() << "    final top: " << getBlockName(BestPred) << "\n");
616   return BestPred;
617 }
618
619
620 /// \brief Find the best loop exiting block for layout.
621 ///
622 /// This routine implements the logic to analyze the loop looking for the best
623 /// block to layout at the top of the loop. Typically this is done to maximize
624 /// fallthrough opportunities.
625 MachineBasicBlock *
626 MachineBlockPlacement::findBestLoopExit(MachineFunction &F,
627                                         MachineLoop &L,
628                                         const BlockFilterSet &LoopBlockSet) {
629   // We don't want to layout the loop linearly in all cases. If the loop header
630   // is just a normal basic block in the loop, we want to look for what block
631   // within the loop is the best one to layout at the top. However, if the loop
632   // header has be pre-merged into a chain due to predecessors not having
633   // analyzable branches, *and* the predecessor it is merged with is *not* part
634   // of the loop, rotating the header into the middle of the loop will create
635   // a non-contiguous range of blocks which is Very Bad. So start with the
636   // header and only rotate if safe.
637   BlockChain &HeaderChain = *BlockToChain[L.getHeader()];
638   if (!LoopBlockSet.count(*HeaderChain.begin()))
639     return nullptr;
640
641   BlockFrequency BestExitEdgeFreq;
642   unsigned BestExitLoopDepth = 0;
643   MachineBasicBlock *ExitingBB = nullptr;
644   // If there are exits to outer loops, loop rotation can severely limit
645   // fallthrough opportunites unless it selects such an exit. Keep a set of
646   // blocks where rotating to exit with that block will reach an outer loop.
647   SmallPtrSet<MachineBasicBlock *, 4> BlocksExitingToOuterLoop;
648
649   DEBUG(dbgs() << "Finding best loop exit for: "
650                << getBlockName(L.getHeader()) << "\n");
651   for (MachineLoop::block_iterator I = L.block_begin(),
652                                    E = L.block_end();
653        I != E; ++I) {
654     BlockChain &Chain = *BlockToChain[*I];
655     // Ensure that this block is at the end of a chain; otherwise it could be
656     // mid-way through an inner loop or a successor of an analyzable branch.
657     if (*I != *std::prev(Chain.end()))
658       continue;
659
660     // Now walk the successors. We need to establish whether this has a viable
661     // exiting successor and whether it has a viable non-exiting successor.
662     // We store the old exiting state and restore it if a viable looping
663     // successor isn't found.
664     MachineBasicBlock *OldExitingBB = ExitingBB;
665     BlockFrequency OldBestExitEdgeFreq = BestExitEdgeFreq;
666     bool HasLoopingSucc = false;
667     // FIXME: Due to the performance of the probability and weight routines in
668     // the MBPI analysis, we use the internal weights and manually compute the
669     // probabilities to avoid quadratic behavior.
670     uint32_t WeightScale = 0;
671     uint32_t SumWeight = MBPI->getSumForBlock(*I, WeightScale);
672     for (MachineBasicBlock::succ_iterator SI = (*I)->succ_begin(),
673                                           SE = (*I)->succ_end();
674          SI != SE; ++SI) {
675       if ((*SI)->isLandingPad())
676         continue;
677       if (*SI == *I)
678         continue;
679       BlockChain &SuccChain = *BlockToChain[*SI];
680       // Don't split chains, either this chain or the successor's chain.
681       if (&Chain == &SuccChain) {
682         DEBUG(dbgs() << "    exiting: " << getBlockName(*I) << " -> "
683                      << getBlockName(*SI) << " (chain conflict)\n");
684         continue;
685       }
686
687       uint32_t SuccWeight = MBPI->getEdgeWeight(*I, *SI);
688       if (LoopBlockSet.count(*SI)) {
689         DEBUG(dbgs() << "    looping: " << getBlockName(*I) << " -> "
690                      << getBlockName(*SI) << " (" << SuccWeight << ")\n");
691         HasLoopingSucc = true;
692         continue;
693       }
694
695       unsigned SuccLoopDepth = 0;
696       if (MachineLoop *ExitLoop = MLI->getLoopFor(*SI)) {
697         SuccLoopDepth = ExitLoop->getLoopDepth();
698         if (ExitLoop->contains(&L))
699           BlocksExitingToOuterLoop.insert(*I);
700       }
701
702       BranchProbability SuccProb(SuccWeight / WeightScale, SumWeight);
703       BlockFrequency ExitEdgeFreq = MBFI->getBlockFreq(*I) * SuccProb;
704       DEBUG(dbgs() << "    exiting: " << getBlockName(*I) << " -> "
705                    << getBlockName(*SI) << " [L:" << SuccLoopDepth
706                    << "] (";
707                    MBFI->printBlockFreq(dbgs(), ExitEdgeFreq) << ")\n");
708       // Note that we bias this toward an existing layout successor to retain
709       // incoming order in the absence of better information. The exit must have
710       // a frequency higher than the current exit before we consider breaking
711       // the layout.
712       BranchProbability Bias(100 - ExitBlockBias, 100);
713       if (!ExitingBB || BestExitLoopDepth < SuccLoopDepth ||
714           ExitEdgeFreq > BestExitEdgeFreq ||
715           ((*I)->isLayoutSuccessor(*SI) &&
716            !(ExitEdgeFreq < BestExitEdgeFreq * Bias))) {
717         BestExitEdgeFreq = ExitEdgeFreq;
718         ExitingBB = *I;
719       }
720     }
721
722     // Restore the old exiting state, no viable looping successor was found.
723     if (!HasLoopingSucc) {
724       ExitingBB = OldExitingBB;
725       BestExitEdgeFreq = OldBestExitEdgeFreq;
726       continue;
727     }
728   }
729   // Without a candidate exiting block or with only a single block in the
730   // loop, just use the loop header to layout the loop.
731   if (!ExitingBB || L.getNumBlocks() == 1)
732     return nullptr;
733
734   // Also, if we have exit blocks which lead to outer loops but didn't select
735   // one of them as the exiting block we are rotating toward, disable loop
736   // rotation altogether.
737   if (!BlocksExitingToOuterLoop.empty() &&
738       !BlocksExitingToOuterLoop.count(ExitingBB))
739     return nullptr;
740
741   DEBUG(dbgs() << "  Best exiting block: " << getBlockName(ExitingBB) << "\n");
742   return ExitingBB;
743 }
744
745 /// \brief Attempt to rotate an exiting block to the bottom of the loop.
746 ///
747 /// Once we have built a chain, try to rotate it to line up the hot exit block
748 /// with fallthrough out of the loop if doing so doesn't introduce unnecessary
749 /// branches. For example, if the loop has fallthrough into its header and out
750 /// of its bottom already, don't rotate it.
751 void MachineBlockPlacement::rotateLoop(BlockChain &LoopChain,
752                                        MachineBasicBlock *ExitingBB,
753                                        const BlockFilterSet &LoopBlockSet) {
754   if (!ExitingBB)
755     return;
756
757   MachineBasicBlock *Top = *LoopChain.begin();
758   bool ViableTopFallthrough = false;
759   for (MachineBasicBlock::pred_iterator PI = Top->pred_begin(),
760                                         PE = Top->pred_end();
761        PI != PE; ++PI) {
762     BlockChain *PredChain = BlockToChain[*PI];
763     if (!LoopBlockSet.count(*PI) &&
764         (!PredChain || *PI == *std::prev(PredChain->end()))) {
765       ViableTopFallthrough = true;
766       break;
767     }
768   }
769
770   // If the header has viable fallthrough, check whether the current loop
771   // bottom is a viable exiting block. If so, bail out as rotating will
772   // introduce an unnecessary branch.
773   if (ViableTopFallthrough) {
774     MachineBasicBlock *Bottom = *std::prev(LoopChain.end());
775     for (MachineBasicBlock::succ_iterator SI = Bottom->succ_begin(),
776                                           SE = Bottom->succ_end();
777          SI != SE; ++SI) {
778       BlockChain *SuccChain = BlockToChain[*SI];
779       if (!LoopBlockSet.count(*SI) &&
780           (!SuccChain || *SI == *SuccChain->begin()))
781         return;
782     }
783   }
784
785   BlockChain::iterator ExitIt = std::find(LoopChain.begin(), LoopChain.end(),
786                                           ExitingBB);
787   if (ExitIt == LoopChain.end())
788     return;
789
790   std::rotate(LoopChain.begin(), std::next(ExitIt), LoopChain.end());
791 }
792
793 /// \brief Forms basic block chains from the natural loop structures.
794 ///
795 /// These chains are designed to preserve the existing *structure* of the code
796 /// as much as possible. We can then stitch the chains together in a way which
797 /// both preserves the topological structure and minimizes taken conditional
798 /// branches.
799 void MachineBlockPlacement::buildLoopChains(MachineFunction &F,
800                                             MachineLoop &L) {
801   // First recurse through any nested loops, building chains for those inner
802   // loops.
803   for (MachineLoop::iterator LI = L.begin(), LE = L.end(); LI != LE; ++LI)
804     buildLoopChains(F, **LI);
805
806   SmallVector<MachineBasicBlock *, 16> BlockWorkList;
807   BlockFilterSet LoopBlockSet(L.block_begin(), L.block_end());
808
809   // First check to see if there is an obviously preferable top block for the
810   // loop. This will default to the header, but may end up as one of the
811   // predecessors to the header if there is one which will result in strictly
812   // fewer branches in the loop body.
813   MachineBasicBlock *LoopTop = findBestLoopTop(L, LoopBlockSet);
814
815   // If we selected just the header for the loop top, look for a potentially
816   // profitable exit block in the event that rotating the loop can eliminate
817   // branches by placing an exit edge at the bottom.
818   MachineBasicBlock *ExitingBB = nullptr;
819   if (LoopTop == L.getHeader())
820     ExitingBB = findBestLoopExit(F, L, LoopBlockSet);
821
822   BlockChain &LoopChain = *BlockToChain[LoopTop];
823
824   // FIXME: This is a really lame way of walking the chains in the loop: we
825   // walk the blocks, and use a set to prevent visiting a particular chain
826   // twice.
827   SmallPtrSet<BlockChain *, 4> UpdatedPreds;
828   assert(LoopChain.LoopPredecessors == 0);
829   UpdatedPreds.insert(&LoopChain);
830   for (MachineLoop::block_iterator BI = L.block_begin(),
831                                    BE = L.block_end();
832        BI != BE; ++BI) {
833     BlockChain &Chain = *BlockToChain[*BI];
834     if (!UpdatedPreds.insert(&Chain).second)
835       continue;
836
837     assert(Chain.LoopPredecessors == 0);
838     for (BlockChain::iterator BCI = Chain.begin(), BCE = Chain.end();
839          BCI != BCE; ++BCI) {
840       assert(BlockToChain[*BCI] == &Chain);
841       for (MachineBasicBlock::pred_iterator PI = (*BCI)->pred_begin(),
842                                             PE = (*BCI)->pred_end();
843            PI != PE; ++PI) {
844         if (BlockToChain[*PI] == &Chain || !LoopBlockSet.count(*PI))
845           continue;
846         ++Chain.LoopPredecessors;
847       }
848     }
849
850     if (Chain.LoopPredecessors == 0)
851       BlockWorkList.push_back(*Chain.begin());
852   }
853
854   buildChain(LoopTop, LoopChain, BlockWorkList, &LoopBlockSet);
855   rotateLoop(LoopChain, ExitingBB, LoopBlockSet);
856
857   DEBUG({
858     // Crash at the end so we get all of the debugging output first.
859     bool BadLoop = false;
860     if (LoopChain.LoopPredecessors) {
861       BadLoop = true;
862       dbgs() << "Loop chain contains a block without its preds placed!\n"
863              << "  Loop header:  " << getBlockName(*L.block_begin()) << "\n"
864              << "  Chain header: " << getBlockName(*LoopChain.begin()) << "\n";
865     }
866     for (BlockChain::iterator BCI = LoopChain.begin(), BCE = LoopChain.end();
867          BCI != BCE; ++BCI) {
868       dbgs() << "          ... " << getBlockName(*BCI) << "\n";
869       if (!LoopBlockSet.erase(*BCI)) {
870         // We don't mark the loop as bad here because there are real situations
871         // where this can occur. For example, with an unanalyzable fallthrough
872         // from a loop block to a non-loop block or vice versa.
873         dbgs() << "Loop chain contains a block not contained by the loop!\n"
874                << "  Loop header:  " << getBlockName(*L.block_begin()) << "\n"
875                << "  Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
876                << "  Bad block:    " << getBlockName(*BCI) << "\n";
877       }
878     }
879
880     if (!LoopBlockSet.empty()) {
881       BadLoop = true;
882       for (BlockFilterSet::iterator LBI = LoopBlockSet.begin(),
883                                     LBE = LoopBlockSet.end();
884            LBI != LBE; ++LBI)
885         dbgs() << "Loop contains blocks never placed into a chain!\n"
886                << "  Loop header:  " << getBlockName(*L.block_begin()) << "\n"
887                << "  Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
888                << "  Bad block:    " << getBlockName(*LBI) << "\n";
889     }
890     assert(!BadLoop && "Detected problems with the placement of this loop.");
891   });
892 }
893
894 void MachineBlockPlacement::buildCFGChains(MachineFunction &F) {
895   // Ensure that every BB in the function has an associated chain to simplify
896   // the assumptions of the remaining algorithm.
897   SmallVector<MachineOperand, 4> Cond; // For AnalyzeBranch.
898   for (MachineFunction::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
899     MachineBasicBlock *BB = FI;
900     BlockChain *Chain
901       = new (ChainAllocator.Allocate()) BlockChain(BlockToChain, BB);
902     // Also, merge any blocks which we cannot reason about and must preserve
903     // the exact fallthrough behavior for.
904     for (;;) {
905       Cond.clear();
906       MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
907       if (!TII->AnalyzeBranch(*BB, TBB, FBB, Cond) || !FI->canFallThrough())
908         break;
909
910       MachineFunction::iterator NextFI(std::next(FI));
911       MachineBasicBlock *NextBB = NextFI;
912       // Ensure that the layout successor is a viable block, as we know that
913       // fallthrough is a possibility.
914       assert(NextFI != FE && "Can't fallthrough past the last block.");
915       DEBUG(dbgs() << "Pre-merging due to unanalyzable fallthrough: "
916                    << getBlockName(BB) << " -> " << getBlockName(NextBB)
917                    << "\n");
918       Chain->merge(NextBB, nullptr);
919       FI = NextFI;
920       BB = NextBB;
921     }
922   }
923
924   if (OutlineOptionalBranches) {
925     // Find the nearest common dominator of all of F's terminators.
926     MachineBasicBlock *Terminator = nullptr;
927     for (MachineBasicBlock &MBB : F) {
928       if (MBB.succ_size() == 0) {
929         if (Terminator == nullptr)
930           Terminator = &MBB;
931         else
932           Terminator = MDT->findNearestCommonDominator(Terminator, &MBB);
933       }
934     }
935
936     // MBBs dominating this common dominator are unavoidable.
937     UnavoidableBlocks.clear();
938     for (MachineBasicBlock &MBB : F) {
939       if (MDT->dominates(&MBB, Terminator)) {
940         UnavoidableBlocks.insert(&MBB);
941       }
942     }
943   }
944
945   // Build any loop-based chains.
946   for (MachineLoopInfo::iterator LI = MLI->begin(), LE = MLI->end(); LI != LE;
947        ++LI)
948     buildLoopChains(F, **LI);
949
950   SmallVector<MachineBasicBlock *, 16> BlockWorkList;
951
952   SmallPtrSet<BlockChain *, 4> UpdatedPreds;
953   for (MachineFunction::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
954     MachineBasicBlock *BB = &*FI;
955     BlockChain &Chain = *BlockToChain[BB];
956     if (!UpdatedPreds.insert(&Chain).second)
957       continue;
958
959     assert(Chain.LoopPredecessors == 0);
960     for (BlockChain::iterator BCI = Chain.begin(), BCE = Chain.end();
961          BCI != BCE; ++BCI) {
962       assert(BlockToChain[*BCI] == &Chain);
963       for (MachineBasicBlock::pred_iterator PI = (*BCI)->pred_begin(),
964                                             PE = (*BCI)->pred_end();
965            PI != PE; ++PI) {
966         if (BlockToChain[*PI] == &Chain)
967           continue;
968         ++Chain.LoopPredecessors;
969       }
970     }
971
972     if (Chain.LoopPredecessors == 0)
973       BlockWorkList.push_back(*Chain.begin());
974   }
975
976   BlockChain &FunctionChain = *BlockToChain[&F.front()];
977   buildChain(&F.front(), FunctionChain, BlockWorkList);
978
979 #ifndef NDEBUG
980   typedef SmallPtrSet<MachineBasicBlock *, 16> FunctionBlockSetType;
981 #endif
982   DEBUG({
983     // Crash at the end so we get all of the debugging output first.
984     bool BadFunc = false;
985     FunctionBlockSetType FunctionBlockSet;
986     for (MachineFunction::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI)
987       FunctionBlockSet.insert(FI);
988
989     for (BlockChain::iterator BCI = FunctionChain.begin(),
990                               BCE = FunctionChain.end();
991          BCI != BCE; ++BCI)
992       if (!FunctionBlockSet.erase(*BCI)) {
993         BadFunc = true;
994         dbgs() << "Function chain contains a block not in the function!\n"
995                << "  Bad block:    " << getBlockName(*BCI) << "\n";
996       }
997
998     if (!FunctionBlockSet.empty()) {
999       BadFunc = true;
1000       for (FunctionBlockSetType::iterator FBI = FunctionBlockSet.begin(),
1001                                           FBE = FunctionBlockSet.end();
1002            FBI != FBE; ++FBI)
1003         dbgs() << "Function contains blocks never placed into a chain!\n"
1004                << "  Bad block:    " << getBlockName(*FBI) << "\n";
1005     }
1006     assert(!BadFunc && "Detected problems with the block placement.");
1007   });
1008
1009   // Splice the blocks into place.
1010   MachineFunction::iterator InsertPos = F.begin();
1011   for (BlockChain::iterator BI = FunctionChain.begin(),
1012                             BE = FunctionChain.end();
1013        BI != BE; ++BI) {
1014     DEBUG(dbgs() << (BI == FunctionChain.begin() ? "Placing chain "
1015                                                   : "          ... ")
1016           << getBlockName(*BI) << "\n");
1017     if (InsertPos != MachineFunction::iterator(*BI))
1018       F.splice(InsertPos, *BI);
1019     else
1020       ++InsertPos;
1021
1022     // Update the terminator of the previous block.
1023     if (BI == FunctionChain.begin())
1024       continue;
1025     MachineBasicBlock *PrevBB = std::prev(MachineFunction::iterator(*BI));
1026
1027     // FIXME: It would be awesome of updateTerminator would just return rather
1028     // than assert when the branch cannot be analyzed in order to remove this
1029     // boiler plate.
1030     Cond.clear();
1031     MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
1032     if (!TII->AnalyzeBranch(*PrevBB, TBB, FBB, Cond)) {
1033       // The "PrevBB" is not yet updated to reflect current code layout, so,
1034       //   o. it may fall-through to a block without explict "goto" instruction
1035       //      before layout, and no longer fall-through it after layout; or 
1036       //   o. just opposite.
1037       // 
1038       // AnalyzeBranch() may return erroneous value for FBB when these two
1039       // situations take place. For the first scenario FBB is mistakenly set
1040       // NULL; for the 2nd scenario, the FBB, which is expected to be NULL,
1041       // is mistakenly pointing to "*BI".
1042       //
1043       bool needUpdateBr = true;
1044       if (!Cond.empty() && (!FBB || FBB == *BI)) {
1045         PrevBB->updateTerminator();
1046         needUpdateBr = false;
1047         Cond.clear();
1048         TBB = FBB = nullptr;
1049         if (TII->AnalyzeBranch(*PrevBB, TBB, FBB, Cond)) {
1050           // FIXME: This should never take place.
1051           TBB = FBB = nullptr;
1052         }
1053       }
1054
1055       // If PrevBB has a two-way branch, try to re-order the branches
1056       // such that we branch to the successor with higher weight first.
1057       if (TBB && !Cond.empty() && FBB &&
1058           MBPI->getEdgeWeight(PrevBB, FBB) > MBPI->getEdgeWeight(PrevBB, TBB) &&
1059           !TII->ReverseBranchCondition(Cond)) {
1060         DEBUG(dbgs() << "Reverse order of the two branches: "
1061                      << getBlockName(PrevBB) << "\n");
1062         DEBUG(dbgs() << "    Edge weight: " << MBPI->getEdgeWeight(PrevBB, FBB)
1063                      << " vs " << MBPI->getEdgeWeight(PrevBB, TBB) << "\n");
1064         DebugLoc dl;  // FIXME: this is nowhere
1065         TII->RemoveBranch(*PrevBB);
1066         TII->InsertBranch(*PrevBB, FBB, TBB, Cond, dl);
1067         needUpdateBr = true;
1068       }
1069       if (needUpdateBr)
1070         PrevBB->updateTerminator();
1071     }
1072   }
1073
1074   // Fixup the last block.
1075   Cond.clear();
1076   MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
1077   if (!TII->AnalyzeBranch(F.back(), TBB, FBB, Cond))
1078     F.back().updateTerminator();
1079
1080   // Walk through the backedges of the function now that we have fully laid out
1081   // the basic blocks and align the destination of each backedge. We don't rely
1082   // exclusively on the loop info here so that we can align backedges in
1083   // unnatural CFGs and backedges that were introduced purely because of the
1084   // loop rotations done during this layout pass.
1085   if (F.getFunction()->hasFnAttribute(Attribute::OptimizeForSize))
1086     return;
1087   if (FunctionChain.begin() == FunctionChain.end())
1088     return;  // Empty chain.
1089
1090   const BranchProbability ColdProb(1, 5); // 20%
1091   BlockFrequency EntryFreq = MBFI->getBlockFreq(F.begin());
1092   BlockFrequency WeightedEntryFreq = EntryFreq * ColdProb;
1093   for (BlockChain::iterator BI = std::next(FunctionChain.begin()),
1094                             BE = FunctionChain.end();
1095        BI != BE; ++BI) {
1096     // Don't align non-looping basic blocks. These are unlikely to execute
1097     // enough times to matter in practice. Note that we'll still handle
1098     // unnatural CFGs inside of a natural outer loop (the common case) and
1099     // rotated loops.
1100     MachineLoop *L = MLI->getLoopFor(*BI);
1101     if (!L)
1102       continue;
1103
1104     unsigned Align = TLI->getPrefLoopAlignment(L);
1105     if (!Align)
1106       continue;  // Don't care about loop alignment.
1107
1108     // If the block is cold relative to the function entry don't waste space
1109     // aligning it.
1110     BlockFrequency Freq = MBFI->getBlockFreq(*BI);
1111     if (Freq < WeightedEntryFreq)
1112       continue;
1113
1114     // If the block is cold relative to its loop header, don't align it
1115     // regardless of what edges into the block exist.
1116     MachineBasicBlock *LoopHeader = L->getHeader();
1117     BlockFrequency LoopHeaderFreq = MBFI->getBlockFreq(LoopHeader);
1118     if (Freq < (LoopHeaderFreq * ColdProb))
1119       continue;
1120
1121     // Check for the existence of a non-layout predecessor which would benefit
1122     // from aligning this block.
1123     MachineBasicBlock *LayoutPred = *std::prev(BI);
1124
1125     // Force alignment if all the predecessors are jumps. We already checked
1126     // that the block isn't cold above.
1127     if (!LayoutPred->isSuccessor(*BI)) {
1128       (*BI)->setAlignment(Align);
1129       continue;
1130     }
1131
1132     // Align this block if the layout predecessor's edge into this block is
1133     // cold relative to the block. When this is true, other predecessors make up
1134     // all of the hot entries into the block and thus alignment is likely to be
1135     // important.
1136     BranchProbability LayoutProb = MBPI->getEdgeProbability(LayoutPred, *BI);
1137     BlockFrequency LayoutEdgeFreq = MBFI->getBlockFreq(LayoutPred) * LayoutProb;
1138     if (LayoutEdgeFreq <= (Freq * ColdProb))
1139       (*BI)->setAlignment(Align);
1140   }
1141 }
1142
1143 bool MachineBlockPlacement::runOnMachineFunction(MachineFunction &F) {
1144   // Check for single-block functions and skip them.
1145   if (std::next(F.begin()) == F.end())
1146     return false;
1147
1148   if (skipOptnoneFunction(*F.getFunction()))
1149     return false;
1150
1151   MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
1152   MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
1153   MLI = &getAnalysis<MachineLoopInfo>();
1154   TII = F.getSubtarget().getInstrInfo();
1155   TLI = F.getSubtarget().getTargetLowering();
1156   MDT = &getAnalysis<MachineDominatorTree>();
1157   assert(BlockToChain.empty());
1158
1159   buildCFGChains(F);
1160
1161   BlockToChain.clear();
1162   ChainAllocator.DestroyAll();
1163
1164   if (AlignAllBlock)
1165     // Align all of the blocks in the function to a specific alignment.
1166     for (MachineFunction::iterator FI = F.begin(), FE = F.end();
1167          FI != FE; ++FI)
1168       FI->setAlignment(AlignAllBlock);
1169
1170   // We always return true as we have no way to track whether the final order
1171   // differs from the original order.
1172   return true;
1173 }
1174
1175 namespace {
1176 /// \brief A pass to compute block placement statistics.
1177 ///
1178 /// A separate pass to compute interesting statistics for evaluating block
1179 /// placement. This is separate from the actual placement pass so that they can
1180 /// be computed in the absence of any placement transformations or when using
1181 /// alternative placement strategies.
1182 class MachineBlockPlacementStats : public MachineFunctionPass {
1183   /// \brief A handle to the branch probability pass.
1184   const MachineBranchProbabilityInfo *MBPI;
1185
1186   /// \brief A handle to the function-wide block frequency pass.
1187   const MachineBlockFrequencyInfo *MBFI;
1188
1189 public:
1190   static char ID; // Pass identification, replacement for typeid
1191   MachineBlockPlacementStats() : MachineFunctionPass(ID) {
1192     initializeMachineBlockPlacementStatsPass(*PassRegistry::getPassRegistry());
1193   }
1194
1195   bool runOnMachineFunction(MachineFunction &F) override;
1196
1197   void getAnalysisUsage(AnalysisUsage &AU) const override {
1198     AU.addRequired<MachineBranchProbabilityInfo>();
1199     AU.addRequired<MachineBlockFrequencyInfo>();
1200     AU.setPreservesAll();
1201     MachineFunctionPass::getAnalysisUsage(AU);
1202   }
1203 };
1204 }
1205
1206 char MachineBlockPlacementStats::ID = 0;
1207 char &llvm::MachineBlockPlacementStatsID = MachineBlockPlacementStats::ID;
1208 INITIALIZE_PASS_BEGIN(MachineBlockPlacementStats, "block-placement-stats",
1209                       "Basic Block Placement Stats", false, false)
1210 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
1211 INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
1212 INITIALIZE_PASS_END(MachineBlockPlacementStats, "block-placement-stats",
1213                     "Basic Block Placement Stats", false, false)
1214
1215 bool MachineBlockPlacementStats::runOnMachineFunction(MachineFunction &F) {
1216   // Check for single-block functions and skip them.
1217   if (std::next(F.begin()) == F.end())
1218     return false;
1219
1220   MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
1221   MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
1222
1223   for (MachineFunction::iterator I = F.begin(), E = F.end(); I != E; ++I) {
1224     BlockFrequency BlockFreq = MBFI->getBlockFreq(I);
1225     Statistic &NumBranches = (I->succ_size() > 1) ? NumCondBranches
1226                                                   : NumUncondBranches;
1227     Statistic &BranchTakenFreq = (I->succ_size() > 1) ? CondBranchTakenFreq
1228                                                       : UncondBranchTakenFreq;
1229     for (MachineBasicBlock::succ_iterator SI = I->succ_begin(),
1230                                           SE = I->succ_end();
1231          SI != SE; ++SI) {
1232       // Skip if this successor is a fallthrough.
1233       if (I->isLayoutSuccessor(*SI))
1234         continue;
1235
1236       BlockFrequency EdgeFreq = BlockFreq * MBPI->getEdgeProbability(I, *SI);
1237       ++NumBranches;
1238       BranchTakenFreq += EdgeFreq.getFrequency();
1239     }
1240   }
1241
1242   return false;
1243 }
1244