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