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