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