blob: 8c268cf32d85f1c29e1cbf161a621ba6a796eb21 [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 {
Jessica Paquettec9ab4c22017-10-17 18:43:15 +000095private:
96 /// The start index of this \p Candidate in the instruction list.
Jessica Paquette4cf187b2017-09-27 20:47:39 +000097 unsigned StartIdx;
Jessica Paquetteacffa282017-03-23 21:27:38 +000098
99 /// The number of instructions in this \p Candidate.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000100 unsigned Len;
Jessica Paquetteacffa282017-03-23 21:27:38 +0000101
Jessica Paquettec9ab4c22017-10-17 18:43:15 +0000102public:
103 /// Set to false if the candidate overlapped with another candidate.
104 bool InCandidateList = true;
105
106 /// \brief The index of this \p Candidate's \p OutlinedFunction in the list of
Jessica Paquetteacffa282017-03-23 21:27:38 +0000107 /// \p OutlinedFunctions.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000108 unsigned FunctionIdx;
Jessica Paquetteacffa282017-03-23 21:27:38 +0000109
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000110 /// Contains all target-specific information for this \p Candidate.
111 TargetInstrInfo::MachineOutlinerInfo MInfo;
Jessica Paquetted87f5442017-07-29 02:55:46 +0000112
Jessica Paquettec9ab4c22017-10-17 18:43:15 +0000113 /// Return the number of instructions in this Candidate.
114 unsigned length() const { return Len; }
115
116 /// Return the start index of this candidate.
117 unsigned startIdx() const { return StartIdx; }
118
119 // Return the end index of this candidate.
120 unsigned endIdx() const { return StartIdx + Len - 1; }
121
Jessica Paquetteacffa282017-03-23 21:27:38 +0000122 /// \brief The number of instructions that would be saved by outlining every
123 /// candidate of this type.
124 ///
125 /// This is a fixed value which is not updated during the candidate pruning
126 /// process. It is only used for deciding which candidate to keep if two
127 /// candidates overlap. The true benefit is stored in the OutlinedFunction
128 /// for some given candidate.
129 unsigned Benefit = 0;
130
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000131 Candidate(unsigned StartIdx, unsigned Len, unsigned FunctionIdx)
132 : StartIdx(StartIdx), Len(Len), FunctionIdx(FunctionIdx) {}
Jessica Paquetteacffa282017-03-23 21:27:38 +0000133
134 Candidate() {}
135
136 /// \brief Used to ensure that \p Candidates are outlined in an order that
137 /// preserves the start and end indices of other \p Candidates.
Jessica Paquettec9ab4c22017-10-17 18:43:15 +0000138 bool operator<(const Candidate &RHS) const {
139 return startIdx() > RHS.startIdx();
140 }
Jessica Paquetteacffa282017-03-23 21:27:38 +0000141};
142
143/// \brief The information necessary to create an outlined function for some
144/// class of candidate.
145struct OutlinedFunction {
146
Jessica Paquette85af63d2017-10-17 19:03:23 +0000147private:
148 /// The number of candidates for this \p OutlinedFunction.
149 unsigned OccurrenceCount = 0;
150
151public:
Jessica Paquetteacffa282017-03-23 21:27:38 +0000152 /// The actual outlined function created.
153 /// This is initialized after we go through and create the actual function.
154 MachineFunction *MF = nullptr;
155
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000156 /// A number assigned to this function which appears at the end of its name.
157 unsigned Name;
Jessica Paquetteacffa282017-03-23 21:27:38 +0000158
Jessica Paquetteacffa282017-03-23 21:27:38 +0000159 /// \brief The sequence of integers corresponding to the instructions in this
160 /// function.
161 std::vector<unsigned> Sequence;
162
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000163 /// Contains all target-specific information for this \p OutlinedFunction.
164 TargetInstrInfo::MachineOutlinerInfo MInfo;
Jessica Paquetteacffa282017-03-23 21:27:38 +0000165
Jessica Paquette85af63d2017-10-17 19:03:23 +0000166 /// Return the number of candidates for this \p OutlinedFunction.
Jessica Paquette60d31fc2017-10-17 21:11:58 +0000167 unsigned getOccurrenceCount() { return OccurrenceCount; }
Jessica Paquette85af63d2017-10-17 19:03:23 +0000168
169 /// Decrement the occurrence count of this OutlinedFunction and return the
170 /// new count.
171 unsigned decrement() {
172 assert(OccurrenceCount > 0 && "Can't decrement an empty function!");
173 OccurrenceCount--;
174 return getOccurrenceCount();
175 }
176
Jessica Paquetteacc15e12017-10-03 20:32:55 +0000177 /// \brief Return the number of instructions it would take to outline this
178 /// function.
179 unsigned getOutliningCost() {
180 return (OccurrenceCount * MInfo.CallOverhead) + Sequence.size() +
181 MInfo.FrameOverhead;
182 }
183
184 /// \brief Return the number of instructions that would be saved by outlining
185 /// this function.
186 unsigned getBenefit() {
187 unsigned NotOutlinedCost = OccurrenceCount * Sequence.size();
188 unsigned OutlinedCost = getOutliningCost();
189 return (NotOutlinedCost < OutlinedCost) ? 0
190 : NotOutlinedCost - OutlinedCost;
191 }
192
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000193 OutlinedFunction(unsigned Name, unsigned OccurrenceCount,
Jessica Paquetteacc15e12017-10-03 20:32:55 +0000194 const std::vector<unsigned> &Sequence,
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000195 TargetInstrInfo::MachineOutlinerInfo &MInfo)
Jessica Paquette85af63d2017-10-17 19:03:23 +0000196 : OccurrenceCount(OccurrenceCount), Name(Name), Sequence(Sequence),
Jessica Paquetteacc15e12017-10-03 20:32:55 +0000197 MInfo(MInfo) {}
Jessica Paquetteacffa282017-03-23 21:27:38 +0000198};
199
Jessica Paquette596f4832017-03-06 21:31:18 +0000200/// Represents an undefined index in the suffix tree.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000201const unsigned EmptyIdx = -1;
Jessica Paquette596f4832017-03-06 21:31:18 +0000202
203/// A node in a suffix tree which represents a substring or suffix.
204///
205/// Each node has either no children or at least two children, with the root
206/// being a exception in the empty tree.
207///
208/// Children are represented as a map between unsigned integers and nodes. If
209/// a node N has a child M on unsigned integer k, then the mapping represented
210/// by N is a proper prefix of the mapping represented by M. Note that this,
211/// although similar to a trie is somewhat different: each node stores a full
212/// substring of the full mapping rather than a single character state.
213///
214/// Each internal node contains a pointer to the internal node representing
215/// the same string, but with the first character chopped off. This is stored
216/// in \p Link. Each leaf node stores the start index of its respective
217/// suffix in \p SuffixIdx.
218struct SuffixTreeNode {
219
220 /// The children of this node.
221 ///
222 /// A child existing on an unsigned integer implies that from the mapping
223 /// represented by the current node, there is a way to reach another
224 /// mapping by tacking that character on the end of the current string.
225 DenseMap<unsigned, SuffixTreeNode *> Children;
226
227 /// A flag set to false if the node has been pruned from the tree.
228 bool IsInTree = true;
229
230 /// The start index of this node's substring in the main string.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000231 unsigned StartIdx = EmptyIdx;
Jessica Paquette596f4832017-03-06 21:31:18 +0000232
233 /// The end index of this node's substring in the main string.
234 ///
235 /// Every leaf node must have its \p EndIdx incremented at the end of every
236 /// step in the construction algorithm. To avoid having to update O(N)
237 /// nodes individually at the end of every step, the end index is stored
238 /// as a pointer.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000239 unsigned *EndIdx = nullptr;
Jessica Paquette596f4832017-03-06 21:31:18 +0000240
241 /// For leaves, the start index of the suffix represented by this node.
242 ///
243 /// For all other nodes, this is ignored.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000244 unsigned SuffixIdx = EmptyIdx;
Jessica Paquette596f4832017-03-06 21:31:18 +0000245
246 /// \brief For internal nodes, a pointer to the internal node representing
247 /// the same sequence with the first character chopped off.
248 ///
Jessica Paquette4602c342017-07-28 05:59:30 +0000249 /// This acts as a shortcut in Ukkonen's algorithm. One of the things that
Jessica Paquette596f4832017-03-06 21:31:18 +0000250 /// Ukkonen's algorithm does to achieve linear-time construction is
251 /// keep track of which node the next insert should be at. This makes each
252 /// insert O(1), and there are a total of O(N) inserts. The suffix link
253 /// helps with inserting children of internal nodes.
254 ///
Jessica Paquette78681be2017-07-27 23:24:43 +0000255 /// Say we add a child to an internal node with associated mapping S. The
Jessica Paquette596f4832017-03-06 21:31:18 +0000256 /// next insertion must be at the node representing S - its first character.
257 /// This is given by the way that we iteratively build the tree in Ukkonen's
258 /// algorithm. The main idea is to look at the suffixes of each prefix in the
259 /// string, starting with the longest suffix of the prefix, and ending with
260 /// the shortest. Therefore, if we keep pointers between such nodes, we can
261 /// move to the next insertion point in O(1) time. If we don't, then we'd
262 /// have to query from the root, which takes O(N) time. This would make the
263 /// construction algorithm O(N^2) rather than O(N).
Jessica Paquette596f4832017-03-06 21:31:18 +0000264 SuffixTreeNode *Link = nullptr;
265
266 /// The parent of this node. Every node except for the root has a parent.
267 SuffixTreeNode *Parent = nullptr;
268
269 /// The number of times this node's string appears in the tree.
270 ///
271 /// This is equal to the number of leaf children of the string. It represents
272 /// the number of suffixes that the node's string is a prefix of.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000273 unsigned OccurrenceCount = 0;
Jessica Paquette596f4832017-03-06 21:31:18 +0000274
Jessica Paquetteacffa282017-03-23 21:27:38 +0000275 /// The length of the string formed by concatenating the edge labels from the
276 /// root to this node.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000277 unsigned ConcatLen = 0;
Jessica Paquetteacffa282017-03-23 21:27:38 +0000278
Jessica Paquette596f4832017-03-06 21:31:18 +0000279 /// Returns true if this node is a leaf.
280 bool isLeaf() const { return SuffixIdx != EmptyIdx; }
281
282 /// Returns true if this node is the root of its owning \p SuffixTree.
283 bool isRoot() const { return StartIdx == EmptyIdx; }
284
285 /// Return the number of elements in the substring associated with this node.
286 size_t size() const {
287
288 // Is it the root? If so, it's the empty string so return 0.
289 if (isRoot())
290 return 0;
291
292 assert(*EndIdx != EmptyIdx && "EndIdx is undefined!");
293
294 // Size = the number of elements in the string.
295 // For example, [0 1 2 3] has length 4, not 3. 3-0 = 3, so we have 3-0+1.
296 return *EndIdx - StartIdx + 1;
297 }
298
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000299 SuffixTreeNode(unsigned StartIdx, unsigned *EndIdx, SuffixTreeNode *Link,
Jessica Paquette596f4832017-03-06 21:31:18 +0000300 SuffixTreeNode *Parent)
301 : StartIdx(StartIdx), EndIdx(EndIdx), Link(Link), Parent(Parent) {}
302
303 SuffixTreeNode() {}
304};
305
306/// A data structure for fast substring queries.
307///
308/// Suffix trees represent the suffixes of their input strings in their leaves.
309/// A suffix tree is a type of compressed trie structure where each node
310/// represents an entire substring rather than a single character. Each leaf
311/// of the tree is a suffix.
312///
313/// A suffix tree can be seen as a type of state machine where each state is a
314/// substring of the full string. The tree is structured so that, for a string
315/// of length N, there are exactly N leaves in the tree. This structure allows
316/// us to quickly find repeated substrings of the input string.
317///
318/// In this implementation, a "string" is a vector of unsigned integers.
319/// These integers may result from hashing some data type. A suffix tree can
320/// contain 1 or many strings, which can then be queried as one large string.
321///
322/// The suffix tree is implemented using Ukkonen's algorithm for linear-time
323/// suffix tree construction. Ukkonen's algorithm is explained in more detail
324/// in the paper by Esko Ukkonen "On-line construction of suffix trees. The
325/// paper is available at
326///
327/// https://www.cs.helsinki.fi/u/ukkonen/SuffixT1withFigs.pdf
328class SuffixTree {
Jessica Paquette78681be2017-07-27 23:24:43 +0000329public:
330 /// Stores each leaf node in the tree.
331 ///
332 /// This is used for finding outlining candidates.
333 std::vector<SuffixTreeNode *> LeafVector;
334
Jessica Paquette596f4832017-03-06 21:31:18 +0000335 /// Each element is an integer representing an instruction in the module.
336 ArrayRef<unsigned> Str;
337
Jessica Paquette78681be2017-07-27 23:24:43 +0000338private:
Jessica Paquette596f4832017-03-06 21:31:18 +0000339 /// Maintains each node in the tree.
Jessica Paquetted4cb9c62017-03-08 23:55:33 +0000340 SpecificBumpPtrAllocator<SuffixTreeNode> NodeAllocator;
Jessica Paquette596f4832017-03-06 21:31:18 +0000341
342 /// The root of the suffix tree.
343 ///
344 /// The root represents the empty string. It is maintained by the
345 /// \p NodeAllocator like every other node in the tree.
346 SuffixTreeNode *Root = nullptr;
347
Jessica Paquette596f4832017-03-06 21:31:18 +0000348 /// Maintains the end indices of the internal nodes in the tree.
349 ///
350 /// Each internal node is guaranteed to never have its end index change
351 /// during the construction algorithm; however, leaves must be updated at
352 /// every step. Therefore, we need to store leaf end indices by reference
353 /// to avoid updating O(N) leaves at every step of construction. Thus,
354 /// every internal node must be allocated its own end index.
355 BumpPtrAllocator InternalEndIdxAllocator;
356
357 /// The end index of each leaf in the tree.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000358 unsigned LeafEndIdx = -1;
Jessica Paquette596f4832017-03-06 21:31:18 +0000359
360 /// \brief Helper struct which keeps track of the next insertion point in
361 /// Ukkonen's algorithm.
362 struct ActiveState {
363 /// The next node to insert at.
364 SuffixTreeNode *Node;
365
366 /// The index of the first character in the substring currently being added.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000367 unsigned Idx = EmptyIdx;
Jessica Paquette596f4832017-03-06 21:31:18 +0000368
369 /// The length of the substring we have to add at the current step.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000370 unsigned Len = 0;
Jessica Paquette596f4832017-03-06 21:31:18 +0000371 };
372
373 /// \brief The point the next insertion will take place at in the
374 /// construction algorithm.
375 ActiveState Active;
376
377 /// Allocate a leaf node and add it to the tree.
378 ///
379 /// \param Parent The parent of this node.
380 /// \param StartIdx The start index of this node's associated string.
381 /// \param Edge The label on the edge leaving \p Parent to this node.
382 ///
383 /// \returns A pointer to the allocated leaf node.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000384 SuffixTreeNode *insertLeaf(SuffixTreeNode &Parent, unsigned StartIdx,
Jessica Paquette596f4832017-03-06 21:31:18 +0000385 unsigned Edge) {
386
387 assert(StartIdx <= LeafEndIdx && "String can't start after it ends!");
388
Jessica Paquette78681be2017-07-27 23:24:43 +0000389 SuffixTreeNode *N = new (NodeAllocator.Allocate())
390 SuffixTreeNode(StartIdx, &LeafEndIdx, nullptr, &Parent);
Jessica Paquette596f4832017-03-06 21:31:18 +0000391 Parent.Children[Edge] = N;
392
393 return N;
394 }
395
396 /// Allocate an internal node and add it to the tree.
397 ///
398 /// \param Parent The parent of this node. Only null when allocating the root.
399 /// \param StartIdx The start index of this node's associated string.
400 /// \param EndIdx The end index of this node's associated string.
401 /// \param Edge The label on the edge leaving \p Parent to this node.
402 ///
403 /// \returns A pointer to the allocated internal node.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000404 SuffixTreeNode *insertInternalNode(SuffixTreeNode *Parent, unsigned StartIdx,
405 unsigned EndIdx, unsigned Edge) {
Jessica Paquette596f4832017-03-06 21:31:18 +0000406
407 assert(StartIdx <= EndIdx && "String can't start after it ends!");
408 assert(!(!Parent && StartIdx != EmptyIdx) &&
Jessica Paquette78681be2017-07-27 23:24:43 +0000409 "Non-root internal nodes must have parents!");
Jessica Paquette596f4832017-03-06 21:31:18 +0000410
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000411 unsigned *E = new (InternalEndIdxAllocator) unsigned(EndIdx);
Jessica Paquette78681be2017-07-27 23:24:43 +0000412 SuffixTreeNode *N = new (NodeAllocator.Allocate())
413 SuffixTreeNode(StartIdx, E, Root, Parent);
Jessica Paquette596f4832017-03-06 21:31:18 +0000414 if (Parent)
415 Parent->Children[Edge] = N;
416
417 return N;
418 }
419
420 /// \brief Set the suffix indices of the leaves to the start indices of their
421 /// respective suffixes. Also stores each leaf in \p LeafVector at its
422 /// respective suffix index.
423 ///
424 /// \param[in] CurrNode The node currently being visited.
425 /// \param CurrIdx The current index of the string being visited.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000426 void setSuffixIndices(SuffixTreeNode &CurrNode, unsigned CurrIdx) {
Jessica Paquette596f4832017-03-06 21:31:18 +0000427
428 bool IsLeaf = CurrNode.Children.size() == 0 && !CurrNode.isRoot();
429
Jessica Paquetteacffa282017-03-23 21:27:38 +0000430 // Store the length of the concatenation of all strings from the root to
431 // this node.
432 if (!CurrNode.isRoot()) {
433 if (CurrNode.ConcatLen == 0)
434 CurrNode.ConcatLen = CurrNode.size();
435
436 if (CurrNode.Parent)
Jessica Paquette78681be2017-07-27 23:24:43 +0000437 CurrNode.ConcatLen += CurrNode.Parent->ConcatLen;
Jessica Paquetteacffa282017-03-23 21:27:38 +0000438 }
439
Jessica Paquette596f4832017-03-06 21:31:18 +0000440 // Traverse the tree depth-first.
441 for (auto &ChildPair : CurrNode.Children) {
442 assert(ChildPair.second && "Node had a null child!");
Jessica Paquette78681be2017-07-27 23:24:43 +0000443 setSuffixIndices(*ChildPair.second, CurrIdx + ChildPair.second->size());
Jessica Paquette596f4832017-03-06 21:31:18 +0000444 }
445
446 // Is this node a leaf?
447 if (IsLeaf) {
448 // If yes, give it a suffix index and bump its parent's occurrence count.
449 CurrNode.SuffixIdx = Str.size() - CurrIdx;
450 assert(CurrNode.Parent && "CurrNode had no parent!");
451 CurrNode.Parent->OccurrenceCount++;
452
453 // Store the leaf in the leaf vector for pruning later.
454 LeafVector[CurrNode.SuffixIdx] = &CurrNode;
455 }
456 }
457
458 /// \brief Construct the suffix tree for the prefix of the input ending at
459 /// \p EndIdx.
460 ///
461 /// Used to construct the full suffix tree iteratively. At the end of each
462 /// step, the constructed suffix tree is either a valid suffix tree, or a
463 /// suffix tree with implicit suffixes. At the end of the final step, the
464 /// suffix tree is a valid tree.
465 ///
466 /// \param EndIdx The end index of the current prefix in the main string.
467 /// \param SuffixesToAdd The number of suffixes that must be added
468 /// to complete the suffix tree at the current phase.
469 ///
470 /// \returns The number of suffixes that have not been added at the end of
471 /// this step.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000472 unsigned extend(unsigned EndIdx, unsigned SuffixesToAdd) {
Jessica Paquette596f4832017-03-06 21:31:18 +0000473 SuffixTreeNode *NeedsLink = nullptr;
474
475 while (SuffixesToAdd > 0) {
Jessica Paquette78681be2017-07-27 23:24:43 +0000476
Jessica Paquette596f4832017-03-06 21:31:18 +0000477 // Are we waiting to add anything other than just the last character?
478 if (Active.Len == 0) {
479 // If not, then say the active index is the end index.
480 Active.Idx = EndIdx;
481 }
482
483 assert(Active.Idx <= EndIdx && "Start index can't be after end index!");
484
485 // The first character in the current substring we're looking at.
486 unsigned FirstChar = Str[Active.Idx];
487
488 // Have we inserted anything starting with FirstChar at the current node?
489 if (Active.Node->Children.count(FirstChar) == 0) {
490 // If not, then we can just insert a leaf and move too the next step.
491 insertLeaf(*Active.Node, EndIdx, FirstChar);
492
493 // The active node is an internal node, and we visited it, so it must
494 // need a link if it doesn't have one.
495 if (NeedsLink) {
496 NeedsLink->Link = Active.Node;
497 NeedsLink = nullptr;
498 }
499 } else {
500 // There's a match with FirstChar, so look for the point in the tree to
501 // insert a new node.
502 SuffixTreeNode *NextNode = Active.Node->Children[FirstChar];
503
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000504 unsigned SubstringLen = NextNode->size();
Jessica Paquette596f4832017-03-06 21:31:18 +0000505
506 // Is the current suffix we're trying to insert longer than the size of
507 // the child we want to move to?
508 if (Active.Len >= SubstringLen) {
509 // If yes, then consume the characters we've seen and move to the next
510 // node.
511 Active.Idx += SubstringLen;
512 Active.Len -= SubstringLen;
513 Active.Node = NextNode;
514 continue;
515 }
516
517 // Otherwise, the suffix we're trying to insert must be contained in the
518 // next node we want to move to.
519 unsigned LastChar = Str[EndIdx];
520
521 // Is the string we're trying to insert a substring of the next node?
522 if (Str[NextNode->StartIdx + Active.Len] == LastChar) {
523 // If yes, then we're done for this step. Remember our insertion point
524 // and move to the next end index. At this point, we have an implicit
525 // suffix tree.
526 if (NeedsLink && !Active.Node->isRoot()) {
527 NeedsLink->Link = Active.Node;
528 NeedsLink = nullptr;
529 }
530
531 Active.Len++;
532 break;
533 }
534
535 // The string we're trying to insert isn't a substring of the next node,
536 // but matches up to a point. Split the node.
537 //
538 // For example, say we ended our search at a node n and we're trying to
539 // insert ABD. Then we'll create a new node s for AB, reduce n to just
540 // representing C, and insert a new leaf node l to represent d. This
541 // allows us to ensure that if n was a leaf, it remains a leaf.
542 //
543 // | ABC ---split---> | AB
544 // n s
545 // C / \ D
546 // n l
547
548 // The node s from the diagram
549 SuffixTreeNode *SplitNode =
Jessica Paquette78681be2017-07-27 23:24:43 +0000550 insertInternalNode(Active.Node, NextNode->StartIdx,
551 NextNode->StartIdx + Active.Len - 1, FirstChar);
Jessica Paquette596f4832017-03-06 21:31:18 +0000552
553 // Insert the new node representing the new substring into the tree as
554 // a child of the split node. This is the node l from the diagram.
555 insertLeaf(*SplitNode, EndIdx, LastChar);
556
557 // Make the old node a child of the split node and update its start
558 // index. This is the node n from the diagram.
559 NextNode->StartIdx += Active.Len;
560 NextNode->Parent = SplitNode;
561 SplitNode->Children[Str[NextNode->StartIdx]] = NextNode;
562
563 // SplitNode is an internal node, update the suffix link.
564 if (NeedsLink)
565 NeedsLink->Link = SplitNode;
566
567 NeedsLink = SplitNode;
568 }
569
570 // We've added something new to the tree, so there's one less suffix to
571 // add.
572 SuffixesToAdd--;
573
574 if (Active.Node->isRoot()) {
575 if (Active.Len > 0) {
576 Active.Len--;
577 Active.Idx = EndIdx - SuffixesToAdd + 1;
578 }
579 } else {
580 // Start the next phase at the next smallest suffix.
581 Active.Node = Active.Node->Link;
582 }
583 }
584
585 return SuffixesToAdd;
586 }
587
Jessica Paquette596f4832017-03-06 21:31:18 +0000588public:
Jessica Paquette596f4832017-03-06 21:31:18 +0000589 /// Construct a suffix tree from a sequence of unsigned integers.
590 ///
591 /// \param Str The string to construct the suffix tree for.
592 SuffixTree(const std::vector<unsigned> &Str) : Str(Str) {
593 Root = insertInternalNode(nullptr, EmptyIdx, EmptyIdx, 0);
594 Root->IsInTree = true;
595 Active.Node = Root;
Jessica Paquette78681be2017-07-27 23:24:43 +0000596 LeafVector = std::vector<SuffixTreeNode *>(Str.size());
Jessica Paquette596f4832017-03-06 21:31:18 +0000597
598 // Keep track of the number of suffixes we have to add of the current
599 // prefix.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000600 unsigned SuffixesToAdd = 0;
Jessica Paquette596f4832017-03-06 21:31:18 +0000601 Active.Node = Root;
602
603 // Construct the suffix tree iteratively on each prefix of the string.
604 // PfxEndIdx is the end index of the current prefix.
605 // End is one past the last element in the string.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000606 for (unsigned PfxEndIdx = 0, End = Str.size(); PfxEndIdx < End;
607 PfxEndIdx++) {
Jessica Paquette596f4832017-03-06 21:31:18 +0000608 SuffixesToAdd++;
609 LeafEndIdx = PfxEndIdx; // Extend each of the leaves.
610 SuffixesToAdd = extend(PfxEndIdx, SuffixesToAdd);
611 }
612
613 // Set the suffix indices of each leaf.
614 assert(Root && "Root node can't be nullptr!");
615 setSuffixIndices(*Root, 0);
616 }
617};
618
Jessica Paquette596f4832017-03-06 21:31:18 +0000619/// \brief Maps \p MachineInstrs to unsigned integers and stores the mappings.
620struct InstructionMapper {
621
622 /// \brief The next available integer to assign to a \p MachineInstr that
623 /// cannot be outlined.
624 ///
625 /// Set to -3 for compatability with \p DenseMapInfo<unsigned>.
626 unsigned IllegalInstrNumber = -3;
627
628 /// \brief The next available integer to assign to a \p MachineInstr that can
629 /// be outlined.
630 unsigned LegalInstrNumber = 0;
631
632 /// Correspondence from \p MachineInstrs to unsigned integers.
633 DenseMap<MachineInstr *, unsigned, MachineInstrExpressionTrait>
634 InstructionIntegerMap;
635
636 /// Corresponcence from unsigned integers to \p MachineInstrs.
637 /// Inverse of \p InstructionIntegerMap.
638 DenseMap<unsigned, MachineInstr *> IntegerInstructionMap;
639
640 /// The vector of unsigned integers that the module is mapped to.
641 std::vector<unsigned> UnsignedVec;
642
643 /// \brief Stores the location of the instruction associated with the integer
644 /// at index i in \p UnsignedVec for each index i.
645 std::vector<MachineBasicBlock::iterator> InstrList;
646
647 /// \brief Maps \p *It to a legal integer.
648 ///
649 /// Updates \p InstrList, \p UnsignedVec, \p InstructionIntegerMap,
650 /// \p IntegerInstructionMap, and \p LegalInstrNumber.
651 ///
652 /// \returns The integer that \p *It was mapped to.
653 unsigned mapToLegalUnsigned(MachineBasicBlock::iterator &It) {
654
655 // Get the integer for this instruction or give it the current
656 // LegalInstrNumber.
657 InstrList.push_back(It);
658 MachineInstr &MI = *It;
659 bool WasInserted;
660 DenseMap<MachineInstr *, unsigned, MachineInstrExpressionTrait>::iterator
Jessica Paquette78681be2017-07-27 23:24:43 +0000661 ResultIt;
Jessica Paquette596f4832017-03-06 21:31:18 +0000662 std::tie(ResultIt, WasInserted) =
Jessica Paquette78681be2017-07-27 23:24:43 +0000663 InstructionIntegerMap.insert(std::make_pair(&MI, LegalInstrNumber));
Jessica Paquette596f4832017-03-06 21:31:18 +0000664 unsigned MINumber = ResultIt->second;
665
666 // There was an insertion.
667 if (WasInserted) {
668 LegalInstrNumber++;
669 IntegerInstructionMap.insert(std::make_pair(MINumber, &MI));
670 }
671
672 UnsignedVec.push_back(MINumber);
673
674 // Make sure we don't overflow or use any integers reserved by the DenseMap.
675 if (LegalInstrNumber >= IllegalInstrNumber)
676 report_fatal_error("Instruction mapping overflow!");
677
Jessica Paquette78681be2017-07-27 23:24:43 +0000678 assert(LegalInstrNumber != DenseMapInfo<unsigned>::getEmptyKey() &&
679 "Tried to assign DenseMap tombstone or empty key to instruction.");
680 assert(LegalInstrNumber != DenseMapInfo<unsigned>::getTombstoneKey() &&
681 "Tried to assign DenseMap tombstone or empty key to instruction.");
Jessica Paquette596f4832017-03-06 21:31:18 +0000682
683 return MINumber;
684 }
685
686 /// Maps \p *It to an illegal integer.
687 ///
688 /// Updates \p InstrList, \p UnsignedVec, and \p IllegalInstrNumber.
689 ///
690 /// \returns The integer that \p *It was mapped to.
691 unsigned mapToIllegalUnsigned(MachineBasicBlock::iterator &It) {
692 unsigned MINumber = IllegalInstrNumber;
693
694 InstrList.push_back(It);
695 UnsignedVec.push_back(IllegalInstrNumber);
696 IllegalInstrNumber--;
697
698 assert(LegalInstrNumber < IllegalInstrNumber &&
699 "Instruction mapping overflow!");
700
Jessica Paquette78681be2017-07-27 23:24:43 +0000701 assert(IllegalInstrNumber != DenseMapInfo<unsigned>::getEmptyKey() &&
702 "IllegalInstrNumber cannot be DenseMap tombstone or empty key!");
Jessica Paquette596f4832017-03-06 21:31:18 +0000703
Jessica Paquette78681be2017-07-27 23:24:43 +0000704 assert(IllegalInstrNumber != DenseMapInfo<unsigned>::getTombstoneKey() &&
705 "IllegalInstrNumber cannot be DenseMap tombstone or empty key!");
Jessica Paquette596f4832017-03-06 21:31:18 +0000706
707 return MINumber;
708 }
709
710 /// \brief Transforms a \p MachineBasicBlock into a \p vector of \p unsigneds
711 /// and appends it to \p UnsignedVec and \p InstrList.
712 ///
713 /// Two instructions are assigned the same integer if they are identical.
714 /// If an instruction is deemed unsafe to outline, then it will be assigned an
715 /// unique integer. The resulting mapping is placed into a suffix tree and
716 /// queried for candidates.
717 ///
718 /// \param MBB The \p MachineBasicBlock to be translated into integers.
719 /// \param TRI \p TargetRegisterInfo for the module.
720 /// \param TII \p TargetInstrInfo for the module.
721 void convertToUnsignedVec(MachineBasicBlock &MBB,
722 const TargetRegisterInfo &TRI,
723 const TargetInstrInfo &TII) {
724 for (MachineBasicBlock::iterator It = MBB.begin(), Et = MBB.end(); It != Et;
725 It++) {
726
727 // Keep track of where this instruction is in the module.
Jessica Paquette78681be2017-07-27 23:24:43 +0000728 switch (TII.getOutliningType(*It)) {
729 case TargetInstrInfo::MachineOutlinerInstrType::Illegal:
730 mapToIllegalUnsigned(It);
731 break;
Jessica Paquette596f4832017-03-06 21:31:18 +0000732
Jessica Paquette78681be2017-07-27 23:24:43 +0000733 case TargetInstrInfo::MachineOutlinerInstrType::Legal:
734 mapToLegalUnsigned(It);
735 break;
Jessica Paquette596f4832017-03-06 21:31:18 +0000736
Jessica Paquette78681be2017-07-27 23:24:43 +0000737 case TargetInstrInfo::MachineOutlinerInstrType::Invisible:
738 break;
Jessica Paquette596f4832017-03-06 21:31:18 +0000739 }
740 }
741
742 // After we're done every insertion, uniquely terminate this part of the
743 // "string". This makes sure we won't match across basic block or function
744 // boundaries since the "end" is encoded uniquely and thus appears in no
745 // repeated substring.
746 InstrList.push_back(MBB.end());
747 UnsignedVec.push_back(IllegalInstrNumber);
748 IllegalInstrNumber--;
749 }
750
751 InstructionMapper() {
752 // Make sure that the implementation of DenseMapInfo<unsigned> hasn't
753 // changed.
754 assert(DenseMapInfo<unsigned>::getEmptyKey() == (unsigned)-1 &&
Jessica Paquette78681be2017-07-27 23:24:43 +0000755 "DenseMapInfo<unsigned>'s empty key isn't -1!");
Jessica Paquette596f4832017-03-06 21:31:18 +0000756 assert(DenseMapInfo<unsigned>::getTombstoneKey() == (unsigned)-2 &&
Jessica Paquette78681be2017-07-27 23:24:43 +0000757 "DenseMapInfo<unsigned>'s tombstone key isn't -2!");
Jessica Paquette596f4832017-03-06 21:31:18 +0000758 }
759};
760
761/// \brief An interprocedural pass which finds repeated sequences of
762/// instructions and replaces them with calls to functions.
763///
764/// Each instruction is mapped to an unsigned integer and placed in a string.
765/// The resulting mapping is then placed in a \p SuffixTree. The \p SuffixTree
766/// is then repeatedly queried for repeated sequences of instructions. Each
767/// non-overlapping repeated sequence is then placed in its own
768/// \p MachineFunction and each instance is then replaced with a call to that
769/// function.
770struct MachineOutliner : public ModulePass {
771
772 static char ID;
773
Jessica Paquette13593842017-10-07 00:16:34 +0000774 /// \brief Set to true if the outliner should consider functions with
775 /// linkonceodr linkage.
776 bool OutlineFromLinkOnceODRs = false;
777
Jessica Paquette596f4832017-03-06 21:31:18 +0000778 StringRef getPassName() const override { return "Machine Outliner"; }
779
780 void getAnalysisUsage(AnalysisUsage &AU) const override {
781 AU.addRequired<MachineModuleInfo>();
782 AU.addPreserved<MachineModuleInfo>();
783 AU.setPreservesAll();
784 ModulePass::getAnalysisUsage(AU);
785 }
786
Jessica Paquettec9ab4c22017-10-17 18:43:15 +0000787 MachineOutliner(bool OutlineFromLinkOnceODRs = false)
788 : ModulePass(ID), OutlineFromLinkOnceODRs(OutlineFromLinkOnceODRs) {
Jessica Paquette596f4832017-03-06 21:31:18 +0000789 initializeMachineOutlinerPass(*PassRegistry::getPassRegistry());
790 }
791
Jessica Paquette78681be2017-07-27 23:24:43 +0000792 /// Find all repeated substrings that satisfy the outlining cost model.
793 ///
794 /// If a substring appears at least twice, then it must be represented by
795 /// an internal node which appears in at least two suffixes. Each suffix is
796 /// represented by a leaf node. To do this, we visit each internal node in
797 /// the tree, using the leaf children of each internal node. If an internal
798 /// node represents a beneficial substring, then we use each of its leaf
799 /// children to find the locations of its substring.
800 ///
801 /// \param ST A suffix tree to query.
802 /// \param TII TargetInstrInfo for the target.
803 /// \param Mapper Contains outlining mapping information.
804 /// \param[out] CandidateList Filled with candidates representing each
805 /// beneficial substring.
806 /// \param[out] FunctionList Filled with a list of \p OutlinedFunctions each
807 /// type of candidate.
808 ///
809 /// \returns The length of the longest candidate found.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000810 unsigned findCandidates(SuffixTree &ST, const TargetInstrInfo &TII,
811 InstructionMapper &Mapper,
812 std::vector<Candidate> &CandidateList,
813 std::vector<OutlinedFunction> &FunctionList);
Jessica Paquette78681be2017-07-27 23:24:43 +0000814
Jessica Paquette596f4832017-03-06 21:31:18 +0000815 /// \brief Replace the sequences of instructions represented by the
816 /// \p Candidates in \p CandidateList with calls to \p MachineFunctions
817 /// described in \p FunctionList.
818 ///
819 /// \param M The module we are outlining from.
820 /// \param CandidateList A list of candidates to be outlined.
821 /// \param FunctionList A list of functions to be inserted into the module.
822 /// \param Mapper Contains the instruction mappings for the module.
823 bool outline(Module &M, const ArrayRef<Candidate> &CandidateList,
824 std::vector<OutlinedFunction> &FunctionList,
825 InstructionMapper &Mapper);
826
827 /// Creates a function for \p OF and inserts it into the module.
828 MachineFunction *createOutlinedFunction(Module &M, const OutlinedFunction &OF,
829 InstructionMapper &Mapper);
830
831 /// Find potential outlining candidates and store them in \p CandidateList.
832 ///
833 /// For each type of potential candidate, also build an \p OutlinedFunction
834 /// struct containing the information to build the function for that
835 /// candidate.
836 ///
837 /// \param[out] CandidateList Filled with outlining candidates for the module.
838 /// \param[out] FunctionList Filled with functions corresponding to each type
839 /// of \p Candidate.
840 /// \param ST The suffix tree for the module.
841 /// \param TII TargetInstrInfo for the module.
842 ///
843 /// \returns The length of the longest candidate found. 0 if there are none.
844 unsigned buildCandidateList(std::vector<Candidate> &CandidateList,
845 std::vector<OutlinedFunction> &FunctionList,
Jessica Paquette78681be2017-07-27 23:24:43 +0000846 SuffixTree &ST, InstructionMapper &Mapper,
Jessica Paquettec984e212017-03-13 18:39:33 +0000847 const TargetInstrInfo &TII);
Jessica Paquette596f4832017-03-06 21:31:18 +0000848
Jessica Paquette60d31fc2017-10-17 21:11:58 +0000849 /// Helper function for pruneOverlaps.
850 /// Removes \p C from the candidate list, and updates its \p OutlinedFunction.
851 void prune(Candidate &C, std::vector<OutlinedFunction> &FunctionList);
852
Jessica Paquette596f4832017-03-06 21:31:18 +0000853 /// \brief Remove any overlapping candidates that weren't handled by the
854 /// suffix tree's pruning method.
855 ///
856 /// Pruning from the suffix tree doesn't necessarily remove all overlaps.
857 /// If a short candidate is chosen for outlining, then a longer candidate
858 /// which has that short candidate as a suffix is chosen, the tree's pruning
859 /// method will not find it. Thus, we need to prune before outlining as well.
860 ///
861 /// \param[in,out] CandidateList A list of outlining candidates.
862 /// \param[in,out] FunctionList A list of functions to be outlined.
Jessica Paquette809d7082017-07-28 03:21:58 +0000863 /// \param Mapper Contains instruction mapping info for outlining.
Jessica Paquette596f4832017-03-06 21:31:18 +0000864 /// \param MaxCandidateLen The length of the longest candidate.
865 /// \param TII TargetInstrInfo for the module.
866 void pruneOverlaps(std::vector<Candidate> &CandidateList,
867 std::vector<OutlinedFunction> &FunctionList,
Jessica Paquette809d7082017-07-28 03:21:58 +0000868 InstructionMapper &Mapper, unsigned MaxCandidateLen,
869 const TargetInstrInfo &TII);
Jessica Paquette596f4832017-03-06 21:31:18 +0000870
871 /// Construct a suffix tree on the instructions in \p M and outline repeated
872 /// strings from that tree.
873 bool runOnModule(Module &M) override;
874};
875
876} // Anonymous namespace.
877
878char MachineOutliner::ID = 0;
879
880namespace llvm {
Jessica Paquette13593842017-10-07 00:16:34 +0000881ModulePass *createMachineOutlinerPass(bool OutlineFromLinkOnceODRs) {
882 return new MachineOutliner(OutlineFromLinkOnceODRs);
883}
884
Jessica Paquette78681be2017-07-27 23:24:43 +0000885} // namespace llvm
Jessica Paquette596f4832017-03-06 21:31:18 +0000886
Jessica Paquette78681be2017-07-27 23:24:43 +0000887INITIALIZE_PASS(MachineOutliner, DEBUG_TYPE, "Machine Function Outliner", false,
888 false)
889
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000890unsigned
Jessica Paquette78681be2017-07-27 23:24:43 +0000891MachineOutliner::findCandidates(SuffixTree &ST, const TargetInstrInfo &TII,
892 InstructionMapper &Mapper,
893 std::vector<Candidate> &CandidateList,
894 std::vector<OutlinedFunction> &FunctionList) {
Jessica Paquette78681be2017-07-27 23:24:43 +0000895 CandidateList.clear();
896 FunctionList.clear();
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000897 unsigned MaxLen = 0;
Jessica Paquette78681be2017-07-27 23:24:43 +0000898
899 // FIXME: Visit internal nodes instead of leaves.
900 for (SuffixTreeNode *Leaf : ST.LeafVector) {
901 assert(Leaf && "Leaves in LeafVector cannot be null!");
902 if (!Leaf->IsInTree)
903 continue;
904
905 assert(Leaf->Parent && "All leaves must have parents!");
906 SuffixTreeNode &Parent = *(Leaf->Parent);
907
908 // If it doesn't appear enough, or we already outlined from it, skip it.
909 if (Parent.OccurrenceCount < 2 || Parent.isRoot() || !Parent.IsInTree)
910 continue;
911
Jessica Paquette809d7082017-07-28 03:21:58 +0000912 // Figure out if this candidate is beneficial.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000913 unsigned StringLen = Leaf->ConcatLen - (unsigned)Leaf->size();
Jessica Paquette95c11072017-08-14 22:57:41 +0000914
915 // Too short to be beneficial; skip it.
916 // FIXME: This isn't necessarily true for, say, X86. If we factor in
917 // instruction lengths we need more information than this.
918 if (StringLen < 2)
919 continue;
920
Jessica Paquetted87f5442017-07-29 02:55:46 +0000921 // If this is a beneficial class of candidate, then every one is stored in
922 // this vector.
923 std::vector<Candidate> CandidatesForRepeatedSeq;
924
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000925 // Describes the start and end point of each candidate. This allows the
926 // target to infer some information about each occurrence of each repeated
927 // sequence.
Jessica Paquetted87f5442017-07-29 02:55:46 +0000928 // FIXME: CandidatesForRepeatedSeq and this should be combined.
929 std::vector<
930 std::pair<MachineBasicBlock::iterator, MachineBasicBlock::iterator>>
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000931 RepeatedSequenceLocs;
Jessica Paquetted87f5442017-07-29 02:55:46 +0000932
Jessica Paquette809d7082017-07-28 03:21:58 +0000933 // Figure out the call overhead for each instance of the sequence.
934 for (auto &ChildPair : Parent.Children) {
935 SuffixTreeNode *M = ChildPair.second;
Jessica Paquette78681be2017-07-27 23:24:43 +0000936
Jessica Paquette809d7082017-07-28 03:21:58 +0000937 if (M && M->IsInTree && M->isLeaf()) {
938 // Each sequence is over [StartIt, EndIt].
939 MachineBasicBlock::iterator StartIt = Mapper.InstrList[M->SuffixIdx];
940 MachineBasicBlock::iterator EndIt =
941 Mapper.InstrList[M->SuffixIdx + StringLen - 1];
Jessica Paquetted87f5442017-07-29 02:55:46 +0000942
Jessica Paquetteacc15e12017-10-03 20:32:55 +0000943 CandidatesForRepeatedSeq.emplace_back(M->SuffixIdx, StringLen,
944 FunctionList.size());
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000945 RepeatedSequenceLocs.emplace_back(std::make_pair(StartIt, EndIt));
Jessica Paquetted87f5442017-07-29 02:55:46 +0000946
947 // Never visit this leaf again.
948 M->IsInTree = false;
Jessica Paquette809d7082017-07-28 03:21:58 +0000949 }
950 }
951
Jessica Paquetteacc15e12017-10-03 20:32:55 +0000952 // We've found something we might want to outline.
953 // Create an OutlinedFunction to store it and check if it'd be beneficial
954 // to outline.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000955 TargetInstrInfo::MachineOutlinerInfo MInfo =
956 TII.getOutlininingCandidateInfo(RepeatedSequenceLocs);
Jessica Paquetteacc15e12017-10-03 20:32:55 +0000957 std::vector<unsigned> Seq;
958 for (unsigned i = Leaf->SuffixIdx; i < Leaf->SuffixIdx + StringLen; i++)
959 Seq.push_back(ST.Str[i]);
960 OutlinedFunction OF(FunctionList.size(), Parent.OccurrenceCount, Seq,
961 MInfo);
962 unsigned Benefit = OF.getBenefit();
Jessica Paquette809d7082017-07-28 03:21:58 +0000963
Jessica Paquetteffe4abc2017-08-31 21:02:45 +0000964 // Is it better to outline this candidate than not?
Jessica Paquetteacc15e12017-10-03 20:32:55 +0000965 if (Benefit < 1) {
Jessica Paquetteffe4abc2017-08-31 21:02:45 +0000966 // Outlining this candidate would take more instructions than not
967 // outlining.
968 // Emit a remark explaining why we didn't outline this candidate.
969 std::pair<MachineBasicBlock::iterator, MachineBasicBlock::iterator> C =
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000970 RepeatedSequenceLocs[0];
Vivek Pandya95906582017-10-11 17:12:59 +0000971 MachineOptimizationRemarkEmitter MORE(
972 *(C.first->getParent()->getParent()), nullptr);
973 MORE.emit([&]() {
974 MachineOptimizationRemarkMissed R(DEBUG_TYPE, "NotOutliningCheaper",
975 C.first->getDebugLoc(),
976 C.first->getParent());
977 R << "Did not outline " << NV("Length", StringLen) << " instructions"
978 << " from " << NV("NumOccurrences", RepeatedSequenceLocs.size())
979 << " locations."
980 << " Instructions from outlining all occurrences ("
981 << NV("OutliningCost", OF.getOutliningCost()) << ")"
982 << " >= Unoutlined instruction count ("
Jessica Paquette85af63d2017-10-17 19:03:23 +0000983 << NV("NotOutliningCost", StringLen * OF.getOccurrenceCount()) << ")"
Vivek Pandya95906582017-10-11 17:12:59 +0000984 << " (Also found at: ";
Jessica Paquetteffe4abc2017-08-31 21:02:45 +0000985
Vivek Pandya95906582017-10-11 17:12:59 +0000986 // Tell the user the other places the candidate was found.
987 for (unsigned i = 1, e = RepeatedSequenceLocs.size(); i < e; i++) {
988 R << NV((Twine("OtherStartLoc") + Twine(i)).str(),
989 RepeatedSequenceLocs[i].first->getDebugLoc());
990 if (i != e - 1)
991 R << ", ";
992 }
Jessica Paquetteffe4abc2017-08-31 21:02:45 +0000993
Vivek Pandya95906582017-10-11 17:12:59 +0000994 R << ")";
995 return R;
996 });
Jessica Paquetteffe4abc2017-08-31 21:02:45 +0000997
998 // Move to the next candidate.
Jessica Paquette78681be2017-07-27 23:24:43 +0000999 continue;
Jessica Paquetteffe4abc2017-08-31 21:02:45 +00001000 }
Jessica Paquette78681be2017-07-27 23:24:43 +00001001
1002 if (StringLen > MaxLen)
1003 MaxLen = StringLen;
1004
Jessica Paquetted87f5442017-07-29 02:55:46 +00001005 // At this point, the candidate class is seen as beneficial. Set their
1006 // benefit values and save them in the candidate list.
1007 for (Candidate &C : CandidatesForRepeatedSeq) {
1008 C.Benefit = Benefit;
Jessica Paquette4cf187b2017-09-27 20:47:39 +00001009 C.MInfo = MInfo;
Jessica Paquetted87f5442017-07-29 02:55:46 +00001010 CandidateList.push_back(C);
Jessica Paquette78681be2017-07-27 23:24:43 +00001011 }
1012
Jessica Paquetteacc15e12017-10-03 20:32:55 +00001013 FunctionList.push_back(OF);
Jessica Paquette78681be2017-07-27 23:24:43 +00001014
1015 // Move to the next function.
Jessica Paquette78681be2017-07-27 23:24:43 +00001016 Parent.IsInTree = false;
1017 }
1018
1019 return MaxLen;
1020}
Jessica Paquette596f4832017-03-06 21:31:18 +00001021
Jessica Paquette60d31fc2017-10-17 21:11:58 +00001022// Remove C from the candidate space, and update its OutlinedFunction.
1023void MachineOutliner::prune(Candidate &C,
1024 std::vector<OutlinedFunction> &FunctionList) {
1025 // Get the OutlinedFunction associated with this Candidate.
1026 OutlinedFunction &F = FunctionList[C.FunctionIdx];
1027
1028 // Update C's associated function's occurrence count.
1029 F.decrement();
1030
1031 // Remove C from the CandidateList.
1032 C.InCandidateList = false;
1033
1034 DEBUG(dbgs() << "- Removed a Candidate \n";
1035 dbgs() << "--- Num fns left for candidate: " << F.getOccurrenceCount()
1036 << "\n";
1037 dbgs() << "--- Candidate's functions's benefit: " << F.getBenefit()
1038 << "\n";);
1039}
1040
Jessica Paquette596f4832017-03-06 21:31:18 +00001041void MachineOutliner::pruneOverlaps(std::vector<Candidate> &CandidateList,
1042 std::vector<OutlinedFunction> &FunctionList,
Jessica Paquette809d7082017-07-28 03:21:58 +00001043 InstructionMapper &Mapper,
Jessica Paquette596f4832017-03-06 21:31:18 +00001044 unsigned MaxCandidateLen,
1045 const TargetInstrInfo &TII) {
Jessica Paquette91999162017-09-28 23:39:36 +00001046
1047 // Return true if this candidate became unbeneficial for outlining in a
1048 // previous step.
Jessica Paquette60d31fc2017-10-17 21:11:58 +00001049 auto ShouldSkipCandidate = [&FunctionList, this](Candidate &C) {
Jessica Paquette91999162017-09-28 23:39:36 +00001050
1051 // Check if the candidate was removed in a previous step.
1052 if (!C.InCandidateList)
1053 return true;
1054
Jessica Paquette85af63d2017-10-17 19:03:23 +00001055 // C must be alive. Check if we should remove it.
Jessica Paquette60d31fc2017-10-17 21:11:58 +00001056 if (FunctionList[C.FunctionIdx].getBenefit() < 1) {
1057 prune(C, FunctionList);
Jessica Paquette91999162017-09-28 23:39:36 +00001058 return true;
1059 }
1060
1061 // C is in the list, and F is still beneficial.
1062 return false;
1063 };
1064
Jessica Paquetteacffa282017-03-23 21:27:38 +00001065 // TODO: Experiment with interval trees or other interval-checking structures
1066 // to lower the time complexity of this function.
1067 // TODO: Can we do better than the simple greedy choice?
1068 // Check for overlaps in the range.
1069 // This is O(MaxCandidateLen * CandidateList.size()).
Jessica Paquette596f4832017-03-06 21:31:18 +00001070 for (auto It = CandidateList.begin(), Et = CandidateList.end(); It != Et;
1071 It++) {
1072 Candidate &C1 = *It;
Jessica Paquette596f4832017-03-06 21:31:18 +00001073
Jessica Paquette91999162017-09-28 23:39:36 +00001074 // If C1 was already pruned, or its function is no longer beneficial for
1075 // outlining, move to the next candidate.
1076 if (ShouldSkipCandidate(C1))
Jessica Paquette596f4832017-03-06 21:31:18 +00001077 continue;
1078
Jessica Paquette596f4832017-03-06 21:31:18 +00001079 // The minimum start index of any candidate that could overlap with this
1080 // one.
1081 unsigned FarthestPossibleIdx = 0;
1082
1083 // Either the index is 0, or it's at most MaxCandidateLen indices away.
Jessica Paquettec9ab4c22017-10-17 18:43:15 +00001084 if (C1.startIdx() > MaxCandidateLen)
1085 FarthestPossibleIdx = C1.startIdx() - MaxCandidateLen;
Jessica Paquette596f4832017-03-06 21:31:18 +00001086
Jessica Paquetteacffa282017-03-23 21:27:38 +00001087 // Compare against the candidates in the list that start at at most
1088 // FarthestPossibleIdx indices away from C1. There are at most
1089 // MaxCandidateLen of these.
Jessica Paquette596f4832017-03-06 21:31:18 +00001090 for (auto Sit = It + 1; Sit != Et; Sit++) {
1091 Candidate &C2 = *Sit;
Jessica Paquette596f4832017-03-06 21:31:18 +00001092
1093 // Is this candidate too far away to overlap?
Jessica Paquettec9ab4c22017-10-17 18:43:15 +00001094 if (C2.startIdx() < FarthestPossibleIdx)
Jessica Paquette596f4832017-03-06 21:31:18 +00001095 break;
1096
Jessica Paquette91999162017-09-28 23:39:36 +00001097 // If C2 was already pruned, or its function is no longer beneficial for
1098 // outlining, move to the next candidate.
1099 if (ShouldSkipCandidate(C2))
Jessica Paquette596f4832017-03-06 21:31:18 +00001100 continue;
1101
Jessica Paquette596f4832017-03-06 21:31:18 +00001102 // Do C1 and C2 overlap?
1103 //
1104 // Not overlapping:
1105 // High indices... [C1End ... C1Start][C2End ... C2Start] ...Low indices
1106 //
1107 // We sorted our candidate list so C2Start <= C1Start. We know that
1108 // C2End > C2Start since each candidate has length >= 2. Therefore, all we
1109 // have to check is C2End < C2Start to see if we overlap.
Jessica Paquettec9ab4c22017-10-17 18:43:15 +00001110 if (C2.endIdx() < C1.startIdx())
Jessica Paquette596f4832017-03-06 21:31:18 +00001111 continue;
1112
Jessica Paquetteacffa282017-03-23 21:27:38 +00001113 // C1 and C2 overlap.
1114 // We need to choose the better of the two.
1115 //
1116 // Approximate this by picking the one which would have saved us the
1117 // most instructions before any pruning.
Jessica Paquette60d31fc2017-10-17 21:11:58 +00001118
1119 // Is C2 a better candidate?
1120 if (C2.Benefit > C1.Benefit) {
1121 // Yes, so prune C1. Since C1 is dead, we don't have to compare it
1122 // against anything anymore, so break.
1123 prune(C1, FunctionList);
Jessica Paquetteacffa282017-03-23 21:27:38 +00001124 break;
1125 }
Jessica Paquette60d31fc2017-10-17 21:11:58 +00001126
1127 // Prune C2 and move on to the next candidate.
1128 prune(C2, FunctionList);
Jessica Paquette596f4832017-03-06 21:31:18 +00001129 }
1130 }
1131}
1132
1133unsigned
1134MachineOutliner::buildCandidateList(std::vector<Candidate> &CandidateList,
1135 std::vector<OutlinedFunction> &FunctionList,
Jessica Paquette78681be2017-07-27 23:24:43 +00001136 SuffixTree &ST, InstructionMapper &Mapper,
Jessica Paquette596f4832017-03-06 21:31:18 +00001137 const TargetInstrInfo &TII) {
1138
1139 std::vector<unsigned> CandidateSequence; // Current outlining candidate.
Jessica Paquette4cf187b2017-09-27 20:47:39 +00001140 unsigned MaxCandidateLen = 0; // Length of the longest candidate.
Jessica Paquette596f4832017-03-06 21:31:18 +00001141
Jessica Paquette78681be2017-07-27 23:24:43 +00001142 MaxCandidateLen =
1143 findCandidates(ST, TII, Mapper, CandidateList, FunctionList);
Jessica Paquette596f4832017-03-06 21:31:18 +00001144
Jessica Paquette596f4832017-03-06 21:31:18 +00001145 // Sort the candidates in decending order. This will simplify the outlining
1146 // process when we have to remove the candidates from the mapping by
1147 // allowing us to cut them out without keeping track of an offset.
1148 std::stable_sort(CandidateList.begin(), CandidateList.end());
1149
1150 return MaxCandidateLen;
1151}
1152
1153MachineFunction *
1154MachineOutliner::createOutlinedFunction(Module &M, const OutlinedFunction &OF,
Jessica Paquette78681be2017-07-27 23:24:43 +00001155 InstructionMapper &Mapper) {
Jessica Paquette596f4832017-03-06 21:31:18 +00001156
1157 // Create the function name. This should be unique. For now, just hash the
1158 // module name and include it in the function name plus the number of this
1159 // function.
1160 std::ostringstream NameStream;
Jessica Paquette78681be2017-07-27 23:24:43 +00001161 NameStream << "OUTLINED_FUNCTION_" << OF.Name;
Jessica Paquette596f4832017-03-06 21:31:18 +00001162
1163 // Create the function using an IR-level function.
1164 LLVMContext &C = M.getContext();
1165 Function *F = dyn_cast<Function>(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00001166 M.getOrInsertFunction(NameStream.str(), Type::getVoidTy(C)));
Jessica Paquette596f4832017-03-06 21:31:18 +00001167 assert(F && "Function was null!");
1168
1169 // NOTE: If this is linkonceodr, then we can take advantage of linker deduping
1170 // which gives us better results when we outline from linkonceodr functions.
1171 F->setLinkage(GlobalValue::PrivateLinkage);
1172 F->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
1173
1174 BasicBlock *EntryBB = BasicBlock::Create(C, "entry", F);
1175 IRBuilder<> Builder(EntryBB);
1176 Builder.CreateRetVoid();
1177
1178 MachineModuleInfo &MMI = getAnalysis<MachineModuleInfo>();
Matthias Braun7bda1952017-06-06 00:44:35 +00001179 MachineFunction &MF = MMI.getOrCreateMachineFunction(*F);
Jessica Paquette596f4832017-03-06 21:31:18 +00001180 MachineBasicBlock &MBB = *MF.CreateMachineBasicBlock();
1181 const TargetSubtargetInfo &STI = MF.getSubtarget();
1182 const TargetInstrInfo &TII = *STI.getInstrInfo();
1183
1184 // Insert the new function into the module.
1185 MF.insert(MF.begin(), &MBB);
1186
Jessica Paquette4cf187b2017-09-27 20:47:39 +00001187 TII.insertOutlinerPrologue(MBB, MF, OF.MInfo);
Jessica Paquette596f4832017-03-06 21:31:18 +00001188
1189 // Copy over the instructions for the function using the integer mappings in
1190 // its sequence.
1191 for (unsigned Str : OF.Sequence) {
1192 MachineInstr *NewMI =
1193 MF.CloneMachineInstr(Mapper.IntegerInstructionMap.find(Str)->second);
1194 NewMI->dropMemRefs();
1195
1196 // Don't keep debug information for outlined instructions.
1197 // FIXME: This means outlined functions are currently undebuggable.
1198 NewMI->setDebugLoc(DebugLoc());
1199 MBB.insert(MBB.end(), NewMI);
1200 }
1201
Jessica Paquette4cf187b2017-09-27 20:47:39 +00001202 TII.insertOutlinerEpilogue(MBB, MF, OF.MInfo);
Jessica Paquette596f4832017-03-06 21:31:18 +00001203
1204 return &MF;
1205}
1206
1207bool MachineOutliner::outline(Module &M,
1208 const ArrayRef<Candidate> &CandidateList,
1209 std::vector<OutlinedFunction> &FunctionList,
1210 InstructionMapper &Mapper) {
1211
1212 bool OutlinedSomething = false;
Jessica Paquette596f4832017-03-06 21:31:18 +00001213 // Replace the candidates with calls to their respective outlined functions.
1214 for (const Candidate &C : CandidateList) {
1215
1216 // Was the candidate removed during pruneOverlaps?
1217 if (!C.InCandidateList)
1218 continue;
1219
1220 // If not, then look at its OutlinedFunction.
1221 OutlinedFunction &OF = FunctionList[C.FunctionIdx];
1222
1223 // Was its OutlinedFunction made unbeneficial during pruneOverlaps?
Jessica Paquette85af63d2017-10-17 19:03:23 +00001224 if (OF.getBenefit() < 1)
Jessica Paquette596f4832017-03-06 21:31:18 +00001225 continue;
1226
1227 // If not, then outline it.
Jessica Paquettec9ab4c22017-10-17 18:43:15 +00001228 assert(C.startIdx() < Mapper.InstrList.size() &&
1229 "Candidate out of bounds!");
1230 MachineBasicBlock *MBB = (*Mapper.InstrList[C.startIdx()]).getParent();
1231 MachineBasicBlock::iterator StartIt = Mapper.InstrList[C.startIdx()];
1232 unsigned EndIdx = C.endIdx();
Jessica Paquette596f4832017-03-06 21:31:18 +00001233
1234 assert(EndIdx < Mapper.InstrList.size() && "Candidate out of bounds!");
1235 MachineBasicBlock::iterator EndIt = Mapper.InstrList[EndIdx];
1236 assert(EndIt != MBB->end() && "EndIt out of bounds!");
1237
1238 EndIt++; // Erase needs one past the end index.
1239
1240 // Does this candidate have a function yet?
Jessica Paquetteacffa282017-03-23 21:27:38 +00001241 if (!OF.MF) {
Jessica Paquette596f4832017-03-06 21:31:18 +00001242 OF.MF = createOutlinedFunction(M, OF, Mapper);
Jessica Paquetteacffa282017-03-23 21:27:38 +00001243 FunctionsCreated++;
1244 }
Jessica Paquette596f4832017-03-06 21:31:18 +00001245
1246 MachineFunction *MF = OF.MF;
1247 const TargetSubtargetInfo &STI = MF->getSubtarget();
1248 const TargetInstrInfo &TII = *STI.getInstrInfo();
1249
1250 // Insert a call to the new function and erase the old sequence.
Jessica Paquette4cf187b2017-09-27 20:47:39 +00001251 TII.insertOutlinedCall(M, *MBB, StartIt, *MF, C.MInfo);
Jessica Paquettec9ab4c22017-10-17 18:43:15 +00001252 StartIt = Mapper.InstrList[C.startIdx()];
Jessica Paquette596f4832017-03-06 21:31:18 +00001253 MBB->erase(StartIt, EndIt);
1254
1255 OutlinedSomething = true;
1256
1257 // Statistics.
1258 NumOutlined++;
1259 }
1260
Jessica Paquette78681be2017-07-27 23:24:43 +00001261 DEBUG(dbgs() << "OutlinedSomething = " << OutlinedSomething << "\n";);
Jessica Paquette596f4832017-03-06 21:31:18 +00001262
1263 return OutlinedSomething;
1264}
1265
1266bool MachineOutliner::runOnModule(Module &M) {
1267
1268 // Is there anything in the module at all?
1269 if (M.empty())
1270 return false;
1271
1272 MachineModuleInfo &MMI = getAnalysis<MachineModuleInfo>();
Jessica Paquette78681be2017-07-27 23:24:43 +00001273 const TargetSubtargetInfo &STI =
1274 MMI.getOrCreateMachineFunction(*M.begin()).getSubtarget();
Jessica Paquette596f4832017-03-06 21:31:18 +00001275 const TargetRegisterInfo *TRI = STI.getRegisterInfo();
1276 const TargetInstrInfo *TII = STI.getInstrInfo();
1277
1278 InstructionMapper Mapper;
1279
1280 // Build instruction mappings for each function in the module.
1281 for (Function &F : M) {
Matthias Braun7bda1952017-06-06 00:44:35 +00001282 MachineFunction &MF = MMI.getOrCreateMachineFunction(F);
Jessica Paquette596f4832017-03-06 21:31:18 +00001283
1284 // Is the function empty? Safe to outline from?
Jessica Paquette13593842017-10-07 00:16:34 +00001285 if (F.empty() ||
1286 !TII->isFunctionSafeToOutlineFrom(MF, OutlineFromLinkOnceODRs))
Jessica Paquette596f4832017-03-06 21:31:18 +00001287 continue;
1288
1289 // If it is, look at each MachineBasicBlock in the function.
1290 for (MachineBasicBlock &MBB : MF) {
1291
1292 // Is there anything in MBB?
1293 if (MBB.empty())
1294 continue;
1295
1296 // If yes, map it.
1297 Mapper.convertToUnsignedVec(MBB, *TRI, *TII);
1298 }
1299 }
1300
1301 // Construct a suffix tree, use it to find candidates, and then outline them.
1302 SuffixTree ST(Mapper.UnsignedVec);
1303 std::vector<Candidate> CandidateList;
1304 std::vector<OutlinedFunction> FunctionList;
1305
Jessica Paquetteacffa282017-03-23 21:27:38 +00001306 // Find all of the outlining candidates.
Jessica Paquette596f4832017-03-06 21:31:18 +00001307 unsigned MaxCandidateLen =
Jessica Paquettec984e212017-03-13 18:39:33 +00001308 buildCandidateList(CandidateList, FunctionList, ST, Mapper, *TII);
Jessica Paquette596f4832017-03-06 21:31:18 +00001309
Jessica Paquetteacffa282017-03-23 21:27:38 +00001310 // Remove candidates that overlap with other candidates.
Jessica Paquette809d7082017-07-28 03:21:58 +00001311 pruneOverlaps(CandidateList, FunctionList, Mapper, MaxCandidateLen, *TII);
Jessica Paquetteacffa282017-03-23 21:27:38 +00001312
1313 // Outline each of the candidates and return true if something was outlined.
Jessica Paquette596f4832017-03-06 21:31:18 +00001314 return outline(M, CandidateList, FunctionList, Mapper);
1315}