17a7e6055SDimitry Andric //===---- MachineOutliner.cpp - Outline instructions -----------*- C++ -*-===//
27a7e6055SDimitry Andric //
37a7e6055SDimitry Andric //                     The LLVM Compiler Infrastructure
47a7e6055SDimitry Andric //
57a7e6055SDimitry Andric // This file is distributed under the University of Illinois Open Source
67a7e6055SDimitry Andric // License. See LICENSE.TXT for details.
77a7e6055SDimitry Andric //
87a7e6055SDimitry Andric //===----------------------------------------------------------------------===//
97a7e6055SDimitry Andric ///
107a7e6055SDimitry Andric /// \file
117a7e6055SDimitry Andric /// Replaces repeated sequences of instructions with function calls.
127a7e6055SDimitry Andric ///
137a7e6055SDimitry Andric /// This works by placing every instruction from every basic block in a
147a7e6055SDimitry Andric /// suffix tree, and repeatedly querying that tree for repeated sequences of
157a7e6055SDimitry Andric /// instructions. If a sequence of instructions appears often, then it ought
167a7e6055SDimitry Andric /// to be beneficial to pull out into a function.
177a7e6055SDimitry Andric ///
182cab237bSDimitry Andric /// The MachineOutliner communicates with a given target using hooks defined in
192cab237bSDimitry Andric /// TargetInstrInfo.h. The target supplies the outliner with information on how
202cab237bSDimitry Andric /// a specific sequence of instructions should be outlined. This information
212cab237bSDimitry Andric /// is used to deduce the number of instructions necessary to
222cab237bSDimitry Andric ///
232cab237bSDimitry Andric /// * Create an outlined function
242cab237bSDimitry Andric /// * Call that outlined function
252cab237bSDimitry Andric ///
262cab237bSDimitry Andric /// Targets must implement
272cab237bSDimitry Andric ///   * getOutliningCandidateInfo
284ba319b5SDimitry Andric ///   * buildOutlinedFrame
292cab237bSDimitry Andric ///   * insertOutlinedCall
302cab237bSDimitry Andric ///   * isFunctionSafeToOutlineFrom
312cab237bSDimitry Andric ///
322cab237bSDimitry Andric /// in order to make use of the MachineOutliner.
332cab237bSDimitry Andric ///
347a7e6055SDimitry Andric /// This was originally presented at the 2016 LLVM Developers' Meeting in the
357a7e6055SDimitry Andric /// talk "Reducing Code Size Using Outlining". For a high-level overview of
367a7e6055SDimitry Andric /// how this pass works, the talk is available on YouTube at
377a7e6055SDimitry Andric ///
387a7e6055SDimitry Andric /// https://www.youtube.com/watch?v=yorld-WSOeU
397a7e6055SDimitry Andric ///
407a7e6055SDimitry Andric /// The slides for the talk are available at
417a7e6055SDimitry Andric ///
427a7e6055SDimitry Andric /// http://www.llvm.org/devmtg/2016-11/Slides/Paquette-Outliner.pdf
437a7e6055SDimitry Andric ///
447a7e6055SDimitry Andric /// The talk provides an overview of how the outliner finds candidates and
457a7e6055SDimitry Andric /// ultimately outlines them. It describes how the main data structure for this
467a7e6055SDimitry Andric /// pass, the suffix tree, is queried and purged for candidates. It also gives
477a7e6055SDimitry Andric /// a simplified suffix tree construction algorithm for suffix trees based off
487a7e6055SDimitry Andric /// of the algorithm actually used here, Ukkonen's algorithm.
497a7e6055SDimitry Andric ///
507a7e6055SDimitry Andric /// For the original RFC for this pass, please see
517a7e6055SDimitry Andric ///
527a7e6055SDimitry Andric /// http://lists.llvm.org/pipermail/llvm-dev/2016-August/104170.html
537a7e6055SDimitry Andric ///
547a7e6055SDimitry Andric /// For more information on the suffix tree data structure, please see
557a7e6055SDimitry Andric /// https://www.cs.helsinki.fi/u/ukkonen/SuffixT1withFigs.pdf
567a7e6055SDimitry Andric ///
577a7e6055SDimitry Andric //===----------------------------------------------------------------------===//
584ba319b5SDimitry Andric #include "llvm/CodeGen/MachineOutliner.h"
597a7e6055SDimitry Andric #include "llvm/ADT/DenseMap.h"
607a7e6055SDimitry Andric #include "llvm/ADT/Statistic.h"
617a7e6055SDimitry Andric #include "llvm/ADT/Twine.h"
627a7e6055SDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
637a7e6055SDimitry Andric #include "llvm/CodeGen/MachineModuleInfo.h"
642cab237bSDimitry Andric #include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h"
654ba319b5SDimitry Andric #include "llvm/CodeGen/MachineRegisterInfo.h"
667a7e6055SDimitry Andric #include "llvm/CodeGen/Passes.h"
672cab237bSDimitry Andric #include "llvm/CodeGen/TargetInstrInfo.h"
682cab237bSDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h"
694ba319b5SDimitry Andric #include "llvm/IR/DIBuilder.h"
707a7e6055SDimitry Andric #include "llvm/IR/IRBuilder.h"
714ba319b5SDimitry Andric #include "llvm/IR/Mangler.h"
727a7e6055SDimitry Andric #include "llvm/Support/Allocator.h"
734ba319b5SDimitry Andric #include "llvm/Support/CommandLine.h"
747a7e6055SDimitry Andric #include "llvm/Support/Debug.h"
757a7e6055SDimitry Andric #include "llvm/Support/raw_ostream.h"
767a7e6055SDimitry Andric #include <functional>
777a7e6055SDimitry Andric #include <map>
787a7e6055SDimitry Andric #include <sstream>
797a7e6055SDimitry Andric #include <tuple>
807a7e6055SDimitry Andric #include <vector>
817a7e6055SDimitry Andric 
827a7e6055SDimitry Andric #define DEBUG_TYPE "machine-outliner"
837a7e6055SDimitry Andric 
847a7e6055SDimitry Andric using namespace llvm;
852cab237bSDimitry Andric using namespace ore;
864ba319b5SDimitry Andric using namespace outliner;
877a7e6055SDimitry Andric 
887a7e6055SDimitry Andric STATISTIC(NumOutlined, "Number of candidates outlined");
897a7e6055SDimitry Andric STATISTIC(FunctionsCreated, "Number of functions created");
907a7e6055SDimitry Andric 
914ba319b5SDimitry Andric // Set to true if the user wants the outliner to run on linkonceodr linkage
924ba319b5SDimitry Andric // functions. This is false by default because the linker can dedupe linkonceodr
934ba319b5SDimitry Andric // functions. Since the outliner is confined to a single module (modulo LTO),
944ba319b5SDimitry Andric // this is off by default. It should, however, be the default behaviour in
954ba319b5SDimitry Andric // LTO.
964ba319b5SDimitry Andric static cl::opt<bool> EnableLinkOnceODROutlining(
974ba319b5SDimitry Andric     "enable-linkonceodr-outlining",
984ba319b5SDimitry Andric     cl::Hidden,
994ba319b5SDimitry Andric     cl::desc("Enable the machine outliner on linkonceodr functions"),
1004ba319b5SDimitry Andric     cl::init(false));
1014ba319b5SDimitry Andric 
1027a7e6055SDimitry Andric namespace {
1037a7e6055SDimitry Andric 
1047a7e6055SDimitry Andric /// Represents an undefined index in the suffix tree.
1052cab237bSDimitry Andric const unsigned EmptyIdx = -1;
1067a7e6055SDimitry Andric 
1077a7e6055SDimitry Andric /// A node in a suffix tree which represents a substring or suffix.
1087a7e6055SDimitry Andric ///
1097a7e6055SDimitry Andric /// Each node has either no children or at least two children, with the root
1107a7e6055SDimitry Andric /// being a exception in the empty tree.
1117a7e6055SDimitry Andric ///
1127a7e6055SDimitry Andric /// Children are represented as a map between unsigned integers and nodes. If
1137a7e6055SDimitry Andric /// a node N has a child M on unsigned integer k, then the mapping represented
1147a7e6055SDimitry Andric /// by N is a proper prefix of the mapping represented by M. Note that this,
1157a7e6055SDimitry Andric /// although similar to a trie is somewhat different: each node stores a full
1167a7e6055SDimitry Andric /// substring of the full mapping rather than a single character state.
1177a7e6055SDimitry Andric ///
1187a7e6055SDimitry Andric /// Each internal node contains a pointer to the internal node representing
1197a7e6055SDimitry Andric /// the same string, but with the first character chopped off. This is stored
1207a7e6055SDimitry Andric /// in \p Link. Each leaf node stores the start index of its respective
1217a7e6055SDimitry Andric /// suffix in \p SuffixIdx.
1227a7e6055SDimitry Andric struct SuffixTreeNode {
1237a7e6055SDimitry Andric 
1247a7e6055SDimitry Andric   /// The children of this node.
1257a7e6055SDimitry Andric   ///
1267a7e6055SDimitry Andric   /// A child existing on an unsigned integer implies that from the mapping
1277a7e6055SDimitry Andric   /// represented by the current node, there is a way to reach another
1287a7e6055SDimitry Andric   /// mapping by tacking that character on the end of the current string.
1297a7e6055SDimitry Andric   DenseMap<unsigned, SuffixTreeNode *> Children;
1307a7e6055SDimitry Andric 
1317a7e6055SDimitry Andric   /// The start index of this node's substring in the main string.
1322cab237bSDimitry Andric   unsigned StartIdx = EmptyIdx;
1337a7e6055SDimitry Andric 
1347a7e6055SDimitry Andric   /// The end index of this node's substring in the main string.
1357a7e6055SDimitry Andric   ///
1367a7e6055SDimitry Andric   /// Every leaf node must have its \p EndIdx incremented at the end of every
1377a7e6055SDimitry Andric   /// step in the construction algorithm. To avoid having to update O(N)
1387a7e6055SDimitry Andric   /// nodes individually at the end of every step, the end index is stored
1397a7e6055SDimitry Andric   /// as a pointer.
1402cab237bSDimitry Andric   unsigned *EndIdx = nullptr;
1417a7e6055SDimitry Andric 
1427a7e6055SDimitry Andric   /// For leaves, the start index of the suffix represented by this node.
1437a7e6055SDimitry Andric   ///
1447a7e6055SDimitry Andric   /// For all other nodes, this is ignored.
1452cab237bSDimitry Andric   unsigned SuffixIdx = EmptyIdx;
1467a7e6055SDimitry Andric 
1474ba319b5SDimitry Andric   /// For internal nodes, a pointer to the internal node representing
1487a7e6055SDimitry Andric   /// the same sequence with the first character chopped off.
1497a7e6055SDimitry Andric   ///
1502cab237bSDimitry Andric   /// This acts as a shortcut in Ukkonen's algorithm. One of the things that
1517a7e6055SDimitry Andric   /// Ukkonen's algorithm does to achieve linear-time construction is
1527a7e6055SDimitry Andric   /// keep track of which node the next insert should be at. This makes each
1537a7e6055SDimitry Andric   /// insert O(1), and there are a total of O(N) inserts. The suffix link
1547a7e6055SDimitry Andric   /// helps with inserting children of internal nodes.
1557a7e6055SDimitry Andric   ///
1567a7e6055SDimitry Andric   /// Say we add a child to an internal node with associated mapping S. The
1577a7e6055SDimitry Andric   /// next insertion must be at the node representing S - its first character.
1587a7e6055SDimitry Andric   /// This is given by the way that we iteratively build the tree in Ukkonen's
1597a7e6055SDimitry Andric   /// algorithm. The main idea is to look at the suffixes of each prefix in the
1607a7e6055SDimitry Andric   /// string, starting with the longest suffix of the prefix, and ending with
1617a7e6055SDimitry Andric   /// the shortest. Therefore, if we keep pointers between such nodes, we can
1627a7e6055SDimitry Andric   /// move to the next insertion point in O(1) time. If we don't, then we'd
1637a7e6055SDimitry Andric   /// have to query from the root, which takes O(N) time. This would make the
1647a7e6055SDimitry Andric   /// construction algorithm O(N^2) rather than O(N).
1657a7e6055SDimitry Andric   SuffixTreeNode *Link = nullptr;
1667a7e6055SDimitry Andric 
1677a7e6055SDimitry Andric   /// The length of the string formed by concatenating the edge labels from the
1687a7e6055SDimitry Andric   /// root to this node.
1692cab237bSDimitry Andric   unsigned ConcatLen = 0;
1707a7e6055SDimitry Andric 
1717a7e6055SDimitry Andric   /// Returns true if this node is a leaf.
isLeaf__anon1330aca00111::SuffixTreeNode1727a7e6055SDimitry Andric   bool isLeaf() const { return SuffixIdx != EmptyIdx; }
1737a7e6055SDimitry Andric 
1747a7e6055SDimitry Andric   /// Returns true if this node is the root of its owning \p SuffixTree.
isRoot__anon1330aca00111::SuffixTreeNode1757a7e6055SDimitry Andric   bool isRoot() const { return StartIdx == EmptyIdx; }
1767a7e6055SDimitry Andric 
1777a7e6055SDimitry Andric   /// Return the number of elements in the substring associated with this node.
size__anon1330aca00111::SuffixTreeNode1787a7e6055SDimitry Andric   size_t size() const {
1797a7e6055SDimitry Andric 
1807a7e6055SDimitry Andric     // Is it the root? If so, it's the empty string so return 0.
1817a7e6055SDimitry Andric     if (isRoot())
1827a7e6055SDimitry Andric       return 0;
1837a7e6055SDimitry Andric 
1847a7e6055SDimitry Andric     assert(*EndIdx != EmptyIdx && "EndIdx is undefined!");
1857a7e6055SDimitry Andric 
1867a7e6055SDimitry Andric     // Size = the number of elements in the string.
1877a7e6055SDimitry Andric     // For example, [0 1 2 3] has length 4, not 3. 3-0 = 3, so we have 3-0+1.
1887a7e6055SDimitry Andric     return *EndIdx - StartIdx + 1;
1897a7e6055SDimitry Andric   }
1907a7e6055SDimitry Andric 
SuffixTreeNode__anon1330aca00111::SuffixTreeNode191*b5893f02SDimitry Andric   SuffixTreeNode(unsigned StartIdx, unsigned *EndIdx, SuffixTreeNode *Link)
192*b5893f02SDimitry Andric       : StartIdx(StartIdx), EndIdx(EndIdx), Link(Link) {}
1937a7e6055SDimitry Andric 
SuffixTreeNode__anon1330aca00111::SuffixTreeNode1947a7e6055SDimitry Andric   SuffixTreeNode() {}
1957a7e6055SDimitry Andric };
1967a7e6055SDimitry Andric 
1977a7e6055SDimitry Andric /// A data structure for fast substring queries.
1987a7e6055SDimitry Andric ///
1997a7e6055SDimitry Andric /// Suffix trees represent the suffixes of their input strings in their leaves.
2007a7e6055SDimitry Andric /// A suffix tree is a type of compressed trie structure where each node
2017a7e6055SDimitry Andric /// represents an entire substring rather than a single character. Each leaf
2027a7e6055SDimitry Andric /// of the tree is a suffix.
2037a7e6055SDimitry Andric ///
2047a7e6055SDimitry Andric /// A suffix tree can be seen as a type of state machine where each state is a
2057a7e6055SDimitry Andric /// substring of the full string. The tree is structured so that, for a string
2067a7e6055SDimitry Andric /// of length N, there are exactly N leaves in the tree. This structure allows
2077a7e6055SDimitry Andric /// us to quickly find repeated substrings of the input string.
2087a7e6055SDimitry Andric ///
2097a7e6055SDimitry Andric /// In this implementation, a "string" is a vector of unsigned integers.
2107a7e6055SDimitry Andric /// These integers may result from hashing some data type. A suffix tree can
2117a7e6055SDimitry Andric /// contain 1 or many strings, which can then be queried as one large string.
2127a7e6055SDimitry Andric ///
2137a7e6055SDimitry Andric /// The suffix tree is implemented using Ukkonen's algorithm for linear-time
2147a7e6055SDimitry Andric /// suffix tree construction. Ukkonen's algorithm is explained in more detail
2157a7e6055SDimitry Andric /// in the paper by Esko Ukkonen "On-line construction of suffix trees. The
2167a7e6055SDimitry Andric /// paper is available at
2177a7e6055SDimitry Andric ///
2187a7e6055SDimitry Andric /// https://www.cs.helsinki.fi/u/ukkonen/SuffixT1withFigs.pdf
2197a7e6055SDimitry Andric class SuffixTree {
2202cab237bSDimitry Andric public:
2217a7e6055SDimitry Andric   /// Each element is an integer representing an instruction in the module.
2227a7e6055SDimitry Andric   ArrayRef<unsigned> Str;
2237a7e6055SDimitry Andric 
224*b5893f02SDimitry Andric   /// A repeated substring in the tree.
225*b5893f02SDimitry Andric   struct RepeatedSubstring {
226*b5893f02SDimitry Andric     /// The length of the string.
227*b5893f02SDimitry Andric     unsigned Length;
228*b5893f02SDimitry Andric 
229*b5893f02SDimitry Andric     /// The start indices of each occurrence.
230*b5893f02SDimitry Andric     std::vector<unsigned> StartIndices;
231*b5893f02SDimitry Andric   };
232*b5893f02SDimitry Andric 
2332cab237bSDimitry Andric private:
2347a7e6055SDimitry Andric   /// Maintains each node in the tree.
2357a7e6055SDimitry Andric   SpecificBumpPtrAllocator<SuffixTreeNode> NodeAllocator;
2367a7e6055SDimitry Andric 
2377a7e6055SDimitry Andric   /// The root of the suffix tree.
2387a7e6055SDimitry Andric   ///
2397a7e6055SDimitry Andric   /// The root represents the empty string. It is maintained by the
2407a7e6055SDimitry Andric   /// \p NodeAllocator like every other node in the tree.
2417a7e6055SDimitry Andric   SuffixTreeNode *Root = nullptr;
2427a7e6055SDimitry Andric 
2437a7e6055SDimitry Andric   /// Maintains the end indices of the internal nodes in the tree.
2447a7e6055SDimitry Andric   ///
2457a7e6055SDimitry Andric   /// Each internal node is guaranteed to never have its end index change
2467a7e6055SDimitry Andric   /// during the construction algorithm; however, leaves must be updated at
2477a7e6055SDimitry Andric   /// every step. Therefore, we need to store leaf end indices by reference
2487a7e6055SDimitry Andric   /// to avoid updating O(N) leaves at every step of construction. Thus,
2497a7e6055SDimitry Andric   /// every internal node must be allocated its own end index.
2507a7e6055SDimitry Andric   BumpPtrAllocator InternalEndIdxAllocator;
2517a7e6055SDimitry Andric 
2527a7e6055SDimitry Andric   /// The end index of each leaf in the tree.
2532cab237bSDimitry Andric   unsigned LeafEndIdx = -1;
2547a7e6055SDimitry Andric 
2554ba319b5SDimitry Andric   /// Helper struct which keeps track of the next insertion point in
2567a7e6055SDimitry Andric   /// Ukkonen's algorithm.
2577a7e6055SDimitry Andric   struct ActiveState {
2587a7e6055SDimitry Andric     /// The next node to insert at.
2597a7e6055SDimitry Andric     SuffixTreeNode *Node;
2607a7e6055SDimitry Andric 
2617a7e6055SDimitry Andric     /// The index of the first character in the substring currently being added.
2622cab237bSDimitry Andric     unsigned Idx = EmptyIdx;
2637a7e6055SDimitry Andric 
2647a7e6055SDimitry Andric     /// The length of the substring we have to add at the current step.
2652cab237bSDimitry Andric     unsigned Len = 0;
2667a7e6055SDimitry Andric   };
2677a7e6055SDimitry Andric 
2684ba319b5SDimitry Andric   /// The point the next insertion will take place at in the
2697a7e6055SDimitry Andric   /// construction algorithm.
2707a7e6055SDimitry Andric   ActiveState Active;
2717a7e6055SDimitry Andric 
2727a7e6055SDimitry Andric   /// Allocate a leaf node and add it to the tree.
2737a7e6055SDimitry Andric   ///
2747a7e6055SDimitry Andric   /// \param Parent The parent of this node.
2757a7e6055SDimitry Andric   /// \param StartIdx The start index of this node's associated string.
2767a7e6055SDimitry Andric   /// \param Edge The label on the edge leaving \p Parent to this node.
2777a7e6055SDimitry Andric   ///
2787a7e6055SDimitry Andric   /// \returns A pointer to the allocated leaf node.
insertLeaf(SuffixTreeNode & Parent,unsigned StartIdx,unsigned Edge)2792cab237bSDimitry Andric   SuffixTreeNode *insertLeaf(SuffixTreeNode &Parent, unsigned StartIdx,
2807a7e6055SDimitry Andric                              unsigned Edge) {
2817a7e6055SDimitry Andric 
2827a7e6055SDimitry Andric     assert(StartIdx <= LeafEndIdx && "String can't start after it ends!");
2837a7e6055SDimitry Andric 
2842cab237bSDimitry Andric     SuffixTreeNode *N = new (NodeAllocator.Allocate())
285*b5893f02SDimitry Andric         SuffixTreeNode(StartIdx, &LeafEndIdx, nullptr);
2867a7e6055SDimitry Andric     Parent.Children[Edge] = N;
2877a7e6055SDimitry Andric 
2887a7e6055SDimitry Andric     return N;
2897a7e6055SDimitry Andric   }
2907a7e6055SDimitry Andric 
2917a7e6055SDimitry Andric   /// Allocate an internal node and add it to the tree.
2927a7e6055SDimitry Andric   ///
2937a7e6055SDimitry Andric   /// \param Parent The parent of this node. Only null when allocating the root.
2947a7e6055SDimitry Andric   /// \param StartIdx The start index of this node's associated string.
2957a7e6055SDimitry Andric   /// \param EndIdx The end index of this node's associated string.
2967a7e6055SDimitry Andric   /// \param Edge The label on the edge leaving \p Parent to this node.
2977a7e6055SDimitry Andric   ///
2987a7e6055SDimitry Andric   /// \returns A pointer to the allocated internal node.
insertInternalNode(SuffixTreeNode * Parent,unsigned StartIdx,unsigned EndIdx,unsigned Edge)2992cab237bSDimitry Andric   SuffixTreeNode *insertInternalNode(SuffixTreeNode *Parent, unsigned StartIdx,
3002cab237bSDimitry Andric                                      unsigned EndIdx, unsigned Edge) {
3017a7e6055SDimitry Andric 
3027a7e6055SDimitry Andric     assert(StartIdx <= EndIdx && "String can't start after it ends!");
3037a7e6055SDimitry Andric     assert(!(!Parent && StartIdx != EmptyIdx) &&
3047a7e6055SDimitry Andric            "Non-root internal nodes must have parents!");
3057a7e6055SDimitry Andric 
3062cab237bSDimitry Andric     unsigned *E = new (InternalEndIdxAllocator) unsigned(EndIdx);
3072cab237bSDimitry Andric     SuffixTreeNode *N = new (NodeAllocator.Allocate())
308*b5893f02SDimitry Andric         SuffixTreeNode(StartIdx, E, Root);
3097a7e6055SDimitry Andric     if (Parent)
3107a7e6055SDimitry Andric       Parent->Children[Edge] = N;
3117a7e6055SDimitry Andric 
3127a7e6055SDimitry Andric     return N;
3137a7e6055SDimitry Andric   }
3147a7e6055SDimitry Andric 
3154ba319b5SDimitry Andric   /// Set the suffix indices of the leaves to the start indices of their
316*b5893f02SDimitry Andric   /// respective suffixes.
3177a7e6055SDimitry Andric   ///
3187a7e6055SDimitry Andric   /// \param[in] CurrNode The node currently being visited.
319*b5893f02SDimitry Andric   /// \param CurrNodeLen The concatenation of all node sizes from the root to
320*b5893f02SDimitry Andric   /// this node. Used to produce suffix indices.
setSuffixIndices(SuffixTreeNode & CurrNode,unsigned CurrNodeLen)321*b5893f02SDimitry Andric   void setSuffixIndices(SuffixTreeNode &CurrNode, unsigned CurrNodeLen) {
3227a7e6055SDimitry Andric 
3237a7e6055SDimitry Andric     bool IsLeaf = CurrNode.Children.size() == 0 && !CurrNode.isRoot();
3247a7e6055SDimitry Andric 
325*b5893f02SDimitry Andric     // Store the concatenation of lengths down from the root.
326*b5893f02SDimitry Andric     CurrNode.ConcatLen = CurrNodeLen;
3277a7e6055SDimitry Andric     // Traverse the tree depth-first.
3287a7e6055SDimitry Andric     for (auto &ChildPair : CurrNode.Children) {
3297a7e6055SDimitry Andric       assert(ChildPair.second && "Node had a null child!");
330*b5893f02SDimitry Andric       setSuffixIndices(*ChildPair.second,
331*b5893f02SDimitry Andric                        CurrNodeLen + ChildPair.second->size());
3327a7e6055SDimitry Andric     }
3337a7e6055SDimitry Andric 
334*b5893f02SDimitry Andric     // Is this node a leaf? If it is, give it a suffix index.
335*b5893f02SDimitry Andric     if (IsLeaf)
336*b5893f02SDimitry Andric       CurrNode.SuffixIdx = Str.size() - CurrNodeLen;
3377a7e6055SDimitry Andric   }
3387a7e6055SDimitry Andric 
3394ba319b5SDimitry Andric   /// Construct the suffix tree for the prefix of the input ending at
3407a7e6055SDimitry Andric   /// \p EndIdx.
3417a7e6055SDimitry Andric   ///
3427a7e6055SDimitry Andric   /// Used to construct the full suffix tree iteratively. At the end of each
3437a7e6055SDimitry Andric   /// step, the constructed suffix tree is either a valid suffix tree, or a
3447a7e6055SDimitry Andric   /// suffix tree with implicit suffixes. At the end of the final step, the
3457a7e6055SDimitry Andric   /// suffix tree is a valid tree.
3467a7e6055SDimitry Andric   ///
3477a7e6055SDimitry Andric   /// \param EndIdx The end index of the current prefix in the main string.
3487a7e6055SDimitry Andric   /// \param SuffixesToAdd The number of suffixes that must be added
3497a7e6055SDimitry Andric   /// to complete the suffix tree at the current phase.
3507a7e6055SDimitry Andric   ///
3517a7e6055SDimitry Andric   /// \returns The number of suffixes that have not been added at the end of
3527a7e6055SDimitry Andric   /// this step.
extend(unsigned EndIdx,unsigned SuffixesToAdd)3532cab237bSDimitry Andric   unsigned extend(unsigned EndIdx, unsigned SuffixesToAdd) {
3547a7e6055SDimitry Andric     SuffixTreeNode *NeedsLink = nullptr;
3557a7e6055SDimitry Andric 
3567a7e6055SDimitry Andric     while (SuffixesToAdd > 0) {
3577a7e6055SDimitry Andric 
3587a7e6055SDimitry Andric       // Are we waiting to add anything other than just the last character?
3597a7e6055SDimitry Andric       if (Active.Len == 0) {
3607a7e6055SDimitry Andric         // If not, then say the active index is the end index.
3617a7e6055SDimitry Andric         Active.Idx = EndIdx;
3627a7e6055SDimitry Andric       }
3637a7e6055SDimitry Andric 
3647a7e6055SDimitry Andric       assert(Active.Idx <= EndIdx && "Start index can't be after end index!");
3657a7e6055SDimitry Andric 
3667a7e6055SDimitry Andric       // The first character in the current substring we're looking at.
3677a7e6055SDimitry Andric       unsigned FirstChar = Str[Active.Idx];
3687a7e6055SDimitry Andric 
3697a7e6055SDimitry Andric       // Have we inserted anything starting with FirstChar at the current node?
3707a7e6055SDimitry Andric       if (Active.Node->Children.count(FirstChar) == 0) {
3717a7e6055SDimitry Andric         // If not, then we can just insert a leaf and move too the next step.
3727a7e6055SDimitry Andric         insertLeaf(*Active.Node, EndIdx, FirstChar);
3737a7e6055SDimitry Andric 
3747a7e6055SDimitry Andric         // The active node is an internal node, and we visited it, so it must
3757a7e6055SDimitry Andric         // need a link if it doesn't have one.
3767a7e6055SDimitry Andric         if (NeedsLink) {
3777a7e6055SDimitry Andric           NeedsLink->Link = Active.Node;
3787a7e6055SDimitry Andric           NeedsLink = nullptr;
3797a7e6055SDimitry Andric         }
3807a7e6055SDimitry Andric       } else {
3817a7e6055SDimitry Andric         // There's a match with FirstChar, so look for the point in the tree to
3827a7e6055SDimitry Andric         // insert a new node.
3837a7e6055SDimitry Andric         SuffixTreeNode *NextNode = Active.Node->Children[FirstChar];
3847a7e6055SDimitry Andric 
3852cab237bSDimitry Andric         unsigned SubstringLen = NextNode->size();
3867a7e6055SDimitry Andric 
3877a7e6055SDimitry Andric         // Is the current suffix we're trying to insert longer than the size of
3887a7e6055SDimitry Andric         // the child we want to move to?
3897a7e6055SDimitry Andric         if (Active.Len >= SubstringLen) {
3907a7e6055SDimitry Andric           // If yes, then consume the characters we've seen and move to the next
3917a7e6055SDimitry Andric           // node.
3927a7e6055SDimitry Andric           Active.Idx += SubstringLen;
3937a7e6055SDimitry Andric           Active.Len -= SubstringLen;
3947a7e6055SDimitry Andric           Active.Node = NextNode;
3957a7e6055SDimitry Andric           continue;
3967a7e6055SDimitry Andric         }
3977a7e6055SDimitry Andric 
3987a7e6055SDimitry Andric         // Otherwise, the suffix we're trying to insert must be contained in the
3997a7e6055SDimitry Andric         // next node we want to move to.
4007a7e6055SDimitry Andric         unsigned LastChar = Str[EndIdx];
4017a7e6055SDimitry Andric 
4027a7e6055SDimitry Andric         // Is the string we're trying to insert a substring of the next node?
4037a7e6055SDimitry Andric         if (Str[NextNode->StartIdx + Active.Len] == LastChar) {
4047a7e6055SDimitry Andric           // If yes, then we're done for this step. Remember our insertion point
4057a7e6055SDimitry Andric           // and move to the next end index. At this point, we have an implicit
4067a7e6055SDimitry Andric           // suffix tree.
4077a7e6055SDimitry Andric           if (NeedsLink && !Active.Node->isRoot()) {
4087a7e6055SDimitry Andric             NeedsLink->Link = Active.Node;
4097a7e6055SDimitry Andric             NeedsLink = nullptr;
4107a7e6055SDimitry Andric           }
4117a7e6055SDimitry Andric 
4127a7e6055SDimitry Andric           Active.Len++;
4137a7e6055SDimitry Andric           break;
4147a7e6055SDimitry Andric         }
4157a7e6055SDimitry Andric 
4167a7e6055SDimitry Andric         // The string we're trying to insert isn't a substring of the next node,
4177a7e6055SDimitry Andric         // but matches up to a point. Split the node.
4187a7e6055SDimitry Andric         //
4197a7e6055SDimitry Andric         // For example, say we ended our search at a node n and we're trying to
4207a7e6055SDimitry Andric         // insert ABD. Then we'll create a new node s for AB, reduce n to just
4217a7e6055SDimitry Andric         // representing C, and insert a new leaf node l to represent d. This
4227a7e6055SDimitry Andric         // allows us to ensure that if n was a leaf, it remains a leaf.
4237a7e6055SDimitry Andric         //
4247a7e6055SDimitry Andric         //   | ABC  ---split--->  | AB
4257a7e6055SDimitry Andric         //   n                    s
4267a7e6055SDimitry Andric         //                     C / \ D
4277a7e6055SDimitry Andric         //                      n   l
4287a7e6055SDimitry Andric 
4297a7e6055SDimitry Andric         // The node s from the diagram
4307a7e6055SDimitry Andric         SuffixTreeNode *SplitNode =
4312cab237bSDimitry Andric             insertInternalNode(Active.Node, NextNode->StartIdx,
4322cab237bSDimitry Andric                                NextNode->StartIdx + Active.Len - 1, FirstChar);
4337a7e6055SDimitry Andric 
4347a7e6055SDimitry Andric         // Insert the new node representing the new substring into the tree as
4357a7e6055SDimitry Andric         // a child of the split node. This is the node l from the diagram.
4367a7e6055SDimitry Andric         insertLeaf(*SplitNode, EndIdx, LastChar);
4377a7e6055SDimitry Andric 
4387a7e6055SDimitry Andric         // Make the old node a child of the split node and update its start
4397a7e6055SDimitry Andric         // index. This is the node n from the diagram.
4407a7e6055SDimitry Andric         NextNode->StartIdx += Active.Len;
4417a7e6055SDimitry Andric         SplitNode->Children[Str[NextNode->StartIdx]] = NextNode;
4427a7e6055SDimitry Andric 
4437a7e6055SDimitry Andric         // SplitNode is an internal node, update the suffix link.
4447a7e6055SDimitry Andric         if (NeedsLink)
4457a7e6055SDimitry Andric           NeedsLink->Link = SplitNode;
4467a7e6055SDimitry Andric 
4477a7e6055SDimitry Andric         NeedsLink = SplitNode;
4487a7e6055SDimitry Andric       }
4497a7e6055SDimitry Andric 
4507a7e6055SDimitry Andric       // We've added something new to the tree, so there's one less suffix to
4517a7e6055SDimitry Andric       // add.
4527a7e6055SDimitry Andric       SuffixesToAdd--;
4537a7e6055SDimitry Andric 
4547a7e6055SDimitry Andric       if (Active.Node->isRoot()) {
4557a7e6055SDimitry Andric         if (Active.Len > 0) {
4567a7e6055SDimitry Andric           Active.Len--;
4577a7e6055SDimitry Andric           Active.Idx = EndIdx - SuffixesToAdd + 1;
4587a7e6055SDimitry Andric         }
4597a7e6055SDimitry Andric       } else {
4607a7e6055SDimitry Andric         // Start the next phase at the next smallest suffix.
4617a7e6055SDimitry Andric         Active.Node = Active.Node->Link;
4627a7e6055SDimitry Andric       }
4637a7e6055SDimitry Andric     }
4647a7e6055SDimitry Andric 
4657a7e6055SDimitry Andric     return SuffixesToAdd;
4667a7e6055SDimitry Andric   }
4677a7e6055SDimitry Andric 
4687a7e6055SDimitry Andric public:
4697a7e6055SDimitry Andric   /// Construct a suffix tree from a sequence of unsigned integers.
4707a7e6055SDimitry Andric   ///
4717a7e6055SDimitry Andric   /// \param Str The string to construct the suffix tree for.
SuffixTree(const std::vector<unsigned> & Str)4727a7e6055SDimitry Andric   SuffixTree(const std::vector<unsigned> &Str) : Str(Str) {
4737a7e6055SDimitry Andric     Root = insertInternalNode(nullptr, EmptyIdx, EmptyIdx, 0);
4747a7e6055SDimitry Andric     Active.Node = Root;
4757a7e6055SDimitry Andric 
4767a7e6055SDimitry Andric     // Keep track of the number of suffixes we have to add of the current
4777a7e6055SDimitry Andric     // prefix.
4782cab237bSDimitry Andric     unsigned SuffixesToAdd = 0;
4797a7e6055SDimitry Andric     Active.Node = Root;
4807a7e6055SDimitry Andric 
4817a7e6055SDimitry Andric     // Construct the suffix tree iteratively on each prefix of the string.
4827a7e6055SDimitry Andric     // PfxEndIdx is the end index of the current prefix.
4837a7e6055SDimitry Andric     // End is one past the last element in the string.
4842cab237bSDimitry Andric     for (unsigned PfxEndIdx = 0, End = Str.size(); PfxEndIdx < End;
4852cab237bSDimitry Andric          PfxEndIdx++) {
4867a7e6055SDimitry Andric       SuffixesToAdd++;
4877a7e6055SDimitry Andric       LeafEndIdx = PfxEndIdx; // Extend each of the leaves.
4887a7e6055SDimitry Andric       SuffixesToAdd = extend(PfxEndIdx, SuffixesToAdd);
4897a7e6055SDimitry Andric     }
4907a7e6055SDimitry Andric 
4917a7e6055SDimitry Andric     // Set the suffix indices of each leaf.
4927a7e6055SDimitry Andric     assert(Root && "Root node can't be nullptr!");
4937a7e6055SDimitry Andric     setSuffixIndices(*Root, 0);
4947a7e6055SDimitry Andric   }
495*b5893f02SDimitry Andric 
496*b5893f02SDimitry Andric 
497*b5893f02SDimitry Andric   /// Iterator for finding all repeated substrings in the suffix tree.
498*b5893f02SDimitry Andric   struct RepeatedSubstringIterator {
499*b5893f02SDimitry Andric     private:
500*b5893f02SDimitry Andric     /// The current node we're visiting.
501*b5893f02SDimitry Andric     SuffixTreeNode *N = nullptr;
502*b5893f02SDimitry Andric 
503*b5893f02SDimitry Andric     /// The repeated substring associated with this node.
504*b5893f02SDimitry Andric     RepeatedSubstring RS;
505*b5893f02SDimitry Andric 
506*b5893f02SDimitry Andric     /// The nodes left to visit.
507*b5893f02SDimitry Andric     std::vector<SuffixTreeNode *> ToVisit;
508*b5893f02SDimitry Andric 
509*b5893f02SDimitry Andric     /// The minimum length of a repeated substring to find.
510*b5893f02SDimitry Andric     /// Since we're outlining, we want at least two instructions in the range.
511*b5893f02SDimitry Andric     /// FIXME: This may not be true for targets like X86 which support many
512*b5893f02SDimitry Andric     /// instruction lengths.
513*b5893f02SDimitry Andric     const unsigned MinLength = 2;
514*b5893f02SDimitry Andric 
515*b5893f02SDimitry Andric     /// Move the iterator to the next repeated substring.
advance__anon1330aca00111::SuffixTree::RepeatedSubstringIterator516*b5893f02SDimitry Andric     void advance() {
517*b5893f02SDimitry Andric       // Clear the current state. If we're at the end of the range, then this
518*b5893f02SDimitry Andric       // is the state we want to be in.
519*b5893f02SDimitry Andric       RS = RepeatedSubstring();
520*b5893f02SDimitry Andric       N = nullptr;
521*b5893f02SDimitry Andric 
522*b5893f02SDimitry Andric       // Each leaf node represents a repeat of a string.
523*b5893f02SDimitry Andric       std::vector<SuffixTreeNode *> LeafChildren;
524*b5893f02SDimitry Andric 
525*b5893f02SDimitry Andric       // Continue visiting nodes until we find one which repeats more than once.
526*b5893f02SDimitry Andric       while (!ToVisit.empty()) {
527*b5893f02SDimitry Andric         SuffixTreeNode *Curr = ToVisit.back();
528*b5893f02SDimitry Andric         ToVisit.pop_back();
529*b5893f02SDimitry Andric         LeafChildren.clear();
530*b5893f02SDimitry Andric 
531*b5893f02SDimitry Andric         // Keep track of the length of the string associated with the node. If
532*b5893f02SDimitry Andric         // it's too short, we'll quit.
533*b5893f02SDimitry Andric         unsigned Length = Curr->ConcatLen;
534*b5893f02SDimitry Andric 
535*b5893f02SDimitry Andric         // Iterate over each child, saving internal nodes for visiting, and
536*b5893f02SDimitry Andric         // leaf nodes in LeafChildren. Internal nodes represent individual
537*b5893f02SDimitry Andric         // strings, which may repeat.
538*b5893f02SDimitry Andric         for (auto &ChildPair : Curr->Children) {
539*b5893f02SDimitry Andric           // Save all of this node's children for processing.
540*b5893f02SDimitry Andric           if (!ChildPair.second->isLeaf())
541*b5893f02SDimitry Andric             ToVisit.push_back(ChildPair.second);
542*b5893f02SDimitry Andric 
543*b5893f02SDimitry Andric           // It's not an internal node, so it must be a leaf. If we have a
544*b5893f02SDimitry Andric           // long enough string, then save the leaf children.
545*b5893f02SDimitry Andric           else if (Length >= MinLength)
546*b5893f02SDimitry Andric             LeafChildren.push_back(ChildPair.second);
547*b5893f02SDimitry Andric         }
548*b5893f02SDimitry Andric 
549*b5893f02SDimitry Andric         // The root never represents a repeated substring. If we're looking at
550*b5893f02SDimitry Andric         // that, then skip it.
551*b5893f02SDimitry Andric         if (Curr->isRoot())
552*b5893f02SDimitry Andric           continue;
553*b5893f02SDimitry Andric 
554*b5893f02SDimitry Andric         // Do we have any repeated substrings?
555*b5893f02SDimitry Andric         if (LeafChildren.size() >= 2) {
556*b5893f02SDimitry Andric           // Yes. Update the state to reflect this, and then bail out.
557*b5893f02SDimitry Andric           N = Curr;
558*b5893f02SDimitry Andric           RS.Length = Length;
559*b5893f02SDimitry Andric           for (SuffixTreeNode *Leaf : LeafChildren)
560*b5893f02SDimitry Andric             RS.StartIndices.push_back(Leaf->SuffixIdx);
561*b5893f02SDimitry Andric           break;
562*b5893f02SDimitry Andric         }
563*b5893f02SDimitry Andric       }
564*b5893f02SDimitry Andric 
565*b5893f02SDimitry Andric       // At this point, either NewRS is an empty RepeatedSubstring, or it was
566*b5893f02SDimitry Andric       // set in the above loop. Similarly, N is either nullptr, or the node
567*b5893f02SDimitry Andric       // associated with NewRS.
568*b5893f02SDimitry Andric     }
569*b5893f02SDimitry Andric 
570*b5893f02SDimitry Andric   public:
571*b5893f02SDimitry Andric     /// Return the current repeated substring.
operator *__anon1330aca00111::SuffixTree::RepeatedSubstringIterator572*b5893f02SDimitry Andric     RepeatedSubstring &operator*() { return RS; }
573*b5893f02SDimitry Andric 
operator ++__anon1330aca00111::SuffixTree::RepeatedSubstringIterator574*b5893f02SDimitry Andric     RepeatedSubstringIterator &operator++() {
575*b5893f02SDimitry Andric       advance();
576*b5893f02SDimitry Andric       return *this;
577*b5893f02SDimitry Andric     }
578*b5893f02SDimitry Andric 
operator ++__anon1330aca00111::SuffixTree::RepeatedSubstringIterator579*b5893f02SDimitry Andric     RepeatedSubstringIterator operator++(int I) {
580*b5893f02SDimitry Andric       RepeatedSubstringIterator It(*this);
581*b5893f02SDimitry Andric       advance();
582*b5893f02SDimitry Andric       return It;
583*b5893f02SDimitry Andric     }
584*b5893f02SDimitry Andric 
operator ==__anon1330aca00111::SuffixTree::RepeatedSubstringIterator585*b5893f02SDimitry Andric     bool operator==(const RepeatedSubstringIterator &Other) {
586*b5893f02SDimitry Andric       return N == Other.N;
587*b5893f02SDimitry Andric     }
operator !=__anon1330aca00111::SuffixTree::RepeatedSubstringIterator588*b5893f02SDimitry Andric     bool operator!=(const RepeatedSubstringIterator &Other) {
589*b5893f02SDimitry Andric       return !(*this == Other);
590*b5893f02SDimitry Andric     }
591*b5893f02SDimitry Andric 
RepeatedSubstringIterator__anon1330aca00111::SuffixTree::RepeatedSubstringIterator592*b5893f02SDimitry Andric     RepeatedSubstringIterator(SuffixTreeNode *N) : N(N) {
593*b5893f02SDimitry Andric       // Do we have a non-null node?
594*b5893f02SDimitry Andric       if (N) {
595*b5893f02SDimitry Andric         // Yes. At the first step, we need to visit all of N's children.
596*b5893f02SDimitry Andric         // Note: This means that we visit N last.
597*b5893f02SDimitry Andric         ToVisit.push_back(N);
598*b5893f02SDimitry Andric         advance();
599*b5893f02SDimitry Andric       }
600*b5893f02SDimitry Andric     }
601*b5893f02SDimitry Andric };
602*b5893f02SDimitry Andric 
603*b5893f02SDimitry Andric   typedef RepeatedSubstringIterator iterator;
begin()604*b5893f02SDimitry Andric   iterator begin() { return iterator(Root); }
end()605*b5893f02SDimitry Andric   iterator end() { return iterator(nullptr); }
6067a7e6055SDimitry Andric };
6077a7e6055SDimitry Andric 
6084ba319b5SDimitry Andric /// Maps \p MachineInstrs to unsigned integers and stores the mappings.
6097a7e6055SDimitry Andric struct InstructionMapper {
6107a7e6055SDimitry Andric 
6114ba319b5SDimitry Andric   /// The next available integer to assign to a \p MachineInstr that
6127a7e6055SDimitry Andric   /// cannot be outlined.
6137a7e6055SDimitry Andric   ///
6147a7e6055SDimitry Andric   /// Set to -3 for compatability with \p DenseMapInfo<unsigned>.
6157a7e6055SDimitry Andric   unsigned IllegalInstrNumber = -3;
6167a7e6055SDimitry Andric 
6174ba319b5SDimitry Andric   /// The next available integer to assign to a \p MachineInstr that can
6187a7e6055SDimitry Andric   /// be outlined.
6197a7e6055SDimitry Andric   unsigned LegalInstrNumber = 0;
6207a7e6055SDimitry Andric 
6217a7e6055SDimitry Andric   /// Correspondence from \p MachineInstrs to unsigned integers.
6227a7e6055SDimitry Andric   DenseMap<MachineInstr *, unsigned, MachineInstrExpressionTrait>
6237a7e6055SDimitry Andric       InstructionIntegerMap;
6247a7e6055SDimitry Andric 
625*b5893f02SDimitry Andric   /// Correspondence between \p MachineBasicBlocks and target-defined flags.
626*b5893f02SDimitry Andric   DenseMap<MachineBasicBlock *, unsigned> MBBFlagsMap;
6277a7e6055SDimitry Andric 
6287a7e6055SDimitry Andric   /// The vector of unsigned integers that the module is mapped to.
6297a7e6055SDimitry Andric   std::vector<unsigned> UnsignedVec;
6307a7e6055SDimitry Andric 
6314ba319b5SDimitry Andric   /// Stores the location of the instruction associated with the integer
6327a7e6055SDimitry Andric   /// at index i in \p UnsignedVec for each index i.
6337a7e6055SDimitry Andric   std::vector<MachineBasicBlock::iterator> InstrList;
6347a7e6055SDimitry Andric 
635*b5893f02SDimitry Andric   // Set if we added an illegal number in the previous step.
636*b5893f02SDimitry Andric   // Since each illegal number is unique, we only need one of them between
637*b5893f02SDimitry Andric   // each range of legal numbers. This lets us make sure we don't add more
638*b5893f02SDimitry Andric   // than one illegal number per range.
639*b5893f02SDimitry Andric   bool AddedIllegalLastTime = false;
640*b5893f02SDimitry Andric 
6414ba319b5SDimitry Andric   /// Maps \p *It to a legal integer.
6427a7e6055SDimitry Andric   ///
643*b5893f02SDimitry Andric   /// Updates \p CanOutlineWithPrevInstr, \p HaveLegalRange, \p InstrListForMBB,
644*b5893f02SDimitry Andric   /// \p UnsignedVecForMBB, \p InstructionIntegerMap, and \p LegalInstrNumber.
6457a7e6055SDimitry Andric   ///
6467a7e6055SDimitry Andric   /// \returns The integer that \p *It was mapped to.
mapToLegalUnsigned__anon1330aca00111::InstructionMapper647*b5893f02SDimitry Andric   unsigned mapToLegalUnsigned(
648*b5893f02SDimitry Andric       MachineBasicBlock::iterator &It, bool &CanOutlineWithPrevInstr,
649*b5893f02SDimitry Andric       bool &HaveLegalRange, unsigned &NumLegalInBlock,
650*b5893f02SDimitry Andric       std::vector<unsigned> &UnsignedVecForMBB,
651*b5893f02SDimitry Andric       std::vector<MachineBasicBlock::iterator> &InstrListForMBB) {
652*b5893f02SDimitry Andric     // We added something legal, so we should unset the AddedLegalLastTime
653*b5893f02SDimitry Andric     // flag.
654*b5893f02SDimitry Andric     AddedIllegalLastTime = false;
655*b5893f02SDimitry Andric 
656*b5893f02SDimitry Andric     // If we have at least two adjacent legal instructions (which may have
657*b5893f02SDimitry Andric     // invisible instructions in between), remember that.
658*b5893f02SDimitry Andric     if (CanOutlineWithPrevInstr)
659*b5893f02SDimitry Andric       HaveLegalRange = true;
660*b5893f02SDimitry Andric     CanOutlineWithPrevInstr = true;
661*b5893f02SDimitry Andric 
662*b5893f02SDimitry Andric     // Keep track of the number of legal instructions we insert.
663*b5893f02SDimitry Andric     NumLegalInBlock++;
6647a7e6055SDimitry Andric 
6657a7e6055SDimitry Andric     // Get the integer for this instruction or give it the current
6667a7e6055SDimitry Andric     // LegalInstrNumber.
667*b5893f02SDimitry Andric     InstrListForMBB.push_back(It);
6687a7e6055SDimitry Andric     MachineInstr &MI = *It;
6697a7e6055SDimitry Andric     bool WasInserted;
6707a7e6055SDimitry Andric     DenseMap<MachineInstr *, unsigned, MachineInstrExpressionTrait>::iterator
6717a7e6055SDimitry Andric         ResultIt;
6727a7e6055SDimitry Andric     std::tie(ResultIt, WasInserted) =
6737a7e6055SDimitry Andric         InstructionIntegerMap.insert(std::make_pair(&MI, LegalInstrNumber));
6747a7e6055SDimitry Andric     unsigned MINumber = ResultIt->second;
6757a7e6055SDimitry Andric 
6767a7e6055SDimitry Andric     // There was an insertion.
677*b5893f02SDimitry Andric     if (WasInserted)
6787a7e6055SDimitry Andric       LegalInstrNumber++;
6797a7e6055SDimitry Andric 
680*b5893f02SDimitry Andric     UnsignedVecForMBB.push_back(MINumber);
6817a7e6055SDimitry Andric 
6827a7e6055SDimitry Andric     // Make sure we don't overflow or use any integers reserved by the DenseMap.
6837a7e6055SDimitry Andric     if (LegalInstrNumber >= IllegalInstrNumber)
6847a7e6055SDimitry Andric       report_fatal_error("Instruction mapping overflow!");
6857a7e6055SDimitry Andric 
6862cab237bSDimitry Andric     assert(LegalInstrNumber != DenseMapInfo<unsigned>::getEmptyKey() &&
6872cab237bSDimitry Andric            "Tried to assign DenseMap tombstone or empty key to instruction.");
6882cab237bSDimitry Andric     assert(LegalInstrNumber != DenseMapInfo<unsigned>::getTombstoneKey() &&
6892cab237bSDimitry Andric            "Tried to assign DenseMap tombstone or empty key to instruction.");
6907a7e6055SDimitry Andric 
6917a7e6055SDimitry Andric     return MINumber;
6927a7e6055SDimitry Andric   }
6937a7e6055SDimitry Andric 
6947a7e6055SDimitry Andric   /// Maps \p *It to an illegal integer.
6957a7e6055SDimitry Andric   ///
696*b5893f02SDimitry Andric   /// Updates \p InstrListForMBB, \p UnsignedVecForMBB, and \p
697*b5893f02SDimitry Andric   /// IllegalInstrNumber.
6987a7e6055SDimitry Andric   ///
6997a7e6055SDimitry Andric   /// \returns The integer that \p *It was mapped to.
mapToIllegalUnsigned__anon1330aca00111::InstructionMapper700*b5893f02SDimitry Andric   unsigned mapToIllegalUnsigned(MachineBasicBlock::iterator &It,
701*b5893f02SDimitry Andric   bool &CanOutlineWithPrevInstr, std::vector<unsigned> &UnsignedVecForMBB,
702*b5893f02SDimitry Andric   std::vector<MachineBasicBlock::iterator> &InstrListForMBB) {
703*b5893f02SDimitry Andric     // Can't outline an illegal instruction. Set the flag.
704*b5893f02SDimitry Andric     CanOutlineWithPrevInstr = false;
705*b5893f02SDimitry Andric 
706*b5893f02SDimitry Andric     // Only add one illegal number per range of legal numbers.
707*b5893f02SDimitry Andric     if (AddedIllegalLastTime)
708*b5893f02SDimitry Andric       return IllegalInstrNumber;
709*b5893f02SDimitry Andric 
710*b5893f02SDimitry Andric     // Remember that we added an illegal number last time.
711*b5893f02SDimitry Andric     AddedIllegalLastTime = true;
7127a7e6055SDimitry Andric     unsigned MINumber = IllegalInstrNumber;
7137a7e6055SDimitry Andric 
714*b5893f02SDimitry Andric     InstrListForMBB.push_back(It);
715*b5893f02SDimitry Andric     UnsignedVecForMBB.push_back(IllegalInstrNumber);
7167a7e6055SDimitry Andric     IllegalInstrNumber--;
7177a7e6055SDimitry Andric 
7187a7e6055SDimitry Andric     assert(LegalInstrNumber < IllegalInstrNumber &&
7197a7e6055SDimitry Andric            "Instruction mapping overflow!");
7207a7e6055SDimitry Andric 
7212cab237bSDimitry Andric     assert(IllegalInstrNumber != DenseMapInfo<unsigned>::getEmptyKey() &&
7227a7e6055SDimitry Andric            "IllegalInstrNumber cannot be DenseMap tombstone or empty key!");
7237a7e6055SDimitry Andric 
7242cab237bSDimitry Andric     assert(IllegalInstrNumber != DenseMapInfo<unsigned>::getTombstoneKey() &&
7257a7e6055SDimitry Andric            "IllegalInstrNumber cannot be DenseMap tombstone or empty key!");
7267a7e6055SDimitry Andric 
7277a7e6055SDimitry Andric     return MINumber;
7287a7e6055SDimitry Andric   }
7297a7e6055SDimitry Andric 
7304ba319b5SDimitry Andric   /// Transforms a \p MachineBasicBlock into a \p vector of \p unsigneds
7317a7e6055SDimitry Andric   /// and appends it to \p UnsignedVec and \p InstrList.
7327a7e6055SDimitry Andric   ///
7337a7e6055SDimitry Andric   /// Two instructions are assigned the same integer if they are identical.
7347a7e6055SDimitry Andric   /// If an instruction is deemed unsafe to outline, then it will be assigned an
7357a7e6055SDimitry Andric   /// unique integer. The resulting mapping is placed into a suffix tree and
7367a7e6055SDimitry Andric   /// queried for candidates.
7377a7e6055SDimitry Andric   ///
7387a7e6055SDimitry Andric   /// \param MBB The \p MachineBasicBlock to be translated into integers.
7394ba319b5SDimitry Andric   /// \param TII \p TargetInstrInfo for the function.
convertToUnsignedVec__anon1330aca00111::InstructionMapper7407a7e6055SDimitry Andric   void convertToUnsignedVec(MachineBasicBlock &MBB,
7417a7e6055SDimitry Andric                             const TargetInstrInfo &TII) {
742*b5893f02SDimitry Andric     unsigned Flags = 0;
7434ba319b5SDimitry Andric 
744*b5893f02SDimitry Andric     // Don't even map in this case.
745*b5893f02SDimitry Andric     if (!TII.isMBBSafeToOutlineFrom(MBB, Flags))
746*b5893f02SDimitry Andric       return;
7477a7e6055SDimitry Andric 
748*b5893f02SDimitry Andric     // Store info for the MBB for later outlining.
749*b5893f02SDimitry Andric     MBBFlagsMap[&MBB] = Flags;
750*b5893f02SDimitry Andric 
751*b5893f02SDimitry Andric     MachineBasicBlock::iterator It = MBB.begin();
752*b5893f02SDimitry Andric 
753*b5893f02SDimitry Andric     // The number of instructions in this block that will be considered for
754*b5893f02SDimitry Andric     // outlining.
755*b5893f02SDimitry Andric     unsigned NumLegalInBlock = 0;
756*b5893f02SDimitry Andric 
757*b5893f02SDimitry Andric     // True if we have at least two legal instructions which aren't separated
758*b5893f02SDimitry Andric     // by an illegal instruction.
759*b5893f02SDimitry Andric     bool HaveLegalRange = false;
760*b5893f02SDimitry Andric 
761*b5893f02SDimitry Andric     // True if we can perform outlining given the last mapped (non-invisible)
762*b5893f02SDimitry Andric     // instruction. This lets us know if we have a legal range.
763*b5893f02SDimitry Andric     bool CanOutlineWithPrevInstr = false;
764*b5893f02SDimitry Andric 
765*b5893f02SDimitry Andric     // FIXME: Should this all just be handled in the target, rather than using
766*b5893f02SDimitry Andric     // repeated calls to getOutliningType?
767*b5893f02SDimitry Andric     std::vector<unsigned> UnsignedVecForMBB;
768*b5893f02SDimitry Andric     std::vector<MachineBasicBlock::iterator> InstrListForMBB;
769*b5893f02SDimitry Andric 
770*b5893f02SDimitry Andric     for (MachineBasicBlock::iterator Et = MBB.end(); It != Et; It++) {
7717a7e6055SDimitry Andric       // Keep track of where this instruction is in the module.
7724ba319b5SDimitry Andric       switch (TII.getOutliningType(It, Flags)) {
7734ba319b5SDimitry Andric       case InstrType::Illegal:
774*b5893f02SDimitry Andric         mapToIllegalUnsigned(It, CanOutlineWithPrevInstr,
775*b5893f02SDimitry Andric                              UnsignedVecForMBB, InstrListForMBB);
7767a7e6055SDimitry Andric         break;
7777a7e6055SDimitry Andric 
7784ba319b5SDimitry Andric       case InstrType::Legal:
779*b5893f02SDimitry Andric         mapToLegalUnsigned(It, CanOutlineWithPrevInstr, HaveLegalRange,
780*b5893f02SDimitry Andric                            NumLegalInBlock, UnsignedVecForMBB, InstrListForMBB);
7817a7e6055SDimitry Andric         break;
7827a7e6055SDimitry Andric 
7834ba319b5SDimitry Andric       case InstrType::LegalTerminator:
784*b5893f02SDimitry Andric         mapToLegalUnsigned(It, CanOutlineWithPrevInstr, HaveLegalRange,
785*b5893f02SDimitry Andric                            NumLegalInBlock, UnsignedVecForMBB, InstrListForMBB);
786*b5893f02SDimitry Andric         // The instruction also acts as a terminator, so we have to record that
787*b5893f02SDimitry Andric         // in the string.
788*b5893f02SDimitry Andric         mapToIllegalUnsigned(It, CanOutlineWithPrevInstr, UnsignedVecForMBB,
789*b5893f02SDimitry Andric         InstrListForMBB);
7904ba319b5SDimitry Andric         break;
7914ba319b5SDimitry Andric 
7924ba319b5SDimitry Andric       case InstrType::Invisible:
793*b5893f02SDimitry Andric         // Normally this is set by mapTo(Blah)Unsigned, but we just want to
794*b5893f02SDimitry Andric         // skip this instruction. So, unset the flag here.
795*b5893f02SDimitry Andric         AddedIllegalLastTime = false;
7967a7e6055SDimitry Andric         break;
7977a7e6055SDimitry Andric       }
7987a7e6055SDimitry Andric     }
7997a7e6055SDimitry Andric 
800*b5893f02SDimitry Andric     // Are there enough legal instructions in the block for outlining to be
801*b5893f02SDimitry Andric     // possible?
802*b5893f02SDimitry Andric     if (HaveLegalRange) {
8037a7e6055SDimitry Andric       // After we're done every insertion, uniquely terminate this part of the
8047a7e6055SDimitry Andric       // "string". This makes sure we won't match across basic block or function
8057a7e6055SDimitry Andric       // boundaries since the "end" is encoded uniquely and thus appears in no
8067a7e6055SDimitry Andric       // repeated substring.
807*b5893f02SDimitry Andric       mapToIllegalUnsigned(It, CanOutlineWithPrevInstr, UnsignedVecForMBB,
808*b5893f02SDimitry Andric       InstrListForMBB);
809*b5893f02SDimitry Andric       InstrList.insert(InstrList.end(), InstrListForMBB.begin(),
810*b5893f02SDimitry Andric                        InstrListForMBB.end());
811*b5893f02SDimitry Andric       UnsignedVec.insert(UnsignedVec.end(), UnsignedVecForMBB.begin(),
812*b5893f02SDimitry Andric                          UnsignedVecForMBB.end());
813*b5893f02SDimitry Andric     }
8147a7e6055SDimitry Andric   }
8157a7e6055SDimitry Andric 
InstructionMapper__anon1330aca00111::InstructionMapper8167a7e6055SDimitry Andric   InstructionMapper() {
8177a7e6055SDimitry Andric     // Make sure that the implementation of DenseMapInfo<unsigned> hasn't
8187a7e6055SDimitry Andric     // changed.
8197a7e6055SDimitry Andric     assert(DenseMapInfo<unsigned>::getEmptyKey() == (unsigned)-1 &&
8207a7e6055SDimitry Andric            "DenseMapInfo<unsigned>'s empty key isn't -1!");
8217a7e6055SDimitry Andric     assert(DenseMapInfo<unsigned>::getTombstoneKey() == (unsigned)-2 &&
8227a7e6055SDimitry Andric            "DenseMapInfo<unsigned>'s tombstone key isn't -2!");
8237a7e6055SDimitry Andric   }
8247a7e6055SDimitry Andric };
8257a7e6055SDimitry Andric 
8264ba319b5SDimitry Andric /// An interprocedural pass which finds repeated sequences of
8277a7e6055SDimitry Andric /// instructions and replaces them with calls to functions.
8287a7e6055SDimitry Andric ///
8297a7e6055SDimitry Andric /// Each instruction is mapped to an unsigned integer and placed in a string.
8307a7e6055SDimitry Andric /// The resulting mapping is then placed in a \p SuffixTree. The \p SuffixTree
8317a7e6055SDimitry Andric /// is then repeatedly queried for repeated sequences of instructions. Each
8327a7e6055SDimitry Andric /// non-overlapping repeated sequence is then placed in its own
8337a7e6055SDimitry Andric /// \p MachineFunction and each instance is then replaced with a call to that
8347a7e6055SDimitry Andric /// function.
8357a7e6055SDimitry Andric struct MachineOutliner : public ModulePass {
8367a7e6055SDimitry Andric 
8377a7e6055SDimitry Andric   static char ID;
8387a7e6055SDimitry Andric 
8394ba319b5SDimitry Andric   /// Set to true if the outliner should consider functions with
8402cab237bSDimitry Andric   /// linkonceodr linkage.
8412cab237bSDimitry Andric   bool OutlineFromLinkOnceODRs = false;
8422cab237bSDimitry Andric 
8434ba319b5SDimitry Andric   /// Set to true if the outliner should run on all functions in the module
8444ba319b5SDimitry Andric   /// considered safe for outlining.
8454ba319b5SDimitry Andric   /// Set to true by default for compatibility with llc's -run-pass option.
8464ba319b5SDimitry Andric   /// Set when the pass is constructed in TargetPassConfig.
8474ba319b5SDimitry Andric   bool RunOnAllFunctions = true;
8484ba319b5SDimitry Andric 
getPassName__anon1330aca00111::MachineOutliner8497a7e6055SDimitry Andric   StringRef getPassName() const override { return "Machine Outliner"; }
8507a7e6055SDimitry Andric 
getAnalysisUsage__anon1330aca00111::MachineOutliner8517a7e6055SDimitry Andric   void getAnalysisUsage(AnalysisUsage &AU) const override {
8527a7e6055SDimitry Andric     AU.addRequired<MachineModuleInfo>();
8537a7e6055SDimitry Andric     AU.addPreserved<MachineModuleInfo>();
8547a7e6055SDimitry Andric     AU.setPreservesAll();
8557a7e6055SDimitry Andric     ModulePass::getAnalysisUsage(AU);
8567a7e6055SDimitry Andric   }
8577a7e6055SDimitry Andric 
MachineOutliner__anon1330aca00111::MachineOutliner8584ba319b5SDimitry Andric   MachineOutliner() : ModulePass(ID) {
8597a7e6055SDimitry Andric     initializeMachineOutlinerPass(*PassRegistry::getPassRegistry());
8607a7e6055SDimitry Andric   }
8617a7e6055SDimitry Andric 
8624ba319b5SDimitry Andric   /// Remark output explaining that not outlining a set of candidates would be
8634ba319b5SDimitry Andric   /// better than outlining that set.
8644ba319b5SDimitry Andric   void emitNotOutliningCheaperRemark(
8654ba319b5SDimitry Andric       unsigned StringLen, std::vector<Candidate> &CandidatesForRepeatedSeq,
8664ba319b5SDimitry Andric       OutlinedFunction &OF);
8674ba319b5SDimitry Andric 
8684ba319b5SDimitry Andric   /// Remark output explaining that a function was outlined.
8694ba319b5SDimitry Andric   void emitOutlinedFunctionRemark(OutlinedFunction &OF);
8704ba319b5SDimitry Andric 
871*b5893f02SDimitry Andric   /// Find all repeated substrings that satisfy the outlining cost model by
872*b5893f02SDimitry Andric   /// constructing a suffix tree.
8732cab237bSDimitry Andric   ///
8742cab237bSDimitry Andric   /// If a substring appears at least twice, then it must be represented by
8754ba319b5SDimitry Andric   /// an internal node which appears in at least two suffixes. Each suffix
8764ba319b5SDimitry Andric   /// is represented by a leaf node. To do this, we visit each internal node
8774ba319b5SDimitry Andric   /// in the tree, using the leaf children of each internal node. If an
8784ba319b5SDimitry Andric   /// internal node represents a beneficial substring, then we use each of
8794ba319b5SDimitry Andric   /// its leaf children to find the locations of its substring.
8802cab237bSDimitry Andric   ///
8812cab237bSDimitry Andric   /// \param Mapper Contains outlining mapping information.
8824ba319b5SDimitry Andric   /// \param[out] FunctionList Filled with a list of \p OutlinedFunctions
8834ba319b5SDimitry Andric   /// each type of candidate.
884*b5893f02SDimitry Andric   void findCandidates(InstructionMapper &Mapper,
8852cab237bSDimitry Andric                       std::vector<OutlinedFunction> &FunctionList);
8862cab237bSDimitry Andric 
887*b5893f02SDimitry Andric   /// Replace the sequences of instructions represented by \p OutlinedFunctions
888*b5893f02SDimitry Andric   /// with calls to functions.
8897a7e6055SDimitry Andric   ///
8907a7e6055SDimitry Andric   /// \param M The module we are outlining from.
8917a7e6055SDimitry Andric   /// \param FunctionList A list of functions to be inserted into the module.
8927a7e6055SDimitry Andric   /// \param Mapper Contains the instruction mappings for the module.
893*b5893f02SDimitry Andric   bool outline(Module &M, std::vector<OutlinedFunction> &FunctionList,
8947a7e6055SDimitry Andric                InstructionMapper &Mapper);
8957a7e6055SDimitry Andric 
8967a7e6055SDimitry Andric   /// Creates a function for \p OF and inserts it into the module.
897*b5893f02SDimitry Andric   MachineFunction *createOutlinedFunction(Module &M, OutlinedFunction &OF,
898*b5893f02SDimitry Andric                                           InstructionMapper &Mapper,
899*b5893f02SDimitry Andric                                           unsigned Name);
9007a7e6055SDimitry Andric 
9017a7e6055SDimitry Andric   /// Construct a suffix tree on the instructions in \p M and outline repeated
9027a7e6055SDimitry Andric   /// strings from that tree.
9037a7e6055SDimitry Andric   bool runOnModule(Module &M) override;
9044ba319b5SDimitry Andric 
9054ba319b5SDimitry Andric   /// Return a DISubprogram for OF if one exists, and null otherwise. Helper
9064ba319b5SDimitry Andric   /// function for remark emission.
getSubprogramOrNull__anon1330aca00111::MachineOutliner9074ba319b5SDimitry Andric   DISubprogram *getSubprogramOrNull(const OutlinedFunction &OF) {
9084ba319b5SDimitry Andric     DISubprogram *SP;
909*b5893f02SDimitry Andric     for (const Candidate &C : OF.Candidates)
910*b5893f02SDimitry Andric       if (C.getMF() && (SP = C.getMF()->getFunction().getSubprogram()))
9114ba319b5SDimitry Andric         return SP;
9124ba319b5SDimitry Andric     return nullptr;
9134ba319b5SDimitry Andric   }
9147a7e6055SDimitry Andric 
915*b5893f02SDimitry Andric   /// Populate and \p InstructionMapper with instruction-to-integer mappings.
916*b5893f02SDimitry Andric   /// These are used to construct a suffix tree.
917*b5893f02SDimitry Andric   void populateMapper(InstructionMapper &Mapper, Module &M,
918*b5893f02SDimitry Andric                       MachineModuleInfo &MMI);
919*b5893f02SDimitry Andric 
920*b5893f02SDimitry Andric   /// Initialize information necessary to output a size remark.
921*b5893f02SDimitry Andric   /// FIXME: This should be handled by the pass manager, not the outliner.
922*b5893f02SDimitry Andric   /// FIXME: This is nearly identical to the initSizeRemarkInfo in the legacy
923*b5893f02SDimitry Andric   /// pass manager.
924*b5893f02SDimitry Andric   void initSizeRemarkInfo(
925*b5893f02SDimitry Andric       const Module &M, const MachineModuleInfo &MMI,
926*b5893f02SDimitry Andric       StringMap<unsigned> &FunctionToInstrCount);
927*b5893f02SDimitry Andric 
928*b5893f02SDimitry Andric   /// Emit the remark.
929*b5893f02SDimitry Andric   // FIXME: This should be handled by the pass manager, not the outliner.
930*b5893f02SDimitry Andric   void emitInstrCountChangedRemark(
931*b5893f02SDimitry Andric       const Module &M, const MachineModuleInfo &MMI,
932*b5893f02SDimitry Andric       const StringMap<unsigned> &FunctionToInstrCount);
933*b5893f02SDimitry Andric };
9347a7e6055SDimitry Andric } // Anonymous namespace.
9357a7e6055SDimitry Andric 
9367a7e6055SDimitry Andric char MachineOutliner::ID = 0;
9377a7e6055SDimitry Andric 
9387a7e6055SDimitry Andric namespace llvm {
createMachineOutlinerPass(bool RunOnAllFunctions)9394ba319b5SDimitry Andric ModulePass *createMachineOutlinerPass(bool RunOnAllFunctions) {
9404ba319b5SDimitry Andric   MachineOutliner *OL = new MachineOutliner();
9414ba319b5SDimitry Andric   OL->RunOnAllFunctions = RunOnAllFunctions;
9424ba319b5SDimitry Andric   return OL;
9437a7e6055SDimitry Andric }
9447a7e6055SDimitry Andric 
9452cab237bSDimitry Andric } // namespace llvm
9467a7e6055SDimitry Andric 
9472cab237bSDimitry Andric INITIALIZE_PASS(MachineOutliner, DEBUG_TYPE, "Machine Function Outliner", false,
9482cab237bSDimitry Andric                 false)
9492cab237bSDimitry Andric 
emitNotOutliningCheaperRemark(unsigned StringLen,std::vector<Candidate> & CandidatesForRepeatedSeq,OutlinedFunction & OF)9504ba319b5SDimitry Andric void MachineOutliner::emitNotOutliningCheaperRemark(
9514ba319b5SDimitry Andric     unsigned StringLen, std::vector<Candidate> &CandidatesForRepeatedSeq,
9524ba319b5SDimitry Andric     OutlinedFunction &OF) {
953*b5893f02SDimitry Andric   // FIXME: Right now, we arbitrarily choose some Candidate from the
954*b5893f02SDimitry Andric   // OutlinedFunction. This isn't necessarily fixed, nor does it have to be.
955*b5893f02SDimitry Andric   // We should probably sort these by function name or something to make sure
956*b5893f02SDimitry Andric   // the remarks are stable.
9574ba319b5SDimitry Andric   Candidate &C = CandidatesForRepeatedSeq.front();
9584ba319b5SDimitry Andric   MachineOptimizationRemarkEmitter MORE(*(C.getMF()), nullptr);
9594ba319b5SDimitry Andric   MORE.emit([&]() {
9604ba319b5SDimitry Andric     MachineOptimizationRemarkMissed R(DEBUG_TYPE, "NotOutliningCheaper",
9614ba319b5SDimitry Andric                                       C.front()->getDebugLoc(), C.getMBB());
9624ba319b5SDimitry Andric     R << "Did not outline " << NV("Length", StringLen) << " instructions"
9634ba319b5SDimitry Andric       << " from " << NV("NumOccurrences", CandidatesForRepeatedSeq.size())
9644ba319b5SDimitry Andric       << " locations."
9654ba319b5SDimitry Andric       << " Bytes from outlining all occurrences ("
9664ba319b5SDimitry Andric       << NV("OutliningCost", OF.getOutliningCost()) << ")"
9674ba319b5SDimitry Andric       << " >= Unoutlined instruction bytes ("
9684ba319b5SDimitry Andric       << NV("NotOutliningCost", OF.getNotOutlinedCost()) << ")"
9694ba319b5SDimitry Andric       << " (Also found at: ";
9704ba319b5SDimitry Andric 
9714ba319b5SDimitry Andric     // Tell the user the other places the candidate was found.
9724ba319b5SDimitry Andric     for (unsigned i = 1, e = CandidatesForRepeatedSeq.size(); i < e; i++) {
9734ba319b5SDimitry Andric       R << NV((Twine("OtherStartLoc") + Twine(i)).str(),
9744ba319b5SDimitry Andric               CandidatesForRepeatedSeq[i].front()->getDebugLoc());
9754ba319b5SDimitry Andric       if (i != e - 1)
9764ba319b5SDimitry Andric         R << ", ";
9774ba319b5SDimitry Andric     }
9784ba319b5SDimitry Andric 
9794ba319b5SDimitry Andric     R << ")";
9804ba319b5SDimitry Andric     return R;
9814ba319b5SDimitry Andric   });
9824ba319b5SDimitry Andric }
9834ba319b5SDimitry Andric 
emitOutlinedFunctionRemark(OutlinedFunction & OF)9844ba319b5SDimitry Andric void MachineOutliner::emitOutlinedFunctionRemark(OutlinedFunction &OF) {
9854ba319b5SDimitry Andric   MachineBasicBlock *MBB = &*OF.MF->begin();
9864ba319b5SDimitry Andric   MachineOptimizationRemarkEmitter MORE(*OF.MF, nullptr);
9874ba319b5SDimitry Andric   MachineOptimizationRemark R(DEBUG_TYPE, "OutlinedFunction",
9884ba319b5SDimitry Andric                               MBB->findDebugLoc(MBB->begin()), MBB);
9894ba319b5SDimitry Andric   R << "Saved " << NV("OutliningBenefit", OF.getBenefit()) << " bytes by "
990*b5893f02SDimitry Andric     << "outlining " << NV("Length", OF.getNumInstrs()) << " instructions "
9914ba319b5SDimitry Andric     << "from " << NV("NumOccurrences", OF.getOccurrenceCount())
9924ba319b5SDimitry Andric     << " locations. "
9934ba319b5SDimitry Andric     << "(Found at: ";
9944ba319b5SDimitry Andric 
9954ba319b5SDimitry Andric   // Tell the user the other places the candidate was found.
9964ba319b5SDimitry Andric   for (size_t i = 0, e = OF.Candidates.size(); i < e; i++) {
9974ba319b5SDimitry Andric 
9984ba319b5SDimitry Andric     R << NV((Twine("StartLoc") + Twine(i)).str(),
999*b5893f02SDimitry Andric             OF.Candidates[i].front()->getDebugLoc());
10004ba319b5SDimitry Andric     if (i != e - 1)
10014ba319b5SDimitry Andric       R << ", ";
10024ba319b5SDimitry Andric   }
10034ba319b5SDimitry Andric 
10044ba319b5SDimitry Andric   R << ")";
10054ba319b5SDimitry Andric 
10064ba319b5SDimitry Andric   MORE.emit(R);
10074ba319b5SDimitry Andric }
10084ba319b5SDimitry Andric 
1009*b5893f02SDimitry Andric void
findCandidates(InstructionMapper & Mapper,std::vector<OutlinedFunction> & FunctionList)1010*b5893f02SDimitry Andric MachineOutliner::findCandidates(InstructionMapper &Mapper,
10112cab237bSDimitry Andric                                 std::vector<OutlinedFunction> &FunctionList) {
10122cab237bSDimitry Andric   FunctionList.clear();
1013*b5893f02SDimitry Andric   SuffixTree ST(Mapper.UnsignedVec);
10142cab237bSDimitry Andric 
1015*b5893f02SDimitry Andric   // First, find dall of the repeated substrings in the tree of minimum length
1016*b5893f02SDimitry Andric   // 2.
10172cab237bSDimitry Andric   std::vector<Candidate> CandidatesForRepeatedSeq;
1018*b5893f02SDimitry Andric   for (auto It = ST.begin(), Et = ST.end(); It != Et; ++It) {
1019*b5893f02SDimitry Andric     CandidatesForRepeatedSeq.clear();
1020*b5893f02SDimitry Andric     SuffixTree::RepeatedSubstring RS = *It;
1021*b5893f02SDimitry Andric     unsigned StringLen = RS.Length;
1022*b5893f02SDimitry Andric     for (const unsigned &StartIdx : RS.StartIndices) {
10232cab237bSDimitry Andric       unsigned EndIdx = StartIdx + StringLen - 1;
10242cab237bSDimitry Andric       // Trick: Discard some candidates that would be incompatible with the
10252cab237bSDimitry Andric       // ones we've already found for this sequence. This will save us some
10262cab237bSDimitry Andric       // work in candidate selection.
10272cab237bSDimitry Andric       //
10282cab237bSDimitry Andric       // If two candidates overlap, then we can't outline them both. This
10292cab237bSDimitry Andric       // happens when we have candidates that look like, say
10302cab237bSDimitry Andric       //
10312cab237bSDimitry Andric       // AA (where each "A" is an instruction).
10322cab237bSDimitry Andric       //
10332cab237bSDimitry Andric       // We might have some portion of the module that looks like this:
10342cab237bSDimitry Andric       // AAAAAA (6 A's)
10352cab237bSDimitry Andric       //
10362cab237bSDimitry Andric       // In this case, there are 5 different copies of "AA" in this range, but
10372cab237bSDimitry Andric       // at most 3 can be outlined. If only outlining 3 of these is going to
10382cab237bSDimitry Andric       // be unbeneficial, then we ought to not bother.
10392cab237bSDimitry Andric       //
10402cab237bSDimitry Andric       // Note that two things DON'T overlap when they look like this:
10412cab237bSDimitry Andric       // start1...end1 .... start2...end2
10422cab237bSDimitry Andric       // That is, one must either
10432cab237bSDimitry Andric       // * End before the other starts
10442cab237bSDimitry Andric       // * Start after the other ends
1045*b5893f02SDimitry Andric       if (std::all_of(
1046*b5893f02SDimitry Andric               CandidatesForRepeatedSeq.begin(), CandidatesForRepeatedSeq.end(),
10472cab237bSDimitry Andric               [&StartIdx, &EndIdx](const Candidate &C) {
1048*b5893f02SDimitry Andric                 return (EndIdx < C.getStartIdx() || StartIdx > C.getEndIdx());
10492cab237bSDimitry Andric               })) {
10502cab237bSDimitry Andric         // It doesn't overlap with anything, so we can outline it.
10512cab237bSDimitry Andric         // Each sequence is over [StartIt, EndIt].
10524ba319b5SDimitry Andric         // Save the candidate and its location.
10534ba319b5SDimitry Andric 
10542cab237bSDimitry Andric         MachineBasicBlock::iterator StartIt = Mapper.InstrList[StartIdx];
10552cab237bSDimitry Andric         MachineBasicBlock::iterator EndIt = Mapper.InstrList[EndIdx];
1056*b5893f02SDimitry Andric         MachineBasicBlock *MBB = StartIt->getParent();
10572cab237bSDimitry Andric 
10584ba319b5SDimitry Andric         CandidatesForRepeatedSeq.emplace_back(StartIdx, StringLen, StartIt,
1059*b5893f02SDimitry Andric                                               EndIt, MBB, FunctionList.size(),
1060*b5893f02SDimitry Andric                                               Mapper.MBBFlagsMap[MBB]);
10612cab237bSDimitry Andric       }
10622cab237bSDimitry Andric     }
10632cab237bSDimitry Andric 
10642cab237bSDimitry Andric     // We've found something we might want to outline.
10652cab237bSDimitry Andric     // Create an OutlinedFunction to store it and check if it'd be beneficial
10662cab237bSDimitry Andric     // to outline.
1067*b5893f02SDimitry Andric     if (CandidatesForRepeatedSeq.size() < 2)
10684ba319b5SDimitry Andric       continue;
10694ba319b5SDimitry Andric 
10704ba319b5SDimitry Andric     // Arbitrarily choose a TII from the first candidate.
10714ba319b5SDimitry Andric     // FIXME: Should getOutliningCandidateInfo move to TargetMachine?
10724ba319b5SDimitry Andric     const TargetInstrInfo *TII =
10734ba319b5SDimitry Andric         CandidatesForRepeatedSeq[0].getMF()->getSubtarget().getInstrInfo();
10744ba319b5SDimitry Andric 
10754ba319b5SDimitry Andric     OutlinedFunction OF =
10764ba319b5SDimitry Andric         TII->getOutliningCandidateInfo(CandidatesForRepeatedSeq);
10774ba319b5SDimitry Andric 
1078*b5893f02SDimitry Andric     // If we deleted too many candidates, then there's nothing worth outlining.
1079*b5893f02SDimitry Andric     // FIXME: This should take target-specified instruction sizes into account.
1080*b5893f02SDimitry Andric     if (OF.Candidates.size() < 2)
10814ba319b5SDimitry Andric       continue;
10824ba319b5SDimitry Andric 
10832cab237bSDimitry Andric     // Is it better to outline this candidate than not?
10844ba319b5SDimitry Andric     if (OF.getBenefit() < 1) {
10854ba319b5SDimitry Andric       emitNotOutliningCheaperRemark(StringLen, CandidatesForRepeatedSeq, OF);
10862cab237bSDimitry Andric       continue;
10872cab237bSDimitry Andric     }
10882cab237bSDimitry Andric 
10892cab237bSDimitry Andric     FunctionList.push_back(OF);
10902cab237bSDimitry Andric   }
10917a7e6055SDimitry Andric }
10927a7e6055SDimitry Andric 
10937a7e6055SDimitry Andric MachineFunction *
createOutlinedFunction(Module & M,OutlinedFunction & OF,InstructionMapper & Mapper,unsigned Name)1094*b5893f02SDimitry Andric MachineOutliner::createOutlinedFunction(Module &M, OutlinedFunction &OF,
1095*b5893f02SDimitry Andric                                         InstructionMapper &Mapper,
1096*b5893f02SDimitry Andric                                         unsigned Name) {
10977a7e6055SDimitry Andric 
10987a7e6055SDimitry Andric   // Create the function name. This should be unique. For now, just hash the
10997a7e6055SDimitry Andric   // module name and include it in the function name plus the number of this
11007a7e6055SDimitry Andric   // function.
11017a7e6055SDimitry Andric   std::ostringstream NameStream;
1102*b5893f02SDimitry Andric   // FIXME: We should have a better naming scheme. This should be stable,
1103*b5893f02SDimitry Andric   // regardless of changes to the outliner's cost model/traversal order.
1104*b5893f02SDimitry Andric   NameStream << "OUTLINED_FUNCTION_" << Name;
11057a7e6055SDimitry Andric 
11067a7e6055SDimitry Andric   // Create the function using an IR-level function.
11077a7e6055SDimitry Andric   LLVMContext &C = M.getContext();
11087a7e6055SDimitry Andric   Function *F = dyn_cast<Function>(
11097a7e6055SDimitry Andric       M.getOrInsertFunction(NameStream.str(), Type::getVoidTy(C)));
11107a7e6055SDimitry Andric   assert(F && "Function was null!");
11117a7e6055SDimitry Andric 
11127a7e6055SDimitry Andric   // NOTE: If this is linkonceodr, then we can take advantage of linker deduping
11137a7e6055SDimitry Andric   // which gives us better results when we outline from linkonceodr functions.
11144ba319b5SDimitry Andric   F->setLinkage(GlobalValue::InternalLinkage);
11157a7e6055SDimitry Andric   F->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
11167a7e6055SDimitry Andric 
11174ba319b5SDimitry Andric   // FIXME: Set nounwind, so we don't generate eh_frame? Haven't verified it's
11184ba319b5SDimitry Andric   // necessary.
11194ba319b5SDimitry Andric 
11204ba319b5SDimitry Andric   // Set optsize/minsize, so we don't insert padding between outlined
11214ba319b5SDimitry Andric   // functions.
11224ba319b5SDimitry Andric   F->addFnAttr(Attribute::OptimizeForSize);
11234ba319b5SDimitry Andric   F->addFnAttr(Attribute::MinSize);
11244ba319b5SDimitry Andric 
1125*b5893f02SDimitry Andric   // Include target features from an arbitrary candidate for the outlined
1126*b5893f02SDimitry Andric   // function. This makes sure the outlined function knows what kinds of
1127*b5893f02SDimitry Andric   // instructions are going into it. This is fine, since all parent functions
1128*b5893f02SDimitry Andric   // must necessarily support the instructions that are in the outlined region.
1129*b5893f02SDimitry Andric   Candidate &FirstCand = OF.Candidates.front();
1130*b5893f02SDimitry Andric   const Function &ParentFn = FirstCand.getMF()->getFunction();
1131*b5893f02SDimitry Andric   if (ParentFn.hasFnAttribute("target-features"))
1132*b5893f02SDimitry Andric     F->addFnAttr(ParentFn.getFnAttribute("target-features"));
11334ba319b5SDimitry Andric 
11347a7e6055SDimitry Andric   BasicBlock *EntryBB = BasicBlock::Create(C, "entry", F);
11357a7e6055SDimitry Andric   IRBuilder<> Builder(EntryBB);
11367a7e6055SDimitry Andric   Builder.CreateRetVoid();
11377a7e6055SDimitry Andric 
11387a7e6055SDimitry Andric   MachineModuleInfo &MMI = getAnalysis<MachineModuleInfo>();
1139db17bf38SDimitry Andric   MachineFunction &MF = MMI.getOrCreateMachineFunction(*F);
11407a7e6055SDimitry Andric   MachineBasicBlock &MBB = *MF.CreateMachineBasicBlock();
11417a7e6055SDimitry Andric   const TargetSubtargetInfo &STI = MF.getSubtarget();
11427a7e6055SDimitry Andric   const TargetInstrInfo &TII = *STI.getInstrInfo();
11437a7e6055SDimitry Andric 
11447a7e6055SDimitry Andric   // Insert the new function into the module.
11457a7e6055SDimitry Andric   MF.insert(MF.begin(), &MBB);
11467a7e6055SDimitry Andric 
1147*b5893f02SDimitry Andric   for (auto I = FirstCand.front(), E = std::next(FirstCand.back()); I != E;
1148*b5893f02SDimitry Andric        ++I) {
1149*b5893f02SDimitry Andric     MachineInstr *NewMI = MF.CloneMachineInstr(&*I);
1150*b5893f02SDimitry Andric     NewMI->dropMemRefs(MF);
11517a7e6055SDimitry Andric 
11527a7e6055SDimitry Andric     // Don't keep debug information for outlined instructions.
11537a7e6055SDimitry Andric     NewMI->setDebugLoc(DebugLoc());
11547a7e6055SDimitry Andric     MBB.insert(MBB.end(), NewMI);
11557a7e6055SDimitry Andric   }
11567a7e6055SDimitry Andric 
11574ba319b5SDimitry Andric   TII.buildOutlinedFrame(MBB, MF, OF);
11587a7e6055SDimitry Andric 
1159*b5893f02SDimitry Andric   // Outlined functions shouldn't preserve liveness.
1160*b5893f02SDimitry Andric   MF.getProperties().reset(MachineFunctionProperties::Property::TracksLiveness);
1161*b5893f02SDimitry Andric   MF.getRegInfo().freezeReservedRegs(MF);
1162*b5893f02SDimitry Andric 
11634ba319b5SDimitry Andric   // If there's a DISubprogram associated with this outlined function, then
11644ba319b5SDimitry Andric   // emit debug info for the outlined function.
11654ba319b5SDimitry Andric   if (DISubprogram *SP = getSubprogramOrNull(OF)) {
11664ba319b5SDimitry Andric     // We have a DISubprogram. Get its DICompileUnit.
11674ba319b5SDimitry Andric     DICompileUnit *CU = SP->getUnit();
11684ba319b5SDimitry Andric     DIBuilder DB(M, true, CU);
11694ba319b5SDimitry Andric     DIFile *Unit = SP->getFile();
11704ba319b5SDimitry Andric     Mangler Mg;
11714ba319b5SDimitry Andric     // Get the mangled name of the function for the linkage name.
11724ba319b5SDimitry Andric     std::string Dummy;
11734ba319b5SDimitry Andric     llvm::raw_string_ostream MangledNameStream(Dummy);
11744ba319b5SDimitry Andric     Mg.getNameWithPrefix(MangledNameStream, F, false);
11754ba319b5SDimitry Andric 
1176*b5893f02SDimitry Andric     DISubprogram *OutlinedSP = DB.createFunction(
11774ba319b5SDimitry Andric         Unit /* Context */, F->getName(), StringRef(MangledNameStream.str()),
11784ba319b5SDimitry Andric         Unit /* File */,
11794ba319b5SDimitry Andric         0 /* Line 0 is reserved for compiler-generated code. */,
1180*b5893f02SDimitry Andric         DB.createSubroutineType(DB.getOrCreateTypeArray(None)), /* void type */
1181*b5893f02SDimitry Andric         0, /* Line 0 is reserved for compiler-generated code. */
11824ba319b5SDimitry Andric         DINode::DIFlags::FlagArtificial /* Compiler-generated code. */,
1183*b5893f02SDimitry Andric         /* Outlined code is optimized code by definition. */
1184*b5893f02SDimitry Andric         DISubprogram::SPFlagDefinition | DISubprogram::SPFlagOptimized);
11854ba319b5SDimitry Andric 
11864ba319b5SDimitry Andric     // Don't add any new variables to the subprogram.
1187*b5893f02SDimitry Andric     DB.finalizeSubprogram(OutlinedSP);
11884ba319b5SDimitry Andric 
11894ba319b5SDimitry Andric     // Attach subprogram to the function.
1190*b5893f02SDimitry Andric     F->setSubprogram(OutlinedSP);
11914ba319b5SDimitry Andric     // We're done with the DIBuilder.
11924ba319b5SDimitry Andric     DB.finalize();
11934ba319b5SDimitry Andric   }
11944ba319b5SDimitry Andric 
11957a7e6055SDimitry Andric   return &MF;
11967a7e6055SDimitry Andric }
11977a7e6055SDimitry Andric 
outline(Module & M,std::vector<OutlinedFunction> & FunctionList,InstructionMapper & Mapper)1198*b5893f02SDimitry Andric bool MachineOutliner::outline(Module &M,
1199*b5893f02SDimitry Andric                               std::vector<OutlinedFunction> &FunctionList,
1200*b5893f02SDimitry Andric                               InstructionMapper &Mapper) {
12017a7e6055SDimitry Andric 
12027a7e6055SDimitry Andric   bool OutlinedSomething = false;
12037a7e6055SDimitry Andric 
1204*b5893f02SDimitry Andric   // Number to append to the current outlined function.
1205*b5893f02SDimitry Andric   unsigned OutlinedFunctionNum = 0;
12067a7e6055SDimitry Andric 
1207*b5893f02SDimitry Andric   // Sort by benefit. The most beneficial functions should be outlined first.
1208*b5893f02SDimitry Andric   std::stable_sort(
1209*b5893f02SDimitry Andric       FunctionList.begin(), FunctionList.end(),
1210*b5893f02SDimitry Andric       [](const OutlinedFunction &LHS, const OutlinedFunction &RHS) {
1211*b5893f02SDimitry Andric         return LHS.getBenefit() > RHS.getBenefit();
1212*b5893f02SDimitry Andric       });
1213*b5893f02SDimitry Andric 
1214*b5893f02SDimitry Andric   // Walk over each function, outlining them as we go along. Functions are
1215*b5893f02SDimitry Andric   // outlined greedily, based off the sort above.
1216*b5893f02SDimitry Andric   for (OutlinedFunction &OF : FunctionList) {
1217*b5893f02SDimitry Andric     // If we outlined something that overlapped with a candidate in a previous
1218*b5893f02SDimitry Andric     // step, then we can't outline from it.
1219*b5893f02SDimitry Andric     erase_if(OF.Candidates, [&Mapper](Candidate &C) {
1220*b5893f02SDimitry Andric       return std::any_of(
1221*b5893f02SDimitry Andric           Mapper.UnsignedVec.begin() + C.getStartIdx(),
1222*b5893f02SDimitry Andric           Mapper.UnsignedVec.begin() + C.getEndIdx() + 1,
1223*b5893f02SDimitry Andric           [](unsigned I) { return (I == static_cast<unsigned>(-1)); });
1224*b5893f02SDimitry Andric     });
1225*b5893f02SDimitry Andric 
1226*b5893f02SDimitry Andric     // If we made it unbeneficial to outline this function, skip it.
12272cab237bSDimitry Andric     if (OF.getBenefit() < 1)
12287a7e6055SDimitry Andric       continue;
12297a7e6055SDimitry Andric 
1230*b5893f02SDimitry Andric     // It's beneficial. Create the function and outline its sequence's
1231*b5893f02SDimitry Andric     // occurrences.
1232*b5893f02SDimitry Andric     OF.MF = createOutlinedFunction(M, OF, Mapper, OutlinedFunctionNum);
12334ba319b5SDimitry Andric     emitOutlinedFunctionRemark(OF);
12347a7e6055SDimitry Andric     FunctionsCreated++;
1235*b5893f02SDimitry Andric     OutlinedFunctionNum++; // Created a function, move to the next name.
12367a7e6055SDimitry Andric     MachineFunction *MF = OF.MF;
12377a7e6055SDimitry Andric     const TargetSubtargetInfo &STI = MF->getSubtarget();
12387a7e6055SDimitry Andric     const TargetInstrInfo &TII = *STI.getInstrInfo();
12397a7e6055SDimitry Andric 
1240*b5893f02SDimitry Andric     // Replace occurrences of the sequence with calls to the new function.
1241*b5893f02SDimitry Andric     for (Candidate &C : OF.Candidates) {
1242*b5893f02SDimitry Andric       MachineBasicBlock &MBB = *C.getMBB();
1243*b5893f02SDimitry Andric       MachineBasicBlock::iterator StartIt = C.front();
1244*b5893f02SDimitry Andric       MachineBasicBlock::iterator EndIt = C.back();
12457a7e6055SDimitry Andric 
1246*b5893f02SDimitry Andric       // Insert the call.
1247*b5893f02SDimitry Andric       auto CallInst = TII.insertOutlinedCall(M, MBB, StartIt, *MF, C);
1248*b5893f02SDimitry Andric 
1249*b5893f02SDimitry Andric       // If the caller tracks liveness, then we need to make sure that
1250*b5893f02SDimitry Andric       // anything we outline doesn't break liveness assumptions. The outlined
1251*b5893f02SDimitry Andric       // functions themselves currently don't track liveness, but we should
1252*b5893f02SDimitry Andric       // make sure that the ranges we yank things out of aren't wrong.
12534ba319b5SDimitry Andric       if (MBB.getParent()->getProperties().hasProperty(
12544ba319b5SDimitry Andric               MachineFunctionProperties::Property::TracksLiveness)) {
1255*b5893f02SDimitry Andric         // Helper lambda for adding implicit def operands to the call
1256*b5893f02SDimitry Andric         // instruction.
12574ba319b5SDimitry Andric         auto CopyDefs = [&CallInst](MachineInstr &MI) {
12584ba319b5SDimitry Andric           for (MachineOperand &MOP : MI.operands()) {
12594ba319b5SDimitry Andric             // Skip over anything that isn't a register.
12604ba319b5SDimitry Andric             if (!MOP.isReg())
12614ba319b5SDimitry Andric               continue;
12624ba319b5SDimitry Andric 
12634ba319b5SDimitry Andric             // If it's a def, add it to the call instruction.
12644ba319b5SDimitry Andric             if (MOP.isDef())
1265*b5893f02SDimitry Andric               CallInst->addOperand(MachineOperand::CreateReg(
1266*b5893f02SDimitry Andric                   MOP.getReg(), true, /* isDef = true */
12674ba319b5SDimitry Andric                   true /* isImp = true */));
12684ba319b5SDimitry Andric           }
12694ba319b5SDimitry Andric         };
12704ba319b5SDimitry Andric         // Copy over the defs in the outlined range.
12714ba319b5SDimitry Andric         // First inst in outlined range <-- Anything that's defined in this
1272*b5893f02SDimitry Andric         // ...                           .. range has to be added as an
1273*b5893f02SDimitry Andric         // implicit Last inst in outlined range  <-- def to the call
1274*b5893f02SDimitry Andric         // instruction.
12754ba319b5SDimitry Andric         std::for_each(CallInst, std::next(EndIt), CopyDefs);
12764ba319b5SDimitry Andric       }
12774ba319b5SDimitry Andric 
12784ba319b5SDimitry Andric       // Erase from the point after where the call was inserted up to, and
12794ba319b5SDimitry Andric       // including, the final instruction in the sequence.
12804ba319b5SDimitry Andric       // Erase needs one past the end, so we need std::next there too.
12814ba319b5SDimitry Andric       MBB.erase(std::next(StartIt), std::next(EndIt));
1282*b5893f02SDimitry Andric 
1283*b5893f02SDimitry Andric       // Keep track of what we removed by marking them all as -1.
1284*b5893f02SDimitry Andric       std::for_each(Mapper.UnsignedVec.begin() + C.getStartIdx(),
1285*b5893f02SDimitry Andric                     Mapper.UnsignedVec.begin() + C.getEndIdx() + 1,
1286*b5893f02SDimitry Andric                     [](unsigned &I) { I = static_cast<unsigned>(-1); });
12877a7e6055SDimitry Andric       OutlinedSomething = true;
12887a7e6055SDimitry Andric 
12897a7e6055SDimitry Andric       // Statistics.
12907a7e6055SDimitry Andric       NumOutlined++;
12917a7e6055SDimitry Andric     }
1292*b5893f02SDimitry Andric   }
12937a7e6055SDimitry Andric 
12944ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "OutlinedSomething = " << OutlinedSomething << "\n";);
12957a7e6055SDimitry Andric 
12967a7e6055SDimitry Andric   return OutlinedSomething;
12977a7e6055SDimitry Andric }
12987a7e6055SDimitry Andric 
populateMapper(InstructionMapper & Mapper,Module & M,MachineModuleInfo & MMI)1299*b5893f02SDimitry Andric void MachineOutliner::populateMapper(InstructionMapper &Mapper, Module &M,
1300*b5893f02SDimitry Andric                                      MachineModuleInfo &MMI) {
13014ba319b5SDimitry Andric   // Build instruction mappings for each function in the module. Start by
13024ba319b5SDimitry Andric   // iterating over each Function in M.
13037a7e6055SDimitry Andric   for (Function &F : M) {
13047a7e6055SDimitry Andric 
13054ba319b5SDimitry Andric     // If there's nothing in F, then there's no reason to try and outline from
13064ba319b5SDimitry Andric     // it.
13074ba319b5SDimitry Andric     if (F.empty())
13087a7e6055SDimitry Andric       continue;
13097a7e6055SDimitry Andric 
13104ba319b5SDimitry Andric     // There's something in F. Check if it has a MachineFunction associated with
13114ba319b5SDimitry Andric     // it.
13124ba319b5SDimitry Andric     MachineFunction *MF = MMI.getMachineFunction(F);
13137a7e6055SDimitry Andric 
13144ba319b5SDimitry Andric     // If it doesn't, then there's nothing to outline from. Move to the next
13154ba319b5SDimitry Andric     // Function.
13164ba319b5SDimitry Andric     if (!MF)
13174ba319b5SDimitry Andric       continue;
13184ba319b5SDimitry Andric 
13194ba319b5SDimitry Andric     const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
13204ba319b5SDimitry Andric 
13214ba319b5SDimitry Andric     if (!RunOnAllFunctions && !TII->shouldOutlineFromFunctionByDefault(*MF))
13224ba319b5SDimitry Andric       continue;
13234ba319b5SDimitry Andric 
13244ba319b5SDimitry Andric     // We have a MachineFunction. Ask the target if it's suitable for outlining.
13254ba319b5SDimitry Andric     // If it isn't, then move on to the next Function in the module.
13264ba319b5SDimitry Andric     if (!TII->isFunctionSafeToOutlineFrom(*MF, OutlineFromLinkOnceODRs))
13274ba319b5SDimitry Andric       continue;
13284ba319b5SDimitry Andric 
13294ba319b5SDimitry Andric     // We have a function suitable for outlining. Iterate over every
13304ba319b5SDimitry Andric     // MachineBasicBlock in MF and try to map its instructions to a list of
13314ba319b5SDimitry Andric     // unsigned integers.
13324ba319b5SDimitry Andric     for (MachineBasicBlock &MBB : *MF) {
13334ba319b5SDimitry Andric       // If there isn't anything in MBB, then there's no point in outlining from
13344ba319b5SDimitry Andric       // it.
1335*b5893f02SDimitry Andric       // If there are fewer than 2 instructions in the MBB, then it can't ever
1336*b5893f02SDimitry Andric       // contain something worth outlining.
1337*b5893f02SDimitry Andric       // FIXME: This should be based off of the maximum size in B of an outlined
1338*b5893f02SDimitry Andric       // call versus the size in B of the MBB.
1339*b5893f02SDimitry Andric       if (MBB.empty() || MBB.size() < 2)
13407a7e6055SDimitry Andric         continue;
13417a7e6055SDimitry Andric 
13424ba319b5SDimitry Andric       // Check if MBB could be the target of an indirect branch. If it is, then
13434ba319b5SDimitry Andric       // we don't want to outline from it.
13444ba319b5SDimitry Andric       if (MBB.hasAddressTaken())
13454ba319b5SDimitry Andric         continue;
13464ba319b5SDimitry Andric 
13474ba319b5SDimitry Andric       // MBB is suitable for outlining. Map it to a list of unsigneds.
13484ba319b5SDimitry Andric       Mapper.convertToUnsignedVec(MBB, *TII);
13497a7e6055SDimitry Andric     }
13507a7e6055SDimitry Andric   }
1351*b5893f02SDimitry Andric }
13527a7e6055SDimitry Andric 
initSizeRemarkInfo(const Module & M,const MachineModuleInfo & MMI,StringMap<unsigned> & FunctionToInstrCount)1353*b5893f02SDimitry Andric void MachineOutliner::initSizeRemarkInfo(
1354*b5893f02SDimitry Andric     const Module &M, const MachineModuleInfo &MMI,
1355*b5893f02SDimitry Andric     StringMap<unsigned> &FunctionToInstrCount) {
1356*b5893f02SDimitry Andric   // Collect instruction counts for every function. We'll use this to emit
1357*b5893f02SDimitry Andric   // per-function size remarks later.
1358*b5893f02SDimitry Andric   for (const Function &F : M) {
1359*b5893f02SDimitry Andric     MachineFunction *MF = MMI.getMachineFunction(F);
1360*b5893f02SDimitry Andric 
1361*b5893f02SDimitry Andric     // We only care about MI counts here. If there's no MachineFunction at this
1362*b5893f02SDimitry Andric     // point, then there won't be after the outliner runs, so let's move on.
1363*b5893f02SDimitry Andric     if (!MF)
1364*b5893f02SDimitry Andric       continue;
1365*b5893f02SDimitry Andric     FunctionToInstrCount[F.getName().str()] = MF->getInstructionCount();
1366*b5893f02SDimitry Andric   }
1367*b5893f02SDimitry Andric }
1368*b5893f02SDimitry Andric 
emitInstrCountChangedRemark(const Module & M,const MachineModuleInfo & MMI,const StringMap<unsigned> & FunctionToInstrCount)1369*b5893f02SDimitry Andric void MachineOutliner::emitInstrCountChangedRemark(
1370*b5893f02SDimitry Andric     const Module &M, const MachineModuleInfo &MMI,
1371*b5893f02SDimitry Andric     const StringMap<unsigned> &FunctionToInstrCount) {
1372*b5893f02SDimitry Andric   // Iterate over each function in the module and emit remarks.
1373*b5893f02SDimitry Andric   // Note that we won't miss anything by doing this, because the outliner never
1374*b5893f02SDimitry Andric   // deletes functions.
1375*b5893f02SDimitry Andric   for (const Function &F : M) {
1376*b5893f02SDimitry Andric     MachineFunction *MF = MMI.getMachineFunction(F);
1377*b5893f02SDimitry Andric 
1378*b5893f02SDimitry Andric     // The outliner never deletes functions. If we don't have a MF here, then we
1379*b5893f02SDimitry Andric     // didn't have one prior to outlining either.
1380*b5893f02SDimitry Andric     if (!MF)
1381*b5893f02SDimitry Andric       continue;
1382*b5893f02SDimitry Andric 
1383*b5893f02SDimitry Andric     std::string Fname = F.getName();
1384*b5893f02SDimitry Andric     unsigned FnCountAfter = MF->getInstructionCount();
1385*b5893f02SDimitry Andric     unsigned FnCountBefore = 0;
1386*b5893f02SDimitry Andric 
1387*b5893f02SDimitry Andric     // Check if the function was recorded before.
1388*b5893f02SDimitry Andric     auto It = FunctionToInstrCount.find(Fname);
1389*b5893f02SDimitry Andric 
1390*b5893f02SDimitry Andric     // Did we have a previously-recorded size? If yes, then set FnCountBefore
1391*b5893f02SDimitry Andric     // to that.
1392*b5893f02SDimitry Andric     if (It != FunctionToInstrCount.end())
1393*b5893f02SDimitry Andric       FnCountBefore = It->second;
1394*b5893f02SDimitry Andric 
1395*b5893f02SDimitry Andric     // Compute the delta and emit a remark if there was a change.
1396*b5893f02SDimitry Andric     int64_t FnDelta = static_cast<int64_t>(FnCountAfter) -
1397*b5893f02SDimitry Andric                       static_cast<int64_t>(FnCountBefore);
1398*b5893f02SDimitry Andric     if (FnDelta == 0)
1399*b5893f02SDimitry Andric       continue;
1400*b5893f02SDimitry Andric 
1401*b5893f02SDimitry Andric     MachineOptimizationRemarkEmitter MORE(*MF, nullptr);
1402*b5893f02SDimitry Andric     MORE.emit([&]() {
1403*b5893f02SDimitry Andric       MachineOptimizationRemarkAnalysis R("size-info", "FunctionMISizeChange",
1404*b5893f02SDimitry Andric                                           DiagnosticLocation(),
1405*b5893f02SDimitry Andric                                           &MF->front());
1406*b5893f02SDimitry Andric       R << DiagnosticInfoOptimizationBase::Argument("Pass", "Machine Outliner")
1407*b5893f02SDimitry Andric         << ": Function: "
1408*b5893f02SDimitry Andric         << DiagnosticInfoOptimizationBase::Argument("Function", F.getName())
1409*b5893f02SDimitry Andric         << ": MI instruction count changed from "
1410*b5893f02SDimitry Andric         << DiagnosticInfoOptimizationBase::Argument("MIInstrsBefore",
1411*b5893f02SDimitry Andric                                                     FnCountBefore)
1412*b5893f02SDimitry Andric         << " to "
1413*b5893f02SDimitry Andric         << DiagnosticInfoOptimizationBase::Argument("MIInstrsAfter",
1414*b5893f02SDimitry Andric                                                     FnCountAfter)
1415*b5893f02SDimitry Andric         << "; Delta: "
1416*b5893f02SDimitry Andric         << DiagnosticInfoOptimizationBase::Argument("Delta", FnDelta);
1417*b5893f02SDimitry Andric       return R;
1418*b5893f02SDimitry Andric     });
1419*b5893f02SDimitry Andric   }
1420*b5893f02SDimitry Andric }
1421*b5893f02SDimitry Andric 
runOnModule(Module & M)1422*b5893f02SDimitry Andric bool MachineOutliner::runOnModule(Module &M) {
1423*b5893f02SDimitry Andric   // Check if there's anything in the module. If it's empty, then there's
1424*b5893f02SDimitry Andric   // nothing to outline.
1425*b5893f02SDimitry Andric   if (M.empty())
1426*b5893f02SDimitry Andric     return false;
1427*b5893f02SDimitry Andric 
1428*b5893f02SDimitry Andric   MachineModuleInfo &MMI = getAnalysis<MachineModuleInfo>();
1429*b5893f02SDimitry Andric 
1430*b5893f02SDimitry Andric   // If the user passed -enable-machine-outliner=always or
1431*b5893f02SDimitry Andric   // -enable-machine-outliner, the pass will run on all functions in the module.
1432*b5893f02SDimitry Andric   // Otherwise, if the target supports default outlining, it will run on all
1433*b5893f02SDimitry Andric   // functions deemed by the target to be worth outlining from by default. Tell
1434*b5893f02SDimitry Andric   // the user how the outliner is running.
1435*b5893f02SDimitry Andric   LLVM_DEBUG(
1436*b5893f02SDimitry Andric     dbgs() << "Machine Outliner: Running on ";
1437*b5893f02SDimitry Andric     if (RunOnAllFunctions)
1438*b5893f02SDimitry Andric       dbgs() << "all functions";
1439*b5893f02SDimitry Andric     else
1440*b5893f02SDimitry Andric       dbgs() << "target-default functions";
1441*b5893f02SDimitry Andric     dbgs() << "\n"
1442*b5893f02SDimitry Andric   );
1443*b5893f02SDimitry Andric 
1444*b5893f02SDimitry Andric   // If the user specifies that they want to outline from linkonceodrs, set
1445*b5893f02SDimitry Andric   // it here.
1446*b5893f02SDimitry Andric   OutlineFromLinkOnceODRs = EnableLinkOnceODROutlining;
1447*b5893f02SDimitry Andric   InstructionMapper Mapper;
1448*b5893f02SDimitry Andric 
1449*b5893f02SDimitry Andric   // Prepare instruction mappings for the suffix tree.
1450*b5893f02SDimitry Andric   populateMapper(Mapper, M, MMI);
14517a7e6055SDimitry Andric   std::vector<OutlinedFunction> FunctionList;
14527a7e6055SDimitry Andric 
14537a7e6055SDimitry Andric   // Find all of the outlining candidates.
1454*b5893f02SDimitry Andric   findCandidates(Mapper, FunctionList);
14557a7e6055SDimitry Andric 
1456*b5893f02SDimitry Andric   // If we've requested size remarks, then collect the MI counts of every
1457*b5893f02SDimitry Andric   // function before outlining, and the MI counts after outlining.
1458*b5893f02SDimitry Andric   // FIXME: This shouldn't be in the outliner at all; it should ultimately be
1459*b5893f02SDimitry Andric   // the pass manager's responsibility.
1460*b5893f02SDimitry Andric   // This could pretty easily be placed in outline instead, but because we
1461*b5893f02SDimitry Andric   // really ultimately *don't* want this here, it's done like this for now
1462*b5893f02SDimitry Andric   // instead.
1463*b5893f02SDimitry Andric 
1464*b5893f02SDimitry Andric   // Check if we want size remarks.
1465*b5893f02SDimitry Andric   bool ShouldEmitSizeRemarks = M.shouldEmitInstrCountChangedRemark();
1466*b5893f02SDimitry Andric   StringMap<unsigned> FunctionToInstrCount;
1467*b5893f02SDimitry Andric   if (ShouldEmitSizeRemarks)
1468*b5893f02SDimitry Andric     initSizeRemarkInfo(M, MMI, FunctionToInstrCount);
14697a7e6055SDimitry Andric 
14707a7e6055SDimitry Andric   // Outline each of the candidates and return true if something was outlined.
1471*b5893f02SDimitry Andric   bool OutlinedSomething = outline(M, FunctionList, Mapper);
1472*b5893f02SDimitry Andric 
1473*b5893f02SDimitry Andric   // If we outlined something, we definitely changed the MI count of the
1474*b5893f02SDimitry Andric   // module. If we've asked for size remarks, then output them.
1475*b5893f02SDimitry Andric   // FIXME: This should be in the pass manager.
1476*b5893f02SDimitry Andric   if (ShouldEmitSizeRemarks && OutlinedSomething)
1477*b5893f02SDimitry Andric     emitInstrCountChangedRemark(M, MMI, FunctionToInstrCount);
14784ba319b5SDimitry Andric 
14794ba319b5SDimitry Andric   return OutlinedSomething;
14807a7e6055SDimitry Andric }
1481