1 //===---- MachineOutliner.cpp - Outline instructions -----------*- C++ -*-===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 /// 10 /// \file 11 /// Replaces repeated sequences of instructions with function calls. 12 /// 13 /// This works by placing every instruction from every basic block in a 14 /// suffix tree, and repeatedly querying that tree for repeated sequences of 15 /// instructions. If a sequence of instructions appears often, then it ought 16 /// to be beneficial to pull out into a function. 17 /// 18 /// This was originally presented at the 2016 LLVM Developers' Meeting in the 19 /// talk "Reducing Code Size Using Outlining". For a high-level overview of 20 /// how this pass works, the talk is available on YouTube at 21 /// 22 /// https://www.youtube.com/watch?v=yorld-WSOeU 23 /// 24 /// The slides for the talk are available at 25 /// 26 /// http://www.llvm.org/devmtg/2016-11/Slides/Paquette-Outliner.pdf 27 /// 28 /// The talk provides an overview of how the outliner finds candidates and 29 /// ultimately outlines them. It describes how the main data structure for this 30 /// pass, the suffix tree, is queried and purged for candidates. It also gives 31 /// a simplified suffix tree construction algorithm for suffix trees based off 32 /// of the algorithm actually used here, Ukkonen's algorithm. 33 /// 34 /// For the original RFC for this pass, please see 35 /// 36 /// http://lists.llvm.org/pipermail/llvm-dev/2016-August/104170.html 37 /// 38 /// For more information on the suffix tree data structure, please see 39 /// https://www.cs.helsinki.fi/u/ukkonen/SuffixT1withFigs.pdf 40 /// 41 //===----------------------------------------------------------------------===// 42 #include "llvm/ADT/DenseMap.h" 43 #include "llvm/ADT/Statistic.h" 44 #include "llvm/ADT/Twine.h" 45 #include "llvm/CodeGen/MachineFrameInfo.h" 46 #include "llvm/CodeGen/MachineFunction.h" 47 #include "llvm/CodeGen/MachineInstrBuilder.h" 48 #include "llvm/CodeGen/MachineModuleInfo.h" 49 #include "llvm/CodeGen/Passes.h" 50 #include "llvm/IR/IRBuilder.h" 51 #include "llvm/Support/Allocator.h" 52 #include "llvm/Support/Debug.h" 53 #include "llvm/Support/raw_ostream.h" 54 #include "llvm/Target/TargetInstrInfo.h" 55 #include "llvm/Target/TargetMachine.h" 56 #include "llvm/Target/TargetRegisterInfo.h" 57 #include "llvm/Target/TargetSubtargetInfo.h" 58 #include <functional> 59 #include <map> 60 #include <sstream> 61 #include <tuple> 62 #include <vector> 63 64 #define DEBUG_TYPE "machine-outliner" 65 66 using namespace llvm; 67 68 STATISTIC(NumOutlined, "Number of candidates outlined"); 69 STATISTIC(FunctionsCreated, "Number of functions created"); 70 71 namespace { 72 73 /// Represents an undefined index in the suffix tree. 74 const size_t EmptyIdx = -1; 75 76 /// A node in a suffix tree which represents a substring or suffix. 77 /// 78 /// Each node has either no children or at least two children, with the root 79 /// being a exception in the empty tree. 80 /// 81 /// Children are represented as a map between unsigned integers and nodes. If 82 /// a node N has a child M on unsigned integer k, then the mapping represented 83 /// by N is a proper prefix of the mapping represented by M. Note that this, 84 /// although similar to a trie is somewhat different: each node stores a full 85 /// substring of the full mapping rather than a single character state. 86 /// 87 /// Each internal node contains a pointer to the internal node representing 88 /// the same string, but with the first character chopped off. This is stored 89 /// in \p Link. Each leaf node stores the start index of its respective 90 /// suffix in \p SuffixIdx. 91 struct SuffixTreeNode { 92 93 /// The children of this node. 94 /// 95 /// A child existing on an unsigned integer implies that from the mapping 96 /// represented by the current node, there is a way to reach another 97 /// mapping by tacking that character on the end of the current string. 98 DenseMap<unsigned, SuffixTreeNode *> Children; 99 100 /// A flag set to false if the node has been pruned from the tree. 101 bool IsInTree = true; 102 103 /// The start index of this node's substring in the main string. 104 size_t StartIdx = EmptyIdx; 105 106 /// The end index of this node's substring in the main string. 107 /// 108 /// Every leaf node must have its \p EndIdx incremented at the end of every 109 /// step in the construction algorithm. To avoid having to update O(N) 110 /// nodes individually at the end of every step, the end index is stored 111 /// as a pointer. 112 size_t *EndIdx = nullptr; 113 114 /// For leaves, the start index of the suffix represented by this node. 115 /// 116 /// For all other nodes, this is ignored. 117 size_t SuffixIdx = EmptyIdx; 118 119 /// \brief For internal nodes, a pointer to the internal node representing 120 /// the same sequence with the first character chopped off. 121 /// 122 /// This has two major purposes in the suffix tree. The first is as a 123 /// shortcut in Ukkonen's construction algorithm. One of the things that 124 /// Ukkonen's algorithm does to achieve linear-time construction is 125 /// keep track of which node the next insert should be at. This makes each 126 /// insert O(1), and there are a total of O(N) inserts. The suffix link 127 /// helps with inserting children of internal nodes. 128 /// 129 /// Say we add a child to an internal node with associated mapping S. The 130 /// next insertion must be at the node representing S - its first character. 131 /// This is given by the way that we iteratively build the tree in Ukkonen's 132 /// algorithm. The main idea is to look at the suffixes of each prefix in the 133 /// string, starting with the longest suffix of the prefix, and ending with 134 /// the shortest. Therefore, if we keep pointers between such nodes, we can 135 /// move to the next insertion point in O(1) time. If we don't, then we'd 136 /// have to query from the root, which takes O(N) time. This would make the 137 /// construction algorithm O(N^2) rather than O(N). 138 /// 139 /// The suffix link is also used during the tree pruning process to let us 140 /// quickly throw out a bunch of potential overlaps. Say we have a sequence 141 /// S we want to outline. Then each of its suffixes contribute to at least 142 /// one overlapping case. Therefore, we can follow the suffix links 143 /// starting at the node associated with S to the root and "delete" those 144 /// nodes, save for the root. For each candidate, this removes 145 /// O(|candidate|) overlaps from the search space. We don't actually 146 /// completely invalidate these nodes though; doing that is far too 147 /// aggressive. Consider the following pathological string: 148 /// 149 /// 1 2 3 1 2 3 2 3 2 3 2 3 2 3 2 3 2 3 150 /// 151 /// If we, for the sake of example, outlined 1 2 3, then we would throw 152 /// out all instances of 2 3. This isn't desirable. To get around this, 153 /// when we visit a link node, we decrement its occurrence count by the 154 /// number of sequences we outlined in the current step. In the pathological 155 /// example, the 2 3 node would have an occurrence count of 8, while the 156 /// 1 2 3 node would have an occurrence count of 2. Thus, the 2 3 node 157 /// would survive to the next round allowing us to outline the extra 158 /// instances of 2 3. 159 SuffixTreeNode *Link = nullptr; 160 161 /// The parent of this node. Every node except for the root has a parent. 162 SuffixTreeNode *Parent = nullptr; 163 164 /// The number of times this node's string appears in the tree. 165 /// 166 /// This is equal to the number of leaf children of the string. It represents 167 /// the number of suffixes that the node's string is a prefix of. 168 size_t OccurrenceCount = 0; 169 170 /// Returns true if this node is a leaf. 171 bool isLeaf() const { return SuffixIdx != EmptyIdx; } 172 173 /// Returns true if this node is the root of its owning \p SuffixTree. 174 bool isRoot() const { return StartIdx == EmptyIdx; } 175 176 /// Return the number of elements in the substring associated with this node. 177 size_t size() const { 178 179 // Is it the root? If so, it's the empty string so return 0. 180 if (isRoot()) 181 return 0; 182 183 assert(*EndIdx != EmptyIdx && "EndIdx is undefined!"); 184 185 // Size = the number of elements in the string. 186 // For example, [0 1 2 3] has length 4, not 3. 3-0 = 3, so we have 3-0+1. 187 return *EndIdx - StartIdx + 1; 188 } 189 190 SuffixTreeNode(size_t StartIdx, size_t *EndIdx, SuffixTreeNode *Link, 191 SuffixTreeNode *Parent) 192 : StartIdx(StartIdx), EndIdx(EndIdx), Link(Link), Parent(Parent) {} 193 194 SuffixTreeNode() {} 195 }; 196 197 /// A data structure for fast substring queries. 198 /// 199 /// Suffix trees represent the suffixes of their input strings in their leaves. 200 /// A suffix tree is a type of compressed trie structure where each node 201 /// represents an entire substring rather than a single character. Each leaf 202 /// of the tree is a suffix. 203 /// 204 /// A suffix tree can be seen as a type of state machine where each state is a 205 /// substring of the full string. The tree is structured so that, for a string 206 /// of length N, there are exactly N leaves in the tree. This structure allows 207 /// us to quickly find repeated substrings of the input string. 208 /// 209 /// In this implementation, a "string" is a vector of unsigned integers. 210 /// These integers may result from hashing some data type. A suffix tree can 211 /// contain 1 or many strings, which can then be queried as one large string. 212 /// 213 /// The suffix tree is implemented using Ukkonen's algorithm for linear-time 214 /// suffix tree construction. Ukkonen's algorithm is explained in more detail 215 /// in the paper by Esko Ukkonen "On-line construction of suffix trees. The 216 /// paper is available at 217 /// 218 /// https://www.cs.helsinki.fi/u/ukkonen/SuffixT1withFigs.pdf 219 class SuffixTree { 220 private: 221 /// Each element is an integer representing an instruction in the module. 222 ArrayRef<unsigned> Str; 223 224 /// Maintains each node in the tree. 225 SpecificBumpPtrAllocator<SuffixTreeNode> NodeAllocator; 226 227 /// The root of the suffix tree. 228 /// 229 /// The root represents the empty string. It is maintained by the 230 /// \p NodeAllocator like every other node in the tree. 231 SuffixTreeNode *Root = nullptr; 232 233 /// Stores each leaf in the tree for better pruning. 234 std::vector<SuffixTreeNode *> LeafVector; 235 236 /// Maintains the end indices of the internal nodes in the tree. 237 /// 238 /// Each internal node is guaranteed to never have its end index change 239 /// during the construction algorithm; however, leaves must be updated at 240 /// every step. Therefore, we need to store leaf end indices by reference 241 /// to avoid updating O(N) leaves at every step of construction. Thus, 242 /// every internal node must be allocated its own end index. 243 BumpPtrAllocator InternalEndIdxAllocator; 244 245 /// The end index of each leaf in the tree. 246 size_t LeafEndIdx = -1; 247 248 /// \brief Helper struct which keeps track of the next insertion point in 249 /// Ukkonen's algorithm. 250 struct ActiveState { 251 /// The next node to insert at. 252 SuffixTreeNode *Node; 253 254 /// The index of the first character in the substring currently being added. 255 size_t Idx = EmptyIdx; 256 257 /// The length of the substring we have to add at the current step. 258 size_t Len = 0; 259 }; 260 261 /// \brief The point the next insertion will take place at in the 262 /// construction algorithm. 263 ActiveState Active; 264 265 /// Allocate a leaf node and add it to the tree. 266 /// 267 /// \param Parent The parent of this node. 268 /// \param StartIdx The start index of this node's associated string. 269 /// \param Edge The label on the edge leaving \p Parent to this node. 270 /// 271 /// \returns A pointer to the allocated leaf node. 272 SuffixTreeNode *insertLeaf(SuffixTreeNode &Parent, size_t StartIdx, 273 unsigned Edge) { 274 275 assert(StartIdx <= LeafEndIdx && "String can't start after it ends!"); 276 277 SuffixTreeNode *N = new (NodeAllocator.Allocate()) SuffixTreeNode(StartIdx, 278 &LeafEndIdx, 279 nullptr, 280 &Parent); 281 Parent.Children[Edge] = N; 282 283 return N; 284 } 285 286 /// Allocate an internal node and add it to the tree. 287 /// 288 /// \param Parent The parent of this node. Only null when allocating the root. 289 /// \param StartIdx The start index of this node's associated string. 290 /// \param EndIdx The end index of this node's associated string. 291 /// \param Edge The label on the edge leaving \p Parent to this node. 292 /// 293 /// \returns A pointer to the allocated internal node. 294 SuffixTreeNode *insertInternalNode(SuffixTreeNode *Parent, size_t StartIdx, 295 size_t EndIdx, unsigned Edge) { 296 297 assert(StartIdx <= EndIdx && "String can't start after it ends!"); 298 assert(!(!Parent && StartIdx != EmptyIdx) && 299 "Non-root internal nodes must have parents!"); 300 301 size_t *E = new (InternalEndIdxAllocator) size_t(EndIdx); 302 SuffixTreeNode *N = new (NodeAllocator.Allocate()) SuffixTreeNode(StartIdx, 303 E, 304 Root, 305 Parent); 306 if (Parent) 307 Parent->Children[Edge] = N; 308 309 return N; 310 } 311 312 /// \brief Set the suffix indices of the leaves to the start indices of their 313 /// respective suffixes. Also stores each leaf in \p LeafVector at its 314 /// respective suffix index. 315 /// 316 /// \param[in] CurrNode The node currently being visited. 317 /// \param CurrIdx The current index of the string being visited. 318 void setSuffixIndices(SuffixTreeNode &CurrNode, size_t CurrIdx) { 319 320 bool IsLeaf = CurrNode.Children.size() == 0 && !CurrNode.isRoot(); 321 322 // Traverse the tree depth-first. 323 for (auto &ChildPair : CurrNode.Children) { 324 assert(ChildPair.second && "Node had a null child!"); 325 setSuffixIndices(*ChildPair.second, 326 CurrIdx + ChildPair.second->size()); 327 } 328 329 // Is this node a leaf? 330 if (IsLeaf) { 331 // If yes, give it a suffix index and bump its parent's occurrence count. 332 CurrNode.SuffixIdx = Str.size() - CurrIdx; 333 assert(CurrNode.Parent && "CurrNode had no parent!"); 334 CurrNode.Parent->OccurrenceCount++; 335 336 // Store the leaf in the leaf vector for pruning later. 337 LeafVector[CurrNode.SuffixIdx] = &CurrNode; 338 } 339 } 340 341 /// \brief Construct the suffix tree for the prefix of the input ending at 342 /// \p EndIdx. 343 /// 344 /// Used to construct the full suffix tree iteratively. At the end of each 345 /// step, the constructed suffix tree is either a valid suffix tree, or a 346 /// suffix tree with implicit suffixes. At the end of the final step, the 347 /// suffix tree is a valid tree. 348 /// 349 /// \param EndIdx The end index of the current prefix in the main string. 350 /// \param SuffixesToAdd The number of suffixes that must be added 351 /// to complete the suffix tree at the current phase. 352 /// 353 /// \returns The number of suffixes that have not been added at the end of 354 /// this step. 355 unsigned extend(size_t EndIdx, size_t SuffixesToAdd) { 356 SuffixTreeNode *NeedsLink = nullptr; 357 358 while (SuffixesToAdd > 0) { 359 360 // Are we waiting to add anything other than just the last character? 361 if (Active.Len == 0) { 362 // If not, then say the active index is the end index. 363 Active.Idx = EndIdx; 364 } 365 366 assert(Active.Idx <= EndIdx && "Start index can't be after end index!"); 367 368 // The first character in the current substring we're looking at. 369 unsigned FirstChar = Str[Active.Idx]; 370 371 // Have we inserted anything starting with FirstChar at the current node? 372 if (Active.Node->Children.count(FirstChar) == 0) { 373 // If not, then we can just insert a leaf and move too the next step. 374 insertLeaf(*Active.Node, EndIdx, FirstChar); 375 376 // The active node is an internal node, and we visited it, so it must 377 // need a link if it doesn't have one. 378 if (NeedsLink) { 379 NeedsLink->Link = Active.Node; 380 NeedsLink = nullptr; 381 } 382 } else { 383 // There's a match with FirstChar, so look for the point in the tree to 384 // insert a new node. 385 SuffixTreeNode *NextNode = Active.Node->Children[FirstChar]; 386 387 size_t SubstringLen = NextNode->size(); 388 389 // Is the current suffix we're trying to insert longer than the size of 390 // the child we want to move to? 391 if (Active.Len >= SubstringLen) { 392 // If yes, then consume the characters we've seen and move to the next 393 // node. 394 Active.Idx += SubstringLen; 395 Active.Len -= SubstringLen; 396 Active.Node = NextNode; 397 continue; 398 } 399 400 // Otherwise, the suffix we're trying to insert must be contained in the 401 // next node we want to move to. 402 unsigned LastChar = Str[EndIdx]; 403 404 // Is the string we're trying to insert a substring of the next node? 405 if (Str[NextNode->StartIdx + Active.Len] == LastChar) { 406 // If yes, then we're done for this step. Remember our insertion point 407 // and move to the next end index. At this point, we have an implicit 408 // suffix tree. 409 if (NeedsLink && !Active.Node->isRoot()) { 410 NeedsLink->Link = Active.Node; 411 NeedsLink = nullptr; 412 } 413 414 Active.Len++; 415 break; 416 } 417 418 // The string we're trying to insert isn't a substring of the next node, 419 // but matches up to a point. Split the node. 420 // 421 // For example, say we ended our search at a node n and we're trying to 422 // insert ABD. Then we'll create a new node s for AB, reduce n to just 423 // representing C, and insert a new leaf node l to represent d. This 424 // allows us to ensure that if n was a leaf, it remains a leaf. 425 // 426 // | ABC ---split---> | AB 427 // n s 428 // C / \ D 429 // n l 430 431 // The node s from the diagram 432 SuffixTreeNode *SplitNode = 433 insertInternalNode(Active.Node, 434 NextNode->StartIdx, 435 NextNode->StartIdx + Active.Len - 1, 436 FirstChar); 437 438 // Insert the new node representing the new substring into the tree as 439 // a child of the split node. This is the node l from the diagram. 440 insertLeaf(*SplitNode, EndIdx, LastChar); 441 442 // Make the old node a child of the split node and update its start 443 // index. This is the node n from the diagram. 444 NextNode->StartIdx += Active.Len; 445 NextNode->Parent = SplitNode; 446 SplitNode->Children[Str[NextNode->StartIdx]] = NextNode; 447 448 // SplitNode is an internal node, update the suffix link. 449 if (NeedsLink) 450 NeedsLink->Link = SplitNode; 451 452 NeedsLink = SplitNode; 453 } 454 455 // We've added something new to the tree, so there's one less suffix to 456 // add. 457 SuffixesToAdd--; 458 459 if (Active.Node->isRoot()) { 460 if (Active.Len > 0) { 461 Active.Len--; 462 Active.Idx = EndIdx - SuffixesToAdd + 1; 463 } 464 } else { 465 // Start the next phase at the next smallest suffix. 466 Active.Node = Active.Node->Link; 467 } 468 } 469 470 return SuffixesToAdd; 471 } 472 473 /// \brief Return the start index and length of a string which maximizes a 474 /// benefit function by traversing the tree depth-first. 475 /// 476 /// Helper function for \p bestRepeatedSubstring. 477 /// 478 /// \param CurrNode The node currently being visited. 479 /// \param CurrLen Length of the current string. 480 /// \param[out] BestLen Length of the most beneficial substring. 481 /// \param[out] MaxBenefit Benefit of the most beneficial substring. 482 /// \param[out] BestStartIdx Start index of the most beneficial substring. 483 /// \param BenefitFn The function the query should return a maximum string 484 /// for. 485 void findBest(SuffixTreeNode &CurrNode, size_t CurrLen, size_t &BestLen, 486 size_t &MaxBenefit, size_t &BestStartIdx, 487 const std::function<unsigned(SuffixTreeNode &, size_t CurrLen)> 488 &BenefitFn) { 489 490 if (!CurrNode.IsInTree) 491 return; 492 493 // Can we traverse further down the tree? 494 if (!CurrNode.isLeaf()) { 495 // If yes, continue the traversal. 496 for (auto &ChildPair : CurrNode.Children) { 497 if (ChildPair.second && ChildPair.second->IsInTree) 498 findBest(*ChildPair.second, CurrLen + ChildPair.second->size(), 499 BestLen, MaxBenefit, BestStartIdx, BenefitFn); 500 } 501 } else { 502 // We hit a leaf. 503 size_t StringLen = CurrLen - CurrNode.size(); 504 unsigned Benefit = BenefitFn(CurrNode, StringLen); 505 506 // Did we do better than in the last step? 507 if (Benefit <= MaxBenefit) 508 return; 509 510 // We did better, so update the best string. 511 MaxBenefit = Benefit; 512 BestStartIdx = CurrNode.SuffixIdx; 513 BestLen = StringLen; 514 } 515 } 516 517 public: 518 519 unsigned operator[](const size_t i) const { 520 return Str[i]; 521 } 522 523 /// \brief Return a substring of the tree with maximum benefit if such a 524 /// substring exists. 525 /// 526 /// Clears the input vector and fills it with a maximum substring or empty. 527 /// 528 /// \param[in,out] Best The most beneficial substring in the tree. Empty 529 /// if it does not exist. 530 /// \param BenefitFn The function the query should return a maximum string 531 /// for. 532 void bestRepeatedSubstring(std::vector<unsigned> &Best, 533 const std::function<unsigned(SuffixTreeNode &, size_t CurrLen)> 534 &BenefitFn) { 535 Best.clear(); 536 size_t Length = 0; // Becomes the length of the best substring. 537 size_t Benefit = 0; // Becomes the benefit of the best substring. 538 size_t StartIdx = 0; // Becomes the start index of the best substring. 539 findBest(*Root, 0, Length, Benefit, StartIdx, BenefitFn); 540 541 for (size_t Idx = 0; Idx < Length; Idx++) 542 Best.push_back(Str[Idx + StartIdx]); 543 } 544 545 /// Perform a depth-first search for \p QueryString on the suffix tree. 546 /// 547 /// \param QueryString The string to search for. 548 /// \param CurrIdx The current index in \p QueryString that is being matched 549 /// against. 550 /// \param CurrNode The suffix tree node being searched in. 551 /// 552 /// \returns A \p SuffixTreeNode that \p QueryString appears in if such a 553 /// node exists, and \p nullptr otherwise. 554 SuffixTreeNode *findString(const std::vector<unsigned> &QueryString, 555 size_t &CurrIdx, SuffixTreeNode *CurrNode) { 556 557 // The search ended at a nonexistent or pruned node. Quit. 558 if (!CurrNode || !CurrNode->IsInTree) 559 return nullptr; 560 561 unsigned Edge = QueryString[CurrIdx]; // The edge we want to move on. 562 SuffixTreeNode *NextNode = CurrNode->Children[Edge]; // Next node in query. 563 564 if (CurrNode->isRoot()) { 565 // If we're at the root we have to check if there's a child, and move to 566 // that child. Don't consume the character since \p Root represents the 567 // empty string. 568 if (NextNode && NextNode->IsInTree) 569 return findString(QueryString, CurrIdx, NextNode); 570 return nullptr; 571 } 572 573 size_t StrIdx = CurrNode->StartIdx; 574 size_t MaxIdx = QueryString.size(); 575 bool ContinueSearching = false; 576 577 // Match as far as possible into the string. If there's a mismatch, quit. 578 for (; CurrIdx < MaxIdx; CurrIdx++, StrIdx++) { 579 Edge = QueryString[CurrIdx]; 580 581 // We matched perfectly, but still have a remainder to search. 582 if (StrIdx > *(CurrNode->EndIdx)) { 583 ContinueSearching = true; 584 break; 585 } 586 587 if (Edge != Str[StrIdx]) 588 return nullptr; 589 } 590 591 NextNode = CurrNode->Children[Edge]; 592 593 // Move to the node which matches what we're looking for and continue 594 // searching. 595 if (ContinueSearching) 596 return findString(QueryString, CurrIdx, NextNode); 597 598 // We matched perfectly so we're done. 599 return CurrNode; 600 } 601 602 /// \brief Remove a node from a tree and all nodes representing proper 603 /// suffixes of that node's string. 604 /// 605 /// This is used in the outlining algorithm to reduce the number of 606 /// overlapping candidates 607 /// 608 /// \param N The suffix tree node to start pruning from. 609 /// \param Len The length of the string to be pruned. 610 /// 611 /// \returns True if this candidate didn't overlap with a previously chosen 612 /// candidate. 613 bool prune(SuffixTreeNode *N, size_t Len) { 614 615 bool NoOverlap = true; 616 std::vector<unsigned> IndicesToPrune; 617 618 // Look at each of N's children. 619 for (auto &ChildPair : N->Children) { 620 SuffixTreeNode *M = ChildPair.second; 621 622 // Is this a leaf child? 623 if (M && M->IsInTree && M->isLeaf()) { 624 // Save each leaf child's suffix indices and remove them from the tree. 625 IndicesToPrune.push_back(M->SuffixIdx); 626 M->IsInTree = false; 627 } 628 } 629 630 // Remove each suffix we have to prune from the tree. Each of these will be 631 // I + some offset for I in IndicesToPrune and some offset < Len. 632 unsigned Offset = 1; 633 for (unsigned CurrentSuffix = 1; CurrentSuffix < Len; CurrentSuffix++) { 634 for (unsigned I : IndicesToPrune) { 635 636 unsigned PruneIdx = I + Offset; 637 638 // Is this index actually in the string? 639 if (PruneIdx < LeafVector.size()) { 640 // If yes, we have to try and prune it. 641 // Was the current leaf already pruned by another candidate? 642 if (LeafVector[PruneIdx]->IsInTree) { 643 // If not, prune it. 644 LeafVector[PruneIdx]->IsInTree = false; 645 } else { 646 // If yes, signify that we've found an overlap, but keep pruning. 647 NoOverlap = false; 648 } 649 650 // Update the parent of the current leaf's occurrence count. 651 SuffixTreeNode *Parent = LeafVector[PruneIdx]->Parent; 652 653 // Is the parent still in the tree? 654 if (Parent->OccurrenceCount > 0) { 655 Parent->OccurrenceCount--; 656 Parent->IsInTree = (Parent->OccurrenceCount > 1); 657 } 658 } 659 } 660 661 // Move to the next character in the string. 662 Offset++; 663 } 664 665 // We know we can never outline anything which starts one index back from 666 // the indices we want to outline. This is because our minimum outlining 667 // length is always 2. 668 for (unsigned I : IndicesToPrune) { 669 if (I > 0) { 670 671 unsigned PruneIdx = I-1; 672 SuffixTreeNode *Parent = LeafVector[PruneIdx]->Parent; 673 674 // Was the leaf one index back from I already pruned? 675 if (LeafVector[PruneIdx]->IsInTree) { 676 // If not, prune it. 677 LeafVector[PruneIdx]->IsInTree = false; 678 } else { 679 // If yes, signify that we've found an overlap, but keep pruning. 680 NoOverlap = false; 681 } 682 683 // Update the parent of the current leaf's occurrence count. 684 if (Parent->OccurrenceCount > 0) { 685 Parent->OccurrenceCount--; 686 Parent->IsInTree = (Parent->OccurrenceCount > 1); 687 } 688 } 689 } 690 691 // Finally, remove N from the tree and set its occurrence count to 0. 692 N->IsInTree = false; 693 N->OccurrenceCount = 0; 694 695 return NoOverlap; 696 } 697 698 /// \brief Find each occurrence of of a string in \p QueryString and prune 699 /// their nodes. 700 /// 701 /// \param QueryString The string to search for. 702 /// \param[out] Occurrences The start indices of each occurrence. 703 /// 704 /// \returns Whether or not the occurrence overlaps with a previous candidate. 705 bool findOccurrencesAndPrune(const std::vector<unsigned> &QueryString, 706 std::vector<size_t> &Occurrences) { 707 size_t Dummy = 0; 708 SuffixTreeNode *N = findString(QueryString, Dummy, Root); 709 710 if (!N || !N->IsInTree) 711 return false; 712 713 // If this is an internal node, occurrences are the number of leaf children 714 // of the node. 715 for (auto &ChildPair : N->Children) { 716 SuffixTreeNode *M = ChildPair.second; 717 718 // Is it a leaf? If so, we have an occurrence. 719 if (M && M->IsInTree && M->isLeaf()) 720 Occurrences.push_back(M->SuffixIdx); 721 } 722 723 // If we're in a leaf, then this node is the only occurrence. 724 if (N->isLeaf()) 725 Occurrences.push_back(N->SuffixIdx); 726 727 return prune(N, QueryString.size()); 728 } 729 730 /// Construct a suffix tree from a sequence of unsigned integers. 731 /// 732 /// \param Str The string to construct the suffix tree for. 733 SuffixTree(const std::vector<unsigned> &Str) : Str(Str) { 734 Root = insertInternalNode(nullptr, EmptyIdx, EmptyIdx, 0); 735 Root->IsInTree = true; 736 Active.Node = Root; 737 LeafVector = std::vector<SuffixTreeNode*>(Str.size()); 738 739 // Keep track of the number of suffixes we have to add of the current 740 // prefix. 741 size_t SuffixesToAdd = 0; 742 Active.Node = Root; 743 744 // Construct the suffix tree iteratively on each prefix of the string. 745 // PfxEndIdx is the end index of the current prefix. 746 // End is one past the last element in the string. 747 for (size_t PfxEndIdx = 0, End = Str.size(); PfxEndIdx < End; PfxEndIdx++) { 748 SuffixesToAdd++; 749 LeafEndIdx = PfxEndIdx; // Extend each of the leaves. 750 SuffixesToAdd = extend(PfxEndIdx, SuffixesToAdd); 751 } 752 753 // Set the suffix indices of each leaf. 754 assert(Root && "Root node can't be nullptr!"); 755 setSuffixIndices(*Root, 0); 756 } 757 }; 758 759 /// \brief An individual sequence of instructions to be replaced with a call to 760 /// an outlined function. 761 struct Candidate { 762 763 /// Set to false if the candidate overlapped with another candidate. 764 bool InCandidateList = true; 765 766 /// The start index of this \p Candidate. 767 size_t StartIdx; 768 769 /// The number of instructions in this \p Candidate. 770 size_t Len; 771 772 /// The index of this \p Candidate's \p OutlinedFunction in the list of 773 /// \p OutlinedFunctions. 774 size_t FunctionIdx; 775 776 Candidate(size_t StartIdx, size_t Len, size_t FunctionIdx) 777 : StartIdx(StartIdx), Len(Len), FunctionIdx(FunctionIdx) {} 778 779 Candidate() {} 780 781 /// \brief Used to ensure that \p Candidates are outlined in an order that 782 /// preserves the start and end indices of other \p Candidates. 783 bool operator<(const Candidate &RHS) const { return StartIdx > RHS.StartIdx; } 784 }; 785 786 /// \brief The information necessary to create an outlined function for some 787 /// class of candidate. 788 struct OutlinedFunction { 789 790 /// The actual outlined function created. 791 /// This is initialized after we go through and create the actual function. 792 MachineFunction *MF = nullptr; 793 794 /// A number assigned to this function which appears at the end of its name. 795 size_t Name; 796 797 /// The number of times that this function has appeared. 798 size_t OccurrenceCount = 0; 799 800 /// \brief The sequence of integers corresponding to the instructions in this 801 /// function. 802 std::vector<unsigned> Sequence; 803 804 /// The number of instructions this function would save. 805 unsigned Benefit = 0; 806 807 bool IsTailCall = false; 808 809 OutlinedFunction(size_t Name, size_t OccurrenceCount, 810 const std::vector<unsigned> &Sequence, 811 unsigned Benefit, bool IsTailCall) 812 : Name(Name), OccurrenceCount(OccurrenceCount), Sequence(Sequence), 813 Benefit(Benefit), IsTailCall(IsTailCall) 814 {} 815 }; 816 817 /// \brief Maps \p MachineInstrs to unsigned integers and stores the mappings. 818 struct InstructionMapper { 819 820 /// \brief The next available integer to assign to a \p MachineInstr that 821 /// cannot be outlined. 822 /// 823 /// Set to -3 for compatability with \p DenseMapInfo<unsigned>. 824 unsigned IllegalInstrNumber = -3; 825 826 /// \brief The next available integer to assign to a \p MachineInstr that can 827 /// be outlined. 828 unsigned LegalInstrNumber = 0; 829 830 /// Correspondence from \p MachineInstrs to unsigned integers. 831 DenseMap<MachineInstr *, unsigned, MachineInstrExpressionTrait> 832 InstructionIntegerMap; 833 834 /// Corresponcence from unsigned integers to \p MachineInstrs. 835 /// Inverse of \p InstructionIntegerMap. 836 DenseMap<unsigned, MachineInstr *> IntegerInstructionMap; 837 838 /// The vector of unsigned integers that the module is mapped to. 839 std::vector<unsigned> UnsignedVec; 840 841 /// \brief Stores the location of the instruction associated with the integer 842 /// at index i in \p UnsignedVec for each index i. 843 std::vector<MachineBasicBlock::iterator> InstrList; 844 845 /// \brief Maps \p *It to a legal integer. 846 /// 847 /// Updates \p InstrList, \p UnsignedVec, \p InstructionIntegerMap, 848 /// \p IntegerInstructionMap, and \p LegalInstrNumber. 849 /// 850 /// \returns The integer that \p *It was mapped to. 851 unsigned mapToLegalUnsigned(MachineBasicBlock::iterator &It) { 852 853 // Get the integer for this instruction or give it the current 854 // LegalInstrNumber. 855 InstrList.push_back(It); 856 MachineInstr &MI = *It; 857 bool WasInserted; 858 DenseMap<MachineInstr *, unsigned, MachineInstrExpressionTrait>::iterator 859 ResultIt; 860 std::tie(ResultIt, WasInserted) = 861 InstructionIntegerMap.insert(std::make_pair(&MI, LegalInstrNumber)); 862 unsigned MINumber = ResultIt->second; 863 864 // There was an insertion. 865 if (WasInserted) { 866 LegalInstrNumber++; 867 IntegerInstructionMap.insert(std::make_pair(MINumber, &MI)); 868 } 869 870 UnsignedVec.push_back(MINumber); 871 872 // Make sure we don't overflow or use any integers reserved by the DenseMap. 873 if (LegalInstrNumber >= IllegalInstrNumber) 874 report_fatal_error("Instruction mapping overflow!"); 875 876 assert(LegalInstrNumber != DenseMapInfo<unsigned>::getEmptyKey() 877 && "Tried to assign DenseMap tombstone or empty key to instruction."); 878 assert(LegalInstrNumber != DenseMapInfo<unsigned>::getTombstoneKey() 879 && "Tried to assign DenseMap tombstone or empty key to instruction."); 880 881 return MINumber; 882 } 883 884 /// Maps \p *It to an illegal integer. 885 /// 886 /// Updates \p InstrList, \p UnsignedVec, and \p IllegalInstrNumber. 887 /// 888 /// \returns The integer that \p *It was mapped to. 889 unsigned mapToIllegalUnsigned(MachineBasicBlock::iterator &It) { 890 unsigned MINumber = IllegalInstrNumber; 891 892 InstrList.push_back(It); 893 UnsignedVec.push_back(IllegalInstrNumber); 894 IllegalInstrNumber--; 895 896 assert(LegalInstrNumber < IllegalInstrNumber && 897 "Instruction mapping overflow!"); 898 899 assert(IllegalInstrNumber != 900 DenseMapInfo<unsigned>::getEmptyKey() && 901 "IllegalInstrNumber cannot be DenseMap tombstone or empty key!"); 902 903 assert(IllegalInstrNumber != 904 DenseMapInfo<unsigned>::getTombstoneKey() && 905 "IllegalInstrNumber cannot be DenseMap tombstone or empty key!"); 906 907 return MINumber; 908 } 909 910 /// \brief Transforms a \p MachineBasicBlock into a \p vector of \p unsigneds 911 /// and appends it to \p UnsignedVec and \p InstrList. 912 /// 913 /// Two instructions are assigned the same integer if they are identical. 914 /// If an instruction is deemed unsafe to outline, then it will be assigned an 915 /// unique integer. The resulting mapping is placed into a suffix tree and 916 /// queried for candidates. 917 /// 918 /// \param MBB The \p MachineBasicBlock to be translated into integers. 919 /// \param TRI \p TargetRegisterInfo for the module. 920 /// \param TII \p TargetInstrInfo for the module. 921 void convertToUnsignedVec(MachineBasicBlock &MBB, 922 const TargetRegisterInfo &TRI, 923 const TargetInstrInfo &TII) { 924 for (MachineBasicBlock::iterator It = MBB.begin(), Et = MBB.end(); It != Et; 925 It++) { 926 927 // Keep track of where this instruction is in the module. 928 switch(TII.getOutliningType(*It)) { 929 case TargetInstrInfo::MachineOutlinerInstrType::Illegal: 930 mapToIllegalUnsigned(It); 931 break; 932 933 case TargetInstrInfo::MachineOutlinerInstrType::Legal: 934 mapToLegalUnsigned(It); 935 break; 936 937 case TargetInstrInfo::MachineOutlinerInstrType::Invisible: 938 break; 939 } 940 } 941 942 // After we're done every insertion, uniquely terminate this part of the 943 // "string". This makes sure we won't match across basic block or function 944 // boundaries since the "end" is encoded uniquely and thus appears in no 945 // repeated substring. 946 InstrList.push_back(MBB.end()); 947 UnsignedVec.push_back(IllegalInstrNumber); 948 IllegalInstrNumber--; 949 } 950 951 InstructionMapper() { 952 // Make sure that the implementation of DenseMapInfo<unsigned> hasn't 953 // changed. 954 assert(DenseMapInfo<unsigned>::getEmptyKey() == (unsigned)-1 && 955 "DenseMapInfo<unsigned>'s empty key isn't -1!"); 956 assert(DenseMapInfo<unsigned>::getTombstoneKey() == (unsigned)-2 && 957 "DenseMapInfo<unsigned>'s tombstone key isn't -2!"); 958 } 959 }; 960 961 /// \brief An interprocedural pass which finds repeated sequences of 962 /// instructions and replaces them with calls to functions. 963 /// 964 /// Each instruction is mapped to an unsigned integer and placed in a string. 965 /// The resulting mapping is then placed in a \p SuffixTree. The \p SuffixTree 966 /// is then repeatedly queried for repeated sequences of instructions. Each 967 /// non-overlapping repeated sequence is then placed in its own 968 /// \p MachineFunction and each instance is then replaced with a call to that 969 /// function. 970 struct MachineOutliner : public ModulePass { 971 972 static char ID; 973 974 StringRef getPassName() const override { return "Machine Outliner"; } 975 976 void getAnalysisUsage(AnalysisUsage &AU) const override { 977 AU.addRequired<MachineModuleInfo>(); 978 AU.addPreserved<MachineModuleInfo>(); 979 AU.setPreservesAll(); 980 ModulePass::getAnalysisUsage(AU); 981 } 982 983 MachineOutliner() : ModulePass(ID) { 984 initializeMachineOutlinerPass(*PassRegistry::getPassRegistry()); 985 } 986 987 /// \brief Replace the sequences of instructions represented by the 988 /// \p Candidates in \p CandidateList with calls to \p MachineFunctions 989 /// described in \p FunctionList. 990 /// 991 /// \param M The module we are outlining from. 992 /// \param CandidateList A list of candidates to be outlined. 993 /// \param FunctionList A list of functions to be inserted into the module. 994 /// \param Mapper Contains the instruction mappings for the module. 995 bool outline(Module &M, const ArrayRef<Candidate> &CandidateList, 996 std::vector<OutlinedFunction> &FunctionList, 997 InstructionMapper &Mapper); 998 999 /// Creates a function for \p OF and inserts it into the module. 1000 MachineFunction *createOutlinedFunction(Module &M, const OutlinedFunction &OF, 1001 InstructionMapper &Mapper); 1002 1003 /// Find potential outlining candidates and store them in \p CandidateList. 1004 /// 1005 /// For each type of potential candidate, also build an \p OutlinedFunction 1006 /// struct containing the information to build the function for that 1007 /// candidate. 1008 /// 1009 /// \param[out] CandidateList Filled with outlining candidates for the module. 1010 /// \param[out] FunctionList Filled with functions corresponding to each type 1011 /// of \p Candidate. 1012 /// \param ST The suffix tree for the module. 1013 /// \param TII TargetInstrInfo for the module. 1014 /// 1015 /// \returns The length of the longest candidate found. 0 if there are none. 1016 unsigned buildCandidateList(std::vector<Candidate> &CandidateList, 1017 std::vector<OutlinedFunction> &FunctionList, 1018 SuffixTree &ST, 1019 InstructionMapper &Mapper, 1020 const TargetInstrInfo &TII); 1021 1022 /// \brief Remove any overlapping candidates that weren't handled by the 1023 /// suffix tree's pruning method. 1024 /// 1025 /// Pruning from the suffix tree doesn't necessarily remove all overlaps. 1026 /// If a short candidate is chosen for outlining, then a longer candidate 1027 /// which has that short candidate as a suffix is chosen, the tree's pruning 1028 /// method will not find it. Thus, we need to prune before outlining as well. 1029 /// 1030 /// \param[in,out] CandidateList A list of outlining candidates. 1031 /// \param[in,out] FunctionList A list of functions to be outlined. 1032 /// \param MaxCandidateLen The length of the longest candidate. 1033 /// \param TII TargetInstrInfo for the module. 1034 void pruneOverlaps(std::vector<Candidate> &CandidateList, 1035 std::vector<OutlinedFunction> &FunctionList, 1036 unsigned MaxCandidateLen, 1037 const TargetInstrInfo &TII); 1038 1039 /// Construct a suffix tree on the instructions in \p M and outline repeated 1040 /// strings from that tree. 1041 bool runOnModule(Module &M) override; 1042 }; 1043 1044 } // Anonymous namespace. 1045 1046 char MachineOutliner::ID = 0; 1047 1048 namespace llvm { 1049 ModulePass *createMachineOutlinerPass() { return new MachineOutliner(); } 1050 } 1051 1052 INITIALIZE_PASS(MachineOutliner, "machine-outliner", 1053 "Machine Function Outliner", false, false) 1054 1055 void MachineOutliner::pruneOverlaps(std::vector<Candidate> &CandidateList, 1056 std::vector<OutlinedFunction> &FunctionList, 1057 unsigned MaxCandidateLen, 1058 const TargetInstrInfo &TII) { 1059 1060 // Check for overlaps in the range. This is O(n^2) worst case, but we can 1061 // alleviate that somewhat by bounding our search space using the start 1062 // index of our first candidate and the maximum distance an overlapping 1063 // candidate could have from the first candidate. 1064 for (auto It = CandidateList.begin(), Et = CandidateList.end(); It != Et; 1065 It++) { 1066 Candidate &C1 = *It; 1067 OutlinedFunction &F1 = FunctionList[C1.FunctionIdx]; 1068 1069 // If we removed this candidate, skip it. 1070 if (!C1.InCandidateList) 1071 continue; 1072 1073 // If the candidate's function isn't good to outline anymore, then 1074 // remove the candidate and skip it. 1075 if (F1.OccurrenceCount < 2 || F1.Benefit < 1) { 1076 C1.InCandidateList = false; 1077 continue; 1078 } 1079 1080 // The minimum start index of any candidate that could overlap with this 1081 // one. 1082 unsigned FarthestPossibleIdx = 0; 1083 1084 // Either the index is 0, or it's at most MaxCandidateLen indices away. 1085 if (C1.StartIdx > MaxCandidateLen) 1086 FarthestPossibleIdx = C1.StartIdx - MaxCandidateLen; 1087 1088 // Compare against the other candidates in the list. 1089 // This is at most MaxCandidateLen/2 other candidates. 1090 // This is because each candidate has to be at least 2 indices away. 1091 // = O(n * MaxCandidateLen/2) comparisons 1092 // 1093 // On average, the maximum length of a candidate is quite small; a fraction 1094 // of the total module length in terms of instructions. If the maximum 1095 // candidate length is large, then there are fewer possible candidates to 1096 // compare against in the first place. 1097 for (auto Sit = It + 1; Sit != Et; Sit++) { 1098 Candidate &C2 = *Sit; 1099 OutlinedFunction &F2 = FunctionList[C2.FunctionIdx]; 1100 1101 // Is this candidate too far away to overlap? 1102 // NOTE: This will be true in 1103 // O(max(FarthestPossibleIdx/2, #Candidates remaining)) steps 1104 // for every candidate. 1105 if (C2.StartIdx < FarthestPossibleIdx) 1106 break; 1107 1108 // Did we already remove this candidate in a previous step? 1109 if (!C2.InCandidateList) 1110 continue; 1111 1112 // Is the function beneficial to outline? 1113 if (F2.OccurrenceCount < 2 || F2.Benefit < 1) { 1114 // If not, remove this candidate and move to the next one. 1115 C2.InCandidateList = false; 1116 continue; 1117 } 1118 1119 size_t C2End = C2.StartIdx + C2.Len - 1; 1120 1121 // Do C1 and C2 overlap? 1122 // 1123 // Not overlapping: 1124 // High indices... [C1End ... C1Start][C2End ... C2Start] ...Low indices 1125 // 1126 // We sorted our candidate list so C2Start <= C1Start. We know that 1127 // C2End > C2Start since each candidate has length >= 2. Therefore, all we 1128 // have to check is C2End < C2Start to see if we overlap. 1129 if (C2End < C1.StartIdx) 1130 continue; 1131 1132 // C2 overlaps with C1. Because we pruned the tree already, the only way 1133 // this can happen is if C1 is a proper suffix of C2. Thus, we must have 1134 // found C1 first during our query, so it must have benefit greater or 1135 // equal to C2. Greedily pick C1 as the candidate to keep and toss out C2. 1136 DEBUG ( 1137 size_t C1End = C1.StartIdx + C1.Len - 1; 1138 dbgs() << "- Found an overlap to purge.\n"; 1139 dbgs() << "--- C1 :[" << C1.StartIdx << ", " << C1End << "]\n"; 1140 dbgs() << "--- C2 :[" << C2.StartIdx << ", " << C2End << "]\n"; 1141 ); 1142 1143 // Update the function's occurrence count and benefit to reflec that C2 1144 // is being removed. 1145 F2.OccurrenceCount--; 1146 F2.Benefit = TII.getOutliningBenefit(F2.Sequence.size(), 1147 F2.OccurrenceCount, 1148 F2.IsTailCall 1149 ); 1150 1151 // Mark C2 as not in the list. 1152 C2.InCandidateList = false; 1153 1154 DEBUG ( 1155 dbgs() << "- Removed C2. \n"; 1156 dbgs() << "--- Num fns left for C2: " << F2.OccurrenceCount << "\n"; 1157 dbgs() << "--- C2's benefit: " << F2.Benefit << "\n"; 1158 ); 1159 } 1160 } 1161 } 1162 1163 unsigned 1164 MachineOutliner::buildCandidateList(std::vector<Candidate> &CandidateList, 1165 std::vector<OutlinedFunction> &FunctionList, 1166 SuffixTree &ST, 1167 InstructionMapper &Mapper, 1168 const TargetInstrInfo &TII) { 1169 1170 std::vector<unsigned> CandidateSequence; // Current outlining candidate. 1171 unsigned MaxCandidateLen = 0; // Length of the longest candidate. 1172 1173 // Function for maximizing query in the suffix tree. 1174 // This allows us to define more fine-grained types of things to outline in 1175 // the target without putting target-specific info in the suffix tree. 1176 auto BenefitFn = [&TII, &ST, &Mapper](const SuffixTreeNode &Curr, 1177 size_t StringLen) { 1178 1179 // Any leaf whose parent is the root only has one occurrence. 1180 if (Curr.Parent->isRoot()) 1181 return 0u; 1182 1183 // Anything with length < 2 will never be beneficial on any target. 1184 if (StringLen < 2) 1185 return 0u; 1186 1187 size_t Occurrences = Curr.Parent->OccurrenceCount; 1188 1189 // Anything with fewer than 2 occurrences will never be beneficial on any 1190 // target. 1191 if (Occurrences < 2) 1192 return 0u; 1193 1194 // Check if the last instruction in the sequence is a return. 1195 MachineInstr *LastInstr = 1196 Mapper.IntegerInstructionMap[ST[Curr.SuffixIdx + StringLen - 1]]; 1197 assert(LastInstr && "Last instruction in sequence was unmapped!"); 1198 1199 // The only way a terminator could be mapped as legal is if it was safe to 1200 // tail call. 1201 bool IsTailCall = LastInstr->isTerminator(); 1202 1203 return TII.getOutliningBenefit(StringLen, Occurrences, IsTailCall); 1204 }; 1205 1206 // Repeatedly query the suffix tree for the substring that maximizes 1207 // BenefitFn. Find the occurrences of that string, prune the tree, and store 1208 // each occurrence as a candidate. 1209 for (ST.bestRepeatedSubstring(CandidateSequence, BenefitFn); 1210 CandidateSequence.size() > 1; 1211 ST.bestRepeatedSubstring(CandidateSequence, BenefitFn)) { 1212 1213 std::vector<size_t> Occurrences; 1214 1215 bool GotNonOverlappingCandidate = 1216 ST.findOccurrencesAndPrune(CandidateSequence, Occurrences); 1217 1218 // Is the candidate we found known to overlap with something we already 1219 // outlined? 1220 if (!GotNonOverlappingCandidate) 1221 continue; 1222 1223 // Is this candidate the longest so far? 1224 if (CandidateSequence.size() > MaxCandidateLen) 1225 MaxCandidateLen = CandidateSequence.size(); 1226 1227 MachineInstr *LastInstr = 1228 Mapper.IntegerInstructionMap[CandidateSequence.back()]; 1229 assert(LastInstr && "Last instruction in sequence was unmapped!"); 1230 1231 // The only way a terminator could be mapped as legal is if it was safe to 1232 // tail call. 1233 bool IsTailCall = LastInstr->isTerminator(); 1234 1235 // Keep track of the benefit of outlining this candidate in its 1236 // OutlinedFunction. 1237 unsigned FnBenefit = TII.getOutliningBenefit(CandidateSequence.size(), 1238 Occurrences.size(), 1239 IsTailCall 1240 ); 1241 1242 assert(FnBenefit > 0 && "Function cannot be unbeneficial!"); 1243 1244 // Save an OutlinedFunction for this candidate. 1245 FunctionList.emplace_back( 1246 FunctionList.size(), // Number of this function. 1247 Occurrences.size(), // Number of occurrences. 1248 CandidateSequence, // Sequence to outline. 1249 FnBenefit, // Instructions saved by outlining this function. 1250 IsTailCall // Flag set if this function is to be tail called. 1251 ); 1252 1253 // Save each of the occurrences of the candidate so we can outline them. 1254 for (size_t &Occ : Occurrences) 1255 CandidateList.emplace_back( 1256 Occ, // Starting idx in that MBB. 1257 CandidateSequence.size(), // Candidate length. 1258 FunctionList.size() - 1 // Idx of the corresponding function. 1259 ); 1260 1261 FunctionsCreated++; 1262 } 1263 1264 // Sort the candidates in decending order. This will simplify the outlining 1265 // process when we have to remove the candidates from the mapping by 1266 // allowing us to cut them out without keeping track of an offset. 1267 std::stable_sort(CandidateList.begin(), CandidateList.end()); 1268 1269 return MaxCandidateLen; 1270 } 1271 1272 MachineFunction * 1273 MachineOutliner::createOutlinedFunction(Module &M, const OutlinedFunction &OF, 1274 InstructionMapper &Mapper) { 1275 1276 // Create the function name. This should be unique. For now, just hash the 1277 // module name and include it in the function name plus the number of this 1278 // function. 1279 std::ostringstream NameStream; 1280 NameStream << "OUTLINED_FUNCTION" << "_" << OF.Name; 1281 1282 // Create the function using an IR-level function. 1283 LLVMContext &C = M.getContext(); 1284 Function *F = dyn_cast<Function>( 1285 M.getOrInsertFunction(NameStream.str(), Type::getVoidTy(C), nullptr)); 1286 assert(F && "Function was null!"); 1287 1288 // NOTE: If this is linkonceodr, then we can take advantage of linker deduping 1289 // which gives us better results when we outline from linkonceodr functions. 1290 F->setLinkage(GlobalValue::PrivateLinkage); 1291 F->setUnnamedAddr(GlobalValue::UnnamedAddr::Global); 1292 1293 BasicBlock *EntryBB = BasicBlock::Create(C, "entry", F); 1294 IRBuilder<> Builder(EntryBB); 1295 Builder.CreateRetVoid(); 1296 1297 MachineModuleInfo &MMI = getAnalysis<MachineModuleInfo>(); 1298 MachineFunction &MF = MMI.getMachineFunction(*F); 1299 MachineBasicBlock &MBB = *MF.CreateMachineBasicBlock(); 1300 const TargetSubtargetInfo &STI = MF.getSubtarget(); 1301 const TargetInstrInfo &TII = *STI.getInstrInfo(); 1302 1303 // Insert the new function into the module. 1304 MF.insert(MF.begin(), &MBB); 1305 1306 TII.insertOutlinerPrologue(MBB, MF, OF.IsTailCall); 1307 1308 // Copy over the instructions for the function using the integer mappings in 1309 // its sequence. 1310 for (unsigned Str : OF.Sequence) { 1311 MachineInstr *NewMI = 1312 MF.CloneMachineInstr(Mapper.IntegerInstructionMap.find(Str)->second); 1313 NewMI->dropMemRefs(); 1314 1315 // Don't keep debug information for outlined instructions. 1316 // FIXME: This means outlined functions are currently undebuggable. 1317 NewMI->setDebugLoc(DebugLoc()); 1318 MBB.insert(MBB.end(), NewMI); 1319 } 1320 1321 TII.insertOutlinerEpilogue(MBB, MF, OF.IsTailCall); 1322 1323 return &MF; 1324 } 1325 1326 bool MachineOutliner::outline(Module &M, 1327 const ArrayRef<Candidate> &CandidateList, 1328 std::vector<OutlinedFunction> &FunctionList, 1329 InstructionMapper &Mapper) { 1330 1331 bool OutlinedSomething = false; 1332 1333 // Replace the candidates with calls to their respective outlined functions. 1334 for (const Candidate &C : CandidateList) { 1335 1336 // Was the candidate removed during pruneOverlaps? 1337 if (!C.InCandidateList) 1338 continue; 1339 1340 // If not, then look at its OutlinedFunction. 1341 OutlinedFunction &OF = FunctionList[C.FunctionIdx]; 1342 1343 // Was its OutlinedFunction made unbeneficial during pruneOverlaps? 1344 if (OF.OccurrenceCount < 2 || OF.Benefit < 1) 1345 continue; 1346 1347 // If not, then outline it. 1348 assert(C.StartIdx < Mapper.InstrList.size() && "Candidate out of bounds!"); 1349 MachineBasicBlock *MBB = (*Mapper.InstrList[C.StartIdx]).getParent(); 1350 MachineBasicBlock::iterator StartIt = Mapper.InstrList[C.StartIdx]; 1351 unsigned EndIdx = C.StartIdx + C.Len - 1; 1352 1353 assert(EndIdx < Mapper.InstrList.size() && "Candidate out of bounds!"); 1354 MachineBasicBlock::iterator EndIt = Mapper.InstrList[EndIdx]; 1355 assert(EndIt != MBB->end() && "EndIt out of bounds!"); 1356 1357 EndIt++; // Erase needs one past the end index. 1358 1359 // Does this candidate have a function yet? 1360 if (!OF.MF) 1361 OF.MF = createOutlinedFunction(M, OF, Mapper); 1362 1363 MachineFunction *MF = OF.MF; 1364 const TargetSubtargetInfo &STI = MF->getSubtarget(); 1365 const TargetInstrInfo &TII = *STI.getInstrInfo(); 1366 1367 // Insert a call to the new function and erase the old sequence. 1368 TII.insertOutlinedCall(M, *MBB, StartIt, *MF, OF.IsTailCall); 1369 StartIt = Mapper.InstrList[C.StartIdx]; 1370 MBB->erase(StartIt, EndIt); 1371 1372 OutlinedSomething = true; 1373 1374 // Statistics. 1375 NumOutlined++; 1376 } 1377 1378 DEBUG ( 1379 dbgs() << "OutlinedSomething = " << OutlinedSomething << "\n"; 1380 ); 1381 1382 return OutlinedSomething; 1383 } 1384 1385 bool MachineOutliner::runOnModule(Module &M) { 1386 1387 // Is there anything in the module at all? 1388 if (M.empty()) 1389 return false; 1390 1391 MachineModuleInfo &MMI = getAnalysis<MachineModuleInfo>(); 1392 const TargetSubtargetInfo &STI = MMI.getMachineFunction(*M.begin()) 1393 .getSubtarget(); 1394 const TargetRegisterInfo *TRI = STI.getRegisterInfo(); 1395 const TargetInstrInfo *TII = STI.getInstrInfo(); 1396 1397 InstructionMapper Mapper; 1398 1399 // Build instruction mappings for each function in the module. 1400 for (Function &F : M) { 1401 MachineFunction &MF = MMI.getMachineFunction(F); 1402 1403 // Is the function empty? Safe to outline from? 1404 if (F.empty() || !TII->isFunctionSafeToOutlineFrom(MF)) 1405 continue; 1406 1407 // If it is, look at each MachineBasicBlock in the function. 1408 for (MachineBasicBlock &MBB : MF) { 1409 1410 // Is there anything in MBB? 1411 if (MBB.empty()) 1412 continue; 1413 1414 // If yes, map it. 1415 Mapper.convertToUnsignedVec(MBB, *TRI, *TII); 1416 } 1417 } 1418 1419 // Construct a suffix tree, use it to find candidates, and then outline them. 1420 SuffixTree ST(Mapper.UnsignedVec); 1421 std::vector<Candidate> CandidateList; 1422 std::vector<OutlinedFunction> FunctionList; 1423 1424 unsigned MaxCandidateLen = 1425 buildCandidateList(CandidateList, FunctionList, ST, Mapper, *TII); 1426 1427 pruneOverlaps(CandidateList, FunctionList, MaxCandidateLen, *TII); 1428 return outline(M, CandidateList, FunctionList, Mapper); 1429 } 1430