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