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