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 /// The MachineOutliner communicates with a given target using hooks defined in 19 /// TargetInstrInfo.h. The target supplies the outliner with information on how 20 /// a specific sequence of instructions should be outlined. This information 21 /// is used to deduce the number of instructions necessary to 22 /// 23 /// * Create an outlined function 24 /// * Call that outlined function 25 /// 26 /// Targets must implement 27 /// * getOutliningCandidateInfo 28 /// * insertOutlinerEpilogue 29 /// * insertOutlinedCall 30 /// * insertOutlinerPrologue 31 /// * isFunctionSafeToOutlineFrom 32 /// 33 /// in order to make use of the MachineOutliner. 34 /// 35 /// This was originally presented at the 2016 LLVM Developers' Meeting in the 36 /// talk "Reducing Code Size Using Outlining". For a high-level overview of 37 /// how this pass works, the talk is available on YouTube at 38 /// 39 /// https://www.youtube.com/watch?v=yorld-WSOeU 40 /// 41 /// The slides for the talk are available at 42 /// 43 /// http://www.llvm.org/devmtg/2016-11/Slides/Paquette-Outliner.pdf 44 /// 45 /// The talk provides an overview of how the outliner finds candidates and 46 /// ultimately outlines them. It describes how the main data structure for this 47 /// pass, the suffix tree, is queried and purged for candidates. It also gives 48 /// a simplified suffix tree construction algorithm for suffix trees based off 49 /// of the algorithm actually used here, Ukkonen's algorithm. 50 /// 51 /// For the original RFC for this pass, please see 52 /// 53 /// http://lists.llvm.org/pipermail/llvm-dev/2016-August/104170.html 54 /// 55 /// For more information on the suffix tree data structure, please see 56 /// https://www.cs.helsinki.fi/u/ukkonen/SuffixT1withFigs.pdf 57 /// 58 //===----------------------------------------------------------------------===// 59 #include "llvm/ADT/DenseMap.h" 60 #include "llvm/ADT/Statistic.h" 61 #include "llvm/ADT/Twine.h" 62 #include "llvm/CodeGen/MachineFunction.h" 63 #include "llvm/CodeGen/MachineModuleInfo.h" 64 #include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h" 65 #include "llvm/CodeGen/MachineRegisterInfo.h" 66 #include "llvm/CodeGen/Passes.h" 67 #include "llvm/CodeGen/TargetInstrInfo.h" 68 #include "llvm/CodeGen/TargetRegisterInfo.h" 69 #include "llvm/CodeGen/TargetSubtargetInfo.h" 70 #include "llvm/IR/DIBuilder.h" 71 #include "llvm/IR/IRBuilder.h" 72 #include "llvm/IR/Mangler.h" 73 #include "llvm/Support/Allocator.h" 74 #include "llvm/Support/CommandLine.h" 75 #include "llvm/Support/Debug.h" 76 #include "llvm/Support/raw_ostream.h" 77 #include <functional> 78 #include <map> 79 #include <sstream> 80 #include <tuple> 81 #include <vector> 82 83 #define DEBUG_TYPE "machine-outliner" 84 85 using namespace llvm; 86 using namespace ore; 87 88 STATISTIC(NumOutlined, "Number of candidates outlined"); 89 STATISTIC(FunctionsCreated, "Number of functions created"); 90 91 // Set to true if the user wants the outliner to run on linkonceodr linkage 92 // functions. This is false by default because the linker can dedupe linkonceodr 93 // functions. Since the outliner is confined to a single module (modulo LTO), 94 // this is off by default. It should, however, be the default behaviour in 95 // LTO. 96 static cl::opt<bool> EnableLinkOnceODROutlining( 97 "enable-linkonceodr-outlining", 98 cl::Hidden, 99 cl::desc("Enable the machine outliner on linkonceodr functions"), 100 cl::init(false)); 101 102 namespace { 103 104 /// An individual sequence of instructions to be replaced with a call to 105 /// an outlined function. 106 struct Candidate { 107 private: 108 /// The start index of this \p Candidate in the instruction list. 109 unsigned StartIdx; 110 111 /// The number of instructions in this \p Candidate. 112 unsigned Len; 113 114 /// The MachineFunction containing this \p Candidate. 115 MachineFunction *MF = nullptr; 116 117 public: 118 /// Set to false if the candidate overlapped with another candidate. 119 bool InCandidateList = true; 120 121 /// The index of this \p Candidate's \p OutlinedFunction in the list of 122 /// \p OutlinedFunctions. 123 unsigned FunctionIdx; 124 125 /// Contains all target-specific information for this \p Candidate. 126 TargetInstrInfo::MachineOutlinerInfo MInfo; 127 128 /// If there is a DISubprogram associated with the function that this 129 /// Candidate lives in, return it. 130 DISubprogram *getSubprogramOrNull() const { 131 assert(MF && "Candidate has no MF!"); 132 if (DISubprogram *SP = MF->getFunction().getSubprogram()) 133 return SP; 134 return nullptr; 135 } 136 137 /// Return the number of instructions in this Candidate. 138 unsigned getLength() const { return Len; } 139 140 /// Return the start index of this candidate. 141 unsigned getStartIdx() const { return StartIdx; } 142 143 // Return the end index of this candidate. 144 unsigned getEndIdx() const { return StartIdx + Len - 1; } 145 146 /// The number of instructions that would be saved by outlining every 147 /// candidate of this type. 148 /// 149 /// This is a fixed value which is not updated during the candidate pruning 150 /// process. It is only used for deciding which candidate to keep if two 151 /// candidates overlap. The true benefit is stored in the OutlinedFunction 152 /// for some given candidate. 153 unsigned Benefit = 0; 154 155 Candidate(unsigned StartIdx, unsigned Len, unsigned FunctionIdx, 156 MachineFunction *MF) 157 : StartIdx(StartIdx), Len(Len), MF(MF), FunctionIdx(FunctionIdx) {} 158 159 Candidate() {} 160 161 /// Used to ensure that \p Candidates are outlined in an order that 162 /// preserves the start and end indices of other \p Candidates. 163 bool operator<(const Candidate &RHS) const { 164 return getStartIdx() > RHS.getStartIdx(); 165 } 166 }; 167 168 /// The information necessary to create an outlined function for some 169 /// class of candidate. 170 struct OutlinedFunction { 171 172 private: 173 /// The number of candidates for this \p OutlinedFunction. 174 unsigned OccurrenceCount = 0; 175 176 public: 177 std::vector<std::shared_ptr<Candidate>> Candidates; 178 179 /// The actual outlined function created. 180 /// This is initialized after we go through and create the actual function. 181 MachineFunction *MF = nullptr; 182 183 /// A number assigned to this function which appears at the end of its name. 184 unsigned Name; 185 186 /// The sequence of integers corresponding to the instructions in this 187 /// function. 188 std::vector<unsigned> Sequence; 189 190 /// Contains all target-specific information for this \p OutlinedFunction. 191 TargetInstrInfo::MachineOutlinerInfo MInfo; 192 193 /// If there is a DISubprogram for any Candidate for this outlined function, 194 /// then return it. Otherwise, return nullptr. 195 DISubprogram *getSubprogramOrNull() const { 196 for (const auto &C : Candidates) 197 if (DISubprogram *SP = C->getSubprogramOrNull()) 198 return SP; 199 return nullptr; 200 } 201 202 /// Return the number of candidates for this \p OutlinedFunction. 203 unsigned getOccurrenceCount() { return OccurrenceCount; } 204 205 /// Decrement the occurrence count of this OutlinedFunction and return the 206 /// new count. 207 unsigned decrement() { 208 assert(OccurrenceCount > 0 && "Can't decrement an empty function!"); 209 OccurrenceCount--; 210 return getOccurrenceCount(); 211 } 212 213 /// Return the number of instructions it would take to outline this 214 /// function. 215 unsigned getOutliningCost() { 216 return (OccurrenceCount * MInfo.CallOverhead) + Sequence.size() + 217 MInfo.FrameOverhead; 218 } 219 220 /// Return the number of instructions that would be saved by outlining 221 /// this function. 222 unsigned getBenefit() { 223 unsigned NotOutlinedCost = OccurrenceCount * Sequence.size(); 224 unsigned OutlinedCost = getOutliningCost(); 225 return (NotOutlinedCost < OutlinedCost) ? 0 226 : NotOutlinedCost - OutlinedCost; 227 } 228 229 OutlinedFunction(unsigned Name, unsigned OccurrenceCount, 230 const std::vector<unsigned> &Sequence, 231 TargetInstrInfo::MachineOutlinerInfo &MInfo) 232 : OccurrenceCount(OccurrenceCount), Name(Name), Sequence(Sequence), 233 MInfo(MInfo) {} 234 }; 235 236 /// Represents an undefined index in the suffix tree. 237 const unsigned EmptyIdx = -1; 238 239 /// A node in a suffix tree which represents a substring or suffix. 240 /// 241 /// Each node has either no children or at least two children, with the root 242 /// being a exception in the empty tree. 243 /// 244 /// Children are represented as a map between unsigned integers and nodes. If 245 /// a node N has a child M on unsigned integer k, then the mapping represented 246 /// by N is a proper prefix of the mapping represented by M. Note that this, 247 /// although similar to a trie is somewhat different: each node stores a full 248 /// substring of the full mapping rather than a single character state. 249 /// 250 /// Each internal node contains a pointer to the internal node representing 251 /// the same string, but with the first character chopped off. This is stored 252 /// in \p Link. Each leaf node stores the start index of its respective 253 /// suffix in \p SuffixIdx. 254 struct SuffixTreeNode { 255 256 /// The children of this node. 257 /// 258 /// A child existing on an unsigned integer implies that from the mapping 259 /// represented by the current node, there is a way to reach another 260 /// mapping by tacking that character on the end of the current string. 261 DenseMap<unsigned, SuffixTreeNode *> Children; 262 263 /// A flag set to false if the node has been pruned from the tree. 264 bool IsInTree = true; 265 266 /// The start index of this node's substring in the main string. 267 unsigned StartIdx = EmptyIdx; 268 269 /// The end index of this node's substring in the main string. 270 /// 271 /// Every leaf node must have its \p EndIdx incremented at the end of every 272 /// step in the construction algorithm. To avoid having to update O(N) 273 /// nodes individually at the end of every step, the end index is stored 274 /// as a pointer. 275 unsigned *EndIdx = nullptr; 276 277 /// For leaves, the start index of the suffix represented by this node. 278 /// 279 /// For all other nodes, this is ignored. 280 unsigned SuffixIdx = EmptyIdx; 281 282 /// For internal nodes, a pointer to the internal node representing 283 /// the same sequence with the first character chopped off. 284 /// 285 /// This acts as a shortcut in Ukkonen's algorithm. One of the things that 286 /// Ukkonen's algorithm does to achieve linear-time construction is 287 /// keep track of which node the next insert should be at. This makes each 288 /// insert O(1), and there are a total of O(N) inserts. The suffix link 289 /// helps with inserting children of internal nodes. 290 /// 291 /// Say we add a child to an internal node with associated mapping S. The 292 /// next insertion must be at the node representing S - its first character. 293 /// This is given by the way that we iteratively build the tree in Ukkonen's 294 /// algorithm. The main idea is to look at the suffixes of each prefix in the 295 /// string, starting with the longest suffix of the prefix, and ending with 296 /// the shortest. Therefore, if we keep pointers between such nodes, we can 297 /// move to the next insertion point in O(1) time. If we don't, then we'd 298 /// have to query from the root, which takes O(N) time. This would make the 299 /// construction algorithm O(N^2) rather than O(N). 300 SuffixTreeNode *Link = nullptr; 301 302 /// The parent of this node. Every node except for the root has a parent. 303 SuffixTreeNode *Parent = nullptr; 304 305 /// The number of times this node's string appears in the tree. 306 /// 307 /// This is equal to the number of leaf children of the string. It represents 308 /// the number of suffixes that the node's string is a prefix of. 309 unsigned OccurrenceCount = 0; 310 311 /// The length of the string formed by concatenating the edge labels from the 312 /// root to this node. 313 unsigned ConcatLen = 0; 314 315 /// Returns true if this node is a leaf. 316 bool isLeaf() const { return SuffixIdx != EmptyIdx; } 317 318 /// Returns true if this node is the root of its owning \p SuffixTree. 319 bool isRoot() const { return StartIdx == EmptyIdx; } 320 321 /// Return the number of elements in the substring associated with this node. 322 size_t size() const { 323 324 // Is it the root? If so, it's the empty string so return 0. 325 if (isRoot()) 326 return 0; 327 328 assert(*EndIdx != EmptyIdx && "EndIdx is undefined!"); 329 330 // Size = the number of elements in the string. 331 // For example, [0 1 2 3] has length 4, not 3. 3-0 = 3, so we have 3-0+1. 332 return *EndIdx - StartIdx + 1; 333 } 334 335 SuffixTreeNode(unsigned StartIdx, unsigned *EndIdx, SuffixTreeNode *Link, 336 SuffixTreeNode *Parent) 337 : StartIdx(StartIdx), EndIdx(EndIdx), Link(Link), Parent(Parent) {} 338 339 SuffixTreeNode() {} 340 }; 341 342 /// A data structure for fast substring queries. 343 /// 344 /// Suffix trees represent the suffixes of their input strings in their leaves. 345 /// A suffix tree is a type of compressed trie structure where each node 346 /// represents an entire substring rather than a single character. Each leaf 347 /// of the tree is a suffix. 348 /// 349 /// A suffix tree can be seen as a type of state machine where each state is a 350 /// substring of the full string. The tree is structured so that, for a string 351 /// of length N, there are exactly N leaves in the tree. This structure allows 352 /// us to quickly find repeated substrings of the input string. 353 /// 354 /// In this implementation, a "string" is a vector of unsigned integers. 355 /// These integers may result from hashing some data type. A suffix tree can 356 /// contain 1 or many strings, which can then be queried as one large string. 357 /// 358 /// The suffix tree is implemented using Ukkonen's algorithm for linear-time 359 /// suffix tree construction. Ukkonen's algorithm is explained in more detail 360 /// in the paper by Esko Ukkonen "On-line construction of suffix trees. The 361 /// paper is available at 362 /// 363 /// https://www.cs.helsinki.fi/u/ukkonen/SuffixT1withFigs.pdf 364 class SuffixTree { 365 public: 366 /// Stores each leaf node in the tree. 367 /// 368 /// This is used for finding outlining candidates. 369 std::vector<SuffixTreeNode *> LeafVector; 370 371 /// Each element is an integer representing an instruction in the module. 372 ArrayRef<unsigned> Str; 373 374 private: 375 /// Maintains each node in the tree. 376 SpecificBumpPtrAllocator<SuffixTreeNode> NodeAllocator; 377 378 /// The root of the suffix tree. 379 /// 380 /// The root represents the empty string. It is maintained by the 381 /// \p NodeAllocator like every other node in the tree. 382 SuffixTreeNode *Root = nullptr; 383 384 /// Maintains the end indices of the internal nodes in the tree. 385 /// 386 /// Each internal node is guaranteed to never have its end index change 387 /// during the construction algorithm; however, leaves must be updated at 388 /// every step. Therefore, we need to store leaf end indices by reference 389 /// to avoid updating O(N) leaves at every step of construction. Thus, 390 /// every internal node must be allocated its own end index. 391 BumpPtrAllocator InternalEndIdxAllocator; 392 393 /// The end index of each leaf in the tree. 394 unsigned LeafEndIdx = -1; 395 396 /// Helper struct which keeps track of the next insertion point in 397 /// Ukkonen's algorithm. 398 struct ActiveState { 399 /// The next node to insert at. 400 SuffixTreeNode *Node; 401 402 /// The index of the first character in the substring currently being added. 403 unsigned Idx = EmptyIdx; 404 405 /// The length of the substring we have to add at the current step. 406 unsigned Len = 0; 407 }; 408 409 /// The point the next insertion will take place at in the 410 /// construction algorithm. 411 ActiveState Active; 412 413 /// Allocate a leaf node and add it to the tree. 414 /// 415 /// \param Parent The parent of this node. 416 /// \param StartIdx The start index of this node's associated string. 417 /// \param Edge The label on the edge leaving \p Parent to this node. 418 /// 419 /// \returns A pointer to the allocated leaf node. 420 SuffixTreeNode *insertLeaf(SuffixTreeNode &Parent, unsigned StartIdx, 421 unsigned Edge) { 422 423 assert(StartIdx <= LeafEndIdx && "String can't start after it ends!"); 424 425 SuffixTreeNode *N = new (NodeAllocator.Allocate()) 426 SuffixTreeNode(StartIdx, &LeafEndIdx, nullptr, &Parent); 427 Parent.Children[Edge] = N; 428 429 return N; 430 } 431 432 /// Allocate an internal node and add it to the tree. 433 /// 434 /// \param Parent The parent of this node. Only null when allocating the root. 435 /// \param StartIdx The start index of this node's associated string. 436 /// \param EndIdx The end index of this node's associated string. 437 /// \param Edge The label on the edge leaving \p Parent to this node. 438 /// 439 /// \returns A pointer to the allocated internal node. 440 SuffixTreeNode *insertInternalNode(SuffixTreeNode *Parent, unsigned StartIdx, 441 unsigned EndIdx, unsigned Edge) { 442 443 assert(StartIdx <= EndIdx && "String can't start after it ends!"); 444 assert(!(!Parent && StartIdx != EmptyIdx) && 445 "Non-root internal nodes must have parents!"); 446 447 unsigned *E = new (InternalEndIdxAllocator) unsigned(EndIdx); 448 SuffixTreeNode *N = new (NodeAllocator.Allocate()) 449 SuffixTreeNode(StartIdx, E, Root, Parent); 450 if (Parent) 451 Parent->Children[Edge] = N; 452 453 return N; 454 } 455 456 /// Set the suffix indices of the leaves to the start indices of their 457 /// respective suffixes. Also stores each leaf in \p LeafVector at its 458 /// respective suffix index. 459 /// 460 /// \param[in] CurrNode The node currently being visited. 461 /// \param CurrIdx The current index of the string being visited. 462 void setSuffixIndices(SuffixTreeNode &CurrNode, unsigned CurrIdx) { 463 464 bool IsLeaf = CurrNode.Children.size() == 0 && !CurrNode.isRoot(); 465 466 // Store the length of the concatenation of all strings from the root to 467 // this node. 468 if (!CurrNode.isRoot()) { 469 if (CurrNode.ConcatLen == 0) 470 CurrNode.ConcatLen = CurrNode.size(); 471 472 if (CurrNode.Parent) 473 CurrNode.ConcatLen += CurrNode.Parent->ConcatLen; 474 } 475 476 // Traverse the tree depth-first. 477 for (auto &ChildPair : CurrNode.Children) { 478 assert(ChildPair.second && "Node had a null child!"); 479 setSuffixIndices(*ChildPair.second, CurrIdx + ChildPair.second->size()); 480 } 481 482 // Is this node a leaf? 483 if (IsLeaf) { 484 // If yes, give it a suffix index and bump its parent's occurrence count. 485 CurrNode.SuffixIdx = Str.size() - CurrIdx; 486 assert(CurrNode.Parent && "CurrNode had no parent!"); 487 CurrNode.Parent->OccurrenceCount++; 488 489 // Store the leaf in the leaf vector for pruning later. 490 LeafVector[CurrNode.SuffixIdx] = &CurrNode; 491 } 492 } 493 494 /// Construct the suffix tree for the prefix of the input ending at 495 /// \p EndIdx. 496 /// 497 /// Used to construct the full suffix tree iteratively. At the end of each 498 /// step, the constructed suffix tree is either a valid suffix tree, or a 499 /// suffix tree with implicit suffixes. At the end of the final step, the 500 /// suffix tree is a valid tree. 501 /// 502 /// \param EndIdx The end index of the current prefix in the main string. 503 /// \param SuffixesToAdd The number of suffixes that must be added 504 /// to complete the suffix tree at the current phase. 505 /// 506 /// \returns The number of suffixes that have not been added at the end of 507 /// this step. 508 unsigned extend(unsigned EndIdx, unsigned SuffixesToAdd) { 509 SuffixTreeNode *NeedsLink = nullptr; 510 511 while (SuffixesToAdd > 0) { 512 513 // Are we waiting to add anything other than just the last character? 514 if (Active.Len == 0) { 515 // If not, then say the active index is the end index. 516 Active.Idx = EndIdx; 517 } 518 519 assert(Active.Idx <= EndIdx && "Start index can't be after end index!"); 520 521 // The first character in the current substring we're looking at. 522 unsigned FirstChar = Str[Active.Idx]; 523 524 // Have we inserted anything starting with FirstChar at the current node? 525 if (Active.Node->Children.count(FirstChar) == 0) { 526 // If not, then we can just insert a leaf and move too the next step. 527 insertLeaf(*Active.Node, EndIdx, FirstChar); 528 529 // The active node is an internal node, and we visited it, so it must 530 // need a link if it doesn't have one. 531 if (NeedsLink) { 532 NeedsLink->Link = Active.Node; 533 NeedsLink = nullptr; 534 } 535 } else { 536 // There's a match with FirstChar, so look for the point in the tree to 537 // insert a new node. 538 SuffixTreeNode *NextNode = Active.Node->Children[FirstChar]; 539 540 unsigned SubstringLen = NextNode->size(); 541 542 // Is the current suffix we're trying to insert longer than the size of 543 // the child we want to move to? 544 if (Active.Len >= SubstringLen) { 545 // If yes, then consume the characters we've seen and move to the next 546 // node. 547 Active.Idx += SubstringLen; 548 Active.Len -= SubstringLen; 549 Active.Node = NextNode; 550 continue; 551 } 552 553 // Otherwise, the suffix we're trying to insert must be contained in the 554 // next node we want to move to. 555 unsigned LastChar = Str[EndIdx]; 556 557 // Is the string we're trying to insert a substring of the next node? 558 if (Str[NextNode->StartIdx + Active.Len] == LastChar) { 559 // If yes, then we're done for this step. Remember our insertion point 560 // and move to the next end index. At this point, we have an implicit 561 // suffix tree. 562 if (NeedsLink && !Active.Node->isRoot()) { 563 NeedsLink->Link = Active.Node; 564 NeedsLink = nullptr; 565 } 566 567 Active.Len++; 568 break; 569 } 570 571 // The string we're trying to insert isn't a substring of the next node, 572 // but matches up to a point. Split the node. 573 // 574 // For example, say we ended our search at a node n and we're trying to 575 // insert ABD. Then we'll create a new node s for AB, reduce n to just 576 // representing C, and insert a new leaf node l to represent d. This 577 // allows us to ensure that if n was a leaf, it remains a leaf. 578 // 579 // | ABC ---split---> | AB 580 // n s 581 // C / \ D 582 // n l 583 584 // The node s from the diagram 585 SuffixTreeNode *SplitNode = 586 insertInternalNode(Active.Node, NextNode->StartIdx, 587 NextNode->StartIdx + Active.Len - 1, FirstChar); 588 589 // Insert the new node representing the new substring into the tree as 590 // a child of the split node. This is the node l from the diagram. 591 insertLeaf(*SplitNode, EndIdx, LastChar); 592 593 // Make the old node a child of the split node and update its start 594 // index. This is the node n from the diagram. 595 NextNode->StartIdx += Active.Len; 596 NextNode->Parent = SplitNode; 597 SplitNode->Children[Str[NextNode->StartIdx]] = NextNode; 598 599 // SplitNode is an internal node, update the suffix link. 600 if (NeedsLink) 601 NeedsLink->Link = SplitNode; 602 603 NeedsLink = SplitNode; 604 } 605 606 // We've added something new to the tree, so there's one less suffix to 607 // add. 608 SuffixesToAdd--; 609 610 if (Active.Node->isRoot()) { 611 if (Active.Len > 0) { 612 Active.Len--; 613 Active.Idx = EndIdx - SuffixesToAdd + 1; 614 } 615 } else { 616 // Start the next phase at the next smallest suffix. 617 Active.Node = Active.Node->Link; 618 } 619 } 620 621 return SuffixesToAdd; 622 } 623 624 public: 625 /// Construct a suffix tree from a sequence of unsigned integers. 626 /// 627 /// \param Str The string to construct the suffix tree for. 628 SuffixTree(const std::vector<unsigned> &Str) : Str(Str) { 629 Root = insertInternalNode(nullptr, EmptyIdx, EmptyIdx, 0); 630 Root->IsInTree = true; 631 Active.Node = Root; 632 LeafVector = std::vector<SuffixTreeNode *>(Str.size()); 633 634 // Keep track of the number of suffixes we have to add of the current 635 // prefix. 636 unsigned SuffixesToAdd = 0; 637 Active.Node = Root; 638 639 // Construct the suffix tree iteratively on each prefix of the string. 640 // PfxEndIdx is the end index of the current prefix. 641 // End is one past the last element in the string. 642 for (unsigned PfxEndIdx = 0, End = Str.size(); PfxEndIdx < End; 643 PfxEndIdx++) { 644 SuffixesToAdd++; 645 LeafEndIdx = PfxEndIdx; // Extend each of the leaves. 646 SuffixesToAdd = extend(PfxEndIdx, SuffixesToAdd); 647 } 648 649 // Set the suffix indices of each leaf. 650 assert(Root && "Root node can't be nullptr!"); 651 setSuffixIndices(*Root, 0); 652 } 653 }; 654 655 /// Maps \p MachineInstrs to unsigned integers and stores the mappings. 656 struct InstructionMapper { 657 658 /// The next available integer to assign to a \p MachineInstr that 659 /// cannot be outlined. 660 /// 661 /// Set to -3 for compatability with \p DenseMapInfo<unsigned>. 662 unsigned IllegalInstrNumber = -3; 663 664 /// The next available integer to assign to a \p MachineInstr that can 665 /// be outlined. 666 unsigned LegalInstrNumber = 0; 667 668 /// Correspondence from \p MachineInstrs to unsigned integers. 669 DenseMap<MachineInstr *, unsigned, MachineInstrExpressionTrait> 670 InstructionIntegerMap; 671 672 /// Corresponcence from unsigned integers to \p MachineInstrs. 673 /// Inverse of \p InstructionIntegerMap. 674 DenseMap<unsigned, MachineInstr *> IntegerInstructionMap; 675 676 /// The vector of unsigned integers that the module is mapped to. 677 std::vector<unsigned> UnsignedVec; 678 679 /// Stores the location of the instruction associated with the integer 680 /// at index i in \p UnsignedVec for each index i. 681 std::vector<MachineBasicBlock::iterator> InstrList; 682 683 /// Maps \p *It to a legal integer. 684 /// 685 /// Updates \p InstrList, \p UnsignedVec, \p InstructionIntegerMap, 686 /// \p IntegerInstructionMap, and \p LegalInstrNumber. 687 /// 688 /// \returns The integer that \p *It was mapped to. 689 unsigned mapToLegalUnsigned(MachineBasicBlock::iterator &It) { 690 691 // Get the integer for this instruction or give it the current 692 // LegalInstrNumber. 693 InstrList.push_back(It); 694 MachineInstr &MI = *It; 695 bool WasInserted; 696 DenseMap<MachineInstr *, unsigned, MachineInstrExpressionTrait>::iterator 697 ResultIt; 698 std::tie(ResultIt, WasInserted) = 699 InstructionIntegerMap.insert(std::make_pair(&MI, LegalInstrNumber)); 700 unsigned MINumber = ResultIt->second; 701 702 // There was an insertion. 703 if (WasInserted) { 704 LegalInstrNumber++; 705 IntegerInstructionMap.insert(std::make_pair(MINumber, &MI)); 706 } 707 708 UnsignedVec.push_back(MINumber); 709 710 // Make sure we don't overflow or use any integers reserved by the DenseMap. 711 if (LegalInstrNumber >= IllegalInstrNumber) 712 report_fatal_error("Instruction mapping overflow!"); 713 714 assert(LegalInstrNumber != DenseMapInfo<unsigned>::getEmptyKey() && 715 "Tried to assign DenseMap tombstone or empty key to instruction."); 716 assert(LegalInstrNumber != DenseMapInfo<unsigned>::getTombstoneKey() && 717 "Tried to assign DenseMap tombstone or empty key to instruction."); 718 719 return MINumber; 720 } 721 722 /// Maps \p *It to an illegal integer. 723 /// 724 /// Updates \p InstrList, \p UnsignedVec, and \p IllegalInstrNumber. 725 /// 726 /// \returns The integer that \p *It was mapped to. 727 unsigned mapToIllegalUnsigned(MachineBasicBlock::iterator &It) { 728 unsigned MINumber = IllegalInstrNumber; 729 730 InstrList.push_back(It); 731 UnsignedVec.push_back(IllegalInstrNumber); 732 IllegalInstrNumber--; 733 734 assert(LegalInstrNumber < IllegalInstrNumber && 735 "Instruction mapping overflow!"); 736 737 assert(IllegalInstrNumber != DenseMapInfo<unsigned>::getEmptyKey() && 738 "IllegalInstrNumber cannot be DenseMap tombstone or empty key!"); 739 740 assert(IllegalInstrNumber != DenseMapInfo<unsigned>::getTombstoneKey() && 741 "IllegalInstrNumber cannot be DenseMap tombstone or empty key!"); 742 743 return MINumber; 744 } 745 746 /// Transforms a \p MachineBasicBlock into a \p vector of \p unsigneds 747 /// and appends it to \p UnsignedVec and \p InstrList. 748 /// 749 /// Two instructions are assigned the same integer if they are identical. 750 /// If an instruction is deemed unsafe to outline, then it will be assigned an 751 /// unique integer. The resulting mapping is placed into a suffix tree and 752 /// queried for candidates. 753 /// 754 /// \param MBB The \p MachineBasicBlock to be translated into integers. 755 /// \param TRI \p TargetRegisterInfo for the module. 756 /// \param TII \p TargetInstrInfo for the module. 757 void convertToUnsignedVec(MachineBasicBlock &MBB, 758 const TargetRegisterInfo &TRI, 759 const TargetInstrInfo &TII) { 760 unsigned Flags = TII.getMachineOutlinerMBBFlags(MBB); 761 762 for (MachineBasicBlock::iterator It = MBB.begin(), Et = MBB.end(); It != Et; 763 It++) { 764 765 // Keep track of where this instruction is in the module. 766 switch (TII.getOutliningType(It, Flags)) { 767 case TargetInstrInfo::MachineOutlinerInstrType::Illegal: 768 mapToIllegalUnsigned(It); 769 break; 770 771 case TargetInstrInfo::MachineOutlinerInstrType::Legal: 772 mapToLegalUnsigned(It); 773 break; 774 775 case TargetInstrInfo::MachineOutlinerInstrType::Invisible: 776 break; 777 } 778 } 779 780 // After we're done every insertion, uniquely terminate this part of the 781 // "string". This makes sure we won't match across basic block or function 782 // boundaries since the "end" is encoded uniquely and thus appears in no 783 // repeated substring. 784 InstrList.push_back(MBB.end()); 785 UnsignedVec.push_back(IllegalInstrNumber); 786 IllegalInstrNumber--; 787 } 788 789 InstructionMapper() { 790 // Make sure that the implementation of DenseMapInfo<unsigned> hasn't 791 // changed. 792 assert(DenseMapInfo<unsigned>::getEmptyKey() == (unsigned)-1 && 793 "DenseMapInfo<unsigned>'s empty key isn't -1!"); 794 assert(DenseMapInfo<unsigned>::getTombstoneKey() == (unsigned)-2 && 795 "DenseMapInfo<unsigned>'s tombstone key isn't -2!"); 796 } 797 }; 798 799 /// An interprocedural pass which finds repeated sequences of 800 /// instructions and replaces them with calls to functions. 801 /// 802 /// Each instruction is mapped to an unsigned integer and placed in a string. 803 /// The resulting mapping is then placed in a \p SuffixTree. The \p SuffixTree 804 /// is then repeatedly queried for repeated sequences of instructions. Each 805 /// non-overlapping repeated sequence is then placed in its own 806 /// \p MachineFunction and each instance is then replaced with a call to that 807 /// function. 808 struct MachineOutliner : public ModulePass { 809 810 static char ID; 811 812 /// Set to true if the outliner should consider functions with 813 /// linkonceodr linkage. 814 bool OutlineFromLinkOnceODRs = false; 815 816 // Collection of IR functions created by the outliner. 817 std::vector<Function *> CreatedIRFunctions; 818 819 StringRef getPassName() const override { return "Machine Outliner"; } 820 821 void getAnalysisUsage(AnalysisUsage &AU) const override { 822 AU.addRequired<MachineModuleInfo>(); 823 AU.addPreserved<MachineModuleInfo>(); 824 AU.setPreservesAll(); 825 ModulePass::getAnalysisUsage(AU); 826 } 827 828 MachineOutliner() : ModulePass(ID) { 829 initializeMachineOutlinerPass(*PassRegistry::getPassRegistry()); 830 } 831 832 /// Find all repeated substrings that satisfy the outlining cost model. 833 /// 834 /// If a substring appears at least twice, then it must be represented by 835 /// an internal node which appears in at least two suffixes. Each suffix is 836 /// represented by a leaf node. To do this, we visit each internal node in 837 /// the tree, using the leaf children of each internal node. If an internal 838 /// node represents a beneficial substring, then we use each of its leaf 839 /// children to find the locations of its substring. 840 /// 841 /// \param ST A suffix tree to query. 842 /// \param TII TargetInstrInfo for the target. 843 /// \param Mapper Contains outlining mapping information. 844 /// \param[out] CandidateList Filled with candidates representing each 845 /// beneficial substring. 846 /// \param[out] FunctionList Filled with a list of \p OutlinedFunctions each 847 /// type of candidate. 848 /// 849 /// \returns The length of the longest candidate found. 850 unsigned 851 findCandidates(SuffixTree &ST, const TargetInstrInfo &TII, 852 InstructionMapper &Mapper, 853 std::vector<std::shared_ptr<Candidate>> &CandidateList, 854 std::vector<OutlinedFunction> &FunctionList); 855 856 /// Replace the sequences of instructions represented by the 857 /// \p Candidates in \p CandidateList with calls to \p MachineFunctions 858 /// described in \p FunctionList. 859 /// 860 /// \param M The module we are outlining from. 861 /// \param CandidateList A list of candidates to be outlined. 862 /// \param FunctionList A list of functions to be inserted into the module. 863 /// \param Mapper Contains the instruction mappings for the module. 864 bool outline(Module &M, 865 const ArrayRef<std::shared_ptr<Candidate>> &CandidateList, 866 std::vector<OutlinedFunction> &FunctionList, 867 InstructionMapper &Mapper); 868 869 /// Creates a function for \p OF and inserts it into the module. 870 MachineFunction *createOutlinedFunction(Module &M, const OutlinedFunction &OF, 871 InstructionMapper &Mapper); 872 873 /// Find potential outlining candidates and store them in \p CandidateList. 874 /// 875 /// For each type of potential candidate, also build an \p OutlinedFunction 876 /// struct containing the information to build the function for that 877 /// candidate. 878 /// 879 /// \param[out] CandidateList Filled with outlining candidates for the module. 880 /// \param[out] FunctionList Filled with functions corresponding to each type 881 /// of \p Candidate. 882 /// \param ST The suffix tree for the module. 883 /// \param TII TargetInstrInfo for the module. 884 /// 885 /// \returns The length of the longest candidate found. 0 if there are none. 886 unsigned 887 buildCandidateList(std::vector<std::shared_ptr<Candidate>> &CandidateList, 888 std::vector<OutlinedFunction> &FunctionList, 889 SuffixTree &ST, InstructionMapper &Mapper, 890 const TargetInstrInfo &TII); 891 892 /// Helper function for pruneOverlaps. 893 /// Removes \p C from the candidate list, and updates its \p OutlinedFunction. 894 void prune(Candidate &C, std::vector<OutlinedFunction> &FunctionList); 895 896 /// Remove any overlapping candidates that weren't handled by the 897 /// suffix tree's pruning method. 898 /// 899 /// Pruning from the suffix tree doesn't necessarily remove all overlaps. 900 /// If a short candidate is chosen for outlining, then a longer candidate 901 /// which has that short candidate as a suffix is chosen, the tree's pruning 902 /// method will not find it. Thus, we need to prune before outlining as well. 903 /// 904 /// \param[in,out] CandidateList A list of outlining candidates. 905 /// \param[in,out] FunctionList A list of functions to be outlined. 906 /// \param Mapper Contains instruction mapping info for outlining. 907 /// \param MaxCandidateLen The length of the longest candidate. 908 /// \param TII TargetInstrInfo for the module. 909 void pruneOverlaps(std::vector<std::shared_ptr<Candidate>> &CandidateList, 910 std::vector<OutlinedFunction> &FunctionList, 911 InstructionMapper &Mapper, unsigned MaxCandidateLen, 912 const TargetInstrInfo &TII); 913 914 /// Construct a suffix tree on the instructions in \p M and outline repeated 915 /// strings from that tree. 916 bool runOnModule(Module &M) override; 917 }; 918 919 } // Anonymous namespace. 920 921 char MachineOutliner::ID = 0; 922 923 namespace llvm { 924 ModulePass *createMachineOutlinerPass() { 925 return new MachineOutliner(); 926 } 927 928 } // namespace llvm 929 930 INITIALIZE_PASS(MachineOutliner, DEBUG_TYPE, "Machine Function Outliner", false, 931 false) 932 933 unsigned MachineOutliner::findCandidates( 934 SuffixTree &ST, const TargetInstrInfo &TII, InstructionMapper &Mapper, 935 std::vector<std::shared_ptr<Candidate>> &CandidateList, 936 std::vector<OutlinedFunction> &FunctionList) { 937 CandidateList.clear(); 938 FunctionList.clear(); 939 unsigned MaxLen = 0; 940 941 // FIXME: Visit internal nodes instead of leaves. 942 for (SuffixTreeNode *Leaf : ST.LeafVector) { 943 assert(Leaf && "Leaves in LeafVector cannot be null!"); 944 if (!Leaf->IsInTree) 945 continue; 946 947 assert(Leaf->Parent && "All leaves must have parents!"); 948 SuffixTreeNode &Parent = *(Leaf->Parent); 949 950 // If it doesn't appear enough, or we already outlined from it, skip it. 951 if (Parent.OccurrenceCount < 2 || Parent.isRoot() || !Parent.IsInTree) 952 continue; 953 954 // Figure out if this candidate is beneficial. 955 unsigned StringLen = Leaf->ConcatLen - (unsigned)Leaf->size(); 956 957 // Too short to be beneficial; skip it. 958 // FIXME: This isn't necessarily true for, say, X86. If we factor in 959 // instruction lengths we need more information than this. 960 if (StringLen < 2) 961 continue; 962 963 // If this is a beneficial class of candidate, then every one is stored in 964 // this vector. 965 std::vector<Candidate> CandidatesForRepeatedSeq; 966 967 // Describes the start and end point of each candidate. This allows the 968 // target to infer some information about each occurrence of each repeated 969 // sequence. 970 // FIXME: CandidatesForRepeatedSeq and this should be combined. 971 std::vector< 972 std::pair<MachineBasicBlock::iterator, MachineBasicBlock::iterator>> 973 RepeatedSequenceLocs; 974 975 // Figure out the call overhead for each instance of the sequence. 976 for (auto &ChildPair : Parent.Children) { 977 SuffixTreeNode *M = ChildPair.second; 978 979 if (M && M->IsInTree && M->isLeaf()) { 980 // Never visit this leaf again. 981 M->IsInTree = false; 982 unsigned StartIdx = M->SuffixIdx; 983 unsigned EndIdx = StartIdx + StringLen - 1; 984 985 // Trick: Discard some candidates that would be incompatible with the 986 // ones we've already found for this sequence. This will save us some 987 // work in candidate selection. 988 // 989 // If two candidates overlap, then we can't outline them both. This 990 // happens when we have candidates that look like, say 991 // 992 // AA (where each "A" is an instruction). 993 // 994 // We might have some portion of the module that looks like this: 995 // AAAAAA (6 A's) 996 // 997 // In this case, there are 5 different copies of "AA" in this range, but 998 // at most 3 can be outlined. If only outlining 3 of these is going to 999 // be unbeneficial, then we ought to not bother. 1000 // 1001 // Note that two things DON'T overlap when they look like this: 1002 // start1...end1 .... start2...end2 1003 // That is, one must either 1004 // * End before the other starts 1005 // * Start after the other ends 1006 if (std::all_of(CandidatesForRepeatedSeq.begin(), 1007 CandidatesForRepeatedSeq.end(), 1008 [&StartIdx, &EndIdx](const Candidate &C) { 1009 return (EndIdx < C.getStartIdx() || 1010 StartIdx > C.getEndIdx()); 1011 })) { 1012 // It doesn't overlap with anything, so we can outline it. 1013 // Each sequence is over [StartIt, EndIt]. 1014 MachineBasicBlock::iterator StartIt = Mapper.InstrList[StartIdx]; 1015 MachineBasicBlock::iterator EndIt = Mapper.InstrList[EndIdx]; 1016 1017 // Save the MachineFunction containing the Candidate. 1018 MachineFunction *MF = StartIt->getParent()->getParent(); 1019 assert(MF && "Candidate doesn't have a MF?"); 1020 1021 // Save the candidate and its location. 1022 CandidatesForRepeatedSeq.emplace_back(StartIdx, StringLen, 1023 FunctionList.size(), MF); 1024 RepeatedSequenceLocs.emplace_back(std::make_pair(StartIt, EndIt)); 1025 } 1026 } 1027 } 1028 1029 // We've found something we might want to outline. 1030 // Create an OutlinedFunction to store it and check if it'd be beneficial 1031 // to outline. 1032 TargetInstrInfo::MachineOutlinerInfo MInfo = 1033 TII.getOutlininingCandidateInfo(RepeatedSequenceLocs); 1034 std::vector<unsigned> Seq; 1035 for (unsigned i = Leaf->SuffixIdx; i < Leaf->SuffixIdx + StringLen; i++) 1036 Seq.push_back(ST.Str[i]); 1037 OutlinedFunction OF(FunctionList.size(), CandidatesForRepeatedSeq.size(), 1038 Seq, MInfo); 1039 unsigned Benefit = OF.getBenefit(); 1040 1041 // Is it better to outline this candidate than not? 1042 if (Benefit < 1) { 1043 // Outlining this candidate would take more instructions than not 1044 // outlining. 1045 // Emit a remark explaining why we didn't outline this candidate. 1046 std::pair<MachineBasicBlock::iterator, MachineBasicBlock::iterator> C = 1047 RepeatedSequenceLocs[0]; 1048 MachineOptimizationRemarkEmitter MORE( 1049 *(C.first->getParent()->getParent()), nullptr); 1050 MORE.emit([&]() { 1051 MachineOptimizationRemarkMissed R(DEBUG_TYPE, "NotOutliningCheaper", 1052 C.first->getDebugLoc(), 1053 C.first->getParent()); 1054 R << "Did not outline " << NV("Length", StringLen) << " instructions" 1055 << " from " << NV("NumOccurrences", RepeatedSequenceLocs.size()) 1056 << " locations." 1057 << " Instructions from outlining all occurrences (" 1058 << NV("OutliningCost", OF.getOutliningCost()) << ")" 1059 << " >= Unoutlined instruction count (" 1060 << NV("NotOutliningCost", StringLen * OF.getOccurrenceCount()) << ")" 1061 << " (Also found at: "; 1062 1063 // Tell the user the other places the candidate was found. 1064 for (unsigned i = 1, e = RepeatedSequenceLocs.size(); i < e; i++) { 1065 R << NV((Twine("OtherStartLoc") + Twine(i)).str(), 1066 RepeatedSequenceLocs[i].first->getDebugLoc()); 1067 if (i != e - 1) 1068 R << ", "; 1069 } 1070 1071 R << ")"; 1072 return R; 1073 }); 1074 1075 // Move to the next candidate. 1076 continue; 1077 } 1078 1079 if (StringLen > MaxLen) 1080 MaxLen = StringLen; 1081 1082 // At this point, the candidate class is seen as beneficial. Set their 1083 // benefit values and save them in the candidate list. 1084 std::vector<std::shared_ptr<Candidate>> CandidatesForFn; 1085 for (Candidate &C : CandidatesForRepeatedSeq) { 1086 C.Benefit = Benefit; 1087 C.MInfo = MInfo; 1088 std::shared_ptr<Candidate> Cptr = std::make_shared<Candidate>(C); 1089 CandidateList.push_back(Cptr); 1090 CandidatesForFn.push_back(Cptr); 1091 } 1092 1093 FunctionList.push_back(OF); 1094 FunctionList.back().Candidates = CandidatesForFn; 1095 1096 // Move to the next function. 1097 Parent.IsInTree = false; 1098 } 1099 1100 return MaxLen; 1101 } 1102 1103 // Remove C from the candidate space, and update its OutlinedFunction. 1104 void MachineOutliner::prune(Candidate &C, 1105 std::vector<OutlinedFunction> &FunctionList) { 1106 // Get the OutlinedFunction associated with this Candidate. 1107 OutlinedFunction &F = FunctionList[C.FunctionIdx]; 1108 1109 // Update C's associated function's occurrence count. 1110 F.decrement(); 1111 1112 // Remove C from the CandidateList. 1113 C.InCandidateList = false; 1114 1115 LLVM_DEBUG(dbgs() << "- Removed a Candidate \n"; 1116 dbgs() << "--- Num fns left for candidate: " 1117 << F.getOccurrenceCount() << "\n"; 1118 dbgs() << "--- Candidate's functions's benefit: " << F.getBenefit() 1119 << "\n";); 1120 } 1121 1122 void MachineOutliner::pruneOverlaps( 1123 std::vector<std::shared_ptr<Candidate>> &CandidateList, 1124 std::vector<OutlinedFunction> &FunctionList, InstructionMapper &Mapper, 1125 unsigned MaxCandidateLen, const TargetInstrInfo &TII) { 1126 1127 // Return true if this candidate became unbeneficial for outlining in a 1128 // previous step. 1129 auto ShouldSkipCandidate = [&FunctionList, this](Candidate &C) { 1130 1131 // Check if the candidate was removed in a previous step. 1132 if (!C.InCandidateList) 1133 return true; 1134 1135 // C must be alive. Check if we should remove it. 1136 if (FunctionList[C.FunctionIdx].getBenefit() < 1) { 1137 prune(C, FunctionList); 1138 return true; 1139 } 1140 1141 // C is in the list, and F is still beneficial. 1142 return false; 1143 }; 1144 1145 // TODO: Experiment with interval trees or other interval-checking structures 1146 // to lower the time complexity of this function. 1147 // TODO: Can we do better than the simple greedy choice? 1148 // Check for overlaps in the range. 1149 // This is O(MaxCandidateLen * CandidateList.size()). 1150 for (auto It = CandidateList.begin(), Et = CandidateList.end(); It != Et; 1151 It++) { 1152 Candidate &C1 = **It; 1153 1154 // If C1 was already pruned, or its function is no longer beneficial for 1155 // outlining, move to the next candidate. 1156 if (ShouldSkipCandidate(C1)) 1157 continue; 1158 1159 // The minimum start index of any candidate that could overlap with this 1160 // one. 1161 unsigned FarthestPossibleIdx = 0; 1162 1163 // Either the index is 0, or it's at most MaxCandidateLen indices away. 1164 if (C1.getStartIdx() > MaxCandidateLen) 1165 FarthestPossibleIdx = C1.getStartIdx() - MaxCandidateLen; 1166 1167 // Compare against the candidates in the list that start at most 1168 // FarthestPossibleIdx indices away from C1. There are at most 1169 // MaxCandidateLen of these. 1170 for (auto Sit = It + 1; Sit != Et; Sit++) { 1171 Candidate &C2 = **Sit; 1172 1173 // Is this candidate too far away to overlap? 1174 if (C2.getStartIdx() < FarthestPossibleIdx) 1175 break; 1176 1177 // If C2 was already pruned, or its function is no longer beneficial for 1178 // outlining, move to the next candidate. 1179 if (ShouldSkipCandidate(C2)) 1180 continue; 1181 1182 // Do C1 and C2 overlap? 1183 // 1184 // Not overlapping: 1185 // High indices... [C1End ... C1Start][C2End ... C2Start] ...Low indices 1186 // 1187 // We sorted our candidate list so C2Start <= C1Start. We know that 1188 // C2End > C2Start since each candidate has length >= 2. Therefore, all we 1189 // have to check is C2End < C2Start to see if we overlap. 1190 if (C2.getEndIdx() < C1.getStartIdx()) 1191 continue; 1192 1193 // C1 and C2 overlap. 1194 // We need to choose the better of the two. 1195 // 1196 // Approximate this by picking the one which would have saved us the 1197 // most instructions before any pruning. 1198 1199 // Is C2 a better candidate? 1200 if (C2.Benefit > C1.Benefit) { 1201 // Yes, so prune C1. Since C1 is dead, we don't have to compare it 1202 // against anything anymore, so break. 1203 prune(C1, FunctionList); 1204 break; 1205 } 1206 1207 // Prune C2 and move on to the next candidate. 1208 prune(C2, FunctionList); 1209 } 1210 } 1211 } 1212 1213 unsigned MachineOutliner::buildCandidateList( 1214 std::vector<std::shared_ptr<Candidate>> &CandidateList, 1215 std::vector<OutlinedFunction> &FunctionList, SuffixTree &ST, 1216 InstructionMapper &Mapper, const TargetInstrInfo &TII) { 1217 1218 std::vector<unsigned> CandidateSequence; // Current outlining candidate. 1219 unsigned MaxCandidateLen = 0; // Length of the longest candidate. 1220 1221 MaxCandidateLen = 1222 findCandidates(ST, TII, Mapper, CandidateList, FunctionList); 1223 1224 // Sort the candidates in decending order. This will simplify the outlining 1225 // process when we have to remove the candidates from the mapping by 1226 // allowing us to cut them out without keeping track of an offset. 1227 std::stable_sort( 1228 CandidateList.begin(), CandidateList.end(), 1229 [](const std::shared_ptr<Candidate> &LHS, 1230 const std::shared_ptr<Candidate> &RHS) { return *LHS < *RHS; }); 1231 1232 return MaxCandidateLen; 1233 } 1234 1235 MachineFunction * 1236 MachineOutliner::createOutlinedFunction(Module &M, const OutlinedFunction &OF, 1237 InstructionMapper &Mapper) { 1238 1239 // Create the function name. This should be unique. For now, just hash the 1240 // module name and include it in the function name plus the number of this 1241 // function. 1242 std::ostringstream NameStream; 1243 NameStream << "OUTLINED_FUNCTION_" << OF.Name; 1244 1245 // Create the function using an IR-level function. 1246 LLVMContext &C = M.getContext(); 1247 Function *F = dyn_cast<Function>( 1248 M.getOrInsertFunction(NameStream.str(), Type::getVoidTy(C))); 1249 assert(F && "Function was null!"); 1250 1251 // NOTE: If this is linkonceodr, then we can take advantage of linker deduping 1252 // which gives us better results when we outline from linkonceodr functions. 1253 F->setLinkage(GlobalValue::InternalLinkage); 1254 F->setUnnamedAddr(GlobalValue::UnnamedAddr::Global); 1255 1256 // FIXME: Set nounwind, so we don't generate eh_frame? Haven't verified it's 1257 // necessary. 1258 1259 // Set optsize/minsize, so we don't insert padding between outlined 1260 // functions. 1261 F->addFnAttr(Attribute::OptimizeForSize); 1262 F->addFnAttr(Attribute::MinSize); 1263 1264 // Save F so that we can add debug info later if we need to. 1265 CreatedIRFunctions.push_back(F); 1266 1267 BasicBlock *EntryBB = BasicBlock::Create(C, "entry", F); 1268 IRBuilder<> Builder(EntryBB); 1269 Builder.CreateRetVoid(); 1270 1271 MachineModuleInfo &MMI = getAnalysis<MachineModuleInfo>(); 1272 MachineFunction &MF = MMI.getOrCreateMachineFunction(*F); 1273 MachineBasicBlock &MBB = *MF.CreateMachineBasicBlock(); 1274 const TargetSubtargetInfo &STI = MF.getSubtarget(); 1275 const TargetInstrInfo &TII = *STI.getInstrInfo(); 1276 1277 // Insert the new function into the module. 1278 MF.insert(MF.begin(), &MBB); 1279 1280 TII.insertOutlinerPrologue(MBB, MF, OF.MInfo); 1281 1282 // Copy over the instructions for the function using the integer mappings in 1283 // its sequence. 1284 for (unsigned Str : OF.Sequence) { 1285 MachineInstr *NewMI = 1286 MF.CloneMachineInstr(Mapper.IntegerInstructionMap.find(Str)->second); 1287 NewMI->dropMemRefs(); 1288 1289 // Don't keep debug information for outlined instructions. 1290 NewMI->setDebugLoc(DebugLoc()); 1291 MBB.insert(MBB.end(), NewMI); 1292 } 1293 1294 TII.insertOutlinerEpilogue(MBB, MF, OF.MInfo); 1295 1296 // If there's a DISubprogram associated with this outlined function, then 1297 // emit debug info for the outlined function. 1298 if (DISubprogram *SP = OF.getSubprogramOrNull()) { 1299 // We have a DISubprogram. Get its DICompileUnit. 1300 DICompileUnit *CU = SP->getUnit(); 1301 DIBuilder DB(M, true, CU); 1302 DIFile *Unit = SP->getFile(); 1303 Mangler Mg; 1304 1305 // Walk over each IR function we created in the outliner and create 1306 // DISubprograms for each function. 1307 for (Function *F : CreatedIRFunctions) { 1308 // Get the mangled name of the function for the linkage name. 1309 std::string Dummy; 1310 llvm::raw_string_ostream MangledNameStream(Dummy); 1311 Mg.getNameWithPrefix(MangledNameStream, F, false); 1312 1313 DISubprogram *SP = DB.createFunction( 1314 Unit /* Context */, F->getName(), StringRef(MangledNameStream.str()), 1315 Unit /* File */, 1316 0 /* Line 0 is reserved for compiler-generated code. */, 1317 DB.createSubroutineType( 1318 DB.getOrCreateTypeArray(None)), /* void type */ 1319 false, true, 0, /* Line 0 is reserved for compiler-generated code. */ 1320 DINode::DIFlags::FlagArtificial /* Compiler-generated code. */, 1321 true /* Outlined code is optimized code by definition. */); 1322 1323 // Don't add any new variables to the subprogram. 1324 DB.finalizeSubprogram(SP); 1325 1326 // Attach subprogram to the function. 1327 F->setSubprogram(SP); 1328 } 1329 1330 // We're done with the DIBuilder. 1331 DB.finalize(); 1332 } 1333 1334 // Outlined functions shouldn't preserve liveness. 1335 MF.getProperties().reset(MachineFunctionProperties::Property::TracksLiveness); 1336 MF.getRegInfo().freezeReservedRegs(MF); 1337 return &MF; 1338 } 1339 1340 bool MachineOutliner::outline( 1341 Module &M, const ArrayRef<std::shared_ptr<Candidate>> &CandidateList, 1342 std::vector<OutlinedFunction> &FunctionList, InstructionMapper &Mapper) { 1343 1344 bool OutlinedSomething = false; 1345 // Replace the candidates with calls to their respective outlined functions. 1346 for (const std::shared_ptr<Candidate> &Cptr : CandidateList) { 1347 Candidate &C = *Cptr; 1348 // Was the candidate removed during pruneOverlaps? 1349 if (!C.InCandidateList) 1350 continue; 1351 1352 // If not, then look at its OutlinedFunction. 1353 OutlinedFunction &OF = FunctionList[C.FunctionIdx]; 1354 1355 // Was its OutlinedFunction made unbeneficial during pruneOverlaps? 1356 if (OF.getBenefit() < 1) 1357 continue; 1358 1359 // If not, then outline it. 1360 assert(C.getStartIdx() < Mapper.InstrList.size() && 1361 "Candidate out of bounds!"); 1362 MachineBasicBlock *MBB = (*Mapper.InstrList[C.getStartIdx()]).getParent(); 1363 MachineBasicBlock::iterator StartIt = Mapper.InstrList[C.getStartIdx()]; 1364 unsigned EndIdx = C.getEndIdx(); 1365 1366 assert(EndIdx < Mapper.InstrList.size() && "Candidate out of bounds!"); 1367 MachineBasicBlock::iterator EndIt = Mapper.InstrList[EndIdx]; 1368 assert(EndIt != MBB->end() && "EndIt out of bounds!"); 1369 1370 // Does this candidate have a function yet? 1371 if (!OF.MF) { 1372 OF.MF = createOutlinedFunction(M, OF, Mapper); 1373 MachineBasicBlock *MBB = &*OF.MF->begin(); 1374 1375 // Output a remark telling the user that an outlined function was created, 1376 // and explaining where it came from. 1377 MachineOptimizationRemarkEmitter MORE(*OF.MF, nullptr); 1378 MachineOptimizationRemark R(DEBUG_TYPE, "OutlinedFunction", 1379 MBB->findDebugLoc(MBB->begin()), MBB); 1380 R << "Saved " << NV("OutliningBenefit", OF.getBenefit()) 1381 << " instructions by " 1382 << "outlining " << NV("Length", OF.Sequence.size()) << " instructions " 1383 << "from " << NV("NumOccurrences", OF.getOccurrenceCount()) 1384 << " locations. " 1385 << "(Found at: "; 1386 1387 // Tell the user the other places the candidate was found. 1388 for (size_t i = 0, e = OF.Candidates.size(); i < e; i++) { 1389 1390 // Skip over things that were pruned. 1391 if (!OF.Candidates[i]->InCandidateList) 1392 continue; 1393 1394 R << NV( 1395 (Twine("StartLoc") + Twine(i)).str(), 1396 Mapper.InstrList[OF.Candidates[i]->getStartIdx()]->getDebugLoc()); 1397 if (i != e - 1) 1398 R << ", "; 1399 } 1400 1401 R << ")"; 1402 1403 MORE.emit(R); 1404 FunctionsCreated++; 1405 } 1406 1407 MachineFunction *MF = OF.MF; 1408 const TargetSubtargetInfo &STI = MF->getSubtarget(); 1409 const TargetInstrInfo &TII = *STI.getInstrInfo(); 1410 1411 // Insert a call to the new function and erase the old sequence. 1412 auto CallInst = TII.insertOutlinedCall(M, *MBB, StartIt, *MF, C.MInfo); 1413 StartIt = Mapper.InstrList[C.getStartIdx()]; 1414 1415 // If the caller tracks liveness, then we need to make sure that anything 1416 // we outline doesn't break liveness assumptions. 1417 // The outlined functions themselves currently don't track liveness, but 1418 // we should make sure that the ranges we yank things out of aren't 1419 // wrong. 1420 if (MBB->getParent()->getProperties().hasProperty( 1421 MachineFunctionProperties::Property::TracksLiveness)) { 1422 // Helper lambda for adding implicit def operands to the call instruction. 1423 auto CopyDefs = [&CallInst](MachineInstr &MI) { 1424 for (MachineOperand &MOP : MI.operands()) { 1425 // Skip over anything that isn't a register. 1426 if (!MOP.isReg()) 1427 continue; 1428 1429 // If it's a def, add it to the call instruction. 1430 if (MOP.isDef()) 1431 CallInst->addOperand( 1432 MachineOperand::CreateReg(MOP.getReg(), true, /* isDef = true */ 1433 true /* isImp = true */)); 1434 } 1435 }; 1436 1437 // Copy over the defs in the outlined range. 1438 // First inst in outlined range <-- Anything that's defined in this 1439 // ... .. range has to be added as an implicit 1440 // Last inst in outlined range <-- def to the call instruction. 1441 std::for_each(CallInst, EndIt, CopyDefs); 1442 } 1443 1444 EndIt++; // Erase needs one past the end index. 1445 MBB->erase(StartIt, EndIt); 1446 OutlinedSomething = true; 1447 1448 // Statistics. 1449 NumOutlined++; 1450 } 1451 1452 LLVM_DEBUG(dbgs() << "OutlinedSomething = " << OutlinedSomething << "\n";); 1453 1454 return OutlinedSomething; 1455 } 1456 1457 bool MachineOutliner::runOnModule(Module &M) { 1458 // Check if there's anything in the module. If it's empty, then there's 1459 // nothing to outline. 1460 if (M.empty()) 1461 return false; 1462 1463 MachineModuleInfo &MMI = getAnalysis<MachineModuleInfo>(); 1464 const TargetSubtargetInfo &STI = 1465 MMI.getOrCreateMachineFunction(*M.begin()).getSubtarget(); 1466 const TargetRegisterInfo *TRI = STI.getRegisterInfo(); 1467 const TargetInstrInfo *TII = STI.getInstrInfo(); 1468 1469 // Does the target implement the MachineOutliner? If it doesn't, quit here. 1470 if (!TII->useMachineOutliner()) { 1471 // No. So we're done. 1472 LLVM_DEBUG( 1473 dbgs() 1474 << "Skipping pass: Target does not support the MachineOutliner.\n"); 1475 return false; 1476 } 1477 1478 // If the user specifies that they want to outline from linkonceodrs, set 1479 // it here. 1480 OutlineFromLinkOnceODRs = EnableLinkOnceODROutlining; 1481 1482 InstructionMapper Mapper; 1483 1484 // Build instruction mappings for each function in the module. Start by 1485 // iterating over each Function in M. 1486 for (Function &F : M) { 1487 1488 // If there's nothing in F, then there's no reason to try and outline from 1489 // it. 1490 if (F.empty()) 1491 continue; 1492 1493 // There's something in F. Check if it has a MachineFunction associated with 1494 // it. 1495 MachineFunction *MF = MMI.getMachineFunction(F); 1496 1497 // If it doesn't, then there's nothing to outline from. Move to the next 1498 // Function. 1499 if (!MF) 1500 continue; 1501 1502 // We have a MachineFunction. Ask the target if it's suitable for outlining. 1503 // If it isn't, then move on to the next Function in the module. 1504 if (!TII->isFunctionSafeToOutlineFrom(*MF, OutlineFromLinkOnceODRs)) 1505 continue; 1506 1507 // We have a function suitable for outlining. Iterate over every 1508 // MachineBasicBlock in MF and try to map its instructions to a list of 1509 // unsigned integers. 1510 for (MachineBasicBlock &MBB : *MF) { 1511 // If there isn't anything in MBB, then there's no point in outlining from 1512 // it. 1513 if (MBB.empty()) 1514 continue; 1515 1516 // Check if MBB could be the target of an indirect branch. If it is, then 1517 // we don't want to outline from it. 1518 if (MBB.hasAddressTaken()) 1519 continue; 1520 1521 // MBB is suitable for outlining. Map it to a list of unsigneds. 1522 Mapper.convertToUnsignedVec(MBB, *TRI, *TII); 1523 } 1524 } 1525 1526 // Construct a suffix tree, use it to find candidates, and then outline them. 1527 SuffixTree ST(Mapper.UnsignedVec); 1528 std::vector<std::shared_ptr<Candidate>> CandidateList; 1529 std::vector<OutlinedFunction> FunctionList; 1530 1531 // Find all of the outlining candidates. 1532 unsigned MaxCandidateLen = 1533 buildCandidateList(CandidateList, FunctionList, ST, Mapper, *TII); 1534 1535 // Remove candidates that overlap with other candidates. 1536 pruneOverlaps(CandidateList, FunctionList, Mapper, MaxCandidateLen, *TII); 1537 1538 // Outline each of the candidates and return true if something was outlined. 1539 bool OutlinedSomething = outline(M, CandidateList, FunctionList, Mapper); 1540 1541 return OutlinedSomething; 1542 } 1543