blob: 5aecc84481a8c4227e66db58cff1225430f5a649 [file] [log] [blame]
Jessica Paquette596f4832017-03-06 21:31:18 +00001//===---- 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 Paquette4cf187b2017-09-27 20:47:39 +000018/// 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 Paquette596f4832017-03-06 21:31:18 +000035/// 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 Paquette596f4832017-03-06 21:31:18 +000062#include "llvm/CodeGen/MachineFunction.h"
Jessica Paquette596f4832017-03-06 21:31:18 +000063#include "llvm/CodeGen/MachineModuleInfo.h"
Jessica Paquetteffe4abc2017-08-31 21:02:45 +000064#include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h"
Geoff Berry82203c42018-01-31 20:15:16 +000065#include "llvm/CodeGen/MachineRegisterInfo.h"
Jessica Paquette596f4832017-03-06 21:31:18 +000066#include "llvm/CodeGen/Passes.h"
David Blaikie3f833ed2017-11-08 01:01:31 +000067#include "llvm/CodeGen/TargetInstrInfo.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000068#include "llvm/CodeGen/TargetRegisterInfo.h"
69#include "llvm/CodeGen/TargetSubtargetInfo.h"
Jessica Paquette729e6862018-01-18 00:00:58 +000070#include "llvm/IR/DIBuilder.h"
Jessica Paquette596f4832017-03-06 21:31:18 +000071#include "llvm/IR/IRBuilder.h"
Jessica Paquettea499c3c2018-01-19 21:21:49 +000072#include "llvm/IR/Mangler.h"
Jessica Paquette596f4832017-03-06 21:31:18 +000073#include "llvm/Support/Allocator.h"
Jessica Paquette1eca23b2018-04-19 22:17:07 +000074#include "llvm/Support/CommandLine.h"
Jessica Paquette596f4832017-03-06 21:31:18 +000075#include "llvm/Support/Debug.h"
76#include "llvm/Support/raw_ostream.h"
Jessica Paquette596f4832017-03-06 21:31:18 +000077#include <functional>
78#include <map>
79#include <sstream>
80#include <tuple>
81#include <vector>
82
83#define DEBUG_TYPE "machine-outliner"
84
85using namespace llvm;
Jessica Paquetteffe4abc2017-08-31 21:02:45 +000086using namespace ore;
Jessica Paquette596f4832017-03-06 21:31:18 +000087
88STATISTIC(NumOutlined, "Number of candidates outlined");
89STATISTIC(FunctionsCreated, "Number of functions created");
90
Jessica Paquette1eca23b2018-04-19 22:17:07 +000091// 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.
96static 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 Paquette596f4832017-03-06 21:31:18 +0000102namespace {
103
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000104/// An individual sequence of instructions to be replaced with a call to
Jessica Paquetteacffa282017-03-23 21:27:38 +0000105/// an outlined function.
106struct Candidate {
Jessica Paquettec9ab4c22017-10-17 18:43:15 +0000107private:
108 /// The start index of this \p Candidate in the instruction list.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000109 unsigned StartIdx;
Jessica Paquetteacffa282017-03-23 21:27:38 +0000110
111 /// The number of instructions in this \p Candidate.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000112 unsigned Len;
Jessica Paquetteacffa282017-03-23 21:27:38 +0000113
Jessica Paquettea499c3c2018-01-19 21:21:49 +0000114 /// The MachineFunction containing this \p Candidate.
115 MachineFunction *MF = nullptr;
116
Jessica Paquettec9ab4c22017-10-17 18:43:15 +0000117public:
118 /// Set to false if the candidate overlapped with another candidate.
119 bool InCandidateList = true;
120
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000121 /// The index of this \p Candidate's \p OutlinedFunction in the list of
Jessica Paquetteacffa282017-03-23 21:27:38 +0000122 /// \p OutlinedFunctions.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000123 unsigned FunctionIdx;
Jessica Paquetteacffa282017-03-23 21:27:38 +0000124
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000125 /// Contains all target-specific information for this \p Candidate.
126 TargetInstrInfo::MachineOutlinerInfo MInfo;
Jessica Paquetted87f5442017-07-29 02:55:46 +0000127
Jessica Paquettea499c3c2018-01-19 21:21:49 +0000128 /// 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 Paquettec9ab4c22017-10-17 18:43:15 +0000137 /// Return the number of instructions in this Candidate.
Jessica Paquette1934fd22017-10-23 16:25:53 +0000138 unsigned getLength() const { return Len; }
Jessica Paquettec9ab4c22017-10-17 18:43:15 +0000139
140 /// Return the start index of this candidate.
Jessica Paquette1934fd22017-10-23 16:25:53 +0000141 unsigned getStartIdx() const { return StartIdx; }
Jessica Paquettec9ab4c22017-10-17 18:43:15 +0000142
143 // Return the end index of this candidate.
Jessica Paquette1934fd22017-10-23 16:25:53 +0000144 unsigned getEndIdx() const { return StartIdx + Len - 1; }
Jessica Paquettec9ab4c22017-10-17 18:43:15 +0000145
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000146 /// The number of instructions that would be saved by outlining every
Jessica Paquetteacffa282017-03-23 21:27:38 +0000147 /// 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 Paquettea499c3c2018-01-19 21:21:49 +0000155 Candidate(unsigned StartIdx, unsigned Len, unsigned FunctionIdx,
156 MachineFunction *MF)
157 : StartIdx(StartIdx), Len(Len), MF(MF), FunctionIdx(FunctionIdx) {}
Jessica Paquetteacffa282017-03-23 21:27:38 +0000158
159 Candidate() {}
160
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000161 /// Used to ensure that \p Candidates are outlined in an order that
Jessica Paquetteacffa282017-03-23 21:27:38 +0000162 /// preserves the start and end indices of other \p Candidates.
Jessica Paquettec9ab4c22017-10-17 18:43:15 +0000163 bool operator<(const Candidate &RHS) const {
Jessica Paquette1934fd22017-10-23 16:25:53 +0000164 return getStartIdx() > RHS.getStartIdx();
Jessica Paquettec9ab4c22017-10-17 18:43:15 +0000165 }
Jessica Paquetteacffa282017-03-23 21:27:38 +0000166};
167
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000168/// The information necessary to create an outlined function for some
Jessica Paquetteacffa282017-03-23 21:27:38 +0000169/// class of candidate.
170struct OutlinedFunction {
171
Jessica Paquette85af63d2017-10-17 19:03:23 +0000172private:
173 /// The number of candidates for this \p OutlinedFunction.
174 unsigned OccurrenceCount = 0;
175
176public:
Jessica Paquette9df7fde2017-10-23 23:36:46 +0000177 std::vector<std::shared_ptr<Candidate>> Candidates;
178
Jessica Paquetteacffa282017-03-23 21:27:38 +0000179 /// The actual outlined function created.
180 /// This is initialized after we go through and create the actual function.
181 MachineFunction *MF = nullptr;
182
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000183 /// A number assigned to this function which appears at the end of its name.
184 unsigned Name;
Jessica Paquetteacffa282017-03-23 21:27:38 +0000185
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000186 /// The sequence of integers corresponding to the instructions in this
Jessica Paquetteacffa282017-03-23 21:27:38 +0000187 /// function.
188 std::vector<unsigned> Sequence;
189
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000190 /// Contains all target-specific information for this \p OutlinedFunction.
191 TargetInstrInfo::MachineOutlinerInfo MInfo;
Jessica Paquetteacffa282017-03-23 21:27:38 +0000192
Jessica Paquettea499c3c2018-01-19 21:21:49 +0000193 /// 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 Paquette85af63d2017-10-17 19:03:23 +0000202 /// Return the number of candidates for this \p OutlinedFunction.
Jessica Paquette60d31fc2017-10-17 21:11:58 +0000203 unsigned getOccurrenceCount() { return OccurrenceCount; }
Jessica Paquette85af63d2017-10-17 19:03:23 +0000204
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
Eli Friedman4081a572018-05-18 01:52:16 +0000213 /// Return the number of bytes it would take to outline this
Jessica Paquetteacc15e12017-10-03 20:32:55 +0000214 /// function.
215 unsigned getOutliningCost() {
Eli Friedman4081a572018-05-18 01:52:16 +0000216 return (OccurrenceCount * MInfo.CallOverhead) + MInfo.SequenceSize +
Jessica Paquetteacc15e12017-10-03 20:32:55 +0000217 MInfo.FrameOverhead;
218 }
219
Eli Friedman4081a572018-05-18 01:52:16 +0000220 /// Return the size in bytes of the unoutlined sequences.
221 unsigned getNotOutlinedCost() {
222 return OccurrenceCount * MInfo.SequenceSize;
223 }
224
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000225 /// Return the number of instructions that would be saved by outlining
Jessica Paquetteacc15e12017-10-03 20:32:55 +0000226 /// this function.
227 unsigned getBenefit() {
Eli Friedman4081a572018-05-18 01:52:16 +0000228 unsigned NotOutlinedCost = getNotOutlinedCost();
Jessica Paquetteacc15e12017-10-03 20:32:55 +0000229 unsigned OutlinedCost = getOutliningCost();
230 return (NotOutlinedCost < OutlinedCost) ? 0
231 : NotOutlinedCost - OutlinedCost;
232 }
233
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000234 OutlinedFunction(unsigned Name, unsigned OccurrenceCount,
Jessica Paquetteacc15e12017-10-03 20:32:55 +0000235 const std::vector<unsigned> &Sequence,
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000236 TargetInstrInfo::MachineOutlinerInfo &MInfo)
Jessica Paquette85af63d2017-10-17 19:03:23 +0000237 : OccurrenceCount(OccurrenceCount), Name(Name), Sequence(Sequence),
Jessica Paquetteacc15e12017-10-03 20:32:55 +0000238 MInfo(MInfo) {}
Jessica Paquetteacffa282017-03-23 21:27:38 +0000239};
240
Jessica Paquette596f4832017-03-06 21:31:18 +0000241/// Represents an undefined index in the suffix tree.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000242const unsigned EmptyIdx = -1;
Jessica Paquette596f4832017-03-06 21:31:18 +0000243
244/// A node in a suffix tree which represents a substring or suffix.
245///
246/// Each node has either no children or at least two children, with the root
247/// being a exception in the empty tree.
248///
249/// Children are represented as a map between unsigned integers and nodes. If
250/// a node N has a child M on unsigned integer k, then the mapping represented
251/// by N is a proper prefix of the mapping represented by M. Note that this,
252/// although similar to a trie is somewhat different: each node stores a full
253/// substring of the full mapping rather than a single character state.
254///
255/// Each internal node contains a pointer to the internal node representing
256/// the same string, but with the first character chopped off. This is stored
257/// in \p Link. Each leaf node stores the start index of its respective
258/// suffix in \p SuffixIdx.
259struct SuffixTreeNode {
260
261 /// The children of this node.
262 ///
263 /// A child existing on an unsigned integer implies that from the mapping
264 /// represented by the current node, there is a way to reach another
265 /// mapping by tacking that character on the end of the current string.
266 DenseMap<unsigned, SuffixTreeNode *> Children;
267
268 /// A flag set to false if the node has been pruned from the tree.
269 bool IsInTree = true;
270
271 /// The start index of this node's substring in the main string.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000272 unsigned StartIdx = EmptyIdx;
Jessica Paquette596f4832017-03-06 21:31:18 +0000273
274 /// The end index of this node's substring in the main string.
275 ///
276 /// Every leaf node must have its \p EndIdx incremented at the end of every
277 /// step in the construction algorithm. To avoid having to update O(N)
278 /// nodes individually at the end of every step, the end index is stored
279 /// as a pointer.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000280 unsigned *EndIdx = nullptr;
Jessica Paquette596f4832017-03-06 21:31:18 +0000281
282 /// For leaves, the start index of the suffix represented by this node.
283 ///
284 /// For all other nodes, this is ignored.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000285 unsigned SuffixIdx = EmptyIdx;
Jessica Paquette596f4832017-03-06 21:31:18 +0000286
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000287 /// For internal nodes, a pointer to the internal node representing
Jessica Paquette596f4832017-03-06 21:31:18 +0000288 /// the same sequence with the first character chopped off.
289 ///
Jessica Paquette4602c342017-07-28 05:59:30 +0000290 /// This acts as a shortcut in Ukkonen's algorithm. One of the things that
Jessica Paquette596f4832017-03-06 21:31:18 +0000291 /// Ukkonen's algorithm does to achieve linear-time construction is
292 /// keep track of which node the next insert should be at. This makes each
293 /// insert O(1), and there are a total of O(N) inserts. The suffix link
294 /// helps with inserting children of internal nodes.
295 ///
Jessica Paquette78681be2017-07-27 23:24:43 +0000296 /// Say we add a child to an internal node with associated mapping S. The
Jessica Paquette596f4832017-03-06 21:31:18 +0000297 /// next insertion must be at the node representing S - its first character.
298 /// This is given by the way that we iteratively build the tree in Ukkonen's
299 /// algorithm. The main idea is to look at the suffixes of each prefix in the
300 /// string, starting with the longest suffix of the prefix, and ending with
301 /// the shortest. Therefore, if we keep pointers between such nodes, we can
302 /// move to the next insertion point in O(1) time. If we don't, then we'd
303 /// have to query from the root, which takes O(N) time. This would make the
304 /// construction algorithm O(N^2) rather than O(N).
Jessica Paquette596f4832017-03-06 21:31:18 +0000305 SuffixTreeNode *Link = nullptr;
306
307 /// The parent of this node. Every node except for the root has a parent.
308 SuffixTreeNode *Parent = nullptr;
309
310 /// The number of times this node's string appears in the tree.
311 ///
312 /// This is equal to the number of leaf children of the string. It represents
313 /// the number of suffixes that the node's string is a prefix of.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000314 unsigned OccurrenceCount = 0;
Jessica Paquette596f4832017-03-06 21:31:18 +0000315
Jessica Paquetteacffa282017-03-23 21:27:38 +0000316 /// The length of the string formed by concatenating the edge labels from the
317 /// root to this node.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000318 unsigned ConcatLen = 0;
Jessica Paquetteacffa282017-03-23 21:27:38 +0000319
Jessica Paquette596f4832017-03-06 21:31:18 +0000320 /// Returns true if this node is a leaf.
321 bool isLeaf() const { return SuffixIdx != EmptyIdx; }
322
323 /// Returns true if this node is the root of its owning \p SuffixTree.
324 bool isRoot() const { return StartIdx == EmptyIdx; }
325
326 /// Return the number of elements in the substring associated with this node.
327 size_t size() const {
328
329 // Is it the root? If so, it's the empty string so return 0.
330 if (isRoot())
331 return 0;
332
333 assert(*EndIdx != EmptyIdx && "EndIdx is undefined!");
334
335 // Size = the number of elements in the string.
336 // For example, [0 1 2 3] has length 4, not 3. 3-0 = 3, so we have 3-0+1.
337 return *EndIdx - StartIdx + 1;
338 }
339
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000340 SuffixTreeNode(unsigned StartIdx, unsigned *EndIdx, SuffixTreeNode *Link,
Jessica Paquette596f4832017-03-06 21:31:18 +0000341 SuffixTreeNode *Parent)
342 : StartIdx(StartIdx), EndIdx(EndIdx), Link(Link), Parent(Parent) {}
343
344 SuffixTreeNode() {}
345};
346
347/// A data structure for fast substring queries.
348///
349/// Suffix trees represent the suffixes of their input strings in their leaves.
350/// A suffix tree is a type of compressed trie structure where each node
351/// represents an entire substring rather than a single character. Each leaf
352/// of the tree is a suffix.
353///
354/// A suffix tree can be seen as a type of state machine where each state is a
355/// substring of the full string. The tree is structured so that, for a string
356/// of length N, there are exactly N leaves in the tree. This structure allows
357/// us to quickly find repeated substrings of the input string.
358///
359/// In this implementation, a "string" is a vector of unsigned integers.
360/// These integers may result from hashing some data type. A suffix tree can
361/// contain 1 or many strings, which can then be queried as one large string.
362///
363/// The suffix tree is implemented using Ukkonen's algorithm for linear-time
364/// suffix tree construction. Ukkonen's algorithm is explained in more detail
365/// in the paper by Esko Ukkonen "On-line construction of suffix trees. The
366/// paper is available at
367///
368/// https://www.cs.helsinki.fi/u/ukkonen/SuffixT1withFigs.pdf
369class SuffixTree {
Jessica Paquette78681be2017-07-27 23:24:43 +0000370public:
371 /// Stores each leaf node in the tree.
372 ///
373 /// This is used for finding outlining candidates.
374 std::vector<SuffixTreeNode *> LeafVector;
375
Jessica Paquette596f4832017-03-06 21:31:18 +0000376 /// Each element is an integer representing an instruction in the module.
377 ArrayRef<unsigned> Str;
378
Jessica Paquette78681be2017-07-27 23:24:43 +0000379private:
Jessica Paquette596f4832017-03-06 21:31:18 +0000380 /// Maintains each node in the tree.
Jessica Paquetted4cb9c62017-03-08 23:55:33 +0000381 SpecificBumpPtrAllocator<SuffixTreeNode> NodeAllocator;
Jessica Paquette596f4832017-03-06 21:31:18 +0000382
383 /// The root of the suffix tree.
384 ///
385 /// The root represents the empty string. It is maintained by the
386 /// \p NodeAllocator like every other node in the tree.
387 SuffixTreeNode *Root = nullptr;
388
Jessica Paquette596f4832017-03-06 21:31:18 +0000389 /// Maintains the end indices of the internal nodes in the tree.
390 ///
391 /// Each internal node is guaranteed to never have its end index change
392 /// during the construction algorithm; however, leaves must be updated at
393 /// every step. Therefore, we need to store leaf end indices by reference
394 /// to avoid updating O(N) leaves at every step of construction. Thus,
395 /// every internal node must be allocated its own end index.
396 BumpPtrAllocator InternalEndIdxAllocator;
397
398 /// The end index of each leaf in the tree.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000399 unsigned LeafEndIdx = -1;
Jessica Paquette596f4832017-03-06 21:31:18 +0000400
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000401 /// Helper struct which keeps track of the next insertion point in
Jessica Paquette596f4832017-03-06 21:31:18 +0000402 /// Ukkonen's algorithm.
403 struct ActiveState {
404 /// The next node to insert at.
405 SuffixTreeNode *Node;
406
407 /// The index of the first character in the substring currently being added.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000408 unsigned Idx = EmptyIdx;
Jessica Paquette596f4832017-03-06 21:31:18 +0000409
410 /// The length of the substring we have to add at the current step.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000411 unsigned Len = 0;
Jessica Paquette596f4832017-03-06 21:31:18 +0000412 };
413
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000414 /// The point the next insertion will take place at in the
Jessica Paquette596f4832017-03-06 21:31:18 +0000415 /// construction algorithm.
416 ActiveState Active;
417
418 /// Allocate a leaf node and add it to the tree.
419 ///
420 /// \param Parent The parent of this node.
421 /// \param StartIdx The start index of this node's associated string.
422 /// \param Edge The label on the edge leaving \p Parent to this node.
423 ///
424 /// \returns A pointer to the allocated leaf node.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000425 SuffixTreeNode *insertLeaf(SuffixTreeNode &Parent, unsigned StartIdx,
Jessica Paquette596f4832017-03-06 21:31:18 +0000426 unsigned Edge) {
427
428 assert(StartIdx <= LeafEndIdx && "String can't start after it ends!");
429
Jessica Paquette78681be2017-07-27 23:24:43 +0000430 SuffixTreeNode *N = new (NodeAllocator.Allocate())
431 SuffixTreeNode(StartIdx, &LeafEndIdx, nullptr, &Parent);
Jessica Paquette596f4832017-03-06 21:31:18 +0000432 Parent.Children[Edge] = N;
433
434 return N;
435 }
436
437 /// Allocate an internal node and add it to the tree.
438 ///
439 /// \param Parent The parent of this node. Only null when allocating the root.
440 /// \param StartIdx The start index of this node's associated string.
441 /// \param EndIdx The end index of this node's associated string.
442 /// \param Edge The label on the edge leaving \p Parent to this node.
443 ///
444 /// \returns A pointer to the allocated internal node.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000445 SuffixTreeNode *insertInternalNode(SuffixTreeNode *Parent, unsigned StartIdx,
446 unsigned EndIdx, unsigned Edge) {
Jessica Paquette596f4832017-03-06 21:31:18 +0000447
448 assert(StartIdx <= EndIdx && "String can't start after it ends!");
449 assert(!(!Parent && StartIdx != EmptyIdx) &&
Jessica Paquette78681be2017-07-27 23:24:43 +0000450 "Non-root internal nodes must have parents!");
Jessica Paquette596f4832017-03-06 21:31:18 +0000451
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000452 unsigned *E = new (InternalEndIdxAllocator) unsigned(EndIdx);
Jessica Paquette78681be2017-07-27 23:24:43 +0000453 SuffixTreeNode *N = new (NodeAllocator.Allocate())
454 SuffixTreeNode(StartIdx, E, Root, Parent);
Jessica Paquette596f4832017-03-06 21:31:18 +0000455 if (Parent)
456 Parent->Children[Edge] = N;
457
458 return N;
459 }
460
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000461 /// Set the suffix indices of the leaves to the start indices of their
Jessica Paquette596f4832017-03-06 21:31:18 +0000462 /// respective suffixes. Also stores each leaf in \p LeafVector at its
463 /// respective suffix index.
464 ///
465 /// \param[in] CurrNode The node currently being visited.
466 /// \param CurrIdx The current index of the string being visited.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000467 void setSuffixIndices(SuffixTreeNode &CurrNode, unsigned CurrIdx) {
Jessica Paquette596f4832017-03-06 21:31:18 +0000468
469 bool IsLeaf = CurrNode.Children.size() == 0 && !CurrNode.isRoot();
470
Jessica Paquetteacffa282017-03-23 21:27:38 +0000471 // Store the length of the concatenation of all strings from the root to
472 // this node.
473 if (!CurrNode.isRoot()) {
474 if (CurrNode.ConcatLen == 0)
475 CurrNode.ConcatLen = CurrNode.size();
476
477 if (CurrNode.Parent)
Jessica Paquette78681be2017-07-27 23:24:43 +0000478 CurrNode.ConcatLen += CurrNode.Parent->ConcatLen;
Jessica Paquetteacffa282017-03-23 21:27:38 +0000479 }
480
Jessica Paquette596f4832017-03-06 21:31:18 +0000481 // Traverse the tree depth-first.
482 for (auto &ChildPair : CurrNode.Children) {
483 assert(ChildPair.second && "Node had a null child!");
Jessica Paquette78681be2017-07-27 23:24:43 +0000484 setSuffixIndices(*ChildPair.second, CurrIdx + ChildPair.second->size());
Jessica Paquette596f4832017-03-06 21:31:18 +0000485 }
486
487 // Is this node a leaf?
488 if (IsLeaf) {
489 // If yes, give it a suffix index and bump its parent's occurrence count.
490 CurrNode.SuffixIdx = Str.size() - CurrIdx;
491 assert(CurrNode.Parent && "CurrNode had no parent!");
492 CurrNode.Parent->OccurrenceCount++;
493
494 // Store the leaf in the leaf vector for pruning later.
495 LeafVector[CurrNode.SuffixIdx] = &CurrNode;
496 }
497 }
498
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000499 /// Construct the suffix tree for the prefix of the input ending at
Jessica Paquette596f4832017-03-06 21:31:18 +0000500 /// \p EndIdx.
501 ///
502 /// Used to construct the full suffix tree iteratively. At the end of each
503 /// step, the constructed suffix tree is either a valid suffix tree, or a
504 /// suffix tree with implicit suffixes. At the end of the final step, the
505 /// suffix tree is a valid tree.
506 ///
507 /// \param EndIdx The end index of the current prefix in the main string.
508 /// \param SuffixesToAdd The number of suffixes that must be added
509 /// to complete the suffix tree at the current phase.
510 ///
511 /// \returns The number of suffixes that have not been added at the end of
512 /// this step.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000513 unsigned extend(unsigned EndIdx, unsigned SuffixesToAdd) {
Jessica Paquette596f4832017-03-06 21:31:18 +0000514 SuffixTreeNode *NeedsLink = nullptr;
515
516 while (SuffixesToAdd > 0) {
Jessica Paquette78681be2017-07-27 23:24:43 +0000517
Jessica Paquette596f4832017-03-06 21:31:18 +0000518 // Are we waiting to add anything other than just the last character?
519 if (Active.Len == 0) {
520 // If not, then say the active index is the end index.
521 Active.Idx = EndIdx;
522 }
523
524 assert(Active.Idx <= EndIdx && "Start index can't be after end index!");
525
526 // The first character in the current substring we're looking at.
527 unsigned FirstChar = Str[Active.Idx];
528
529 // Have we inserted anything starting with FirstChar at the current node?
530 if (Active.Node->Children.count(FirstChar) == 0) {
531 // If not, then we can just insert a leaf and move too the next step.
532 insertLeaf(*Active.Node, EndIdx, FirstChar);
533
534 // The active node is an internal node, and we visited it, so it must
535 // need a link if it doesn't have one.
536 if (NeedsLink) {
537 NeedsLink->Link = Active.Node;
538 NeedsLink = nullptr;
539 }
540 } else {
541 // There's a match with FirstChar, so look for the point in the tree to
542 // insert a new node.
543 SuffixTreeNode *NextNode = Active.Node->Children[FirstChar];
544
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000545 unsigned SubstringLen = NextNode->size();
Jessica Paquette596f4832017-03-06 21:31:18 +0000546
547 // Is the current suffix we're trying to insert longer than the size of
548 // the child we want to move to?
549 if (Active.Len >= SubstringLen) {
550 // If yes, then consume the characters we've seen and move to the next
551 // node.
552 Active.Idx += SubstringLen;
553 Active.Len -= SubstringLen;
554 Active.Node = NextNode;
555 continue;
556 }
557
558 // Otherwise, the suffix we're trying to insert must be contained in the
559 // next node we want to move to.
560 unsigned LastChar = Str[EndIdx];
561
562 // Is the string we're trying to insert a substring of the next node?
563 if (Str[NextNode->StartIdx + Active.Len] == LastChar) {
564 // If yes, then we're done for this step. Remember our insertion point
565 // and move to the next end index. At this point, we have an implicit
566 // suffix tree.
567 if (NeedsLink && !Active.Node->isRoot()) {
568 NeedsLink->Link = Active.Node;
569 NeedsLink = nullptr;
570 }
571
572 Active.Len++;
573 break;
574 }
575
576 // The string we're trying to insert isn't a substring of the next node,
577 // but matches up to a point. Split the node.
578 //
579 // For example, say we ended our search at a node n and we're trying to
580 // insert ABD. Then we'll create a new node s for AB, reduce n to just
581 // representing C, and insert a new leaf node l to represent d. This
582 // allows us to ensure that if n was a leaf, it remains a leaf.
583 //
584 // | ABC ---split---> | AB
585 // n s
586 // C / \ D
587 // n l
588
589 // The node s from the diagram
590 SuffixTreeNode *SplitNode =
Jessica Paquette78681be2017-07-27 23:24:43 +0000591 insertInternalNode(Active.Node, NextNode->StartIdx,
592 NextNode->StartIdx + Active.Len - 1, FirstChar);
Jessica Paquette596f4832017-03-06 21:31:18 +0000593
594 // Insert the new node representing the new substring into the tree as
595 // a child of the split node. This is the node l from the diagram.
596 insertLeaf(*SplitNode, EndIdx, LastChar);
597
598 // Make the old node a child of the split node and update its start
599 // index. This is the node n from the diagram.
600 NextNode->StartIdx += Active.Len;
601 NextNode->Parent = SplitNode;
602 SplitNode->Children[Str[NextNode->StartIdx]] = NextNode;
603
604 // SplitNode is an internal node, update the suffix link.
605 if (NeedsLink)
606 NeedsLink->Link = SplitNode;
607
608 NeedsLink = SplitNode;
609 }
610
611 // We've added something new to the tree, so there's one less suffix to
612 // add.
613 SuffixesToAdd--;
614
615 if (Active.Node->isRoot()) {
616 if (Active.Len > 0) {
617 Active.Len--;
618 Active.Idx = EndIdx - SuffixesToAdd + 1;
619 }
620 } else {
621 // Start the next phase at the next smallest suffix.
622 Active.Node = Active.Node->Link;
623 }
624 }
625
626 return SuffixesToAdd;
627 }
628
Jessica Paquette596f4832017-03-06 21:31:18 +0000629public:
Jessica Paquette596f4832017-03-06 21:31:18 +0000630 /// Construct a suffix tree from a sequence of unsigned integers.
631 ///
632 /// \param Str The string to construct the suffix tree for.
633 SuffixTree(const std::vector<unsigned> &Str) : Str(Str) {
634 Root = insertInternalNode(nullptr, EmptyIdx, EmptyIdx, 0);
635 Root->IsInTree = true;
636 Active.Node = Root;
Jessica Paquette78681be2017-07-27 23:24:43 +0000637 LeafVector = std::vector<SuffixTreeNode *>(Str.size());
Jessica Paquette596f4832017-03-06 21:31:18 +0000638
639 // Keep track of the number of suffixes we have to add of the current
640 // prefix.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000641 unsigned SuffixesToAdd = 0;
Jessica Paquette596f4832017-03-06 21:31:18 +0000642 Active.Node = Root;
643
644 // Construct the suffix tree iteratively on each prefix of the string.
645 // PfxEndIdx is the end index of the current prefix.
646 // End is one past the last element in the string.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000647 for (unsigned PfxEndIdx = 0, End = Str.size(); PfxEndIdx < End;
648 PfxEndIdx++) {
Jessica Paquette596f4832017-03-06 21:31:18 +0000649 SuffixesToAdd++;
650 LeafEndIdx = PfxEndIdx; // Extend each of the leaves.
651 SuffixesToAdd = extend(PfxEndIdx, SuffixesToAdd);
652 }
653
654 // Set the suffix indices of each leaf.
655 assert(Root && "Root node can't be nullptr!");
656 setSuffixIndices(*Root, 0);
657 }
658};
659
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000660/// Maps \p MachineInstrs to unsigned integers and stores the mappings.
Jessica Paquette596f4832017-03-06 21:31:18 +0000661struct InstructionMapper {
662
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000663 /// The next available integer to assign to a \p MachineInstr that
Jessica Paquette596f4832017-03-06 21:31:18 +0000664 /// cannot be outlined.
665 ///
666 /// Set to -3 for compatability with \p DenseMapInfo<unsigned>.
667 unsigned IllegalInstrNumber = -3;
668
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000669 /// The next available integer to assign to a \p MachineInstr that can
Jessica Paquette596f4832017-03-06 21:31:18 +0000670 /// be outlined.
671 unsigned LegalInstrNumber = 0;
672
673 /// Correspondence from \p MachineInstrs to unsigned integers.
674 DenseMap<MachineInstr *, unsigned, MachineInstrExpressionTrait>
675 InstructionIntegerMap;
676
677 /// Corresponcence from unsigned integers to \p MachineInstrs.
678 /// Inverse of \p InstructionIntegerMap.
679 DenseMap<unsigned, MachineInstr *> IntegerInstructionMap;
680
681 /// The vector of unsigned integers that the module is mapped to.
682 std::vector<unsigned> UnsignedVec;
683
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000684 /// Stores the location of the instruction associated with the integer
Jessica Paquette596f4832017-03-06 21:31:18 +0000685 /// at index i in \p UnsignedVec for each index i.
686 std::vector<MachineBasicBlock::iterator> InstrList;
687
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000688 /// Maps \p *It to a legal integer.
Jessica Paquette596f4832017-03-06 21:31:18 +0000689 ///
690 /// Updates \p InstrList, \p UnsignedVec, \p InstructionIntegerMap,
691 /// \p IntegerInstructionMap, and \p LegalInstrNumber.
692 ///
693 /// \returns The integer that \p *It was mapped to.
694 unsigned mapToLegalUnsigned(MachineBasicBlock::iterator &It) {
695
696 // Get the integer for this instruction or give it the current
697 // LegalInstrNumber.
698 InstrList.push_back(It);
699 MachineInstr &MI = *It;
700 bool WasInserted;
701 DenseMap<MachineInstr *, unsigned, MachineInstrExpressionTrait>::iterator
Jessica Paquette78681be2017-07-27 23:24:43 +0000702 ResultIt;
Jessica Paquette596f4832017-03-06 21:31:18 +0000703 std::tie(ResultIt, WasInserted) =
Jessica Paquette78681be2017-07-27 23:24:43 +0000704 InstructionIntegerMap.insert(std::make_pair(&MI, LegalInstrNumber));
Jessica Paquette596f4832017-03-06 21:31:18 +0000705 unsigned MINumber = ResultIt->second;
706
707 // There was an insertion.
708 if (WasInserted) {
709 LegalInstrNumber++;
710 IntegerInstructionMap.insert(std::make_pair(MINumber, &MI));
711 }
712
713 UnsignedVec.push_back(MINumber);
714
715 // Make sure we don't overflow or use any integers reserved by the DenseMap.
716 if (LegalInstrNumber >= IllegalInstrNumber)
717 report_fatal_error("Instruction mapping overflow!");
718
Jessica Paquette78681be2017-07-27 23:24:43 +0000719 assert(LegalInstrNumber != DenseMapInfo<unsigned>::getEmptyKey() &&
720 "Tried to assign DenseMap tombstone or empty key to instruction.");
721 assert(LegalInstrNumber != DenseMapInfo<unsigned>::getTombstoneKey() &&
722 "Tried to assign DenseMap tombstone or empty key to instruction.");
Jessica Paquette596f4832017-03-06 21:31:18 +0000723
724 return MINumber;
725 }
726
727 /// Maps \p *It to an illegal integer.
728 ///
729 /// Updates \p InstrList, \p UnsignedVec, and \p IllegalInstrNumber.
730 ///
731 /// \returns The integer that \p *It was mapped to.
732 unsigned mapToIllegalUnsigned(MachineBasicBlock::iterator &It) {
733 unsigned MINumber = IllegalInstrNumber;
734
735 InstrList.push_back(It);
736 UnsignedVec.push_back(IllegalInstrNumber);
737 IllegalInstrNumber--;
738
739 assert(LegalInstrNumber < IllegalInstrNumber &&
740 "Instruction mapping overflow!");
741
Jessica Paquette78681be2017-07-27 23:24:43 +0000742 assert(IllegalInstrNumber != DenseMapInfo<unsigned>::getEmptyKey() &&
743 "IllegalInstrNumber cannot be DenseMap tombstone or empty key!");
Jessica Paquette596f4832017-03-06 21:31:18 +0000744
Jessica Paquette78681be2017-07-27 23:24:43 +0000745 assert(IllegalInstrNumber != DenseMapInfo<unsigned>::getTombstoneKey() &&
746 "IllegalInstrNumber cannot be DenseMap tombstone or empty key!");
Jessica Paquette596f4832017-03-06 21:31:18 +0000747
748 return MINumber;
749 }
750
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000751 /// Transforms a \p MachineBasicBlock into a \p vector of \p unsigneds
Jessica Paquette596f4832017-03-06 21:31:18 +0000752 /// and appends it to \p UnsignedVec and \p InstrList.
753 ///
754 /// Two instructions are assigned the same integer if they are identical.
755 /// If an instruction is deemed unsafe to outline, then it will be assigned an
756 /// unique integer. The resulting mapping is placed into a suffix tree and
757 /// queried for candidates.
758 ///
759 /// \param MBB The \p MachineBasicBlock to be translated into integers.
760 /// \param TRI \p TargetRegisterInfo for the module.
761 /// \param TII \p TargetInstrInfo for the module.
762 void convertToUnsignedVec(MachineBasicBlock &MBB,
763 const TargetRegisterInfo &TRI,
764 const TargetInstrInfo &TII) {
Jessica Paquette3291e732018-01-09 00:26:18 +0000765 unsigned Flags = TII.getMachineOutlinerMBBFlags(MBB);
766
Jessica Paquette596f4832017-03-06 21:31:18 +0000767 for (MachineBasicBlock::iterator It = MBB.begin(), Et = MBB.end(); It != Et;
768 It++) {
769
770 // Keep track of where this instruction is in the module.
Jessica Paquette3291e732018-01-09 00:26:18 +0000771 switch (TII.getOutliningType(It, Flags)) {
Jessica Paquette78681be2017-07-27 23:24:43 +0000772 case TargetInstrInfo::MachineOutlinerInstrType::Illegal:
773 mapToIllegalUnsigned(It);
774 break;
Jessica Paquette596f4832017-03-06 21:31:18 +0000775
Jessica Paquette78681be2017-07-27 23:24:43 +0000776 case TargetInstrInfo::MachineOutlinerInstrType::Legal:
777 mapToLegalUnsigned(It);
778 break;
Jessica Paquette596f4832017-03-06 21:31:18 +0000779
Eli Friedman042dc9e2018-05-22 19:11:06 +0000780 case TargetInstrInfo::MachineOutlinerInstrType::LegalTerminator:
781 mapToLegalUnsigned(It);
782 InstrList.push_back(It);
783 UnsignedVec.push_back(IllegalInstrNumber);
784 IllegalInstrNumber--;
785 break;
786
Jessica Paquette78681be2017-07-27 23:24:43 +0000787 case TargetInstrInfo::MachineOutlinerInstrType::Invisible:
788 break;
Jessica Paquette596f4832017-03-06 21:31:18 +0000789 }
790 }
791
792 // After we're done every insertion, uniquely terminate this part of the
793 // "string". This makes sure we won't match across basic block or function
794 // boundaries since the "end" is encoded uniquely and thus appears in no
795 // repeated substring.
796 InstrList.push_back(MBB.end());
797 UnsignedVec.push_back(IllegalInstrNumber);
798 IllegalInstrNumber--;
799 }
800
801 InstructionMapper() {
802 // Make sure that the implementation of DenseMapInfo<unsigned> hasn't
803 // changed.
804 assert(DenseMapInfo<unsigned>::getEmptyKey() == (unsigned)-1 &&
Jessica Paquette78681be2017-07-27 23:24:43 +0000805 "DenseMapInfo<unsigned>'s empty key isn't -1!");
Jessica Paquette596f4832017-03-06 21:31:18 +0000806 assert(DenseMapInfo<unsigned>::getTombstoneKey() == (unsigned)-2 &&
Jessica Paquette78681be2017-07-27 23:24:43 +0000807 "DenseMapInfo<unsigned>'s tombstone key isn't -2!");
Jessica Paquette596f4832017-03-06 21:31:18 +0000808 }
809};
810
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000811/// An interprocedural pass which finds repeated sequences of
Jessica Paquette596f4832017-03-06 21:31:18 +0000812/// instructions and replaces them with calls to functions.
813///
814/// Each instruction is mapped to an unsigned integer and placed in a string.
815/// The resulting mapping is then placed in a \p SuffixTree. The \p SuffixTree
816/// is then repeatedly queried for repeated sequences of instructions. Each
817/// non-overlapping repeated sequence is then placed in its own
818/// \p MachineFunction and each instance is then replaced with a call to that
819/// function.
820struct MachineOutliner : public ModulePass {
821
822 static char ID;
823
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000824 /// Set to true if the outliner should consider functions with
Jessica Paquette13593842017-10-07 00:16:34 +0000825 /// linkonceodr linkage.
826 bool OutlineFromLinkOnceODRs = false;
827
Jessica Paquette729e6862018-01-18 00:00:58 +0000828 // Collection of IR functions created by the outliner.
829 std::vector<Function *> CreatedIRFunctions;
830
Jessica Paquette596f4832017-03-06 21:31:18 +0000831 StringRef getPassName() const override { return "Machine Outliner"; }
832
833 void getAnalysisUsage(AnalysisUsage &AU) const override {
834 AU.addRequired<MachineModuleInfo>();
835 AU.addPreserved<MachineModuleInfo>();
836 AU.setPreservesAll();
837 ModulePass::getAnalysisUsage(AU);
838 }
839
Jessica Paquette1eca23b2018-04-19 22:17:07 +0000840 MachineOutliner() : ModulePass(ID) {
Jessica Paquette596f4832017-03-06 21:31:18 +0000841 initializeMachineOutlinerPass(*PassRegistry::getPassRegistry());
842 }
843
Jessica Paquette78681be2017-07-27 23:24:43 +0000844 /// Find all repeated substrings that satisfy the outlining cost model.
845 ///
846 /// If a substring appears at least twice, then it must be represented by
847 /// an internal node which appears in at least two suffixes. Each suffix is
848 /// represented by a leaf node. To do this, we visit each internal node in
849 /// the tree, using the leaf children of each internal node. If an internal
850 /// node represents a beneficial substring, then we use each of its leaf
851 /// children to find the locations of its substring.
852 ///
853 /// \param ST A suffix tree to query.
854 /// \param TII TargetInstrInfo for the target.
855 /// \param Mapper Contains outlining mapping information.
856 /// \param[out] CandidateList Filled with candidates representing each
857 /// beneficial substring.
858 /// \param[out] FunctionList Filled with a list of \p OutlinedFunctions each
859 /// type of candidate.
860 ///
861 /// \returns The length of the longest candidate found.
Jessica Paquette9df7fde2017-10-23 23:36:46 +0000862 unsigned
863 findCandidates(SuffixTree &ST, const TargetInstrInfo &TII,
864 InstructionMapper &Mapper,
865 std::vector<std::shared_ptr<Candidate>> &CandidateList,
866 std::vector<OutlinedFunction> &FunctionList);
Jessica Paquette78681be2017-07-27 23:24:43 +0000867
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000868 /// Replace the sequences of instructions represented by the
Jessica Paquette596f4832017-03-06 21:31:18 +0000869 /// \p Candidates in \p CandidateList with calls to \p MachineFunctions
870 /// described in \p FunctionList.
871 ///
872 /// \param M The module we are outlining from.
873 /// \param CandidateList A list of candidates to be outlined.
874 /// \param FunctionList A list of functions to be inserted into the module.
875 /// \param Mapper Contains the instruction mappings for the module.
Jessica Paquette9df7fde2017-10-23 23:36:46 +0000876 bool outline(Module &M,
877 const ArrayRef<std::shared_ptr<Candidate>> &CandidateList,
Jessica Paquette596f4832017-03-06 21:31:18 +0000878 std::vector<OutlinedFunction> &FunctionList,
879 InstructionMapper &Mapper);
880
881 /// Creates a function for \p OF and inserts it into the module.
882 MachineFunction *createOutlinedFunction(Module &M, const OutlinedFunction &OF,
883 InstructionMapper &Mapper);
884
885 /// Find potential outlining candidates and store them in \p CandidateList.
886 ///
887 /// For each type of potential candidate, also build an \p OutlinedFunction
888 /// struct containing the information to build the function for that
889 /// candidate.
890 ///
891 /// \param[out] CandidateList Filled with outlining candidates for the module.
892 /// \param[out] FunctionList Filled with functions corresponding to each type
893 /// of \p Candidate.
894 /// \param ST The suffix tree for the module.
895 /// \param TII TargetInstrInfo for the module.
896 ///
897 /// \returns The length of the longest candidate found. 0 if there are none.
Jessica Paquette9df7fde2017-10-23 23:36:46 +0000898 unsigned
899 buildCandidateList(std::vector<std::shared_ptr<Candidate>> &CandidateList,
900 std::vector<OutlinedFunction> &FunctionList,
901 SuffixTree &ST, InstructionMapper &Mapper,
902 const TargetInstrInfo &TII);
Jessica Paquette596f4832017-03-06 21:31:18 +0000903
Jessica Paquette60d31fc2017-10-17 21:11:58 +0000904 /// Helper function for pruneOverlaps.
905 /// Removes \p C from the candidate list, and updates its \p OutlinedFunction.
906 void prune(Candidate &C, std::vector<OutlinedFunction> &FunctionList);
907
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000908 /// Remove any overlapping candidates that weren't handled by the
Jessica Paquette596f4832017-03-06 21:31:18 +0000909 /// suffix tree's pruning method.
910 ///
911 /// Pruning from the suffix tree doesn't necessarily remove all overlaps.
912 /// If a short candidate is chosen for outlining, then a longer candidate
913 /// which has that short candidate as a suffix is chosen, the tree's pruning
914 /// method will not find it. Thus, we need to prune before outlining as well.
915 ///
916 /// \param[in,out] CandidateList A list of outlining candidates.
917 /// \param[in,out] FunctionList A list of functions to be outlined.
Jessica Paquette809d7082017-07-28 03:21:58 +0000918 /// \param Mapper Contains instruction mapping info for outlining.
Jessica Paquette596f4832017-03-06 21:31:18 +0000919 /// \param MaxCandidateLen The length of the longest candidate.
920 /// \param TII TargetInstrInfo for the module.
Jessica Paquette9df7fde2017-10-23 23:36:46 +0000921 void pruneOverlaps(std::vector<std::shared_ptr<Candidate>> &CandidateList,
Jessica Paquette596f4832017-03-06 21:31:18 +0000922 std::vector<OutlinedFunction> &FunctionList,
Jessica Paquette809d7082017-07-28 03:21:58 +0000923 InstructionMapper &Mapper, unsigned MaxCandidateLen,
924 const TargetInstrInfo &TII);
Jessica Paquette596f4832017-03-06 21:31:18 +0000925
926 /// Construct a suffix tree on the instructions in \p M and outline repeated
927 /// strings from that tree.
928 bool runOnModule(Module &M) override;
929};
930
931} // Anonymous namespace.
932
933char MachineOutliner::ID = 0;
934
935namespace llvm {
Jessica Paquette1eca23b2018-04-19 22:17:07 +0000936ModulePass *createMachineOutlinerPass() {
937 return new MachineOutliner();
Jessica Paquette13593842017-10-07 00:16:34 +0000938}
939
Jessica Paquette78681be2017-07-27 23:24:43 +0000940} // namespace llvm
Jessica Paquette596f4832017-03-06 21:31:18 +0000941
Jessica Paquette78681be2017-07-27 23:24:43 +0000942INITIALIZE_PASS(MachineOutliner, DEBUG_TYPE, "Machine Function Outliner", false,
943 false)
944
Jessica Paquette9df7fde2017-10-23 23:36:46 +0000945unsigned MachineOutliner::findCandidates(
946 SuffixTree &ST, const TargetInstrInfo &TII, InstructionMapper &Mapper,
947 std::vector<std::shared_ptr<Candidate>> &CandidateList,
948 std::vector<OutlinedFunction> &FunctionList) {
Jessica Paquette78681be2017-07-27 23:24:43 +0000949 CandidateList.clear();
950 FunctionList.clear();
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000951 unsigned MaxLen = 0;
Jessica Paquette78681be2017-07-27 23:24:43 +0000952
953 // FIXME: Visit internal nodes instead of leaves.
954 for (SuffixTreeNode *Leaf : ST.LeafVector) {
955 assert(Leaf && "Leaves in LeafVector cannot be null!");
956 if (!Leaf->IsInTree)
957 continue;
958
959 assert(Leaf->Parent && "All leaves must have parents!");
960 SuffixTreeNode &Parent = *(Leaf->Parent);
961
962 // If it doesn't appear enough, or we already outlined from it, skip it.
963 if (Parent.OccurrenceCount < 2 || Parent.isRoot() || !Parent.IsInTree)
964 continue;
965
Jessica Paquette809d7082017-07-28 03:21:58 +0000966 // Figure out if this candidate is beneficial.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000967 unsigned StringLen = Leaf->ConcatLen - (unsigned)Leaf->size();
Jessica Paquette95c11072017-08-14 22:57:41 +0000968
969 // Too short to be beneficial; skip it.
970 // FIXME: This isn't necessarily true for, say, X86. If we factor in
971 // instruction lengths we need more information than this.
972 if (StringLen < 2)
973 continue;
974
Jessica Paquetted87f5442017-07-29 02:55:46 +0000975 // If this is a beneficial class of candidate, then every one is stored in
976 // this vector.
977 std::vector<Candidate> CandidatesForRepeatedSeq;
978
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000979 // Describes the start and end point of each candidate. This allows the
980 // target to infer some information about each occurrence of each repeated
981 // sequence.
Jessica Paquetted87f5442017-07-29 02:55:46 +0000982 // FIXME: CandidatesForRepeatedSeq and this should be combined.
983 std::vector<
984 std::pair<MachineBasicBlock::iterator, MachineBasicBlock::iterator>>
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000985 RepeatedSequenceLocs;
Jessica Paquetted87f5442017-07-29 02:55:46 +0000986
Jessica Paquette809d7082017-07-28 03:21:58 +0000987 // Figure out the call overhead for each instance of the sequence.
988 for (auto &ChildPair : Parent.Children) {
989 SuffixTreeNode *M = ChildPair.second;
Jessica Paquette78681be2017-07-27 23:24:43 +0000990
Jessica Paquette809d7082017-07-28 03:21:58 +0000991 if (M && M->IsInTree && M->isLeaf()) {
Jessica Paquetted87f5442017-07-29 02:55:46 +0000992 // Never visit this leaf again.
993 M->IsInTree = false;
Jessica Paquette52df8012017-12-01 21:56:56 +0000994 unsigned StartIdx = M->SuffixIdx;
995 unsigned EndIdx = StartIdx + StringLen - 1;
996
997 // Trick: Discard some candidates that would be incompatible with the
998 // ones we've already found for this sequence. This will save us some
999 // work in candidate selection.
1000 //
1001 // If two candidates overlap, then we can't outline them both. This
1002 // happens when we have candidates that look like, say
1003 //
1004 // AA (where each "A" is an instruction).
1005 //
1006 // We might have some portion of the module that looks like this:
1007 // AAAAAA (6 A's)
1008 //
1009 // In this case, there are 5 different copies of "AA" in this range, but
1010 // at most 3 can be outlined. If only outlining 3 of these is going to
1011 // be unbeneficial, then we ought to not bother.
1012 //
1013 // Note that two things DON'T overlap when they look like this:
1014 // start1...end1 .... start2...end2
1015 // That is, one must either
1016 // * End before the other starts
1017 // * Start after the other ends
1018 if (std::all_of(CandidatesForRepeatedSeq.begin(),
1019 CandidatesForRepeatedSeq.end(),
1020 [&StartIdx, &EndIdx](const Candidate &C) {
1021 return (EndIdx < C.getStartIdx() ||
1022 StartIdx > C.getEndIdx());
1023 })) {
1024 // It doesn't overlap with anything, so we can outline it.
1025 // Each sequence is over [StartIt, EndIt].
1026 MachineBasicBlock::iterator StartIt = Mapper.InstrList[StartIdx];
1027 MachineBasicBlock::iterator EndIt = Mapper.InstrList[EndIdx];
1028
Jessica Paquettea499c3c2018-01-19 21:21:49 +00001029 // Save the MachineFunction containing the Candidate.
1030 MachineFunction *MF = StartIt->getParent()->getParent();
1031 assert(MF && "Candidate doesn't have a MF?");
1032
Jessica Paquette52df8012017-12-01 21:56:56 +00001033 // Save the candidate and its location.
1034 CandidatesForRepeatedSeq.emplace_back(StartIdx, StringLen,
Jessica Paquettea499c3c2018-01-19 21:21:49 +00001035 FunctionList.size(), MF);
Jessica Paquette52df8012017-12-01 21:56:56 +00001036 RepeatedSequenceLocs.emplace_back(std::make_pair(StartIt, EndIt));
1037 }
Jessica Paquette809d7082017-07-28 03:21:58 +00001038 }
1039 }
1040
Jessica Paquetteacc15e12017-10-03 20:32:55 +00001041 // We've found something we might want to outline.
1042 // Create an OutlinedFunction to store it and check if it'd be beneficial
1043 // to outline.
Jessica Paquette4cf187b2017-09-27 20:47:39 +00001044 TargetInstrInfo::MachineOutlinerInfo MInfo =
1045 TII.getOutlininingCandidateInfo(RepeatedSequenceLocs);
Jessica Paquetteacc15e12017-10-03 20:32:55 +00001046 std::vector<unsigned> Seq;
1047 for (unsigned i = Leaf->SuffixIdx; i < Leaf->SuffixIdx + StringLen; i++)
1048 Seq.push_back(ST.Str[i]);
Jessica Paquette52df8012017-12-01 21:56:56 +00001049 OutlinedFunction OF(FunctionList.size(), CandidatesForRepeatedSeq.size(),
1050 Seq, MInfo);
Jessica Paquetteacc15e12017-10-03 20:32:55 +00001051 unsigned Benefit = OF.getBenefit();
Jessica Paquette809d7082017-07-28 03:21:58 +00001052
Jessica Paquetteffe4abc2017-08-31 21:02:45 +00001053 // Is it better to outline this candidate than not?
Jessica Paquetteacc15e12017-10-03 20:32:55 +00001054 if (Benefit < 1) {
Jessica Paquetteffe4abc2017-08-31 21:02:45 +00001055 // Outlining this candidate would take more instructions than not
1056 // outlining.
1057 // Emit a remark explaining why we didn't outline this candidate.
1058 std::pair<MachineBasicBlock::iterator, MachineBasicBlock::iterator> C =
Jessica Paquette4cf187b2017-09-27 20:47:39 +00001059 RepeatedSequenceLocs[0];
Vivek Pandya95906582017-10-11 17:12:59 +00001060 MachineOptimizationRemarkEmitter MORE(
1061 *(C.first->getParent()->getParent()), nullptr);
1062 MORE.emit([&]() {
1063 MachineOptimizationRemarkMissed R(DEBUG_TYPE, "NotOutliningCheaper",
1064 C.first->getDebugLoc(),
1065 C.first->getParent());
1066 R << "Did not outline " << NV("Length", StringLen) << " instructions"
1067 << " from " << NV("NumOccurrences", RepeatedSequenceLocs.size())
1068 << " locations."
Eli Friedman4081a572018-05-18 01:52:16 +00001069 << " Bytes from outlining all occurrences ("
Vivek Pandya95906582017-10-11 17:12:59 +00001070 << NV("OutliningCost", OF.getOutliningCost()) << ")"
Eli Friedman4081a572018-05-18 01:52:16 +00001071 << " >= Unoutlined instruction bytes ("
1072 << NV("NotOutliningCost", OF.getNotOutlinedCost()) << ")"
Vivek Pandya95906582017-10-11 17:12:59 +00001073 << " (Also found at: ";
Jessica Paquetteffe4abc2017-08-31 21:02:45 +00001074
Vivek Pandya95906582017-10-11 17:12:59 +00001075 // Tell the user the other places the candidate was found.
1076 for (unsigned i = 1, e = RepeatedSequenceLocs.size(); i < e; i++) {
1077 R << NV((Twine("OtherStartLoc") + Twine(i)).str(),
1078 RepeatedSequenceLocs[i].first->getDebugLoc());
1079 if (i != e - 1)
1080 R << ", ";
1081 }
Jessica Paquetteffe4abc2017-08-31 21:02:45 +00001082
Vivek Pandya95906582017-10-11 17:12:59 +00001083 R << ")";
1084 return R;
1085 });
Jessica Paquetteffe4abc2017-08-31 21:02:45 +00001086
1087 // Move to the next candidate.
Jessica Paquette78681be2017-07-27 23:24:43 +00001088 continue;
Jessica Paquetteffe4abc2017-08-31 21:02:45 +00001089 }
Jessica Paquette78681be2017-07-27 23:24:43 +00001090
1091 if (StringLen > MaxLen)
1092 MaxLen = StringLen;
1093
Jessica Paquetted87f5442017-07-29 02:55:46 +00001094 // At this point, the candidate class is seen as beneficial. Set their
1095 // benefit values and save them in the candidate list.
Jessica Paquette9df7fde2017-10-23 23:36:46 +00001096 std::vector<std::shared_ptr<Candidate>> CandidatesForFn;
Jessica Paquetted87f5442017-07-29 02:55:46 +00001097 for (Candidate &C : CandidatesForRepeatedSeq) {
1098 C.Benefit = Benefit;
Jessica Paquette4cf187b2017-09-27 20:47:39 +00001099 C.MInfo = MInfo;
Jessica Paquette9df7fde2017-10-23 23:36:46 +00001100 std::shared_ptr<Candidate> Cptr = std::make_shared<Candidate>(C);
1101 CandidateList.push_back(Cptr);
1102 CandidatesForFn.push_back(Cptr);
Jessica Paquette78681be2017-07-27 23:24:43 +00001103 }
1104
Jessica Paquetteacc15e12017-10-03 20:32:55 +00001105 FunctionList.push_back(OF);
Jessica Paquette9df7fde2017-10-23 23:36:46 +00001106 FunctionList.back().Candidates = CandidatesForFn;
Jessica Paquette78681be2017-07-27 23:24:43 +00001107
1108 // Move to the next function.
Jessica Paquette78681be2017-07-27 23:24:43 +00001109 Parent.IsInTree = false;
1110 }
1111
1112 return MaxLen;
1113}
Jessica Paquette596f4832017-03-06 21:31:18 +00001114
Jessica Paquette60d31fc2017-10-17 21:11:58 +00001115// Remove C from the candidate space, and update its OutlinedFunction.
1116void MachineOutliner::prune(Candidate &C,
1117 std::vector<OutlinedFunction> &FunctionList) {
1118 // Get the OutlinedFunction associated with this Candidate.
1119 OutlinedFunction &F = FunctionList[C.FunctionIdx];
1120
1121 // Update C's associated function's occurrence count.
1122 F.decrement();
1123
1124 // Remove C from the CandidateList.
1125 C.InCandidateList = false;
1126
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001127 LLVM_DEBUG(dbgs() << "- Removed a Candidate \n";
1128 dbgs() << "--- Num fns left for candidate: "
1129 << F.getOccurrenceCount() << "\n";
1130 dbgs() << "--- Candidate's functions's benefit: " << F.getBenefit()
1131 << "\n";);
Jessica Paquette60d31fc2017-10-17 21:11:58 +00001132}
1133
Jessica Paquette9df7fde2017-10-23 23:36:46 +00001134void MachineOutliner::pruneOverlaps(
1135 std::vector<std::shared_ptr<Candidate>> &CandidateList,
1136 std::vector<OutlinedFunction> &FunctionList, InstructionMapper &Mapper,
1137 unsigned MaxCandidateLen, const TargetInstrInfo &TII) {
Jessica Paquette91999162017-09-28 23:39:36 +00001138
1139 // Return true if this candidate became unbeneficial for outlining in a
1140 // previous step.
Jessica Paquette60d31fc2017-10-17 21:11:58 +00001141 auto ShouldSkipCandidate = [&FunctionList, this](Candidate &C) {
Jessica Paquette91999162017-09-28 23:39:36 +00001142
1143 // Check if the candidate was removed in a previous step.
1144 if (!C.InCandidateList)
1145 return true;
1146
Jessica Paquette85af63d2017-10-17 19:03:23 +00001147 // C must be alive. Check if we should remove it.
Jessica Paquette60d31fc2017-10-17 21:11:58 +00001148 if (FunctionList[C.FunctionIdx].getBenefit() < 1) {
1149 prune(C, FunctionList);
Jessica Paquette91999162017-09-28 23:39:36 +00001150 return true;
1151 }
1152
1153 // C is in the list, and F is still beneficial.
1154 return false;
1155 };
1156
Jessica Paquetteacffa282017-03-23 21:27:38 +00001157 // TODO: Experiment with interval trees or other interval-checking structures
1158 // to lower the time complexity of this function.
1159 // TODO: Can we do better than the simple greedy choice?
1160 // Check for overlaps in the range.
1161 // This is O(MaxCandidateLen * CandidateList.size()).
Jessica Paquette596f4832017-03-06 21:31:18 +00001162 for (auto It = CandidateList.begin(), Et = CandidateList.end(); It != Et;
1163 It++) {
Jessica Paquette9df7fde2017-10-23 23:36:46 +00001164 Candidate &C1 = **It;
Jessica Paquette596f4832017-03-06 21:31:18 +00001165
Jessica Paquette91999162017-09-28 23:39:36 +00001166 // If C1 was already pruned, or its function is no longer beneficial for
1167 // outlining, move to the next candidate.
1168 if (ShouldSkipCandidate(C1))
Jessica Paquette596f4832017-03-06 21:31:18 +00001169 continue;
1170
Jessica Paquette596f4832017-03-06 21:31:18 +00001171 // The minimum start index of any candidate that could overlap with this
1172 // one.
1173 unsigned FarthestPossibleIdx = 0;
1174
1175 // Either the index is 0, or it's at most MaxCandidateLen indices away.
Jessica Paquette1934fd22017-10-23 16:25:53 +00001176 if (C1.getStartIdx() > MaxCandidateLen)
1177 FarthestPossibleIdx = C1.getStartIdx() - MaxCandidateLen;
Jessica Paquette596f4832017-03-06 21:31:18 +00001178
Hiroshi Inoue0909ca12018-01-26 08:15:29 +00001179 // Compare against the candidates in the list that start at most
Jessica Paquetteacffa282017-03-23 21:27:38 +00001180 // FarthestPossibleIdx indices away from C1. There are at most
1181 // MaxCandidateLen of these.
Jessica Paquette596f4832017-03-06 21:31:18 +00001182 for (auto Sit = It + 1; Sit != Et; Sit++) {
Jessica Paquette9df7fde2017-10-23 23:36:46 +00001183 Candidate &C2 = **Sit;
Jessica Paquette596f4832017-03-06 21:31:18 +00001184
1185 // Is this candidate too far away to overlap?
Jessica Paquette1934fd22017-10-23 16:25:53 +00001186 if (C2.getStartIdx() < FarthestPossibleIdx)
Jessica Paquette596f4832017-03-06 21:31:18 +00001187 break;
1188
Jessica Paquette91999162017-09-28 23:39:36 +00001189 // If C2 was already pruned, or its function is no longer beneficial for
1190 // outlining, move to the next candidate.
1191 if (ShouldSkipCandidate(C2))
Jessica Paquette596f4832017-03-06 21:31:18 +00001192 continue;
1193
Jessica Paquette596f4832017-03-06 21:31:18 +00001194 // Do C1 and C2 overlap?
1195 //
1196 // Not overlapping:
1197 // High indices... [C1End ... C1Start][C2End ... C2Start] ...Low indices
1198 //
1199 // We sorted our candidate list so C2Start <= C1Start. We know that
1200 // C2End > C2Start since each candidate has length >= 2. Therefore, all we
1201 // have to check is C2End < C2Start to see if we overlap.
Jessica Paquette1934fd22017-10-23 16:25:53 +00001202 if (C2.getEndIdx() < C1.getStartIdx())
Jessica Paquette596f4832017-03-06 21:31:18 +00001203 continue;
1204
Jessica Paquetteacffa282017-03-23 21:27:38 +00001205 // C1 and C2 overlap.
1206 // We need to choose the better of the two.
1207 //
1208 // Approximate this by picking the one which would have saved us the
1209 // most instructions before any pruning.
Jessica Paquette60d31fc2017-10-17 21:11:58 +00001210
1211 // Is C2 a better candidate?
1212 if (C2.Benefit > C1.Benefit) {
1213 // Yes, so prune C1. Since C1 is dead, we don't have to compare it
1214 // against anything anymore, so break.
1215 prune(C1, FunctionList);
Jessica Paquetteacffa282017-03-23 21:27:38 +00001216 break;
1217 }
Jessica Paquette60d31fc2017-10-17 21:11:58 +00001218
1219 // Prune C2 and move on to the next candidate.
1220 prune(C2, FunctionList);
Jessica Paquette596f4832017-03-06 21:31:18 +00001221 }
1222 }
1223}
1224
Jessica Paquette9df7fde2017-10-23 23:36:46 +00001225unsigned MachineOutliner::buildCandidateList(
1226 std::vector<std::shared_ptr<Candidate>> &CandidateList,
1227 std::vector<OutlinedFunction> &FunctionList, SuffixTree &ST,
1228 InstructionMapper &Mapper, const TargetInstrInfo &TII) {
Jessica Paquette596f4832017-03-06 21:31:18 +00001229
1230 std::vector<unsigned> CandidateSequence; // Current outlining candidate.
Jessica Paquette4cf187b2017-09-27 20:47:39 +00001231 unsigned MaxCandidateLen = 0; // Length of the longest candidate.
Jessica Paquette596f4832017-03-06 21:31:18 +00001232
Jessica Paquette78681be2017-07-27 23:24:43 +00001233 MaxCandidateLen =
1234 findCandidates(ST, TII, Mapper, CandidateList, FunctionList);
Jessica Paquette596f4832017-03-06 21:31:18 +00001235
Jessica Paquette596f4832017-03-06 21:31:18 +00001236 // Sort the candidates in decending order. This will simplify the outlining
1237 // process when we have to remove the candidates from the mapping by
1238 // allowing us to cut them out without keeping track of an offset.
Jessica Paquette9df7fde2017-10-23 23:36:46 +00001239 std::stable_sort(
1240 CandidateList.begin(), CandidateList.end(),
1241 [](const std::shared_ptr<Candidate> &LHS,
1242 const std::shared_ptr<Candidate> &RHS) { return *LHS < *RHS; });
Jessica Paquette596f4832017-03-06 21:31:18 +00001243
1244 return MaxCandidateLen;
1245}
1246
1247MachineFunction *
1248MachineOutliner::createOutlinedFunction(Module &M, const OutlinedFunction &OF,
Jessica Paquette78681be2017-07-27 23:24:43 +00001249 InstructionMapper &Mapper) {
Jessica Paquette596f4832017-03-06 21:31:18 +00001250
1251 // Create the function name. This should be unique. For now, just hash the
1252 // module name and include it in the function name plus the number of this
1253 // function.
1254 std::ostringstream NameStream;
Jessica Paquette78681be2017-07-27 23:24:43 +00001255 NameStream << "OUTLINED_FUNCTION_" << OF.Name;
Jessica Paquette596f4832017-03-06 21:31:18 +00001256
1257 // Create the function using an IR-level function.
1258 LLVMContext &C = M.getContext();
1259 Function *F = dyn_cast<Function>(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00001260 M.getOrInsertFunction(NameStream.str(), Type::getVoidTy(C)));
Jessica Paquette596f4832017-03-06 21:31:18 +00001261 assert(F && "Function was null!");
1262
1263 // NOTE: If this is linkonceodr, then we can take advantage of linker deduping
1264 // which gives us better results when we outline from linkonceodr functions.
Jessica Paquetted506bf82018-04-03 21:36:00 +00001265 F->setLinkage(GlobalValue::InternalLinkage);
Jessica Paquette596f4832017-03-06 21:31:18 +00001266 F->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
1267
Eli Friedman25bef202018-05-15 23:36:46 +00001268 // FIXME: Set nounwind, so we don't generate eh_frame? Haven't verified it's
1269 // necessary.
1270
1271 // Set optsize/minsize, so we don't insert padding between outlined
1272 // functions.
1273 F->addFnAttr(Attribute::OptimizeForSize);
1274 F->addFnAttr(Attribute::MinSize);
1275
Jessica Paquette729e6862018-01-18 00:00:58 +00001276 // Save F so that we can add debug info later if we need to.
1277 CreatedIRFunctions.push_back(F);
1278
Jessica Paquette596f4832017-03-06 21:31:18 +00001279 BasicBlock *EntryBB = BasicBlock::Create(C, "entry", F);
1280 IRBuilder<> Builder(EntryBB);
1281 Builder.CreateRetVoid();
1282
1283 MachineModuleInfo &MMI = getAnalysis<MachineModuleInfo>();
Matthias Braun7bda1952017-06-06 00:44:35 +00001284 MachineFunction &MF = MMI.getOrCreateMachineFunction(*F);
Jessica Paquette596f4832017-03-06 21:31:18 +00001285 MachineBasicBlock &MBB = *MF.CreateMachineBasicBlock();
1286 const TargetSubtargetInfo &STI = MF.getSubtarget();
1287 const TargetInstrInfo &TII = *STI.getInstrInfo();
1288
1289 // Insert the new function into the module.
1290 MF.insert(MF.begin(), &MBB);
1291
Jessica Paquette4cf187b2017-09-27 20:47:39 +00001292 TII.insertOutlinerPrologue(MBB, MF, OF.MInfo);
Jessica Paquette596f4832017-03-06 21:31:18 +00001293
1294 // Copy over the instructions for the function using the integer mappings in
1295 // its sequence.
1296 for (unsigned Str : OF.Sequence) {
1297 MachineInstr *NewMI =
1298 MF.CloneMachineInstr(Mapper.IntegerInstructionMap.find(Str)->second);
1299 NewMI->dropMemRefs();
1300
1301 // Don't keep debug information for outlined instructions.
Jessica Paquette596f4832017-03-06 21:31:18 +00001302 NewMI->setDebugLoc(DebugLoc());
1303 MBB.insert(MBB.end(), NewMI);
1304 }
1305
Jessica Paquette4cf187b2017-09-27 20:47:39 +00001306 TII.insertOutlinerEpilogue(MBB, MF, OF.MInfo);
Jessica Paquette729e6862018-01-18 00:00:58 +00001307
Jessica Paquettea499c3c2018-01-19 21:21:49 +00001308 // If there's a DISubprogram associated with this outlined function, then
1309 // emit debug info for the outlined function.
1310 if (DISubprogram *SP = OF.getSubprogramOrNull()) {
1311 // We have a DISubprogram. Get its DICompileUnit.
1312 DICompileUnit *CU = SP->getUnit();
1313 DIBuilder DB(M, true, CU);
1314 DIFile *Unit = SP->getFile();
1315 Mangler Mg;
1316
1317 // Walk over each IR function we created in the outliner and create
1318 // DISubprograms for each function.
1319 for (Function *F : CreatedIRFunctions) {
1320 // Get the mangled name of the function for the linkage name.
1321 std::string Dummy;
1322 llvm::raw_string_ostream MangledNameStream(Dummy);
1323 Mg.getNameWithPrefix(MangledNameStream, F, false);
1324
1325 DISubprogram *SP = DB.createFunction(
1326 Unit /* Context */, F->getName(), StringRef(MangledNameStream.str()),
1327 Unit /* File */,
1328 0 /* Line 0 is reserved for compiler-generated code. */,
1329 DB.createSubroutineType(
1330 DB.getOrCreateTypeArray(None)), /* void type */
1331 false, true, 0, /* Line 0 is reserved for compiler-generated code. */
1332 DINode::DIFlags::FlagArtificial /* Compiler-generated code. */,
1333 true /* Outlined code is optimized code by definition. */);
1334
1335 // Don't add any new variables to the subprogram.
1336 DB.finalizeSubprogram(SP);
1337
1338 // Attach subprogram to the function.
1339 F->setSubprogram(SP);
1340 }
1341
1342 // We're done with the DIBuilder.
1343 DB.finalize();
1344 }
1345
Jessica Paquette0b672492018-04-27 23:36:35 +00001346 // Outlined functions shouldn't preserve liveness.
1347 MF.getProperties().reset(MachineFunctionProperties::Property::TracksLiveness);
Geoff Berry82203c42018-01-31 20:15:16 +00001348 MF.getRegInfo().freezeReservedRegs(MF);
Jessica Paquette596f4832017-03-06 21:31:18 +00001349 return &MF;
1350}
1351
Jessica Paquette9df7fde2017-10-23 23:36:46 +00001352bool MachineOutliner::outline(
1353 Module &M, const ArrayRef<std::shared_ptr<Candidate>> &CandidateList,
1354 std::vector<OutlinedFunction> &FunctionList, InstructionMapper &Mapper) {
Jessica Paquette596f4832017-03-06 21:31:18 +00001355
1356 bool OutlinedSomething = false;
Jessica Paquette596f4832017-03-06 21:31:18 +00001357 // Replace the candidates with calls to their respective outlined functions.
Jessica Paquette9df7fde2017-10-23 23:36:46 +00001358 for (const std::shared_ptr<Candidate> &Cptr : CandidateList) {
1359 Candidate &C = *Cptr;
Jessica Paquette596f4832017-03-06 21:31:18 +00001360 // Was the candidate removed during pruneOverlaps?
1361 if (!C.InCandidateList)
1362 continue;
1363
1364 // If not, then look at its OutlinedFunction.
1365 OutlinedFunction &OF = FunctionList[C.FunctionIdx];
1366
1367 // Was its OutlinedFunction made unbeneficial during pruneOverlaps?
Jessica Paquette85af63d2017-10-17 19:03:23 +00001368 if (OF.getBenefit() < 1)
Jessica Paquette596f4832017-03-06 21:31:18 +00001369 continue;
1370
1371 // If not, then outline it.
Jessica Paquette1934fd22017-10-23 16:25:53 +00001372 assert(C.getStartIdx() < Mapper.InstrList.size() &&
Jessica Paquettec9ab4c22017-10-17 18:43:15 +00001373 "Candidate out of bounds!");
Jessica Paquette1934fd22017-10-23 16:25:53 +00001374 MachineBasicBlock *MBB = (*Mapper.InstrList[C.getStartIdx()]).getParent();
1375 MachineBasicBlock::iterator StartIt = Mapper.InstrList[C.getStartIdx()];
1376 unsigned EndIdx = C.getEndIdx();
Jessica Paquette596f4832017-03-06 21:31:18 +00001377
1378 assert(EndIdx < Mapper.InstrList.size() && "Candidate out of bounds!");
1379 MachineBasicBlock::iterator EndIt = Mapper.InstrList[EndIdx];
1380 assert(EndIt != MBB->end() && "EndIt out of bounds!");
1381
Jessica Paquette596f4832017-03-06 21:31:18 +00001382 // Does this candidate have a function yet?
Jessica Paquetteacffa282017-03-23 21:27:38 +00001383 if (!OF.MF) {
Jessica Paquette596f4832017-03-06 21:31:18 +00001384 OF.MF = createOutlinedFunction(M, OF, Mapper);
Jessica Paquette9df7fde2017-10-23 23:36:46 +00001385 MachineBasicBlock *MBB = &*OF.MF->begin();
1386
1387 // Output a remark telling the user that an outlined function was created,
1388 // and explaining where it came from.
1389 MachineOptimizationRemarkEmitter MORE(*OF.MF, nullptr);
1390 MachineOptimizationRemark R(DEBUG_TYPE, "OutlinedFunction",
1391 MBB->findDebugLoc(MBB->begin()), MBB);
1392 R << "Saved " << NV("OutliningBenefit", OF.getBenefit())
Eli Friedman4081a572018-05-18 01:52:16 +00001393 << " bytes by "
Jessica Paquette9df7fde2017-10-23 23:36:46 +00001394 << "outlining " << NV("Length", OF.Sequence.size()) << " instructions "
1395 << "from " << NV("NumOccurrences", OF.getOccurrenceCount())
1396 << " locations. "
1397 << "(Found at: ";
1398
1399 // Tell the user the other places the candidate was found.
1400 for (size_t i = 0, e = OF.Candidates.size(); i < e; i++) {
1401
1402 // Skip over things that were pruned.
1403 if (!OF.Candidates[i]->InCandidateList)
1404 continue;
1405
1406 R << NV(
1407 (Twine("StartLoc") + Twine(i)).str(),
1408 Mapper.InstrList[OF.Candidates[i]->getStartIdx()]->getDebugLoc());
1409 if (i != e - 1)
1410 R << ", ";
1411 }
1412
1413 R << ")";
1414
1415 MORE.emit(R);
Jessica Paquetteacffa282017-03-23 21:27:38 +00001416 FunctionsCreated++;
1417 }
Jessica Paquette596f4832017-03-06 21:31:18 +00001418
1419 MachineFunction *MF = OF.MF;
1420 const TargetSubtargetInfo &STI = MF->getSubtarget();
1421 const TargetInstrInfo &TII = *STI.getInstrInfo();
1422
1423 // Insert a call to the new function and erase the old sequence.
Jessica Paquette0b672492018-04-27 23:36:35 +00001424 auto CallInst = TII.insertOutlinedCall(M, *MBB, StartIt, *MF, C.MInfo);
Jessica Paquette1934fd22017-10-23 16:25:53 +00001425 StartIt = Mapper.InstrList[C.getStartIdx()];
Jessica Paquette596f4832017-03-06 21:31:18 +00001426
Jessica Paquette0b672492018-04-27 23:36:35 +00001427 // If the caller tracks liveness, then we need to make sure that anything
1428 // we outline doesn't break liveness assumptions.
1429 // The outlined functions themselves currently don't track liveness, but
1430 // we should make sure that the ranges we yank things out of aren't
1431 // wrong.
1432 if (MBB->getParent()->getProperties().hasProperty(
1433 MachineFunctionProperties::Property::TracksLiveness)) {
1434 // Helper lambda for adding implicit def operands to the call instruction.
1435 auto CopyDefs = [&CallInst](MachineInstr &MI) {
1436 for (MachineOperand &MOP : MI.operands()) {
1437 // Skip over anything that isn't a register.
1438 if (!MOP.isReg())
1439 continue;
1440
1441 // If it's a def, add it to the call instruction.
1442 if (MOP.isDef())
1443 CallInst->addOperand(
1444 MachineOperand::CreateReg(MOP.getReg(), true, /* isDef = true */
1445 true /* isImp = true */));
1446 }
1447 };
1448
1449 // Copy over the defs in the outlined range.
1450 // First inst in outlined range <-- Anything that's defined in this
1451 // ... .. range has to be added as an implicit
1452 // Last inst in outlined range <-- def to the call instruction.
1453 std::for_each(CallInst, EndIt, CopyDefs);
1454 }
1455
1456 EndIt++; // Erase needs one past the end index.
1457 MBB->erase(StartIt, EndIt);
Jessica Paquette596f4832017-03-06 21:31:18 +00001458 OutlinedSomething = true;
1459
1460 // Statistics.
1461 NumOutlined++;
1462 }
1463
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001464 LLVM_DEBUG(dbgs() << "OutlinedSomething = " << OutlinedSomething << "\n";);
Jessica Paquette596f4832017-03-06 21:31:18 +00001465
1466 return OutlinedSomething;
1467}
1468
1469bool MachineOutliner::runOnModule(Module &M) {
Jessica Paquettedf822742018-03-22 21:07:09 +00001470 // Check if there's anything in the module. If it's empty, then there's
1471 // nothing to outline.
Jessica Paquette596f4832017-03-06 21:31:18 +00001472 if (M.empty())
1473 return false;
1474
1475 MachineModuleInfo &MMI = getAnalysis<MachineModuleInfo>();
Jessica Paquette78681be2017-07-27 23:24:43 +00001476 const TargetSubtargetInfo &STI =
1477 MMI.getOrCreateMachineFunction(*M.begin()).getSubtarget();
Jessica Paquette596f4832017-03-06 21:31:18 +00001478 const TargetRegisterInfo *TRI = STI.getRegisterInfo();
1479 const TargetInstrInfo *TII = STI.getInstrInfo();
Jessica Paquettebccd18b2018-04-04 19:13:31 +00001480
1481 // Does the target implement the MachineOutliner? If it doesn't, quit here.
1482 if (!TII->useMachineOutliner()) {
1483 // No. So we're done.
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001484 LLVM_DEBUG(
1485 dbgs()
1486 << "Skipping pass: Target does not support the MachineOutliner.\n");
Jessica Paquettebccd18b2018-04-04 19:13:31 +00001487 return false;
1488 }
1489
Jessica Paquette1eca23b2018-04-19 22:17:07 +00001490 // If the user specifies that they want to outline from linkonceodrs, set
1491 // it here.
1492 OutlineFromLinkOnceODRs = EnableLinkOnceODROutlining;
1493
Jessica Paquette596f4832017-03-06 21:31:18 +00001494 InstructionMapper Mapper;
1495
Jessica Paquettedf822742018-03-22 21:07:09 +00001496 // Build instruction mappings for each function in the module. Start by
1497 // iterating over each Function in M.
Jessica Paquette596f4832017-03-06 21:31:18 +00001498 for (Function &F : M) {
Jessica Paquette596f4832017-03-06 21:31:18 +00001499
Jessica Paquettedf822742018-03-22 21:07:09 +00001500 // If there's nothing in F, then there's no reason to try and outline from
1501 // it.
1502 if (F.empty())
Jessica Paquette596f4832017-03-06 21:31:18 +00001503 continue;
1504
Jessica Paquettedf822742018-03-22 21:07:09 +00001505 // There's something in F. Check if it has a MachineFunction associated with
1506 // it.
1507 MachineFunction *MF = MMI.getMachineFunction(F);
Jessica Paquette596f4832017-03-06 21:31:18 +00001508
Jessica Paquettedf822742018-03-22 21:07:09 +00001509 // If it doesn't, then there's nothing to outline from. Move to the next
1510 // Function.
1511 if (!MF)
1512 continue;
1513
1514 // We have a MachineFunction. Ask the target if it's suitable for outlining.
1515 // If it isn't, then move on to the next Function in the module.
1516 if (!TII->isFunctionSafeToOutlineFrom(*MF, OutlineFromLinkOnceODRs))
1517 continue;
1518
1519 // We have a function suitable for outlining. Iterate over every
1520 // MachineBasicBlock in MF and try to map its instructions to a list of
1521 // unsigned integers.
1522 for (MachineBasicBlock &MBB : *MF) {
1523 // If there isn't anything in MBB, then there's no point in outlining from
1524 // it.
1525 if (MBB.empty())
Jessica Paquette596f4832017-03-06 21:31:18 +00001526 continue;
1527
Jessica Paquettedf822742018-03-22 21:07:09 +00001528 // Check if MBB could be the target of an indirect branch. If it is, then
1529 // we don't want to outline from it.
1530 if (MBB.hasAddressTaken())
1531 continue;
1532
1533 // MBB is suitable for outlining. Map it to a list of unsigneds.
Jessica Paquette596f4832017-03-06 21:31:18 +00001534 Mapper.convertToUnsignedVec(MBB, *TRI, *TII);
1535 }
1536 }
1537
1538 // Construct a suffix tree, use it to find candidates, and then outline them.
1539 SuffixTree ST(Mapper.UnsignedVec);
Jessica Paquette9df7fde2017-10-23 23:36:46 +00001540 std::vector<std::shared_ptr<Candidate>> CandidateList;
Jessica Paquette596f4832017-03-06 21:31:18 +00001541 std::vector<OutlinedFunction> FunctionList;
1542
Jessica Paquetteacffa282017-03-23 21:27:38 +00001543 // Find all of the outlining candidates.
Jessica Paquette596f4832017-03-06 21:31:18 +00001544 unsigned MaxCandidateLen =
Jessica Paquettec984e212017-03-13 18:39:33 +00001545 buildCandidateList(CandidateList, FunctionList, ST, Mapper, *TII);
Jessica Paquette596f4832017-03-06 21:31:18 +00001546
Jessica Paquetteacffa282017-03-23 21:27:38 +00001547 // Remove candidates that overlap with other candidates.
Jessica Paquette809d7082017-07-28 03:21:58 +00001548 pruneOverlaps(CandidateList, FunctionList, Mapper, MaxCandidateLen, *TII);
Jessica Paquetteacffa282017-03-23 21:27:38 +00001549
1550 // Outline each of the candidates and return true if something was outlined.
Jessica Paquette729e6862018-01-18 00:00:58 +00001551 bool OutlinedSomething = outline(M, CandidateList, FunctionList, Mapper);
1552
Jessica Paquette729e6862018-01-18 00:00:58 +00001553 return OutlinedSomething;
Jessica Paquette596f4832017-03-06 21:31:18 +00001554}