blob: 458d949136c95cd14580bc262283ab8d69663a04 [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
167 /// The parent of this node. Every node except for the root has a parent.
168 SuffixTreeNode *Parent = nullptr;
169
Jessica Paquetteacffa282017-03-23 21:27:38 +0000170 /// The length of the string formed by concatenating the edge labels from the
171 /// root to this node.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000172 unsigned ConcatLen = 0;
Jessica Paquetteacffa282017-03-23 21:27:38 +0000173
Jessica Paquette596f4832017-03-06 21:31:18 +0000174 /// Returns true if this node is a leaf.
175 bool isLeaf() const { return SuffixIdx != EmptyIdx; }
176
177 /// Returns true if this node is the root of its owning \p SuffixTree.
178 bool isRoot() const { return StartIdx == EmptyIdx; }
179
180 /// Return the number of elements in the substring associated with this node.
181 size_t size() const {
182
183 // Is it the root? If so, it's the empty string so return 0.
184 if (isRoot())
185 return 0;
186
187 assert(*EndIdx != EmptyIdx && "EndIdx is undefined!");
188
189 // Size = the number of elements in the string.
190 // For example, [0 1 2 3] has length 4, not 3. 3-0 = 3, so we have 3-0+1.
191 return *EndIdx - StartIdx + 1;
192 }
193
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000194 SuffixTreeNode(unsigned StartIdx, unsigned *EndIdx, SuffixTreeNode *Link,
Jessica Paquette596f4832017-03-06 21:31:18 +0000195 SuffixTreeNode *Parent)
196 : StartIdx(StartIdx), EndIdx(EndIdx), Link(Link), Parent(Parent) {}
197
198 SuffixTreeNode() {}
199};
200
201/// A data structure for fast substring queries.
202///
203/// Suffix trees represent the suffixes of their input strings in their leaves.
204/// A suffix tree is a type of compressed trie structure where each node
205/// represents an entire substring rather than a single character. Each leaf
206/// of the tree is a suffix.
207///
208/// A suffix tree can be seen as a type of state machine where each state is a
209/// substring of the full string. The tree is structured so that, for a string
210/// of length N, there are exactly N leaves in the tree. This structure allows
211/// us to quickly find repeated substrings of the input string.
212///
213/// In this implementation, a "string" is a vector of unsigned integers.
214/// These integers may result from hashing some data type. A suffix tree can
215/// contain 1 or many strings, which can then be queried as one large string.
216///
217/// The suffix tree is implemented using Ukkonen's algorithm for linear-time
218/// suffix tree construction. Ukkonen's algorithm is explained in more detail
219/// in the paper by Esko Ukkonen "On-line construction of suffix trees. The
220/// paper is available at
221///
222/// https://www.cs.helsinki.fi/u/ukkonen/SuffixT1withFigs.pdf
223class SuffixTree {
Jessica Paquette78681be2017-07-27 23:24:43 +0000224public:
Jessica Paquette596f4832017-03-06 21:31:18 +0000225 /// Each element is an integer representing an instruction in the module.
226 ArrayRef<unsigned> Str;
227
Jessica Paquette4e54ef82018-11-06 21:46:41 +0000228 /// A repeated substring in the tree.
229 struct RepeatedSubstring {
230 /// The length of the string.
231 unsigned Length;
232
233 /// The start indices of each occurrence.
234 std::vector<unsigned> StartIndices;
235 };
236
Jessica Paquette78681be2017-07-27 23:24:43 +0000237private:
Jessica Paquette596f4832017-03-06 21:31:18 +0000238 /// Maintains each node in the tree.
Jessica Paquetted4cb9c62017-03-08 23:55:33 +0000239 SpecificBumpPtrAllocator<SuffixTreeNode> NodeAllocator;
Jessica Paquette596f4832017-03-06 21:31:18 +0000240
241 /// The root of the suffix tree.
242 ///
243 /// The root represents the empty string. It is maintained by the
244 /// \p NodeAllocator like every other node in the tree.
245 SuffixTreeNode *Root = nullptr;
246
Jessica Paquette596f4832017-03-06 21:31:18 +0000247 /// Maintains the end indices of the internal nodes in the tree.
248 ///
249 /// Each internal node is guaranteed to never have its end index change
250 /// during the construction algorithm; however, leaves must be updated at
251 /// every step. Therefore, we need to store leaf end indices by reference
252 /// to avoid updating O(N) leaves at every step of construction. Thus,
253 /// every internal node must be allocated its own end index.
254 BumpPtrAllocator InternalEndIdxAllocator;
255
256 /// The end index of each leaf in the tree.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000257 unsigned LeafEndIdx = -1;
Jessica Paquette596f4832017-03-06 21:31:18 +0000258
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000259 /// Helper struct which keeps track of the next insertion point in
Jessica Paquette596f4832017-03-06 21:31:18 +0000260 /// Ukkonen's algorithm.
261 struct ActiveState {
262 /// The next node to insert at.
263 SuffixTreeNode *Node;
264
265 /// The index of the first character in the substring currently being added.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000266 unsigned Idx = EmptyIdx;
Jessica Paquette596f4832017-03-06 21:31:18 +0000267
268 /// The length of the substring we have to add at the current step.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000269 unsigned Len = 0;
Jessica Paquette596f4832017-03-06 21:31:18 +0000270 };
271
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000272 /// The point the next insertion will take place at in the
Jessica Paquette596f4832017-03-06 21:31:18 +0000273 /// construction algorithm.
274 ActiveState Active;
275
276 /// Allocate a leaf node and add it to the tree.
277 ///
278 /// \param Parent The parent of this node.
279 /// \param StartIdx The start index of this node's associated string.
280 /// \param Edge The label on the edge leaving \p Parent to this node.
281 ///
282 /// \returns A pointer to the allocated leaf node.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000283 SuffixTreeNode *insertLeaf(SuffixTreeNode &Parent, unsigned StartIdx,
Jessica Paquette596f4832017-03-06 21:31:18 +0000284 unsigned Edge) {
285
286 assert(StartIdx <= LeafEndIdx && "String can't start after it ends!");
287
Jessica Paquette78681be2017-07-27 23:24:43 +0000288 SuffixTreeNode *N = new (NodeAllocator.Allocate())
289 SuffixTreeNode(StartIdx, &LeafEndIdx, nullptr, &Parent);
Jessica Paquette596f4832017-03-06 21:31:18 +0000290 Parent.Children[Edge] = N;
291
292 return N;
293 }
294
295 /// Allocate an internal node and add it to the tree.
296 ///
297 /// \param Parent The parent of this node. Only null when allocating the root.
298 /// \param StartIdx The start index of this node's associated string.
299 /// \param EndIdx The end index of this node's associated string.
300 /// \param Edge The label on the edge leaving \p Parent to this node.
301 ///
302 /// \returns A pointer to the allocated internal node.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000303 SuffixTreeNode *insertInternalNode(SuffixTreeNode *Parent, unsigned StartIdx,
304 unsigned EndIdx, unsigned Edge) {
Jessica Paquette596f4832017-03-06 21:31:18 +0000305
306 assert(StartIdx <= EndIdx && "String can't start after it ends!");
307 assert(!(!Parent && StartIdx != EmptyIdx) &&
Jessica Paquette78681be2017-07-27 23:24:43 +0000308 "Non-root internal nodes must have parents!");
Jessica Paquette596f4832017-03-06 21:31:18 +0000309
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000310 unsigned *E = new (InternalEndIdxAllocator) unsigned(EndIdx);
Jessica Paquette78681be2017-07-27 23:24:43 +0000311 SuffixTreeNode *N = new (NodeAllocator.Allocate())
312 SuffixTreeNode(StartIdx, E, Root, Parent);
Jessica Paquette596f4832017-03-06 21:31:18 +0000313 if (Parent)
314 Parent->Children[Edge] = N;
315
316 return N;
317 }
318
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000319 /// Set the suffix indices of the leaves to the start indices of their
Jessica Paquette4e54ef82018-11-06 21:46:41 +0000320 /// respective suffixes.
Jessica Paquette596f4832017-03-06 21:31:18 +0000321 ///
322 /// \param[in] CurrNode The node currently being visited.
323 /// \param CurrIdx The current index of the string being visited.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000324 void setSuffixIndices(SuffixTreeNode &CurrNode, unsigned CurrIdx) {
Jessica Paquette596f4832017-03-06 21:31:18 +0000325
326 bool IsLeaf = CurrNode.Children.size() == 0 && !CurrNode.isRoot();
327
Jessica Paquetteacffa282017-03-23 21:27:38 +0000328 // Store the length of the concatenation of all strings from the root to
329 // this node.
330 if (!CurrNode.isRoot()) {
331 if (CurrNode.ConcatLen == 0)
332 CurrNode.ConcatLen = CurrNode.size();
333
334 if (CurrNode.Parent)
Jessica Paquette78681be2017-07-27 23:24:43 +0000335 CurrNode.ConcatLen += CurrNode.Parent->ConcatLen;
Jessica Paquetteacffa282017-03-23 21:27:38 +0000336 }
337
Jessica Paquette596f4832017-03-06 21:31:18 +0000338 // Traverse the tree depth-first.
339 for (auto &ChildPair : CurrNode.Children) {
340 assert(ChildPair.second && "Node had a null child!");
Jessica Paquette78681be2017-07-27 23:24:43 +0000341 setSuffixIndices(*ChildPair.second, CurrIdx + ChildPair.second->size());
Jessica Paquette596f4832017-03-06 21:31:18 +0000342 }
343
344 // Is this node a leaf?
345 if (IsLeaf) {
346 // If yes, give it a suffix index and bump its parent's occurrence count.
347 CurrNode.SuffixIdx = Str.size() - CurrIdx;
348 assert(CurrNode.Parent && "CurrNode had no parent!");
Jessica Paquette596f4832017-03-06 21:31:18 +0000349 }
350 }
351
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000352 /// Construct the suffix tree for the prefix of the input ending at
Jessica Paquette596f4832017-03-06 21:31:18 +0000353 /// \p EndIdx.
354 ///
355 /// Used to construct the full suffix tree iteratively. At the end of each
356 /// step, the constructed suffix tree is either a valid suffix tree, or a
357 /// suffix tree with implicit suffixes. At the end of the final step, the
358 /// suffix tree is a valid tree.
359 ///
360 /// \param EndIdx The end index of the current prefix in the main string.
361 /// \param SuffixesToAdd The number of suffixes that must be added
362 /// to complete the suffix tree at the current phase.
363 ///
364 /// \returns The number of suffixes that have not been added at the end of
365 /// this step.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000366 unsigned extend(unsigned EndIdx, unsigned SuffixesToAdd) {
Jessica Paquette596f4832017-03-06 21:31:18 +0000367 SuffixTreeNode *NeedsLink = nullptr;
368
369 while (SuffixesToAdd > 0) {
Jessica Paquette78681be2017-07-27 23:24:43 +0000370
Jessica Paquette596f4832017-03-06 21:31:18 +0000371 // Are we waiting to add anything other than just the last character?
372 if (Active.Len == 0) {
373 // If not, then say the active index is the end index.
374 Active.Idx = EndIdx;
375 }
376
377 assert(Active.Idx <= EndIdx && "Start index can't be after end index!");
378
379 // The first character in the current substring we're looking at.
380 unsigned FirstChar = Str[Active.Idx];
381
382 // Have we inserted anything starting with FirstChar at the current node?
383 if (Active.Node->Children.count(FirstChar) == 0) {
384 // If not, then we can just insert a leaf and move too the next step.
385 insertLeaf(*Active.Node, EndIdx, FirstChar);
386
387 // The active node is an internal node, and we visited it, so it must
388 // need a link if it doesn't have one.
389 if (NeedsLink) {
390 NeedsLink->Link = Active.Node;
391 NeedsLink = nullptr;
392 }
393 } else {
394 // There's a match with FirstChar, so look for the point in the tree to
395 // insert a new node.
396 SuffixTreeNode *NextNode = Active.Node->Children[FirstChar];
397
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000398 unsigned SubstringLen = NextNode->size();
Jessica Paquette596f4832017-03-06 21:31:18 +0000399
400 // Is the current suffix we're trying to insert longer than the size of
401 // the child we want to move to?
402 if (Active.Len >= SubstringLen) {
403 // If yes, then consume the characters we've seen and move to the next
404 // node.
405 Active.Idx += SubstringLen;
406 Active.Len -= SubstringLen;
407 Active.Node = NextNode;
408 continue;
409 }
410
411 // Otherwise, the suffix we're trying to insert must be contained in the
412 // next node we want to move to.
413 unsigned LastChar = Str[EndIdx];
414
415 // Is the string we're trying to insert a substring of the next node?
416 if (Str[NextNode->StartIdx + Active.Len] == LastChar) {
417 // If yes, then we're done for this step. Remember our insertion point
418 // and move to the next end index. At this point, we have an implicit
419 // suffix tree.
420 if (NeedsLink && !Active.Node->isRoot()) {
421 NeedsLink->Link = Active.Node;
422 NeedsLink = nullptr;
423 }
424
425 Active.Len++;
426 break;
427 }
428
429 // The string we're trying to insert isn't a substring of the next node,
430 // but matches up to a point. Split the node.
431 //
432 // For example, say we ended our search at a node n and we're trying to
433 // insert ABD. Then we'll create a new node s for AB, reduce n to just
434 // representing C, and insert a new leaf node l to represent d. This
435 // allows us to ensure that if n was a leaf, it remains a leaf.
436 //
437 // | ABC ---split---> | AB
438 // n s
439 // C / \ D
440 // n l
441
442 // The node s from the diagram
443 SuffixTreeNode *SplitNode =
Jessica Paquette78681be2017-07-27 23:24:43 +0000444 insertInternalNode(Active.Node, NextNode->StartIdx,
445 NextNode->StartIdx + Active.Len - 1, FirstChar);
Jessica Paquette596f4832017-03-06 21:31:18 +0000446
447 // Insert the new node representing the new substring into the tree as
448 // a child of the split node. This is the node l from the diagram.
449 insertLeaf(*SplitNode, EndIdx, LastChar);
450
451 // Make the old node a child of the split node and update its start
452 // index. This is the node n from the diagram.
453 NextNode->StartIdx += Active.Len;
454 NextNode->Parent = SplitNode;
455 SplitNode->Children[Str[NextNode->StartIdx]] = NextNode;
456
457 // SplitNode is an internal node, update the suffix link.
458 if (NeedsLink)
459 NeedsLink->Link = SplitNode;
460
461 NeedsLink = SplitNode;
462 }
463
464 // We've added something new to the tree, so there's one less suffix to
465 // add.
466 SuffixesToAdd--;
467
468 if (Active.Node->isRoot()) {
469 if (Active.Len > 0) {
470 Active.Len--;
471 Active.Idx = EndIdx - SuffixesToAdd + 1;
472 }
473 } else {
474 // Start the next phase at the next smallest suffix.
475 Active.Node = Active.Node->Link;
476 }
477 }
478
479 return SuffixesToAdd;
480 }
481
Jessica Paquette596f4832017-03-06 21:31:18 +0000482public:
Jessica Paquette596f4832017-03-06 21:31:18 +0000483 /// Construct a suffix tree from a sequence of unsigned integers.
484 ///
485 /// \param Str The string to construct the suffix tree for.
486 SuffixTree(const std::vector<unsigned> &Str) : Str(Str) {
487 Root = insertInternalNode(nullptr, EmptyIdx, EmptyIdx, 0);
Jessica Paquette596f4832017-03-06 21:31:18 +0000488 Active.Node = Root;
Jessica Paquette596f4832017-03-06 21:31:18 +0000489
490 // Keep track of the number of suffixes we have to add of the current
491 // prefix.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000492 unsigned SuffixesToAdd = 0;
Jessica Paquette596f4832017-03-06 21:31:18 +0000493 Active.Node = Root;
494
495 // Construct the suffix tree iteratively on each prefix of the string.
496 // PfxEndIdx is the end index of the current prefix.
497 // End is one past the last element in the string.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000498 for (unsigned PfxEndIdx = 0, End = Str.size(); PfxEndIdx < End;
499 PfxEndIdx++) {
Jessica Paquette596f4832017-03-06 21:31:18 +0000500 SuffixesToAdd++;
501 LeafEndIdx = PfxEndIdx; // Extend each of the leaves.
502 SuffixesToAdd = extend(PfxEndIdx, SuffixesToAdd);
503 }
504
505 // Set the suffix indices of each leaf.
506 assert(Root && "Root node can't be nullptr!");
507 setSuffixIndices(*Root, 0);
508 }
Jessica Paquette4e54ef82018-11-06 21:46:41 +0000509
Jessica Paquettea409cc92018-11-07 19:20:55 +0000510
511 /// Iterator for finding all repeated substrings in the suffix tree.
512 struct RepeatedSubstringIterator {
513 private:
514 /// The current node we're visiting.
515 SuffixTreeNode *N = nullptr;
516
517 /// The repeated substring associated with this node.
518 RepeatedSubstring RS;
519
520 /// The nodes left to visit.
521 std::vector<SuffixTreeNode *> ToVisit;
522
523 /// The minimum length of a repeated substring to find.
524 /// Since we're outlining, we want at least two instructions in the range.
525 /// FIXME: This may not be true for targets like X86 which support many
526 /// instruction lengths.
527 const unsigned MinLength = 2;
528
529 /// Move the iterator to the next repeated substring.
530 void advance() {
531 // Clear the current state. If we're at the end of the range, then this
532 // is the state we want to be in.
533 RS = RepeatedSubstring();
534 N = nullptr;
535
536 // Continue visiting nodes until we find one which repeats more than once.
537 while (!ToVisit.empty()) {
538 SuffixTreeNode *Curr = ToVisit.back();
539 ToVisit.pop_back();
540
541 // Keep track of the length of the string associated with the node. If
542 // it's too short, we'll quit.
543 unsigned Length = Curr->ConcatLen;
544
545 // Each leaf node represents a repeat of a string.
546 std::vector<SuffixTreeNode *> LeafChildren;
547
548 // Iterate over each child, saving internal nodes for visiting, and
549 // leaf nodes in LeafChildren. Internal nodes represent individual
550 // strings, which may repeat.
551 for (auto &ChildPair : Curr->Children) {
552 // Save all of this node's children for processing.
553 if (!ChildPair.second->isLeaf())
554 ToVisit.push_back(ChildPair.second);
555
556 // It's not an internal node, so it must be a leaf. If we have a
557 // long enough string, then save the leaf children.
558 else if (Length >= MinLength)
559 LeafChildren.push_back(ChildPair.second);
560 }
561
562 // The root never represents a repeated substring. If we're looking at
563 // that, then skip it.
564 if (Curr->isRoot())
565 continue;
566
567 // Do we have any repeated substrings?
568 if (LeafChildren.size() >= 2) {
569 // Yes. Update the state to reflect this, and then bail out.
570 N = Curr;
571 RS.Length = Length;
572 for (SuffixTreeNode *Leaf : LeafChildren)
573 RS.StartIndices.push_back(Leaf->SuffixIdx);
574 break;
575 }
576 }
577
578 // At this point, either NewRS is an empty RepeatedSubstring, or it was
579 // set in the above loop. Similarly, N is either nullptr, or the node
580 // associated with NewRS.
581 }
582
583 public:
584 /// Return the current repeated substring.
585 RepeatedSubstring &operator*() { return RS; }
586
587 RepeatedSubstringIterator &operator++() {
588 advance();
589 return *this;
590 }
591
592 RepeatedSubstringIterator operator++(int I) {
593 RepeatedSubstringIterator It(*this);
594 advance();
595 return It;
596 }
597
598 bool operator==(const RepeatedSubstringIterator &Other) {
599 return N == Other.N;
600 }
601 bool operator!=(const RepeatedSubstringIterator &Other) {
602 return !(*this == Other);
603 }
604
605 RepeatedSubstringIterator(SuffixTreeNode *N) : N(N) {
606 // Do we have a non-null node?
607 if (N) {
608 // Yes. At the first step, we need to visit all of N's children.
609 // Note: This means that we visit N last.
610 ToVisit.push_back(N);
611 advance();
612 }
613 }
614};
615
616 typedef RepeatedSubstringIterator iterator;
617 iterator begin() { return iterator(Root); }
618 iterator end() { return iterator(nullptr); }
Jessica Paquette596f4832017-03-06 21:31:18 +0000619};
620
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000621/// Maps \p MachineInstrs to unsigned integers and stores the mappings.
Jessica Paquette596f4832017-03-06 21:31:18 +0000622struct InstructionMapper {
623
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000624 /// The next available integer to assign to a \p MachineInstr that
Jessica Paquette596f4832017-03-06 21:31:18 +0000625 /// cannot be outlined.
626 ///
627 /// Set to -3 for compatability with \p DenseMapInfo<unsigned>.
628 unsigned IllegalInstrNumber = -3;
629
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000630 /// The next available integer to assign to a \p MachineInstr that can
Jessica Paquette596f4832017-03-06 21:31:18 +0000631 /// be outlined.
632 unsigned LegalInstrNumber = 0;
633
634 /// Correspondence from \p MachineInstrs to unsigned integers.
635 DenseMap<MachineInstr *, unsigned, MachineInstrExpressionTrait>
636 InstructionIntegerMap;
637
638 /// Corresponcence from unsigned integers to \p MachineInstrs.
639 /// Inverse of \p InstructionIntegerMap.
640 DenseMap<unsigned, MachineInstr *> IntegerInstructionMap;
641
642 /// The vector of unsigned integers that the module is mapped to.
643 std::vector<unsigned> UnsignedVec;
644
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000645 /// Stores the location of the instruction associated with the integer
Jessica Paquette596f4832017-03-06 21:31:18 +0000646 /// at index i in \p UnsignedVec for each index i.
647 std::vector<MachineBasicBlock::iterator> InstrList;
648
Jessica Paquettec991cf32018-11-01 23:09:06 +0000649 // Set if we added an illegal number in the previous step.
650 // Since each illegal number is unique, we only need one of them between
651 // each range of legal numbers. This lets us make sure we don't add more
652 // than one illegal number per range.
653 bool AddedIllegalLastTime = false;
654
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000655 /// Maps \p *It to a legal integer.
Jessica Paquette596f4832017-03-06 21:31:18 +0000656 ///
657 /// Updates \p InstrList, \p UnsignedVec, \p InstructionIntegerMap,
658 /// \p IntegerInstructionMap, and \p LegalInstrNumber.
659 ///
660 /// \returns The integer that \p *It was mapped to.
661 unsigned mapToLegalUnsigned(MachineBasicBlock::iterator &It) {
Jessica Paquettec991cf32018-11-01 23:09:06 +0000662 // We added something legal, so we should unset the AddedLegalLastTime
663 // flag.
664 AddedIllegalLastTime = false;
Jessica Paquette596f4832017-03-06 21:31:18 +0000665
666 // Get the integer for this instruction or give it the current
667 // LegalInstrNumber.
668 InstrList.push_back(It);
669 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
683 UnsignedVec.push_back(MINumber);
684
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 ///
699 /// Updates \p InstrList, \p UnsignedVec, and \p IllegalInstrNumber.
700 ///
701 /// \returns The integer that \p *It was mapped to.
702 unsigned mapToIllegalUnsigned(MachineBasicBlock::iterator &It) {
Jessica Paquettec991cf32018-11-01 23:09:06 +0000703 // Only add one illegal number per range of legal numbers.
704 if (AddedIllegalLastTime)
705 return IllegalInstrNumber;
706
707 // Remember that we added an illegal number last time.
708 AddedIllegalLastTime = true;
Jessica Paquette596f4832017-03-06 21:31:18 +0000709 unsigned MINumber = IllegalInstrNumber;
710
711 InstrList.push_back(It);
712 UnsignedVec.push_back(IllegalInstrNumber);
713 IllegalInstrNumber--;
714
715 assert(LegalInstrNumber < IllegalInstrNumber &&
716 "Instruction mapping overflow!");
717
Jessica Paquette78681be2017-07-27 23:24:43 +0000718 assert(IllegalInstrNumber != DenseMapInfo<unsigned>::getEmptyKey() &&
719 "IllegalInstrNumber cannot be DenseMap tombstone or empty key!");
Jessica Paquette596f4832017-03-06 21:31:18 +0000720
Jessica Paquette78681be2017-07-27 23:24:43 +0000721 assert(IllegalInstrNumber != DenseMapInfo<unsigned>::getTombstoneKey() &&
722 "IllegalInstrNumber cannot be DenseMap tombstone or empty key!");
Jessica Paquette596f4832017-03-06 21:31:18 +0000723
724 return MINumber;
725 }
726
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000727 /// Transforms a \p MachineBasicBlock into a \p vector of \p unsigneds
Jessica Paquette596f4832017-03-06 21:31:18 +0000728 /// and appends it to \p UnsignedVec and \p InstrList.
729 ///
730 /// Two instructions are assigned the same integer if they are identical.
731 /// If an instruction is deemed unsafe to outline, then it will be assigned an
732 /// unique integer. The resulting mapping is placed into a suffix tree and
733 /// queried for candidates.
734 ///
735 /// \param MBB The \p MachineBasicBlock to be translated into integers.
Eli Friedmanda080782018-08-01 00:37:20 +0000736 /// \param TII \p TargetInstrInfo for the function.
Jessica Paquette596f4832017-03-06 21:31:18 +0000737 void convertToUnsignedVec(MachineBasicBlock &MBB,
Jessica Paquette596f4832017-03-06 21:31:18 +0000738 const TargetInstrInfo &TII) {
Jessica Paquette3291e732018-01-09 00:26:18 +0000739 unsigned Flags = TII.getMachineOutlinerMBBFlags(MBB);
Jessica Paquettec991cf32018-11-01 23:09:06 +0000740 MachineBasicBlock::iterator It = MBB.begin();
741 for (MachineBasicBlock::iterator Et = MBB.end(); It != Et; It++) {
Jessica Paquette596f4832017-03-06 21:31:18 +0000742 // Keep track of where this instruction is in the module.
Jessica Paquette3291e732018-01-09 00:26:18 +0000743 switch (TII.getOutliningType(It, Flags)) {
Jessica Paquetteaa087322018-06-04 21:14:16 +0000744 case InstrType::Illegal:
Jessica Paquette78681be2017-07-27 23:24:43 +0000745 mapToIllegalUnsigned(It);
746 break;
Jessica Paquette596f4832017-03-06 21:31:18 +0000747
Jessica Paquetteaa087322018-06-04 21:14:16 +0000748 case InstrType::Legal:
Jessica Paquette78681be2017-07-27 23:24:43 +0000749 mapToLegalUnsigned(It);
750 break;
Jessica Paquette596f4832017-03-06 21:31:18 +0000751
Jessica Paquetteaa087322018-06-04 21:14:16 +0000752 case InstrType::LegalTerminator:
Eli Friedman042dc9e2018-05-22 19:11:06 +0000753 mapToLegalUnsigned(It);
Jessica Paquettec991cf32018-11-01 23:09:06 +0000754 // The instruction also acts as a terminator, so we have to record that
755 // in the string.
756 mapToIllegalUnsigned(It);
Eli Friedman042dc9e2018-05-22 19:11:06 +0000757 break;
758
Jessica Paquetteaa087322018-06-04 21:14:16 +0000759 case InstrType::Invisible:
Jessica Paquettec991cf32018-11-01 23:09:06 +0000760 // Normally this is set by mapTo(Blah)Unsigned, but we just want to
761 // skip this instruction. So, unset the flag here.
Jessica Paquettebd729882018-09-17 18:40:21 +0000762 AddedIllegalLastTime = false;
Jessica Paquette78681be2017-07-27 23:24:43 +0000763 break;
Jessica Paquette596f4832017-03-06 21:31:18 +0000764 }
765 }
766
767 // After we're done every insertion, uniquely terminate this part of the
768 // "string". This makes sure we won't match across basic block or function
769 // boundaries since the "end" is encoded uniquely and thus appears in no
770 // repeated substring.
Jessica Paquettec991cf32018-11-01 23:09:06 +0000771 mapToIllegalUnsigned(It);
Jessica Paquette596f4832017-03-06 21:31:18 +0000772 }
773
774 InstructionMapper() {
775 // Make sure that the implementation of DenseMapInfo<unsigned> hasn't
776 // changed.
777 assert(DenseMapInfo<unsigned>::getEmptyKey() == (unsigned)-1 &&
Jessica Paquette78681be2017-07-27 23:24:43 +0000778 "DenseMapInfo<unsigned>'s empty key isn't -1!");
Jessica Paquette596f4832017-03-06 21:31:18 +0000779 assert(DenseMapInfo<unsigned>::getTombstoneKey() == (unsigned)-2 &&
Jessica Paquette78681be2017-07-27 23:24:43 +0000780 "DenseMapInfo<unsigned>'s tombstone key isn't -2!");
Jessica Paquette596f4832017-03-06 21:31:18 +0000781 }
782};
783
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000784/// An interprocedural pass which finds repeated sequences of
Jessica Paquette596f4832017-03-06 21:31:18 +0000785/// instructions and replaces them with calls to functions.
786///
787/// Each instruction is mapped to an unsigned integer and placed in a string.
788/// The resulting mapping is then placed in a \p SuffixTree. The \p SuffixTree
789/// is then repeatedly queried for repeated sequences of instructions. Each
790/// non-overlapping repeated sequence is then placed in its own
791/// \p MachineFunction and each instance is then replaced with a call to that
792/// function.
793struct MachineOutliner : public ModulePass {
794
795 static char ID;
796
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000797 /// Set to true if the outliner should consider functions with
Jessica Paquette13593842017-10-07 00:16:34 +0000798 /// linkonceodr linkage.
799 bool OutlineFromLinkOnceODRs = false;
800
Jessica Paquette8bda1882018-06-30 03:56:03 +0000801 /// Set to true if the outliner should run on all functions in the module
802 /// considered safe for outlining.
803 /// Set to true by default for compatibility with llc's -run-pass option.
804 /// Set when the pass is constructed in TargetPassConfig.
805 bool RunOnAllFunctions = true;
806
Jessica Paquette596f4832017-03-06 21:31:18 +0000807 StringRef getPassName() const override { return "Machine Outliner"; }
808
809 void getAnalysisUsage(AnalysisUsage &AU) const override {
810 AU.addRequired<MachineModuleInfo>();
811 AU.addPreserved<MachineModuleInfo>();
812 AU.setPreservesAll();
813 ModulePass::getAnalysisUsage(AU);
814 }
815
Jessica Paquette1eca23b2018-04-19 22:17:07 +0000816 MachineOutliner() : ModulePass(ID) {
Jessica Paquette596f4832017-03-06 21:31:18 +0000817 initializeMachineOutlinerPass(*PassRegistry::getPassRegistry());
818 }
819
Jessica Paquette1cc52a02018-07-24 17:37:28 +0000820 /// Remark output explaining that not outlining a set of candidates would be
821 /// better than outlining that set.
822 void emitNotOutliningCheaperRemark(
823 unsigned StringLen, std::vector<Candidate> &CandidatesForRepeatedSeq,
824 OutlinedFunction &OF);
825
Jessica Paquette58e706a2018-07-24 20:20:45 +0000826 /// Remark output explaining that a function was outlined.
827 void emitOutlinedFunctionRemark(OutlinedFunction &OF);
828
Jessica Paquette78681be2017-07-27 23:24:43 +0000829 /// Find all repeated substrings that satisfy the outlining cost model.
830 ///
831 /// If a substring appears at least twice, then it must be represented by
Jessica Paquette1cc52a02018-07-24 17:37:28 +0000832 /// an internal node which appears in at least two suffixes. Each suffix
833 /// is represented by a leaf node. To do this, we visit each internal node
834 /// in the tree, using the leaf children of each internal node. If an
835 /// internal node represents a beneficial substring, then we use each of
836 /// its leaf children to find the locations of its substring.
Jessica Paquette78681be2017-07-27 23:24:43 +0000837 ///
838 /// \param ST A suffix tree to query.
Jessica Paquette78681be2017-07-27 23:24:43 +0000839 /// \param Mapper Contains outlining mapping information.
840 /// \param[out] CandidateList Filled with candidates representing each
841 /// beneficial substring.
Jessica Paquette1cc52a02018-07-24 17:37:28 +0000842 /// \param[out] FunctionList Filled with a list of \p OutlinedFunctions
843 /// each type of candidate.
Jessica Paquette78681be2017-07-27 23:24:43 +0000844 ///
845 /// \returns The length of the longest candidate found.
Jessica Paquette9df7fde2017-10-23 23:36:46 +0000846 unsigned
Eli Friedmanda080782018-08-01 00:37:20 +0000847 findCandidates(SuffixTree &ST,
Jessica Paquette9df7fde2017-10-23 23:36:46 +0000848 InstructionMapper &Mapper,
849 std::vector<std::shared_ptr<Candidate>> &CandidateList,
850 std::vector<OutlinedFunction> &FunctionList);
Jessica Paquette78681be2017-07-27 23:24:43 +0000851
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000852 /// Replace the sequences of instructions represented by the
Jessica Paquette596f4832017-03-06 21:31:18 +0000853 /// \p Candidates in \p CandidateList with calls to \p MachineFunctions
854 /// described in \p FunctionList.
855 ///
856 /// \param M The module we are outlining from.
857 /// \param CandidateList A list of candidates to be outlined.
858 /// \param FunctionList A list of functions to be inserted into the module.
859 /// \param Mapper Contains the instruction mappings for the module.
Jessica Paquette9df7fde2017-10-23 23:36:46 +0000860 bool outline(Module &M,
861 const ArrayRef<std::shared_ptr<Candidate>> &CandidateList,
Jessica Paquette596f4832017-03-06 21:31:18 +0000862 std::vector<OutlinedFunction> &FunctionList,
863 InstructionMapper &Mapper);
864
865 /// Creates a function for \p OF and inserts it into the module.
866 MachineFunction *createOutlinedFunction(Module &M, const OutlinedFunction &OF,
Jessica Paquettea3eb0fa2018-11-07 18:36:43 +0000867 InstructionMapper &Mapper,
868 unsigned Name);
Jessica Paquette596f4832017-03-06 21:31:18 +0000869
870 /// Find potential outlining candidates and store them in \p CandidateList.
871 ///
872 /// For each type of potential candidate, also build an \p OutlinedFunction
873 /// struct containing the information to build the function for that
874 /// candidate.
875 ///
876 /// \param[out] CandidateList Filled with outlining candidates for the module.
877 /// \param[out] FunctionList Filled with functions corresponding to each type
878 /// of \p Candidate.
879 /// \param ST The suffix tree for the module.
Jessica Paquette596f4832017-03-06 21:31:18 +0000880 ///
881 /// \returns The length of the longest candidate found. 0 if there are none.
Jessica Paquette9df7fde2017-10-23 23:36:46 +0000882 unsigned
883 buildCandidateList(std::vector<std::shared_ptr<Candidate>> &CandidateList,
884 std::vector<OutlinedFunction> &FunctionList,
Eli Friedmanda080782018-08-01 00:37:20 +0000885 SuffixTree &ST, InstructionMapper &Mapper);
Jessica Paquette596f4832017-03-06 21:31:18 +0000886
Jessica Paquette60d31fc2017-10-17 21:11:58 +0000887 /// Helper function for pruneOverlaps.
888 /// Removes \p C from the candidate list, and updates its \p OutlinedFunction.
889 void prune(Candidate &C, std::vector<OutlinedFunction> &FunctionList);
890
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000891 /// Remove any overlapping candidates that weren't handled by the
Jessica Paquette596f4832017-03-06 21:31:18 +0000892 /// suffix tree's pruning method.
893 ///
894 /// Pruning from the suffix tree doesn't necessarily remove all overlaps.
895 /// If a short candidate is chosen for outlining, then a longer candidate
896 /// which has that short candidate as a suffix is chosen, the tree's pruning
897 /// method will not find it. Thus, we need to prune before outlining as well.
898 ///
899 /// \param[in,out] CandidateList A list of outlining candidates.
900 /// \param[in,out] FunctionList A list of functions to be outlined.
Jessica Paquette809d7082017-07-28 03:21:58 +0000901 /// \param Mapper Contains instruction mapping info for outlining.
Jessica Paquette596f4832017-03-06 21:31:18 +0000902 /// \param MaxCandidateLen The length of the longest candidate.
Jessica Paquette9df7fde2017-10-23 23:36:46 +0000903 void pruneOverlaps(std::vector<std::shared_ptr<Candidate>> &CandidateList,
Jessica Paquette596f4832017-03-06 21:31:18 +0000904 std::vector<OutlinedFunction> &FunctionList,
Eli Friedmanda080782018-08-01 00:37:20 +0000905 InstructionMapper &Mapper, unsigned MaxCandidateLen);
Jessica Paquette596f4832017-03-06 21:31:18 +0000906
907 /// Construct a suffix tree on the instructions in \p M and outline repeated
908 /// strings from that tree.
909 bool runOnModule(Module &M) override;
Jessica Paquetteaa087322018-06-04 21:14:16 +0000910
911 /// Return a DISubprogram for OF if one exists, and null otherwise. Helper
912 /// function for remark emission.
913 DISubprogram *getSubprogramOrNull(const OutlinedFunction &OF) {
914 DISubprogram *SP;
915 for (const std::shared_ptr<Candidate> &C : OF.Candidates)
916 if (C && C->getMF() && (SP = C->getMF()->getFunction().getSubprogram()))
917 return SP;
918 return nullptr;
919 }
Jessica Paquette050d1ac2018-09-11 16:33:46 +0000920
921 /// Populate and \p InstructionMapper with instruction-to-integer mappings.
922 /// These are used to construct a suffix tree.
923 void populateMapper(InstructionMapper &Mapper, Module &M,
924 MachineModuleInfo &MMI);
Jessica Paquette596f4832017-03-06 21:31:18 +0000925
Jessica Paquette2386eab2018-09-11 23:05:34 +0000926 /// Initialize information necessary to output a size remark.
927 /// FIXME: This should be handled by the pass manager, not the outliner.
928 /// FIXME: This is nearly identical to the initSizeRemarkInfo in the legacy
929 /// pass manager.
930 void initSizeRemarkInfo(
931 const Module &M, const MachineModuleInfo &MMI,
932 StringMap<unsigned> &FunctionToInstrCount);
933
934 /// Emit the remark.
935 // FIXME: This should be handled by the pass manager, not the outliner.
936 void emitInstrCountChangedRemark(
937 const Module &M, const MachineModuleInfo &MMI,
938 const StringMap<unsigned> &FunctionToInstrCount);
939};
Jessica Paquette596f4832017-03-06 21:31:18 +0000940} // Anonymous namespace.
941
942char MachineOutliner::ID = 0;
943
944namespace llvm {
Jessica Paquette8bda1882018-06-30 03:56:03 +0000945ModulePass *createMachineOutlinerPass(bool RunOnAllFunctions) {
946 MachineOutliner *OL = new MachineOutliner();
947 OL->RunOnAllFunctions = RunOnAllFunctions;
948 return OL;
Jessica Paquette13593842017-10-07 00:16:34 +0000949}
950
Jessica Paquette78681be2017-07-27 23:24:43 +0000951} // namespace llvm
Jessica Paquette596f4832017-03-06 21:31:18 +0000952
Jessica Paquette78681be2017-07-27 23:24:43 +0000953INITIALIZE_PASS(MachineOutliner, DEBUG_TYPE, "Machine Function Outliner", false,
954 false)
955
Jessica Paquette1cc52a02018-07-24 17:37:28 +0000956void MachineOutliner::emitNotOutliningCheaperRemark(
957 unsigned StringLen, std::vector<Candidate> &CandidatesForRepeatedSeq,
958 OutlinedFunction &OF) {
Jessica Paquettec991cf32018-11-01 23:09:06 +0000959 // FIXME: Right now, we arbitrarily choose some Candidate from the
960 // OutlinedFunction. This isn't necessarily fixed, nor does it have to be.
961 // We should probably sort these by function name or something to make sure
962 // the remarks are stable.
Jessica Paquette1cc52a02018-07-24 17:37:28 +0000963 Candidate &C = CandidatesForRepeatedSeq.front();
964 MachineOptimizationRemarkEmitter MORE(*(C.getMF()), nullptr);
965 MORE.emit([&]() {
966 MachineOptimizationRemarkMissed R(DEBUG_TYPE, "NotOutliningCheaper",
967 C.front()->getDebugLoc(), C.getMBB());
968 R << "Did not outline " << NV("Length", StringLen) << " instructions"
969 << " from " << NV("NumOccurrences", CandidatesForRepeatedSeq.size())
970 << " locations."
971 << " Bytes from outlining all occurrences ("
972 << NV("OutliningCost", OF.getOutliningCost()) << ")"
973 << " >= Unoutlined instruction bytes ("
974 << NV("NotOutliningCost", OF.getNotOutlinedCost()) << ")"
975 << " (Also found at: ";
976
977 // Tell the user the other places the candidate was found.
978 for (unsigned i = 1, e = CandidatesForRepeatedSeq.size(); i < e; i++) {
979 R << NV((Twine("OtherStartLoc") + Twine(i)).str(),
980 CandidatesForRepeatedSeq[i].front()->getDebugLoc());
981 if (i != e - 1)
982 R << ", ";
983 }
984
985 R << ")";
986 return R;
987 });
988}
989
Jessica Paquette58e706a2018-07-24 20:20:45 +0000990void MachineOutliner::emitOutlinedFunctionRemark(OutlinedFunction &OF) {
991 MachineBasicBlock *MBB = &*OF.MF->begin();
992 MachineOptimizationRemarkEmitter MORE(*OF.MF, nullptr);
993 MachineOptimizationRemark R(DEBUG_TYPE, "OutlinedFunction",
994 MBB->findDebugLoc(MBB->begin()), MBB);
995 R << "Saved " << NV("OutliningBenefit", OF.getBenefit()) << " bytes by "
996 << "outlining " << NV("Length", OF.Sequence.size()) << " instructions "
997 << "from " << NV("NumOccurrences", OF.getOccurrenceCount())
998 << " locations. "
999 << "(Found at: ";
1000
1001 // Tell the user the other places the candidate was found.
1002 for (size_t i = 0, e = OF.Candidates.size(); i < e; i++) {
1003
1004 // Skip over things that were pruned.
1005 if (!OF.Candidates[i]->InCandidateList)
1006 continue;
1007
1008 R << NV((Twine("StartLoc") + Twine(i)).str(),
1009 OF.Candidates[i]->front()->getDebugLoc());
1010 if (i != e - 1)
1011 R << ", ";
1012 }
1013
1014 R << ")";
1015
1016 MORE.emit(R);
1017}
1018
Jessica Paquette9df7fde2017-10-23 23:36:46 +00001019unsigned MachineOutliner::findCandidates(
Eli Friedmanda080782018-08-01 00:37:20 +00001020 SuffixTree &ST, InstructionMapper &Mapper,
Jessica Paquette9df7fde2017-10-23 23:36:46 +00001021 std::vector<std::shared_ptr<Candidate>> &CandidateList,
1022 std::vector<OutlinedFunction> &FunctionList) {
Jessica Paquette78681be2017-07-27 23:24:43 +00001023 CandidateList.clear();
1024 FunctionList.clear();
Jessica Paquette4cf187b2017-09-27 20:47:39 +00001025 unsigned MaxLen = 0;
Jessica Paquette78681be2017-07-27 23:24:43 +00001026
Jessica Paquette4e54ef82018-11-06 21:46:41 +00001027 // First, find dall of the repeated substrings in the tree of minimum length
1028 // 2.
Jessica Paquettea409cc92018-11-07 19:20:55 +00001029 for (auto It = ST.begin(), Et = ST.end(); It != Et; ++It) {
1030 SuffixTree::RepeatedSubstring RS = *It;
Jessica Paquetted87f5442017-07-29 02:55:46 +00001031 std::vector<Candidate> CandidatesForRepeatedSeq;
Jessica Paquette4e54ef82018-11-06 21:46:41 +00001032 unsigned StringLen = RS.Length;
1033 for (const unsigned &StartIdx : RS.StartIndices) {
1034 unsigned EndIdx = StartIdx + StringLen - 1;
1035 // Trick: Discard some candidates that would be incompatible with the
1036 // ones we've already found for this sequence. This will save us some
1037 // work in candidate selection.
1038 //
1039 // If two candidates overlap, then we can't outline them both. This
1040 // happens when we have candidates that look like, say
1041 //
1042 // AA (where each "A" is an instruction).
1043 //
1044 // We might have some portion of the module that looks like this:
1045 // AAAAAA (6 A's)
1046 //
1047 // In this case, there are 5 different copies of "AA" in this range, but
1048 // at most 3 can be outlined. If only outlining 3 of these is going to
1049 // be unbeneficial, then we ought to not bother.
1050 //
1051 // Note that two things DON'T overlap when they look like this:
1052 // start1...end1 .... start2...end2
1053 // That is, one must either
1054 // * End before the other starts
1055 // * Start after the other ends
1056 if (std::all_of(
1057 CandidatesForRepeatedSeq.begin(), CandidatesForRepeatedSeq.end(),
1058 [&StartIdx, &EndIdx](const Candidate &C) {
1059 return (EndIdx < C.getStartIdx() || StartIdx > C.getEndIdx());
1060 })) {
1061 // It doesn't overlap with anything, so we can outline it.
1062 // Each sequence is over [StartIt, EndIt].
1063 // Save the candidate and its location.
Jessica Paquetted87f5442017-07-29 02:55:46 +00001064
Jessica Paquette4e54ef82018-11-06 21:46:41 +00001065 MachineBasicBlock::iterator StartIt = Mapper.InstrList[StartIdx];
1066 MachineBasicBlock::iterator EndIt = Mapper.InstrList[EndIdx];
Jessica Paquette78681be2017-07-27 23:24:43 +00001067
Jessica Paquette4e54ef82018-11-06 21:46:41 +00001068 CandidatesForRepeatedSeq.emplace_back(StartIdx, StringLen, StartIt,
1069 EndIt, StartIt->getParent(),
1070 FunctionList.size());
Jessica Paquette809d7082017-07-28 03:21:58 +00001071 }
1072 }
1073
Jessica Paquetteacc15e12017-10-03 20:32:55 +00001074 // We've found something we might want to outline.
1075 // Create an OutlinedFunction to store it and check if it'd be beneficial
1076 // to outline.
Eli Friedmanda080782018-08-01 00:37:20 +00001077 if (CandidatesForRepeatedSeq.empty())
1078 continue;
1079
1080 // Arbitrarily choose a TII from the first candidate.
1081 // FIXME: Should getOutliningCandidateInfo move to TargetMachine?
1082 const TargetInstrInfo *TII =
1083 CandidatesForRepeatedSeq[0].getMF()->getSubtarget().getInstrInfo();
1084
Jessica Paquette9d93c602018-07-27 18:21:57 +00001085 OutlinedFunction OF =
Eli Friedmanda080782018-08-01 00:37:20 +00001086 TII->getOutliningCandidateInfo(CandidatesForRepeatedSeq);
Jessica Paquette9d93c602018-07-27 18:21:57 +00001087
1088 // If we deleted every candidate, then there's nothing to outline.
1089 if (OF.Candidates.empty())
1090 continue;
1091
Jessica Paquetteacc15e12017-10-03 20:32:55 +00001092 std::vector<unsigned> Seq;
Jessica Paquette4e54ef82018-11-06 21:46:41 +00001093 unsigned StartIdx = RS.StartIndices[0]; // Grab any start index.
1094 for (unsigned i = StartIdx; i < StartIdx + StringLen; i++)
Jessica Paquetteacc15e12017-10-03 20:32:55 +00001095 Seq.push_back(ST.Str[i]);
Jessica Paquette69f517d2018-07-24 20:13:10 +00001096 OF.Sequence = Seq;
Jessica Paquette809d7082017-07-28 03:21:58 +00001097
Jessica Paquetteffe4abc2017-08-31 21:02:45 +00001098 // Is it better to outline this candidate than not?
Jessica Paquettef94d1d22018-07-24 17:36:13 +00001099 if (OF.getBenefit() < 1) {
Jessica Paquette1cc52a02018-07-24 17:37:28 +00001100 emitNotOutliningCheaperRemark(StringLen, CandidatesForRepeatedSeq, OF);
Jessica Paquette78681be2017-07-27 23:24:43 +00001101 continue;
Jessica Paquetteffe4abc2017-08-31 21:02:45 +00001102 }
Jessica Paquette78681be2017-07-27 23:24:43 +00001103
1104 if (StringLen > MaxLen)
1105 MaxLen = StringLen;
1106
Jessica Paquettef94d1d22018-07-24 17:36:13 +00001107 // The function is beneficial. Save its candidates to the candidate list
1108 // for pruning.
1109 for (std::shared_ptr<Candidate> &C : OF.Candidates)
1110 CandidateList.push_back(C);
Jessica Paquetteacc15e12017-10-03 20:32:55 +00001111 FunctionList.push_back(OF);
Jessica Paquette78681be2017-07-27 23:24:43 +00001112 }
1113
1114 return MaxLen;
1115}
Jessica Paquette596f4832017-03-06 21:31:18 +00001116
Jessica Paquette60d31fc2017-10-17 21:11:58 +00001117// Remove C from the candidate space, and update its OutlinedFunction.
1118void MachineOutliner::prune(Candidate &C,
1119 std::vector<OutlinedFunction> &FunctionList) {
1120 // Get the OutlinedFunction associated with this Candidate.
1121 OutlinedFunction &F = FunctionList[C.FunctionIdx];
1122
1123 // Update C's associated function's occurrence count.
1124 F.decrement();
1125
1126 // Remove C from the CandidateList.
1127 C.InCandidateList = false;
1128
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001129 LLVM_DEBUG(dbgs() << "- Removed a Candidate \n";
1130 dbgs() << "--- Num fns left for candidate: "
1131 << F.getOccurrenceCount() << "\n";
1132 dbgs() << "--- Candidate's functions's benefit: " << F.getBenefit()
1133 << "\n";);
Jessica Paquette60d31fc2017-10-17 21:11:58 +00001134}
1135
Jessica Paquette9df7fde2017-10-23 23:36:46 +00001136void MachineOutliner::pruneOverlaps(
1137 std::vector<std::shared_ptr<Candidate>> &CandidateList,
1138 std::vector<OutlinedFunction> &FunctionList, InstructionMapper &Mapper,
Eli Friedmanda080782018-08-01 00:37:20 +00001139 unsigned MaxCandidateLen) {
Jessica Paquette91999162017-09-28 23:39:36 +00001140
1141 // Return true if this candidate became unbeneficial for outlining in a
1142 // previous step.
Jessica Paquette60d31fc2017-10-17 21:11:58 +00001143 auto ShouldSkipCandidate = [&FunctionList, this](Candidate &C) {
Jessica Paquette91999162017-09-28 23:39:36 +00001144
1145 // Check if the candidate was removed in a previous step.
1146 if (!C.InCandidateList)
1147 return true;
1148
Jessica Paquette85af63d2017-10-17 19:03:23 +00001149 // C must be alive. Check if we should remove it.
Jessica Paquette60d31fc2017-10-17 21:11:58 +00001150 if (FunctionList[C.FunctionIdx].getBenefit() < 1) {
1151 prune(C, FunctionList);
Jessica Paquette91999162017-09-28 23:39:36 +00001152 return true;
1153 }
1154
1155 // C is in the list, and F is still beneficial.
1156 return false;
1157 };
1158
Jessica Paquetteacffa282017-03-23 21:27:38 +00001159 // TODO: Experiment with interval trees or other interval-checking structures
1160 // to lower the time complexity of this function.
1161 // TODO: Can we do better than the simple greedy choice?
1162 // Check for overlaps in the range.
1163 // This is O(MaxCandidateLen * CandidateList.size()).
Jessica Paquette596f4832017-03-06 21:31:18 +00001164 for (auto It = CandidateList.begin(), Et = CandidateList.end(); It != Et;
1165 It++) {
Jessica Paquette9df7fde2017-10-23 23:36:46 +00001166 Candidate &C1 = **It;
Jessica Paquette596f4832017-03-06 21:31:18 +00001167
Jessica Paquette91999162017-09-28 23:39:36 +00001168 // If C1 was already pruned, or its function is no longer beneficial for
1169 // outlining, move to the next candidate.
1170 if (ShouldSkipCandidate(C1))
Jessica Paquette596f4832017-03-06 21:31:18 +00001171 continue;
1172
Jessica Paquette596f4832017-03-06 21:31:18 +00001173 // The minimum start index of any candidate that could overlap with this
1174 // one.
1175 unsigned FarthestPossibleIdx = 0;
1176
1177 // Either the index is 0, or it's at most MaxCandidateLen indices away.
Jessica Paquette1934fd22017-10-23 16:25:53 +00001178 if (C1.getStartIdx() > MaxCandidateLen)
1179 FarthestPossibleIdx = C1.getStartIdx() - MaxCandidateLen;
Jessica Paquette596f4832017-03-06 21:31:18 +00001180
Hiroshi Inoue0909ca12018-01-26 08:15:29 +00001181 // Compare against the candidates in the list that start at most
Jessica Paquetteacffa282017-03-23 21:27:38 +00001182 // FarthestPossibleIdx indices away from C1. There are at most
1183 // MaxCandidateLen of these.
Jessica Paquette596f4832017-03-06 21:31:18 +00001184 for (auto Sit = It + 1; Sit != Et; Sit++) {
Jessica Paquette9df7fde2017-10-23 23:36:46 +00001185 Candidate &C2 = **Sit;
Jessica Paquette596f4832017-03-06 21:31:18 +00001186
1187 // Is this candidate too far away to overlap?
Jessica Paquette1934fd22017-10-23 16:25:53 +00001188 if (C2.getStartIdx() < FarthestPossibleIdx)
Jessica Paquette596f4832017-03-06 21:31:18 +00001189 break;
1190
Jessica Paquette91999162017-09-28 23:39:36 +00001191 // If C2 was already pruned, or its function is no longer beneficial for
1192 // outlining, move to the next candidate.
1193 if (ShouldSkipCandidate(C2))
Jessica Paquette596f4832017-03-06 21:31:18 +00001194 continue;
1195
Jessica Paquette596f4832017-03-06 21:31:18 +00001196 // Do C1 and C2 overlap?
1197 //
1198 // Not overlapping:
1199 // High indices... [C1End ... C1Start][C2End ... C2Start] ...Low indices
1200 //
1201 // We sorted our candidate list so C2Start <= C1Start. We know that
1202 // C2End > C2Start since each candidate has length >= 2. Therefore, all we
1203 // have to check is C2End < C2Start to see if we overlap.
Jessica Paquette1934fd22017-10-23 16:25:53 +00001204 if (C2.getEndIdx() < C1.getStartIdx())
Jessica Paquette596f4832017-03-06 21:31:18 +00001205 continue;
1206
Jessica Paquetteacffa282017-03-23 21:27:38 +00001207 // C1 and C2 overlap.
1208 // We need to choose the better of the two.
1209 //
1210 // Approximate this by picking the one which would have saved us the
1211 // most instructions before any pruning.
Jessica Paquette60d31fc2017-10-17 21:11:58 +00001212
1213 // Is C2 a better candidate?
1214 if (C2.Benefit > C1.Benefit) {
1215 // Yes, so prune C1. Since C1 is dead, we don't have to compare it
1216 // against anything anymore, so break.
1217 prune(C1, FunctionList);
Jessica Paquetteacffa282017-03-23 21:27:38 +00001218 break;
1219 }
Jessica Paquette60d31fc2017-10-17 21:11:58 +00001220
1221 // Prune C2 and move on to the next candidate.
1222 prune(C2, FunctionList);
Jessica Paquette596f4832017-03-06 21:31:18 +00001223 }
1224 }
1225}
1226
Jessica Paquette9df7fde2017-10-23 23:36:46 +00001227unsigned MachineOutliner::buildCandidateList(
1228 std::vector<std::shared_ptr<Candidate>> &CandidateList,
1229 std::vector<OutlinedFunction> &FunctionList, SuffixTree &ST,
Eli Friedmanda080782018-08-01 00:37:20 +00001230 InstructionMapper &Mapper) {
Jessica Paquette596f4832017-03-06 21:31:18 +00001231
1232 std::vector<unsigned> CandidateSequence; // Current outlining candidate.
Jessica Paquette4cf187b2017-09-27 20:47:39 +00001233 unsigned MaxCandidateLen = 0; // Length of the longest candidate.
Jessica Paquette596f4832017-03-06 21:31:18 +00001234
Jessica Paquette78681be2017-07-27 23:24:43 +00001235 MaxCandidateLen =
Eli Friedmanda080782018-08-01 00:37:20 +00001236 findCandidates(ST, Mapper, CandidateList, FunctionList);
Jessica Paquette596f4832017-03-06 21:31:18 +00001237
Jessica Paquette596f4832017-03-06 21:31:18 +00001238 // Sort the candidates in decending order. This will simplify the outlining
1239 // process when we have to remove the candidates from the mapping by
1240 // allowing us to cut them out without keeping track of an offset.
Jessica Paquette9df7fde2017-10-23 23:36:46 +00001241 std::stable_sort(
1242 CandidateList.begin(), CandidateList.end(),
1243 [](const std::shared_ptr<Candidate> &LHS,
1244 const std::shared_ptr<Candidate> &RHS) { return *LHS < *RHS; });
Jessica Paquette596f4832017-03-06 21:31:18 +00001245
1246 return MaxCandidateLen;
1247}
1248
1249MachineFunction *
1250MachineOutliner::createOutlinedFunction(Module &M, const OutlinedFunction &OF,
Jessica Paquettea3eb0fa2018-11-07 18:36:43 +00001251 InstructionMapper &Mapper,
1252 unsigned Name) {
Jessica Paquette596f4832017-03-06 21:31:18 +00001253
1254 // Create the function name. This should be unique. For now, just hash the
1255 // module name and include it in the function name plus the number of this
1256 // function.
1257 std::ostringstream NameStream;
Jessica Paquettea3eb0fa2018-11-07 18:36:43 +00001258 // FIXME: We should have a better naming scheme. This should be stable,
1259 // regardless of changes to the outliner's cost model/traversal order.
1260 NameStream << "OUTLINED_FUNCTION_" << Name;
Jessica Paquette596f4832017-03-06 21:31:18 +00001261
1262 // Create the function using an IR-level function.
1263 LLVMContext &C = M.getContext();
1264 Function *F = dyn_cast<Function>(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00001265 M.getOrInsertFunction(NameStream.str(), Type::getVoidTy(C)));
Jessica Paquette596f4832017-03-06 21:31:18 +00001266 assert(F && "Function was null!");
1267
1268 // NOTE: If this is linkonceodr, then we can take advantage of linker deduping
1269 // which gives us better results when we outline from linkonceodr functions.
Jessica Paquetted506bf82018-04-03 21:36:00 +00001270 F->setLinkage(GlobalValue::InternalLinkage);
Jessica Paquette596f4832017-03-06 21:31:18 +00001271 F->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
1272
Eli Friedman25bef202018-05-15 23:36:46 +00001273 // FIXME: Set nounwind, so we don't generate eh_frame? Haven't verified it's
1274 // necessary.
1275
1276 // Set optsize/minsize, so we don't insert padding between outlined
1277 // functions.
1278 F->addFnAttr(Attribute::OptimizeForSize);
1279 F->addFnAttr(Attribute::MinSize);
1280
Jessica Paquettee3932ee2018-10-29 20:27:07 +00001281 // Include target features from an arbitrary candidate for the outlined
1282 // function. This makes sure the outlined function knows what kinds of
1283 // instructions are going into it. This is fine, since all parent functions
1284 // must necessarily support the instructions that are in the outlined region.
1285 const Function &ParentFn = OF.Candidates.front()->getMF()->getFunction();
1286 if (ParentFn.hasFnAttribute("target-features"))
1287 F->addFnAttr(ParentFn.getFnAttribute("target-features"));
1288
Jessica Paquette596f4832017-03-06 21:31:18 +00001289 BasicBlock *EntryBB = BasicBlock::Create(C, "entry", F);
1290 IRBuilder<> Builder(EntryBB);
1291 Builder.CreateRetVoid();
1292
1293 MachineModuleInfo &MMI = getAnalysis<MachineModuleInfo>();
Matthias Braun7bda1952017-06-06 00:44:35 +00001294 MachineFunction &MF = MMI.getOrCreateMachineFunction(*F);
Jessica Paquette596f4832017-03-06 21:31:18 +00001295 MachineBasicBlock &MBB = *MF.CreateMachineBasicBlock();
1296 const TargetSubtargetInfo &STI = MF.getSubtarget();
1297 const TargetInstrInfo &TII = *STI.getInstrInfo();
1298
1299 // Insert the new function into the module.
1300 MF.insert(MF.begin(), &MBB);
1301
Jessica Paquette596f4832017-03-06 21:31:18 +00001302 // Copy over the instructions for the function using the integer mappings in
1303 // its sequence.
1304 for (unsigned Str : OF.Sequence) {
1305 MachineInstr *NewMI =
1306 MF.CloneMachineInstr(Mapper.IntegerInstructionMap.find(Str)->second);
Chandler Carruthc73c0302018-08-16 21:30:05 +00001307 NewMI->dropMemRefs(MF);
Jessica Paquette596f4832017-03-06 21:31:18 +00001308
1309 // Don't keep debug information for outlined instructions.
Jessica Paquette596f4832017-03-06 21:31:18 +00001310 NewMI->setDebugLoc(DebugLoc());
1311 MBB.insert(MBB.end(), NewMI);
1312 }
1313
Jessica Paquette69f517d2018-07-24 20:13:10 +00001314 TII.buildOutlinedFrame(MBB, MF, OF);
Jessica Paquette729e6862018-01-18 00:00:58 +00001315
Jessica Paquettecc06a782018-09-20 18:53:53 +00001316 // Outlined functions shouldn't preserve liveness.
1317 MF.getProperties().reset(MachineFunctionProperties::Property::TracksLiveness);
1318 MF.getRegInfo().freezeReservedRegs(MF);
1319
Jessica Paquettea499c3c2018-01-19 21:21:49 +00001320 // If there's a DISubprogram associated with this outlined function, then
1321 // emit debug info for the outlined function.
Jessica Paquetteaa087322018-06-04 21:14:16 +00001322 if (DISubprogram *SP = getSubprogramOrNull(OF)) {
Jessica Paquettea499c3c2018-01-19 21:21:49 +00001323 // We have a DISubprogram. Get its DICompileUnit.
1324 DICompileUnit *CU = SP->getUnit();
1325 DIBuilder DB(M, true, CU);
1326 DIFile *Unit = SP->getFile();
1327 Mangler Mg;
Jessica Paquettecc06a782018-09-20 18:53:53 +00001328 // Get the mangled name of the function for the linkage name.
1329 std::string Dummy;
1330 llvm::raw_string_ostream MangledNameStream(Dummy);
1331 Mg.getNameWithPrefix(MangledNameStream, F, false);
Jessica Paquettea499c3c2018-01-19 21:21:49 +00001332
Jessica Paquettecc06a782018-09-20 18:53:53 +00001333 DISubprogram *OutlinedSP = DB.createFunction(
1334 Unit /* Context */, F->getName(), StringRef(MangledNameStream.str()),
1335 Unit /* File */,
1336 0 /* Line 0 is reserved for compiler-generated code. */,
1337 DB.createSubroutineType(DB.getOrCreateTypeArray(None)), /* void type */
1338 false, true, 0, /* Line 0 is reserved for compiler-generated code. */
1339 DINode::DIFlags::FlagArtificial /* Compiler-generated code. */,
1340 true /* Outlined code is optimized code by definition. */);
Jessica Paquettea499c3c2018-01-19 21:21:49 +00001341
Jessica Paquettecc06a782018-09-20 18:53:53 +00001342 // Don't add any new variables to the subprogram.
1343 DB.finalizeSubprogram(OutlinedSP);
Jessica Paquettea499c3c2018-01-19 21:21:49 +00001344
Jessica Paquettecc06a782018-09-20 18:53:53 +00001345 // Attach subprogram to the function.
1346 F->setSubprogram(OutlinedSP);
Jessica Paquettea499c3c2018-01-19 21:21:49 +00001347 // We're done with the DIBuilder.
1348 DB.finalize();
1349 }
1350
Jessica Paquette596f4832017-03-06 21:31:18 +00001351 return &MF;
1352}
1353
Jessica Paquette9df7fde2017-10-23 23:36:46 +00001354bool MachineOutliner::outline(
1355 Module &M, const ArrayRef<std::shared_ptr<Candidate>> &CandidateList,
1356 std::vector<OutlinedFunction> &FunctionList, InstructionMapper &Mapper) {
Jessica Paquette596f4832017-03-06 21:31:18 +00001357
1358 bool OutlinedSomething = false;
Jessica Paquettea3eb0fa2018-11-07 18:36:43 +00001359
1360 // Number to append to the current outlined function.
1361 unsigned OutlinedFunctionNum = 0;
1362
Jessica Paquette596f4832017-03-06 21:31:18 +00001363 // Replace the candidates with calls to their respective outlined functions.
Jessica Paquette9df7fde2017-10-23 23:36:46 +00001364 for (const std::shared_ptr<Candidate> &Cptr : CandidateList) {
1365 Candidate &C = *Cptr;
Jessica Paquette596f4832017-03-06 21:31:18 +00001366 // Was the candidate removed during pruneOverlaps?
1367 if (!C.InCandidateList)
1368 continue;
1369
1370 // If not, then look at its OutlinedFunction.
1371 OutlinedFunction &OF = FunctionList[C.FunctionIdx];
1372
1373 // Was its OutlinedFunction made unbeneficial during pruneOverlaps?
Jessica Paquette85af63d2017-10-17 19:03:23 +00001374 if (OF.getBenefit() < 1)
Jessica Paquette596f4832017-03-06 21:31:18 +00001375 continue;
1376
Jessica Paquette596f4832017-03-06 21:31:18 +00001377 // Does this candidate have a function yet?
Jessica Paquetteacffa282017-03-23 21:27:38 +00001378 if (!OF.MF) {
Jessica Paquettea3eb0fa2018-11-07 18:36:43 +00001379 OF.MF = createOutlinedFunction(M, OF, Mapper, OutlinedFunctionNum);
Jessica Paquette58e706a2018-07-24 20:20:45 +00001380 emitOutlinedFunctionRemark(OF);
Jessica Paquetteacffa282017-03-23 21:27:38 +00001381 FunctionsCreated++;
Jessica Paquettea3eb0fa2018-11-07 18:36:43 +00001382 OutlinedFunctionNum++; // Created a function, move to the next name.
Jessica Paquetteacffa282017-03-23 21:27:38 +00001383 }
Jessica Paquette596f4832017-03-06 21:31:18 +00001384
1385 MachineFunction *MF = OF.MF;
Jessica Paquetteaa087322018-06-04 21:14:16 +00001386 MachineBasicBlock &MBB = *C.getMBB();
1387 MachineBasicBlock::iterator StartIt = C.front();
1388 MachineBasicBlock::iterator EndIt = C.back();
1389 assert(StartIt != C.getMBB()->end() && "StartIt out of bounds!");
1390 assert(EndIt != C.getMBB()->end() && "EndIt out of bounds!");
1391
Jessica Paquette596f4832017-03-06 21:31:18 +00001392 const TargetSubtargetInfo &STI = MF->getSubtarget();
1393 const TargetInstrInfo &TII = *STI.getInstrInfo();
1394
1395 // Insert a call to the new function and erase the old sequence.
Jessica Paquettefca55122018-07-24 17:42:11 +00001396 auto CallInst = TII.insertOutlinedCall(M, MBB, StartIt, *OF.MF, C);
Jessica Paquette596f4832017-03-06 21:31:18 +00001397
Jessica Paquette0b672492018-04-27 23:36:35 +00001398 // If the caller tracks liveness, then we need to make sure that anything
1399 // we outline doesn't break liveness assumptions.
1400 // The outlined functions themselves currently don't track liveness, but
1401 // we should make sure that the ranges we yank things out of aren't
1402 // wrong.
Jessica Paquetteaa087322018-06-04 21:14:16 +00001403 if (MBB.getParent()->getProperties().hasProperty(
Jessica Paquette0b672492018-04-27 23:36:35 +00001404 MachineFunctionProperties::Property::TracksLiveness)) {
1405 // Helper lambda for adding implicit def operands to the call instruction.
1406 auto CopyDefs = [&CallInst](MachineInstr &MI) {
1407 for (MachineOperand &MOP : MI.operands()) {
1408 // Skip over anything that isn't a register.
1409 if (!MOP.isReg())
1410 continue;
1411
1412 // If it's a def, add it to the call instruction.
1413 if (MOP.isDef())
1414 CallInst->addOperand(
1415 MachineOperand::CreateReg(MOP.getReg(), true, /* isDef = true */
1416 true /* isImp = true */));
1417 }
1418 };
1419
1420 // Copy over the defs in the outlined range.
1421 // First inst in outlined range <-- Anything that's defined in this
1422 // ... .. range has to be added as an implicit
1423 // Last inst in outlined range <-- def to the call instruction.
Francis Visoiu Mistrihf905bf12018-07-14 09:40:01 +00001424 std::for_each(CallInst, std::next(EndIt), CopyDefs);
Jessica Paquette0b672492018-04-27 23:36:35 +00001425 }
1426
Jessica Paquetteaa087322018-06-04 21:14:16 +00001427 // Erase from the point after where the call was inserted up to, and
1428 // including, the final instruction in the sequence.
1429 // Erase needs one past the end, so we need std::next there too.
1430 MBB.erase(std::next(StartIt), std::next(EndIt));
Jessica Paquette596f4832017-03-06 21:31:18 +00001431 OutlinedSomething = true;
1432
1433 // Statistics.
1434 NumOutlined++;
1435 }
1436
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001437 LLVM_DEBUG(dbgs() << "OutlinedSomething = " << OutlinedSomething << "\n";);
Jessica Paquette596f4832017-03-06 21:31:18 +00001438
1439 return OutlinedSomething;
1440}
1441
Jessica Paquette050d1ac2018-09-11 16:33:46 +00001442void MachineOutliner::populateMapper(InstructionMapper &Mapper, Module &M,
1443 MachineModuleInfo &MMI) {
Jessica Paquettedf822742018-03-22 21:07:09 +00001444 // Build instruction mappings for each function in the module. Start by
1445 // iterating over each Function in M.
Jessica Paquette596f4832017-03-06 21:31:18 +00001446 for (Function &F : M) {
Jessica Paquette596f4832017-03-06 21:31:18 +00001447
Jessica Paquettedf822742018-03-22 21:07:09 +00001448 // If there's nothing in F, then there's no reason to try and outline from
1449 // it.
1450 if (F.empty())
Jessica Paquette596f4832017-03-06 21:31:18 +00001451 continue;
1452
Jessica Paquettedf822742018-03-22 21:07:09 +00001453 // There's something in F. Check if it has a MachineFunction associated with
1454 // it.
1455 MachineFunction *MF = MMI.getMachineFunction(F);
Jessica Paquette596f4832017-03-06 21:31:18 +00001456
Jessica Paquettedf822742018-03-22 21:07:09 +00001457 // If it doesn't, then there's nothing to outline from. Move to the next
1458 // Function.
1459 if (!MF)
1460 continue;
1461
Eli Friedmanda080782018-08-01 00:37:20 +00001462 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
1463
Jessica Paquette8bda1882018-06-30 03:56:03 +00001464 if (!RunOnAllFunctions && !TII->shouldOutlineFromFunctionByDefault(*MF))
1465 continue;
1466
Jessica Paquettedf822742018-03-22 21:07:09 +00001467 // We have a MachineFunction. Ask the target if it's suitable for outlining.
1468 // If it isn't, then move on to the next Function in the module.
1469 if (!TII->isFunctionSafeToOutlineFrom(*MF, OutlineFromLinkOnceODRs))
1470 continue;
1471
1472 // We have a function suitable for outlining. Iterate over every
1473 // MachineBasicBlock in MF and try to map its instructions to a list of
1474 // unsigned integers.
1475 for (MachineBasicBlock &MBB : *MF) {
1476 // If there isn't anything in MBB, then there's no point in outlining from
1477 // it.
Jessica Paquetteb320ca22018-09-20 21:53:25 +00001478 // If there are fewer than 2 instructions in the MBB, then it can't ever
1479 // contain something worth outlining.
1480 // FIXME: This should be based off of the maximum size in B of an outlined
1481 // call versus the size in B of the MBB.
1482 if (MBB.empty() || MBB.size() < 2)
Jessica Paquette596f4832017-03-06 21:31:18 +00001483 continue;
1484
Jessica Paquettedf822742018-03-22 21:07:09 +00001485 // Check if MBB could be the target of an indirect branch. If it is, then
1486 // we don't want to outline from it.
1487 if (MBB.hasAddressTaken())
1488 continue;
1489
1490 // MBB is suitable for outlining. Map it to a list of unsigneds.
Eli Friedmanda080782018-08-01 00:37:20 +00001491 Mapper.convertToUnsignedVec(MBB, *TII);
Jessica Paquette596f4832017-03-06 21:31:18 +00001492 }
1493 }
Jessica Paquette050d1ac2018-09-11 16:33:46 +00001494}
1495
Jessica Paquette2386eab2018-09-11 23:05:34 +00001496void MachineOutliner::initSizeRemarkInfo(
1497 const Module &M, const MachineModuleInfo &MMI,
1498 StringMap<unsigned> &FunctionToInstrCount) {
1499 // Collect instruction counts for every function. We'll use this to emit
1500 // per-function size remarks later.
1501 for (const Function &F : M) {
1502 MachineFunction *MF = MMI.getMachineFunction(F);
1503
1504 // We only care about MI counts here. If there's no MachineFunction at this
1505 // point, then there won't be after the outliner runs, so let's move on.
1506 if (!MF)
1507 continue;
1508 FunctionToInstrCount[F.getName().str()] = MF->getInstructionCount();
1509 }
1510}
1511
1512void MachineOutliner::emitInstrCountChangedRemark(
1513 const Module &M, const MachineModuleInfo &MMI,
1514 const StringMap<unsigned> &FunctionToInstrCount) {
1515 // Iterate over each function in the module and emit remarks.
1516 // Note that we won't miss anything by doing this, because the outliner never
1517 // deletes functions.
1518 for (const Function &F : M) {
1519 MachineFunction *MF = MMI.getMachineFunction(F);
1520
1521 // The outliner never deletes functions. If we don't have a MF here, then we
1522 // didn't have one prior to outlining either.
1523 if (!MF)
1524 continue;
1525
1526 std::string Fname = F.getName();
1527 unsigned FnCountAfter = MF->getInstructionCount();
1528 unsigned FnCountBefore = 0;
1529
1530 // Check if the function was recorded before.
1531 auto It = FunctionToInstrCount.find(Fname);
1532
1533 // Did we have a previously-recorded size? If yes, then set FnCountBefore
1534 // to that.
1535 if (It != FunctionToInstrCount.end())
1536 FnCountBefore = It->second;
1537
1538 // Compute the delta and emit a remark if there was a change.
1539 int64_t FnDelta = static_cast<int64_t>(FnCountAfter) -
1540 static_cast<int64_t>(FnCountBefore);
1541 if (FnDelta == 0)
1542 continue;
1543
1544 MachineOptimizationRemarkEmitter MORE(*MF, nullptr);
1545 MORE.emit([&]() {
1546 MachineOptimizationRemarkAnalysis R("size-info", "FunctionMISizeChange",
1547 DiagnosticLocation(),
1548 &MF->front());
1549 R << DiagnosticInfoOptimizationBase::Argument("Pass", "Machine Outliner")
1550 << ": Function: "
1551 << DiagnosticInfoOptimizationBase::Argument("Function", F.getName())
1552 << ": MI instruction count changed from "
1553 << DiagnosticInfoOptimizationBase::Argument("MIInstrsBefore",
1554 FnCountBefore)
1555 << " to "
1556 << DiagnosticInfoOptimizationBase::Argument("MIInstrsAfter",
1557 FnCountAfter)
1558 << "; Delta: "
1559 << DiagnosticInfoOptimizationBase::Argument("Delta", FnDelta);
1560 return R;
1561 });
1562 }
1563}
1564
Jessica Paquette050d1ac2018-09-11 16:33:46 +00001565bool MachineOutliner::runOnModule(Module &M) {
1566 // Check if there's anything in the module. If it's empty, then there's
1567 // nothing to outline.
1568 if (M.empty())
1569 return false;
1570
1571 MachineModuleInfo &MMI = getAnalysis<MachineModuleInfo>();
1572
1573 // If the user passed -enable-machine-outliner=always or
1574 // -enable-machine-outliner, the pass will run on all functions in the module.
1575 // Otherwise, if the target supports default outlining, it will run on all
1576 // functions deemed by the target to be worth outlining from by default. Tell
1577 // the user how the outliner is running.
1578 LLVM_DEBUG(
1579 dbgs() << "Machine Outliner: Running on ";
1580 if (RunOnAllFunctions)
1581 dbgs() << "all functions";
1582 else
1583 dbgs() << "target-default functions";
1584 dbgs() << "\n"
1585 );
1586
1587 // If the user specifies that they want to outline from linkonceodrs, set
1588 // it here.
1589 OutlineFromLinkOnceODRs = EnableLinkOnceODROutlining;
1590 InstructionMapper Mapper;
1591
1592 // Prepare instruction mappings for the suffix tree.
1593 populateMapper(Mapper, M, MMI);
Jessica Paquette596f4832017-03-06 21:31:18 +00001594
1595 // Construct a suffix tree, use it to find candidates, and then outline them.
1596 SuffixTree ST(Mapper.UnsignedVec);
Jessica Paquette9df7fde2017-10-23 23:36:46 +00001597 std::vector<std::shared_ptr<Candidate>> CandidateList;
Jessica Paquette596f4832017-03-06 21:31:18 +00001598 std::vector<OutlinedFunction> FunctionList;
1599
Jessica Paquetteacffa282017-03-23 21:27:38 +00001600 // Find all of the outlining candidates.
Jessica Paquette596f4832017-03-06 21:31:18 +00001601 unsigned MaxCandidateLen =
Eli Friedmanda080782018-08-01 00:37:20 +00001602 buildCandidateList(CandidateList, FunctionList, ST, Mapper);
Jessica Paquette596f4832017-03-06 21:31:18 +00001603
Jessica Paquetteacffa282017-03-23 21:27:38 +00001604 // Remove candidates that overlap with other candidates.
Eli Friedmanda080782018-08-01 00:37:20 +00001605 pruneOverlaps(CandidateList, FunctionList, Mapper, MaxCandidateLen);
Jessica Paquetteacffa282017-03-23 21:27:38 +00001606
Jessica Paquette2386eab2018-09-11 23:05:34 +00001607 // If we've requested size remarks, then collect the MI counts of every
1608 // function before outlining, and the MI counts after outlining.
1609 // FIXME: This shouldn't be in the outliner at all; it should ultimately be
1610 // the pass manager's responsibility.
1611 // This could pretty easily be placed in outline instead, but because we
1612 // really ultimately *don't* want this here, it's done like this for now
1613 // instead.
1614
1615 // Check if we want size remarks.
1616 bool ShouldEmitSizeRemarks = M.shouldEmitInstrCountChangedRemark();
1617 StringMap<unsigned> FunctionToInstrCount;
1618 if (ShouldEmitSizeRemarks)
1619 initSizeRemarkInfo(M, MMI, FunctionToInstrCount);
1620
Jessica Paquetteacffa282017-03-23 21:27:38 +00001621 // Outline each of the candidates and return true if something was outlined.
Jessica Paquette729e6862018-01-18 00:00:58 +00001622 bool OutlinedSomething = outline(M, CandidateList, FunctionList, Mapper);
1623
Jessica Paquette2386eab2018-09-11 23:05:34 +00001624 // If we outlined something, we definitely changed the MI count of the
1625 // module. If we've asked for size remarks, then output them.
1626 // FIXME: This should be in the pass manager.
1627 if (ShouldEmitSizeRemarks && OutlinedSomething)
1628 emitInstrCountChangedRemark(M, MMI, FunctionToInstrCount);
1629
Jessica Paquette729e6862018-01-18 00:00:58 +00001630 return OutlinedSomething;
Jessica Paquette596f4832017-03-06 21:31:18 +00001631}