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