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