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