blob: 38aea4fdc98a6d74ffe72cbffff54cb022ca872c [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"
62#include "llvm/CodeGen/MachineFrameInfo.h"
63#include "llvm/CodeGen/MachineFunction.h"
64#include "llvm/CodeGen/MachineInstrBuilder.h"
65#include "llvm/CodeGen/MachineModuleInfo.h"
Jessica Paquetteffe4abc2017-08-31 21:02:45 +000066#include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h"
Jessica Paquette596f4832017-03-06 21:31:18 +000067#include "llvm/CodeGen/Passes.h"
68#include "llvm/IR/IRBuilder.h"
69#include "llvm/Support/Allocator.h"
70#include "llvm/Support/Debug.h"
71#include "llvm/Support/raw_ostream.h"
72#include "llvm/Target/TargetInstrInfo.h"
73#include "llvm/Target/TargetMachine.h"
74#include "llvm/Target/TargetRegisterInfo.h"
75#include "llvm/Target/TargetSubtargetInfo.h"
76#include <functional>
77#include <map>
78#include <sstream>
79#include <tuple>
80#include <vector>
81
82#define DEBUG_TYPE "machine-outliner"
83
84using namespace llvm;
Jessica Paquetteffe4abc2017-08-31 21:02:45 +000085using namespace ore;
Jessica Paquette596f4832017-03-06 21:31:18 +000086
87STATISTIC(NumOutlined, "Number of candidates outlined");
88STATISTIC(FunctionsCreated, "Number of functions created");
89
90namespace {
91
Jessica Paquetteacffa282017-03-23 21:27:38 +000092/// \brief An individual sequence of instructions to be replaced with a call to
93/// an outlined function.
94struct Candidate {
95
96 /// Set to false if the candidate overlapped with another candidate.
97 bool InCandidateList = true;
98
99 /// The start index of this \p Candidate.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000100 unsigned StartIdx;
Jessica Paquetteacffa282017-03-23 21:27:38 +0000101
102 /// The number of instructions in this \p Candidate.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000103 unsigned Len;
Jessica Paquetteacffa282017-03-23 21:27:38 +0000104
105 /// The index of this \p Candidate's \p OutlinedFunction in the list of
106 /// \p OutlinedFunctions.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000107 unsigned FunctionIdx;
Jessica Paquetteacffa282017-03-23 21:27:38 +0000108
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000109 /// Contains all target-specific information for this \p Candidate.
110 TargetInstrInfo::MachineOutlinerInfo MInfo;
Jessica Paquetted87f5442017-07-29 02:55:46 +0000111
Jessica Paquetteacffa282017-03-23 21:27:38 +0000112 /// \brief The number of instructions that would be saved by outlining every
113 /// candidate of this type.
114 ///
115 /// This is a fixed value which is not updated during the candidate pruning
116 /// process. It is only used for deciding which candidate to keep if two
117 /// candidates overlap. The true benefit is stored in the OutlinedFunction
118 /// for some given candidate.
119 unsigned Benefit = 0;
120
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000121 Candidate(unsigned StartIdx, unsigned Len, unsigned FunctionIdx)
122 : StartIdx(StartIdx), Len(Len), FunctionIdx(FunctionIdx) {}
Jessica Paquetteacffa282017-03-23 21:27:38 +0000123
124 Candidate() {}
125
126 /// \brief Used to ensure that \p Candidates are outlined in an order that
127 /// preserves the start and end indices of other \p Candidates.
128 bool operator<(const Candidate &RHS) const { return StartIdx > RHS.StartIdx; }
129};
130
131/// \brief The information necessary to create an outlined function for some
132/// class of candidate.
133struct OutlinedFunction {
134
135 /// The actual outlined function created.
136 /// This is initialized after we go through and create the actual function.
137 MachineFunction *MF = nullptr;
138
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000139 /// A number assigned to this function which appears at the end of its name.
140 unsigned Name;
Jessica Paquetteacffa282017-03-23 21:27:38 +0000141
142 /// The number of candidates for this OutlinedFunction.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000143 unsigned OccurrenceCount = 0;
Jessica Paquetteacffa282017-03-23 21:27:38 +0000144
145 /// \brief The sequence of integers corresponding to the instructions in this
146 /// function.
147 std::vector<unsigned> Sequence;
148
149 /// The number of instructions this function would save.
150 unsigned Benefit = 0;
151
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000152 /// Contains all target-specific information for this \p OutlinedFunction.
153 TargetInstrInfo::MachineOutlinerInfo MInfo;
Jessica Paquetteacffa282017-03-23 21:27:38 +0000154
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000155 OutlinedFunction(unsigned Name, unsigned OccurrenceCount,
Jessica Paquette78681be2017-07-27 23:24:43 +0000156 const std::vector<unsigned> &Sequence, unsigned Benefit,
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000157 TargetInstrInfo::MachineOutlinerInfo &MInfo)
Jessica Paquetteacffa282017-03-23 21:27:38 +0000158 : Name(Name), OccurrenceCount(OccurrenceCount), Sequence(Sequence),
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000159 Benefit(Benefit), MInfo(MInfo) {}
Jessica Paquetteacffa282017-03-23 21:27:38 +0000160};
161
Jessica Paquette596f4832017-03-06 21:31:18 +0000162/// Represents an undefined index in the suffix tree.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000163const unsigned EmptyIdx = -1;
Jessica Paquette596f4832017-03-06 21:31:18 +0000164
165/// A node in a suffix tree which represents a substring or suffix.
166///
167/// Each node has either no children or at least two children, with the root
168/// being a exception in the empty tree.
169///
170/// Children are represented as a map between unsigned integers and nodes. If
171/// a node N has a child M on unsigned integer k, then the mapping represented
172/// by N is a proper prefix of the mapping represented by M. Note that this,
173/// although similar to a trie is somewhat different: each node stores a full
174/// substring of the full mapping rather than a single character state.
175///
176/// Each internal node contains a pointer to the internal node representing
177/// the same string, but with the first character chopped off. This is stored
178/// in \p Link. Each leaf node stores the start index of its respective
179/// suffix in \p SuffixIdx.
180struct SuffixTreeNode {
181
182 /// The children of this node.
183 ///
184 /// A child existing on an unsigned integer implies that from the mapping
185 /// represented by the current node, there is a way to reach another
186 /// mapping by tacking that character on the end of the current string.
187 DenseMap<unsigned, SuffixTreeNode *> Children;
188
189 /// A flag set to false if the node has been pruned from the tree.
190 bool IsInTree = true;
191
192 /// The start index of this node's substring in the main string.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000193 unsigned StartIdx = EmptyIdx;
Jessica Paquette596f4832017-03-06 21:31:18 +0000194
195 /// The end index of this node's substring in the main string.
196 ///
197 /// Every leaf node must have its \p EndIdx incremented at the end of every
198 /// step in the construction algorithm. To avoid having to update O(N)
199 /// nodes individually at the end of every step, the end index is stored
200 /// as a pointer.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000201 unsigned *EndIdx = nullptr;
Jessica Paquette596f4832017-03-06 21:31:18 +0000202
203 /// For leaves, the start index of the suffix represented by this node.
204 ///
205 /// For all other nodes, this is ignored.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000206 unsigned SuffixIdx = EmptyIdx;
Jessica Paquette596f4832017-03-06 21:31:18 +0000207
208 /// \brief For internal nodes, a pointer to the internal node representing
209 /// the same sequence with the first character chopped off.
210 ///
Jessica Paquette4602c342017-07-28 05:59:30 +0000211 /// This acts as a shortcut in Ukkonen's algorithm. One of the things that
Jessica Paquette596f4832017-03-06 21:31:18 +0000212 /// Ukkonen's algorithm does to achieve linear-time construction is
213 /// keep track of which node the next insert should be at. This makes each
214 /// insert O(1), and there are a total of O(N) inserts. The suffix link
215 /// helps with inserting children of internal nodes.
216 ///
Jessica Paquette78681be2017-07-27 23:24:43 +0000217 /// Say we add a child to an internal node with associated mapping S. The
Jessica Paquette596f4832017-03-06 21:31:18 +0000218 /// next insertion must be at the node representing S - its first character.
219 /// This is given by the way that we iteratively build the tree in Ukkonen's
220 /// algorithm. The main idea is to look at the suffixes of each prefix in the
221 /// string, starting with the longest suffix of the prefix, and ending with
222 /// the shortest. Therefore, if we keep pointers between such nodes, we can
223 /// move to the next insertion point in O(1) time. If we don't, then we'd
224 /// have to query from the root, which takes O(N) time. This would make the
225 /// construction algorithm O(N^2) rather than O(N).
Jessica Paquette596f4832017-03-06 21:31:18 +0000226 SuffixTreeNode *Link = nullptr;
227
228 /// The parent of this node. Every node except for the root has a parent.
229 SuffixTreeNode *Parent = nullptr;
230
231 /// The number of times this node's string appears in the tree.
232 ///
233 /// This is equal to the number of leaf children of the string. It represents
234 /// the number of suffixes that the node's string is a prefix of.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000235 unsigned OccurrenceCount = 0;
Jessica Paquette596f4832017-03-06 21:31:18 +0000236
Jessica Paquetteacffa282017-03-23 21:27:38 +0000237 /// The length of the string formed by concatenating the edge labels from the
238 /// root to this node.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000239 unsigned ConcatLen = 0;
Jessica Paquetteacffa282017-03-23 21:27:38 +0000240
Jessica Paquette596f4832017-03-06 21:31:18 +0000241 /// Returns true if this node is a leaf.
242 bool isLeaf() const { return SuffixIdx != EmptyIdx; }
243
244 /// Returns true if this node is the root of its owning \p SuffixTree.
245 bool isRoot() const { return StartIdx == EmptyIdx; }
246
247 /// Return the number of elements in the substring associated with this node.
248 size_t size() const {
249
250 // Is it the root? If so, it's the empty string so return 0.
251 if (isRoot())
252 return 0;
253
254 assert(*EndIdx != EmptyIdx && "EndIdx is undefined!");
255
256 // Size = the number of elements in the string.
257 // For example, [0 1 2 3] has length 4, not 3. 3-0 = 3, so we have 3-0+1.
258 return *EndIdx - StartIdx + 1;
259 }
260
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000261 SuffixTreeNode(unsigned StartIdx, unsigned *EndIdx, SuffixTreeNode *Link,
Jessica Paquette596f4832017-03-06 21:31:18 +0000262 SuffixTreeNode *Parent)
263 : StartIdx(StartIdx), EndIdx(EndIdx), Link(Link), Parent(Parent) {}
264
265 SuffixTreeNode() {}
266};
267
268/// A data structure for fast substring queries.
269///
270/// Suffix trees represent the suffixes of their input strings in their leaves.
271/// A suffix tree is a type of compressed trie structure where each node
272/// represents an entire substring rather than a single character. Each leaf
273/// of the tree is a suffix.
274///
275/// A suffix tree can be seen as a type of state machine where each state is a
276/// substring of the full string. The tree is structured so that, for a string
277/// of length N, there are exactly N leaves in the tree. This structure allows
278/// us to quickly find repeated substrings of the input string.
279///
280/// In this implementation, a "string" is a vector of unsigned integers.
281/// These integers may result from hashing some data type. A suffix tree can
282/// contain 1 or many strings, which can then be queried as one large string.
283///
284/// The suffix tree is implemented using Ukkonen's algorithm for linear-time
285/// suffix tree construction. Ukkonen's algorithm is explained in more detail
286/// in the paper by Esko Ukkonen "On-line construction of suffix trees. The
287/// paper is available at
288///
289/// https://www.cs.helsinki.fi/u/ukkonen/SuffixT1withFigs.pdf
290class SuffixTree {
Jessica Paquette78681be2017-07-27 23:24:43 +0000291public:
292 /// Stores each leaf node in the tree.
293 ///
294 /// This is used for finding outlining candidates.
295 std::vector<SuffixTreeNode *> LeafVector;
296
Jessica Paquette596f4832017-03-06 21:31:18 +0000297 /// Each element is an integer representing an instruction in the module.
298 ArrayRef<unsigned> Str;
299
Jessica Paquette78681be2017-07-27 23:24:43 +0000300private:
Jessica Paquette596f4832017-03-06 21:31:18 +0000301 /// Maintains each node in the tree.
Jessica Paquetted4cb9c62017-03-08 23:55:33 +0000302 SpecificBumpPtrAllocator<SuffixTreeNode> NodeAllocator;
Jessica Paquette596f4832017-03-06 21:31:18 +0000303
304 /// The root of the suffix tree.
305 ///
306 /// The root represents the empty string. It is maintained by the
307 /// \p NodeAllocator like every other node in the tree.
308 SuffixTreeNode *Root = nullptr;
309
Jessica Paquette596f4832017-03-06 21:31:18 +0000310 /// Maintains the end indices of the internal nodes in the tree.
311 ///
312 /// Each internal node is guaranteed to never have its end index change
313 /// during the construction algorithm; however, leaves must be updated at
314 /// every step. Therefore, we need to store leaf end indices by reference
315 /// to avoid updating O(N) leaves at every step of construction. Thus,
316 /// every internal node must be allocated its own end index.
317 BumpPtrAllocator InternalEndIdxAllocator;
318
319 /// The end index of each leaf in the tree.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000320 unsigned LeafEndIdx = -1;
Jessica Paquette596f4832017-03-06 21:31:18 +0000321
322 /// \brief Helper struct which keeps track of the next insertion point in
323 /// Ukkonen's algorithm.
324 struct ActiveState {
325 /// The next node to insert at.
326 SuffixTreeNode *Node;
327
328 /// The index of the first character in the substring currently being added.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000329 unsigned Idx = EmptyIdx;
Jessica Paquette596f4832017-03-06 21:31:18 +0000330
331 /// The length of the substring we have to add at the current step.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000332 unsigned Len = 0;
Jessica Paquette596f4832017-03-06 21:31:18 +0000333 };
334
335 /// \brief The point the next insertion will take place at in the
336 /// construction algorithm.
337 ActiveState Active;
338
339 /// Allocate a leaf node and add it to the tree.
340 ///
341 /// \param Parent The parent of this node.
342 /// \param StartIdx The start index of this node's associated string.
343 /// \param Edge The label on the edge leaving \p Parent to this node.
344 ///
345 /// \returns A pointer to the allocated leaf node.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000346 SuffixTreeNode *insertLeaf(SuffixTreeNode &Parent, unsigned StartIdx,
Jessica Paquette596f4832017-03-06 21:31:18 +0000347 unsigned Edge) {
348
349 assert(StartIdx <= LeafEndIdx && "String can't start after it ends!");
350
Jessica Paquette78681be2017-07-27 23:24:43 +0000351 SuffixTreeNode *N = new (NodeAllocator.Allocate())
352 SuffixTreeNode(StartIdx, &LeafEndIdx, nullptr, &Parent);
Jessica Paquette596f4832017-03-06 21:31:18 +0000353 Parent.Children[Edge] = N;
354
355 return N;
356 }
357
358 /// Allocate an internal node and add it to the tree.
359 ///
360 /// \param Parent The parent of this node. Only null when allocating the root.
361 /// \param StartIdx The start index of this node's associated string.
362 /// \param EndIdx The end index of this node's associated string.
363 /// \param Edge The label on the edge leaving \p Parent to this node.
364 ///
365 /// \returns A pointer to the allocated internal node.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000366 SuffixTreeNode *insertInternalNode(SuffixTreeNode *Parent, unsigned StartIdx,
367 unsigned EndIdx, unsigned Edge) {
Jessica Paquette596f4832017-03-06 21:31:18 +0000368
369 assert(StartIdx <= EndIdx && "String can't start after it ends!");
370 assert(!(!Parent && StartIdx != EmptyIdx) &&
Jessica Paquette78681be2017-07-27 23:24:43 +0000371 "Non-root internal nodes must have parents!");
Jessica Paquette596f4832017-03-06 21:31:18 +0000372
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000373 unsigned *E = new (InternalEndIdxAllocator) unsigned(EndIdx);
Jessica Paquette78681be2017-07-27 23:24:43 +0000374 SuffixTreeNode *N = new (NodeAllocator.Allocate())
375 SuffixTreeNode(StartIdx, E, Root, Parent);
Jessica Paquette596f4832017-03-06 21:31:18 +0000376 if (Parent)
377 Parent->Children[Edge] = N;
378
379 return N;
380 }
381
382 /// \brief Set the suffix indices of the leaves to the start indices of their
383 /// respective suffixes. Also stores each leaf in \p LeafVector at its
384 /// respective suffix index.
385 ///
386 /// \param[in] CurrNode The node currently being visited.
387 /// \param CurrIdx The current index of the string being visited.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000388 void setSuffixIndices(SuffixTreeNode &CurrNode, unsigned CurrIdx) {
Jessica Paquette596f4832017-03-06 21:31:18 +0000389
390 bool IsLeaf = CurrNode.Children.size() == 0 && !CurrNode.isRoot();
391
Jessica Paquetteacffa282017-03-23 21:27:38 +0000392 // Store the length of the concatenation of all strings from the root to
393 // this node.
394 if (!CurrNode.isRoot()) {
395 if (CurrNode.ConcatLen == 0)
396 CurrNode.ConcatLen = CurrNode.size();
397
398 if (CurrNode.Parent)
Jessica Paquette78681be2017-07-27 23:24:43 +0000399 CurrNode.ConcatLen += CurrNode.Parent->ConcatLen;
Jessica Paquetteacffa282017-03-23 21:27:38 +0000400 }
401
Jessica Paquette596f4832017-03-06 21:31:18 +0000402 // Traverse the tree depth-first.
403 for (auto &ChildPair : CurrNode.Children) {
404 assert(ChildPair.second && "Node had a null child!");
Jessica Paquette78681be2017-07-27 23:24:43 +0000405 setSuffixIndices(*ChildPair.second, CurrIdx + ChildPair.second->size());
Jessica Paquette596f4832017-03-06 21:31:18 +0000406 }
407
408 // Is this node a leaf?
409 if (IsLeaf) {
410 // If yes, give it a suffix index and bump its parent's occurrence count.
411 CurrNode.SuffixIdx = Str.size() - CurrIdx;
412 assert(CurrNode.Parent && "CurrNode had no parent!");
413 CurrNode.Parent->OccurrenceCount++;
414
415 // Store the leaf in the leaf vector for pruning later.
416 LeafVector[CurrNode.SuffixIdx] = &CurrNode;
417 }
418 }
419
420 /// \brief Construct the suffix tree for the prefix of the input ending at
421 /// \p EndIdx.
422 ///
423 /// Used to construct the full suffix tree iteratively. At the end of each
424 /// step, the constructed suffix tree is either a valid suffix tree, or a
425 /// suffix tree with implicit suffixes. At the end of the final step, the
426 /// suffix tree is a valid tree.
427 ///
428 /// \param EndIdx The end index of the current prefix in the main string.
429 /// \param SuffixesToAdd The number of suffixes that must be added
430 /// to complete the suffix tree at the current phase.
431 ///
432 /// \returns The number of suffixes that have not been added at the end of
433 /// this step.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000434 unsigned extend(unsigned EndIdx, unsigned SuffixesToAdd) {
Jessica Paquette596f4832017-03-06 21:31:18 +0000435 SuffixTreeNode *NeedsLink = nullptr;
436
437 while (SuffixesToAdd > 0) {
Jessica Paquette78681be2017-07-27 23:24:43 +0000438
Jessica Paquette596f4832017-03-06 21:31:18 +0000439 // Are we waiting to add anything other than just the last character?
440 if (Active.Len == 0) {
441 // If not, then say the active index is the end index.
442 Active.Idx = EndIdx;
443 }
444
445 assert(Active.Idx <= EndIdx && "Start index can't be after end index!");
446
447 // The first character in the current substring we're looking at.
448 unsigned FirstChar = Str[Active.Idx];
449
450 // Have we inserted anything starting with FirstChar at the current node?
451 if (Active.Node->Children.count(FirstChar) == 0) {
452 // If not, then we can just insert a leaf and move too the next step.
453 insertLeaf(*Active.Node, EndIdx, FirstChar);
454
455 // The active node is an internal node, and we visited it, so it must
456 // need a link if it doesn't have one.
457 if (NeedsLink) {
458 NeedsLink->Link = Active.Node;
459 NeedsLink = nullptr;
460 }
461 } else {
462 // There's a match with FirstChar, so look for the point in the tree to
463 // insert a new node.
464 SuffixTreeNode *NextNode = Active.Node->Children[FirstChar];
465
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000466 unsigned SubstringLen = NextNode->size();
Jessica Paquette596f4832017-03-06 21:31:18 +0000467
468 // Is the current suffix we're trying to insert longer than the size of
469 // the child we want to move to?
470 if (Active.Len >= SubstringLen) {
471 // If yes, then consume the characters we've seen and move to the next
472 // node.
473 Active.Idx += SubstringLen;
474 Active.Len -= SubstringLen;
475 Active.Node = NextNode;
476 continue;
477 }
478
479 // Otherwise, the suffix we're trying to insert must be contained in the
480 // next node we want to move to.
481 unsigned LastChar = Str[EndIdx];
482
483 // Is the string we're trying to insert a substring of the next node?
484 if (Str[NextNode->StartIdx + Active.Len] == LastChar) {
485 // If yes, then we're done for this step. Remember our insertion point
486 // and move to the next end index. At this point, we have an implicit
487 // suffix tree.
488 if (NeedsLink && !Active.Node->isRoot()) {
489 NeedsLink->Link = Active.Node;
490 NeedsLink = nullptr;
491 }
492
493 Active.Len++;
494 break;
495 }
496
497 // The string we're trying to insert isn't a substring of the next node,
498 // but matches up to a point. Split the node.
499 //
500 // For example, say we ended our search at a node n and we're trying to
501 // insert ABD. Then we'll create a new node s for AB, reduce n to just
502 // representing C, and insert a new leaf node l to represent d. This
503 // allows us to ensure that if n was a leaf, it remains a leaf.
504 //
505 // | ABC ---split---> | AB
506 // n s
507 // C / \ D
508 // n l
509
510 // The node s from the diagram
511 SuffixTreeNode *SplitNode =
Jessica Paquette78681be2017-07-27 23:24:43 +0000512 insertInternalNode(Active.Node, NextNode->StartIdx,
513 NextNode->StartIdx + Active.Len - 1, FirstChar);
Jessica Paquette596f4832017-03-06 21:31:18 +0000514
515 // Insert the new node representing the new substring into the tree as
516 // a child of the split node. This is the node l from the diagram.
517 insertLeaf(*SplitNode, EndIdx, LastChar);
518
519 // Make the old node a child of the split node and update its start
520 // index. This is the node n from the diagram.
521 NextNode->StartIdx += Active.Len;
522 NextNode->Parent = SplitNode;
523 SplitNode->Children[Str[NextNode->StartIdx]] = NextNode;
524
525 // SplitNode is an internal node, update the suffix link.
526 if (NeedsLink)
527 NeedsLink->Link = SplitNode;
528
529 NeedsLink = SplitNode;
530 }
531
532 // We've added something new to the tree, so there's one less suffix to
533 // add.
534 SuffixesToAdd--;
535
536 if (Active.Node->isRoot()) {
537 if (Active.Len > 0) {
538 Active.Len--;
539 Active.Idx = EndIdx - SuffixesToAdd + 1;
540 }
541 } else {
542 // Start the next phase at the next smallest suffix.
543 Active.Node = Active.Node->Link;
544 }
545 }
546
547 return SuffixesToAdd;
548 }
549
Jessica Paquette596f4832017-03-06 21:31:18 +0000550public:
Jessica Paquette596f4832017-03-06 21:31:18 +0000551 /// Construct a suffix tree from a sequence of unsigned integers.
552 ///
553 /// \param Str The string to construct the suffix tree for.
554 SuffixTree(const std::vector<unsigned> &Str) : Str(Str) {
555 Root = insertInternalNode(nullptr, EmptyIdx, EmptyIdx, 0);
556 Root->IsInTree = true;
557 Active.Node = Root;
Jessica Paquette78681be2017-07-27 23:24:43 +0000558 LeafVector = std::vector<SuffixTreeNode *>(Str.size());
Jessica Paquette596f4832017-03-06 21:31:18 +0000559
560 // Keep track of the number of suffixes we have to add of the current
561 // prefix.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000562 unsigned SuffixesToAdd = 0;
Jessica Paquette596f4832017-03-06 21:31:18 +0000563 Active.Node = Root;
564
565 // Construct the suffix tree iteratively on each prefix of the string.
566 // PfxEndIdx is the end index of the current prefix.
567 // End is one past the last element in the string.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000568 for (unsigned PfxEndIdx = 0, End = Str.size(); PfxEndIdx < End;
569 PfxEndIdx++) {
Jessica Paquette596f4832017-03-06 21:31:18 +0000570 SuffixesToAdd++;
571 LeafEndIdx = PfxEndIdx; // Extend each of the leaves.
572 SuffixesToAdd = extend(PfxEndIdx, SuffixesToAdd);
573 }
574
575 // Set the suffix indices of each leaf.
576 assert(Root && "Root node can't be nullptr!");
577 setSuffixIndices(*Root, 0);
578 }
579};
580
Jessica Paquette596f4832017-03-06 21:31:18 +0000581/// \brief Maps \p MachineInstrs to unsigned integers and stores the mappings.
582struct InstructionMapper {
583
584 /// \brief The next available integer to assign to a \p MachineInstr that
585 /// cannot be outlined.
586 ///
587 /// Set to -3 for compatability with \p DenseMapInfo<unsigned>.
588 unsigned IllegalInstrNumber = -3;
589
590 /// \brief The next available integer to assign to a \p MachineInstr that can
591 /// be outlined.
592 unsigned LegalInstrNumber = 0;
593
594 /// Correspondence from \p MachineInstrs to unsigned integers.
595 DenseMap<MachineInstr *, unsigned, MachineInstrExpressionTrait>
596 InstructionIntegerMap;
597
598 /// Corresponcence from unsigned integers to \p MachineInstrs.
599 /// Inverse of \p InstructionIntegerMap.
600 DenseMap<unsigned, MachineInstr *> IntegerInstructionMap;
601
602 /// The vector of unsigned integers that the module is mapped to.
603 std::vector<unsigned> UnsignedVec;
604
605 /// \brief Stores the location of the instruction associated with the integer
606 /// at index i in \p UnsignedVec for each index i.
607 std::vector<MachineBasicBlock::iterator> InstrList;
608
609 /// \brief Maps \p *It to a legal integer.
610 ///
611 /// Updates \p InstrList, \p UnsignedVec, \p InstructionIntegerMap,
612 /// \p IntegerInstructionMap, and \p LegalInstrNumber.
613 ///
614 /// \returns The integer that \p *It was mapped to.
615 unsigned mapToLegalUnsigned(MachineBasicBlock::iterator &It) {
616
617 // Get the integer for this instruction or give it the current
618 // LegalInstrNumber.
619 InstrList.push_back(It);
620 MachineInstr &MI = *It;
621 bool WasInserted;
622 DenseMap<MachineInstr *, unsigned, MachineInstrExpressionTrait>::iterator
Jessica Paquette78681be2017-07-27 23:24:43 +0000623 ResultIt;
Jessica Paquette596f4832017-03-06 21:31:18 +0000624 std::tie(ResultIt, WasInserted) =
Jessica Paquette78681be2017-07-27 23:24:43 +0000625 InstructionIntegerMap.insert(std::make_pair(&MI, LegalInstrNumber));
Jessica Paquette596f4832017-03-06 21:31:18 +0000626 unsigned MINumber = ResultIt->second;
627
628 // There was an insertion.
629 if (WasInserted) {
630 LegalInstrNumber++;
631 IntegerInstructionMap.insert(std::make_pair(MINumber, &MI));
632 }
633
634 UnsignedVec.push_back(MINumber);
635
636 // Make sure we don't overflow or use any integers reserved by the DenseMap.
637 if (LegalInstrNumber >= IllegalInstrNumber)
638 report_fatal_error("Instruction mapping overflow!");
639
Jessica Paquette78681be2017-07-27 23:24:43 +0000640 assert(LegalInstrNumber != DenseMapInfo<unsigned>::getEmptyKey() &&
641 "Tried to assign DenseMap tombstone or empty key to instruction.");
642 assert(LegalInstrNumber != DenseMapInfo<unsigned>::getTombstoneKey() &&
643 "Tried to assign DenseMap tombstone or empty key to instruction.");
Jessica Paquette596f4832017-03-06 21:31:18 +0000644
645 return MINumber;
646 }
647
648 /// Maps \p *It to an illegal integer.
649 ///
650 /// Updates \p InstrList, \p UnsignedVec, and \p IllegalInstrNumber.
651 ///
652 /// \returns The integer that \p *It was mapped to.
653 unsigned mapToIllegalUnsigned(MachineBasicBlock::iterator &It) {
654 unsigned MINumber = IllegalInstrNumber;
655
656 InstrList.push_back(It);
657 UnsignedVec.push_back(IllegalInstrNumber);
658 IllegalInstrNumber--;
659
660 assert(LegalInstrNumber < IllegalInstrNumber &&
661 "Instruction mapping overflow!");
662
Jessica Paquette78681be2017-07-27 23:24:43 +0000663 assert(IllegalInstrNumber != DenseMapInfo<unsigned>::getEmptyKey() &&
664 "IllegalInstrNumber cannot be DenseMap tombstone or empty key!");
Jessica Paquette596f4832017-03-06 21:31:18 +0000665
Jessica Paquette78681be2017-07-27 23:24:43 +0000666 assert(IllegalInstrNumber != DenseMapInfo<unsigned>::getTombstoneKey() &&
667 "IllegalInstrNumber cannot be DenseMap tombstone or empty key!");
Jessica Paquette596f4832017-03-06 21:31:18 +0000668
669 return MINumber;
670 }
671
672 /// \brief Transforms a \p MachineBasicBlock into a \p vector of \p unsigneds
673 /// and appends it to \p UnsignedVec and \p InstrList.
674 ///
675 /// Two instructions are assigned the same integer if they are identical.
676 /// If an instruction is deemed unsafe to outline, then it will be assigned an
677 /// unique integer. The resulting mapping is placed into a suffix tree and
678 /// queried for candidates.
679 ///
680 /// \param MBB The \p MachineBasicBlock to be translated into integers.
681 /// \param TRI \p TargetRegisterInfo for the module.
682 /// \param TII \p TargetInstrInfo for the module.
683 void convertToUnsignedVec(MachineBasicBlock &MBB,
684 const TargetRegisterInfo &TRI,
685 const TargetInstrInfo &TII) {
686 for (MachineBasicBlock::iterator It = MBB.begin(), Et = MBB.end(); It != Et;
687 It++) {
688
689 // Keep track of where this instruction is in the module.
Jessica Paquette78681be2017-07-27 23:24:43 +0000690 switch (TII.getOutliningType(*It)) {
691 case TargetInstrInfo::MachineOutlinerInstrType::Illegal:
692 mapToIllegalUnsigned(It);
693 break;
Jessica Paquette596f4832017-03-06 21:31:18 +0000694
Jessica Paquette78681be2017-07-27 23:24:43 +0000695 case TargetInstrInfo::MachineOutlinerInstrType::Legal:
696 mapToLegalUnsigned(It);
697 break;
Jessica Paquette596f4832017-03-06 21:31:18 +0000698
Jessica Paquette78681be2017-07-27 23:24:43 +0000699 case TargetInstrInfo::MachineOutlinerInstrType::Invisible:
700 break;
Jessica Paquette596f4832017-03-06 21:31:18 +0000701 }
702 }
703
704 // After we're done every insertion, uniquely terminate this part of the
705 // "string". This makes sure we won't match across basic block or function
706 // boundaries since the "end" is encoded uniquely and thus appears in no
707 // repeated substring.
708 InstrList.push_back(MBB.end());
709 UnsignedVec.push_back(IllegalInstrNumber);
710 IllegalInstrNumber--;
711 }
712
713 InstructionMapper() {
714 // Make sure that the implementation of DenseMapInfo<unsigned> hasn't
715 // changed.
716 assert(DenseMapInfo<unsigned>::getEmptyKey() == (unsigned)-1 &&
Jessica Paquette78681be2017-07-27 23:24:43 +0000717 "DenseMapInfo<unsigned>'s empty key isn't -1!");
Jessica Paquette596f4832017-03-06 21:31:18 +0000718 assert(DenseMapInfo<unsigned>::getTombstoneKey() == (unsigned)-2 &&
Jessica Paquette78681be2017-07-27 23:24:43 +0000719 "DenseMapInfo<unsigned>'s tombstone key isn't -2!");
Jessica Paquette596f4832017-03-06 21:31:18 +0000720 }
721};
722
723/// \brief An interprocedural pass which finds repeated sequences of
724/// instructions and replaces them with calls to functions.
725///
726/// Each instruction is mapped to an unsigned integer and placed in a string.
727/// The resulting mapping is then placed in a \p SuffixTree. The \p SuffixTree
728/// is then repeatedly queried for repeated sequences of instructions. Each
729/// non-overlapping repeated sequence is then placed in its own
730/// \p MachineFunction and each instance is then replaced with a call to that
731/// function.
732struct MachineOutliner : public ModulePass {
733
734 static char ID;
735
736 StringRef getPassName() const override { return "Machine Outliner"; }
737
738 void getAnalysisUsage(AnalysisUsage &AU) const override {
739 AU.addRequired<MachineModuleInfo>();
740 AU.addPreserved<MachineModuleInfo>();
741 AU.setPreservesAll();
742 ModulePass::getAnalysisUsage(AU);
743 }
744
745 MachineOutliner() : ModulePass(ID) {
746 initializeMachineOutlinerPass(*PassRegistry::getPassRegistry());
747 }
748
Jessica Paquette78681be2017-07-27 23:24:43 +0000749 /// Find all repeated substrings that satisfy the outlining cost model.
750 ///
751 /// If a substring appears at least twice, then it must be represented by
752 /// an internal node which appears in at least two suffixes. Each suffix is
753 /// represented by a leaf node. To do this, we visit each internal node in
754 /// the tree, using the leaf children of each internal node. If an internal
755 /// node represents a beneficial substring, then we use each of its leaf
756 /// children to find the locations of its substring.
757 ///
758 /// \param ST A suffix tree to query.
759 /// \param TII TargetInstrInfo for the target.
760 /// \param Mapper Contains outlining mapping information.
761 /// \param[out] CandidateList Filled with candidates representing each
762 /// beneficial substring.
763 /// \param[out] FunctionList Filled with a list of \p OutlinedFunctions each
764 /// type of candidate.
765 ///
766 /// \returns The length of the longest candidate found.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000767 unsigned findCandidates(SuffixTree &ST, const TargetInstrInfo &TII,
768 InstructionMapper &Mapper,
769 std::vector<Candidate> &CandidateList,
770 std::vector<OutlinedFunction> &FunctionList);
Jessica Paquette78681be2017-07-27 23:24:43 +0000771
Jessica Paquette596f4832017-03-06 21:31:18 +0000772 /// \brief Replace the sequences of instructions represented by the
773 /// \p Candidates in \p CandidateList with calls to \p MachineFunctions
774 /// described in \p FunctionList.
775 ///
776 /// \param M The module we are outlining from.
777 /// \param CandidateList A list of candidates to be outlined.
778 /// \param FunctionList A list of functions to be inserted into the module.
779 /// \param Mapper Contains the instruction mappings for the module.
780 bool outline(Module &M, const ArrayRef<Candidate> &CandidateList,
781 std::vector<OutlinedFunction> &FunctionList,
782 InstructionMapper &Mapper);
783
784 /// Creates a function for \p OF and inserts it into the module.
785 MachineFunction *createOutlinedFunction(Module &M, const OutlinedFunction &OF,
786 InstructionMapper &Mapper);
787
788 /// Find potential outlining candidates and store them in \p CandidateList.
789 ///
790 /// For each type of potential candidate, also build an \p OutlinedFunction
791 /// struct containing the information to build the function for that
792 /// candidate.
793 ///
794 /// \param[out] CandidateList Filled with outlining candidates for the module.
795 /// \param[out] FunctionList Filled with functions corresponding to each type
796 /// of \p Candidate.
797 /// \param ST The suffix tree for the module.
798 /// \param TII TargetInstrInfo for the module.
799 ///
800 /// \returns The length of the longest candidate found. 0 if there are none.
801 unsigned buildCandidateList(std::vector<Candidate> &CandidateList,
802 std::vector<OutlinedFunction> &FunctionList,
Jessica Paquette78681be2017-07-27 23:24:43 +0000803 SuffixTree &ST, InstructionMapper &Mapper,
Jessica Paquettec984e212017-03-13 18:39:33 +0000804 const TargetInstrInfo &TII);
Jessica Paquette596f4832017-03-06 21:31:18 +0000805
806 /// \brief Remove any overlapping candidates that weren't handled by the
807 /// suffix tree's pruning method.
808 ///
809 /// Pruning from the suffix tree doesn't necessarily remove all overlaps.
810 /// If a short candidate is chosen for outlining, then a longer candidate
811 /// which has that short candidate as a suffix is chosen, the tree's pruning
812 /// method will not find it. Thus, we need to prune before outlining as well.
813 ///
814 /// \param[in,out] CandidateList A list of outlining candidates.
815 /// \param[in,out] FunctionList A list of functions to be outlined.
Jessica Paquette809d7082017-07-28 03:21:58 +0000816 /// \param Mapper Contains instruction mapping info for outlining.
Jessica Paquette596f4832017-03-06 21:31:18 +0000817 /// \param MaxCandidateLen The length of the longest candidate.
818 /// \param TII TargetInstrInfo for the module.
819 void pruneOverlaps(std::vector<Candidate> &CandidateList,
820 std::vector<OutlinedFunction> &FunctionList,
Jessica Paquette809d7082017-07-28 03:21:58 +0000821 InstructionMapper &Mapper, unsigned MaxCandidateLen,
822 const TargetInstrInfo &TII);
Jessica Paquette596f4832017-03-06 21:31:18 +0000823
824 /// Construct a suffix tree on the instructions in \p M and outline repeated
825 /// strings from that tree.
826 bool runOnModule(Module &M) override;
827};
828
829} // Anonymous namespace.
830
831char MachineOutliner::ID = 0;
832
833namespace llvm {
834ModulePass *createMachineOutlinerPass() { return new MachineOutliner(); }
Jessica Paquette78681be2017-07-27 23:24:43 +0000835} // namespace llvm
Jessica Paquette596f4832017-03-06 21:31:18 +0000836
Jessica Paquette78681be2017-07-27 23:24:43 +0000837INITIALIZE_PASS(MachineOutliner, DEBUG_TYPE, "Machine Function Outliner", false,
838 false)
839
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000840unsigned
Jessica Paquette78681be2017-07-27 23:24:43 +0000841MachineOutliner::findCandidates(SuffixTree &ST, const TargetInstrInfo &TII,
842 InstructionMapper &Mapper,
843 std::vector<Candidate> &CandidateList,
844 std::vector<OutlinedFunction> &FunctionList) {
Jessica Paquette78681be2017-07-27 23:24:43 +0000845 CandidateList.clear();
846 FunctionList.clear();
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000847 unsigned FnIdx = 0;
848 unsigned MaxLen = 0;
Jessica Paquette78681be2017-07-27 23:24:43 +0000849
850 // FIXME: Visit internal nodes instead of leaves.
851 for (SuffixTreeNode *Leaf : ST.LeafVector) {
852 assert(Leaf && "Leaves in LeafVector cannot be null!");
853 if (!Leaf->IsInTree)
854 continue;
855
856 assert(Leaf->Parent && "All leaves must have parents!");
857 SuffixTreeNode &Parent = *(Leaf->Parent);
858
859 // If it doesn't appear enough, or we already outlined from it, skip it.
860 if (Parent.OccurrenceCount < 2 || Parent.isRoot() || !Parent.IsInTree)
861 continue;
862
Jessica Paquette809d7082017-07-28 03:21:58 +0000863 // Figure out if this candidate is beneficial.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000864 unsigned StringLen = Leaf->ConcatLen - (unsigned)Leaf->size();
Jessica Paquette95c11072017-08-14 22:57:41 +0000865
866 // Too short to be beneficial; skip it.
867 // FIXME: This isn't necessarily true for, say, X86. If we factor in
868 // instruction lengths we need more information than this.
869 if (StringLen < 2)
870 continue;
871
Jessica Paquetted87f5442017-07-29 02:55:46 +0000872 // If this is a beneficial class of candidate, then every one is stored in
873 // this vector.
874 std::vector<Candidate> CandidatesForRepeatedSeq;
875
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000876 // Describes the start and end point of each candidate. This allows the
877 // target to infer some information about each occurrence of each repeated
878 // sequence.
Jessica Paquetted87f5442017-07-29 02:55:46 +0000879 // FIXME: CandidatesForRepeatedSeq and this should be combined.
880 std::vector<
881 std::pair<MachineBasicBlock::iterator, MachineBasicBlock::iterator>>
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000882 RepeatedSequenceLocs;
Jessica Paquetted87f5442017-07-29 02:55:46 +0000883
Jessica Paquette809d7082017-07-28 03:21:58 +0000884 // Figure out the call overhead for each instance of the sequence.
885 for (auto &ChildPair : Parent.Children) {
886 SuffixTreeNode *M = ChildPair.second;
Jessica Paquette78681be2017-07-27 23:24:43 +0000887
Jessica Paquette809d7082017-07-28 03:21:58 +0000888 if (M && M->IsInTree && M->isLeaf()) {
889 // Each sequence is over [StartIt, EndIt].
890 MachineBasicBlock::iterator StartIt = Mapper.InstrList[M->SuffixIdx];
891 MachineBasicBlock::iterator EndIt =
892 Mapper.InstrList[M->SuffixIdx + StringLen - 1];
Jessica Paquetted87f5442017-07-29 02:55:46 +0000893
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000894 CandidatesForRepeatedSeq.emplace_back(M->SuffixIdx, StringLen, FnIdx);
895 RepeatedSequenceLocs.emplace_back(std::make_pair(StartIt, EndIt));
Jessica Paquetted87f5442017-07-29 02:55:46 +0000896
897 // Never visit this leaf again.
898 M->IsInTree = false;
Jessica Paquette809d7082017-07-28 03:21:58 +0000899 }
900 }
901
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000902 unsigned SequenceOverhead = StringLen;
903 TargetInstrInfo::MachineOutlinerInfo MInfo =
904 TII.getOutlininingCandidateInfo(RepeatedSequenceLocs);
Jessica Paquette809d7082017-07-28 03:21:58 +0000905
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000906 unsigned OutliningCost =
907 (MInfo.CallOverhead * Parent.OccurrenceCount) + MInfo.FrameOverhead;
908 unsigned NotOutliningCost = SequenceOverhead * Parent.OccurrenceCount;
Jessica Paquette809d7082017-07-28 03:21:58 +0000909
Jessica Paquetteffe4abc2017-08-31 21:02:45 +0000910 // Is it better to outline this candidate than not?
911 if (NotOutliningCost <= OutliningCost) {
912 // Outlining this candidate would take more instructions than not
913 // outlining.
914 // Emit a remark explaining why we didn't outline this candidate.
915 std::pair<MachineBasicBlock::iterator, MachineBasicBlock::iterator> C =
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000916 RepeatedSequenceLocs[0];
Jessica Paquetteffe4abc2017-08-31 21:02:45 +0000917 MachineOptimizationRemarkEmitter MORE(
918 *(C.first->getParent()->getParent()), nullptr);
919 MachineOptimizationRemarkMissed R(DEBUG_TYPE, "NotOutliningCheaper",
920 C.first->getDebugLoc(),
921 C.first->getParent());
922 R << "Did not outline " << NV("Length", StringLen) << " instructions"
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000923 << " from " << NV("NumOccurrences", RepeatedSequenceLocs.size())
Jessica Paquetteffe4abc2017-08-31 21:02:45 +0000924 << " locations."
925 << " Instructions from outlining all occurrences ("
926 << NV("OutliningCost", OutliningCost) << ")"
927 << " >= Unoutlined instruction count ("
928 << NV("NotOutliningCost", NotOutliningCost) << ")"
929 << " (Also found at: ";
930
931 // Tell the user the other places the candidate was found.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000932 for (unsigned i = 1, e = RepeatedSequenceLocs.size(); i < e; i++) {
Jessica Paquetteffe4abc2017-08-31 21:02:45 +0000933 R << NV((Twine("OtherStartLoc") + Twine(i)).str(),
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000934 RepeatedSequenceLocs[i].first->getDebugLoc());
Jessica Paquetteffe4abc2017-08-31 21:02:45 +0000935 if (i != e - 1)
936 R << ", ";
937 }
938
939 R << ")";
940 MORE.emit(R);
941
942 // Move to the next candidate.
Jessica Paquette78681be2017-07-27 23:24:43 +0000943 continue;
Jessica Paquetteffe4abc2017-08-31 21:02:45 +0000944 }
Jessica Paquette78681be2017-07-27 23:24:43 +0000945
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000946 unsigned Benefit = NotOutliningCost - OutliningCost;
Jessica Paquette809d7082017-07-28 03:21:58 +0000947
Jessica Paquette78681be2017-07-27 23:24:43 +0000948 if (StringLen > MaxLen)
949 MaxLen = StringLen;
950
Jessica Paquetted87f5442017-07-29 02:55:46 +0000951 // At this point, the candidate class is seen as beneficial. Set their
952 // benefit values and save them in the candidate list.
953 for (Candidate &C : CandidatesForRepeatedSeq) {
954 C.Benefit = Benefit;
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000955 C.MInfo = MInfo;
Jessica Paquetted87f5442017-07-29 02:55:46 +0000956 CandidateList.push_back(C);
Jessica Paquette78681be2017-07-27 23:24:43 +0000957 }
958
959 // Save the function for the new candidate sequence.
960 std::vector<unsigned> CandidateSequence;
961 for (unsigned i = Leaf->SuffixIdx; i < Leaf->SuffixIdx + StringLen; i++)
962 CandidateSequence.push_back(ST.Str[i]);
963
Jessica Paquetted87f5442017-07-29 02:55:46 +0000964 FunctionList.emplace_back(FnIdx, CandidatesForRepeatedSeq.size(),
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000965 CandidateSequence, Benefit, MInfo);
Jessica Paquette78681be2017-07-27 23:24:43 +0000966
967 // Move to the next function.
968 FnIdx++;
969 Parent.IsInTree = false;
970 }
971
972 return MaxLen;
973}
Jessica Paquette596f4832017-03-06 21:31:18 +0000974
975void MachineOutliner::pruneOverlaps(std::vector<Candidate> &CandidateList,
976 std::vector<OutlinedFunction> &FunctionList,
Jessica Paquette809d7082017-07-28 03:21:58 +0000977 InstructionMapper &Mapper,
Jessica Paquette596f4832017-03-06 21:31:18 +0000978 unsigned MaxCandidateLen,
979 const TargetInstrInfo &TII) {
Jessica Paquetteacffa282017-03-23 21:27:38 +0000980 // TODO: Experiment with interval trees or other interval-checking structures
981 // to lower the time complexity of this function.
982 // TODO: Can we do better than the simple greedy choice?
983 // Check for overlaps in the range.
984 // This is O(MaxCandidateLen * CandidateList.size()).
Jessica Paquette596f4832017-03-06 21:31:18 +0000985 for (auto It = CandidateList.begin(), Et = CandidateList.end(); It != Et;
986 It++) {
987 Candidate &C1 = *It;
988 OutlinedFunction &F1 = FunctionList[C1.FunctionIdx];
989
990 // If we removed this candidate, skip it.
991 if (!C1.InCandidateList)
992 continue;
993
Jessica Paquetteacffa282017-03-23 21:27:38 +0000994 // Is it still worth it to outline C1?
995 if (F1.Benefit < 1 || F1.OccurrenceCount < 2) {
996 assert(F1.OccurrenceCount > 0 &&
Jessica Paquette78681be2017-07-27 23:24:43 +0000997 "Can't remove OutlinedFunction with no occurrences!");
Jessica Paquetteacffa282017-03-23 21:27:38 +0000998 F1.OccurrenceCount--;
Jessica Paquette596f4832017-03-06 21:31:18 +0000999 C1.InCandidateList = false;
1000 continue;
1001 }
1002
1003 // The minimum start index of any candidate that could overlap with this
1004 // one.
1005 unsigned FarthestPossibleIdx = 0;
1006
1007 // Either the index is 0, or it's at most MaxCandidateLen indices away.
1008 if (C1.StartIdx > MaxCandidateLen)
1009 FarthestPossibleIdx = C1.StartIdx - MaxCandidateLen;
1010
Jessica Paquetteacffa282017-03-23 21:27:38 +00001011 // Compare against the candidates in the list that start at at most
1012 // FarthestPossibleIdx indices away from C1. There are at most
1013 // MaxCandidateLen of these.
Jessica Paquette596f4832017-03-06 21:31:18 +00001014 for (auto Sit = It + 1; Sit != Et; Sit++) {
1015 Candidate &C2 = *Sit;
1016 OutlinedFunction &F2 = FunctionList[C2.FunctionIdx];
1017
1018 // Is this candidate too far away to overlap?
Jessica Paquette596f4832017-03-06 21:31:18 +00001019 if (C2.StartIdx < FarthestPossibleIdx)
1020 break;
1021
1022 // Did we already remove this candidate in a previous step?
1023 if (!C2.InCandidateList)
1024 continue;
1025
1026 // Is the function beneficial to outline?
1027 if (F2.OccurrenceCount < 2 || F2.Benefit < 1) {
1028 // If not, remove this candidate and move to the next one.
Jessica Paquetteacffa282017-03-23 21:27:38 +00001029 assert(F2.OccurrenceCount > 0 &&
1030 "Can't remove OutlinedFunction with no occurrences!");
1031 F2.OccurrenceCount--;
Jessica Paquette596f4832017-03-06 21:31:18 +00001032 C2.InCandidateList = false;
1033 continue;
1034 }
1035
Jessica Paquette4cf187b2017-09-27 20:47:39 +00001036 unsigned C2End = C2.StartIdx + C2.Len - 1;
Jessica Paquette596f4832017-03-06 21:31:18 +00001037
1038 // Do C1 and C2 overlap?
1039 //
1040 // Not overlapping:
1041 // High indices... [C1End ... C1Start][C2End ... C2Start] ...Low indices
1042 //
1043 // We sorted our candidate list so C2Start <= C1Start. We know that
1044 // C2End > C2Start since each candidate has length >= 2. Therefore, all we
1045 // have to check is C2End < C2Start to see if we overlap.
1046 if (C2End < C1.StartIdx)
1047 continue;
1048
Jessica Paquetteacffa282017-03-23 21:27:38 +00001049 // C1 and C2 overlap.
1050 // We need to choose the better of the two.
1051 //
1052 // Approximate this by picking the one which would have saved us the
1053 // most instructions before any pruning.
1054 if (C1.Benefit >= C2.Benefit) {
Jessica Paquette596f4832017-03-06 21:31:18 +00001055
Jessica Paquetteacffa282017-03-23 21:27:38 +00001056 // C1 is better, so remove C2 and update C2's OutlinedFunction to
1057 // reflect the removal.
1058 assert(F2.OccurrenceCount > 0 &&
1059 "Can't remove OutlinedFunction with no occurrences!");
1060 F2.OccurrenceCount--;
Jessica Paquette809d7082017-07-28 03:21:58 +00001061
1062 // Remove the call overhead from the removed sequence.
Jessica Paquette4cf187b2017-09-27 20:47:39 +00001063 F2.Benefit += C2.MInfo.CallOverhead;
Jessica Paquetted87f5442017-07-29 02:55:46 +00001064
Jessica Paquette809d7082017-07-28 03:21:58 +00001065 // Add back one instance of the sequence.
Jessica Paquette809d7082017-07-28 03:21:58 +00001066 if (F2.Sequence.size() > F2.Benefit)
1067 F2.Benefit = 0;
1068 else
1069 F2.Benefit -= F2.Sequence.size();
Jessica Paquette596f4832017-03-06 21:31:18 +00001070
Jessica Paquetteacffa282017-03-23 21:27:38 +00001071 C2.InCandidateList = false;
Jessica Paquette596f4832017-03-06 21:31:18 +00001072
Jessica Paquette78681be2017-07-27 23:24:43 +00001073 DEBUG(dbgs() << "- Removed C2. \n";
1074 dbgs() << "--- Num fns left for C2: " << F2.OccurrenceCount
1075 << "\n";
1076 dbgs() << "--- C2's benefit: " << F2.Benefit << "\n";);
Jessica Paquetteacffa282017-03-23 21:27:38 +00001077
1078 } else {
1079 // C2 is better, so remove C1 and update C1's OutlinedFunction to
1080 // reflect the removal.
1081 assert(F1.OccurrenceCount > 0 &&
1082 "Can't remove OutlinedFunction with no occurrences!");
1083 F1.OccurrenceCount--;
Jessica Paquette809d7082017-07-28 03:21:58 +00001084
1085 // Remove the call overhead from the removed sequence.
Jessica Paquette4cf187b2017-09-27 20:47:39 +00001086 F1.Benefit += C1.MInfo.CallOverhead;
Jessica Paquette809d7082017-07-28 03:21:58 +00001087
1088 // Add back one instance of the sequence.
1089 if (F1.Sequence.size() > F1.Benefit)
1090 F1.Benefit = 0;
1091 else
1092 F1.Benefit -= F1.Sequence.size();
1093
Jessica Paquetteacffa282017-03-23 21:27:38 +00001094 C1.InCandidateList = false;
1095
Jessica Paquette78681be2017-07-27 23:24:43 +00001096 DEBUG(dbgs() << "- Removed C1. \n";
1097 dbgs() << "--- Num fns left for C1: " << F1.OccurrenceCount
1098 << "\n";
1099 dbgs() << "--- C1's benefit: " << F1.Benefit << "\n";);
Jessica Paquetteacffa282017-03-23 21:27:38 +00001100
1101 // C1 is out, so we don't have to compare it against anyone else.
1102 break;
1103 }
Jessica Paquette596f4832017-03-06 21:31:18 +00001104 }
1105 }
1106}
1107
1108unsigned
1109MachineOutliner::buildCandidateList(std::vector<Candidate> &CandidateList,
1110 std::vector<OutlinedFunction> &FunctionList,
Jessica Paquette78681be2017-07-27 23:24:43 +00001111 SuffixTree &ST, InstructionMapper &Mapper,
Jessica Paquette596f4832017-03-06 21:31:18 +00001112 const TargetInstrInfo &TII) {
1113
1114 std::vector<unsigned> CandidateSequence; // Current outlining candidate.
Jessica Paquette4cf187b2017-09-27 20:47:39 +00001115 unsigned MaxCandidateLen = 0; // Length of the longest candidate.
Jessica Paquette596f4832017-03-06 21:31:18 +00001116
Jessica Paquette78681be2017-07-27 23:24:43 +00001117 MaxCandidateLen =
1118 findCandidates(ST, TII, Mapper, CandidateList, FunctionList);
Jessica Paquette596f4832017-03-06 21:31:18 +00001119
Jessica Paquette596f4832017-03-06 21:31:18 +00001120 // Sort the candidates in decending order. This will simplify the outlining
1121 // process when we have to remove the candidates from the mapping by
1122 // allowing us to cut them out without keeping track of an offset.
1123 std::stable_sort(CandidateList.begin(), CandidateList.end());
1124
1125 return MaxCandidateLen;
1126}
1127
1128MachineFunction *
1129MachineOutliner::createOutlinedFunction(Module &M, const OutlinedFunction &OF,
Jessica Paquette78681be2017-07-27 23:24:43 +00001130 InstructionMapper &Mapper) {
Jessica Paquette596f4832017-03-06 21:31:18 +00001131
1132 // Create the function name. This should be unique. For now, just hash the
1133 // module name and include it in the function name plus the number of this
1134 // function.
1135 std::ostringstream NameStream;
Jessica Paquette78681be2017-07-27 23:24:43 +00001136 NameStream << "OUTLINED_FUNCTION_" << OF.Name;
Jessica Paquette596f4832017-03-06 21:31:18 +00001137
1138 // Create the function using an IR-level function.
1139 LLVMContext &C = M.getContext();
1140 Function *F = dyn_cast<Function>(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00001141 M.getOrInsertFunction(NameStream.str(), Type::getVoidTy(C)));
Jessica Paquette596f4832017-03-06 21:31:18 +00001142 assert(F && "Function was null!");
1143
1144 // NOTE: If this is linkonceodr, then we can take advantage of linker deduping
1145 // which gives us better results when we outline from linkonceodr functions.
1146 F->setLinkage(GlobalValue::PrivateLinkage);
1147 F->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
1148
1149 BasicBlock *EntryBB = BasicBlock::Create(C, "entry", F);
1150 IRBuilder<> Builder(EntryBB);
1151 Builder.CreateRetVoid();
1152
1153 MachineModuleInfo &MMI = getAnalysis<MachineModuleInfo>();
Matthias Braun7bda1952017-06-06 00:44:35 +00001154 MachineFunction &MF = MMI.getOrCreateMachineFunction(*F);
Jessica Paquette596f4832017-03-06 21:31:18 +00001155 MachineBasicBlock &MBB = *MF.CreateMachineBasicBlock();
1156 const TargetSubtargetInfo &STI = MF.getSubtarget();
1157 const TargetInstrInfo &TII = *STI.getInstrInfo();
1158
1159 // Insert the new function into the module.
1160 MF.insert(MF.begin(), &MBB);
1161
Jessica Paquette4cf187b2017-09-27 20:47:39 +00001162 TII.insertOutlinerPrologue(MBB, MF, OF.MInfo);
Jessica Paquette596f4832017-03-06 21:31:18 +00001163
1164 // Copy over the instructions for the function using the integer mappings in
1165 // its sequence.
1166 for (unsigned Str : OF.Sequence) {
1167 MachineInstr *NewMI =
1168 MF.CloneMachineInstr(Mapper.IntegerInstructionMap.find(Str)->second);
1169 NewMI->dropMemRefs();
1170
1171 // Don't keep debug information for outlined instructions.
1172 // FIXME: This means outlined functions are currently undebuggable.
1173 NewMI->setDebugLoc(DebugLoc());
1174 MBB.insert(MBB.end(), NewMI);
1175 }
1176
Jessica Paquette4cf187b2017-09-27 20:47:39 +00001177 TII.insertOutlinerEpilogue(MBB, MF, OF.MInfo);
Jessica Paquette596f4832017-03-06 21:31:18 +00001178
1179 return &MF;
1180}
1181
1182bool MachineOutliner::outline(Module &M,
1183 const ArrayRef<Candidate> &CandidateList,
1184 std::vector<OutlinedFunction> &FunctionList,
1185 InstructionMapper &Mapper) {
1186
1187 bool OutlinedSomething = false;
Jessica Paquette596f4832017-03-06 21:31:18 +00001188 // Replace the candidates with calls to their respective outlined functions.
1189 for (const Candidate &C : CandidateList) {
1190
1191 // Was the candidate removed during pruneOverlaps?
1192 if (!C.InCandidateList)
1193 continue;
1194
1195 // If not, then look at its OutlinedFunction.
1196 OutlinedFunction &OF = FunctionList[C.FunctionIdx];
1197
1198 // Was its OutlinedFunction made unbeneficial during pruneOverlaps?
1199 if (OF.OccurrenceCount < 2 || OF.Benefit < 1)
1200 continue;
1201
1202 // If not, then outline it.
1203 assert(C.StartIdx < Mapper.InstrList.size() && "Candidate out of bounds!");
1204 MachineBasicBlock *MBB = (*Mapper.InstrList[C.StartIdx]).getParent();
1205 MachineBasicBlock::iterator StartIt = Mapper.InstrList[C.StartIdx];
1206 unsigned EndIdx = C.StartIdx + C.Len - 1;
1207
1208 assert(EndIdx < Mapper.InstrList.size() && "Candidate out of bounds!");
1209 MachineBasicBlock::iterator EndIt = Mapper.InstrList[EndIdx];
1210 assert(EndIt != MBB->end() && "EndIt out of bounds!");
1211
1212 EndIt++; // Erase needs one past the end index.
1213
1214 // Does this candidate have a function yet?
Jessica Paquetteacffa282017-03-23 21:27:38 +00001215 if (!OF.MF) {
Jessica Paquette596f4832017-03-06 21:31:18 +00001216 OF.MF = createOutlinedFunction(M, OF, Mapper);
Jessica Paquetteacffa282017-03-23 21:27:38 +00001217 FunctionsCreated++;
1218 }
Jessica Paquette596f4832017-03-06 21:31:18 +00001219
1220 MachineFunction *MF = OF.MF;
1221 const TargetSubtargetInfo &STI = MF->getSubtarget();
1222 const TargetInstrInfo &TII = *STI.getInstrInfo();
1223
1224 // Insert a call to the new function and erase the old sequence.
Jessica Paquette4cf187b2017-09-27 20:47:39 +00001225 TII.insertOutlinedCall(M, *MBB, StartIt, *MF, C.MInfo);
Jessica Paquette596f4832017-03-06 21:31:18 +00001226 StartIt = Mapper.InstrList[C.StartIdx];
1227 MBB->erase(StartIt, EndIt);
1228
1229 OutlinedSomething = true;
1230
1231 // Statistics.
1232 NumOutlined++;
1233 }
1234
Jessica Paquette78681be2017-07-27 23:24:43 +00001235 DEBUG(dbgs() << "OutlinedSomething = " << OutlinedSomething << "\n";);
Jessica Paquette596f4832017-03-06 21:31:18 +00001236
1237 return OutlinedSomething;
1238}
1239
1240bool MachineOutliner::runOnModule(Module &M) {
1241
1242 // Is there anything in the module at all?
1243 if (M.empty())
1244 return false;
1245
1246 MachineModuleInfo &MMI = getAnalysis<MachineModuleInfo>();
Jessica Paquette78681be2017-07-27 23:24:43 +00001247 const TargetSubtargetInfo &STI =
1248 MMI.getOrCreateMachineFunction(*M.begin()).getSubtarget();
Jessica Paquette596f4832017-03-06 21:31:18 +00001249 const TargetRegisterInfo *TRI = STI.getRegisterInfo();
1250 const TargetInstrInfo *TII = STI.getInstrInfo();
1251
1252 InstructionMapper Mapper;
1253
1254 // Build instruction mappings for each function in the module.
1255 for (Function &F : M) {
Matthias Braun7bda1952017-06-06 00:44:35 +00001256 MachineFunction &MF = MMI.getOrCreateMachineFunction(F);
Jessica Paquette596f4832017-03-06 21:31:18 +00001257
1258 // Is the function empty? Safe to outline from?
1259 if (F.empty() || !TII->isFunctionSafeToOutlineFrom(MF))
1260 continue;
1261
1262 // If it is, look at each MachineBasicBlock in the function.
1263 for (MachineBasicBlock &MBB : MF) {
1264
1265 // Is there anything in MBB?
1266 if (MBB.empty())
1267 continue;
1268
1269 // If yes, map it.
1270 Mapper.convertToUnsignedVec(MBB, *TRI, *TII);
1271 }
1272 }
1273
1274 // Construct a suffix tree, use it to find candidates, and then outline them.
1275 SuffixTree ST(Mapper.UnsignedVec);
1276 std::vector<Candidate> CandidateList;
1277 std::vector<OutlinedFunction> FunctionList;
1278
Jessica Paquetteacffa282017-03-23 21:27:38 +00001279 // Find all of the outlining candidates.
Jessica Paquette596f4832017-03-06 21:31:18 +00001280 unsigned MaxCandidateLen =
Jessica Paquettec984e212017-03-13 18:39:33 +00001281 buildCandidateList(CandidateList, FunctionList, ST, Mapper, *TII);
Jessica Paquette596f4832017-03-06 21:31:18 +00001282
Jessica Paquetteacffa282017-03-23 21:27:38 +00001283 // Remove candidates that overlap with other candidates.
Jessica Paquette809d7082017-07-28 03:21:58 +00001284 pruneOverlaps(CandidateList, FunctionList, Mapper, MaxCandidateLen, *TII);
Jessica Paquetteacffa282017-03-23 21:27:38 +00001285
1286 // Outline each of the candidates and return true if something was outlined.
Jessica Paquette596f4832017-03-06 21:31:18 +00001287 return outline(M, CandidateList, FunctionList, Mapper);
1288}