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