1 //===---- 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 ///
18 /// The MachineOutliner communicates with a given target using hooks defined in
19 /// TargetInstrInfo.h. The target supplies the outliner with information on how
20 /// a specific sequence of instructions should be outlined. This information
21 /// is used to deduce the number of instructions necessary to
22 ///
23 /// * Create an outlined function
24 /// * Call that outlined function
25 ///
26 /// Targets must implement
27 ///   * getOutliningCandidateInfo
28 ///   * insertOutlinerEpilogue
29 ///   * insertOutlinedCall
30 ///   * insertOutlinerPrologue
31 ///   * isFunctionSafeToOutlineFrom
32 ///
33 /// in order to make use of the MachineOutliner.
34 ///
35 /// This was originally presented at the 2016 LLVM Developers' Meeting in the
36 /// talk "Reducing Code Size Using Outlining". For a high-level overview of
37 /// how this pass works, the talk is available on YouTube at
38 ///
39 /// https://www.youtube.com/watch?v=yorld-WSOeU
40 ///
41 /// The slides for the talk are available at
42 ///
43 /// http://www.llvm.org/devmtg/2016-11/Slides/Paquette-Outliner.pdf
44 ///
45 /// The talk provides an overview of how the outliner finds candidates and
46 /// ultimately outlines them. It describes how the main data structure for this
47 /// pass, the suffix tree, is queried and purged for candidates. It also gives
48 /// a simplified suffix tree construction algorithm for suffix trees based off
49 /// of the algorithm actually used here, Ukkonen's algorithm.
50 ///
51 /// For the original RFC for this pass, please see
52 ///
53 /// http://lists.llvm.org/pipermail/llvm-dev/2016-August/104170.html
54 ///
55 /// For more information on the suffix tree data structure, please see
56 /// https://www.cs.helsinki.fi/u/ukkonen/SuffixT1withFigs.pdf
57 ///
58 //===----------------------------------------------------------------------===//
59 #include "llvm/ADT/DenseMap.h"
60 #include "llvm/ADT/Statistic.h"
61 #include "llvm/ADT/Twine.h"
62 #include "llvm/CodeGen/MachineFunction.h"
63 #include "llvm/CodeGen/MachineModuleInfo.h"
64 #include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h"
65 #include "llvm/CodeGen/MachineRegisterInfo.h"
66 #include "llvm/CodeGen/Passes.h"
67 #include "llvm/CodeGen/TargetInstrInfo.h"
68 #include "llvm/CodeGen/TargetRegisterInfo.h"
69 #include "llvm/CodeGen/TargetSubtargetInfo.h"
70 #include "llvm/IR/DIBuilder.h"
71 #include "llvm/IR/IRBuilder.h"
72 #include "llvm/IR/Mangler.h"
73 #include "llvm/Support/Allocator.h"
74 #include "llvm/Support/CommandLine.h"
75 #include "llvm/Support/Debug.h"
76 #include "llvm/Support/raw_ostream.h"
77 #include <functional>
78 #include <map>
79 #include <sstream>
80 #include <tuple>
81 #include <vector>
82 
83 #define DEBUG_TYPE "machine-outliner"
84 
85 using namespace llvm;
86 using namespace ore;
87 
88 STATISTIC(NumOutlined, "Number of candidates outlined");
89 STATISTIC(FunctionsCreated, "Number of functions created");
90 
91 // 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.
96 static 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 
102 namespace {
103 
104 /// An individual sequence of instructions to be replaced with a call to
105 /// an outlined function.
106 struct Candidate {
107 private:
108   /// The start index of this \p Candidate in the instruction list.
109   unsigned StartIdx;
110 
111   /// The number of instructions in this \p Candidate.
112   unsigned Len;
113 
114   /// The MachineFunction containing this \p Candidate.
115   MachineFunction *MF = nullptr;
116 
117 public:
118   /// Set to false if the candidate overlapped with another candidate.
119   bool InCandidateList = true;
120 
121   /// The index of this \p Candidate's \p OutlinedFunction in the list of
122   /// \p OutlinedFunctions.
123   unsigned FunctionIdx;
124 
125   /// Contains all target-specific information for this \p Candidate.
126   TargetInstrInfo::MachineOutlinerInfo MInfo;
127 
128   /// If there is a DISubprogram associated with the function that this
129   /// Candidate lives in, return it.
130   DISubprogram *getSubprogramOrNull() const {
131     assert(MF && "Candidate has no MF!");
132     if (DISubprogram *SP = MF->getFunction().getSubprogram())
133       return SP;
134     return nullptr;
135   }
136 
137   /// Return the number of instructions in this Candidate.
138   unsigned getLength() const { return Len; }
139 
140   /// Return the start index of this candidate.
141   unsigned getStartIdx() const { return StartIdx; }
142 
143   // Return the end index of this candidate.
144   unsigned getEndIdx() const { return StartIdx + Len - 1; }
145 
146   /// The number of instructions that would be saved by outlining every
147   /// candidate of this type.
148   ///
149   /// This is a fixed value which is not updated during the candidate pruning
150   /// process. It is only used for deciding which candidate to keep if two
151   /// candidates overlap. The true benefit is stored in the OutlinedFunction
152   /// for some given candidate.
153   unsigned Benefit = 0;
154 
155   Candidate(unsigned StartIdx, unsigned Len, unsigned FunctionIdx,
156             MachineFunction *MF)
157       : StartIdx(StartIdx), Len(Len), MF(MF), FunctionIdx(FunctionIdx) {}
158 
159   Candidate() {}
160 
161   /// Used to ensure that \p Candidates are outlined in an order that
162   /// preserves the start and end indices of other \p Candidates.
163   bool operator<(const Candidate &RHS) const {
164     return getStartIdx() > RHS.getStartIdx();
165   }
166 };
167 
168 /// The information necessary to create an outlined function for some
169 /// class of candidate.
170 struct OutlinedFunction {
171 
172 private:
173   /// The number of candidates for this \p OutlinedFunction.
174   unsigned OccurrenceCount = 0;
175 
176 public:
177   std::vector<std::shared_ptr<Candidate>> Candidates;
178 
179   /// The actual outlined function created.
180   /// This is initialized after we go through and create the actual function.
181   MachineFunction *MF = nullptr;
182 
183   /// A number assigned to this function which appears at the end of its name.
184   unsigned Name;
185 
186   /// The sequence of integers corresponding to the instructions in this
187   /// function.
188   std::vector<unsigned> Sequence;
189 
190   /// Contains all target-specific information for this \p OutlinedFunction.
191   TargetInstrInfo::MachineOutlinerInfo MInfo;
192 
193   /// If there is a DISubprogram for any Candidate for this outlined function,
194   /// then return it. Otherwise, return nullptr.
195   DISubprogram *getSubprogramOrNull() const {
196     for (const auto &C : Candidates)
197       if (DISubprogram *SP = C->getSubprogramOrNull())
198         return SP;
199     return nullptr;
200   }
201 
202   /// Return the number of candidates for this \p OutlinedFunction.
203   unsigned getOccurrenceCount() { return OccurrenceCount; }
204 
205   /// Decrement the occurrence count of this OutlinedFunction and return the
206   /// new count.
207   unsigned decrement() {
208     assert(OccurrenceCount > 0 && "Can't decrement an empty function!");
209     OccurrenceCount--;
210     return getOccurrenceCount();
211   }
212 
213   /// Return the number of bytes it would take to outline this
214   /// function.
215   unsigned getOutliningCost() {
216     return (OccurrenceCount * MInfo.CallOverhead) + MInfo.SequenceSize +
217            MInfo.FrameOverhead;
218   }
219 
220   /// Return the size in bytes of the unoutlined sequences.
221   unsigned getNotOutlinedCost() {
222     return OccurrenceCount * MInfo.SequenceSize;
223   }
224 
225   /// Return the number of instructions that would be saved by outlining
226   /// this function.
227   unsigned getBenefit() {
228     unsigned NotOutlinedCost = getNotOutlinedCost();
229     unsigned OutlinedCost = getOutliningCost();
230     return (NotOutlinedCost < OutlinedCost) ? 0
231                                             : NotOutlinedCost - OutlinedCost;
232   }
233 
234   OutlinedFunction(unsigned Name, unsigned OccurrenceCount,
235                    const std::vector<unsigned> &Sequence,
236                    TargetInstrInfo::MachineOutlinerInfo &MInfo)
237       : OccurrenceCount(OccurrenceCount), Name(Name), Sequence(Sequence),
238         MInfo(MInfo) {}
239 };
240 
241 /// Represents an undefined index in the suffix tree.
242 const unsigned EmptyIdx = -1;
243 
244 /// A node in a suffix tree which represents a substring or suffix.
245 ///
246 /// Each node has either no children or at least two children, with the root
247 /// being a exception in the empty tree.
248 ///
249 /// Children are represented as a map between unsigned integers and nodes. If
250 /// a node N has a child M on unsigned integer k, then the mapping represented
251 /// by N is a proper prefix of the mapping represented by M. Note that this,
252 /// although similar to a trie is somewhat different: each node stores a full
253 /// substring of the full mapping rather than a single character state.
254 ///
255 /// Each internal node contains a pointer to the internal node representing
256 /// the same string, but with the first character chopped off. This is stored
257 /// in \p Link. Each leaf node stores the start index of its respective
258 /// suffix in \p SuffixIdx.
259 struct SuffixTreeNode {
260 
261   /// The children of this node.
262   ///
263   /// A child existing on an unsigned integer implies that from the mapping
264   /// represented by the current node, there is a way to reach another
265   /// mapping by tacking that character on the end of the current string.
266   DenseMap<unsigned, SuffixTreeNode *> Children;
267 
268   /// A flag set to false if the node has been pruned from the tree.
269   bool IsInTree = true;
270 
271   /// The start index of this node's substring in the main string.
272   unsigned StartIdx = EmptyIdx;
273 
274   /// The end index of this node's substring in the main string.
275   ///
276   /// Every leaf node must have its \p EndIdx incremented at the end of every
277   /// step in the construction algorithm. To avoid having to update O(N)
278   /// nodes individually at the end of every step, the end index is stored
279   /// as a pointer.
280   unsigned *EndIdx = nullptr;
281 
282   /// For leaves, the start index of the suffix represented by this node.
283   ///
284   /// For all other nodes, this is ignored.
285   unsigned SuffixIdx = EmptyIdx;
286 
287   /// For internal nodes, a pointer to the internal node representing
288   /// the same sequence with the first character chopped off.
289   ///
290   /// This acts as a shortcut in Ukkonen's algorithm. One of the things that
291   /// Ukkonen's algorithm does to achieve linear-time construction is
292   /// keep track of which node the next insert should be at. This makes each
293   /// insert O(1), and there are a total of O(N) inserts. The suffix link
294   /// helps with inserting children of internal nodes.
295   ///
296   /// Say we add a child to an internal node with associated mapping S. The
297   /// next insertion must be at the node representing S - its first character.
298   /// This is given by the way that we iteratively build the tree in Ukkonen's
299   /// algorithm. The main idea is to look at the suffixes of each prefix in the
300   /// string, starting with the longest suffix of the prefix, and ending with
301   /// the shortest. Therefore, if we keep pointers between such nodes, we can
302   /// move to the next insertion point in O(1) time. If we don't, then we'd
303   /// have to query from the root, which takes O(N) time. This would make the
304   /// construction algorithm O(N^2) rather than O(N).
305   SuffixTreeNode *Link = nullptr;
306 
307   /// The parent of this node. Every node except for the root has a parent.
308   SuffixTreeNode *Parent = nullptr;
309 
310   /// The number of times this node's string appears in the tree.
311   ///
312   /// This is equal to the number of leaf children of the string. It represents
313   /// the number of suffixes that the node's string is a prefix of.
314   unsigned OccurrenceCount = 0;
315 
316   /// The length of the string formed by concatenating the edge labels from the
317   /// root to this node.
318   unsigned ConcatLen = 0;
319 
320   /// Returns true if this node is a leaf.
321   bool isLeaf() const { return SuffixIdx != EmptyIdx; }
322 
323   /// Returns true if this node is the root of its owning \p SuffixTree.
324   bool isRoot() const { return StartIdx == EmptyIdx; }
325 
326   /// Return the number of elements in the substring associated with this node.
327   size_t size() const {
328 
329     // Is it the root? If so, it's the empty string so return 0.
330     if (isRoot())
331       return 0;
332 
333     assert(*EndIdx != EmptyIdx && "EndIdx is undefined!");
334 
335     // Size = the number of elements in the string.
336     // For example, [0 1 2 3] has length 4, not 3. 3-0 = 3, so we have 3-0+1.
337     return *EndIdx - StartIdx + 1;
338   }
339 
340   SuffixTreeNode(unsigned StartIdx, unsigned *EndIdx, SuffixTreeNode *Link,
341                  SuffixTreeNode *Parent)
342       : StartIdx(StartIdx), EndIdx(EndIdx), Link(Link), Parent(Parent) {}
343 
344   SuffixTreeNode() {}
345 };
346 
347 /// A data structure for fast substring queries.
348 ///
349 /// Suffix trees represent the suffixes of their input strings in their leaves.
350 /// A suffix tree is a type of compressed trie structure where each node
351 /// represents an entire substring rather than a single character. Each leaf
352 /// of the tree is a suffix.
353 ///
354 /// A suffix tree can be seen as a type of state machine where each state is a
355 /// substring of the full string. The tree is structured so that, for a string
356 /// of length N, there are exactly N leaves in the tree. This structure allows
357 /// us to quickly find repeated substrings of the input string.
358 ///
359 /// In this implementation, a "string" is a vector of unsigned integers.
360 /// These integers may result from hashing some data type. A suffix tree can
361 /// contain 1 or many strings, which can then be queried as one large string.
362 ///
363 /// The suffix tree is implemented using Ukkonen's algorithm for linear-time
364 /// suffix tree construction. Ukkonen's algorithm is explained in more detail
365 /// in the paper by Esko Ukkonen "On-line construction of suffix trees. The
366 /// paper is available at
367 ///
368 /// https://www.cs.helsinki.fi/u/ukkonen/SuffixT1withFigs.pdf
369 class SuffixTree {
370 public:
371   /// Stores each leaf node in the tree.
372   ///
373   /// This is used for finding outlining candidates.
374   std::vector<SuffixTreeNode *> LeafVector;
375 
376   /// Each element is an integer representing an instruction in the module.
377   ArrayRef<unsigned> Str;
378 
379 private:
380   /// Maintains each node in the tree.
381   SpecificBumpPtrAllocator<SuffixTreeNode> NodeAllocator;
382 
383   /// The root of the suffix tree.
384   ///
385   /// The root represents the empty string. It is maintained by the
386   /// \p NodeAllocator like every other node in the tree.
387   SuffixTreeNode *Root = nullptr;
388 
389   /// Maintains the end indices of the internal nodes in the tree.
390   ///
391   /// Each internal node is guaranteed to never have its end index change
392   /// during the construction algorithm; however, leaves must be updated at
393   /// every step. Therefore, we need to store leaf end indices by reference
394   /// to avoid updating O(N) leaves at every step of construction. Thus,
395   /// every internal node must be allocated its own end index.
396   BumpPtrAllocator InternalEndIdxAllocator;
397 
398   /// The end index of each leaf in the tree.
399   unsigned LeafEndIdx = -1;
400 
401   /// Helper struct which keeps track of the next insertion point in
402   /// Ukkonen's algorithm.
403   struct ActiveState {
404     /// The next node to insert at.
405     SuffixTreeNode *Node;
406 
407     /// The index of the first character in the substring currently being added.
408     unsigned Idx = EmptyIdx;
409 
410     /// The length of the substring we have to add at the current step.
411     unsigned Len = 0;
412   };
413 
414   /// The point the next insertion will take place at in the
415   /// construction algorithm.
416   ActiveState Active;
417 
418   /// Allocate a leaf node and add it to the tree.
419   ///
420   /// \param Parent The parent of this node.
421   /// \param StartIdx The start index of this node's associated string.
422   /// \param Edge The label on the edge leaving \p Parent to this node.
423   ///
424   /// \returns A pointer to the allocated leaf node.
425   SuffixTreeNode *insertLeaf(SuffixTreeNode &Parent, unsigned StartIdx,
426                              unsigned Edge) {
427 
428     assert(StartIdx <= LeafEndIdx && "String can't start after it ends!");
429 
430     SuffixTreeNode *N = new (NodeAllocator.Allocate())
431         SuffixTreeNode(StartIdx, &LeafEndIdx, nullptr, &Parent);
432     Parent.Children[Edge] = N;
433 
434     return N;
435   }
436 
437   /// Allocate an internal node and add it to the tree.
438   ///
439   /// \param Parent The parent of this node. Only null when allocating the root.
440   /// \param StartIdx The start index of this node's associated string.
441   /// \param EndIdx The end index of this node's associated string.
442   /// \param Edge The label on the edge leaving \p Parent to this node.
443   ///
444   /// \returns A pointer to the allocated internal node.
445   SuffixTreeNode *insertInternalNode(SuffixTreeNode *Parent, unsigned StartIdx,
446                                      unsigned EndIdx, unsigned Edge) {
447 
448     assert(StartIdx <= EndIdx && "String can't start after it ends!");
449     assert(!(!Parent && StartIdx != EmptyIdx) &&
450            "Non-root internal nodes must have parents!");
451 
452     unsigned *E = new (InternalEndIdxAllocator) unsigned(EndIdx);
453     SuffixTreeNode *N = new (NodeAllocator.Allocate())
454         SuffixTreeNode(StartIdx, E, Root, Parent);
455     if (Parent)
456       Parent->Children[Edge] = N;
457 
458     return N;
459   }
460 
461   /// Set the suffix indices of the leaves to the start indices of their
462   /// respective suffixes. Also stores each leaf in \p LeafVector at its
463   /// respective suffix index.
464   ///
465   /// \param[in] CurrNode The node currently being visited.
466   /// \param CurrIdx The current index of the string being visited.
467   void setSuffixIndices(SuffixTreeNode &CurrNode, unsigned CurrIdx) {
468 
469     bool IsLeaf = CurrNode.Children.size() == 0 && !CurrNode.isRoot();
470 
471     // Store the length of the concatenation of all strings from the root to
472     // this node.
473     if (!CurrNode.isRoot()) {
474       if (CurrNode.ConcatLen == 0)
475         CurrNode.ConcatLen = CurrNode.size();
476 
477       if (CurrNode.Parent)
478         CurrNode.ConcatLen += CurrNode.Parent->ConcatLen;
479     }
480 
481     // Traverse the tree depth-first.
482     for (auto &ChildPair : CurrNode.Children) {
483       assert(ChildPair.second && "Node had a null child!");
484       setSuffixIndices(*ChildPair.second, CurrIdx + ChildPair.second->size());
485     }
486 
487     // Is this node a leaf?
488     if (IsLeaf) {
489       // If yes, give it a suffix index and bump its parent's occurrence count.
490       CurrNode.SuffixIdx = Str.size() - CurrIdx;
491       assert(CurrNode.Parent && "CurrNode had no parent!");
492       CurrNode.Parent->OccurrenceCount++;
493 
494       // Store the leaf in the leaf vector for pruning later.
495       LeafVector[CurrNode.SuffixIdx] = &CurrNode;
496     }
497   }
498 
499   /// Construct the suffix tree for the prefix of the input ending at
500   /// \p EndIdx.
501   ///
502   /// Used to construct the full suffix tree iteratively. At the end of each
503   /// step, the constructed suffix tree is either a valid suffix tree, or a
504   /// suffix tree with implicit suffixes. At the end of the final step, the
505   /// suffix tree is a valid tree.
506   ///
507   /// \param EndIdx The end index of the current prefix in the main string.
508   /// \param SuffixesToAdd The number of suffixes that must be added
509   /// to complete the suffix tree at the current phase.
510   ///
511   /// \returns The number of suffixes that have not been added at the end of
512   /// this step.
513   unsigned extend(unsigned EndIdx, unsigned SuffixesToAdd) {
514     SuffixTreeNode *NeedsLink = nullptr;
515 
516     while (SuffixesToAdd > 0) {
517 
518       // Are we waiting to add anything other than just the last character?
519       if (Active.Len == 0) {
520         // If not, then say the active index is the end index.
521         Active.Idx = EndIdx;
522       }
523 
524       assert(Active.Idx <= EndIdx && "Start index can't be after end index!");
525 
526       // The first character in the current substring we're looking at.
527       unsigned FirstChar = Str[Active.Idx];
528 
529       // Have we inserted anything starting with FirstChar at the current node?
530       if (Active.Node->Children.count(FirstChar) == 0) {
531         // If not, then we can just insert a leaf and move too the next step.
532         insertLeaf(*Active.Node, EndIdx, FirstChar);
533 
534         // The active node is an internal node, and we visited it, so it must
535         // need a link if it doesn't have one.
536         if (NeedsLink) {
537           NeedsLink->Link = Active.Node;
538           NeedsLink = nullptr;
539         }
540       } else {
541         // There's a match with FirstChar, so look for the point in the tree to
542         // insert a new node.
543         SuffixTreeNode *NextNode = Active.Node->Children[FirstChar];
544 
545         unsigned SubstringLen = NextNode->size();
546 
547         // Is the current suffix we're trying to insert longer than the size of
548         // the child we want to move to?
549         if (Active.Len >= SubstringLen) {
550           // If yes, then consume the characters we've seen and move to the next
551           // node.
552           Active.Idx += SubstringLen;
553           Active.Len -= SubstringLen;
554           Active.Node = NextNode;
555           continue;
556         }
557 
558         // Otherwise, the suffix we're trying to insert must be contained in the
559         // next node we want to move to.
560         unsigned LastChar = Str[EndIdx];
561 
562         // Is the string we're trying to insert a substring of the next node?
563         if (Str[NextNode->StartIdx + Active.Len] == LastChar) {
564           // If yes, then we're done for this step. Remember our insertion point
565           // and move to the next end index. At this point, we have an implicit
566           // suffix tree.
567           if (NeedsLink && !Active.Node->isRoot()) {
568             NeedsLink->Link = Active.Node;
569             NeedsLink = nullptr;
570           }
571 
572           Active.Len++;
573           break;
574         }
575 
576         // The string we're trying to insert isn't a substring of the next node,
577         // but matches up to a point. Split the node.
578         //
579         // For example, say we ended our search at a node n and we're trying to
580         // insert ABD. Then we'll create a new node s for AB, reduce n to just
581         // representing C, and insert a new leaf node l to represent d. This
582         // allows us to ensure that if n was a leaf, it remains a leaf.
583         //
584         //   | ABC  ---split--->  | AB
585         //   n                    s
586         //                     C / \ D
587         //                      n   l
588 
589         // The node s from the diagram
590         SuffixTreeNode *SplitNode =
591             insertInternalNode(Active.Node, NextNode->StartIdx,
592                                NextNode->StartIdx + Active.Len - 1, FirstChar);
593 
594         // Insert the new node representing the new substring into the tree as
595         // a child of the split node. This is the node l from the diagram.
596         insertLeaf(*SplitNode, EndIdx, LastChar);
597 
598         // Make the old node a child of the split node and update its start
599         // index. This is the node n from the diagram.
600         NextNode->StartIdx += Active.Len;
601         NextNode->Parent = SplitNode;
602         SplitNode->Children[Str[NextNode->StartIdx]] = NextNode;
603 
604         // SplitNode is an internal node, update the suffix link.
605         if (NeedsLink)
606           NeedsLink->Link = SplitNode;
607 
608         NeedsLink = SplitNode;
609       }
610 
611       // We've added something new to the tree, so there's one less suffix to
612       // add.
613       SuffixesToAdd--;
614 
615       if (Active.Node->isRoot()) {
616         if (Active.Len > 0) {
617           Active.Len--;
618           Active.Idx = EndIdx - SuffixesToAdd + 1;
619         }
620       } else {
621         // Start the next phase at the next smallest suffix.
622         Active.Node = Active.Node->Link;
623       }
624     }
625 
626     return SuffixesToAdd;
627   }
628 
629 public:
630   /// Construct a suffix tree from a sequence of unsigned integers.
631   ///
632   /// \param Str The string to construct the suffix tree for.
633   SuffixTree(const std::vector<unsigned> &Str) : Str(Str) {
634     Root = insertInternalNode(nullptr, EmptyIdx, EmptyIdx, 0);
635     Root->IsInTree = true;
636     Active.Node = Root;
637     LeafVector = std::vector<SuffixTreeNode *>(Str.size());
638 
639     // Keep track of the number of suffixes we have to add of the current
640     // prefix.
641     unsigned SuffixesToAdd = 0;
642     Active.Node = Root;
643 
644     // Construct the suffix tree iteratively on each prefix of the string.
645     // PfxEndIdx is the end index of the current prefix.
646     // End is one past the last element in the string.
647     for (unsigned PfxEndIdx = 0, End = Str.size(); PfxEndIdx < End;
648          PfxEndIdx++) {
649       SuffixesToAdd++;
650       LeafEndIdx = PfxEndIdx; // Extend each of the leaves.
651       SuffixesToAdd = extend(PfxEndIdx, SuffixesToAdd);
652     }
653 
654     // Set the suffix indices of each leaf.
655     assert(Root && "Root node can't be nullptr!");
656     setSuffixIndices(*Root, 0);
657   }
658 };
659 
660 /// Maps \p MachineInstrs to unsigned integers and stores the mappings.
661 struct InstructionMapper {
662 
663   /// The next available integer to assign to a \p MachineInstr that
664   /// cannot be outlined.
665   ///
666   /// Set to -3 for compatability with \p DenseMapInfo<unsigned>.
667   unsigned IllegalInstrNumber = -3;
668 
669   /// The next available integer to assign to a \p MachineInstr that can
670   /// be outlined.
671   unsigned LegalInstrNumber = 0;
672 
673   /// Correspondence from \p MachineInstrs to unsigned integers.
674   DenseMap<MachineInstr *, unsigned, MachineInstrExpressionTrait>
675       InstructionIntegerMap;
676 
677   /// Corresponcence from unsigned integers to \p MachineInstrs.
678   /// Inverse of \p InstructionIntegerMap.
679   DenseMap<unsigned, MachineInstr *> IntegerInstructionMap;
680 
681   /// The vector of unsigned integers that the module is mapped to.
682   std::vector<unsigned> UnsignedVec;
683 
684   /// Stores the location of the instruction associated with the integer
685   /// at index i in \p UnsignedVec for each index i.
686   std::vector<MachineBasicBlock::iterator> InstrList;
687 
688   /// Maps \p *It to a legal integer.
689   ///
690   /// Updates \p InstrList, \p UnsignedVec, \p InstructionIntegerMap,
691   /// \p IntegerInstructionMap, and \p LegalInstrNumber.
692   ///
693   /// \returns The integer that \p *It was mapped to.
694   unsigned mapToLegalUnsigned(MachineBasicBlock::iterator &It) {
695 
696     // Get the integer for this instruction or give it the current
697     // LegalInstrNumber.
698     InstrList.push_back(It);
699     MachineInstr &MI = *It;
700     bool WasInserted;
701     DenseMap<MachineInstr *, unsigned, MachineInstrExpressionTrait>::iterator
702         ResultIt;
703     std::tie(ResultIt, WasInserted) =
704         InstructionIntegerMap.insert(std::make_pair(&MI, LegalInstrNumber));
705     unsigned MINumber = ResultIt->second;
706 
707     // There was an insertion.
708     if (WasInserted) {
709       LegalInstrNumber++;
710       IntegerInstructionMap.insert(std::make_pair(MINumber, &MI));
711     }
712 
713     UnsignedVec.push_back(MINumber);
714 
715     // Make sure we don't overflow or use any integers reserved by the DenseMap.
716     if (LegalInstrNumber >= IllegalInstrNumber)
717       report_fatal_error("Instruction mapping overflow!");
718 
719     assert(LegalInstrNumber != DenseMapInfo<unsigned>::getEmptyKey() &&
720            "Tried to assign DenseMap tombstone or empty key to instruction.");
721     assert(LegalInstrNumber != DenseMapInfo<unsigned>::getTombstoneKey() &&
722            "Tried to assign DenseMap tombstone or empty key to instruction.");
723 
724     return MINumber;
725   }
726 
727   /// Maps \p *It to an illegal integer.
728   ///
729   /// Updates \p InstrList, \p UnsignedVec, and \p IllegalInstrNumber.
730   ///
731   /// \returns The integer that \p *It was mapped to.
732   unsigned mapToIllegalUnsigned(MachineBasicBlock::iterator &It) {
733     unsigned MINumber = IllegalInstrNumber;
734 
735     InstrList.push_back(It);
736     UnsignedVec.push_back(IllegalInstrNumber);
737     IllegalInstrNumber--;
738 
739     assert(LegalInstrNumber < IllegalInstrNumber &&
740            "Instruction mapping overflow!");
741 
742     assert(IllegalInstrNumber != DenseMapInfo<unsigned>::getEmptyKey() &&
743            "IllegalInstrNumber cannot be DenseMap tombstone or empty key!");
744 
745     assert(IllegalInstrNumber != DenseMapInfo<unsigned>::getTombstoneKey() &&
746            "IllegalInstrNumber cannot be DenseMap tombstone or empty key!");
747 
748     return MINumber;
749   }
750 
751   /// Transforms a \p MachineBasicBlock into a \p vector of \p unsigneds
752   /// and appends it to \p UnsignedVec and \p InstrList.
753   ///
754   /// Two instructions are assigned the same integer if they are identical.
755   /// If an instruction is deemed unsafe to outline, then it will be assigned an
756   /// unique integer. The resulting mapping is placed into a suffix tree and
757   /// queried for candidates.
758   ///
759   /// \param MBB The \p MachineBasicBlock to be translated into integers.
760   /// \param TRI \p TargetRegisterInfo for the module.
761   /// \param TII \p TargetInstrInfo for the module.
762   void convertToUnsignedVec(MachineBasicBlock &MBB,
763                             const TargetRegisterInfo &TRI,
764                             const TargetInstrInfo &TII) {
765     unsigned Flags = TII.getMachineOutlinerMBBFlags(MBB);
766 
767     for (MachineBasicBlock::iterator It = MBB.begin(), Et = MBB.end(); It != Et;
768          It++) {
769 
770       // Keep track of where this instruction is in the module.
771       switch (TII.getOutliningType(It, Flags)) {
772       case TargetInstrInfo::MachineOutlinerInstrType::Illegal:
773         mapToIllegalUnsigned(It);
774         break;
775 
776       case TargetInstrInfo::MachineOutlinerInstrType::Legal:
777         mapToLegalUnsigned(It);
778         break;
779 
780       case TargetInstrInfo::MachineOutlinerInstrType::LegalTerminator:
781         mapToLegalUnsigned(It);
782         InstrList.push_back(It);
783         UnsignedVec.push_back(IllegalInstrNumber);
784         IllegalInstrNumber--;
785         break;
786 
787       case TargetInstrInfo::MachineOutlinerInstrType::Invisible:
788         break;
789       }
790     }
791 
792     // After we're done every insertion, uniquely terminate this part of the
793     // "string". This makes sure we won't match across basic block or function
794     // boundaries since the "end" is encoded uniquely and thus appears in no
795     // repeated substring.
796     InstrList.push_back(MBB.end());
797     UnsignedVec.push_back(IllegalInstrNumber);
798     IllegalInstrNumber--;
799   }
800 
801   InstructionMapper() {
802     // Make sure that the implementation of DenseMapInfo<unsigned> hasn't
803     // changed.
804     assert(DenseMapInfo<unsigned>::getEmptyKey() == (unsigned)-1 &&
805            "DenseMapInfo<unsigned>'s empty key isn't -1!");
806     assert(DenseMapInfo<unsigned>::getTombstoneKey() == (unsigned)-2 &&
807            "DenseMapInfo<unsigned>'s tombstone key isn't -2!");
808   }
809 };
810 
811 /// An interprocedural pass which finds repeated sequences of
812 /// instructions and replaces them with calls to functions.
813 ///
814 /// Each instruction is mapped to an unsigned integer and placed in a string.
815 /// The resulting mapping is then placed in a \p SuffixTree. The \p SuffixTree
816 /// is then repeatedly queried for repeated sequences of instructions. Each
817 /// non-overlapping repeated sequence is then placed in its own
818 /// \p MachineFunction and each instance is then replaced with a call to that
819 /// function.
820 struct MachineOutliner : public ModulePass {
821 
822   static char ID;
823 
824   /// Set to true if the outliner should consider functions with
825   /// linkonceodr linkage.
826   bool OutlineFromLinkOnceODRs = false;
827 
828   // Collection of IR functions created by the outliner.
829   std::vector<Function *> CreatedIRFunctions;
830 
831   StringRef getPassName() const override { return "Machine Outliner"; }
832 
833   void getAnalysisUsage(AnalysisUsage &AU) const override {
834     AU.addRequired<MachineModuleInfo>();
835     AU.addPreserved<MachineModuleInfo>();
836     AU.setPreservesAll();
837     ModulePass::getAnalysisUsage(AU);
838   }
839 
840   MachineOutliner() : ModulePass(ID) {
841     initializeMachineOutlinerPass(*PassRegistry::getPassRegistry());
842   }
843 
844   /// Find all repeated substrings that satisfy the outlining cost model.
845   ///
846   /// If a substring appears at least twice, then it must be represented by
847   /// an internal node which appears in at least two suffixes. Each suffix is
848   /// represented by a leaf node. To do this, we visit each internal node in
849   /// the tree, using the leaf children of each internal node. If an internal
850   /// node represents a beneficial substring, then we use each of its leaf
851   /// children to find the locations of its substring.
852   ///
853   /// \param ST A suffix tree to query.
854   /// \param TII TargetInstrInfo for the target.
855   /// \param Mapper Contains outlining mapping information.
856   /// \param[out] CandidateList Filled with candidates representing each
857   /// beneficial substring.
858   /// \param[out] FunctionList Filled with a list of \p OutlinedFunctions each
859   /// type of candidate.
860   ///
861   /// \returns The length of the longest candidate found.
862   unsigned
863   findCandidates(SuffixTree &ST, const TargetInstrInfo &TII,
864                  InstructionMapper &Mapper,
865                  std::vector<std::shared_ptr<Candidate>> &CandidateList,
866                  std::vector<OutlinedFunction> &FunctionList);
867 
868   /// Replace the sequences of instructions represented by the
869   /// \p Candidates in \p CandidateList with calls to \p MachineFunctions
870   /// described in \p FunctionList.
871   ///
872   /// \param M The module we are outlining from.
873   /// \param CandidateList A list of candidates to be outlined.
874   /// \param FunctionList A list of functions to be inserted into the module.
875   /// \param Mapper Contains the instruction mappings for the module.
876   bool outline(Module &M,
877                const ArrayRef<std::shared_ptr<Candidate>> &CandidateList,
878                std::vector<OutlinedFunction> &FunctionList,
879                InstructionMapper &Mapper);
880 
881   /// Creates a function for \p OF and inserts it into the module.
882   MachineFunction *createOutlinedFunction(Module &M, const OutlinedFunction &OF,
883                                           InstructionMapper &Mapper);
884 
885   /// Find potential outlining candidates and store them in \p CandidateList.
886   ///
887   /// For each type of potential candidate, also build an \p OutlinedFunction
888   /// struct containing the information to build the function for that
889   /// candidate.
890   ///
891   /// \param[out] CandidateList Filled with outlining candidates for the module.
892   /// \param[out] FunctionList Filled with functions corresponding to each type
893   /// of \p Candidate.
894   /// \param ST The suffix tree for the module.
895   /// \param TII TargetInstrInfo for the module.
896   ///
897   /// \returns The length of the longest candidate found. 0 if there are none.
898   unsigned
899   buildCandidateList(std::vector<std::shared_ptr<Candidate>> &CandidateList,
900                      std::vector<OutlinedFunction> &FunctionList,
901                      SuffixTree &ST, InstructionMapper &Mapper,
902                      const TargetInstrInfo &TII);
903 
904   /// Helper function for pruneOverlaps.
905   /// Removes \p C from the candidate list, and updates its \p OutlinedFunction.
906   void prune(Candidate &C, std::vector<OutlinedFunction> &FunctionList);
907 
908   /// Remove any overlapping candidates that weren't handled by the
909   /// suffix tree's pruning method.
910   ///
911   /// Pruning from the suffix tree doesn't necessarily remove all overlaps.
912   /// If a short candidate is chosen for outlining, then a longer candidate
913   /// which has that short candidate as a suffix is chosen, the tree's pruning
914   /// method will not find it. Thus, we need to prune before outlining as well.
915   ///
916   /// \param[in,out] CandidateList A list of outlining candidates.
917   /// \param[in,out] FunctionList A list of functions to be outlined.
918   /// \param Mapper Contains instruction mapping info for outlining.
919   /// \param MaxCandidateLen The length of the longest candidate.
920   /// \param TII TargetInstrInfo for the module.
921   void pruneOverlaps(std::vector<std::shared_ptr<Candidate>> &CandidateList,
922                      std::vector<OutlinedFunction> &FunctionList,
923                      InstructionMapper &Mapper, unsigned MaxCandidateLen,
924                      const TargetInstrInfo &TII);
925 
926   /// Construct a suffix tree on the instructions in \p M and outline repeated
927   /// strings from that tree.
928   bool runOnModule(Module &M) override;
929 };
930 
931 } // Anonymous namespace.
932 
933 char MachineOutliner::ID = 0;
934 
935 namespace llvm {
936 ModulePass *createMachineOutlinerPass() {
937   return new MachineOutliner();
938 }
939 
940 } // namespace llvm
941 
942 INITIALIZE_PASS(MachineOutliner, DEBUG_TYPE, "Machine Function Outliner", false,
943                 false)
944 
945 unsigned MachineOutliner::findCandidates(
946     SuffixTree &ST, const TargetInstrInfo &TII, InstructionMapper &Mapper,
947     std::vector<std::shared_ptr<Candidate>> &CandidateList,
948     std::vector<OutlinedFunction> &FunctionList) {
949   CandidateList.clear();
950   FunctionList.clear();
951   unsigned MaxLen = 0;
952 
953   // FIXME: Visit internal nodes instead of leaves.
954   for (SuffixTreeNode *Leaf : ST.LeafVector) {
955     assert(Leaf && "Leaves in LeafVector cannot be null!");
956     if (!Leaf->IsInTree)
957       continue;
958 
959     assert(Leaf->Parent && "All leaves must have parents!");
960     SuffixTreeNode &Parent = *(Leaf->Parent);
961 
962     // If it doesn't appear enough, or we already outlined from it, skip it.
963     if (Parent.OccurrenceCount < 2 || Parent.isRoot() || !Parent.IsInTree)
964       continue;
965 
966     // Figure out if this candidate is beneficial.
967     unsigned StringLen = Leaf->ConcatLen - (unsigned)Leaf->size();
968 
969     // Too short to be beneficial; skip it.
970     // FIXME: This isn't necessarily true for, say, X86. If we factor in
971     // instruction lengths we need more information than this.
972     if (StringLen < 2)
973       continue;
974 
975     // If this is a beneficial class of candidate, then every one is stored in
976     // this vector.
977     std::vector<Candidate> CandidatesForRepeatedSeq;
978 
979     // Describes the start and end point of each candidate. This allows the
980     // target to infer some information about each occurrence of each repeated
981     // sequence.
982     // FIXME: CandidatesForRepeatedSeq and this should be combined.
983     std::vector<
984         std::pair<MachineBasicBlock::iterator, MachineBasicBlock::iterator>>
985         RepeatedSequenceLocs;
986 
987     // Figure out the call overhead for each instance of the sequence.
988     for (auto &ChildPair : Parent.Children) {
989       SuffixTreeNode *M = ChildPair.second;
990 
991       if (M && M->IsInTree && M->isLeaf()) {
992         // Never visit this leaf again.
993         M->IsInTree = false;
994         unsigned StartIdx = M->SuffixIdx;
995         unsigned EndIdx = StartIdx + StringLen - 1;
996 
997         // Trick: Discard some candidates that would be incompatible with the
998         // ones we've already found for this sequence. This will save us some
999         // work in candidate selection.
1000         //
1001         // If two candidates overlap, then we can't outline them both. This
1002         // happens when we have candidates that look like, say
1003         //
1004         // AA (where each "A" is an instruction).
1005         //
1006         // We might have some portion of the module that looks like this:
1007         // AAAAAA (6 A's)
1008         //
1009         // In this case, there are 5 different copies of "AA" in this range, but
1010         // at most 3 can be outlined. If only outlining 3 of these is going to
1011         // be unbeneficial, then we ought to not bother.
1012         //
1013         // Note that two things DON'T overlap when they look like this:
1014         // start1...end1 .... start2...end2
1015         // That is, one must either
1016         // * End before the other starts
1017         // * Start after the other ends
1018         if (std::all_of(CandidatesForRepeatedSeq.begin(),
1019                         CandidatesForRepeatedSeq.end(),
1020                         [&StartIdx, &EndIdx](const Candidate &C) {
1021                           return (EndIdx < C.getStartIdx() ||
1022                                   StartIdx > C.getEndIdx());
1023                         })) {
1024           // It doesn't overlap with anything, so we can outline it.
1025           // Each sequence is over [StartIt, EndIt].
1026           MachineBasicBlock::iterator StartIt = Mapper.InstrList[StartIdx];
1027           MachineBasicBlock::iterator EndIt = Mapper.InstrList[EndIdx];
1028 
1029           // Save the MachineFunction containing the Candidate.
1030           MachineFunction *MF = StartIt->getParent()->getParent();
1031           assert(MF && "Candidate doesn't have a MF?");
1032 
1033           // Save the candidate and its location.
1034           CandidatesForRepeatedSeq.emplace_back(StartIdx, StringLen,
1035                                                 FunctionList.size(), MF);
1036           RepeatedSequenceLocs.emplace_back(std::make_pair(StartIt, EndIt));
1037         }
1038       }
1039     }
1040 
1041     // We've found something we might want to outline.
1042     // Create an OutlinedFunction to store it and check if it'd be beneficial
1043     // to outline.
1044     TargetInstrInfo::MachineOutlinerInfo MInfo =
1045         TII.getOutlininingCandidateInfo(RepeatedSequenceLocs);
1046     std::vector<unsigned> Seq;
1047     for (unsigned i = Leaf->SuffixIdx; i < Leaf->SuffixIdx + StringLen; i++)
1048       Seq.push_back(ST.Str[i]);
1049     OutlinedFunction OF(FunctionList.size(), CandidatesForRepeatedSeq.size(),
1050                         Seq, MInfo);
1051     unsigned Benefit = OF.getBenefit();
1052 
1053     // Is it better to outline this candidate than not?
1054     if (Benefit < 1) {
1055       // Outlining this candidate would take more instructions than not
1056       // outlining.
1057       // Emit a remark explaining why we didn't outline this candidate.
1058       std::pair<MachineBasicBlock::iterator, MachineBasicBlock::iterator> C =
1059           RepeatedSequenceLocs[0];
1060       MachineOptimizationRemarkEmitter MORE(
1061           *(C.first->getParent()->getParent()), nullptr);
1062       MORE.emit([&]() {
1063         MachineOptimizationRemarkMissed R(DEBUG_TYPE, "NotOutliningCheaper",
1064                                           C.first->getDebugLoc(),
1065                                           C.first->getParent());
1066         R << "Did not outline " << NV("Length", StringLen) << " instructions"
1067           << " from " << NV("NumOccurrences", RepeatedSequenceLocs.size())
1068           << " locations."
1069           << " Bytes from outlining all occurrences ("
1070           << NV("OutliningCost", OF.getOutliningCost()) << ")"
1071           << " >= Unoutlined instruction bytes ("
1072           << NV("NotOutliningCost", OF.getNotOutlinedCost()) << ")"
1073           << " (Also found at: ";
1074 
1075         // Tell the user the other places the candidate was found.
1076         for (unsigned i = 1, e = RepeatedSequenceLocs.size(); i < e; i++) {
1077           R << NV((Twine("OtherStartLoc") + Twine(i)).str(),
1078                   RepeatedSequenceLocs[i].first->getDebugLoc());
1079           if (i != e - 1)
1080             R << ", ";
1081         }
1082 
1083         R << ")";
1084         return R;
1085       });
1086 
1087       // Move to the next candidate.
1088       continue;
1089     }
1090 
1091     if (StringLen > MaxLen)
1092       MaxLen = StringLen;
1093 
1094     // At this point, the candidate class is seen as beneficial. Set their
1095     // benefit values and save them in the candidate list.
1096     std::vector<std::shared_ptr<Candidate>> CandidatesForFn;
1097     for (Candidate &C : CandidatesForRepeatedSeq) {
1098       C.Benefit = Benefit;
1099       C.MInfo = MInfo;
1100       std::shared_ptr<Candidate> Cptr = std::make_shared<Candidate>(C);
1101       CandidateList.push_back(Cptr);
1102       CandidatesForFn.push_back(Cptr);
1103     }
1104 
1105     FunctionList.push_back(OF);
1106     FunctionList.back().Candidates = CandidatesForFn;
1107 
1108     // Move to the next function.
1109     Parent.IsInTree = false;
1110   }
1111 
1112   return MaxLen;
1113 }
1114 
1115 // Remove C from the candidate space, and update its OutlinedFunction.
1116 void MachineOutliner::prune(Candidate &C,
1117                             std::vector<OutlinedFunction> &FunctionList) {
1118   // Get the OutlinedFunction associated with this Candidate.
1119   OutlinedFunction &F = FunctionList[C.FunctionIdx];
1120 
1121   // Update C's associated function's occurrence count.
1122   F.decrement();
1123 
1124   // Remove C from the CandidateList.
1125   C.InCandidateList = false;
1126 
1127   LLVM_DEBUG(dbgs() << "- Removed a Candidate \n";
1128              dbgs() << "--- Num fns left for candidate: "
1129                     << F.getOccurrenceCount() << "\n";
1130              dbgs() << "--- Candidate's functions's benefit: " << F.getBenefit()
1131                     << "\n";);
1132 }
1133 
1134 void MachineOutliner::pruneOverlaps(
1135     std::vector<std::shared_ptr<Candidate>> &CandidateList,
1136     std::vector<OutlinedFunction> &FunctionList, InstructionMapper &Mapper,
1137     unsigned MaxCandidateLen, const TargetInstrInfo &TII) {
1138 
1139   // Return true if this candidate became unbeneficial for outlining in a
1140   // previous step.
1141   auto ShouldSkipCandidate = [&FunctionList, this](Candidate &C) {
1142 
1143     // Check if the candidate was removed in a previous step.
1144     if (!C.InCandidateList)
1145       return true;
1146 
1147     // C must be alive. Check if we should remove it.
1148     if (FunctionList[C.FunctionIdx].getBenefit() < 1) {
1149       prune(C, FunctionList);
1150       return true;
1151     }
1152 
1153     // C is in the list, and F is still beneficial.
1154     return false;
1155   };
1156 
1157   // TODO: Experiment with interval trees or other interval-checking structures
1158   // to lower the time complexity of this function.
1159   // TODO: Can we do better than the simple greedy choice?
1160   // Check for overlaps in the range.
1161   // This is O(MaxCandidateLen * CandidateList.size()).
1162   for (auto It = CandidateList.begin(), Et = CandidateList.end(); It != Et;
1163        It++) {
1164     Candidate &C1 = **It;
1165 
1166     // If C1 was already pruned, or its function is no longer beneficial for
1167     // outlining, move to the next candidate.
1168     if (ShouldSkipCandidate(C1))
1169       continue;
1170 
1171     // The minimum start index of any candidate that could overlap with this
1172     // one.
1173     unsigned FarthestPossibleIdx = 0;
1174 
1175     // Either the index is 0, or it's at most MaxCandidateLen indices away.
1176     if (C1.getStartIdx() > MaxCandidateLen)
1177       FarthestPossibleIdx = C1.getStartIdx() - MaxCandidateLen;
1178 
1179     // Compare against the candidates in the list that start at most
1180     // FarthestPossibleIdx indices away from C1. There are at most
1181     // MaxCandidateLen of these.
1182     for (auto Sit = It + 1; Sit != Et; Sit++) {
1183       Candidate &C2 = **Sit;
1184 
1185       // Is this candidate too far away to overlap?
1186       if (C2.getStartIdx() < FarthestPossibleIdx)
1187         break;
1188 
1189       // If C2 was already pruned, or its function is no longer beneficial for
1190       // outlining, move to the next candidate.
1191       if (ShouldSkipCandidate(C2))
1192         continue;
1193 
1194       // Do C1 and C2 overlap?
1195       //
1196       // Not overlapping:
1197       // High indices... [C1End ... C1Start][C2End ... C2Start] ...Low indices
1198       //
1199       // We sorted our candidate list so C2Start <= C1Start. We know that
1200       // C2End > C2Start since each candidate has length >= 2. Therefore, all we
1201       // have to check is C2End < C2Start to see if we overlap.
1202       if (C2.getEndIdx() < C1.getStartIdx())
1203         continue;
1204 
1205       // C1 and C2 overlap.
1206       // We need to choose the better of the two.
1207       //
1208       // Approximate this by picking the one which would have saved us the
1209       // most instructions before any pruning.
1210 
1211       // Is C2 a better candidate?
1212       if (C2.Benefit > C1.Benefit) {
1213         // Yes, so prune C1. Since C1 is dead, we don't have to compare it
1214         // against anything anymore, so break.
1215         prune(C1, FunctionList);
1216         break;
1217       }
1218 
1219       // Prune C2 and move on to the next candidate.
1220       prune(C2, FunctionList);
1221     }
1222   }
1223 }
1224 
1225 unsigned MachineOutliner::buildCandidateList(
1226     std::vector<std::shared_ptr<Candidate>> &CandidateList,
1227     std::vector<OutlinedFunction> &FunctionList, SuffixTree &ST,
1228     InstructionMapper &Mapper, const TargetInstrInfo &TII) {
1229 
1230   std::vector<unsigned> CandidateSequence; // Current outlining candidate.
1231   unsigned MaxCandidateLen = 0;            // Length of the longest candidate.
1232 
1233   MaxCandidateLen =
1234       findCandidates(ST, TII, Mapper, CandidateList, FunctionList);
1235 
1236   // Sort the candidates in decending order. This will simplify the outlining
1237   // process when we have to remove the candidates from the mapping by
1238   // allowing us to cut them out without keeping track of an offset.
1239   std::stable_sort(
1240       CandidateList.begin(), CandidateList.end(),
1241       [](const std::shared_ptr<Candidate> &LHS,
1242          const std::shared_ptr<Candidate> &RHS) { return *LHS < *RHS; });
1243 
1244   return MaxCandidateLen;
1245 }
1246 
1247 MachineFunction *
1248 MachineOutliner::createOutlinedFunction(Module &M, const OutlinedFunction &OF,
1249                                         InstructionMapper &Mapper) {
1250 
1251   // Create the function name. This should be unique. For now, just hash the
1252   // module name and include it in the function name plus the number of this
1253   // function.
1254   std::ostringstream NameStream;
1255   NameStream << "OUTLINED_FUNCTION_" << OF.Name;
1256 
1257   // Create the function using an IR-level function.
1258   LLVMContext &C = M.getContext();
1259   Function *F = dyn_cast<Function>(
1260       M.getOrInsertFunction(NameStream.str(), Type::getVoidTy(C)));
1261   assert(F && "Function was null!");
1262 
1263   // NOTE: If this is linkonceodr, then we can take advantage of linker deduping
1264   // which gives us better results when we outline from linkonceodr functions.
1265   F->setLinkage(GlobalValue::InternalLinkage);
1266   F->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
1267 
1268   // FIXME: Set nounwind, so we don't generate eh_frame? Haven't verified it's
1269   // necessary.
1270 
1271   // Set optsize/minsize, so we don't insert padding between outlined
1272   // functions.
1273   F->addFnAttr(Attribute::OptimizeForSize);
1274   F->addFnAttr(Attribute::MinSize);
1275 
1276   // Save F so that we can add debug info later if we need to.
1277   CreatedIRFunctions.push_back(F);
1278 
1279   BasicBlock *EntryBB = BasicBlock::Create(C, "entry", F);
1280   IRBuilder<> Builder(EntryBB);
1281   Builder.CreateRetVoid();
1282 
1283   MachineModuleInfo &MMI = getAnalysis<MachineModuleInfo>();
1284   MachineFunction &MF = MMI.getOrCreateMachineFunction(*F);
1285   MachineBasicBlock &MBB = *MF.CreateMachineBasicBlock();
1286   const TargetSubtargetInfo &STI = MF.getSubtarget();
1287   const TargetInstrInfo &TII = *STI.getInstrInfo();
1288 
1289   // Insert the new function into the module.
1290   MF.insert(MF.begin(), &MBB);
1291 
1292   TII.insertOutlinerPrologue(MBB, MF, OF.MInfo);
1293 
1294   // Copy over the instructions for the function using the integer mappings in
1295   // its sequence.
1296   for (unsigned Str : OF.Sequence) {
1297     MachineInstr *NewMI =
1298         MF.CloneMachineInstr(Mapper.IntegerInstructionMap.find(Str)->second);
1299     NewMI->dropMemRefs();
1300 
1301     // Don't keep debug information for outlined instructions.
1302     NewMI->setDebugLoc(DebugLoc());
1303     MBB.insert(MBB.end(), NewMI);
1304   }
1305 
1306   TII.insertOutlinerEpilogue(MBB, MF, OF.MInfo);
1307 
1308   // If there's a DISubprogram associated with this outlined function, then
1309   // emit debug info for the outlined function.
1310   if (DISubprogram *SP = OF.getSubprogramOrNull()) {
1311     // We have a DISubprogram. Get its DICompileUnit.
1312     DICompileUnit *CU = SP->getUnit();
1313     DIBuilder DB(M, true, CU);
1314     DIFile *Unit = SP->getFile();
1315     Mangler Mg;
1316 
1317     // Walk over each IR function we created in the outliner and create
1318     // DISubprograms for each function.
1319     for (Function *F : CreatedIRFunctions) {
1320       // Get the mangled name of the function for the linkage name.
1321       std::string Dummy;
1322       llvm::raw_string_ostream MangledNameStream(Dummy);
1323       Mg.getNameWithPrefix(MangledNameStream, F, false);
1324 
1325       DISubprogram *SP = DB.createFunction(
1326           Unit /* Context */, F->getName(), StringRef(MangledNameStream.str()),
1327           Unit /* File */,
1328           0 /* Line 0 is reserved for compiler-generated code. */,
1329           DB.createSubroutineType(
1330               DB.getOrCreateTypeArray(None)), /* void type */
1331           false, true, 0, /* Line 0 is reserved for compiler-generated code. */
1332           DINode::DIFlags::FlagArtificial /* Compiler-generated code. */,
1333           true /* Outlined code is optimized code by definition. */);
1334 
1335       // Don't add any new variables to the subprogram.
1336       DB.finalizeSubprogram(SP);
1337 
1338       // Attach subprogram to the function.
1339       F->setSubprogram(SP);
1340     }
1341 
1342     // We're done with the DIBuilder.
1343     DB.finalize();
1344   }
1345 
1346   // Outlined functions shouldn't preserve liveness.
1347   MF.getProperties().reset(MachineFunctionProperties::Property::TracksLiveness);
1348   MF.getRegInfo().freezeReservedRegs(MF);
1349   return &MF;
1350 }
1351 
1352 bool MachineOutliner::outline(
1353     Module &M, const ArrayRef<std::shared_ptr<Candidate>> &CandidateList,
1354     std::vector<OutlinedFunction> &FunctionList, InstructionMapper &Mapper) {
1355 
1356   bool OutlinedSomething = false;
1357   // Replace the candidates with calls to their respective outlined functions.
1358   for (const std::shared_ptr<Candidate> &Cptr : CandidateList) {
1359     Candidate &C = *Cptr;
1360     // Was the candidate removed during pruneOverlaps?
1361     if (!C.InCandidateList)
1362       continue;
1363 
1364     // If not, then look at its OutlinedFunction.
1365     OutlinedFunction &OF = FunctionList[C.FunctionIdx];
1366 
1367     // Was its OutlinedFunction made unbeneficial during pruneOverlaps?
1368     if (OF.getBenefit() < 1)
1369       continue;
1370 
1371     // If not, then outline it.
1372     assert(C.getStartIdx() < Mapper.InstrList.size() &&
1373            "Candidate out of bounds!");
1374     MachineBasicBlock *MBB = (*Mapper.InstrList[C.getStartIdx()]).getParent();
1375     MachineBasicBlock::iterator StartIt = Mapper.InstrList[C.getStartIdx()];
1376     unsigned EndIdx = C.getEndIdx();
1377 
1378     assert(EndIdx < Mapper.InstrList.size() && "Candidate out of bounds!");
1379     MachineBasicBlock::iterator EndIt = Mapper.InstrList[EndIdx];
1380     assert(EndIt != MBB->end() && "EndIt out of bounds!");
1381 
1382     // Does this candidate have a function yet?
1383     if (!OF.MF) {
1384       OF.MF = createOutlinedFunction(M, OF, Mapper);
1385       MachineBasicBlock *MBB = &*OF.MF->begin();
1386 
1387       // Output a remark telling the user that an outlined function was created,
1388       // and explaining where it came from.
1389       MachineOptimizationRemarkEmitter MORE(*OF.MF, nullptr);
1390       MachineOptimizationRemark R(DEBUG_TYPE, "OutlinedFunction",
1391                                   MBB->findDebugLoc(MBB->begin()), MBB);
1392       R << "Saved " << NV("OutliningBenefit", OF.getBenefit())
1393         << " bytes by "
1394         << "outlining " << NV("Length", OF.Sequence.size()) << " instructions "
1395         << "from " << NV("NumOccurrences", OF.getOccurrenceCount())
1396         << " locations. "
1397         << "(Found at: ";
1398 
1399       // Tell the user the other places the candidate was found.
1400       for (size_t i = 0, e = OF.Candidates.size(); i < e; i++) {
1401 
1402         // Skip over things that were pruned.
1403         if (!OF.Candidates[i]->InCandidateList)
1404           continue;
1405 
1406         R << NV(
1407             (Twine("StartLoc") + Twine(i)).str(),
1408             Mapper.InstrList[OF.Candidates[i]->getStartIdx()]->getDebugLoc());
1409         if (i != e - 1)
1410           R << ", ";
1411       }
1412 
1413       R << ")";
1414 
1415       MORE.emit(R);
1416       FunctionsCreated++;
1417     }
1418 
1419     MachineFunction *MF = OF.MF;
1420     const TargetSubtargetInfo &STI = MF->getSubtarget();
1421     const TargetInstrInfo &TII = *STI.getInstrInfo();
1422 
1423     // Insert a call to the new function and erase the old sequence.
1424     auto CallInst = TII.insertOutlinedCall(M, *MBB, StartIt, *MF, C.MInfo);
1425     StartIt = Mapper.InstrList[C.getStartIdx()];
1426 
1427     // If the caller tracks liveness, then we need to make sure that anything
1428     // we outline doesn't break liveness assumptions.
1429     // The outlined functions themselves currently don't track liveness, but
1430     // we should make sure that the ranges we yank things out of aren't
1431     // wrong.
1432     if (MBB->getParent()->getProperties().hasProperty(
1433             MachineFunctionProperties::Property::TracksLiveness)) {
1434       // Helper lambda for adding implicit def operands to the call instruction.
1435       auto CopyDefs = [&CallInst](MachineInstr &MI) {
1436         for (MachineOperand &MOP : MI.operands()) {
1437           // Skip over anything that isn't a register.
1438           if (!MOP.isReg())
1439             continue;
1440 
1441           // If it's a def, add it to the call instruction.
1442           if (MOP.isDef())
1443             CallInst->addOperand(
1444                 MachineOperand::CreateReg(MOP.getReg(), true, /* isDef = true */
1445                                           true /* isImp = true */));
1446         }
1447       };
1448 
1449       // Copy over the defs in the outlined range.
1450       // First inst in outlined range <-- Anything that's defined in this
1451       // ...                           .. range has to be added as an implicit
1452       // Last inst in outlined range  <-- def to the call instruction.
1453       std::for_each(CallInst, EndIt, CopyDefs);
1454     }
1455 
1456     EndIt++; // Erase needs one past the end index.
1457     MBB->erase(StartIt, EndIt);
1458     OutlinedSomething = true;
1459 
1460     // Statistics.
1461     NumOutlined++;
1462   }
1463 
1464   LLVM_DEBUG(dbgs() << "OutlinedSomething = " << OutlinedSomething << "\n";);
1465 
1466   return OutlinedSomething;
1467 }
1468 
1469 bool MachineOutliner::runOnModule(Module &M) {
1470   // Check if there's anything in the module. If it's empty, then there's
1471   // nothing to outline.
1472   if (M.empty())
1473     return false;
1474 
1475   MachineModuleInfo &MMI = getAnalysis<MachineModuleInfo>();
1476   const TargetSubtargetInfo &STI =
1477       MMI.getOrCreateMachineFunction(*M.begin()).getSubtarget();
1478   const TargetRegisterInfo *TRI = STI.getRegisterInfo();
1479   const TargetInstrInfo *TII = STI.getInstrInfo();
1480 
1481   // Does the target implement the MachineOutliner? If it doesn't, quit here.
1482   if (!TII->useMachineOutliner()) {
1483     // No. So we're done.
1484     LLVM_DEBUG(
1485         dbgs()
1486         << "Skipping pass: Target does not support the MachineOutliner.\n");
1487     return false;
1488   }
1489 
1490   // If the user specifies that they want to outline from linkonceodrs, set
1491   // it here.
1492   OutlineFromLinkOnceODRs = EnableLinkOnceODROutlining;
1493 
1494   InstructionMapper Mapper;
1495 
1496   // Build instruction mappings for each function in the module. Start by
1497   // iterating over each Function in M.
1498   for (Function &F : M) {
1499 
1500     // If there's nothing in F, then there's no reason to try and outline from
1501     // it.
1502     if (F.empty())
1503       continue;
1504 
1505     // There's something in F. Check if it has a MachineFunction associated with
1506     // it.
1507     MachineFunction *MF = MMI.getMachineFunction(F);
1508 
1509     // If it doesn't, then there's nothing to outline from. Move to the next
1510     // Function.
1511     if (!MF)
1512       continue;
1513 
1514     // We have a MachineFunction. Ask the target if it's suitable for outlining.
1515     // If it isn't, then move on to the next Function in the module.
1516     if (!TII->isFunctionSafeToOutlineFrom(*MF, OutlineFromLinkOnceODRs))
1517       continue;
1518 
1519     // We have a function suitable for outlining. Iterate over every
1520     // MachineBasicBlock in MF and try to map its instructions to a list of
1521     // unsigned integers.
1522     for (MachineBasicBlock &MBB : *MF) {
1523       // If there isn't anything in MBB, then there's no point in outlining from
1524       // it.
1525       if (MBB.empty())
1526         continue;
1527 
1528       // Check if MBB could be the target of an indirect branch. If it is, then
1529       // we don't want to outline from it.
1530       if (MBB.hasAddressTaken())
1531         continue;
1532 
1533       // MBB is suitable for outlining. Map it to a list of unsigneds.
1534       Mapper.convertToUnsignedVec(MBB, *TRI, *TII);
1535     }
1536   }
1537 
1538   // Construct a suffix tree, use it to find candidates, and then outline them.
1539   SuffixTree ST(Mapper.UnsignedVec);
1540   std::vector<std::shared_ptr<Candidate>> CandidateList;
1541   std::vector<OutlinedFunction> FunctionList;
1542 
1543   // Find all of the outlining candidates.
1544   unsigned MaxCandidateLen =
1545       buildCandidateList(CandidateList, FunctionList, ST, Mapper, *TII);
1546 
1547   // Remove candidates that overlap with other candidates.
1548   pruneOverlaps(CandidateList, FunctionList, Mapper, MaxCandidateLen, *TII);
1549 
1550   // Outline each of the candidates and return true if something was outlined.
1551   bool OutlinedSomething = outline(M, CandidateList, FunctionList, Mapper);
1552 
1553   return OutlinedSomething;
1554 }
1555