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 /// This was originally presented at the 2016 LLVM Developers' Meeting in the
19 /// talk "Reducing Code Size Using Outlining". For a high-level overview of
20 /// how this pass works, the talk is available on YouTube at
21 ///
22 /// https://www.youtube.com/watch?v=yorld-WSOeU
23 ///
24 /// The slides for the talk are available at
25 ///
26 /// http://www.llvm.org/devmtg/2016-11/Slides/Paquette-Outliner.pdf
27 ///
28 /// The talk provides an overview of how the outliner finds candidates and
29 /// ultimately outlines them. It describes how the main data structure for this
30 /// pass, the suffix tree, is queried and purged for candidates. It also gives
31 /// a simplified suffix tree construction algorithm for suffix trees based off
32 /// of the algorithm actually used here, Ukkonen's algorithm.
33 ///
34 /// For the original RFC for this pass, please see
35 ///
36 /// http://lists.llvm.org/pipermail/llvm-dev/2016-August/104170.html
37 ///
38 /// For more information on the suffix tree data structure, please see
39 /// https://www.cs.helsinki.fi/u/ukkonen/SuffixT1withFigs.pdf
40 ///
41 //===----------------------------------------------------------------------===//
42 #include "llvm/ADT/DenseMap.h"
43 #include "llvm/ADT/Statistic.h"
44 #include "llvm/ADT/Twine.h"
45 #include "llvm/CodeGen/MachineFrameInfo.h"
46 #include "llvm/CodeGen/MachineFunction.h"
47 #include "llvm/CodeGen/MachineInstrBuilder.h"
48 #include "llvm/CodeGen/MachineModuleInfo.h"
49 #include "llvm/CodeGen/Passes.h"
50 #include "llvm/IR/IRBuilder.h"
51 #include "llvm/Support/Allocator.h"
52 #include "llvm/Support/Debug.h"
53 #include "llvm/Support/raw_ostream.h"
54 #include "llvm/Target/TargetInstrInfo.h"
55 #include "llvm/Target/TargetMachine.h"
56 #include "llvm/Target/TargetRegisterInfo.h"
57 #include "llvm/Target/TargetSubtargetInfo.h"
58 #include <functional>
59 #include <map>
60 #include <sstream>
61 #include <tuple>
62 #include <vector>
63 
64 #define DEBUG_TYPE "machine-outliner"
65 
66 using namespace llvm;
67 
68 STATISTIC(NumOutlined, "Number of candidates outlined");
69 STATISTIC(FunctionsCreated, "Number of functions created");
70 
71 namespace {
72 
73 /// \brief An individual sequence of instructions to be replaced with a call to
74 /// an outlined function.
75 struct Candidate {
76 
77   /// Set to false if the candidate overlapped with another candidate.
78   bool InCandidateList = true;
79 
80   /// The start index of this \p Candidate.
81   size_t StartIdx;
82 
83   /// The number of instructions in this \p Candidate.
84   size_t Len;
85 
86   /// The index of this \p Candidate's \p OutlinedFunction in the list of
87   /// \p OutlinedFunctions.
88   size_t FunctionIdx;
89 
90   /// Target-defined unsigned defining how to emit a call for this candidate.
91   unsigned CallClass = 0;
92 
93   /// \brief The number of instructions that would be saved by outlining every
94   /// candidate of this type.
95   ///
96   /// This is a fixed value which is not updated during the candidate pruning
97   /// process. It is only used for deciding which candidate to keep if two
98   /// candidates overlap. The true benefit is stored in the OutlinedFunction
99   /// for some given candidate.
100   unsigned Benefit = 0;
101 
102   Candidate(size_t StartIdx, size_t Len, size_t FunctionIdx, unsigned CallClass)
103       : StartIdx(StartIdx), Len(Len), FunctionIdx(FunctionIdx),
104         CallClass(CallClass) {}
105 
106   Candidate() {}
107 
108   /// \brief Used to ensure that \p Candidates are outlined in an order that
109   /// preserves the start and end indices of other \p Candidates.
110   bool operator<(const Candidate &RHS) const { return StartIdx > RHS.StartIdx; }
111 };
112 
113 /// \brief The information necessary to create an outlined function for some
114 /// class of candidate.
115 struct OutlinedFunction {
116 
117   /// The actual outlined function created.
118   /// This is initialized after we go through and create the actual function.
119   MachineFunction *MF = nullptr;
120 
121   /// A numbefr assigned to this function which appears at the end of its name.
122   size_t Name;
123 
124   /// The number of candidates for this OutlinedFunction.
125   size_t OccurrenceCount = 0;
126 
127   /// \brief The sequence of integers corresponding to the instructions in this
128   /// function.
129   std::vector<unsigned> Sequence;
130 
131   /// The number of instructions this function would save.
132   unsigned Benefit = 0;
133 
134   /// Target-defined unsigned defining how to emit the frame for this function.
135   unsigned FrameClass = 0;
136 
137   OutlinedFunction(size_t Name, size_t OccurrenceCount,
138                    const std::vector<unsigned> &Sequence, unsigned Benefit,
139                    unsigned FrameClass)
140       : Name(Name), OccurrenceCount(OccurrenceCount), Sequence(Sequence),
141         Benefit(Benefit), FrameClass(FrameClass) {}
142 };
143 
144 /// Represents an undefined index in the suffix tree.
145 const size_t EmptyIdx = -1;
146 
147 /// A node in a suffix tree which represents a substring or suffix.
148 ///
149 /// Each node has either no children or at least two children, with the root
150 /// being a exception in the empty tree.
151 ///
152 /// Children are represented as a map between unsigned integers and nodes. If
153 /// a node N has a child M on unsigned integer k, then the mapping represented
154 /// by N is a proper prefix of the mapping represented by M. Note that this,
155 /// although similar to a trie is somewhat different: each node stores a full
156 /// substring of the full mapping rather than a single character state.
157 ///
158 /// Each internal node contains a pointer to the internal node representing
159 /// the same string, but with the first character chopped off. This is stored
160 /// in \p Link. Each leaf node stores the start index of its respective
161 /// suffix in \p SuffixIdx.
162 struct SuffixTreeNode {
163 
164   /// The children of this node.
165   ///
166   /// A child existing on an unsigned integer implies that from the mapping
167   /// represented by the current node, there is a way to reach another
168   /// mapping by tacking that character on the end of the current string.
169   DenseMap<unsigned, SuffixTreeNode *> Children;
170 
171   /// A flag set to false if the node has been pruned from the tree.
172   bool IsInTree = true;
173 
174   /// The start index of this node's substring in the main string.
175   size_t StartIdx = EmptyIdx;
176 
177   /// The end index of this node's substring in the main string.
178   ///
179   /// Every leaf node must have its \p EndIdx incremented at the end of every
180   /// step in the construction algorithm. To avoid having to update O(N)
181   /// nodes individually at the end of every step, the end index is stored
182   /// as a pointer.
183   size_t *EndIdx = nullptr;
184 
185   /// For leaves, the start index of the suffix represented by this node.
186   ///
187   /// For all other nodes, this is ignored.
188   size_t SuffixIdx = EmptyIdx;
189 
190   /// \brief For internal nodes, a pointer to the internal node representing
191   /// the same sequence with the first character chopped off.
192   ///
193   /// This acts as a shortcut in Ukkonen's algorithm. One of the things that
194   /// Ukkonen's algorithm does to achieve linear-time construction is
195   /// keep track of which node the next insert should be at. This makes each
196   /// insert O(1), and there are a total of O(N) inserts. The suffix link
197   /// helps with inserting children of internal nodes.
198   ///
199   /// Say we add a child to an internal node with associated mapping S. The
200   /// next insertion must be at the node representing S - its first character.
201   /// This is given by the way that we iteratively build the tree in Ukkonen's
202   /// algorithm. The main idea is to look at the suffixes of each prefix in the
203   /// string, starting with the longest suffix of the prefix, and ending with
204   /// the shortest. Therefore, if we keep pointers between such nodes, we can
205   /// move to the next insertion point in O(1) time. If we don't, then we'd
206   /// have to query from the root, which takes O(N) time. This would make the
207   /// construction algorithm O(N^2) rather than O(N).
208   SuffixTreeNode *Link = nullptr;
209 
210   /// The parent of this node. Every node except for the root has a parent.
211   SuffixTreeNode *Parent = nullptr;
212 
213   /// The number of times this node's string appears in the tree.
214   ///
215   /// This is equal to the number of leaf children of the string. It represents
216   /// the number of suffixes that the node's string is a prefix of.
217   size_t OccurrenceCount = 0;
218 
219   /// The length of the string formed by concatenating the edge labels from the
220   /// root to this node.
221   size_t ConcatLen = 0;
222 
223   /// Returns true if this node is a leaf.
224   bool isLeaf() const { return SuffixIdx != EmptyIdx; }
225 
226   /// Returns true if this node is the root of its owning \p SuffixTree.
227   bool isRoot() const { return StartIdx == EmptyIdx; }
228 
229   /// Return the number of elements in the substring associated with this node.
230   size_t size() const {
231 
232     // Is it the root? If so, it's the empty string so return 0.
233     if (isRoot())
234       return 0;
235 
236     assert(*EndIdx != EmptyIdx && "EndIdx is undefined!");
237 
238     // Size = the number of elements in the string.
239     // For example, [0 1 2 3] has length 4, not 3. 3-0 = 3, so we have 3-0+1.
240     return *EndIdx - StartIdx + 1;
241   }
242 
243   SuffixTreeNode(size_t StartIdx, size_t *EndIdx, SuffixTreeNode *Link,
244                  SuffixTreeNode *Parent)
245       : StartIdx(StartIdx), EndIdx(EndIdx), Link(Link), Parent(Parent) {}
246 
247   SuffixTreeNode() {}
248 };
249 
250 /// A data structure for fast substring queries.
251 ///
252 /// Suffix trees represent the suffixes of their input strings in their leaves.
253 /// A suffix tree is a type of compressed trie structure where each node
254 /// represents an entire substring rather than a single character. Each leaf
255 /// of the tree is a suffix.
256 ///
257 /// A suffix tree can be seen as a type of state machine where each state is a
258 /// substring of the full string. The tree is structured so that, for a string
259 /// of length N, there are exactly N leaves in the tree. This structure allows
260 /// us to quickly find repeated substrings of the input string.
261 ///
262 /// In this implementation, a "string" is a vector of unsigned integers.
263 /// These integers may result from hashing some data type. A suffix tree can
264 /// contain 1 or many strings, which can then be queried as one large string.
265 ///
266 /// The suffix tree is implemented using Ukkonen's algorithm for linear-time
267 /// suffix tree construction. Ukkonen's algorithm is explained in more detail
268 /// in the paper by Esko Ukkonen "On-line construction of suffix trees. The
269 /// paper is available at
270 ///
271 /// https://www.cs.helsinki.fi/u/ukkonen/SuffixT1withFigs.pdf
272 class SuffixTree {
273 public:
274   /// Stores each leaf node in the tree.
275   ///
276   /// This is used for finding outlining candidates.
277   std::vector<SuffixTreeNode *> LeafVector;
278 
279   /// Each element is an integer representing an instruction in the module.
280   ArrayRef<unsigned> Str;
281 
282 private:
283   /// Maintains each node in the tree.
284   SpecificBumpPtrAllocator<SuffixTreeNode> NodeAllocator;
285 
286   /// The root of the suffix tree.
287   ///
288   /// The root represents the empty string. It is maintained by the
289   /// \p NodeAllocator like every other node in the tree.
290   SuffixTreeNode *Root = nullptr;
291 
292   /// Maintains the end indices of the internal nodes in the tree.
293   ///
294   /// Each internal node is guaranteed to never have its end index change
295   /// during the construction algorithm; however, leaves must be updated at
296   /// every step. Therefore, we need to store leaf end indices by reference
297   /// to avoid updating O(N) leaves at every step of construction. Thus,
298   /// every internal node must be allocated its own end index.
299   BumpPtrAllocator InternalEndIdxAllocator;
300 
301   /// The end index of each leaf in the tree.
302   size_t LeafEndIdx = -1;
303 
304   /// \brief Helper struct which keeps track of the next insertion point in
305   /// Ukkonen's algorithm.
306   struct ActiveState {
307     /// The next node to insert at.
308     SuffixTreeNode *Node;
309 
310     /// The index of the first character in the substring currently being added.
311     size_t Idx = EmptyIdx;
312 
313     /// The length of the substring we have to add at the current step.
314     size_t Len = 0;
315   };
316 
317   /// \brief The point the next insertion will take place at in the
318   /// construction algorithm.
319   ActiveState Active;
320 
321   /// Allocate a leaf node and add it to the tree.
322   ///
323   /// \param Parent The parent of this node.
324   /// \param StartIdx The start index of this node's associated string.
325   /// \param Edge The label on the edge leaving \p Parent to this node.
326   ///
327   /// \returns A pointer to the allocated leaf node.
328   SuffixTreeNode *insertLeaf(SuffixTreeNode &Parent, size_t StartIdx,
329                              unsigned Edge) {
330 
331     assert(StartIdx <= LeafEndIdx && "String can't start after it ends!");
332 
333     SuffixTreeNode *N = new (NodeAllocator.Allocate())
334         SuffixTreeNode(StartIdx, &LeafEndIdx, nullptr, &Parent);
335     Parent.Children[Edge] = N;
336 
337     return N;
338   }
339 
340   /// Allocate an internal node and add it to the tree.
341   ///
342   /// \param Parent The parent of this node. Only null when allocating the root.
343   /// \param StartIdx The start index of this node's associated string.
344   /// \param EndIdx The end index of this node's associated string.
345   /// \param Edge The label on the edge leaving \p Parent to this node.
346   ///
347   /// \returns A pointer to the allocated internal node.
348   SuffixTreeNode *insertInternalNode(SuffixTreeNode *Parent, size_t StartIdx,
349                                      size_t EndIdx, unsigned Edge) {
350 
351     assert(StartIdx <= EndIdx && "String can't start after it ends!");
352     assert(!(!Parent && StartIdx != EmptyIdx) &&
353            "Non-root internal nodes must have parents!");
354 
355     size_t *E = new (InternalEndIdxAllocator) size_t(EndIdx);
356     SuffixTreeNode *N = new (NodeAllocator.Allocate())
357         SuffixTreeNode(StartIdx, E, Root, Parent);
358     if (Parent)
359       Parent->Children[Edge] = N;
360 
361     return N;
362   }
363 
364   /// \brief Set the suffix indices of the leaves to the start indices of their
365   /// respective suffixes. Also stores each leaf in \p LeafVector at its
366   /// respective suffix index.
367   ///
368   /// \param[in] CurrNode The node currently being visited.
369   /// \param CurrIdx The current index of the string being visited.
370   void setSuffixIndices(SuffixTreeNode &CurrNode, size_t CurrIdx) {
371 
372     bool IsLeaf = CurrNode.Children.size() == 0 && !CurrNode.isRoot();
373 
374     // Store the length of the concatenation of all strings from the root to
375     // this node.
376     if (!CurrNode.isRoot()) {
377       if (CurrNode.ConcatLen == 0)
378         CurrNode.ConcatLen = CurrNode.size();
379 
380       if (CurrNode.Parent)
381         CurrNode.ConcatLen += CurrNode.Parent->ConcatLen;
382     }
383 
384     // Traverse the tree depth-first.
385     for (auto &ChildPair : CurrNode.Children) {
386       assert(ChildPair.second && "Node had a null child!");
387       setSuffixIndices(*ChildPair.second, CurrIdx + ChildPair.second->size());
388     }
389 
390     // Is this node a leaf?
391     if (IsLeaf) {
392       // If yes, give it a suffix index and bump its parent's occurrence count.
393       CurrNode.SuffixIdx = Str.size() - CurrIdx;
394       assert(CurrNode.Parent && "CurrNode had no parent!");
395       CurrNode.Parent->OccurrenceCount++;
396 
397       // Store the leaf in the leaf vector for pruning later.
398       LeafVector[CurrNode.SuffixIdx] = &CurrNode;
399     }
400   }
401 
402   /// \brief Construct the suffix tree for the prefix of the input ending at
403   /// \p EndIdx.
404   ///
405   /// Used to construct the full suffix tree iteratively. At the end of each
406   /// step, the constructed suffix tree is either a valid suffix tree, or a
407   /// suffix tree with implicit suffixes. At the end of the final step, the
408   /// suffix tree is a valid tree.
409   ///
410   /// \param EndIdx The end index of the current prefix in the main string.
411   /// \param SuffixesToAdd The number of suffixes that must be added
412   /// to complete the suffix tree at the current phase.
413   ///
414   /// \returns The number of suffixes that have not been added at the end of
415   /// this step.
416   unsigned extend(size_t EndIdx, size_t SuffixesToAdd) {
417     SuffixTreeNode *NeedsLink = nullptr;
418 
419     while (SuffixesToAdd > 0) {
420 
421       // Are we waiting to add anything other than just the last character?
422       if (Active.Len == 0) {
423         // If not, then say the active index is the end index.
424         Active.Idx = EndIdx;
425       }
426 
427       assert(Active.Idx <= EndIdx && "Start index can't be after end index!");
428 
429       // The first character in the current substring we're looking at.
430       unsigned FirstChar = Str[Active.Idx];
431 
432       // Have we inserted anything starting with FirstChar at the current node?
433       if (Active.Node->Children.count(FirstChar) == 0) {
434         // If not, then we can just insert a leaf and move too the next step.
435         insertLeaf(*Active.Node, EndIdx, FirstChar);
436 
437         // The active node is an internal node, and we visited it, so it must
438         // need a link if it doesn't have one.
439         if (NeedsLink) {
440           NeedsLink->Link = Active.Node;
441           NeedsLink = nullptr;
442         }
443       } else {
444         // There's a match with FirstChar, so look for the point in the tree to
445         // insert a new node.
446         SuffixTreeNode *NextNode = Active.Node->Children[FirstChar];
447 
448         size_t SubstringLen = NextNode->size();
449 
450         // Is the current suffix we're trying to insert longer than the size of
451         // the child we want to move to?
452         if (Active.Len >= SubstringLen) {
453           // If yes, then consume the characters we've seen and move to the next
454           // node.
455           Active.Idx += SubstringLen;
456           Active.Len -= SubstringLen;
457           Active.Node = NextNode;
458           continue;
459         }
460 
461         // Otherwise, the suffix we're trying to insert must be contained in the
462         // next node we want to move to.
463         unsigned LastChar = Str[EndIdx];
464 
465         // Is the string we're trying to insert a substring of the next node?
466         if (Str[NextNode->StartIdx + Active.Len] == LastChar) {
467           // If yes, then we're done for this step. Remember our insertion point
468           // and move to the next end index. At this point, we have an implicit
469           // suffix tree.
470           if (NeedsLink && !Active.Node->isRoot()) {
471             NeedsLink->Link = Active.Node;
472             NeedsLink = nullptr;
473           }
474 
475           Active.Len++;
476           break;
477         }
478 
479         // The string we're trying to insert isn't a substring of the next node,
480         // but matches up to a point. Split the node.
481         //
482         // For example, say we ended our search at a node n and we're trying to
483         // insert ABD. Then we'll create a new node s for AB, reduce n to just
484         // representing C, and insert a new leaf node l to represent d. This
485         // allows us to ensure that if n was a leaf, it remains a leaf.
486         //
487         //   | ABC  ---split--->  | AB
488         //   n                    s
489         //                     C / \ D
490         //                      n   l
491 
492         // The node s from the diagram
493         SuffixTreeNode *SplitNode =
494             insertInternalNode(Active.Node, NextNode->StartIdx,
495                                NextNode->StartIdx + Active.Len - 1, FirstChar);
496 
497         // Insert the new node representing the new substring into the tree as
498         // a child of the split node. This is the node l from the diagram.
499         insertLeaf(*SplitNode, EndIdx, LastChar);
500 
501         // Make the old node a child of the split node and update its start
502         // index. This is the node n from the diagram.
503         NextNode->StartIdx += Active.Len;
504         NextNode->Parent = SplitNode;
505         SplitNode->Children[Str[NextNode->StartIdx]] = NextNode;
506 
507         // SplitNode is an internal node, update the suffix link.
508         if (NeedsLink)
509           NeedsLink->Link = SplitNode;
510 
511         NeedsLink = SplitNode;
512       }
513 
514       // We've added something new to the tree, so there's one less suffix to
515       // add.
516       SuffixesToAdd--;
517 
518       if (Active.Node->isRoot()) {
519         if (Active.Len > 0) {
520           Active.Len--;
521           Active.Idx = EndIdx - SuffixesToAdd + 1;
522         }
523       } else {
524         // Start the next phase at the next smallest suffix.
525         Active.Node = Active.Node->Link;
526       }
527     }
528 
529     return SuffixesToAdd;
530   }
531 
532 public:
533   /// Construct a suffix tree from a sequence of unsigned integers.
534   ///
535   /// \param Str The string to construct the suffix tree for.
536   SuffixTree(const std::vector<unsigned> &Str) : Str(Str) {
537     Root = insertInternalNode(nullptr, EmptyIdx, EmptyIdx, 0);
538     Root->IsInTree = true;
539     Active.Node = Root;
540     LeafVector = std::vector<SuffixTreeNode *>(Str.size());
541 
542     // Keep track of the number of suffixes we have to add of the current
543     // prefix.
544     size_t SuffixesToAdd = 0;
545     Active.Node = Root;
546 
547     // Construct the suffix tree iteratively on each prefix of the string.
548     // PfxEndIdx is the end index of the current prefix.
549     // End is one past the last element in the string.
550     for (size_t PfxEndIdx = 0, End = Str.size(); PfxEndIdx < End; PfxEndIdx++) {
551       SuffixesToAdd++;
552       LeafEndIdx = PfxEndIdx; // Extend each of the leaves.
553       SuffixesToAdd = extend(PfxEndIdx, SuffixesToAdd);
554     }
555 
556     // Set the suffix indices of each leaf.
557     assert(Root && "Root node can't be nullptr!");
558     setSuffixIndices(*Root, 0);
559   }
560 };
561 
562 /// \brief Maps \p MachineInstrs to unsigned integers and stores the mappings.
563 struct InstructionMapper {
564 
565   /// \brief The next available integer to assign to a \p MachineInstr that
566   /// cannot be outlined.
567   ///
568   /// Set to -3 for compatability with \p DenseMapInfo<unsigned>.
569   unsigned IllegalInstrNumber = -3;
570 
571   /// \brief The next available integer to assign to a \p MachineInstr that can
572   /// be outlined.
573   unsigned LegalInstrNumber = 0;
574 
575   /// Correspondence from \p MachineInstrs to unsigned integers.
576   DenseMap<MachineInstr *, unsigned, MachineInstrExpressionTrait>
577       InstructionIntegerMap;
578 
579   /// Corresponcence from unsigned integers to \p MachineInstrs.
580   /// Inverse of \p InstructionIntegerMap.
581   DenseMap<unsigned, MachineInstr *> IntegerInstructionMap;
582 
583   /// The vector of unsigned integers that the module is mapped to.
584   std::vector<unsigned> UnsignedVec;
585 
586   /// \brief Stores the location of the instruction associated with the integer
587   /// at index i in \p UnsignedVec for each index i.
588   std::vector<MachineBasicBlock::iterator> InstrList;
589 
590   /// \brief Maps \p *It to a legal integer.
591   ///
592   /// Updates \p InstrList, \p UnsignedVec, \p InstructionIntegerMap,
593   /// \p IntegerInstructionMap, and \p LegalInstrNumber.
594   ///
595   /// \returns The integer that \p *It was mapped to.
596   unsigned mapToLegalUnsigned(MachineBasicBlock::iterator &It) {
597 
598     // Get the integer for this instruction or give it the current
599     // LegalInstrNumber.
600     InstrList.push_back(It);
601     MachineInstr &MI = *It;
602     bool WasInserted;
603     DenseMap<MachineInstr *, unsigned, MachineInstrExpressionTrait>::iterator
604         ResultIt;
605     std::tie(ResultIt, WasInserted) =
606         InstructionIntegerMap.insert(std::make_pair(&MI, LegalInstrNumber));
607     unsigned MINumber = ResultIt->second;
608 
609     // There was an insertion.
610     if (WasInserted) {
611       LegalInstrNumber++;
612       IntegerInstructionMap.insert(std::make_pair(MINumber, &MI));
613     }
614 
615     UnsignedVec.push_back(MINumber);
616 
617     // Make sure we don't overflow or use any integers reserved by the DenseMap.
618     if (LegalInstrNumber >= IllegalInstrNumber)
619       report_fatal_error("Instruction mapping overflow!");
620 
621     assert(LegalInstrNumber != DenseMapInfo<unsigned>::getEmptyKey() &&
622            "Tried to assign DenseMap tombstone or empty key to instruction.");
623     assert(LegalInstrNumber != DenseMapInfo<unsigned>::getTombstoneKey() &&
624            "Tried to assign DenseMap tombstone or empty key to instruction.");
625 
626     return MINumber;
627   }
628 
629   /// Maps \p *It to an illegal integer.
630   ///
631   /// Updates \p InstrList, \p UnsignedVec, and \p IllegalInstrNumber.
632   ///
633   /// \returns The integer that \p *It was mapped to.
634   unsigned mapToIllegalUnsigned(MachineBasicBlock::iterator &It) {
635     unsigned MINumber = IllegalInstrNumber;
636 
637     InstrList.push_back(It);
638     UnsignedVec.push_back(IllegalInstrNumber);
639     IllegalInstrNumber--;
640 
641     assert(LegalInstrNumber < IllegalInstrNumber &&
642            "Instruction mapping overflow!");
643 
644     assert(IllegalInstrNumber != DenseMapInfo<unsigned>::getEmptyKey() &&
645            "IllegalInstrNumber cannot be DenseMap tombstone or empty key!");
646 
647     assert(IllegalInstrNumber != DenseMapInfo<unsigned>::getTombstoneKey() &&
648            "IllegalInstrNumber cannot be DenseMap tombstone or empty key!");
649 
650     return MINumber;
651   }
652 
653   /// \brief Transforms a \p MachineBasicBlock into a \p vector of \p unsigneds
654   /// and appends it to \p UnsignedVec and \p InstrList.
655   ///
656   /// Two instructions are assigned the same integer if they are identical.
657   /// If an instruction is deemed unsafe to outline, then it will be assigned an
658   /// unique integer. The resulting mapping is placed into a suffix tree and
659   /// queried for candidates.
660   ///
661   /// \param MBB The \p MachineBasicBlock to be translated into integers.
662   /// \param TRI \p TargetRegisterInfo for the module.
663   /// \param TII \p TargetInstrInfo for the module.
664   void convertToUnsignedVec(MachineBasicBlock &MBB,
665                             const TargetRegisterInfo &TRI,
666                             const TargetInstrInfo &TII) {
667     for (MachineBasicBlock::iterator It = MBB.begin(), Et = MBB.end(); It != Et;
668          It++) {
669 
670       // Keep track of where this instruction is in the module.
671       switch (TII.getOutliningType(*It)) {
672       case TargetInstrInfo::MachineOutlinerInstrType::Illegal:
673         mapToIllegalUnsigned(It);
674         break;
675 
676       case TargetInstrInfo::MachineOutlinerInstrType::Legal:
677         mapToLegalUnsigned(It);
678         break;
679 
680       case TargetInstrInfo::MachineOutlinerInstrType::Invisible:
681         break;
682       }
683     }
684 
685     // After we're done every insertion, uniquely terminate this part of the
686     // "string". This makes sure we won't match across basic block or function
687     // boundaries since the "end" is encoded uniquely and thus appears in no
688     // repeated substring.
689     InstrList.push_back(MBB.end());
690     UnsignedVec.push_back(IllegalInstrNumber);
691     IllegalInstrNumber--;
692   }
693 
694   InstructionMapper() {
695     // Make sure that the implementation of DenseMapInfo<unsigned> hasn't
696     // changed.
697     assert(DenseMapInfo<unsigned>::getEmptyKey() == (unsigned)-1 &&
698            "DenseMapInfo<unsigned>'s empty key isn't -1!");
699     assert(DenseMapInfo<unsigned>::getTombstoneKey() == (unsigned)-2 &&
700            "DenseMapInfo<unsigned>'s tombstone key isn't -2!");
701   }
702 };
703 
704 /// \brief An interprocedural pass which finds repeated sequences of
705 /// instructions and replaces them with calls to functions.
706 ///
707 /// Each instruction is mapped to an unsigned integer and placed in a string.
708 /// The resulting mapping is then placed in a \p SuffixTree. The \p SuffixTree
709 /// is then repeatedly queried for repeated sequences of instructions. Each
710 /// non-overlapping repeated sequence is then placed in its own
711 /// \p MachineFunction and each instance is then replaced with a call to that
712 /// function.
713 struct MachineOutliner : public ModulePass {
714 
715   static char ID;
716 
717   StringRef getPassName() const override { return "Machine Outliner"; }
718 
719   void getAnalysisUsage(AnalysisUsage &AU) const override {
720     AU.addRequired<MachineModuleInfo>();
721     AU.addPreserved<MachineModuleInfo>();
722     AU.setPreservesAll();
723     ModulePass::getAnalysisUsage(AU);
724   }
725 
726   MachineOutliner() : ModulePass(ID) {
727     initializeMachineOutlinerPass(*PassRegistry::getPassRegistry());
728   }
729 
730   /// Find all repeated substrings that satisfy the outlining cost model.
731   ///
732   /// If a substring appears at least twice, then it must be represented by
733   /// an internal node which appears in at least two suffixes. Each suffix is
734   /// represented by a leaf node. To do this, we visit each internal node in
735   /// the tree, using the leaf children of each internal node. If an internal
736   /// node represents a beneficial substring, then we use each of its leaf
737   /// children to find the locations of its substring.
738   ///
739   /// \param ST A suffix tree to query.
740   /// \param TII TargetInstrInfo for the target.
741   /// \param Mapper Contains outlining mapping information.
742   /// \param[out] CandidateList Filled with candidates representing each
743   /// beneficial substring.
744   /// \param[out] FunctionList Filled with a list of \p OutlinedFunctions each
745   /// type of candidate.
746   ///
747   /// \returns The length of the longest candidate found.
748   size_t findCandidates(SuffixTree &ST, const TargetInstrInfo &TII,
749                         InstructionMapper &Mapper,
750                         std::vector<Candidate> &CandidateList,
751                         std::vector<OutlinedFunction> &FunctionList);
752 
753   /// \brief Replace the sequences of instructions represented by the
754   /// \p Candidates in \p CandidateList with calls to \p MachineFunctions
755   /// described in \p FunctionList.
756   ///
757   /// \param M The module we are outlining from.
758   /// \param CandidateList A list of candidates to be outlined.
759   /// \param FunctionList A list of functions to be inserted into the module.
760   /// \param Mapper Contains the instruction mappings for the module.
761   bool outline(Module &M, const ArrayRef<Candidate> &CandidateList,
762                std::vector<OutlinedFunction> &FunctionList,
763                InstructionMapper &Mapper);
764 
765   /// Creates a function for \p OF and inserts it into the module.
766   MachineFunction *createOutlinedFunction(Module &M, const OutlinedFunction &OF,
767                                           InstructionMapper &Mapper);
768 
769   /// Find potential outlining candidates and store them in \p CandidateList.
770   ///
771   /// For each type of potential candidate, also build an \p OutlinedFunction
772   /// struct containing the information to build the function for that
773   /// candidate.
774   ///
775   /// \param[out] CandidateList Filled with outlining candidates for the module.
776   /// \param[out] FunctionList Filled with functions corresponding to each type
777   /// of \p Candidate.
778   /// \param ST The suffix tree for the module.
779   /// \param TII TargetInstrInfo for the module.
780   ///
781   /// \returns The length of the longest candidate found. 0 if there are none.
782   unsigned buildCandidateList(std::vector<Candidate> &CandidateList,
783                               std::vector<OutlinedFunction> &FunctionList,
784                               SuffixTree &ST, InstructionMapper &Mapper,
785                               const TargetInstrInfo &TII);
786 
787   /// \brief Remove any overlapping candidates that weren't handled by the
788   /// suffix tree's pruning method.
789   ///
790   /// Pruning from the suffix tree doesn't necessarily remove all overlaps.
791   /// If a short candidate is chosen for outlining, then a longer candidate
792   /// which has that short candidate as a suffix is chosen, the tree's pruning
793   /// method will not find it. Thus, we need to prune before outlining as well.
794   ///
795   /// \param[in,out] CandidateList A list of outlining candidates.
796   /// \param[in,out] FunctionList A list of functions to be outlined.
797   /// \param Mapper Contains instruction mapping info for outlining.
798   /// \param MaxCandidateLen The length of the longest candidate.
799   /// \param TII TargetInstrInfo for the module.
800   void pruneOverlaps(std::vector<Candidate> &CandidateList,
801                      std::vector<OutlinedFunction> &FunctionList,
802                      InstructionMapper &Mapper, unsigned MaxCandidateLen,
803                      const TargetInstrInfo &TII);
804 
805   /// Construct a suffix tree on the instructions in \p M and outline repeated
806   /// strings from that tree.
807   bool runOnModule(Module &M) override;
808 };
809 
810 } // Anonymous namespace.
811 
812 char MachineOutliner::ID = 0;
813 
814 namespace llvm {
815 ModulePass *createMachineOutlinerPass() { return new MachineOutliner(); }
816 } // namespace llvm
817 
818 INITIALIZE_PASS(MachineOutliner, DEBUG_TYPE, "Machine Function Outliner", false,
819                 false)
820 
821 size_t
822 MachineOutliner::findCandidates(SuffixTree &ST, const TargetInstrInfo &TII,
823                                 InstructionMapper &Mapper,
824                                 std::vector<Candidate> &CandidateList,
825                                 std::vector<OutlinedFunction> &FunctionList) {
826 
827   CandidateList.clear();
828   FunctionList.clear();
829   size_t FnIdx = 0;
830   size_t MaxLen = 0;
831 
832   // FIXME: Visit internal nodes instead of leaves.
833   for (SuffixTreeNode *Leaf : ST.LeafVector) {
834     assert(Leaf && "Leaves in LeafVector cannot be null!");
835     if (!Leaf->IsInTree)
836       continue;
837 
838     assert(Leaf->Parent && "All leaves must have parents!");
839     SuffixTreeNode &Parent = *(Leaf->Parent);
840 
841     // If it doesn't appear enough, or we already outlined from it, skip it.
842     if (Parent.OccurrenceCount < 2 || Parent.isRoot() || !Parent.IsInTree)
843       continue;
844 
845     // Figure out if this candidate is beneficial.
846     size_t StringLen = Leaf->ConcatLen - Leaf->size();
847 
848     // Too short to be beneficial; skip it.
849     // FIXME: This isn't necessarily true for, say, X86. If we factor in
850     // instruction lengths we need more information than this.
851     if (StringLen < 2)
852       continue;
853 
854     size_t CallOverhead = 0;
855     size_t SequenceOverhead = StringLen;
856 
857     // If this is a beneficial class of candidate, then every one is stored in
858     // this vector.
859     std::vector<Candidate> CandidatesForRepeatedSeq;
860 
861     // Used for getOutliningFrameOverhead.
862     // FIXME: CandidatesForRepeatedSeq and this should be combined.
863     std::vector<
864         std::pair<MachineBasicBlock::iterator, MachineBasicBlock::iterator>>
865         CandidateClass;
866 
867     // Figure out the call overhead for each instance of the sequence.
868     for (auto &ChildPair : Parent.Children) {
869       SuffixTreeNode *M = ChildPair.second;
870 
871       if (M && M->IsInTree && M->isLeaf()) {
872         // Each sequence is over [StartIt, EndIt].
873         MachineBasicBlock::iterator StartIt = Mapper.InstrList[M->SuffixIdx];
874         MachineBasicBlock::iterator EndIt =
875             Mapper.InstrList[M->SuffixIdx + StringLen - 1];
876 
877         // Get the overhead for calling a function for this sequence and any
878         // target-specified data for how to construct the call.
879         std::pair<size_t, unsigned> CallOverheadPair =
880             TII.getOutliningCallOverhead(StartIt, EndIt);
881         CallOverhead += CallOverheadPair.first;
882         CandidatesForRepeatedSeq.emplace_back(M->SuffixIdx, StringLen, FnIdx,
883                                               CallOverheadPair.second);
884         CandidateClass.emplace_back(std::make_pair(StartIt, EndIt));
885 
886         // Never visit this leaf again.
887         M->IsInTree = false;
888       }
889     }
890 
891     std::pair<size_t, unsigned> FrameOverheadPair =
892         TII.getOutliningFrameOverhead(CandidateClass);
893     size_t FrameOverhead = FrameOverheadPair.first;
894 
895     size_t OutliningCost = CallOverhead + FrameOverhead + SequenceOverhead;
896     size_t NotOutliningCost = SequenceOverhead * Parent.OccurrenceCount;
897 
898     if (NotOutliningCost <= OutliningCost)
899       continue;
900 
901     size_t Benefit = NotOutliningCost - OutliningCost;
902 
903     if (StringLen > MaxLen)
904       MaxLen = StringLen;
905 
906     // At this point, the candidate class is seen as beneficial. Set their
907     // benefit values and save them in the candidate list.
908     for (Candidate &C : CandidatesForRepeatedSeq) {
909       C.Benefit = Benefit;
910       CandidateList.push_back(C);
911     }
912 
913     // Save the function for the new candidate sequence.
914     std::vector<unsigned> CandidateSequence;
915     for (unsigned i = Leaf->SuffixIdx; i < Leaf->SuffixIdx + StringLen; i++)
916       CandidateSequence.push_back(ST.Str[i]);
917 
918     FunctionList.emplace_back(FnIdx, CandidatesForRepeatedSeq.size(),
919                               CandidateSequence, Benefit,
920                               FrameOverheadPair.second);
921 
922     // Move to the next function.
923     FnIdx++;
924     Parent.IsInTree = false;
925   }
926 
927   return MaxLen;
928 }
929 
930 void MachineOutliner::pruneOverlaps(std::vector<Candidate> &CandidateList,
931                                     std::vector<OutlinedFunction> &FunctionList,
932                                     InstructionMapper &Mapper,
933                                     unsigned MaxCandidateLen,
934                                     const TargetInstrInfo &TII) {
935   // TODO: Experiment with interval trees or other interval-checking structures
936   // to lower the time complexity of this function.
937   // TODO: Can we do better than the simple greedy choice?
938   // Check for overlaps in the range.
939   // This is O(MaxCandidateLen * CandidateList.size()).
940   for (auto It = CandidateList.begin(), Et = CandidateList.end(); It != Et;
941        It++) {
942     Candidate &C1 = *It;
943     OutlinedFunction &F1 = FunctionList[C1.FunctionIdx];
944 
945     // If we removed this candidate, skip it.
946     if (!C1.InCandidateList)
947       continue;
948 
949     // Is it still worth it to outline C1?
950     if (F1.Benefit < 1 || F1.OccurrenceCount < 2) {
951       assert(F1.OccurrenceCount > 0 &&
952              "Can't remove OutlinedFunction with no occurrences!");
953       F1.OccurrenceCount--;
954       C1.InCandidateList = false;
955       continue;
956     }
957 
958     // The minimum start index of any candidate that could overlap with this
959     // one.
960     unsigned FarthestPossibleIdx = 0;
961 
962     // Either the index is 0, or it's at most MaxCandidateLen indices away.
963     if (C1.StartIdx > MaxCandidateLen)
964       FarthestPossibleIdx = C1.StartIdx - MaxCandidateLen;
965 
966     // Compare against the candidates in the list that start at at most
967     // FarthestPossibleIdx indices away from C1. There are at most
968     // MaxCandidateLen of these.
969     for (auto Sit = It + 1; Sit != Et; Sit++) {
970       Candidate &C2 = *Sit;
971       OutlinedFunction &F2 = FunctionList[C2.FunctionIdx];
972 
973       // Is this candidate too far away to overlap?
974       if (C2.StartIdx < FarthestPossibleIdx)
975         break;
976 
977       // Did we already remove this candidate in a previous step?
978       if (!C2.InCandidateList)
979         continue;
980 
981       // Is the function beneficial to outline?
982       if (F2.OccurrenceCount < 2 || F2.Benefit < 1) {
983         // If not, remove this candidate and move to the next one.
984         assert(F2.OccurrenceCount > 0 &&
985                "Can't remove OutlinedFunction with no occurrences!");
986         F2.OccurrenceCount--;
987         C2.InCandidateList = false;
988         continue;
989       }
990 
991       size_t C2End = C2.StartIdx + C2.Len - 1;
992 
993       // Do C1 and C2 overlap?
994       //
995       // Not overlapping:
996       // High indices... [C1End ... C1Start][C2End ... C2Start] ...Low indices
997       //
998       // We sorted our candidate list so C2Start <= C1Start. We know that
999       // C2End > C2Start since each candidate has length >= 2. Therefore, all we
1000       // have to check is C2End < C2Start to see if we overlap.
1001       if (C2End < C1.StartIdx)
1002         continue;
1003 
1004       // C1 and C2 overlap.
1005       // We need to choose the better of the two.
1006       //
1007       // Approximate this by picking the one which would have saved us the
1008       // most instructions before any pruning.
1009       if (C1.Benefit >= C2.Benefit) {
1010 
1011         // C1 is better, so remove C2 and update C2's OutlinedFunction to
1012         // reflect the removal.
1013         assert(F2.OccurrenceCount > 0 &&
1014                "Can't remove OutlinedFunction with no occurrences!");
1015         F2.OccurrenceCount--;
1016 
1017         // Remove the call overhead from the removed sequence.
1018         MachineBasicBlock::iterator StartIt = Mapper.InstrList[C2.StartIdx];
1019         MachineBasicBlock::iterator EndIt =
1020             Mapper.InstrList[C2.StartIdx + C2.Len - 1];
1021 
1022         F2.Benefit += TII.getOutliningCallOverhead(StartIt, EndIt).first;
1023         // Add back one instance of the sequence.
1024 
1025         if (F2.Sequence.size() > F2.Benefit)
1026           F2.Benefit = 0;
1027         else
1028           F2.Benefit -= F2.Sequence.size();
1029 
1030         C2.InCandidateList = false;
1031 
1032         DEBUG(dbgs() << "- Removed C2. \n";
1033               dbgs() << "--- Num fns left for C2: " << F2.OccurrenceCount
1034                      << "\n";
1035               dbgs() << "--- C2's benefit: " << F2.Benefit << "\n";);
1036 
1037       } else {
1038         // C2 is better, so remove C1 and update C1's OutlinedFunction to
1039         // reflect the removal.
1040         assert(F1.OccurrenceCount > 0 &&
1041                "Can't remove OutlinedFunction with no occurrences!");
1042         F1.OccurrenceCount--;
1043 
1044         // Remove the call overhead from the removed sequence.
1045         MachineBasicBlock::iterator StartIt = Mapper.InstrList[C1.StartIdx];
1046         MachineBasicBlock::iterator EndIt =
1047             Mapper.InstrList[C1.StartIdx + C1.Len - 1];
1048 
1049         F1.Benefit += TII.getOutliningCallOverhead(StartIt, EndIt).first;
1050 
1051         // Add back one instance of the sequence.
1052         if (F1.Sequence.size() > F1.Benefit)
1053           F1.Benefit = 0;
1054         else
1055           F1.Benefit -= F1.Sequence.size();
1056 
1057         C1.InCandidateList = false;
1058 
1059         DEBUG(dbgs() << "- Removed C1. \n";
1060               dbgs() << "--- Num fns left for C1: " << F1.OccurrenceCount
1061                      << "\n";
1062               dbgs() << "--- C1's benefit: " << F1.Benefit << "\n";);
1063 
1064         // C1 is out, so we don't have to compare it against anyone else.
1065         break;
1066       }
1067     }
1068   }
1069 }
1070 
1071 unsigned
1072 MachineOutliner::buildCandidateList(std::vector<Candidate> &CandidateList,
1073                                     std::vector<OutlinedFunction> &FunctionList,
1074                                     SuffixTree &ST, InstructionMapper &Mapper,
1075                                     const TargetInstrInfo &TII) {
1076 
1077   std::vector<unsigned> CandidateSequence; // Current outlining candidate.
1078   size_t MaxCandidateLen = 0;              // Length of the longest candidate.
1079 
1080   MaxCandidateLen =
1081       findCandidates(ST, TII, Mapper, CandidateList, FunctionList);
1082 
1083   // Sort the candidates in decending order. This will simplify the outlining
1084   // process when we have to remove the candidates from the mapping by
1085   // allowing us to cut them out without keeping track of an offset.
1086   std::stable_sort(CandidateList.begin(), CandidateList.end());
1087 
1088   return MaxCandidateLen;
1089 }
1090 
1091 MachineFunction *
1092 MachineOutliner::createOutlinedFunction(Module &M, const OutlinedFunction &OF,
1093                                         InstructionMapper &Mapper) {
1094 
1095   // Create the function name. This should be unique. For now, just hash the
1096   // module name and include it in the function name plus the number of this
1097   // function.
1098   std::ostringstream NameStream;
1099   NameStream << "OUTLINED_FUNCTION_" << OF.Name;
1100 
1101   // Create the function using an IR-level function.
1102   LLVMContext &C = M.getContext();
1103   Function *F = dyn_cast<Function>(
1104       M.getOrInsertFunction(NameStream.str(), Type::getVoidTy(C)));
1105   assert(F && "Function was null!");
1106 
1107   // NOTE: If this is linkonceodr, then we can take advantage of linker deduping
1108   // which gives us better results when we outline from linkonceodr functions.
1109   F->setLinkage(GlobalValue::PrivateLinkage);
1110   F->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
1111 
1112   BasicBlock *EntryBB = BasicBlock::Create(C, "entry", F);
1113   IRBuilder<> Builder(EntryBB);
1114   Builder.CreateRetVoid();
1115 
1116   MachineModuleInfo &MMI = getAnalysis<MachineModuleInfo>();
1117   MachineFunction &MF = MMI.getOrCreateMachineFunction(*F);
1118   MachineBasicBlock &MBB = *MF.CreateMachineBasicBlock();
1119   const TargetSubtargetInfo &STI = MF.getSubtarget();
1120   const TargetInstrInfo &TII = *STI.getInstrInfo();
1121 
1122   // Insert the new function into the module.
1123   MF.insert(MF.begin(), &MBB);
1124 
1125   TII.insertOutlinerPrologue(MBB, MF, OF.FrameClass);
1126 
1127   // Copy over the instructions for the function using the integer mappings in
1128   // its sequence.
1129   for (unsigned Str : OF.Sequence) {
1130     MachineInstr *NewMI =
1131         MF.CloneMachineInstr(Mapper.IntegerInstructionMap.find(Str)->second);
1132     NewMI->dropMemRefs();
1133 
1134     // Don't keep debug information for outlined instructions.
1135     // FIXME: This means outlined functions are currently undebuggable.
1136     NewMI->setDebugLoc(DebugLoc());
1137     MBB.insert(MBB.end(), NewMI);
1138   }
1139 
1140   TII.insertOutlinerEpilogue(MBB, MF, OF.FrameClass);
1141 
1142   return &MF;
1143 }
1144 
1145 bool MachineOutliner::outline(Module &M,
1146                               const ArrayRef<Candidate> &CandidateList,
1147                               std::vector<OutlinedFunction> &FunctionList,
1148                               InstructionMapper &Mapper) {
1149 
1150   bool OutlinedSomething = false;
1151 
1152   // Replace the candidates with calls to their respective outlined functions.
1153   for (const Candidate &C : CandidateList) {
1154 
1155     // Was the candidate removed during pruneOverlaps?
1156     if (!C.InCandidateList)
1157       continue;
1158 
1159     // If not, then look at its OutlinedFunction.
1160     OutlinedFunction &OF = FunctionList[C.FunctionIdx];
1161 
1162     // Was its OutlinedFunction made unbeneficial during pruneOverlaps?
1163     if (OF.OccurrenceCount < 2 || OF.Benefit < 1)
1164       continue;
1165 
1166     // If not, then outline it.
1167     assert(C.StartIdx < Mapper.InstrList.size() && "Candidate out of bounds!");
1168     MachineBasicBlock *MBB = (*Mapper.InstrList[C.StartIdx]).getParent();
1169     MachineBasicBlock::iterator StartIt = Mapper.InstrList[C.StartIdx];
1170     unsigned EndIdx = C.StartIdx + C.Len - 1;
1171 
1172     assert(EndIdx < Mapper.InstrList.size() && "Candidate out of bounds!");
1173     MachineBasicBlock::iterator EndIt = Mapper.InstrList[EndIdx];
1174     assert(EndIt != MBB->end() && "EndIt out of bounds!");
1175 
1176     EndIt++; // Erase needs one past the end index.
1177 
1178     // Does this candidate have a function yet?
1179     if (!OF.MF) {
1180       OF.MF = createOutlinedFunction(M, OF, Mapper);
1181       FunctionsCreated++;
1182     }
1183 
1184     MachineFunction *MF = OF.MF;
1185     const TargetSubtargetInfo &STI = MF->getSubtarget();
1186     const TargetInstrInfo &TII = *STI.getInstrInfo();
1187 
1188     // Insert a call to the new function and erase the old sequence.
1189     TII.insertOutlinedCall(M, *MBB, StartIt, *MF, C.CallClass);
1190     StartIt = Mapper.InstrList[C.StartIdx];
1191     MBB->erase(StartIt, EndIt);
1192 
1193     OutlinedSomething = true;
1194 
1195     // Statistics.
1196     NumOutlined++;
1197   }
1198 
1199   DEBUG(dbgs() << "OutlinedSomething = " << OutlinedSomething << "\n";);
1200 
1201   return OutlinedSomething;
1202 }
1203 
1204 bool MachineOutliner::runOnModule(Module &M) {
1205 
1206   // Is there anything in the module at all?
1207   if (M.empty())
1208     return false;
1209 
1210   MachineModuleInfo &MMI = getAnalysis<MachineModuleInfo>();
1211   const TargetSubtargetInfo &STI =
1212       MMI.getOrCreateMachineFunction(*M.begin()).getSubtarget();
1213   const TargetRegisterInfo *TRI = STI.getRegisterInfo();
1214   const TargetInstrInfo *TII = STI.getInstrInfo();
1215 
1216   InstructionMapper Mapper;
1217 
1218   // Build instruction mappings for each function in the module.
1219   for (Function &F : M) {
1220     MachineFunction &MF = MMI.getOrCreateMachineFunction(F);
1221 
1222     // Is the function empty? Safe to outline from?
1223     if (F.empty() || !TII->isFunctionSafeToOutlineFrom(MF))
1224       continue;
1225 
1226     // If it is, look at each MachineBasicBlock in the function.
1227     for (MachineBasicBlock &MBB : MF) {
1228 
1229       // Is there anything in MBB?
1230       if (MBB.empty())
1231         continue;
1232 
1233       // If yes, map it.
1234       Mapper.convertToUnsignedVec(MBB, *TRI, *TII);
1235     }
1236   }
1237 
1238   // Construct a suffix tree, use it to find candidates, and then outline them.
1239   SuffixTree ST(Mapper.UnsignedVec);
1240   std::vector<Candidate> CandidateList;
1241   std::vector<OutlinedFunction> FunctionList;
1242 
1243   // Find all of the outlining candidates.
1244   unsigned MaxCandidateLen =
1245       buildCandidateList(CandidateList, FunctionList, ST, Mapper, *TII);
1246 
1247   // Remove candidates that overlap with other candidates.
1248   pruneOverlaps(CandidateList, FunctionList, Mapper, MaxCandidateLen, *TII);
1249 
1250   // Outline each of the candidates and return true if something was outlined.
1251   return outline(M, CandidateList, FunctionList, Mapper);
1252 }
1253