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