blob: 8bd02f0ed24a219bf0ce3f5ce2c9acb4abe4f390 [file] [log] [blame]
Jessica Paquette596f4832017-03-06 21:31:18 +00001//===---- MachineOutliner.cpp - Outline instructions -----------*- C++ -*-===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Jessica Paquette596f4832017-03-06 21:31:18 +00006//
7//===----------------------------------------------------------------------===//
8///
9/// \file
10/// Replaces repeated sequences of instructions with function calls.
11///
12/// This works by placing every instruction from every basic block in a
13/// suffix tree, and repeatedly querying that tree for repeated sequences of
14/// instructions. If a sequence of instructions appears often, then it ought
15/// to be beneficial to pull out into a function.
16///
Jessica Paquette4cf187b2017-09-27 20:47:39 +000017/// The MachineOutliner communicates with a given target using hooks defined in
18/// TargetInstrInfo.h. The target supplies the outliner with information on how
19/// a specific sequence of instructions should be outlined. This information
20/// is used to deduce the number of instructions necessary to
21///
22/// * Create an outlined function
23/// * Call that outlined function
24///
25/// Targets must implement
26/// * getOutliningCandidateInfo
Jessica Paquette32de26d2018-06-19 21:14:48 +000027/// * buildOutlinedFrame
Jessica Paquette4cf187b2017-09-27 20:47:39 +000028/// * insertOutlinedCall
Jessica Paquette4cf187b2017-09-27 20:47:39 +000029/// * isFunctionSafeToOutlineFrom
30///
31/// in order to make use of the MachineOutliner.
32///
Jessica Paquette596f4832017-03-06 21:31:18 +000033/// This was originally presented at the 2016 LLVM Developers' Meeting in the
34/// talk "Reducing Code Size Using Outlining". For a high-level overview of
35/// how this pass works, the talk is available on YouTube at
36///
37/// https://www.youtube.com/watch?v=yorld-WSOeU
38///
39/// The slides for the talk are available at
40///
41/// http://www.llvm.org/devmtg/2016-11/Slides/Paquette-Outliner.pdf
42///
43/// The talk provides an overview of how the outliner finds candidates and
44/// ultimately outlines them. It describes how the main data structure for this
45/// pass, the suffix tree, is queried and purged for candidates. It also gives
46/// a simplified suffix tree construction algorithm for suffix trees based off
47/// of the algorithm actually used here, Ukkonen's algorithm.
48///
49/// For the original RFC for this pass, please see
50///
51/// http://lists.llvm.org/pipermail/llvm-dev/2016-August/104170.html
52///
53/// For more information on the suffix tree data structure, please see
54/// https://www.cs.helsinki.fi/u/ukkonen/SuffixT1withFigs.pdf
55///
56//===----------------------------------------------------------------------===//
Jessica Paquetteaa087322018-06-04 21:14:16 +000057#include "llvm/CodeGen/MachineOutliner.h"
Jessica Paquette596f4832017-03-06 21:31:18 +000058#include "llvm/ADT/DenseMap.h"
Jin Linfc6fda92020-03-05 13:54:58 -080059#include "llvm/ADT/SmallSet.h"
Jessica Paquette596f4832017-03-06 21:31:18 +000060#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"
Reid Kleckner05da2fe2019-11-13 13:15:01 -080072#include "llvm/InitializePasses.h"
Jessica Paquette596f4832017-03-06 21:31:18 +000073#include "llvm/Support/Allocator.h"
Jessica Paquette1eca23b2018-04-19 22:17:07 +000074#include "llvm/Support/CommandLine.h"
Jessica Paquette596f4832017-03-06 21:31:18 +000075#include "llvm/Support/Debug.h"
76#include "llvm/Support/raw_ostream.h"
Jessica Paquette596f4832017-03-06 21:31:18 +000077#include <functional>
Jessica Paquette596f4832017-03-06 21:31:18 +000078#include <tuple>
79#include <vector>
80
81#define DEBUG_TYPE "machine-outliner"
82
83using namespace llvm;
Jessica Paquetteffe4abc2017-08-31 21:02:45 +000084using namespace ore;
Jessica Paquetteaa087322018-06-04 21:14:16 +000085using namespace outliner;
Jessica Paquette596f4832017-03-06 21:31:18 +000086
87STATISTIC(NumOutlined, "Number of candidates outlined");
88STATISTIC(FunctionsCreated, "Number of functions created");
89
Jessica Paquette1eca23b2018-04-19 22:17:07 +000090// Set to true if the user wants the outliner to run on linkonceodr linkage
91// functions. This is false by default because the linker can dedupe linkonceodr
92// functions. Since the outliner is confined to a single module (modulo LTO),
93// this is off by default. It should, however, be the default behaviour in
94// LTO.
95static cl::opt<bool> EnableLinkOnceODROutlining(
Puyan Lotfi6b7615a2019-10-28 17:57:51 -040096 "enable-linkonceodr-outlining", cl::Hidden,
Jessica Paquette1eca23b2018-04-19 22:17:07 +000097 cl::desc("Enable the machine outliner on linkonceodr functions"),
98 cl::init(false));
99
Puyan Lotfiffd5e122020-04-29 03:33:47 -0400100/// Number of times to re-run the outliner. This is not the total number of runs
101/// as the outliner will run at least one time. The default value is set to 0,
102/// meaning the outliner will run one time and rerun zero times after that.
103static cl::opt<unsigned> OutlinerReruns(
104 "machine-outliner-reruns", cl::init(0), cl::Hidden,
105 cl::desc(
106 "Number of times to rerun the outliner after the initial outline"));
Jin Lin0d896272020-03-17 15:40:26 -0700107
Jessica Paquette596f4832017-03-06 21:31:18 +0000108namespace {
109
110/// Represents an undefined index in the suffix tree.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000111const unsigned EmptyIdx = -1;
Jessica Paquette596f4832017-03-06 21:31:18 +0000112
113/// A node in a suffix tree which represents a substring or suffix.
114///
115/// Each node has either no children or at least two children, with the root
116/// being a exception in the empty tree.
117///
118/// Children are represented as a map between unsigned integers and nodes. If
119/// a node N has a child M on unsigned integer k, then the mapping represented
120/// by N is a proper prefix of the mapping represented by M. Note that this,
121/// although similar to a trie is somewhat different: each node stores a full
122/// substring of the full mapping rather than a single character state.
123///
124/// Each internal node contains a pointer to the internal node representing
125/// the same string, but with the first character chopped off. This is stored
126/// in \p Link. Each leaf node stores the start index of its respective
127/// suffix in \p SuffixIdx.
128struct SuffixTreeNode {
129
130 /// The children of this node.
131 ///
132 /// A child existing on an unsigned integer implies that from the mapping
133 /// represented by the current node, there is a way to reach another
134 /// mapping by tacking that character on the end of the current string.
135 DenseMap<unsigned, SuffixTreeNode *> Children;
136
Jessica Paquette596f4832017-03-06 21:31:18 +0000137 /// The start index of this node's substring in the main string.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000138 unsigned StartIdx = EmptyIdx;
Jessica Paquette596f4832017-03-06 21:31:18 +0000139
140 /// The end index of this node's substring in the main string.
141 ///
142 /// Every leaf node must have its \p EndIdx incremented at the end of every
143 /// step in the construction algorithm. To avoid having to update O(N)
144 /// nodes individually at the end of every step, the end index is stored
145 /// as a pointer.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000146 unsigned *EndIdx = nullptr;
Jessica Paquette596f4832017-03-06 21:31:18 +0000147
148 /// For leaves, the start index of the suffix represented by this node.
149 ///
150 /// For all other nodes, this is ignored.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000151 unsigned SuffixIdx = EmptyIdx;
Jessica Paquette596f4832017-03-06 21:31:18 +0000152
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000153 /// For internal nodes, a pointer to the internal node representing
Jessica Paquette596f4832017-03-06 21:31:18 +0000154 /// the same sequence with the first character chopped off.
155 ///
Jessica Paquette4602c342017-07-28 05:59:30 +0000156 /// This acts as a shortcut in Ukkonen's algorithm. One of the things that
Jessica Paquette596f4832017-03-06 21:31:18 +0000157 /// Ukkonen's algorithm does to achieve linear-time construction is
158 /// keep track of which node the next insert should be at. This makes each
159 /// insert O(1), and there are a total of O(N) inserts. The suffix link
160 /// helps with inserting children of internal nodes.
161 ///
Jessica Paquette78681be2017-07-27 23:24:43 +0000162 /// Say we add a child to an internal node with associated mapping S. The
Jessica Paquette596f4832017-03-06 21:31:18 +0000163 /// next insertion must be at the node representing S - its first character.
164 /// This is given by the way that we iteratively build the tree in Ukkonen's
165 /// algorithm. The main idea is to look at the suffixes of each prefix in the
166 /// string, starting with the longest suffix of the prefix, and ending with
167 /// the shortest. Therefore, if we keep pointers between such nodes, we can
168 /// move to the next insertion point in O(1) time. If we don't, then we'd
169 /// have to query from the root, which takes O(N) time. This would make the
170 /// construction algorithm O(N^2) rather than O(N).
Jessica Paquette596f4832017-03-06 21:31:18 +0000171 SuffixTreeNode *Link = nullptr;
172
Jessica Paquetteacffa282017-03-23 21:27:38 +0000173 /// The length of the string formed by concatenating the edge labels from the
174 /// root to this node.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000175 unsigned ConcatLen = 0;
Jessica Paquetteacffa282017-03-23 21:27:38 +0000176
Jessica Paquette596f4832017-03-06 21:31:18 +0000177 /// Returns true if this node is a leaf.
178 bool isLeaf() const { return SuffixIdx != EmptyIdx; }
179
180 /// Returns true if this node is the root of its owning \p SuffixTree.
181 bool isRoot() const { return StartIdx == EmptyIdx; }
182
183 /// Return the number of elements in the substring associated with this node.
184 size_t size() const {
185
186 // Is it the root? If so, it's the empty string so return 0.
187 if (isRoot())
188 return 0;
189
190 assert(*EndIdx != EmptyIdx && "EndIdx is undefined!");
191
192 // Size = the number of elements in the string.
193 // For example, [0 1 2 3] has length 4, not 3. 3-0 = 3, so we have 3-0+1.
194 return *EndIdx - StartIdx + 1;
195 }
196
Jessica Paquettedf5b09b2018-11-07 19:56:13 +0000197 SuffixTreeNode(unsigned StartIdx, unsigned *EndIdx, SuffixTreeNode *Link)
198 : StartIdx(StartIdx), EndIdx(EndIdx), Link(Link) {}
Jessica Paquette596f4832017-03-06 21:31:18 +0000199
200 SuffixTreeNode() {}
201};
202
203/// A data structure for fast substring queries.
204///
205/// Suffix trees represent the suffixes of their input strings in their leaves.
206/// A suffix tree is a type of compressed trie structure where each node
207/// represents an entire substring rather than a single character. Each leaf
208/// of the tree is a suffix.
209///
210/// A suffix tree can be seen as a type of state machine where each state is a
211/// substring of the full string. The tree is structured so that, for a string
212/// of length N, there are exactly N leaves in the tree. This structure allows
213/// us to quickly find repeated substrings of the input string.
214///
215/// In this implementation, a "string" is a vector of unsigned integers.
216/// These integers may result from hashing some data type. A suffix tree can
217/// contain 1 or many strings, which can then be queried as one large string.
218///
219/// The suffix tree is implemented using Ukkonen's algorithm for linear-time
220/// suffix tree construction. Ukkonen's algorithm is explained in more detail
221/// in the paper by Esko Ukkonen "On-line construction of suffix trees. The
222/// paper is available at
223///
224/// https://www.cs.helsinki.fi/u/ukkonen/SuffixT1withFigs.pdf
225class SuffixTree {
Jessica Paquette78681be2017-07-27 23:24:43 +0000226public:
Jessica Paquette596f4832017-03-06 21:31:18 +0000227 /// Each element is an integer representing an instruction in the module.
228 ArrayRef<unsigned> Str;
229
Jessica Paquette4e54ef82018-11-06 21:46:41 +0000230 /// A repeated substring in the tree.
231 struct RepeatedSubstring {
232 /// The length of the string.
233 unsigned Length;
234
235 /// The start indices of each occurrence.
236 std::vector<unsigned> StartIndices;
237 };
238
Jessica Paquette78681be2017-07-27 23:24:43 +0000239private:
Jessica Paquette596f4832017-03-06 21:31:18 +0000240 /// Maintains each node in the tree.
Jessica Paquetted4cb9c62017-03-08 23:55:33 +0000241 SpecificBumpPtrAllocator<SuffixTreeNode> NodeAllocator;
Jessica Paquette596f4832017-03-06 21:31:18 +0000242
243 /// The root of the suffix tree.
244 ///
245 /// The root represents the empty string. It is maintained by the
246 /// \p NodeAllocator like every other node in the tree.
247 SuffixTreeNode *Root = nullptr;
248
Jessica Paquette596f4832017-03-06 21:31:18 +0000249 /// Maintains the end indices of the internal nodes in the tree.
250 ///
251 /// Each internal node is guaranteed to never have its end index change
252 /// during the construction algorithm; however, leaves must be updated at
253 /// every step. Therefore, we need to store leaf end indices by reference
254 /// to avoid updating O(N) leaves at every step of construction. Thus,
255 /// every internal node must be allocated its own end index.
256 BumpPtrAllocator InternalEndIdxAllocator;
257
258 /// The end index of each leaf in the tree.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000259 unsigned LeafEndIdx = -1;
Jessica Paquette596f4832017-03-06 21:31:18 +0000260
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000261 /// Helper struct which keeps track of the next insertion point in
Jessica Paquette596f4832017-03-06 21:31:18 +0000262 /// Ukkonen's algorithm.
263 struct ActiveState {
264 /// The next node to insert at.
Simon Pilgrimc7f127d2019-11-05 15:08:21 +0000265 SuffixTreeNode *Node = nullptr;
Jessica Paquette596f4832017-03-06 21:31:18 +0000266
267 /// The index of the first character in the substring currently being added.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000268 unsigned Idx = EmptyIdx;
Jessica Paquette596f4832017-03-06 21:31:18 +0000269
270 /// The length of the substring we have to add at the current step.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000271 unsigned Len = 0;
Jessica Paquette596f4832017-03-06 21:31:18 +0000272 };
273
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000274 /// The point the next insertion will take place at in the
Jessica Paquette596f4832017-03-06 21:31:18 +0000275 /// construction algorithm.
276 ActiveState Active;
277
278 /// Allocate a leaf node and add it to the tree.
279 ///
280 /// \param Parent The parent of this node.
281 /// \param StartIdx The start index of this node's associated string.
282 /// \param Edge The label on the edge leaving \p Parent to this node.
283 ///
284 /// \returns A pointer to the allocated leaf node.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000285 SuffixTreeNode *insertLeaf(SuffixTreeNode &Parent, unsigned StartIdx,
Jessica Paquette596f4832017-03-06 21:31:18 +0000286 unsigned Edge) {
287
288 assert(StartIdx <= LeafEndIdx && "String can't start after it ends!");
289
Jessica Paquette78681be2017-07-27 23:24:43 +0000290 SuffixTreeNode *N = new (NodeAllocator.Allocate())
Jessica Paquettedf5b09b2018-11-07 19:56:13 +0000291 SuffixTreeNode(StartIdx, &LeafEndIdx, nullptr);
Jessica Paquette596f4832017-03-06 21:31:18 +0000292 Parent.Children[Edge] = N;
293
294 return N;
295 }
296
297 /// Allocate an internal node and add it to the tree.
298 ///
299 /// \param Parent The parent of this node. Only null when allocating the root.
300 /// \param StartIdx The start index of this node's associated string.
301 /// \param EndIdx The end index of this node's associated string.
302 /// \param Edge The label on the edge leaving \p Parent to this node.
303 ///
304 /// \returns A pointer to the allocated internal node.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000305 SuffixTreeNode *insertInternalNode(SuffixTreeNode *Parent, unsigned StartIdx,
306 unsigned EndIdx, unsigned Edge) {
Jessica Paquette596f4832017-03-06 21:31:18 +0000307
308 assert(StartIdx <= EndIdx && "String can't start after it ends!");
309 assert(!(!Parent && StartIdx != EmptyIdx) &&
Jessica Paquette78681be2017-07-27 23:24:43 +0000310 "Non-root internal nodes must have parents!");
Jessica Paquette596f4832017-03-06 21:31:18 +0000311
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000312 unsigned *E = new (InternalEndIdxAllocator) unsigned(EndIdx);
Puyan Lotfi6b7615a2019-10-28 17:57:51 -0400313 SuffixTreeNode *N =
314 new (NodeAllocator.Allocate()) SuffixTreeNode(StartIdx, E, Root);
Jessica Paquette596f4832017-03-06 21:31:18 +0000315 if (Parent)
316 Parent->Children[Edge] = N;
317
318 return N;
319 }
320
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000321 /// Set the suffix indices of the leaves to the start indices of their
Jessica Paquette4e54ef82018-11-06 21:46:41 +0000322 /// respective suffixes.
Jessica Paquetted5750772019-12-20 15:57:39 -0800323 void setSuffixIndices() {
324 // List of nodes we need to visit along with the current length of the
325 // string.
326 std::vector<std::pair<SuffixTreeNode *, unsigned>> ToVisit;
Jessica Paquette596f4832017-03-06 21:31:18 +0000327
Jessica Paquetted5750772019-12-20 15:57:39 -0800328 // Current node being visited.
329 SuffixTreeNode *CurrNode = Root;
Jessica Paquette596f4832017-03-06 21:31:18 +0000330
Jessica Paquetted5750772019-12-20 15:57:39 -0800331 // Sum of the lengths of the nodes down the path to the current one.
332 unsigned CurrNodeLen = 0;
333 ToVisit.push_back({CurrNode, CurrNodeLen});
334 while (!ToVisit.empty()) {
335 std::tie(CurrNode, CurrNodeLen) = ToVisit.back();
336 ToVisit.pop_back();
337 CurrNode->ConcatLen = CurrNodeLen;
338 for (auto &ChildPair : CurrNode->Children) {
339 assert(ChildPair.second && "Node had a null child!");
340 ToVisit.push_back(
341 {ChildPair.second, CurrNodeLen + ChildPair.second->size()});
342 }
343
344 // No children, so we are at the end of the string.
345 if (CurrNode->Children.size() == 0 && !CurrNode->isRoot())
346 CurrNode->SuffixIdx = Str.size() - CurrNodeLen;
Jessica Paquette596f4832017-03-06 21:31:18 +0000347 }
Jessica Paquette596f4832017-03-06 21:31:18 +0000348 }
349
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000350 /// Construct the suffix tree for the prefix of the input ending at
Jessica Paquette596f4832017-03-06 21:31:18 +0000351 /// \p EndIdx.
352 ///
353 /// Used to construct the full suffix tree iteratively. At the end of each
354 /// step, the constructed suffix tree is either a valid suffix tree, or a
355 /// suffix tree with implicit suffixes. At the end of the final step, the
356 /// suffix tree is a valid tree.
357 ///
358 /// \param EndIdx The end index of the current prefix in the main string.
359 /// \param SuffixesToAdd The number of suffixes that must be added
360 /// to complete the suffix tree at the current phase.
361 ///
362 /// \returns The number of suffixes that have not been added at the end of
363 /// this step.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000364 unsigned extend(unsigned EndIdx, unsigned SuffixesToAdd) {
Jessica Paquette596f4832017-03-06 21:31:18 +0000365 SuffixTreeNode *NeedsLink = nullptr;
366
367 while (SuffixesToAdd > 0) {
Jessica Paquette78681be2017-07-27 23:24:43 +0000368
Jessica Paquette596f4832017-03-06 21:31:18 +0000369 // Are we waiting to add anything other than just the last character?
370 if (Active.Len == 0) {
371 // If not, then say the active index is the end index.
372 Active.Idx = EndIdx;
373 }
374
375 assert(Active.Idx <= EndIdx && "Start index can't be after end index!");
376
377 // The first character in the current substring we're looking at.
378 unsigned FirstChar = Str[Active.Idx];
379
380 // Have we inserted anything starting with FirstChar at the current node?
381 if (Active.Node->Children.count(FirstChar) == 0) {
382 // If not, then we can just insert a leaf and move too the next step.
383 insertLeaf(*Active.Node, EndIdx, FirstChar);
384
385 // The active node is an internal node, and we visited it, so it must
386 // need a link if it doesn't have one.
387 if (NeedsLink) {
388 NeedsLink->Link = Active.Node;
389 NeedsLink = nullptr;
390 }
391 } else {
392 // There's a match with FirstChar, so look for the point in the tree to
393 // insert a new node.
394 SuffixTreeNode *NextNode = Active.Node->Children[FirstChar];
395
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000396 unsigned SubstringLen = NextNode->size();
Jessica Paquette596f4832017-03-06 21:31:18 +0000397
398 // Is the current suffix we're trying to insert longer than the size of
399 // the child we want to move to?
400 if (Active.Len >= SubstringLen) {
401 // If yes, then consume the characters we've seen and move to the next
402 // node.
403 Active.Idx += SubstringLen;
404 Active.Len -= SubstringLen;
405 Active.Node = NextNode;
406 continue;
407 }
408
409 // Otherwise, the suffix we're trying to insert must be contained in the
410 // next node we want to move to.
411 unsigned LastChar = Str[EndIdx];
412
413 // Is the string we're trying to insert a substring of the next node?
414 if (Str[NextNode->StartIdx + Active.Len] == LastChar) {
415 // If yes, then we're done for this step. Remember our insertion point
416 // and move to the next end index. At this point, we have an implicit
417 // suffix tree.
418 if (NeedsLink && !Active.Node->isRoot()) {
419 NeedsLink->Link = Active.Node;
420 NeedsLink = nullptr;
421 }
422
423 Active.Len++;
424 break;
425 }
426
427 // The string we're trying to insert isn't a substring of the next node,
428 // but matches up to a point. Split the node.
429 //
430 // For example, say we ended our search at a node n and we're trying to
431 // insert ABD. Then we'll create a new node s for AB, reduce n to just
432 // representing C, and insert a new leaf node l to represent d. This
433 // allows us to ensure that if n was a leaf, it remains a leaf.
434 //
435 // | ABC ---split---> | AB
436 // n s
437 // C / \ D
438 // n l
439
440 // The node s from the diagram
441 SuffixTreeNode *SplitNode =
Jessica Paquette78681be2017-07-27 23:24:43 +0000442 insertInternalNode(Active.Node, NextNode->StartIdx,
443 NextNode->StartIdx + Active.Len - 1, FirstChar);
Jessica Paquette596f4832017-03-06 21:31:18 +0000444
445 // Insert the new node representing the new substring into the tree as
446 // a child of the split node. This is the node l from the diagram.
447 insertLeaf(*SplitNode, EndIdx, LastChar);
448
449 // Make the old node a child of the split node and update its start
450 // index. This is the node n from the diagram.
451 NextNode->StartIdx += Active.Len;
Jessica Paquette596f4832017-03-06 21:31:18 +0000452 SplitNode->Children[Str[NextNode->StartIdx]] = NextNode;
453
454 // SplitNode is an internal node, update the suffix link.
455 if (NeedsLink)
456 NeedsLink->Link = SplitNode;
457
458 NeedsLink = SplitNode;
459 }
460
461 // We've added something new to the tree, so there's one less suffix to
462 // add.
463 SuffixesToAdd--;
464
465 if (Active.Node->isRoot()) {
466 if (Active.Len > 0) {
467 Active.Len--;
468 Active.Idx = EndIdx - SuffixesToAdd + 1;
469 }
470 } else {
471 // Start the next phase at the next smallest suffix.
472 Active.Node = Active.Node->Link;
473 }
474 }
475
476 return SuffixesToAdd;
477 }
478
Jessica Paquette596f4832017-03-06 21:31:18 +0000479public:
Jessica Paquette596f4832017-03-06 21:31:18 +0000480 /// Construct a suffix tree from a sequence of unsigned integers.
481 ///
482 /// \param Str The string to construct the suffix tree for.
483 SuffixTree(const std::vector<unsigned> &Str) : Str(Str) {
484 Root = insertInternalNode(nullptr, EmptyIdx, EmptyIdx, 0);
Jessica Paquette596f4832017-03-06 21:31:18 +0000485 Active.Node = Root;
Jessica Paquette596f4832017-03-06 21:31:18 +0000486
487 // Keep track of the number of suffixes we have to add of the current
488 // prefix.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000489 unsigned SuffixesToAdd = 0;
Jessica Paquette596f4832017-03-06 21:31:18 +0000490
491 // Construct the suffix tree iteratively on each prefix of the string.
492 // PfxEndIdx is the end index of the current prefix.
493 // End is one past the last element in the string.
Jessica Paquette4cf187b2017-09-27 20:47:39 +0000494 for (unsigned PfxEndIdx = 0, End = Str.size(); PfxEndIdx < End;
495 PfxEndIdx++) {
Jessica Paquette596f4832017-03-06 21:31:18 +0000496 SuffixesToAdd++;
497 LeafEndIdx = PfxEndIdx; // Extend each of the leaves.
498 SuffixesToAdd = extend(PfxEndIdx, SuffixesToAdd);
499 }
500
501 // Set the suffix indices of each leaf.
502 assert(Root && "Root node can't be nullptr!");
Jessica Paquetted5750772019-12-20 15:57:39 -0800503 setSuffixIndices();
Jessica Paquette596f4832017-03-06 21:31:18 +0000504 }
Jessica Paquette4e54ef82018-11-06 21:46:41 +0000505
Jessica Paquettea409cc92018-11-07 19:20:55 +0000506 /// Iterator for finding all repeated substrings in the suffix tree.
507 struct RepeatedSubstringIterator {
Puyan Lotfi6b7615a2019-10-28 17:57:51 -0400508 private:
Jessica Paquettea409cc92018-11-07 19:20:55 +0000509 /// The current node we're visiting.
510 SuffixTreeNode *N = nullptr;
511
512 /// The repeated substring associated with this node.
513 RepeatedSubstring RS;
514
515 /// The nodes left to visit.
516 std::vector<SuffixTreeNode *> ToVisit;
517
518 /// The minimum length of a repeated substring to find.
519 /// Since we're outlining, we want at least two instructions in the range.
520 /// FIXME: This may not be true for targets like X86 which support many
521 /// instruction lengths.
522 const unsigned MinLength = 2;
523
524 /// Move the iterator to the next repeated substring.
525 void advance() {
526 // Clear the current state. If we're at the end of the range, then this
527 // is the state we want to be in.
528 RS = RepeatedSubstring();
529 N = nullptr;
530
Jessica Paquette3cd70b32018-12-06 00:26:21 +0000531 // Each leaf node represents a repeat of a string.
532 std::vector<SuffixTreeNode *> LeafChildren;
533
Jessica Paquettea409cc92018-11-07 19:20:55 +0000534 // Continue visiting nodes until we find one which repeats more than once.
535 while (!ToVisit.empty()) {
536 SuffixTreeNode *Curr = ToVisit.back();
537 ToVisit.pop_back();
Jessica Paquette3cd70b32018-12-06 00:26:21 +0000538 LeafChildren.clear();
Jessica Paquettea409cc92018-11-07 19:20:55 +0000539
540 // Keep track of the length of the string associated with the node. If
541 // it's too short, we'll quit.
542 unsigned Length = Curr->ConcatLen;
543
Jessica Paquettea409cc92018-11-07 19:20:55 +0000544 // Iterate over each child, saving internal nodes for visiting, and
545 // leaf nodes in LeafChildren. Internal nodes represent individual
546 // strings, which may repeat.
547 for (auto &ChildPair : Curr->Children) {
548 // Save all of this node's children for processing.
549 if (!ChildPair.second->isLeaf())
550 ToVisit.push_back(ChildPair.second);
551
552 // It's not an internal node, so it must be a leaf. If we have a
553 // long enough string, then save the leaf children.
554 else if (Length >= MinLength)
555 LeafChildren.push_back(ChildPair.second);
556 }
557
558 // The root never represents a repeated substring. If we're looking at
559 // that, then skip it.
560 if (Curr->isRoot())
561 continue;
562
563 // Do we have any repeated substrings?
564 if (LeafChildren.size() >= 2) {
565 // Yes. Update the state to reflect this, and then bail out.
566 N = Curr;
567 RS.Length = Length;
568 for (SuffixTreeNode *Leaf : LeafChildren)
569 RS.StartIndices.push_back(Leaf->SuffixIdx);
570 break;
571 }
572 }
573
574 // At this point, either NewRS is an empty RepeatedSubstring, or it was
575 // set in the above loop. Similarly, N is either nullptr, or the node
576 // associated with NewRS.
577 }
578
579 public:
580 /// Return the current repeated substring.
581 RepeatedSubstring &operator*() { return RS; }
582
583 RepeatedSubstringIterator &operator++() {
584 advance();
585 return *this;
586 }
587
588 RepeatedSubstringIterator operator++(int I) {
589 RepeatedSubstringIterator It(*this);
590 advance();
591 return It;
592 }
593
594 bool operator==(const RepeatedSubstringIterator &Other) {
595 return N == Other.N;
596 }
597 bool operator!=(const RepeatedSubstringIterator &Other) {
598 return !(*this == Other);
599 }
600
601 RepeatedSubstringIterator(SuffixTreeNode *N) : N(N) {
602 // Do we have a non-null node?
603 if (N) {
604 // Yes. At the first step, we need to visit all of N's children.
605 // Note: This means that we visit N last.
606 ToVisit.push_back(N);
607 advance();
608 }
609 }
Puyan Lotfi6b7615a2019-10-28 17:57:51 -0400610 };
Jessica Paquettea409cc92018-11-07 19:20:55 +0000611
612 typedef RepeatedSubstringIterator iterator;
613 iterator begin() { return iterator(Root); }
614 iterator end() { return iterator(nullptr); }
Jessica Paquette596f4832017-03-06 21:31:18 +0000615};
616
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000617/// Maps \p MachineInstrs to unsigned integers and stores the mappings.
Jessica Paquette596f4832017-03-06 21:31:18 +0000618struct InstructionMapper {
619
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000620 /// The next available integer to assign to a \p MachineInstr that
Jessica Paquette596f4832017-03-06 21:31:18 +0000621 /// cannot be outlined.
622 ///
623 /// Set to -3 for compatability with \p DenseMapInfo<unsigned>.
624 unsigned IllegalInstrNumber = -3;
625
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000626 /// The next available integer to assign to a \p MachineInstr that can
Jessica Paquette596f4832017-03-06 21:31:18 +0000627 /// be outlined.
628 unsigned LegalInstrNumber = 0;
629
630 /// Correspondence from \p MachineInstrs to unsigned integers.
631 DenseMap<MachineInstr *, unsigned, MachineInstrExpressionTrait>
632 InstructionIntegerMap;
633
Jessica Paquettecad864d2018-11-13 23:01:34 +0000634 /// Correspondence between \p MachineBasicBlocks and target-defined flags.
635 DenseMap<MachineBasicBlock *, unsigned> MBBFlagsMap;
636
Jessica Paquette596f4832017-03-06 21:31:18 +0000637 /// The vector of unsigned integers that the module is mapped to.
638 std::vector<unsigned> UnsignedVec;
639
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000640 /// Stores the location of the instruction associated with the integer
Jessica Paquette596f4832017-03-06 21:31:18 +0000641 /// at index i in \p UnsignedVec for each index i.
642 std::vector<MachineBasicBlock::iterator> InstrList;
643
Jessica Paquettec991cf32018-11-01 23:09:06 +0000644 // Set if we added an illegal number in the previous step.
645 // Since each illegal number is unique, we only need one of them between
646 // each range of legal numbers. This lets us make sure we don't add more
647 // than one illegal number per range.
648 bool AddedIllegalLastTime = false;
649
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000650 /// Maps \p *It to a legal integer.
Jessica Paquette596f4832017-03-06 21:31:18 +0000651 ///
Jessica Paquettec4cf7752018-11-08 00:33:38 +0000652 /// Updates \p CanOutlineWithPrevInstr, \p HaveLegalRange, \p InstrListForMBB,
Jessica Paquetteca3ed962018-12-06 00:01:51 +0000653 /// \p UnsignedVecForMBB, \p InstructionIntegerMap, and \p LegalInstrNumber.
Jessica Paquette596f4832017-03-06 21:31:18 +0000654 ///
655 /// \returns The integer that \p *It was mapped to.
Jessica Paquette267d2662018-11-08 00:02:11 +0000656 unsigned mapToLegalUnsigned(
Jessica Paquettec4cf7752018-11-08 00:33:38 +0000657 MachineBasicBlock::iterator &It, bool &CanOutlineWithPrevInstr,
658 bool &HaveLegalRange, unsigned &NumLegalInBlock,
Jessica Paquette267d2662018-11-08 00:02:11 +0000659 std::vector<unsigned> &UnsignedVecForMBB,
660 std::vector<MachineBasicBlock::iterator> &InstrListForMBB) {
Jessica Paquettec991cf32018-11-01 23:09:06 +0000661 // We added something legal, so we should unset the AddedLegalLastTime
662 // flag.
663 AddedIllegalLastTime = false;
Jessica Paquette596f4832017-03-06 21:31:18 +0000664
Jessica Paquettec4cf7752018-11-08 00:33:38 +0000665 // If we have at least two adjacent legal instructions (which may have
666 // invisible instructions in between), remember that.
667 if (CanOutlineWithPrevInstr)
668 HaveLegalRange = true;
669 CanOutlineWithPrevInstr = true;
670
Jessica Paquette267d2662018-11-08 00:02:11 +0000671 // Keep track of the number of legal instructions we insert.
672 NumLegalInBlock++;
673
Jessica Paquette596f4832017-03-06 21:31:18 +0000674 // Get the integer for this instruction or give it the current
675 // LegalInstrNumber.
Jessica Paquette267d2662018-11-08 00:02:11 +0000676 InstrListForMBB.push_back(It);
Jessica Paquette596f4832017-03-06 21:31:18 +0000677 MachineInstr &MI = *It;
678 bool WasInserted;
679 DenseMap<MachineInstr *, unsigned, MachineInstrExpressionTrait>::iterator
Jessica Paquette78681be2017-07-27 23:24:43 +0000680 ResultIt;
Jessica Paquette596f4832017-03-06 21:31:18 +0000681 std::tie(ResultIt, WasInserted) =
Jessica Paquette78681be2017-07-27 23:24:43 +0000682 InstructionIntegerMap.insert(std::make_pair(&MI, LegalInstrNumber));
Jessica Paquette596f4832017-03-06 21:31:18 +0000683 unsigned MINumber = ResultIt->second;
684
685 // There was an insertion.
Jessica Paquetteca3ed962018-12-06 00:01:51 +0000686 if (WasInserted)
Jessica Paquette596f4832017-03-06 21:31:18 +0000687 LegalInstrNumber++;
Jessica Paquette596f4832017-03-06 21:31:18 +0000688
Jessica Paquette267d2662018-11-08 00:02:11 +0000689 UnsignedVecForMBB.push_back(MINumber);
Jessica Paquette596f4832017-03-06 21:31:18 +0000690
691 // Make sure we don't overflow or use any integers reserved by the DenseMap.
692 if (LegalInstrNumber >= IllegalInstrNumber)
693 report_fatal_error("Instruction mapping overflow!");
694
Jessica Paquette78681be2017-07-27 23:24:43 +0000695 assert(LegalInstrNumber != DenseMapInfo<unsigned>::getEmptyKey() &&
696 "Tried to assign DenseMap tombstone or empty key to instruction.");
697 assert(LegalInstrNumber != DenseMapInfo<unsigned>::getTombstoneKey() &&
698 "Tried to assign DenseMap tombstone or empty key to instruction.");
Jessica Paquette596f4832017-03-06 21:31:18 +0000699
700 return MINumber;
701 }
702
703 /// Maps \p *It to an illegal integer.
704 ///
Jessica Paquette267d2662018-11-08 00:02:11 +0000705 /// Updates \p InstrListForMBB, \p UnsignedVecForMBB, and \p
706 /// IllegalInstrNumber.
Jessica Paquette596f4832017-03-06 21:31:18 +0000707 ///
708 /// \returns The integer that \p *It was mapped to.
Puyan Lotfi6b7615a2019-10-28 17:57:51 -0400709 unsigned mapToIllegalUnsigned(
710 MachineBasicBlock::iterator &It, bool &CanOutlineWithPrevInstr,
711 std::vector<unsigned> &UnsignedVecForMBB,
712 std::vector<MachineBasicBlock::iterator> &InstrListForMBB) {
Jessica Paquettec4cf7752018-11-08 00:33:38 +0000713 // Can't outline an illegal instruction. Set the flag.
714 CanOutlineWithPrevInstr = false;
715
Jessica Paquettec991cf32018-11-01 23:09:06 +0000716 // Only add one illegal number per range of legal numbers.
717 if (AddedIllegalLastTime)
718 return IllegalInstrNumber;
719
720 // Remember that we added an illegal number last time.
721 AddedIllegalLastTime = true;
Jessica Paquette596f4832017-03-06 21:31:18 +0000722 unsigned MINumber = IllegalInstrNumber;
723
Jessica Paquette267d2662018-11-08 00:02:11 +0000724 InstrListForMBB.push_back(It);
725 UnsignedVecForMBB.push_back(IllegalInstrNumber);
Jessica Paquette596f4832017-03-06 21:31:18 +0000726 IllegalInstrNumber--;
727
728 assert(LegalInstrNumber < IllegalInstrNumber &&
729 "Instruction mapping overflow!");
730
Jessica Paquette78681be2017-07-27 23:24:43 +0000731 assert(IllegalInstrNumber != DenseMapInfo<unsigned>::getEmptyKey() &&
732 "IllegalInstrNumber cannot be DenseMap tombstone or empty key!");
Jessica Paquette596f4832017-03-06 21:31:18 +0000733
Jessica Paquette78681be2017-07-27 23:24:43 +0000734 assert(IllegalInstrNumber != DenseMapInfo<unsigned>::getTombstoneKey() &&
735 "IllegalInstrNumber cannot be DenseMap tombstone or empty key!");
Jessica Paquette596f4832017-03-06 21:31:18 +0000736
737 return MINumber;
738 }
739
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000740 /// Transforms a \p MachineBasicBlock into a \p vector of \p unsigneds
Jessica Paquette596f4832017-03-06 21:31:18 +0000741 /// and appends it to \p UnsignedVec and \p InstrList.
742 ///
743 /// Two instructions are assigned the same integer if they are identical.
744 /// If an instruction is deemed unsafe to outline, then it will be assigned an
745 /// unique integer. The resulting mapping is placed into a suffix tree and
746 /// queried for candidates.
747 ///
748 /// \param MBB The \p MachineBasicBlock to be translated into integers.
Eli Friedmanda080782018-08-01 00:37:20 +0000749 /// \param TII \p TargetInstrInfo for the function.
Jessica Paquette596f4832017-03-06 21:31:18 +0000750 void convertToUnsignedVec(MachineBasicBlock &MBB,
Jessica Paquette596f4832017-03-06 21:31:18 +0000751 const TargetInstrInfo &TII) {
Alexander Kornienko3635c892018-11-13 16:41:05 +0000752 unsigned Flags = 0;
Jessica Paquette82d9c0a2018-11-12 23:51:32 +0000753
754 // Don't even map in this case.
755 if (!TII.isMBBSafeToOutlineFrom(MBB, Flags))
756 return;
757
Jessica Paquettecad864d2018-11-13 23:01:34 +0000758 // Store info for the MBB for later outlining.
759 MBBFlagsMap[&MBB] = Flags;
760
Jessica Paquettec991cf32018-11-01 23:09:06 +0000761 MachineBasicBlock::iterator It = MBB.begin();
Jessica Paquette267d2662018-11-08 00:02:11 +0000762
763 // The number of instructions in this block that will be considered for
764 // outlining.
765 unsigned NumLegalInBlock = 0;
766
Jessica Paquettec4cf7752018-11-08 00:33:38 +0000767 // True if we have at least two legal instructions which aren't separated
768 // by an illegal instruction.
769 bool HaveLegalRange = false;
770
771 // True if we can perform outlining given the last mapped (non-invisible)
772 // instruction. This lets us know if we have a legal range.
773 bool CanOutlineWithPrevInstr = false;
774
Jessica Paquette267d2662018-11-08 00:02:11 +0000775 // FIXME: Should this all just be handled in the target, rather than using
776 // repeated calls to getOutliningType?
777 std::vector<unsigned> UnsignedVecForMBB;
778 std::vector<MachineBasicBlock::iterator> InstrListForMBB;
779
Simon Pilgrim76166a12019-11-05 16:46:10 +0000780 for (MachineBasicBlock::iterator Et = MBB.end(); It != Et; ++It) {
Jessica Paquette596f4832017-03-06 21:31:18 +0000781 // Keep track of where this instruction is in the module.
Jessica Paquette3291e732018-01-09 00:26:18 +0000782 switch (TII.getOutliningType(It, Flags)) {
Jessica Paquetteaa087322018-06-04 21:14:16 +0000783 case InstrType::Illegal:
Puyan Lotfi6b7615a2019-10-28 17:57:51 -0400784 mapToIllegalUnsigned(It, CanOutlineWithPrevInstr, UnsignedVecForMBB,
785 InstrListForMBB);
Jessica Paquette78681be2017-07-27 23:24:43 +0000786 break;
Jessica Paquette596f4832017-03-06 21:31:18 +0000787
Jessica Paquetteaa087322018-06-04 21:14:16 +0000788 case InstrType::Legal:
Jessica Paquettec4cf7752018-11-08 00:33:38 +0000789 mapToLegalUnsigned(It, CanOutlineWithPrevInstr, HaveLegalRange,
790 NumLegalInBlock, UnsignedVecForMBB, InstrListForMBB);
Jessica Paquette78681be2017-07-27 23:24:43 +0000791 break;
Jessica Paquette596f4832017-03-06 21:31:18 +0000792
Jessica Paquetteaa087322018-06-04 21:14:16 +0000793 case InstrType::LegalTerminator:
Jessica Paquettec4cf7752018-11-08 00:33:38 +0000794 mapToLegalUnsigned(It, CanOutlineWithPrevInstr, HaveLegalRange,
795 NumLegalInBlock, UnsignedVecForMBB, InstrListForMBB);
Jessica Paquettec991cf32018-11-01 23:09:06 +0000796 // The instruction also acts as a terminator, so we have to record that
797 // in the string.
Jessica Paquettec4cf7752018-11-08 00:33:38 +0000798 mapToIllegalUnsigned(It, CanOutlineWithPrevInstr, UnsignedVecForMBB,
Puyan Lotfi6b7615a2019-10-28 17:57:51 -0400799 InstrListForMBB);
Eli Friedman042dc9e2018-05-22 19:11:06 +0000800 break;
801
Jessica Paquetteaa087322018-06-04 21:14:16 +0000802 case InstrType::Invisible:
Jessica Paquettec991cf32018-11-01 23:09:06 +0000803 // Normally this is set by mapTo(Blah)Unsigned, but we just want to
804 // skip this instruction. So, unset the flag here.
Jessica Paquettebd729882018-09-17 18:40:21 +0000805 AddedIllegalLastTime = false;
Jessica Paquette78681be2017-07-27 23:24:43 +0000806 break;
Jessica Paquette596f4832017-03-06 21:31:18 +0000807 }
808 }
809
Jessica Paquette267d2662018-11-08 00:02:11 +0000810 // Are there enough legal instructions in the block for outlining to be
811 // possible?
Jessica Paquettec4cf7752018-11-08 00:33:38 +0000812 if (HaveLegalRange) {
Jessica Paquette267d2662018-11-08 00:02:11 +0000813 // After we're done every insertion, uniquely terminate this part of the
814 // "string". This makes sure we won't match across basic block or function
815 // boundaries since the "end" is encoded uniquely and thus appears in no
816 // repeated substring.
Jessica Paquettec4cf7752018-11-08 00:33:38 +0000817 mapToIllegalUnsigned(It, CanOutlineWithPrevInstr, UnsignedVecForMBB,
Puyan Lotfi6b7615a2019-10-28 17:57:51 -0400818 InstrListForMBB);
Jessica Paquette267d2662018-11-08 00:02:11 +0000819 InstrList.insert(InstrList.end(), InstrListForMBB.begin(),
820 InstrListForMBB.end());
821 UnsignedVec.insert(UnsignedVec.end(), UnsignedVecForMBB.begin(),
822 UnsignedVecForMBB.end());
823 }
Jessica Paquette596f4832017-03-06 21:31:18 +0000824 }
825
826 InstructionMapper() {
827 // Make sure that the implementation of DenseMapInfo<unsigned> hasn't
828 // changed.
829 assert(DenseMapInfo<unsigned>::getEmptyKey() == (unsigned)-1 &&
Jessica Paquette78681be2017-07-27 23:24:43 +0000830 "DenseMapInfo<unsigned>'s empty key isn't -1!");
Jessica Paquette596f4832017-03-06 21:31:18 +0000831 assert(DenseMapInfo<unsigned>::getTombstoneKey() == (unsigned)-2 &&
Jessica Paquette78681be2017-07-27 23:24:43 +0000832 "DenseMapInfo<unsigned>'s tombstone key isn't -2!");
Jessica Paquette596f4832017-03-06 21:31:18 +0000833 }
834};
835
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000836/// An interprocedural pass which finds repeated sequences of
Jessica Paquette596f4832017-03-06 21:31:18 +0000837/// instructions and replaces them with calls to functions.
838///
839/// Each instruction is mapped to an unsigned integer and placed in a string.
840/// The resulting mapping is then placed in a \p SuffixTree. The \p SuffixTree
841/// is then repeatedly queried for repeated sequences of instructions. Each
842/// non-overlapping repeated sequence is then placed in its own
843/// \p MachineFunction and each instance is then replaced with a call to that
844/// function.
845struct MachineOutliner : public ModulePass {
846
847 static char ID;
848
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000849 /// Set to true if the outliner should consider functions with
Jessica Paquette13593842017-10-07 00:16:34 +0000850 /// linkonceodr linkage.
851 bool OutlineFromLinkOnceODRs = false;
852
Jin Lin0d896272020-03-17 15:40:26 -0700853 /// The current repeat number of machine outlining.
854 unsigned OutlineRepeatedNum = 0;
855
Jessica Paquette8bda1882018-06-30 03:56:03 +0000856 /// Set to true if the outliner should run on all functions in the module
857 /// considered safe for outlining.
858 /// Set to true by default for compatibility with llc's -run-pass option.
859 /// Set when the pass is constructed in TargetPassConfig.
860 bool RunOnAllFunctions = true;
861
Jessica Paquette596f4832017-03-06 21:31:18 +0000862 StringRef getPassName() const override { return "Machine Outliner"; }
863
864 void getAnalysisUsage(AnalysisUsage &AU) const override {
Yuanfang Chencc382cf2019-09-30 17:54:50 +0000865 AU.addRequired<MachineModuleInfoWrapperPass>();
866 AU.addPreserved<MachineModuleInfoWrapperPass>();
Jessica Paquette596f4832017-03-06 21:31:18 +0000867 AU.setPreservesAll();
868 ModulePass::getAnalysisUsage(AU);
869 }
870
Jessica Paquette1eca23b2018-04-19 22:17:07 +0000871 MachineOutliner() : ModulePass(ID) {
Jessica Paquette596f4832017-03-06 21:31:18 +0000872 initializeMachineOutlinerPass(*PassRegistry::getPassRegistry());
873 }
874
Jessica Paquette1cc52a02018-07-24 17:37:28 +0000875 /// Remark output explaining that not outlining a set of candidates would be
876 /// better than outlining that set.
877 void emitNotOutliningCheaperRemark(
878 unsigned StringLen, std::vector<Candidate> &CandidatesForRepeatedSeq,
879 OutlinedFunction &OF);
880
Jessica Paquette58e706a2018-07-24 20:20:45 +0000881 /// Remark output explaining that a function was outlined.
882 void emitOutlinedFunctionRemark(OutlinedFunction &OF);
883
Jessica Paquettece3a2dc2018-12-05 23:39:07 +0000884 /// Find all repeated substrings that satisfy the outlining cost model by
885 /// constructing a suffix tree.
Jessica Paquette78681be2017-07-27 23:24:43 +0000886 ///
887 /// If a substring appears at least twice, then it must be represented by
Jessica Paquette1cc52a02018-07-24 17:37:28 +0000888 /// an internal node which appears in at least two suffixes. Each suffix
889 /// is represented by a leaf node. To do this, we visit each internal node
890 /// in the tree, using the leaf children of each internal node. If an
891 /// internal node represents a beneficial substring, then we use each of
892 /// its leaf children to find the locations of its substring.
Jessica Paquette78681be2017-07-27 23:24:43 +0000893 ///
Jessica Paquette78681be2017-07-27 23:24:43 +0000894 /// \param Mapper Contains outlining mapping information.
Jessica Paquette1cc52a02018-07-24 17:37:28 +0000895 /// \param[out] FunctionList Filled with a list of \p OutlinedFunctions
896 /// each type of candidate.
Jessica Paquettece3a2dc2018-12-05 23:39:07 +0000897 void findCandidates(InstructionMapper &Mapper,
898 std::vector<OutlinedFunction> &FunctionList);
Jessica Paquette78681be2017-07-27 23:24:43 +0000899
Jessica Paquette4ae3b712018-12-05 22:50:26 +0000900 /// Replace the sequences of instructions represented by \p OutlinedFunctions
901 /// with calls to functions.
Jessica Paquette596f4832017-03-06 21:31:18 +0000902 ///
903 /// \param M The module we are outlining from.
Jessica Paquette596f4832017-03-06 21:31:18 +0000904 /// \param FunctionList A list of functions to be inserted into the module.
905 /// \param Mapper Contains the instruction mappings for the module.
Jessica Paquette4ae3b712018-12-05 22:50:26 +0000906 bool outline(Module &M, std::vector<OutlinedFunction> &FunctionList,
Puyan Lotfi6b7615a2019-10-28 17:57:51 -0400907 InstructionMapper &Mapper, unsigned &OutlinedFunctionNum);
Jessica Paquette596f4832017-03-06 21:31:18 +0000908
909 /// Creates a function for \p OF and inserts it into the module.
Jessica Paquettee18d6ff2018-12-05 23:24:22 +0000910 MachineFunction *createOutlinedFunction(Module &M, OutlinedFunction &OF,
Jessica Paquettea3eb0fa2018-11-07 18:36:43 +0000911 InstructionMapper &Mapper,
912 unsigned Name);
Jessica Paquette596f4832017-03-06 21:31:18 +0000913
Puyan Lotfiffd5e122020-04-29 03:33:47 -0400914 /// Calls 'doOutline()' 1 + OutlinerReruns times.
Jin Lin7b166d52020-03-17 18:33:55 -0700915 bool runOnModule(Module &M) override;
Jin Linab2dcff2020-03-17 15:40:26 -0700916
Jessica Paquette596f4832017-03-06 21:31:18 +0000917 /// Construct a suffix tree on the instructions in \p M and outline repeated
918 /// strings from that tree.
Puyan Lotfia51fc8d2019-10-28 15:10:21 -0400919 bool doOutline(Module &M, unsigned &OutlinedFunctionNum);
Jessica Paquetteaa087322018-06-04 21:14:16 +0000920
921 /// Return a DISubprogram for OF if one exists, and null otherwise. Helper
922 /// function for remark emission.
923 DISubprogram *getSubprogramOrNull(const OutlinedFunction &OF) {
Jessica Paquettee18d6ff2018-12-05 23:24:22 +0000924 for (const Candidate &C : OF.Candidates)
Simon Pilgrim7ad25832019-11-05 15:58:04 +0000925 if (MachineFunction *MF = C.getMF())
926 if (DISubprogram *SP = MF->getFunction().getSubprogram())
927 return SP;
Jessica Paquetteaa087322018-06-04 21:14:16 +0000928 return nullptr;
929 }
Jessica Paquette050d1ac2018-09-11 16:33:46 +0000930
931 /// Populate and \p InstructionMapper with instruction-to-integer mappings.
932 /// These are used to construct a suffix tree.
933 void populateMapper(InstructionMapper &Mapper, Module &M,
934 MachineModuleInfo &MMI);
Jessica Paquette596f4832017-03-06 21:31:18 +0000935
Jessica Paquette2386eab2018-09-11 23:05:34 +0000936 /// Initialize information necessary to output a size remark.
937 /// FIXME: This should be handled by the pass manager, not the outliner.
938 /// FIXME: This is nearly identical to the initSizeRemarkInfo in the legacy
939 /// pass manager.
Puyan Lotfi6b7615a2019-10-28 17:57:51 -0400940 void initSizeRemarkInfo(const Module &M, const MachineModuleInfo &MMI,
941 StringMap<unsigned> &FunctionToInstrCount);
Jessica Paquette2386eab2018-09-11 23:05:34 +0000942
943 /// Emit the remark.
944 // FIXME: This should be handled by the pass manager, not the outliner.
Puyan Lotfi6b7615a2019-10-28 17:57:51 -0400945 void
946 emitInstrCountChangedRemark(const Module &M, const MachineModuleInfo &MMI,
947 const StringMap<unsigned> &FunctionToInstrCount);
Jessica Paquette2386eab2018-09-11 23:05:34 +0000948};
Jessica Paquette596f4832017-03-06 21:31:18 +0000949} // Anonymous namespace.
950
951char MachineOutliner::ID = 0;
952
953namespace llvm {
Jessica Paquette8bda1882018-06-30 03:56:03 +0000954ModulePass *createMachineOutlinerPass(bool RunOnAllFunctions) {
955 MachineOutliner *OL = new MachineOutliner();
956 OL->RunOnAllFunctions = RunOnAllFunctions;
957 return OL;
Jessica Paquette13593842017-10-07 00:16:34 +0000958}
959
Jessica Paquette78681be2017-07-27 23:24:43 +0000960} // namespace llvm
Jessica Paquette596f4832017-03-06 21:31:18 +0000961
Jessica Paquette78681be2017-07-27 23:24:43 +0000962INITIALIZE_PASS(MachineOutliner, DEBUG_TYPE, "Machine Function Outliner", false,
963 false)
964
Jessica Paquette1cc52a02018-07-24 17:37:28 +0000965void MachineOutliner::emitNotOutliningCheaperRemark(
966 unsigned StringLen, std::vector<Candidate> &CandidatesForRepeatedSeq,
967 OutlinedFunction &OF) {
Jessica Paquettec991cf32018-11-01 23:09:06 +0000968 // FIXME: Right now, we arbitrarily choose some Candidate from the
969 // OutlinedFunction. This isn't necessarily fixed, nor does it have to be.
970 // We should probably sort these by function name or something to make sure
971 // the remarks are stable.
Jessica Paquette1cc52a02018-07-24 17:37:28 +0000972 Candidate &C = CandidatesForRepeatedSeq.front();
973 MachineOptimizationRemarkEmitter MORE(*(C.getMF()), nullptr);
974 MORE.emit([&]() {
975 MachineOptimizationRemarkMissed R(DEBUG_TYPE, "NotOutliningCheaper",
976 C.front()->getDebugLoc(), C.getMBB());
977 R << "Did not outline " << NV("Length", StringLen) << " instructions"
978 << " from " << NV("NumOccurrences", CandidatesForRepeatedSeq.size())
979 << " locations."
980 << " Bytes from outlining all occurrences ("
981 << NV("OutliningCost", OF.getOutliningCost()) << ")"
982 << " >= Unoutlined instruction bytes ("
983 << NV("NotOutliningCost", OF.getNotOutlinedCost()) << ")"
984 << " (Also found at: ";
985
986 // Tell the user the other places the candidate was found.
987 for (unsigned i = 1, e = CandidatesForRepeatedSeq.size(); i < e; i++) {
988 R << NV((Twine("OtherStartLoc") + Twine(i)).str(),
989 CandidatesForRepeatedSeq[i].front()->getDebugLoc());
990 if (i != e - 1)
991 R << ", ";
992 }
993
994 R << ")";
995 return R;
996 });
997}
998
Jessica Paquette58e706a2018-07-24 20:20:45 +0000999void MachineOutliner::emitOutlinedFunctionRemark(OutlinedFunction &OF) {
1000 MachineBasicBlock *MBB = &*OF.MF->begin();
1001 MachineOptimizationRemarkEmitter MORE(*OF.MF, nullptr);
1002 MachineOptimizationRemark R(DEBUG_TYPE, "OutlinedFunction",
1003 MBB->findDebugLoc(MBB->begin()), MBB);
1004 R << "Saved " << NV("OutliningBenefit", OF.getBenefit()) << " bytes by "
Jessica Paquette34b618b2018-12-05 17:57:33 +00001005 << "outlining " << NV("Length", OF.getNumInstrs()) << " instructions "
Jessica Paquette58e706a2018-07-24 20:20:45 +00001006 << "from " << NV("NumOccurrences", OF.getOccurrenceCount())
1007 << " locations. "
1008 << "(Found at: ";
1009
1010 // Tell the user the other places the candidate was found.
1011 for (size_t i = 0, e = OF.Candidates.size(); i < e; i++) {
1012
Jessica Paquette58e706a2018-07-24 20:20:45 +00001013 R << NV((Twine("StartLoc") + Twine(i)).str(),
Jessica Paquettee18d6ff2018-12-05 23:24:22 +00001014 OF.Candidates[i].front()->getDebugLoc());
Jessica Paquette58e706a2018-07-24 20:20:45 +00001015 if (i != e - 1)
1016 R << ", ";
1017 }
1018
1019 R << ")";
1020
1021 MORE.emit(R);
1022}
1023
Puyan Lotfi6b7615a2019-10-28 17:57:51 -04001024void MachineOutliner::findCandidates(
1025 InstructionMapper &Mapper, std::vector<OutlinedFunction> &FunctionList) {
Jessica Paquette78681be2017-07-27 23:24:43 +00001026 FunctionList.clear();
Jessica Paquettece3a2dc2018-12-05 23:39:07 +00001027 SuffixTree ST(Mapper.UnsignedVec);
Jessica Paquette78681be2017-07-27 23:24:43 +00001028
David Tellenbachfbe7f5e2019-10-30 16:28:11 +00001029 // First, find all of the repeated substrings in the tree of minimum length
Jessica Paquette4e54ef82018-11-06 21:46:41 +00001030 // 2.
Jessica Paquetted4e7d072018-12-06 00:04:03 +00001031 std::vector<Candidate> CandidatesForRepeatedSeq;
Jessica Paquettea409cc92018-11-07 19:20:55 +00001032 for (auto It = ST.begin(), Et = ST.end(); It != Et; ++It) {
Jessica Paquetted4e7d072018-12-06 00:04:03 +00001033 CandidatesForRepeatedSeq.clear();
Jessica Paquettea409cc92018-11-07 19:20:55 +00001034 SuffixTree::RepeatedSubstring RS = *It;
Jessica Paquette4e54ef82018-11-06 21:46:41 +00001035 unsigned StringLen = RS.Length;
1036 for (const unsigned &StartIdx : RS.StartIndices) {
1037 unsigned EndIdx = StartIdx + StringLen - 1;
1038 // Trick: Discard some candidates that would be incompatible with the
1039 // ones we've already found for this sequence. This will save us some
1040 // work in candidate selection.
1041 //
1042 // If two candidates overlap, then we can't outline them both. This
1043 // happens when we have candidates that look like, say
1044 //
1045 // AA (where each "A" is an instruction).
1046 //
1047 // We might have some portion of the module that looks like this:
1048 // AAAAAA (6 A's)
1049 //
1050 // In this case, there are 5 different copies of "AA" in this range, but
1051 // at most 3 can be outlined. If only outlining 3 of these is going to
1052 // be unbeneficial, then we ought to not bother.
1053 //
1054 // Note that two things DON'T overlap when they look like this:
1055 // start1...end1 .... start2...end2
1056 // That is, one must either
1057 // * End before the other starts
1058 // * Start after the other ends
1059 if (std::all_of(
1060 CandidatesForRepeatedSeq.begin(), CandidatesForRepeatedSeq.end(),
1061 [&StartIdx, &EndIdx](const Candidate &C) {
1062 return (EndIdx < C.getStartIdx() || StartIdx > C.getEndIdx());
1063 })) {
1064 // It doesn't overlap with anything, so we can outline it.
1065 // Each sequence is over [StartIt, EndIt].
1066 // Save the candidate and its location.
Jessica Paquetted87f5442017-07-29 02:55:46 +00001067
Jessica Paquette4e54ef82018-11-06 21:46:41 +00001068 MachineBasicBlock::iterator StartIt = Mapper.InstrList[StartIdx];
1069 MachineBasicBlock::iterator EndIt = Mapper.InstrList[EndIdx];
Jessica Paquettecad864d2018-11-13 23:01:34 +00001070 MachineBasicBlock *MBB = StartIt->getParent();
Jessica Paquette78681be2017-07-27 23:24:43 +00001071
Jessica Paquette4e54ef82018-11-06 21:46:41 +00001072 CandidatesForRepeatedSeq.emplace_back(StartIdx, StringLen, StartIt,
Jessica Paquettecad864d2018-11-13 23:01:34 +00001073 EndIt, MBB, FunctionList.size(),
1074 Mapper.MBBFlagsMap[MBB]);
Jessica Paquette809d7082017-07-28 03:21:58 +00001075 }
1076 }
1077
Jessica Paquetteacc15e12017-10-03 20:32:55 +00001078 // We've found something we might want to outline.
1079 // Create an OutlinedFunction to store it and check if it'd be beneficial
1080 // to outline.
Jessica Paquetteddb039a2018-11-15 00:02:24 +00001081 if (CandidatesForRepeatedSeq.size() < 2)
Eli Friedmanda080782018-08-01 00:37:20 +00001082 continue;
1083
1084 // Arbitrarily choose a TII from the first candidate.
1085 // FIXME: Should getOutliningCandidateInfo move to TargetMachine?
1086 const TargetInstrInfo *TII =
1087 CandidatesForRepeatedSeq[0].getMF()->getSubtarget().getInstrInfo();
1088
Jessica Paquette9d93c602018-07-27 18:21:57 +00001089 OutlinedFunction OF =
Eli Friedmanda080782018-08-01 00:37:20 +00001090 TII->getOutliningCandidateInfo(CandidatesForRepeatedSeq);
Jessica Paquette9d93c602018-07-27 18:21:57 +00001091
Jessica Paquetteb2d53c52018-11-13 22:16:27 +00001092 // If we deleted too many candidates, then there's nothing worth outlining.
1093 // FIXME: This should take target-specified instruction sizes into account.
1094 if (OF.Candidates.size() < 2)
Jessica Paquette9d93c602018-07-27 18:21:57 +00001095 continue;
1096
Jessica Paquetteffe4abc2017-08-31 21:02:45 +00001097 // Is it better to outline this candidate than not?
Jessica Paquettef94d1d22018-07-24 17:36:13 +00001098 if (OF.getBenefit() < 1) {
Jessica Paquette1cc52a02018-07-24 17:37:28 +00001099 emitNotOutliningCheaperRemark(StringLen, CandidatesForRepeatedSeq, OF);
Jessica Paquette78681be2017-07-27 23:24:43 +00001100 continue;
Jessica Paquetteffe4abc2017-08-31 21:02:45 +00001101 }
Jessica Paquette78681be2017-07-27 23:24:43 +00001102
Jessica Paquetteacc15e12017-10-03 20:32:55 +00001103 FunctionList.push_back(OF);
Jessica Paquette78681be2017-07-27 23:24:43 +00001104 }
Jessica Paquette596f4832017-03-06 21:31:18 +00001105}
1106
Puyan Lotfi6b7615a2019-10-28 17:57:51 -04001107MachineFunction *MachineOutliner::createOutlinedFunction(
1108 Module &M, OutlinedFunction &OF, InstructionMapper &Mapper, unsigned Name) {
Jessica Paquette596f4832017-03-06 21:31:18 +00001109
Fangrui Songae6c9402019-04-10 14:52:37 +00001110 // Create the function name. This should be unique.
Jessica Paquettea3eb0fa2018-11-07 18:36:43 +00001111 // FIXME: We should have a better naming scheme. This should be stable,
1112 // regardless of changes to the outliner's cost model/traversal order.
Puyan Lotfi0c4aab22020-05-05 23:25:13 -04001113 std::string FunctionName = "OUTLINED_FUNCTION_";
Jin Lin0d896272020-03-17 15:40:26 -07001114 if (OutlineRepeatedNum > 0)
Puyan Lotfi0c4aab22020-05-05 23:25:13 -04001115 FunctionName += std::to_string(OutlineRepeatedNum + 1) + "_";
1116 FunctionName += std::to_string(Name);
Jessica Paquette596f4832017-03-06 21:31:18 +00001117
1118 // Create the function using an IR-level function.
1119 LLVMContext &C = M.getContext();
Fangrui Songae6c9402019-04-10 14:52:37 +00001120 Function *F = Function::Create(FunctionType::get(Type::getVoidTy(C), false),
1121 Function::ExternalLinkage, FunctionName, M);
Jessica Paquette596f4832017-03-06 21:31:18 +00001122
1123 // NOTE: If this is linkonceodr, then we can take advantage of linker deduping
1124 // which gives us better results when we outline from linkonceodr functions.
Jessica Paquetted506bf82018-04-03 21:36:00 +00001125 F->setLinkage(GlobalValue::InternalLinkage);
Jessica Paquette596f4832017-03-06 21:31:18 +00001126 F->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
1127
Eli Friedman25bef202018-05-15 23:36:46 +00001128 // FIXME: Set nounwind, so we don't generate eh_frame? Haven't verified it's
1129 // necessary.
1130
1131 // Set optsize/minsize, so we don't insert padding between outlined
1132 // functions.
1133 F->addFnAttr(Attribute::OptimizeForSize);
1134 F->addFnAttr(Attribute::MinSize);
1135
Jessica Paquettee3932ee2018-10-29 20:27:07 +00001136 // Include target features from an arbitrary candidate for the outlined
1137 // function. This makes sure the outlined function knows what kinds of
1138 // instructions are going into it. This is fine, since all parent functions
1139 // must necessarily support the instructions that are in the outlined region.
Jessica Paquettee18d6ff2018-12-05 23:24:22 +00001140 Candidate &FirstCand = OF.Candidates.front();
Jessica Paquette34b618b2018-12-05 17:57:33 +00001141 const Function &ParentFn = FirstCand.getMF()->getFunction();
Jessica Paquettee3932ee2018-10-29 20:27:07 +00001142 if (ParentFn.hasFnAttribute("target-features"))
1143 F->addFnAttr(ParentFn.getFnAttribute("target-features"));
1144
Jessica Paquette596f4832017-03-06 21:31:18 +00001145 BasicBlock *EntryBB = BasicBlock::Create(C, "entry", F);
1146 IRBuilder<> Builder(EntryBB);
1147 Builder.CreateRetVoid();
1148
Yuanfang Chencc382cf2019-09-30 17:54:50 +00001149 MachineModuleInfo &MMI = getAnalysis<MachineModuleInfoWrapperPass>().getMMI();
Matthias Braun7bda1952017-06-06 00:44:35 +00001150 MachineFunction &MF = MMI.getOrCreateMachineFunction(*F);
Jessica Paquette596f4832017-03-06 21:31:18 +00001151 MachineBasicBlock &MBB = *MF.CreateMachineBasicBlock();
1152 const TargetSubtargetInfo &STI = MF.getSubtarget();
1153 const TargetInstrInfo &TII = *STI.getInstrInfo();
1154
1155 // Insert the new function into the module.
1156 MF.insert(MF.begin(), &MBB);
1157
Andrew Litteken8d5024f2020-04-09 18:06:38 -07001158 MachineFunction *OriginalMF = FirstCand.front()->getMF();
1159 const std::vector<MCCFIInstruction> &Instrs =
1160 OriginalMF->getFrameInstructions();
Jessica Paquette34b618b2018-12-05 17:57:33 +00001161 for (auto I = FirstCand.front(), E = std::next(FirstCand.back()); I != E;
1162 ++I) {
1163 MachineInstr *NewMI = MF.CloneMachineInstr(&*I);
Andrew Litteken8d5024f2020-04-09 18:06:38 -07001164 if (I->isCFIInstruction()) {
1165 unsigned CFIIndex = NewMI->getOperand(0).getCFIIndex();
1166 MCCFIInstruction CFI = Instrs[CFIIndex];
1167 (void)MF.addFrameInst(CFI);
1168 }
Chandler Carruthc73c0302018-08-16 21:30:05 +00001169 NewMI->dropMemRefs(MF);
Jessica Paquette596f4832017-03-06 21:31:18 +00001170
1171 // Don't keep debug information for outlined instructions.
Jessica Paquette596f4832017-03-06 21:31:18 +00001172 NewMI->setDebugLoc(DebugLoc());
1173 MBB.insert(MBB.end(), NewMI);
1174 }
1175
Eli Friedman1a78b0b2020-04-21 17:40:41 -07001176 // Set normal properties for a late MachineFunction.
1177 MF.getProperties().reset(MachineFunctionProperties::Property::IsSSA);
1178 MF.getProperties().set(MachineFunctionProperties::Property::NoPHIs);
1179 MF.getProperties().set(MachineFunctionProperties::Property::NoVRegs);
1180 MF.getProperties().set(MachineFunctionProperties::Property::TracksLiveness);
Jessica Paquettecc06a782018-09-20 18:53:53 +00001181 MF.getRegInfo().freezeReservedRegs(MF);
1182
Eli Friedman1a78b0b2020-04-21 17:40:41 -07001183 // Compute live-in set for outlined fn
1184 const MachineRegisterInfo &MRI = MF.getRegInfo();
1185 const TargetRegisterInfo &TRI = *MRI.getTargetRegisterInfo();
1186 LivePhysRegs LiveIns(TRI);
1187 for (auto &Cand : OF.Candidates) {
1188 // Figure out live-ins at the first instruction.
1189 MachineBasicBlock &OutlineBB = *Cand.front()->getParent();
1190 LivePhysRegs CandLiveIns(TRI);
1191 CandLiveIns.addLiveOuts(OutlineBB);
1192 for (const MachineInstr &MI :
1193 reverse(make_range(Cand.front(), OutlineBB.end())))
1194 CandLiveIns.stepBackward(MI);
1195
1196 // The live-in set for the outlined function is the union of the live-ins
1197 // from all the outlining points.
1198 for (MCPhysReg Reg : make_range(CandLiveIns.begin(), CandLiveIns.end()))
1199 LiveIns.addReg(Reg);
1200 }
1201 addLiveIns(MBB, LiveIns);
1202
1203 TII.buildOutlinedFrame(MBB, MF, OF);
1204
Jessica Paquettea499c3c2018-01-19 21:21:49 +00001205 // If there's a DISubprogram associated with this outlined function, then
1206 // emit debug info for the outlined function.
Jessica Paquetteaa087322018-06-04 21:14:16 +00001207 if (DISubprogram *SP = getSubprogramOrNull(OF)) {
Jessica Paquettea499c3c2018-01-19 21:21:49 +00001208 // We have a DISubprogram. Get its DICompileUnit.
1209 DICompileUnit *CU = SP->getUnit();
1210 DIBuilder DB(M, true, CU);
1211 DIFile *Unit = SP->getFile();
1212 Mangler Mg;
Jessica Paquettecc06a782018-09-20 18:53:53 +00001213 // Get the mangled name of the function for the linkage name.
1214 std::string Dummy;
1215 llvm::raw_string_ostream MangledNameStream(Dummy);
1216 Mg.getNameWithPrefix(MangledNameStream, F, false);
Jessica Paquettea499c3c2018-01-19 21:21:49 +00001217
Jessica Paquettecc06a782018-09-20 18:53:53 +00001218 DISubprogram *OutlinedSP = DB.createFunction(
1219 Unit /* Context */, F->getName(), StringRef(MangledNameStream.str()),
1220 Unit /* File */,
1221 0 /* Line 0 is reserved for compiler-generated code. */,
1222 DB.createSubroutineType(DB.getOrCreateTypeArray(None)), /* void type */
Paul Robinsoncda54212018-11-19 18:29:28 +00001223 0, /* Line 0 is reserved for compiler-generated code. */
Jessica Paquettecc06a782018-09-20 18:53:53 +00001224 DINode::DIFlags::FlagArtificial /* Compiler-generated code. */,
Paul Robinsoncda54212018-11-19 18:29:28 +00001225 /* Outlined code is optimized code by definition. */
1226 DISubprogram::SPFlagDefinition | DISubprogram::SPFlagOptimized);
Jessica Paquettea499c3c2018-01-19 21:21:49 +00001227
Jessica Paquettecc06a782018-09-20 18:53:53 +00001228 // Don't add any new variables to the subprogram.
1229 DB.finalizeSubprogram(OutlinedSP);
Jessica Paquettea499c3c2018-01-19 21:21:49 +00001230
Jessica Paquettecc06a782018-09-20 18:53:53 +00001231 // Attach subprogram to the function.
1232 F->setSubprogram(OutlinedSP);
Jessica Paquettea499c3c2018-01-19 21:21:49 +00001233 // We're done with the DIBuilder.
1234 DB.finalize();
1235 }
1236
Jessica Paquette596f4832017-03-06 21:31:18 +00001237 return &MF;
1238}
1239
Jessica Paquette4ae3b712018-12-05 22:50:26 +00001240bool MachineOutliner::outline(Module &M,
1241 std::vector<OutlinedFunction> &FunctionList,
Puyan Lotfia51fc8d2019-10-28 15:10:21 -04001242 InstructionMapper &Mapper,
1243 unsigned &OutlinedFunctionNum) {
Jessica Paquette596f4832017-03-06 21:31:18 +00001244
1245 bool OutlinedSomething = false;
Jessica Paquettea3eb0fa2018-11-07 18:36:43 +00001246
Jessica Paquette962b3ae2018-12-05 21:36:04 +00001247 // Sort by benefit. The most beneficial functions should be outlined first.
Fangrui Songefd94c52019-04-23 14:51:27 +00001248 llvm::stable_sort(FunctionList, [](const OutlinedFunction &LHS,
1249 const OutlinedFunction &RHS) {
1250 return LHS.getBenefit() > RHS.getBenefit();
1251 });
Jessica Paquette596f4832017-03-06 21:31:18 +00001252
Jessica Paquette962b3ae2018-12-05 21:36:04 +00001253 // Walk over each function, outlining them as we go along. Functions are
1254 // outlined greedily, based off the sort above.
1255 for (OutlinedFunction &OF : FunctionList) {
1256 // If we outlined something that overlapped with a candidate in a previous
1257 // step, then we can't outline from it.
Jessica Paquettee18d6ff2018-12-05 23:24:22 +00001258 erase_if(OF.Candidates, [&Mapper](Candidate &C) {
Jessica Paquetted9d93092018-12-05 22:47:25 +00001259 return std::any_of(
Jessica Paquettee18d6ff2018-12-05 23:24:22 +00001260 Mapper.UnsignedVec.begin() + C.getStartIdx(),
1261 Mapper.UnsignedVec.begin() + C.getEndIdx() + 1,
Jessica Paquetted9d93092018-12-05 22:47:25 +00001262 [](unsigned I) { return (I == static_cast<unsigned>(-1)); });
Jessica Paquette235d8772018-12-05 22:27:38 +00001263 });
Jessica Paquette596f4832017-03-06 21:31:18 +00001264
Jessica Paquette962b3ae2018-12-05 21:36:04 +00001265 // If we made it unbeneficial to outline this function, skip it.
Jessica Paquette85af63d2017-10-17 19:03:23 +00001266 if (OF.getBenefit() < 1)
Jessica Paquette596f4832017-03-06 21:31:18 +00001267 continue;
1268
Jessica Paquette962b3ae2018-12-05 21:36:04 +00001269 // It's beneficial. Create the function and outline its sequence's
1270 // occurrences.
1271 OF.MF = createOutlinedFunction(M, OF, Mapper, OutlinedFunctionNum);
1272 emitOutlinedFunctionRemark(OF);
1273 FunctionsCreated++;
1274 OutlinedFunctionNum++; // Created a function, move to the next name.
Jessica Paquette596f4832017-03-06 21:31:18 +00001275 MachineFunction *MF = OF.MF;
1276 const TargetSubtargetInfo &STI = MF->getSubtarget();
1277 const TargetInstrInfo &TII = *STI.getInstrInfo();
1278
Jessica Paquette962b3ae2018-12-05 21:36:04 +00001279 // Replace occurrences of the sequence with calls to the new function.
Jessica Paquettee18d6ff2018-12-05 23:24:22 +00001280 for (Candidate &C : OF.Candidates) {
Jessica Paquette962b3ae2018-12-05 21:36:04 +00001281 MachineBasicBlock &MBB = *C.getMBB();
1282 MachineBasicBlock::iterator StartIt = C.front();
1283 MachineBasicBlock::iterator EndIt = C.back();
Jessica Paquette596f4832017-03-06 21:31:18 +00001284
Jessica Paquette962b3ae2018-12-05 21:36:04 +00001285 // Insert the call.
1286 auto CallInst = TII.insertOutlinedCall(M, MBB, StartIt, *MF, C);
Jessica Paquette0b672492018-04-27 23:36:35 +00001287
Jessica Paquette962b3ae2018-12-05 21:36:04 +00001288 // If the caller tracks liveness, then we need to make sure that
1289 // anything we outline doesn't break liveness assumptions. The outlined
1290 // functions themselves currently don't track liveness, but we should
1291 // make sure that the ranges we yank things out of aren't wrong.
1292 if (MBB.getParent()->getProperties().hasProperty(
1293 MachineFunctionProperties::Property::TracksLiveness)) {
Jin Linfc6fda92020-03-05 13:54:58 -08001294 // The following code is to add implicit def operands to the call
Djordje Todorovic71d38692019-06-27 13:10:29 +00001295 // instruction. It also updates call site information for moved
1296 // code.
Jin Linfc6fda92020-03-05 13:54:58 -08001297 SmallSet<Register, 2> UseRegs, DefRegs;
Jessica Paquette962b3ae2018-12-05 21:36:04 +00001298 // Copy over the defs in the outlined range.
1299 // First inst in outlined range <-- Anything that's defined in this
1300 // ... .. range has to be added as an
1301 // implicit Last inst in outlined range <-- def to the call
Djordje Todorovic71d38692019-06-27 13:10:29 +00001302 // instruction. Also remove call site information for outlined block
Jin Linfc6fda92020-03-05 13:54:58 -08001303 // of code. The exposed uses need to be copied in the outlined range.
Puyan Lotfiffd5e122020-04-29 03:33:47 -04001304 for (MachineBasicBlock::reverse_iterator
1305 Iter = EndIt.getReverse(),
1306 Last = std::next(CallInst.getReverse());
Jin Linfc6fda92020-03-05 13:54:58 -08001307 Iter != Last; Iter++) {
1308 MachineInstr *MI = &*Iter;
1309 for (MachineOperand &MOP : MI->operands()) {
1310 // Skip over anything that isn't a register.
1311 if (!MOP.isReg())
1312 continue;
1313
1314 if (MOP.isDef()) {
1315 // Introduce DefRegs set to skip the redundant register.
1316 DefRegs.insert(MOP.getReg());
1317 if (UseRegs.count(MOP.getReg()))
1318 // Since the regiester is modeled as defined,
1319 // it is not necessary to be put in use register set.
1320 UseRegs.erase(MOP.getReg());
1321 } else if (!MOP.isUndef()) {
1322 // Any register which is not undefined should
1323 // be put in the use register set.
1324 UseRegs.insert(MOP.getReg());
1325 }
1326 }
1327 if (MI->isCandidateForCallSiteEntry())
1328 MI->getMF()->eraseCallSiteInfo(MI);
1329 }
1330
1331 for (const Register &I : DefRegs)
Puyan Lotfiffd5e122020-04-29 03:33:47 -04001332 // If it's a def, add it to the call instruction.
1333 CallInst->addOperand(
1334 MachineOperand::CreateReg(I, true, /* isDef = true */
1335 true /* isImp = true */));
Jin Linfc6fda92020-03-05 13:54:58 -08001336
1337 for (const Register &I : UseRegs)
1338 // If it's a exposed use, add it to the call instruction.
1339 CallInst->addOperand(
1340 MachineOperand::CreateReg(I, false, /* isDef = false */
1341 true /* isImp = true */));
Jessica Paquette962b3ae2018-12-05 21:36:04 +00001342 }
1343
1344 // Erase from the point after where the call was inserted up to, and
1345 // including, the final instruction in the sequence.
1346 // Erase needs one past the end, so we need std::next there too.
1347 MBB.erase(std::next(StartIt), std::next(EndIt));
Jessica Paquette235d8772018-12-05 22:27:38 +00001348
Jessica Paquetted9d93092018-12-05 22:47:25 +00001349 // Keep track of what we removed by marking them all as -1.
Jessica Paquette235d8772018-12-05 22:27:38 +00001350 std::for_each(Mapper.UnsignedVec.begin() + C.getStartIdx(),
1351 Mapper.UnsignedVec.begin() + C.getEndIdx() + 1,
Jessica Paquetted9d93092018-12-05 22:47:25 +00001352 [](unsigned &I) { I = static_cast<unsigned>(-1); });
Jessica Paquette962b3ae2018-12-05 21:36:04 +00001353 OutlinedSomething = true;
1354
1355 // Statistics.
1356 NumOutlined++;
Jessica Paquette0b672492018-04-27 23:36:35 +00001357 }
Jessica Paquette596f4832017-03-06 21:31:18 +00001358 }
1359
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001360 LLVM_DEBUG(dbgs() << "OutlinedSomething = " << OutlinedSomething << "\n";);
Jessica Paquette596f4832017-03-06 21:31:18 +00001361 return OutlinedSomething;
1362}
1363
Jessica Paquette050d1ac2018-09-11 16:33:46 +00001364void MachineOutliner::populateMapper(InstructionMapper &Mapper, Module &M,
1365 MachineModuleInfo &MMI) {
Jessica Paquettedf822742018-03-22 21:07:09 +00001366 // Build instruction mappings for each function in the module. Start by
1367 // iterating over each Function in M.
Jessica Paquette596f4832017-03-06 21:31:18 +00001368 for (Function &F : M) {
Jessica Paquette596f4832017-03-06 21:31:18 +00001369
Jessica Paquettedf822742018-03-22 21:07:09 +00001370 // If there's nothing in F, then there's no reason to try and outline from
1371 // it.
1372 if (F.empty())
Jessica Paquette596f4832017-03-06 21:31:18 +00001373 continue;
1374
Jessica Paquettedf822742018-03-22 21:07:09 +00001375 // There's something in F. Check if it has a MachineFunction associated with
1376 // it.
1377 MachineFunction *MF = MMI.getMachineFunction(F);
Jessica Paquette596f4832017-03-06 21:31:18 +00001378
Jessica Paquettedf822742018-03-22 21:07:09 +00001379 // If it doesn't, then there's nothing to outline from. Move to the next
1380 // Function.
1381 if (!MF)
1382 continue;
1383
Eli Friedmanda080782018-08-01 00:37:20 +00001384 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
1385
Jessica Paquette8bda1882018-06-30 03:56:03 +00001386 if (!RunOnAllFunctions && !TII->shouldOutlineFromFunctionByDefault(*MF))
1387 continue;
1388
Jessica Paquettedf822742018-03-22 21:07:09 +00001389 // We have a MachineFunction. Ask the target if it's suitable for outlining.
1390 // If it isn't, then move on to the next Function in the module.
1391 if (!TII->isFunctionSafeToOutlineFrom(*MF, OutlineFromLinkOnceODRs))
1392 continue;
1393
1394 // We have a function suitable for outlining. Iterate over every
1395 // MachineBasicBlock in MF and try to map its instructions to a list of
1396 // unsigned integers.
1397 for (MachineBasicBlock &MBB : *MF) {
1398 // If there isn't anything in MBB, then there's no point in outlining from
1399 // it.
Jessica Paquetteb320ca22018-09-20 21:53:25 +00001400 // If there are fewer than 2 instructions in the MBB, then it can't ever
1401 // contain something worth outlining.
1402 // FIXME: This should be based off of the maximum size in B of an outlined
1403 // call versus the size in B of the MBB.
1404 if (MBB.empty() || MBB.size() < 2)
Jessica Paquette596f4832017-03-06 21:31:18 +00001405 continue;
1406
Jessica Paquettedf822742018-03-22 21:07:09 +00001407 // Check if MBB could be the target of an indirect branch. If it is, then
1408 // we don't want to outline from it.
1409 if (MBB.hasAddressTaken())
1410 continue;
1411
1412 // MBB is suitable for outlining. Map it to a list of unsigneds.
Eli Friedmanda080782018-08-01 00:37:20 +00001413 Mapper.convertToUnsignedVec(MBB, *TII);
Jessica Paquette596f4832017-03-06 21:31:18 +00001414 }
1415 }
Jessica Paquette050d1ac2018-09-11 16:33:46 +00001416}
1417
Jessica Paquette2386eab2018-09-11 23:05:34 +00001418void MachineOutliner::initSizeRemarkInfo(
1419 const Module &M, const MachineModuleInfo &MMI,
1420 StringMap<unsigned> &FunctionToInstrCount) {
1421 // Collect instruction counts for every function. We'll use this to emit
1422 // per-function size remarks later.
1423 for (const Function &F : M) {
1424 MachineFunction *MF = MMI.getMachineFunction(F);
1425
1426 // We only care about MI counts here. If there's no MachineFunction at this
1427 // point, then there won't be after the outliner runs, so let's move on.
1428 if (!MF)
1429 continue;
1430 FunctionToInstrCount[F.getName().str()] = MF->getInstructionCount();
1431 }
1432}
1433
1434void MachineOutliner::emitInstrCountChangedRemark(
1435 const Module &M, const MachineModuleInfo &MMI,
1436 const StringMap<unsigned> &FunctionToInstrCount) {
1437 // Iterate over each function in the module and emit remarks.
1438 // Note that we won't miss anything by doing this, because the outliner never
1439 // deletes functions.
1440 for (const Function &F : M) {
1441 MachineFunction *MF = MMI.getMachineFunction(F);
1442
1443 // The outliner never deletes functions. If we don't have a MF here, then we
1444 // didn't have one prior to outlining either.
1445 if (!MF)
1446 continue;
1447
Benjamin Krameradcd0262020-01-28 20:23:46 +01001448 std::string Fname = std::string(F.getName());
Jessica Paquette2386eab2018-09-11 23:05:34 +00001449 unsigned FnCountAfter = MF->getInstructionCount();
1450 unsigned FnCountBefore = 0;
1451
1452 // Check if the function was recorded before.
1453 auto It = FunctionToInstrCount.find(Fname);
1454
1455 // Did we have a previously-recorded size? If yes, then set FnCountBefore
1456 // to that.
1457 if (It != FunctionToInstrCount.end())
1458 FnCountBefore = It->second;
1459
1460 // Compute the delta and emit a remark if there was a change.
1461 int64_t FnDelta = static_cast<int64_t>(FnCountAfter) -
1462 static_cast<int64_t>(FnCountBefore);
1463 if (FnDelta == 0)
1464 continue;
1465
1466 MachineOptimizationRemarkEmitter MORE(*MF, nullptr);
1467 MORE.emit([&]() {
1468 MachineOptimizationRemarkAnalysis R("size-info", "FunctionMISizeChange",
Puyan Lotfi6b7615a2019-10-28 17:57:51 -04001469 DiagnosticLocation(), &MF->front());
Jessica Paquette2386eab2018-09-11 23:05:34 +00001470 R << DiagnosticInfoOptimizationBase::Argument("Pass", "Machine Outliner")
1471 << ": Function: "
1472 << DiagnosticInfoOptimizationBase::Argument("Function", F.getName())
1473 << ": MI instruction count changed from "
1474 << DiagnosticInfoOptimizationBase::Argument("MIInstrsBefore",
1475 FnCountBefore)
1476 << " to "
1477 << DiagnosticInfoOptimizationBase::Argument("MIInstrsAfter",
1478 FnCountAfter)
1479 << "; Delta: "
1480 << DiagnosticInfoOptimizationBase::Argument("Delta", FnDelta);
1481 return R;
1482 });
1483 }
1484}
1485
Puyan Lotfiffd5e122020-04-29 03:33:47 -04001486bool MachineOutliner::runOnModule(Module &M) {
Jessica Paquette050d1ac2018-09-11 16:33:46 +00001487 // Check if there's anything in the module. If it's empty, then there's
1488 // nothing to outline.
1489 if (M.empty())
1490 return false;
1491
Puyan Lotfia51fc8d2019-10-28 15:10:21 -04001492 // Number to append to the current outlined function.
1493 unsigned OutlinedFunctionNum = 0;
1494
Puyan Lotfiffd5e122020-04-29 03:33:47 -04001495 OutlineRepeatedNum = 0;
Puyan Lotfia51fc8d2019-10-28 15:10:21 -04001496 if (!doOutline(M, OutlinedFunctionNum))
1497 return false;
Puyan Lotfiffd5e122020-04-29 03:33:47 -04001498
1499 for (unsigned I = 0; I < OutlinerReruns; ++I) {
1500 OutlinedFunctionNum = 0;
1501 OutlineRepeatedNum++;
1502 if (!doOutline(M, OutlinedFunctionNum)) {
1503 LLVM_DEBUG({
1504 dbgs() << "Did not outline on iteration " << I + 2 << " out of "
1505 << OutlinerReruns + 1 << "\n";
1506 });
1507 break;
1508 }
1509 }
1510
Puyan Lotfia51fc8d2019-10-28 15:10:21 -04001511 return true;
1512}
1513
1514bool MachineOutliner::doOutline(Module &M, unsigned &OutlinedFunctionNum) {
Yuanfang Chencc382cf2019-09-30 17:54:50 +00001515 MachineModuleInfo &MMI = getAnalysis<MachineModuleInfoWrapperPass>().getMMI();
Jessica Paquette050d1ac2018-09-11 16:33:46 +00001516
1517 // If the user passed -enable-machine-outliner=always or
1518 // -enable-machine-outliner, the pass will run on all functions in the module.
1519 // Otherwise, if the target supports default outlining, it will run on all
1520 // functions deemed by the target to be worth outlining from by default. Tell
1521 // the user how the outliner is running.
Puyan Lotfi6b7615a2019-10-28 17:57:51 -04001522 LLVM_DEBUG({
Jessica Paquette050d1ac2018-09-11 16:33:46 +00001523 dbgs() << "Machine Outliner: Running on ";
1524 if (RunOnAllFunctions)
1525 dbgs() << "all functions";
1526 else
1527 dbgs() << "target-default functions";
Puyan Lotfi6b7615a2019-10-28 17:57:51 -04001528 dbgs() << "\n";
1529 });
Jessica Paquette050d1ac2018-09-11 16:33:46 +00001530
1531 // If the user specifies that they want to outline from linkonceodrs, set
1532 // it here.
1533 OutlineFromLinkOnceODRs = EnableLinkOnceODROutlining;
1534 InstructionMapper Mapper;
1535
1536 // Prepare instruction mappings for the suffix tree.
1537 populateMapper(Mapper, M, MMI);
Jessica Paquette596f4832017-03-06 21:31:18 +00001538 std::vector<OutlinedFunction> FunctionList;
1539
Jessica Paquetteacffa282017-03-23 21:27:38 +00001540 // Find all of the outlining candidates.
Jessica Paquettece3a2dc2018-12-05 23:39:07 +00001541 findCandidates(Mapper, FunctionList);
Jessica Paquetteacffa282017-03-23 21:27:38 +00001542
Jessica Paquette2386eab2018-09-11 23:05:34 +00001543 // If we've requested size remarks, then collect the MI counts of every
1544 // function before outlining, and the MI counts after outlining.
1545 // FIXME: This shouldn't be in the outliner at all; it should ultimately be
1546 // the pass manager's responsibility.
1547 // This could pretty easily be placed in outline instead, but because we
1548 // really ultimately *don't* want this here, it's done like this for now
1549 // instead.
1550
1551 // Check if we want size remarks.
1552 bool ShouldEmitSizeRemarks = M.shouldEmitInstrCountChangedRemark();
1553 StringMap<unsigned> FunctionToInstrCount;
1554 if (ShouldEmitSizeRemarks)
1555 initSizeRemarkInfo(M, MMI, FunctionToInstrCount);
1556
Jessica Paquetteacffa282017-03-23 21:27:38 +00001557 // Outline each of the candidates and return true if something was outlined.
Puyan Lotfia51fc8d2019-10-28 15:10:21 -04001558 bool OutlinedSomething =
1559 outline(M, FunctionList, Mapper, OutlinedFunctionNum);
Jessica Paquette729e6862018-01-18 00:00:58 +00001560
Jessica Paquette2386eab2018-09-11 23:05:34 +00001561 // If we outlined something, we definitely changed the MI count of the
1562 // module. If we've asked for size remarks, then output them.
1563 // FIXME: This should be in the pass manager.
1564 if (ShouldEmitSizeRemarks && OutlinedSomething)
1565 emitInstrCountChangedRemark(M, MMI, FunctionToInstrCount);
1566
Puyan Lotfiffd5e122020-04-29 03:33:47 -04001567 LLVM_DEBUG({
1568 if (!OutlinedSomething)
1569 dbgs() << "Stopped outlining at iteration " << OutlineRepeatedNum
1570 << " because no changes were found.\n";
1571 });
1572
Jessica Paquette729e6862018-01-18 00:00:58 +00001573 return OutlinedSomething;
Jessica Paquette596f4832017-03-06 21:31:18 +00001574}