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