1dff0c46cSDimitry Andric //===-- MachineBlockPlacement.cpp - Basic Block Code Layout optimization --===// 2dff0c46cSDimitry Andric // 3dff0c46cSDimitry Andric // The LLVM Compiler Infrastructure 4dff0c46cSDimitry Andric // 5dff0c46cSDimitry Andric // This file is distributed under the University of Illinois Open Source 6dff0c46cSDimitry Andric // License. See LICENSE.TXT for details. 7dff0c46cSDimitry Andric // 8dff0c46cSDimitry Andric //===----------------------------------------------------------------------===// 9dff0c46cSDimitry Andric // 10dff0c46cSDimitry Andric // This file implements basic block placement transformations using the CFG 11dff0c46cSDimitry Andric // structure and branch probability estimates. 12dff0c46cSDimitry Andric // 13dff0c46cSDimitry Andric // The pass strives to preserve the structure of the CFG (that is, retain 147ae0e2c9SDimitry Andric // a topological ordering of basic blocks) in the absence of a *strong* signal 15dff0c46cSDimitry Andric // to the contrary from probabilities. However, within the CFG structure, it 16dff0c46cSDimitry Andric // attempts to choose an ordering which favors placing more likely sequences of 17dff0c46cSDimitry Andric // blocks adjacent to each other. 18dff0c46cSDimitry Andric // 19dff0c46cSDimitry Andric // The algorithm works from the inner-most loop within a function outward, and 20dff0c46cSDimitry Andric // at each stage walks through the basic blocks, trying to coalesce them into 21dff0c46cSDimitry Andric // sequential chains where allowed by the CFG (or demanded by heavy 22dff0c46cSDimitry Andric // probabilities). Finally, it walks the blocks in topological order, and the 23dff0c46cSDimitry Andric // first time it reaches a chain of basic blocks, it schedules them in the 24dff0c46cSDimitry Andric // function in-order. 25dff0c46cSDimitry Andric // 26dff0c46cSDimitry Andric //===----------------------------------------------------------------------===// 27dff0c46cSDimitry Andric 28139f7f9bSDimitry Andric #include "llvm/CodeGen/Passes.h" 293ca95b02SDimitry Andric #include "llvm/CodeGen/TargetPassConfig.h" 303ca95b02SDimitry Andric #include "BranchFolding.h" 31139f7f9bSDimitry Andric #include "llvm/ADT/DenseMap.h" 32139f7f9bSDimitry Andric #include "llvm/ADT/SmallPtrSet.h" 33139f7f9bSDimitry Andric #include "llvm/ADT/SmallVector.h" 34139f7f9bSDimitry Andric #include "llvm/ADT/Statistic.h" 357a7e6055SDimitry Andric #include "llvm/Analysis/BlockFrequencyInfoImpl.h" 36dff0c46cSDimitry Andric #include "llvm/CodeGen/MachineBasicBlock.h" 37dff0c46cSDimitry Andric #include "llvm/CodeGen/MachineBlockFrequencyInfo.h" 38dff0c46cSDimitry Andric #include "llvm/CodeGen/MachineBranchProbabilityInfo.h" 39dff0c46cSDimitry Andric #include "llvm/CodeGen/MachineFunction.h" 40dff0c46cSDimitry Andric #include "llvm/CodeGen/MachineFunctionPass.h" 41dff0c46cSDimitry Andric #include "llvm/CodeGen/MachineLoopInfo.h" 42dff0c46cSDimitry Andric #include "llvm/CodeGen/MachineModuleInfo.h" 437a7e6055SDimitry Andric #include "llvm/CodeGen/MachinePostDominators.h" 44d88c1a5aSDimitry Andric #include "llvm/CodeGen/TailDuplicator.h" 45dff0c46cSDimitry Andric #include "llvm/Support/Allocator.h" 46284c1978SDimitry Andric #include "llvm/Support/CommandLine.h" 47dff0c46cSDimitry Andric #include "llvm/Support/Debug.h" 48ff0cc061SDimitry Andric #include "llvm/Support/raw_ostream.h" 49dff0c46cSDimitry Andric #include "llvm/Target/TargetInstrInfo.h" 50dff0c46cSDimitry Andric #include "llvm/Target/TargetLowering.h" 5139d628a0SDimitry Andric #include "llvm/Target/TargetSubtargetInfo.h" 52dff0c46cSDimitry Andric #include <algorithm> 537a7e6055SDimitry Andric #include <functional> 547a7e6055SDimitry Andric #include <utility> 55dff0c46cSDimitry Andric using namespace llvm; 56dff0c46cSDimitry Andric 57ff0cc061SDimitry Andric #define DEBUG_TYPE "block-placement" 5891bc56edSDimitry Andric 59dff0c46cSDimitry Andric STATISTIC(NumCondBranches, "Number of conditional branches"); 607d523365SDimitry Andric STATISTIC(NumUncondBranches, "Number of unconditional branches"); 61dff0c46cSDimitry Andric STATISTIC(CondBranchTakenFreq, 62dff0c46cSDimitry Andric "Potential frequency of taking conditional branches"); 63dff0c46cSDimitry Andric STATISTIC(UncondBranchTakenFreq, 64dff0c46cSDimitry Andric "Potential frequency of taking unconditional branches"); 65dff0c46cSDimitry Andric 66284c1978SDimitry Andric static cl::opt<unsigned> AlignAllBlock("align-all-blocks", 67284c1978SDimitry Andric cl::desc("Force the alignment of all " 68284c1978SDimitry Andric "blocks in the function."), 69284c1978SDimitry Andric cl::init(0), cl::Hidden); 70284c1978SDimitry Andric 713ca95b02SDimitry Andric static cl::opt<unsigned> AlignAllNonFallThruBlocks( 723ca95b02SDimitry Andric "align-all-nofallthru-blocks", 733ca95b02SDimitry Andric cl::desc("Force the alignment of all " 743ca95b02SDimitry Andric "blocks that have no fall-through predecessors (i.e. don't add " 753ca95b02SDimitry Andric "nops that are executed)."), 767d523365SDimitry Andric cl::init(0), cl::Hidden); 777d523365SDimitry Andric 7891bc56edSDimitry Andric // FIXME: Find a good default for this flag and remove the flag. 79ff0cc061SDimitry Andric static cl::opt<unsigned> ExitBlockBias( 80ff0cc061SDimitry Andric "block-placement-exit-block-bias", 8191bc56edSDimitry Andric cl::desc("Block frequency percentage a loop exit block needs " 8291bc56edSDimitry Andric "over the original exit to be considered the new exit."), 8391bc56edSDimitry Andric cl::init(0), cl::Hidden); 8491bc56edSDimitry Andric 85d88c1a5aSDimitry Andric // Definition: 86d88c1a5aSDimitry Andric // - Outlining: placement of a basic block outside the chain or hot path. 87d88c1a5aSDimitry Andric 887d523365SDimitry Andric static cl::opt<unsigned> LoopToColdBlockRatio( 897d523365SDimitry Andric "loop-to-cold-block-ratio", 907d523365SDimitry Andric cl::desc("Outline loop blocks from loop chain if (frequency of loop) / " 917d523365SDimitry Andric "(frequency of block) is greater than this ratio"), 927d523365SDimitry Andric cl::init(5), cl::Hidden); 937d523365SDimitry Andric 947d523365SDimitry Andric static cl::opt<bool> 957d523365SDimitry Andric PreciseRotationCost("precise-rotation-cost", 967d523365SDimitry Andric cl::desc("Model the cost of loop rotation more " 977d523365SDimitry Andric "precisely by using profile data."), 987d523365SDimitry Andric cl::init(false), cl::Hidden); 993ca95b02SDimitry Andric static cl::opt<bool> 1003ca95b02SDimitry Andric ForcePreciseRotationCost("force-precise-rotation-cost", 1013ca95b02SDimitry Andric cl::desc("Force the use of precise cost " 1023ca95b02SDimitry Andric "loop rotation strategy."), 1033ca95b02SDimitry Andric cl::init(false), cl::Hidden); 1047d523365SDimitry Andric 1057d523365SDimitry Andric static cl::opt<unsigned> MisfetchCost( 1067d523365SDimitry Andric "misfetch-cost", 1073ca95b02SDimitry Andric cl::desc("Cost that models the probabilistic risk of an instruction " 1087d523365SDimitry Andric "misfetch due to a jump comparing to falling through, whose cost " 1097d523365SDimitry Andric "is zero."), 1107d523365SDimitry Andric cl::init(1), cl::Hidden); 1117d523365SDimitry Andric 1127d523365SDimitry Andric static cl::opt<unsigned> JumpInstCost("jump-inst-cost", 1137d523365SDimitry Andric cl::desc("Cost of jump instructions."), 1147d523365SDimitry Andric cl::init(1), cl::Hidden); 115d88c1a5aSDimitry Andric static cl::opt<bool> 116d88c1a5aSDimitry Andric TailDupPlacement("tail-dup-placement", 117d88c1a5aSDimitry Andric cl::desc("Perform tail duplication during placement. " 118d88c1a5aSDimitry Andric "Creates more fallthrough opportunites in " 119d88c1a5aSDimitry Andric "outline branches."), 120d88c1a5aSDimitry Andric cl::init(true), cl::Hidden); 1217d523365SDimitry Andric 1223ca95b02SDimitry Andric static cl::opt<bool> 1233ca95b02SDimitry Andric BranchFoldPlacement("branch-fold-placement", 1243ca95b02SDimitry Andric cl::desc("Perform branch folding during placement. " 1253ca95b02SDimitry Andric "Reduces code size."), 1263ca95b02SDimitry Andric cl::init(true), cl::Hidden); 1273ca95b02SDimitry Andric 128d88c1a5aSDimitry Andric // Heuristic for tail duplication. 1297a7e6055SDimitry Andric static cl::opt<unsigned> TailDupPlacementThreshold( 130d88c1a5aSDimitry Andric "tail-dup-placement-threshold", 131d88c1a5aSDimitry Andric cl::desc("Instruction cutoff for tail duplication during layout. " 132d88c1a5aSDimitry Andric "Tail merging during layout is forced to have a threshold " 133d88c1a5aSDimitry Andric "that won't conflict."), cl::init(2), 134d88c1a5aSDimitry Andric cl::Hidden); 135d88c1a5aSDimitry Andric 1365517e702SDimitry Andric // Heuristic for aggressive tail duplication. 1375517e702SDimitry Andric static cl::opt<unsigned> TailDupPlacementAggressiveThreshold( 1385517e702SDimitry Andric "tail-dup-placement-aggressive-threshold", 1395517e702SDimitry Andric cl::desc("Instruction cutoff for aggressive tail duplication during " 1405517e702SDimitry Andric "layout. Used at -O3. Tail merging during layout is forced to " 1415517e702SDimitry Andric "have a threshold that won't conflict."), cl::init(3), 1425517e702SDimitry Andric cl::Hidden); 1435517e702SDimitry Andric 1447a7e6055SDimitry Andric // Heuristic for tail duplication. 1457a7e6055SDimitry Andric static cl::opt<unsigned> TailDupPlacementPenalty( 1467a7e6055SDimitry Andric "tail-dup-placement-penalty", 1477a7e6055SDimitry Andric cl::desc("Cost penalty for blocks that can avoid breaking CFG by copying. " 1487a7e6055SDimitry Andric "Copying can increase fallthrough, but it also increases icache " 1497a7e6055SDimitry Andric "pressure. This parameter controls the penalty to account for that. " 1507a7e6055SDimitry Andric "Percent as integer."), 1517a7e6055SDimitry Andric cl::init(2), 1527a7e6055SDimitry Andric cl::Hidden); 1537a7e6055SDimitry Andric 1547a7e6055SDimitry Andric // Heuristic for triangle chains. 1557a7e6055SDimitry Andric static cl::opt<unsigned> TriangleChainCount( 1567a7e6055SDimitry Andric "triangle-chain-count", 1577a7e6055SDimitry Andric cl::desc("Number of triangle-shaped-CFG's that need to be in a row for the " 1587a7e6055SDimitry Andric "triangle tail duplication heuristic to kick in. 0 to disable."), 1597a7e6055SDimitry Andric cl::init(2), 1607a7e6055SDimitry Andric cl::Hidden); 1617a7e6055SDimitry Andric 1623ca95b02SDimitry Andric extern cl::opt<unsigned> StaticLikelyProb; 1633ca95b02SDimitry Andric extern cl::opt<unsigned> ProfileLikelyProb; 1643ca95b02SDimitry Andric 1657a7e6055SDimitry Andric // Internal option used to control BFI display only after MBP pass. 1667a7e6055SDimitry Andric // Defined in CodeGen/MachineBlockFrequencyInfo.cpp: 1677a7e6055SDimitry Andric // -view-block-layout-with-bfi= 1687a7e6055SDimitry Andric extern cl::opt<GVDAGType> ViewBlockLayoutWithBFI; 1697a7e6055SDimitry Andric 1707a7e6055SDimitry Andric // Command line option to specify the name of the function for CFG dump 1717a7e6055SDimitry Andric // Defined in Analysis/BlockFrequencyInfo.cpp: -view-bfi-func-name= 1727a7e6055SDimitry Andric extern cl::opt<std::string> ViewBlockFreqFuncName; 1737a7e6055SDimitry Andric 174dff0c46cSDimitry Andric namespace { 175dff0c46cSDimitry Andric class BlockChain; 176dff0c46cSDimitry Andric /// \brief Type for our function-wide basic block -> block chain mapping. 1777a7e6055SDimitry Andric typedef DenseMap<const MachineBasicBlock *, BlockChain *> BlockToChainMapType; 178dff0c46cSDimitry Andric } 179dff0c46cSDimitry Andric 180dff0c46cSDimitry Andric namespace { 181dff0c46cSDimitry Andric /// \brief A chain of blocks which will be laid out contiguously. 182dff0c46cSDimitry Andric /// 183dff0c46cSDimitry Andric /// This is the datastructure representing a chain of consecutive blocks that 184dff0c46cSDimitry Andric /// are profitable to layout together in order to maximize fallthrough 1857ae0e2c9SDimitry Andric /// probabilities and code locality. We also can use a block chain to represent 1867ae0e2c9SDimitry Andric /// a sequence of basic blocks which have some external (correctness) 1877ae0e2c9SDimitry Andric /// requirement for sequential layout. 188dff0c46cSDimitry Andric /// 1897ae0e2c9SDimitry Andric /// Chains can be built around a single basic block and can be merged to grow 1907ae0e2c9SDimitry Andric /// them. They participate in a block-to-chain mapping, which is updated 1917ae0e2c9SDimitry Andric /// automatically as chains are merged together. 192dff0c46cSDimitry Andric class BlockChain { 193dff0c46cSDimitry Andric /// \brief The sequence of blocks belonging to this chain. 194dff0c46cSDimitry Andric /// 195dff0c46cSDimitry Andric /// This is the sequence of blocks for a particular chain. These will be laid 196dff0c46cSDimitry Andric /// out in-order within the function. 197dff0c46cSDimitry Andric SmallVector<MachineBasicBlock *, 4> Blocks; 198dff0c46cSDimitry Andric 199dff0c46cSDimitry Andric /// \brief A handle to the function-wide basic block to block chain mapping. 200dff0c46cSDimitry Andric /// 201dff0c46cSDimitry Andric /// This is retained in each block chain to simplify the computation of child 202dff0c46cSDimitry Andric /// block chains for SCC-formation and iteration. We store the edges to child 203dff0c46cSDimitry Andric /// basic blocks, and map them back to their associated chains using this 204dff0c46cSDimitry Andric /// structure. 205dff0c46cSDimitry Andric BlockToChainMapType &BlockToChain; 206dff0c46cSDimitry Andric 207dff0c46cSDimitry Andric public: 208dff0c46cSDimitry Andric /// \brief Construct a new BlockChain. 209dff0c46cSDimitry Andric /// 210dff0c46cSDimitry Andric /// This builds a new block chain representing a single basic block in the 211dff0c46cSDimitry Andric /// function. It also registers itself as the chain that block participates 212dff0c46cSDimitry Andric /// in with the BlockToChain mapping. 213dff0c46cSDimitry Andric BlockChain(BlockToChainMapType &BlockToChain, MachineBasicBlock *BB) 2143ca95b02SDimitry Andric : Blocks(1, BB), BlockToChain(BlockToChain), UnscheduledPredecessors(0) { 215dff0c46cSDimitry Andric assert(BB && "Cannot create a chain with a null basic block"); 216dff0c46cSDimitry Andric BlockToChain[BB] = this; 217dff0c46cSDimitry Andric } 218dff0c46cSDimitry Andric 219dff0c46cSDimitry Andric /// \brief Iterator over blocks within the chain. 220cb4dff85SDimitry Andric typedef SmallVectorImpl<MachineBasicBlock *>::iterator iterator; 2217a7e6055SDimitry Andric typedef SmallVectorImpl<MachineBasicBlock *>::const_iterator const_iterator; 222dff0c46cSDimitry Andric 223dff0c46cSDimitry Andric /// \brief Beginning of blocks within the chain. 224cb4dff85SDimitry Andric iterator begin() { return Blocks.begin(); } 2257a7e6055SDimitry Andric const_iterator begin() const { return Blocks.begin(); } 226dff0c46cSDimitry Andric 227dff0c46cSDimitry Andric /// \brief End of blocks within the chain. 228cb4dff85SDimitry Andric iterator end() { return Blocks.end(); } 2297a7e6055SDimitry Andric const_iterator end() const { return Blocks.end(); } 230dff0c46cSDimitry Andric 231d88c1a5aSDimitry Andric bool remove(MachineBasicBlock* BB) { 232d88c1a5aSDimitry Andric for(iterator i = begin(); i != end(); ++i) { 233d88c1a5aSDimitry Andric if (*i == BB) { 234d88c1a5aSDimitry Andric Blocks.erase(i); 235d88c1a5aSDimitry Andric return true; 236d88c1a5aSDimitry Andric } 237d88c1a5aSDimitry Andric } 238d88c1a5aSDimitry Andric return false; 239d88c1a5aSDimitry Andric } 240d88c1a5aSDimitry Andric 241dff0c46cSDimitry Andric /// \brief Merge a block chain into this one. 242dff0c46cSDimitry Andric /// 243dff0c46cSDimitry Andric /// This routine merges a block chain into this one. It takes care of forming 244dff0c46cSDimitry Andric /// a contiguous sequence of basic blocks, updating the edge list, and 245dff0c46cSDimitry Andric /// updating the block -> chain mapping. It does not free or tear down the 246dff0c46cSDimitry Andric /// old chain, but the old chain's block list is no longer valid. 247dff0c46cSDimitry Andric void merge(MachineBasicBlock *BB, BlockChain *Chain) { 248d8866befSDimitry Andric assert(BB && "Can't merge a null block."); 249d8866befSDimitry Andric assert(!Blocks.empty() && "Can't merge into an empty chain."); 250dff0c46cSDimitry Andric 251dff0c46cSDimitry Andric // Fast path in case we don't have a chain already. 252dff0c46cSDimitry Andric if (!Chain) { 253d8866befSDimitry Andric assert(!BlockToChain[BB] && 254d8866befSDimitry Andric "Passed chain is null, but BB has entry in BlockToChain."); 255dff0c46cSDimitry Andric Blocks.push_back(BB); 256dff0c46cSDimitry Andric BlockToChain[BB] = this; 257dff0c46cSDimitry Andric return; 258dff0c46cSDimitry Andric } 259dff0c46cSDimitry Andric 260d8866befSDimitry Andric assert(BB == *Chain->begin() && "Passed BB is not head of Chain."); 261dff0c46cSDimitry Andric assert(Chain->begin() != Chain->end()); 262dff0c46cSDimitry Andric 263dff0c46cSDimitry Andric // Update the incoming blocks to point to this chain, and add them to the 264dff0c46cSDimitry Andric // chain structure. 265ff0cc061SDimitry Andric for (MachineBasicBlock *ChainBB : *Chain) { 266ff0cc061SDimitry Andric Blocks.push_back(ChainBB); 267d8866befSDimitry Andric assert(BlockToChain[ChainBB] == Chain && "Incoming blocks not in chain."); 268ff0cc061SDimitry Andric BlockToChain[ChainBB] = this; 269dff0c46cSDimitry Andric } 270dff0c46cSDimitry Andric } 271dff0c46cSDimitry Andric 272dff0c46cSDimitry Andric #ifndef NDEBUG 273dff0c46cSDimitry Andric /// \brief Dump the blocks in this chain. 27491bc56edSDimitry Andric LLVM_DUMP_METHOD void dump() { 275ff0cc061SDimitry Andric for (MachineBasicBlock *MBB : *this) 276ff0cc061SDimitry Andric MBB->dump(); 277dff0c46cSDimitry Andric } 278dff0c46cSDimitry Andric #endif // NDEBUG 279dff0c46cSDimitry Andric 2803ca95b02SDimitry Andric /// \brief Count of predecessors of any block within the chain which have not 2813ca95b02SDimitry Andric /// yet been scheduled. In general, we will delay scheduling this chain 2823ca95b02SDimitry Andric /// until those predecessors are scheduled (or we find a sufficiently good 2833ca95b02SDimitry Andric /// reason to override this heuristic.) Note that when forming loop chains, 2843ca95b02SDimitry Andric /// blocks outside the loop are ignored and treated as if they were already 2853ca95b02SDimitry Andric /// scheduled. 286dff0c46cSDimitry Andric /// 2873ca95b02SDimitry Andric /// Note: This field is reinitialized multiple times - once for each loop, 2883ca95b02SDimitry Andric /// and then once for the function as a whole. 2893ca95b02SDimitry Andric unsigned UnscheduledPredecessors; 290dff0c46cSDimitry Andric }; 2913dac3a9bSDimitry Andric } 292dff0c46cSDimitry Andric 293dff0c46cSDimitry Andric namespace { 294dff0c46cSDimitry Andric class MachineBlockPlacement : public MachineFunctionPass { 295dff0c46cSDimitry Andric /// \brief A typedef for a block filter set. 2967a7e6055SDimitry Andric typedef SmallSetVector<const MachineBasicBlock *, 16> BlockFilterSet; 2977a7e6055SDimitry Andric 2987a7e6055SDimitry Andric /// Pair struct containing basic block and taildup profitiability 2997a7e6055SDimitry Andric struct BlockAndTailDupResult { 3007a7e6055SDimitry Andric MachineBasicBlock *BB; 3017a7e6055SDimitry Andric bool ShouldTailDup; 3027a7e6055SDimitry Andric }; 3037a7e6055SDimitry Andric 3047a7e6055SDimitry Andric /// Triple struct containing edge weight and the edge. 3057a7e6055SDimitry Andric struct WeightedEdge { 3067a7e6055SDimitry Andric BlockFrequency Weight; 3077a7e6055SDimitry Andric MachineBasicBlock *Src; 3087a7e6055SDimitry Andric MachineBasicBlock *Dest; 3097a7e6055SDimitry Andric }; 310dff0c46cSDimitry Andric 3113ca95b02SDimitry Andric /// \brief work lists of blocks that are ready to be laid out 3123ca95b02SDimitry Andric SmallVector<MachineBasicBlock *, 16> BlockWorkList; 3133ca95b02SDimitry Andric SmallVector<MachineBasicBlock *, 16> EHPadWorkList; 3143ca95b02SDimitry Andric 3157a7e6055SDimitry Andric /// Edges that have already been computed as optimal. 3167a7e6055SDimitry Andric DenseMap<const MachineBasicBlock *, BlockAndTailDupResult> ComputedEdges; 3177a7e6055SDimitry Andric 3183ca95b02SDimitry Andric /// \brief Machine Function 3193ca95b02SDimitry Andric MachineFunction *F; 3203ca95b02SDimitry Andric 321dff0c46cSDimitry Andric /// \brief A handle to the branch probability pass. 322dff0c46cSDimitry Andric const MachineBranchProbabilityInfo *MBPI; 323dff0c46cSDimitry Andric 324dff0c46cSDimitry Andric /// \brief A handle to the function-wide block frequency pass. 3253ca95b02SDimitry Andric std::unique_ptr<BranchFolder::MBFIWrapper> MBFI; 326dff0c46cSDimitry Andric 327dff0c46cSDimitry Andric /// \brief A handle to the loop info. 3283ca95b02SDimitry Andric MachineLoopInfo *MLI; 329dff0c46cSDimitry Andric 330d88c1a5aSDimitry Andric /// \brief Preferred loop exit. 331d88c1a5aSDimitry Andric /// Member variable for convenience. It may be removed by duplication deep 332d88c1a5aSDimitry Andric /// in the call stack. 333d88c1a5aSDimitry Andric MachineBasicBlock *PreferredLoopExit; 334d88c1a5aSDimitry Andric 335dff0c46cSDimitry Andric /// \brief A handle to the target's instruction info. 336dff0c46cSDimitry Andric const TargetInstrInfo *TII; 337dff0c46cSDimitry Andric 338dff0c46cSDimitry Andric /// \brief A handle to the target's lowering info. 339139f7f9bSDimitry Andric const TargetLoweringBase *TLI; 340dff0c46cSDimitry Andric 341ff0cc061SDimitry Andric /// \brief A handle to the post dominator tree. 3427a7e6055SDimitry Andric MachinePostDominatorTree *MPDT; 343ff0cc061SDimitry Andric 344d88c1a5aSDimitry Andric /// \brief Duplicator used to duplicate tails during placement. 345d88c1a5aSDimitry Andric /// 346d88c1a5aSDimitry Andric /// Placement decisions can open up new tail duplication opportunities, but 347d88c1a5aSDimitry Andric /// since tail duplication affects placement decisions of later blocks, it 348d88c1a5aSDimitry Andric /// must be done inline. 349d88c1a5aSDimitry Andric TailDuplicator TailDup; 350d88c1a5aSDimitry Andric 351dff0c46cSDimitry Andric /// \brief Allocator and owner of BlockChain structures. 352dff0c46cSDimitry Andric /// 3537ae0e2c9SDimitry Andric /// We build BlockChains lazily while processing the loop structure of 3547ae0e2c9SDimitry Andric /// a function. To reduce malloc traffic, we allocate them using this 3557ae0e2c9SDimitry Andric /// slab-like allocator, and destroy them after the pass completes. An 3567ae0e2c9SDimitry Andric /// important guarantee is that this allocator produces stable pointers to 3577ae0e2c9SDimitry Andric /// the chains. 358dff0c46cSDimitry Andric SpecificBumpPtrAllocator<BlockChain> ChainAllocator; 359dff0c46cSDimitry Andric 360dff0c46cSDimitry Andric /// \brief Function wide BasicBlock to BlockChain mapping. 361dff0c46cSDimitry Andric /// 362dff0c46cSDimitry Andric /// This mapping allows efficiently moving from any given basic block to the 363dff0c46cSDimitry Andric /// BlockChain it participates in, if any. We use it to, among other things, 364dff0c46cSDimitry Andric /// allow implicitly defining edges between chains as the existing edges 365dff0c46cSDimitry Andric /// between basic blocks. 3667a7e6055SDimitry Andric DenseMap<const MachineBasicBlock *, BlockChain *> BlockToChain; 367dff0c46cSDimitry Andric 368d88c1a5aSDimitry Andric #ifndef NDEBUG 369d88c1a5aSDimitry Andric /// The set of basic blocks that have terminators that cannot be fully 370d88c1a5aSDimitry Andric /// analyzed. These basic blocks cannot be re-ordered safely by 371d88c1a5aSDimitry Andric /// MachineBlockPlacement, and we must preserve physical layout of these 372d88c1a5aSDimitry Andric /// blocks and their successors through the pass. 373d88c1a5aSDimitry Andric SmallPtrSet<MachineBasicBlock *, 4> BlocksWithUnanalyzableExits; 374d88c1a5aSDimitry Andric #endif 375d88c1a5aSDimitry Andric 376d88c1a5aSDimitry Andric /// Decrease the UnscheduledPredecessors count for all blocks in chain, and 377d88c1a5aSDimitry Andric /// if the count goes to 0, add them to the appropriate work list. 3787a7e6055SDimitry Andric void markChainSuccessors( 3797a7e6055SDimitry Andric const BlockChain &Chain, const MachineBasicBlock *LoopHeaderBB, 38091bc56edSDimitry Andric const BlockFilterSet *BlockFilter = nullptr); 381d88c1a5aSDimitry Andric 382d88c1a5aSDimitry Andric /// Decrease the UnscheduledPredecessors count for a single block, and 383d88c1a5aSDimitry Andric /// if the count goes to 0, add them to the appropriate work list. 384d88c1a5aSDimitry Andric void markBlockSuccessors( 3857a7e6055SDimitry Andric const BlockChain &Chain, const MachineBasicBlock *BB, 3867a7e6055SDimitry Andric const MachineBasicBlock *LoopHeaderBB, 387d88c1a5aSDimitry Andric const BlockFilterSet *BlockFilter = nullptr); 388d88c1a5aSDimitry Andric 3893ca95b02SDimitry Andric BranchProbability 3907a7e6055SDimitry Andric collectViableSuccessors( 3917a7e6055SDimitry Andric const MachineBasicBlock *BB, const BlockChain &Chain, 3923ca95b02SDimitry Andric const BlockFilterSet *BlockFilter, 3933ca95b02SDimitry Andric SmallVector<MachineBasicBlock *, 4> &Successors); 3947a7e6055SDimitry Andric bool shouldPredBlockBeOutlined( 3957a7e6055SDimitry Andric const MachineBasicBlock *BB, const MachineBasicBlock *Succ, 3967a7e6055SDimitry Andric const BlockChain &Chain, const BlockFilterSet *BlockFilter, 3977a7e6055SDimitry Andric BranchProbability SuccProb, BranchProbability HotProb); 398d88c1a5aSDimitry Andric bool repeatedlyTailDuplicateBlock( 399d88c1a5aSDimitry Andric MachineBasicBlock *BB, MachineBasicBlock *&LPred, 4007a7e6055SDimitry Andric const MachineBasicBlock *LoopHeaderBB, 401d88c1a5aSDimitry Andric BlockChain &Chain, BlockFilterSet *BlockFilter, 402d88c1a5aSDimitry Andric MachineFunction::iterator &PrevUnplacedBlockIt); 4037a7e6055SDimitry Andric bool maybeTailDuplicateBlock( 4047a7e6055SDimitry Andric MachineBasicBlock *BB, MachineBasicBlock *LPred, 4057a7e6055SDimitry Andric BlockChain &Chain, BlockFilterSet *BlockFilter, 406d88c1a5aSDimitry Andric MachineFunction::iterator &PrevUnplacedBlockIt, 407d88c1a5aSDimitry Andric bool &DuplicatedToPred); 4087a7e6055SDimitry Andric bool hasBetterLayoutPredecessor( 4097a7e6055SDimitry Andric const MachineBasicBlock *BB, const MachineBasicBlock *Succ, 4107a7e6055SDimitry Andric const BlockChain &SuccChain, BranchProbability SuccProb, 4117a7e6055SDimitry Andric BranchProbability RealSuccProb, const BlockChain &Chain, 4123ca95b02SDimitry Andric const BlockFilterSet *BlockFilter); 4137a7e6055SDimitry Andric BlockAndTailDupResult selectBestSuccessor( 4147a7e6055SDimitry Andric const MachineBasicBlock *BB, const BlockChain &Chain, 415dff0c46cSDimitry Andric const BlockFilterSet *BlockFilter); 4167a7e6055SDimitry Andric MachineBasicBlock *selectBestCandidateBlock( 4177a7e6055SDimitry Andric const BlockChain &Chain, SmallVectorImpl<MachineBasicBlock *> &WorkList); 4187a7e6055SDimitry Andric MachineBasicBlock *getFirstUnplacedBlock( 4197a7e6055SDimitry Andric const BlockChain &PlacedChain, 420dff0c46cSDimitry Andric MachineFunction::iterator &PrevUnplacedBlockIt, 421dff0c46cSDimitry Andric const BlockFilterSet *BlockFilter); 4223ca95b02SDimitry Andric 4233ca95b02SDimitry Andric /// \brief Add a basic block to the work list if it is appropriate. 4243ca95b02SDimitry Andric /// 4253ca95b02SDimitry Andric /// If the optional parameter BlockFilter is provided, only MBB 4263ca95b02SDimitry Andric /// present in the set will be added to the worklist. If nullptr 4273ca95b02SDimitry Andric /// is provided, no filtering occurs. 4287a7e6055SDimitry Andric void fillWorkLists(const MachineBasicBlock *MBB, 4293ca95b02SDimitry Andric SmallPtrSetImpl<BlockChain *> &UpdatedPreds, 4303ca95b02SDimitry Andric const BlockFilterSet *BlockFilter); 4317a7e6055SDimitry Andric void buildChain(const MachineBasicBlock *BB, BlockChain &Chain, 432d88c1a5aSDimitry Andric BlockFilterSet *BlockFilter = nullptr); 4337a7e6055SDimitry Andric MachineBasicBlock *findBestLoopTop( 4347a7e6055SDimitry Andric const MachineLoop &L, const BlockFilterSet &LoopBlockSet); 4357a7e6055SDimitry Andric MachineBasicBlock *findBestLoopExit( 4367a7e6055SDimitry Andric const MachineLoop &L, const BlockFilterSet &LoopBlockSet); 4377a7e6055SDimitry Andric BlockFilterSet collectLoopBlockSet(const MachineLoop &L); 4387a7e6055SDimitry Andric void buildLoopChains(const MachineLoop &L); 4397a7e6055SDimitry Andric void rotateLoop( 4407a7e6055SDimitry Andric BlockChain &LoopChain, const MachineBasicBlock *ExitingBB, 441cb4dff85SDimitry Andric const BlockFilterSet &LoopBlockSet); 4427a7e6055SDimitry Andric void rotateLoopWithProfile( 4437a7e6055SDimitry Andric BlockChain &LoopChain, const MachineLoop &L, 444dff0c46cSDimitry Andric const BlockFilterSet &LoopBlockSet); 4453ca95b02SDimitry Andric void buildCFGChains(); 4463ca95b02SDimitry Andric void optimizeBranches(); 4473ca95b02SDimitry Andric void alignBlocks(); 4487a7e6055SDimitry Andric /// Returns true if a block should be tail-duplicated to increase fallthrough 4497a7e6055SDimitry Andric /// opportunities. 4507a7e6055SDimitry Andric bool shouldTailDuplicate(MachineBasicBlock *BB); 4517a7e6055SDimitry Andric /// Check the edge frequencies to see if tail duplication will increase 4527a7e6055SDimitry Andric /// fallthroughs. 4537a7e6055SDimitry Andric bool isProfitableToTailDup( 4547a7e6055SDimitry Andric const MachineBasicBlock *BB, const MachineBasicBlock *Succ, 4557a7e6055SDimitry Andric BranchProbability AdjustedSumProb, 4567a7e6055SDimitry Andric const BlockChain &Chain, const BlockFilterSet *BlockFilter); 4577a7e6055SDimitry Andric /// Check for a trellis layout. 4587a7e6055SDimitry Andric bool isTrellis(const MachineBasicBlock *BB, 4597a7e6055SDimitry Andric const SmallVectorImpl<MachineBasicBlock *> &ViableSuccs, 4607a7e6055SDimitry Andric const BlockChain &Chain, const BlockFilterSet *BlockFilter); 4617a7e6055SDimitry Andric /// Get the best successor given a trellis layout. 4627a7e6055SDimitry Andric BlockAndTailDupResult getBestTrellisSuccessor( 4637a7e6055SDimitry Andric const MachineBasicBlock *BB, 4647a7e6055SDimitry Andric const SmallVectorImpl<MachineBasicBlock *> &ViableSuccs, 4657a7e6055SDimitry Andric BranchProbability AdjustedSumProb, const BlockChain &Chain, 4667a7e6055SDimitry Andric const BlockFilterSet *BlockFilter); 4677a7e6055SDimitry Andric /// Get the best pair of non-conflicting edges. 4687a7e6055SDimitry Andric static std::pair<WeightedEdge, WeightedEdge> getBestNonConflictingEdges( 4697a7e6055SDimitry Andric const MachineBasicBlock *BB, 4707a7e6055SDimitry Andric MutableArrayRef<SmallVector<WeightedEdge, 8>> Edges); 4717a7e6055SDimitry Andric /// Returns true if a block can tail duplicate into all unplaced 4727a7e6055SDimitry Andric /// predecessors. Filters based on loop. 4737a7e6055SDimitry Andric bool canTailDuplicateUnplacedPreds( 4747a7e6055SDimitry Andric const MachineBasicBlock *BB, MachineBasicBlock *Succ, 4757a7e6055SDimitry Andric const BlockChain &Chain, const BlockFilterSet *BlockFilter); 4767a7e6055SDimitry Andric /// Find chains of triangles to tail-duplicate where a global analysis works, 4777a7e6055SDimitry Andric /// but a local analysis would not find them. 4787a7e6055SDimitry Andric void precomputeTriangleChains(); 479dff0c46cSDimitry Andric 480dff0c46cSDimitry Andric public: 481dff0c46cSDimitry Andric static char ID; // Pass identification, replacement for typeid 482dff0c46cSDimitry Andric MachineBlockPlacement() : MachineFunctionPass(ID) { 483dff0c46cSDimitry Andric initializeMachineBlockPlacementPass(*PassRegistry::getPassRegistry()); 484dff0c46cSDimitry Andric } 485dff0c46cSDimitry Andric 48691bc56edSDimitry Andric bool runOnMachineFunction(MachineFunction &F) override; 487dff0c46cSDimitry Andric 48891bc56edSDimitry Andric void getAnalysisUsage(AnalysisUsage &AU) const override { 489dff0c46cSDimitry Andric AU.addRequired<MachineBranchProbabilityInfo>(); 490dff0c46cSDimitry Andric AU.addRequired<MachineBlockFrequencyInfo>(); 4917a7e6055SDimitry Andric if (TailDupPlacement) 4927a7e6055SDimitry Andric AU.addRequired<MachinePostDominatorTree>(); 493dff0c46cSDimitry Andric AU.addRequired<MachineLoopInfo>(); 4943ca95b02SDimitry Andric AU.addRequired<TargetPassConfig>(); 495dff0c46cSDimitry Andric MachineFunctionPass::getAnalysisUsage(AU); 496dff0c46cSDimitry Andric } 497dff0c46cSDimitry Andric }; 4983dac3a9bSDimitry Andric } 499dff0c46cSDimitry Andric 500dff0c46cSDimitry Andric char MachineBlockPlacement::ID = 0; 501dff0c46cSDimitry Andric char &llvm::MachineBlockPlacementID = MachineBlockPlacement::ID; 502302affcbSDimitry Andric INITIALIZE_PASS_BEGIN(MachineBlockPlacement, DEBUG_TYPE, 503dff0c46cSDimitry Andric "Branch Probability Basic Block Placement", false, false) 504dff0c46cSDimitry Andric INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo) 505dff0c46cSDimitry Andric INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo) 5067a7e6055SDimitry Andric INITIALIZE_PASS_DEPENDENCY(MachinePostDominatorTree) 507dff0c46cSDimitry Andric INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo) 508302affcbSDimitry Andric INITIALIZE_PASS_END(MachineBlockPlacement, DEBUG_TYPE, 509dff0c46cSDimitry Andric "Branch Probability Basic Block Placement", false, false) 510dff0c46cSDimitry Andric 511dff0c46cSDimitry Andric #ifndef NDEBUG 512dff0c46cSDimitry Andric /// \brief Helper to print the name of a MBB. 513dff0c46cSDimitry Andric /// 514dff0c46cSDimitry Andric /// Only used by debug logging. 5157a7e6055SDimitry Andric static std::string getBlockName(const MachineBasicBlock *BB) { 516dff0c46cSDimitry Andric std::string Result; 517dff0c46cSDimitry Andric raw_string_ostream OS(Result); 518ff0cc061SDimitry Andric OS << "BB#" << BB->getNumber(); 5193ca95b02SDimitry Andric OS << " ('" << BB->getName() << "')"; 520dff0c46cSDimitry Andric OS.flush(); 521dff0c46cSDimitry Andric return Result; 522dff0c46cSDimitry Andric } 523dff0c46cSDimitry Andric #endif 524dff0c46cSDimitry Andric 525dff0c46cSDimitry Andric /// \brief Mark a chain's successors as having one fewer preds. 526dff0c46cSDimitry Andric /// 527dff0c46cSDimitry Andric /// When a chain is being merged into the "placed" chain, this routine will 528dff0c46cSDimitry Andric /// quickly walk the successors of each block in the chain and mark them as 529dff0c46cSDimitry Andric /// having one fewer active predecessor. It also adds any successors of this 530d88c1a5aSDimitry Andric /// chain which reach the zero-predecessor state to the appropriate worklist. 531dff0c46cSDimitry Andric void MachineBlockPlacement::markChainSuccessors( 5327a7e6055SDimitry Andric const BlockChain &Chain, const MachineBasicBlock *LoopHeaderBB, 533dff0c46cSDimitry Andric const BlockFilterSet *BlockFilter) { 534dff0c46cSDimitry Andric // Walk all the blocks in this chain, marking their successors as having 535dff0c46cSDimitry Andric // a predecessor placed. 536ff0cc061SDimitry Andric for (MachineBasicBlock *MBB : Chain) { 537d88c1a5aSDimitry Andric markBlockSuccessors(Chain, MBB, LoopHeaderBB, BlockFilter); 538d88c1a5aSDimitry Andric } 539d88c1a5aSDimitry Andric } 540d88c1a5aSDimitry Andric 541d88c1a5aSDimitry Andric /// \brief Mark a single block's successors as having one fewer preds. 542d88c1a5aSDimitry Andric /// 543d88c1a5aSDimitry Andric /// Under normal circumstances, this is only called by markChainSuccessors, 544d88c1a5aSDimitry Andric /// but if a block that was to be placed is completely tail-duplicated away, 545d88c1a5aSDimitry Andric /// and was duplicated into the chain end, we need to redo markBlockSuccessors 546d88c1a5aSDimitry Andric /// for just that block. 547d88c1a5aSDimitry Andric void MachineBlockPlacement::markBlockSuccessors( 5487a7e6055SDimitry Andric const BlockChain &Chain, const MachineBasicBlock *MBB, 5497a7e6055SDimitry Andric const MachineBasicBlock *LoopHeaderBB, const BlockFilterSet *BlockFilter) { 550dff0c46cSDimitry Andric // Add any successors for which this is the only un-placed in-loop 551dff0c46cSDimitry Andric // predecessor to the worklist as a viable candidate for CFG-neutral 552dff0c46cSDimitry Andric // placement. No subsequent placement of this block will violate the CFG 553dff0c46cSDimitry Andric // shape, so we get to use heuristics to choose a favorable placement. 554ff0cc061SDimitry Andric for (MachineBasicBlock *Succ : MBB->successors()) { 555ff0cc061SDimitry Andric if (BlockFilter && !BlockFilter->count(Succ)) 556dff0c46cSDimitry Andric continue; 557ff0cc061SDimitry Andric BlockChain &SuccChain = *BlockToChain[Succ]; 558dff0c46cSDimitry Andric // Disregard edges within a fixed chain, or edges to the loop header. 559ff0cc061SDimitry Andric if (&Chain == &SuccChain || Succ == LoopHeaderBB) 560dff0c46cSDimitry Andric continue; 561dff0c46cSDimitry Andric 562dff0c46cSDimitry Andric // This is a cross-chain edge that is within the loop, so decrement the 563dff0c46cSDimitry Andric // loop predecessor count of the destination chain. 5643ca95b02SDimitry Andric if (SuccChain.UnscheduledPredecessors == 0 || 5653ca95b02SDimitry Andric --SuccChain.UnscheduledPredecessors > 0) 5663ca95b02SDimitry Andric continue; 5673ca95b02SDimitry Andric 568d88c1a5aSDimitry Andric auto *NewBB = *SuccChain.begin(); 569d88c1a5aSDimitry Andric if (NewBB->isEHPad()) 570d88c1a5aSDimitry Andric EHPadWorkList.push_back(NewBB); 5713ca95b02SDimitry Andric else 572d88c1a5aSDimitry Andric BlockWorkList.push_back(NewBB); 573dff0c46cSDimitry Andric } 574dff0c46cSDimitry Andric } 575dff0c46cSDimitry Andric 5763ca95b02SDimitry Andric /// This helper function collects the set of successors of block 5773ca95b02SDimitry Andric /// \p BB that are allowed to be its layout successors, and return 5783ca95b02SDimitry Andric /// the total branch probability of edges from \p BB to those 5793ca95b02SDimitry Andric /// blocks. 5803ca95b02SDimitry Andric BranchProbability MachineBlockPlacement::collectViableSuccessors( 5817a7e6055SDimitry Andric const MachineBasicBlock *BB, const BlockChain &Chain, 5827a7e6055SDimitry Andric const BlockFilterSet *BlockFilter, 5833ca95b02SDimitry Andric SmallVector<MachineBasicBlock *, 4> &Successors) { 5843ca95b02SDimitry Andric // Adjust edge probabilities by excluding edges pointing to blocks that is 5853ca95b02SDimitry Andric // either not in BlockFilter or is already in the current chain. Consider the 5863ca95b02SDimitry Andric // following CFG: 5873ca95b02SDimitry Andric // 5883ca95b02SDimitry Andric // --->A 5893ca95b02SDimitry Andric // | / \ 5903ca95b02SDimitry Andric // | B C 5913ca95b02SDimitry Andric // | \ / \ 5923ca95b02SDimitry Andric // ----D E 5933ca95b02SDimitry Andric // 5943ca95b02SDimitry Andric // Assume A->C is very hot (>90%), and C->D has a 50% probability, then after 5953ca95b02SDimitry Andric // A->C is chosen as a fall-through, D won't be selected as a successor of C 5963ca95b02SDimitry Andric // due to CFG constraint (the probability of C->D is not greater than 5973ca95b02SDimitry Andric // HotProb to break top-order). If we exclude E that is not in BlockFilter 5983ca95b02SDimitry Andric // when calculating the probability of C->D, D will be selected and we 5993ca95b02SDimitry Andric // will get A C D B as the layout of this loop. 6003ca95b02SDimitry Andric auto AdjustedSumProb = BranchProbability::getOne(); 6013ca95b02SDimitry Andric for (MachineBasicBlock *Succ : BB->successors()) { 6023ca95b02SDimitry Andric bool SkipSucc = false; 6033ca95b02SDimitry Andric if (Succ->isEHPad() || (BlockFilter && !BlockFilter->count(Succ))) { 6043ca95b02SDimitry Andric SkipSucc = true; 6053ca95b02SDimitry Andric } else { 6063ca95b02SDimitry Andric BlockChain *SuccChain = BlockToChain[Succ]; 6073ca95b02SDimitry Andric if (SuccChain == &Chain) { 6083ca95b02SDimitry Andric SkipSucc = true; 6093ca95b02SDimitry Andric } else if (Succ != *SuccChain->begin()) { 6103ca95b02SDimitry Andric DEBUG(dbgs() << " " << getBlockName(Succ) << " -> Mid chain!\n"); 6113ca95b02SDimitry Andric continue; 6123ca95b02SDimitry Andric } 6133ca95b02SDimitry Andric } 6143ca95b02SDimitry Andric if (SkipSucc) 6153ca95b02SDimitry Andric AdjustedSumProb -= MBPI->getEdgeProbability(BB, Succ); 6163ca95b02SDimitry Andric else 6173ca95b02SDimitry Andric Successors.push_back(Succ); 6183ca95b02SDimitry Andric } 6193ca95b02SDimitry Andric 6203ca95b02SDimitry Andric return AdjustedSumProb; 6213ca95b02SDimitry Andric } 6223ca95b02SDimitry Andric 6233ca95b02SDimitry Andric /// The helper function returns the branch probability that is adjusted 6243ca95b02SDimitry Andric /// or normalized over the new total \p AdjustedSumProb. 6253ca95b02SDimitry Andric static BranchProbability 6263ca95b02SDimitry Andric getAdjustedProbability(BranchProbability OrigProb, 6273ca95b02SDimitry Andric BranchProbability AdjustedSumProb) { 6283ca95b02SDimitry Andric BranchProbability SuccProb; 6293ca95b02SDimitry Andric uint32_t SuccProbN = OrigProb.getNumerator(); 6303ca95b02SDimitry Andric uint32_t SuccProbD = AdjustedSumProb.getNumerator(); 6313ca95b02SDimitry Andric if (SuccProbN >= SuccProbD) 6323ca95b02SDimitry Andric SuccProb = BranchProbability::getOne(); 6333ca95b02SDimitry Andric else 6343ca95b02SDimitry Andric SuccProb = BranchProbability(SuccProbN, SuccProbD); 6353ca95b02SDimitry Andric 6363ca95b02SDimitry Andric return SuccProb; 6373ca95b02SDimitry Andric } 6383ca95b02SDimitry Andric 6397a7e6055SDimitry Andric /// Check if \p BB has exactly the successors in \p Successors. 6407a7e6055SDimitry Andric static bool 6417a7e6055SDimitry Andric hasSameSuccessors(MachineBasicBlock &BB, 6427a7e6055SDimitry Andric SmallPtrSetImpl<const MachineBasicBlock *> &Successors) { 6437a7e6055SDimitry Andric if (BB.succ_size() != Successors.size()) 6443ca95b02SDimitry Andric return false; 6457a7e6055SDimitry Andric // We don't want to count self-loops 6467a7e6055SDimitry Andric if (Successors.count(&BB)) 6477a7e6055SDimitry Andric return false; 6487a7e6055SDimitry Andric for (MachineBasicBlock *Succ : BB.successors()) 6497a7e6055SDimitry Andric if (!Successors.count(Succ)) 6507a7e6055SDimitry Andric return false; 6517a7e6055SDimitry Andric return true; 6527a7e6055SDimitry Andric } 6537a7e6055SDimitry Andric 6547a7e6055SDimitry Andric /// Check if a block should be tail duplicated to increase fallthrough 6557a7e6055SDimitry Andric /// opportunities. 6567a7e6055SDimitry Andric /// \p BB Block to check. 6577a7e6055SDimitry Andric bool MachineBlockPlacement::shouldTailDuplicate(MachineBasicBlock *BB) { 6587a7e6055SDimitry Andric // Blocks with single successors don't create additional fallthrough 6597a7e6055SDimitry Andric // opportunities. Don't duplicate them. TODO: When conditional exits are 6607a7e6055SDimitry Andric // analyzable, allow them to be duplicated. 6617a7e6055SDimitry Andric bool IsSimple = TailDup.isSimpleBB(BB); 6627a7e6055SDimitry Andric 6637a7e6055SDimitry Andric if (BB->succ_size() == 1) 6647a7e6055SDimitry Andric return false; 6657a7e6055SDimitry Andric return TailDup.shouldTailDuplicate(IsSimple, *BB); 6667a7e6055SDimitry Andric } 6677a7e6055SDimitry Andric 6687a7e6055SDimitry Andric /// Compare 2 BlockFrequency's with a small penalty for \p A. 6697a7e6055SDimitry Andric /// In order to be conservative, we apply a X% penalty to account for 6707a7e6055SDimitry Andric /// increased icache pressure and static heuristics. For small frequencies 6717a7e6055SDimitry Andric /// we use only the numerators to improve accuracy. For simplicity, we assume the 6727a7e6055SDimitry Andric /// penalty is less than 100% 6737a7e6055SDimitry Andric /// TODO(iteratee): Use 64-bit fixed point edge frequencies everywhere. 6747a7e6055SDimitry Andric static bool greaterWithBias(BlockFrequency A, BlockFrequency B, 6757a7e6055SDimitry Andric uint64_t EntryFreq) { 6767a7e6055SDimitry Andric BranchProbability ThresholdProb(TailDupPlacementPenalty, 100); 6777a7e6055SDimitry Andric BlockFrequency Gain = A - B; 6787a7e6055SDimitry Andric return (Gain / ThresholdProb).getFrequency() >= EntryFreq; 6797a7e6055SDimitry Andric } 6807a7e6055SDimitry Andric 6817a7e6055SDimitry Andric /// Check the edge frequencies to see if tail duplication will increase 6827a7e6055SDimitry Andric /// fallthroughs. It only makes sense to call this function when 6837a7e6055SDimitry Andric /// \p Succ would not be chosen otherwise. Tail duplication of \p Succ is 6847a7e6055SDimitry Andric /// always locally profitable if we would have picked \p Succ without 6857a7e6055SDimitry Andric /// considering duplication. 6867a7e6055SDimitry Andric bool MachineBlockPlacement::isProfitableToTailDup( 6877a7e6055SDimitry Andric const MachineBasicBlock *BB, const MachineBasicBlock *Succ, 6887a7e6055SDimitry Andric BranchProbability QProb, 6897a7e6055SDimitry Andric const BlockChain &Chain, const BlockFilterSet *BlockFilter) { 6907a7e6055SDimitry Andric // We need to do a probability calculation to make sure this is profitable. 6917a7e6055SDimitry Andric // First: does succ have a successor that post-dominates? This affects the 6927a7e6055SDimitry Andric // calculation. The 2 relevant cases are: 6937a7e6055SDimitry Andric // BB BB 6947a7e6055SDimitry Andric // | \Qout | \Qout 6957a7e6055SDimitry Andric // P| C |P C 6967a7e6055SDimitry Andric // = C' = C' 6977a7e6055SDimitry Andric // | /Qin | /Qin 6987a7e6055SDimitry Andric // | / | / 6997a7e6055SDimitry Andric // Succ Succ 7007a7e6055SDimitry Andric // / \ | \ V 7017a7e6055SDimitry Andric // U/ =V |U \ 7027a7e6055SDimitry Andric // / \ = D 7037a7e6055SDimitry Andric // D E | / 7047a7e6055SDimitry Andric // | / 7057a7e6055SDimitry Andric // |/ 7067a7e6055SDimitry Andric // PDom 7077a7e6055SDimitry Andric // '=' : Branch taken for that CFG edge 7087a7e6055SDimitry Andric // In the second case, Placing Succ while duplicating it into C prevents the 7097a7e6055SDimitry Andric // fallthrough of Succ into either D or PDom, because they now have C as an 7107a7e6055SDimitry Andric // unplaced predecessor 7117a7e6055SDimitry Andric 7127a7e6055SDimitry Andric // Start by figuring out which case we fall into 7137a7e6055SDimitry Andric MachineBasicBlock *PDom = nullptr; 7147a7e6055SDimitry Andric SmallVector<MachineBasicBlock *, 4> SuccSuccs; 7157a7e6055SDimitry Andric // Only scan the relevant successors 7167a7e6055SDimitry Andric auto AdjustedSuccSumProb = 7177a7e6055SDimitry Andric collectViableSuccessors(Succ, Chain, BlockFilter, SuccSuccs); 7187a7e6055SDimitry Andric BranchProbability PProb = MBPI->getEdgeProbability(BB, Succ); 7197a7e6055SDimitry Andric auto BBFreq = MBFI->getBlockFreq(BB); 7207a7e6055SDimitry Andric auto SuccFreq = MBFI->getBlockFreq(Succ); 7217a7e6055SDimitry Andric BlockFrequency P = BBFreq * PProb; 7227a7e6055SDimitry Andric BlockFrequency Qout = BBFreq * QProb; 7237a7e6055SDimitry Andric uint64_t EntryFreq = MBFI->getEntryFreq(); 7247a7e6055SDimitry Andric // If there are no more successors, it is profitable to copy, as it strictly 7257a7e6055SDimitry Andric // increases fallthrough. 7267a7e6055SDimitry Andric if (SuccSuccs.size() == 0) 7277a7e6055SDimitry Andric return greaterWithBias(P, Qout, EntryFreq); 7287a7e6055SDimitry Andric 7297a7e6055SDimitry Andric auto BestSuccSucc = BranchProbability::getZero(); 7307a7e6055SDimitry Andric // Find the PDom or the best Succ if no PDom exists. 7317a7e6055SDimitry Andric for (MachineBasicBlock *SuccSucc : SuccSuccs) { 7327a7e6055SDimitry Andric auto Prob = MBPI->getEdgeProbability(Succ, SuccSucc); 7337a7e6055SDimitry Andric if (Prob > BestSuccSucc) 7347a7e6055SDimitry Andric BestSuccSucc = Prob; 7357a7e6055SDimitry Andric if (PDom == nullptr) 7367a7e6055SDimitry Andric if (MPDT->dominates(SuccSucc, Succ)) { 7377a7e6055SDimitry Andric PDom = SuccSucc; 7387a7e6055SDimitry Andric break; 7397a7e6055SDimitry Andric } 7407a7e6055SDimitry Andric } 7417a7e6055SDimitry Andric // For the comparisons, we need to know Succ's best incoming edge that isn't 7427a7e6055SDimitry Andric // from BB. 7437a7e6055SDimitry Andric auto SuccBestPred = BlockFrequency(0); 7447a7e6055SDimitry Andric for (MachineBasicBlock *SuccPred : Succ->predecessors()) { 7457a7e6055SDimitry Andric if (SuccPred == Succ || SuccPred == BB 7467a7e6055SDimitry Andric || BlockToChain[SuccPred] == &Chain 7477a7e6055SDimitry Andric || (BlockFilter && !BlockFilter->count(SuccPred))) 7483ca95b02SDimitry Andric continue; 7497a7e6055SDimitry Andric auto Freq = MBFI->getBlockFreq(SuccPred) 7507a7e6055SDimitry Andric * MBPI->getEdgeProbability(SuccPred, Succ); 7517a7e6055SDimitry Andric if (Freq > SuccBestPred) 7527a7e6055SDimitry Andric SuccBestPred = Freq; 7537a7e6055SDimitry Andric } 7547a7e6055SDimitry Andric // Qin is Succ's best unplaced incoming edge that isn't BB 7557a7e6055SDimitry Andric BlockFrequency Qin = SuccBestPred; 7567a7e6055SDimitry Andric // If it doesn't have a post-dominating successor, here is the calculation: 7577a7e6055SDimitry Andric // BB BB 7587a7e6055SDimitry Andric // | \Qout | \ 7597a7e6055SDimitry Andric // P| C | = 7607a7e6055SDimitry Andric // = C' | C 7617a7e6055SDimitry Andric // | /Qin | | 7627a7e6055SDimitry Andric // | / | C' (+Succ) 7637a7e6055SDimitry Andric // Succ Succ /| 7647a7e6055SDimitry Andric // / \ | \/ | 7657a7e6055SDimitry Andric // U/ =V | == | 7667a7e6055SDimitry Andric // / \ | / \| 7677a7e6055SDimitry Andric // D E D E 7687a7e6055SDimitry Andric // '=' : Branch taken for that CFG edge 7697a7e6055SDimitry Andric // Cost in the first case is: P + V 7707a7e6055SDimitry Andric // For this calculation, we always assume P > Qout. If Qout > P 7717a7e6055SDimitry Andric // The result of this function will be ignored at the caller. 7727a7e6055SDimitry Andric // Let F = SuccFreq - Qin 7737a7e6055SDimitry Andric // Cost in the second case is: Qout + min(Qin, F) * U + max(Qin, F) * V 7747a7e6055SDimitry Andric 7757a7e6055SDimitry Andric if (PDom == nullptr || !Succ->isSuccessor(PDom)) { 7767a7e6055SDimitry Andric BranchProbability UProb = BestSuccSucc; 7777a7e6055SDimitry Andric BranchProbability VProb = AdjustedSuccSumProb - UProb; 7787a7e6055SDimitry Andric BlockFrequency F = SuccFreq - Qin; 7797a7e6055SDimitry Andric BlockFrequency V = SuccFreq * VProb; 7807a7e6055SDimitry Andric BlockFrequency QinU = std::min(Qin, F) * UProb; 7817a7e6055SDimitry Andric BlockFrequency BaseCost = P + V; 7827a7e6055SDimitry Andric BlockFrequency DupCost = Qout + QinU + std::max(Qin, F) * VProb; 7837a7e6055SDimitry Andric return greaterWithBias(BaseCost, DupCost, EntryFreq); 7847a7e6055SDimitry Andric } 7857a7e6055SDimitry Andric BranchProbability UProb = MBPI->getEdgeProbability(Succ, PDom); 7867a7e6055SDimitry Andric BranchProbability VProb = AdjustedSuccSumProb - UProb; 7877a7e6055SDimitry Andric BlockFrequency U = SuccFreq * UProb; 7887a7e6055SDimitry Andric BlockFrequency V = SuccFreq * VProb; 7897a7e6055SDimitry Andric BlockFrequency F = SuccFreq - Qin; 7907a7e6055SDimitry Andric // If there is a post-dominating successor, here is the calculation: 7917a7e6055SDimitry Andric // BB BB BB BB 7927a7e6055SDimitry Andric // | \Qout | \ | \Qout | \ 7937a7e6055SDimitry Andric // |P C | = |P C | = 7947a7e6055SDimitry Andric // = C' |P C = C' |P C 7957a7e6055SDimitry Andric // | /Qin | | | /Qin | | 7967a7e6055SDimitry Andric // | / | C' (+Succ) | / | C' (+Succ) 7977a7e6055SDimitry Andric // Succ Succ /| Succ Succ /| 7987a7e6055SDimitry Andric // | \ V | \/ | | \ V | \/ | 7997a7e6055SDimitry Andric // |U \ |U /\ =? |U = |U /\ | 8007a7e6055SDimitry Andric // = D = = =?| | D | = =| 8017a7e6055SDimitry Andric // | / |/ D | / |/ D 8027a7e6055SDimitry Andric // | / | / | = | / 8037a7e6055SDimitry Andric // |/ | / |/ | = 8047a7e6055SDimitry Andric // Dom Dom Dom Dom 8057a7e6055SDimitry Andric // '=' : Branch taken for that CFG edge 8067a7e6055SDimitry Andric // The cost for taken branches in the first case is P + U 8077a7e6055SDimitry Andric // Let F = SuccFreq - Qin 8087a7e6055SDimitry Andric // The cost in the second case (assuming independence), given the layout: 8097a7e6055SDimitry Andric // BB, Succ, (C+Succ), D, Dom or the layout: 8107a7e6055SDimitry Andric // BB, Succ, D, Dom, (C+Succ) 8117a7e6055SDimitry Andric // is Qout + max(F, Qin) * U + min(F, Qin) 8127a7e6055SDimitry Andric // compare P + U vs Qout + P * U + Qin. 8137a7e6055SDimitry Andric // 8147a7e6055SDimitry Andric // The 3rd and 4th cases cover when Dom would be chosen to follow Succ. 8157a7e6055SDimitry Andric // 8167a7e6055SDimitry Andric // For the 3rd case, the cost is P + 2 * V 8177a7e6055SDimitry Andric // For the 4th case, the cost is Qout + min(Qin, F) * U + max(Qin, F) * V + V 8187a7e6055SDimitry Andric // We choose 4 over 3 when (P + V) > Qout + min(Qin, F) * U + max(Qin, F) * V 8197a7e6055SDimitry Andric if (UProb > AdjustedSuccSumProb / 2 && 8207a7e6055SDimitry Andric !hasBetterLayoutPredecessor(Succ, PDom, *BlockToChain[PDom], UProb, UProb, 8217a7e6055SDimitry Andric Chain, BlockFilter)) 8227a7e6055SDimitry Andric // Cases 3 & 4 8237a7e6055SDimitry Andric return greaterWithBias( 8247a7e6055SDimitry Andric (P + V), (Qout + std::max(Qin, F) * VProb + std::min(Qin, F) * UProb), 8257a7e6055SDimitry Andric EntryFreq); 8267a7e6055SDimitry Andric // Cases 1 & 2 8277a7e6055SDimitry Andric return greaterWithBias((P + U), 8287a7e6055SDimitry Andric (Qout + std::min(Qin, F) * AdjustedSuccSumProb + 8297a7e6055SDimitry Andric std::max(Qin, F) * UProb), 8307a7e6055SDimitry Andric EntryFreq); 8317a7e6055SDimitry Andric } 8327a7e6055SDimitry Andric 8337a7e6055SDimitry Andric /// Check for a trellis layout. \p BB is the upper part of a trellis if its 8347a7e6055SDimitry Andric /// successors form the lower part of a trellis. A successor set S forms the 8357a7e6055SDimitry Andric /// lower part of a trellis if all of the predecessors of S are either in S or 8367a7e6055SDimitry Andric /// have all of S as successors. We ignore trellises where BB doesn't have 2 8377a7e6055SDimitry Andric /// successors because for fewer than 2, it's trivial, and for 3 or greater they 8387a7e6055SDimitry Andric /// are very uncommon and complex to compute optimally. Allowing edges within S 8397a7e6055SDimitry Andric /// is not strictly a trellis, but the same algorithm works, so we allow it. 8407a7e6055SDimitry Andric bool MachineBlockPlacement::isTrellis( 8417a7e6055SDimitry Andric const MachineBasicBlock *BB, 8427a7e6055SDimitry Andric const SmallVectorImpl<MachineBasicBlock *> &ViableSuccs, 8437a7e6055SDimitry Andric const BlockChain &Chain, const BlockFilterSet *BlockFilter) { 8447a7e6055SDimitry Andric // Technically BB could form a trellis with branching factor higher than 2. 8457a7e6055SDimitry Andric // But that's extremely uncommon. 8467a7e6055SDimitry Andric if (BB->succ_size() != 2 || ViableSuccs.size() != 2) 8477a7e6055SDimitry Andric return false; 8487a7e6055SDimitry Andric 8497a7e6055SDimitry Andric SmallPtrSet<const MachineBasicBlock *, 2> Successors(BB->succ_begin(), 8507a7e6055SDimitry Andric BB->succ_end()); 8517a7e6055SDimitry Andric // To avoid reviewing the same predecessors twice. 8527a7e6055SDimitry Andric SmallPtrSet<const MachineBasicBlock *, 8> SeenPreds; 8537a7e6055SDimitry Andric 8547a7e6055SDimitry Andric for (MachineBasicBlock *Succ : ViableSuccs) { 8557a7e6055SDimitry Andric int PredCount = 0; 8567a7e6055SDimitry Andric for (auto SuccPred : Succ->predecessors()) { 8577a7e6055SDimitry Andric // Allow triangle successors, but don't count them. 8587a7e6055SDimitry Andric if (Successors.count(SuccPred)) { 8597a7e6055SDimitry Andric // Make sure that it is actually a triangle. 8607a7e6055SDimitry Andric for (MachineBasicBlock *CheckSucc : SuccPred->successors()) 8617a7e6055SDimitry Andric if (!Successors.count(CheckSucc)) 8627a7e6055SDimitry Andric return false; 8633ca95b02SDimitry Andric continue; 8647a7e6055SDimitry Andric } 8657a7e6055SDimitry Andric const BlockChain *PredChain = BlockToChain[SuccPred]; 8667a7e6055SDimitry Andric if (SuccPred == BB || (BlockFilter && !BlockFilter->count(SuccPred)) || 8677a7e6055SDimitry Andric PredChain == &Chain || PredChain == BlockToChain[Succ]) 8687a7e6055SDimitry Andric continue; 8697a7e6055SDimitry Andric ++PredCount; 8707a7e6055SDimitry Andric // Perform the successor check only once. 8717a7e6055SDimitry Andric if (!SeenPreds.insert(SuccPred).second) 8727a7e6055SDimitry Andric continue; 8737a7e6055SDimitry Andric if (!hasSameSuccessors(*SuccPred, Successors)) 8747a7e6055SDimitry Andric return false; 8757a7e6055SDimitry Andric } 8767a7e6055SDimitry Andric // If one of the successors has only BB as a predecessor, it is not a 8777a7e6055SDimitry Andric // trellis. 8787a7e6055SDimitry Andric if (PredCount < 1) 8793ca95b02SDimitry Andric return false; 8803ca95b02SDimitry Andric } 8813ca95b02SDimitry Andric return true; 8827a7e6055SDimitry Andric } 8837a7e6055SDimitry Andric 8847a7e6055SDimitry Andric /// Pick the highest total weight pair of edges that can both be laid out. 8857a7e6055SDimitry Andric /// The edges in \p Edges[0] are assumed to have a different destination than 8867a7e6055SDimitry Andric /// the edges in \p Edges[1]. Simple counting shows that the best pair is either 8877a7e6055SDimitry Andric /// the individual highest weight edges to the 2 different destinations, or in 8887a7e6055SDimitry Andric /// case of a conflict, one of them should be replaced with a 2nd best edge. 8897a7e6055SDimitry Andric std::pair<MachineBlockPlacement::WeightedEdge, 8907a7e6055SDimitry Andric MachineBlockPlacement::WeightedEdge> 8917a7e6055SDimitry Andric MachineBlockPlacement::getBestNonConflictingEdges( 8927a7e6055SDimitry Andric const MachineBasicBlock *BB, 8937a7e6055SDimitry Andric MutableArrayRef<SmallVector<MachineBlockPlacement::WeightedEdge, 8>> 8947a7e6055SDimitry Andric Edges) { 8957a7e6055SDimitry Andric // Sort the edges, and then for each successor, find the best incoming 8967a7e6055SDimitry Andric // predecessor. If the best incoming predecessors aren't the same, 8977a7e6055SDimitry Andric // then that is clearly the best layout. If there is a conflict, one of the 8987a7e6055SDimitry Andric // successors will have to fallthrough from the second best predecessor. We 8997a7e6055SDimitry Andric // compare which combination is better overall. 9007a7e6055SDimitry Andric 9017a7e6055SDimitry Andric // Sort for highest frequency. 9027a7e6055SDimitry Andric auto Cmp = [](WeightedEdge A, WeightedEdge B) { return A.Weight > B.Weight; }; 9037a7e6055SDimitry Andric 9047a7e6055SDimitry Andric std::stable_sort(Edges[0].begin(), Edges[0].end(), Cmp); 9057a7e6055SDimitry Andric std::stable_sort(Edges[1].begin(), Edges[1].end(), Cmp); 9067a7e6055SDimitry Andric auto BestA = Edges[0].begin(); 9077a7e6055SDimitry Andric auto BestB = Edges[1].begin(); 9087a7e6055SDimitry Andric // Arrange for the correct answer to be in BestA and BestB 9097a7e6055SDimitry Andric // If the 2 best edges don't conflict, the answer is already there. 9107a7e6055SDimitry Andric if (BestA->Src == BestB->Src) { 9117a7e6055SDimitry Andric // Compare the total fallthrough of (Best + Second Best) for both pairs 9127a7e6055SDimitry Andric auto SecondBestA = std::next(BestA); 9137a7e6055SDimitry Andric auto SecondBestB = std::next(BestB); 9147a7e6055SDimitry Andric BlockFrequency BestAScore = BestA->Weight + SecondBestB->Weight; 9157a7e6055SDimitry Andric BlockFrequency BestBScore = BestB->Weight + SecondBestA->Weight; 9167a7e6055SDimitry Andric if (BestAScore < BestBScore) 9177a7e6055SDimitry Andric BestA = SecondBestA; 9187a7e6055SDimitry Andric else 9197a7e6055SDimitry Andric BestB = SecondBestB; 9207a7e6055SDimitry Andric } 9217a7e6055SDimitry Andric // Arrange for the BB edge to be in BestA if it exists. 9227a7e6055SDimitry Andric if (BestB->Src == BB) 9237a7e6055SDimitry Andric std::swap(BestA, BestB); 9247a7e6055SDimitry Andric return std::make_pair(*BestA, *BestB); 9257a7e6055SDimitry Andric } 9267a7e6055SDimitry Andric 9277a7e6055SDimitry Andric /// Get the best successor from \p BB based on \p BB being part of a trellis. 9287a7e6055SDimitry Andric /// We only handle trellises with 2 successors, so the algorithm is 9297a7e6055SDimitry Andric /// straightforward: Find the best pair of edges that don't conflict. We find 9307a7e6055SDimitry Andric /// the best incoming edge for each successor in the trellis. If those conflict, 9317a7e6055SDimitry Andric /// we consider which of them should be replaced with the second best. 9327a7e6055SDimitry Andric /// Upon return the two best edges will be in \p BestEdges. If one of the edges 9337a7e6055SDimitry Andric /// comes from \p BB, it will be in \p BestEdges[0] 9347a7e6055SDimitry Andric MachineBlockPlacement::BlockAndTailDupResult 9357a7e6055SDimitry Andric MachineBlockPlacement::getBestTrellisSuccessor( 9367a7e6055SDimitry Andric const MachineBasicBlock *BB, 9377a7e6055SDimitry Andric const SmallVectorImpl<MachineBasicBlock *> &ViableSuccs, 9387a7e6055SDimitry Andric BranchProbability AdjustedSumProb, const BlockChain &Chain, 9397a7e6055SDimitry Andric const BlockFilterSet *BlockFilter) { 9407a7e6055SDimitry Andric 9417a7e6055SDimitry Andric BlockAndTailDupResult Result = {nullptr, false}; 9427a7e6055SDimitry Andric SmallPtrSet<const MachineBasicBlock *, 4> Successors(BB->succ_begin(), 9437a7e6055SDimitry Andric BB->succ_end()); 9447a7e6055SDimitry Andric 9457a7e6055SDimitry Andric // We assume size 2 because it's common. For general n, we would have to do 9467a7e6055SDimitry Andric // the Hungarian algorithm, but it's not worth the complexity because more 9477a7e6055SDimitry Andric // than 2 successors is fairly uncommon, and a trellis even more so. 9487a7e6055SDimitry Andric if (Successors.size() != 2 || ViableSuccs.size() != 2) 9497a7e6055SDimitry Andric return Result; 9507a7e6055SDimitry Andric 9517a7e6055SDimitry Andric // Collect the edge frequencies of all edges that form the trellis. 9527a7e6055SDimitry Andric SmallVector<WeightedEdge, 8> Edges[2]; 9537a7e6055SDimitry Andric int SuccIndex = 0; 9547a7e6055SDimitry Andric for (auto Succ : ViableSuccs) { 9557a7e6055SDimitry Andric for (MachineBasicBlock *SuccPred : Succ->predecessors()) { 9567a7e6055SDimitry Andric // Skip any placed predecessors that are not BB 9577a7e6055SDimitry Andric if (SuccPred != BB) 9587a7e6055SDimitry Andric if ((BlockFilter && !BlockFilter->count(SuccPred)) || 9597a7e6055SDimitry Andric BlockToChain[SuccPred] == &Chain || 9607a7e6055SDimitry Andric BlockToChain[SuccPred] == BlockToChain[Succ]) 9617a7e6055SDimitry Andric continue; 9627a7e6055SDimitry Andric BlockFrequency EdgeFreq = MBFI->getBlockFreq(SuccPred) * 9637a7e6055SDimitry Andric MBPI->getEdgeProbability(SuccPred, Succ); 9647a7e6055SDimitry Andric Edges[SuccIndex].push_back({EdgeFreq, SuccPred, Succ}); 9657a7e6055SDimitry Andric } 9667a7e6055SDimitry Andric ++SuccIndex; 9677a7e6055SDimitry Andric } 9687a7e6055SDimitry Andric 9697a7e6055SDimitry Andric // Pick the best combination of 2 edges from all the edges in the trellis. 9707a7e6055SDimitry Andric WeightedEdge BestA, BestB; 9717a7e6055SDimitry Andric std::tie(BestA, BestB) = getBestNonConflictingEdges(BB, Edges); 9727a7e6055SDimitry Andric 9737a7e6055SDimitry Andric if (BestA.Src != BB) { 9747a7e6055SDimitry Andric // If we have a trellis, and BB doesn't have the best fallthrough edges, 9757a7e6055SDimitry Andric // we shouldn't choose any successor. We've already looked and there's a 9767a7e6055SDimitry Andric // better fallthrough edge for all the successors. 9777a7e6055SDimitry Andric DEBUG(dbgs() << "Trellis, but not one of the chosen edges.\n"); 9787a7e6055SDimitry Andric return Result; 9797a7e6055SDimitry Andric } 9807a7e6055SDimitry Andric 9817a7e6055SDimitry Andric // Did we pick the triangle edge? If tail-duplication is profitable, do 9827a7e6055SDimitry Andric // that instead. Otherwise merge the triangle edge now while we know it is 9837a7e6055SDimitry Andric // optimal. 9847a7e6055SDimitry Andric if (BestA.Dest == BestB.Src) { 9857a7e6055SDimitry Andric // The edges are BB->Succ1->Succ2, and we're looking to see if BB->Succ2 9867a7e6055SDimitry Andric // would be better. 9877a7e6055SDimitry Andric MachineBasicBlock *Succ1 = BestA.Dest; 9887a7e6055SDimitry Andric MachineBasicBlock *Succ2 = BestB.Dest; 9897a7e6055SDimitry Andric // Check to see if tail-duplication would be profitable. 9907a7e6055SDimitry Andric if (TailDupPlacement && shouldTailDuplicate(Succ2) && 9917a7e6055SDimitry Andric canTailDuplicateUnplacedPreds(BB, Succ2, Chain, BlockFilter) && 9927a7e6055SDimitry Andric isProfitableToTailDup(BB, Succ2, MBPI->getEdgeProbability(BB, Succ1), 9937a7e6055SDimitry Andric Chain, BlockFilter)) { 9947a7e6055SDimitry Andric DEBUG(BranchProbability Succ2Prob = getAdjustedProbability( 9957a7e6055SDimitry Andric MBPI->getEdgeProbability(BB, Succ2), AdjustedSumProb); 9967a7e6055SDimitry Andric dbgs() << " Selected: " << getBlockName(Succ2) 9977a7e6055SDimitry Andric << ", probability: " << Succ2Prob << " (Tail Duplicate)\n"); 9987a7e6055SDimitry Andric Result.BB = Succ2; 9997a7e6055SDimitry Andric Result.ShouldTailDup = true; 10007a7e6055SDimitry Andric return Result; 10017a7e6055SDimitry Andric } 10027a7e6055SDimitry Andric } 10037a7e6055SDimitry Andric // We have already computed the optimal edge for the other side of the 10047a7e6055SDimitry Andric // trellis. 10057a7e6055SDimitry Andric ComputedEdges[BestB.Src] = { BestB.Dest, false }; 10067a7e6055SDimitry Andric 10077a7e6055SDimitry Andric auto TrellisSucc = BestA.Dest; 10087a7e6055SDimitry Andric DEBUG(BranchProbability SuccProb = getAdjustedProbability( 10097a7e6055SDimitry Andric MBPI->getEdgeProbability(BB, TrellisSucc), AdjustedSumProb); 10107a7e6055SDimitry Andric dbgs() << " Selected: " << getBlockName(TrellisSucc) 10117a7e6055SDimitry Andric << ", probability: " << SuccProb << " (Trellis)\n"); 10127a7e6055SDimitry Andric Result.BB = TrellisSucc; 10137a7e6055SDimitry Andric return Result; 10147a7e6055SDimitry Andric } 10157a7e6055SDimitry Andric 10167a7e6055SDimitry Andric /// When the option TailDupPlacement is on, this method checks if the 10177a7e6055SDimitry Andric /// fallthrough candidate block \p Succ (of block \p BB) can be tail-duplicated 10187a7e6055SDimitry Andric /// into all of its unplaced, unfiltered predecessors, that are not BB. 10197a7e6055SDimitry Andric bool MachineBlockPlacement::canTailDuplicateUnplacedPreds( 10207a7e6055SDimitry Andric const MachineBasicBlock *BB, MachineBasicBlock *Succ, 10217a7e6055SDimitry Andric const BlockChain &Chain, const BlockFilterSet *BlockFilter) { 10227a7e6055SDimitry Andric if (!shouldTailDuplicate(Succ)) 10233ca95b02SDimitry Andric return false; 10247a7e6055SDimitry Andric 10257a7e6055SDimitry Andric // For CFG checking. 10267a7e6055SDimitry Andric SmallPtrSet<const MachineBasicBlock *, 4> Successors(BB->succ_begin(), 10277a7e6055SDimitry Andric BB->succ_end()); 10287a7e6055SDimitry Andric for (MachineBasicBlock *Pred : Succ->predecessors()) { 10297a7e6055SDimitry Andric // Make sure all unplaced and unfiltered predecessors can be 10307a7e6055SDimitry Andric // tail-duplicated into. 10317a7e6055SDimitry Andric // Skip any blocks that are already placed or not in this loop. 10327a7e6055SDimitry Andric if (Pred == BB || (BlockFilter && !BlockFilter->count(Pred)) 10337a7e6055SDimitry Andric || BlockToChain[Pred] == &Chain) 10347a7e6055SDimitry Andric continue; 10357a7e6055SDimitry Andric if (!TailDup.canTailDuplicate(Succ, Pred)) { 10367a7e6055SDimitry Andric if (Successors.size() > 1 && hasSameSuccessors(*Pred, Successors)) 10377a7e6055SDimitry Andric // This will result in a trellis after tail duplication, so we don't 10387a7e6055SDimitry Andric // need to copy Succ into this predecessor. In the presence 10397a7e6055SDimitry Andric // of a trellis tail duplication can continue to be profitable. 10407a7e6055SDimitry Andric // For example: 10417a7e6055SDimitry Andric // A A 10427a7e6055SDimitry Andric // |\ |\ 10437a7e6055SDimitry Andric // | \ | \ 10447a7e6055SDimitry Andric // | C | C+BB 10457a7e6055SDimitry Andric // | / | | 10467a7e6055SDimitry Andric // |/ | | 10477a7e6055SDimitry Andric // BB => BB | 10487a7e6055SDimitry Andric // |\ |\/| 10497a7e6055SDimitry Andric // | \ |/\| 10507a7e6055SDimitry Andric // | D | D 10517a7e6055SDimitry Andric // | / | / 10527a7e6055SDimitry Andric // |/ |/ 10537a7e6055SDimitry Andric // Succ Succ 10547a7e6055SDimitry Andric // 10557a7e6055SDimitry Andric // After BB was duplicated into C, the layout looks like the one on the 10567a7e6055SDimitry Andric // right. BB and C now have the same successors. When considering 10577a7e6055SDimitry Andric // whether Succ can be duplicated into all its unplaced predecessors, we 10587a7e6055SDimitry Andric // ignore C. 10597a7e6055SDimitry Andric // We can do this because C already has a profitable fallthrough, namely 10607a7e6055SDimitry Andric // D. TODO(iteratee): ignore sufficiently cold predecessors for 10617a7e6055SDimitry Andric // duplication and for this test. 10627a7e6055SDimitry Andric // 10637a7e6055SDimitry Andric // This allows trellises to be laid out in 2 separate chains 10647a7e6055SDimitry Andric // (A,B,Succ,...) and later (C,D,...) This is a reasonable heuristic 10657a7e6055SDimitry Andric // because it allows the creation of 2 fallthrough paths with links 10667a7e6055SDimitry Andric // between them, and we correctly identify the best layout for these 10677a7e6055SDimitry Andric // CFGs. We want to extend trellises that the user created in addition 10687a7e6055SDimitry Andric // to trellises created by tail-duplication, so we just look for the 10697a7e6055SDimitry Andric // CFG. 10707a7e6055SDimitry Andric continue; 10717a7e6055SDimitry Andric return false; 10727a7e6055SDimitry Andric } 10737a7e6055SDimitry Andric } 10747a7e6055SDimitry Andric return true; 10757a7e6055SDimitry Andric } 10767a7e6055SDimitry Andric 10777a7e6055SDimitry Andric /// Find chains of triangles where we believe it would be profitable to 10787a7e6055SDimitry Andric /// tail-duplicate them all, but a local analysis would not find them. 10797a7e6055SDimitry Andric /// There are 3 ways this can be profitable: 10807a7e6055SDimitry Andric /// 1) The post-dominators marked 50% are actually taken 55% (This shrinks with 10817a7e6055SDimitry Andric /// longer chains) 10827a7e6055SDimitry Andric /// 2) The chains are statically correlated. Branch probabilities have a very 10837a7e6055SDimitry Andric /// U-shaped distribution. 10847a7e6055SDimitry Andric /// [http://nrs.harvard.edu/urn-3:HUL.InstRepos:24015805] 10857a7e6055SDimitry Andric /// If the branches in a chain are likely to be from the same side of the 10867a7e6055SDimitry Andric /// distribution as their predecessor, but are independent at runtime, this 10877a7e6055SDimitry Andric /// transformation is profitable. (Because the cost of being wrong is a small 10887a7e6055SDimitry Andric /// fixed cost, unlike the standard triangle layout where the cost of being 10897a7e6055SDimitry Andric /// wrong scales with the # of triangles.) 10907a7e6055SDimitry Andric /// 3) The chains are dynamically correlated. If the probability that a previous 10917a7e6055SDimitry Andric /// branch was taken positively influences whether the next branch will be 10927a7e6055SDimitry Andric /// taken 10937a7e6055SDimitry Andric /// We believe that 2 and 3 are common enough to justify the small margin in 1. 10947a7e6055SDimitry Andric void MachineBlockPlacement::precomputeTriangleChains() { 10957a7e6055SDimitry Andric struct TriangleChain { 10967a7e6055SDimitry Andric std::vector<MachineBasicBlock *> Edges; 10977a7e6055SDimitry Andric TriangleChain(MachineBasicBlock *src, MachineBasicBlock *dst) 10987a7e6055SDimitry Andric : Edges({src, dst}) {} 10997a7e6055SDimitry Andric 11007a7e6055SDimitry Andric void append(MachineBasicBlock *dst) { 11017a7e6055SDimitry Andric assert(getKey()->isSuccessor(dst) && 11027a7e6055SDimitry Andric "Attempting to append a block that is not a successor."); 11037a7e6055SDimitry Andric Edges.push_back(dst); 11047a7e6055SDimitry Andric } 11057a7e6055SDimitry Andric 11067a7e6055SDimitry Andric unsigned count() const { return Edges.size() - 1; } 11077a7e6055SDimitry Andric 11087a7e6055SDimitry Andric MachineBasicBlock *getKey() const { 11097a7e6055SDimitry Andric return Edges.back(); 11107a7e6055SDimitry Andric } 11117a7e6055SDimitry Andric }; 11127a7e6055SDimitry Andric 11137a7e6055SDimitry Andric if (TriangleChainCount == 0) 11147a7e6055SDimitry Andric return; 11157a7e6055SDimitry Andric 11167a7e6055SDimitry Andric DEBUG(dbgs() << "Pre-computing triangle chains.\n"); 11177a7e6055SDimitry Andric // Map from last block to the chain that contains it. This allows us to extend 11187a7e6055SDimitry Andric // chains as we find new triangles. 11197a7e6055SDimitry Andric DenseMap<const MachineBasicBlock *, TriangleChain> TriangleChainMap; 11207a7e6055SDimitry Andric for (MachineBasicBlock &BB : *F) { 11217a7e6055SDimitry Andric // If BB doesn't have 2 successors, it doesn't start a triangle. 11227a7e6055SDimitry Andric if (BB.succ_size() != 2) 11237a7e6055SDimitry Andric continue; 11247a7e6055SDimitry Andric MachineBasicBlock *PDom = nullptr; 11257a7e6055SDimitry Andric for (MachineBasicBlock *Succ : BB.successors()) { 11267a7e6055SDimitry Andric if (!MPDT->dominates(Succ, &BB)) 11277a7e6055SDimitry Andric continue; 11287a7e6055SDimitry Andric PDom = Succ; 11297a7e6055SDimitry Andric break; 11307a7e6055SDimitry Andric } 11317a7e6055SDimitry Andric // If BB doesn't have a post-dominating successor, it doesn't form a 11327a7e6055SDimitry Andric // triangle. 11337a7e6055SDimitry Andric if (PDom == nullptr) 11347a7e6055SDimitry Andric continue; 11357a7e6055SDimitry Andric // If PDom has a hint that it is low probability, skip this triangle. 11367a7e6055SDimitry Andric if (MBPI->getEdgeProbability(&BB, PDom) < BranchProbability(50, 100)) 11377a7e6055SDimitry Andric continue; 11387a7e6055SDimitry Andric // If PDom isn't eligible for duplication, this isn't the kind of triangle 11397a7e6055SDimitry Andric // we're looking for. 11407a7e6055SDimitry Andric if (!shouldTailDuplicate(PDom)) 11417a7e6055SDimitry Andric continue; 11427a7e6055SDimitry Andric bool CanTailDuplicate = true; 11437a7e6055SDimitry Andric // If PDom can't tail-duplicate into it's non-BB predecessors, then this 11447a7e6055SDimitry Andric // isn't the kind of triangle we're looking for. 11457a7e6055SDimitry Andric for (MachineBasicBlock* Pred : PDom->predecessors()) { 11467a7e6055SDimitry Andric if (Pred == &BB) 11477a7e6055SDimitry Andric continue; 11487a7e6055SDimitry Andric if (!TailDup.canTailDuplicate(PDom, Pred)) { 11497a7e6055SDimitry Andric CanTailDuplicate = false; 11507a7e6055SDimitry Andric break; 11517a7e6055SDimitry Andric } 11527a7e6055SDimitry Andric } 11537a7e6055SDimitry Andric // If we can't tail-duplicate PDom to its predecessors, then skip this 11547a7e6055SDimitry Andric // triangle. 11557a7e6055SDimitry Andric if (!CanTailDuplicate) 11567a7e6055SDimitry Andric continue; 11577a7e6055SDimitry Andric 11587a7e6055SDimitry Andric // Now we have an interesting triangle. Insert it if it's not part of an 11597a7e6055SDimitry Andric // existing chain 11607a7e6055SDimitry Andric // Note: This cannot be replaced with a call insert() or emplace() because 11617a7e6055SDimitry Andric // the find key is BB, but the insert/emplace key is PDom. 11627a7e6055SDimitry Andric auto Found = TriangleChainMap.find(&BB); 11637a7e6055SDimitry Andric // If it is, remove the chain from the map, grow it, and put it back in the 11647a7e6055SDimitry Andric // map with the end as the new key. 11657a7e6055SDimitry Andric if (Found != TriangleChainMap.end()) { 11667a7e6055SDimitry Andric TriangleChain Chain = std::move(Found->second); 11677a7e6055SDimitry Andric TriangleChainMap.erase(Found); 11687a7e6055SDimitry Andric Chain.append(PDom); 11697a7e6055SDimitry Andric TriangleChainMap.insert(std::make_pair(Chain.getKey(), std::move(Chain))); 11707a7e6055SDimitry Andric } else { 11717a7e6055SDimitry Andric auto InsertResult = TriangleChainMap.try_emplace(PDom, &BB, PDom); 11727a7e6055SDimitry Andric assert(InsertResult.second && "Block seen twice."); 11737a7e6055SDimitry Andric (void)InsertResult; 11747a7e6055SDimitry Andric } 11757a7e6055SDimitry Andric } 11767a7e6055SDimitry Andric 11777a7e6055SDimitry Andric // Iterating over a DenseMap is safe here, because the only thing in the body 11787a7e6055SDimitry Andric // of the loop is inserting into another DenseMap (ComputedEdges). 11797a7e6055SDimitry Andric // ComputedEdges is never iterated, so this doesn't lead to non-determinism. 11807a7e6055SDimitry Andric for (auto &ChainPair : TriangleChainMap) { 11817a7e6055SDimitry Andric TriangleChain &Chain = ChainPair.second; 11827a7e6055SDimitry Andric // Benchmarking has shown that due to branch correlation duplicating 2 or 11837a7e6055SDimitry Andric // more triangles is profitable, despite the calculations assuming 11847a7e6055SDimitry Andric // independence. 11857a7e6055SDimitry Andric if (Chain.count() < TriangleChainCount) 11867a7e6055SDimitry Andric continue; 11877a7e6055SDimitry Andric MachineBasicBlock *dst = Chain.Edges.back(); 11887a7e6055SDimitry Andric Chain.Edges.pop_back(); 11897a7e6055SDimitry Andric for (MachineBasicBlock *src : reverse(Chain.Edges)) { 11907a7e6055SDimitry Andric DEBUG(dbgs() << "Marking edge: " << getBlockName(src) << "->" << 11917a7e6055SDimitry Andric getBlockName(dst) << " as pre-computed based on triangles.\n"); 11927a7e6055SDimitry Andric 11937a7e6055SDimitry Andric auto InsertResult = ComputedEdges.insert({src, {dst, true}}); 11947a7e6055SDimitry Andric assert(InsertResult.second && "Block seen twice."); 11957a7e6055SDimitry Andric (void)InsertResult; 11967a7e6055SDimitry Andric 11977a7e6055SDimitry Andric dst = src; 11987a7e6055SDimitry Andric } 11997a7e6055SDimitry Andric } 12003ca95b02SDimitry Andric } 12013ca95b02SDimitry Andric 12023ca95b02SDimitry Andric // When profile is not present, return the StaticLikelyProb. 12033ca95b02SDimitry Andric // When profile is available, we need to handle the triangle-shape CFG. 12043ca95b02SDimitry Andric static BranchProbability getLayoutSuccessorProbThreshold( 12057a7e6055SDimitry Andric const MachineBasicBlock *BB) { 12063ca95b02SDimitry Andric if (!BB->getParent()->getFunction()->getEntryCount()) 12073ca95b02SDimitry Andric return BranchProbability(StaticLikelyProb, 100); 12083ca95b02SDimitry Andric if (BB->succ_size() == 2) { 12093ca95b02SDimitry Andric const MachineBasicBlock *Succ1 = *BB->succ_begin(); 12103ca95b02SDimitry Andric const MachineBasicBlock *Succ2 = *(BB->succ_begin() + 1); 12113ca95b02SDimitry Andric if (Succ1->isSuccessor(Succ2) || Succ2->isSuccessor(Succ1)) { 12123ca95b02SDimitry Andric /* See case 1 below for the cost analysis. For BB->Succ to 12133ca95b02SDimitry Andric * be taken with smaller cost, the following needs to hold: 12143ca95b02SDimitry Andric * Prob(BB->Succ) > 2 * Prob(BB->Pred) 12157a7e6055SDimitry Andric * So the threshold T in the calculation below 12167a7e6055SDimitry Andric * (1-T) * Prob(BB->Succ) > T * Prob(BB->Pred) 12177a7e6055SDimitry Andric * So T / (1 - T) = 2, Yielding T = 2/3 12187a7e6055SDimitry Andric * Also adding user specified branch bias, we have 12193ca95b02SDimitry Andric * T = (2/3)*(ProfileLikelyProb/50) 12203ca95b02SDimitry Andric * = (2*ProfileLikelyProb)/150) 12213ca95b02SDimitry Andric */ 12223ca95b02SDimitry Andric return BranchProbability(2 * ProfileLikelyProb, 150); 12233ca95b02SDimitry Andric } 12243ca95b02SDimitry Andric } 12253ca95b02SDimitry Andric return BranchProbability(ProfileLikelyProb, 100); 12263ca95b02SDimitry Andric } 12273ca95b02SDimitry Andric 12283ca95b02SDimitry Andric /// Checks to see if the layout candidate block \p Succ has a better layout 12293ca95b02SDimitry Andric /// predecessor than \c BB. If yes, returns true. 12307a7e6055SDimitry Andric /// \p SuccProb: The probability adjusted for only remaining blocks. 12317a7e6055SDimitry Andric /// Only used for logging 12327a7e6055SDimitry Andric /// \p RealSuccProb: The un-adjusted probability. 12337a7e6055SDimitry Andric /// \p Chain: The chain that BB belongs to and Succ is being considered for. 12347a7e6055SDimitry Andric /// \p BlockFilter: if non-null, the set of blocks that make up the loop being 12357a7e6055SDimitry Andric /// considered 12363ca95b02SDimitry Andric bool MachineBlockPlacement::hasBetterLayoutPredecessor( 12377a7e6055SDimitry Andric const MachineBasicBlock *BB, const MachineBasicBlock *Succ, 12387a7e6055SDimitry Andric const BlockChain &SuccChain, BranchProbability SuccProb, 12397a7e6055SDimitry Andric BranchProbability RealSuccProb, const BlockChain &Chain, 12407a7e6055SDimitry Andric const BlockFilterSet *BlockFilter) { 12413ca95b02SDimitry Andric 12423ca95b02SDimitry Andric // There isn't a better layout when there are no unscheduled predecessors. 12433ca95b02SDimitry Andric if (SuccChain.UnscheduledPredecessors == 0) 12443ca95b02SDimitry Andric return false; 12453ca95b02SDimitry Andric 12463ca95b02SDimitry Andric // There are two basic scenarios here: 12473ca95b02SDimitry Andric // ------------------------------------- 12483ca95b02SDimitry Andric // Case 1: triangular shape CFG (if-then): 12493ca95b02SDimitry Andric // BB 12503ca95b02SDimitry Andric // | \ 12513ca95b02SDimitry Andric // | \ 12523ca95b02SDimitry Andric // | Pred 12533ca95b02SDimitry Andric // | / 12543ca95b02SDimitry Andric // Succ 12553ca95b02SDimitry Andric // In this case, we are evaluating whether to select edge -> Succ, e.g. 12563ca95b02SDimitry Andric // set Succ as the layout successor of BB. Picking Succ as BB's 12573ca95b02SDimitry Andric // successor breaks the CFG constraints (FIXME: define these constraints). 12583ca95b02SDimitry Andric // With this layout, Pred BB 12593ca95b02SDimitry Andric // is forced to be outlined, so the overall cost will be cost of the 12603ca95b02SDimitry Andric // branch taken from BB to Pred, plus the cost of back taken branch 12613ca95b02SDimitry Andric // from Pred to Succ, as well as the additional cost associated 12623ca95b02SDimitry Andric // with the needed unconditional jump instruction from Pred To Succ. 12633ca95b02SDimitry Andric 12643ca95b02SDimitry Andric // The cost of the topological order layout is the taken branch cost 12653ca95b02SDimitry Andric // from BB to Succ, so to make BB->Succ a viable candidate, the following 12663ca95b02SDimitry Andric // must hold: 12673ca95b02SDimitry Andric // 2 * freq(BB->Pred) * taken_branch_cost + unconditional_jump_cost 12683ca95b02SDimitry Andric // < freq(BB->Succ) * taken_branch_cost. 12693ca95b02SDimitry Andric // Ignoring unconditional jump cost, we get 12703ca95b02SDimitry Andric // freq(BB->Succ) > 2 * freq(BB->Pred), i.e., 12713ca95b02SDimitry Andric // prob(BB->Succ) > 2 * prob(BB->Pred) 12723ca95b02SDimitry Andric // 12733ca95b02SDimitry Andric // When real profile data is available, we can precisely compute the 12743ca95b02SDimitry Andric // probability threshold that is needed for edge BB->Succ to be considered. 12753ca95b02SDimitry Andric // Without profile data, the heuristic requires the branch bias to be 12763ca95b02SDimitry Andric // a lot larger to make sure the signal is very strong (e.g. 80% default). 12773ca95b02SDimitry Andric // ----------------------------------------------------------------- 12783ca95b02SDimitry Andric // Case 2: diamond like CFG (if-then-else): 12793ca95b02SDimitry Andric // S 12803ca95b02SDimitry Andric // / \ 12813ca95b02SDimitry Andric // | \ 12823ca95b02SDimitry Andric // BB Pred 12833ca95b02SDimitry Andric // \ / 12843ca95b02SDimitry Andric // Succ 12853ca95b02SDimitry Andric // .. 12863ca95b02SDimitry Andric // 12873ca95b02SDimitry Andric // The current block is BB and edge BB->Succ is now being evaluated. 12883ca95b02SDimitry Andric // Note that edge S->BB was previously already selected because 12893ca95b02SDimitry Andric // prob(S->BB) > prob(S->Pred). 12903ca95b02SDimitry Andric // At this point, 2 blocks can be placed after BB: Pred or Succ. If we 12913ca95b02SDimitry Andric // choose Pred, we will have a topological ordering as shown on the left 12923ca95b02SDimitry Andric // in the picture below. If we choose Succ, we have the solution as shown 12933ca95b02SDimitry Andric // on the right: 12943ca95b02SDimitry Andric // 12953ca95b02SDimitry Andric // topo-order: 12963ca95b02SDimitry Andric // 12973ca95b02SDimitry Andric // S----- ---S 12983ca95b02SDimitry Andric // | | | | 12993ca95b02SDimitry Andric // ---BB | | BB 13003ca95b02SDimitry Andric // | | | | 13013ca95b02SDimitry Andric // | pred-- | Succ-- 13023ca95b02SDimitry Andric // | | | | 13033ca95b02SDimitry Andric // ---succ ---pred-- 13043ca95b02SDimitry Andric // 13053ca95b02SDimitry Andric // cost = freq(S->Pred) + freq(BB->Succ) cost = 2 * freq (S->Pred) 13063ca95b02SDimitry Andric // = freq(S->Pred) + freq(S->BB) 13073ca95b02SDimitry Andric // 13083ca95b02SDimitry Andric // If we have profile data (i.e, branch probabilities can be trusted), the 13093ca95b02SDimitry Andric // cost (number of taken branches) with layout S->BB->Succ->Pred is 2 * 13103ca95b02SDimitry Andric // freq(S->Pred) while the cost of topo order is freq(S->Pred) + freq(S->BB). 13113ca95b02SDimitry Andric // We know Prob(S->BB) > Prob(S->Pred), so freq(S->BB) > freq(S->Pred), which 13123ca95b02SDimitry Andric // means the cost of topological order is greater. 13133ca95b02SDimitry Andric // When profile data is not available, however, we need to be more 13143ca95b02SDimitry Andric // conservative. If the branch prediction is wrong, breaking the topo-order 13153ca95b02SDimitry Andric // will actually yield a layout with large cost. For this reason, we need 13163ca95b02SDimitry Andric // strong biased branch at block S with Prob(S->BB) in order to select 13173ca95b02SDimitry Andric // BB->Succ. This is equivalent to looking the CFG backward with backward 13183ca95b02SDimitry Andric // edge: Prob(Succ->BB) needs to >= HotProb in order to be selected (without 13193ca95b02SDimitry Andric // profile data). 1320d88c1a5aSDimitry Andric // -------------------------------------------------------------------------- 1321d88c1a5aSDimitry Andric // Case 3: forked diamond 1322d88c1a5aSDimitry Andric // S 1323d88c1a5aSDimitry Andric // / \ 1324d88c1a5aSDimitry Andric // / \ 1325d88c1a5aSDimitry Andric // BB Pred 1326d88c1a5aSDimitry Andric // | \ / | 1327d88c1a5aSDimitry Andric // | \ / | 1328d88c1a5aSDimitry Andric // | X | 1329d88c1a5aSDimitry Andric // | / \ | 1330d88c1a5aSDimitry Andric // | / \ | 1331d88c1a5aSDimitry Andric // S1 S2 1332d88c1a5aSDimitry Andric // 1333d88c1a5aSDimitry Andric // The current block is BB and edge BB->S1 is now being evaluated. 1334d88c1a5aSDimitry Andric // As above S->BB was already selected because 1335d88c1a5aSDimitry Andric // prob(S->BB) > prob(S->Pred). Assume that prob(BB->S1) >= prob(BB->S2). 1336d88c1a5aSDimitry Andric // 1337d88c1a5aSDimitry Andric // topo-order: 1338d88c1a5aSDimitry Andric // 1339d88c1a5aSDimitry Andric // S-------| ---S 1340d88c1a5aSDimitry Andric // | | | | 1341d88c1a5aSDimitry Andric // ---BB | | BB 1342d88c1a5aSDimitry Andric // | | | | 1343d88c1a5aSDimitry Andric // | Pred----| | S1---- 1344d88c1a5aSDimitry Andric // | | | | 1345d88c1a5aSDimitry Andric // --(S1 or S2) ---Pred-- 13467a7e6055SDimitry Andric // | 13477a7e6055SDimitry Andric // S2 1348d88c1a5aSDimitry Andric // 1349d88c1a5aSDimitry Andric // topo-cost = freq(S->Pred) + freq(BB->S1) + freq(BB->S2) 1350d88c1a5aSDimitry Andric // + min(freq(Pred->S1), freq(Pred->S2)) 1351d88c1a5aSDimitry Andric // Non-topo-order cost: 1352d88c1a5aSDimitry Andric // non-topo-cost = 2 * freq(S->Pred) + freq(BB->S2). 1353d88c1a5aSDimitry Andric // To be conservative, we can assume that min(freq(Pred->S1), freq(Pred->S2)) 1354d88c1a5aSDimitry Andric // is 0. Then the non topo layout is better when 1355d88c1a5aSDimitry Andric // freq(S->Pred) < freq(BB->S1). 1356d88c1a5aSDimitry Andric // This is exactly what is checked below. 1357d88c1a5aSDimitry Andric // Note there are other shapes that apply (Pred may not be a single block, 1358d88c1a5aSDimitry Andric // but they all fit this general pattern.) 13593ca95b02SDimitry Andric BranchProbability HotProb = getLayoutSuccessorProbThreshold(BB); 13603ca95b02SDimitry Andric 13613ca95b02SDimitry Andric // Make sure that a hot successor doesn't have a globally more 13623ca95b02SDimitry Andric // important predecessor. 13633ca95b02SDimitry Andric BlockFrequency CandidateEdgeFreq = MBFI->getBlockFreq(BB) * RealSuccProb; 13643ca95b02SDimitry Andric bool BadCFGConflict = false; 13653ca95b02SDimitry Andric 13663ca95b02SDimitry Andric for (MachineBasicBlock *Pred : Succ->predecessors()) { 13673ca95b02SDimitry Andric if (Pred == Succ || BlockToChain[Pred] == &SuccChain || 13683ca95b02SDimitry Andric (BlockFilter && !BlockFilter->count(Pred)) || 13697a7e6055SDimitry Andric BlockToChain[Pred] == &Chain || 13707a7e6055SDimitry Andric // This check is redundant except for look ahead. This function is 13717a7e6055SDimitry Andric // called for lookahead by isProfitableToTailDup when BB hasn't been 13727a7e6055SDimitry Andric // placed yet. 13737a7e6055SDimitry Andric (Pred == BB)) 13743ca95b02SDimitry Andric continue; 1375d88c1a5aSDimitry Andric // Do backward checking. 1376d88c1a5aSDimitry Andric // For all cases above, we need a backward checking to filter out edges that 13777a7e6055SDimitry Andric // are not 'strongly' biased. 13783ca95b02SDimitry Andric // BB Pred 13793ca95b02SDimitry Andric // \ / 13803ca95b02SDimitry Andric // Succ 13813ca95b02SDimitry Andric // We select edge BB->Succ if 13823ca95b02SDimitry Andric // freq(BB->Succ) > freq(Succ) * HotProb 13833ca95b02SDimitry Andric // i.e. freq(BB->Succ) > freq(BB->Succ) * HotProb + freq(Pred->Succ) * 13843ca95b02SDimitry Andric // HotProb 13853ca95b02SDimitry Andric // i.e. freq((BB->Succ) * (1 - HotProb) > freq(Pred->Succ) * HotProb 1386d88c1a5aSDimitry Andric // Case 1 is covered too, because the first equation reduces to: 1387d88c1a5aSDimitry Andric // prob(BB->Succ) > HotProb. (freq(Succ) = freq(BB) for a triangle) 13883ca95b02SDimitry Andric BlockFrequency PredEdgeFreq = 13893ca95b02SDimitry Andric MBFI->getBlockFreq(Pred) * MBPI->getEdgeProbability(Pred, Succ); 13903ca95b02SDimitry Andric if (PredEdgeFreq * HotProb >= CandidateEdgeFreq * HotProb.getCompl()) { 13913ca95b02SDimitry Andric BadCFGConflict = true; 13923ca95b02SDimitry Andric break; 13933ca95b02SDimitry Andric } 13943ca95b02SDimitry Andric } 13953ca95b02SDimitry Andric 13963ca95b02SDimitry Andric if (BadCFGConflict) { 1397d88c1a5aSDimitry Andric DEBUG(dbgs() << " Not a candidate: " << getBlockName(Succ) << " -> " << SuccProb 13983ca95b02SDimitry Andric << " (prob) (non-cold CFG conflict)\n"); 13993ca95b02SDimitry Andric return true; 14003ca95b02SDimitry Andric } 14013ca95b02SDimitry Andric 14023ca95b02SDimitry Andric return false; 14033ca95b02SDimitry Andric } 14043ca95b02SDimitry Andric 1405dff0c46cSDimitry Andric /// \brief Select the best successor for a block. 1406dff0c46cSDimitry Andric /// 1407dff0c46cSDimitry Andric /// This looks across all successors of a particular block and attempts to 1408dff0c46cSDimitry Andric /// select the "best" one to be the layout successor. It only considers direct 1409dff0c46cSDimitry Andric /// successors which also pass the block filter. It will attempt to avoid 1410dff0c46cSDimitry Andric /// breaking CFG structure, but cave and break such structures in the case of 1411dff0c46cSDimitry Andric /// very hot successor edges. 1412dff0c46cSDimitry Andric /// 14137a7e6055SDimitry Andric /// \returns The best successor block found, or null if none are viable, along 14147a7e6055SDimitry Andric /// with a boolean indicating if tail duplication is necessary. 14157a7e6055SDimitry Andric MachineBlockPlacement::BlockAndTailDupResult 14167a7e6055SDimitry Andric MachineBlockPlacement::selectBestSuccessor( 14177a7e6055SDimitry Andric const MachineBasicBlock *BB, const BlockChain &Chain, 1418dff0c46cSDimitry Andric const BlockFilterSet *BlockFilter) { 14193ca95b02SDimitry Andric const BranchProbability HotProb(StaticLikelyProb, 100); 1420dff0c46cSDimitry Andric 14217a7e6055SDimitry Andric BlockAndTailDupResult BestSucc = { nullptr, false }; 14227d523365SDimitry Andric auto BestProb = BranchProbability::getZero(); 14237d523365SDimitry Andric 14247d523365SDimitry Andric SmallVector<MachineBasicBlock *, 4> Successors; 14253ca95b02SDimitry Andric auto AdjustedSumProb = 14263ca95b02SDimitry Andric collectViableSuccessors(BB, Chain, BlockFilter, Successors); 1427dff0c46cSDimitry Andric 1428d88c1a5aSDimitry Andric DEBUG(dbgs() << "Selecting best successor for: " << getBlockName(BB) << "\n"); 14297a7e6055SDimitry Andric 14307a7e6055SDimitry Andric // if we already precomputed the best successor for BB, return that if still 14317a7e6055SDimitry Andric // applicable. 14327a7e6055SDimitry Andric auto FoundEdge = ComputedEdges.find(BB); 14337a7e6055SDimitry Andric if (FoundEdge != ComputedEdges.end()) { 14347a7e6055SDimitry Andric MachineBasicBlock *Succ = FoundEdge->second.BB; 14357a7e6055SDimitry Andric ComputedEdges.erase(FoundEdge); 14367a7e6055SDimitry Andric BlockChain *SuccChain = BlockToChain[Succ]; 14377a7e6055SDimitry Andric if (BB->isSuccessor(Succ) && (!BlockFilter || BlockFilter->count(Succ)) && 14387a7e6055SDimitry Andric SuccChain != &Chain && Succ == *SuccChain->begin()) 14397a7e6055SDimitry Andric return FoundEdge->second; 14407a7e6055SDimitry Andric } 14417a7e6055SDimitry Andric 14427a7e6055SDimitry Andric // if BB is part of a trellis, Use the trellis to determine the optimal 14437a7e6055SDimitry Andric // fallthrough edges 14447a7e6055SDimitry Andric if (isTrellis(BB, Successors, Chain, BlockFilter)) 14457a7e6055SDimitry Andric return getBestTrellisSuccessor(BB, Successors, AdjustedSumProb, Chain, 14467a7e6055SDimitry Andric BlockFilter); 14477a7e6055SDimitry Andric 14487a7e6055SDimitry Andric // For blocks with CFG violations, we may be able to lay them out anyway with 14497a7e6055SDimitry Andric // tail-duplication. We keep this vector so we can perform the probability 14507a7e6055SDimitry Andric // calculations the minimum number of times. 14517a7e6055SDimitry Andric SmallVector<std::tuple<BranchProbability, MachineBasicBlock *>, 4> 14527a7e6055SDimitry Andric DupCandidates; 14537d523365SDimitry Andric for (MachineBasicBlock *Succ : Successors) { 14547d523365SDimitry Andric auto RealSuccProb = MBPI->getEdgeProbability(BB, Succ); 14553ca95b02SDimitry Andric BranchProbability SuccProb = 14563ca95b02SDimitry Andric getAdjustedProbability(RealSuccProb, AdjustedSumProb); 1457dff0c46cSDimitry Andric 14583ca95b02SDimitry Andric BlockChain &SuccChain = *BlockToChain[Succ]; 14593ca95b02SDimitry Andric // Skip the edge \c BB->Succ if block \c Succ has a better layout 14603ca95b02SDimitry Andric // predecessor that yields lower global cost. 14613ca95b02SDimitry Andric if (hasBetterLayoutPredecessor(BB, Succ, SuccChain, SuccProb, RealSuccProb, 14627a7e6055SDimitry Andric Chain, BlockFilter)) { 14637a7e6055SDimitry Andric // If tail duplication would make Succ profitable, place it. 14647a7e6055SDimitry Andric if (TailDupPlacement && shouldTailDuplicate(Succ)) 14657a7e6055SDimitry Andric DupCandidates.push_back(std::make_tuple(SuccProb, Succ)); 14663ca95b02SDimitry Andric continue; 14677a7e6055SDimitry Andric } 14683ca95b02SDimitry Andric 14693ca95b02SDimitry Andric DEBUG( 1470d88c1a5aSDimitry Andric dbgs() << " Candidate: " << getBlockName(Succ) << ", probability: " 1471d88c1a5aSDimitry Andric << SuccProb 14723ca95b02SDimitry Andric << (SuccChain.UnscheduledPredecessors != 0 ? " (CFG break)" : "") 1473dff0c46cSDimitry Andric << "\n"); 1474d88c1a5aSDimitry Andric 14757a7e6055SDimitry Andric if (BestSucc.BB && BestProb >= SuccProb) { 1476d88c1a5aSDimitry Andric DEBUG(dbgs() << " Not the best candidate, continuing\n"); 1477dff0c46cSDimitry Andric continue; 1478d88c1a5aSDimitry Andric } 1479d88c1a5aSDimitry Andric 1480d88c1a5aSDimitry Andric DEBUG(dbgs() << " Setting it as best candidate\n"); 14817a7e6055SDimitry Andric BestSucc.BB = Succ; 14827d523365SDimitry Andric BestProb = SuccProb; 1483dff0c46cSDimitry Andric } 14847a7e6055SDimitry Andric // Handle the tail duplication candidates in order of decreasing probability. 14857a7e6055SDimitry Andric // Stop at the first one that is profitable. Also stop if they are less 14867a7e6055SDimitry Andric // profitable than BestSucc. Position is important because we preserve it and 14877a7e6055SDimitry Andric // prefer first best match. Here we aren't comparing in order, so we capture 14887a7e6055SDimitry Andric // the position instead. 14897a7e6055SDimitry Andric if (DupCandidates.size() != 0) { 14907a7e6055SDimitry Andric auto cmp = 14917a7e6055SDimitry Andric [](const std::tuple<BranchProbability, MachineBasicBlock *> &a, 14927a7e6055SDimitry Andric const std::tuple<BranchProbability, MachineBasicBlock *> &b) { 14937a7e6055SDimitry Andric return std::get<0>(a) > std::get<0>(b); 14947a7e6055SDimitry Andric }; 14957a7e6055SDimitry Andric std::stable_sort(DupCandidates.begin(), DupCandidates.end(), cmp); 14967a7e6055SDimitry Andric } 14977a7e6055SDimitry Andric for(auto &Tup : DupCandidates) { 14987a7e6055SDimitry Andric BranchProbability DupProb; 14997a7e6055SDimitry Andric MachineBasicBlock *Succ; 15007a7e6055SDimitry Andric std::tie(DupProb, Succ) = Tup; 15017a7e6055SDimitry Andric if (DupProb < BestProb) 15027a7e6055SDimitry Andric break; 15037a7e6055SDimitry Andric if (canTailDuplicateUnplacedPreds(BB, Succ, Chain, BlockFilter) 15047a7e6055SDimitry Andric && (isProfitableToTailDup(BB, Succ, BestProb, Chain, BlockFilter))) { 15057a7e6055SDimitry Andric DEBUG( 15067a7e6055SDimitry Andric dbgs() << " Candidate: " << getBlockName(Succ) << ", probability: " 15077a7e6055SDimitry Andric << DupProb 15087a7e6055SDimitry Andric << " (Tail Duplicate)\n"); 15097a7e6055SDimitry Andric BestSucc.BB = Succ; 15107a7e6055SDimitry Andric BestSucc.ShouldTailDup = true; 15117a7e6055SDimitry Andric break; 15127a7e6055SDimitry Andric } 15137a7e6055SDimitry Andric } 15147a7e6055SDimitry Andric 15157a7e6055SDimitry Andric if (BestSucc.BB) 15167a7e6055SDimitry Andric DEBUG(dbgs() << " Selected: " << getBlockName(BestSucc.BB) << "\n"); 1517d88c1a5aSDimitry Andric 1518dff0c46cSDimitry Andric return BestSucc; 1519dff0c46cSDimitry Andric } 1520dff0c46cSDimitry Andric 1521dff0c46cSDimitry Andric /// \brief Select the best block from a worklist. 1522dff0c46cSDimitry Andric /// 1523dff0c46cSDimitry Andric /// This looks through the provided worklist as a list of candidate basic 1524dff0c46cSDimitry Andric /// blocks and select the most profitable one to place. The definition of 1525dff0c46cSDimitry Andric /// profitable only really makes sense in the context of a loop. This returns 1526dff0c46cSDimitry Andric /// the most frequently visited block in the worklist, which in the case of 1527dff0c46cSDimitry Andric /// a loop, is the one most desirable to be physically close to the rest of the 15283ca95b02SDimitry Andric /// loop body in order to improve i-cache behavior. 1529dff0c46cSDimitry Andric /// 1530dff0c46cSDimitry Andric /// \returns The best block found, or null if none are viable. 1531dff0c46cSDimitry Andric MachineBasicBlock *MachineBlockPlacement::selectBestCandidateBlock( 15327a7e6055SDimitry Andric const BlockChain &Chain, SmallVectorImpl<MachineBasicBlock *> &WorkList) { 1533dff0c46cSDimitry Andric // Once we need to walk the worklist looking for a candidate, cleanup the 1534dff0c46cSDimitry Andric // worklist of already placed entries. 1535dff0c46cSDimitry Andric // FIXME: If this shows up on profiles, it could be folded (at the cost of 1536dff0c46cSDimitry Andric // some code complexity) into the loop below. 1537d88c1a5aSDimitry Andric WorkList.erase(remove_if(WorkList, 153891bc56edSDimitry Andric [&](MachineBasicBlock *BB) { 153991bc56edSDimitry Andric return BlockToChain.lookup(BB) == &Chain; 154091bc56edSDimitry Andric }), 1541dff0c46cSDimitry Andric WorkList.end()); 1542dff0c46cSDimitry Andric 15433ca95b02SDimitry Andric if (WorkList.empty()) 15443ca95b02SDimitry Andric return nullptr; 15453ca95b02SDimitry Andric 15463ca95b02SDimitry Andric bool IsEHPad = WorkList[0]->isEHPad(); 15473ca95b02SDimitry Andric 154891bc56edSDimitry Andric MachineBasicBlock *BestBlock = nullptr; 1549dff0c46cSDimitry Andric BlockFrequency BestFreq; 1550ff0cc061SDimitry Andric for (MachineBasicBlock *MBB : WorkList) { 1551d8866befSDimitry Andric assert(MBB->isEHPad() == IsEHPad && 1552d8866befSDimitry Andric "EHPad mismatch between block and work list."); 15533ca95b02SDimitry Andric 1554ff0cc061SDimitry Andric BlockChain &SuccChain = *BlockToChain[MBB]; 15553ca95b02SDimitry Andric if (&SuccChain == &Chain) 1556dff0c46cSDimitry Andric continue; 15573ca95b02SDimitry Andric 1558d8866befSDimitry Andric assert(SuccChain.UnscheduledPredecessors == 0 && 1559d8866befSDimitry Andric "Found CFG-violating block"); 1560dff0c46cSDimitry Andric 1561ff0cc061SDimitry Andric BlockFrequency CandidateFreq = MBFI->getBlockFreq(MBB); 1562ff0cc061SDimitry Andric DEBUG(dbgs() << " " << getBlockName(MBB) << " -> "; 156391bc56edSDimitry Andric MBFI->printBlockFreq(dbgs(), CandidateFreq) << " (freq)\n"); 15643ca95b02SDimitry Andric 15653ca95b02SDimitry Andric // For ehpad, we layout the least probable first as to avoid jumping back 15663ca95b02SDimitry Andric // from least probable landingpads to more probable ones. 15673ca95b02SDimitry Andric // 15683ca95b02SDimitry Andric // FIXME: Using probability is probably (!) not the best way to achieve 15693ca95b02SDimitry Andric // this. We should probably have a more principled approach to layout 15703ca95b02SDimitry Andric // cleanup code. 15713ca95b02SDimitry Andric // 15723ca95b02SDimitry Andric // The goal is to get: 15733ca95b02SDimitry Andric // 15743ca95b02SDimitry Andric // +--------------------------+ 15753ca95b02SDimitry Andric // | V 15763ca95b02SDimitry Andric // InnerLp -> InnerCleanup OuterLp -> OuterCleanup -> Resume 15773ca95b02SDimitry Andric // 15783ca95b02SDimitry Andric // Rather than: 15793ca95b02SDimitry Andric // 15803ca95b02SDimitry Andric // +-------------------------------------+ 15813ca95b02SDimitry Andric // V | 15823ca95b02SDimitry Andric // OuterLp -> OuterCleanup -> Resume InnerLp -> InnerCleanup 15833ca95b02SDimitry Andric if (BestBlock && (IsEHPad ^ (BestFreq >= CandidateFreq))) 1584dff0c46cSDimitry Andric continue; 15853ca95b02SDimitry Andric 1586ff0cc061SDimitry Andric BestBlock = MBB; 1587dff0c46cSDimitry Andric BestFreq = CandidateFreq; 1588dff0c46cSDimitry Andric } 15893ca95b02SDimitry Andric 1590dff0c46cSDimitry Andric return BestBlock; 1591dff0c46cSDimitry Andric } 1592dff0c46cSDimitry Andric 1593dff0c46cSDimitry Andric /// \brief Retrieve the first unplaced basic block. 1594dff0c46cSDimitry Andric /// 1595dff0c46cSDimitry Andric /// This routine is called when we are unable to use the CFG to walk through 1596dff0c46cSDimitry Andric /// all of the basic blocks and form a chain due to unnatural loops in the CFG. 1597dff0c46cSDimitry Andric /// We walk through the function's blocks in order, starting from the 1598dff0c46cSDimitry Andric /// LastUnplacedBlockIt. We update this iterator on each call to avoid 1599dff0c46cSDimitry Andric /// re-scanning the entire sequence on repeated calls to this routine. 1600dff0c46cSDimitry Andric MachineBasicBlock *MachineBlockPlacement::getFirstUnplacedBlock( 16013ca95b02SDimitry Andric const BlockChain &PlacedChain, 1602dff0c46cSDimitry Andric MachineFunction::iterator &PrevUnplacedBlockIt, 1603dff0c46cSDimitry Andric const BlockFilterSet *BlockFilter) { 16043ca95b02SDimitry Andric for (MachineFunction::iterator I = PrevUnplacedBlockIt, E = F->end(); I != E; 1605dff0c46cSDimitry Andric ++I) { 16067d523365SDimitry Andric if (BlockFilter && !BlockFilter->count(&*I)) 1607dff0c46cSDimitry Andric continue; 16087d523365SDimitry Andric if (BlockToChain[&*I] != &PlacedChain) { 1609dff0c46cSDimitry Andric PrevUnplacedBlockIt = I; 1610dff0c46cSDimitry Andric // Now select the head of the chain to which the unplaced block belongs 1611dff0c46cSDimitry Andric // as the block to place. This will force the entire chain to be placed, 1612dff0c46cSDimitry Andric // and satisfies the requirements of merging chains. 16137d523365SDimitry Andric return *BlockToChain[&*I]->begin(); 1614dff0c46cSDimitry Andric } 1615dff0c46cSDimitry Andric } 161691bc56edSDimitry Andric return nullptr; 1617dff0c46cSDimitry Andric } 1618dff0c46cSDimitry Andric 16193ca95b02SDimitry Andric void MachineBlockPlacement::fillWorkLists( 16207a7e6055SDimitry Andric const MachineBasicBlock *MBB, 16213ca95b02SDimitry Andric SmallPtrSetImpl<BlockChain *> &UpdatedPreds, 16223ca95b02SDimitry Andric const BlockFilterSet *BlockFilter = nullptr) { 16233ca95b02SDimitry Andric BlockChain &Chain = *BlockToChain[MBB]; 16243ca95b02SDimitry Andric if (!UpdatedPreds.insert(&Chain).second) 16253ca95b02SDimitry Andric return; 16263ca95b02SDimitry Andric 1627d8866befSDimitry Andric assert( 1628d8866befSDimitry Andric Chain.UnscheduledPredecessors == 0 && 1629d8866befSDimitry Andric "Attempting to place block with unscheduled predecessors in worklist."); 16303ca95b02SDimitry Andric for (MachineBasicBlock *ChainBB : Chain) { 1631d8866befSDimitry Andric assert(BlockToChain[ChainBB] == &Chain && 1632d8866befSDimitry Andric "Block in chain doesn't match BlockToChain map."); 16333ca95b02SDimitry Andric for (MachineBasicBlock *Pred : ChainBB->predecessors()) { 16343ca95b02SDimitry Andric if (BlockFilter && !BlockFilter->count(Pred)) 16353ca95b02SDimitry Andric continue; 16363ca95b02SDimitry Andric if (BlockToChain[Pred] == &Chain) 16373ca95b02SDimitry Andric continue; 16383ca95b02SDimitry Andric ++Chain.UnscheduledPredecessors; 16393ca95b02SDimitry Andric } 16403ca95b02SDimitry Andric } 16413ca95b02SDimitry Andric 16423ca95b02SDimitry Andric if (Chain.UnscheduledPredecessors != 0) 16433ca95b02SDimitry Andric return; 16443ca95b02SDimitry Andric 16457a7e6055SDimitry Andric MachineBasicBlock *BB = *Chain.begin(); 16467a7e6055SDimitry Andric if (BB->isEHPad()) 16477a7e6055SDimitry Andric EHPadWorkList.push_back(BB); 16483ca95b02SDimitry Andric else 16497a7e6055SDimitry Andric BlockWorkList.push_back(BB); 16503ca95b02SDimitry Andric } 16513ca95b02SDimitry Andric 1652dff0c46cSDimitry Andric void MachineBlockPlacement::buildChain( 16537a7e6055SDimitry Andric const MachineBasicBlock *HeadBB, BlockChain &Chain, 1654d88c1a5aSDimitry Andric BlockFilterSet *BlockFilter) { 16557a7e6055SDimitry Andric assert(HeadBB && "BB must not be null.\n"); 16567a7e6055SDimitry Andric assert(BlockToChain[HeadBB] == &Chain && "BlockToChainMap mis-match.\n"); 16573ca95b02SDimitry Andric MachineFunction::iterator PrevUnplacedBlockIt = F->begin(); 1658dff0c46cSDimitry Andric 16597a7e6055SDimitry Andric const MachineBasicBlock *LoopHeaderBB = HeadBB; 16603ca95b02SDimitry Andric markChainSuccessors(Chain, LoopHeaderBB, BlockFilter); 16617a7e6055SDimitry Andric MachineBasicBlock *BB = *std::prev(Chain.end()); 1662dff0c46cSDimitry Andric for (;;) { 16633ca95b02SDimitry Andric assert(BB && "null block found at end of chain in loop."); 16643ca95b02SDimitry Andric assert(BlockToChain[BB] == &Chain && "BlockToChainMap mis-match in loop."); 16653ca95b02SDimitry Andric assert(*std::prev(Chain.end()) == BB && "BB Not found at end of chain."); 16663ca95b02SDimitry Andric 1667dff0c46cSDimitry Andric 1668dff0c46cSDimitry Andric // Look for the best viable successor if there is one to place immediately 1669dff0c46cSDimitry Andric // after this block. 16707a7e6055SDimitry Andric auto Result = selectBestSuccessor(BB, Chain, BlockFilter); 16717a7e6055SDimitry Andric MachineBasicBlock* BestSucc = Result.BB; 16727a7e6055SDimitry Andric bool ShouldTailDup = Result.ShouldTailDup; 16737a7e6055SDimitry Andric if (TailDupPlacement) 16747a7e6055SDimitry Andric ShouldTailDup |= (BestSucc && shouldTailDuplicate(BestSucc)); 1675dff0c46cSDimitry Andric 1676dff0c46cSDimitry Andric // If an immediate successor isn't available, look for the best viable 1677dff0c46cSDimitry Andric // block among those we've identified as not violating the loop's CFG at 1678dff0c46cSDimitry Andric // this point. This won't be a fallthrough, but it will increase locality. 1679dff0c46cSDimitry Andric if (!BestSucc) 16803ca95b02SDimitry Andric BestSucc = selectBestCandidateBlock(Chain, BlockWorkList); 16813ca95b02SDimitry Andric if (!BestSucc) 16823ca95b02SDimitry Andric BestSucc = selectBestCandidateBlock(Chain, EHPadWorkList); 1683dff0c46cSDimitry Andric 1684dff0c46cSDimitry Andric if (!BestSucc) { 16853ca95b02SDimitry Andric BestSucc = getFirstUnplacedBlock(Chain, PrevUnplacedBlockIt, BlockFilter); 1686dff0c46cSDimitry Andric if (!BestSucc) 1687dff0c46cSDimitry Andric break; 1688dff0c46cSDimitry Andric 1689dff0c46cSDimitry Andric DEBUG(dbgs() << "Unnatural loop CFG detected, forcibly merging the " 1690dff0c46cSDimitry Andric "layout successor until the CFG reduces\n"); 1691dff0c46cSDimitry Andric } 1692dff0c46cSDimitry Andric 1693d88c1a5aSDimitry Andric // Placement may have changed tail duplication opportunities. 1694d88c1a5aSDimitry Andric // Check for that now. 16957a7e6055SDimitry Andric if (TailDupPlacement && BestSucc && ShouldTailDup) { 1696d88c1a5aSDimitry Andric // If the chosen successor was duplicated into all its predecessors, 1697d88c1a5aSDimitry Andric // don't bother laying it out, just go round the loop again with BB as 1698d88c1a5aSDimitry Andric // the chain end. 1699d88c1a5aSDimitry Andric if (repeatedlyTailDuplicateBlock(BestSucc, BB, LoopHeaderBB, Chain, 1700d88c1a5aSDimitry Andric BlockFilter, PrevUnplacedBlockIt)) 1701d88c1a5aSDimitry Andric continue; 1702d88c1a5aSDimitry Andric } 1703d88c1a5aSDimitry Andric 1704dff0c46cSDimitry Andric // Place this block, updating the datastructures to reflect its placement. 1705dff0c46cSDimitry Andric BlockChain &SuccChain = *BlockToChain[BestSucc]; 17063ca95b02SDimitry Andric // Zero out UnscheduledPredecessors for the successor we're about to merge in case 1707dff0c46cSDimitry Andric // we selected a successor that didn't fit naturally into the CFG. 17083ca95b02SDimitry Andric SuccChain.UnscheduledPredecessors = 0; 17093ca95b02SDimitry Andric DEBUG(dbgs() << "Merging from " << getBlockName(BB) << " to " 17103ca95b02SDimitry Andric << getBlockName(BestSucc) << "\n"); 17113ca95b02SDimitry Andric markChainSuccessors(SuccChain, LoopHeaderBB, BlockFilter); 1712dff0c46cSDimitry Andric Chain.merge(BestSucc, &SuccChain); 171391bc56edSDimitry Andric BB = *std::prev(Chain.end()); 1714dff0c46cSDimitry Andric } 1715dff0c46cSDimitry Andric 1716dff0c46cSDimitry Andric DEBUG(dbgs() << "Finished forming chain for header block " 17173ca95b02SDimitry Andric << getBlockName(*Chain.begin()) << "\n"); 1718dff0c46cSDimitry Andric } 1719dff0c46cSDimitry Andric 1720dff0c46cSDimitry Andric /// \brief Find the best loop top block for layout. 1721dff0c46cSDimitry Andric /// 1722cb4dff85SDimitry Andric /// Look for a block which is strictly better than the loop header for laying 1723cb4dff85SDimitry Andric /// out at the top of the loop. This looks for one and only one pattern: 1724cb4dff85SDimitry Andric /// a latch block with no conditional exit. This block will cause a conditional 1725cb4dff85SDimitry Andric /// jump around it or will be the bottom of the loop if we lay it out in place, 1726cb4dff85SDimitry Andric /// but if it it doesn't end up at the bottom of the loop for any reason, 1727cb4dff85SDimitry Andric /// rotation alone won't fix it. Because such a block will always result in an 1728cb4dff85SDimitry Andric /// unconditional jump (for the backedge) rotating it in front of the loop 1729cb4dff85SDimitry Andric /// header is always profitable. 1730cb4dff85SDimitry Andric MachineBasicBlock * 17317a7e6055SDimitry Andric MachineBlockPlacement::findBestLoopTop(const MachineLoop &L, 1732cb4dff85SDimitry Andric const BlockFilterSet &LoopBlockSet) { 1733d88c1a5aSDimitry Andric // Placing the latch block before the header may introduce an extra branch 1734d88c1a5aSDimitry Andric // that skips this block the first time the loop is executed, which we want 1735d88c1a5aSDimitry Andric // to avoid when optimising for size. 1736d88c1a5aSDimitry Andric // FIXME: in theory there is a case that does not introduce a new branch, 1737d88c1a5aSDimitry Andric // i.e. when the layout predecessor does not fallthrough to the loop header. 1738d88c1a5aSDimitry Andric // In practice this never happens though: there always seems to be a preheader 1739d88c1a5aSDimitry Andric // that can fallthrough and that is also placed before the header. 1740d88c1a5aSDimitry Andric if (F->getFunction()->optForSize()) 1741d88c1a5aSDimitry Andric return L.getHeader(); 1742d88c1a5aSDimitry Andric 1743cb4dff85SDimitry Andric // Check that the header hasn't been fused with a preheader block due to 1744cb4dff85SDimitry Andric // crazy branches. If it has, we need to start with the header at the top to 1745cb4dff85SDimitry Andric // prevent pulling the preheader into the loop body. 1746cb4dff85SDimitry Andric BlockChain &HeaderChain = *BlockToChain[L.getHeader()]; 1747cb4dff85SDimitry Andric if (!LoopBlockSet.count(*HeaderChain.begin())) 1748cb4dff85SDimitry Andric return L.getHeader(); 1749cb4dff85SDimitry Andric 1750ff0cc061SDimitry Andric DEBUG(dbgs() << "Finding best loop top for: " << getBlockName(L.getHeader()) 1751ff0cc061SDimitry Andric << "\n"); 1752cb4dff85SDimitry Andric 1753cb4dff85SDimitry Andric BlockFrequency BestPredFreq; 175491bc56edSDimitry Andric MachineBasicBlock *BestPred = nullptr; 1755ff0cc061SDimitry Andric for (MachineBasicBlock *Pred : L.getHeader()->predecessors()) { 1756cb4dff85SDimitry Andric if (!LoopBlockSet.count(Pred)) 1757cb4dff85SDimitry Andric continue; 1758d88c1a5aSDimitry Andric DEBUG(dbgs() << " header pred: " << getBlockName(Pred) << ", has " 175991bc56edSDimitry Andric << Pred->succ_size() << " successors, "; 176091bc56edSDimitry Andric MBFI->printBlockFreq(dbgs(), Pred) << " freq\n"); 1761cb4dff85SDimitry Andric if (Pred->succ_size() > 1) 1762cb4dff85SDimitry Andric continue; 1763cb4dff85SDimitry Andric 1764cb4dff85SDimitry Andric BlockFrequency PredFreq = MBFI->getBlockFreq(Pred); 1765cb4dff85SDimitry Andric if (!BestPred || PredFreq > BestPredFreq || 1766cb4dff85SDimitry Andric (!(PredFreq < BestPredFreq) && 1767cb4dff85SDimitry Andric Pred->isLayoutSuccessor(L.getHeader()))) { 1768cb4dff85SDimitry Andric BestPred = Pred; 1769cb4dff85SDimitry Andric BestPredFreq = PredFreq; 1770cb4dff85SDimitry Andric } 1771cb4dff85SDimitry Andric } 1772cb4dff85SDimitry Andric 1773cb4dff85SDimitry Andric // If no direct predecessor is fine, just use the loop header. 17743ca95b02SDimitry Andric if (!BestPred) { 17753ca95b02SDimitry Andric DEBUG(dbgs() << " final top unchanged\n"); 1776cb4dff85SDimitry Andric return L.getHeader(); 17773ca95b02SDimitry Andric } 1778cb4dff85SDimitry Andric 1779cb4dff85SDimitry Andric // Walk backwards through any straight line of predecessors. 1780cb4dff85SDimitry Andric while (BestPred->pred_size() == 1 && 1781cb4dff85SDimitry Andric (*BestPred->pred_begin())->succ_size() == 1 && 1782cb4dff85SDimitry Andric *BestPred->pred_begin() != L.getHeader()) 1783cb4dff85SDimitry Andric BestPred = *BestPred->pred_begin(); 1784cb4dff85SDimitry Andric 1785cb4dff85SDimitry Andric DEBUG(dbgs() << " final top: " << getBlockName(BestPred) << "\n"); 1786cb4dff85SDimitry Andric return BestPred; 1787cb4dff85SDimitry Andric } 1788cb4dff85SDimitry Andric 1789cb4dff85SDimitry Andric /// \brief Find the best loop exiting block for layout. 1790cb4dff85SDimitry Andric /// 1791dff0c46cSDimitry Andric /// This routine implements the logic to analyze the loop looking for the best 1792dff0c46cSDimitry Andric /// block to layout at the top of the loop. Typically this is done to maximize 1793dff0c46cSDimitry Andric /// fallthrough opportunities. 1794dff0c46cSDimitry Andric MachineBasicBlock * 17957a7e6055SDimitry Andric MachineBlockPlacement::findBestLoopExit(const MachineLoop &L, 1796dff0c46cSDimitry Andric const BlockFilterSet &LoopBlockSet) { 1797dff0c46cSDimitry Andric // We don't want to layout the loop linearly in all cases. If the loop header 1798dff0c46cSDimitry Andric // is just a normal basic block in the loop, we want to look for what block 1799dff0c46cSDimitry Andric // within the loop is the best one to layout at the top. However, if the loop 1800dff0c46cSDimitry Andric // header has be pre-merged into a chain due to predecessors not having 1801dff0c46cSDimitry Andric // analyzable branches, *and* the predecessor it is merged with is *not* part 1802dff0c46cSDimitry Andric // of the loop, rotating the header into the middle of the loop will create 1803dff0c46cSDimitry Andric // a non-contiguous range of blocks which is Very Bad. So start with the 1804dff0c46cSDimitry Andric // header and only rotate if safe. 1805dff0c46cSDimitry Andric BlockChain &HeaderChain = *BlockToChain[L.getHeader()]; 1806dff0c46cSDimitry Andric if (!LoopBlockSet.count(*HeaderChain.begin())) 180791bc56edSDimitry Andric return nullptr; 1808dff0c46cSDimitry Andric 1809dff0c46cSDimitry Andric BlockFrequency BestExitEdgeFreq; 1810cb4dff85SDimitry Andric unsigned BestExitLoopDepth = 0; 181191bc56edSDimitry Andric MachineBasicBlock *ExitingBB = nullptr; 1812dff0c46cSDimitry Andric // If there are exits to outer loops, loop rotation can severely limit 18133ca95b02SDimitry Andric // fallthrough opportunities unless it selects such an exit. Keep a set of 1814dff0c46cSDimitry Andric // blocks where rotating to exit with that block will reach an outer loop. 1815dff0c46cSDimitry Andric SmallPtrSet<MachineBasicBlock *, 4> BlocksExitingToOuterLoop; 1816dff0c46cSDimitry Andric 1817ff0cc061SDimitry Andric DEBUG(dbgs() << "Finding best loop exit for: " << getBlockName(L.getHeader()) 1818ff0cc061SDimitry Andric << "\n"); 1819ff0cc061SDimitry Andric for (MachineBasicBlock *MBB : L.getBlocks()) { 1820ff0cc061SDimitry Andric BlockChain &Chain = *BlockToChain[MBB]; 1821dff0c46cSDimitry Andric // Ensure that this block is at the end of a chain; otherwise it could be 1822ff0cc061SDimitry Andric // mid-way through an inner loop or a successor of an unanalyzable branch. 1823ff0cc061SDimitry Andric if (MBB != *std::prev(Chain.end())) 1824dff0c46cSDimitry Andric continue; 1825dff0c46cSDimitry Andric 1826dff0c46cSDimitry Andric // Now walk the successors. We need to establish whether this has a viable 1827dff0c46cSDimitry Andric // exiting successor and whether it has a viable non-exiting successor. 1828dff0c46cSDimitry Andric // We store the old exiting state and restore it if a viable looping 1829dff0c46cSDimitry Andric // successor isn't found. 1830dff0c46cSDimitry Andric MachineBasicBlock *OldExitingBB = ExitingBB; 1831dff0c46cSDimitry Andric BlockFrequency OldBestExitEdgeFreq = BestExitEdgeFreq; 1832cb4dff85SDimitry Andric bool HasLoopingSucc = false; 1833ff0cc061SDimitry Andric for (MachineBasicBlock *Succ : MBB->successors()) { 18347d523365SDimitry Andric if (Succ->isEHPad()) 1835dff0c46cSDimitry Andric continue; 1836ff0cc061SDimitry Andric if (Succ == MBB) 1837dff0c46cSDimitry Andric continue; 1838ff0cc061SDimitry Andric BlockChain &SuccChain = *BlockToChain[Succ]; 1839dff0c46cSDimitry Andric // Don't split chains, either this chain or the successor's chain. 1840cb4dff85SDimitry Andric if (&Chain == &SuccChain) { 1841ff0cc061SDimitry Andric DEBUG(dbgs() << " exiting: " << getBlockName(MBB) << " -> " 1842ff0cc061SDimitry Andric << getBlockName(Succ) << " (chain conflict)\n"); 1843dff0c46cSDimitry Andric continue; 1844dff0c46cSDimitry Andric } 1845dff0c46cSDimitry Andric 18467d523365SDimitry Andric auto SuccProb = MBPI->getEdgeProbability(MBB, Succ); 1847ff0cc061SDimitry Andric if (LoopBlockSet.count(Succ)) { 1848ff0cc061SDimitry Andric DEBUG(dbgs() << " looping: " << getBlockName(MBB) << " -> " 18497d523365SDimitry Andric << getBlockName(Succ) << " (" << SuccProb << ")\n"); 1850cb4dff85SDimitry Andric HasLoopingSucc = true; 1851dff0c46cSDimitry Andric continue; 1852cb4dff85SDimitry Andric } 1853dff0c46cSDimitry Andric 1854cb4dff85SDimitry Andric unsigned SuccLoopDepth = 0; 1855ff0cc061SDimitry Andric if (MachineLoop *ExitLoop = MLI->getLoopFor(Succ)) { 1856cb4dff85SDimitry Andric SuccLoopDepth = ExitLoop->getLoopDepth(); 1857cb4dff85SDimitry Andric if (ExitLoop->contains(&L)) 1858ff0cc061SDimitry Andric BlocksExitingToOuterLoop.insert(MBB); 1859dff0c46cSDimitry Andric } 1860dff0c46cSDimitry Andric 1861ff0cc061SDimitry Andric BlockFrequency ExitEdgeFreq = MBFI->getBlockFreq(MBB) * SuccProb; 1862ff0cc061SDimitry Andric DEBUG(dbgs() << " exiting: " << getBlockName(MBB) << " -> " 1863ff0cc061SDimitry Andric << getBlockName(Succ) << " [L:" << SuccLoopDepth << "] ("; 186491bc56edSDimitry Andric MBFI->printBlockFreq(dbgs(), ExitEdgeFreq) << ")\n"); 186591bc56edSDimitry Andric // Note that we bias this toward an existing layout successor to retain 186691bc56edSDimitry Andric // incoming order in the absence of better information. The exit must have 186791bc56edSDimitry Andric // a frequency higher than the current exit before we consider breaking 186891bc56edSDimitry Andric // the layout. 186991bc56edSDimitry Andric BranchProbability Bias(100 - ExitBlockBias, 100); 1870ff0cc061SDimitry Andric if (!ExitingBB || SuccLoopDepth > BestExitLoopDepth || 1871cb4dff85SDimitry Andric ExitEdgeFreq > BestExitEdgeFreq || 1872ff0cc061SDimitry Andric (MBB->isLayoutSuccessor(Succ) && 187391bc56edSDimitry Andric !(ExitEdgeFreq < BestExitEdgeFreq * Bias))) { 1874dff0c46cSDimitry Andric BestExitEdgeFreq = ExitEdgeFreq; 1875ff0cc061SDimitry Andric ExitingBB = MBB; 1876dff0c46cSDimitry Andric } 1877dff0c46cSDimitry Andric } 1878dff0c46cSDimitry Andric 1879cb4dff85SDimitry Andric if (!HasLoopingSucc) { 1880ff0cc061SDimitry Andric // Restore the old exiting state, no viable looping successor was found. 1881dff0c46cSDimitry Andric ExitingBB = OldExitingBB; 1882dff0c46cSDimitry Andric BestExitEdgeFreq = OldBestExitEdgeFreq; 1883dff0c46cSDimitry Andric } 1884dff0c46cSDimitry Andric } 1885cb4dff85SDimitry Andric // Without a candidate exiting block or with only a single block in the 1886dff0c46cSDimitry Andric // loop, just use the loop header to layout the loop. 1887d88c1a5aSDimitry Andric if (!ExitingBB) { 1888d88c1a5aSDimitry Andric DEBUG(dbgs() << " No other candidate exit blocks, using loop header\n"); 188991bc56edSDimitry Andric return nullptr; 1890d88c1a5aSDimitry Andric } 1891d88c1a5aSDimitry Andric if (L.getNumBlocks() == 1) { 1892d88c1a5aSDimitry Andric DEBUG(dbgs() << " Loop has 1 block, using loop header as exit\n"); 1893d88c1a5aSDimitry Andric return nullptr; 1894d88c1a5aSDimitry Andric } 1895dff0c46cSDimitry Andric 1896dff0c46cSDimitry Andric // Also, if we have exit blocks which lead to outer loops but didn't select 1897dff0c46cSDimitry Andric // one of them as the exiting block we are rotating toward, disable loop 1898dff0c46cSDimitry Andric // rotation altogether. 1899dff0c46cSDimitry Andric if (!BlocksExitingToOuterLoop.empty() && 1900dff0c46cSDimitry Andric !BlocksExitingToOuterLoop.count(ExitingBB)) 190191bc56edSDimitry Andric return nullptr; 1902dff0c46cSDimitry Andric 1903dff0c46cSDimitry Andric DEBUG(dbgs() << " Best exiting block: " << getBlockName(ExitingBB) << "\n"); 1904cb4dff85SDimitry Andric return ExitingBB; 1905cb4dff85SDimitry Andric } 1906cb4dff85SDimitry Andric 1907cb4dff85SDimitry Andric /// \brief Attempt to rotate an exiting block to the bottom of the loop. 1908cb4dff85SDimitry Andric /// 1909cb4dff85SDimitry Andric /// Once we have built a chain, try to rotate it to line up the hot exit block 1910cb4dff85SDimitry Andric /// with fallthrough out of the loop if doing so doesn't introduce unnecessary 1911cb4dff85SDimitry Andric /// branches. For example, if the loop has fallthrough into its header and out 1912cb4dff85SDimitry Andric /// of its bottom already, don't rotate it. 1913cb4dff85SDimitry Andric void MachineBlockPlacement::rotateLoop(BlockChain &LoopChain, 19147a7e6055SDimitry Andric const MachineBasicBlock *ExitingBB, 1915cb4dff85SDimitry Andric const BlockFilterSet &LoopBlockSet) { 1916cb4dff85SDimitry Andric if (!ExitingBB) 1917cb4dff85SDimitry Andric return; 1918cb4dff85SDimitry Andric 1919cb4dff85SDimitry Andric MachineBasicBlock *Top = *LoopChain.begin(); 1920cb4dff85SDimitry Andric bool ViableTopFallthrough = false; 1921ff0cc061SDimitry Andric for (MachineBasicBlock *Pred : Top->predecessors()) { 1922ff0cc061SDimitry Andric BlockChain *PredChain = BlockToChain[Pred]; 1923ff0cc061SDimitry Andric if (!LoopBlockSet.count(Pred) && 1924ff0cc061SDimitry Andric (!PredChain || Pred == *std::prev(PredChain->end()))) { 1925cb4dff85SDimitry Andric ViableTopFallthrough = true; 1926cb4dff85SDimitry Andric break; 1927cb4dff85SDimitry Andric } 1928cb4dff85SDimitry Andric } 1929cb4dff85SDimitry Andric 1930cb4dff85SDimitry Andric // If the header has viable fallthrough, check whether the current loop 1931cb4dff85SDimitry Andric // bottom is a viable exiting block. If so, bail out as rotating will 1932cb4dff85SDimitry Andric // introduce an unnecessary branch. 1933cb4dff85SDimitry Andric if (ViableTopFallthrough) { 193491bc56edSDimitry Andric MachineBasicBlock *Bottom = *std::prev(LoopChain.end()); 1935ff0cc061SDimitry Andric for (MachineBasicBlock *Succ : Bottom->successors()) { 1936ff0cc061SDimitry Andric BlockChain *SuccChain = BlockToChain[Succ]; 1937ff0cc061SDimitry Andric if (!LoopBlockSet.count(Succ) && 1938ff0cc061SDimitry Andric (!SuccChain || Succ == *SuccChain->begin())) 1939cb4dff85SDimitry Andric return; 1940cb4dff85SDimitry Andric } 1941cb4dff85SDimitry Andric } 1942cb4dff85SDimitry Andric 1943d88c1a5aSDimitry Andric BlockChain::iterator ExitIt = find(LoopChain, ExitingBB); 1944cb4dff85SDimitry Andric if (ExitIt == LoopChain.end()) 1945cb4dff85SDimitry Andric return; 1946cb4dff85SDimitry Andric 194791bc56edSDimitry Andric std::rotate(LoopChain.begin(), std::next(ExitIt), LoopChain.end()); 1948dff0c46cSDimitry Andric } 1949dff0c46cSDimitry Andric 19507d523365SDimitry Andric /// \brief Attempt to rotate a loop based on profile data to reduce branch cost. 19517d523365SDimitry Andric /// 19527d523365SDimitry Andric /// With profile data, we can determine the cost in terms of missed fall through 19537d523365SDimitry Andric /// opportunities when rotating a loop chain and select the best rotation. 19547d523365SDimitry Andric /// Basically, there are three kinds of cost to consider for each rotation: 19557d523365SDimitry Andric /// 1. The possibly missed fall through edge (if it exists) from BB out of 19567d523365SDimitry Andric /// the loop to the loop header. 19577d523365SDimitry Andric /// 2. The possibly missed fall through edges (if they exist) from the loop 19587d523365SDimitry Andric /// exits to BB out of the loop. 19597d523365SDimitry Andric /// 3. The missed fall through edge (if it exists) from the last BB to the 19607d523365SDimitry Andric /// first BB in the loop chain. 19617d523365SDimitry Andric /// Therefore, the cost for a given rotation is the sum of costs listed above. 19627d523365SDimitry Andric /// We select the best rotation with the smallest cost. 19637d523365SDimitry Andric void MachineBlockPlacement::rotateLoopWithProfile( 19647a7e6055SDimitry Andric BlockChain &LoopChain, const MachineLoop &L, 19657a7e6055SDimitry Andric const BlockFilterSet &LoopBlockSet) { 19667d523365SDimitry Andric auto HeaderBB = L.getHeader(); 1967d88c1a5aSDimitry Andric auto HeaderIter = find(LoopChain, HeaderBB); 19687d523365SDimitry Andric auto RotationPos = LoopChain.end(); 19697d523365SDimitry Andric 19707d523365SDimitry Andric BlockFrequency SmallestRotationCost = BlockFrequency::getMaxFrequency(); 19717d523365SDimitry Andric 19727d523365SDimitry Andric // A utility lambda that scales up a block frequency by dividing it by a 19737d523365SDimitry Andric // branch probability which is the reciprocal of the scale. 19747d523365SDimitry Andric auto ScaleBlockFrequency = [](BlockFrequency Freq, 19757d523365SDimitry Andric unsigned Scale) -> BlockFrequency { 19767d523365SDimitry Andric if (Scale == 0) 19777d523365SDimitry Andric return 0; 19787d523365SDimitry Andric // Use operator / between BlockFrequency and BranchProbability to implement 19797d523365SDimitry Andric // saturating multiplication. 19807d523365SDimitry Andric return Freq / BranchProbability(1, Scale); 19817d523365SDimitry Andric }; 19827d523365SDimitry Andric 19837d523365SDimitry Andric // Compute the cost of the missed fall-through edge to the loop header if the 19847d523365SDimitry Andric // chain head is not the loop header. As we only consider natural loops with 19857d523365SDimitry Andric // single header, this computation can be done only once. 19867d523365SDimitry Andric BlockFrequency HeaderFallThroughCost(0); 19877d523365SDimitry Andric for (auto *Pred : HeaderBB->predecessors()) { 19887d523365SDimitry Andric BlockChain *PredChain = BlockToChain[Pred]; 19897d523365SDimitry Andric if (!LoopBlockSet.count(Pred) && 19907d523365SDimitry Andric (!PredChain || Pred == *std::prev(PredChain->end()))) { 19917d523365SDimitry Andric auto EdgeFreq = 19927d523365SDimitry Andric MBFI->getBlockFreq(Pred) * MBPI->getEdgeProbability(Pred, HeaderBB); 19937d523365SDimitry Andric auto FallThruCost = ScaleBlockFrequency(EdgeFreq, MisfetchCost); 19947d523365SDimitry Andric // If the predecessor has only an unconditional jump to the header, we 19957d523365SDimitry Andric // need to consider the cost of this jump. 19967d523365SDimitry Andric if (Pred->succ_size() == 1) 19977d523365SDimitry Andric FallThruCost += ScaleBlockFrequency(EdgeFreq, JumpInstCost); 19987d523365SDimitry Andric HeaderFallThroughCost = std::max(HeaderFallThroughCost, FallThruCost); 19997d523365SDimitry Andric } 20007d523365SDimitry Andric } 20017d523365SDimitry Andric 20027d523365SDimitry Andric // Here we collect all exit blocks in the loop, and for each exit we find out 20037d523365SDimitry Andric // its hottest exit edge. For each loop rotation, we define the loop exit cost 20047d523365SDimitry Andric // as the sum of frequencies of exit edges we collect here, excluding the exit 20057d523365SDimitry Andric // edge from the tail of the loop chain. 20067d523365SDimitry Andric SmallVector<std::pair<MachineBasicBlock *, BlockFrequency>, 4> ExitsWithFreq; 20077d523365SDimitry Andric for (auto BB : LoopChain) { 20087d523365SDimitry Andric auto LargestExitEdgeProb = BranchProbability::getZero(); 20097d523365SDimitry Andric for (auto *Succ : BB->successors()) { 20107d523365SDimitry Andric BlockChain *SuccChain = BlockToChain[Succ]; 20117d523365SDimitry Andric if (!LoopBlockSet.count(Succ) && 20127d523365SDimitry Andric (!SuccChain || Succ == *SuccChain->begin())) { 20137d523365SDimitry Andric auto SuccProb = MBPI->getEdgeProbability(BB, Succ); 20147d523365SDimitry Andric LargestExitEdgeProb = std::max(LargestExitEdgeProb, SuccProb); 20157d523365SDimitry Andric } 20167d523365SDimitry Andric } 20177d523365SDimitry Andric if (LargestExitEdgeProb > BranchProbability::getZero()) { 20187d523365SDimitry Andric auto ExitFreq = MBFI->getBlockFreq(BB) * LargestExitEdgeProb; 20197d523365SDimitry Andric ExitsWithFreq.emplace_back(BB, ExitFreq); 20207d523365SDimitry Andric } 20217d523365SDimitry Andric } 20227d523365SDimitry Andric 20237d523365SDimitry Andric // In this loop we iterate every block in the loop chain and calculate the 20247d523365SDimitry Andric // cost assuming the block is the head of the loop chain. When the loop ends, 20257d523365SDimitry Andric // we should have found the best candidate as the loop chain's head. 20267d523365SDimitry Andric for (auto Iter = LoopChain.begin(), TailIter = std::prev(LoopChain.end()), 20277d523365SDimitry Andric EndIter = LoopChain.end(); 20287d523365SDimitry Andric Iter != EndIter; Iter++, TailIter++) { 20297d523365SDimitry Andric // TailIter is used to track the tail of the loop chain if the block we are 20307d523365SDimitry Andric // checking (pointed by Iter) is the head of the chain. 20317d523365SDimitry Andric if (TailIter == LoopChain.end()) 20327d523365SDimitry Andric TailIter = LoopChain.begin(); 20337d523365SDimitry Andric 20347d523365SDimitry Andric auto TailBB = *TailIter; 20357d523365SDimitry Andric 20367d523365SDimitry Andric // Calculate the cost by putting this BB to the top. 20377d523365SDimitry Andric BlockFrequency Cost = 0; 20387d523365SDimitry Andric 20397d523365SDimitry Andric // If the current BB is the loop header, we need to take into account the 20407d523365SDimitry Andric // cost of the missed fall through edge from outside of the loop to the 20417d523365SDimitry Andric // header. 20427d523365SDimitry Andric if (Iter != HeaderIter) 20437d523365SDimitry Andric Cost += HeaderFallThroughCost; 20447d523365SDimitry Andric 20457d523365SDimitry Andric // Collect the loop exit cost by summing up frequencies of all exit edges 20467d523365SDimitry Andric // except the one from the chain tail. 20477d523365SDimitry Andric for (auto &ExitWithFreq : ExitsWithFreq) 20487d523365SDimitry Andric if (TailBB != ExitWithFreq.first) 20497d523365SDimitry Andric Cost += ExitWithFreq.second; 20507d523365SDimitry Andric 20517d523365SDimitry Andric // The cost of breaking the once fall-through edge from the tail to the top 20527d523365SDimitry Andric // of the loop chain. Here we need to consider three cases: 20537d523365SDimitry Andric // 1. If the tail node has only one successor, then we will get an 20547d523365SDimitry Andric // additional jmp instruction. So the cost here is (MisfetchCost + 20557d523365SDimitry Andric // JumpInstCost) * tail node frequency. 20567d523365SDimitry Andric // 2. If the tail node has two successors, then we may still get an 20577d523365SDimitry Andric // additional jmp instruction if the layout successor after the loop 20587d523365SDimitry Andric // chain is not its CFG successor. Note that the more frequently executed 20597d523365SDimitry Andric // jmp instruction will be put ahead of the other one. Assume the 20607d523365SDimitry Andric // frequency of those two branches are x and y, where x is the frequency 20617d523365SDimitry Andric // of the edge to the chain head, then the cost will be 20627d523365SDimitry Andric // (x * MisfetechCost + min(x, y) * JumpInstCost) * tail node frequency. 20637d523365SDimitry Andric // 3. If the tail node has more than two successors (this rarely happens), 20647d523365SDimitry Andric // we won't consider any additional cost. 20657d523365SDimitry Andric if (TailBB->isSuccessor(*Iter)) { 20667d523365SDimitry Andric auto TailBBFreq = MBFI->getBlockFreq(TailBB); 20677d523365SDimitry Andric if (TailBB->succ_size() == 1) 20687d523365SDimitry Andric Cost += ScaleBlockFrequency(TailBBFreq.getFrequency(), 20697d523365SDimitry Andric MisfetchCost + JumpInstCost); 20707d523365SDimitry Andric else if (TailBB->succ_size() == 2) { 20717d523365SDimitry Andric auto TailToHeadProb = MBPI->getEdgeProbability(TailBB, *Iter); 20727d523365SDimitry Andric auto TailToHeadFreq = TailBBFreq * TailToHeadProb; 20737d523365SDimitry Andric auto ColderEdgeFreq = TailToHeadProb > BranchProbability(1, 2) 20747d523365SDimitry Andric ? TailBBFreq * TailToHeadProb.getCompl() 20757d523365SDimitry Andric : TailToHeadFreq; 20767d523365SDimitry Andric Cost += ScaleBlockFrequency(TailToHeadFreq, MisfetchCost) + 20777d523365SDimitry Andric ScaleBlockFrequency(ColderEdgeFreq, JumpInstCost); 20787d523365SDimitry Andric } 20797d523365SDimitry Andric } 20807d523365SDimitry Andric 20813ca95b02SDimitry Andric DEBUG(dbgs() << "The cost of loop rotation by making " << getBlockName(*Iter) 20827d523365SDimitry Andric << " to the top: " << Cost.getFrequency() << "\n"); 20837d523365SDimitry Andric 20847d523365SDimitry Andric if (Cost < SmallestRotationCost) { 20857d523365SDimitry Andric SmallestRotationCost = Cost; 20867d523365SDimitry Andric RotationPos = Iter; 20877d523365SDimitry Andric } 20887d523365SDimitry Andric } 20897d523365SDimitry Andric 20907d523365SDimitry Andric if (RotationPos != LoopChain.end()) { 20913ca95b02SDimitry Andric DEBUG(dbgs() << "Rotate loop by making " << getBlockName(*RotationPos) 20927d523365SDimitry Andric << " to the top\n"); 20937d523365SDimitry Andric std::rotate(LoopChain.begin(), RotationPos, LoopChain.end()); 20947d523365SDimitry Andric } 20957d523365SDimitry Andric } 20967d523365SDimitry Andric 20977d523365SDimitry Andric /// \brief Collect blocks in the given loop that are to be placed. 20987d523365SDimitry Andric /// 20997d523365SDimitry Andric /// When profile data is available, exclude cold blocks from the returned set; 21007d523365SDimitry Andric /// otherwise, collect all blocks in the loop. 21017d523365SDimitry Andric MachineBlockPlacement::BlockFilterSet 21027a7e6055SDimitry Andric MachineBlockPlacement::collectLoopBlockSet(const MachineLoop &L) { 21037d523365SDimitry Andric BlockFilterSet LoopBlockSet; 21047d523365SDimitry Andric 21057d523365SDimitry Andric // Filter cold blocks off from LoopBlockSet when profile data is available. 21067d523365SDimitry Andric // Collect the sum of frequencies of incoming edges to the loop header from 21077d523365SDimitry Andric // outside. If we treat the loop as a super block, this is the frequency of 21087d523365SDimitry Andric // the loop. Then for each block in the loop, we calculate the ratio between 21097d523365SDimitry Andric // its frequency and the frequency of the loop block. When it is too small, 21107d523365SDimitry Andric // don't add it to the loop chain. If there are outer loops, then this block 21117d523365SDimitry Andric // will be merged into the first outer loop chain for which this block is not 21127d523365SDimitry Andric // cold anymore. This needs precise profile data and we only do this when 21137d523365SDimitry Andric // profile data is available. 21143ca95b02SDimitry Andric if (F->getFunction()->getEntryCount()) { 21157d523365SDimitry Andric BlockFrequency LoopFreq(0); 21167d523365SDimitry Andric for (auto LoopPred : L.getHeader()->predecessors()) 21177d523365SDimitry Andric if (!L.contains(LoopPred)) 21187d523365SDimitry Andric LoopFreq += MBFI->getBlockFreq(LoopPred) * 21197d523365SDimitry Andric MBPI->getEdgeProbability(LoopPred, L.getHeader()); 21207d523365SDimitry Andric 21217d523365SDimitry Andric for (MachineBasicBlock *LoopBB : L.getBlocks()) { 21227d523365SDimitry Andric auto Freq = MBFI->getBlockFreq(LoopBB).getFrequency(); 21237d523365SDimitry Andric if (Freq == 0 || LoopFreq.getFrequency() / Freq > LoopToColdBlockRatio) 21247d523365SDimitry Andric continue; 21257d523365SDimitry Andric LoopBlockSet.insert(LoopBB); 21267d523365SDimitry Andric } 21277d523365SDimitry Andric } else 21287d523365SDimitry Andric LoopBlockSet.insert(L.block_begin(), L.block_end()); 21297d523365SDimitry Andric 21307d523365SDimitry Andric return LoopBlockSet; 21317d523365SDimitry Andric } 21327d523365SDimitry Andric 2133dff0c46cSDimitry Andric /// \brief Forms basic block chains from the natural loop structures. 2134dff0c46cSDimitry Andric /// 2135dff0c46cSDimitry Andric /// These chains are designed to preserve the existing *structure* of the code 2136dff0c46cSDimitry Andric /// as much as possible. We can then stitch the chains together in a way which 2137dff0c46cSDimitry Andric /// both preserves the topological structure and minimizes taken conditional 2138dff0c46cSDimitry Andric /// branches. 21397a7e6055SDimitry Andric void MachineBlockPlacement::buildLoopChains(const MachineLoop &L) { 2140dff0c46cSDimitry Andric // First recurse through any nested loops, building chains for those inner 2141dff0c46cSDimitry Andric // loops. 21427a7e6055SDimitry Andric for (const MachineLoop *InnerLoop : L) 21433ca95b02SDimitry Andric buildLoopChains(*InnerLoop); 2144dff0c46cSDimitry Andric 2145d8866befSDimitry Andric assert(BlockWorkList.empty() && 2146d8866befSDimitry Andric "BlockWorkList not empty when starting to build loop chains."); 2147d8866befSDimitry Andric assert(EHPadWorkList.empty() && 2148d8866befSDimitry Andric "EHPadWorkList not empty when starting to build loop chains."); 21493ca95b02SDimitry Andric BlockFilterSet LoopBlockSet = collectLoopBlockSet(L); 21507d523365SDimitry Andric 21517d523365SDimitry Andric // Check if we have profile data for this function. If yes, we will rotate 21527d523365SDimitry Andric // this loop by modeling costs more precisely which requires the profile data 21537d523365SDimitry Andric // for better layout. 21547d523365SDimitry Andric bool RotateLoopWithProfile = 21553ca95b02SDimitry Andric ForcePreciseRotationCost || 21563ca95b02SDimitry Andric (PreciseRotationCost && F->getFunction()->getEntryCount()); 2157dff0c46cSDimitry Andric 2158cb4dff85SDimitry Andric // First check to see if there is an obviously preferable top block for the 2159cb4dff85SDimitry Andric // loop. This will default to the header, but may end up as one of the 2160cb4dff85SDimitry Andric // predecessors to the header if there is one which will result in strictly 2161cb4dff85SDimitry Andric // fewer branches in the loop body. 21627d523365SDimitry Andric // When we use profile data to rotate the loop, this is unnecessary. 21637d523365SDimitry Andric MachineBasicBlock *LoopTop = 21647d523365SDimitry Andric RotateLoopWithProfile ? L.getHeader() : findBestLoopTop(L, LoopBlockSet); 2165cb4dff85SDimitry Andric 2166cb4dff85SDimitry Andric // If we selected just the header for the loop top, look for a potentially 2167cb4dff85SDimitry Andric // profitable exit block in the event that rotating the loop can eliminate 2168cb4dff85SDimitry Andric // branches by placing an exit edge at the bottom. 21697d523365SDimitry Andric if (!RotateLoopWithProfile && LoopTop == L.getHeader()) 2170d88c1a5aSDimitry Andric PreferredLoopExit = findBestLoopExit(L, LoopBlockSet); 2171cb4dff85SDimitry Andric 2172cb4dff85SDimitry Andric BlockChain &LoopChain = *BlockToChain[LoopTop]; 2173dff0c46cSDimitry Andric 2174dff0c46cSDimitry Andric // FIXME: This is a really lame way of walking the chains in the loop: we 2175dff0c46cSDimitry Andric // walk the blocks, and use a set to prevent visiting a particular chain 2176dff0c46cSDimitry Andric // twice. 2177dff0c46cSDimitry Andric SmallPtrSet<BlockChain *, 4> UpdatedPreds; 2178d8866befSDimitry Andric assert(LoopChain.UnscheduledPredecessors == 0 && 2179d8866befSDimitry Andric "LoopChain should not have unscheduled predecessors."); 2180dff0c46cSDimitry Andric UpdatedPreds.insert(&LoopChain); 21817d523365SDimitry Andric 21827a7e6055SDimitry Andric for (const MachineBasicBlock *LoopBB : LoopBlockSet) 21833ca95b02SDimitry Andric fillWorkLists(LoopBB, UpdatedPreds, &LoopBlockSet); 2184dff0c46cSDimitry Andric 21853ca95b02SDimitry Andric buildChain(LoopTop, LoopChain, &LoopBlockSet); 21867d523365SDimitry Andric 21877d523365SDimitry Andric if (RotateLoopWithProfile) 21887d523365SDimitry Andric rotateLoopWithProfile(LoopChain, L, LoopBlockSet); 21897d523365SDimitry Andric else 2190d88c1a5aSDimitry Andric rotateLoop(LoopChain, PreferredLoopExit, LoopBlockSet); 2191dff0c46cSDimitry Andric 2192dff0c46cSDimitry Andric DEBUG({ 2193dff0c46cSDimitry Andric // Crash at the end so we get all of the debugging output first. 2194dff0c46cSDimitry Andric bool BadLoop = false; 21953ca95b02SDimitry Andric if (LoopChain.UnscheduledPredecessors) { 2196dff0c46cSDimitry Andric BadLoop = true; 2197dff0c46cSDimitry Andric dbgs() << "Loop chain contains a block without its preds placed!\n" 2198dff0c46cSDimitry Andric << " Loop header: " << getBlockName(*L.block_begin()) << "\n" 2199dff0c46cSDimitry Andric << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n"; 2200dff0c46cSDimitry Andric } 2201ff0cc061SDimitry Andric for (MachineBasicBlock *ChainBB : LoopChain) { 2202ff0cc061SDimitry Andric dbgs() << " ... " << getBlockName(ChainBB) << "\n"; 2203d88c1a5aSDimitry Andric if (!LoopBlockSet.remove(ChainBB)) { 2204dff0c46cSDimitry Andric // We don't mark the loop as bad here because there are real situations 2205dff0c46cSDimitry Andric // where this can occur. For example, with an unanalyzable fallthrough 2206dff0c46cSDimitry Andric // from a loop block to a non-loop block or vice versa. 2207dff0c46cSDimitry Andric dbgs() << "Loop chain contains a block not contained by the loop!\n" 2208dff0c46cSDimitry Andric << " Loop header: " << getBlockName(*L.block_begin()) << "\n" 2209dff0c46cSDimitry Andric << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n" 2210ff0cc061SDimitry Andric << " Bad block: " << getBlockName(ChainBB) << "\n"; 2211dff0c46cSDimitry Andric } 2212cb4dff85SDimitry Andric } 2213dff0c46cSDimitry Andric 2214dff0c46cSDimitry Andric if (!LoopBlockSet.empty()) { 2215dff0c46cSDimitry Andric BadLoop = true; 22167a7e6055SDimitry Andric for (const MachineBasicBlock *LoopBB : LoopBlockSet) 2217dff0c46cSDimitry Andric dbgs() << "Loop contains blocks never placed into a chain!\n" 2218dff0c46cSDimitry Andric << " Loop header: " << getBlockName(*L.block_begin()) << "\n" 2219dff0c46cSDimitry Andric << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n" 2220ff0cc061SDimitry Andric << " Bad block: " << getBlockName(LoopBB) << "\n"; 2221dff0c46cSDimitry Andric } 2222dff0c46cSDimitry Andric assert(!BadLoop && "Detected problems with the placement of this loop."); 2223dff0c46cSDimitry Andric }); 22243ca95b02SDimitry Andric 22253ca95b02SDimitry Andric BlockWorkList.clear(); 22263ca95b02SDimitry Andric EHPadWorkList.clear(); 2227dff0c46cSDimitry Andric } 2228dff0c46cSDimitry Andric 22293ca95b02SDimitry Andric void MachineBlockPlacement::buildCFGChains() { 2230dff0c46cSDimitry Andric // Ensure that every BB in the function has an associated chain to simplify 2231dff0c46cSDimitry Andric // the assumptions of the remaining algorithm. 2232dff0c46cSDimitry Andric SmallVector<MachineOperand, 4> Cond; // For AnalyzeBranch. 22333ca95b02SDimitry Andric for (MachineFunction::iterator FI = F->begin(), FE = F->end(); FI != FE; 22343ca95b02SDimitry Andric ++FI) { 22357d523365SDimitry Andric MachineBasicBlock *BB = &*FI; 2236ff0cc061SDimitry Andric BlockChain *Chain = 2237ff0cc061SDimitry Andric new (ChainAllocator.Allocate()) BlockChain(BlockToChain, BB); 2238dff0c46cSDimitry Andric // Also, merge any blocks which we cannot reason about and must preserve 2239dff0c46cSDimitry Andric // the exact fallthrough behavior for. 2240dff0c46cSDimitry Andric for (;;) { 2241dff0c46cSDimitry Andric Cond.clear(); 224291bc56edSDimitry Andric MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch. 22433ca95b02SDimitry Andric if (!TII->analyzeBranch(*BB, TBB, FBB, Cond) || !FI->canFallThrough()) 2244dff0c46cSDimitry Andric break; 2245dff0c46cSDimitry Andric 22467d523365SDimitry Andric MachineFunction::iterator NextFI = std::next(FI); 22477d523365SDimitry Andric MachineBasicBlock *NextBB = &*NextFI; 2248dff0c46cSDimitry Andric // Ensure that the layout successor is a viable block, as we know that 2249dff0c46cSDimitry Andric // fallthrough is a possibility. 2250dff0c46cSDimitry Andric assert(NextFI != FE && "Can't fallthrough past the last block."); 2251dff0c46cSDimitry Andric DEBUG(dbgs() << "Pre-merging due to unanalyzable fallthrough: " 2252dff0c46cSDimitry Andric << getBlockName(BB) << " -> " << getBlockName(NextBB) 2253dff0c46cSDimitry Andric << "\n"); 225491bc56edSDimitry Andric Chain->merge(NextBB, nullptr); 2255d88c1a5aSDimitry Andric #ifndef NDEBUG 2256d88c1a5aSDimitry Andric BlocksWithUnanalyzableExits.insert(&*BB); 2257d88c1a5aSDimitry Andric #endif 2258dff0c46cSDimitry Andric FI = NextFI; 2259dff0c46cSDimitry Andric BB = NextBB; 2260dff0c46cSDimitry Andric } 2261dff0c46cSDimitry Andric } 2262dff0c46cSDimitry Andric 2263dff0c46cSDimitry Andric // Build any loop-based chains. 2264d88c1a5aSDimitry Andric PreferredLoopExit = nullptr; 2265ff0cc061SDimitry Andric for (MachineLoop *L : *MLI) 22663ca95b02SDimitry Andric buildLoopChains(*L); 2267dff0c46cSDimitry Andric 2268d8866befSDimitry Andric assert(BlockWorkList.empty() && 2269d8866befSDimitry Andric "BlockWorkList should be empty before building final chain."); 2270d8866befSDimitry Andric assert(EHPadWorkList.empty() && 2271d8866befSDimitry Andric "EHPadWorkList should be empty before building final chain."); 2272dff0c46cSDimitry Andric 2273dff0c46cSDimitry Andric SmallPtrSet<BlockChain *, 4> UpdatedPreds; 22743ca95b02SDimitry Andric for (MachineBasicBlock &MBB : *F) 22753ca95b02SDimitry Andric fillWorkLists(&MBB, UpdatedPreds); 2276dff0c46cSDimitry Andric 22773ca95b02SDimitry Andric BlockChain &FunctionChain = *BlockToChain[&F->front()]; 22783ca95b02SDimitry Andric buildChain(&F->front(), FunctionChain); 2279dff0c46cSDimitry Andric 228091bc56edSDimitry Andric #ifndef NDEBUG 2281dff0c46cSDimitry Andric typedef SmallPtrSet<MachineBasicBlock *, 16> FunctionBlockSetType; 228291bc56edSDimitry Andric #endif 2283dff0c46cSDimitry Andric DEBUG({ 2284dff0c46cSDimitry Andric // Crash at the end so we get all of the debugging output first. 2285dff0c46cSDimitry Andric bool BadFunc = false; 2286dff0c46cSDimitry Andric FunctionBlockSetType FunctionBlockSet; 22873ca95b02SDimitry Andric for (MachineBasicBlock &MBB : *F) 2288ff0cc061SDimitry Andric FunctionBlockSet.insert(&MBB); 2289dff0c46cSDimitry Andric 2290ff0cc061SDimitry Andric for (MachineBasicBlock *ChainBB : FunctionChain) 2291ff0cc061SDimitry Andric if (!FunctionBlockSet.erase(ChainBB)) { 2292dff0c46cSDimitry Andric BadFunc = true; 2293dff0c46cSDimitry Andric dbgs() << "Function chain contains a block not in the function!\n" 2294ff0cc061SDimitry Andric << " Bad block: " << getBlockName(ChainBB) << "\n"; 2295dff0c46cSDimitry Andric } 2296dff0c46cSDimitry Andric 2297dff0c46cSDimitry Andric if (!FunctionBlockSet.empty()) { 2298dff0c46cSDimitry Andric BadFunc = true; 2299ff0cc061SDimitry Andric for (MachineBasicBlock *RemainingBB : FunctionBlockSet) 2300dff0c46cSDimitry Andric dbgs() << "Function contains blocks never placed into a chain!\n" 2301ff0cc061SDimitry Andric << " Bad block: " << getBlockName(RemainingBB) << "\n"; 2302dff0c46cSDimitry Andric } 2303dff0c46cSDimitry Andric assert(!BadFunc && "Detected problems with the block placement."); 2304dff0c46cSDimitry Andric }); 2305dff0c46cSDimitry Andric 2306dff0c46cSDimitry Andric // Splice the blocks into place. 23073ca95b02SDimitry Andric MachineFunction::iterator InsertPos = F->begin(); 23083ca95b02SDimitry Andric DEBUG(dbgs() << "[MBP] Function: "<< F->getName() << "\n"); 2309ff0cc061SDimitry Andric for (MachineBasicBlock *ChainBB : FunctionChain) { 2310ff0cc061SDimitry Andric DEBUG(dbgs() << (ChainBB == *FunctionChain.begin() ? "Placing chain " 2311dff0c46cSDimitry Andric : " ... ") 2312ff0cc061SDimitry Andric << getBlockName(ChainBB) << "\n"); 2313ff0cc061SDimitry Andric if (InsertPos != MachineFunction::iterator(ChainBB)) 23143ca95b02SDimitry Andric F->splice(InsertPos, ChainBB); 2315dff0c46cSDimitry Andric else 2316dff0c46cSDimitry Andric ++InsertPos; 2317dff0c46cSDimitry Andric 2318dff0c46cSDimitry Andric // Update the terminator of the previous block. 2319ff0cc061SDimitry Andric if (ChainBB == *FunctionChain.begin()) 2320dff0c46cSDimitry Andric continue; 23217d523365SDimitry Andric MachineBasicBlock *PrevBB = &*std::prev(MachineFunction::iterator(ChainBB)); 2322dff0c46cSDimitry Andric 2323dff0c46cSDimitry Andric // FIXME: It would be awesome of updateTerminator would just return rather 2324dff0c46cSDimitry Andric // than assert when the branch cannot be analyzed in order to remove this 2325dff0c46cSDimitry Andric // boiler plate. 2326dff0c46cSDimitry Andric Cond.clear(); 232791bc56edSDimitry Andric MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch. 23283ca95b02SDimitry Andric 2329d88c1a5aSDimitry Andric #ifndef NDEBUG 2330d88c1a5aSDimitry Andric if (!BlocksWithUnanalyzableExits.count(PrevBB)) { 2331d88c1a5aSDimitry Andric // Given the exact block placement we chose, we may actually not _need_ to 2332d88c1a5aSDimitry Andric // be able to edit PrevBB's terminator sequence, but not being _able_ to 2333d88c1a5aSDimitry Andric // do that at this point is a bug. 2334d88c1a5aSDimitry Andric assert((!TII->analyzeBranch(*PrevBB, TBB, FBB, Cond) || 2335d88c1a5aSDimitry Andric !PrevBB->canFallThrough()) && 2336d88c1a5aSDimitry Andric "Unexpected block with un-analyzable fallthrough!"); 2337d88c1a5aSDimitry Andric Cond.clear(); 2338d88c1a5aSDimitry Andric TBB = FBB = nullptr; 2339d88c1a5aSDimitry Andric } 2340d88c1a5aSDimitry Andric #endif 2341d88c1a5aSDimitry Andric 2342f785676fSDimitry Andric // The "PrevBB" is not yet updated to reflect current code layout, so, 23433ca95b02SDimitry Andric // o. it may fall-through to a block without explicit "goto" instruction 2344f785676fSDimitry Andric // before layout, and no longer fall-through it after layout; or 2345f785676fSDimitry Andric // o. just opposite. 2346f785676fSDimitry Andric // 23473ca95b02SDimitry Andric // analyzeBranch() may return erroneous value for FBB when these two 23483ca95b02SDimitry Andric // situations take place. For the first scenario FBB is mistakenly set NULL; 23493ca95b02SDimitry Andric // for the 2nd scenario, the FBB, which is expected to be NULL, is 23503ca95b02SDimitry Andric // mistakenly pointing to "*BI". 23513ca95b02SDimitry Andric // Thus, if the future change needs to use FBB before the layout is set, it 23523ca95b02SDimitry Andric // has to correct FBB first by using the code similar to the following: 2353f785676fSDimitry Andric // 23543ca95b02SDimitry Andric // if (!Cond.empty() && (!FBB || FBB == ChainBB)) { 23553ca95b02SDimitry Andric // PrevBB->updateTerminator(); 23563ca95b02SDimitry Andric // Cond.clear(); 23573ca95b02SDimitry Andric // TBB = FBB = nullptr; 23583ca95b02SDimitry Andric // if (TII->analyzeBranch(*PrevBB, TBB, FBB, Cond)) { 23593ca95b02SDimitry Andric // // FIXME: This should never take place. 23603ca95b02SDimitry Andric // TBB = FBB = nullptr; 23613ca95b02SDimitry Andric // } 23623ca95b02SDimitry Andric // } 23633ca95b02SDimitry Andric if (!TII->analyzeBranch(*PrevBB, TBB, FBB, Cond)) 2364f785676fSDimitry Andric PrevBB->updateTerminator(); 23657ae0e2c9SDimitry Andric } 2366dff0c46cSDimitry Andric 2367dff0c46cSDimitry Andric // Fixup the last block. 2368dff0c46cSDimitry Andric Cond.clear(); 236991bc56edSDimitry Andric MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch. 23703ca95b02SDimitry Andric if (!TII->analyzeBranch(F->back(), TBB, FBB, Cond)) 23713ca95b02SDimitry Andric F->back().updateTerminator(); 2372dff0c46cSDimitry Andric 23733ca95b02SDimitry Andric BlockWorkList.clear(); 23743ca95b02SDimitry Andric EHPadWorkList.clear(); 23753ca95b02SDimitry Andric } 23763ca95b02SDimitry Andric 23773ca95b02SDimitry Andric void MachineBlockPlacement::optimizeBranches() { 23783ca95b02SDimitry Andric BlockChain &FunctionChain = *BlockToChain[&F->front()]; 23793ca95b02SDimitry Andric SmallVector<MachineOperand, 4> Cond; // For AnalyzeBranch. 23803ca95b02SDimitry Andric 23813ca95b02SDimitry Andric // Now that all the basic blocks in the chain have the proper layout, 23823ca95b02SDimitry Andric // make a final call to AnalyzeBranch with AllowModify set. 23833ca95b02SDimitry Andric // Indeed, the target may be able to optimize the branches in a way we 23843ca95b02SDimitry Andric // cannot because all branches may not be analyzable. 23853ca95b02SDimitry Andric // E.g., the target may be able to remove an unconditional branch to 23863ca95b02SDimitry Andric // a fallthrough when it occurs after predicated terminators. 23873ca95b02SDimitry Andric for (MachineBasicBlock *ChainBB : FunctionChain) { 23883ca95b02SDimitry Andric Cond.clear(); 23893ca95b02SDimitry Andric MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch. 23903ca95b02SDimitry Andric if (!TII->analyzeBranch(*ChainBB, TBB, FBB, Cond, /*AllowModify*/ true)) { 23913ca95b02SDimitry Andric // If PrevBB has a two-way branch, try to re-order the branches 23923ca95b02SDimitry Andric // such that we branch to the successor with higher probability first. 23933ca95b02SDimitry Andric if (TBB && !Cond.empty() && FBB && 23943ca95b02SDimitry Andric MBPI->getEdgeProbability(ChainBB, FBB) > 23953ca95b02SDimitry Andric MBPI->getEdgeProbability(ChainBB, TBB) && 2396d88c1a5aSDimitry Andric !TII->reverseBranchCondition(Cond)) { 23973ca95b02SDimitry Andric DEBUG(dbgs() << "Reverse order of the two branches: " 23983ca95b02SDimitry Andric << getBlockName(ChainBB) << "\n"); 23993ca95b02SDimitry Andric DEBUG(dbgs() << " Edge probability: " 24003ca95b02SDimitry Andric << MBPI->getEdgeProbability(ChainBB, FBB) << " vs " 24013ca95b02SDimitry Andric << MBPI->getEdgeProbability(ChainBB, TBB) << "\n"); 24023ca95b02SDimitry Andric DebugLoc dl; // FIXME: this is nowhere 2403d88c1a5aSDimitry Andric TII->removeBranch(*ChainBB); 2404d88c1a5aSDimitry Andric TII->insertBranch(*ChainBB, FBB, TBB, Cond, dl); 24053ca95b02SDimitry Andric ChainBB->updateTerminator(); 24063ca95b02SDimitry Andric } 24073ca95b02SDimitry Andric } 24083ca95b02SDimitry Andric } 24093ca95b02SDimitry Andric } 24103ca95b02SDimitry Andric 24113ca95b02SDimitry Andric void MachineBlockPlacement::alignBlocks() { 2412cb4dff85SDimitry Andric // Walk through the backedges of the function now that we have fully laid out 2413cb4dff85SDimitry Andric // the basic blocks and align the destination of each backedge. We don't rely 24147ae0e2c9SDimitry Andric // exclusively on the loop info here so that we can align backedges in 24157ae0e2c9SDimitry Andric // unnatural CFGs and backedges that were introduced purely because of the 24167ae0e2c9SDimitry Andric // loop rotations done during this layout pass. 24173ca95b02SDimitry Andric if (F->getFunction()->optForSize()) 2418dff0c46cSDimitry Andric return; 24193ca95b02SDimitry Andric BlockChain &FunctionChain = *BlockToChain[&F->front()]; 24207ae0e2c9SDimitry Andric if (FunctionChain.begin() == FunctionChain.end()) 24217ae0e2c9SDimitry Andric return; // Empty chain. 2422dff0c46cSDimitry Andric 24237ae0e2c9SDimitry Andric const BranchProbability ColdProb(1, 5); // 20% 24243ca95b02SDimitry Andric BlockFrequency EntryFreq = MBFI->getBlockFreq(&F->front()); 24257ae0e2c9SDimitry Andric BlockFrequency WeightedEntryFreq = EntryFreq * ColdProb; 2426ff0cc061SDimitry Andric for (MachineBasicBlock *ChainBB : FunctionChain) { 2427ff0cc061SDimitry Andric if (ChainBB == *FunctionChain.begin()) 2428ff0cc061SDimitry Andric continue; 2429ff0cc061SDimitry Andric 24307ae0e2c9SDimitry Andric // Don't align non-looping basic blocks. These are unlikely to execute 24317ae0e2c9SDimitry Andric // enough times to matter in practice. Note that we'll still handle 24327ae0e2c9SDimitry Andric // unnatural CFGs inside of a natural outer loop (the common case) and 24337ae0e2c9SDimitry Andric // rotated loops. 2434ff0cc061SDimitry Andric MachineLoop *L = MLI->getLoopFor(ChainBB); 24357ae0e2c9SDimitry Andric if (!L) 24367ae0e2c9SDimitry Andric continue; 24377ae0e2c9SDimitry Andric 243839d628a0SDimitry Andric unsigned Align = TLI->getPrefLoopAlignment(L); 243939d628a0SDimitry Andric if (!Align) 244039d628a0SDimitry Andric continue; // Don't care about loop alignment. 244139d628a0SDimitry Andric 24427ae0e2c9SDimitry Andric // If the block is cold relative to the function entry don't waste space 24437ae0e2c9SDimitry Andric // aligning it. 2444ff0cc061SDimitry Andric BlockFrequency Freq = MBFI->getBlockFreq(ChainBB); 24457ae0e2c9SDimitry Andric if (Freq < WeightedEntryFreq) 24467ae0e2c9SDimitry Andric continue; 24477ae0e2c9SDimitry Andric 24487ae0e2c9SDimitry Andric // If the block is cold relative to its loop header, don't align it 24497ae0e2c9SDimitry Andric // regardless of what edges into the block exist. 24507ae0e2c9SDimitry Andric MachineBasicBlock *LoopHeader = L->getHeader(); 24517ae0e2c9SDimitry Andric BlockFrequency LoopHeaderFreq = MBFI->getBlockFreq(LoopHeader); 24527ae0e2c9SDimitry Andric if (Freq < (LoopHeaderFreq * ColdProb)) 24537ae0e2c9SDimitry Andric continue; 24547ae0e2c9SDimitry Andric 24557ae0e2c9SDimitry Andric // Check for the existence of a non-layout predecessor which would benefit 24567ae0e2c9SDimitry Andric // from aligning this block. 2457ff0cc061SDimitry Andric MachineBasicBlock *LayoutPred = 2458ff0cc061SDimitry Andric &*std::prev(MachineFunction::iterator(ChainBB)); 24597ae0e2c9SDimitry Andric 24607ae0e2c9SDimitry Andric // Force alignment if all the predecessors are jumps. We already checked 24617ae0e2c9SDimitry Andric // that the block isn't cold above. 2462ff0cc061SDimitry Andric if (!LayoutPred->isSuccessor(ChainBB)) { 2463ff0cc061SDimitry Andric ChainBB->setAlignment(Align); 24647ae0e2c9SDimitry Andric continue; 24657ae0e2c9SDimitry Andric } 24667ae0e2c9SDimitry Andric 24677ae0e2c9SDimitry Andric // Align this block if the layout predecessor's edge into this block is 2468139f7f9bSDimitry Andric // cold relative to the block. When this is true, other predecessors make up 24697ae0e2c9SDimitry Andric // all of the hot entries into the block and thus alignment is likely to be 24707ae0e2c9SDimitry Andric // important. 2471ff0cc061SDimitry Andric BranchProbability LayoutProb = 2472ff0cc061SDimitry Andric MBPI->getEdgeProbability(LayoutPred, ChainBB); 24737ae0e2c9SDimitry Andric BlockFrequency LayoutEdgeFreq = MBFI->getBlockFreq(LayoutPred) * LayoutProb; 24747ae0e2c9SDimitry Andric if (LayoutEdgeFreq <= (Freq * ColdProb)) 2475ff0cc061SDimitry Andric ChainBB->setAlignment(Align); 2476cb4dff85SDimitry Andric } 2477dff0c46cSDimitry Andric } 2478dff0c46cSDimitry Andric 2479d88c1a5aSDimitry Andric /// Tail duplicate \p BB into (some) predecessors if profitable, repeating if 2480d88c1a5aSDimitry Andric /// it was duplicated into its chain predecessor and removed. 2481d88c1a5aSDimitry Andric /// \p BB - Basic block that may be duplicated. 2482d88c1a5aSDimitry Andric /// 2483d88c1a5aSDimitry Andric /// \p LPred - Chosen layout predecessor of \p BB. 2484d88c1a5aSDimitry Andric /// Updated to be the chain end if LPred is removed. 2485d88c1a5aSDimitry Andric /// \p Chain - Chain to which \p LPred belongs, and \p BB will belong. 2486d88c1a5aSDimitry Andric /// \p BlockFilter - Set of blocks that belong to the loop being laid out. 2487d88c1a5aSDimitry Andric /// Used to identify which blocks to update predecessor 2488d88c1a5aSDimitry Andric /// counts. 2489d88c1a5aSDimitry Andric /// \p PrevUnplacedBlockIt - Iterator pointing to the last block that was 2490d88c1a5aSDimitry Andric /// chosen in the given order due to unnatural CFG 2491d88c1a5aSDimitry Andric /// only needed if \p BB is removed and 2492d88c1a5aSDimitry Andric /// \p PrevUnplacedBlockIt pointed to \p BB. 2493d88c1a5aSDimitry Andric /// @return true if \p BB was removed. 2494d88c1a5aSDimitry Andric bool MachineBlockPlacement::repeatedlyTailDuplicateBlock( 2495d88c1a5aSDimitry Andric MachineBasicBlock *BB, MachineBasicBlock *&LPred, 24967a7e6055SDimitry Andric const MachineBasicBlock *LoopHeaderBB, 2497d88c1a5aSDimitry Andric BlockChain &Chain, BlockFilterSet *BlockFilter, 2498d88c1a5aSDimitry Andric MachineFunction::iterator &PrevUnplacedBlockIt) { 2499d88c1a5aSDimitry Andric bool Removed, DuplicatedToLPred; 2500d88c1a5aSDimitry Andric bool DuplicatedToOriginalLPred; 2501d88c1a5aSDimitry Andric Removed = maybeTailDuplicateBlock(BB, LPred, Chain, BlockFilter, 2502d88c1a5aSDimitry Andric PrevUnplacedBlockIt, 2503d88c1a5aSDimitry Andric DuplicatedToLPred); 2504d88c1a5aSDimitry Andric if (!Removed) 2505d88c1a5aSDimitry Andric return false; 2506d88c1a5aSDimitry Andric DuplicatedToOriginalLPred = DuplicatedToLPred; 2507d88c1a5aSDimitry Andric // Iteratively try to duplicate again. It can happen that a block that is 2508d88c1a5aSDimitry Andric // duplicated into is still small enough to be duplicated again. 2509d88c1a5aSDimitry Andric // No need to call markBlockSuccessors in this case, as the blocks being 2510d88c1a5aSDimitry Andric // duplicated from here on are already scheduled. 2511d88c1a5aSDimitry Andric // Note that DuplicatedToLPred always implies Removed. 2512d88c1a5aSDimitry Andric while (DuplicatedToLPred) { 2513d88c1a5aSDimitry Andric assert (Removed && "Block must have been removed to be duplicated into its " 2514d88c1a5aSDimitry Andric "layout predecessor."); 2515d88c1a5aSDimitry Andric MachineBasicBlock *DupBB, *DupPred; 2516d88c1a5aSDimitry Andric // The removal callback causes Chain.end() to be updated when a block is 2517d88c1a5aSDimitry Andric // removed. On the first pass through the loop, the chain end should be the 2518d88c1a5aSDimitry Andric // same as it was on function entry. On subsequent passes, because we are 2519d88c1a5aSDimitry Andric // duplicating the block at the end of the chain, if it is removed the 2520d88c1a5aSDimitry Andric // chain will have shrunk by one block. 2521d88c1a5aSDimitry Andric BlockChain::iterator ChainEnd = Chain.end(); 2522d88c1a5aSDimitry Andric DupBB = *(--ChainEnd); 2523d88c1a5aSDimitry Andric // Now try to duplicate again. 2524d88c1a5aSDimitry Andric if (ChainEnd == Chain.begin()) 2525d88c1a5aSDimitry Andric break; 2526d88c1a5aSDimitry Andric DupPred = *std::prev(ChainEnd); 2527d88c1a5aSDimitry Andric Removed = maybeTailDuplicateBlock(DupBB, DupPred, Chain, BlockFilter, 2528d88c1a5aSDimitry Andric PrevUnplacedBlockIt, 2529d88c1a5aSDimitry Andric DuplicatedToLPred); 2530d88c1a5aSDimitry Andric } 2531d88c1a5aSDimitry Andric // If BB was duplicated into LPred, it is now scheduled. But because it was 2532d88c1a5aSDimitry Andric // removed, markChainSuccessors won't be called for its chain. Instead we 2533d88c1a5aSDimitry Andric // call markBlockSuccessors for LPred to achieve the same effect. This must go 2534d88c1a5aSDimitry Andric // at the end because repeating the tail duplication can increase the number 2535d88c1a5aSDimitry Andric // of unscheduled predecessors. 2536d88c1a5aSDimitry Andric LPred = *std::prev(Chain.end()); 2537d88c1a5aSDimitry Andric if (DuplicatedToOriginalLPred) 2538d88c1a5aSDimitry Andric markBlockSuccessors(Chain, LPred, LoopHeaderBB, BlockFilter); 2539d88c1a5aSDimitry Andric return true; 2540d88c1a5aSDimitry Andric } 2541d88c1a5aSDimitry Andric 2542d88c1a5aSDimitry Andric /// Tail duplicate \p BB into (some) predecessors if profitable. 2543d88c1a5aSDimitry Andric /// \p BB - Basic block that may be duplicated 2544d88c1a5aSDimitry Andric /// \p LPred - Chosen layout predecessor of \p BB 2545d88c1a5aSDimitry Andric /// \p Chain - Chain to which \p LPred belongs, and \p BB will belong. 2546d88c1a5aSDimitry Andric /// \p BlockFilter - Set of blocks that belong to the loop being laid out. 2547d88c1a5aSDimitry Andric /// Used to identify which blocks to update predecessor 2548d88c1a5aSDimitry Andric /// counts. 2549d88c1a5aSDimitry Andric /// \p PrevUnplacedBlockIt - Iterator pointing to the last block that was 2550d88c1a5aSDimitry Andric /// chosen in the given order due to unnatural CFG 2551d88c1a5aSDimitry Andric /// only needed if \p BB is removed and 2552d88c1a5aSDimitry Andric /// \p PrevUnplacedBlockIt pointed to \p BB. 2553d88c1a5aSDimitry Andric /// \p DuplicatedToLPred - True if the block was duplicated into LPred. Will 2554d88c1a5aSDimitry Andric /// only be true if the block was removed. 2555d88c1a5aSDimitry Andric /// \return - True if the block was duplicated into all preds and removed. 2556d88c1a5aSDimitry Andric bool MachineBlockPlacement::maybeTailDuplicateBlock( 2557d88c1a5aSDimitry Andric MachineBasicBlock *BB, MachineBasicBlock *LPred, 25587a7e6055SDimitry Andric BlockChain &Chain, BlockFilterSet *BlockFilter, 2559d88c1a5aSDimitry Andric MachineFunction::iterator &PrevUnplacedBlockIt, 2560d88c1a5aSDimitry Andric bool &DuplicatedToLPred) { 2561d88c1a5aSDimitry Andric DuplicatedToLPred = false; 25627a7e6055SDimitry Andric if (!shouldTailDuplicate(BB)) 25637a7e6055SDimitry Andric return false; 25647a7e6055SDimitry Andric 2565d88c1a5aSDimitry Andric DEBUG(dbgs() << "Redoing tail duplication for Succ#" 2566d88c1a5aSDimitry Andric << BB->getNumber() << "\n"); 25677a7e6055SDimitry Andric 2568d88c1a5aSDimitry Andric // This has to be a callback because none of it can be done after 2569d88c1a5aSDimitry Andric // BB is deleted. 2570d88c1a5aSDimitry Andric bool Removed = false; 2571d88c1a5aSDimitry Andric auto RemovalCallback = 2572d88c1a5aSDimitry Andric [&](MachineBasicBlock *RemBB) { 2573d88c1a5aSDimitry Andric // Signal to outer function 2574d88c1a5aSDimitry Andric Removed = true; 2575d88c1a5aSDimitry Andric 2576d88c1a5aSDimitry Andric // Conservative default. 2577d88c1a5aSDimitry Andric bool InWorkList = true; 2578d88c1a5aSDimitry Andric // Remove from the Chain and Chain Map 2579d88c1a5aSDimitry Andric if (BlockToChain.count(RemBB)) { 2580d88c1a5aSDimitry Andric BlockChain *Chain = BlockToChain[RemBB]; 2581d88c1a5aSDimitry Andric InWorkList = Chain->UnscheduledPredecessors == 0; 2582d88c1a5aSDimitry Andric Chain->remove(RemBB); 2583d88c1a5aSDimitry Andric BlockToChain.erase(RemBB); 2584d88c1a5aSDimitry Andric } 2585d88c1a5aSDimitry Andric 2586d88c1a5aSDimitry Andric // Handle the unplaced block iterator 2587d88c1a5aSDimitry Andric if (&(*PrevUnplacedBlockIt) == RemBB) { 2588d88c1a5aSDimitry Andric PrevUnplacedBlockIt++; 2589d88c1a5aSDimitry Andric } 2590d88c1a5aSDimitry Andric 2591d88c1a5aSDimitry Andric // Handle the Work Lists 2592d88c1a5aSDimitry Andric if (InWorkList) { 2593d88c1a5aSDimitry Andric SmallVectorImpl<MachineBasicBlock *> &RemoveList = BlockWorkList; 2594d88c1a5aSDimitry Andric if (RemBB->isEHPad()) 2595d88c1a5aSDimitry Andric RemoveList = EHPadWorkList; 2596d88c1a5aSDimitry Andric RemoveList.erase( 2597d88c1a5aSDimitry Andric remove_if(RemoveList, 2598d88c1a5aSDimitry Andric [RemBB](MachineBasicBlock *BB) {return BB == RemBB;}), 2599d88c1a5aSDimitry Andric RemoveList.end()); 2600d88c1a5aSDimitry Andric } 2601d88c1a5aSDimitry Andric 2602d88c1a5aSDimitry Andric // Handle the filter set 2603d88c1a5aSDimitry Andric if (BlockFilter) { 2604d88c1a5aSDimitry Andric BlockFilter->remove(RemBB); 2605d88c1a5aSDimitry Andric } 2606d88c1a5aSDimitry Andric 2607d88c1a5aSDimitry Andric // Remove the block from loop info. 2608d88c1a5aSDimitry Andric MLI->removeBlock(RemBB); 2609d88c1a5aSDimitry Andric if (RemBB == PreferredLoopExit) 2610d88c1a5aSDimitry Andric PreferredLoopExit = nullptr; 2611d88c1a5aSDimitry Andric 2612d88c1a5aSDimitry Andric DEBUG(dbgs() << "TailDuplicator deleted block: " 2613d88c1a5aSDimitry Andric << getBlockName(RemBB) << "\n"); 2614d88c1a5aSDimitry Andric }; 2615d88c1a5aSDimitry Andric auto RemovalCallbackRef = 2616d88c1a5aSDimitry Andric llvm::function_ref<void(MachineBasicBlock*)>(RemovalCallback); 2617d88c1a5aSDimitry Andric 2618d88c1a5aSDimitry Andric SmallVector<MachineBasicBlock *, 8> DuplicatedPreds; 26197a7e6055SDimitry Andric bool IsSimple = TailDup.isSimpleBB(BB); 2620d88c1a5aSDimitry Andric TailDup.tailDuplicateAndUpdate(IsSimple, BB, LPred, 2621d88c1a5aSDimitry Andric &DuplicatedPreds, &RemovalCallbackRef); 2622d88c1a5aSDimitry Andric 2623d88c1a5aSDimitry Andric // Update UnscheduledPredecessors to reflect tail-duplication. 2624d88c1a5aSDimitry Andric DuplicatedToLPred = false; 2625d88c1a5aSDimitry Andric for (MachineBasicBlock *Pred : DuplicatedPreds) { 2626d88c1a5aSDimitry Andric // We're only looking for unscheduled predecessors that match the filter. 2627d88c1a5aSDimitry Andric BlockChain* PredChain = BlockToChain[Pred]; 2628d88c1a5aSDimitry Andric if (Pred == LPred) 2629d88c1a5aSDimitry Andric DuplicatedToLPred = true; 2630d88c1a5aSDimitry Andric if (Pred == LPred || (BlockFilter && !BlockFilter->count(Pred)) 2631d88c1a5aSDimitry Andric || PredChain == &Chain) 2632d88c1a5aSDimitry Andric continue; 2633d88c1a5aSDimitry Andric for (MachineBasicBlock *NewSucc : Pred->successors()) { 2634d88c1a5aSDimitry Andric if (BlockFilter && !BlockFilter->count(NewSucc)) 2635d88c1a5aSDimitry Andric continue; 2636d88c1a5aSDimitry Andric BlockChain *NewChain = BlockToChain[NewSucc]; 2637d88c1a5aSDimitry Andric if (NewChain != &Chain && NewChain != PredChain) 2638d88c1a5aSDimitry Andric NewChain->UnscheduledPredecessors++; 2639d88c1a5aSDimitry Andric } 2640d88c1a5aSDimitry Andric } 2641d88c1a5aSDimitry Andric return Removed; 2642d88c1a5aSDimitry Andric } 2643d88c1a5aSDimitry Andric 26443ca95b02SDimitry Andric bool MachineBlockPlacement::runOnMachineFunction(MachineFunction &MF) { 26453ca95b02SDimitry Andric if (skipFunction(*MF.getFunction())) 26463ca95b02SDimitry Andric return false; 26473ca95b02SDimitry Andric 2648dff0c46cSDimitry Andric // Check for single-block functions and skip them. 26493ca95b02SDimitry Andric if (std::next(MF.begin()) == MF.end()) 265091bc56edSDimitry Andric return false; 265191bc56edSDimitry Andric 26523ca95b02SDimitry Andric F = &MF; 2653dff0c46cSDimitry Andric MBPI = &getAnalysis<MachineBranchProbabilityInfo>(); 26543ca95b02SDimitry Andric MBFI = llvm::make_unique<BranchFolder::MBFIWrapper>( 26553ca95b02SDimitry Andric getAnalysis<MachineBlockFrequencyInfo>()); 2656dff0c46cSDimitry Andric MLI = &getAnalysis<MachineLoopInfo>(); 26573ca95b02SDimitry Andric TII = MF.getSubtarget().getInstrInfo(); 26583ca95b02SDimitry Andric TLI = MF.getSubtarget().getTargetLowering(); 26597a7e6055SDimitry Andric MPDT = nullptr; 2660d88c1a5aSDimitry Andric 2661d88c1a5aSDimitry Andric // Initialize PreferredLoopExit to nullptr here since it may never be set if 2662d88c1a5aSDimitry Andric // there are no MachineLoops. 2663d88c1a5aSDimitry Andric PreferredLoopExit = nullptr; 2664d88c1a5aSDimitry Andric 2665d8866befSDimitry Andric assert(BlockToChain.empty() && 2666d8866befSDimitry Andric "BlockToChain map should be empty before starting placement."); 2667d8866befSDimitry Andric assert(ComputedEdges.empty() && 2668d8866befSDimitry Andric "Computed Edge map should be empty before starting placement."); 26697a7e6055SDimitry Andric 26705517e702SDimitry Andric unsigned TailDupSize = TailDupPlacementThreshold; 26715517e702SDimitry Andric // If only the aggressive threshold is explicitly set, use it. 26725517e702SDimitry Andric if (TailDupPlacementAggressiveThreshold.getNumOccurrences() != 0 && 26735517e702SDimitry Andric TailDupPlacementThreshold.getNumOccurrences() == 0) 26745517e702SDimitry Andric TailDupSize = TailDupPlacementAggressiveThreshold; 26755517e702SDimitry Andric 26765517e702SDimitry Andric TargetPassConfig *PassConfig = &getAnalysis<TargetPassConfig>(); 26775517e702SDimitry Andric // For agressive optimization, we can adjust some thresholds to be less 26785517e702SDimitry Andric // conservative. 26795517e702SDimitry Andric if (PassConfig->getOptLevel() >= CodeGenOpt::Aggressive) { 26805517e702SDimitry Andric // At O3 we should be more willing to copy blocks for tail duplication. This 26815517e702SDimitry Andric // increases size pressure, so we only do it at O3 26825517e702SDimitry Andric // Do this unless only the regular threshold is explicitly set. 26835517e702SDimitry Andric if (TailDupPlacementThreshold.getNumOccurrences() == 0 || 26845517e702SDimitry Andric TailDupPlacementAggressiveThreshold.getNumOccurrences() != 0) 26855517e702SDimitry Andric TailDupSize = TailDupPlacementAggressiveThreshold; 26865517e702SDimitry Andric } 26875517e702SDimitry Andric 2688d88c1a5aSDimitry Andric if (TailDupPlacement) { 26897a7e6055SDimitry Andric MPDT = &getAnalysis<MachinePostDominatorTree>(); 2690d88c1a5aSDimitry Andric if (MF.getFunction()->optForSize()) 2691d88c1a5aSDimitry Andric TailDupSize = 1; 2692d88c1a5aSDimitry Andric TailDup.initMF(MF, MBPI, /* LayoutMode */ true, TailDupSize); 26937a7e6055SDimitry Andric precomputeTriangleChains(); 2694d88c1a5aSDimitry Andric } 2695d88c1a5aSDimitry Andric 26963ca95b02SDimitry Andric buildCFGChains(); 26973ca95b02SDimitry Andric 26983ca95b02SDimitry Andric // Changing the layout can create new tail merging opportunities. 26993ca95b02SDimitry Andric // TailMerge can create jump into if branches that make CFG irreducible for 27003ca95b02SDimitry Andric // HW that requires structured CFG. 27013ca95b02SDimitry Andric bool EnableTailMerge = !MF.getTarget().requiresStructuredCFG() && 27023ca95b02SDimitry Andric PassConfig->getEnableTailMerge() && 27033ca95b02SDimitry Andric BranchFoldPlacement; 27043ca95b02SDimitry Andric // No tail merging opportunities if the block number is less than four. 27053ca95b02SDimitry Andric if (MF.size() > 3 && EnableTailMerge) { 27065517e702SDimitry Andric unsigned TailMergeSize = TailDupSize + 1; 27073ca95b02SDimitry Andric BranchFolder BF(/*EnableTailMerge=*/true, /*CommonHoist=*/false, *MBFI, 2708d88c1a5aSDimitry Andric *MBPI, TailMergeSize); 27093ca95b02SDimitry Andric 27103ca95b02SDimitry Andric if (BF.OptimizeFunction(MF, TII, MF.getSubtarget().getRegisterInfo(), 27113ca95b02SDimitry Andric getAnalysisIfAvailable<MachineModuleInfo>(), MLI, 27123ca95b02SDimitry Andric /*AfterBlockPlacement=*/true)) { 27133ca95b02SDimitry Andric // Redo the layout if tail merging creates/removes/moves blocks. 27143ca95b02SDimitry Andric BlockToChain.clear(); 27157a7e6055SDimitry Andric ComputedEdges.clear(); 27167a7e6055SDimitry Andric // Must redo the post-dominator tree if blocks were changed. 27177a7e6055SDimitry Andric if (MPDT) 27187a7e6055SDimitry Andric MPDT->runOnMachineFunction(MF); 27193ca95b02SDimitry Andric ChainAllocator.DestroyAll(); 27203ca95b02SDimitry Andric buildCFGChains(); 27213ca95b02SDimitry Andric } 27223ca95b02SDimitry Andric } 27233ca95b02SDimitry Andric 27243ca95b02SDimitry Andric optimizeBranches(); 27253ca95b02SDimitry Andric alignBlocks(); 2726dff0c46cSDimitry Andric 2727dff0c46cSDimitry Andric BlockToChain.clear(); 27287a7e6055SDimitry Andric ComputedEdges.clear(); 2729dff0c46cSDimitry Andric ChainAllocator.DestroyAll(); 2730dff0c46cSDimitry Andric 2731284c1978SDimitry Andric if (AlignAllBlock) 2732284c1978SDimitry Andric // Align all of the blocks in the function to a specific alignment. 27333ca95b02SDimitry Andric for (MachineBasicBlock &MBB : MF) 2734ff0cc061SDimitry Andric MBB.setAlignment(AlignAllBlock); 27353ca95b02SDimitry Andric else if (AlignAllNonFallThruBlocks) { 27363ca95b02SDimitry Andric // Align all of the blocks that have no fall-through predecessors to a 27373ca95b02SDimitry Andric // specific alignment. 27383ca95b02SDimitry Andric for (auto MBI = std::next(MF.begin()), MBE = MF.end(); MBI != MBE; ++MBI) { 27393ca95b02SDimitry Andric auto LayoutPred = std::prev(MBI); 27403ca95b02SDimitry Andric if (!LayoutPred->isSuccessor(&*MBI)) 27413ca95b02SDimitry Andric MBI->setAlignment(AlignAllNonFallThruBlocks); 27423ca95b02SDimitry Andric } 27433ca95b02SDimitry Andric } 27447a7e6055SDimitry Andric if (ViewBlockLayoutWithBFI != GVDT_None && 27457a7e6055SDimitry Andric (ViewBlockFreqFuncName.empty() || 27467a7e6055SDimitry Andric F->getFunction()->getName().equals(ViewBlockFreqFuncName))) { 27477a7e6055SDimitry Andric MBFI->view("MBP." + MF.getName(), false); 27487a7e6055SDimitry Andric } 27497a7e6055SDimitry Andric 2750284c1978SDimitry Andric 2751dff0c46cSDimitry Andric // We always return true as we have no way to track whether the final order 2752dff0c46cSDimitry Andric // differs from the original order. 2753dff0c46cSDimitry Andric return true; 2754dff0c46cSDimitry Andric } 2755dff0c46cSDimitry Andric 2756dff0c46cSDimitry Andric namespace { 2757dff0c46cSDimitry Andric /// \brief A pass to compute block placement statistics. 2758dff0c46cSDimitry Andric /// 2759dff0c46cSDimitry Andric /// A separate pass to compute interesting statistics for evaluating block 2760dff0c46cSDimitry Andric /// placement. This is separate from the actual placement pass so that they can 27617ae0e2c9SDimitry Andric /// be computed in the absence of any placement transformations or when using 2762dff0c46cSDimitry Andric /// alternative placement strategies. 2763dff0c46cSDimitry Andric class MachineBlockPlacementStats : public MachineFunctionPass { 2764dff0c46cSDimitry Andric /// \brief A handle to the branch probability pass. 2765dff0c46cSDimitry Andric const MachineBranchProbabilityInfo *MBPI; 2766dff0c46cSDimitry Andric 2767dff0c46cSDimitry Andric /// \brief A handle to the function-wide block frequency pass. 2768dff0c46cSDimitry Andric const MachineBlockFrequencyInfo *MBFI; 2769dff0c46cSDimitry Andric 2770dff0c46cSDimitry Andric public: 2771dff0c46cSDimitry Andric static char ID; // Pass identification, replacement for typeid 2772dff0c46cSDimitry Andric MachineBlockPlacementStats() : MachineFunctionPass(ID) { 2773dff0c46cSDimitry Andric initializeMachineBlockPlacementStatsPass(*PassRegistry::getPassRegistry()); 2774dff0c46cSDimitry Andric } 2775dff0c46cSDimitry Andric 277691bc56edSDimitry Andric bool runOnMachineFunction(MachineFunction &F) override; 2777dff0c46cSDimitry Andric 277891bc56edSDimitry Andric void getAnalysisUsage(AnalysisUsage &AU) const override { 2779dff0c46cSDimitry Andric AU.addRequired<MachineBranchProbabilityInfo>(); 2780dff0c46cSDimitry Andric AU.addRequired<MachineBlockFrequencyInfo>(); 2781dff0c46cSDimitry Andric AU.setPreservesAll(); 2782dff0c46cSDimitry Andric MachineFunctionPass::getAnalysisUsage(AU); 2783dff0c46cSDimitry Andric } 2784dff0c46cSDimitry Andric }; 27853dac3a9bSDimitry Andric } 2786dff0c46cSDimitry Andric 2787dff0c46cSDimitry Andric char MachineBlockPlacementStats::ID = 0; 2788dff0c46cSDimitry Andric char &llvm::MachineBlockPlacementStatsID = MachineBlockPlacementStats::ID; 2789dff0c46cSDimitry Andric INITIALIZE_PASS_BEGIN(MachineBlockPlacementStats, "block-placement-stats", 2790dff0c46cSDimitry Andric "Basic Block Placement Stats", false, false) 2791dff0c46cSDimitry Andric INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo) 2792dff0c46cSDimitry Andric INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo) 2793dff0c46cSDimitry Andric INITIALIZE_PASS_END(MachineBlockPlacementStats, "block-placement-stats", 2794dff0c46cSDimitry Andric "Basic Block Placement Stats", false, false) 2795dff0c46cSDimitry Andric 2796dff0c46cSDimitry Andric bool MachineBlockPlacementStats::runOnMachineFunction(MachineFunction &F) { 2797dff0c46cSDimitry Andric // Check for single-block functions and skip them. 279891bc56edSDimitry Andric if (std::next(F.begin()) == F.end()) 2799dff0c46cSDimitry Andric return false; 2800dff0c46cSDimitry Andric 2801dff0c46cSDimitry Andric MBPI = &getAnalysis<MachineBranchProbabilityInfo>(); 2802dff0c46cSDimitry Andric MBFI = &getAnalysis<MachineBlockFrequencyInfo>(); 2803dff0c46cSDimitry Andric 2804ff0cc061SDimitry Andric for (MachineBasicBlock &MBB : F) { 2805ff0cc061SDimitry Andric BlockFrequency BlockFreq = MBFI->getBlockFreq(&MBB); 2806ff0cc061SDimitry Andric Statistic &NumBranches = 2807ff0cc061SDimitry Andric (MBB.succ_size() > 1) ? NumCondBranches : NumUncondBranches; 2808ff0cc061SDimitry Andric Statistic &BranchTakenFreq = 2809ff0cc061SDimitry Andric (MBB.succ_size() > 1) ? CondBranchTakenFreq : UncondBranchTakenFreq; 2810ff0cc061SDimitry Andric for (MachineBasicBlock *Succ : MBB.successors()) { 2811dff0c46cSDimitry Andric // Skip if this successor is a fallthrough. 2812ff0cc061SDimitry Andric if (MBB.isLayoutSuccessor(Succ)) 2813dff0c46cSDimitry Andric continue; 2814dff0c46cSDimitry Andric 2815ff0cc061SDimitry Andric BlockFrequency EdgeFreq = 2816ff0cc061SDimitry Andric BlockFreq * MBPI->getEdgeProbability(&MBB, Succ); 2817dff0c46cSDimitry Andric ++NumBranches; 2818dff0c46cSDimitry Andric BranchTakenFreq += EdgeFreq.getFrequency(); 2819dff0c46cSDimitry Andric } 2820dff0c46cSDimitry Andric } 2821dff0c46cSDimitry Andric 2822dff0c46cSDimitry Andric return false; 2823dff0c46cSDimitry Andric } 2824