1 //===- bolt/Passes/ExtTSPReorderAlgorithm.cpp - Order basic blocks --------===// 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 // ExtTSP - layout of basic blocks with i-cache optimization. 10 // 11 // The algorithm is a greedy heuristic that works with chains (ordered lists) 12 // of basic blocks. Initially all chains are isolated basic blocks. On every 13 // iteration, we pick a pair of chains whose merging yields the biggest increase 14 // in the ExtTSP value, which models how i-cache "friendly" a specific chain is. 15 // A pair of chains giving the maximum gain is merged into a new chain. The 16 // procedure stops when there is only one chain left, or when merging does not 17 // increase ExtTSP. In the latter case, the remaining chains are sorted by 18 // density in decreasing order. 19 // 20 // An important aspect is the way two chains are merged. Unlike earlier 21 // algorithms (e.g., OptimizeCacheReorderAlgorithm or Pettis-Hansen), two 22 // chains, X and Y, are first split into three, X1, X2, and Y. Then we 23 // consider all possible ways of gluing the three chains (e.g., X1YX2, X1X2Y, 24 // X2X1Y, X2YX1, YX1X2, YX2X1) and choose the one producing the largest score. 25 // This improves the quality of the final result (the search space is larger) 26 // while keeping the implementation sufficiently fast. 27 // 28 // Reference: 29 // * A. Newell and S. Pupyrev, Improved Basic Block Reordering, 30 // IEEE Transactions on Computers, 2020 31 // https://arxiv.org/abs/1809.04676 32 // 33 //===----------------------------------------------------------------------===// 34 35 #include "bolt/Core/BinaryBasicBlock.h" 36 #include "bolt/Core/BinaryFunction.h" 37 #include "bolt/Passes/ReorderAlgorithm.h" 38 #include "llvm/Support/CommandLine.h" 39 40 using namespace llvm; 41 using namespace bolt; 42 43 namespace opts { 44 45 extern cl::OptionCategory BoltOptCategory; 46 extern cl::opt<bool> NoThreads; 47 48 cl::opt<unsigned> 49 ChainSplitThreshold("chain-split-threshold", 50 cl::desc("The maximum size of a chain to apply splitting"), 51 cl::init(128), 52 cl::ReallyHidden, 53 cl::ZeroOrMore, 54 cl::cat(BoltOptCategory)); 55 56 cl::opt<double> 57 ForwardWeight("forward-weight", 58 cl::desc("The weight of forward jumps for ExtTSP value"), 59 cl::init(0.1), 60 cl::ReallyHidden, 61 cl::ZeroOrMore, 62 cl::cat(BoltOptCategory)); 63 64 cl::opt<double> 65 BackwardWeight("backward-weight", 66 cl::desc("The weight of backward jumps for ExtTSP value"), 67 cl::init(0.1), 68 cl::ReallyHidden, 69 cl::ZeroOrMore, 70 cl::cat(BoltOptCategory)); 71 72 cl::opt<unsigned> 73 ForwardDistance("forward-distance", 74 cl::desc("The maximum distance (in bytes) of forward jumps for ExtTSP value"), 75 cl::init(1024), 76 cl::ReallyHidden, 77 cl::ZeroOrMore, 78 cl::cat(BoltOptCategory)); 79 80 cl::opt<unsigned> 81 BackwardDistance("backward-distance", 82 cl::desc("The maximum distance (in bytes) of backward jumps for ExtTSP value"), 83 cl::init(640), 84 cl::ReallyHidden, 85 cl::ZeroOrMore, 86 cl::cat(BoltOptCategory)); 87 88 } 89 90 namespace llvm { 91 namespace bolt { 92 93 // Epsilon for comparison of doubles 94 constexpr double EPS = 1e-8; 95 96 class Block; 97 class Chain; 98 class Edge; 99 100 // Calculate Ext-TSP value, which quantifies the expected number of i-cache 101 // misses for a given ordering of basic blocks 102 double extTSPScore(uint64_t SrcAddr, uint64_t SrcSize, uint64_t DstAddr, 103 uint64_t Count) { 104 assert(Count != BinaryBasicBlock::COUNT_NO_PROFILE); 105 106 // Fallthrough 107 if (SrcAddr + SrcSize == DstAddr) { 108 // Assume that FallthroughWeight = 1.0 after normalization 109 return static_cast<double>(Count); 110 } 111 // Forward 112 if (SrcAddr + SrcSize < DstAddr) { 113 const uint64_t Dist = DstAddr - (SrcAddr + SrcSize); 114 if (Dist <= opts::ForwardDistance) { 115 double Prob = 1.0 - static_cast<double>(Dist) / opts::ForwardDistance; 116 return opts::ForwardWeight * Prob * Count; 117 } 118 return 0; 119 } 120 // Backward 121 const uint64_t Dist = SrcAddr + SrcSize - DstAddr; 122 if (Dist <= opts::BackwardDistance) { 123 double Prob = 1.0 - static_cast<double>(Dist) / opts::BackwardDistance; 124 return opts::BackwardWeight * Prob * Count; 125 } 126 return 0; 127 } 128 129 using BlockPair = std::pair<Block *, Block *>; 130 using JumpList = std::vector<std::pair<BlockPair, uint64_t>>; 131 using BlockIter = std::vector<Block *>::const_iterator; 132 133 enum MergeTypeTy { 134 X_Y = 0, 135 X1_Y_X2 = 1, 136 Y_X2_X1 = 2, 137 X2_X1_Y = 3, 138 }; 139 140 class MergeGainTy { 141 public: 142 explicit MergeGainTy() {} 143 explicit MergeGainTy(double Score, size_t MergeOffset, MergeTypeTy MergeType) 144 : Score(Score), MergeOffset(MergeOffset), MergeType(MergeType) {} 145 146 double score() const { return Score; } 147 148 size_t mergeOffset() const { return MergeOffset; } 149 150 MergeTypeTy mergeType() const { return MergeType; } 151 152 // returns 'true' iff Other is preferred over this 153 bool operator<(const MergeGainTy &Other) const { 154 return (Other.Score > EPS && Other.Score > Score + EPS); 155 } 156 157 private: 158 double Score{-1.0}; 159 size_t MergeOffset{0}; 160 MergeTypeTy MergeType{MergeTypeTy::X_Y}; 161 }; 162 163 // A node in CFG corresponding to a BinaryBasicBlock. 164 // The class wraps several mutable fields utilized in the ExtTSP algorithm 165 class Block { 166 public: 167 Block(const Block &) = delete; 168 Block(Block &&) = default; 169 Block &operator=(const Block &) = delete; 170 Block &operator=(Block &&) = default; 171 172 // Corresponding basic block 173 BinaryBasicBlock *BB{nullptr}; 174 // Current chain of the basic block 175 Chain *CurChain{nullptr}; 176 // (Estimated) size of the block in the binary 177 uint64_t Size{0}; 178 // Execution count of the block in the binary 179 uint64_t ExecutionCount{0}; 180 // An original index of the node in CFG 181 size_t Index{0}; 182 // The index of the block in the current chain 183 size_t CurIndex{0}; 184 // An offset of the block in the current chain 185 mutable uint64_t EstimatedAddr{0}; 186 // Fallthrough successor of the node in CFG 187 Block *FallthroughSucc{nullptr}; 188 // Fallthrough predecessor of the node in CFG 189 Block *FallthroughPred{nullptr}; 190 // Outgoing jumps from the block 191 std::vector<std::pair<Block *, uint64_t>> OutJumps; 192 // Incoming jumps to the block 193 std::vector<std::pair<Block *, uint64_t>> InJumps; 194 // Total execution count of incoming jumps 195 uint64_t InWeight{0}; 196 // Total execution count of outgoing jumps 197 uint64_t OutWeight{0}; 198 199 public: 200 explicit Block(BinaryBasicBlock *BB_, uint64_t Size_) 201 : BB(BB_), Size(Size_), ExecutionCount(BB_->getKnownExecutionCount()), 202 Index(BB->getLayoutIndex()) {} 203 204 bool adjacent(const Block *Other) const { 205 return hasOutJump(Other) || hasInJump(Other); 206 } 207 208 bool hasOutJump(const Block *Other) const { 209 for (std::pair<Block *, uint64_t> Jump : OutJumps) { 210 if (Jump.first == Other) 211 return true; 212 } 213 return false; 214 } 215 216 bool hasInJump(const Block *Other) const { 217 for (std::pair<Block *, uint64_t> Jump : InJumps) { 218 if (Jump.first == Other) 219 return true; 220 } 221 return false; 222 } 223 }; 224 225 // A chain (ordered sequence) of CFG nodes (basic blocks) 226 class Chain { 227 public: 228 Chain(const Chain &) = delete; 229 Chain(Chain &&) = default; 230 Chain &operator=(const Chain &) = delete; 231 Chain &operator=(Chain &&) = default; 232 233 explicit Chain(size_t Id, Block *Block) 234 : Id(Id), IsEntry(Block->Index == 0), 235 ExecutionCount(Block->ExecutionCount), Size(Block->Size), Score(0), 236 Blocks(1, Block) {} 237 238 size_t id() const { return Id; } 239 240 uint64_t size() const { return Size; } 241 242 double density() const { return static_cast<double>(ExecutionCount) / Size; } 243 244 uint64_t executionCount() const { return ExecutionCount; } 245 246 bool isEntryPoint() const { return IsEntry; } 247 248 double score() const { return Score; } 249 250 void setScore(double NewScore) { Score = NewScore; } 251 252 const std::vector<Block *> &blocks() const { return Blocks; } 253 254 const std::vector<std::pair<Chain *, Edge *>> &edges() const { return Edges; } 255 256 Edge *getEdge(Chain *Other) const { 257 for (std::pair<Chain *, Edge *> It : Edges) { 258 if (It.first == Other) 259 return It.second; 260 } 261 return nullptr; 262 } 263 264 void removeEdge(Chain *Other) { 265 auto It = Edges.begin(); 266 while (It != Edges.end()) { 267 if (It->first == Other) { 268 Edges.erase(It); 269 return; 270 } 271 It++; 272 } 273 } 274 275 void addEdge(Chain *Other, Edge *Edge) { Edges.emplace_back(Other, Edge); } 276 277 void merge(Chain *Other, const std::vector<Block *> &MergedBlocks) { 278 Blocks = MergedBlocks; 279 IsEntry |= Other->IsEntry; 280 ExecutionCount += Other->ExecutionCount; 281 Size += Other->Size; 282 // Update block's chains 283 for (size_t Idx = 0; Idx < Blocks.size(); Idx++) { 284 Blocks[Idx]->CurChain = this; 285 Blocks[Idx]->CurIndex = Idx; 286 } 287 } 288 289 void mergeEdges(Chain *Other); 290 291 void clear() { 292 Blocks.clear(); 293 Edges.clear(); 294 } 295 296 private: 297 size_t Id; 298 bool IsEntry; 299 uint64_t ExecutionCount; 300 uint64_t Size; 301 // Cached ext-tsp score for the chain 302 double Score; 303 // Blocks of the chain 304 std::vector<Block *> Blocks; 305 // Adjacent chains and corresponding edges (lists of jumps) 306 std::vector<std::pair<Chain *, Edge *>> Edges; 307 }; 308 309 // An edge in CFG reprsenting jumps between chains of BinaryBasicBlocks. 310 // When blocks are merged into chains, the edges are combined too so that 311 // there is always at most one edge between a pair of chains 312 class Edge { 313 public: 314 Edge(const Edge &) = delete; 315 Edge(Edge &&) = default; 316 Edge &operator=(const Edge &) = delete; 317 Edge &operator=(Edge &&) = default; 318 319 explicit Edge(Block *SrcBlock, Block *DstBlock, uint64_t EC) 320 : SrcChain(SrcBlock->CurChain), DstChain(DstBlock->CurChain), 321 Jumps(1, std::make_pair(std::make_pair(SrcBlock, DstBlock), EC)) {} 322 323 const JumpList &jumps() const { return Jumps; } 324 325 void changeEndpoint(Chain *From, Chain *To) { 326 if (From == SrcChain) 327 SrcChain = To; 328 if (From == DstChain) 329 DstChain = To; 330 } 331 332 void appendJump(Block *SrcBlock, Block *DstBlock, uint64_t EC) { 333 Jumps.emplace_back(std::make_pair(SrcBlock, DstBlock), EC); 334 } 335 336 void moveJumps(Edge *Other) { 337 Jumps.insert(Jumps.end(), Other->Jumps.begin(), Other->Jumps.end()); 338 Other->Jumps.clear(); 339 } 340 341 bool hasCachedMergeGain(Chain *Src, Chain *Dst) const { 342 return Src == SrcChain ? CacheValidForward : CacheValidBackward; 343 } 344 345 MergeGainTy getCachedMergeGain(Chain *Src, Chain *Dst) const { 346 return Src == SrcChain ? CachedGainForward : CachedGainBackward; 347 } 348 349 void setCachedMergeGain(Chain *Src, Chain *Dst, MergeGainTy MergeGain) { 350 if (Src == SrcChain) { 351 CachedGainForward = MergeGain; 352 CacheValidForward = true; 353 } else { 354 CachedGainBackward = MergeGain; 355 CacheValidBackward = true; 356 } 357 } 358 359 void invalidateCache() { 360 CacheValidForward = false; 361 CacheValidBackward = false; 362 } 363 364 private: 365 Chain *SrcChain{nullptr}; 366 Chain *DstChain{nullptr}; 367 // Original jumps in the binary with correspinding execution counts 368 JumpList Jumps; 369 // Cached ext-tsp value for merging the pair of chains 370 // Since the gain of merging (Src, Dst) and (Dst, Src) might be different, 371 // we store both values here 372 MergeGainTy CachedGainForward; 373 MergeGainTy CachedGainBackward; 374 // Whether the cached value must be recomputed 375 bool CacheValidForward{false}; 376 bool CacheValidBackward{false}; 377 }; 378 379 void Chain::mergeEdges(Chain *Other) { 380 assert(this != Other && "cannot merge a chain with itself"); 381 382 // Update edges adjacent to chain Other 383 for (auto EdgeIt : Other->Edges) { 384 Chain *const DstChain = EdgeIt.first; 385 Edge *const DstEdge = EdgeIt.second; 386 Chain *const TargetChain = DstChain == Other ? this : DstChain; 387 388 // Find the corresponding edge in the current chain 389 Edge *curEdge = getEdge(TargetChain); 390 if (curEdge == nullptr) { 391 DstEdge->changeEndpoint(Other, this); 392 this->addEdge(TargetChain, DstEdge); 393 if (DstChain != this && DstChain != Other) { 394 DstChain->addEdge(this, DstEdge); 395 } 396 } else { 397 curEdge->moveJumps(DstEdge); 398 } 399 // Cleanup leftover edge 400 if (DstChain != Other) { 401 DstChain->removeEdge(Other); 402 } 403 } 404 } 405 406 // A wrapper around three chains of basic blocks; it is used to avoid extra 407 // instantiation of the vectors. 408 class MergedChain { 409 public: 410 MergedChain(BlockIter Begin1, BlockIter End1, BlockIter Begin2 = BlockIter(), 411 BlockIter End2 = BlockIter(), BlockIter Begin3 = BlockIter(), 412 BlockIter End3 = BlockIter()) 413 : Begin1(Begin1), End1(End1), Begin2(Begin2), End2(End2), Begin3(Begin3), 414 End3(End3) {} 415 416 template <typename F> void forEach(const F &Func) const { 417 for (auto It = Begin1; It != End1; It++) 418 Func(*It); 419 for (auto It = Begin2; It != End2; It++) 420 Func(*It); 421 for (auto It = Begin3; It != End3; It++) 422 Func(*It); 423 } 424 425 std::vector<Block *> getBlocks() const { 426 std::vector<Block *> Result; 427 Result.reserve(std::distance(Begin1, End1) + std::distance(Begin2, End2) + 428 std::distance(Begin3, End3)); 429 Result.insert(Result.end(), Begin1, End1); 430 Result.insert(Result.end(), Begin2, End2); 431 Result.insert(Result.end(), Begin3, End3); 432 return Result; 433 } 434 435 const Block *getFirstBlock() const { return *Begin1; } 436 437 private: 438 BlockIter Begin1; 439 BlockIter End1; 440 BlockIter Begin2; 441 BlockIter End2; 442 BlockIter Begin3; 443 BlockIter End3; 444 }; 445 446 /// Deterministically compare pairs of chains 447 bool compareChainPairs(const Chain *A1, const Chain *B1, const Chain *A2, 448 const Chain *B2) { 449 const uint64_t Samples1 = A1->executionCount() + B1->executionCount(); 450 const uint64_t Samples2 = A2->executionCount() + B2->executionCount(); 451 if (Samples1 != Samples2) 452 return Samples1 < Samples2; 453 454 // Making the order deterministic 455 if (A1 != A2) 456 return A1->id() < A2->id(); 457 return B1->id() < B2->id(); 458 } 459 class ExtTSP { 460 public: 461 ExtTSP(const BinaryFunction &BF) : BF(BF) { initialize(); } 462 463 /// Run the algorithm and return an ordering of basic block 464 void run(BinaryFunction::BasicBlockOrderType &Order) { 465 // Pass 1: Merge blocks with their fallthrough successors 466 mergeFallthroughs(); 467 468 // Pass 2: Merge pairs of chains while improving the ExtTSP objective 469 mergeChainPairs(); 470 471 // Pass 3: Merge cold blocks to reduce code size 472 mergeColdChains(); 473 474 // Collect blocks from all chains 475 concatChains(Order); 476 } 477 478 private: 479 /// Initialize algorithm's data structures 480 void initialize() { 481 // Create a separate MCCodeEmitter to allow lock-free execution 482 BinaryContext::IndependentCodeEmitter Emitter; 483 if (!opts::NoThreads) { 484 Emitter = BF.getBinaryContext().createIndependentMCCodeEmitter(); 485 } 486 487 // Initialize CFG nodes 488 AllBlocks.reserve(BF.layout_size()); 489 size_t LayoutIndex = 0; 490 for (BinaryBasicBlock *BB : BF.layout()) { 491 BB->setLayoutIndex(LayoutIndex++); 492 uint64_t Size = 493 std::max<uint64_t>(BB->estimateSize(Emitter.MCE.get()), 1); 494 AllBlocks.emplace_back(BB, Size); 495 } 496 497 // Initialize edges for the blocks and compute their total in/out weights 498 size_t NumEdges = 0; 499 for (Block &Block : AllBlocks) { 500 auto BI = Block.BB->branch_info_begin(); 501 for (BinaryBasicBlock *SuccBB : Block.BB->successors()) { 502 assert(BI->Count != BinaryBasicBlock::COUNT_NO_PROFILE && 503 "missing profile for a jump"); 504 if (SuccBB != Block.BB && BI->Count > 0) { 505 class Block &SuccBlock = AllBlocks[SuccBB->getLayoutIndex()]; 506 uint64_t Count = BI->Count; 507 SuccBlock.InWeight += Count; 508 SuccBlock.InJumps.emplace_back(&Block, Count); 509 Block.OutWeight += Count; 510 Block.OutJumps.emplace_back(&SuccBlock, Count); 511 NumEdges++; 512 } 513 ++BI; 514 } 515 } 516 517 // Initialize execution count for every basic block, which is the 518 // maximum over the sums of all in and out edge weights. 519 // Also execution count of the entry point is set to at least 1 520 for (Block &Block : AllBlocks) { 521 size_t Index = Block.Index; 522 Block.ExecutionCount = std::max(Block.ExecutionCount, Block.InWeight); 523 Block.ExecutionCount = std::max(Block.ExecutionCount, Block.OutWeight); 524 if (Index == 0 && Block.ExecutionCount == 0) 525 Block.ExecutionCount = 1; 526 } 527 528 // Initialize chains 529 AllChains.reserve(BF.layout_size()); 530 HotChains.reserve(BF.layout_size()); 531 for (Block &Block : AllBlocks) { 532 AllChains.emplace_back(Block.Index, &Block); 533 Block.CurChain = &AllChains.back(); 534 if (Block.ExecutionCount > 0) { 535 HotChains.push_back(&AllChains.back()); 536 } 537 } 538 539 // Initialize edges 540 AllEdges.reserve(NumEdges); 541 for (Block &Block : AllBlocks) { 542 for (std::pair<class Block *, uint64_t> &Jump : Block.OutJumps) { 543 class Block *const SuccBlock = Jump.first; 544 Edge *CurEdge = Block.CurChain->getEdge(SuccBlock->CurChain); 545 // this edge is already present in the graph 546 if (CurEdge != nullptr) { 547 assert(SuccBlock->CurChain->getEdge(Block.CurChain) != nullptr); 548 CurEdge->appendJump(&Block, SuccBlock, Jump.second); 549 continue; 550 } 551 // this is a new edge 552 AllEdges.emplace_back(&Block, SuccBlock, Jump.second); 553 Block.CurChain->addEdge(SuccBlock->CurChain, &AllEdges.back()); 554 SuccBlock->CurChain->addEdge(Block.CurChain, &AllEdges.back()); 555 } 556 } 557 assert(AllEdges.size() <= NumEdges && "Incorrect number of created edges"); 558 } 559 560 /// For a pair of blocks, A and B, block B is the fallthrough successor of A, 561 /// if (i) all jumps (based on profile) from A goes to B and (ii) all jumps 562 /// to B are from A. Such blocks should be adjacent in an optimal ordering; 563 /// the method finds and merges such pairs of blocks 564 void mergeFallthroughs() { 565 // Find fallthroughs based on edge weights 566 for (Block &Block : AllBlocks) { 567 if (Block.BB->succ_size() == 1 && 568 Block.BB->getSuccessor()->pred_size() == 1 && 569 Block.BB->getSuccessor()->getLayoutIndex() != 0) { 570 size_t SuccIndex = Block.BB->getSuccessor()->getLayoutIndex(); 571 Block.FallthroughSucc = &AllBlocks[SuccIndex]; 572 AllBlocks[SuccIndex].FallthroughPred = &Block; 573 continue; 574 } 575 576 if (Block.OutWeight == 0) 577 continue; 578 for (std::pair<class Block *, uint64_t> &Edge : Block.OutJumps) { 579 class Block *const SuccBlock = Edge.first; 580 // Successor cannot be the first BB, which is pinned 581 if (Block.OutWeight == Edge.second && 582 SuccBlock->InWeight == Edge.second && SuccBlock->Index != 0) { 583 Block.FallthroughSucc = SuccBlock; 584 SuccBlock->FallthroughPred = &Block; 585 break; 586 } 587 } 588 } 589 590 // There might be 'cycles' in the fallthrough dependencies (since profile 591 // data isn't 100% accurate). 592 // Break the cycles by choosing the block with smallest index as the tail 593 for (Block &Block : AllBlocks) { 594 if (Block.FallthroughSucc == nullptr || Block.FallthroughPred == nullptr) 595 continue; 596 597 class Block *SuccBlock = Block.FallthroughSucc; 598 while (SuccBlock != nullptr && SuccBlock != &Block) { 599 SuccBlock = SuccBlock->FallthroughSucc; 600 } 601 if (SuccBlock == nullptr) 602 continue; 603 // break the cycle 604 AllBlocks[Block.FallthroughPred->Index].FallthroughSucc = nullptr; 605 Block.FallthroughPred = nullptr; 606 } 607 608 // Merge blocks with their fallthrough successors 609 for (Block &Block : AllBlocks) { 610 if (Block.FallthroughPred == nullptr && 611 Block.FallthroughSucc != nullptr) { 612 class Block *CurBlock = &Block; 613 while (CurBlock->FallthroughSucc != nullptr) { 614 class Block *const NextBlock = CurBlock->FallthroughSucc; 615 mergeChains(Block.CurChain, NextBlock->CurChain, 0, MergeTypeTy::X_Y); 616 CurBlock = NextBlock; 617 } 618 } 619 } 620 } 621 622 /// Merge pairs of chains while improving the ExtTSP objective 623 void mergeChainPairs() { 624 while (HotChains.size() > 1) { 625 Chain *BestChainPred = nullptr; 626 Chain *BestChainSucc = nullptr; 627 auto BestGain = MergeGainTy(); 628 // Iterate over all pairs of chains 629 for (Chain *ChainPred : HotChains) { 630 // Get candidates for merging with the current chain 631 for (auto EdgeIter : ChainPred->edges()) { 632 Chain *ChainSucc = EdgeIter.first; 633 Edge *ChainEdge = EdgeIter.second; 634 // Ignore loop edges 635 if (ChainPred == ChainSucc) 636 continue; 637 638 // Compute the gain of merging the two chains 639 MergeGainTy CurGain = mergeGain(ChainPred, ChainSucc, ChainEdge); 640 if (CurGain.score() <= EPS) 641 continue; 642 643 if (BestGain < CurGain || 644 (std::abs(CurGain.score() - BestGain.score()) < EPS && 645 compareChainPairs(ChainPred, ChainSucc, BestChainPred, 646 BestChainSucc))) { 647 BestGain = CurGain; 648 BestChainPred = ChainPred; 649 BestChainSucc = ChainSucc; 650 } 651 } 652 } 653 654 // Stop merging when there is no improvement 655 if (BestGain.score() <= EPS) 656 break; 657 658 // Merge the best pair of chains 659 mergeChains(BestChainPred, BestChainSucc, BestGain.mergeOffset(), 660 BestGain.mergeType()); 661 } 662 } 663 664 /// Merge cold blocks to reduce code size 665 void mergeColdChains() { 666 for (BinaryBasicBlock *SrcBB : BF.layout()) { 667 // Iterating in reverse order to make sure original fallthrough jumps are 668 // merged first 669 for (auto Itr = SrcBB->succ_rbegin(); Itr != SrcBB->succ_rend(); ++Itr) { 670 BinaryBasicBlock *DstBB = *Itr; 671 size_t SrcIndex = SrcBB->getLayoutIndex(); 672 size_t DstIndex = DstBB->getLayoutIndex(); 673 Chain *SrcChain = AllBlocks[SrcIndex].CurChain; 674 Chain *DstChain = AllBlocks[DstIndex].CurChain; 675 if (SrcChain != DstChain && !DstChain->isEntryPoint() && 676 SrcChain->blocks().back()->Index == SrcIndex && 677 DstChain->blocks().front()->Index == DstIndex) { 678 mergeChains(SrcChain, DstChain, 0, MergeTypeTy::X_Y); 679 } 680 } 681 } 682 } 683 684 /// Compute ExtTSP score for a given order of basic blocks 685 double score(const MergedChain &MergedBlocks, const JumpList &Jumps) const { 686 if (Jumps.empty()) 687 return 0.0; 688 uint64_t CurAddr = 0; 689 MergedBlocks.forEach( 690 [&](const Block *BB) { 691 BB->EstimatedAddr = CurAddr; 692 CurAddr += BB->Size; 693 } 694 ); 695 696 double Score = 0; 697 for (const std::pair<std::pair<Block *, Block *>, uint64_t> &Jump : Jumps) { 698 const Block *SrcBlock = Jump.first.first; 699 const Block *DstBlock = Jump.first.second; 700 Score += extTSPScore(SrcBlock->EstimatedAddr, SrcBlock->Size, 701 DstBlock->EstimatedAddr, Jump.second); 702 } 703 return Score; 704 } 705 706 /// Compute the gain of merging two chains 707 /// 708 /// The function considers all possible ways of merging two chains and 709 /// computes the one having the largest increase in ExtTSP objective. The 710 /// result is a pair with the first element being the gain and the second 711 /// element being the corresponding merging type. 712 MergeGainTy mergeGain(Chain *ChainPred, Chain *ChainSucc, Edge *Edge) const { 713 if (Edge->hasCachedMergeGain(ChainPred, ChainSucc)) { 714 return Edge->getCachedMergeGain(ChainPred, ChainSucc); 715 } 716 717 // Precompute jumps between ChainPred and ChainSucc 718 JumpList Jumps = Edge->jumps(); 719 class Edge *EdgePP = ChainPred->getEdge(ChainPred); 720 if (EdgePP != nullptr) 721 Jumps.insert(Jumps.end(), EdgePP->jumps().begin(), EdgePP->jumps().end()); 722 assert(Jumps.size() > 0 && "trying to merge chains w/o jumps"); 723 724 MergeGainTy Gain = MergeGainTy(); 725 // Try to concatenate two chains w/o splitting 726 Gain = computeMergeGain(Gain, ChainPred, ChainSucc, Jumps, 0, 727 MergeTypeTy::X_Y); 728 729 // Try to break ChainPred in various ways and concatenate with ChainSucc 730 if (ChainPred->blocks().size() <= opts::ChainSplitThreshold) { 731 for (size_t Offset = 1; Offset < ChainPred->blocks().size(); Offset++) { 732 Block *BB1 = ChainPred->blocks()[Offset - 1]; 733 Block *BB2 = ChainPred->blocks()[Offset]; 734 // Does the splitting break FT successors? 735 if (BB1->FallthroughSucc != nullptr) { 736 (void)BB2; 737 assert(BB1->FallthroughSucc == BB2 && "Fallthrough not preserved"); 738 continue; 739 } 740 741 Gain = computeMergeGain(Gain, ChainPred, ChainSucc, Jumps, Offset, 742 MergeTypeTy::X1_Y_X2); 743 Gain = computeMergeGain(Gain, ChainPred, ChainSucc, Jumps, Offset, 744 MergeTypeTy::Y_X2_X1); 745 Gain = computeMergeGain(Gain, ChainPred, ChainSucc, Jumps, Offset, 746 MergeTypeTy::X2_X1_Y); 747 } 748 } 749 750 Edge->setCachedMergeGain(ChainPred, ChainSucc, Gain); 751 return Gain; 752 } 753 754 /// Merge two chains and update the best Gain 755 MergeGainTy computeMergeGain(const MergeGainTy &CurGain, 756 const Chain *ChainPred, const Chain *ChainSucc, 757 const JumpList &Jumps, size_t MergeOffset, 758 MergeTypeTy MergeType) const { 759 MergedChain MergedBlocks = mergeBlocks( 760 ChainPred->blocks(), ChainSucc->blocks(), MergeOffset, MergeType); 761 762 // Do not allow a merge that does not preserve the original entry block 763 if ((ChainPred->isEntryPoint() || ChainSucc->isEntryPoint()) && 764 MergedBlocks.getFirstBlock()->Index != 0) 765 return CurGain; 766 767 // The gain for the new chain 768 const double NewScore = score(MergedBlocks, Jumps) - ChainPred->score(); 769 auto NewGain = MergeGainTy(NewScore, MergeOffset, MergeType); 770 return CurGain < NewGain ? NewGain : CurGain; 771 } 772 773 /// Merge two chains of blocks respecting a given merge 'type' and 'offset' 774 /// 775 /// If MergeType == 0, then the result is a concatentation of two chains. 776 /// Otherwise, the first chain is cut into two sub-chains at the offset, 777 /// and merged using all possible ways of concatenating three chains. 778 MergedChain mergeBlocks(const std::vector<Block *> &X, 779 const std::vector<Block *> &Y, size_t MergeOffset, 780 MergeTypeTy MergeType) const { 781 // Split the first chain, X, into X1 and X2 782 BlockIter BeginX1 = X.begin(); 783 BlockIter EndX1 = X.begin() + MergeOffset; 784 BlockIter BeginX2 = X.begin() + MergeOffset; 785 BlockIter EndX2 = X.end(); 786 BlockIter BeginY = Y.begin(); 787 BlockIter EndY = Y.end(); 788 789 // Construct a new chain from the three existing ones 790 switch (MergeType) { 791 case MergeTypeTy::X_Y: 792 return MergedChain(BeginX1, EndX2, BeginY, EndY); 793 case MergeTypeTy::X1_Y_X2: 794 return MergedChain(BeginX1, EndX1, BeginY, EndY, BeginX2, EndX2); 795 case MergeTypeTy::Y_X2_X1: 796 return MergedChain(BeginY, EndY, BeginX2, EndX2, BeginX1, EndX1); 797 case MergeTypeTy::X2_X1_Y: 798 return MergedChain(BeginX2, EndX2, BeginX1, EndX1, BeginY, EndY); 799 } 800 801 llvm_unreachable("unexpected merge type"); 802 } 803 804 /// Merge chain From into chain Into, update the list of active chains, 805 /// adjacency information, and the corresponding cached values 806 void mergeChains(Chain *Into, Chain *From, size_t MergeOffset, 807 MergeTypeTy MergeType) { 808 assert(Into != From && "a chain cannot be merged with itself"); 809 810 // Merge the blocks 811 MergedChain MergedBlocks = 812 mergeBlocks(Into->blocks(), From->blocks(), MergeOffset, MergeType); 813 Into->merge(From, MergedBlocks.getBlocks()); 814 Into->mergeEdges(From); 815 From->clear(); 816 817 // Update cached ext-tsp score for the new chain 818 Edge *SelfEdge = Into->getEdge(Into); 819 if (SelfEdge != nullptr) { 820 MergedBlocks = MergedChain(Into->blocks().begin(), Into->blocks().end()); 821 Into->setScore(score(MergedBlocks, SelfEdge->jumps())); 822 } 823 824 // Remove chain From from the list of active chains 825 auto Iter = std::remove(HotChains.begin(), HotChains.end(), From); 826 HotChains.erase(Iter, HotChains.end()); 827 828 // Invalidate caches 829 for (std::pair<Chain *, Edge *> EdgeIter : Into->edges()) { 830 EdgeIter.second->invalidateCache(); 831 } 832 } 833 834 /// Concatenate all chains into a final order 835 void concatChains(BinaryFunction::BasicBlockOrderType &Order) { 836 // Collect chains 837 std::vector<Chain *> SortedChains; 838 for (Chain &Chain : AllChains) { 839 if (Chain.blocks().size() > 0) { 840 SortedChains.push_back(&Chain); 841 } 842 } 843 844 // Sorting chains by density in decreasing order 845 std::stable_sort( 846 SortedChains.begin(), SortedChains.end(), 847 [](const Chain *C1, const Chain *C2) { 848 // Original entry point to the front 849 if (C1->isEntryPoint() != C2->isEntryPoint()) { 850 if (C1->isEntryPoint()) 851 return true; 852 if (C2->isEntryPoint()) 853 return false; 854 } 855 856 const double D1 = C1->density(); 857 const double D2 = C2->density(); 858 if (D1 != D2) 859 return D1 > D2; 860 861 // Making the order deterministic 862 return C1->id() < C2->id(); 863 } 864 ); 865 866 // Collect the basic blocks in the order specified by their chains 867 Order.reserve(BF.layout_size()); 868 for (Chain *Chain : SortedChains) { 869 for (Block *Block : Chain->blocks()) { 870 Order.push_back(Block->BB); 871 } 872 } 873 } 874 875 private: 876 // The binary function 877 const BinaryFunction &BF; 878 879 // All CFG nodes (basic blocks) 880 std::vector<Block> AllBlocks; 881 882 // All chains of blocks 883 std::vector<Chain> AllChains; 884 885 // Active chains. The vector gets updated at runtime when chains are merged 886 std::vector<Chain *> HotChains; 887 888 // All edges between chains 889 std::vector<Edge> AllEdges; 890 }; 891 892 void ExtTSPReorderAlgorithm::reorderBasicBlocks(const BinaryFunction &BF, 893 BasicBlockOrder &Order) const { 894 if (BF.layout_empty()) 895 return; 896 897 // Do not change layout of functions w/o profile information 898 if (!BF.hasValidProfile() || BF.layout_size() <= 2) { 899 for (BinaryBasicBlock *BB : BF.layout()) { 900 Order.push_back(BB); 901 } 902 return; 903 } 904 905 // Apply the algorithm 906 ExtTSP(BF).run(Order); 907 908 // Verify correctness 909 assert(Order[0]->isEntryPoint() && "Original entry point is not preserved"); 910 assert(Order.size() == BF.layout_size() && "Wrong size of reordered layout"); 911 } 912 913 } // namespace bolt 914 } // namespace llvm 915