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