blob: 143310ea16f88e012255a0258241798fcccd61e0 [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
Jessica Paquette32de26d2018-06-19 21:14:48 +000028/// * buildOutlinedFrame
Jessica Paquette4cf187b2017-09-27 20:47:39 +000029/// * insertOutlinedCall
Jessica Paquette4cf187b2017-09-27 20:47:39 +000030/// * isFunctionSafeToOutlineFrom
31///
32/// in order to make use of the MachineOutliner.
33///
Jessica Paquette596f4832017-03-06 21:31:18 +000034/// This was originally presented at the 2016 LLVM Developers' Meeting in the
35/// talk "Reducing Code Size Using Outlining". For a high-level overview of
36/// how this pass works, the talk is available on YouTube at
37///
38/// https://www.youtube.com/watch?v=yorld-WSOeU
39///
40/// The slides for the talk are available at
41///
42/// http://www.llvm.org/devmtg/2016-11/Slides/Paquette-Outliner.pdf
43///
44/// The talk provides an overview of how the outliner finds candidates and
45/// ultimately outlines them. It describes how the main data structure for this
46/// pass, the suffix tree, is queried and purged for candidates. It also gives
47/// a simplified suffix tree construction algorithm for suffix trees based off
48/// of the algorithm actually used here, Ukkonen's algorithm.
49///
50/// For the original RFC for this pass, please see
51///
52/// http://lists.llvm.org/pipermail/llvm-dev/2016-August/104170.html
53///
54/// For more information on the suffix tree data structure, please see
55/// https://www.cs.helsinki.fi/u/ukkonen/SuffixT1withFigs.pdf
56///
57//===----------------------------------------------------------------------===//
Jessica Paquetteaa087322018-06-04 21:14:16 +000058#include "llvm/CodeGen/MachineOutliner.h"
Jessica Paquette596f4832017-03-06 21:31:18 +000059#include "llvm/ADT/DenseMap.h"
60#include "llvm/ADT/Statistic.h"
61#include "llvm/ADT/Twine.h"
Jessica Paquette596f4832017-03-06 21:31:18 +000062#include "llvm/CodeGen/MachineFunction.h"
Jessica Paquette596f4832017-03-06 21:31:18 +000063#include "llvm/CodeGen/MachineModuleInfo.h"
Jessica Paquetteffe4abc2017-08-31 21:02:45 +000064#include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h"
Geoff Berry82203c42018-01-31 20:15:16 +000065#include "llvm/CodeGen/MachineRegisterInfo.h"
Jessica Paquette596f4832017-03-06 21:31:18 +000066#include "llvm/CodeGen/Passes.h"
David Blaikie3f833ed2017-11-08 01:01:31 +000067#include "llvm/CodeGen/TargetInstrInfo.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000068#include "llvm/CodeGen/TargetSubtargetInfo.h"
Jessica Paquette729e6862018-01-18 00:00:58 +000069#include "llvm/IR/DIBuilder.h"
Jessica Paquette596f4832017-03-06 21:31:18 +000070#include "llvm/IR/IRBuilder.h"
Jessica Paquettea499c3c2018-01-19 21:21:49 +000071#include "llvm/IR/Mangler.h"
Jessica Paquette596f4832017-03-06 21:31:18 +000072#include "llvm/Support/Allocator.h"
Jessica Paquette1eca23b2018-04-19 22:17:07 +000073#include "llvm/Support/CommandLine.h"
Jessica Paquette596f4832017-03-06 21:31:18 +000074#include "llvm/Support/Debug.h"
75#include "llvm/Support/raw_ostream.h"
Jessica Paquette596f4832017-03-06 21:31:18 +000076#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 Paquetteaa087322018-06-04 21:14:16 +000086using namespace outliner;
Jessica Paquette596f4832017-03-06 21:31:18 +000087
88STATISTIC(NumOutlined, "Number of candidates outlined");
89STATISTIC(FunctionsCreated, "Number of functions created");
90
Jessica Paquette1eca23b2018-04-19 22:17:07 +000091// Set to true if the user wants the outliner to run on linkonceodr linkage
92// functions. This is false by default because the linker can dedupe linkonceodr
93// functions. Since the outliner is confined to a single module (modulo LTO),
94// this is off by default. It should, however, be the default behaviour in
95// LTO.
96static cl::opt<bool> EnableLinkOnceODROutlining(
97 "enable-linkonceodr-outlining",
98 cl::Hidden,
99 cl::desc("Enable the machine outliner on linkonceodr functions"),
100 cl::init(false));
101
Jessica Paquette596f4832017-03-06 21:31:18 +0000102namespace {
103
104/// Represents an undefined index in the suffix tree.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000105const unsigned EmptyIdx = -1;
Jessica Paquette596f4832017-03-06 21:31:18 +0000106
107/// A node in a suffix tree which represents a substring or suffix.
108///
109/// Each node has either no children or at least two children, with the root
110/// being a exception in the empty tree.
111///
112/// Children are represented as a map between unsigned integers and nodes. If
113/// a node N has a child M on unsigned integer k, then the mapping represented
114/// by N is a proper prefix of the mapping represented by M. Note that this,
115/// although similar to a trie is somewhat different: each node stores a full
116/// substring of the full mapping rather than a single character state.
117///
118/// Each internal node contains a pointer to the internal node representing
119/// the same string, but with the first character chopped off. This is stored
120/// in \p Link. Each leaf node stores the start index of its respective
121/// suffix in \p SuffixIdx.
122struct SuffixTreeNode {
123
124 /// The children of this node.
125 ///
126 /// A child existing on an unsigned integer implies that from the mapping
127 /// represented by the current node, there is a way to reach another
128 /// mapping by tacking that character on the end of the current string.
129 DenseMap<unsigned, SuffixTreeNode *> Children;
130
Jessica Paquette596f4832017-03-06 21:31:18 +0000131 /// The start index of this node's substring in the main string.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000132 unsigned StartIdx = EmptyIdx;
Jessica Paquette596f4832017-03-06 21:31:18 +0000133
134 /// The end index of this node's substring in the main string.
135 ///
136 /// Every leaf node must have its \p EndIdx incremented at the end of every
137 /// step in the construction algorithm. To avoid having to update O(N)
138 /// nodes individually at the end of every step, the end index is stored
139 /// as a pointer.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000140 unsigned *EndIdx = nullptr;
Jessica Paquette596f4832017-03-06 21:31:18 +0000141
142 /// For leaves, the start index of the suffix represented by this node.
143 ///
144 /// For all other nodes, this is ignored.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000145 unsigned SuffixIdx = EmptyIdx;
Jessica Paquette596f4832017-03-06 21:31:18 +0000146
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000147 /// For internal nodes, a pointer to the internal node representing
Jessica Paquette596f4832017-03-06 21:31:18 +0000148 /// the same sequence with the first character chopped off.
149 ///
Jessica Paquette4602c342017-07-28 05:59:30 +0000150 /// This acts as a shortcut in Ukkonen's algorithm. One of the things that
Jessica Paquette596f4832017-03-06 21:31:18 +0000151 /// Ukkonen's algorithm does to achieve linear-time construction is
152 /// keep track of which node the next insert should be at. This makes each
153 /// insert O(1), and there are a total of O(N) inserts. The suffix link
154 /// helps with inserting children of internal nodes.
155 ///
Jessica Paquette78681be2017-07-27 23:24:43 +0000156 /// Say we add a child to an internal node with associated mapping S. The
Jessica Paquette596f4832017-03-06 21:31:18 +0000157 /// next insertion must be at the node representing S - its first character.
158 /// This is given by the way that we iteratively build the tree in Ukkonen's
159 /// algorithm. The main idea is to look at the suffixes of each prefix in the
160 /// string, starting with the longest suffix of the prefix, and ending with
161 /// the shortest. Therefore, if we keep pointers between such nodes, we can
162 /// move to the next insertion point in O(1) time. If we don't, then we'd
163 /// have to query from the root, which takes O(N) time. This would make the
164 /// construction algorithm O(N^2) rather than O(N).
Jessica Paquette596f4832017-03-06 21:31:18 +0000165 SuffixTreeNode *Link = nullptr;
166
Jessica Paquetteacffa282017-03-23 21:27:38 +0000167 /// The length of the string formed by concatenating the edge labels from the
168 /// root to this node.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000169 unsigned ConcatLen = 0;
Jessica Paquetteacffa282017-03-23 21:27:38 +0000170
Jessica Paquette596f4832017-03-06 21:31:18 +0000171 /// Returns true if this node is a leaf.
172 bool isLeaf() const { return SuffixIdx != EmptyIdx; }
173
174 /// Returns true if this node is the root of its owning \p SuffixTree.
175 bool isRoot() const { return StartIdx == EmptyIdx; }
176
177 /// Return the number of elements in the substring associated with this node.
178 size_t size() const {
179
180 // Is it the root? If so, it's the empty string so return 0.
181 if (isRoot())
182 return 0;
183
184 assert(*EndIdx != EmptyIdx && "EndIdx is undefined!");
185
186 // Size = the number of elements in the string.
187 // For example, [0 1 2 3] has length 4, not 3. 3-0 = 3, so we have 3-0+1.
188 return *EndIdx - StartIdx + 1;
189 }
190
Jessica Paquettedf5b09b2018-11-07 19:56:13 +0000191 SuffixTreeNode(unsigned StartIdx, unsigned *EndIdx, SuffixTreeNode *Link)
192 : StartIdx(StartIdx), EndIdx(EndIdx), Link(Link) {}
Jessica Paquette596f4832017-03-06 21:31:18 +0000193
194 SuffixTreeNode() {}
195};
196
197/// A data structure for fast substring queries.
198///
199/// Suffix trees represent the suffixes of their input strings in their leaves.
200/// A suffix tree is a type of compressed trie structure where each node
201/// represents an entire substring rather than a single character. Each leaf
202/// of the tree is a suffix.
203///
204/// A suffix tree can be seen as a type of state machine where each state is a
205/// substring of the full string. The tree is structured so that, for a string
206/// of length N, there are exactly N leaves in the tree. This structure allows
207/// us to quickly find repeated substrings of the input string.
208///
209/// In this implementation, a "string" is a vector of unsigned integers.
210/// These integers may result from hashing some data type. A suffix tree can
211/// contain 1 or many strings, which can then be queried as one large string.
212///
213/// The suffix tree is implemented using Ukkonen's algorithm for linear-time
214/// suffix tree construction. Ukkonen's algorithm is explained in more detail
215/// in the paper by Esko Ukkonen "On-line construction of suffix trees. The
216/// paper is available at
217///
218/// https://www.cs.helsinki.fi/u/ukkonen/SuffixT1withFigs.pdf
219class SuffixTree {
Jessica Paquette78681be2017-07-27 23:24:43 +0000220public:
Jessica Paquette596f4832017-03-06 21:31:18 +0000221 /// Each element is an integer representing an instruction in the module.
222 ArrayRef<unsigned> Str;
223
Jessica Paquette4e54ef82018-11-06 21:46:41 +0000224 /// A repeated substring in the tree.
225 struct RepeatedSubstring {
226 /// The length of the string.
227 unsigned Length;
228
229 /// The start indices of each occurrence.
230 std::vector<unsigned> StartIndices;
231 };
232
Jessica Paquette78681be2017-07-27 23:24:43 +0000233private:
Jessica Paquette596f4832017-03-06 21:31:18 +0000234 /// Maintains each node in the tree.
Jessica Paquetted4cb9c62017-03-08 23:55:33 +0000235 SpecificBumpPtrAllocator<SuffixTreeNode> NodeAllocator;
Jessica Paquette596f4832017-03-06 21:31:18 +0000236
237 /// The root of the suffix tree.
238 ///
239 /// The root represents the empty string. It is maintained by the
240 /// \p NodeAllocator like every other node in the tree.
241 SuffixTreeNode *Root = nullptr;
242
Jessica Paquette596f4832017-03-06 21:31:18 +0000243 /// Maintains the end indices of the internal nodes in the tree.
244 ///
245 /// Each internal node is guaranteed to never have its end index change
246 /// during the construction algorithm; however, leaves must be updated at
247 /// every step. Therefore, we need to store leaf end indices by reference
248 /// to avoid updating O(N) leaves at every step of construction. Thus,
249 /// every internal node must be allocated its own end index.
250 BumpPtrAllocator InternalEndIdxAllocator;
251
252 /// The end index of each leaf in the tree.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000253 unsigned LeafEndIdx = -1;
Jessica Paquette596f4832017-03-06 21:31:18 +0000254
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000255 /// Helper struct which keeps track of the next insertion point in
Jessica Paquette596f4832017-03-06 21:31:18 +0000256 /// Ukkonen's algorithm.
257 struct ActiveState {
258 /// The next node to insert at.
259 SuffixTreeNode *Node;
260
261 /// The index of the first character in the substring currently being added.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000262 unsigned Idx = EmptyIdx;
Jessica Paquette596f4832017-03-06 21:31:18 +0000263
264 /// The length of the substring we have to add at the current step.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000265 unsigned Len = 0;
Jessica Paquette596f4832017-03-06 21:31:18 +0000266 };
267
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000268 /// The point the next insertion will take place at in the
Jessica Paquette596f4832017-03-06 21:31:18 +0000269 /// construction algorithm.
270 ActiveState Active;
271
272 /// Allocate a leaf node and add it to the tree.
273 ///
274 /// \param Parent The parent of this node.
275 /// \param StartIdx The start index of this node's associated string.
276 /// \param Edge The label on the edge leaving \p Parent to this node.
277 ///
278 /// \returns A pointer to the allocated leaf node.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000279 SuffixTreeNode *insertLeaf(SuffixTreeNode &Parent, unsigned StartIdx,
Jessica Paquette596f4832017-03-06 21:31:18 +0000280 unsigned Edge) {
281
282 assert(StartIdx <= LeafEndIdx && "String can't start after it ends!");
283
Jessica Paquette78681be2017-07-27 23:24:43 +0000284 SuffixTreeNode *N = new (NodeAllocator.Allocate())
Jessica Paquettedf5b09b2018-11-07 19:56:13 +0000285 SuffixTreeNode(StartIdx, &LeafEndIdx, nullptr);
Jessica Paquette596f4832017-03-06 21:31:18 +0000286 Parent.Children[Edge] = N;
287
288 return N;
289 }
290
291 /// Allocate an internal node and add it to the tree.
292 ///
293 /// \param Parent The parent of this node. Only null when allocating the root.
294 /// \param StartIdx The start index of this node's associated string.
295 /// \param EndIdx The end index of this node's associated string.
296 /// \param Edge The label on the edge leaving \p Parent to this node.
297 ///
298 /// \returns A pointer to the allocated internal node.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000299 SuffixTreeNode *insertInternalNode(SuffixTreeNode *Parent, unsigned StartIdx,
300 unsigned EndIdx, unsigned Edge) {
Jessica Paquette596f4832017-03-06 21:31:18 +0000301
302 assert(StartIdx <= EndIdx && "String can't start after it ends!");
303 assert(!(!Parent && StartIdx != EmptyIdx) &&
Jessica Paquette78681be2017-07-27 23:24:43 +0000304 "Non-root internal nodes must have parents!");
Jessica Paquette596f4832017-03-06 21:31:18 +0000305
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000306 unsigned *E = new (InternalEndIdxAllocator) unsigned(EndIdx);
Jessica Paquette78681be2017-07-27 23:24:43 +0000307 SuffixTreeNode *N = new (NodeAllocator.Allocate())
Jessica Paquettedf5b09b2018-11-07 19:56:13 +0000308 SuffixTreeNode(StartIdx, E, Root);
Jessica Paquette596f4832017-03-06 21:31:18 +0000309 if (Parent)
310 Parent->Children[Edge] = N;
311
312 return N;
313 }
314
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000315 /// Set the suffix indices of the leaves to the start indices of their
Jessica Paquette4e54ef82018-11-06 21:46:41 +0000316 /// respective suffixes.
Jessica Paquette596f4832017-03-06 21:31:18 +0000317 ///
318 /// \param[in] CurrNode The node currently being visited.
Jessica Paquettedf5b09b2018-11-07 19:56:13 +0000319 /// \param CurrNodeLen The concatenation of all node sizes from the root to
320 /// this node. Used to produce suffix indices.
321 void setSuffixIndices(SuffixTreeNode &CurrNode, unsigned CurrNodeLen) {
Jessica Paquette596f4832017-03-06 21:31:18 +0000322
323 bool IsLeaf = CurrNode.Children.size() == 0 && !CurrNode.isRoot();
324
Jessica Paquettedf5b09b2018-11-07 19:56:13 +0000325 // Store the concatenation of lengths down from the root.
326 CurrNode.ConcatLen = CurrNodeLen;
Jessica Paquette596f4832017-03-06 21:31:18 +0000327 // Traverse the tree depth-first.
328 for (auto &ChildPair : CurrNode.Children) {
329 assert(ChildPair.second && "Node had a null child!");
Jessica Paquettedf5b09b2018-11-07 19:56:13 +0000330 setSuffixIndices(*ChildPair.second,
331 CurrNodeLen + ChildPair.second->size());
Jessica Paquette596f4832017-03-06 21:31:18 +0000332 }
333
Jessica Paquettedf5b09b2018-11-07 19:56:13 +0000334 // Is this node a leaf? If it is, give it a suffix index.
335 if (IsLeaf)
336 CurrNode.SuffixIdx = Str.size() - CurrNodeLen;
Jessica Paquette596f4832017-03-06 21:31:18 +0000337 }
338
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000339 /// Construct the suffix tree for the prefix of the input ending at
Jessica Paquette596f4832017-03-06 21:31:18 +0000340 /// \p EndIdx.
341 ///
342 /// Used to construct the full suffix tree iteratively. At the end of each
343 /// step, the constructed suffix tree is either a valid suffix tree, or a
344 /// suffix tree with implicit suffixes. At the end of the final step, the
345 /// suffix tree is a valid tree.
346 ///
347 /// \param EndIdx The end index of the current prefix in the main string.
348 /// \param SuffixesToAdd The number of suffixes that must be added
349 /// to complete the suffix tree at the current phase.
350 ///
351 /// \returns The number of suffixes that have not been added at the end of
352 /// this step.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000353 unsigned extend(unsigned EndIdx, unsigned SuffixesToAdd) {
Jessica Paquette596f4832017-03-06 21:31:18 +0000354 SuffixTreeNode *NeedsLink = nullptr;
355
356 while (SuffixesToAdd > 0) {
Jessica Paquette78681be2017-07-27 23:24:43 +0000357
Jessica Paquette596f4832017-03-06 21:31:18 +0000358 // Are we waiting to add anything other than just the last character?
359 if (Active.Len == 0) {
360 // If not, then say the active index is the end index.
361 Active.Idx = EndIdx;
362 }
363
364 assert(Active.Idx <= EndIdx && "Start index can't be after end index!");
365
366 // The first character in the current substring we're looking at.
367 unsigned FirstChar = Str[Active.Idx];
368
369 // Have we inserted anything starting with FirstChar at the current node?
370 if (Active.Node->Children.count(FirstChar) == 0) {
371 // If not, then we can just insert a leaf and move too the next step.
372 insertLeaf(*Active.Node, EndIdx, FirstChar);
373
374 // The active node is an internal node, and we visited it, so it must
375 // need a link if it doesn't have one.
376 if (NeedsLink) {
377 NeedsLink->Link = Active.Node;
378 NeedsLink = nullptr;
379 }
380 } else {
381 // There's a match with FirstChar, so look for the point in the tree to
382 // insert a new node.
383 SuffixTreeNode *NextNode = Active.Node->Children[FirstChar];
384
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000385 unsigned SubstringLen = NextNode->size();
Jessica Paquette596f4832017-03-06 21:31:18 +0000386
387 // Is the current suffix we're trying to insert longer than the size of
388 // the child we want to move to?
389 if (Active.Len >= SubstringLen) {
390 // If yes, then consume the characters we've seen and move to the next
391 // node.
392 Active.Idx += SubstringLen;
393 Active.Len -= SubstringLen;
394 Active.Node = NextNode;
395 continue;
396 }
397
398 // Otherwise, the suffix we're trying to insert must be contained in the
399 // next node we want to move to.
400 unsigned LastChar = Str[EndIdx];
401
402 // Is the string we're trying to insert a substring of the next node?
403 if (Str[NextNode->StartIdx + Active.Len] == LastChar) {
404 // If yes, then we're done for this step. Remember our insertion point
405 // and move to the next end index. At this point, we have an implicit
406 // suffix tree.
407 if (NeedsLink && !Active.Node->isRoot()) {
408 NeedsLink->Link = Active.Node;
409 NeedsLink = nullptr;
410 }
411
412 Active.Len++;
413 break;
414 }
415
416 // The string we're trying to insert isn't a substring of the next node,
417 // but matches up to a point. Split the node.
418 //
419 // For example, say we ended our search at a node n and we're trying to
420 // insert ABD. Then we'll create a new node s for AB, reduce n to just
421 // representing C, and insert a new leaf node l to represent d. This
422 // allows us to ensure that if n was a leaf, it remains a leaf.
423 //
424 // | ABC ---split---> | AB
425 // n s
426 // C / \ D
427 // n l
428
429 // The node s from the diagram
430 SuffixTreeNode *SplitNode =
Jessica Paquette78681be2017-07-27 23:24:43 +0000431 insertInternalNode(Active.Node, NextNode->StartIdx,
432 NextNode->StartIdx + Active.Len - 1, FirstChar);
Jessica Paquette596f4832017-03-06 21:31:18 +0000433
434 // Insert the new node representing the new substring into the tree as
435 // a child of the split node. This is the node l from the diagram.
436 insertLeaf(*SplitNode, EndIdx, LastChar);
437
438 // Make the old node a child of the split node and update its start
439 // index. This is the node n from the diagram.
440 NextNode->StartIdx += Active.Len;
Jessica Paquette596f4832017-03-06 21:31:18 +0000441 SplitNode->Children[Str[NextNode->StartIdx]] = NextNode;
442
443 // SplitNode is an internal node, update the suffix link.
444 if (NeedsLink)
445 NeedsLink->Link = SplitNode;
446
447 NeedsLink = SplitNode;
448 }
449
450 // We've added something new to the tree, so there's one less suffix to
451 // add.
452 SuffixesToAdd--;
453
454 if (Active.Node->isRoot()) {
455 if (Active.Len > 0) {
456 Active.Len--;
457 Active.Idx = EndIdx - SuffixesToAdd + 1;
458 }
459 } else {
460 // Start the next phase at the next smallest suffix.
461 Active.Node = Active.Node->Link;
462 }
463 }
464
465 return SuffixesToAdd;
466 }
467
Jessica Paquette596f4832017-03-06 21:31:18 +0000468public:
Jessica Paquette596f4832017-03-06 21:31:18 +0000469 /// Construct a suffix tree from a sequence of unsigned integers.
470 ///
471 /// \param Str The string to construct the suffix tree for.
472 SuffixTree(const std::vector<unsigned> &Str) : Str(Str) {
473 Root = insertInternalNode(nullptr, EmptyIdx, EmptyIdx, 0);
Jessica Paquette596f4832017-03-06 21:31:18 +0000474 Active.Node = Root;
Jessica Paquette596f4832017-03-06 21:31:18 +0000475
476 // Keep track of the number of suffixes we have to add of the current
477 // prefix.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000478 unsigned SuffixesToAdd = 0;
Jessica Paquette596f4832017-03-06 21:31:18 +0000479 Active.Node = Root;
480
481 // Construct the suffix tree iteratively on each prefix of the string.
482 // PfxEndIdx is the end index of the current prefix.
483 // End is one past the last element in the string.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000484 for (unsigned PfxEndIdx = 0, End = Str.size(); PfxEndIdx < End;
485 PfxEndIdx++) {
Jessica Paquette596f4832017-03-06 21:31:18 +0000486 SuffixesToAdd++;
487 LeafEndIdx = PfxEndIdx; // Extend each of the leaves.
488 SuffixesToAdd = extend(PfxEndIdx, SuffixesToAdd);
489 }
490
491 // Set the suffix indices of each leaf.
492 assert(Root && "Root node can't be nullptr!");
493 setSuffixIndices(*Root, 0);
494 }
Jessica Paquette4e54ef82018-11-06 21:46:41 +0000495
Jessica Paquettea409cc92018-11-07 19:20:55 +0000496
497 /// Iterator for finding all repeated substrings in the suffix tree.
498 struct RepeatedSubstringIterator {
499 private:
500 /// The current node we're visiting.
501 SuffixTreeNode *N = nullptr;
502
503 /// The repeated substring associated with this node.
504 RepeatedSubstring RS;
505
506 /// The nodes left to visit.
507 std::vector<SuffixTreeNode *> ToVisit;
508
509 /// The minimum length of a repeated substring to find.
510 /// Since we're outlining, we want at least two instructions in the range.
511 /// FIXME: This may not be true for targets like X86 which support many
512 /// instruction lengths.
513 const unsigned MinLength = 2;
514
515 /// Move the iterator to the next repeated substring.
516 void advance() {
517 // Clear the current state. If we're at the end of the range, then this
518 // is the state we want to be in.
519 RS = RepeatedSubstring();
520 N = nullptr;
521
522 // Continue visiting nodes until we find one which repeats more than once.
523 while (!ToVisit.empty()) {
524 SuffixTreeNode *Curr = ToVisit.back();
525 ToVisit.pop_back();
526
527 // Keep track of the length of the string associated with the node. If
528 // it's too short, we'll quit.
529 unsigned Length = Curr->ConcatLen;
530
531 // Each leaf node represents a repeat of a string.
532 std::vector<SuffixTreeNode *> LeafChildren;
533
534 // Iterate over each child, saving internal nodes for visiting, and
535 // leaf nodes in LeafChildren. Internal nodes represent individual
536 // strings, which may repeat.
537 for (auto &ChildPair : Curr->Children) {
538 // Save all of this node's children for processing.
539 if (!ChildPair.second->isLeaf())
540 ToVisit.push_back(ChildPair.second);
541
542 // It's not an internal node, so it must be a leaf. If we have a
543 // long enough string, then save the leaf children.
544 else if (Length >= MinLength)
545 LeafChildren.push_back(ChildPair.second);
546 }
547
548 // The root never represents a repeated substring. If we're looking at
549 // that, then skip it.
550 if (Curr->isRoot())
551 continue;
552
553 // Do we have any repeated substrings?
554 if (LeafChildren.size() >= 2) {
555 // Yes. Update the state to reflect this, and then bail out.
556 N = Curr;
557 RS.Length = Length;
558 for (SuffixTreeNode *Leaf : LeafChildren)
559 RS.StartIndices.push_back(Leaf->SuffixIdx);
560 break;
561 }
562 }
563
564 // At this point, either NewRS is an empty RepeatedSubstring, or it was
565 // set in the above loop. Similarly, N is either nullptr, or the node
566 // associated with NewRS.
567 }
568
569 public:
570 /// Return the current repeated substring.
571 RepeatedSubstring &operator*() { return RS; }
572
573 RepeatedSubstringIterator &operator++() {
574 advance();
575 return *this;
576 }
577
578 RepeatedSubstringIterator operator++(int I) {
579 RepeatedSubstringIterator It(*this);
580 advance();
581 return It;
582 }
583
584 bool operator==(const RepeatedSubstringIterator &Other) {
585 return N == Other.N;
586 }
587 bool operator!=(const RepeatedSubstringIterator &Other) {
588 return !(*this == Other);
589 }
590
591 RepeatedSubstringIterator(SuffixTreeNode *N) : N(N) {
592 // Do we have a non-null node?
593 if (N) {
594 // Yes. At the first step, we need to visit all of N's children.
595 // Note: This means that we visit N last.
596 ToVisit.push_back(N);
597 advance();
598 }
599 }
600};
601
602 typedef RepeatedSubstringIterator iterator;
603 iterator begin() { return iterator(Root); }
604 iterator end() { return iterator(nullptr); }
Jessica Paquette596f4832017-03-06 21:31:18 +0000605};
606
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000607/// Maps \p MachineInstrs to unsigned integers and stores the mappings.
Jessica Paquette596f4832017-03-06 21:31:18 +0000608struct InstructionMapper {
609
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000610 /// The next available integer to assign to a \p MachineInstr that
Jessica Paquette596f4832017-03-06 21:31:18 +0000611 /// cannot be outlined.
612 ///
613 /// Set to -3 for compatability with \p DenseMapInfo<unsigned>.
614 unsigned IllegalInstrNumber = -3;
615
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000616 /// The next available integer to assign to a \p MachineInstr that can
Jessica Paquette596f4832017-03-06 21:31:18 +0000617 /// be outlined.
618 unsigned LegalInstrNumber = 0;
619
620 /// Correspondence from \p MachineInstrs to unsigned integers.
621 DenseMap<MachineInstr *, unsigned, MachineInstrExpressionTrait>
622 InstructionIntegerMap;
623
624 /// Corresponcence from unsigned integers to \p MachineInstrs.
625 /// Inverse of \p InstructionIntegerMap.
626 DenseMap<unsigned, MachineInstr *> IntegerInstructionMap;
627
628 /// The vector of unsigned integers that the module is mapped to.
629 std::vector<unsigned> UnsignedVec;
630
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000631 /// Stores the location of the instruction associated with the integer
Jessica Paquette596f4832017-03-06 21:31:18 +0000632 /// at index i in \p UnsignedVec for each index i.
633 std::vector<MachineBasicBlock::iterator> InstrList;
634
Jessica Paquettec991cf32018-11-01 23:09:06 +0000635 // Set if we added an illegal number in the previous step.
636 // Since each illegal number is unique, we only need one of them between
637 // each range of legal numbers. This lets us make sure we don't add more
638 // than one illegal number per range.
639 bool AddedIllegalLastTime = false;
640
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000641 /// Maps \p *It to a legal integer.
Jessica Paquette596f4832017-03-06 21:31:18 +0000642 ///
Jessica Paquettec4cf7752018-11-08 00:33:38 +0000643 /// Updates \p CanOutlineWithPrevInstr, \p HaveLegalRange, \p InstrListForMBB,
644 /// \p UnsignedVecForMBB, \p InstructionIntegerMap, \p IntegerInstructionMap,
645 /// and \p LegalInstrNumber.
Jessica Paquette596f4832017-03-06 21:31:18 +0000646 ///
647 /// \returns The integer that \p *It was mapped to.
Jessica Paquette267d2662018-11-08 00:02:11 +0000648 unsigned mapToLegalUnsigned(
Jessica Paquettec4cf7752018-11-08 00:33:38 +0000649 MachineBasicBlock::iterator &It, bool &CanOutlineWithPrevInstr,
650 bool &HaveLegalRange, unsigned &NumLegalInBlock,
Jessica Paquette267d2662018-11-08 00:02:11 +0000651 std::vector<unsigned> &UnsignedVecForMBB,
652 std::vector<MachineBasicBlock::iterator> &InstrListForMBB) {
Jessica Paquettec991cf32018-11-01 23:09:06 +0000653 // We added something legal, so we should unset the AddedLegalLastTime
654 // flag.
655 AddedIllegalLastTime = false;
Jessica Paquette596f4832017-03-06 21:31:18 +0000656
Jessica Paquettec4cf7752018-11-08 00:33:38 +0000657 // If we have at least two adjacent legal instructions (which may have
658 // invisible instructions in between), remember that.
659 if (CanOutlineWithPrevInstr)
660 HaveLegalRange = true;
661 CanOutlineWithPrevInstr = true;
662
Jessica Paquette267d2662018-11-08 00:02:11 +0000663 // Keep track of the number of legal instructions we insert.
664 NumLegalInBlock++;
665
Jessica Paquette596f4832017-03-06 21:31:18 +0000666 // Get the integer for this instruction or give it the current
667 // LegalInstrNumber.
Jessica Paquette267d2662018-11-08 00:02:11 +0000668 InstrListForMBB.push_back(It);
Jessica Paquette596f4832017-03-06 21:31:18 +0000669 MachineInstr &MI = *It;
670 bool WasInserted;
671 DenseMap<MachineInstr *, unsigned, MachineInstrExpressionTrait>::iterator
Jessica Paquette78681be2017-07-27 23:24:43 +0000672 ResultIt;
Jessica Paquette596f4832017-03-06 21:31:18 +0000673 std::tie(ResultIt, WasInserted) =
Jessica Paquette78681be2017-07-27 23:24:43 +0000674 InstructionIntegerMap.insert(std::make_pair(&MI, LegalInstrNumber));
Jessica Paquette596f4832017-03-06 21:31:18 +0000675 unsigned MINumber = ResultIt->second;
676
677 // There was an insertion.
678 if (WasInserted) {
679 LegalInstrNumber++;
680 IntegerInstructionMap.insert(std::make_pair(MINumber, &MI));
681 }
682
Jessica Paquette267d2662018-11-08 00:02:11 +0000683 UnsignedVecForMBB.push_back(MINumber);
Jessica Paquette596f4832017-03-06 21:31:18 +0000684
685 // Make sure we don't overflow or use any integers reserved by the DenseMap.
686 if (LegalInstrNumber >= IllegalInstrNumber)
687 report_fatal_error("Instruction mapping overflow!");
688
Jessica Paquette78681be2017-07-27 23:24:43 +0000689 assert(LegalInstrNumber != DenseMapInfo<unsigned>::getEmptyKey() &&
690 "Tried to assign DenseMap tombstone or empty key to instruction.");
691 assert(LegalInstrNumber != DenseMapInfo<unsigned>::getTombstoneKey() &&
692 "Tried to assign DenseMap tombstone or empty key to instruction.");
Jessica Paquette596f4832017-03-06 21:31:18 +0000693
694 return MINumber;
695 }
696
697 /// Maps \p *It to an illegal integer.
698 ///
Jessica Paquette267d2662018-11-08 00:02:11 +0000699 /// Updates \p InstrListForMBB, \p UnsignedVecForMBB, and \p
700 /// IllegalInstrNumber.
Jessica Paquette596f4832017-03-06 21:31:18 +0000701 ///
702 /// \returns The integer that \p *It was mapped to.
Jessica Paquettec4cf7752018-11-08 00:33:38 +0000703 unsigned mapToIllegalUnsigned(MachineBasicBlock::iterator &It,
704 bool &CanOutlineWithPrevInstr, std::vector<unsigned> &UnsignedVecForMBB,
705 std::vector<MachineBasicBlock::iterator> &InstrListForMBB) {
706 // Can't outline an illegal instruction. Set the flag.
707 CanOutlineWithPrevInstr = false;
708
Jessica Paquettec991cf32018-11-01 23:09:06 +0000709 // Only add one illegal number per range of legal numbers.
710 if (AddedIllegalLastTime)
711 return IllegalInstrNumber;
712
713 // Remember that we added an illegal number last time.
714 AddedIllegalLastTime = true;
Jessica Paquette596f4832017-03-06 21:31:18 +0000715 unsigned MINumber = IllegalInstrNumber;
716
Jessica Paquette267d2662018-11-08 00:02:11 +0000717 InstrListForMBB.push_back(It);
718 UnsignedVecForMBB.push_back(IllegalInstrNumber);
Jessica Paquette596f4832017-03-06 21:31:18 +0000719 IllegalInstrNumber--;
720
721 assert(LegalInstrNumber < IllegalInstrNumber &&
722 "Instruction mapping overflow!");
723
Jessica Paquette78681be2017-07-27 23:24:43 +0000724 assert(IllegalInstrNumber != DenseMapInfo<unsigned>::getEmptyKey() &&
725 "IllegalInstrNumber cannot be DenseMap tombstone or empty key!");
Jessica Paquette596f4832017-03-06 21:31:18 +0000726
Jessica Paquette78681be2017-07-27 23:24:43 +0000727 assert(IllegalInstrNumber != DenseMapInfo<unsigned>::getTombstoneKey() &&
728 "IllegalInstrNumber cannot be DenseMap tombstone or empty key!");
Jessica Paquette596f4832017-03-06 21:31:18 +0000729
730 return MINumber;
731 }
732
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000733 /// Transforms a \p MachineBasicBlock into a \p vector of \p unsigneds
Jessica Paquette596f4832017-03-06 21:31:18 +0000734 /// and appends it to \p UnsignedVec and \p InstrList.
735 ///
736 /// Two instructions are assigned the same integer if they are identical.
737 /// If an instruction is deemed unsafe to outline, then it will be assigned an
738 /// unique integer. The resulting mapping is placed into a suffix tree and
739 /// queried for candidates.
740 ///
741 /// \param MBB The \p MachineBasicBlock to be translated into integers.
Eli Friedmanda080782018-08-01 00:37:20 +0000742 /// \param TII \p TargetInstrInfo for the function.
Jessica Paquette596f4832017-03-06 21:31:18 +0000743 void convertToUnsignedVec(MachineBasicBlock &MBB,
Jessica Paquette596f4832017-03-06 21:31:18 +0000744 const TargetInstrInfo &TII) {
Jessica Paquette3291e732018-01-09 00:26:18 +0000745 unsigned Flags = TII.getMachineOutlinerMBBFlags(MBB);
Jessica Paquettec991cf32018-11-01 23:09:06 +0000746 MachineBasicBlock::iterator It = MBB.begin();
Jessica Paquette267d2662018-11-08 00:02:11 +0000747
748 // The number of instructions in this block that will be considered for
749 // outlining.
750 unsigned NumLegalInBlock = 0;
751
Jessica Paquettec4cf7752018-11-08 00:33:38 +0000752 // True if we have at least two legal instructions which aren't separated
753 // by an illegal instruction.
754 bool HaveLegalRange = false;
755
756 // True if we can perform outlining given the last mapped (non-invisible)
757 // instruction. This lets us know if we have a legal range.
758 bool CanOutlineWithPrevInstr = false;
759
Jessica Paquette267d2662018-11-08 00:02:11 +0000760 // FIXME: Should this all just be handled in the target, rather than using
761 // repeated calls to getOutliningType?
762 std::vector<unsigned> UnsignedVecForMBB;
763 std::vector<MachineBasicBlock::iterator> InstrListForMBB;
764
Jessica Paquettec991cf32018-11-01 23:09:06 +0000765 for (MachineBasicBlock::iterator Et = MBB.end(); It != Et; It++) {
Jessica Paquette596f4832017-03-06 21:31:18 +0000766 // Keep track of where this instruction is in the module.
Jessica Paquette3291e732018-01-09 00:26:18 +0000767 switch (TII.getOutliningType(It, Flags)) {
Jessica Paquetteaa087322018-06-04 21:14:16 +0000768 case InstrType::Illegal:
Jessica Paquettec4cf7752018-11-08 00:33:38 +0000769 mapToIllegalUnsigned(It, CanOutlineWithPrevInstr,
770 UnsignedVecForMBB, InstrListForMBB);
Jessica Paquette78681be2017-07-27 23:24:43 +0000771 break;
Jessica Paquette596f4832017-03-06 21:31:18 +0000772
Jessica Paquetteaa087322018-06-04 21:14:16 +0000773 case InstrType::Legal:
Jessica Paquettec4cf7752018-11-08 00:33:38 +0000774 mapToLegalUnsigned(It, CanOutlineWithPrevInstr, HaveLegalRange,
775 NumLegalInBlock, UnsignedVecForMBB, InstrListForMBB);
Jessica Paquette78681be2017-07-27 23:24:43 +0000776 break;
Jessica Paquette596f4832017-03-06 21:31:18 +0000777
Jessica Paquetteaa087322018-06-04 21:14:16 +0000778 case InstrType::LegalTerminator:
Jessica Paquettec4cf7752018-11-08 00:33:38 +0000779 mapToLegalUnsigned(It, CanOutlineWithPrevInstr, HaveLegalRange,
780 NumLegalInBlock, UnsignedVecForMBB, InstrListForMBB);
Jessica Paquettec991cf32018-11-01 23:09:06 +0000781 // The instruction also acts as a terminator, so we have to record that
782 // in the string.
Jessica Paquettec4cf7752018-11-08 00:33:38 +0000783 mapToIllegalUnsigned(It, CanOutlineWithPrevInstr, UnsignedVecForMBB,
784 InstrListForMBB);
Eli Friedman042dc9e2018-05-22 19:11:06 +0000785 break;
786
Jessica Paquetteaa087322018-06-04 21:14:16 +0000787 case InstrType::Invisible:
Jessica Paquettec991cf32018-11-01 23:09:06 +0000788 // Normally this is set by mapTo(Blah)Unsigned, but we just want to
789 // skip this instruction. So, unset the flag here.
Jessica Paquettebd729882018-09-17 18:40:21 +0000790 AddedIllegalLastTime = false;
Jessica Paquette78681be2017-07-27 23:24:43 +0000791 break;
Jessica Paquette596f4832017-03-06 21:31:18 +0000792 }
793 }
794
Jessica Paquette267d2662018-11-08 00:02:11 +0000795 // Are there enough legal instructions in the block for outlining to be
796 // possible?
Jessica Paquettec4cf7752018-11-08 00:33:38 +0000797 if (HaveLegalRange) {
Jessica Paquette267d2662018-11-08 00:02:11 +0000798 // After we're done every insertion, uniquely terminate this part of the
799 // "string". This makes sure we won't match across basic block or function
800 // boundaries since the "end" is encoded uniquely and thus appears in no
801 // repeated substring.
Jessica Paquettec4cf7752018-11-08 00:33:38 +0000802 mapToIllegalUnsigned(It, CanOutlineWithPrevInstr, UnsignedVecForMBB,
803 InstrListForMBB);
Jessica Paquette267d2662018-11-08 00:02:11 +0000804 InstrList.insert(InstrList.end(), InstrListForMBB.begin(),
805 InstrListForMBB.end());
806 UnsignedVec.insert(UnsignedVec.end(), UnsignedVecForMBB.begin(),
807 UnsignedVecForMBB.end());
808 }
Jessica Paquette596f4832017-03-06 21:31:18 +0000809 }
810
811 InstructionMapper() {
812 // Make sure that the implementation of DenseMapInfo<unsigned> hasn't
813 // changed.
814 assert(DenseMapInfo<unsigned>::getEmptyKey() == (unsigned)-1 &&
Jessica Paquette78681be2017-07-27 23:24:43 +0000815 "DenseMapInfo<unsigned>'s empty key isn't -1!");
Jessica Paquette596f4832017-03-06 21:31:18 +0000816 assert(DenseMapInfo<unsigned>::getTombstoneKey() == (unsigned)-2 &&
Jessica Paquette78681be2017-07-27 23:24:43 +0000817 "DenseMapInfo<unsigned>'s tombstone key isn't -2!");
Jessica Paquette596f4832017-03-06 21:31:18 +0000818 }
819};
820
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000821/// An interprocedural pass which finds repeated sequences of
Jessica Paquette596f4832017-03-06 21:31:18 +0000822/// instructions and replaces them with calls to functions.
823///
824/// Each instruction is mapped to an unsigned integer and placed in a string.
825/// The resulting mapping is then placed in a \p SuffixTree. The \p SuffixTree
826/// is then repeatedly queried for repeated sequences of instructions. Each
827/// non-overlapping repeated sequence is then placed in its own
828/// \p MachineFunction and each instance is then replaced with a call to that
829/// function.
830struct MachineOutliner : public ModulePass {
831
832 static char ID;
833
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000834 /// Set to true if the outliner should consider functions with
Jessica Paquette13593842017-10-07 00:16:34 +0000835 /// linkonceodr linkage.
836 bool OutlineFromLinkOnceODRs = false;
837
Jessica Paquette8bda1882018-06-30 03:56:03 +0000838 /// Set to true if the outliner should run on all functions in the module
839 /// considered safe for outlining.
840 /// Set to true by default for compatibility with llc's -run-pass option.
841 /// Set when the pass is constructed in TargetPassConfig.
842 bool RunOnAllFunctions = true;
843
Jessica Paquette596f4832017-03-06 21:31:18 +0000844 StringRef getPassName() const override { return "Machine Outliner"; }
845
846 void getAnalysisUsage(AnalysisUsage &AU) const override {
847 AU.addRequired<MachineModuleInfo>();
848 AU.addPreserved<MachineModuleInfo>();
849 AU.setPreservesAll();
850 ModulePass::getAnalysisUsage(AU);
851 }
852
Jessica Paquette1eca23b2018-04-19 22:17:07 +0000853 MachineOutliner() : ModulePass(ID) {
Jessica Paquette596f4832017-03-06 21:31:18 +0000854 initializeMachineOutlinerPass(*PassRegistry::getPassRegistry());
855 }
856
Jessica Paquette1cc52a02018-07-24 17:37:28 +0000857 /// Remark output explaining that not outlining a set of candidates would be
858 /// better than outlining that set.
859 void emitNotOutliningCheaperRemark(
860 unsigned StringLen, std::vector<Candidate> &CandidatesForRepeatedSeq,
861 OutlinedFunction &OF);
862
Jessica Paquette58e706a2018-07-24 20:20:45 +0000863 /// Remark output explaining that a function was outlined.
864 void emitOutlinedFunctionRemark(OutlinedFunction &OF);
865
Jessica Paquette78681be2017-07-27 23:24:43 +0000866 /// Find all repeated substrings that satisfy the outlining cost model.
867 ///
868 /// If a substring appears at least twice, then it must be represented by
Jessica Paquette1cc52a02018-07-24 17:37:28 +0000869 /// an internal node which appears in at least two suffixes. Each suffix
870 /// is represented by a leaf node. To do this, we visit each internal node
871 /// in the tree, using the leaf children of each internal node. If an
872 /// internal node represents a beneficial substring, then we use each of
873 /// its leaf children to find the locations of its substring.
Jessica Paquette78681be2017-07-27 23:24:43 +0000874 ///
875 /// \param ST A suffix tree to query.
Jessica Paquette78681be2017-07-27 23:24:43 +0000876 /// \param Mapper Contains outlining mapping information.
877 /// \param[out] CandidateList Filled with candidates representing each
878 /// beneficial substring.
Jessica Paquette1cc52a02018-07-24 17:37:28 +0000879 /// \param[out] FunctionList Filled with a list of \p OutlinedFunctions
880 /// each type of candidate.
Jessica Paquette78681be2017-07-27 23:24:43 +0000881 ///
882 /// \returns The length of the longest candidate found.
Jessica Paquette9df7fde2017-10-23 23:36:46 +0000883 unsigned
Eli Friedmanda080782018-08-01 00:37:20 +0000884 findCandidates(SuffixTree &ST,
Jessica Paquette9df7fde2017-10-23 23:36:46 +0000885 InstructionMapper &Mapper,
886 std::vector<std::shared_ptr<Candidate>> &CandidateList,
887 std::vector<OutlinedFunction> &FunctionList);
Jessica Paquette78681be2017-07-27 23:24:43 +0000888
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000889 /// Replace the sequences of instructions represented by the
Jessica Paquette596f4832017-03-06 21:31:18 +0000890 /// \p Candidates in \p CandidateList with calls to \p MachineFunctions
891 /// described in \p FunctionList.
892 ///
893 /// \param M The module we are outlining from.
894 /// \param CandidateList A list of candidates to be outlined.
895 /// \param FunctionList A list of functions to be inserted into the module.
896 /// \param Mapper Contains the instruction mappings for the module.
Jessica Paquette9df7fde2017-10-23 23:36:46 +0000897 bool outline(Module &M,
898 const ArrayRef<std::shared_ptr<Candidate>> &CandidateList,
Jessica Paquette596f4832017-03-06 21:31:18 +0000899 std::vector<OutlinedFunction> &FunctionList,
900 InstructionMapper &Mapper);
901
902 /// Creates a function for \p OF and inserts it into the module.
903 MachineFunction *createOutlinedFunction(Module &M, const OutlinedFunction &OF,
Jessica Paquettea3eb0fa2018-11-07 18:36:43 +0000904 InstructionMapper &Mapper,
905 unsigned Name);
Jessica Paquette596f4832017-03-06 21:31:18 +0000906
907 /// Find potential outlining candidates and store them in \p CandidateList.
908 ///
909 /// For each type of potential candidate, also build an \p OutlinedFunction
910 /// struct containing the information to build the function for that
911 /// candidate.
912 ///
913 /// \param[out] CandidateList Filled with outlining candidates for the module.
914 /// \param[out] FunctionList Filled with functions corresponding to each type
915 /// of \p Candidate.
916 /// \param ST The suffix tree for the module.
Jessica Paquette596f4832017-03-06 21:31:18 +0000917 ///
918 /// \returns The length of the longest candidate found. 0 if there are none.
Jessica Paquette9df7fde2017-10-23 23:36:46 +0000919 unsigned
920 buildCandidateList(std::vector<std::shared_ptr<Candidate>> &CandidateList,
921 std::vector<OutlinedFunction> &FunctionList,
Jessica Paquette39542722018-11-12 17:50:55 +0000922 InstructionMapper &Mapper);
Jessica Paquette596f4832017-03-06 21:31:18 +0000923
Jessica Paquette60d31fc2017-10-17 21:11:58 +0000924 /// Helper function for pruneOverlaps.
925 /// Removes \p C from the candidate list, and updates its \p OutlinedFunction.
926 void prune(Candidate &C, std::vector<OutlinedFunction> &FunctionList);
927
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000928 /// Remove any overlapping candidates that weren't handled by the
Jessica Paquette596f4832017-03-06 21:31:18 +0000929 /// suffix tree's pruning method.
930 ///
931 /// Pruning from the suffix tree doesn't necessarily remove all overlaps.
932 /// If a short candidate is chosen for outlining, then a longer candidate
933 /// which has that short candidate as a suffix is chosen, the tree's pruning
934 /// method will not find it. Thus, we need to prune before outlining as well.
935 ///
936 /// \param[in,out] CandidateList A list of outlining candidates.
937 /// \param[in,out] FunctionList A list of functions to be outlined.
Jessica Paquette809d7082017-07-28 03:21:58 +0000938 /// \param Mapper Contains instruction mapping info for outlining.
Jessica Paquette596f4832017-03-06 21:31:18 +0000939 /// \param MaxCandidateLen The length of the longest candidate.
Jessica Paquette9df7fde2017-10-23 23:36:46 +0000940 void pruneOverlaps(std::vector<std::shared_ptr<Candidate>> &CandidateList,
Jessica Paquette596f4832017-03-06 21:31:18 +0000941 std::vector<OutlinedFunction> &FunctionList,
Eli Friedmanda080782018-08-01 00:37:20 +0000942 InstructionMapper &Mapper, unsigned MaxCandidateLen);
Jessica Paquette596f4832017-03-06 21:31:18 +0000943
944 /// Construct a suffix tree on the instructions in \p M and outline repeated
945 /// strings from that tree.
946 bool runOnModule(Module &M) override;
Jessica Paquetteaa087322018-06-04 21:14:16 +0000947
948 /// Return a DISubprogram for OF if one exists, and null otherwise. Helper
949 /// function for remark emission.
950 DISubprogram *getSubprogramOrNull(const OutlinedFunction &OF) {
951 DISubprogram *SP;
952 for (const std::shared_ptr<Candidate> &C : OF.Candidates)
953 if (C && C->getMF() && (SP = C->getMF()->getFunction().getSubprogram()))
954 return SP;
955 return nullptr;
956 }
Jessica Paquette050d1ac2018-09-11 16:33:46 +0000957
958 /// Populate and \p InstructionMapper with instruction-to-integer mappings.
959 /// These are used to construct a suffix tree.
960 void populateMapper(InstructionMapper &Mapper, Module &M,
961 MachineModuleInfo &MMI);
Jessica Paquette596f4832017-03-06 21:31:18 +0000962
Jessica Paquette2386eab2018-09-11 23:05:34 +0000963 /// Initialize information necessary to output a size remark.
964 /// FIXME: This should be handled by the pass manager, not the outliner.
965 /// FIXME: This is nearly identical to the initSizeRemarkInfo in the legacy
966 /// pass manager.
967 void initSizeRemarkInfo(
968 const Module &M, const MachineModuleInfo &MMI,
969 StringMap<unsigned> &FunctionToInstrCount);
970
971 /// Emit the remark.
972 // FIXME: This should be handled by the pass manager, not the outliner.
973 void emitInstrCountChangedRemark(
974 const Module &M, const MachineModuleInfo &MMI,
975 const StringMap<unsigned> &FunctionToInstrCount);
976};
Jessica Paquette596f4832017-03-06 21:31:18 +0000977} // Anonymous namespace.
978
979char MachineOutliner::ID = 0;
980
981namespace llvm {
Jessica Paquette8bda1882018-06-30 03:56:03 +0000982ModulePass *createMachineOutlinerPass(bool RunOnAllFunctions) {
983 MachineOutliner *OL = new MachineOutliner();
984 OL->RunOnAllFunctions = RunOnAllFunctions;
985 return OL;
Jessica Paquette13593842017-10-07 00:16:34 +0000986}
987
Jessica Paquette78681be2017-07-27 23:24:43 +0000988} // namespace llvm
Jessica Paquette596f4832017-03-06 21:31:18 +0000989
Jessica Paquette78681be2017-07-27 23:24:43 +0000990INITIALIZE_PASS(MachineOutliner, DEBUG_TYPE, "Machine Function Outliner", false,
991 false)
992
Jessica Paquette1cc52a02018-07-24 17:37:28 +0000993void MachineOutliner::emitNotOutliningCheaperRemark(
994 unsigned StringLen, std::vector<Candidate> &CandidatesForRepeatedSeq,
995 OutlinedFunction &OF) {
Jessica Paquettec991cf32018-11-01 23:09:06 +0000996 // FIXME: Right now, we arbitrarily choose some Candidate from the
997 // OutlinedFunction. This isn't necessarily fixed, nor does it have to be.
998 // We should probably sort these by function name or something to make sure
999 // the remarks are stable.
Jessica Paquette1cc52a02018-07-24 17:37:28 +00001000 Candidate &C = CandidatesForRepeatedSeq.front();
1001 MachineOptimizationRemarkEmitter MORE(*(C.getMF()), nullptr);
1002 MORE.emit([&]() {
1003 MachineOptimizationRemarkMissed R(DEBUG_TYPE, "NotOutliningCheaper",
1004 C.front()->getDebugLoc(), C.getMBB());
1005 R << "Did not outline " << NV("Length", StringLen) << " instructions"
1006 << " from " << NV("NumOccurrences", CandidatesForRepeatedSeq.size())
1007 << " locations."
1008 << " Bytes from outlining all occurrences ("
1009 << NV("OutliningCost", OF.getOutliningCost()) << ")"
1010 << " >= Unoutlined instruction bytes ("
1011 << NV("NotOutliningCost", OF.getNotOutlinedCost()) << ")"
1012 << " (Also found at: ";
1013
1014 // Tell the user the other places the candidate was found.
1015 for (unsigned i = 1, e = CandidatesForRepeatedSeq.size(); i < e; i++) {
1016 R << NV((Twine("OtherStartLoc") + Twine(i)).str(),
1017 CandidatesForRepeatedSeq[i].front()->getDebugLoc());
1018 if (i != e - 1)
1019 R << ", ";
1020 }
1021
1022 R << ")";
1023 return R;
1024 });
1025}
1026
Jessica Paquette58e706a2018-07-24 20:20:45 +00001027void MachineOutliner::emitOutlinedFunctionRemark(OutlinedFunction &OF) {
1028 MachineBasicBlock *MBB = &*OF.MF->begin();
1029 MachineOptimizationRemarkEmitter MORE(*OF.MF, nullptr);
1030 MachineOptimizationRemark R(DEBUG_TYPE, "OutlinedFunction",
1031 MBB->findDebugLoc(MBB->begin()), MBB);
1032 R << "Saved " << NV("OutliningBenefit", OF.getBenefit()) << " bytes by "
1033 << "outlining " << NV("Length", OF.Sequence.size()) << " instructions "
1034 << "from " << NV("NumOccurrences", OF.getOccurrenceCount())
1035 << " locations. "
1036 << "(Found at: ";
1037
1038 // Tell the user the other places the candidate was found.
1039 for (size_t i = 0, e = OF.Candidates.size(); i < e; i++) {
1040
1041 // Skip over things that were pruned.
1042 if (!OF.Candidates[i]->InCandidateList)
1043 continue;
1044
1045 R << NV((Twine("StartLoc") + Twine(i)).str(),
1046 OF.Candidates[i]->front()->getDebugLoc());
1047 if (i != e - 1)
1048 R << ", ";
1049 }
1050
1051 R << ")";
1052
1053 MORE.emit(R);
1054}
1055
Jessica Paquette9df7fde2017-10-23 23:36:46 +00001056unsigned MachineOutliner::findCandidates(
Eli Friedmanda080782018-08-01 00:37:20 +00001057 SuffixTree &ST, InstructionMapper &Mapper,
Jessica Paquette9df7fde2017-10-23 23:36:46 +00001058 std::vector<std::shared_ptr<Candidate>> &CandidateList,
1059 std::vector<OutlinedFunction> &FunctionList) {
Jessica Paquette78681be2017-07-27 23:24:43 +00001060 CandidateList.clear();
1061 FunctionList.clear();
Jessica Paquette4cf187b2017-09-27 20:47:39 +00001062 unsigned MaxLen = 0;
Jessica Paquette78681be2017-07-27 23:24:43 +00001063
Jessica Paquette4e54ef82018-11-06 21:46:41 +00001064 // First, find dall of the repeated substrings in the tree of minimum length
1065 // 2.
Jessica Paquettea409cc92018-11-07 19:20:55 +00001066 for (auto It = ST.begin(), Et = ST.end(); It != Et; ++It) {
1067 SuffixTree::RepeatedSubstring RS = *It;
Jessica Paquetted87f5442017-07-29 02:55:46 +00001068 std::vector<Candidate> CandidatesForRepeatedSeq;
Jessica Paquette4e54ef82018-11-06 21:46:41 +00001069 unsigned StringLen = RS.Length;
1070 for (const unsigned &StartIdx : RS.StartIndices) {
1071 unsigned EndIdx = StartIdx + StringLen - 1;
1072 // Trick: Discard some candidates that would be incompatible with the
1073 // ones we've already found for this sequence. This will save us some
1074 // work in candidate selection.
1075 //
1076 // If two candidates overlap, then we can't outline them both. This
1077 // happens when we have candidates that look like, say
1078 //
1079 // AA (where each "A" is an instruction).
1080 //
1081 // We might have some portion of the module that looks like this:
1082 // AAAAAA (6 A's)
1083 //
1084 // In this case, there are 5 different copies of "AA" in this range, but
1085 // at most 3 can be outlined. If only outlining 3 of these is going to
1086 // be unbeneficial, then we ought to not bother.
1087 //
1088 // Note that two things DON'T overlap when they look like this:
1089 // start1...end1 .... start2...end2
1090 // That is, one must either
1091 // * End before the other starts
1092 // * Start after the other ends
1093 if (std::all_of(
1094 CandidatesForRepeatedSeq.begin(), CandidatesForRepeatedSeq.end(),
1095 [&StartIdx, &EndIdx](const Candidate &C) {
1096 return (EndIdx < C.getStartIdx() || StartIdx > C.getEndIdx());
1097 })) {
1098 // It doesn't overlap with anything, so we can outline it.
1099 // Each sequence is over [StartIt, EndIt].
1100 // Save the candidate and its location.
Jessica Paquetted87f5442017-07-29 02:55:46 +00001101
Jessica Paquette4e54ef82018-11-06 21:46:41 +00001102 MachineBasicBlock::iterator StartIt = Mapper.InstrList[StartIdx];
1103 MachineBasicBlock::iterator EndIt = Mapper.InstrList[EndIdx];
Jessica Paquette78681be2017-07-27 23:24:43 +00001104
Jessica Paquette4e54ef82018-11-06 21:46:41 +00001105 CandidatesForRepeatedSeq.emplace_back(StartIdx, StringLen, StartIt,
1106 EndIt, StartIt->getParent(),
1107 FunctionList.size());
Jessica Paquette809d7082017-07-28 03:21:58 +00001108 }
1109 }
1110
Jessica Paquetteacc15e12017-10-03 20:32:55 +00001111 // We've found something we might want to outline.
1112 // Create an OutlinedFunction to store it and check if it'd be beneficial
1113 // to outline.
Eli Friedmanda080782018-08-01 00:37:20 +00001114 if (CandidatesForRepeatedSeq.empty())
1115 continue;
1116
1117 // Arbitrarily choose a TII from the first candidate.
1118 // FIXME: Should getOutliningCandidateInfo move to TargetMachine?
1119 const TargetInstrInfo *TII =
1120 CandidatesForRepeatedSeq[0].getMF()->getSubtarget().getInstrInfo();
1121
Jessica Paquette9d93c602018-07-27 18:21:57 +00001122 OutlinedFunction OF =
Eli Friedmanda080782018-08-01 00:37:20 +00001123 TII->getOutliningCandidateInfo(CandidatesForRepeatedSeq);
Jessica Paquette9d93c602018-07-27 18:21:57 +00001124
1125 // If we deleted every candidate, then there's nothing to outline.
1126 if (OF.Candidates.empty())
1127 continue;
1128
Jessica Paquetteacc15e12017-10-03 20:32:55 +00001129 std::vector<unsigned> Seq;
Jessica Paquette4e54ef82018-11-06 21:46:41 +00001130 unsigned StartIdx = RS.StartIndices[0]; // Grab any start index.
1131 for (unsigned i = StartIdx; i < StartIdx + StringLen; i++)
Jessica Paquetteacc15e12017-10-03 20:32:55 +00001132 Seq.push_back(ST.Str[i]);
Jessica Paquette69f517d2018-07-24 20:13:10 +00001133 OF.Sequence = Seq;
Jessica Paquette809d7082017-07-28 03:21:58 +00001134
Jessica Paquetteffe4abc2017-08-31 21:02:45 +00001135 // Is it better to outline this candidate than not?
Jessica Paquettef94d1d22018-07-24 17:36:13 +00001136 if (OF.getBenefit() < 1) {
Jessica Paquette1cc52a02018-07-24 17:37:28 +00001137 emitNotOutliningCheaperRemark(StringLen, CandidatesForRepeatedSeq, OF);
Jessica Paquette78681be2017-07-27 23:24:43 +00001138 continue;
Jessica Paquetteffe4abc2017-08-31 21:02:45 +00001139 }
Jessica Paquette78681be2017-07-27 23:24:43 +00001140
1141 if (StringLen > MaxLen)
1142 MaxLen = StringLen;
1143
Jessica Paquettef94d1d22018-07-24 17:36:13 +00001144 // The function is beneficial. Save its candidates to the candidate list
1145 // for pruning.
1146 for (std::shared_ptr<Candidate> &C : OF.Candidates)
1147 CandidateList.push_back(C);
Jessica Paquetteacc15e12017-10-03 20:32:55 +00001148 FunctionList.push_back(OF);
Jessica Paquette78681be2017-07-27 23:24:43 +00001149 }
1150
1151 return MaxLen;
1152}
Jessica Paquette596f4832017-03-06 21:31:18 +00001153
Jessica Paquette60d31fc2017-10-17 21:11:58 +00001154// Remove C from the candidate space, and update its OutlinedFunction.
1155void MachineOutliner::prune(Candidate &C,
1156 std::vector<OutlinedFunction> &FunctionList) {
1157 // Get the OutlinedFunction associated with this Candidate.
1158 OutlinedFunction &F = FunctionList[C.FunctionIdx];
1159
1160 // Update C's associated function's occurrence count.
1161 F.decrement();
1162
1163 // Remove C from the CandidateList.
1164 C.InCandidateList = false;
1165
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001166 LLVM_DEBUG(dbgs() << "- Removed a Candidate \n";
1167 dbgs() << "--- Num fns left for candidate: "
1168 << F.getOccurrenceCount() << "\n";
1169 dbgs() << "--- Candidate's functions's benefit: " << F.getBenefit()
1170 << "\n";);
Jessica Paquette60d31fc2017-10-17 21:11:58 +00001171}
1172
Jessica Paquette9df7fde2017-10-23 23:36:46 +00001173void MachineOutliner::pruneOverlaps(
1174 std::vector<std::shared_ptr<Candidate>> &CandidateList,
1175 std::vector<OutlinedFunction> &FunctionList, InstructionMapper &Mapper,
Eli Friedmanda080782018-08-01 00:37:20 +00001176 unsigned MaxCandidateLen) {
Jessica Paquette91999162017-09-28 23:39:36 +00001177
1178 // Return true if this candidate became unbeneficial for outlining in a
1179 // previous step.
Jessica Paquette60d31fc2017-10-17 21:11:58 +00001180 auto ShouldSkipCandidate = [&FunctionList, this](Candidate &C) {
Jessica Paquette91999162017-09-28 23:39:36 +00001181
1182 // Check if the candidate was removed in a previous step.
1183 if (!C.InCandidateList)
1184 return true;
1185
Jessica Paquette85af63d2017-10-17 19:03:23 +00001186 // C must be alive. Check if we should remove it.
Jessica Paquette60d31fc2017-10-17 21:11:58 +00001187 if (FunctionList[C.FunctionIdx].getBenefit() < 1) {
1188 prune(C, FunctionList);
Jessica Paquette91999162017-09-28 23:39:36 +00001189 return true;
1190 }
1191
1192 // C is in the list, and F is still beneficial.
1193 return false;
1194 };
1195
Jessica Paquetteacffa282017-03-23 21:27:38 +00001196 // TODO: Experiment with interval trees or other interval-checking structures
1197 // to lower the time complexity of this function.
1198 // TODO: Can we do better than the simple greedy choice?
1199 // Check for overlaps in the range.
1200 // This is O(MaxCandidateLen * CandidateList.size()).
Jessica Paquette596f4832017-03-06 21:31:18 +00001201 for (auto It = CandidateList.begin(), Et = CandidateList.end(); It != Et;
1202 It++) {
Jessica Paquette9df7fde2017-10-23 23:36:46 +00001203 Candidate &C1 = **It;
Jessica Paquette596f4832017-03-06 21:31:18 +00001204
Jessica Paquette91999162017-09-28 23:39:36 +00001205 // If C1 was already pruned, or its function is no longer beneficial for
1206 // outlining, move to the next candidate.
1207 if (ShouldSkipCandidate(C1))
Jessica Paquette596f4832017-03-06 21:31:18 +00001208 continue;
1209
Jessica Paquette596f4832017-03-06 21:31:18 +00001210 // The minimum start index of any candidate that could overlap with this
1211 // one.
1212 unsigned FarthestPossibleIdx = 0;
1213
1214 // Either the index is 0, or it's at most MaxCandidateLen indices away.
Jessica Paquette1934fd22017-10-23 16:25:53 +00001215 if (C1.getStartIdx() > MaxCandidateLen)
1216 FarthestPossibleIdx = C1.getStartIdx() - MaxCandidateLen;
Jessica Paquette596f4832017-03-06 21:31:18 +00001217
Jessica Paquette97021442018-11-12 17:50:56 +00001218 MachineBasicBlock *C1MBB = C1.getMBB();
1219
Hiroshi Inoue0909ca12018-01-26 08:15:29 +00001220 // Compare against the candidates in the list that start at most
Jessica Paquetteacffa282017-03-23 21:27:38 +00001221 // FarthestPossibleIdx indices away from C1. There are at most
1222 // MaxCandidateLen of these.
Jessica Paquette596f4832017-03-06 21:31:18 +00001223 for (auto Sit = It + 1; Sit != Et; Sit++) {
Jessica Paquette9df7fde2017-10-23 23:36:46 +00001224 Candidate &C2 = **Sit;
Jessica Paquette596f4832017-03-06 21:31:18 +00001225
Jessica Paquette97021442018-11-12 17:50:56 +00001226 // If the two candidates don't belong to the same MBB, then we're done.
1227 // Because we sorted the candidates, there's no way that we'd find a
1228 // candidate in C1MBB after this point.
1229 if (C2.getMBB() != C1MBB)
1230 break;
1231
Jessica Paquette596f4832017-03-06 21:31:18 +00001232 // Is this candidate too far away to overlap?
Jessica Paquette1934fd22017-10-23 16:25:53 +00001233 if (C2.getStartIdx() < FarthestPossibleIdx)
Jessica Paquette596f4832017-03-06 21:31:18 +00001234 break;
1235
Jessica Paquette91999162017-09-28 23:39:36 +00001236 // If C2 was already pruned, or its function is no longer beneficial for
1237 // outlining, move to the next candidate.
1238 if (ShouldSkipCandidate(C2))
Jessica Paquette596f4832017-03-06 21:31:18 +00001239 continue;
1240
Jessica Paquette596f4832017-03-06 21:31:18 +00001241 // Do C1 and C2 overlap?
1242 //
1243 // Not overlapping:
1244 // High indices... [C1End ... C1Start][C2End ... C2Start] ...Low indices
1245 //
1246 // We sorted our candidate list so C2Start <= C1Start. We know that
1247 // C2End > C2Start since each candidate has length >= 2. Therefore, all we
1248 // have to check is C2End < C2Start to see if we overlap.
Jessica Paquette1934fd22017-10-23 16:25:53 +00001249 if (C2.getEndIdx() < C1.getStartIdx())
Jessica Paquette596f4832017-03-06 21:31:18 +00001250 continue;
1251
Jessica Paquetteacffa282017-03-23 21:27:38 +00001252 // C1 and C2 overlap.
1253 // We need to choose the better of the two.
1254 //
1255 // Approximate this by picking the one which would have saved us the
1256 // most instructions before any pruning.
Jessica Paquette60d31fc2017-10-17 21:11:58 +00001257
1258 // Is C2 a better candidate?
1259 if (C2.Benefit > C1.Benefit) {
1260 // Yes, so prune C1. Since C1 is dead, we don't have to compare it
1261 // against anything anymore, so break.
1262 prune(C1, FunctionList);
Jessica Paquetteacffa282017-03-23 21:27:38 +00001263 break;
1264 }
Jessica Paquette60d31fc2017-10-17 21:11:58 +00001265
1266 // Prune C2 and move on to the next candidate.
1267 prune(C2, FunctionList);
Jessica Paquette596f4832017-03-06 21:31:18 +00001268 }
1269 }
1270}
1271
Jessica Paquette9df7fde2017-10-23 23:36:46 +00001272unsigned MachineOutliner::buildCandidateList(
1273 std::vector<std::shared_ptr<Candidate>> &CandidateList,
Jessica Paquette39542722018-11-12 17:50:55 +00001274 std::vector<OutlinedFunction> &FunctionList,
Eli Friedmanda080782018-08-01 00:37:20 +00001275 InstructionMapper &Mapper) {
Jessica Paquette39542722018-11-12 17:50:55 +00001276 // Construct a suffix tree and use it to find candidates.
1277 SuffixTree ST(Mapper.UnsignedVec);
Jessica Paquette596f4832017-03-06 21:31:18 +00001278
1279 std::vector<unsigned> CandidateSequence; // Current outlining candidate.
Jessica Paquette4cf187b2017-09-27 20:47:39 +00001280 unsigned MaxCandidateLen = 0; // Length of the longest candidate.
Jessica Paquette596f4832017-03-06 21:31:18 +00001281
Jessica Paquette78681be2017-07-27 23:24:43 +00001282 MaxCandidateLen =
Eli Friedmanda080782018-08-01 00:37:20 +00001283 findCandidates(ST, Mapper, CandidateList, FunctionList);
Jessica Paquette596f4832017-03-06 21:31:18 +00001284
Jessica Paquette596f4832017-03-06 21:31:18 +00001285 // Sort the candidates in decending order. This will simplify the outlining
1286 // process when we have to remove the candidates from the mapping by
1287 // allowing us to cut them out without keeping track of an offset.
Jessica Paquette9df7fde2017-10-23 23:36:46 +00001288 std::stable_sort(
1289 CandidateList.begin(), CandidateList.end(),
1290 [](const std::shared_ptr<Candidate> &LHS,
1291 const std::shared_ptr<Candidate> &RHS) { return *LHS < *RHS; });
Jessica Paquette596f4832017-03-06 21:31:18 +00001292
1293 return MaxCandidateLen;
1294}
1295
1296MachineFunction *
1297MachineOutliner::createOutlinedFunction(Module &M, const OutlinedFunction &OF,
Jessica Paquettea3eb0fa2018-11-07 18:36:43 +00001298 InstructionMapper &Mapper,
1299 unsigned Name) {
Jessica Paquette596f4832017-03-06 21:31:18 +00001300
1301 // Create the function name. This should be unique. For now, just hash the
1302 // module name and include it in the function name plus the number of this
1303 // function.
1304 std::ostringstream NameStream;
Jessica Paquettea3eb0fa2018-11-07 18:36:43 +00001305 // FIXME: We should have a better naming scheme. This should be stable,
1306 // regardless of changes to the outliner's cost model/traversal order.
1307 NameStream << "OUTLINED_FUNCTION_" << Name;
Jessica Paquette596f4832017-03-06 21:31:18 +00001308
1309 // Create the function using an IR-level function.
1310 LLVMContext &C = M.getContext();
1311 Function *F = dyn_cast<Function>(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00001312 M.getOrInsertFunction(NameStream.str(), Type::getVoidTy(C)));
Jessica Paquette596f4832017-03-06 21:31:18 +00001313 assert(F && "Function was null!");
1314
1315 // NOTE: If this is linkonceodr, then we can take advantage of linker deduping
1316 // which gives us better results when we outline from linkonceodr functions.
Jessica Paquetted506bf82018-04-03 21:36:00 +00001317 F->setLinkage(GlobalValue::InternalLinkage);
Jessica Paquette596f4832017-03-06 21:31:18 +00001318 F->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
1319
Eli Friedman25bef202018-05-15 23:36:46 +00001320 // FIXME: Set nounwind, so we don't generate eh_frame? Haven't verified it's
1321 // necessary.
1322
1323 // Set optsize/minsize, so we don't insert padding between outlined
1324 // functions.
1325 F->addFnAttr(Attribute::OptimizeForSize);
1326 F->addFnAttr(Attribute::MinSize);
1327
Jessica Paquettee3932ee2018-10-29 20:27:07 +00001328 // Include target features from an arbitrary candidate for the outlined
1329 // function. This makes sure the outlined function knows what kinds of
1330 // instructions are going into it. This is fine, since all parent functions
1331 // must necessarily support the instructions that are in the outlined region.
1332 const Function &ParentFn = OF.Candidates.front()->getMF()->getFunction();
1333 if (ParentFn.hasFnAttribute("target-features"))
1334 F->addFnAttr(ParentFn.getFnAttribute("target-features"));
1335
Jessica Paquette596f4832017-03-06 21:31:18 +00001336 BasicBlock *EntryBB = BasicBlock::Create(C, "entry", F);
1337 IRBuilder<> Builder(EntryBB);
1338 Builder.CreateRetVoid();
1339
1340 MachineModuleInfo &MMI = getAnalysis<MachineModuleInfo>();
Matthias Braun7bda1952017-06-06 00:44:35 +00001341 MachineFunction &MF = MMI.getOrCreateMachineFunction(*F);
Jessica Paquette596f4832017-03-06 21:31:18 +00001342 MachineBasicBlock &MBB = *MF.CreateMachineBasicBlock();
1343 const TargetSubtargetInfo &STI = MF.getSubtarget();
1344 const TargetInstrInfo &TII = *STI.getInstrInfo();
1345
1346 // Insert the new function into the module.
1347 MF.insert(MF.begin(), &MBB);
1348
Jessica Paquette596f4832017-03-06 21:31:18 +00001349 // Copy over the instructions for the function using the integer mappings in
1350 // its sequence.
1351 for (unsigned Str : OF.Sequence) {
1352 MachineInstr *NewMI =
1353 MF.CloneMachineInstr(Mapper.IntegerInstructionMap.find(Str)->second);
Chandler Carruthc73c0302018-08-16 21:30:05 +00001354 NewMI->dropMemRefs(MF);
Jessica Paquette596f4832017-03-06 21:31:18 +00001355
1356 // Don't keep debug information for outlined instructions.
Jessica Paquette596f4832017-03-06 21:31:18 +00001357 NewMI->setDebugLoc(DebugLoc());
1358 MBB.insert(MBB.end(), NewMI);
1359 }
1360
Jessica Paquette69f517d2018-07-24 20:13:10 +00001361 TII.buildOutlinedFrame(MBB, MF, OF);
Jessica Paquette729e6862018-01-18 00:00:58 +00001362
Jessica Paquettecc06a782018-09-20 18:53:53 +00001363 // Outlined functions shouldn't preserve liveness.
1364 MF.getProperties().reset(MachineFunctionProperties::Property::TracksLiveness);
1365 MF.getRegInfo().freezeReservedRegs(MF);
1366
Jessica Paquettea499c3c2018-01-19 21:21:49 +00001367 // If there's a DISubprogram associated with this outlined function, then
1368 // emit debug info for the outlined function.
Jessica Paquetteaa087322018-06-04 21:14:16 +00001369 if (DISubprogram *SP = getSubprogramOrNull(OF)) {
Jessica Paquettea499c3c2018-01-19 21:21:49 +00001370 // We have a DISubprogram. Get its DICompileUnit.
1371 DICompileUnit *CU = SP->getUnit();
1372 DIBuilder DB(M, true, CU);
1373 DIFile *Unit = SP->getFile();
1374 Mangler Mg;
Jessica Paquettecc06a782018-09-20 18:53:53 +00001375 // Get the mangled name of the function for the linkage name.
1376 std::string Dummy;
1377 llvm::raw_string_ostream MangledNameStream(Dummy);
1378 Mg.getNameWithPrefix(MangledNameStream, F, false);
Jessica Paquettea499c3c2018-01-19 21:21:49 +00001379
Jessica Paquettecc06a782018-09-20 18:53:53 +00001380 DISubprogram *OutlinedSP = DB.createFunction(
1381 Unit /* Context */, F->getName(), StringRef(MangledNameStream.str()),
1382 Unit /* File */,
1383 0 /* Line 0 is reserved for compiler-generated code. */,
1384 DB.createSubroutineType(DB.getOrCreateTypeArray(None)), /* void type */
1385 false, true, 0, /* Line 0 is reserved for compiler-generated code. */
1386 DINode::DIFlags::FlagArtificial /* Compiler-generated code. */,
1387 true /* Outlined code is optimized code by definition. */);
Jessica Paquettea499c3c2018-01-19 21:21:49 +00001388
Jessica Paquettecc06a782018-09-20 18:53:53 +00001389 // Don't add any new variables to the subprogram.
1390 DB.finalizeSubprogram(OutlinedSP);
Jessica Paquettea499c3c2018-01-19 21:21:49 +00001391
Jessica Paquettecc06a782018-09-20 18:53:53 +00001392 // Attach subprogram to the function.
1393 F->setSubprogram(OutlinedSP);
Jessica Paquettea499c3c2018-01-19 21:21:49 +00001394 // We're done with the DIBuilder.
1395 DB.finalize();
1396 }
1397
Jessica Paquette596f4832017-03-06 21:31:18 +00001398 return &MF;
1399}
1400
Jessica Paquette9df7fde2017-10-23 23:36:46 +00001401bool MachineOutliner::outline(
1402 Module &M, const ArrayRef<std::shared_ptr<Candidate>> &CandidateList,
1403 std::vector<OutlinedFunction> &FunctionList, InstructionMapper &Mapper) {
Jessica Paquette596f4832017-03-06 21:31:18 +00001404
1405 bool OutlinedSomething = false;
Jessica Paquettea3eb0fa2018-11-07 18:36:43 +00001406
1407 // Number to append to the current outlined function.
1408 unsigned OutlinedFunctionNum = 0;
1409
Jessica Paquette596f4832017-03-06 21:31:18 +00001410 // Replace the candidates with calls to their respective outlined functions.
Jessica Paquette9df7fde2017-10-23 23:36:46 +00001411 for (const std::shared_ptr<Candidate> &Cptr : CandidateList) {
1412 Candidate &C = *Cptr;
Jessica Paquette596f4832017-03-06 21:31:18 +00001413 // Was the candidate removed during pruneOverlaps?
1414 if (!C.InCandidateList)
1415 continue;
1416
1417 // If not, then look at its OutlinedFunction.
1418 OutlinedFunction &OF = FunctionList[C.FunctionIdx];
1419
1420 // Was its OutlinedFunction made unbeneficial during pruneOverlaps?
Jessica Paquette85af63d2017-10-17 19:03:23 +00001421 if (OF.getBenefit() < 1)
Jessica Paquette596f4832017-03-06 21:31:18 +00001422 continue;
1423
Jessica Paquette596f4832017-03-06 21:31:18 +00001424 // Does this candidate have a function yet?
Jessica Paquetteacffa282017-03-23 21:27:38 +00001425 if (!OF.MF) {
Jessica Paquettea3eb0fa2018-11-07 18:36:43 +00001426 OF.MF = createOutlinedFunction(M, OF, Mapper, OutlinedFunctionNum);
Jessica Paquette58e706a2018-07-24 20:20:45 +00001427 emitOutlinedFunctionRemark(OF);
Jessica Paquetteacffa282017-03-23 21:27:38 +00001428 FunctionsCreated++;
Jessica Paquettea3eb0fa2018-11-07 18:36:43 +00001429 OutlinedFunctionNum++; // Created a function, move to the next name.
Jessica Paquetteacffa282017-03-23 21:27:38 +00001430 }
Jessica Paquette596f4832017-03-06 21:31:18 +00001431
1432 MachineFunction *MF = OF.MF;
Jessica Paquetteaa087322018-06-04 21:14:16 +00001433 MachineBasicBlock &MBB = *C.getMBB();
1434 MachineBasicBlock::iterator StartIt = C.front();
1435 MachineBasicBlock::iterator EndIt = C.back();
1436 assert(StartIt != C.getMBB()->end() && "StartIt out of bounds!");
1437 assert(EndIt != C.getMBB()->end() && "EndIt out of bounds!");
1438
Jessica Paquette596f4832017-03-06 21:31:18 +00001439 const TargetSubtargetInfo &STI = MF->getSubtarget();
1440 const TargetInstrInfo &TII = *STI.getInstrInfo();
1441
1442 // Insert a call to the new function and erase the old sequence.
Jessica Paquettefca55122018-07-24 17:42:11 +00001443 auto CallInst = TII.insertOutlinedCall(M, MBB, StartIt, *OF.MF, C);
Jessica Paquette596f4832017-03-06 21:31:18 +00001444
Jessica Paquette0b672492018-04-27 23:36:35 +00001445 // If the caller tracks liveness, then we need to make sure that anything
1446 // we outline doesn't break liveness assumptions.
1447 // The outlined functions themselves currently don't track liveness, but
1448 // we should make sure that the ranges we yank things out of aren't
1449 // wrong.
Jessica Paquetteaa087322018-06-04 21:14:16 +00001450 if (MBB.getParent()->getProperties().hasProperty(
Jessica Paquette0b672492018-04-27 23:36:35 +00001451 MachineFunctionProperties::Property::TracksLiveness)) {
1452 // Helper lambda for adding implicit def operands to the call instruction.
1453 auto CopyDefs = [&CallInst](MachineInstr &MI) {
1454 for (MachineOperand &MOP : MI.operands()) {
1455 // Skip over anything that isn't a register.
1456 if (!MOP.isReg())
1457 continue;
1458
1459 // If it's a def, add it to the call instruction.
1460 if (MOP.isDef())
1461 CallInst->addOperand(
1462 MachineOperand::CreateReg(MOP.getReg(), true, /* isDef = true */
1463 true /* isImp = true */));
1464 }
1465 };
1466
1467 // Copy over the defs in the outlined range.
1468 // First inst in outlined range <-- Anything that's defined in this
1469 // ... .. range has to be added as an implicit
1470 // Last inst in outlined range <-- def to the call instruction.
Francis Visoiu Mistrihf905bf12018-07-14 09:40:01 +00001471 std::for_each(CallInst, std::next(EndIt), CopyDefs);
Jessica Paquette0b672492018-04-27 23:36:35 +00001472 }
1473
Jessica Paquetteaa087322018-06-04 21:14:16 +00001474 // Erase from the point after where the call was inserted up to, and
1475 // including, the final instruction in the sequence.
1476 // Erase needs one past the end, so we need std::next there too.
1477 MBB.erase(std::next(StartIt), std::next(EndIt));
Jessica Paquette596f4832017-03-06 21:31:18 +00001478 OutlinedSomething = true;
1479
1480 // Statistics.
1481 NumOutlined++;
1482 }
1483
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001484 LLVM_DEBUG(dbgs() << "OutlinedSomething = " << OutlinedSomething << "\n";);
Jessica Paquette596f4832017-03-06 21:31:18 +00001485
1486 return OutlinedSomething;
1487}
1488
Jessica Paquette050d1ac2018-09-11 16:33:46 +00001489void MachineOutliner::populateMapper(InstructionMapper &Mapper, Module &M,
1490 MachineModuleInfo &MMI) {
Jessica Paquettedf822742018-03-22 21:07:09 +00001491 // Build instruction mappings for each function in the module. Start by
1492 // iterating over each Function in M.
Jessica Paquette596f4832017-03-06 21:31:18 +00001493 for (Function &F : M) {
Jessica Paquette596f4832017-03-06 21:31:18 +00001494
Jessica Paquettedf822742018-03-22 21:07:09 +00001495 // If there's nothing in F, then there's no reason to try and outline from
1496 // it.
1497 if (F.empty())
Jessica Paquette596f4832017-03-06 21:31:18 +00001498 continue;
1499
Jessica Paquettedf822742018-03-22 21:07:09 +00001500 // There's something in F. Check if it has a MachineFunction associated with
1501 // it.
1502 MachineFunction *MF = MMI.getMachineFunction(F);
Jessica Paquette596f4832017-03-06 21:31:18 +00001503
Jessica Paquettedf822742018-03-22 21:07:09 +00001504 // If it doesn't, then there's nothing to outline from. Move to the next
1505 // Function.
1506 if (!MF)
1507 continue;
1508
Eli Friedmanda080782018-08-01 00:37:20 +00001509 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
1510
Jessica Paquette8bda1882018-06-30 03:56:03 +00001511 if (!RunOnAllFunctions && !TII->shouldOutlineFromFunctionByDefault(*MF))
1512 continue;
1513
Jessica Paquettedf822742018-03-22 21:07:09 +00001514 // We have a MachineFunction. Ask the target if it's suitable for outlining.
1515 // If it isn't, then move on to the next Function in the module.
1516 if (!TII->isFunctionSafeToOutlineFrom(*MF, OutlineFromLinkOnceODRs))
1517 continue;
1518
1519 // We have a function suitable for outlining. Iterate over every
1520 // MachineBasicBlock in MF and try to map its instructions to a list of
1521 // unsigned integers.
1522 for (MachineBasicBlock &MBB : *MF) {
1523 // If there isn't anything in MBB, then there's no point in outlining from
1524 // it.
Jessica Paquetteb320ca22018-09-20 21:53:25 +00001525 // If there are fewer than 2 instructions in the MBB, then it can't ever
1526 // contain something worth outlining.
1527 // FIXME: This should be based off of the maximum size in B of an outlined
1528 // call versus the size in B of the MBB.
1529 if (MBB.empty() || MBB.size() < 2)
Jessica Paquette596f4832017-03-06 21:31:18 +00001530 continue;
1531
Jessica Paquettedf822742018-03-22 21:07:09 +00001532 // Check if MBB could be the target of an indirect branch. If it is, then
1533 // we don't want to outline from it.
1534 if (MBB.hasAddressTaken())
1535 continue;
1536
1537 // MBB is suitable for outlining. Map it to a list of unsigneds.
Eli Friedmanda080782018-08-01 00:37:20 +00001538 Mapper.convertToUnsignedVec(MBB, *TII);
Jessica Paquette596f4832017-03-06 21:31:18 +00001539 }
1540 }
Jessica Paquette050d1ac2018-09-11 16:33:46 +00001541}
1542
Jessica Paquette2386eab2018-09-11 23:05:34 +00001543void MachineOutliner::initSizeRemarkInfo(
1544 const Module &M, const MachineModuleInfo &MMI,
1545 StringMap<unsigned> &FunctionToInstrCount) {
1546 // Collect instruction counts for every function. We'll use this to emit
1547 // per-function size remarks later.
1548 for (const Function &F : M) {
1549 MachineFunction *MF = MMI.getMachineFunction(F);
1550
1551 // We only care about MI counts here. If there's no MachineFunction at this
1552 // point, then there won't be after the outliner runs, so let's move on.
1553 if (!MF)
1554 continue;
1555 FunctionToInstrCount[F.getName().str()] = MF->getInstructionCount();
1556 }
1557}
1558
1559void MachineOutliner::emitInstrCountChangedRemark(
1560 const Module &M, const MachineModuleInfo &MMI,
1561 const StringMap<unsigned> &FunctionToInstrCount) {
1562 // Iterate over each function in the module and emit remarks.
1563 // Note that we won't miss anything by doing this, because the outliner never
1564 // deletes functions.
1565 for (const Function &F : M) {
1566 MachineFunction *MF = MMI.getMachineFunction(F);
1567
1568 // The outliner never deletes functions. If we don't have a MF here, then we
1569 // didn't have one prior to outlining either.
1570 if (!MF)
1571 continue;
1572
1573 std::string Fname = F.getName();
1574 unsigned FnCountAfter = MF->getInstructionCount();
1575 unsigned FnCountBefore = 0;
1576
1577 // Check if the function was recorded before.
1578 auto It = FunctionToInstrCount.find(Fname);
1579
1580 // Did we have a previously-recorded size? If yes, then set FnCountBefore
1581 // to that.
1582 if (It != FunctionToInstrCount.end())
1583 FnCountBefore = It->second;
1584
1585 // Compute the delta and emit a remark if there was a change.
1586 int64_t FnDelta = static_cast<int64_t>(FnCountAfter) -
1587 static_cast<int64_t>(FnCountBefore);
1588 if (FnDelta == 0)
1589 continue;
1590
1591 MachineOptimizationRemarkEmitter MORE(*MF, nullptr);
1592 MORE.emit([&]() {
1593 MachineOptimizationRemarkAnalysis R("size-info", "FunctionMISizeChange",
1594 DiagnosticLocation(),
1595 &MF->front());
1596 R << DiagnosticInfoOptimizationBase::Argument("Pass", "Machine Outliner")
1597 << ": Function: "
1598 << DiagnosticInfoOptimizationBase::Argument("Function", F.getName())
1599 << ": MI instruction count changed from "
1600 << DiagnosticInfoOptimizationBase::Argument("MIInstrsBefore",
1601 FnCountBefore)
1602 << " to "
1603 << DiagnosticInfoOptimizationBase::Argument("MIInstrsAfter",
1604 FnCountAfter)
1605 << "; Delta: "
1606 << DiagnosticInfoOptimizationBase::Argument("Delta", FnDelta);
1607 return R;
1608 });
1609 }
1610}
1611
Jessica Paquette050d1ac2018-09-11 16:33:46 +00001612bool MachineOutliner::runOnModule(Module &M) {
1613 // Check if there's anything in the module. If it's empty, then there's
1614 // nothing to outline.
1615 if (M.empty())
1616 return false;
1617
1618 MachineModuleInfo &MMI = getAnalysis<MachineModuleInfo>();
1619
1620 // If the user passed -enable-machine-outliner=always or
1621 // -enable-machine-outliner, the pass will run on all functions in the module.
1622 // Otherwise, if the target supports default outlining, it will run on all
1623 // functions deemed by the target to be worth outlining from by default. Tell
1624 // the user how the outliner is running.
1625 LLVM_DEBUG(
1626 dbgs() << "Machine Outliner: Running on ";
1627 if (RunOnAllFunctions)
1628 dbgs() << "all functions";
1629 else
1630 dbgs() << "target-default functions";
1631 dbgs() << "\n"
1632 );
1633
1634 // If the user specifies that they want to outline from linkonceodrs, set
1635 // it here.
1636 OutlineFromLinkOnceODRs = EnableLinkOnceODROutlining;
1637 InstructionMapper Mapper;
1638
1639 // Prepare instruction mappings for the suffix tree.
1640 populateMapper(Mapper, M, MMI);
Jessica Paquette9df7fde2017-10-23 23:36:46 +00001641 std::vector<std::shared_ptr<Candidate>> CandidateList;
Jessica Paquette596f4832017-03-06 21:31:18 +00001642 std::vector<OutlinedFunction> FunctionList;
1643
Jessica Paquetteacffa282017-03-23 21:27:38 +00001644 // Find all of the outlining candidates.
Jessica Paquette596f4832017-03-06 21:31:18 +00001645 unsigned MaxCandidateLen =
Jessica Paquette39542722018-11-12 17:50:55 +00001646 buildCandidateList(CandidateList, FunctionList, Mapper);
Jessica Paquette596f4832017-03-06 21:31:18 +00001647
Jessica Paquetteacffa282017-03-23 21:27:38 +00001648 // Remove candidates that overlap with other candidates.
Eli Friedmanda080782018-08-01 00:37:20 +00001649 pruneOverlaps(CandidateList, FunctionList, Mapper, MaxCandidateLen);
Jessica Paquetteacffa282017-03-23 21:27:38 +00001650
Jessica Paquette2386eab2018-09-11 23:05:34 +00001651 // If we've requested size remarks, then collect the MI counts of every
1652 // function before outlining, and the MI counts after outlining.
1653 // FIXME: This shouldn't be in the outliner at all; it should ultimately be
1654 // the pass manager's responsibility.
1655 // This could pretty easily be placed in outline instead, but because we
1656 // really ultimately *don't* want this here, it's done like this for now
1657 // instead.
1658
1659 // Check if we want size remarks.
1660 bool ShouldEmitSizeRemarks = M.shouldEmitInstrCountChangedRemark();
1661 StringMap<unsigned> FunctionToInstrCount;
1662 if (ShouldEmitSizeRemarks)
1663 initSizeRemarkInfo(M, MMI, FunctionToInstrCount);
1664
Jessica Paquetteacffa282017-03-23 21:27:38 +00001665 // Outline each of the candidates and return true if something was outlined.
Jessica Paquette729e6862018-01-18 00:00:58 +00001666 bool OutlinedSomething = outline(M, CandidateList, FunctionList, Mapper);
1667
Jessica Paquette2386eab2018-09-11 23:05:34 +00001668 // If we outlined something, we definitely changed the MI count of the
1669 // module. If we've asked for size remarks, then output them.
1670 // FIXME: This should be in the pass manager.
1671 if (ShouldEmitSizeRemarks && OutlinedSomething)
1672 emitInstrCountChangedRemark(M, MMI, FunctionToInstrCount);
1673
Jessica Paquette729e6862018-01-18 00:00:58 +00001674 return OutlinedSomething;
Jessica Paquette596f4832017-03-06 21:31:18 +00001675}