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