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