LLVM API Documentation

MachineBlockPlacement.cpp
Go to the documentation of this file.
00001 //===-- MachineBlockPlacement.cpp - Basic Block Code Layout optimization --===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements basic block placement transformations using the CFG
00011 // structure and branch probability estimates.
00012 //
00013 // The pass strives to preserve the structure of the CFG (that is, retain
00014 // a topological ordering of basic blocks) in the absence of a *strong* signal
00015 // to the contrary from probabilities. However, within the CFG structure, it
00016 // attempts to choose an ordering which favors placing more likely sequences of
00017 // blocks adjacent to each other.
00018 //
00019 // The algorithm works from the inner-most loop within a function outward, and
00020 // at each stage walks through the basic blocks, trying to coalesce them into
00021 // sequential chains where allowed by the CFG (or demanded by heavy
00022 // probabilities). Finally, it walks the blocks in topological order, and the
00023 // first time it reaches a chain of basic blocks, it schedules them in the
00024 // function in-order.
00025 //
00026 //===----------------------------------------------------------------------===//
00027 
00028 #include "llvm/CodeGen/Passes.h"
00029 #include "llvm/ADT/DenseMap.h"
00030 #include "llvm/ADT/SmallPtrSet.h"
00031 #include "llvm/ADT/SmallVector.h"
00032 #include "llvm/ADT/Statistic.h"
00033 #include "llvm/CodeGen/MachineBasicBlock.h"
00034 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
00035 #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
00036 #include "llvm/CodeGen/MachineFunction.h"
00037 #include "llvm/CodeGen/MachineFunctionPass.h"
00038 #include "llvm/CodeGen/MachineLoopInfo.h"
00039 #include "llvm/CodeGen/MachineModuleInfo.h"
00040 #include "llvm/Support/Allocator.h"
00041 #include "llvm/Support/CommandLine.h"
00042 #include "llvm/Support/Debug.h"
00043 #include "llvm/Target/TargetInstrInfo.h"
00044 #include "llvm/Target/TargetLowering.h"
00045 #include "llvm/Target/TargetSubtargetInfo.h"
00046 #include <algorithm>
00047 using namespace llvm;
00048 
00049 #define DEBUG_TYPE "block-placement2"
00050 
00051 STATISTIC(NumCondBranches, "Number of conditional branches");
00052 STATISTIC(NumUncondBranches, "Number of uncondittional branches");
00053 STATISTIC(CondBranchTakenFreq,
00054           "Potential frequency of taking conditional branches");
00055 STATISTIC(UncondBranchTakenFreq,
00056           "Potential frequency of taking unconditional branches");
00057 
00058 static cl::opt<unsigned> AlignAllBlock("align-all-blocks",
00059                                        cl::desc("Force the alignment of all "
00060                                                 "blocks in the function."),
00061                                        cl::init(0), cl::Hidden);
00062 
00063 // FIXME: Find a good default for this flag and remove the flag.
00064 static cl::opt<unsigned>
00065 ExitBlockBias("block-placement-exit-block-bias",
00066               cl::desc("Block frequency percentage a loop exit block needs "
00067                        "over the original exit to be considered the new exit."),
00068               cl::init(0), cl::Hidden);
00069 
00070 namespace {
00071 class BlockChain;
00072 /// \brief Type for our function-wide basic block -> block chain mapping.
00073 typedef DenseMap<MachineBasicBlock *, BlockChain *> BlockToChainMapType;
00074 }
00075 
00076 namespace {
00077 /// \brief A chain of blocks which will be laid out contiguously.
00078 ///
00079 /// This is the datastructure representing a chain of consecutive blocks that
00080 /// are profitable to layout together in order to maximize fallthrough
00081 /// probabilities and code locality. We also can use a block chain to represent
00082 /// a sequence of basic blocks which have some external (correctness)
00083 /// requirement for sequential layout.
00084 ///
00085 /// Chains can be built around a single basic block and can be merged to grow
00086 /// them. They participate in a block-to-chain mapping, which is updated
00087 /// automatically as chains are merged together.
00088 class BlockChain {
00089   /// \brief The sequence of blocks belonging to this chain.
00090   ///
00091   /// This is the sequence of blocks for a particular chain. These will be laid
00092   /// out in-order within the function.
00093   SmallVector<MachineBasicBlock *, 4> Blocks;
00094 
00095   /// \brief A handle to the function-wide basic block to block chain mapping.
00096   ///
00097   /// This is retained in each block chain to simplify the computation of child
00098   /// block chains for SCC-formation and iteration. We store the edges to child
00099   /// basic blocks, and map them back to their associated chains using this
00100   /// structure.
00101   BlockToChainMapType &BlockToChain;
00102 
00103 public:
00104   /// \brief Construct a new BlockChain.
00105   ///
00106   /// This builds a new block chain representing a single basic block in the
00107   /// function. It also registers itself as the chain that block participates
00108   /// in with the BlockToChain mapping.
00109   BlockChain(BlockToChainMapType &BlockToChain, MachineBasicBlock *BB)
00110     : Blocks(1, BB), BlockToChain(BlockToChain), LoopPredecessors(0) {
00111     assert(BB && "Cannot create a chain with a null basic block");
00112     BlockToChain[BB] = this;
00113   }
00114 
00115   /// \brief Iterator over blocks within the chain.
00116   typedef SmallVectorImpl<MachineBasicBlock *>::iterator iterator;
00117 
00118   /// \brief Beginning of blocks within the chain.
00119   iterator begin() { return Blocks.begin(); }
00120 
00121   /// \brief End of blocks within the chain.
00122   iterator end() { return Blocks.end(); }
00123 
00124   /// \brief Merge a block chain into this one.
00125   ///
00126   /// This routine merges a block chain into this one. It takes care of forming
00127   /// a contiguous sequence of basic blocks, updating the edge list, and
00128   /// updating the block -> chain mapping. It does not free or tear down the
00129   /// old chain, but the old chain's block list is no longer valid.
00130   void merge(MachineBasicBlock *BB, BlockChain *Chain) {
00131     assert(BB);
00132     assert(!Blocks.empty());
00133 
00134     // Fast path in case we don't have a chain already.
00135     if (!Chain) {
00136       assert(!BlockToChain[BB]);
00137       Blocks.push_back(BB);
00138       BlockToChain[BB] = this;
00139       return;
00140     }
00141 
00142     assert(BB == *Chain->begin());
00143     assert(Chain->begin() != Chain->end());
00144 
00145     // Update the incoming blocks to point to this chain, and add them to the
00146     // chain structure.
00147     for (BlockChain::iterator BI = Chain->begin(), BE = Chain->end();
00148          BI != BE; ++BI) {
00149       Blocks.push_back(*BI);
00150       assert(BlockToChain[*BI] == Chain && "Incoming blocks not in chain");
00151       BlockToChain[*BI] = this;
00152     }
00153   }
00154 
00155 #ifndef NDEBUG
00156   /// \brief Dump the blocks in this chain.
00157   LLVM_DUMP_METHOD void dump() {
00158     for (iterator I = begin(), E = end(); I != E; ++I)
00159       (*I)->dump();
00160   }
00161 #endif // NDEBUG
00162 
00163   /// \brief Count of predecessors within the loop currently being processed.
00164   ///
00165   /// This count is updated at each loop we process to represent the number of
00166   /// in-loop predecessors of this chain.
00167   unsigned LoopPredecessors;
00168 };
00169 }
00170 
00171 namespace {
00172 class MachineBlockPlacement : public MachineFunctionPass {
00173   /// \brief A typedef for a block filter set.
00174   typedef SmallPtrSet<MachineBasicBlock *, 16> BlockFilterSet;
00175 
00176   /// \brief A handle to the branch probability pass.
00177   const MachineBranchProbabilityInfo *MBPI;
00178 
00179   /// \brief A handle to the function-wide block frequency pass.
00180   const MachineBlockFrequencyInfo *MBFI;
00181 
00182   /// \brief A handle to the loop info.
00183   const MachineLoopInfo *MLI;
00184 
00185   /// \brief A handle to the target's instruction info.
00186   const TargetInstrInfo *TII;
00187 
00188   /// \brief A handle to the target's lowering info.
00189   const TargetLoweringBase *TLI;
00190 
00191   /// \brief Allocator and owner of BlockChain structures.
00192   ///
00193   /// We build BlockChains lazily while processing the loop structure of
00194   /// a function. To reduce malloc traffic, we allocate them using this
00195   /// slab-like allocator, and destroy them after the pass completes. An
00196   /// important guarantee is that this allocator produces stable pointers to
00197   /// the chains.
00198   SpecificBumpPtrAllocator<BlockChain> ChainAllocator;
00199 
00200   /// \brief Function wide BasicBlock to BlockChain mapping.
00201   ///
00202   /// This mapping allows efficiently moving from any given basic block to the
00203   /// BlockChain it participates in, if any. We use it to, among other things,
00204   /// allow implicitly defining edges between chains as the existing edges
00205   /// between basic blocks.
00206   DenseMap<MachineBasicBlock *, BlockChain *> BlockToChain;
00207 
00208   void markChainSuccessors(BlockChain &Chain,
00209                            MachineBasicBlock *LoopHeaderBB,
00210                            SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
00211                            const BlockFilterSet *BlockFilter = nullptr);
00212   MachineBasicBlock *selectBestSuccessor(MachineBasicBlock *BB,
00213                                          BlockChain &Chain,
00214                                          const BlockFilterSet *BlockFilter);
00215   MachineBasicBlock *selectBestCandidateBlock(
00216       BlockChain &Chain, SmallVectorImpl<MachineBasicBlock *> &WorkList,
00217       const BlockFilterSet *BlockFilter);
00218   MachineBasicBlock *getFirstUnplacedBlock(
00219       MachineFunction &F,
00220       const BlockChain &PlacedChain,
00221       MachineFunction::iterator &PrevUnplacedBlockIt,
00222       const BlockFilterSet *BlockFilter);
00223   void buildChain(MachineBasicBlock *BB, BlockChain &Chain,
00224                   SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
00225                   const BlockFilterSet *BlockFilter = nullptr);
00226   MachineBasicBlock *findBestLoopTop(MachineLoop &L,
00227                                      const BlockFilterSet &LoopBlockSet);
00228   MachineBasicBlock *findBestLoopExit(MachineFunction &F,
00229                                       MachineLoop &L,
00230                                       const BlockFilterSet &LoopBlockSet);
00231   void buildLoopChains(MachineFunction &F, MachineLoop &L);
00232   void rotateLoop(BlockChain &LoopChain, MachineBasicBlock *ExitingBB,
00233                   const BlockFilterSet &LoopBlockSet);
00234   void buildCFGChains(MachineFunction &F);
00235 
00236 public:
00237   static char ID; // Pass identification, replacement for typeid
00238   MachineBlockPlacement() : MachineFunctionPass(ID) {
00239     initializeMachineBlockPlacementPass(*PassRegistry::getPassRegistry());
00240   }
00241 
00242   bool runOnMachineFunction(MachineFunction &F) override;
00243 
00244   void getAnalysisUsage(AnalysisUsage &AU) const override {
00245     AU.addRequired<MachineBranchProbabilityInfo>();
00246     AU.addRequired<MachineBlockFrequencyInfo>();
00247     AU.addRequired<MachineLoopInfo>();
00248     MachineFunctionPass::getAnalysisUsage(AU);
00249   }
00250 };
00251 }
00252 
00253 char MachineBlockPlacement::ID = 0;
00254 char &llvm::MachineBlockPlacementID = MachineBlockPlacement::ID;
00255 INITIALIZE_PASS_BEGIN(MachineBlockPlacement, "block-placement2",
00256                       "Branch Probability Basic Block Placement", false, false)
00257 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
00258 INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
00259 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
00260 INITIALIZE_PASS_END(MachineBlockPlacement, "block-placement2",
00261                     "Branch Probability Basic Block Placement", false, false)
00262 
00263 #ifndef NDEBUG
00264 /// \brief Helper to print the name of a MBB.
00265 ///
00266 /// Only used by debug logging.
00267 static std::string getBlockName(MachineBasicBlock *BB) {
00268   std::string Result;
00269   raw_string_ostream OS(Result);
00270   OS << "BB#" << BB->getNumber()
00271      << " (derived from LLVM BB '" << BB->getName() << "')";
00272   OS.flush();
00273   return Result;
00274 }
00275 
00276 /// \brief Helper to print the number of a MBB.
00277 ///
00278 /// Only used by debug logging.
00279 static std::string getBlockNum(MachineBasicBlock *BB) {
00280   std::string Result;
00281   raw_string_ostream OS(Result);
00282   OS << "BB#" << BB->getNumber();
00283   OS.flush();
00284   return Result;
00285 }
00286 #endif
00287 
00288 /// \brief Mark a chain's successors as having one fewer preds.
00289 ///
00290 /// When a chain is being merged into the "placed" chain, this routine will
00291 /// quickly walk the successors of each block in the chain and mark them as
00292 /// having one fewer active predecessor. It also adds any successors of this
00293 /// chain which reach the zero-predecessor state to the worklist passed in.
00294 void MachineBlockPlacement::markChainSuccessors(
00295     BlockChain &Chain,
00296     MachineBasicBlock *LoopHeaderBB,
00297     SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
00298     const BlockFilterSet *BlockFilter) {
00299   // Walk all the blocks in this chain, marking their successors as having
00300   // a predecessor placed.
00301   for (BlockChain::iterator CBI = Chain.begin(), CBE = Chain.end();
00302        CBI != CBE; ++CBI) {
00303     // Add any successors for which this is the only un-placed in-loop
00304     // predecessor to the worklist as a viable candidate for CFG-neutral
00305     // placement. No subsequent placement of this block will violate the CFG
00306     // shape, so we get to use heuristics to choose a favorable placement.
00307     for (MachineBasicBlock::succ_iterator SI = (*CBI)->succ_begin(),
00308                                           SE = (*CBI)->succ_end();
00309          SI != SE; ++SI) {
00310       if (BlockFilter && !BlockFilter->count(*SI))
00311         continue;
00312       BlockChain &SuccChain = *BlockToChain[*SI];
00313       // Disregard edges within a fixed chain, or edges to the loop header.
00314       if (&Chain == &SuccChain || *SI == LoopHeaderBB)
00315         continue;
00316 
00317       // This is a cross-chain edge that is within the loop, so decrement the
00318       // loop predecessor count of the destination chain.
00319       if (SuccChain.LoopPredecessors > 0 && --SuccChain.LoopPredecessors == 0)
00320         BlockWorkList.push_back(*SuccChain.begin());
00321     }
00322   }
00323 }
00324 
00325 /// \brief Select the best successor for a block.
00326 ///
00327 /// This looks across all successors of a particular block and attempts to
00328 /// select the "best" one to be the layout successor. It only considers direct
00329 /// successors which also pass the block filter. It will attempt to avoid
00330 /// breaking CFG structure, but cave and break such structures in the case of
00331 /// very hot successor edges.
00332 ///
00333 /// \returns The best successor block found, or null if none are viable.
00334 MachineBasicBlock *MachineBlockPlacement::selectBestSuccessor(
00335     MachineBasicBlock *BB, BlockChain &Chain,
00336     const BlockFilterSet *BlockFilter) {
00337   const BranchProbability HotProb(4, 5); // 80%
00338 
00339   MachineBasicBlock *BestSucc = nullptr;
00340   // FIXME: Due to the performance of the probability and weight routines in
00341   // the MBPI analysis, we manually compute probabilities using the edge
00342   // weights. This is suboptimal as it means that the somewhat subtle
00343   // definition of edge weight semantics is encoded here as well. We should
00344   // improve the MBPI interface to efficiently support query patterns such as
00345   // this.
00346   uint32_t BestWeight = 0;
00347   uint32_t WeightScale = 0;
00348   uint32_t SumWeight = MBPI->getSumForBlock(BB, WeightScale);
00349   DEBUG(dbgs() << "Attempting merge from: " << getBlockName(BB) << "\n");
00350   for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
00351                                         SE = BB->succ_end();
00352        SI != SE; ++SI) {
00353     if (BlockFilter && !BlockFilter->count(*SI))
00354       continue;
00355     BlockChain &SuccChain = *BlockToChain[*SI];
00356     if (&SuccChain == &Chain) {
00357       DEBUG(dbgs() << "    " << getBlockName(*SI) << " -> Already merged!\n");
00358       continue;
00359     }
00360     if (*SI != *SuccChain.begin()) {
00361       DEBUG(dbgs() << "    " << getBlockName(*SI) << " -> Mid chain!\n");
00362       continue;
00363     }
00364 
00365     uint32_t SuccWeight = MBPI->getEdgeWeight(BB, *SI);
00366     BranchProbability SuccProb(SuccWeight / WeightScale, SumWeight);
00367 
00368     // Only consider successors which are either "hot", or wouldn't violate
00369     // any CFG constraints.
00370     if (SuccChain.LoopPredecessors != 0) {
00371       if (SuccProb < HotProb) {
00372         DEBUG(dbgs() << "    " << getBlockName(*SI) << " -> " << SuccProb
00373                      << " (prob) (CFG conflict)\n");
00374         continue;
00375       }
00376 
00377       // Make sure that a hot successor doesn't have a globally more important
00378       // predecessor.
00379       BlockFrequency CandidateEdgeFreq
00380         = MBFI->getBlockFreq(BB) * SuccProb * HotProb.getCompl();
00381       bool BadCFGConflict = false;
00382       for (MachineBasicBlock::pred_iterator PI = (*SI)->pred_begin(),
00383                                             PE = (*SI)->pred_end();
00384            PI != PE; ++PI) {
00385         if (*PI == *SI || (BlockFilter && !BlockFilter->count(*PI)) ||
00386             BlockToChain[*PI] == &Chain)
00387           continue;
00388         BlockFrequency PredEdgeFreq
00389           = MBFI->getBlockFreq(*PI) * MBPI->getEdgeProbability(*PI, *SI);
00390         if (PredEdgeFreq >= CandidateEdgeFreq) {
00391           BadCFGConflict = true;
00392           break;
00393         }
00394       }
00395       if (BadCFGConflict) {
00396         DEBUG(dbgs() << "    " << getBlockName(*SI) << " -> " << SuccProb
00397                      << " (prob) (non-cold CFG conflict)\n");
00398         continue;
00399       }
00400     }
00401 
00402     DEBUG(dbgs() << "    " << getBlockName(*SI) << " -> " << SuccProb
00403                  << " (prob)"
00404                  << (SuccChain.LoopPredecessors != 0 ? " (CFG break)" : "")
00405                  << "\n");
00406     if (BestSucc && BestWeight >= SuccWeight)
00407       continue;
00408     BestSucc = *SI;
00409     BestWeight = SuccWeight;
00410   }
00411   return BestSucc;
00412 }
00413 
00414 /// \brief Select the best block from a worklist.
00415 ///
00416 /// This looks through the provided worklist as a list of candidate basic
00417 /// blocks and select the most profitable one to place. The definition of
00418 /// profitable only really makes sense in the context of a loop. This returns
00419 /// the most frequently visited block in the worklist, which in the case of
00420 /// a loop, is the one most desirable to be physically close to the rest of the
00421 /// loop body in order to improve icache behavior.
00422 ///
00423 /// \returns The best block found, or null if none are viable.
00424 MachineBasicBlock *MachineBlockPlacement::selectBestCandidateBlock(
00425     BlockChain &Chain, SmallVectorImpl<MachineBasicBlock *> &WorkList,
00426     const BlockFilterSet *BlockFilter) {
00427   // Once we need to walk the worklist looking for a candidate, cleanup the
00428   // worklist of already placed entries.
00429   // FIXME: If this shows up on profiles, it could be folded (at the cost of
00430   // some code complexity) into the loop below.
00431   WorkList.erase(std::remove_if(WorkList.begin(), WorkList.end(),
00432                                 [&](MachineBasicBlock *BB) {
00433                    return BlockToChain.lookup(BB) == &Chain;
00434                  }),
00435                  WorkList.end());
00436 
00437   MachineBasicBlock *BestBlock = nullptr;
00438   BlockFrequency BestFreq;
00439   for (SmallVectorImpl<MachineBasicBlock *>::iterator WBI = WorkList.begin(),
00440                                                       WBE = WorkList.end();
00441        WBI != WBE; ++WBI) {
00442     BlockChain &SuccChain = *BlockToChain[*WBI];
00443     if (&SuccChain == &Chain) {
00444       DEBUG(dbgs() << "    " << getBlockName(*WBI)
00445                    << " -> Already merged!\n");
00446       continue;
00447     }
00448     assert(SuccChain.LoopPredecessors == 0 && "Found CFG-violating block");
00449 
00450     BlockFrequency CandidateFreq = MBFI->getBlockFreq(*WBI);
00451     DEBUG(dbgs() << "    " << getBlockName(*WBI) << " -> ";
00452                  MBFI->printBlockFreq(dbgs(), CandidateFreq) << " (freq)\n");
00453     if (BestBlock && BestFreq >= CandidateFreq)
00454       continue;
00455     BestBlock = *WBI;
00456     BestFreq = CandidateFreq;
00457   }
00458   return BestBlock;
00459 }
00460 
00461 /// \brief Retrieve the first unplaced basic block.
00462 ///
00463 /// This routine is called when we are unable to use the CFG to walk through
00464 /// all of the basic blocks and form a chain due to unnatural loops in the CFG.
00465 /// We walk through the function's blocks in order, starting from the
00466 /// LastUnplacedBlockIt. We update this iterator on each call to avoid
00467 /// re-scanning the entire sequence on repeated calls to this routine.
00468 MachineBasicBlock *MachineBlockPlacement::getFirstUnplacedBlock(
00469     MachineFunction &F, const BlockChain &PlacedChain,
00470     MachineFunction::iterator &PrevUnplacedBlockIt,
00471     const BlockFilterSet *BlockFilter) {
00472   for (MachineFunction::iterator I = PrevUnplacedBlockIt, E = F.end(); I != E;
00473        ++I) {
00474     if (BlockFilter && !BlockFilter->count(I))
00475       continue;
00476     if (BlockToChain[I] != &PlacedChain) {
00477       PrevUnplacedBlockIt = I;
00478       // Now select the head of the chain to which the unplaced block belongs
00479       // as the block to place. This will force the entire chain to be placed,
00480       // and satisfies the requirements of merging chains.
00481       return *BlockToChain[I]->begin();
00482     }
00483   }
00484   return nullptr;
00485 }
00486 
00487 void MachineBlockPlacement::buildChain(
00488     MachineBasicBlock *BB,
00489     BlockChain &Chain,
00490     SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
00491     const BlockFilterSet *BlockFilter) {
00492   assert(BB);
00493   assert(BlockToChain[BB] == &Chain);
00494   MachineFunction &F = *BB->getParent();
00495   MachineFunction::iterator PrevUnplacedBlockIt = F.begin();
00496 
00497   MachineBasicBlock *LoopHeaderBB = BB;
00498   markChainSuccessors(Chain, LoopHeaderBB, BlockWorkList, BlockFilter);
00499   BB = *std::prev(Chain.end());
00500   for (;;) {
00501     assert(BB);
00502     assert(BlockToChain[BB] == &Chain);
00503     assert(*std::prev(Chain.end()) == BB);
00504 
00505     // Look for the best viable successor if there is one to place immediately
00506     // after this block.
00507     MachineBasicBlock *BestSucc = selectBestSuccessor(BB, Chain, BlockFilter);
00508 
00509     // If an immediate successor isn't available, look for the best viable
00510     // block among those we've identified as not violating the loop's CFG at
00511     // this point. This won't be a fallthrough, but it will increase locality.
00512     if (!BestSucc)
00513       BestSucc = selectBestCandidateBlock(Chain, BlockWorkList, BlockFilter);
00514 
00515     if (!BestSucc) {
00516       BestSucc = getFirstUnplacedBlock(F, Chain, PrevUnplacedBlockIt,
00517                                        BlockFilter);
00518       if (!BestSucc)
00519         break;
00520 
00521       DEBUG(dbgs() << "Unnatural loop CFG detected, forcibly merging the "
00522                       "layout successor until the CFG reduces\n");
00523     }
00524 
00525     // Place this block, updating the datastructures to reflect its placement.
00526     BlockChain &SuccChain = *BlockToChain[BestSucc];
00527     // Zero out LoopPredecessors for the successor we're about to merge in case
00528     // we selected a successor that didn't fit naturally into the CFG.
00529     SuccChain.LoopPredecessors = 0;
00530     DEBUG(dbgs() << "Merging from " << getBlockNum(BB)
00531                  << " to " << getBlockNum(BestSucc) << "\n");
00532     markChainSuccessors(SuccChain, LoopHeaderBB, BlockWorkList, BlockFilter);
00533     Chain.merge(BestSucc, &SuccChain);
00534     BB = *std::prev(Chain.end());
00535   }
00536 
00537   DEBUG(dbgs() << "Finished forming chain for header block "
00538                << getBlockNum(*Chain.begin()) << "\n");
00539 }
00540 
00541 /// \brief Find the best loop top block for layout.
00542 ///
00543 /// Look for a block which is strictly better than the loop header for laying
00544 /// out at the top of the loop. This looks for one and only one pattern:
00545 /// a latch block with no conditional exit. This block will cause a conditional
00546 /// jump around it or will be the bottom of the loop if we lay it out in place,
00547 /// but if it it doesn't end up at the bottom of the loop for any reason,
00548 /// rotation alone won't fix it. Because such a block will always result in an
00549 /// unconditional jump (for the backedge) rotating it in front of the loop
00550 /// header is always profitable.
00551 MachineBasicBlock *
00552 MachineBlockPlacement::findBestLoopTop(MachineLoop &L,
00553                                        const BlockFilterSet &LoopBlockSet) {
00554   // Check that the header hasn't been fused with a preheader block due to
00555   // crazy branches. If it has, we need to start with the header at the top to
00556   // prevent pulling the preheader into the loop body.
00557   BlockChain &HeaderChain = *BlockToChain[L.getHeader()];
00558   if (!LoopBlockSet.count(*HeaderChain.begin()))
00559     return L.getHeader();
00560 
00561   DEBUG(dbgs() << "Finding best loop top for: "
00562                << getBlockName(L.getHeader()) << "\n");
00563 
00564   BlockFrequency BestPredFreq;
00565   MachineBasicBlock *BestPred = nullptr;
00566   for (MachineBasicBlock::pred_iterator PI = L.getHeader()->pred_begin(),
00567                                         PE = L.getHeader()->pred_end();
00568        PI != PE; ++PI) {
00569     MachineBasicBlock *Pred = *PI;
00570     if (!LoopBlockSet.count(Pred))
00571       continue;
00572     DEBUG(dbgs() << "    header pred: " << getBlockName(Pred) << ", "
00573                  << Pred->succ_size() << " successors, ";
00574                  MBFI->printBlockFreq(dbgs(), Pred) << " freq\n");
00575     if (Pred->succ_size() > 1)
00576       continue;
00577 
00578     BlockFrequency PredFreq = MBFI->getBlockFreq(Pred);
00579     if (!BestPred || PredFreq > BestPredFreq ||
00580         (!(PredFreq < BestPredFreq) &&
00581          Pred->isLayoutSuccessor(L.getHeader()))) {
00582       BestPred = Pred;
00583       BestPredFreq = PredFreq;
00584     }
00585   }
00586 
00587   // If no direct predecessor is fine, just use the loop header.
00588   if (!BestPred)
00589     return L.getHeader();
00590 
00591   // Walk backwards through any straight line of predecessors.
00592   while (BestPred->pred_size() == 1 &&
00593          (*BestPred->pred_begin())->succ_size() == 1 &&
00594          *BestPred->pred_begin() != L.getHeader())
00595     BestPred = *BestPred->pred_begin();
00596 
00597   DEBUG(dbgs() << "    final top: " << getBlockName(BestPred) << "\n");
00598   return BestPred;
00599 }
00600 
00601 
00602 /// \brief Find the best loop exiting block for layout.
00603 ///
00604 /// This routine implements the logic to analyze the loop looking for the best
00605 /// block to layout at the top of the loop. Typically this is done to maximize
00606 /// fallthrough opportunities.
00607 MachineBasicBlock *
00608 MachineBlockPlacement::findBestLoopExit(MachineFunction &F,
00609                                         MachineLoop &L,
00610                                         const BlockFilterSet &LoopBlockSet) {
00611   // We don't want to layout the loop linearly in all cases. If the loop header
00612   // is just a normal basic block in the loop, we want to look for what block
00613   // within the loop is the best one to layout at the top. However, if the loop
00614   // header has be pre-merged into a chain due to predecessors not having
00615   // analyzable branches, *and* the predecessor it is merged with is *not* part
00616   // of the loop, rotating the header into the middle of the loop will create
00617   // a non-contiguous range of blocks which is Very Bad. So start with the
00618   // header and only rotate if safe.
00619   BlockChain &HeaderChain = *BlockToChain[L.getHeader()];
00620   if (!LoopBlockSet.count(*HeaderChain.begin()))
00621     return nullptr;
00622 
00623   BlockFrequency BestExitEdgeFreq;
00624   unsigned BestExitLoopDepth = 0;
00625   MachineBasicBlock *ExitingBB = nullptr;
00626   // If there are exits to outer loops, loop rotation can severely limit
00627   // fallthrough opportunites unless it selects such an exit. Keep a set of
00628   // blocks where rotating to exit with that block will reach an outer loop.
00629   SmallPtrSet<MachineBasicBlock *, 4> BlocksExitingToOuterLoop;
00630 
00631   DEBUG(dbgs() << "Finding best loop exit for: "
00632                << getBlockName(L.getHeader()) << "\n");
00633   for (MachineLoop::block_iterator I = L.block_begin(),
00634                                    E = L.block_end();
00635        I != E; ++I) {
00636     BlockChain &Chain = *BlockToChain[*I];
00637     // Ensure that this block is at the end of a chain; otherwise it could be
00638     // mid-way through an inner loop or a successor of an analyzable branch.
00639     if (*I != *std::prev(Chain.end()))
00640       continue;
00641 
00642     // Now walk the successors. We need to establish whether this has a viable
00643     // exiting successor and whether it has a viable non-exiting successor.
00644     // We store the old exiting state and restore it if a viable looping
00645     // successor isn't found.
00646     MachineBasicBlock *OldExitingBB = ExitingBB;
00647     BlockFrequency OldBestExitEdgeFreq = BestExitEdgeFreq;
00648     bool HasLoopingSucc = false;
00649     // FIXME: Due to the performance of the probability and weight routines in
00650     // the MBPI analysis, we use the internal weights and manually compute the
00651     // probabilities to avoid quadratic behavior.
00652     uint32_t WeightScale = 0;
00653     uint32_t SumWeight = MBPI->getSumForBlock(*I, WeightScale);
00654     for (MachineBasicBlock::succ_iterator SI = (*I)->succ_begin(),
00655                                           SE = (*I)->succ_end();
00656          SI != SE; ++SI) {
00657       if ((*SI)->isLandingPad())
00658         continue;
00659       if (*SI == *I)
00660         continue;
00661       BlockChain &SuccChain = *BlockToChain[*SI];
00662       // Don't split chains, either this chain or the successor's chain.
00663       if (&Chain == &SuccChain) {
00664         DEBUG(dbgs() << "    exiting: " << getBlockName(*I) << " -> "
00665                      << getBlockName(*SI) << " (chain conflict)\n");
00666         continue;
00667       }
00668 
00669       uint32_t SuccWeight = MBPI->getEdgeWeight(*I, *SI);
00670       if (LoopBlockSet.count(*SI)) {
00671         DEBUG(dbgs() << "    looping: " << getBlockName(*I) << " -> "
00672                      << getBlockName(*SI) << " (" << SuccWeight << ")\n");
00673         HasLoopingSucc = true;
00674         continue;
00675       }
00676 
00677       unsigned SuccLoopDepth = 0;
00678       if (MachineLoop *ExitLoop = MLI->getLoopFor(*SI)) {
00679         SuccLoopDepth = ExitLoop->getLoopDepth();
00680         if (ExitLoop->contains(&L))
00681           BlocksExitingToOuterLoop.insert(*I);
00682       }
00683 
00684       BranchProbability SuccProb(SuccWeight / WeightScale, SumWeight);
00685       BlockFrequency ExitEdgeFreq = MBFI->getBlockFreq(*I) * SuccProb;
00686       DEBUG(dbgs() << "    exiting: " << getBlockName(*I) << " -> "
00687                    << getBlockName(*SI) << " [L:" << SuccLoopDepth
00688                    << "] (";
00689                    MBFI->printBlockFreq(dbgs(), ExitEdgeFreq) << ")\n");
00690       // Note that we bias this toward an existing layout successor to retain
00691       // incoming order in the absence of better information. The exit must have
00692       // a frequency higher than the current exit before we consider breaking
00693       // the layout.
00694       BranchProbability Bias(100 - ExitBlockBias, 100);
00695       if (!ExitingBB || BestExitLoopDepth < SuccLoopDepth ||
00696           ExitEdgeFreq > BestExitEdgeFreq ||
00697           ((*I)->isLayoutSuccessor(*SI) &&
00698            !(ExitEdgeFreq < BestExitEdgeFreq * Bias))) {
00699         BestExitEdgeFreq = ExitEdgeFreq;
00700         ExitingBB = *I;
00701       }
00702     }
00703 
00704     // Restore the old exiting state, no viable looping successor was found.
00705     if (!HasLoopingSucc) {
00706       ExitingBB = OldExitingBB;
00707       BestExitEdgeFreq = OldBestExitEdgeFreq;
00708       continue;
00709     }
00710   }
00711   // Without a candidate exiting block or with only a single block in the
00712   // loop, just use the loop header to layout the loop.
00713   if (!ExitingBB || L.getNumBlocks() == 1)
00714     return nullptr;
00715 
00716   // Also, if we have exit blocks which lead to outer loops but didn't select
00717   // one of them as the exiting block we are rotating toward, disable loop
00718   // rotation altogether.
00719   if (!BlocksExitingToOuterLoop.empty() &&
00720       !BlocksExitingToOuterLoop.count(ExitingBB))
00721     return nullptr;
00722 
00723   DEBUG(dbgs() << "  Best exiting block: " << getBlockName(ExitingBB) << "\n");
00724   return ExitingBB;
00725 }
00726 
00727 /// \brief Attempt to rotate an exiting block to the bottom of the loop.
00728 ///
00729 /// Once we have built a chain, try to rotate it to line up the hot exit block
00730 /// with fallthrough out of the loop if doing so doesn't introduce unnecessary
00731 /// branches. For example, if the loop has fallthrough into its header and out
00732 /// of its bottom already, don't rotate it.
00733 void MachineBlockPlacement::rotateLoop(BlockChain &LoopChain,
00734                                        MachineBasicBlock *ExitingBB,
00735                                        const BlockFilterSet &LoopBlockSet) {
00736   if (!ExitingBB)
00737     return;
00738 
00739   MachineBasicBlock *Top = *LoopChain.begin();
00740   bool ViableTopFallthrough = false;
00741   for (MachineBasicBlock::pred_iterator PI = Top->pred_begin(),
00742                                         PE = Top->pred_end();
00743        PI != PE; ++PI) {
00744     BlockChain *PredChain = BlockToChain[*PI];
00745     if (!LoopBlockSet.count(*PI) &&
00746         (!PredChain || *PI == *std::prev(PredChain->end()))) {
00747       ViableTopFallthrough = true;
00748       break;
00749     }
00750   }
00751 
00752   // If the header has viable fallthrough, check whether the current loop
00753   // bottom is a viable exiting block. If so, bail out as rotating will
00754   // introduce an unnecessary branch.
00755   if (ViableTopFallthrough) {
00756     MachineBasicBlock *Bottom = *std::prev(LoopChain.end());
00757     for (MachineBasicBlock::succ_iterator SI = Bottom->succ_begin(),
00758                                           SE = Bottom->succ_end();
00759          SI != SE; ++SI) {
00760       BlockChain *SuccChain = BlockToChain[*SI];
00761       if (!LoopBlockSet.count(*SI) &&
00762           (!SuccChain || *SI == *SuccChain->begin()))
00763         return;
00764     }
00765   }
00766 
00767   BlockChain::iterator ExitIt = std::find(LoopChain.begin(), LoopChain.end(),
00768                                           ExitingBB);
00769   if (ExitIt == LoopChain.end())
00770     return;
00771 
00772   std::rotate(LoopChain.begin(), std::next(ExitIt), LoopChain.end());
00773 }
00774 
00775 /// \brief Forms basic block chains from the natural loop structures.
00776 ///
00777 /// These chains are designed to preserve the existing *structure* of the code
00778 /// as much as possible. We can then stitch the chains together in a way which
00779 /// both preserves the topological structure and minimizes taken conditional
00780 /// branches.
00781 void MachineBlockPlacement::buildLoopChains(MachineFunction &F,
00782                                             MachineLoop &L) {
00783   // First recurse through any nested loops, building chains for those inner
00784   // loops.
00785   for (MachineLoop::iterator LI = L.begin(), LE = L.end(); LI != LE; ++LI)
00786     buildLoopChains(F, **LI);
00787 
00788   SmallVector<MachineBasicBlock *, 16> BlockWorkList;
00789   BlockFilterSet LoopBlockSet(L.block_begin(), L.block_end());
00790 
00791   // First check to see if there is an obviously preferable top block for the
00792   // loop. This will default to the header, but may end up as one of the
00793   // predecessors to the header if there is one which will result in strictly
00794   // fewer branches in the loop body.
00795   MachineBasicBlock *LoopTop = findBestLoopTop(L, LoopBlockSet);
00796 
00797   // If we selected just the header for the loop top, look for a potentially
00798   // profitable exit block in the event that rotating the loop can eliminate
00799   // branches by placing an exit edge at the bottom.
00800   MachineBasicBlock *ExitingBB = nullptr;
00801   if (LoopTop == L.getHeader())
00802     ExitingBB = findBestLoopExit(F, L, LoopBlockSet);
00803 
00804   BlockChain &LoopChain = *BlockToChain[LoopTop];
00805 
00806   // FIXME: This is a really lame way of walking the chains in the loop: we
00807   // walk the blocks, and use a set to prevent visiting a particular chain
00808   // twice.
00809   SmallPtrSet<BlockChain *, 4> UpdatedPreds;
00810   assert(LoopChain.LoopPredecessors == 0);
00811   UpdatedPreds.insert(&LoopChain);
00812   for (MachineLoop::block_iterator BI = L.block_begin(),
00813                                    BE = L.block_end();
00814        BI != BE; ++BI) {
00815     BlockChain &Chain = *BlockToChain[*BI];
00816     if (!UpdatedPreds.insert(&Chain))
00817       continue;
00818 
00819     assert(Chain.LoopPredecessors == 0);
00820     for (BlockChain::iterator BCI = Chain.begin(), BCE = Chain.end();
00821          BCI != BCE; ++BCI) {
00822       assert(BlockToChain[*BCI] == &Chain);
00823       for (MachineBasicBlock::pred_iterator PI = (*BCI)->pred_begin(),
00824                                             PE = (*BCI)->pred_end();
00825            PI != PE; ++PI) {
00826         if (BlockToChain[*PI] == &Chain || !LoopBlockSet.count(*PI))
00827           continue;
00828         ++Chain.LoopPredecessors;
00829       }
00830     }
00831 
00832     if (Chain.LoopPredecessors == 0)
00833       BlockWorkList.push_back(*Chain.begin());
00834   }
00835 
00836   buildChain(LoopTop, LoopChain, BlockWorkList, &LoopBlockSet);
00837   rotateLoop(LoopChain, ExitingBB, LoopBlockSet);
00838 
00839   DEBUG({
00840     // Crash at the end so we get all of the debugging output first.
00841     bool BadLoop = false;
00842     if (LoopChain.LoopPredecessors) {
00843       BadLoop = true;
00844       dbgs() << "Loop chain contains a block without its preds placed!\n"
00845              << "  Loop header:  " << getBlockName(*L.block_begin()) << "\n"
00846              << "  Chain header: " << getBlockName(*LoopChain.begin()) << "\n";
00847     }
00848     for (BlockChain::iterator BCI = LoopChain.begin(), BCE = LoopChain.end();
00849          BCI != BCE; ++BCI) {
00850       dbgs() << "          ... " << getBlockName(*BCI) << "\n";
00851       if (!LoopBlockSet.erase(*BCI)) {
00852         // We don't mark the loop as bad here because there are real situations
00853         // where this can occur. For example, with an unanalyzable fallthrough
00854         // from a loop block to a non-loop block or vice versa.
00855         dbgs() << "Loop chain contains a block not contained by the loop!\n"
00856                << "  Loop header:  " << getBlockName(*L.block_begin()) << "\n"
00857                << "  Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
00858                << "  Bad block:    " << getBlockName(*BCI) << "\n";
00859       }
00860     }
00861 
00862     if (!LoopBlockSet.empty()) {
00863       BadLoop = true;
00864       for (BlockFilterSet::iterator LBI = LoopBlockSet.begin(),
00865                                     LBE = LoopBlockSet.end();
00866            LBI != LBE; ++LBI)
00867         dbgs() << "Loop contains blocks never placed into a chain!\n"
00868                << "  Loop header:  " << getBlockName(*L.block_begin()) << "\n"
00869                << "  Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
00870                << "  Bad block:    " << getBlockName(*LBI) << "\n";
00871     }
00872     assert(!BadLoop && "Detected problems with the placement of this loop.");
00873   });
00874 }
00875 
00876 void MachineBlockPlacement::buildCFGChains(MachineFunction &F) {
00877   // Ensure that every BB in the function has an associated chain to simplify
00878   // the assumptions of the remaining algorithm.
00879   SmallVector<MachineOperand, 4> Cond; // For AnalyzeBranch.
00880   for (MachineFunction::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
00881     MachineBasicBlock *BB = FI;
00882     BlockChain *Chain
00883       = new (ChainAllocator.Allocate()) BlockChain(BlockToChain, BB);
00884     // Also, merge any blocks which we cannot reason about and must preserve
00885     // the exact fallthrough behavior for.
00886     for (;;) {
00887       Cond.clear();
00888       MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
00889       if (!TII->AnalyzeBranch(*BB, TBB, FBB, Cond) || !FI->canFallThrough())
00890         break;
00891 
00892       MachineFunction::iterator NextFI(std::next(FI));
00893       MachineBasicBlock *NextBB = NextFI;
00894       // Ensure that the layout successor is a viable block, as we know that
00895       // fallthrough is a possibility.
00896       assert(NextFI != FE && "Can't fallthrough past the last block.");
00897       DEBUG(dbgs() << "Pre-merging due to unanalyzable fallthrough: "
00898                    << getBlockName(BB) << " -> " << getBlockName(NextBB)
00899                    << "\n");
00900       Chain->merge(NextBB, nullptr);
00901       FI = NextFI;
00902       BB = NextBB;
00903     }
00904   }
00905 
00906   // Build any loop-based chains.
00907   for (MachineLoopInfo::iterator LI = MLI->begin(), LE = MLI->end(); LI != LE;
00908        ++LI)
00909     buildLoopChains(F, **LI);
00910 
00911   SmallVector<MachineBasicBlock *, 16> BlockWorkList;
00912 
00913   SmallPtrSet<BlockChain *, 4> UpdatedPreds;
00914   for (MachineFunction::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
00915     MachineBasicBlock *BB = &*FI;
00916     BlockChain &Chain = *BlockToChain[BB];
00917     if (!UpdatedPreds.insert(&Chain))
00918       continue;
00919 
00920     assert(Chain.LoopPredecessors == 0);
00921     for (BlockChain::iterator BCI = Chain.begin(), BCE = Chain.end();
00922          BCI != BCE; ++BCI) {
00923       assert(BlockToChain[*BCI] == &Chain);
00924       for (MachineBasicBlock::pred_iterator PI = (*BCI)->pred_begin(),
00925                                             PE = (*BCI)->pred_end();
00926            PI != PE; ++PI) {
00927         if (BlockToChain[*PI] == &Chain)
00928           continue;
00929         ++Chain.LoopPredecessors;
00930       }
00931     }
00932 
00933     if (Chain.LoopPredecessors == 0)
00934       BlockWorkList.push_back(*Chain.begin());
00935   }
00936 
00937   BlockChain &FunctionChain = *BlockToChain[&F.front()];
00938   buildChain(&F.front(), FunctionChain, BlockWorkList);
00939 
00940 #ifndef NDEBUG
00941   typedef SmallPtrSet<MachineBasicBlock *, 16> FunctionBlockSetType;
00942 #endif
00943   DEBUG({
00944     // Crash at the end so we get all of the debugging output first.
00945     bool BadFunc = false;
00946     FunctionBlockSetType FunctionBlockSet;
00947     for (MachineFunction::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI)
00948       FunctionBlockSet.insert(FI);
00949 
00950     for (BlockChain::iterator BCI = FunctionChain.begin(),
00951                               BCE = FunctionChain.end();
00952          BCI != BCE; ++BCI)
00953       if (!FunctionBlockSet.erase(*BCI)) {
00954         BadFunc = true;
00955         dbgs() << "Function chain contains a block not in the function!\n"
00956                << "  Bad block:    " << getBlockName(*BCI) << "\n";
00957       }
00958 
00959     if (!FunctionBlockSet.empty()) {
00960       BadFunc = true;
00961       for (FunctionBlockSetType::iterator FBI = FunctionBlockSet.begin(),
00962                                           FBE = FunctionBlockSet.end();
00963            FBI != FBE; ++FBI)
00964         dbgs() << "Function contains blocks never placed into a chain!\n"
00965                << "  Bad block:    " << getBlockName(*FBI) << "\n";
00966     }
00967     assert(!BadFunc && "Detected problems with the block placement.");
00968   });
00969 
00970   // Splice the blocks into place.
00971   MachineFunction::iterator InsertPos = F.begin();
00972   for (BlockChain::iterator BI = FunctionChain.begin(),
00973                             BE = FunctionChain.end();
00974        BI != BE; ++BI) {
00975     DEBUG(dbgs() << (BI == FunctionChain.begin() ? "Placing chain "
00976                                                   : "          ... ")
00977           << getBlockName(*BI) << "\n");
00978     if (InsertPos != MachineFunction::iterator(*BI))
00979       F.splice(InsertPos, *BI);
00980     else
00981       ++InsertPos;
00982 
00983     // Update the terminator of the previous block.
00984     if (BI == FunctionChain.begin())
00985       continue;
00986     MachineBasicBlock *PrevBB = std::prev(MachineFunction::iterator(*BI));
00987 
00988     // FIXME: It would be awesome of updateTerminator would just return rather
00989     // than assert when the branch cannot be analyzed in order to remove this
00990     // boiler plate.
00991     Cond.clear();
00992     MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
00993     if (!TII->AnalyzeBranch(*PrevBB, TBB, FBB, Cond)) {
00994       // The "PrevBB" is not yet updated to reflect current code layout, so,
00995       //   o. it may fall-through to a block without explict "goto" instruction
00996       //      before layout, and no longer fall-through it after layout; or 
00997       //   o. just opposite.
00998       // 
00999       // AnalyzeBranch() may return erroneous value for FBB when these two
01000       // situations take place. For the first scenario FBB is mistakenly set
01001       // NULL; for the 2nd scenario, the FBB, which is expected to be NULL,
01002       // is mistakenly pointing to "*BI".
01003       //
01004       bool needUpdateBr = true;
01005       if (!Cond.empty() && (!FBB || FBB == *BI)) {
01006         PrevBB->updateTerminator();
01007         needUpdateBr = false;
01008         Cond.clear();
01009         TBB = FBB = nullptr;
01010         if (TII->AnalyzeBranch(*PrevBB, TBB, FBB, Cond)) {
01011           // FIXME: This should never take place.
01012           TBB = FBB = nullptr;
01013         }
01014       }
01015 
01016       // If PrevBB has a two-way branch, try to re-order the branches
01017       // such that we branch to the successor with higher weight first.
01018       if (TBB && !Cond.empty() && FBB &&
01019           MBPI->getEdgeWeight(PrevBB, FBB) > MBPI->getEdgeWeight(PrevBB, TBB) &&
01020           !TII->ReverseBranchCondition(Cond)) {
01021         DEBUG(dbgs() << "Reverse order of the two branches: "
01022                      << getBlockName(PrevBB) << "\n");
01023         DEBUG(dbgs() << "    Edge weight: " << MBPI->getEdgeWeight(PrevBB, FBB)
01024                      << " vs " << MBPI->getEdgeWeight(PrevBB, TBB) << "\n");
01025         DebugLoc dl;  // FIXME: this is nowhere
01026         TII->RemoveBranch(*PrevBB);
01027         TII->InsertBranch(*PrevBB, FBB, TBB, Cond, dl);
01028         needUpdateBr = true;
01029       }
01030       if (needUpdateBr)
01031         PrevBB->updateTerminator();
01032     }
01033   }
01034 
01035   // Fixup the last block.
01036   Cond.clear();
01037   MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
01038   if (!TII->AnalyzeBranch(F.back(), TBB, FBB, Cond))
01039     F.back().updateTerminator();
01040 
01041   // Walk through the backedges of the function now that we have fully laid out
01042   // the basic blocks and align the destination of each backedge. We don't rely
01043   // exclusively on the loop info here so that we can align backedges in
01044   // unnatural CFGs and backedges that were introduced purely because of the
01045   // loop rotations done during this layout pass.
01046   if (F.getFunction()->getAttributes().
01047         hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize))
01048     return;
01049   unsigned Align = TLI->getPrefLoopAlignment();
01050   if (!Align)
01051     return;  // Don't care about loop alignment.
01052   if (FunctionChain.begin() == FunctionChain.end())
01053     return;  // Empty chain.
01054 
01055   const BranchProbability ColdProb(1, 5); // 20%
01056   BlockFrequency EntryFreq = MBFI->getBlockFreq(F.begin());
01057   BlockFrequency WeightedEntryFreq = EntryFreq * ColdProb;
01058   for (BlockChain::iterator BI = std::next(FunctionChain.begin()),
01059                             BE = FunctionChain.end();
01060        BI != BE; ++BI) {
01061     // Don't align non-looping basic blocks. These are unlikely to execute
01062     // enough times to matter in practice. Note that we'll still handle
01063     // unnatural CFGs inside of a natural outer loop (the common case) and
01064     // rotated loops.
01065     MachineLoop *L = MLI->getLoopFor(*BI);
01066     if (!L)
01067       continue;
01068 
01069     // If the block is cold relative to the function entry don't waste space
01070     // aligning it.
01071     BlockFrequency Freq = MBFI->getBlockFreq(*BI);
01072     if (Freq < WeightedEntryFreq)
01073       continue;
01074 
01075     // If the block is cold relative to its loop header, don't align it
01076     // regardless of what edges into the block exist.
01077     MachineBasicBlock *LoopHeader = L->getHeader();
01078     BlockFrequency LoopHeaderFreq = MBFI->getBlockFreq(LoopHeader);
01079     if (Freq < (LoopHeaderFreq * ColdProb))
01080       continue;
01081 
01082     // Check for the existence of a non-layout predecessor which would benefit
01083     // from aligning this block.
01084     MachineBasicBlock *LayoutPred = *std::prev(BI);
01085 
01086     // Force alignment if all the predecessors are jumps. We already checked
01087     // that the block isn't cold above.
01088     if (!LayoutPred->isSuccessor(*BI)) {
01089       (*BI)->setAlignment(Align);
01090       continue;
01091     }
01092 
01093     // Align this block if the layout predecessor's edge into this block is
01094     // cold relative to the block. When this is true, other predecessors make up
01095     // all of the hot entries into the block and thus alignment is likely to be
01096     // important.
01097     BranchProbability LayoutProb = MBPI->getEdgeProbability(LayoutPred, *BI);
01098     BlockFrequency LayoutEdgeFreq = MBFI->getBlockFreq(LayoutPred) * LayoutProb;
01099     if (LayoutEdgeFreq <= (Freq * ColdProb))
01100       (*BI)->setAlignment(Align);
01101   }
01102 }
01103 
01104 bool MachineBlockPlacement::runOnMachineFunction(MachineFunction &F) {
01105   // Check for single-block functions and skip them.
01106   if (std::next(F.begin()) == F.end())
01107     return false;
01108 
01109   if (skipOptnoneFunction(*F.getFunction()))
01110     return false;
01111 
01112   MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
01113   MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
01114   MLI = &getAnalysis<MachineLoopInfo>();
01115   TII = F.getSubtarget().getInstrInfo();
01116   TLI = F.getSubtarget().getTargetLowering();
01117   assert(BlockToChain.empty());
01118 
01119   buildCFGChains(F);
01120 
01121   BlockToChain.clear();
01122   ChainAllocator.DestroyAll();
01123 
01124   if (AlignAllBlock)
01125     // Align all of the blocks in the function to a specific alignment.
01126     for (MachineFunction::iterator FI = F.begin(), FE = F.end();
01127          FI != FE; ++FI)
01128       FI->setAlignment(AlignAllBlock);
01129 
01130   // We always return true as we have no way to track whether the final order
01131   // differs from the original order.
01132   return true;
01133 }
01134 
01135 namespace {
01136 /// \brief A pass to compute block placement statistics.
01137 ///
01138 /// A separate pass to compute interesting statistics for evaluating block
01139 /// placement. This is separate from the actual placement pass so that they can
01140 /// be computed in the absence of any placement transformations or when using
01141 /// alternative placement strategies.
01142 class MachineBlockPlacementStats : public MachineFunctionPass {
01143   /// \brief A handle to the branch probability pass.
01144   const MachineBranchProbabilityInfo *MBPI;
01145 
01146   /// \brief A handle to the function-wide block frequency pass.
01147   const MachineBlockFrequencyInfo *MBFI;
01148 
01149 public:
01150   static char ID; // Pass identification, replacement for typeid
01151   MachineBlockPlacementStats() : MachineFunctionPass(ID) {
01152     initializeMachineBlockPlacementStatsPass(*PassRegistry::getPassRegistry());
01153   }
01154 
01155   bool runOnMachineFunction(MachineFunction &F) override;
01156 
01157   void getAnalysisUsage(AnalysisUsage &AU) const override {
01158     AU.addRequired<MachineBranchProbabilityInfo>();
01159     AU.addRequired<MachineBlockFrequencyInfo>();
01160     AU.setPreservesAll();
01161     MachineFunctionPass::getAnalysisUsage(AU);
01162   }
01163 };
01164 }
01165 
01166 char MachineBlockPlacementStats::ID = 0;
01167 char &llvm::MachineBlockPlacementStatsID = MachineBlockPlacementStats::ID;
01168 INITIALIZE_PASS_BEGIN(MachineBlockPlacementStats, "block-placement-stats",
01169                       "Basic Block Placement Stats", false, false)
01170 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
01171 INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
01172 INITIALIZE_PASS_END(MachineBlockPlacementStats, "block-placement-stats",
01173                     "Basic Block Placement Stats", false, false)
01174 
01175 bool MachineBlockPlacementStats::runOnMachineFunction(MachineFunction &F) {
01176   // Check for single-block functions and skip them.
01177   if (std::next(F.begin()) == F.end())
01178     return false;
01179 
01180   MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
01181   MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
01182 
01183   for (MachineFunction::iterator I = F.begin(), E = F.end(); I != E; ++I) {
01184     BlockFrequency BlockFreq = MBFI->getBlockFreq(I);
01185     Statistic &NumBranches = (I->succ_size() > 1) ? NumCondBranches
01186                                                   : NumUncondBranches;
01187     Statistic &BranchTakenFreq = (I->succ_size() > 1) ? CondBranchTakenFreq
01188                                                       : UncondBranchTakenFreq;
01189     for (MachineBasicBlock::succ_iterator SI = I->succ_begin(),
01190                                           SE = I->succ_end();
01191          SI != SE; ++SI) {
01192       // Skip if this successor is a fallthrough.
01193       if (I->isLayoutSuccessor(*SI))
01194         continue;
01195 
01196       BlockFrequency EdgeFreq = BlockFreq * MBPI->getEdgeProbability(I, *SI);
01197       ++NumBranches;
01198       BranchTakenFreq += EdgeFreq.getFrequency();
01199     }
01200   }
01201 
01202   return false;
01203 }
01204