1 //===- MachineBlockPlacement.cpp - Basic Block Code Layout optimization ---===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements basic block placement transformations using the CFG 10 // structure and branch probability estimates. 11 // 12 // The pass strives to preserve the structure of the CFG (that is, retain 13 // a topological ordering of basic blocks) in the absence of a *strong* signal 14 // to the contrary from probabilities. However, within the CFG structure, it 15 // attempts to choose an ordering which favors placing more likely sequences of 16 // blocks adjacent to each other. 17 // 18 // The algorithm works from the inner-most loop within a function outward, and 19 // at each stage walks through the basic blocks, trying to coalesce them into 20 // sequential chains where allowed by the CFG (or demanded by heavy 21 // probabilities). Finally, it walks the blocks in topological order, and the 22 // first time it reaches a chain of basic blocks, it schedules them in the 23 // function in-order. 24 // 25 //===----------------------------------------------------------------------===// 26 27 #include "BranchFolding.h" 28 #include "llvm/ADT/ArrayRef.h" 29 #include "llvm/ADT/DenseMap.h" 30 #include "llvm/ADT/STLExtras.h" 31 #include "llvm/ADT/SetVector.h" 32 #include "llvm/ADT/SmallPtrSet.h" 33 #include "llvm/ADT/SmallVector.h" 34 #include "llvm/ADT/Statistic.h" 35 #include "llvm/Analysis/BlockFrequencyInfoImpl.h" 36 #include "llvm/Analysis/ProfileSummaryInfo.h" 37 #include "llvm/CodeGen/MachineBasicBlock.h" 38 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h" 39 #include "llvm/CodeGen/MachineBranchProbabilityInfo.h" 40 #include "llvm/CodeGen/MachineFunction.h" 41 #include "llvm/CodeGen/MachineFunctionPass.h" 42 #include "llvm/CodeGen/MachineLoopInfo.h" 43 #include "llvm/CodeGen/MachineModuleInfo.h" 44 #include "llvm/CodeGen/MachinePostDominators.h" 45 #include "llvm/CodeGen/MachineSizeOpts.h" 46 #include "llvm/CodeGen/TailDuplicator.h" 47 #include "llvm/CodeGen/TargetInstrInfo.h" 48 #include "llvm/CodeGen/TargetLowering.h" 49 #include "llvm/CodeGen/TargetPassConfig.h" 50 #include "llvm/CodeGen/TargetSubtargetInfo.h" 51 #include "llvm/IR/DebugLoc.h" 52 #include "llvm/IR/Function.h" 53 #include "llvm/InitializePasses.h" 54 #include "llvm/Pass.h" 55 #include "llvm/Support/Allocator.h" 56 #include "llvm/Support/BlockFrequency.h" 57 #include "llvm/Support/BranchProbability.h" 58 #include "llvm/Support/CodeGen.h" 59 #include "llvm/Support/CommandLine.h" 60 #include "llvm/Support/Compiler.h" 61 #include "llvm/Support/Debug.h" 62 #include "llvm/Support/raw_ostream.h" 63 #include "llvm/Target/TargetMachine.h" 64 #include "llvm/Transforms/Utils/CodeLayout.h" 65 #include <algorithm> 66 #include <cassert> 67 #include <cstdint> 68 #include <iterator> 69 #include <memory> 70 #include <string> 71 #include <tuple> 72 #include <utility> 73 #include <vector> 74 75 using namespace llvm; 76 77 #define DEBUG_TYPE "block-placement" 78 79 STATISTIC(NumCondBranches, "Number of conditional branches"); 80 STATISTIC(NumUncondBranches, "Number of unconditional branches"); 81 STATISTIC(CondBranchTakenFreq, 82 "Potential frequency of taking conditional branches"); 83 STATISTIC(UncondBranchTakenFreq, 84 "Potential frequency of taking unconditional branches"); 85 86 static cl::opt<unsigned> AlignAllBlock( 87 "align-all-blocks", 88 cl::desc("Force the alignment of all blocks in the function in log2 format " 89 "(e.g 4 means align on 16B boundaries)."), 90 cl::init(0), cl::Hidden); 91 92 static cl::opt<unsigned> AlignAllNonFallThruBlocks( 93 "align-all-nofallthru-blocks", 94 cl::desc("Force the alignment of all blocks that have no fall-through " 95 "predecessors (i.e. don't add nops that are executed). In log2 " 96 "format (e.g 4 means align on 16B boundaries)."), 97 cl::init(0), cl::Hidden); 98 99 static cl::opt<unsigned> MaxBytesForAlignmentOverride( 100 "max-bytes-for-alignment", 101 cl::desc("Forces the maximum bytes allowed to be emitted when padding for " 102 "alignment"), 103 cl::init(0), cl::Hidden); 104 105 // FIXME: Find a good default for this flag and remove the flag. 106 static cl::opt<unsigned> ExitBlockBias( 107 "block-placement-exit-block-bias", 108 cl::desc("Block frequency percentage a loop exit block needs " 109 "over the original exit to be considered the new exit."), 110 cl::init(0), cl::Hidden); 111 112 // Definition: 113 // - Outlining: placement of a basic block outside the chain or hot path. 114 115 static cl::opt<unsigned> LoopToColdBlockRatio( 116 "loop-to-cold-block-ratio", 117 cl::desc("Outline loop blocks from loop chain if (frequency of loop) / " 118 "(frequency of block) is greater than this ratio"), 119 cl::init(5), cl::Hidden); 120 121 static cl::opt<bool> ForceLoopColdBlock( 122 "force-loop-cold-block", 123 cl::desc("Force outlining cold blocks from loops."), 124 cl::init(false), cl::Hidden); 125 126 static cl::opt<bool> 127 PreciseRotationCost("precise-rotation-cost", 128 cl::desc("Model the cost of loop rotation more " 129 "precisely by using profile data."), 130 cl::init(false), cl::Hidden); 131 132 static cl::opt<bool> 133 ForcePreciseRotationCost("force-precise-rotation-cost", 134 cl::desc("Force the use of precise cost " 135 "loop rotation strategy."), 136 cl::init(false), cl::Hidden); 137 138 static cl::opt<unsigned> MisfetchCost( 139 "misfetch-cost", 140 cl::desc("Cost that models the probabilistic risk of an instruction " 141 "misfetch due to a jump comparing to falling through, whose cost " 142 "is zero."), 143 cl::init(1), cl::Hidden); 144 145 static cl::opt<unsigned> JumpInstCost("jump-inst-cost", 146 cl::desc("Cost of jump instructions."), 147 cl::init(1), cl::Hidden); 148 static cl::opt<bool> 149 TailDupPlacement("tail-dup-placement", 150 cl::desc("Perform tail duplication during placement. " 151 "Creates more fallthrough opportunites in " 152 "outline branches."), 153 cl::init(true), cl::Hidden); 154 155 static cl::opt<bool> 156 BranchFoldPlacement("branch-fold-placement", 157 cl::desc("Perform branch folding during placement. " 158 "Reduces code size."), 159 cl::init(true), cl::Hidden); 160 161 // Heuristic for tail duplication. 162 static cl::opt<unsigned> TailDupPlacementThreshold( 163 "tail-dup-placement-threshold", 164 cl::desc("Instruction cutoff for tail duplication during layout. " 165 "Tail merging during layout is forced to have a threshold " 166 "that won't conflict."), cl::init(2), 167 cl::Hidden); 168 169 // Heuristic for aggressive tail duplication. 170 static cl::opt<unsigned> TailDupPlacementAggressiveThreshold( 171 "tail-dup-placement-aggressive-threshold", 172 cl::desc("Instruction cutoff for aggressive tail duplication during " 173 "layout. Used at -O3. Tail merging during layout is forced to " 174 "have a threshold that won't conflict."), cl::init(4), 175 cl::Hidden); 176 177 // Heuristic for tail duplication. 178 static cl::opt<unsigned> TailDupPlacementPenalty( 179 "tail-dup-placement-penalty", 180 cl::desc("Cost penalty for blocks that can avoid breaking CFG by copying. " 181 "Copying can increase fallthrough, but it also increases icache " 182 "pressure. This parameter controls the penalty to account for that. " 183 "Percent as integer."), 184 cl::init(2), 185 cl::Hidden); 186 187 // Heuristic for tail duplication if profile count is used in cost model. 188 static cl::opt<unsigned> TailDupProfilePercentThreshold( 189 "tail-dup-profile-percent-threshold", 190 cl::desc("If profile count information is used in tail duplication cost " 191 "model, the gained fall through number from tail duplication " 192 "should be at least this percent of hot count."), 193 cl::init(50), cl::Hidden); 194 195 // Heuristic for triangle chains. 196 static cl::opt<unsigned> TriangleChainCount( 197 "triangle-chain-count", 198 cl::desc("Number of triangle-shaped-CFG's that need to be in a row for the " 199 "triangle tail duplication heuristic to kick in. 0 to disable."), 200 cl::init(2), 201 cl::Hidden); 202 203 extern cl::opt<bool> EnableExtTspBlockPlacement; 204 205 namespace llvm { 206 extern cl::opt<unsigned> StaticLikelyProb; 207 extern cl::opt<unsigned> ProfileLikelyProb; 208 209 // Internal option used to control BFI display only after MBP pass. 210 // Defined in CodeGen/MachineBlockFrequencyInfo.cpp: 211 // -view-block-layout-with-bfi= 212 extern cl::opt<GVDAGType> ViewBlockLayoutWithBFI; 213 214 // Command line option to specify the name of the function for CFG dump 215 // Defined in Analysis/BlockFrequencyInfo.cpp: -view-bfi-func-name= 216 extern cl::opt<std::string> ViewBlockFreqFuncName; 217 } // namespace llvm 218 219 namespace { 220 221 class BlockChain; 222 223 /// Type for our function-wide basic block -> block chain mapping. 224 using BlockToChainMapType = DenseMap<const MachineBasicBlock *, BlockChain *>; 225 226 /// A chain of blocks which will be laid out contiguously. 227 /// 228 /// This is the datastructure representing a chain of consecutive blocks that 229 /// are profitable to layout together in order to maximize fallthrough 230 /// probabilities and code locality. We also can use a block chain to represent 231 /// a sequence of basic blocks which have some external (correctness) 232 /// requirement for sequential layout. 233 /// 234 /// Chains can be built around a single basic block and can be merged to grow 235 /// them. They participate in a block-to-chain mapping, which is updated 236 /// automatically as chains are merged together. 237 class BlockChain { 238 /// The sequence of blocks belonging to this chain. 239 /// 240 /// This is the sequence of blocks for a particular chain. These will be laid 241 /// out in-order within the function. 242 SmallVector<MachineBasicBlock *, 4> Blocks; 243 244 /// A handle to the function-wide basic block to block chain mapping. 245 /// 246 /// This is retained in each block chain to simplify the computation of child 247 /// block chains for SCC-formation and iteration. We store the edges to child 248 /// basic blocks, and map them back to their associated chains using this 249 /// structure. 250 BlockToChainMapType &BlockToChain; 251 252 public: 253 /// Construct a new BlockChain. 254 /// 255 /// This builds a new block chain representing a single basic block in the 256 /// function. It also registers itself as the chain that block participates 257 /// in with the BlockToChain mapping. 258 BlockChain(BlockToChainMapType &BlockToChain, MachineBasicBlock *BB) 259 : Blocks(1, BB), BlockToChain(BlockToChain) { 260 assert(BB && "Cannot create a chain with a null basic block"); 261 BlockToChain[BB] = this; 262 } 263 264 /// Iterator over blocks within the chain. 265 using iterator = SmallVectorImpl<MachineBasicBlock *>::iterator; 266 using const_iterator = SmallVectorImpl<MachineBasicBlock *>::const_iterator; 267 268 /// Beginning of blocks within the chain. 269 iterator begin() { return Blocks.begin(); } 270 const_iterator begin() const { return Blocks.begin(); } 271 272 /// End of blocks within the chain. 273 iterator end() { return Blocks.end(); } 274 const_iterator end() const { return Blocks.end(); } 275 276 bool remove(MachineBasicBlock* BB) { 277 for(iterator i = begin(); i != end(); ++i) { 278 if (*i == BB) { 279 Blocks.erase(i); 280 return true; 281 } 282 } 283 return false; 284 } 285 286 /// Merge a block chain into this one. 287 /// 288 /// This routine merges a block chain into this one. It takes care of forming 289 /// a contiguous sequence of basic blocks, updating the edge list, and 290 /// updating the block -> chain mapping. It does not free or tear down the 291 /// old chain, but the old chain's block list is no longer valid. 292 void merge(MachineBasicBlock *BB, BlockChain *Chain) { 293 assert(BB && "Can't merge a null block."); 294 assert(!Blocks.empty() && "Can't merge into an empty chain."); 295 296 // Fast path in case we don't have a chain already. 297 if (!Chain) { 298 assert(!BlockToChain[BB] && 299 "Passed chain is null, but BB has entry in BlockToChain."); 300 Blocks.push_back(BB); 301 BlockToChain[BB] = this; 302 return; 303 } 304 305 assert(BB == *Chain->begin() && "Passed BB is not head of Chain."); 306 assert(Chain->begin() != Chain->end()); 307 308 // Update the incoming blocks to point to this chain, and add them to the 309 // chain structure. 310 for (MachineBasicBlock *ChainBB : *Chain) { 311 Blocks.push_back(ChainBB); 312 assert(BlockToChain[ChainBB] == Chain && "Incoming blocks not in chain."); 313 BlockToChain[ChainBB] = this; 314 } 315 } 316 317 #ifndef NDEBUG 318 /// Dump the blocks in this chain. 319 LLVM_DUMP_METHOD void dump() { 320 for (MachineBasicBlock *MBB : *this) 321 MBB->dump(); 322 } 323 #endif // NDEBUG 324 325 /// Count of predecessors of any block within the chain which have not 326 /// yet been scheduled. In general, we will delay scheduling this chain 327 /// until those predecessors are scheduled (or we find a sufficiently good 328 /// reason to override this heuristic.) Note that when forming loop chains, 329 /// blocks outside the loop are ignored and treated as if they were already 330 /// scheduled. 331 /// 332 /// Note: This field is reinitialized multiple times - once for each loop, 333 /// and then once for the function as a whole. 334 unsigned UnscheduledPredecessors = 0; 335 }; 336 337 class MachineBlockPlacement : public MachineFunctionPass { 338 /// A type for a block filter set. 339 using BlockFilterSet = SmallSetVector<const MachineBasicBlock *, 16>; 340 341 /// Pair struct containing basic block and taildup profitability 342 struct BlockAndTailDupResult { 343 MachineBasicBlock *BB; 344 bool ShouldTailDup; 345 }; 346 347 /// Triple struct containing edge weight and the edge. 348 struct WeightedEdge { 349 BlockFrequency Weight; 350 MachineBasicBlock *Src; 351 MachineBasicBlock *Dest; 352 }; 353 354 /// work lists of blocks that are ready to be laid out 355 SmallVector<MachineBasicBlock *, 16> BlockWorkList; 356 SmallVector<MachineBasicBlock *, 16> EHPadWorkList; 357 358 /// Edges that have already been computed as optimal. 359 DenseMap<const MachineBasicBlock *, BlockAndTailDupResult> ComputedEdges; 360 361 /// Machine Function 362 MachineFunction *F; 363 364 /// A handle to the branch probability pass. 365 const MachineBranchProbabilityInfo *MBPI; 366 367 /// A handle to the function-wide block frequency pass. 368 std::unique_ptr<MBFIWrapper> MBFI; 369 370 /// A handle to the loop info. 371 MachineLoopInfo *MLI; 372 373 /// Preferred loop exit. 374 /// Member variable for convenience. It may be removed by duplication deep 375 /// in the call stack. 376 MachineBasicBlock *PreferredLoopExit; 377 378 /// A handle to the target's instruction info. 379 const TargetInstrInfo *TII; 380 381 /// A handle to the target's lowering info. 382 const TargetLoweringBase *TLI; 383 384 /// A handle to the post dominator tree. 385 MachinePostDominatorTree *MPDT; 386 387 ProfileSummaryInfo *PSI; 388 389 /// Duplicator used to duplicate tails during placement. 390 /// 391 /// Placement decisions can open up new tail duplication opportunities, but 392 /// since tail duplication affects placement decisions of later blocks, it 393 /// must be done inline. 394 TailDuplicator TailDup; 395 396 /// Partial tail duplication threshold. 397 BlockFrequency DupThreshold; 398 399 /// True: use block profile count to compute tail duplication cost. 400 /// False: use block frequency to compute tail duplication cost. 401 bool UseProfileCount; 402 403 /// Allocator and owner of BlockChain structures. 404 /// 405 /// We build BlockChains lazily while processing the loop structure of 406 /// a function. To reduce malloc traffic, we allocate them using this 407 /// slab-like allocator, and destroy them after the pass completes. An 408 /// important guarantee is that this allocator produces stable pointers to 409 /// the chains. 410 SpecificBumpPtrAllocator<BlockChain> ChainAllocator; 411 412 /// Function wide BasicBlock to BlockChain mapping. 413 /// 414 /// This mapping allows efficiently moving from any given basic block to the 415 /// BlockChain it participates in, if any. We use it to, among other things, 416 /// allow implicitly defining edges between chains as the existing edges 417 /// between basic blocks. 418 DenseMap<const MachineBasicBlock *, BlockChain *> BlockToChain; 419 420 #ifndef NDEBUG 421 /// The set of basic blocks that have terminators that cannot be fully 422 /// analyzed. These basic blocks cannot be re-ordered safely by 423 /// MachineBlockPlacement, and we must preserve physical layout of these 424 /// blocks and their successors through the pass. 425 SmallPtrSet<MachineBasicBlock *, 4> BlocksWithUnanalyzableExits; 426 #endif 427 428 /// Get block profile count or frequency according to UseProfileCount. 429 /// The return value is used to model tail duplication cost. 430 BlockFrequency getBlockCountOrFrequency(const MachineBasicBlock *BB) { 431 if (UseProfileCount) { 432 auto Count = MBFI->getBlockProfileCount(BB); 433 if (Count) 434 return *Count; 435 else 436 return 0; 437 } else 438 return MBFI->getBlockFreq(BB); 439 } 440 441 /// Scale the DupThreshold according to basic block size. 442 BlockFrequency scaleThreshold(MachineBasicBlock *BB); 443 void initDupThreshold(); 444 445 /// Decrease the UnscheduledPredecessors count for all blocks in chain, and 446 /// if the count goes to 0, add them to the appropriate work list. 447 void markChainSuccessors( 448 const BlockChain &Chain, const MachineBasicBlock *LoopHeaderBB, 449 const BlockFilterSet *BlockFilter = nullptr); 450 451 /// Decrease the UnscheduledPredecessors count for a single block, and 452 /// if the count goes to 0, add them to the appropriate work list. 453 void markBlockSuccessors( 454 const BlockChain &Chain, const MachineBasicBlock *BB, 455 const MachineBasicBlock *LoopHeaderBB, 456 const BlockFilterSet *BlockFilter = nullptr); 457 458 BranchProbability 459 collectViableSuccessors( 460 const MachineBasicBlock *BB, const BlockChain &Chain, 461 const BlockFilterSet *BlockFilter, 462 SmallVector<MachineBasicBlock *, 4> &Successors); 463 bool isBestSuccessor(MachineBasicBlock *BB, MachineBasicBlock *Pred, 464 BlockFilterSet *BlockFilter); 465 void findDuplicateCandidates(SmallVectorImpl<MachineBasicBlock *> &Candidates, 466 MachineBasicBlock *BB, 467 BlockFilterSet *BlockFilter); 468 bool repeatedlyTailDuplicateBlock( 469 MachineBasicBlock *BB, MachineBasicBlock *&LPred, 470 const MachineBasicBlock *LoopHeaderBB, 471 BlockChain &Chain, BlockFilterSet *BlockFilter, 472 MachineFunction::iterator &PrevUnplacedBlockIt); 473 bool maybeTailDuplicateBlock( 474 MachineBasicBlock *BB, MachineBasicBlock *LPred, 475 BlockChain &Chain, BlockFilterSet *BlockFilter, 476 MachineFunction::iterator &PrevUnplacedBlockIt, 477 bool &DuplicatedToLPred); 478 bool hasBetterLayoutPredecessor( 479 const MachineBasicBlock *BB, const MachineBasicBlock *Succ, 480 const BlockChain &SuccChain, BranchProbability SuccProb, 481 BranchProbability RealSuccProb, const BlockChain &Chain, 482 const BlockFilterSet *BlockFilter); 483 BlockAndTailDupResult selectBestSuccessor( 484 const MachineBasicBlock *BB, const BlockChain &Chain, 485 const BlockFilterSet *BlockFilter); 486 MachineBasicBlock *selectBestCandidateBlock( 487 const BlockChain &Chain, SmallVectorImpl<MachineBasicBlock *> &WorkList); 488 MachineBasicBlock *getFirstUnplacedBlock( 489 const BlockChain &PlacedChain, 490 MachineFunction::iterator &PrevUnplacedBlockIt, 491 const BlockFilterSet *BlockFilter); 492 493 /// Add a basic block to the work list if it is appropriate. 494 /// 495 /// If the optional parameter BlockFilter is provided, only MBB 496 /// present in the set will be added to the worklist. If nullptr 497 /// is provided, no filtering occurs. 498 void fillWorkLists(const MachineBasicBlock *MBB, 499 SmallPtrSetImpl<BlockChain *> &UpdatedPreds, 500 const BlockFilterSet *BlockFilter); 501 502 void buildChain(const MachineBasicBlock *BB, BlockChain &Chain, 503 BlockFilterSet *BlockFilter = nullptr); 504 bool canMoveBottomBlockToTop(const MachineBasicBlock *BottomBlock, 505 const MachineBasicBlock *OldTop); 506 bool hasViableTopFallthrough(const MachineBasicBlock *Top, 507 const BlockFilterSet &LoopBlockSet); 508 BlockFrequency TopFallThroughFreq(const MachineBasicBlock *Top, 509 const BlockFilterSet &LoopBlockSet); 510 BlockFrequency FallThroughGains(const MachineBasicBlock *NewTop, 511 const MachineBasicBlock *OldTop, 512 const MachineBasicBlock *ExitBB, 513 const BlockFilterSet &LoopBlockSet); 514 MachineBasicBlock *findBestLoopTopHelper(MachineBasicBlock *OldTop, 515 const MachineLoop &L, const BlockFilterSet &LoopBlockSet); 516 MachineBasicBlock *findBestLoopTop( 517 const MachineLoop &L, const BlockFilterSet &LoopBlockSet); 518 MachineBasicBlock *findBestLoopExit( 519 const MachineLoop &L, const BlockFilterSet &LoopBlockSet, 520 BlockFrequency &ExitFreq); 521 BlockFilterSet collectLoopBlockSet(const MachineLoop &L); 522 void buildLoopChains(const MachineLoop &L); 523 void rotateLoop( 524 BlockChain &LoopChain, const MachineBasicBlock *ExitingBB, 525 BlockFrequency ExitFreq, const BlockFilterSet &LoopBlockSet); 526 void rotateLoopWithProfile( 527 BlockChain &LoopChain, const MachineLoop &L, 528 const BlockFilterSet &LoopBlockSet); 529 void buildCFGChains(); 530 void optimizeBranches(); 531 void alignBlocks(); 532 /// Returns true if a block should be tail-duplicated to increase fallthrough 533 /// opportunities. 534 bool shouldTailDuplicate(MachineBasicBlock *BB); 535 /// Check the edge frequencies to see if tail duplication will increase 536 /// fallthroughs. 537 bool isProfitableToTailDup( 538 const MachineBasicBlock *BB, const MachineBasicBlock *Succ, 539 BranchProbability QProb, 540 const BlockChain &Chain, const BlockFilterSet *BlockFilter); 541 542 /// Check for a trellis layout. 543 bool isTrellis(const MachineBasicBlock *BB, 544 const SmallVectorImpl<MachineBasicBlock *> &ViableSuccs, 545 const BlockChain &Chain, const BlockFilterSet *BlockFilter); 546 547 /// Get the best successor given a trellis layout. 548 BlockAndTailDupResult getBestTrellisSuccessor( 549 const MachineBasicBlock *BB, 550 const SmallVectorImpl<MachineBasicBlock *> &ViableSuccs, 551 BranchProbability AdjustedSumProb, const BlockChain &Chain, 552 const BlockFilterSet *BlockFilter); 553 554 /// Get the best pair of non-conflicting edges. 555 static std::pair<WeightedEdge, WeightedEdge> getBestNonConflictingEdges( 556 const MachineBasicBlock *BB, 557 MutableArrayRef<SmallVector<WeightedEdge, 8>> Edges); 558 559 /// Returns true if a block can tail duplicate into all unplaced 560 /// predecessors. Filters based on loop. 561 bool canTailDuplicateUnplacedPreds( 562 const MachineBasicBlock *BB, MachineBasicBlock *Succ, 563 const BlockChain &Chain, const BlockFilterSet *BlockFilter); 564 565 /// Find chains of triangles to tail-duplicate where a global analysis works, 566 /// but a local analysis would not find them. 567 void precomputeTriangleChains(); 568 569 /// Apply a post-processing step optimizing block placement. 570 void applyExtTsp(); 571 572 /// Modify the existing block placement in the function and adjust all jumps. 573 void assignBlockOrder(const std::vector<const MachineBasicBlock *> &NewOrder); 574 575 /// Create a single CFG chain from the current block order. 576 void createCFGChainExtTsp(); 577 578 public: 579 static char ID; // Pass identification, replacement for typeid 580 581 MachineBlockPlacement() : MachineFunctionPass(ID) { 582 initializeMachineBlockPlacementPass(*PassRegistry::getPassRegistry()); 583 } 584 585 bool runOnMachineFunction(MachineFunction &F) override; 586 587 bool allowTailDupPlacement() const { 588 assert(F); 589 return TailDupPlacement && !F->getTarget().requiresStructuredCFG(); 590 } 591 592 void getAnalysisUsage(AnalysisUsage &AU) const override { 593 AU.addRequired<MachineBranchProbabilityInfo>(); 594 AU.addRequired<MachineBlockFrequencyInfo>(); 595 if (TailDupPlacement) 596 AU.addRequired<MachinePostDominatorTree>(); 597 AU.addRequired<MachineLoopInfo>(); 598 AU.addRequired<ProfileSummaryInfoWrapperPass>(); 599 AU.addRequired<TargetPassConfig>(); 600 MachineFunctionPass::getAnalysisUsage(AU); 601 } 602 }; 603 604 } // end anonymous namespace 605 606 char MachineBlockPlacement::ID = 0; 607 608 char &llvm::MachineBlockPlacementID = MachineBlockPlacement::ID; 609 610 INITIALIZE_PASS_BEGIN(MachineBlockPlacement, DEBUG_TYPE, 611 "Branch Probability Basic Block Placement", false, false) 612 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo) 613 INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo) 614 INITIALIZE_PASS_DEPENDENCY(MachinePostDominatorTree) 615 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo) 616 INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass) 617 INITIALIZE_PASS_END(MachineBlockPlacement, DEBUG_TYPE, 618 "Branch Probability Basic Block Placement", false, false) 619 620 #ifndef NDEBUG 621 /// Helper to print the name of a MBB. 622 /// 623 /// Only used by debug logging. 624 static std::string getBlockName(const MachineBasicBlock *BB) { 625 std::string Result; 626 raw_string_ostream OS(Result); 627 OS << printMBBReference(*BB); 628 OS << " ('" << BB->getName() << "')"; 629 OS.flush(); 630 return Result; 631 } 632 #endif 633 634 /// Mark a chain's successors as having one fewer preds. 635 /// 636 /// When a chain is being merged into the "placed" chain, this routine will 637 /// quickly walk the successors of each block in the chain and mark them as 638 /// having one fewer active predecessor. It also adds any successors of this 639 /// chain which reach the zero-predecessor state to the appropriate worklist. 640 void MachineBlockPlacement::markChainSuccessors( 641 const BlockChain &Chain, const MachineBasicBlock *LoopHeaderBB, 642 const BlockFilterSet *BlockFilter) { 643 // Walk all the blocks in this chain, marking their successors as having 644 // a predecessor placed. 645 for (MachineBasicBlock *MBB : Chain) { 646 markBlockSuccessors(Chain, MBB, LoopHeaderBB, BlockFilter); 647 } 648 } 649 650 /// Mark a single block's successors as having one fewer preds. 651 /// 652 /// Under normal circumstances, this is only called by markChainSuccessors, 653 /// but if a block that was to be placed is completely tail-duplicated away, 654 /// and was duplicated into the chain end, we need to redo markBlockSuccessors 655 /// for just that block. 656 void MachineBlockPlacement::markBlockSuccessors( 657 const BlockChain &Chain, const MachineBasicBlock *MBB, 658 const MachineBasicBlock *LoopHeaderBB, const BlockFilterSet *BlockFilter) { 659 // Add any successors for which this is the only un-placed in-loop 660 // predecessor to the worklist as a viable candidate for CFG-neutral 661 // placement. No subsequent placement of this block will violate the CFG 662 // shape, so we get to use heuristics to choose a favorable placement. 663 for (MachineBasicBlock *Succ : MBB->successors()) { 664 if (BlockFilter && !BlockFilter->count(Succ)) 665 continue; 666 BlockChain &SuccChain = *BlockToChain[Succ]; 667 // Disregard edges within a fixed chain, or edges to the loop header. 668 if (&Chain == &SuccChain || Succ == LoopHeaderBB) 669 continue; 670 671 // This is a cross-chain edge that is within the loop, so decrement the 672 // loop predecessor count of the destination chain. 673 if (SuccChain.UnscheduledPredecessors == 0 || 674 --SuccChain.UnscheduledPredecessors > 0) 675 continue; 676 677 auto *NewBB = *SuccChain.begin(); 678 if (NewBB->isEHPad()) 679 EHPadWorkList.push_back(NewBB); 680 else 681 BlockWorkList.push_back(NewBB); 682 } 683 } 684 685 /// This helper function collects the set of successors of block 686 /// \p BB that are allowed to be its layout successors, and return 687 /// the total branch probability of edges from \p BB to those 688 /// blocks. 689 BranchProbability MachineBlockPlacement::collectViableSuccessors( 690 const MachineBasicBlock *BB, const BlockChain &Chain, 691 const BlockFilterSet *BlockFilter, 692 SmallVector<MachineBasicBlock *, 4> &Successors) { 693 // Adjust edge probabilities by excluding edges pointing to blocks that is 694 // either not in BlockFilter or is already in the current chain. Consider the 695 // following CFG: 696 // 697 // --->A 698 // | / \ 699 // | B C 700 // | \ / \ 701 // ----D E 702 // 703 // Assume A->C is very hot (>90%), and C->D has a 50% probability, then after 704 // A->C is chosen as a fall-through, D won't be selected as a successor of C 705 // due to CFG constraint (the probability of C->D is not greater than 706 // HotProb to break topo-order). If we exclude E that is not in BlockFilter 707 // when calculating the probability of C->D, D will be selected and we 708 // will get A C D B as the layout of this loop. 709 auto AdjustedSumProb = BranchProbability::getOne(); 710 for (MachineBasicBlock *Succ : BB->successors()) { 711 bool SkipSucc = false; 712 if (Succ->isEHPad() || (BlockFilter && !BlockFilter->count(Succ))) { 713 SkipSucc = true; 714 } else { 715 BlockChain *SuccChain = BlockToChain[Succ]; 716 if (SuccChain == &Chain) { 717 SkipSucc = true; 718 } else if (Succ != *SuccChain->begin()) { 719 LLVM_DEBUG(dbgs() << " " << getBlockName(Succ) 720 << " -> Mid chain!\n"); 721 continue; 722 } 723 } 724 if (SkipSucc) 725 AdjustedSumProb -= MBPI->getEdgeProbability(BB, Succ); 726 else 727 Successors.push_back(Succ); 728 } 729 730 return AdjustedSumProb; 731 } 732 733 /// The helper function returns the branch probability that is adjusted 734 /// or normalized over the new total \p AdjustedSumProb. 735 static BranchProbability 736 getAdjustedProbability(BranchProbability OrigProb, 737 BranchProbability AdjustedSumProb) { 738 BranchProbability SuccProb; 739 uint32_t SuccProbN = OrigProb.getNumerator(); 740 uint32_t SuccProbD = AdjustedSumProb.getNumerator(); 741 if (SuccProbN >= SuccProbD) 742 SuccProb = BranchProbability::getOne(); 743 else 744 SuccProb = BranchProbability(SuccProbN, SuccProbD); 745 746 return SuccProb; 747 } 748 749 /// Check if \p BB has exactly the successors in \p Successors. 750 static bool 751 hasSameSuccessors(MachineBasicBlock &BB, 752 SmallPtrSetImpl<const MachineBasicBlock *> &Successors) { 753 if (BB.succ_size() != Successors.size()) 754 return false; 755 // We don't want to count self-loops 756 if (Successors.count(&BB)) 757 return false; 758 for (MachineBasicBlock *Succ : BB.successors()) 759 if (!Successors.count(Succ)) 760 return false; 761 return true; 762 } 763 764 /// Check if a block should be tail duplicated to increase fallthrough 765 /// opportunities. 766 /// \p BB Block to check. 767 bool MachineBlockPlacement::shouldTailDuplicate(MachineBasicBlock *BB) { 768 // Blocks with single successors don't create additional fallthrough 769 // opportunities. Don't duplicate them. TODO: When conditional exits are 770 // analyzable, allow them to be duplicated. 771 bool IsSimple = TailDup.isSimpleBB(BB); 772 773 if (BB->succ_size() == 1) 774 return false; 775 return TailDup.shouldTailDuplicate(IsSimple, *BB); 776 } 777 778 /// Compare 2 BlockFrequency's with a small penalty for \p A. 779 /// In order to be conservative, we apply a X% penalty to account for 780 /// increased icache pressure and static heuristics. For small frequencies 781 /// we use only the numerators to improve accuracy. For simplicity, we assume the 782 /// penalty is less than 100% 783 /// TODO(iteratee): Use 64-bit fixed point edge frequencies everywhere. 784 static bool greaterWithBias(BlockFrequency A, BlockFrequency B, 785 uint64_t EntryFreq) { 786 BranchProbability ThresholdProb(TailDupPlacementPenalty, 100); 787 BlockFrequency Gain = A - B; 788 return (Gain / ThresholdProb).getFrequency() >= EntryFreq; 789 } 790 791 /// Check the edge frequencies to see if tail duplication will increase 792 /// fallthroughs. It only makes sense to call this function when 793 /// \p Succ would not be chosen otherwise. Tail duplication of \p Succ is 794 /// always locally profitable if we would have picked \p Succ without 795 /// considering duplication. 796 bool MachineBlockPlacement::isProfitableToTailDup( 797 const MachineBasicBlock *BB, const MachineBasicBlock *Succ, 798 BranchProbability QProb, 799 const BlockChain &Chain, const BlockFilterSet *BlockFilter) { 800 // We need to do a probability calculation to make sure this is profitable. 801 // First: does succ have a successor that post-dominates? This affects the 802 // calculation. The 2 relevant cases are: 803 // BB BB 804 // | \Qout | \Qout 805 // P| C |P C 806 // = C' = C' 807 // | /Qin | /Qin 808 // | / | / 809 // Succ Succ 810 // / \ | \ V 811 // U/ =V |U \ 812 // / \ = D 813 // D E | / 814 // | / 815 // |/ 816 // PDom 817 // '=' : Branch taken for that CFG edge 818 // In the second case, Placing Succ while duplicating it into C prevents the 819 // fallthrough of Succ into either D or PDom, because they now have C as an 820 // unplaced predecessor 821 822 // Start by figuring out which case we fall into 823 MachineBasicBlock *PDom = nullptr; 824 SmallVector<MachineBasicBlock *, 4> SuccSuccs; 825 // Only scan the relevant successors 826 auto AdjustedSuccSumProb = 827 collectViableSuccessors(Succ, Chain, BlockFilter, SuccSuccs); 828 BranchProbability PProb = MBPI->getEdgeProbability(BB, Succ); 829 auto BBFreq = MBFI->getBlockFreq(BB); 830 auto SuccFreq = MBFI->getBlockFreq(Succ); 831 BlockFrequency P = BBFreq * PProb; 832 BlockFrequency Qout = BBFreq * QProb; 833 uint64_t EntryFreq = MBFI->getEntryFreq(); 834 // If there are no more successors, it is profitable to copy, as it strictly 835 // increases fallthrough. 836 if (SuccSuccs.size() == 0) 837 return greaterWithBias(P, Qout, EntryFreq); 838 839 auto BestSuccSucc = BranchProbability::getZero(); 840 // Find the PDom or the best Succ if no PDom exists. 841 for (MachineBasicBlock *SuccSucc : SuccSuccs) { 842 auto Prob = MBPI->getEdgeProbability(Succ, SuccSucc); 843 if (Prob > BestSuccSucc) 844 BestSuccSucc = Prob; 845 if (PDom == nullptr) 846 if (MPDT->dominates(SuccSucc, Succ)) { 847 PDom = SuccSucc; 848 break; 849 } 850 } 851 // For the comparisons, we need to know Succ's best incoming edge that isn't 852 // from BB. 853 auto SuccBestPred = BlockFrequency(0); 854 for (MachineBasicBlock *SuccPred : Succ->predecessors()) { 855 if (SuccPred == Succ || SuccPred == BB 856 || BlockToChain[SuccPred] == &Chain 857 || (BlockFilter && !BlockFilter->count(SuccPred))) 858 continue; 859 auto Freq = MBFI->getBlockFreq(SuccPred) 860 * MBPI->getEdgeProbability(SuccPred, Succ); 861 if (Freq > SuccBestPred) 862 SuccBestPred = Freq; 863 } 864 // Qin is Succ's best unplaced incoming edge that isn't BB 865 BlockFrequency Qin = SuccBestPred; 866 // If it doesn't have a post-dominating successor, here is the calculation: 867 // BB BB 868 // | \Qout | \ 869 // P| C | = 870 // = C' | C 871 // | /Qin | | 872 // | / | C' (+Succ) 873 // Succ Succ /| 874 // / \ | \/ | 875 // U/ =V | == | 876 // / \ | / \| 877 // D E D E 878 // '=' : Branch taken for that CFG edge 879 // Cost in the first case is: P + V 880 // For this calculation, we always assume P > Qout. If Qout > P 881 // The result of this function will be ignored at the caller. 882 // Let F = SuccFreq - Qin 883 // Cost in the second case is: Qout + min(Qin, F) * U + max(Qin, F) * V 884 885 if (PDom == nullptr || !Succ->isSuccessor(PDom)) { 886 BranchProbability UProb = BestSuccSucc; 887 BranchProbability VProb = AdjustedSuccSumProb - UProb; 888 BlockFrequency F = SuccFreq - Qin; 889 BlockFrequency V = SuccFreq * VProb; 890 BlockFrequency QinU = std::min(Qin, F) * UProb; 891 BlockFrequency BaseCost = P + V; 892 BlockFrequency DupCost = Qout + QinU + std::max(Qin, F) * VProb; 893 return greaterWithBias(BaseCost, DupCost, EntryFreq); 894 } 895 BranchProbability UProb = MBPI->getEdgeProbability(Succ, PDom); 896 BranchProbability VProb = AdjustedSuccSumProb - UProb; 897 BlockFrequency U = SuccFreq * UProb; 898 BlockFrequency V = SuccFreq * VProb; 899 BlockFrequency F = SuccFreq - Qin; 900 // If there is a post-dominating successor, here is the calculation: 901 // BB BB BB BB 902 // | \Qout | \ | \Qout | \ 903 // |P C | = |P C | = 904 // = C' |P C = C' |P C 905 // | /Qin | | | /Qin | | 906 // | / | C' (+Succ) | / | C' (+Succ) 907 // Succ Succ /| Succ Succ /| 908 // | \ V | \/ | | \ V | \/ | 909 // |U \ |U /\ =? |U = |U /\ | 910 // = D = = =?| | D | = =| 911 // | / |/ D | / |/ D 912 // | / | / | = | / 913 // |/ | / |/ | = 914 // Dom Dom Dom Dom 915 // '=' : Branch taken for that CFG edge 916 // The cost for taken branches in the first case is P + U 917 // Let F = SuccFreq - Qin 918 // The cost in the second case (assuming independence), given the layout: 919 // BB, Succ, (C+Succ), D, Dom or the layout: 920 // BB, Succ, D, Dom, (C+Succ) 921 // is Qout + max(F, Qin) * U + min(F, Qin) 922 // compare P + U vs Qout + P * U + Qin. 923 // 924 // The 3rd and 4th cases cover when Dom would be chosen to follow Succ. 925 // 926 // For the 3rd case, the cost is P + 2 * V 927 // For the 4th case, the cost is Qout + min(Qin, F) * U + max(Qin, F) * V + V 928 // We choose 4 over 3 when (P + V) > Qout + min(Qin, F) * U + max(Qin, F) * V 929 if (UProb > AdjustedSuccSumProb / 2 && 930 !hasBetterLayoutPredecessor(Succ, PDom, *BlockToChain[PDom], UProb, UProb, 931 Chain, BlockFilter)) 932 // Cases 3 & 4 933 return greaterWithBias( 934 (P + V), (Qout + std::max(Qin, F) * VProb + std::min(Qin, F) * UProb), 935 EntryFreq); 936 // Cases 1 & 2 937 return greaterWithBias((P + U), 938 (Qout + std::min(Qin, F) * AdjustedSuccSumProb + 939 std::max(Qin, F) * UProb), 940 EntryFreq); 941 } 942 943 /// Check for a trellis layout. \p BB is the upper part of a trellis if its 944 /// successors form the lower part of a trellis. A successor set S forms the 945 /// lower part of a trellis if all of the predecessors of S are either in S or 946 /// have all of S as successors. We ignore trellises where BB doesn't have 2 947 /// successors because for fewer than 2, it's trivial, and for 3 or greater they 948 /// are very uncommon and complex to compute optimally. Allowing edges within S 949 /// is not strictly a trellis, but the same algorithm works, so we allow it. 950 bool MachineBlockPlacement::isTrellis( 951 const MachineBasicBlock *BB, 952 const SmallVectorImpl<MachineBasicBlock *> &ViableSuccs, 953 const BlockChain &Chain, const BlockFilterSet *BlockFilter) { 954 // Technically BB could form a trellis with branching factor higher than 2. 955 // But that's extremely uncommon. 956 if (BB->succ_size() != 2 || ViableSuccs.size() != 2) 957 return false; 958 959 SmallPtrSet<const MachineBasicBlock *, 2> Successors(BB->succ_begin(), 960 BB->succ_end()); 961 // To avoid reviewing the same predecessors twice. 962 SmallPtrSet<const MachineBasicBlock *, 8> SeenPreds; 963 964 for (MachineBasicBlock *Succ : ViableSuccs) { 965 int PredCount = 0; 966 for (auto SuccPred : Succ->predecessors()) { 967 // Allow triangle successors, but don't count them. 968 if (Successors.count(SuccPred)) { 969 // Make sure that it is actually a triangle. 970 for (MachineBasicBlock *CheckSucc : SuccPred->successors()) 971 if (!Successors.count(CheckSucc)) 972 return false; 973 continue; 974 } 975 const BlockChain *PredChain = BlockToChain[SuccPred]; 976 if (SuccPred == BB || (BlockFilter && !BlockFilter->count(SuccPred)) || 977 PredChain == &Chain || PredChain == BlockToChain[Succ]) 978 continue; 979 ++PredCount; 980 // Perform the successor check only once. 981 if (!SeenPreds.insert(SuccPred).second) 982 continue; 983 if (!hasSameSuccessors(*SuccPred, Successors)) 984 return false; 985 } 986 // If one of the successors has only BB as a predecessor, it is not a 987 // trellis. 988 if (PredCount < 1) 989 return false; 990 } 991 return true; 992 } 993 994 /// Pick the highest total weight pair of edges that can both be laid out. 995 /// The edges in \p Edges[0] are assumed to have a different destination than 996 /// the edges in \p Edges[1]. Simple counting shows that the best pair is either 997 /// the individual highest weight edges to the 2 different destinations, or in 998 /// case of a conflict, one of them should be replaced with a 2nd best edge. 999 std::pair<MachineBlockPlacement::WeightedEdge, 1000 MachineBlockPlacement::WeightedEdge> 1001 MachineBlockPlacement::getBestNonConflictingEdges( 1002 const MachineBasicBlock *BB, 1003 MutableArrayRef<SmallVector<MachineBlockPlacement::WeightedEdge, 8>> 1004 Edges) { 1005 // Sort the edges, and then for each successor, find the best incoming 1006 // predecessor. If the best incoming predecessors aren't the same, 1007 // then that is clearly the best layout. If there is a conflict, one of the 1008 // successors will have to fallthrough from the second best predecessor. We 1009 // compare which combination is better overall. 1010 1011 // Sort for highest frequency. 1012 auto Cmp = [](WeightedEdge A, WeightedEdge B) { return A.Weight > B.Weight; }; 1013 1014 llvm::stable_sort(Edges[0], Cmp); 1015 llvm::stable_sort(Edges[1], Cmp); 1016 auto BestA = Edges[0].begin(); 1017 auto BestB = Edges[1].begin(); 1018 // Arrange for the correct answer to be in BestA and BestB 1019 // If the 2 best edges don't conflict, the answer is already there. 1020 if (BestA->Src == BestB->Src) { 1021 // Compare the total fallthrough of (Best + Second Best) for both pairs 1022 auto SecondBestA = std::next(BestA); 1023 auto SecondBestB = std::next(BestB); 1024 BlockFrequency BestAScore = BestA->Weight + SecondBestB->Weight; 1025 BlockFrequency BestBScore = BestB->Weight + SecondBestA->Weight; 1026 if (BestAScore < BestBScore) 1027 BestA = SecondBestA; 1028 else 1029 BestB = SecondBestB; 1030 } 1031 // Arrange for the BB edge to be in BestA if it exists. 1032 if (BestB->Src == BB) 1033 std::swap(BestA, BestB); 1034 return std::make_pair(*BestA, *BestB); 1035 } 1036 1037 /// Get the best successor from \p BB based on \p BB being part of a trellis. 1038 /// We only handle trellises with 2 successors, so the algorithm is 1039 /// straightforward: Find the best pair of edges that don't conflict. We find 1040 /// the best incoming edge for each successor in the trellis. If those conflict, 1041 /// we consider which of them should be replaced with the second best. 1042 /// Upon return the two best edges will be in \p BestEdges. If one of the edges 1043 /// comes from \p BB, it will be in \p BestEdges[0] 1044 MachineBlockPlacement::BlockAndTailDupResult 1045 MachineBlockPlacement::getBestTrellisSuccessor( 1046 const MachineBasicBlock *BB, 1047 const SmallVectorImpl<MachineBasicBlock *> &ViableSuccs, 1048 BranchProbability AdjustedSumProb, const BlockChain &Chain, 1049 const BlockFilterSet *BlockFilter) { 1050 1051 BlockAndTailDupResult Result = {nullptr, false}; 1052 SmallPtrSet<const MachineBasicBlock *, 4> Successors(BB->succ_begin(), 1053 BB->succ_end()); 1054 1055 // We assume size 2 because it's common. For general n, we would have to do 1056 // the Hungarian algorithm, but it's not worth the complexity because more 1057 // than 2 successors is fairly uncommon, and a trellis even more so. 1058 if (Successors.size() != 2 || ViableSuccs.size() != 2) 1059 return Result; 1060 1061 // Collect the edge frequencies of all edges that form the trellis. 1062 SmallVector<WeightedEdge, 8> Edges[2]; 1063 int SuccIndex = 0; 1064 for (auto Succ : ViableSuccs) { 1065 for (MachineBasicBlock *SuccPred : Succ->predecessors()) { 1066 // Skip any placed predecessors that are not BB 1067 if (SuccPred != BB) 1068 if ((BlockFilter && !BlockFilter->count(SuccPred)) || 1069 BlockToChain[SuccPred] == &Chain || 1070 BlockToChain[SuccPred] == BlockToChain[Succ]) 1071 continue; 1072 BlockFrequency EdgeFreq = MBFI->getBlockFreq(SuccPred) * 1073 MBPI->getEdgeProbability(SuccPred, Succ); 1074 Edges[SuccIndex].push_back({EdgeFreq, SuccPred, Succ}); 1075 } 1076 ++SuccIndex; 1077 } 1078 1079 // Pick the best combination of 2 edges from all the edges in the trellis. 1080 WeightedEdge BestA, BestB; 1081 std::tie(BestA, BestB) = getBestNonConflictingEdges(BB, Edges); 1082 1083 if (BestA.Src != BB) { 1084 // If we have a trellis, and BB doesn't have the best fallthrough edges, 1085 // we shouldn't choose any successor. We've already looked and there's a 1086 // better fallthrough edge for all the successors. 1087 LLVM_DEBUG(dbgs() << "Trellis, but not one of the chosen edges.\n"); 1088 return Result; 1089 } 1090 1091 // Did we pick the triangle edge? If tail-duplication is profitable, do 1092 // that instead. Otherwise merge the triangle edge now while we know it is 1093 // optimal. 1094 if (BestA.Dest == BestB.Src) { 1095 // The edges are BB->Succ1->Succ2, and we're looking to see if BB->Succ2 1096 // would be better. 1097 MachineBasicBlock *Succ1 = BestA.Dest; 1098 MachineBasicBlock *Succ2 = BestB.Dest; 1099 // Check to see if tail-duplication would be profitable. 1100 if (allowTailDupPlacement() && shouldTailDuplicate(Succ2) && 1101 canTailDuplicateUnplacedPreds(BB, Succ2, Chain, BlockFilter) && 1102 isProfitableToTailDup(BB, Succ2, MBPI->getEdgeProbability(BB, Succ1), 1103 Chain, BlockFilter)) { 1104 LLVM_DEBUG(BranchProbability Succ2Prob = getAdjustedProbability( 1105 MBPI->getEdgeProbability(BB, Succ2), AdjustedSumProb); 1106 dbgs() << " Selected: " << getBlockName(Succ2) 1107 << ", probability: " << Succ2Prob 1108 << " (Tail Duplicate)\n"); 1109 Result.BB = Succ2; 1110 Result.ShouldTailDup = true; 1111 return Result; 1112 } 1113 } 1114 // We have already computed the optimal edge for the other side of the 1115 // trellis. 1116 ComputedEdges[BestB.Src] = { BestB.Dest, false }; 1117 1118 auto TrellisSucc = BestA.Dest; 1119 LLVM_DEBUG(BranchProbability SuccProb = getAdjustedProbability( 1120 MBPI->getEdgeProbability(BB, TrellisSucc), AdjustedSumProb); 1121 dbgs() << " Selected: " << getBlockName(TrellisSucc) 1122 << ", probability: " << SuccProb << " (Trellis)\n"); 1123 Result.BB = TrellisSucc; 1124 return Result; 1125 } 1126 1127 /// When the option allowTailDupPlacement() is on, this method checks if the 1128 /// fallthrough candidate block \p Succ (of block \p BB) can be tail-duplicated 1129 /// into all of its unplaced, unfiltered predecessors, that are not BB. 1130 bool MachineBlockPlacement::canTailDuplicateUnplacedPreds( 1131 const MachineBasicBlock *BB, MachineBasicBlock *Succ, 1132 const BlockChain &Chain, const BlockFilterSet *BlockFilter) { 1133 if (!shouldTailDuplicate(Succ)) 1134 return false; 1135 1136 // The result of canTailDuplicate. 1137 bool Duplicate = true; 1138 // Number of possible duplication. 1139 unsigned int NumDup = 0; 1140 1141 // For CFG checking. 1142 SmallPtrSet<const MachineBasicBlock *, 4> Successors(BB->succ_begin(), 1143 BB->succ_end()); 1144 for (MachineBasicBlock *Pred : Succ->predecessors()) { 1145 // Make sure all unplaced and unfiltered predecessors can be 1146 // tail-duplicated into. 1147 // Skip any blocks that are already placed or not in this loop. 1148 if (Pred == BB || (BlockFilter && !BlockFilter->count(Pred)) 1149 || BlockToChain[Pred] == &Chain) 1150 continue; 1151 if (!TailDup.canTailDuplicate(Succ, Pred)) { 1152 if (Successors.size() > 1 && hasSameSuccessors(*Pred, Successors)) 1153 // This will result in a trellis after tail duplication, so we don't 1154 // need to copy Succ into this predecessor. In the presence 1155 // of a trellis tail duplication can continue to be profitable. 1156 // For example: 1157 // A A 1158 // |\ |\ 1159 // | \ | \ 1160 // | C | C+BB 1161 // | / | | 1162 // |/ | | 1163 // BB => BB | 1164 // |\ |\/| 1165 // | \ |/\| 1166 // | D | D 1167 // | / | / 1168 // |/ |/ 1169 // Succ Succ 1170 // 1171 // After BB was duplicated into C, the layout looks like the one on the 1172 // right. BB and C now have the same successors. When considering 1173 // whether Succ can be duplicated into all its unplaced predecessors, we 1174 // ignore C. 1175 // We can do this because C already has a profitable fallthrough, namely 1176 // D. TODO(iteratee): ignore sufficiently cold predecessors for 1177 // duplication and for this test. 1178 // 1179 // This allows trellises to be laid out in 2 separate chains 1180 // (A,B,Succ,...) and later (C,D,...) This is a reasonable heuristic 1181 // because it allows the creation of 2 fallthrough paths with links 1182 // between them, and we correctly identify the best layout for these 1183 // CFGs. We want to extend trellises that the user created in addition 1184 // to trellises created by tail-duplication, so we just look for the 1185 // CFG. 1186 continue; 1187 Duplicate = false; 1188 continue; 1189 } 1190 NumDup++; 1191 } 1192 1193 // No possible duplication in current filter set. 1194 if (NumDup == 0) 1195 return false; 1196 1197 // If profile information is available, findDuplicateCandidates can do more 1198 // precise benefit analysis. 1199 if (F->getFunction().hasProfileData()) 1200 return true; 1201 1202 // This is mainly for function exit BB. 1203 // The integrated tail duplication is really designed for increasing 1204 // fallthrough from predecessors from Succ to its successors. We may need 1205 // other machanism to handle different cases. 1206 if (Succ->succ_empty()) 1207 return true; 1208 1209 // Plus the already placed predecessor. 1210 NumDup++; 1211 1212 // If the duplication candidate has more unplaced predecessors than 1213 // successors, the extra duplication can't bring more fallthrough. 1214 // 1215 // Pred1 Pred2 Pred3 1216 // \ | / 1217 // \ | / 1218 // \ | / 1219 // Dup 1220 // / \ 1221 // / \ 1222 // Succ1 Succ2 1223 // 1224 // In this example Dup has 2 successors and 3 predecessors, duplication of Dup 1225 // can increase the fallthrough from Pred1 to Succ1 and from Pred2 to Succ2, 1226 // but the duplication into Pred3 can't increase fallthrough. 1227 // 1228 // A small number of extra duplication may not hurt too much. We need a better 1229 // heuristic to handle it. 1230 if ((NumDup > Succ->succ_size()) || !Duplicate) 1231 return false; 1232 1233 return true; 1234 } 1235 1236 /// Find chains of triangles where we believe it would be profitable to 1237 /// tail-duplicate them all, but a local analysis would not find them. 1238 /// There are 3 ways this can be profitable: 1239 /// 1) The post-dominators marked 50% are actually taken 55% (This shrinks with 1240 /// longer chains) 1241 /// 2) The chains are statically correlated. Branch probabilities have a very 1242 /// U-shaped distribution. 1243 /// [http://nrs.harvard.edu/urn-3:HUL.InstRepos:24015805] 1244 /// If the branches in a chain are likely to be from the same side of the 1245 /// distribution as their predecessor, but are independent at runtime, this 1246 /// transformation is profitable. (Because the cost of being wrong is a small 1247 /// fixed cost, unlike the standard triangle layout where the cost of being 1248 /// wrong scales with the # of triangles.) 1249 /// 3) The chains are dynamically correlated. If the probability that a previous 1250 /// branch was taken positively influences whether the next branch will be 1251 /// taken 1252 /// We believe that 2 and 3 are common enough to justify the small margin in 1. 1253 void MachineBlockPlacement::precomputeTriangleChains() { 1254 struct TriangleChain { 1255 std::vector<MachineBasicBlock *> Edges; 1256 1257 TriangleChain(MachineBasicBlock *src, MachineBasicBlock *dst) 1258 : Edges({src, dst}) {} 1259 1260 void append(MachineBasicBlock *dst) { 1261 assert(getKey()->isSuccessor(dst) && 1262 "Attempting to append a block that is not a successor."); 1263 Edges.push_back(dst); 1264 } 1265 1266 unsigned count() const { return Edges.size() - 1; } 1267 1268 MachineBasicBlock *getKey() const { 1269 return Edges.back(); 1270 } 1271 }; 1272 1273 if (TriangleChainCount == 0) 1274 return; 1275 1276 LLVM_DEBUG(dbgs() << "Pre-computing triangle chains.\n"); 1277 // Map from last block to the chain that contains it. This allows us to extend 1278 // chains as we find new triangles. 1279 DenseMap<const MachineBasicBlock *, TriangleChain> TriangleChainMap; 1280 for (MachineBasicBlock &BB : *F) { 1281 // If BB doesn't have 2 successors, it doesn't start a triangle. 1282 if (BB.succ_size() != 2) 1283 continue; 1284 MachineBasicBlock *PDom = nullptr; 1285 for (MachineBasicBlock *Succ : BB.successors()) { 1286 if (!MPDT->dominates(Succ, &BB)) 1287 continue; 1288 PDom = Succ; 1289 break; 1290 } 1291 // If BB doesn't have a post-dominating successor, it doesn't form a 1292 // triangle. 1293 if (PDom == nullptr) 1294 continue; 1295 // If PDom has a hint that it is low probability, skip this triangle. 1296 if (MBPI->getEdgeProbability(&BB, PDom) < BranchProbability(50, 100)) 1297 continue; 1298 // If PDom isn't eligible for duplication, this isn't the kind of triangle 1299 // we're looking for. 1300 if (!shouldTailDuplicate(PDom)) 1301 continue; 1302 bool CanTailDuplicate = true; 1303 // If PDom can't tail-duplicate into it's non-BB predecessors, then this 1304 // isn't the kind of triangle we're looking for. 1305 for (MachineBasicBlock* Pred : PDom->predecessors()) { 1306 if (Pred == &BB) 1307 continue; 1308 if (!TailDup.canTailDuplicate(PDom, Pred)) { 1309 CanTailDuplicate = false; 1310 break; 1311 } 1312 } 1313 // If we can't tail-duplicate PDom to its predecessors, then skip this 1314 // triangle. 1315 if (!CanTailDuplicate) 1316 continue; 1317 1318 // Now we have an interesting triangle. Insert it if it's not part of an 1319 // existing chain. 1320 // Note: This cannot be replaced with a call insert() or emplace() because 1321 // the find key is BB, but the insert/emplace key is PDom. 1322 auto Found = TriangleChainMap.find(&BB); 1323 // If it is, remove the chain from the map, grow it, and put it back in the 1324 // map with the end as the new key. 1325 if (Found != TriangleChainMap.end()) { 1326 TriangleChain Chain = std::move(Found->second); 1327 TriangleChainMap.erase(Found); 1328 Chain.append(PDom); 1329 TriangleChainMap.insert(std::make_pair(Chain.getKey(), std::move(Chain))); 1330 } else { 1331 auto InsertResult = TriangleChainMap.try_emplace(PDom, &BB, PDom); 1332 assert(InsertResult.second && "Block seen twice."); 1333 (void)InsertResult; 1334 } 1335 } 1336 1337 // Iterating over a DenseMap is safe here, because the only thing in the body 1338 // of the loop is inserting into another DenseMap (ComputedEdges). 1339 // ComputedEdges is never iterated, so this doesn't lead to non-determinism. 1340 for (auto &ChainPair : TriangleChainMap) { 1341 TriangleChain &Chain = ChainPair.second; 1342 // Benchmarking has shown that due to branch correlation duplicating 2 or 1343 // more triangles is profitable, despite the calculations assuming 1344 // independence. 1345 if (Chain.count() < TriangleChainCount) 1346 continue; 1347 MachineBasicBlock *dst = Chain.Edges.back(); 1348 Chain.Edges.pop_back(); 1349 for (MachineBasicBlock *src : reverse(Chain.Edges)) { 1350 LLVM_DEBUG(dbgs() << "Marking edge: " << getBlockName(src) << "->" 1351 << getBlockName(dst) 1352 << " as pre-computed based on triangles.\n"); 1353 1354 auto InsertResult = ComputedEdges.insert({src, {dst, true}}); 1355 assert(InsertResult.second && "Block seen twice."); 1356 (void)InsertResult; 1357 1358 dst = src; 1359 } 1360 } 1361 } 1362 1363 // When profile is not present, return the StaticLikelyProb. 1364 // When profile is available, we need to handle the triangle-shape CFG. 1365 static BranchProbability getLayoutSuccessorProbThreshold( 1366 const MachineBasicBlock *BB) { 1367 if (!BB->getParent()->getFunction().hasProfileData()) 1368 return BranchProbability(StaticLikelyProb, 100); 1369 if (BB->succ_size() == 2) { 1370 const MachineBasicBlock *Succ1 = *BB->succ_begin(); 1371 const MachineBasicBlock *Succ2 = *(BB->succ_begin() + 1); 1372 if (Succ1->isSuccessor(Succ2) || Succ2->isSuccessor(Succ1)) { 1373 /* See case 1 below for the cost analysis. For BB->Succ to 1374 * be taken with smaller cost, the following needs to hold: 1375 * Prob(BB->Succ) > 2 * Prob(BB->Pred) 1376 * So the threshold T in the calculation below 1377 * (1-T) * Prob(BB->Succ) > T * Prob(BB->Pred) 1378 * So T / (1 - T) = 2, Yielding T = 2/3 1379 * Also adding user specified branch bias, we have 1380 * T = (2/3)*(ProfileLikelyProb/50) 1381 * = (2*ProfileLikelyProb)/150) 1382 */ 1383 return BranchProbability(2 * ProfileLikelyProb, 150); 1384 } 1385 } 1386 return BranchProbability(ProfileLikelyProb, 100); 1387 } 1388 1389 /// Checks to see if the layout candidate block \p Succ has a better layout 1390 /// predecessor than \c BB. If yes, returns true. 1391 /// \p SuccProb: The probability adjusted for only remaining blocks. 1392 /// Only used for logging 1393 /// \p RealSuccProb: The un-adjusted probability. 1394 /// \p Chain: The chain that BB belongs to and Succ is being considered for. 1395 /// \p BlockFilter: if non-null, the set of blocks that make up the loop being 1396 /// considered 1397 bool MachineBlockPlacement::hasBetterLayoutPredecessor( 1398 const MachineBasicBlock *BB, const MachineBasicBlock *Succ, 1399 const BlockChain &SuccChain, BranchProbability SuccProb, 1400 BranchProbability RealSuccProb, const BlockChain &Chain, 1401 const BlockFilterSet *BlockFilter) { 1402 1403 // There isn't a better layout when there are no unscheduled predecessors. 1404 if (SuccChain.UnscheduledPredecessors == 0) 1405 return false; 1406 1407 // There are two basic scenarios here: 1408 // ------------------------------------- 1409 // Case 1: triangular shape CFG (if-then): 1410 // BB 1411 // | \ 1412 // | \ 1413 // | Pred 1414 // | / 1415 // Succ 1416 // In this case, we are evaluating whether to select edge -> Succ, e.g. 1417 // set Succ as the layout successor of BB. Picking Succ as BB's 1418 // successor breaks the CFG constraints (FIXME: define these constraints). 1419 // With this layout, Pred BB 1420 // is forced to be outlined, so the overall cost will be cost of the 1421 // branch taken from BB to Pred, plus the cost of back taken branch 1422 // from Pred to Succ, as well as the additional cost associated 1423 // with the needed unconditional jump instruction from Pred To Succ. 1424 1425 // The cost of the topological order layout is the taken branch cost 1426 // from BB to Succ, so to make BB->Succ a viable candidate, the following 1427 // must hold: 1428 // 2 * freq(BB->Pred) * taken_branch_cost + unconditional_jump_cost 1429 // < freq(BB->Succ) * taken_branch_cost. 1430 // Ignoring unconditional jump cost, we get 1431 // freq(BB->Succ) > 2 * freq(BB->Pred), i.e., 1432 // prob(BB->Succ) > 2 * prob(BB->Pred) 1433 // 1434 // When real profile data is available, we can precisely compute the 1435 // probability threshold that is needed for edge BB->Succ to be considered. 1436 // Without profile data, the heuristic requires the branch bias to be 1437 // a lot larger to make sure the signal is very strong (e.g. 80% default). 1438 // ----------------------------------------------------------------- 1439 // Case 2: diamond like CFG (if-then-else): 1440 // S 1441 // / \ 1442 // | \ 1443 // BB Pred 1444 // \ / 1445 // Succ 1446 // .. 1447 // 1448 // The current block is BB and edge BB->Succ is now being evaluated. 1449 // Note that edge S->BB was previously already selected because 1450 // prob(S->BB) > prob(S->Pred). 1451 // At this point, 2 blocks can be placed after BB: Pred or Succ. If we 1452 // choose Pred, we will have a topological ordering as shown on the left 1453 // in the picture below. If we choose Succ, we have the solution as shown 1454 // on the right: 1455 // 1456 // topo-order: 1457 // 1458 // S----- ---S 1459 // | | | | 1460 // ---BB | | BB 1461 // | | | | 1462 // | Pred-- | Succ-- 1463 // | | | | 1464 // ---Succ ---Pred-- 1465 // 1466 // cost = freq(S->Pred) + freq(BB->Succ) cost = 2 * freq (S->Pred) 1467 // = freq(S->Pred) + freq(S->BB) 1468 // 1469 // If we have profile data (i.e, branch probabilities can be trusted), the 1470 // cost (number of taken branches) with layout S->BB->Succ->Pred is 2 * 1471 // freq(S->Pred) while the cost of topo order is freq(S->Pred) + freq(S->BB). 1472 // We know Prob(S->BB) > Prob(S->Pred), so freq(S->BB) > freq(S->Pred), which 1473 // means the cost of topological order is greater. 1474 // When profile data is not available, however, we need to be more 1475 // conservative. If the branch prediction is wrong, breaking the topo-order 1476 // will actually yield a layout with large cost. For this reason, we need 1477 // strong biased branch at block S with Prob(S->BB) in order to select 1478 // BB->Succ. This is equivalent to looking the CFG backward with backward 1479 // edge: Prob(Succ->BB) needs to >= HotProb in order to be selected (without 1480 // profile data). 1481 // -------------------------------------------------------------------------- 1482 // Case 3: forked diamond 1483 // S 1484 // / \ 1485 // / \ 1486 // BB Pred 1487 // | \ / | 1488 // | \ / | 1489 // | X | 1490 // | / \ | 1491 // | / \ | 1492 // S1 S2 1493 // 1494 // The current block is BB and edge BB->S1 is now being evaluated. 1495 // As above S->BB was already selected because 1496 // prob(S->BB) > prob(S->Pred). Assume that prob(BB->S1) >= prob(BB->S2). 1497 // 1498 // topo-order: 1499 // 1500 // S-------| ---S 1501 // | | | | 1502 // ---BB | | BB 1503 // | | | | 1504 // | Pred----| | S1---- 1505 // | | | | 1506 // --(S1 or S2) ---Pred-- 1507 // | 1508 // S2 1509 // 1510 // topo-cost = freq(S->Pred) + freq(BB->S1) + freq(BB->S2) 1511 // + min(freq(Pred->S1), freq(Pred->S2)) 1512 // Non-topo-order cost: 1513 // non-topo-cost = 2 * freq(S->Pred) + freq(BB->S2). 1514 // To be conservative, we can assume that min(freq(Pred->S1), freq(Pred->S2)) 1515 // is 0. Then the non topo layout is better when 1516 // freq(S->Pred) < freq(BB->S1). 1517 // This is exactly what is checked below. 1518 // Note there are other shapes that apply (Pred may not be a single block, 1519 // but they all fit this general pattern.) 1520 BranchProbability HotProb = getLayoutSuccessorProbThreshold(BB); 1521 1522 // Make sure that a hot successor doesn't have a globally more 1523 // important predecessor. 1524 BlockFrequency CandidateEdgeFreq = MBFI->getBlockFreq(BB) * RealSuccProb; 1525 bool BadCFGConflict = false; 1526 1527 for (MachineBasicBlock *Pred : Succ->predecessors()) { 1528 BlockChain *PredChain = BlockToChain[Pred]; 1529 if (Pred == Succ || PredChain == &SuccChain || 1530 (BlockFilter && !BlockFilter->count(Pred)) || 1531 PredChain == &Chain || Pred != *std::prev(PredChain->end()) || 1532 // This check is redundant except for look ahead. This function is 1533 // called for lookahead by isProfitableToTailDup when BB hasn't been 1534 // placed yet. 1535 (Pred == BB)) 1536 continue; 1537 // Do backward checking. 1538 // For all cases above, we need a backward checking to filter out edges that 1539 // are not 'strongly' biased. 1540 // BB Pred 1541 // \ / 1542 // Succ 1543 // We select edge BB->Succ if 1544 // freq(BB->Succ) > freq(Succ) * HotProb 1545 // i.e. freq(BB->Succ) > freq(BB->Succ) * HotProb + freq(Pred->Succ) * 1546 // HotProb 1547 // i.e. freq((BB->Succ) * (1 - HotProb) > freq(Pred->Succ) * HotProb 1548 // Case 1 is covered too, because the first equation reduces to: 1549 // prob(BB->Succ) > HotProb. (freq(Succ) = freq(BB) for a triangle) 1550 BlockFrequency PredEdgeFreq = 1551 MBFI->getBlockFreq(Pred) * MBPI->getEdgeProbability(Pred, Succ); 1552 if (PredEdgeFreq * HotProb >= CandidateEdgeFreq * HotProb.getCompl()) { 1553 BadCFGConflict = true; 1554 break; 1555 } 1556 } 1557 1558 if (BadCFGConflict) { 1559 LLVM_DEBUG(dbgs() << " Not a candidate: " << getBlockName(Succ) << " -> " 1560 << SuccProb << " (prob) (non-cold CFG conflict)\n"); 1561 return true; 1562 } 1563 1564 return false; 1565 } 1566 1567 /// Select the best successor for a block. 1568 /// 1569 /// This looks across all successors of a particular block and attempts to 1570 /// select the "best" one to be the layout successor. It only considers direct 1571 /// successors which also pass the block filter. It will attempt to avoid 1572 /// breaking CFG structure, but cave and break such structures in the case of 1573 /// very hot successor edges. 1574 /// 1575 /// \returns The best successor block found, or null if none are viable, along 1576 /// with a boolean indicating if tail duplication is necessary. 1577 MachineBlockPlacement::BlockAndTailDupResult 1578 MachineBlockPlacement::selectBestSuccessor( 1579 const MachineBasicBlock *BB, const BlockChain &Chain, 1580 const BlockFilterSet *BlockFilter) { 1581 const BranchProbability HotProb(StaticLikelyProb, 100); 1582 1583 BlockAndTailDupResult BestSucc = { nullptr, false }; 1584 auto BestProb = BranchProbability::getZero(); 1585 1586 SmallVector<MachineBasicBlock *, 4> Successors; 1587 auto AdjustedSumProb = 1588 collectViableSuccessors(BB, Chain, BlockFilter, Successors); 1589 1590 LLVM_DEBUG(dbgs() << "Selecting best successor for: " << getBlockName(BB) 1591 << "\n"); 1592 1593 // if we already precomputed the best successor for BB, return that if still 1594 // applicable. 1595 auto FoundEdge = ComputedEdges.find(BB); 1596 if (FoundEdge != ComputedEdges.end()) { 1597 MachineBasicBlock *Succ = FoundEdge->second.BB; 1598 ComputedEdges.erase(FoundEdge); 1599 BlockChain *SuccChain = BlockToChain[Succ]; 1600 if (BB->isSuccessor(Succ) && (!BlockFilter || BlockFilter->count(Succ)) && 1601 SuccChain != &Chain && Succ == *SuccChain->begin()) 1602 return FoundEdge->second; 1603 } 1604 1605 // if BB is part of a trellis, Use the trellis to determine the optimal 1606 // fallthrough edges 1607 if (isTrellis(BB, Successors, Chain, BlockFilter)) 1608 return getBestTrellisSuccessor(BB, Successors, AdjustedSumProb, Chain, 1609 BlockFilter); 1610 1611 // For blocks with CFG violations, we may be able to lay them out anyway with 1612 // tail-duplication. We keep this vector so we can perform the probability 1613 // calculations the minimum number of times. 1614 SmallVector<std::pair<BranchProbability, MachineBasicBlock *>, 4> 1615 DupCandidates; 1616 for (MachineBasicBlock *Succ : Successors) { 1617 auto RealSuccProb = MBPI->getEdgeProbability(BB, Succ); 1618 BranchProbability SuccProb = 1619 getAdjustedProbability(RealSuccProb, AdjustedSumProb); 1620 1621 BlockChain &SuccChain = *BlockToChain[Succ]; 1622 // Skip the edge \c BB->Succ if block \c Succ has a better layout 1623 // predecessor that yields lower global cost. 1624 if (hasBetterLayoutPredecessor(BB, Succ, SuccChain, SuccProb, RealSuccProb, 1625 Chain, BlockFilter)) { 1626 // If tail duplication would make Succ profitable, place it. 1627 if (allowTailDupPlacement() && shouldTailDuplicate(Succ)) 1628 DupCandidates.emplace_back(SuccProb, Succ); 1629 continue; 1630 } 1631 1632 LLVM_DEBUG( 1633 dbgs() << " Candidate: " << getBlockName(Succ) 1634 << ", probability: " << SuccProb 1635 << (SuccChain.UnscheduledPredecessors != 0 ? " (CFG break)" : "") 1636 << "\n"); 1637 1638 if (BestSucc.BB && BestProb >= SuccProb) { 1639 LLVM_DEBUG(dbgs() << " Not the best candidate, continuing\n"); 1640 continue; 1641 } 1642 1643 LLVM_DEBUG(dbgs() << " Setting it as best candidate\n"); 1644 BestSucc.BB = Succ; 1645 BestProb = SuccProb; 1646 } 1647 // Handle the tail duplication candidates in order of decreasing probability. 1648 // Stop at the first one that is profitable. Also stop if they are less 1649 // profitable than BestSucc. Position is important because we preserve it and 1650 // prefer first best match. Here we aren't comparing in order, so we capture 1651 // the position instead. 1652 llvm::stable_sort(DupCandidates, 1653 [](std::tuple<BranchProbability, MachineBasicBlock *> L, 1654 std::tuple<BranchProbability, MachineBasicBlock *> R) { 1655 return std::get<0>(L) > std::get<0>(R); 1656 }); 1657 for (auto &Tup : DupCandidates) { 1658 BranchProbability DupProb; 1659 MachineBasicBlock *Succ; 1660 std::tie(DupProb, Succ) = Tup; 1661 if (DupProb < BestProb) 1662 break; 1663 if (canTailDuplicateUnplacedPreds(BB, Succ, Chain, BlockFilter) 1664 && (isProfitableToTailDup(BB, Succ, BestProb, Chain, BlockFilter))) { 1665 LLVM_DEBUG(dbgs() << " Candidate: " << getBlockName(Succ) 1666 << ", probability: " << DupProb 1667 << " (Tail Duplicate)\n"); 1668 BestSucc.BB = Succ; 1669 BestSucc.ShouldTailDup = true; 1670 break; 1671 } 1672 } 1673 1674 if (BestSucc.BB) 1675 LLVM_DEBUG(dbgs() << " Selected: " << getBlockName(BestSucc.BB) << "\n"); 1676 1677 return BestSucc; 1678 } 1679 1680 /// Select the best block from a worklist. 1681 /// 1682 /// This looks through the provided worklist as a list of candidate basic 1683 /// blocks and select the most profitable one to place. The definition of 1684 /// profitable only really makes sense in the context of a loop. This returns 1685 /// the most frequently visited block in the worklist, which in the case of 1686 /// a loop, is the one most desirable to be physically close to the rest of the 1687 /// loop body in order to improve i-cache behavior. 1688 /// 1689 /// \returns The best block found, or null if none are viable. 1690 MachineBasicBlock *MachineBlockPlacement::selectBestCandidateBlock( 1691 const BlockChain &Chain, SmallVectorImpl<MachineBasicBlock *> &WorkList) { 1692 // Once we need to walk the worklist looking for a candidate, cleanup the 1693 // worklist of already placed entries. 1694 // FIXME: If this shows up on profiles, it could be folded (at the cost of 1695 // some code complexity) into the loop below. 1696 llvm::erase_if(WorkList, [&](MachineBasicBlock *BB) { 1697 return BlockToChain.lookup(BB) == &Chain; 1698 }); 1699 1700 if (WorkList.empty()) 1701 return nullptr; 1702 1703 bool IsEHPad = WorkList[0]->isEHPad(); 1704 1705 MachineBasicBlock *BestBlock = nullptr; 1706 BlockFrequency BestFreq; 1707 for (MachineBasicBlock *MBB : WorkList) { 1708 assert(MBB->isEHPad() == IsEHPad && 1709 "EHPad mismatch between block and work list."); 1710 1711 BlockChain &SuccChain = *BlockToChain[MBB]; 1712 if (&SuccChain == &Chain) 1713 continue; 1714 1715 assert(SuccChain.UnscheduledPredecessors == 0 && 1716 "Found CFG-violating block"); 1717 1718 BlockFrequency CandidateFreq = MBFI->getBlockFreq(MBB); 1719 LLVM_DEBUG(dbgs() << " " << getBlockName(MBB) << " -> "; 1720 MBFI->printBlockFreq(dbgs(), CandidateFreq) << " (freq)\n"); 1721 1722 // For ehpad, we layout the least probable first as to avoid jumping back 1723 // from least probable landingpads to more probable ones. 1724 // 1725 // FIXME: Using probability is probably (!) not the best way to achieve 1726 // this. We should probably have a more principled approach to layout 1727 // cleanup code. 1728 // 1729 // The goal is to get: 1730 // 1731 // +--------------------------+ 1732 // | V 1733 // InnerLp -> InnerCleanup OuterLp -> OuterCleanup -> Resume 1734 // 1735 // Rather than: 1736 // 1737 // +-------------------------------------+ 1738 // V | 1739 // OuterLp -> OuterCleanup -> Resume InnerLp -> InnerCleanup 1740 if (BestBlock && (IsEHPad ^ (BestFreq >= CandidateFreq))) 1741 continue; 1742 1743 BestBlock = MBB; 1744 BestFreq = CandidateFreq; 1745 } 1746 1747 return BestBlock; 1748 } 1749 1750 /// Retrieve the first unplaced basic block. 1751 /// 1752 /// This routine is called when we are unable to use the CFG to walk through 1753 /// all of the basic blocks and form a chain due to unnatural loops in the CFG. 1754 /// We walk through the function's blocks in order, starting from the 1755 /// LastUnplacedBlockIt. We update this iterator on each call to avoid 1756 /// re-scanning the entire sequence on repeated calls to this routine. 1757 MachineBasicBlock *MachineBlockPlacement::getFirstUnplacedBlock( 1758 const BlockChain &PlacedChain, 1759 MachineFunction::iterator &PrevUnplacedBlockIt, 1760 const BlockFilterSet *BlockFilter) { 1761 for (MachineFunction::iterator I = PrevUnplacedBlockIt, E = F->end(); I != E; 1762 ++I) { 1763 if (BlockFilter && !BlockFilter->count(&*I)) 1764 continue; 1765 if (BlockToChain[&*I] != &PlacedChain) { 1766 PrevUnplacedBlockIt = I; 1767 // Now select the head of the chain to which the unplaced block belongs 1768 // as the block to place. This will force the entire chain to be placed, 1769 // and satisfies the requirements of merging chains. 1770 return *BlockToChain[&*I]->begin(); 1771 } 1772 } 1773 return nullptr; 1774 } 1775 1776 void MachineBlockPlacement::fillWorkLists( 1777 const MachineBasicBlock *MBB, 1778 SmallPtrSetImpl<BlockChain *> &UpdatedPreds, 1779 const BlockFilterSet *BlockFilter = nullptr) { 1780 BlockChain &Chain = *BlockToChain[MBB]; 1781 if (!UpdatedPreds.insert(&Chain).second) 1782 return; 1783 1784 assert( 1785 Chain.UnscheduledPredecessors == 0 && 1786 "Attempting to place block with unscheduled predecessors in worklist."); 1787 for (MachineBasicBlock *ChainBB : Chain) { 1788 assert(BlockToChain[ChainBB] == &Chain && 1789 "Block in chain doesn't match BlockToChain map."); 1790 for (MachineBasicBlock *Pred : ChainBB->predecessors()) { 1791 if (BlockFilter && !BlockFilter->count(Pred)) 1792 continue; 1793 if (BlockToChain[Pred] == &Chain) 1794 continue; 1795 ++Chain.UnscheduledPredecessors; 1796 } 1797 } 1798 1799 if (Chain.UnscheduledPredecessors != 0) 1800 return; 1801 1802 MachineBasicBlock *BB = *Chain.begin(); 1803 if (BB->isEHPad()) 1804 EHPadWorkList.push_back(BB); 1805 else 1806 BlockWorkList.push_back(BB); 1807 } 1808 1809 void MachineBlockPlacement::buildChain( 1810 const MachineBasicBlock *HeadBB, BlockChain &Chain, 1811 BlockFilterSet *BlockFilter) { 1812 assert(HeadBB && "BB must not be null.\n"); 1813 assert(BlockToChain[HeadBB] == &Chain && "BlockToChainMap mis-match.\n"); 1814 MachineFunction::iterator PrevUnplacedBlockIt = F->begin(); 1815 1816 const MachineBasicBlock *LoopHeaderBB = HeadBB; 1817 markChainSuccessors(Chain, LoopHeaderBB, BlockFilter); 1818 MachineBasicBlock *BB = *std::prev(Chain.end()); 1819 while (true) { 1820 assert(BB && "null block found at end of chain in loop."); 1821 assert(BlockToChain[BB] == &Chain && "BlockToChainMap mis-match in loop."); 1822 assert(*std::prev(Chain.end()) == BB && "BB Not found at end of chain."); 1823 1824 1825 // Look for the best viable successor if there is one to place immediately 1826 // after this block. 1827 auto Result = selectBestSuccessor(BB, Chain, BlockFilter); 1828 MachineBasicBlock* BestSucc = Result.BB; 1829 bool ShouldTailDup = Result.ShouldTailDup; 1830 if (allowTailDupPlacement()) 1831 ShouldTailDup |= (BestSucc && canTailDuplicateUnplacedPreds(BB, BestSucc, 1832 Chain, 1833 BlockFilter)); 1834 1835 // If an immediate successor isn't available, look for the best viable 1836 // block among those we've identified as not violating the loop's CFG at 1837 // this point. This won't be a fallthrough, but it will increase locality. 1838 if (!BestSucc) 1839 BestSucc = selectBestCandidateBlock(Chain, BlockWorkList); 1840 if (!BestSucc) 1841 BestSucc = selectBestCandidateBlock(Chain, EHPadWorkList); 1842 1843 if (!BestSucc) { 1844 BestSucc = getFirstUnplacedBlock(Chain, PrevUnplacedBlockIt, BlockFilter); 1845 if (!BestSucc) 1846 break; 1847 1848 LLVM_DEBUG(dbgs() << "Unnatural loop CFG detected, forcibly merging the " 1849 "layout successor until the CFG reduces\n"); 1850 } 1851 1852 // Placement may have changed tail duplication opportunities. 1853 // Check for that now. 1854 if (allowTailDupPlacement() && BestSucc && ShouldTailDup) { 1855 repeatedlyTailDuplicateBlock(BestSucc, BB, LoopHeaderBB, Chain, 1856 BlockFilter, PrevUnplacedBlockIt); 1857 // If the chosen successor was duplicated into BB, don't bother laying 1858 // it out, just go round the loop again with BB as the chain end. 1859 if (!BB->isSuccessor(BestSucc)) 1860 continue; 1861 } 1862 1863 // Place this block, updating the datastructures to reflect its placement. 1864 BlockChain &SuccChain = *BlockToChain[BestSucc]; 1865 // Zero out UnscheduledPredecessors for the successor we're about to merge in case 1866 // we selected a successor that didn't fit naturally into the CFG. 1867 SuccChain.UnscheduledPredecessors = 0; 1868 LLVM_DEBUG(dbgs() << "Merging from " << getBlockName(BB) << " to " 1869 << getBlockName(BestSucc) << "\n"); 1870 markChainSuccessors(SuccChain, LoopHeaderBB, BlockFilter); 1871 Chain.merge(BestSucc, &SuccChain); 1872 BB = *std::prev(Chain.end()); 1873 } 1874 1875 LLVM_DEBUG(dbgs() << "Finished forming chain for header block " 1876 << getBlockName(*Chain.begin()) << "\n"); 1877 } 1878 1879 // If bottom of block BB has only one successor OldTop, in most cases it is 1880 // profitable to move it before OldTop, except the following case: 1881 // 1882 // -->OldTop<- 1883 // | . | 1884 // | . | 1885 // | . | 1886 // ---Pred | 1887 // | | 1888 // BB----- 1889 // 1890 // If BB is moved before OldTop, Pred needs a taken branch to BB, and it can't 1891 // layout the other successor below it, so it can't reduce taken branch. 1892 // In this case we keep its original layout. 1893 bool 1894 MachineBlockPlacement::canMoveBottomBlockToTop( 1895 const MachineBasicBlock *BottomBlock, 1896 const MachineBasicBlock *OldTop) { 1897 if (BottomBlock->pred_size() != 1) 1898 return true; 1899 MachineBasicBlock *Pred = *BottomBlock->pred_begin(); 1900 if (Pred->succ_size() != 2) 1901 return true; 1902 1903 MachineBasicBlock *OtherBB = *Pred->succ_begin(); 1904 if (OtherBB == BottomBlock) 1905 OtherBB = *Pred->succ_rbegin(); 1906 if (OtherBB == OldTop) 1907 return false; 1908 1909 return true; 1910 } 1911 1912 // Find out the possible fall through frequence to the top of a loop. 1913 BlockFrequency 1914 MachineBlockPlacement::TopFallThroughFreq( 1915 const MachineBasicBlock *Top, 1916 const BlockFilterSet &LoopBlockSet) { 1917 BlockFrequency MaxFreq = 0; 1918 for (MachineBasicBlock *Pred : Top->predecessors()) { 1919 BlockChain *PredChain = BlockToChain[Pred]; 1920 if (!LoopBlockSet.count(Pred) && 1921 (!PredChain || Pred == *std::prev(PredChain->end()))) { 1922 // Found a Pred block can be placed before Top. 1923 // Check if Top is the best successor of Pred. 1924 auto TopProb = MBPI->getEdgeProbability(Pred, Top); 1925 bool TopOK = true; 1926 for (MachineBasicBlock *Succ : Pred->successors()) { 1927 auto SuccProb = MBPI->getEdgeProbability(Pred, Succ); 1928 BlockChain *SuccChain = BlockToChain[Succ]; 1929 // Check if Succ can be placed after Pred. 1930 // Succ should not be in any chain, or it is the head of some chain. 1931 if (!LoopBlockSet.count(Succ) && (SuccProb > TopProb) && 1932 (!SuccChain || Succ == *SuccChain->begin())) { 1933 TopOK = false; 1934 break; 1935 } 1936 } 1937 if (TopOK) { 1938 BlockFrequency EdgeFreq = MBFI->getBlockFreq(Pred) * 1939 MBPI->getEdgeProbability(Pred, Top); 1940 if (EdgeFreq > MaxFreq) 1941 MaxFreq = EdgeFreq; 1942 } 1943 } 1944 } 1945 return MaxFreq; 1946 } 1947 1948 // Compute the fall through gains when move NewTop before OldTop. 1949 // 1950 // In following diagram, edges marked as "-" are reduced fallthrough, edges 1951 // marked as "+" are increased fallthrough, this function computes 1952 // 1953 // SUM(increased fallthrough) - SUM(decreased fallthrough) 1954 // 1955 // | 1956 // | - 1957 // V 1958 // --->OldTop 1959 // | . 1960 // | . 1961 // +| . + 1962 // | Pred ---> 1963 // | |- 1964 // | V 1965 // --- NewTop <--- 1966 // |- 1967 // V 1968 // 1969 BlockFrequency 1970 MachineBlockPlacement::FallThroughGains( 1971 const MachineBasicBlock *NewTop, 1972 const MachineBasicBlock *OldTop, 1973 const MachineBasicBlock *ExitBB, 1974 const BlockFilterSet &LoopBlockSet) { 1975 BlockFrequency FallThrough2Top = TopFallThroughFreq(OldTop, LoopBlockSet); 1976 BlockFrequency FallThrough2Exit = 0; 1977 if (ExitBB) 1978 FallThrough2Exit = MBFI->getBlockFreq(NewTop) * 1979 MBPI->getEdgeProbability(NewTop, ExitBB); 1980 BlockFrequency BackEdgeFreq = MBFI->getBlockFreq(NewTop) * 1981 MBPI->getEdgeProbability(NewTop, OldTop); 1982 1983 // Find the best Pred of NewTop. 1984 MachineBasicBlock *BestPred = nullptr; 1985 BlockFrequency FallThroughFromPred = 0; 1986 for (MachineBasicBlock *Pred : NewTop->predecessors()) { 1987 if (!LoopBlockSet.count(Pred)) 1988 continue; 1989 BlockChain *PredChain = BlockToChain[Pred]; 1990 if (!PredChain || Pred == *std::prev(PredChain->end())) { 1991 BlockFrequency EdgeFreq = MBFI->getBlockFreq(Pred) * 1992 MBPI->getEdgeProbability(Pred, NewTop); 1993 if (EdgeFreq > FallThroughFromPred) { 1994 FallThroughFromPred = EdgeFreq; 1995 BestPred = Pred; 1996 } 1997 } 1998 } 1999 2000 // If NewTop is not placed after Pred, another successor can be placed 2001 // after Pred. 2002 BlockFrequency NewFreq = 0; 2003 if (BestPred) { 2004 for (MachineBasicBlock *Succ : BestPred->successors()) { 2005 if ((Succ == NewTop) || (Succ == BestPred) || !LoopBlockSet.count(Succ)) 2006 continue; 2007 if (ComputedEdges.find(Succ) != ComputedEdges.end()) 2008 continue; 2009 BlockChain *SuccChain = BlockToChain[Succ]; 2010 if ((SuccChain && (Succ != *SuccChain->begin())) || 2011 (SuccChain == BlockToChain[BestPred])) 2012 continue; 2013 BlockFrequency EdgeFreq = MBFI->getBlockFreq(BestPred) * 2014 MBPI->getEdgeProbability(BestPred, Succ); 2015 if (EdgeFreq > NewFreq) 2016 NewFreq = EdgeFreq; 2017 } 2018 BlockFrequency OrigEdgeFreq = MBFI->getBlockFreq(BestPred) * 2019 MBPI->getEdgeProbability(BestPred, NewTop); 2020 if (NewFreq > OrigEdgeFreq) { 2021 // If NewTop is not the best successor of Pred, then Pred doesn't 2022 // fallthrough to NewTop. So there is no FallThroughFromPred and 2023 // NewFreq. 2024 NewFreq = 0; 2025 FallThroughFromPred = 0; 2026 } 2027 } 2028 2029 BlockFrequency Result = 0; 2030 BlockFrequency Gains = BackEdgeFreq + NewFreq; 2031 BlockFrequency Lost = FallThrough2Top + FallThrough2Exit + 2032 FallThroughFromPred; 2033 if (Gains > Lost) 2034 Result = Gains - Lost; 2035 return Result; 2036 } 2037 2038 /// Helper function of findBestLoopTop. Find the best loop top block 2039 /// from predecessors of old top. 2040 /// 2041 /// Look for a block which is strictly better than the old top for laying 2042 /// out before the old top of the loop. This looks for only two patterns: 2043 /// 2044 /// 1. a block has only one successor, the old loop top 2045 /// 2046 /// Because such a block will always result in an unconditional jump, 2047 /// rotating it in front of the old top is always profitable. 2048 /// 2049 /// 2. a block has two successors, one is old top, another is exit 2050 /// and it has more than one predecessors 2051 /// 2052 /// If it is below one of its predecessors P, only P can fall through to 2053 /// it, all other predecessors need a jump to it, and another conditional 2054 /// jump to loop header. If it is moved before loop header, all its 2055 /// predecessors jump to it, then fall through to loop header. So all its 2056 /// predecessors except P can reduce one taken branch. 2057 /// At the same time, move it before old top increases the taken branch 2058 /// to loop exit block, so the reduced taken branch will be compared with 2059 /// the increased taken branch to the loop exit block. 2060 MachineBasicBlock * 2061 MachineBlockPlacement::findBestLoopTopHelper( 2062 MachineBasicBlock *OldTop, 2063 const MachineLoop &L, 2064 const BlockFilterSet &LoopBlockSet) { 2065 // Check that the header hasn't been fused with a preheader block due to 2066 // crazy branches. If it has, we need to start with the header at the top to 2067 // prevent pulling the preheader into the loop body. 2068 BlockChain &HeaderChain = *BlockToChain[OldTop]; 2069 if (!LoopBlockSet.count(*HeaderChain.begin())) 2070 return OldTop; 2071 if (OldTop != *HeaderChain.begin()) 2072 return OldTop; 2073 2074 LLVM_DEBUG(dbgs() << "Finding best loop top for: " << getBlockName(OldTop) 2075 << "\n"); 2076 2077 BlockFrequency BestGains = 0; 2078 MachineBasicBlock *BestPred = nullptr; 2079 for (MachineBasicBlock *Pred : OldTop->predecessors()) { 2080 if (!LoopBlockSet.count(Pred)) 2081 continue; 2082 if (Pred == L.getHeader()) 2083 continue; 2084 LLVM_DEBUG(dbgs() << " old top pred: " << getBlockName(Pred) << ", has " 2085 << Pred->succ_size() << " successors, "; 2086 MBFI->printBlockFreq(dbgs(), Pred) << " freq\n"); 2087 if (Pred->succ_size() > 2) 2088 continue; 2089 2090 MachineBasicBlock *OtherBB = nullptr; 2091 if (Pred->succ_size() == 2) { 2092 OtherBB = *Pred->succ_begin(); 2093 if (OtherBB == OldTop) 2094 OtherBB = *Pred->succ_rbegin(); 2095 } 2096 2097 if (!canMoveBottomBlockToTop(Pred, OldTop)) 2098 continue; 2099 2100 BlockFrequency Gains = FallThroughGains(Pred, OldTop, OtherBB, 2101 LoopBlockSet); 2102 if ((Gains > 0) && (Gains > BestGains || 2103 ((Gains == BestGains) && Pred->isLayoutSuccessor(OldTop)))) { 2104 BestPred = Pred; 2105 BestGains = Gains; 2106 } 2107 } 2108 2109 // If no direct predecessor is fine, just use the loop header. 2110 if (!BestPred) { 2111 LLVM_DEBUG(dbgs() << " final top unchanged\n"); 2112 return OldTop; 2113 } 2114 2115 // Walk backwards through any straight line of predecessors. 2116 while (BestPred->pred_size() == 1 && 2117 (*BestPred->pred_begin())->succ_size() == 1 && 2118 *BestPred->pred_begin() != L.getHeader()) 2119 BestPred = *BestPred->pred_begin(); 2120 2121 LLVM_DEBUG(dbgs() << " final top: " << getBlockName(BestPred) << "\n"); 2122 return BestPred; 2123 } 2124 2125 /// Find the best loop top block for layout. 2126 /// 2127 /// This function iteratively calls findBestLoopTopHelper, until no new better 2128 /// BB can be found. 2129 MachineBasicBlock * 2130 MachineBlockPlacement::findBestLoopTop(const MachineLoop &L, 2131 const BlockFilterSet &LoopBlockSet) { 2132 // Placing the latch block before the header may introduce an extra branch 2133 // that skips this block the first time the loop is executed, which we want 2134 // to avoid when optimising for size. 2135 // FIXME: in theory there is a case that does not introduce a new branch, 2136 // i.e. when the layout predecessor does not fallthrough to the loop header. 2137 // In practice this never happens though: there always seems to be a preheader 2138 // that can fallthrough and that is also placed before the header. 2139 bool OptForSize = F->getFunction().hasOptSize() || 2140 llvm::shouldOptimizeForSize(L.getHeader(), PSI, MBFI.get()); 2141 if (OptForSize) 2142 return L.getHeader(); 2143 2144 MachineBasicBlock *OldTop = nullptr; 2145 MachineBasicBlock *NewTop = L.getHeader(); 2146 while (NewTop != OldTop) { 2147 OldTop = NewTop; 2148 NewTop = findBestLoopTopHelper(OldTop, L, LoopBlockSet); 2149 if (NewTop != OldTop) 2150 ComputedEdges[NewTop] = { OldTop, false }; 2151 } 2152 return NewTop; 2153 } 2154 2155 /// Find the best loop exiting block for layout. 2156 /// 2157 /// This routine implements the logic to analyze the loop looking for the best 2158 /// block to layout at the top of the loop. Typically this is done to maximize 2159 /// fallthrough opportunities. 2160 MachineBasicBlock * 2161 MachineBlockPlacement::findBestLoopExit(const MachineLoop &L, 2162 const BlockFilterSet &LoopBlockSet, 2163 BlockFrequency &ExitFreq) { 2164 // We don't want to layout the loop linearly in all cases. If the loop header 2165 // is just a normal basic block in the loop, we want to look for what block 2166 // within the loop is the best one to layout at the top. However, if the loop 2167 // header has be pre-merged into a chain due to predecessors not having 2168 // analyzable branches, *and* the predecessor it is merged with is *not* part 2169 // of the loop, rotating the header into the middle of the loop will create 2170 // a non-contiguous range of blocks which is Very Bad. So start with the 2171 // header and only rotate if safe. 2172 BlockChain &HeaderChain = *BlockToChain[L.getHeader()]; 2173 if (!LoopBlockSet.count(*HeaderChain.begin())) 2174 return nullptr; 2175 2176 BlockFrequency BestExitEdgeFreq; 2177 unsigned BestExitLoopDepth = 0; 2178 MachineBasicBlock *ExitingBB = nullptr; 2179 // If there are exits to outer loops, loop rotation can severely limit 2180 // fallthrough opportunities unless it selects such an exit. Keep a set of 2181 // blocks where rotating to exit with that block will reach an outer loop. 2182 SmallPtrSet<MachineBasicBlock *, 4> BlocksExitingToOuterLoop; 2183 2184 LLVM_DEBUG(dbgs() << "Finding best loop exit for: " 2185 << getBlockName(L.getHeader()) << "\n"); 2186 for (MachineBasicBlock *MBB : L.getBlocks()) { 2187 BlockChain &Chain = *BlockToChain[MBB]; 2188 // Ensure that this block is at the end of a chain; otherwise it could be 2189 // mid-way through an inner loop or a successor of an unanalyzable branch. 2190 if (MBB != *std::prev(Chain.end())) 2191 continue; 2192 2193 // Now walk the successors. We need to establish whether this has a viable 2194 // exiting successor and whether it has a viable non-exiting successor. 2195 // We store the old exiting state and restore it if a viable looping 2196 // successor isn't found. 2197 MachineBasicBlock *OldExitingBB = ExitingBB; 2198 BlockFrequency OldBestExitEdgeFreq = BestExitEdgeFreq; 2199 bool HasLoopingSucc = false; 2200 for (MachineBasicBlock *Succ : MBB->successors()) { 2201 if (Succ->isEHPad()) 2202 continue; 2203 if (Succ == MBB) 2204 continue; 2205 BlockChain &SuccChain = *BlockToChain[Succ]; 2206 // Don't split chains, either this chain or the successor's chain. 2207 if (&Chain == &SuccChain) { 2208 LLVM_DEBUG(dbgs() << " exiting: " << getBlockName(MBB) << " -> " 2209 << getBlockName(Succ) << " (chain conflict)\n"); 2210 continue; 2211 } 2212 2213 auto SuccProb = MBPI->getEdgeProbability(MBB, Succ); 2214 if (LoopBlockSet.count(Succ)) { 2215 LLVM_DEBUG(dbgs() << " looping: " << getBlockName(MBB) << " -> " 2216 << getBlockName(Succ) << " (" << SuccProb << ")\n"); 2217 HasLoopingSucc = true; 2218 continue; 2219 } 2220 2221 unsigned SuccLoopDepth = 0; 2222 if (MachineLoop *ExitLoop = MLI->getLoopFor(Succ)) { 2223 SuccLoopDepth = ExitLoop->getLoopDepth(); 2224 if (ExitLoop->contains(&L)) 2225 BlocksExitingToOuterLoop.insert(MBB); 2226 } 2227 2228 BlockFrequency ExitEdgeFreq = MBFI->getBlockFreq(MBB) * SuccProb; 2229 LLVM_DEBUG(dbgs() << " exiting: " << getBlockName(MBB) << " -> " 2230 << getBlockName(Succ) << " [L:" << SuccLoopDepth 2231 << "] ("; 2232 MBFI->printBlockFreq(dbgs(), ExitEdgeFreq) << ")\n"); 2233 // Note that we bias this toward an existing layout successor to retain 2234 // incoming order in the absence of better information. The exit must have 2235 // a frequency higher than the current exit before we consider breaking 2236 // the layout. 2237 BranchProbability Bias(100 - ExitBlockBias, 100); 2238 if (!ExitingBB || SuccLoopDepth > BestExitLoopDepth || 2239 ExitEdgeFreq > BestExitEdgeFreq || 2240 (MBB->isLayoutSuccessor(Succ) && 2241 !(ExitEdgeFreq < BestExitEdgeFreq * Bias))) { 2242 BestExitEdgeFreq = ExitEdgeFreq; 2243 ExitingBB = MBB; 2244 } 2245 } 2246 2247 if (!HasLoopingSucc) { 2248 // Restore the old exiting state, no viable looping successor was found. 2249 ExitingBB = OldExitingBB; 2250 BestExitEdgeFreq = OldBestExitEdgeFreq; 2251 } 2252 } 2253 // Without a candidate exiting block or with only a single block in the 2254 // loop, just use the loop header to layout the loop. 2255 if (!ExitingBB) { 2256 LLVM_DEBUG( 2257 dbgs() << " No other candidate exit blocks, using loop header\n"); 2258 return nullptr; 2259 } 2260 if (L.getNumBlocks() == 1) { 2261 LLVM_DEBUG(dbgs() << " Loop has 1 block, using loop header as exit\n"); 2262 return nullptr; 2263 } 2264 2265 // Also, if we have exit blocks which lead to outer loops but didn't select 2266 // one of them as the exiting block we are rotating toward, disable loop 2267 // rotation altogether. 2268 if (!BlocksExitingToOuterLoop.empty() && 2269 !BlocksExitingToOuterLoop.count(ExitingBB)) 2270 return nullptr; 2271 2272 LLVM_DEBUG(dbgs() << " Best exiting block: " << getBlockName(ExitingBB) 2273 << "\n"); 2274 ExitFreq = BestExitEdgeFreq; 2275 return ExitingBB; 2276 } 2277 2278 /// Check if there is a fallthrough to loop header Top. 2279 /// 2280 /// 1. Look for a Pred that can be layout before Top. 2281 /// 2. Check if Top is the most possible successor of Pred. 2282 bool 2283 MachineBlockPlacement::hasViableTopFallthrough( 2284 const MachineBasicBlock *Top, 2285 const BlockFilterSet &LoopBlockSet) { 2286 for (MachineBasicBlock *Pred : Top->predecessors()) { 2287 BlockChain *PredChain = BlockToChain[Pred]; 2288 if (!LoopBlockSet.count(Pred) && 2289 (!PredChain || Pred == *std::prev(PredChain->end()))) { 2290 // Found a Pred block can be placed before Top. 2291 // Check if Top is the best successor of Pred. 2292 auto TopProb = MBPI->getEdgeProbability(Pred, Top); 2293 bool TopOK = true; 2294 for (MachineBasicBlock *Succ : Pred->successors()) { 2295 auto SuccProb = MBPI->getEdgeProbability(Pred, Succ); 2296 BlockChain *SuccChain = BlockToChain[Succ]; 2297 // Check if Succ can be placed after Pred. 2298 // Succ should not be in any chain, or it is the head of some chain. 2299 if ((!SuccChain || Succ == *SuccChain->begin()) && SuccProb > TopProb) { 2300 TopOK = false; 2301 break; 2302 } 2303 } 2304 if (TopOK) 2305 return true; 2306 } 2307 } 2308 return false; 2309 } 2310 2311 /// Attempt to rotate an exiting block to the bottom of the loop. 2312 /// 2313 /// Once we have built a chain, try to rotate it to line up the hot exit block 2314 /// with fallthrough out of the loop if doing so doesn't introduce unnecessary 2315 /// branches. For example, if the loop has fallthrough into its header and out 2316 /// of its bottom already, don't rotate it. 2317 void MachineBlockPlacement::rotateLoop(BlockChain &LoopChain, 2318 const MachineBasicBlock *ExitingBB, 2319 BlockFrequency ExitFreq, 2320 const BlockFilterSet &LoopBlockSet) { 2321 if (!ExitingBB) 2322 return; 2323 2324 MachineBasicBlock *Top = *LoopChain.begin(); 2325 MachineBasicBlock *Bottom = *std::prev(LoopChain.end()); 2326 2327 // If ExitingBB is already the last one in a chain then nothing to do. 2328 if (Bottom == ExitingBB) 2329 return; 2330 2331 // The entry block should always be the first BB in a function. 2332 if (Top->isEntryBlock()) 2333 return; 2334 2335 bool ViableTopFallthrough = hasViableTopFallthrough(Top, LoopBlockSet); 2336 2337 // If the header has viable fallthrough, check whether the current loop 2338 // bottom is a viable exiting block. If so, bail out as rotating will 2339 // introduce an unnecessary branch. 2340 if (ViableTopFallthrough) { 2341 for (MachineBasicBlock *Succ : Bottom->successors()) { 2342 BlockChain *SuccChain = BlockToChain[Succ]; 2343 if (!LoopBlockSet.count(Succ) && 2344 (!SuccChain || Succ == *SuccChain->begin())) 2345 return; 2346 } 2347 2348 // Rotate will destroy the top fallthrough, we need to ensure the new exit 2349 // frequency is larger than top fallthrough. 2350 BlockFrequency FallThrough2Top = TopFallThroughFreq(Top, LoopBlockSet); 2351 if (FallThrough2Top >= ExitFreq) 2352 return; 2353 } 2354 2355 BlockChain::iterator ExitIt = llvm::find(LoopChain, ExitingBB); 2356 if (ExitIt == LoopChain.end()) 2357 return; 2358 2359 // Rotating a loop exit to the bottom when there is a fallthrough to top 2360 // trades the entry fallthrough for an exit fallthrough. 2361 // If there is no bottom->top edge, but the chosen exit block does have 2362 // a fallthrough, we break that fallthrough for nothing in return. 2363 2364 // Let's consider an example. We have a built chain of basic blocks 2365 // B1, B2, ..., Bn, where Bk is a ExitingBB - chosen exit block. 2366 // By doing a rotation we get 2367 // Bk+1, ..., Bn, B1, ..., Bk 2368 // Break of fallthrough to B1 is compensated by a fallthrough from Bk. 2369 // If we had a fallthrough Bk -> Bk+1 it is broken now. 2370 // It might be compensated by fallthrough Bn -> B1. 2371 // So we have a condition to avoid creation of extra branch by loop rotation. 2372 // All below must be true to avoid loop rotation: 2373 // If there is a fallthrough to top (B1) 2374 // There was fallthrough from chosen exit block (Bk) to next one (Bk+1) 2375 // There is no fallthrough from bottom (Bn) to top (B1). 2376 // Please note that there is no exit fallthrough from Bn because we checked it 2377 // above. 2378 if (ViableTopFallthrough) { 2379 assert(std::next(ExitIt) != LoopChain.end() && 2380 "Exit should not be last BB"); 2381 MachineBasicBlock *NextBlockInChain = *std::next(ExitIt); 2382 if (ExitingBB->isSuccessor(NextBlockInChain)) 2383 if (!Bottom->isSuccessor(Top)) 2384 return; 2385 } 2386 2387 LLVM_DEBUG(dbgs() << "Rotating loop to put exit " << getBlockName(ExitingBB) 2388 << " at bottom\n"); 2389 std::rotate(LoopChain.begin(), std::next(ExitIt), LoopChain.end()); 2390 } 2391 2392 /// Attempt to rotate a loop based on profile data to reduce branch cost. 2393 /// 2394 /// With profile data, we can determine the cost in terms of missed fall through 2395 /// opportunities when rotating a loop chain and select the best rotation. 2396 /// Basically, there are three kinds of cost to consider for each rotation: 2397 /// 1. The possibly missed fall through edge (if it exists) from BB out of 2398 /// the loop to the loop header. 2399 /// 2. The possibly missed fall through edges (if they exist) from the loop 2400 /// exits to BB out of the loop. 2401 /// 3. The missed fall through edge (if it exists) from the last BB to the 2402 /// first BB in the loop chain. 2403 /// Therefore, the cost for a given rotation is the sum of costs listed above. 2404 /// We select the best rotation with the smallest cost. 2405 void MachineBlockPlacement::rotateLoopWithProfile( 2406 BlockChain &LoopChain, const MachineLoop &L, 2407 const BlockFilterSet &LoopBlockSet) { 2408 auto RotationPos = LoopChain.end(); 2409 MachineBasicBlock *ChainHeaderBB = *LoopChain.begin(); 2410 2411 // The entry block should always be the first BB in a function. 2412 if (ChainHeaderBB->isEntryBlock()) 2413 return; 2414 2415 BlockFrequency SmallestRotationCost = BlockFrequency::getMaxFrequency(); 2416 2417 // A utility lambda that scales up a block frequency by dividing it by a 2418 // branch probability which is the reciprocal of the scale. 2419 auto ScaleBlockFrequency = [](BlockFrequency Freq, 2420 unsigned Scale) -> BlockFrequency { 2421 if (Scale == 0) 2422 return 0; 2423 // Use operator / between BlockFrequency and BranchProbability to implement 2424 // saturating multiplication. 2425 return Freq / BranchProbability(1, Scale); 2426 }; 2427 2428 // Compute the cost of the missed fall-through edge to the loop header if the 2429 // chain head is not the loop header. As we only consider natural loops with 2430 // single header, this computation can be done only once. 2431 BlockFrequency HeaderFallThroughCost(0); 2432 for (auto *Pred : ChainHeaderBB->predecessors()) { 2433 BlockChain *PredChain = BlockToChain[Pred]; 2434 if (!LoopBlockSet.count(Pred) && 2435 (!PredChain || Pred == *std::prev(PredChain->end()))) { 2436 auto EdgeFreq = MBFI->getBlockFreq(Pred) * 2437 MBPI->getEdgeProbability(Pred, ChainHeaderBB); 2438 auto FallThruCost = ScaleBlockFrequency(EdgeFreq, MisfetchCost); 2439 // If the predecessor has only an unconditional jump to the header, we 2440 // need to consider the cost of this jump. 2441 if (Pred->succ_size() == 1) 2442 FallThruCost += ScaleBlockFrequency(EdgeFreq, JumpInstCost); 2443 HeaderFallThroughCost = std::max(HeaderFallThroughCost, FallThruCost); 2444 } 2445 } 2446 2447 // Here we collect all exit blocks in the loop, and for each exit we find out 2448 // its hottest exit edge. For each loop rotation, we define the loop exit cost 2449 // as the sum of frequencies of exit edges we collect here, excluding the exit 2450 // edge from the tail of the loop chain. 2451 SmallVector<std::pair<MachineBasicBlock *, BlockFrequency>, 4> ExitsWithFreq; 2452 for (auto BB : LoopChain) { 2453 auto LargestExitEdgeProb = BranchProbability::getZero(); 2454 for (auto *Succ : BB->successors()) { 2455 BlockChain *SuccChain = BlockToChain[Succ]; 2456 if (!LoopBlockSet.count(Succ) && 2457 (!SuccChain || Succ == *SuccChain->begin())) { 2458 auto SuccProb = MBPI->getEdgeProbability(BB, Succ); 2459 LargestExitEdgeProb = std::max(LargestExitEdgeProb, SuccProb); 2460 } 2461 } 2462 if (LargestExitEdgeProb > BranchProbability::getZero()) { 2463 auto ExitFreq = MBFI->getBlockFreq(BB) * LargestExitEdgeProb; 2464 ExitsWithFreq.emplace_back(BB, ExitFreq); 2465 } 2466 } 2467 2468 // In this loop we iterate every block in the loop chain and calculate the 2469 // cost assuming the block is the head of the loop chain. When the loop ends, 2470 // we should have found the best candidate as the loop chain's head. 2471 for (auto Iter = LoopChain.begin(), TailIter = std::prev(LoopChain.end()), 2472 EndIter = LoopChain.end(); 2473 Iter != EndIter; Iter++, TailIter++) { 2474 // TailIter is used to track the tail of the loop chain if the block we are 2475 // checking (pointed by Iter) is the head of the chain. 2476 if (TailIter == LoopChain.end()) 2477 TailIter = LoopChain.begin(); 2478 2479 auto TailBB = *TailIter; 2480 2481 // Calculate the cost by putting this BB to the top. 2482 BlockFrequency Cost = 0; 2483 2484 // If the current BB is the loop header, we need to take into account the 2485 // cost of the missed fall through edge from outside of the loop to the 2486 // header. 2487 if (Iter != LoopChain.begin()) 2488 Cost += HeaderFallThroughCost; 2489 2490 // Collect the loop exit cost by summing up frequencies of all exit edges 2491 // except the one from the chain tail. 2492 for (auto &ExitWithFreq : ExitsWithFreq) 2493 if (TailBB != ExitWithFreq.first) 2494 Cost += ExitWithFreq.second; 2495 2496 // The cost of breaking the once fall-through edge from the tail to the top 2497 // of the loop chain. Here we need to consider three cases: 2498 // 1. If the tail node has only one successor, then we will get an 2499 // additional jmp instruction. So the cost here is (MisfetchCost + 2500 // JumpInstCost) * tail node frequency. 2501 // 2. If the tail node has two successors, then we may still get an 2502 // additional jmp instruction if the layout successor after the loop 2503 // chain is not its CFG successor. Note that the more frequently executed 2504 // jmp instruction will be put ahead of the other one. Assume the 2505 // frequency of those two branches are x and y, where x is the frequency 2506 // of the edge to the chain head, then the cost will be 2507 // (x * MisfetechCost + min(x, y) * JumpInstCost) * tail node frequency. 2508 // 3. If the tail node has more than two successors (this rarely happens), 2509 // we won't consider any additional cost. 2510 if (TailBB->isSuccessor(*Iter)) { 2511 auto TailBBFreq = MBFI->getBlockFreq(TailBB); 2512 if (TailBB->succ_size() == 1) 2513 Cost += ScaleBlockFrequency(TailBBFreq.getFrequency(), 2514 MisfetchCost + JumpInstCost); 2515 else if (TailBB->succ_size() == 2) { 2516 auto TailToHeadProb = MBPI->getEdgeProbability(TailBB, *Iter); 2517 auto TailToHeadFreq = TailBBFreq * TailToHeadProb; 2518 auto ColderEdgeFreq = TailToHeadProb > BranchProbability(1, 2) 2519 ? TailBBFreq * TailToHeadProb.getCompl() 2520 : TailToHeadFreq; 2521 Cost += ScaleBlockFrequency(TailToHeadFreq, MisfetchCost) + 2522 ScaleBlockFrequency(ColderEdgeFreq, JumpInstCost); 2523 } 2524 } 2525 2526 LLVM_DEBUG(dbgs() << "The cost of loop rotation by making " 2527 << getBlockName(*Iter) 2528 << " to the top: " << Cost.getFrequency() << "\n"); 2529 2530 if (Cost < SmallestRotationCost) { 2531 SmallestRotationCost = Cost; 2532 RotationPos = Iter; 2533 } 2534 } 2535 2536 if (RotationPos != LoopChain.end()) { 2537 LLVM_DEBUG(dbgs() << "Rotate loop by making " << getBlockName(*RotationPos) 2538 << " to the top\n"); 2539 std::rotate(LoopChain.begin(), RotationPos, LoopChain.end()); 2540 } 2541 } 2542 2543 /// Collect blocks in the given loop that are to be placed. 2544 /// 2545 /// When profile data is available, exclude cold blocks from the returned set; 2546 /// otherwise, collect all blocks in the loop. 2547 MachineBlockPlacement::BlockFilterSet 2548 MachineBlockPlacement::collectLoopBlockSet(const MachineLoop &L) { 2549 BlockFilterSet LoopBlockSet; 2550 2551 // Filter cold blocks off from LoopBlockSet when profile data is available. 2552 // Collect the sum of frequencies of incoming edges to the loop header from 2553 // outside. If we treat the loop as a super block, this is the frequency of 2554 // the loop. Then for each block in the loop, we calculate the ratio between 2555 // its frequency and the frequency of the loop block. When it is too small, 2556 // don't add it to the loop chain. If there are outer loops, then this block 2557 // will be merged into the first outer loop chain for which this block is not 2558 // cold anymore. This needs precise profile data and we only do this when 2559 // profile data is available. 2560 if (F->getFunction().hasProfileData() || ForceLoopColdBlock) { 2561 BlockFrequency LoopFreq(0); 2562 for (auto LoopPred : L.getHeader()->predecessors()) 2563 if (!L.contains(LoopPred)) 2564 LoopFreq += MBFI->getBlockFreq(LoopPred) * 2565 MBPI->getEdgeProbability(LoopPred, L.getHeader()); 2566 2567 for (MachineBasicBlock *LoopBB : L.getBlocks()) { 2568 if (LoopBlockSet.count(LoopBB)) 2569 continue; 2570 auto Freq = MBFI->getBlockFreq(LoopBB).getFrequency(); 2571 if (Freq == 0 || LoopFreq.getFrequency() / Freq > LoopToColdBlockRatio) 2572 continue; 2573 BlockChain *Chain = BlockToChain[LoopBB]; 2574 for (MachineBasicBlock *ChainBB : *Chain) 2575 LoopBlockSet.insert(ChainBB); 2576 } 2577 } else 2578 LoopBlockSet.insert(L.block_begin(), L.block_end()); 2579 2580 return LoopBlockSet; 2581 } 2582 2583 /// Forms basic block chains from the natural loop structures. 2584 /// 2585 /// These chains are designed to preserve the existing *structure* of the code 2586 /// as much as possible. We can then stitch the chains together in a way which 2587 /// both preserves the topological structure and minimizes taken conditional 2588 /// branches. 2589 void MachineBlockPlacement::buildLoopChains(const MachineLoop &L) { 2590 // First recurse through any nested loops, building chains for those inner 2591 // loops. 2592 for (const MachineLoop *InnerLoop : L) 2593 buildLoopChains(*InnerLoop); 2594 2595 assert(BlockWorkList.empty() && 2596 "BlockWorkList not empty when starting to build loop chains."); 2597 assert(EHPadWorkList.empty() && 2598 "EHPadWorkList not empty when starting to build loop chains."); 2599 BlockFilterSet LoopBlockSet = collectLoopBlockSet(L); 2600 2601 // Check if we have profile data for this function. If yes, we will rotate 2602 // this loop by modeling costs more precisely which requires the profile data 2603 // for better layout. 2604 bool RotateLoopWithProfile = 2605 ForcePreciseRotationCost || 2606 (PreciseRotationCost && F->getFunction().hasProfileData()); 2607 2608 // First check to see if there is an obviously preferable top block for the 2609 // loop. This will default to the header, but may end up as one of the 2610 // predecessors to the header if there is one which will result in strictly 2611 // fewer branches in the loop body. 2612 MachineBasicBlock *LoopTop = findBestLoopTop(L, LoopBlockSet); 2613 2614 // If we selected just the header for the loop top, look for a potentially 2615 // profitable exit block in the event that rotating the loop can eliminate 2616 // branches by placing an exit edge at the bottom. 2617 // 2618 // Loops are processed innermost to uttermost, make sure we clear 2619 // PreferredLoopExit before processing a new loop. 2620 PreferredLoopExit = nullptr; 2621 BlockFrequency ExitFreq; 2622 if (!RotateLoopWithProfile && LoopTop == L.getHeader()) 2623 PreferredLoopExit = findBestLoopExit(L, LoopBlockSet, ExitFreq); 2624 2625 BlockChain &LoopChain = *BlockToChain[LoopTop]; 2626 2627 // FIXME: This is a really lame way of walking the chains in the loop: we 2628 // walk the blocks, and use a set to prevent visiting a particular chain 2629 // twice. 2630 SmallPtrSet<BlockChain *, 4> UpdatedPreds; 2631 assert(LoopChain.UnscheduledPredecessors == 0 && 2632 "LoopChain should not have unscheduled predecessors."); 2633 UpdatedPreds.insert(&LoopChain); 2634 2635 for (const MachineBasicBlock *LoopBB : LoopBlockSet) 2636 fillWorkLists(LoopBB, UpdatedPreds, &LoopBlockSet); 2637 2638 buildChain(LoopTop, LoopChain, &LoopBlockSet); 2639 2640 if (RotateLoopWithProfile) 2641 rotateLoopWithProfile(LoopChain, L, LoopBlockSet); 2642 else 2643 rotateLoop(LoopChain, PreferredLoopExit, ExitFreq, LoopBlockSet); 2644 2645 LLVM_DEBUG({ 2646 // Crash at the end so we get all of the debugging output first. 2647 bool BadLoop = false; 2648 if (LoopChain.UnscheduledPredecessors) { 2649 BadLoop = true; 2650 dbgs() << "Loop chain contains a block without its preds placed!\n" 2651 << " Loop header: " << getBlockName(*L.block_begin()) << "\n" 2652 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n"; 2653 } 2654 for (MachineBasicBlock *ChainBB : LoopChain) { 2655 dbgs() << " ... " << getBlockName(ChainBB) << "\n"; 2656 if (!LoopBlockSet.remove(ChainBB)) { 2657 // We don't mark the loop as bad here because there are real situations 2658 // where this can occur. For example, with an unanalyzable fallthrough 2659 // from a loop block to a non-loop block or vice versa. 2660 dbgs() << "Loop chain contains a block not contained by the loop!\n" 2661 << " Loop header: " << getBlockName(*L.block_begin()) << "\n" 2662 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n" 2663 << " Bad block: " << getBlockName(ChainBB) << "\n"; 2664 } 2665 } 2666 2667 if (!LoopBlockSet.empty()) { 2668 BadLoop = true; 2669 for (const MachineBasicBlock *LoopBB : LoopBlockSet) 2670 dbgs() << "Loop contains blocks never placed into a chain!\n" 2671 << " Loop header: " << getBlockName(*L.block_begin()) << "\n" 2672 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n" 2673 << " Bad block: " << getBlockName(LoopBB) << "\n"; 2674 } 2675 assert(!BadLoop && "Detected problems with the placement of this loop."); 2676 }); 2677 2678 BlockWorkList.clear(); 2679 EHPadWorkList.clear(); 2680 } 2681 2682 void MachineBlockPlacement::buildCFGChains() { 2683 // Ensure that every BB in the function has an associated chain to simplify 2684 // the assumptions of the remaining algorithm. 2685 SmallVector<MachineOperand, 4> Cond; // For analyzeBranch. 2686 for (MachineFunction::iterator FI = F->begin(), FE = F->end(); FI != FE; 2687 ++FI) { 2688 MachineBasicBlock *BB = &*FI; 2689 BlockChain *Chain = 2690 new (ChainAllocator.Allocate()) BlockChain(BlockToChain, BB); 2691 // Also, merge any blocks which we cannot reason about and must preserve 2692 // the exact fallthrough behavior for. 2693 while (true) { 2694 Cond.clear(); 2695 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For analyzeBranch. 2696 if (!TII->analyzeBranch(*BB, TBB, FBB, Cond) || !FI->canFallThrough()) 2697 break; 2698 2699 MachineFunction::iterator NextFI = std::next(FI); 2700 MachineBasicBlock *NextBB = &*NextFI; 2701 // Ensure that the layout successor is a viable block, as we know that 2702 // fallthrough is a possibility. 2703 assert(NextFI != FE && "Can't fallthrough past the last block."); 2704 LLVM_DEBUG(dbgs() << "Pre-merging due to unanalyzable fallthrough: " 2705 << getBlockName(BB) << " -> " << getBlockName(NextBB) 2706 << "\n"); 2707 Chain->merge(NextBB, nullptr); 2708 #ifndef NDEBUG 2709 BlocksWithUnanalyzableExits.insert(&*BB); 2710 #endif 2711 FI = NextFI; 2712 BB = NextBB; 2713 } 2714 } 2715 2716 // Build any loop-based chains. 2717 PreferredLoopExit = nullptr; 2718 for (MachineLoop *L : *MLI) 2719 buildLoopChains(*L); 2720 2721 assert(BlockWorkList.empty() && 2722 "BlockWorkList should be empty before building final chain."); 2723 assert(EHPadWorkList.empty() && 2724 "EHPadWorkList should be empty before building final chain."); 2725 2726 SmallPtrSet<BlockChain *, 4> UpdatedPreds; 2727 for (MachineBasicBlock &MBB : *F) 2728 fillWorkLists(&MBB, UpdatedPreds); 2729 2730 BlockChain &FunctionChain = *BlockToChain[&F->front()]; 2731 buildChain(&F->front(), FunctionChain); 2732 2733 #ifndef NDEBUG 2734 using FunctionBlockSetType = SmallPtrSet<MachineBasicBlock *, 16>; 2735 #endif 2736 LLVM_DEBUG({ 2737 // Crash at the end so we get all of the debugging output first. 2738 bool BadFunc = false; 2739 FunctionBlockSetType FunctionBlockSet; 2740 for (MachineBasicBlock &MBB : *F) 2741 FunctionBlockSet.insert(&MBB); 2742 2743 for (MachineBasicBlock *ChainBB : FunctionChain) 2744 if (!FunctionBlockSet.erase(ChainBB)) { 2745 BadFunc = true; 2746 dbgs() << "Function chain contains a block not in the function!\n" 2747 << " Bad block: " << getBlockName(ChainBB) << "\n"; 2748 } 2749 2750 if (!FunctionBlockSet.empty()) { 2751 BadFunc = true; 2752 for (MachineBasicBlock *RemainingBB : FunctionBlockSet) 2753 dbgs() << "Function contains blocks never placed into a chain!\n" 2754 << " Bad block: " << getBlockName(RemainingBB) << "\n"; 2755 } 2756 assert(!BadFunc && "Detected problems with the block placement."); 2757 }); 2758 2759 // Remember original layout ordering, so we can update terminators after 2760 // reordering to point to the original layout successor. 2761 SmallVector<MachineBasicBlock *, 4> OriginalLayoutSuccessors( 2762 F->getNumBlockIDs()); 2763 { 2764 MachineBasicBlock *LastMBB = nullptr; 2765 for (auto &MBB : *F) { 2766 if (LastMBB != nullptr) 2767 OriginalLayoutSuccessors[LastMBB->getNumber()] = &MBB; 2768 LastMBB = &MBB; 2769 } 2770 OriginalLayoutSuccessors[F->back().getNumber()] = nullptr; 2771 } 2772 2773 // Splice the blocks into place. 2774 MachineFunction::iterator InsertPos = F->begin(); 2775 LLVM_DEBUG(dbgs() << "[MBP] Function: " << F->getName() << "\n"); 2776 for (MachineBasicBlock *ChainBB : FunctionChain) { 2777 LLVM_DEBUG(dbgs() << (ChainBB == *FunctionChain.begin() ? "Placing chain " 2778 : " ... ") 2779 << getBlockName(ChainBB) << "\n"); 2780 if (InsertPos != MachineFunction::iterator(ChainBB)) 2781 F->splice(InsertPos, ChainBB); 2782 else 2783 ++InsertPos; 2784 2785 // Update the terminator of the previous block. 2786 if (ChainBB == *FunctionChain.begin()) 2787 continue; 2788 MachineBasicBlock *PrevBB = &*std::prev(MachineFunction::iterator(ChainBB)); 2789 2790 // FIXME: It would be awesome of updateTerminator would just return rather 2791 // than assert when the branch cannot be analyzed in order to remove this 2792 // boiler plate. 2793 Cond.clear(); 2794 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For analyzeBranch. 2795 2796 #ifndef NDEBUG 2797 if (!BlocksWithUnanalyzableExits.count(PrevBB)) { 2798 // Given the exact block placement we chose, we may actually not _need_ to 2799 // be able to edit PrevBB's terminator sequence, but not being _able_ to 2800 // do that at this point is a bug. 2801 assert((!TII->analyzeBranch(*PrevBB, TBB, FBB, Cond) || 2802 !PrevBB->canFallThrough()) && 2803 "Unexpected block with un-analyzable fallthrough!"); 2804 Cond.clear(); 2805 TBB = FBB = nullptr; 2806 } 2807 #endif 2808 2809 // The "PrevBB" is not yet updated to reflect current code layout, so, 2810 // o. it may fall-through to a block without explicit "goto" instruction 2811 // before layout, and no longer fall-through it after layout; or 2812 // o. just opposite. 2813 // 2814 // analyzeBranch() may return erroneous value for FBB when these two 2815 // situations take place. For the first scenario FBB is mistakenly set NULL; 2816 // for the 2nd scenario, the FBB, which is expected to be NULL, is 2817 // mistakenly pointing to "*BI". 2818 // Thus, if the future change needs to use FBB before the layout is set, it 2819 // has to correct FBB first by using the code similar to the following: 2820 // 2821 // if (!Cond.empty() && (!FBB || FBB == ChainBB)) { 2822 // PrevBB->updateTerminator(); 2823 // Cond.clear(); 2824 // TBB = FBB = nullptr; 2825 // if (TII->analyzeBranch(*PrevBB, TBB, FBB, Cond)) { 2826 // // FIXME: This should never take place. 2827 // TBB = FBB = nullptr; 2828 // } 2829 // } 2830 if (!TII->analyzeBranch(*PrevBB, TBB, FBB, Cond)) { 2831 PrevBB->updateTerminator(OriginalLayoutSuccessors[PrevBB->getNumber()]); 2832 } 2833 } 2834 2835 // Fixup the last block. 2836 Cond.clear(); 2837 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For analyzeBranch. 2838 if (!TII->analyzeBranch(F->back(), TBB, FBB, Cond)) { 2839 MachineBasicBlock *PrevBB = &F->back(); 2840 PrevBB->updateTerminator(OriginalLayoutSuccessors[PrevBB->getNumber()]); 2841 } 2842 2843 BlockWorkList.clear(); 2844 EHPadWorkList.clear(); 2845 } 2846 2847 void MachineBlockPlacement::optimizeBranches() { 2848 BlockChain &FunctionChain = *BlockToChain[&F->front()]; 2849 SmallVector<MachineOperand, 4> Cond; // For analyzeBranch. 2850 2851 // Now that all the basic blocks in the chain have the proper layout, 2852 // make a final call to analyzeBranch with AllowModify set. 2853 // Indeed, the target may be able to optimize the branches in a way we 2854 // cannot because all branches may not be analyzable. 2855 // E.g., the target may be able to remove an unconditional branch to 2856 // a fallthrough when it occurs after predicated terminators. 2857 for (MachineBasicBlock *ChainBB : FunctionChain) { 2858 Cond.clear(); 2859 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For analyzeBranch. 2860 if (!TII->analyzeBranch(*ChainBB, TBB, FBB, Cond, /*AllowModify*/ true)) { 2861 // If PrevBB has a two-way branch, try to re-order the branches 2862 // such that we branch to the successor with higher probability first. 2863 if (TBB && !Cond.empty() && FBB && 2864 MBPI->getEdgeProbability(ChainBB, FBB) > 2865 MBPI->getEdgeProbability(ChainBB, TBB) && 2866 !TII->reverseBranchCondition(Cond)) { 2867 LLVM_DEBUG(dbgs() << "Reverse order of the two branches: " 2868 << getBlockName(ChainBB) << "\n"); 2869 LLVM_DEBUG(dbgs() << " Edge probability: " 2870 << MBPI->getEdgeProbability(ChainBB, FBB) << " vs " 2871 << MBPI->getEdgeProbability(ChainBB, TBB) << "\n"); 2872 DebugLoc dl; // FIXME: this is nowhere 2873 TII->removeBranch(*ChainBB); 2874 TII->insertBranch(*ChainBB, FBB, TBB, Cond, dl); 2875 } 2876 } 2877 } 2878 } 2879 2880 void MachineBlockPlacement::alignBlocks() { 2881 // Walk through the backedges of the function now that we have fully laid out 2882 // the basic blocks and align the destination of each backedge. We don't rely 2883 // exclusively on the loop info here so that we can align backedges in 2884 // unnatural CFGs and backedges that were introduced purely because of the 2885 // loop rotations done during this layout pass. 2886 if (F->getFunction().hasMinSize() || 2887 (F->getFunction().hasOptSize() && !TLI->alignLoopsWithOptSize())) 2888 return; 2889 BlockChain &FunctionChain = *BlockToChain[&F->front()]; 2890 if (FunctionChain.begin() == FunctionChain.end()) 2891 return; // Empty chain. 2892 2893 const BranchProbability ColdProb(1, 5); // 20% 2894 BlockFrequency EntryFreq = MBFI->getBlockFreq(&F->front()); 2895 BlockFrequency WeightedEntryFreq = EntryFreq * ColdProb; 2896 for (MachineBasicBlock *ChainBB : FunctionChain) { 2897 if (ChainBB == *FunctionChain.begin()) 2898 continue; 2899 2900 // Don't align non-looping basic blocks. These are unlikely to execute 2901 // enough times to matter in practice. Note that we'll still handle 2902 // unnatural CFGs inside of a natural outer loop (the common case) and 2903 // rotated loops. 2904 MachineLoop *L = MLI->getLoopFor(ChainBB); 2905 if (!L) 2906 continue; 2907 2908 const Align Align = TLI->getPrefLoopAlignment(L); 2909 if (Align == 1) 2910 continue; // Don't care about loop alignment. 2911 2912 // If the block is cold relative to the function entry don't waste space 2913 // aligning it. 2914 BlockFrequency Freq = MBFI->getBlockFreq(ChainBB); 2915 if (Freq < WeightedEntryFreq) 2916 continue; 2917 2918 // If the block is cold relative to its loop header, don't align it 2919 // regardless of what edges into the block exist. 2920 MachineBasicBlock *LoopHeader = L->getHeader(); 2921 BlockFrequency LoopHeaderFreq = MBFI->getBlockFreq(LoopHeader); 2922 if (Freq < (LoopHeaderFreq * ColdProb)) 2923 continue; 2924 2925 // If the global profiles indicates so, don't align it. 2926 if (llvm::shouldOptimizeForSize(ChainBB, PSI, MBFI.get()) && 2927 !TLI->alignLoopsWithOptSize()) 2928 continue; 2929 2930 // Check for the existence of a non-layout predecessor which would benefit 2931 // from aligning this block. 2932 MachineBasicBlock *LayoutPred = 2933 &*std::prev(MachineFunction::iterator(ChainBB)); 2934 2935 auto DetermineMaxAlignmentPadding = [&]() { 2936 // Set the maximum bytes allowed to be emitted for alignment. 2937 unsigned MaxBytes; 2938 if (MaxBytesForAlignmentOverride.getNumOccurrences() > 0) 2939 MaxBytes = MaxBytesForAlignmentOverride; 2940 else 2941 MaxBytes = TLI->getMaxPermittedBytesForAlignment(ChainBB); 2942 ChainBB->setMaxBytesForAlignment(MaxBytes); 2943 }; 2944 2945 // Force alignment if all the predecessors are jumps. We already checked 2946 // that the block isn't cold above. 2947 if (!LayoutPred->isSuccessor(ChainBB)) { 2948 ChainBB->setAlignment(Align); 2949 DetermineMaxAlignmentPadding(); 2950 continue; 2951 } 2952 2953 // Align this block if the layout predecessor's edge into this block is 2954 // cold relative to the block. When this is true, other predecessors make up 2955 // all of the hot entries into the block and thus alignment is likely to be 2956 // important. 2957 BranchProbability LayoutProb = 2958 MBPI->getEdgeProbability(LayoutPred, ChainBB); 2959 BlockFrequency LayoutEdgeFreq = MBFI->getBlockFreq(LayoutPred) * LayoutProb; 2960 if (LayoutEdgeFreq <= (Freq * ColdProb)) { 2961 ChainBB->setAlignment(Align); 2962 DetermineMaxAlignmentPadding(); 2963 } 2964 } 2965 } 2966 2967 /// Tail duplicate \p BB into (some) predecessors if profitable, repeating if 2968 /// it was duplicated into its chain predecessor and removed. 2969 /// \p BB - Basic block that may be duplicated. 2970 /// 2971 /// \p LPred - Chosen layout predecessor of \p BB. 2972 /// Updated to be the chain end if LPred is removed. 2973 /// \p Chain - Chain to which \p LPred belongs, and \p BB will belong. 2974 /// \p BlockFilter - Set of blocks that belong to the loop being laid out. 2975 /// Used to identify which blocks to update predecessor 2976 /// counts. 2977 /// \p PrevUnplacedBlockIt - Iterator pointing to the last block that was 2978 /// chosen in the given order due to unnatural CFG 2979 /// only needed if \p BB is removed and 2980 /// \p PrevUnplacedBlockIt pointed to \p BB. 2981 /// @return true if \p BB was removed. 2982 bool MachineBlockPlacement::repeatedlyTailDuplicateBlock( 2983 MachineBasicBlock *BB, MachineBasicBlock *&LPred, 2984 const MachineBasicBlock *LoopHeaderBB, 2985 BlockChain &Chain, BlockFilterSet *BlockFilter, 2986 MachineFunction::iterator &PrevUnplacedBlockIt) { 2987 bool Removed, DuplicatedToLPred; 2988 bool DuplicatedToOriginalLPred; 2989 Removed = maybeTailDuplicateBlock(BB, LPred, Chain, BlockFilter, 2990 PrevUnplacedBlockIt, 2991 DuplicatedToLPred); 2992 if (!Removed) 2993 return false; 2994 DuplicatedToOriginalLPred = DuplicatedToLPred; 2995 // Iteratively try to duplicate again. It can happen that a block that is 2996 // duplicated into is still small enough to be duplicated again. 2997 // No need to call markBlockSuccessors in this case, as the blocks being 2998 // duplicated from here on are already scheduled. 2999 while (DuplicatedToLPred && Removed) { 3000 MachineBasicBlock *DupBB, *DupPred; 3001 // The removal callback causes Chain.end() to be updated when a block is 3002 // removed. On the first pass through the loop, the chain end should be the 3003 // same as it was on function entry. On subsequent passes, because we are 3004 // duplicating the block at the end of the chain, if it is removed the 3005 // chain will have shrunk by one block. 3006 BlockChain::iterator ChainEnd = Chain.end(); 3007 DupBB = *(--ChainEnd); 3008 // Now try to duplicate again. 3009 if (ChainEnd == Chain.begin()) 3010 break; 3011 DupPred = *std::prev(ChainEnd); 3012 Removed = maybeTailDuplicateBlock(DupBB, DupPred, Chain, BlockFilter, 3013 PrevUnplacedBlockIt, 3014 DuplicatedToLPred); 3015 } 3016 // If BB was duplicated into LPred, it is now scheduled. But because it was 3017 // removed, markChainSuccessors won't be called for its chain. Instead we 3018 // call markBlockSuccessors for LPred to achieve the same effect. This must go 3019 // at the end because repeating the tail duplication can increase the number 3020 // of unscheduled predecessors. 3021 LPred = *std::prev(Chain.end()); 3022 if (DuplicatedToOriginalLPred) 3023 markBlockSuccessors(Chain, LPred, LoopHeaderBB, BlockFilter); 3024 return true; 3025 } 3026 3027 /// Tail duplicate \p BB into (some) predecessors if profitable. 3028 /// \p BB - Basic block that may be duplicated 3029 /// \p LPred - Chosen layout predecessor of \p BB 3030 /// \p Chain - Chain to which \p LPred belongs, and \p BB will belong. 3031 /// \p BlockFilter - Set of blocks that belong to the loop being laid out. 3032 /// Used to identify which blocks to update predecessor 3033 /// counts. 3034 /// \p PrevUnplacedBlockIt - Iterator pointing to the last block that was 3035 /// chosen in the given order due to unnatural CFG 3036 /// only needed if \p BB is removed and 3037 /// \p PrevUnplacedBlockIt pointed to \p BB. 3038 /// \p DuplicatedToLPred - True if the block was duplicated into LPred. 3039 /// \return - True if the block was duplicated into all preds and removed. 3040 bool MachineBlockPlacement::maybeTailDuplicateBlock( 3041 MachineBasicBlock *BB, MachineBasicBlock *LPred, 3042 BlockChain &Chain, BlockFilterSet *BlockFilter, 3043 MachineFunction::iterator &PrevUnplacedBlockIt, 3044 bool &DuplicatedToLPred) { 3045 DuplicatedToLPred = false; 3046 if (!shouldTailDuplicate(BB)) 3047 return false; 3048 3049 LLVM_DEBUG(dbgs() << "Redoing tail duplication for Succ#" << BB->getNumber() 3050 << "\n"); 3051 3052 // This has to be a callback because none of it can be done after 3053 // BB is deleted. 3054 bool Removed = false; 3055 auto RemovalCallback = 3056 [&](MachineBasicBlock *RemBB) { 3057 // Signal to outer function 3058 Removed = true; 3059 3060 // Conservative default. 3061 bool InWorkList = true; 3062 // Remove from the Chain and Chain Map 3063 if (BlockToChain.count(RemBB)) { 3064 BlockChain *Chain = BlockToChain[RemBB]; 3065 InWorkList = Chain->UnscheduledPredecessors == 0; 3066 Chain->remove(RemBB); 3067 BlockToChain.erase(RemBB); 3068 } 3069 3070 // Handle the unplaced block iterator 3071 if (&(*PrevUnplacedBlockIt) == RemBB) { 3072 PrevUnplacedBlockIt++; 3073 } 3074 3075 // Handle the Work Lists 3076 if (InWorkList) { 3077 SmallVectorImpl<MachineBasicBlock *> &RemoveList = BlockWorkList; 3078 if (RemBB->isEHPad()) 3079 RemoveList = EHPadWorkList; 3080 llvm::erase_value(RemoveList, RemBB); 3081 } 3082 3083 // Handle the filter set 3084 if (BlockFilter) { 3085 BlockFilter->remove(RemBB); 3086 } 3087 3088 // Remove the block from loop info. 3089 MLI->removeBlock(RemBB); 3090 if (RemBB == PreferredLoopExit) 3091 PreferredLoopExit = nullptr; 3092 3093 LLVM_DEBUG(dbgs() << "TailDuplicator deleted block: " 3094 << getBlockName(RemBB) << "\n"); 3095 }; 3096 auto RemovalCallbackRef = 3097 function_ref<void(MachineBasicBlock*)>(RemovalCallback); 3098 3099 SmallVector<MachineBasicBlock *, 8> DuplicatedPreds; 3100 bool IsSimple = TailDup.isSimpleBB(BB); 3101 SmallVector<MachineBasicBlock *, 8> CandidatePreds; 3102 SmallVectorImpl<MachineBasicBlock *> *CandidatePtr = nullptr; 3103 if (F->getFunction().hasProfileData()) { 3104 // We can do partial duplication with precise profile information. 3105 findDuplicateCandidates(CandidatePreds, BB, BlockFilter); 3106 if (CandidatePreds.size() == 0) 3107 return false; 3108 if (CandidatePreds.size() < BB->pred_size()) 3109 CandidatePtr = &CandidatePreds; 3110 } 3111 TailDup.tailDuplicateAndUpdate(IsSimple, BB, LPred, &DuplicatedPreds, 3112 &RemovalCallbackRef, CandidatePtr); 3113 3114 // Update UnscheduledPredecessors to reflect tail-duplication. 3115 DuplicatedToLPred = false; 3116 for (MachineBasicBlock *Pred : DuplicatedPreds) { 3117 // We're only looking for unscheduled predecessors that match the filter. 3118 BlockChain* PredChain = BlockToChain[Pred]; 3119 if (Pred == LPred) 3120 DuplicatedToLPred = true; 3121 if (Pred == LPred || (BlockFilter && !BlockFilter->count(Pred)) 3122 || PredChain == &Chain) 3123 continue; 3124 for (MachineBasicBlock *NewSucc : Pred->successors()) { 3125 if (BlockFilter && !BlockFilter->count(NewSucc)) 3126 continue; 3127 BlockChain *NewChain = BlockToChain[NewSucc]; 3128 if (NewChain != &Chain && NewChain != PredChain) 3129 NewChain->UnscheduledPredecessors++; 3130 } 3131 } 3132 return Removed; 3133 } 3134 3135 // Count the number of actual machine instructions. 3136 static uint64_t countMBBInstruction(MachineBasicBlock *MBB) { 3137 uint64_t InstrCount = 0; 3138 for (MachineInstr &MI : *MBB) { 3139 if (!MI.isPHI() && !MI.isMetaInstruction()) 3140 InstrCount += 1; 3141 } 3142 return InstrCount; 3143 } 3144 3145 // The size cost of duplication is the instruction size of the duplicated block. 3146 // So we should scale the threshold accordingly. But the instruction size is not 3147 // available on all targets, so we use the number of instructions instead. 3148 BlockFrequency MachineBlockPlacement::scaleThreshold(MachineBasicBlock *BB) { 3149 return DupThreshold.getFrequency() * countMBBInstruction(BB); 3150 } 3151 3152 // Returns true if BB is Pred's best successor. 3153 bool MachineBlockPlacement::isBestSuccessor(MachineBasicBlock *BB, 3154 MachineBasicBlock *Pred, 3155 BlockFilterSet *BlockFilter) { 3156 if (BB == Pred) 3157 return false; 3158 if (BlockFilter && !BlockFilter->count(Pred)) 3159 return false; 3160 BlockChain *PredChain = BlockToChain[Pred]; 3161 if (PredChain && (Pred != *std::prev(PredChain->end()))) 3162 return false; 3163 3164 // Find the successor with largest probability excluding BB. 3165 BranchProbability BestProb = BranchProbability::getZero(); 3166 for (MachineBasicBlock *Succ : Pred->successors()) 3167 if (Succ != BB) { 3168 if (BlockFilter && !BlockFilter->count(Succ)) 3169 continue; 3170 BlockChain *SuccChain = BlockToChain[Succ]; 3171 if (SuccChain && (Succ != *SuccChain->begin())) 3172 continue; 3173 BranchProbability SuccProb = MBPI->getEdgeProbability(Pred, Succ); 3174 if (SuccProb > BestProb) 3175 BestProb = SuccProb; 3176 } 3177 3178 BranchProbability BBProb = MBPI->getEdgeProbability(Pred, BB); 3179 if (BBProb <= BestProb) 3180 return false; 3181 3182 // Compute the number of reduced taken branches if Pred falls through to BB 3183 // instead of another successor. Then compare it with threshold. 3184 BlockFrequency PredFreq = getBlockCountOrFrequency(Pred); 3185 BlockFrequency Gain = PredFreq * (BBProb - BestProb); 3186 return Gain > scaleThreshold(BB); 3187 } 3188 3189 // Find out the predecessors of BB and BB can be beneficially duplicated into 3190 // them. 3191 void MachineBlockPlacement::findDuplicateCandidates( 3192 SmallVectorImpl<MachineBasicBlock *> &Candidates, 3193 MachineBasicBlock *BB, 3194 BlockFilterSet *BlockFilter) { 3195 MachineBasicBlock *Fallthrough = nullptr; 3196 BranchProbability DefaultBranchProb = BranchProbability::getZero(); 3197 BlockFrequency BBDupThreshold(scaleThreshold(BB)); 3198 SmallVector<MachineBasicBlock *, 8> Preds(BB->predecessors()); 3199 SmallVector<MachineBasicBlock *, 8> Succs(BB->successors()); 3200 3201 // Sort for highest frequency. 3202 auto CmpSucc = [&](MachineBasicBlock *A, MachineBasicBlock *B) { 3203 return MBPI->getEdgeProbability(BB, A) > MBPI->getEdgeProbability(BB, B); 3204 }; 3205 auto CmpPred = [&](MachineBasicBlock *A, MachineBasicBlock *B) { 3206 return MBFI->getBlockFreq(A) > MBFI->getBlockFreq(B); 3207 }; 3208 llvm::stable_sort(Succs, CmpSucc); 3209 llvm::stable_sort(Preds, CmpPred); 3210 3211 auto SuccIt = Succs.begin(); 3212 if (SuccIt != Succs.end()) { 3213 DefaultBranchProb = MBPI->getEdgeProbability(BB, *SuccIt).getCompl(); 3214 } 3215 3216 // For each predecessors of BB, compute the benefit of duplicating BB, 3217 // if it is larger than the threshold, add it into Candidates. 3218 // 3219 // If we have following control flow. 3220 // 3221 // PB1 PB2 PB3 PB4 3222 // \ | / /\ 3223 // \ | / / \ 3224 // \ |/ / \ 3225 // BB----/ OB 3226 // /\ 3227 // / \ 3228 // SB1 SB2 3229 // 3230 // And it can be partially duplicated as 3231 // 3232 // PB2+BB 3233 // | PB1 PB3 PB4 3234 // | | / /\ 3235 // | | / / \ 3236 // | |/ / \ 3237 // | BB----/ OB 3238 // |\ /| 3239 // | X | 3240 // |/ \| 3241 // SB2 SB1 3242 // 3243 // The benefit of duplicating into a predecessor is defined as 3244 // Orig_taken_branch - Duplicated_taken_branch 3245 // 3246 // The Orig_taken_branch is computed with the assumption that predecessor 3247 // jumps to BB and the most possible successor is laid out after BB. 3248 // 3249 // The Duplicated_taken_branch is computed with the assumption that BB is 3250 // duplicated into PB, and one successor is layout after it (SB1 for PB1 and 3251 // SB2 for PB2 in our case). If there is no available successor, the combined 3252 // block jumps to all BB's successor, like PB3 in this example. 3253 // 3254 // If a predecessor has multiple successors, so BB can't be duplicated into 3255 // it. But it can beneficially fall through to BB, and duplicate BB into other 3256 // predecessors. 3257 for (MachineBasicBlock *Pred : Preds) { 3258 BlockFrequency PredFreq = getBlockCountOrFrequency(Pred); 3259 3260 if (!TailDup.canTailDuplicate(BB, Pred)) { 3261 // BB can't be duplicated into Pred, but it is possible to be layout 3262 // below Pred. 3263 if (!Fallthrough && isBestSuccessor(BB, Pred, BlockFilter)) { 3264 Fallthrough = Pred; 3265 if (SuccIt != Succs.end()) 3266 SuccIt++; 3267 } 3268 continue; 3269 } 3270 3271 BlockFrequency OrigCost = PredFreq + PredFreq * DefaultBranchProb; 3272 BlockFrequency DupCost; 3273 if (SuccIt == Succs.end()) { 3274 // Jump to all successors; 3275 if (Succs.size() > 0) 3276 DupCost += PredFreq; 3277 } else { 3278 // Fallthrough to *SuccIt, jump to all other successors; 3279 DupCost += PredFreq; 3280 DupCost -= PredFreq * MBPI->getEdgeProbability(BB, *SuccIt); 3281 } 3282 3283 assert(OrigCost >= DupCost); 3284 OrigCost -= DupCost; 3285 if (OrigCost > BBDupThreshold) { 3286 Candidates.push_back(Pred); 3287 if (SuccIt != Succs.end()) 3288 SuccIt++; 3289 } 3290 } 3291 3292 // No predecessors can optimally fallthrough to BB. 3293 // So we can change one duplication into fallthrough. 3294 if (!Fallthrough) { 3295 if ((Candidates.size() < Preds.size()) && (Candidates.size() > 0)) { 3296 Candidates[0] = Candidates.back(); 3297 Candidates.pop_back(); 3298 } 3299 } 3300 } 3301 3302 void MachineBlockPlacement::initDupThreshold() { 3303 DupThreshold = 0; 3304 if (!F->getFunction().hasProfileData()) 3305 return; 3306 3307 // We prefer to use prifile count. 3308 uint64_t HotThreshold = PSI->getOrCompHotCountThreshold(); 3309 if (HotThreshold != UINT64_MAX) { 3310 UseProfileCount = true; 3311 DupThreshold = HotThreshold * TailDupProfilePercentThreshold / 100; 3312 return; 3313 } 3314 3315 // Profile count is not available, we can use block frequency instead. 3316 BlockFrequency MaxFreq = 0; 3317 for (MachineBasicBlock &MBB : *F) { 3318 BlockFrequency Freq = MBFI->getBlockFreq(&MBB); 3319 if (Freq > MaxFreq) 3320 MaxFreq = Freq; 3321 } 3322 3323 BranchProbability ThresholdProb(TailDupPlacementPenalty, 100); 3324 DupThreshold = MaxFreq * ThresholdProb; 3325 UseProfileCount = false; 3326 } 3327 3328 bool MachineBlockPlacement::runOnMachineFunction(MachineFunction &MF) { 3329 if (skipFunction(MF.getFunction())) 3330 return false; 3331 3332 // Check for single-block functions and skip them. 3333 if (std::next(MF.begin()) == MF.end()) 3334 return false; 3335 3336 F = &MF; 3337 MBPI = &getAnalysis<MachineBranchProbabilityInfo>(); 3338 MBFI = std::make_unique<MBFIWrapper>( 3339 getAnalysis<MachineBlockFrequencyInfo>()); 3340 MLI = &getAnalysis<MachineLoopInfo>(); 3341 TII = MF.getSubtarget().getInstrInfo(); 3342 TLI = MF.getSubtarget().getTargetLowering(); 3343 MPDT = nullptr; 3344 PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI(); 3345 3346 initDupThreshold(); 3347 3348 // Initialize PreferredLoopExit to nullptr here since it may never be set if 3349 // there are no MachineLoops. 3350 PreferredLoopExit = nullptr; 3351 3352 assert(BlockToChain.empty() && 3353 "BlockToChain map should be empty before starting placement."); 3354 assert(ComputedEdges.empty() && 3355 "Computed Edge map should be empty before starting placement."); 3356 3357 unsigned TailDupSize = TailDupPlacementThreshold; 3358 // If only the aggressive threshold is explicitly set, use it. 3359 if (TailDupPlacementAggressiveThreshold.getNumOccurrences() != 0 && 3360 TailDupPlacementThreshold.getNumOccurrences() == 0) 3361 TailDupSize = TailDupPlacementAggressiveThreshold; 3362 3363 TargetPassConfig *PassConfig = &getAnalysis<TargetPassConfig>(); 3364 // For aggressive optimization, we can adjust some thresholds to be less 3365 // conservative. 3366 if (PassConfig->getOptLevel() >= CodeGenOpt::Aggressive) { 3367 // At O3 we should be more willing to copy blocks for tail duplication. This 3368 // increases size pressure, so we only do it at O3 3369 // Do this unless only the regular threshold is explicitly set. 3370 if (TailDupPlacementThreshold.getNumOccurrences() == 0 || 3371 TailDupPlacementAggressiveThreshold.getNumOccurrences() != 0) 3372 TailDupSize = TailDupPlacementAggressiveThreshold; 3373 } 3374 3375 // If there's no threshold provided through options, query the target 3376 // information for a threshold instead. 3377 if (TailDupPlacementThreshold.getNumOccurrences() == 0 && 3378 (PassConfig->getOptLevel() < CodeGenOpt::Aggressive || 3379 TailDupPlacementAggressiveThreshold.getNumOccurrences() == 0)) 3380 TailDupSize = TII->getTailDuplicateSize(PassConfig->getOptLevel()); 3381 3382 if (allowTailDupPlacement()) { 3383 MPDT = &getAnalysis<MachinePostDominatorTree>(); 3384 bool OptForSize = MF.getFunction().hasOptSize() || 3385 llvm::shouldOptimizeForSize(&MF, PSI, &MBFI->getMBFI()); 3386 if (OptForSize) 3387 TailDupSize = 1; 3388 bool PreRegAlloc = false; 3389 TailDup.initMF(MF, PreRegAlloc, MBPI, MBFI.get(), PSI, 3390 /* LayoutMode */ true, TailDupSize); 3391 precomputeTriangleChains(); 3392 } 3393 3394 buildCFGChains(); 3395 3396 // Changing the layout can create new tail merging opportunities. 3397 // TailMerge can create jump into if branches that make CFG irreducible for 3398 // HW that requires structured CFG. 3399 bool EnableTailMerge = !MF.getTarget().requiresStructuredCFG() && 3400 PassConfig->getEnableTailMerge() && 3401 BranchFoldPlacement; 3402 // No tail merging opportunities if the block number is less than four. 3403 if (MF.size() > 3 && EnableTailMerge) { 3404 unsigned TailMergeSize = TailDupSize + 1; 3405 BranchFolder BF(/*DefaultEnableTailMerge=*/true, /*CommonHoist=*/false, 3406 *MBFI, *MBPI, PSI, TailMergeSize); 3407 3408 if (BF.OptimizeFunction(MF, TII, MF.getSubtarget().getRegisterInfo(), MLI, 3409 /*AfterPlacement=*/true)) { 3410 // Redo the layout if tail merging creates/removes/moves blocks. 3411 BlockToChain.clear(); 3412 ComputedEdges.clear(); 3413 // Must redo the post-dominator tree if blocks were changed. 3414 if (MPDT) 3415 MPDT->runOnMachineFunction(MF); 3416 ChainAllocator.DestroyAll(); 3417 buildCFGChains(); 3418 } 3419 } 3420 3421 // Apply a post-processing optimizing block placement. 3422 if (MF.size() >= 3 && EnableExtTspBlockPlacement) { 3423 // Find a new placement and modify the layout of the blocks in the function. 3424 applyExtTsp(); 3425 3426 // Re-create CFG chain so that we can optimizeBranches and alignBlocks. 3427 createCFGChainExtTsp(); 3428 } 3429 3430 optimizeBranches(); 3431 alignBlocks(); 3432 3433 BlockToChain.clear(); 3434 ComputedEdges.clear(); 3435 ChainAllocator.DestroyAll(); 3436 3437 bool HasMaxBytesOverride = 3438 MaxBytesForAlignmentOverride.getNumOccurrences() > 0; 3439 3440 if (AlignAllBlock) 3441 // Align all of the blocks in the function to a specific alignment. 3442 for (MachineBasicBlock &MBB : MF) { 3443 if (HasMaxBytesOverride) 3444 MBB.setAlignment(Align(1ULL << AlignAllBlock), 3445 MaxBytesForAlignmentOverride); 3446 else 3447 MBB.setAlignment(Align(1ULL << AlignAllBlock)); 3448 } 3449 else if (AlignAllNonFallThruBlocks) { 3450 // Align all of the blocks that have no fall-through predecessors to a 3451 // specific alignment. 3452 for (auto MBI = std::next(MF.begin()), MBE = MF.end(); MBI != MBE; ++MBI) { 3453 auto LayoutPred = std::prev(MBI); 3454 if (!LayoutPred->isSuccessor(&*MBI)) { 3455 if (HasMaxBytesOverride) 3456 MBI->setAlignment(Align(1ULL << AlignAllNonFallThruBlocks), 3457 MaxBytesForAlignmentOverride); 3458 else 3459 MBI->setAlignment(Align(1ULL << AlignAllNonFallThruBlocks)); 3460 } 3461 } 3462 } 3463 if (ViewBlockLayoutWithBFI != GVDT_None && 3464 (ViewBlockFreqFuncName.empty() || 3465 F->getFunction().getName().equals(ViewBlockFreqFuncName))) { 3466 MBFI->view("MBP." + MF.getName(), false); 3467 } 3468 3469 // We always return true as we have no way to track whether the final order 3470 // differs from the original order. 3471 return true; 3472 } 3473 3474 void MachineBlockPlacement::applyExtTsp() { 3475 // Prepare data; blocks are indexed by their index in the current ordering. 3476 DenseMap<const MachineBasicBlock *, uint64_t> BlockIndex; 3477 BlockIndex.reserve(F->size()); 3478 std::vector<const MachineBasicBlock *> CurrentBlockOrder; 3479 CurrentBlockOrder.reserve(F->size()); 3480 size_t NumBlocks = 0; 3481 for (const MachineBasicBlock &MBB : *F) { 3482 BlockIndex[&MBB] = NumBlocks++; 3483 CurrentBlockOrder.push_back(&MBB); 3484 } 3485 3486 auto BlockSizes = std::vector<uint64_t>(F->size()); 3487 auto BlockCounts = std::vector<uint64_t>(F->size()); 3488 DenseMap<std::pair<uint64_t, uint64_t>, uint64_t> JumpCounts; 3489 for (MachineBasicBlock &MBB : *F) { 3490 // Getting the block frequency. 3491 BlockFrequency BlockFreq = MBFI->getBlockFreq(&MBB); 3492 BlockCounts[BlockIndex[&MBB]] = BlockFreq.getFrequency(); 3493 // Getting the block size: 3494 // - approximate the size of an instruction by 4 bytes, and 3495 // - ignore debug instructions. 3496 // Note: getting the exact size of each block is target-dependent and can be 3497 // done by extending the interface of MCCodeEmitter. Experimentally we do 3498 // not see a perf improvement with the exact block sizes. 3499 auto NonDbgInsts = 3500 instructionsWithoutDebug(MBB.instr_begin(), MBB.instr_end()); 3501 int NumInsts = std::distance(NonDbgInsts.begin(), NonDbgInsts.end()); 3502 BlockSizes[BlockIndex[&MBB]] = 4 * NumInsts; 3503 // Getting jump frequencies. 3504 for (MachineBasicBlock *Succ : MBB.successors()) { 3505 auto EP = MBPI->getEdgeProbability(&MBB, Succ); 3506 BlockFrequency EdgeFreq = BlockFreq * EP; 3507 auto Edge = std::make_pair(BlockIndex[&MBB], BlockIndex[Succ]); 3508 JumpCounts[Edge] = EdgeFreq.getFrequency(); 3509 } 3510 } 3511 3512 LLVM_DEBUG(dbgs() << "Applying ext-tsp layout for |V| = " << F->size() 3513 << " with profile = " << F->getFunction().hasProfileData() 3514 << " (" << F->getName().str() << ")" 3515 << "\n"); 3516 LLVM_DEBUG( 3517 dbgs() << format(" original layout score: %0.2f\n", 3518 calcExtTspScore(BlockSizes, BlockCounts, JumpCounts))); 3519 3520 // Run the layout algorithm. 3521 auto NewOrder = applyExtTspLayout(BlockSizes, BlockCounts, JumpCounts); 3522 std::vector<const MachineBasicBlock *> NewBlockOrder; 3523 NewBlockOrder.reserve(F->size()); 3524 for (uint64_t Node : NewOrder) { 3525 NewBlockOrder.push_back(CurrentBlockOrder[Node]); 3526 } 3527 LLVM_DEBUG(dbgs() << format(" optimized layout score: %0.2f\n", 3528 calcExtTspScore(NewOrder, BlockSizes, BlockCounts, 3529 JumpCounts))); 3530 3531 // Assign new block order. 3532 assignBlockOrder(NewBlockOrder); 3533 } 3534 3535 void MachineBlockPlacement::assignBlockOrder( 3536 const std::vector<const MachineBasicBlock *> &NewBlockOrder) { 3537 assert(F->size() == NewBlockOrder.size() && "Incorrect size of block order"); 3538 F->RenumberBlocks(); 3539 3540 bool HasChanges = false; 3541 for (size_t I = 0; I < NewBlockOrder.size(); I++) { 3542 if (NewBlockOrder[I] != F->getBlockNumbered(I)) { 3543 HasChanges = true; 3544 break; 3545 } 3546 } 3547 // Stop early if the new block order is identical to the existing one. 3548 if (!HasChanges) 3549 return; 3550 3551 SmallVector<MachineBasicBlock *, 4> PrevFallThroughs(F->getNumBlockIDs()); 3552 for (auto &MBB : *F) { 3553 PrevFallThroughs[MBB.getNumber()] = MBB.getFallThrough(); 3554 } 3555 3556 // Sort basic blocks in the function according to the computed order. 3557 DenseMap<const MachineBasicBlock *, size_t> NewIndex; 3558 for (const MachineBasicBlock *MBB : NewBlockOrder) { 3559 NewIndex[MBB] = NewIndex.size(); 3560 } 3561 F->sort([&](MachineBasicBlock &L, MachineBasicBlock &R) { 3562 return NewIndex[&L] < NewIndex[&R]; 3563 }); 3564 3565 // Update basic block branches by inserting explicit fallthrough branches 3566 // when required and re-optimize branches when possible. 3567 const TargetInstrInfo *TII = F->getSubtarget().getInstrInfo(); 3568 SmallVector<MachineOperand, 4> Cond; 3569 for (auto &MBB : *F) { 3570 MachineFunction::iterator NextMBB = std::next(MBB.getIterator()); 3571 MachineFunction::iterator EndIt = MBB.getParent()->end(); 3572 auto *FTMBB = PrevFallThroughs[MBB.getNumber()]; 3573 // If this block had a fallthrough before we need an explicit unconditional 3574 // branch to that block if the fallthrough block is not adjacent to the 3575 // block in the new order. 3576 if (FTMBB && (NextMBB == EndIt || &*NextMBB != FTMBB)) { 3577 TII->insertUnconditionalBranch(MBB, FTMBB, MBB.findBranchDebugLoc()); 3578 } 3579 3580 // It might be possible to optimize branches by flipping the condition. 3581 Cond.clear(); 3582 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; 3583 if (TII->analyzeBranch(MBB, TBB, FBB, Cond)) 3584 continue; 3585 MBB.updateTerminator(FTMBB); 3586 } 3587 3588 #ifndef NDEBUG 3589 // Make sure we correctly constructed all branches. 3590 F->verify(this, "After optimized block reordering"); 3591 #endif 3592 } 3593 3594 void MachineBlockPlacement::createCFGChainExtTsp() { 3595 BlockToChain.clear(); 3596 ComputedEdges.clear(); 3597 ChainAllocator.DestroyAll(); 3598 3599 MachineBasicBlock *HeadBB = &F->front(); 3600 BlockChain *FunctionChain = 3601 new (ChainAllocator.Allocate()) BlockChain(BlockToChain, HeadBB); 3602 3603 for (MachineBasicBlock &MBB : *F) { 3604 if (HeadBB == &MBB) 3605 continue; // Ignore head of the chain 3606 FunctionChain->merge(&MBB, nullptr); 3607 } 3608 } 3609 3610 namespace { 3611 3612 /// A pass to compute block placement statistics. 3613 /// 3614 /// A separate pass to compute interesting statistics for evaluating block 3615 /// placement. This is separate from the actual placement pass so that they can 3616 /// be computed in the absence of any placement transformations or when using 3617 /// alternative placement strategies. 3618 class MachineBlockPlacementStats : public MachineFunctionPass { 3619 /// A handle to the branch probability pass. 3620 const MachineBranchProbabilityInfo *MBPI; 3621 3622 /// A handle to the function-wide block frequency pass. 3623 const MachineBlockFrequencyInfo *MBFI; 3624 3625 public: 3626 static char ID; // Pass identification, replacement for typeid 3627 3628 MachineBlockPlacementStats() : MachineFunctionPass(ID) { 3629 initializeMachineBlockPlacementStatsPass(*PassRegistry::getPassRegistry()); 3630 } 3631 3632 bool runOnMachineFunction(MachineFunction &F) override; 3633 3634 void getAnalysisUsage(AnalysisUsage &AU) const override { 3635 AU.addRequired<MachineBranchProbabilityInfo>(); 3636 AU.addRequired<MachineBlockFrequencyInfo>(); 3637 AU.setPreservesAll(); 3638 MachineFunctionPass::getAnalysisUsage(AU); 3639 } 3640 }; 3641 3642 } // end anonymous namespace 3643 3644 char MachineBlockPlacementStats::ID = 0; 3645 3646 char &llvm::MachineBlockPlacementStatsID = MachineBlockPlacementStats::ID; 3647 3648 INITIALIZE_PASS_BEGIN(MachineBlockPlacementStats, "block-placement-stats", 3649 "Basic Block Placement Stats", false, false) 3650 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo) 3651 INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo) 3652 INITIALIZE_PASS_END(MachineBlockPlacementStats, "block-placement-stats", 3653 "Basic Block Placement Stats", false, false) 3654 3655 bool MachineBlockPlacementStats::runOnMachineFunction(MachineFunction &F) { 3656 // Check for single-block functions and skip them. 3657 if (std::next(F.begin()) == F.end()) 3658 return false; 3659 3660 MBPI = &getAnalysis<MachineBranchProbabilityInfo>(); 3661 MBFI = &getAnalysis<MachineBlockFrequencyInfo>(); 3662 3663 for (MachineBasicBlock &MBB : F) { 3664 BlockFrequency BlockFreq = MBFI->getBlockFreq(&MBB); 3665 Statistic &NumBranches = 3666 (MBB.succ_size() > 1) ? NumCondBranches : NumUncondBranches; 3667 Statistic &BranchTakenFreq = 3668 (MBB.succ_size() > 1) ? CondBranchTakenFreq : UncondBranchTakenFreq; 3669 for (MachineBasicBlock *Succ : MBB.successors()) { 3670 // Skip if this successor is a fallthrough. 3671 if (MBB.isLayoutSuccessor(Succ)) 3672 continue; 3673 3674 BlockFrequency EdgeFreq = 3675 BlockFreq * MBPI->getEdgeProbability(&MBB, Succ); 3676 ++NumBranches; 3677 BranchTakenFreq += EdgeFreq.getFrequency(); 3678 } 3679 } 3680 3681 return false; 3682 } 3683