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/CodeGen/TailDuplicator.h" 44 #include "llvm/Support/Allocator.h" 45 #include "llvm/Support/CommandLine.h" 46 #include "llvm/Support/Debug.h" 47 #include "llvm/Support/raw_ostream.h" 48 #include "llvm/Target/TargetInstrInfo.h" 49 #include "llvm/Target/TargetLowering.h" 50 #include "llvm/Target/TargetSubtargetInfo.h" 51 #include <algorithm> 52 using namespace llvm; 53 54 #define DEBUG_TYPE "block-placement" 55 56 STATISTIC(NumCondBranches, "Number of conditional branches"); 57 STATISTIC(NumUncondBranches, "Number of unconditional branches"); 58 STATISTIC(CondBranchTakenFreq, 59 "Potential frequency of taking conditional branches"); 60 STATISTIC(UncondBranchTakenFreq, 61 "Potential frequency of taking unconditional branches"); 62 63 static cl::opt<unsigned> AlignAllBlock("align-all-blocks", 64 cl::desc("Force the alignment of all " 65 "blocks in the function."), 66 cl::init(0), cl::Hidden); 67 68 static cl::opt<unsigned> AlignAllNonFallThruBlocks( 69 "align-all-nofallthru-blocks", 70 cl::desc("Force the alignment of all " 71 "blocks that have no fall-through predecessors (i.e. don't add " 72 "nops that are executed)."), 73 cl::init(0), cl::Hidden); 74 75 // FIXME: Find a good default for this flag and remove the flag. 76 static cl::opt<unsigned> ExitBlockBias( 77 "block-placement-exit-block-bias", 78 cl::desc("Block frequency percentage a loop exit block needs " 79 "over the original exit to be considered the new exit."), 80 cl::init(0), cl::Hidden); 81 82 // Definition: 83 // - Outlining: placement of a basic block outside the chain or hot path. 84 85 static cl::opt<bool> OutlineOptionalBranches( 86 "outline-optional-branches", 87 cl::desc("Outlining optional branches will place blocks that are optional " 88 "branches, i.e. branches with a common post dominator, outside " 89 "the hot path or chain"), 90 cl::init(false), cl::Hidden); 91 92 static cl::opt<unsigned> OutlineOptionalThreshold( 93 "outline-optional-threshold", 94 cl::desc("Don't outline optional branches that are a single block with an " 95 "instruction count below this threshold"), 96 cl::init(4), cl::Hidden); 97 98 static cl::opt<unsigned> LoopToColdBlockRatio( 99 "loop-to-cold-block-ratio", 100 cl::desc("Outline loop blocks from loop chain if (frequency of loop) / " 101 "(frequency of block) is greater than this ratio"), 102 cl::init(5), cl::Hidden); 103 104 static cl::opt<bool> 105 PreciseRotationCost("precise-rotation-cost", 106 cl::desc("Model the cost of loop rotation more " 107 "precisely by using profile data."), 108 cl::init(false), cl::Hidden); 109 static cl::opt<bool> 110 ForcePreciseRotationCost("force-precise-rotation-cost", 111 cl::desc("Force the use of precise cost " 112 "loop rotation strategy."), 113 cl::init(false), cl::Hidden); 114 115 static cl::opt<unsigned> MisfetchCost( 116 "misfetch-cost", 117 cl::desc("Cost that models the probabilistic risk of an instruction " 118 "misfetch due to a jump comparing to falling through, whose cost " 119 "is zero."), 120 cl::init(1), cl::Hidden); 121 122 static cl::opt<unsigned> JumpInstCost("jump-inst-cost", 123 cl::desc("Cost of jump instructions."), 124 cl::init(1), cl::Hidden); 125 static cl::opt<bool> 126 TailDupPlacement("tail-dup-placement", 127 cl::desc("Perform tail duplication during placement. " 128 "Creates more fallthrough opportunites in " 129 "outline branches."), 130 cl::init(true), cl::Hidden); 131 132 static cl::opt<bool> 133 BranchFoldPlacement("branch-fold-placement", 134 cl::desc("Perform branch folding during placement. " 135 "Reduces code size."), 136 cl::init(true), cl::Hidden); 137 138 // Heuristic for tail duplication. 139 static cl::opt<unsigned> TailDuplicatePlacementThreshold( 140 "tail-dup-placement-threshold", 141 cl::desc("Instruction cutoff for tail duplication during layout. " 142 "Tail merging during layout is forced to have a threshold " 143 "that won't conflict."), cl::init(2), 144 cl::Hidden); 145 146 extern cl::opt<unsigned> StaticLikelyProb; 147 extern cl::opt<unsigned> ProfileLikelyProb; 148 149 namespace { 150 class BlockChain; 151 /// \brief Type for our function-wide basic block -> block chain mapping. 152 typedef DenseMap<MachineBasicBlock *, BlockChain *> BlockToChainMapType; 153 } 154 155 namespace { 156 /// \brief A chain of blocks which will be laid out contiguously. 157 /// 158 /// This is the datastructure representing a chain of consecutive blocks that 159 /// are profitable to layout together in order to maximize fallthrough 160 /// probabilities and code locality. We also can use a block chain to represent 161 /// a sequence of basic blocks which have some external (correctness) 162 /// requirement for sequential layout. 163 /// 164 /// Chains can be built around a single basic block and can be merged to grow 165 /// them. They participate in a block-to-chain mapping, which is updated 166 /// automatically as chains are merged together. 167 class BlockChain { 168 /// \brief The sequence of blocks belonging to this chain. 169 /// 170 /// This is the sequence of blocks for a particular chain. These will be laid 171 /// out in-order within the function. 172 SmallVector<MachineBasicBlock *, 4> Blocks; 173 174 /// \brief A handle to the function-wide basic block to block chain mapping. 175 /// 176 /// This is retained in each block chain to simplify the computation of child 177 /// block chains for SCC-formation and iteration. We store the edges to child 178 /// basic blocks, and map them back to their associated chains using this 179 /// structure. 180 BlockToChainMapType &BlockToChain; 181 182 public: 183 /// \brief Construct a new BlockChain. 184 /// 185 /// This builds a new block chain representing a single basic block in the 186 /// function. It also registers itself as the chain that block participates 187 /// in with the BlockToChain mapping. 188 BlockChain(BlockToChainMapType &BlockToChain, MachineBasicBlock *BB) 189 : Blocks(1, BB), BlockToChain(BlockToChain), UnscheduledPredecessors(0) { 190 assert(BB && "Cannot create a chain with a null basic block"); 191 BlockToChain[BB] = this; 192 } 193 194 /// \brief Iterator over blocks within the chain. 195 typedef SmallVectorImpl<MachineBasicBlock *>::iterator iterator; 196 197 /// \brief Beginning of blocks within the chain. 198 iterator begin() { return Blocks.begin(); } 199 200 /// \brief End of blocks within the chain. 201 iterator end() { return Blocks.end(); } 202 203 bool remove(MachineBasicBlock* BB) { 204 for(iterator i = begin(); i != end(); ++i) { 205 if (*i == BB) { 206 Blocks.erase(i); 207 return true; 208 } 209 } 210 return false; 211 } 212 213 /// \brief Merge a block chain into this one. 214 /// 215 /// This routine merges a block chain into this one. It takes care of forming 216 /// a contiguous sequence of basic blocks, updating the edge list, and 217 /// updating the block -> chain mapping. It does not free or tear down the 218 /// old chain, but the old chain's block list is no longer valid. 219 void merge(MachineBasicBlock *BB, BlockChain *Chain) { 220 assert(BB); 221 assert(!Blocks.empty()); 222 223 // Fast path in case we don't have a chain already. 224 if (!Chain) { 225 assert(!BlockToChain[BB]); 226 Blocks.push_back(BB); 227 BlockToChain[BB] = this; 228 return; 229 } 230 231 assert(BB == *Chain->begin()); 232 assert(Chain->begin() != Chain->end()); 233 234 // Update the incoming blocks to point to this chain, and add them to the 235 // chain structure. 236 for (MachineBasicBlock *ChainBB : *Chain) { 237 Blocks.push_back(ChainBB); 238 assert(BlockToChain[ChainBB] == Chain && "Incoming blocks not in chain"); 239 BlockToChain[ChainBB] = this; 240 } 241 } 242 243 #ifndef NDEBUG 244 /// \brief Dump the blocks in this chain. 245 LLVM_DUMP_METHOD void dump() { 246 for (MachineBasicBlock *MBB : *this) 247 MBB->dump(); 248 } 249 #endif // NDEBUG 250 251 /// \brief Count of predecessors of any block within the chain which have not 252 /// yet been scheduled. In general, we will delay scheduling this chain 253 /// until those predecessors are scheduled (or we find a sufficiently good 254 /// reason to override this heuristic.) Note that when forming loop chains, 255 /// blocks outside the loop are ignored and treated as if they were already 256 /// scheduled. 257 /// 258 /// Note: This field is reinitialized multiple times - once for each loop, 259 /// and then once for the function as a whole. 260 unsigned UnscheduledPredecessors; 261 }; 262 } 263 264 namespace { 265 class MachineBlockPlacement : public MachineFunctionPass { 266 /// \brief A typedef for a block filter set. 267 typedef SmallSetVector<MachineBasicBlock *, 16> BlockFilterSet; 268 269 /// \brief work lists of blocks that are ready to be laid out 270 SmallVector<MachineBasicBlock *, 16> BlockWorkList; 271 SmallVector<MachineBasicBlock *, 16> EHPadWorkList; 272 273 /// \brief Machine Function 274 MachineFunction *F; 275 276 /// \brief A handle to the branch probability pass. 277 const MachineBranchProbabilityInfo *MBPI; 278 279 /// \brief A handle to the function-wide block frequency pass. 280 std::unique_ptr<BranchFolder::MBFIWrapper> MBFI; 281 282 /// \brief A handle to the loop info. 283 MachineLoopInfo *MLI; 284 285 /// \brief Preferred loop exit. 286 /// Member variable for convenience. It may be removed by duplication deep 287 /// in the call stack. 288 MachineBasicBlock *PreferredLoopExit; 289 290 /// \brief A handle to the target's instruction info. 291 const TargetInstrInfo *TII; 292 293 /// \brief A handle to the target's lowering info. 294 const TargetLoweringBase *TLI; 295 296 /// \brief A handle to the post dominator tree. 297 MachineDominatorTree *MDT; 298 299 /// \brief Duplicator used to duplicate tails during placement. 300 /// 301 /// Placement decisions can open up new tail duplication opportunities, but 302 /// since tail duplication affects placement decisions of later blocks, it 303 /// must be done inline. 304 TailDuplicator TailDup; 305 306 /// \brief A set of blocks that are unavoidably execute, i.e. they dominate 307 /// all terminators of the MachineFunction. 308 SmallPtrSet<MachineBasicBlock *, 4> UnavoidableBlocks; 309 310 /// \brief Allocator and owner of BlockChain structures. 311 /// 312 /// We build BlockChains lazily while processing the loop structure of 313 /// a function. To reduce malloc traffic, we allocate them using this 314 /// slab-like allocator, and destroy them after the pass completes. An 315 /// important guarantee is that this allocator produces stable pointers to 316 /// the chains. 317 SpecificBumpPtrAllocator<BlockChain> ChainAllocator; 318 319 /// \brief Function wide BasicBlock to BlockChain mapping. 320 /// 321 /// This mapping allows efficiently moving from any given basic block to the 322 /// BlockChain it participates in, if any. We use it to, among other things, 323 /// allow implicitly defining edges between chains as the existing edges 324 /// between basic blocks. 325 DenseMap<MachineBasicBlock *, BlockChain *> BlockToChain; 326 327 #ifndef NDEBUG 328 /// The set of basic blocks that have terminators that cannot be fully 329 /// analyzed. These basic blocks cannot be re-ordered safely by 330 /// MachineBlockPlacement, and we must preserve physical layout of these 331 /// blocks and their successors through the pass. 332 SmallPtrSet<MachineBasicBlock *, 4> BlocksWithUnanalyzableExits; 333 #endif 334 335 /// Decrease the UnscheduledPredecessors count for all blocks in chain, and 336 /// if the count goes to 0, add them to the appropriate work list. 337 void markChainSuccessors(BlockChain &Chain, MachineBasicBlock *LoopHeaderBB, 338 const BlockFilterSet *BlockFilter = nullptr); 339 340 /// Decrease the UnscheduledPredecessors count for a single block, and 341 /// if the count goes to 0, add them to the appropriate work list. 342 void markBlockSuccessors( 343 BlockChain &Chain, MachineBasicBlock *BB, MachineBasicBlock *LoopHeaderBB, 344 const BlockFilterSet *BlockFilter = nullptr); 345 346 347 BranchProbability 348 collectViableSuccessors(MachineBasicBlock *BB, BlockChain &Chain, 349 const BlockFilterSet *BlockFilter, 350 SmallVector<MachineBasicBlock *, 4> &Successors); 351 bool shouldPredBlockBeOutlined(MachineBasicBlock *BB, MachineBasicBlock *Succ, 352 BlockChain &Chain, 353 const BlockFilterSet *BlockFilter, 354 BranchProbability SuccProb, 355 BranchProbability HotProb); 356 bool repeatedlyTailDuplicateBlock( 357 MachineBasicBlock *BB, MachineBasicBlock *&LPred, 358 MachineBasicBlock *LoopHeaderBB, 359 BlockChain &Chain, BlockFilterSet *BlockFilter, 360 MachineFunction::iterator &PrevUnplacedBlockIt); 361 bool maybeTailDuplicateBlock(MachineBasicBlock *BB, MachineBasicBlock *LPred, 362 const BlockChain &Chain, 363 BlockFilterSet *BlockFilter, 364 MachineFunction::iterator &PrevUnplacedBlockIt, 365 bool &DuplicatedToPred); 366 bool 367 hasBetterLayoutPredecessor(MachineBasicBlock *BB, MachineBasicBlock *Succ, 368 BlockChain &SuccChain, BranchProbability SuccProb, 369 BranchProbability RealSuccProb, BlockChain &Chain, 370 const BlockFilterSet *BlockFilter); 371 MachineBasicBlock *selectBestSuccessor(MachineBasicBlock *BB, 372 BlockChain &Chain, 373 const BlockFilterSet *BlockFilter); 374 MachineBasicBlock * 375 selectBestCandidateBlock(BlockChain &Chain, 376 SmallVectorImpl<MachineBasicBlock *> &WorkList); 377 MachineBasicBlock * 378 getFirstUnplacedBlock(const BlockChain &PlacedChain, 379 MachineFunction::iterator &PrevUnplacedBlockIt, 380 const BlockFilterSet *BlockFilter); 381 382 /// \brief Add a basic block to the work list if it is appropriate. 383 /// 384 /// If the optional parameter BlockFilter is provided, only MBB 385 /// present in the set will be added to the worklist. If nullptr 386 /// is provided, no filtering occurs. 387 void fillWorkLists(MachineBasicBlock *MBB, 388 SmallPtrSetImpl<BlockChain *> &UpdatedPreds, 389 const BlockFilterSet *BlockFilter); 390 void buildChain(MachineBasicBlock *BB, BlockChain &Chain, 391 BlockFilterSet *BlockFilter = nullptr); 392 MachineBasicBlock *findBestLoopTop(MachineLoop &L, 393 const BlockFilterSet &LoopBlockSet); 394 MachineBasicBlock *findBestLoopExit(MachineLoop &L, 395 const BlockFilterSet &LoopBlockSet); 396 BlockFilterSet collectLoopBlockSet(MachineLoop &L); 397 void buildLoopChains(MachineLoop &L); 398 void rotateLoop(BlockChain &LoopChain, MachineBasicBlock *ExitingBB, 399 const BlockFilterSet &LoopBlockSet); 400 void rotateLoopWithProfile(BlockChain &LoopChain, MachineLoop &L, 401 const BlockFilterSet &LoopBlockSet); 402 void collectMustExecuteBBs(); 403 void buildCFGChains(); 404 void optimizeBranches(); 405 void alignBlocks(); 406 bool shouldTailDuplicate(MachineBasicBlock *BB); 407 bool canTailDuplicateUnplacedPreds( 408 MachineBasicBlock *BB, MachineBasicBlock *Succ, 409 BlockChain &Chain, const BlockFilterSet *BlockFilter); 410 411 public: 412 static char ID; // Pass identification, replacement for typeid 413 MachineBlockPlacement() : MachineFunctionPass(ID) { 414 initializeMachineBlockPlacementPass(*PassRegistry::getPassRegistry()); 415 } 416 417 bool runOnMachineFunction(MachineFunction &F) override; 418 419 void getAnalysisUsage(AnalysisUsage &AU) const override { 420 AU.addRequired<MachineBranchProbabilityInfo>(); 421 AU.addRequired<MachineBlockFrequencyInfo>(); 422 AU.addRequired<MachineDominatorTree>(); 423 AU.addRequired<MachineLoopInfo>(); 424 AU.addRequired<TargetPassConfig>(); 425 MachineFunctionPass::getAnalysisUsage(AU); 426 } 427 }; 428 } 429 430 char MachineBlockPlacement::ID = 0; 431 char &llvm::MachineBlockPlacementID = MachineBlockPlacement::ID; 432 INITIALIZE_PASS_BEGIN(MachineBlockPlacement, "block-placement", 433 "Branch Probability Basic Block Placement", false, false) 434 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo) 435 INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo) 436 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree) 437 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo) 438 INITIALIZE_PASS_END(MachineBlockPlacement, "block-placement", 439 "Branch Probability Basic Block Placement", false, false) 440 441 #ifndef NDEBUG 442 /// \brief Helper to print the name of a MBB. 443 /// 444 /// Only used by debug logging. 445 static std::string getBlockName(MachineBasicBlock *BB) { 446 std::string Result; 447 raw_string_ostream OS(Result); 448 OS << "BB#" << BB->getNumber(); 449 OS << " ('" << BB->getName() << "')"; 450 OS.flush(); 451 return Result; 452 } 453 #endif 454 455 /// \brief Mark a chain's successors as having one fewer preds. 456 /// 457 /// When a chain is being merged into the "placed" chain, this routine will 458 /// quickly walk the successors of each block in the chain and mark them as 459 /// having one fewer active predecessor. It also adds any successors of this 460 /// chain which reach the zero-predecessor state to the appropriate worklist. 461 void MachineBlockPlacement::markChainSuccessors( 462 BlockChain &Chain, MachineBasicBlock *LoopHeaderBB, 463 const BlockFilterSet *BlockFilter) { 464 // Walk all the blocks in this chain, marking their successors as having 465 // a predecessor placed. 466 for (MachineBasicBlock *MBB : Chain) { 467 markBlockSuccessors(Chain, MBB, LoopHeaderBB, BlockFilter); 468 } 469 } 470 471 /// \brief Mark a single block's successors as having one fewer preds. 472 /// 473 /// Under normal circumstances, this is only called by markChainSuccessors, 474 /// but if a block that was to be placed is completely tail-duplicated away, 475 /// and was duplicated into the chain end, we need to redo markBlockSuccessors 476 /// for just that block. 477 void MachineBlockPlacement::markBlockSuccessors( 478 BlockChain &Chain, MachineBasicBlock *MBB, MachineBasicBlock *LoopHeaderBB, 479 const BlockFilterSet *BlockFilter) { 480 // Add any successors for which this is the only un-placed in-loop 481 // predecessor to the worklist as a viable candidate for CFG-neutral 482 // placement. No subsequent placement of this block will violate the CFG 483 // shape, so we get to use heuristics to choose a favorable placement. 484 for (MachineBasicBlock *Succ : MBB->successors()) { 485 if (BlockFilter && !BlockFilter->count(Succ)) 486 continue; 487 BlockChain &SuccChain = *BlockToChain[Succ]; 488 // Disregard edges within a fixed chain, or edges to the loop header. 489 if (&Chain == &SuccChain || Succ == LoopHeaderBB) 490 continue; 491 492 // This is a cross-chain edge that is within the loop, so decrement the 493 // loop predecessor count of the destination chain. 494 if (SuccChain.UnscheduledPredecessors == 0 || 495 --SuccChain.UnscheduledPredecessors > 0) 496 continue; 497 498 auto *NewBB = *SuccChain.begin(); 499 if (NewBB->isEHPad()) 500 EHPadWorkList.push_back(NewBB); 501 else 502 BlockWorkList.push_back(NewBB); 503 } 504 } 505 506 /// This helper function collects the set of successors of block 507 /// \p BB that are allowed to be its layout successors, and return 508 /// the total branch probability of edges from \p BB to those 509 /// blocks. 510 BranchProbability MachineBlockPlacement::collectViableSuccessors( 511 MachineBasicBlock *BB, BlockChain &Chain, const BlockFilterSet *BlockFilter, 512 SmallVector<MachineBasicBlock *, 4> &Successors) { 513 // Adjust edge probabilities by excluding edges pointing to blocks that is 514 // either not in BlockFilter or is already in the current chain. Consider the 515 // following CFG: 516 // 517 // --->A 518 // | / \ 519 // | B C 520 // | \ / \ 521 // ----D E 522 // 523 // Assume A->C is very hot (>90%), and C->D has a 50% probability, then after 524 // A->C is chosen as a fall-through, D won't be selected as a successor of C 525 // due to CFG constraint (the probability of C->D is not greater than 526 // HotProb to break top-order). If we exclude E that is not in BlockFilter 527 // when calculating the probability of C->D, D will be selected and we 528 // will get A C D B as the layout of this loop. 529 auto AdjustedSumProb = BranchProbability::getOne(); 530 for (MachineBasicBlock *Succ : BB->successors()) { 531 bool SkipSucc = false; 532 if (Succ->isEHPad() || (BlockFilter && !BlockFilter->count(Succ))) { 533 SkipSucc = true; 534 } else { 535 BlockChain *SuccChain = BlockToChain[Succ]; 536 if (SuccChain == &Chain) { 537 SkipSucc = true; 538 } else if (Succ != *SuccChain->begin()) { 539 DEBUG(dbgs() << " " << getBlockName(Succ) << " -> Mid chain!\n"); 540 continue; 541 } 542 } 543 if (SkipSucc) 544 AdjustedSumProb -= MBPI->getEdgeProbability(BB, Succ); 545 else 546 Successors.push_back(Succ); 547 } 548 549 return AdjustedSumProb; 550 } 551 552 /// The helper function returns the branch probability that is adjusted 553 /// or normalized over the new total \p AdjustedSumProb. 554 static BranchProbability 555 getAdjustedProbability(BranchProbability OrigProb, 556 BranchProbability AdjustedSumProb) { 557 BranchProbability SuccProb; 558 uint32_t SuccProbN = OrigProb.getNumerator(); 559 uint32_t SuccProbD = AdjustedSumProb.getNumerator(); 560 if (SuccProbN >= SuccProbD) 561 SuccProb = BranchProbability::getOne(); 562 else 563 SuccProb = BranchProbability(SuccProbN, SuccProbD); 564 565 return SuccProb; 566 } 567 568 /// Check if a block should be tail duplicated. 569 /// \p BB Block to check. 570 bool MachineBlockPlacement::shouldTailDuplicate(MachineBasicBlock *BB) { 571 // Blocks with single successors don't create additional fallthrough 572 // opportunities. Don't duplicate them. TODO: When conditional exits are 573 // analyzable, allow them to be duplicated. 574 bool IsSimple = TailDup.isSimpleBB(BB); 575 576 if (BB->succ_size() == 1) 577 return false; 578 return TailDup.shouldTailDuplicate(IsSimple, *BB); 579 } 580 581 /// When the option TailDupPlacement is on, this method checks if the 582 /// fallthrough candidate block \p Succ (of block \p BB) can be tail-duplicated 583 /// into all of its unplaced, unfiltered predecessors, that are not BB. In 584 /// addition we keep a set of blocks that have been tail-duplicated into and 585 /// allow those blocks to be unplaced as well. This allows the creation of a 586 /// second (larger) spine and a short fallthrough spine. 587 /// We also identify blocks with the CFG that would have been produced by 588 /// tail-duplication and lay them out in the same manner. 589 bool MachineBlockPlacement::canTailDuplicateUnplacedPreds( 590 MachineBasicBlock *BB, MachineBasicBlock *Succ, BlockChain &Chain, 591 const BlockFilterSet *BlockFilter) { 592 if (!shouldTailDuplicate(Succ)) 593 return false; 594 595 for (MachineBasicBlock *Pred : Succ->predecessors()) { 596 // Make sure all unplaced and unfiltered predecessors can be 597 // tail-duplicated into. 598 if (Pred == BB || (BlockFilter && !BlockFilter->count(Pred)) 599 || BlockToChain[Pred] == &Chain) 600 continue; 601 if (!TailDup.canTailDuplicate(Succ, Pred)) 602 return false; 603 } 604 return true; 605 } 606 607 /// When the option OutlineOptionalBranches is on, this method 608 /// checks if the fallthrough candidate block \p Succ (of block 609 /// \p BB) also has other unscheduled predecessor blocks which 610 /// are also successors of \p BB (forming triangular shape CFG). 611 /// If none of such predecessors are small, it returns true. 612 /// The caller can choose to select \p Succ as the layout successors 613 /// so that \p Succ's predecessors (optional branches) can be 614 /// outlined. 615 /// FIXME: fold this with more general layout cost analysis. 616 bool MachineBlockPlacement::shouldPredBlockBeOutlined( 617 MachineBasicBlock *BB, MachineBasicBlock *Succ, BlockChain &Chain, 618 const BlockFilterSet *BlockFilter, BranchProbability SuccProb, 619 BranchProbability HotProb) { 620 if (!OutlineOptionalBranches) 621 return false; 622 // If we outline optional branches, look whether Succ is unavoidable, i.e. 623 // dominates all terminators of the MachineFunction. If it does, other 624 // successors must be optional. Don't do this for cold branches. 625 if (SuccProb > HotProb.getCompl() && UnavoidableBlocks.count(Succ) > 0) { 626 for (MachineBasicBlock *Pred : Succ->predecessors()) { 627 // Check whether there is an unplaced optional branch. 628 if (Pred == Succ || (BlockFilter && !BlockFilter->count(Pred)) || 629 BlockToChain[Pred] == &Chain) 630 continue; 631 // Check whether the optional branch has exactly one BB. 632 if (Pred->pred_size() > 1 || *Pred->pred_begin() != BB) 633 continue; 634 // Check whether the optional branch is small. 635 if (Pred->size() < OutlineOptionalThreshold) 636 return false; 637 } 638 return true; 639 } else 640 return false; 641 } 642 643 // When profile is not present, return the StaticLikelyProb. 644 // When profile is available, we need to handle the triangle-shape CFG. 645 static BranchProbability getLayoutSuccessorProbThreshold( 646 MachineBasicBlock *BB) { 647 if (!BB->getParent()->getFunction()->getEntryCount()) 648 return BranchProbability(StaticLikelyProb, 100); 649 if (BB->succ_size() == 2) { 650 const MachineBasicBlock *Succ1 = *BB->succ_begin(); 651 const MachineBasicBlock *Succ2 = *(BB->succ_begin() + 1); 652 if (Succ1->isSuccessor(Succ2) || Succ2->isSuccessor(Succ1)) { 653 /* See case 1 below for the cost analysis. For BB->Succ to 654 * be taken with smaller cost, the following needs to hold: 655 * Prob(BB->Succ) > 2* Prob(BB->Pred) 656 * So the threshold T 657 * T = 2 * (1-Prob(BB->Pred). Since T + Prob(BB->Pred) == 1, 658 * We have T + T/2 = 1, i.e. T = 2/3. Also adding user specified 659 * branch bias, we have 660 * T = (2/3)*(ProfileLikelyProb/50) 661 * = (2*ProfileLikelyProb)/150) 662 */ 663 return BranchProbability(2 * ProfileLikelyProb, 150); 664 } 665 } 666 return BranchProbability(ProfileLikelyProb, 100); 667 } 668 669 /// Checks to see if the layout candidate block \p Succ has a better layout 670 /// predecessor than \c BB. If yes, returns true. 671 bool MachineBlockPlacement::hasBetterLayoutPredecessor( 672 MachineBasicBlock *BB, MachineBasicBlock *Succ, BlockChain &SuccChain, 673 BranchProbability SuccProb, BranchProbability RealSuccProb, 674 BlockChain &Chain, const BlockFilterSet *BlockFilter) { 675 676 // There isn't a better layout when there are no unscheduled predecessors. 677 if (SuccChain.UnscheduledPredecessors == 0) 678 return false; 679 680 // As a heuristic, if we can duplicate the block into all its unscheduled 681 // predecessors, we return false. 682 if (TailDupPlacement 683 && canTailDuplicateUnplacedPreds(BB, Succ, Chain, BlockFilter)) 684 return false; 685 686 // There are two basic scenarios here: 687 // ------------------------------------- 688 // Case 1: triangular shape CFG (if-then): 689 // BB 690 // | \ 691 // | \ 692 // | Pred 693 // | / 694 // Succ 695 // In this case, we are evaluating whether to select edge -> Succ, e.g. 696 // set Succ as the layout successor of BB. Picking Succ as BB's 697 // successor breaks the CFG constraints (FIXME: define these constraints). 698 // With this layout, Pred BB 699 // is forced to be outlined, so the overall cost will be cost of the 700 // branch taken from BB to Pred, plus the cost of back taken branch 701 // from Pred to Succ, as well as the additional cost associated 702 // with the needed unconditional jump instruction from Pred To Succ. 703 704 // The cost of the topological order layout is the taken branch cost 705 // from BB to Succ, so to make BB->Succ a viable candidate, the following 706 // must hold: 707 // 2 * freq(BB->Pred) * taken_branch_cost + unconditional_jump_cost 708 // < freq(BB->Succ) * taken_branch_cost. 709 // Ignoring unconditional jump cost, we get 710 // freq(BB->Succ) > 2 * freq(BB->Pred), i.e., 711 // prob(BB->Succ) > 2 * prob(BB->Pred) 712 // 713 // When real profile data is available, we can precisely compute the 714 // probability threshold that is needed for edge BB->Succ to be considered. 715 // Without profile data, the heuristic requires the branch bias to be 716 // a lot larger to make sure the signal is very strong (e.g. 80% default). 717 // ----------------------------------------------------------------- 718 // Case 2: diamond like CFG (if-then-else): 719 // S 720 // / \ 721 // | \ 722 // BB Pred 723 // \ / 724 // Succ 725 // .. 726 // 727 // The current block is BB and edge BB->Succ is now being evaluated. 728 // Note that edge S->BB was previously already selected because 729 // prob(S->BB) > prob(S->Pred). 730 // At this point, 2 blocks can be placed after BB: Pred or Succ. If we 731 // choose Pred, we will have a topological ordering as shown on the left 732 // in the picture below. If we choose Succ, we have the solution as shown 733 // on the right: 734 // 735 // topo-order: 736 // 737 // S----- ---S 738 // | | | | 739 // ---BB | | BB 740 // | | | | 741 // | pred-- | Succ-- 742 // | | | | 743 // ---succ ---pred-- 744 // 745 // cost = freq(S->Pred) + freq(BB->Succ) cost = 2 * freq (S->Pred) 746 // = freq(S->Pred) + freq(S->BB) 747 // 748 // If we have profile data (i.e, branch probabilities can be trusted), the 749 // cost (number of taken branches) with layout S->BB->Succ->Pred is 2 * 750 // freq(S->Pred) while the cost of topo order is freq(S->Pred) + freq(S->BB). 751 // We know Prob(S->BB) > Prob(S->Pred), so freq(S->BB) > freq(S->Pred), which 752 // means the cost of topological order is greater. 753 // When profile data is not available, however, we need to be more 754 // conservative. If the branch prediction is wrong, breaking the topo-order 755 // will actually yield a layout with large cost. For this reason, we need 756 // strong biased branch at block S with Prob(S->BB) in order to select 757 // BB->Succ. This is equivalent to looking the CFG backward with backward 758 // edge: Prob(Succ->BB) needs to >= HotProb in order to be selected (without 759 // profile data). 760 // -------------------------------------------------------------------------- 761 // Case 3: forked diamond 762 // S 763 // / \ 764 // / \ 765 // BB Pred 766 // | \ / | 767 // | \ / | 768 // | X | 769 // | / \ | 770 // | / \ | 771 // S1 S2 772 // 773 // The current block is BB and edge BB->S1 is now being evaluated. 774 // As above S->BB was already selected because 775 // prob(S->BB) > prob(S->Pred). Assume that prob(BB->S1) >= prob(BB->S2). 776 // 777 // topo-order: 778 // 779 // S-------| ---S 780 // | | | | 781 // ---BB | | BB 782 // | | | | 783 // | Pred----| | S1---- 784 // | | | | 785 // --(S1 or S2) ---Pred-- 786 // 787 // topo-cost = freq(S->Pred) + freq(BB->S1) + freq(BB->S2) 788 // + min(freq(Pred->S1), freq(Pred->S2)) 789 // Non-topo-order cost: 790 // In the worst case, S2 will not get laid out after Pred. 791 // non-topo-cost = 2 * freq(S->Pred) + freq(BB->S2). 792 // To be conservative, we can assume that min(freq(Pred->S1), freq(Pred->S2)) 793 // is 0. Then the non topo layout is better when 794 // freq(S->Pred) < freq(BB->S1). 795 // This is exactly what is checked below. 796 // Note there are other shapes that apply (Pred may not be a single block, 797 // but they all fit this general pattern.) 798 BranchProbability HotProb = getLayoutSuccessorProbThreshold(BB); 799 800 // Make sure that a hot successor doesn't have a globally more 801 // important predecessor. 802 BlockFrequency CandidateEdgeFreq = MBFI->getBlockFreq(BB) * RealSuccProb; 803 bool BadCFGConflict = false; 804 805 for (MachineBasicBlock *Pred : Succ->predecessors()) { 806 if (Pred == Succ || BlockToChain[Pred] == &SuccChain || 807 (BlockFilter && !BlockFilter->count(Pred)) || 808 BlockToChain[Pred] == &Chain) 809 continue; 810 // Do backward checking. 811 // For all cases above, we need a backward checking to filter out edges that 812 // are not 'strongly' biased. With profile data available, the check is 813 // mostly redundant for case 2 (when threshold prob is set at 50%) unless S 814 // has more than two successors. 815 // BB Pred 816 // \ / 817 // Succ 818 // We select edge BB->Succ if 819 // freq(BB->Succ) > freq(Succ) * HotProb 820 // i.e. freq(BB->Succ) > freq(BB->Succ) * HotProb + freq(Pred->Succ) * 821 // HotProb 822 // i.e. freq((BB->Succ) * (1 - HotProb) > freq(Pred->Succ) * HotProb 823 // Case 1 is covered too, because the first equation reduces to: 824 // prob(BB->Succ) > HotProb. (freq(Succ) = freq(BB) for a triangle) 825 BlockFrequency PredEdgeFreq = 826 MBFI->getBlockFreq(Pred) * MBPI->getEdgeProbability(Pred, Succ); 827 if (PredEdgeFreq * HotProb >= CandidateEdgeFreq * HotProb.getCompl()) { 828 BadCFGConflict = true; 829 break; 830 } 831 } 832 833 if (BadCFGConflict) { 834 DEBUG(dbgs() << " Not a candidate: " << getBlockName(Succ) << " -> " << SuccProb 835 << " (prob) (non-cold CFG conflict)\n"); 836 return true; 837 } 838 839 return false; 840 } 841 842 /// \brief Select the best successor for a block. 843 /// 844 /// This looks across all successors of a particular block and attempts to 845 /// select the "best" one to be the layout successor. It only considers direct 846 /// successors which also pass the block filter. It will attempt to avoid 847 /// breaking CFG structure, but cave and break such structures in the case of 848 /// very hot successor edges. 849 /// 850 /// \returns The best successor block found, or null if none are viable. 851 MachineBasicBlock * 852 MachineBlockPlacement::selectBestSuccessor(MachineBasicBlock *BB, 853 BlockChain &Chain, 854 const BlockFilterSet *BlockFilter) { 855 const BranchProbability HotProb(StaticLikelyProb, 100); 856 857 MachineBasicBlock *BestSucc = nullptr; 858 auto BestProb = BranchProbability::getZero(); 859 860 SmallVector<MachineBasicBlock *, 4> Successors; 861 auto AdjustedSumProb = 862 collectViableSuccessors(BB, Chain, BlockFilter, Successors); 863 864 DEBUG(dbgs() << "Selecting best successor for: " << getBlockName(BB) << "\n"); 865 for (MachineBasicBlock *Succ : Successors) { 866 auto RealSuccProb = MBPI->getEdgeProbability(BB, Succ); 867 BranchProbability SuccProb = 868 getAdjustedProbability(RealSuccProb, AdjustedSumProb); 869 870 // This heuristic is off by default. 871 if (shouldPredBlockBeOutlined(BB, Succ, Chain, BlockFilter, SuccProb, 872 HotProb)) 873 return Succ; 874 875 BlockChain &SuccChain = *BlockToChain[Succ]; 876 // Skip the edge \c BB->Succ if block \c Succ has a better layout 877 // predecessor that yields lower global cost. 878 if (hasBetterLayoutPredecessor(BB, Succ, SuccChain, SuccProb, RealSuccProb, 879 Chain, BlockFilter)) 880 continue; 881 882 DEBUG( 883 dbgs() << " Candidate: " << getBlockName(Succ) << ", probability: " 884 << SuccProb 885 << (SuccChain.UnscheduledPredecessors != 0 ? " (CFG break)" : "") 886 << "\n"); 887 888 if (BestSucc && BestProb >= SuccProb) { 889 DEBUG(dbgs() << " Not the best candidate, continuing\n"); 890 continue; 891 } 892 893 DEBUG(dbgs() << " Setting it as best candidate\n"); 894 BestSucc = Succ; 895 BestProb = SuccProb; 896 } 897 if (BestSucc) 898 DEBUG(dbgs() << " Selected: " << getBlockName(BestSucc) << "\n"); 899 900 return BestSucc; 901 } 902 903 /// \brief Select the best block from a worklist. 904 /// 905 /// This looks through the provided worklist as a list of candidate basic 906 /// blocks and select the most profitable one to place. The definition of 907 /// profitable only really makes sense in the context of a loop. This returns 908 /// the most frequently visited block in the worklist, which in the case of 909 /// a loop, is the one most desirable to be physically close to the rest of the 910 /// loop body in order to improve i-cache behavior. 911 /// 912 /// \returns The best block found, or null if none are viable. 913 MachineBasicBlock *MachineBlockPlacement::selectBestCandidateBlock( 914 BlockChain &Chain, SmallVectorImpl<MachineBasicBlock *> &WorkList) { 915 // Once we need to walk the worklist looking for a candidate, cleanup the 916 // worklist of already placed entries. 917 // FIXME: If this shows up on profiles, it could be folded (at the cost of 918 // some code complexity) into the loop below. 919 WorkList.erase(remove_if(WorkList, 920 [&](MachineBasicBlock *BB) { 921 return BlockToChain.lookup(BB) == &Chain; 922 }), 923 WorkList.end()); 924 925 if (WorkList.empty()) 926 return nullptr; 927 928 bool IsEHPad = WorkList[0]->isEHPad(); 929 930 MachineBasicBlock *BestBlock = nullptr; 931 BlockFrequency BestFreq; 932 for (MachineBasicBlock *MBB : WorkList) { 933 assert(MBB->isEHPad() == IsEHPad); 934 935 BlockChain &SuccChain = *BlockToChain[MBB]; 936 if (&SuccChain == &Chain) 937 continue; 938 939 assert(SuccChain.UnscheduledPredecessors == 0 && "Found CFG-violating block"); 940 941 BlockFrequency CandidateFreq = MBFI->getBlockFreq(MBB); 942 DEBUG(dbgs() << " " << getBlockName(MBB) << " -> "; 943 MBFI->printBlockFreq(dbgs(), CandidateFreq) << " (freq)\n"); 944 945 // For ehpad, we layout the least probable first as to avoid jumping back 946 // from least probable landingpads to more probable ones. 947 // 948 // FIXME: Using probability is probably (!) not the best way to achieve 949 // this. We should probably have a more principled approach to layout 950 // cleanup code. 951 // 952 // The goal is to get: 953 // 954 // +--------------------------+ 955 // | V 956 // InnerLp -> InnerCleanup OuterLp -> OuterCleanup -> Resume 957 // 958 // Rather than: 959 // 960 // +-------------------------------------+ 961 // V | 962 // OuterLp -> OuterCleanup -> Resume InnerLp -> InnerCleanup 963 if (BestBlock && (IsEHPad ^ (BestFreq >= CandidateFreq))) 964 continue; 965 966 BestBlock = MBB; 967 BestFreq = CandidateFreq; 968 } 969 970 return BestBlock; 971 } 972 973 /// \brief Retrieve the first unplaced basic block. 974 /// 975 /// This routine is called when we are unable to use the CFG to walk through 976 /// all of the basic blocks and form a chain due to unnatural loops in the CFG. 977 /// We walk through the function's blocks in order, starting from the 978 /// LastUnplacedBlockIt. We update this iterator on each call to avoid 979 /// re-scanning the entire sequence on repeated calls to this routine. 980 MachineBasicBlock *MachineBlockPlacement::getFirstUnplacedBlock( 981 const BlockChain &PlacedChain, 982 MachineFunction::iterator &PrevUnplacedBlockIt, 983 const BlockFilterSet *BlockFilter) { 984 for (MachineFunction::iterator I = PrevUnplacedBlockIt, E = F->end(); I != E; 985 ++I) { 986 if (BlockFilter && !BlockFilter->count(&*I)) 987 continue; 988 if (BlockToChain[&*I] != &PlacedChain) { 989 PrevUnplacedBlockIt = I; 990 // Now select the head of the chain to which the unplaced block belongs 991 // as the block to place. This will force the entire chain to be placed, 992 // and satisfies the requirements of merging chains. 993 return *BlockToChain[&*I]->begin(); 994 } 995 } 996 return nullptr; 997 } 998 999 void MachineBlockPlacement::fillWorkLists( 1000 MachineBasicBlock *MBB, 1001 SmallPtrSetImpl<BlockChain *> &UpdatedPreds, 1002 const BlockFilterSet *BlockFilter = nullptr) { 1003 BlockChain &Chain = *BlockToChain[MBB]; 1004 if (!UpdatedPreds.insert(&Chain).second) 1005 return; 1006 1007 assert(Chain.UnscheduledPredecessors == 0); 1008 for (MachineBasicBlock *ChainBB : Chain) { 1009 assert(BlockToChain[ChainBB] == &Chain); 1010 for (MachineBasicBlock *Pred : ChainBB->predecessors()) { 1011 if (BlockFilter && !BlockFilter->count(Pred)) 1012 continue; 1013 if (BlockToChain[Pred] == &Chain) 1014 continue; 1015 ++Chain.UnscheduledPredecessors; 1016 } 1017 } 1018 1019 if (Chain.UnscheduledPredecessors != 0) 1020 return; 1021 1022 MBB = *Chain.begin(); 1023 if (MBB->isEHPad()) 1024 EHPadWorkList.push_back(MBB); 1025 else 1026 BlockWorkList.push_back(MBB); 1027 } 1028 1029 void MachineBlockPlacement::buildChain( 1030 MachineBasicBlock *BB, BlockChain &Chain, 1031 BlockFilterSet *BlockFilter) { 1032 assert(BB && "BB must not be null.\n"); 1033 assert(BlockToChain[BB] == &Chain && "BlockToChainMap mis-match.\n"); 1034 MachineFunction::iterator PrevUnplacedBlockIt = F->begin(); 1035 1036 MachineBasicBlock *LoopHeaderBB = BB; 1037 markChainSuccessors(Chain, LoopHeaderBB, BlockFilter); 1038 BB = *std::prev(Chain.end()); 1039 for (;;) { 1040 assert(BB && "null block found at end of chain in loop."); 1041 assert(BlockToChain[BB] == &Chain && "BlockToChainMap mis-match in loop."); 1042 assert(*std::prev(Chain.end()) == BB && "BB Not found at end of chain."); 1043 1044 1045 // Look for the best viable successor if there is one to place immediately 1046 // after this block. 1047 MachineBasicBlock *BestSucc = selectBestSuccessor(BB, Chain, BlockFilter); 1048 1049 // If an immediate successor isn't available, look for the best viable 1050 // block among those we've identified as not violating the loop's CFG at 1051 // this point. This won't be a fallthrough, but it will increase locality. 1052 if (!BestSucc) 1053 BestSucc = selectBestCandidateBlock(Chain, BlockWorkList); 1054 if (!BestSucc) 1055 BestSucc = selectBestCandidateBlock(Chain, EHPadWorkList); 1056 1057 if (!BestSucc) { 1058 BestSucc = getFirstUnplacedBlock(Chain, PrevUnplacedBlockIt, BlockFilter); 1059 if (!BestSucc) 1060 break; 1061 1062 DEBUG(dbgs() << "Unnatural loop CFG detected, forcibly merging the " 1063 "layout successor until the CFG reduces\n"); 1064 } 1065 1066 // Placement may have changed tail duplication opportunities. 1067 // Check for that now. 1068 if (TailDupPlacement && BestSucc) { 1069 // If the chosen successor was duplicated into all its predecessors, 1070 // don't bother laying it out, just go round the loop again with BB as 1071 // the chain end. 1072 if (repeatedlyTailDuplicateBlock(BestSucc, BB, LoopHeaderBB, Chain, 1073 BlockFilter, PrevUnplacedBlockIt)) 1074 continue; 1075 } 1076 1077 // Place this block, updating the datastructures to reflect its placement. 1078 BlockChain &SuccChain = *BlockToChain[BestSucc]; 1079 // Zero out UnscheduledPredecessors for the successor we're about to merge in case 1080 // we selected a successor that didn't fit naturally into the CFG. 1081 SuccChain.UnscheduledPredecessors = 0; 1082 DEBUG(dbgs() << "Merging from " << getBlockName(BB) << " to " 1083 << getBlockName(BestSucc) << "\n"); 1084 markChainSuccessors(SuccChain, LoopHeaderBB, BlockFilter); 1085 Chain.merge(BestSucc, &SuccChain); 1086 BB = *std::prev(Chain.end()); 1087 } 1088 1089 DEBUG(dbgs() << "Finished forming chain for header block " 1090 << getBlockName(*Chain.begin()) << "\n"); 1091 } 1092 1093 /// \brief Find the best loop top block for layout. 1094 /// 1095 /// Look for a block which is strictly better than the loop header for laying 1096 /// out at the top of the loop. This looks for one and only one pattern: 1097 /// a latch block with no conditional exit. This block will cause a conditional 1098 /// jump around it or will be the bottom of the loop if we lay it out in place, 1099 /// but if it it doesn't end up at the bottom of the loop for any reason, 1100 /// rotation alone won't fix it. Because such a block will always result in an 1101 /// unconditional jump (for the backedge) rotating it in front of the loop 1102 /// header is always profitable. 1103 MachineBasicBlock * 1104 MachineBlockPlacement::findBestLoopTop(MachineLoop &L, 1105 const BlockFilterSet &LoopBlockSet) { 1106 // Placing the latch block before the header may introduce an extra branch 1107 // that skips this block the first time the loop is executed, which we want 1108 // to avoid when optimising for size. 1109 // FIXME: in theory there is a case that does not introduce a new branch, 1110 // i.e. when the layout predecessor does not fallthrough to the loop header. 1111 // In practice this never happens though: there always seems to be a preheader 1112 // that can fallthrough and that is also placed before the header. 1113 if (F->getFunction()->optForSize()) 1114 return L.getHeader(); 1115 1116 // Check that the header hasn't been fused with a preheader block due to 1117 // crazy branches. If it has, we need to start with the header at the top to 1118 // prevent pulling the preheader into the loop body. 1119 BlockChain &HeaderChain = *BlockToChain[L.getHeader()]; 1120 if (!LoopBlockSet.count(*HeaderChain.begin())) 1121 return L.getHeader(); 1122 1123 DEBUG(dbgs() << "Finding best loop top for: " << getBlockName(L.getHeader()) 1124 << "\n"); 1125 1126 BlockFrequency BestPredFreq; 1127 MachineBasicBlock *BestPred = nullptr; 1128 for (MachineBasicBlock *Pred : L.getHeader()->predecessors()) { 1129 if (!LoopBlockSet.count(Pred)) 1130 continue; 1131 DEBUG(dbgs() << " header pred: " << getBlockName(Pred) << ", has " 1132 << Pred->succ_size() << " successors, "; 1133 MBFI->printBlockFreq(dbgs(), Pred) << " freq\n"); 1134 if (Pred->succ_size() > 1) 1135 continue; 1136 1137 BlockFrequency PredFreq = MBFI->getBlockFreq(Pred); 1138 if (!BestPred || PredFreq > BestPredFreq || 1139 (!(PredFreq < BestPredFreq) && 1140 Pred->isLayoutSuccessor(L.getHeader()))) { 1141 BestPred = Pred; 1142 BestPredFreq = PredFreq; 1143 } 1144 } 1145 1146 // If no direct predecessor is fine, just use the loop header. 1147 if (!BestPred) { 1148 DEBUG(dbgs() << " final top unchanged\n"); 1149 return L.getHeader(); 1150 } 1151 1152 // Walk backwards through any straight line of predecessors. 1153 while (BestPred->pred_size() == 1 && 1154 (*BestPred->pred_begin())->succ_size() == 1 && 1155 *BestPred->pred_begin() != L.getHeader()) 1156 BestPred = *BestPred->pred_begin(); 1157 1158 DEBUG(dbgs() << " final top: " << getBlockName(BestPred) << "\n"); 1159 return BestPred; 1160 } 1161 1162 /// \brief Find the best loop exiting block for layout. 1163 /// 1164 /// This routine implements the logic to analyze the loop looking for the best 1165 /// block to layout at the top of the loop. Typically this is done to maximize 1166 /// fallthrough opportunities. 1167 MachineBasicBlock * 1168 MachineBlockPlacement::findBestLoopExit(MachineLoop &L, 1169 const BlockFilterSet &LoopBlockSet) { 1170 // We don't want to layout the loop linearly in all cases. If the loop header 1171 // is just a normal basic block in the loop, we want to look for what block 1172 // within the loop is the best one to layout at the top. However, if the loop 1173 // header has be pre-merged into a chain due to predecessors not having 1174 // analyzable branches, *and* the predecessor it is merged with is *not* part 1175 // of the loop, rotating the header into the middle of the loop will create 1176 // a non-contiguous range of blocks which is Very Bad. So start with the 1177 // header and only rotate if safe. 1178 BlockChain &HeaderChain = *BlockToChain[L.getHeader()]; 1179 if (!LoopBlockSet.count(*HeaderChain.begin())) 1180 return nullptr; 1181 1182 BlockFrequency BestExitEdgeFreq; 1183 unsigned BestExitLoopDepth = 0; 1184 MachineBasicBlock *ExitingBB = nullptr; 1185 // If there are exits to outer loops, loop rotation can severely limit 1186 // fallthrough opportunities unless it selects such an exit. Keep a set of 1187 // blocks where rotating to exit with that block will reach an outer loop. 1188 SmallPtrSet<MachineBasicBlock *, 4> BlocksExitingToOuterLoop; 1189 1190 DEBUG(dbgs() << "Finding best loop exit for: " << getBlockName(L.getHeader()) 1191 << "\n"); 1192 for (MachineBasicBlock *MBB : L.getBlocks()) { 1193 BlockChain &Chain = *BlockToChain[MBB]; 1194 // Ensure that this block is at the end of a chain; otherwise it could be 1195 // mid-way through an inner loop or a successor of an unanalyzable branch. 1196 if (MBB != *std::prev(Chain.end())) 1197 continue; 1198 1199 // Now walk the successors. We need to establish whether this has a viable 1200 // exiting successor and whether it has a viable non-exiting successor. 1201 // We store the old exiting state and restore it if a viable looping 1202 // successor isn't found. 1203 MachineBasicBlock *OldExitingBB = ExitingBB; 1204 BlockFrequency OldBestExitEdgeFreq = BestExitEdgeFreq; 1205 bool HasLoopingSucc = false; 1206 for (MachineBasicBlock *Succ : MBB->successors()) { 1207 if (Succ->isEHPad()) 1208 continue; 1209 if (Succ == MBB) 1210 continue; 1211 BlockChain &SuccChain = *BlockToChain[Succ]; 1212 // Don't split chains, either this chain or the successor's chain. 1213 if (&Chain == &SuccChain) { 1214 DEBUG(dbgs() << " exiting: " << getBlockName(MBB) << " -> " 1215 << getBlockName(Succ) << " (chain conflict)\n"); 1216 continue; 1217 } 1218 1219 auto SuccProb = MBPI->getEdgeProbability(MBB, Succ); 1220 if (LoopBlockSet.count(Succ)) { 1221 DEBUG(dbgs() << " looping: " << getBlockName(MBB) << " -> " 1222 << getBlockName(Succ) << " (" << SuccProb << ")\n"); 1223 HasLoopingSucc = true; 1224 continue; 1225 } 1226 1227 unsigned SuccLoopDepth = 0; 1228 if (MachineLoop *ExitLoop = MLI->getLoopFor(Succ)) { 1229 SuccLoopDepth = ExitLoop->getLoopDepth(); 1230 if (ExitLoop->contains(&L)) 1231 BlocksExitingToOuterLoop.insert(MBB); 1232 } 1233 1234 BlockFrequency ExitEdgeFreq = MBFI->getBlockFreq(MBB) * SuccProb; 1235 DEBUG(dbgs() << " exiting: " << getBlockName(MBB) << " -> " 1236 << getBlockName(Succ) << " [L:" << SuccLoopDepth << "] ("; 1237 MBFI->printBlockFreq(dbgs(), ExitEdgeFreq) << ")\n"); 1238 // Note that we bias this toward an existing layout successor to retain 1239 // incoming order in the absence of better information. The exit must have 1240 // a frequency higher than the current exit before we consider breaking 1241 // the layout. 1242 BranchProbability Bias(100 - ExitBlockBias, 100); 1243 if (!ExitingBB || SuccLoopDepth > BestExitLoopDepth || 1244 ExitEdgeFreq > BestExitEdgeFreq || 1245 (MBB->isLayoutSuccessor(Succ) && 1246 !(ExitEdgeFreq < BestExitEdgeFreq * Bias))) { 1247 BestExitEdgeFreq = ExitEdgeFreq; 1248 ExitingBB = MBB; 1249 } 1250 } 1251 1252 if (!HasLoopingSucc) { 1253 // Restore the old exiting state, no viable looping successor was found. 1254 ExitingBB = OldExitingBB; 1255 BestExitEdgeFreq = OldBestExitEdgeFreq; 1256 } 1257 } 1258 // Without a candidate exiting block or with only a single block in the 1259 // loop, just use the loop header to layout the loop. 1260 if (!ExitingBB) { 1261 DEBUG(dbgs() << " No other candidate exit blocks, using loop header\n"); 1262 return nullptr; 1263 } 1264 if (L.getNumBlocks() == 1) { 1265 DEBUG(dbgs() << " Loop has 1 block, using loop header as exit\n"); 1266 return nullptr; 1267 } 1268 1269 // Also, if we have exit blocks which lead to outer loops but didn't select 1270 // one of them as the exiting block we are rotating toward, disable loop 1271 // rotation altogether. 1272 if (!BlocksExitingToOuterLoop.empty() && 1273 !BlocksExitingToOuterLoop.count(ExitingBB)) 1274 return nullptr; 1275 1276 DEBUG(dbgs() << " Best exiting block: " << getBlockName(ExitingBB) << "\n"); 1277 return ExitingBB; 1278 } 1279 1280 /// \brief Attempt to rotate an exiting block to the bottom of the loop. 1281 /// 1282 /// Once we have built a chain, try to rotate it to line up the hot exit block 1283 /// with fallthrough out of the loop if doing so doesn't introduce unnecessary 1284 /// branches. For example, if the loop has fallthrough into its header and out 1285 /// of its bottom already, don't rotate it. 1286 void MachineBlockPlacement::rotateLoop(BlockChain &LoopChain, 1287 MachineBasicBlock *ExitingBB, 1288 const BlockFilterSet &LoopBlockSet) { 1289 if (!ExitingBB) 1290 return; 1291 1292 MachineBasicBlock *Top = *LoopChain.begin(); 1293 bool ViableTopFallthrough = false; 1294 for (MachineBasicBlock *Pred : Top->predecessors()) { 1295 BlockChain *PredChain = BlockToChain[Pred]; 1296 if (!LoopBlockSet.count(Pred) && 1297 (!PredChain || Pred == *std::prev(PredChain->end()))) { 1298 ViableTopFallthrough = true; 1299 break; 1300 } 1301 } 1302 1303 // If the header has viable fallthrough, check whether the current loop 1304 // bottom is a viable exiting block. If so, bail out as rotating will 1305 // introduce an unnecessary branch. 1306 if (ViableTopFallthrough) { 1307 MachineBasicBlock *Bottom = *std::prev(LoopChain.end()); 1308 for (MachineBasicBlock *Succ : Bottom->successors()) { 1309 BlockChain *SuccChain = BlockToChain[Succ]; 1310 if (!LoopBlockSet.count(Succ) && 1311 (!SuccChain || Succ == *SuccChain->begin())) 1312 return; 1313 } 1314 } 1315 1316 BlockChain::iterator ExitIt = find(LoopChain, ExitingBB); 1317 if (ExitIt == LoopChain.end()) 1318 return; 1319 1320 std::rotate(LoopChain.begin(), std::next(ExitIt), LoopChain.end()); 1321 } 1322 1323 /// \brief Attempt to rotate a loop based on profile data to reduce branch cost. 1324 /// 1325 /// With profile data, we can determine the cost in terms of missed fall through 1326 /// opportunities when rotating a loop chain and select the best rotation. 1327 /// Basically, there are three kinds of cost to consider for each rotation: 1328 /// 1. The possibly missed fall through edge (if it exists) from BB out of 1329 /// the loop to the loop header. 1330 /// 2. The possibly missed fall through edges (if they exist) from the loop 1331 /// exits to BB out of the loop. 1332 /// 3. The missed fall through edge (if it exists) from the last BB to the 1333 /// first BB in the loop chain. 1334 /// Therefore, the cost for a given rotation is the sum of costs listed above. 1335 /// We select the best rotation with the smallest cost. 1336 void MachineBlockPlacement::rotateLoopWithProfile( 1337 BlockChain &LoopChain, MachineLoop &L, const BlockFilterSet &LoopBlockSet) { 1338 auto HeaderBB = L.getHeader(); 1339 auto HeaderIter = find(LoopChain, HeaderBB); 1340 auto RotationPos = LoopChain.end(); 1341 1342 BlockFrequency SmallestRotationCost = BlockFrequency::getMaxFrequency(); 1343 1344 // A utility lambda that scales up a block frequency by dividing it by a 1345 // branch probability which is the reciprocal of the scale. 1346 auto ScaleBlockFrequency = [](BlockFrequency Freq, 1347 unsigned Scale) -> BlockFrequency { 1348 if (Scale == 0) 1349 return 0; 1350 // Use operator / between BlockFrequency and BranchProbability to implement 1351 // saturating multiplication. 1352 return Freq / BranchProbability(1, Scale); 1353 }; 1354 1355 // Compute the cost of the missed fall-through edge to the loop header if the 1356 // chain head is not the loop header. As we only consider natural loops with 1357 // single header, this computation can be done only once. 1358 BlockFrequency HeaderFallThroughCost(0); 1359 for (auto *Pred : HeaderBB->predecessors()) { 1360 BlockChain *PredChain = BlockToChain[Pred]; 1361 if (!LoopBlockSet.count(Pred) && 1362 (!PredChain || Pred == *std::prev(PredChain->end()))) { 1363 auto EdgeFreq = 1364 MBFI->getBlockFreq(Pred) * MBPI->getEdgeProbability(Pred, HeaderBB); 1365 auto FallThruCost = ScaleBlockFrequency(EdgeFreq, MisfetchCost); 1366 // If the predecessor has only an unconditional jump to the header, we 1367 // need to consider the cost of this jump. 1368 if (Pred->succ_size() == 1) 1369 FallThruCost += ScaleBlockFrequency(EdgeFreq, JumpInstCost); 1370 HeaderFallThroughCost = std::max(HeaderFallThroughCost, FallThruCost); 1371 } 1372 } 1373 1374 // Here we collect all exit blocks in the loop, and for each exit we find out 1375 // its hottest exit edge. For each loop rotation, we define the loop exit cost 1376 // as the sum of frequencies of exit edges we collect here, excluding the exit 1377 // edge from the tail of the loop chain. 1378 SmallVector<std::pair<MachineBasicBlock *, BlockFrequency>, 4> ExitsWithFreq; 1379 for (auto BB : LoopChain) { 1380 auto LargestExitEdgeProb = BranchProbability::getZero(); 1381 for (auto *Succ : BB->successors()) { 1382 BlockChain *SuccChain = BlockToChain[Succ]; 1383 if (!LoopBlockSet.count(Succ) && 1384 (!SuccChain || Succ == *SuccChain->begin())) { 1385 auto SuccProb = MBPI->getEdgeProbability(BB, Succ); 1386 LargestExitEdgeProb = std::max(LargestExitEdgeProb, SuccProb); 1387 } 1388 } 1389 if (LargestExitEdgeProb > BranchProbability::getZero()) { 1390 auto ExitFreq = MBFI->getBlockFreq(BB) * LargestExitEdgeProb; 1391 ExitsWithFreq.emplace_back(BB, ExitFreq); 1392 } 1393 } 1394 1395 // In this loop we iterate every block in the loop chain and calculate the 1396 // cost assuming the block is the head of the loop chain. When the loop ends, 1397 // we should have found the best candidate as the loop chain's head. 1398 for (auto Iter = LoopChain.begin(), TailIter = std::prev(LoopChain.end()), 1399 EndIter = LoopChain.end(); 1400 Iter != EndIter; Iter++, TailIter++) { 1401 // TailIter is used to track the tail of the loop chain if the block we are 1402 // checking (pointed by Iter) is the head of the chain. 1403 if (TailIter == LoopChain.end()) 1404 TailIter = LoopChain.begin(); 1405 1406 auto TailBB = *TailIter; 1407 1408 // Calculate the cost by putting this BB to the top. 1409 BlockFrequency Cost = 0; 1410 1411 // If the current BB is the loop header, we need to take into account the 1412 // cost of the missed fall through edge from outside of the loop to the 1413 // header. 1414 if (Iter != HeaderIter) 1415 Cost += HeaderFallThroughCost; 1416 1417 // Collect the loop exit cost by summing up frequencies of all exit edges 1418 // except the one from the chain tail. 1419 for (auto &ExitWithFreq : ExitsWithFreq) 1420 if (TailBB != ExitWithFreq.first) 1421 Cost += ExitWithFreq.second; 1422 1423 // The cost of breaking the once fall-through edge from the tail to the top 1424 // of the loop chain. Here we need to consider three cases: 1425 // 1. If the tail node has only one successor, then we will get an 1426 // additional jmp instruction. So the cost here is (MisfetchCost + 1427 // JumpInstCost) * tail node frequency. 1428 // 2. If the tail node has two successors, then we may still get an 1429 // additional jmp instruction if the layout successor after the loop 1430 // chain is not its CFG successor. Note that the more frequently executed 1431 // jmp instruction will be put ahead of the other one. Assume the 1432 // frequency of those two branches are x and y, where x is the frequency 1433 // of the edge to the chain head, then the cost will be 1434 // (x * MisfetechCost + min(x, y) * JumpInstCost) * tail node frequency. 1435 // 3. If the tail node has more than two successors (this rarely happens), 1436 // we won't consider any additional cost. 1437 if (TailBB->isSuccessor(*Iter)) { 1438 auto TailBBFreq = MBFI->getBlockFreq(TailBB); 1439 if (TailBB->succ_size() == 1) 1440 Cost += ScaleBlockFrequency(TailBBFreq.getFrequency(), 1441 MisfetchCost + JumpInstCost); 1442 else if (TailBB->succ_size() == 2) { 1443 auto TailToHeadProb = MBPI->getEdgeProbability(TailBB, *Iter); 1444 auto TailToHeadFreq = TailBBFreq * TailToHeadProb; 1445 auto ColderEdgeFreq = TailToHeadProb > BranchProbability(1, 2) 1446 ? TailBBFreq * TailToHeadProb.getCompl() 1447 : TailToHeadFreq; 1448 Cost += ScaleBlockFrequency(TailToHeadFreq, MisfetchCost) + 1449 ScaleBlockFrequency(ColderEdgeFreq, JumpInstCost); 1450 } 1451 } 1452 1453 DEBUG(dbgs() << "The cost of loop rotation by making " << getBlockName(*Iter) 1454 << " to the top: " << Cost.getFrequency() << "\n"); 1455 1456 if (Cost < SmallestRotationCost) { 1457 SmallestRotationCost = Cost; 1458 RotationPos = Iter; 1459 } 1460 } 1461 1462 if (RotationPos != LoopChain.end()) { 1463 DEBUG(dbgs() << "Rotate loop by making " << getBlockName(*RotationPos) 1464 << " to the top\n"); 1465 std::rotate(LoopChain.begin(), RotationPos, LoopChain.end()); 1466 } 1467 } 1468 1469 /// \brief Collect blocks in the given loop that are to be placed. 1470 /// 1471 /// When profile data is available, exclude cold blocks from the returned set; 1472 /// otherwise, collect all blocks in the loop. 1473 MachineBlockPlacement::BlockFilterSet 1474 MachineBlockPlacement::collectLoopBlockSet(MachineLoop &L) { 1475 BlockFilterSet LoopBlockSet; 1476 1477 // Filter cold blocks off from LoopBlockSet when profile data is available. 1478 // Collect the sum of frequencies of incoming edges to the loop header from 1479 // outside. If we treat the loop as a super block, this is the frequency of 1480 // the loop. Then for each block in the loop, we calculate the ratio between 1481 // its frequency and the frequency of the loop block. When it is too small, 1482 // don't add it to the loop chain. If there are outer loops, then this block 1483 // will be merged into the first outer loop chain for which this block is not 1484 // cold anymore. This needs precise profile data and we only do this when 1485 // profile data is available. 1486 if (F->getFunction()->getEntryCount()) { 1487 BlockFrequency LoopFreq(0); 1488 for (auto LoopPred : L.getHeader()->predecessors()) 1489 if (!L.contains(LoopPred)) 1490 LoopFreq += MBFI->getBlockFreq(LoopPred) * 1491 MBPI->getEdgeProbability(LoopPred, L.getHeader()); 1492 1493 for (MachineBasicBlock *LoopBB : L.getBlocks()) { 1494 auto Freq = MBFI->getBlockFreq(LoopBB).getFrequency(); 1495 if (Freq == 0 || LoopFreq.getFrequency() / Freq > LoopToColdBlockRatio) 1496 continue; 1497 LoopBlockSet.insert(LoopBB); 1498 } 1499 } else 1500 LoopBlockSet.insert(L.block_begin(), L.block_end()); 1501 1502 return LoopBlockSet; 1503 } 1504 1505 /// \brief Forms basic block chains from the natural loop structures. 1506 /// 1507 /// These chains are designed to preserve the existing *structure* of the code 1508 /// as much as possible. We can then stitch the chains together in a way which 1509 /// both preserves the topological structure and minimizes taken conditional 1510 /// branches. 1511 void MachineBlockPlacement::buildLoopChains(MachineLoop &L) { 1512 // First recurse through any nested loops, building chains for those inner 1513 // loops. 1514 for (MachineLoop *InnerLoop : L) 1515 buildLoopChains(*InnerLoop); 1516 1517 assert(BlockWorkList.empty()); 1518 assert(EHPadWorkList.empty()); 1519 BlockFilterSet LoopBlockSet = collectLoopBlockSet(L); 1520 1521 // Check if we have profile data for this function. If yes, we will rotate 1522 // this loop by modeling costs more precisely which requires the profile data 1523 // for better layout. 1524 bool RotateLoopWithProfile = 1525 ForcePreciseRotationCost || 1526 (PreciseRotationCost && F->getFunction()->getEntryCount()); 1527 1528 // First check to see if there is an obviously preferable top block for the 1529 // loop. This will default to the header, but may end up as one of the 1530 // predecessors to the header if there is one which will result in strictly 1531 // fewer branches in the loop body. 1532 // When we use profile data to rotate the loop, this is unnecessary. 1533 MachineBasicBlock *LoopTop = 1534 RotateLoopWithProfile ? L.getHeader() : findBestLoopTop(L, LoopBlockSet); 1535 1536 // If we selected just the header for the loop top, look for a potentially 1537 // profitable exit block in the event that rotating the loop can eliminate 1538 // branches by placing an exit edge at the bottom. 1539 if (!RotateLoopWithProfile && LoopTop == L.getHeader()) 1540 PreferredLoopExit = findBestLoopExit(L, LoopBlockSet); 1541 1542 BlockChain &LoopChain = *BlockToChain[LoopTop]; 1543 1544 // FIXME: This is a really lame way of walking the chains in the loop: we 1545 // walk the blocks, and use a set to prevent visiting a particular chain 1546 // twice. 1547 SmallPtrSet<BlockChain *, 4> UpdatedPreds; 1548 assert(LoopChain.UnscheduledPredecessors == 0); 1549 UpdatedPreds.insert(&LoopChain); 1550 1551 for (MachineBasicBlock *LoopBB : LoopBlockSet) 1552 fillWorkLists(LoopBB, UpdatedPreds, &LoopBlockSet); 1553 1554 buildChain(LoopTop, LoopChain, &LoopBlockSet); 1555 1556 if (RotateLoopWithProfile) 1557 rotateLoopWithProfile(LoopChain, L, LoopBlockSet); 1558 else 1559 rotateLoop(LoopChain, PreferredLoopExit, LoopBlockSet); 1560 1561 DEBUG({ 1562 // Crash at the end so we get all of the debugging output first. 1563 bool BadLoop = false; 1564 if (LoopChain.UnscheduledPredecessors) { 1565 BadLoop = true; 1566 dbgs() << "Loop chain contains a block without its preds placed!\n" 1567 << " Loop header: " << getBlockName(*L.block_begin()) << "\n" 1568 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n"; 1569 } 1570 for (MachineBasicBlock *ChainBB : LoopChain) { 1571 dbgs() << " ... " << getBlockName(ChainBB) << "\n"; 1572 if (!LoopBlockSet.remove(ChainBB)) { 1573 // We don't mark the loop as bad here because there are real situations 1574 // where this can occur. For example, with an unanalyzable fallthrough 1575 // from a loop block to a non-loop block or vice versa. 1576 dbgs() << "Loop chain contains a block not contained by the loop!\n" 1577 << " Loop header: " << getBlockName(*L.block_begin()) << "\n" 1578 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n" 1579 << " Bad block: " << getBlockName(ChainBB) << "\n"; 1580 } 1581 } 1582 1583 if (!LoopBlockSet.empty()) { 1584 BadLoop = true; 1585 for (MachineBasicBlock *LoopBB : LoopBlockSet) 1586 dbgs() << "Loop contains blocks never placed into a chain!\n" 1587 << " Loop header: " << getBlockName(*L.block_begin()) << "\n" 1588 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n" 1589 << " Bad block: " << getBlockName(LoopBB) << "\n"; 1590 } 1591 assert(!BadLoop && "Detected problems with the placement of this loop."); 1592 }); 1593 1594 BlockWorkList.clear(); 1595 EHPadWorkList.clear(); 1596 } 1597 1598 /// When OutlineOpitonalBranches is on, this method collects BBs that 1599 /// dominates all terminator blocks of the function \p F. 1600 void MachineBlockPlacement::collectMustExecuteBBs() { 1601 if (OutlineOptionalBranches) { 1602 // Find the nearest common dominator of all of F's terminators. 1603 MachineBasicBlock *Terminator = nullptr; 1604 for (MachineBasicBlock &MBB : *F) { 1605 if (MBB.succ_size() == 0) { 1606 if (Terminator == nullptr) 1607 Terminator = &MBB; 1608 else 1609 Terminator = MDT->findNearestCommonDominator(Terminator, &MBB); 1610 } 1611 } 1612 1613 // MBBs dominating this common dominator are unavoidable. 1614 UnavoidableBlocks.clear(); 1615 for (MachineBasicBlock &MBB : *F) { 1616 if (MDT->dominates(&MBB, Terminator)) { 1617 UnavoidableBlocks.insert(&MBB); 1618 } 1619 } 1620 } 1621 } 1622 1623 void MachineBlockPlacement::buildCFGChains() { 1624 // Ensure that every BB in the function has an associated chain to simplify 1625 // the assumptions of the remaining algorithm. 1626 SmallVector<MachineOperand, 4> Cond; // For AnalyzeBranch. 1627 for (MachineFunction::iterator FI = F->begin(), FE = F->end(); FI != FE; 1628 ++FI) { 1629 MachineBasicBlock *BB = &*FI; 1630 BlockChain *Chain = 1631 new (ChainAllocator.Allocate()) BlockChain(BlockToChain, BB); 1632 // Also, merge any blocks which we cannot reason about and must preserve 1633 // the exact fallthrough behavior for. 1634 for (;;) { 1635 Cond.clear(); 1636 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch. 1637 if (!TII->analyzeBranch(*BB, TBB, FBB, Cond) || !FI->canFallThrough()) 1638 break; 1639 1640 MachineFunction::iterator NextFI = std::next(FI); 1641 MachineBasicBlock *NextBB = &*NextFI; 1642 // Ensure that the layout successor is a viable block, as we know that 1643 // fallthrough is a possibility. 1644 assert(NextFI != FE && "Can't fallthrough past the last block."); 1645 DEBUG(dbgs() << "Pre-merging due to unanalyzable fallthrough: " 1646 << getBlockName(BB) << " -> " << getBlockName(NextBB) 1647 << "\n"); 1648 Chain->merge(NextBB, nullptr); 1649 #ifndef NDEBUG 1650 BlocksWithUnanalyzableExits.insert(&*BB); 1651 #endif 1652 FI = NextFI; 1653 BB = NextBB; 1654 } 1655 } 1656 1657 // Turned on with OutlineOptionalBranches option 1658 collectMustExecuteBBs(); 1659 1660 // Build any loop-based chains. 1661 PreferredLoopExit = nullptr; 1662 for (MachineLoop *L : *MLI) 1663 buildLoopChains(*L); 1664 1665 assert(BlockWorkList.empty()); 1666 assert(EHPadWorkList.empty()); 1667 1668 SmallPtrSet<BlockChain *, 4> UpdatedPreds; 1669 for (MachineBasicBlock &MBB : *F) 1670 fillWorkLists(&MBB, UpdatedPreds); 1671 1672 BlockChain &FunctionChain = *BlockToChain[&F->front()]; 1673 buildChain(&F->front(), FunctionChain); 1674 1675 #ifndef NDEBUG 1676 typedef SmallPtrSet<MachineBasicBlock *, 16> FunctionBlockSetType; 1677 #endif 1678 DEBUG({ 1679 // Crash at the end so we get all of the debugging output first. 1680 bool BadFunc = false; 1681 FunctionBlockSetType FunctionBlockSet; 1682 for (MachineBasicBlock &MBB : *F) 1683 FunctionBlockSet.insert(&MBB); 1684 1685 for (MachineBasicBlock *ChainBB : FunctionChain) 1686 if (!FunctionBlockSet.erase(ChainBB)) { 1687 BadFunc = true; 1688 dbgs() << "Function chain contains a block not in the function!\n" 1689 << " Bad block: " << getBlockName(ChainBB) << "\n"; 1690 } 1691 1692 if (!FunctionBlockSet.empty()) { 1693 BadFunc = true; 1694 for (MachineBasicBlock *RemainingBB : FunctionBlockSet) 1695 dbgs() << "Function contains blocks never placed into a chain!\n" 1696 << " Bad block: " << getBlockName(RemainingBB) << "\n"; 1697 } 1698 assert(!BadFunc && "Detected problems with the block placement."); 1699 }); 1700 1701 // Splice the blocks into place. 1702 MachineFunction::iterator InsertPos = F->begin(); 1703 DEBUG(dbgs() << "[MBP] Function: "<< F->getName() << "\n"); 1704 for (MachineBasicBlock *ChainBB : FunctionChain) { 1705 DEBUG(dbgs() << (ChainBB == *FunctionChain.begin() ? "Placing chain " 1706 : " ... ") 1707 << getBlockName(ChainBB) << "\n"); 1708 if (InsertPos != MachineFunction::iterator(ChainBB)) 1709 F->splice(InsertPos, ChainBB); 1710 else 1711 ++InsertPos; 1712 1713 // Update the terminator of the previous block. 1714 if (ChainBB == *FunctionChain.begin()) 1715 continue; 1716 MachineBasicBlock *PrevBB = &*std::prev(MachineFunction::iterator(ChainBB)); 1717 1718 // FIXME: It would be awesome of updateTerminator would just return rather 1719 // than assert when the branch cannot be analyzed in order to remove this 1720 // boiler plate. 1721 Cond.clear(); 1722 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch. 1723 1724 #ifndef NDEBUG 1725 if (!BlocksWithUnanalyzableExits.count(PrevBB)) { 1726 // Given the exact block placement we chose, we may actually not _need_ to 1727 // be able to edit PrevBB's terminator sequence, but not being _able_ to 1728 // do that at this point is a bug. 1729 assert((!TII->analyzeBranch(*PrevBB, TBB, FBB, Cond) || 1730 !PrevBB->canFallThrough()) && 1731 "Unexpected block with un-analyzable fallthrough!"); 1732 Cond.clear(); 1733 TBB = FBB = nullptr; 1734 } 1735 #endif 1736 1737 // The "PrevBB" is not yet updated to reflect current code layout, so, 1738 // o. it may fall-through to a block without explicit "goto" instruction 1739 // before layout, and no longer fall-through it after layout; or 1740 // o. just opposite. 1741 // 1742 // analyzeBranch() may return erroneous value for FBB when these two 1743 // situations take place. For the first scenario FBB is mistakenly set NULL; 1744 // for the 2nd scenario, the FBB, which is expected to be NULL, is 1745 // mistakenly pointing to "*BI". 1746 // Thus, if the future change needs to use FBB before the layout is set, it 1747 // has to correct FBB first by using the code similar to the following: 1748 // 1749 // if (!Cond.empty() && (!FBB || FBB == ChainBB)) { 1750 // PrevBB->updateTerminator(); 1751 // Cond.clear(); 1752 // TBB = FBB = nullptr; 1753 // if (TII->analyzeBranch(*PrevBB, TBB, FBB, Cond)) { 1754 // // FIXME: This should never take place. 1755 // TBB = FBB = nullptr; 1756 // } 1757 // } 1758 if (!TII->analyzeBranch(*PrevBB, TBB, FBB, Cond)) 1759 PrevBB->updateTerminator(); 1760 } 1761 1762 // Fixup the last block. 1763 Cond.clear(); 1764 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch. 1765 if (!TII->analyzeBranch(F->back(), TBB, FBB, Cond)) 1766 F->back().updateTerminator(); 1767 1768 BlockWorkList.clear(); 1769 EHPadWorkList.clear(); 1770 } 1771 1772 void MachineBlockPlacement::optimizeBranches() { 1773 BlockChain &FunctionChain = *BlockToChain[&F->front()]; 1774 SmallVector<MachineOperand, 4> Cond; // For AnalyzeBranch. 1775 1776 // Now that all the basic blocks in the chain have the proper layout, 1777 // make a final call to AnalyzeBranch with AllowModify set. 1778 // Indeed, the target may be able to optimize the branches in a way we 1779 // cannot because all branches may not be analyzable. 1780 // E.g., the target may be able to remove an unconditional branch to 1781 // a fallthrough when it occurs after predicated terminators. 1782 for (MachineBasicBlock *ChainBB : FunctionChain) { 1783 Cond.clear(); 1784 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch. 1785 if (!TII->analyzeBranch(*ChainBB, TBB, FBB, Cond, /*AllowModify*/ true)) { 1786 // If PrevBB has a two-way branch, try to re-order the branches 1787 // such that we branch to the successor with higher probability first. 1788 if (TBB && !Cond.empty() && FBB && 1789 MBPI->getEdgeProbability(ChainBB, FBB) > 1790 MBPI->getEdgeProbability(ChainBB, TBB) && 1791 !TII->reverseBranchCondition(Cond)) { 1792 DEBUG(dbgs() << "Reverse order of the two branches: " 1793 << getBlockName(ChainBB) << "\n"); 1794 DEBUG(dbgs() << " Edge probability: " 1795 << MBPI->getEdgeProbability(ChainBB, FBB) << " vs " 1796 << MBPI->getEdgeProbability(ChainBB, TBB) << "\n"); 1797 DebugLoc dl; // FIXME: this is nowhere 1798 TII->removeBranch(*ChainBB); 1799 TII->insertBranch(*ChainBB, FBB, TBB, Cond, dl); 1800 ChainBB->updateTerminator(); 1801 } 1802 } 1803 } 1804 } 1805 1806 void MachineBlockPlacement::alignBlocks() { 1807 // Walk through the backedges of the function now that we have fully laid out 1808 // the basic blocks and align the destination of each backedge. We don't rely 1809 // exclusively on the loop info here so that we can align backedges in 1810 // unnatural CFGs and backedges that were introduced purely because of the 1811 // loop rotations done during this layout pass. 1812 if (F->getFunction()->optForSize()) 1813 return; 1814 BlockChain &FunctionChain = *BlockToChain[&F->front()]; 1815 if (FunctionChain.begin() == FunctionChain.end()) 1816 return; // Empty chain. 1817 1818 const BranchProbability ColdProb(1, 5); // 20% 1819 BlockFrequency EntryFreq = MBFI->getBlockFreq(&F->front()); 1820 BlockFrequency WeightedEntryFreq = EntryFreq * ColdProb; 1821 for (MachineBasicBlock *ChainBB : FunctionChain) { 1822 if (ChainBB == *FunctionChain.begin()) 1823 continue; 1824 1825 // Don't align non-looping basic blocks. These are unlikely to execute 1826 // enough times to matter in practice. Note that we'll still handle 1827 // unnatural CFGs inside of a natural outer loop (the common case) and 1828 // rotated loops. 1829 MachineLoop *L = MLI->getLoopFor(ChainBB); 1830 if (!L) 1831 continue; 1832 1833 unsigned Align = TLI->getPrefLoopAlignment(L); 1834 if (!Align) 1835 continue; // Don't care about loop alignment. 1836 1837 // If the block is cold relative to the function entry don't waste space 1838 // aligning it. 1839 BlockFrequency Freq = MBFI->getBlockFreq(ChainBB); 1840 if (Freq < WeightedEntryFreq) 1841 continue; 1842 1843 // If the block is cold relative to its loop header, don't align it 1844 // regardless of what edges into the block exist. 1845 MachineBasicBlock *LoopHeader = L->getHeader(); 1846 BlockFrequency LoopHeaderFreq = MBFI->getBlockFreq(LoopHeader); 1847 if (Freq < (LoopHeaderFreq * ColdProb)) 1848 continue; 1849 1850 // Check for the existence of a non-layout predecessor which would benefit 1851 // from aligning this block. 1852 MachineBasicBlock *LayoutPred = 1853 &*std::prev(MachineFunction::iterator(ChainBB)); 1854 1855 // Force alignment if all the predecessors are jumps. We already checked 1856 // that the block isn't cold above. 1857 if (!LayoutPred->isSuccessor(ChainBB)) { 1858 ChainBB->setAlignment(Align); 1859 continue; 1860 } 1861 1862 // Align this block if the layout predecessor's edge into this block is 1863 // cold relative to the block. When this is true, other predecessors make up 1864 // all of the hot entries into the block and thus alignment is likely to be 1865 // important. 1866 BranchProbability LayoutProb = 1867 MBPI->getEdgeProbability(LayoutPred, ChainBB); 1868 BlockFrequency LayoutEdgeFreq = MBFI->getBlockFreq(LayoutPred) * LayoutProb; 1869 if (LayoutEdgeFreq <= (Freq * ColdProb)) 1870 ChainBB->setAlignment(Align); 1871 } 1872 } 1873 1874 /// Tail duplicate \p BB into (some) predecessors if profitable, repeating if 1875 /// it was duplicated into its chain predecessor and removed. 1876 /// \p BB - Basic block that may be duplicated. 1877 /// 1878 /// \p LPred - Chosen layout predecessor of \p BB. 1879 /// Updated to be the chain end if LPred is removed. 1880 /// \p Chain - Chain to which \p LPred belongs, and \p BB will belong. 1881 /// \p BlockFilter - Set of blocks that belong to the loop being laid out. 1882 /// Used to identify which blocks to update predecessor 1883 /// counts. 1884 /// \p PrevUnplacedBlockIt - Iterator pointing to the last block that was 1885 /// chosen in the given order due to unnatural CFG 1886 /// only needed if \p BB is removed and 1887 /// \p PrevUnplacedBlockIt pointed to \p BB. 1888 /// @return true if \p BB was removed. 1889 bool MachineBlockPlacement::repeatedlyTailDuplicateBlock( 1890 MachineBasicBlock *BB, MachineBasicBlock *&LPred, 1891 MachineBasicBlock *LoopHeaderBB, 1892 BlockChain &Chain, BlockFilterSet *BlockFilter, 1893 MachineFunction::iterator &PrevUnplacedBlockIt) { 1894 bool Removed, DuplicatedToLPred; 1895 bool DuplicatedToOriginalLPred; 1896 Removed = maybeTailDuplicateBlock(BB, LPred, Chain, BlockFilter, 1897 PrevUnplacedBlockIt, 1898 DuplicatedToLPred); 1899 if (!Removed) 1900 return false; 1901 DuplicatedToOriginalLPred = DuplicatedToLPred; 1902 // Iteratively try to duplicate again. It can happen that a block that is 1903 // duplicated into is still small enough to be duplicated again. 1904 // No need to call markBlockSuccessors in this case, as the blocks being 1905 // duplicated from here on are already scheduled. 1906 // Note that DuplicatedToLPred always implies Removed. 1907 while (DuplicatedToLPred) { 1908 assert (Removed && "Block must have been removed to be duplicated into its " 1909 "layout predecessor."); 1910 MachineBasicBlock *DupBB, *DupPred; 1911 // The removal callback causes Chain.end() to be updated when a block is 1912 // removed. On the first pass through the loop, the chain end should be the 1913 // same as it was on function entry. On subsequent passes, because we are 1914 // duplicating the block at the end of the chain, if it is removed the 1915 // chain will have shrunk by one block. 1916 BlockChain::iterator ChainEnd = Chain.end(); 1917 DupBB = *(--ChainEnd); 1918 // Now try to duplicate again. 1919 if (ChainEnd == Chain.begin()) 1920 break; 1921 DupPred = *std::prev(ChainEnd); 1922 Removed = maybeTailDuplicateBlock(DupBB, DupPred, Chain, BlockFilter, 1923 PrevUnplacedBlockIt, 1924 DuplicatedToLPred); 1925 } 1926 // If BB was duplicated into LPred, it is now scheduled. But because it was 1927 // removed, markChainSuccessors won't be called for its chain. Instead we 1928 // call markBlockSuccessors for LPred to achieve the same effect. This must go 1929 // at the end because repeating the tail duplication can increase the number 1930 // of unscheduled predecessors. 1931 LPred = *std::prev(Chain.end()); 1932 if (DuplicatedToOriginalLPred) 1933 markBlockSuccessors(Chain, LPred, LoopHeaderBB, BlockFilter); 1934 return true; 1935 } 1936 1937 /// Tail duplicate \p BB into (some) predecessors if profitable. 1938 /// \p BB - Basic block that may be duplicated 1939 /// \p LPred - Chosen layout predecessor of \p BB 1940 /// \p Chain - Chain to which \p LPred belongs, and \p BB will belong. 1941 /// \p BlockFilter - Set of blocks that belong to the loop being laid out. 1942 /// Used to identify which blocks to update predecessor 1943 /// counts. 1944 /// \p PrevUnplacedBlockIt - Iterator pointing to the last block that was 1945 /// chosen in the given order due to unnatural CFG 1946 /// only needed if \p BB is removed and 1947 /// \p PrevUnplacedBlockIt pointed to \p BB. 1948 /// \p DuplicatedToLPred - True if the block was duplicated into LPred. Will 1949 /// only be true if the block was removed. 1950 /// \return - True if the block was duplicated into all preds and removed. 1951 bool MachineBlockPlacement::maybeTailDuplicateBlock( 1952 MachineBasicBlock *BB, MachineBasicBlock *LPred, 1953 const BlockChain &Chain, BlockFilterSet *BlockFilter, 1954 MachineFunction::iterator &PrevUnplacedBlockIt, 1955 bool &DuplicatedToLPred) { 1956 1957 DuplicatedToLPred = false; 1958 DEBUG(dbgs() << "Redoing tail duplication for Succ#" 1959 << BB->getNumber() << "\n"); 1960 1961 if (!shouldTailDuplicate(BB)) 1962 return false; 1963 // This has to be a callback because none of it can be done after 1964 // BB is deleted. 1965 bool Removed = false; 1966 auto RemovalCallback = 1967 [&](MachineBasicBlock *RemBB) { 1968 // Signal to outer function 1969 Removed = true; 1970 1971 // Conservative default. 1972 bool InWorkList = true; 1973 // Remove from the Chain and Chain Map 1974 if (BlockToChain.count(RemBB)) { 1975 BlockChain *Chain = BlockToChain[RemBB]; 1976 InWorkList = Chain->UnscheduledPredecessors == 0; 1977 Chain->remove(RemBB); 1978 BlockToChain.erase(RemBB); 1979 } 1980 1981 // Handle the unplaced block iterator 1982 if (&(*PrevUnplacedBlockIt) == RemBB) { 1983 PrevUnplacedBlockIt++; 1984 } 1985 1986 // Handle the Work Lists 1987 if (InWorkList) { 1988 SmallVectorImpl<MachineBasicBlock *> &RemoveList = BlockWorkList; 1989 if (RemBB->isEHPad()) 1990 RemoveList = EHPadWorkList; 1991 RemoveList.erase( 1992 remove_if(RemoveList, 1993 [RemBB](MachineBasicBlock *BB) {return BB == RemBB;}), 1994 RemoveList.end()); 1995 } 1996 1997 // Handle the filter set 1998 if (BlockFilter) { 1999 BlockFilter->remove(RemBB); 2000 } 2001 2002 // Remove the block from loop info. 2003 MLI->removeBlock(RemBB); 2004 if (RemBB == PreferredLoopExit) 2005 PreferredLoopExit = nullptr; 2006 2007 DEBUG(dbgs() << "TailDuplicator deleted block: " 2008 << getBlockName(RemBB) << "\n"); 2009 }; 2010 auto RemovalCallbackRef = 2011 llvm::function_ref<void(MachineBasicBlock*)>(RemovalCallback); 2012 2013 SmallVector<MachineBasicBlock *, 8> DuplicatedPreds; 2014 bool IsSimple = TailDup.isSimpleBB(BB); 2015 TailDup.tailDuplicateAndUpdate(IsSimple, BB, LPred, 2016 &DuplicatedPreds, &RemovalCallbackRef); 2017 2018 // Update UnscheduledPredecessors to reflect tail-duplication. 2019 DuplicatedToLPred = false; 2020 for (MachineBasicBlock *Pred : DuplicatedPreds) { 2021 // We're only looking for unscheduled predecessors that match the filter. 2022 BlockChain* PredChain = BlockToChain[Pred]; 2023 if (Pred == LPred) 2024 DuplicatedToLPred = true; 2025 if (Pred == LPred || (BlockFilter && !BlockFilter->count(Pred)) 2026 || PredChain == &Chain) 2027 continue; 2028 for (MachineBasicBlock *NewSucc : Pred->successors()) { 2029 if (BlockFilter && !BlockFilter->count(NewSucc)) 2030 continue; 2031 BlockChain *NewChain = BlockToChain[NewSucc]; 2032 if (NewChain != &Chain && NewChain != PredChain) 2033 NewChain->UnscheduledPredecessors++; 2034 } 2035 } 2036 return Removed; 2037 } 2038 2039 bool MachineBlockPlacement::runOnMachineFunction(MachineFunction &MF) { 2040 if (skipFunction(*MF.getFunction())) 2041 return false; 2042 2043 // Check for single-block functions and skip them. 2044 if (std::next(MF.begin()) == MF.end()) 2045 return false; 2046 2047 F = &MF; 2048 MBPI = &getAnalysis<MachineBranchProbabilityInfo>(); 2049 MBFI = llvm::make_unique<BranchFolder::MBFIWrapper>( 2050 getAnalysis<MachineBlockFrequencyInfo>()); 2051 MLI = &getAnalysis<MachineLoopInfo>(); 2052 TII = MF.getSubtarget().getInstrInfo(); 2053 TLI = MF.getSubtarget().getTargetLowering(); 2054 MDT = &getAnalysis<MachineDominatorTree>(); 2055 2056 // Initialize PreferredLoopExit to nullptr here since it may never be set if 2057 // there are no MachineLoops. 2058 PreferredLoopExit = nullptr; 2059 2060 if (TailDupPlacement) { 2061 unsigned TailDupSize = TailDuplicatePlacementThreshold; 2062 if (MF.getFunction()->optForSize()) 2063 TailDupSize = 1; 2064 TailDup.initMF(MF, MBPI, /* LayoutMode */ true, TailDupSize); 2065 } 2066 2067 assert(BlockToChain.empty()); 2068 2069 buildCFGChains(); 2070 2071 // Changing the layout can create new tail merging opportunities. 2072 TargetPassConfig *PassConfig = &getAnalysis<TargetPassConfig>(); 2073 // TailMerge can create jump into if branches that make CFG irreducible for 2074 // HW that requires structured CFG. 2075 bool EnableTailMerge = !MF.getTarget().requiresStructuredCFG() && 2076 PassConfig->getEnableTailMerge() && 2077 BranchFoldPlacement; 2078 // No tail merging opportunities if the block number is less than four. 2079 if (MF.size() > 3 && EnableTailMerge) { 2080 unsigned TailMergeSize = TailDuplicatePlacementThreshold + 1; 2081 BranchFolder BF(/*EnableTailMerge=*/true, /*CommonHoist=*/false, *MBFI, 2082 *MBPI, TailMergeSize); 2083 2084 if (BF.OptimizeFunction(MF, TII, MF.getSubtarget().getRegisterInfo(), 2085 getAnalysisIfAvailable<MachineModuleInfo>(), MLI, 2086 /*AfterBlockPlacement=*/true)) { 2087 // Redo the layout if tail merging creates/removes/moves blocks. 2088 BlockToChain.clear(); 2089 // Must redo the dominator tree if blocks were changed. 2090 MDT->runOnMachineFunction(MF); 2091 ChainAllocator.DestroyAll(); 2092 buildCFGChains(); 2093 } 2094 } 2095 2096 optimizeBranches(); 2097 alignBlocks(); 2098 2099 BlockToChain.clear(); 2100 ChainAllocator.DestroyAll(); 2101 2102 if (AlignAllBlock) 2103 // Align all of the blocks in the function to a specific alignment. 2104 for (MachineBasicBlock &MBB : MF) 2105 MBB.setAlignment(AlignAllBlock); 2106 else if (AlignAllNonFallThruBlocks) { 2107 // Align all of the blocks that have no fall-through predecessors to a 2108 // specific alignment. 2109 for (auto MBI = std::next(MF.begin()), MBE = MF.end(); MBI != MBE; ++MBI) { 2110 auto LayoutPred = std::prev(MBI); 2111 if (!LayoutPred->isSuccessor(&*MBI)) 2112 MBI->setAlignment(AlignAllNonFallThruBlocks); 2113 } 2114 } 2115 2116 // We always return true as we have no way to track whether the final order 2117 // differs from the original order. 2118 return true; 2119 } 2120 2121 namespace { 2122 /// \brief A pass to compute block placement statistics. 2123 /// 2124 /// A separate pass to compute interesting statistics for evaluating block 2125 /// placement. This is separate from the actual placement pass so that they can 2126 /// be computed in the absence of any placement transformations or when using 2127 /// alternative placement strategies. 2128 class MachineBlockPlacementStats : public MachineFunctionPass { 2129 /// \brief A handle to the branch probability pass. 2130 const MachineBranchProbabilityInfo *MBPI; 2131 2132 /// \brief A handle to the function-wide block frequency pass. 2133 const MachineBlockFrequencyInfo *MBFI; 2134 2135 public: 2136 static char ID; // Pass identification, replacement for typeid 2137 MachineBlockPlacementStats() : MachineFunctionPass(ID) { 2138 initializeMachineBlockPlacementStatsPass(*PassRegistry::getPassRegistry()); 2139 } 2140 2141 bool runOnMachineFunction(MachineFunction &F) override; 2142 2143 void getAnalysisUsage(AnalysisUsage &AU) const override { 2144 AU.addRequired<MachineBranchProbabilityInfo>(); 2145 AU.addRequired<MachineBlockFrequencyInfo>(); 2146 AU.setPreservesAll(); 2147 MachineFunctionPass::getAnalysisUsage(AU); 2148 } 2149 }; 2150 } 2151 2152 char MachineBlockPlacementStats::ID = 0; 2153 char &llvm::MachineBlockPlacementStatsID = MachineBlockPlacementStats::ID; 2154 INITIALIZE_PASS_BEGIN(MachineBlockPlacementStats, "block-placement-stats", 2155 "Basic Block Placement Stats", false, false) 2156 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo) 2157 INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo) 2158 INITIALIZE_PASS_END(MachineBlockPlacementStats, "block-placement-stats", 2159 "Basic Block Placement Stats", false, false) 2160 2161 bool MachineBlockPlacementStats::runOnMachineFunction(MachineFunction &F) { 2162 // Check for single-block functions and skip them. 2163 if (std::next(F.begin()) == F.end()) 2164 return false; 2165 2166 MBPI = &getAnalysis<MachineBranchProbabilityInfo>(); 2167 MBFI = &getAnalysis<MachineBlockFrequencyInfo>(); 2168 2169 for (MachineBasicBlock &MBB : F) { 2170 BlockFrequency BlockFreq = MBFI->getBlockFreq(&MBB); 2171 Statistic &NumBranches = 2172 (MBB.succ_size() > 1) ? NumCondBranches : NumUncondBranches; 2173 Statistic &BranchTakenFreq = 2174 (MBB.succ_size() > 1) ? CondBranchTakenFreq : UncondBranchTakenFreq; 2175 for (MachineBasicBlock *Succ : MBB.successors()) { 2176 // Skip if this successor is a fallthrough. 2177 if (MBB.isLayoutSuccessor(Succ)) 2178 continue; 2179 2180 BlockFrequency EdgeFreq = 2181 BlockFreq * MBPI->getEdgeProbability(&MBB, Succ); 2182 ++NumBranches; 2183 BranchTakenFreq += EdgeFreq.getFrequency(); 2184 } 2185 } 2186 2187 return false; 2188 } 2189