1596f483aSJessica Paquette //===---- MachineOutliner.cpp - Outline instructions -----------*- C++ -*-===//
2596f483aSJessica Paquette //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6596f483aSJessica Paquette //
7596f483aSJessica Paquette //===----------------------------------------------------------------------===//
8596f483aSJessica Paquette ///
9596f483aSJessica Paquette /// \file
10596f483aSJessica Paquette /// Replaces repeated sequences of instructions with function calls.
11596f483aSJessica Paquette ///
12596f483aSJessica Paquette /// This works by placing every instruction from every basic block in a
13596f483aSJessica Paquette /// suffix tree, and repeatedly querying that tree for repeated sequences of
14596f483aSJessica Paquette /// instructions. If a sequence of instructions appears often, then it ought
15596f483aSJessica Paquette /// to be beneficial to pull out into a function.
16596f483aSJessica Paquette ///
174cf187b5SJessica Paquette /// The MachineOutliner communicates with a given target using hooks defined in
184cf187b5SJessica Paquette /// TargetInstrInfo.h. The target supplies the outliner with information on how
194cf187b5SJessica Paquette /// a specific sequence of instructions should be outlined. This information
204cf187b5SJessica Paquette /// is used to deduce the number of instructions necessary to
214cf187b5SJessica Paquette ///
224cf187b5SJessica Paquette /// * Create an outlined function
234cf187b5SJessica Paquette /// * Call that outlined function
244cf187b5SJessica Paquette ///
254cf187b5SJessica Paquette /// Targets must implement
264cf187b5SJessica Paquette ///   * getOutliningCandidateInfo
2732de26d4SJessica Paquette ///   * buildOutlinedFrame
284cf187b5SJessica Paquette ///   * insertOutlinedCall
294cf187b5SJessica Paquette ///   * isFunctionSafeToOutlineFrom
304cf187b5SJessica Paquette ///
314cf187b5SJessica Paquette /// in order to make use of the MachineOutliner.
324cf187b5SJessica Paquette ///
33596f483aSJessica Paquette /// This was originally presented at the 2016 LLVM Developers' Meeting in the
34596f483aSJessica Paquette /// talk "Reducing Code Size Using Outlining". For a high-level overview of
35596f483aSJessica Paquette /// how this pass works, the talk is available on YouTube at
36596f483aSJessica Paquette ///
37596f483aSJessica Paquette /// https://www.youtube.com/watch?v=yorld-WSOeU
38596f483aSJessica Paquette ///
39596f483aSJessica Paquette /// The slides for the talk are available at
40596f483aSJessica Paquette ///
41596f483aSJessica Paquette /// http://www.llvm.org/devmtg/2016-11/Slides/Paquette-Outliner.pdf
42596f483aSJessica Paquette ///
43596f483aSJessica Paquette /// The talk provides an overview of how the outliner finds candidates and
44596f483aSJessica Paquette /// ultimately outlines them. It describes how the main data structure for this
45596f483aSJessica Paquette /// pass, the suffix tree, is queried and purged for candidates. It also gives
46596f483aSJessica Paquette /// a simplified suffix tree construction algorithm for suffix trees based off
47596f483aSJessica Paquette /// of the algorithm actually used here, Ukkonen's algorithm.
48596f483aSJessica Paquette ///
49596f483aSJessica Paquette /// For the original RFC for this pass, please see
50596f483aSJessica Paquette ///
51596f483aSJessica Paquette /// http://lists.llvm.org/pipermail/llvm-dev/2016-August/104170.html
52596f483aSJessica Paquette ///
53596f483aSJessica Paquette /// For more information on the suffix tree data structure, please see
54596f483aSJessica Paquette /// https://www.cs.helsinki.fi/u/ukkonen/SuffixT1withFigs.pdf
55596f483aSJessica Paquette ///
56596f483aSJessica Paquette //===----------------------------------------------------------------------===//
57aa087327SJessica Paquette #include "llvm/CodeGen/MachineOutliner.h"
58596f483aSJessica Paquette #include "llvm/ADT/DenseMap.h"
59fc6fda90SJin Lin #include "llvm/ADT/SmallSet.h"
60596f483aSJessica Paquette #include "llvm/ADT/Statistic.h"
61596f483aSJessica Paquette #include "llvm/ADT/Twine.h"
62596f483aSJessica Paquette #include "llvm/CodeGen/MachineFunction.h"
63596f483aSJessica Paquette #include "llvm/CodeGen/MachineModuleInfo.h"
64ffe4abc5SJessica Paquette #include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h"
6582203c41SGeoff Berry #include "llvm/CodeGen/MachineRegisterInfo.h"
66596f483aSJessica Paquette #include "llvm/CodeGen/Passes.h"
673f833edcSDavid Blaikie #include "llvm/CodeGen/TargetInstrInfo.h"
68b3bde2eaSDavid Blaikie #include "llvm/CodeGen/TargetSubtargetInfo.h"
69729e6869SJessica Paquette #include "llvm/IR/DIBuilder.h"
70596f483aSJessica Paquette #include "llvm/IR/IRBuilder.h"
71a499c3c2SJessica Paquette #include "llvm/IR/Mangler.h"
7205da2fe5SReid Kleckner #include "llvm/InitializePasses.h"
731eca23bdSJessica Paquette #include "llvm/Support/CommandLine.h"
74596f483aSJessica Paquette #include "llvm/Support/Debug.h"
75bb677cacSAndrew Litteken #include "llvm/Support/SuffixTree.h"
76596f483aSJessica Paquette #include "llvm/Support/raw_ostream.h"
77596f483aSJessica Paquette #include <functional>
78596f483aSJessica Paquette #include <tuple>
79596f483aSJessica Paquette #include <vector>
80596f483aSJessica Paquette 
81596f483aSJessica Paquette #define DEBUG_TYPE "machine-outliner"
82596f483aSJessica Paquette 
83596f483aSJessica Paquette using namespace llvm;
84ffe4abc5SJessica Paquette using namespace ore;
85aa087327SJessica Paquette using namespace outliner;
86596f483aSJessica Paquette 
87596f483aSJessica Paquette STATISTIC(NumOutlined, "Number of candidates outlined");
88596f483aSJessica Paquette STATISTIC(FunctionsCreated, "Number of functions created");
89596f483aSJessica Paquette 
901eca23bdSJessica Paquette // Set to true if the user wants the outliner to run on linkonceodr linkage
911eca23bdSJessica Paquette // functions. This is false by default because the linker can dedupe linkonceodr
921eca23bdSJessica Paquette // functions. Since the outliner is confined to a single module (modulo LTO),
931eca23bdSJessica Paquette // this is off by default. It should, however, be the default behaviour in
941eca23bdSJessica Paquette // LTO.
951eca23bdSJessica Paquette static cl::opt<bool> EnableLinkOnceODROutlining(
966b7615aeSPuyan Lotfi     "enable-linkonceodr-outlining", cl::Hidden,
971eca23bdSJessica Paquette     cl::desc("Enable the machine outliner on linkonceodr functions"),
981eca23bdSJessica Paquette     cl::init(false));
991eca23bdSJessica Paquette 
100ffd5e121SPuyan Lotfi /// Number of times to re-run the outliner. This is not the total number of runs
101ffd5e121SPuyan Lotfi /// as the outliner will run at least one time. The default value is set to 0,
102ffd5e121SPuyan Lotfi /// meaning the outliner will run one time and rerun zero times after that.
103ffd5e121SPuyan Lotfi static cl::opt<unsigned> OutlinerReruns(
104ffd5e121SPuyan Lotfi     "machine-outliner-reruns", cl::init(0), cl::Hidden,
105ffd5e121SPuyan Lotfi     cl::desc(
106ffd5e121SPuyan Lotfi         "Number of times to rerun the outliner after the initial outline"));
1070d896278SJin Lin 
108596f483aSJessica Paquette namespace {
109596f483aSJessica Paquette 
1105f8f34e4SAdrian Prantl /// Maps \p MachineInstrs to unsigned integers and stores the mappings.
111596f483aSJessica Paquette struct InstructionMapper {
112596f483aSJessica Paquette 
1135f8f34e4SAdrian Prantl   /// The next available integer to assign to a \p MachineInstr that
114596f483aSJessica Paquette   /// cannot be outlined.
115596f483aSJessica Paquette   ///
116596f483aSJessica Paquette   /// Set to -3 for compatability with \p DenseMapInfo<unsigned>.
117596f483aSJessica Paquette   unsigned IllegalInstrNumber = -3;
118596f483aSJessica Paquette 
1195f8f34e4SAdrian Prantl   /// The next available integer to assign to a \p MachineInstr that can
120596f483aSJessica Paquette   /// be outlined.
121596f483aSJessica Paquette   unsigned LegalInstrNumber = 0;
122596f483aSJessica Paquette 
123596f483aSJessica Paquette   /// Correspondence from \p MachineInstrs to unsigned integers.
124596f483aSJessica Paquette   DenseMap<MachineInstr *, unsigned, MachineInstrExpressionTrait>
125596f483aSJessica Paquette       InstructionIntegerMap;
126596f483aSJessica Paquette 
127cad864d4SJessica Paquette   /// Correspondence between \p MachineBasicBlocks and target-defined flags.
128cad864d4SJessica Paquette   DenseMap<MachineBasicBlock *, unsigned> MBBFlagsMap;
129cad864d4SJessica Paquette 
130596f483aSJessica Paquette   /// The vector of unsigned integers that the module is mapped to.
131596f483aSJessica Paquette   std::vector<unsigned> UnsignedVec;
132596f483aSJessica Paquette 
1335f8f34e4SAdrian Prantl   /// Stores the location of the instruction associated with the integer
134596f483aSJessica Paquette   /// at index i in \p UnsignedVec for each index i.
135596f483aSJessica Paquette   std::vector<MachineBasicBlock::iterator> InstrList;
136596f483aSJessica Paquette 
137c991cf36SJessica Paquette   // Set if we added an illegal number in the previous step.
138c991cf36SJessica Paquette   // Since each illegal number is unique, we only need one of them between
139c991cf36SJessica Paquette   // each range of legal numbers. This lets us make sure we don't add more
140c991cf36SJessica Paquette   // than one illegal number per range.
141c991cf36SJessica Paquette   bool AddedIllegalLastTime = false;
142c991cf36SJessica Paquette 
1435f8f34e4SAdrian Prantl   /// Maps \p *It to a legal integer.
144596f483aSJessica Paquette   ///
145c4cf775aSJessica Paquette   /// Updates \p CanOutlineWithPrevInstr, \p HaveLegalRange, \p InstrListForMBB,
146ca3ed964SJessica Paquette   /// \p UnsignedVecForMBB, \p InstructionIntegerMap, and \p LegalInstrNumber.
147596f483aSJessica Paquette   ///
148596f483aSJessica Paquette   /// \returns The integer that \p *It was mapped to.
149267d266cSJessica Paquette   unsigned mapToLegalUnsigned(
150c4cf775aSJessica Paquette       MachineBasicBlock::iterator &It, bool &CanOutlineWithPrevInstr,
151c4cf775aSJessica Paquette       bool &HaveLegalRange, unsigned &NumLegalInBlock,
152267d266cSJessica Paquette       std::vector<unsigned> &UnsignedVecForMBB,
153267d266cSJessica Paquette       std::vector<MachineBasicBlock::iterator> &InstrListForMBB) {
154c991cf36SJessica Paquette     // We added something legal, so we should unset the AddedLegalLastTime
155c991cf36SJessica Paquette     // flag.
156c991cf36SJessica Paquette     AddedIllegalLastTime = false;
157596f483aSJessica Paquette 
158c4cf775aSJessica Paquette     // If we have at least two adjacent legal instructions (which may have
159c4cf775aSJessica Paquette     // invisible instructions in between), remember that.
160c4cf775aSJessica Paquette     if (CanOutlineWithPrevInstr)
161c4cf775aSJessica Paquette       HaveLegalRange = true;
162c4cf775aSJessica Paquette     CanOutlineWithPrevInstr = true;
163c4cf775aSJessica Paquette 
164267d266cSJessica Paquette     // Keep track of the number of legal instructions we insert.
165267d266cSJessica Paquette     NumLegalInBlock++;
166267d266cSJessica Paquette 
167596f483aSJessica Paquette     // Get the integer for this instruction or give it the current
168596f483aSJessica Paquette     // LegalInstrNumber.
169267d266cSJessica Paquette     InstrListForMBB.push_back(It);
170596f483aSJessica Paquette     MachineInstr &MI = *It;
171596f483aSJessica Paquette     bool WasInserted;
172596f483aSJessica Paquette     DenseMap<MachineInstr *, unsigned, MachineInstrExpressionTrait>::iterator
173596f483aSJessica Paquette         ResultIt;
174596f483aSJessica Paquette     std::tie(ResultIt, WasInserted) =
175596f483aSJessica Paquette         InstructionIntegerMap.insert(std::make_pair(&MI, LegalInstrNumber));
176596f483aSJessica Paquette     unsigned MINumber = ResultIt->second;
177596f483aSJessica Paquette 
178596f483aSJessica Paquette     // There was an insertion.
179ca3ed964SJessica Paquette     if (WasInserted)
180596f483aSJessica Paquette       LegalInstrNumber++;
181596f483aSJessica Paquette 
182267d266cSJessica Paquette     UnsignedVecForMBB.push_back(MINumber);
183596f483aSJessica Paquette 
184596f483aSJessica Paquette     // Make sure we don't overflow or use any integers reserved by the DenseMap.
185596f483aSJessica Paquette     if (LegalInstrNumber >= IllegalInstrNumber)
186596f483aSJessica Paquette       report_fatal_error("Instruction mapping overflow!");
187596f483aSJessica Paquette 
18878681be2SJessica Paquette     assert(LegalInstrNumber != DenseMapInfo<unsigned>::getEmptyKey() &&
18978681be2SJessica Paquette            "Tried to assign DenseMap tombstone or empty key to instruction.");
19078681be2SJessica Paquette     assert(LegalInstrNumber != DenseMapInfo<unsigned>::getTombstoneKey() &&
19178681be2SJessica Paquette            "Tried to assign DenseMap tombstone or empty key to instruction.");
192596f483aSJessica Paquette 
193596f483aSJessica Paquette     return MINumber;
194596f483aSJessica Paquette   }
195596f483aSJessica Paquette 
196596f483aSJessica Paquette   /// Maps \p *It to an illegal integer.
197596f483aSJessica Paquette   ///
198267d266cSJessica Paquette   /// Updates \p InstrListForMBB, \p UnsignedVecForMBB, and \p
199267d266cSJessica Paquette   /// IllegalInstrNumber.
200596f483aSJessica Paquette   ///
201596f483aSJessica Paquette   /// \returns The integer that \p *It was mapped to.
2026b7615aeSPuyan Lotfi   unsigned mapToIllegalUnsigned(
2036b7615aeSPuyan Lotfi       MachineBasicBlock::iterator &It, bool &CanOutlineWithPrevInstr,
2046b7615aeSPuyan Lotfi       std::vector<unsigned> &UnsignedVecForMBB,
205267d266cSJessica Paquette       std::vector<MachineBasicBlock::iterator> &InstrListForMBB) {
206c4cf775aSJessica Paquette     // Can't outline an illegal instruction. Set the flag.
207c4cf775aSJessica Paquette     CanOutlineWithPrevInstr = false;
208c4cf775aSJessica Paquette 
209c991cf36SJessica Paquette     // Only add one illegal number per range of legal numbers.
210c991cf36SJessica Paquette     if (AddedIllegalLastTime)
211c991cf36SJessica Paquette       return IllegalInstrNumber;
212c991cf36SJessica Paquette 
213c991cf36SJessica Paquette     // Remember that we added an illegal number last time.
214c991cf36SJessica Paquette     AddedIllegalLastTime = true;
215596f483aSJessica Paquette     unsigned MINumber = IllegalInstrNumber;
216596f483aSJessica Paquette 
217267d266cSJessica Paquette     InstrListForMBB.push_back(It);
218267d266cSJessica Paquette     UnsignedVecForMBB.push_back(IllegalInstrNumber);
219596f483aSJessica Paquette     IllegalInstrNumber--;
220596f483aSJessica Paquette 
221596f483aSJessica Paquette     assert(LegalInstrNumber < IllegalInstrNumber &&
222596f483aSJessica Paquette            "Instruction mapping overflow!");
223596f483aSJessica Paquette 
22478681be2SJessica Paquette     assert(IllegalInstrNumber != DenseMapInfo<unsigned>::getEmptyKey() &&
225596f483aSJessica Paquette            "IllegalInstrNumber cannot be DenseMap tombstone or empty key!");
226596f483aSJessica Paquette 
22778681be2SJessica Paquette     assert(IllegalInstrNumber != DenseMapInfo<unsigned>::getTombstoneKey() &&
228596f483aSJessica Paquette            "IllegalInstrNumber cannot be DenseMap tombstone or empty key!");
229596f483aSJessica Paquette 
230596f483aSJessica Paquette     return MINumber;
231596f483aSJessica Paquette   }
232596f483aSJessica Paquette 
2335f8f34e4SAdrian Prantl   /// Transforms a \p MachineBasicBlock into a \p vector of \p unsigneds
234596f483aSJessica Paquette   /// and appends it to \p UnsignedVec and \p InstrList.
235596f483aSJessica Paquette   ///
236596f483aSJessica Paquette   /// Two instructions are assigned the same integer if they are identical.
237596f483aSJessica Paquette   /// If an instruction is deemed unsafe to outline, then it will be assigned an
238596f483aSJessica Paquette   /// unique integer. The resulting mapping is placed into a suffix tree and
239596f483aSJessica Paquette   /// queried for candidates.
240596f483aSJessica Paquette   ///
241596f483aSJessica Paquette   /// \param MBB The \p MachineBasicBlock to be translated into integers.
242da08078fSEli Friedman   /// \param TII \p TargetInstrInfo for the function.
243596f483aSJessica Paquette   void convertToUnsignedVec(MachineBasicBlock &MBB,
244596f483aSJessica Paquette                             const TargetInstrInfo &TII) {
2453635c890SAlexander Kornienko     unsigned Flags = 0;
24682d9c0a3SJessica Paquette 
24782d9c0a3SJessica Paquette     // Don't even map in this case.
24882d9c0a3SJessica Paquette     if (!TII.isMBBSafeToOutlineFrom(MBB, Flags))
24982d9c0a3SJessica Paquette       return;
25082d9c0a3SJessica Paquette 
251cad864d4SJessica Paquette     // Store info for the MBB for later outlining.
252cad864d4SJessica Paquette     MBBFlagsMap[&MBB] = Flags;
253cad864d4SJessica Paquette 
254c991cf36SJessica Paquette     MachineBasicBlock::iterator It = MBB.begin();
255267d266cSJessica Paquette 
256267d266cSJessica Paquette     // The number of instructions in this block that will be considered for
257267d266cSJessica Paquette     // outlining.
258267d266cSJessica Paquette     unsigned NumLegalInBlock = 0;
259267d266cSJessica Paquette 
260c4cf775aSJessica Paquette     // True if we have at least two legal instructions which aren't separated
261c4cf775aSJessica Paquette     // by an illegal instruction.
262c4cf775aSJessica Paquette     bool HaveLegalRange = false;
263c4cf775aSJessica Paquette 
264c4cf775aSJessica Paquette     // True if we can perform outlining given the last mapped (non-invisible)
265c4cf775aSJessica Paquette     // instruction. This lets us know if we have a legal range.
266c4cf775aSJessica Paquette     bool CanOutlineWithPrevInstr = false;
267c4cf775aSJessica Paquette 
268267d266cSJessica Paquette     // FIXME: Should this all just be handled in the target, rather than using
269267d266cSJessica Paquette     // repeated calls to getOutliningType?
270267d266cSJessica Paquette     std::vector<unsigned> UnsignedVecForMBB;
271267d266cSJessica Paquette     std::vector<MachineBasicBlock::iterator> InstrListForMBB;
272267d266cSJessica Paquette 
27376166a1aSSimon Pilgrim     for (MachineBasicBlock::iterator Et = MBB.end(); It != Et; ++It) {
274596f483aSJessica Paquette       // Keep track of where this instruction is in the module.
2753291e735SJessica Paquette       switch (TII.getOutliningType(It, Flags)) {
276aa087327SJessica Paquette       case InstrType::Illegal:
2776b7615aeSPuyan Lotfi         mapToIllegalUnsigned(It, CanOutlineWithPrevInstr, UnsignedVecForMBB,
2786b7615aeSPuyan Lotfi                              InstrListForMBB);
279596f483aSJessica Paquette         break;
280596f483aSJessica Paquette 
281aa087327SJessica Paquette       case InstrType::Legal:
282c4cf775aSJessica Paquette         mapToLegalUnsigned(It, CanOutlineWithPrevInstr, HaveLegalRange,
283c4cf775aSJessica Paquette                            NumLegalInBlock, UnsignedVecForMBB, InstrListForMBB);
284596f483aSJessica Paquette         break;
285596f483aSJessica Paquette 
286aa087327SJessica Paquette       case InstrType::LegalTerminator:
287c4cf775aSJessica Paquette         mapToLegalUnsigned(It, CanOutlineWithPrevInstr, HaveLegalRange,
288c4cf775aSJessica Paquette                            NumLegalInBlock, UnsignedVecForMBB, InstrListForMBB);
289c991cf36SJessica Paquette         // The instruction also acts as a terminator, so we have to record that
290c991cf36SJessica Paquette         // in the string.
291c4cf775aSJessica Paquette         mapToIllegalUnsigned(It, CanOutlineWithPrevInstr, UnsignedVecForMBB,
292c4cf775aSJessica Paquette                              InstrListForMBB);
293042dc9e0SEli Friedman         break;
294042dc9e0SEli Friedman 
295aa087327SJessica Paquette       case InstrType::Invisible:
296c991cf36SJessica Paquette         // Normally this is set by mapTo(Blah)Unsigned, but we just want to
297c991cf36SJessica Paquette         // skip this instruction. So, unset the flag here.
298bd72988cSJessica Paquette         AddedIllegalLastTime = false;
299596f483aSJessica Paquette         break;
300596f483aSJessica Paquette       }
301596f483aSJessica Paquette     }
302596f483aSJessica Paquette 
303267d266cSJessica Paquette     // Are there enough legal instructions in the block for outlining to be
304267d266cSJessica Paquette     // possible?
305c4cf775aSJessica Paquette     if (HaveLegalRange) {
306596f483aSJessica Paquette       // After we're done every insertion, uniquely terminate this part of the
307596f483aSJessica Paquette       // "string". This makes sure we won't match across basic block or function
308596f483aSJessica Paquette       // boundaries since the "end" is encoded uniquely and thus appears in no
309596f483aSJessica Paquette       // repeated substring.
310c4cf775aSJessica Paquette       mapToIllegalUnsigned(It, CanOutlineWithPrevInstr, UnsignedVecForMBB,
311c4cf775aSJessica Paquette                            InstrListForMBB);
312267d266cSJessica Paquette       InstrList.insert(InstrList.end(), InstrListForMBB.begin(),
313267d266cSJessica Paquette                        InstrListForMBB.end());
314267d266cSJessica Paquette       UnsignedVec.insert(UnsignedVec.end(), UnsignedVecForMBB.begin(),
315267d266cSJessica Paquette                          UnsignedVecForMBB.end());
316267d266cSJessica Paquette     }
317596f483aSJessica Paquette   }
318596f483aSJessica Paquette 
319596f483aSJessica Paquette   InstructionMapper() {
320596f483aSJessica Paquette     // Make sure that the implementation of DenseMapInfo<unsigned> hasn't
321596f483aSJessica Paquette     // changed.
322596f483aSJessica Paquette     assert(DenseMapInfo<unsigned>::getEmptyKey() == (unsigned)-1 &&
323596f483aSJessica Paquette            "DenseMapInfo<unsigned>'s empty key isn't -1!");
324596f483aSJessica Paquette     assert(DenseMapInfo<unsigned>::getTombstoneKey() == (unsigned)-2 &&
325596f483aSJessica Paquette            "DenseMapInfo<unsigned>'s tombstone key isn't -2!");
326596f483aSJessica Paquette   }
327596f483aSJessica Paquette };
328596f483aSJessica Paquette 
3295f8f34e4SAdrian Prantl /// An interprocedural pass which finds repeated sequences of
330596f483aSJessica Paquette /// instructions and replaces them with calls to functions.
331596f483aSJessica Paquette ///
332596f483aSJessica Paquette /// Each instruction is mapped to an unsigned integer and placed in a string.
333596f483aSJessica Paquette /// The resulting mapping is then placed in a \p SuffixTree. The \p SuffixTree
334596f483aSJessica Paquette /// is then repeatedly queried for repeated sequences of instructions. Each
335596f483aSJessica Paquette /// non-overlapping repeated sequence is then placed in its own
336596f483aSJessica Paquette /// \p MachineFunction and each instance is then replaced with a call to that
337596f483aSJessica Paquette /// function.
338596f483aSJessica Paquette struct MachineOutliner : public ModulePass {
339596f483aSJessica Paquette 
340596f483aSJessica Paquette   static char ID;
341596f483aSJessica Paquette 
3425f8f34e4SAdrian Prantl   /// Set to true if the outliner should consider functions with
34313593843SJessica Paquette   /// linkonceodr linkage.
34413593843SJessica Paquette   bool OutlineFromLinkOnceODRs = false;
34513593843SJessica Paquette 
3460d896278SJin Lin   /// The current repeat number of machine outlining.
3470d896278SJin Lin   unsigned OutlineRepeatedNum = 0;
3480d896278SJin Lin 
3498bda1881SJessica Paquette   /// Set to true if the outliner should run on all functions in the module
3508bda1881SJessica Paquette   /// considered safe for outlining.
3518bda1881SJessica Paquette   /// Set to true by default for compatibility with llc's -run-pass option.
3528bda1881SJessica Paquette   /// Set when the pass is constructed in TargetPassConfig.
3538bda1881SJessica Paquette   bool RunOnAllFunctions = true;
3548bda1881SJessica Paquette 
355596f483aSJessica Paquette   StringRef getPassName() const override { return "Machine Outliner"; }
356596f483aSJessica Paquette 
357596f483aSJessica Paquette   void getAnalysisUsage(AnalysisUsage &AU) const override {
358cc382cf7SYuanfang Chen     AU.addRequired<MachineModuleInfoWrapperPass>();
359cc382cf7SYuanfang Chen     AU.addPreserved<MachineModuleInfoWrapperPass>();
360596f483aSJessica Paquette     AU.setPreservesAll();
361596f483aSJessica Paquette     ModulePass::getAnalysisUsage(AU);
362596f483aSJessica Paquette   }
363596f483aSJessica Paquette 
3641eca23bdSJessica Paquette   MachineOutliner() : ModulePass(ID) {
365596f483aSJessica Paquette     initializeMachineOutlinerPass(*PassRegistry::getPassRegistry());
366596f483aSJessica Paquette   }
367596f483aSJessica Paquette 
3681cc52a00SJessica Paquette   /// Remark output explaining that not outlining a set of candidates would be
3691cc52a00SJessica Paquette   /// better than outlining that set.
3701cc52a00SJessica Paquette   void emitNotOutliningCheaperRemark(
3711cc52a00SJessica Paquette       unsigned StringLen, std::vector<Candidate> &CandidatesForRepeatedSeq,
3721cc52a00SJessica Paquette       OutlinedFunction &OF);
3731cc52a00SJessica Paquette 
37458e706a6SJessica Paquette   /// Remark output explaining that a function was outlined.
37558e706a6SJessica Paquette   void emitOutlinedFunctionRemark(OutlinedFunction &OF);
37658e706a6SJessica Paquette 
377ce3a2dcfSJessica Paquette   /// Find all repeated substrings that satisfy the outlining cost model by
378ce3a2dcfSJessica Paquette   /// constructing a suffix tree.
37978681be2SJessica Paquette   ///
38078681be2SJessica Paquette   /// If a substring appears at least twice, then it must be represented by
3811cc52a00SJessica Paquette   /// an internal node which appears in at least two suffixes. Each suffix
3821cc52a00SJessica Paquette   /// is represented by a leaf node. To do this, we visit each internal node
3831cc52a00SJessica Paquette   /// in the tree, using the leaf children of each internal node. If an
3841cc52a00SJessica Paquette   /// internal node represents a beneficial substring, then we use each of
3851cc52a00SJessica Paquette   /// its leaf children to find the locations of its substring.
38678681be2SJessica Paquette   ///
38778681be2SJessica Paquette   /// \param Mapper Contains outlining mapping information.
3881cc52a00SJessica Paquette   /// \param[out] FunctionList Filled with a list of \p OutlinedFunctions
3891cc52a00SJessica Paquette   /// each type of candidate.
390ce3a2dcfSJessica Paquette   void findCandidates(InstructionMapper &Mapper,
39178681be2SJessica Paquette                       std::vector<OutlinedFunction> &FunctionList);
39278681be2SJessica Paquette 
3934ae3b71dSJessica Paquette   /// Replace the sequences of instructions represented by \p OutlinedFunctions
3944ae3b71dSJessica Paquette   /// with calls to functions.
395596f483aSJessica Paquette   ///
396596f483aSJessica Paquette   /// \param M The module we are outlining from.
397596f483aSJessica Paquette   /// \param FunctionList A list of functions to be inserted into the module.
398596f483aSJessica Paquette   /// \param Mapper Contains the instruction mappings for the module.
3994ae3b71dSJessica Paquette   bool outline(Module &M, std::vector<OutlinedFunction> &FunctionList,
4006b7615aeSPuyan Lotfi                InstructionMapper &Mapper, unsigned &OutlinedFunctionNum);
401596f483aSJessica Paquette 
402596f483aSJessica Paquette   /// Creates a function for \p OF and inserts it into the module.
403e18d6ff0SJessica Paquette   MachineFunction *createOutlinedFunction(Module &M, OutlinedFunction &OF,
404a3eb0facSJessica Paquette                                           InstructionMapper &Mapper,
405a3eb0facSJessica Paquette                                           unsigned Name);
406596f483aSJessica Paquette 
407ffd5e121SPuyan Lotfi   /// Calls 'doOutline()' 1 + OutlinerReruns times.
4087b166d51SJin Lin   bool runOnModule(Module &M) override;
409ab2dcff3SJin Lin 
410596f483aSJessica Paquette   /// Construct a suffix tree on the instructions in \p M and outline repeated
411596f483aSJessica Paquette   /// strings from that tree.
412a51fc8ddSPuyan Lotfi   bool doOutline(Module &M, unsigned &OutlinedFunctionNum);
413aa087327SJessica Paquette 
414aa087327SJessica Paquette   /// Return a DISubprogram for OF if one exists, and null otherwise. Helper
415aa087327SJessica Paquette   /// function for remark emission.
416aa087327SJessica Paquette   DISubprogram *getSubprogramOrNull(const OutlinedFunction &OF) {
417e18d6ff0SJessica Paquette     for (const Candidate &C : OF.Candidates)
4187ad25836SSimon Pilgrim       if (MachineFunction *MF = C.getMF())
4197ad25836SSimon Pilgrim         if (DISubprogram *SP = MF->getFunction().getSubprogram())
420aa087327SJessica Paquette           return SP;
421aa087327SJessica Paquette     return nullptr;
422aa087327SJessica Paquette   }
423050d1ac4SJessica Paquette 
424050d1ac4SJessica Paquette   /// Populate and \p InstructionMapper with instruction-to-integer mappings.
425050d1ac4SJessica Paquette   /// These are used to construct a suffix tree.
426050d1ac4SJessica Paquette   void populateMapper(InstructionMapper &Mapper, Module &M,
427050d1ac4SJessica Paquette                       MachineModuleInfo &MMI);
428596f483aSJessica Paquette 
4292386eab3SJessica Paquette   /// Initialize information necessary to output a size remark.
4302386eab3SJessica Paquette   /// FIXME: This should be handled by the pass manager, not the outliner.
4312386eab3SJessica Paquette   /// FIXME: This is nearly identical to the initSizeRemarkInfo in the legacy
4322386eab3SJessica Paquette   /// pass manager.
4336b7615aeSPuyan Lotfi   void initSizeRemarkInfo(const Module &M, const MachineModuleInfo &MMI,
4342386eab3SJessica Paquette                           StringMap<unsigned> &FunctionToInstrCount);
4352386eab3SJessica Paquette 
4362386eab3SJessica Paquette   /// Emit the remark.
4372386eab3SJessica Paquette   // FIXME: This should be handled by the pass manager, not the outliner.
4386b7615aeSPuyan Lotfi   void
4396b7615aeSPuyan Lotfi   emitInstrCountChangedRemark(const Module &M, const MachineModuleInfo &MMI,
4402386eab3SJessica Paquette                               const StringMap<unsigned> &FunctionToInstrCount);
4412386eab3SJessica Paquette };
442596f483aSJessica Paquette } // Anonymous namespace.
443596f483aSJessica Paquette 
444596f483aSJessica Paquette char MachineOutliner::ID = 0;
445596f483aSJessica Paquette 
446596f483aSJessica Paquette namespace llvm {
4478bda1881SJessica Paquette ModulePass *createMachineOutlinerPass(bool RunOnAllFunctions) {
4488bda1881SJessica Paquette   MachineOutliner *OL = new MachineOutliner();
4498bda1881SJessica Paquette   OL->RunOnAllFunctions = RunOnAllFunctions;
4508bda1881SJessica Paquette   return OL;
45113593843SJessica Paquette }
45213593843SJessica Paquette 
45378681be2SJessica Paquette } // namespace llvm
45478681be2SJessica Paquette 
45578681be2SJessica Paquette INITIALIZE_PASS(MachineOutliner, DEBUG_TYPE, "Machine Function Outliner", false,
45678681be2SJessica Paquette                 false)
45778681be2SJessica Paquette 
4581cc52a00SJessica Paquette void MachineOutliner::emitNotOutliningCheaperRemark(
4591cc52a00SJessica Paquette     unsigned StringLen, std::vector<Candidate> &CandidatesForRepeatedSeq,
4601cc52a00SJessica Paquette     OutlinedFunction &OF) {
461c991cf36SJessica Paquette   // FIXME: Right now, we arbitrarily choose some Candidate from the
462c991cf36SJessica Paquette   // OutlinedFunction. This isn't necessarily fixed, nor does it have to be.
463c991cf36SJessica Paquette   // We should probably sort these by function name or something to make sure
464c991cf36SJessica Paquette   // the remarks are stable.
4651cc52a00SJessica Paquette   Candidate &C = CandidatesForRepeatedSeq.front();
4661cc52a00SJessica Paquette   MachineOptimizationRemarkEmitter MORE(*(C.getMF()), nullptr);
4671cc52a00SJessica Paquette   MORE.emit([&]() {
4681cc52a00SJessica Paquette     MachineOptimizationRemarkMissed R(DEBUG_TYPE, "NotOutliningCheaper",
4691cc52a00SJessica Paquette                                       C.front()->getDebugLoc(), C.getMBB());
4701cc52a00SJessica Paquette     R << "Did not outline " << NV("Length", StringLen) << " instructions"
4711cc52a00SJessica Paquette       << " from " << NV("NumOccurrences", CandidatesForRepeatedSeq.size())
4721cc52a00SJessica Paquette       << " locations."
4731cc52a00SJessica Paquette       << " Bytes from outlining all occurrences ("
4741cc52a00SJessica Paquette       << NV("OutliningCost", OF.getOutliningCost()) << ")"
4751cc52a00SJessica Paquette       << " >= Unoutlined instruction bytes ("
4761cc52a00SJessica Paquette       << NV("NotOutliningCost", OF.getNotOutlinedCost()) << ")"
4771cc52a00SJessica Paquette       << " (Also found at: ";
4781cc52a00SJessica Paquette 
4791cc52a00SJessica Paquette     // Tell the user the other places the candidate was found.
4801cc52a00SJessica Paquette     for (unsigned i = 1, e = CandidatesForRepeatedSeq.size(); i < e; i++) {
4811cc52a00SJessica Paquette       R << NV((Twine("OtherStartLoc") + Twine(i)).str(),
4821cc52a00SJessica Paquette               CandidatesForRepeatedSeq[i].front()->getDebugLoc());
4831cc52a00SJessica Paquette       if (i != e - 1)
4841cc52a00SJessica Paquette         R << ", ";
4851cc52a00SJessica Paquette     }
4861cc52a00SJessica Paquette 
4871cc52a00SJessica Paquette     R << ")";
4881cc52a00SJessica Paquette     return R;
4891cc52a00SJessica Paquette   });
4901cc52a00SJessica Paquette }
4911cc52a00SJessica Paquette 
49258e706a6SJessica Paquette void MachineOutliner::emitOutlinedFunctionRemark(OutlinedFunction &OF) {
49358e706a6SJessica Paquette   MachineBasicBlock *MBB = &*OF.MF->begin();
49458e706a6SJessica Paquette   MachineOptimizationRemarkEmitter MORE(*OF.MF, nullptr);
49558e706a6SJessica Paquette   MachineOptimizationRemark R(DEBUG_TYPE, "OutlinedFunction",
49658e706a6SJessica Paquette                               MBB->findDebugLoc(MBB->begin()), MBB);
49758e706a6SJessica Paquette   R << "Saved " << NV("OutliningBenefit", OF.getBenefit()) << " bytes by "
49834b618bfSJessica Paquette     << "outlining " << NV("Length", OF.getNumInstrs()) << " instructions "
49958e706a6SJessica Paquette     << "from " << NV("NumOccurrences", OF.getOccurrenceCount())
50058e706a6SJessica Paquette     << " locations. "
50158e706a6SJessica Paquette     << "(Found at: ";
50258e706a6SJessica Paquette 
50358e706a6SJessica Paquette   // Tell the user the other places the candidate was found.
50458e706a6SJessica Paquette   for (size_t i = 0, e = OF.Candidates.size(); i < e; i++) {
50558e706a6SJessica Paquette 
50658e706a6SJessica Paquette     R << NV((Twine("StartLoc") + Twine(i)).str(),
507e18d6ff0SJessica Paquette             OF.Candidates[i].front()->getDebugLoc());
50858e706a6SJessica Paquette     if (i != e - 1)
50958e706a6SJessica Paquette       R << ", ";
51058e706a6SJessica Paquette   }
51158e706a6SJessica Paquette 
51258e706a6SJessica Paquette   R << ")";
51358e706a6SJessica Paquette 
51458e706a6SJessica Paquette   MORE.emit(R);
51558e706a6SJessica Paquette }
51658e706a6SJessica Paquette 
5176b7615aeSPuyan Lotfi void MachineOutliner::findCandidates(
5186b7615aeSPuyan Lotfi     InstructionMapper &Mapper, std::vector<OutlinedFunction> &FunctionList) {
51978681be2SJessica Paquette   FunctionList.clear();
520ce3a2dcfSJessica Paquette   SuffixTree ST(Mapper.UnsignedVec);
52178681be2SJessica Paquette 
522fbe7f5e9SDavid Tellenbach   // First, find all of the repeated substrings in the tree of minimum length
5234e54ef88SJessica Paquette   // 2.
524d87f5449SJessica Paquette   std::vector<Candidate> CandidatesForRepeatedSeq;
525d4e7d074SJessica Paquette   for (auto It = ST.begin(), Et = ST.end(); It != Et; ++It) {
526d4e7d074SJessica Paquette     CandidatesForRepeatedSeq.clear();
527d4e7d074SJessica Paquette     SuffixTree::RepeatedSubstring RS = *It;
5284e54ef88SJessica Paquette     unsigned StringLen = RS.Length;
5294e54ef88SJessica Paquette     for (const unsigned &StartIdx : RS.StartIndices) {
53052df8015SJessica Paquette       unsigned EndIdx = StartIdx + StringLen - 1;
53152df8015SJessica Paquette       // Trick: Discard some candidates that would be incompatible with the
53252df8015SJessica Paquette       // ones we've already found for this sequence. This will save us some
53352df8015SJessica Paquette       // work in candidate selection.
53452df8015SJessica Paquette       //
53552df8015SJessica Paquette       // If two candidates overlap, then we can't outline them both. This
53652df8015SJessica Paquette       // happens when we have candidates that look like, say
53752df8015SJessica Paquette       //
53852df8015SJessica Paquette       // AA (where each "A" is an instruction).
53952df8015SJessica Paquette       //
54052df8015SJessica Paquette       // We might have some portion of the module that looks like this:
54152df8015SJessica Paquette       // AAAAAA (6 A's)
54252df8015SJessica Paquette       //
54352df8015SJessica Paquette       // In this case, there are 5 different copies of "AA" in this range, but
54452df8015SJessica Paquette       // at most 3 can be outlined. If only outlining 3 of these is going to
54552df8015SJessica Paquette       // be unbeneficial, then we ought to not bother.
54652df8015SJessica Paquette       //
54752df8015SJessica Paquette       // Note that two things DON'T overlap when they look like this:
54852df8015SJessica Paquette       // start1...end1 .... start2...end2
54952df8015SJessica Paquette       // That is, one must either
55052df8015SJessica Paquette       // * End before the other starts
55152df8015SJessica Paquette       // * Start after the other ends
5524e54ef88SJessica Paquette       if (std::all_of(
5534e54ef88SJessica Paquette               CandidatesForRepeatedSeq.begin(), CandidatesForRepeatedSeq.end(),
55452df8015SJessica Paquette               [&StartIdx, &EndIdx](const Candidate &C) {
5554e54ef88SJessica Paquette                 return (EndIdx < C.getStartIdx() || StartIdx > C.getEndIdx());
55652df8015SJessica Paquette               })) {
55752df8015SJessica Paquette         // It doesn't overlap with anything, so we can outline it.
55852df8015SJessica Paquette         // Each sequence is over [StartIt, EndIt].
559aa087327SJessica Paquette         // Save the candidate and its location.
560aa087327SJessica Paquette 
56152df8015SJessica Paquette         MachineBasicBlock::iterator StartIt = Mapper.InstrList[StartIdx];
56252df8015SJessica Paquette         MachineBasicBlock::iterator EndIt = Mapper.InstrList[EndIdx];
563cad864d4SJessica Paquette         MachineBasicBlock *MBB = StartIt->getParent();
56452df8015SJessica Paquette 
565aa087327SJessica Paquette         CandidatesForRepeatedSeq.emplace_back(StartIdx, StringLen, StartIt,
566cad864d4SJessica Paquette                                               EndIt, MBB, FunctionList.size(),
567cad864d4SJessica Paquette                                               Mapper.MBBFlagsMap[MBB]);
56852df8015SJessica Paquette       }
569809d708bSJessica Paquette     }
570809d708bSJessica Paquette 
571acc15e12SJessica Paquette     // We've found something we might want to outline.
572acc15e12SJessica Paquette     // Create an OutlinedFunction to store it and check if it'd be beneficial
573acc15e12SJessica Paquette     // to outline.
574ddb039a1SJessica Paquette     if (CandidatesForRepeatedSeq.size() < 2)
575da08078fSEli Friedman       continue;
576da08078fSEli Friedman 
577da08078fSEli Friedman     // Arbitrarily choose a TII from the first candidate.
578da08078fSEli Friedman     // FIXME: Should getOutliningCandidateInfo move to TargetMachine?
579da08078fSEli Friedman     const TargetInstrInfo *TII =
580da08078fSEli Friedman         CandidatesForRepeatedSeq[0].getMF()->getSubtarget().getInstrInfo();
581da08078fSEli Friedman 
5829d93c602SJessica Paquette     OutlinedFunction OF =
583da08078fSEli Friedman         TII->getOutliningCandidateInfo(CandidatesForRepeatedSeq);
5849d93c602SJessica Paquette 
585b2d53c5dSJessica Paquette     // If we deleted too many candidates, then there's nothing worth outlining.
586b2d53c5dSJessica Paquette     // FIXME: This should take target-specified instruction sizes into account.
587b2d53c5dSJessica Paquette     if (OF.Candidates.size() < 2)
5889d93c602SJessica Paquette       continue;
5899d93c602SJessica Paquette 
590ffe4abc5SJessica Paquette     // Is it better to outline this candidate than not?
591f94d1d29SJessica Paquette     if (OF.getBenefit() < 1) {
5921cc52a00SJessica Paquette       emitNotOutliningCheaperRemark(StringLen, CandidatesForRepeatedSeq, OF);
59378681be2SJessica Paquette       continue;
594ffe4abc5SJessica Paquette     }
59578681be2SJessica Paquette 
596acc15e12SJessica Paquette     FunctionList.push_back(OF);
59778681be2SJessica Paquette   }
598596f483aSJessica Paquette }
599596f483aSJessica Paquette 
6006b7615aeSPuyan Lotfi MachineFunction *MachineOutliner::createOutlinedFunction(
6016b7615aeSPuyan Lotfi     Module &M, OutlinedFunction &OF, InstructionMapper &Mapper, unsigned Name) {
602596f483aSJessica Paquette 
603ae6c9403SFangrui Song   // Create the function name. This should be unique.
604a3eb0facSJessica Paquette   // FIXME: We should have a better naming scheme. This should be stable,
605a3eb0facSJessica Paquette   // regardless of changes to the outliner's cost model/traversal order.
6060c4aab27SPuyan Lotfi   std::string FunctionName = "OUTLINED_FUNCTION_";
6070d896278SJin Lin   if (OutlineRepeatedNum > 0)
6080c4aab27SPuyan Lotfi     FunctionName += std::to_string(OutlineRepeatedNum + 1) + "_";
6090c4aab27SPuyan Lotfi   FunctionName += std::to_string(Name);
610596f483aSJessica Paquette 
611596f483aSJessica Paquette   // Create the function using an IR-level function.
612596f483aSJessica Paquette   LLVMContext &C = M.getContext();
613ae6c9403SFangrui Song   Function *F = Function::Create(FunctionType::get(Type::getVoidTy(C), false),
614ae6c9403SFangrui Song                                  Function::ExternalLinkage, FunctionName, M);
615596f483aSJessica Paquette 
616596f483aSJessica Paquette   // NOTE: If this is linkonceodr, then we can take advantage of linker deduping
617596f483aSJessica Paquette   // which gives us better results when we outline from linkonceodr functions.
618d506bf8eSJessica Paquette   F->setLinkage(GlobalValue::InternalLinkage);
619596f483aSJessica Paquette   F->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
620596f483aSJessica Paquette 
62125bef201SEli Friedman   // Set optsize/minsize, so we don't insert padding between outlined
62225bef201SEli Friedman   // functions.
62325bef201SEli Friedman   F->addFnAttr(Attribute::OptimizeForSize);
62425bef201SEli Friedman   F->addFnAttr(Attribute::MinSize);
62525bef201SEli Friedman 
626e3932eeeSJessica Paquette   // Include target features from an arbitrary candidate for the outlined
627e3932eeeSJessica Paquette   // function. This makes sure the outlined function knows what kinds of
628e3932eeeSJessica Paquette   // instructions are going into it. This is fine, since all parent functions
629e3932eeeSJessica Paquette   // must necessarily support the instructions that are in the outlined region.
630e18d6ff0SJessica Paquette   Candidate &FirstCand = OF.Candidates.front();
63134b618bfSJessica Paquette   const Function &ParentFn = FirstCand.getMF()->getFunction();
632e3932eeeSJessica Paquette   if (ParentFn.hasFnAttribute("target-features"))
633e3932eeeSJessica Paquette     F->addFnAttr(ParentFn.getFnAttribute("target-features"));
634e3932eeeSJessica Paquette 
635*ca4c1ad8SDavid Green   // Set nounwind, so we don't generate eh_frame.
636*ca4c1ad8SDavid Green   if (llvm::all_of(OF.Candidates, [](const outliner::Candidate &C) {
637*ca4c1ad8SDavid Green         return C.getMF()->getFunction().hasFnAttribute(Attribute::NoUnwind);
638*ca4c1ad8SDavid Green       }))
639*ca4c1ad8SDavid Green     F->addFnAttr(Attribute::NoUnwind);
640*ca4c1ad8SDavid Green 
641596f483aSJessica Paquette   BasicBlock *EntryBB = BasicBlock::Create(C, "entry", F);
642596f483aSJessica Paquette   IRBuilder<> Builder(EntryBB);
643596f483aSJessica Paquette   Builder.CreateRetVoid();
644596f483aSJessica Paquette 
645cc382cf7SYuanfang Chen   MachineModuleInfo &MMI = getAnalysis<MachineModuleInfoWrapperPass>().getMMI();
6467bda1958SMatthias Braun   MachineFunction &MF = MMI.getOrCreateMachineFunction(*F);
647596f483aSJessica Paquette   MachineBasicBlock &MBB = *MF.CreateMachineBasicBlock();
648596f483aSJessica Paquette   const TargetSubtargetInfo &STI = MF.getSubtarget();
649596f483aSJessica Paquette   const TargetInstrInfo &TII = *STI.getInstrInfo();
650596f483aSJessica Paquette 
651596f483aSJessica Paquette   // Insert the new function into the module.
652596f483aSJessica Paquette   MF.insert(MF.begin(), &MBB);
653596f483aSJessica Paquette 
6548d5024f7SAndrew Litteken   MachineFunction *OriginalMF = FirstCand.front()->getMF();
6558d5024f7SAndrew Litteken   const std::vector<MCCFIInstruction> &Instrs =
6568d5024f7SAndrew Litteken       OriginalMF->getFrameInstructions();
65734b618bfSJessica Paquette   for (auto I = FirstCand.front(), E = std::next(FirstCand.back()); I != E;
65834b618bfSJessica Paquette        ++I) {
65934b618bfSJessica Paquette     MachineInstr *NewMI = MF.CloneMachineInstr(&*I);
6608d5024f7SAndrew Litteken     if (I->isCFIInstruction()) {
6618d5024f7SAndrew Litteken       unsigned CFIIndex = NewMI->getOperand(0).getCFIIndex();
6628d5024f7SAndrew Litteken       MCCFIInstruction CFI = Instrs[CFIIndex];
6638d5024f7SAndrew Litteken       (void)MF.addFrameInst(CFI);
6648d5024f7SAndrew Litteken     }
665c73c0307SChandler Carruth     NewMI->dropMemRefs(MF);
666596f483aSJessica Paquette 
667596f483aSJessica Paquette     // Don't keep debug information for outlined instructions.
668596f483aSJessica Paquette     NewMI->setDebugLoc(DebugLoc());
669596f483aSJessica Paquette     MBB.insert(MBB.end(), NewMI);
670596f483aSJessica Paquette   }
671596f483aSJessica Paquette 
6721a78b0bdSEli Friedman   // Set normal properties for a late MachineFunction.
6731a78b0bdSEli Friedman   MF.getProperties().reset(MachineFunctionProperties::Property::IsSSA);
6741a78b0bdSEli Friedman   MF.getProperties().set(MachineFunctionProperties::Property::NoPHIs);
6751a78b0bdSEli Friedman   MF.getProperties().set(MachineFunctionProperties::Property::NoVRegs);
6761a78b0bdSEli Friedman   MF.getProperties().set(MachineFunctionProperties::Property::TracksLiveness);
677cc06a782SJessica Paquette   MF.getRegInfo().freezeReservedRegs(MF);
678cc06a782SJessica Paquette 
6791a78b0bdSEli Friedman   // Compute live-in set for outlined fn
6801a78b0bdSEli Friedman   const MachineRegisterInfo &MRI = MF.getRegInfo();
6811a78b0bdSEli Friedman   const TargetRegisterInfo &TRI = *MRI.getTargetRegisterInfo();
6821a78b0bdSEli Friedman   LivePhysRegs LiveIns(TRI);
6831a78b0bdSEli Friedman   for (auto &Cand : OF.Candidates) {
6841a78b0bdSEli Friedman     // Figure out live-ins at the first instruction.
6851a78b0bdSEli Friedman     MachineBasicBlock &OutlineBB = *Cand.front()->getParent();
6861a78b0bdSEli Friedman     LivePhysRegs CandLiveIns(TRI);
6871a78b0bdSEli Friedman     CandLiveIns.addLiveOuts(OutlineBB);
6881a78b0bdSEli Friedman     for (const MachineInstr &MI :
6891a78b0bdSEli Friedman          reverse(make_range(Cand.front(), OutlineBB.end())))
6901a78b0bdSEli Friedman       CandLiveIns.stepBackward(MI);
6911a78b0bdSEli Friedman 
6921a78b0bdSEli Friedman     // The live-in set for the outlined function is the union of the live-ins
6931a78b0bdSEli Friedman     // from all the outlining points.
6941a78b0bdSEli Friedman     for (MCPhysReg Reg : make_range(CandLiveIns.begin(), CandLiveIns.end()))
6951a78b0bdSEli Friedman       LiveIns.addReg(Reg);
6961a78b0bdSEli Friedman   }
6971a78b0bdSEli Friedman   addLiveIns(MBB, LiveIns);
6981a78b0bdSEli Friedman 
6991a78b0bdSEli Friedman   TII.buildOutlinedFrame(MBB, MF, OF);
7001a78b0bdSEli Friedman 
701a499c3c2SJessica Paquette   // If there's a DISubprogram associated with this outlined function, then
702a499c3c2SJessica Paquette   // emit debug info for the outlined function.
703aa087327SJessica Paquette   if (DISubprogram *SP = getSubprogramOrNull(OF)) {
704a499c3c2SJessica Paquette     // We have a DISubprogram. Get its DICompileUnit.
705a499c3c2SJessica Paquette     DICompileUnit *CU = SP->getUnit();
706a499c3c2SJessica Paquette     DIBuilder DB(M, true, CU);
707a499c3c2SJessica Paquette     DIFile *Unit = SP->getFile();
708a499c3c2SJessica Paquette     Mangler Mg;
709a499c3c2SJessica Paquette     // Get the mangled name of the function for the linkage name.
710a499c3c2SJessica Paquette     std::string Dummy;
711a499c3c2SJessica Paquette     llvm::raw_string_ostream MangledNameStream(Dummy);
712a499c3c2SJessica Paquette     Mg.getNameWithPrefix(MangledNameStream, F, false);
713a499c3c2SJessica Paquette 
714cc06a782SJessica Paquette     DISubprogram *OutlinedSP = DB.createFunction(
715a499c3c2SJessica Paquette         Unit /* Context */, F->getName(), StringRef(MangledNameStream.str()),
716a499c3c2SJessica Paquette         Unit /* File */,
717a499c3c2SJessica Paquette         0 /* Line 0 is reserved for compiler-generated code. */,
718cc06a782SJessica Paquette         DB.createSubroutineType(DB.getOrCreateTypeArray(None)), /* void type */
719cda54210SPaul Robinson         0, /* Line 0 is reserved for compiler-generated code. */
720a499c3c2SJessica Paquette         DINode::DIFlags::FlagArtificial /* Compiler-generated code. */,
721cda54210SPaul Robinson         /* Outlined code is optimized code by definition. */
722cda54210SPaul Robinson         DISubprogram::SPFlagDefinition | DISubprogram::SPFlagOptimized);
723a499c3c2SJessica Paquette 
724a499c3c2SJessica Paquette     // Don't add any new variables to the subprogram.
725cc06a782SJessica Paquette     DB.finalizeSubprogram(OutlinedSP);
726a499c3c2SJessica Paquette 
727a499c3c2SJessica Paquette     // Attach subprogram to the function.
728cc06a782SJessica Paquette     F->setSubprogram(OutlinedSP);
729a499c3c2SJessica Paquette     // We're done with the DIBuilder.
730a499c3c2SJessica Paquette     DB.finalize();
731a499c3c2SJessica Paquette   }
732a499c3c2SJessica Paquette 
733596f483aSJessica Paquette   return &MF;
734596f483aSJessica Paquette }
735596f483aSJessica Paquette 
7364ae3b71dSJessica Paquette bool MachineOutliner::outline(Module &M,
7374ae3b71dSJessica Paquette                               std::vector<OutlinedFunction> &FunctionList,
738a51fc8ddSPuyan Lotfi                               InstructionMapper &Mapper,
739a51fc8ddSPuyan Lotfi                               unsigned &OutlinedFunctionNum) {
740596f483aSJessica Paquette 
741596f483aSJessica Paquette   bool OutlinedSomething = false;
742a3eb0facSJessica Paquette 
743962b3ae6SJessica Paquette   // Sort by benefit. The most beneficial functions should be outlined first.
744efd94c56SFangrui Song   llvm::stable_sort(FunctionList, [](const OutlinedFunction &LHS,
745efd94c56SFangrui Song                                      const OutlinedFunction &RHS) {
746962b3ae6SJessica Paquette     return LHS.getBenefit() > RHS.getBenefit();
747962b3ae6SJessica Paquette   });
748596f483aSJessica Paquette 
749962b3ae6SJessica Paquette   // Walk over each function, outlining them as we go along. Functions are
750962b3ae6SJessica Paquette   // outlined greedily, based off the sort above.
751962b3ae6SJessica Paquette   for (OutlinedFunction &OF : FunctionList) {
752962b3ae6SJessica Paquette     // If we outlined something that overlapped with a candidate in a previous
753962b3ae6SJessica Paquette     // step, then we can't outline from it.
754e18d6ff0SJessica Paquette     erase_if(OF.Candidates, [&Mapper](Candidate &C) {
755d9d9309bSJessica Paquette       return std::any_of(
756e18d6ff0SJessica Paquette           Mapper.UnsignedVec.begin() + C.getStartIdx(),
757e18d6ff0SJessica Paquette           Mapper.UnsignedVec.begin() + C.getEndIdx() + 1,
758d9d9309bSJessica Paquette           [](unsigned I) { return (I == static_cast<unsigned>(-1)); });
759235d877eSJessica Paquette     });
760596f483aSJessica Paquette 
761962b3ae6SJessica Paquette     // If we made it unbeneficial to outline this function, skip it.
76285af63d0SJessica Paquette     if (OF.getBenefit() < 1)
763596f483aSJessica Paquette       continue;
764596f483aSJessica Paquette 
765962b3ae6SJessica Paquette     // It's beneficial. Create the function and outline its sequence's
766962b3ae6SJessica Paquette     // occurrences.
767a3eb0facSJessica Paquette     OF.MF = createOutlinedFunction(M, OF, Mapper, OutlinedFunctionNum);
76858e706a6SJessica Paquette     emitOutlinedFunctionRemark(OF);
769acffa28cSJessica Paquette     FunctionsCreated++;
770a3eb0facSJessica Paquette     OutlinedFunctionNum++; // Created a function, move to the next name.
771596f483aSJessica Paquette     MachineFunction *MF = OF.MF;
772596f483aSJessica Paquette     const TargetSubtargetInfo &STI = MF->getSubtarget();
773596f483aSJessica Paquette     const TargetInstrInfo &TII = *STI.getInstrInfo();
774596f483aSJessica Paquette 
775962b3ae6SJessica Paquette     // Replace occurrences of the sequence with calls to the new function.
776e18d6ff0SJessica Paquette     for (Candidate &C : OF.Candidates) {
777962b3ae6SJessica Paquette       MachineBasicBlock &MBB = *C.getMBB();
778962b3ae6SJessica Paquette       MachineBasicBlock::iterator StartIt = C.front();
779962b3ae6SJessica Paquette       MachineBasicBlock::iterator EndIt = C.back();
780596f483aSJessica Paquette 
781962b3ae6SJessica Paquette       // Insert the call.
782962b3ae6SJessica Paquette       auto CallInst = TII.insertOutlinedCall(M, MBB, StartIt, *MF, C);
783962b3ae6SJessica Paquette 
784962b3ae6SJessica Paquette       // If the caller tracks liveness, then we need to make sure that
785962b3ae6SJessica Paquette       // anything we outline doesn't break liveness assumptions. The outlined
786962b3ae6SJessica Paquette       // functions themselves currently don't track liveness, but we should
787962b3ae6SJessica Paquette       // make sure that the ranges we yank things out of aren't wrong.
788aa087327SJessica Paquette       if (MBB.getParent()->getProperties().hasProperty(
7890b672491SJessica Paquette               MachineFunctionProperties::Property::TracksLiveness)) {
790fc6fda90SJin Lin         // The following code is to add implicit def operands to the call
79171d3869fSDjordje Todorovic         // instruction. It also updates call site information for moved
79271d3869fSDjordje Todorovic         // code.
793fc6fda90SJin Lin         SmallSet<Register, 2> UseRegs, DefRegs;
7940b672491SJessica Paquette         // Copy over the defs in the outlined range.
7950b672491SJessica Paquette         // First inst in outlined range <-- Anything that's defined in this
796962b3ae6SJessica Paquette         // ...                           .. range has to be added as an
797962b3ae6SJessica Paquette         // implicit Last inst in outlined range  <-- def to the call
79871d3869fSDjordje Todorovic         // instruction. Also remove call site information for outlined block
799fc6fda90SJin Lin         // of code. The exposed uses need to be copied in the outlined range.
800ffd5e121SPuyan Lotfi         for (MachineBasicBlock::reverse_iterator
801ffd5e121SPuyan Lotfi                  Iter = EndIt.getReverse(),
802fc6fda90SJin Lin                  Last = std::next(CallInst.getReverse());
803fc6fda90SJin Lin              Iter != Last; Iter++) {
804fc6fda90SJin Lin           MachineInstr *MI = &*Iter;
805fc6fda90SJin Lin           for (MachineOperand &MOP : MI->operands()) {
806fc6fda90SJin Lin             // Skip over anything that isn't a register.
807fc6fda90SJin Lin             if (!MOP.isReg())
808fc6fda90SJin Lin               continue;
809fc6fda90SJin Lin 
810fc6fda90SJin Lin             if (MOP.isDef()) {
811fc6fda90SJin Lin               // Introduce DefRegs set to skip the redundant register.
812fc6fda90SJin Lin               DefRegs.insert(MOP.getReg());
813fc6fda90SJin Lin               if (UseRegs.count(MOP.getReg()))
814fc6fda90SJin Lin                 // Since the regiester is modeled as defined,
815fc6fda90SJin Lin                 // it is not necessary to be put in use register set.
816fc6fda90SJin Lin                 UseRegs.erase(MOP.getReg());
817fc6fda90SJin Lin             } else if (!MOP.isUndef()) {
818fc6fda90SJin Lin               // Any register which is not undefined should
819fc6fda90SJin Lin               // be put in the use register set.
820fc6fda90SJin Lin               UseRegs.insert(MOP.getReg());
821fc6fda90SJin Lin             }
822fc6fda90SJin Lin           }
823fc6fda90SJin Lin           if (MI->isCandidateForCallSiteEntry())
824fc6fda90SJin Lin             MI->getMF()->eraseCallSiteInfo(MI);
825fc6fda90SJin Lin         }
826fc6fda90SJin Lin 
827fc6fda90SJin Lin         for (const Register &I : DefRegs)
828fc6fda90SJin Lin           // If it's a def, add it to the call instruction.
829ffd5e121SPuyan Lotfi           CallInst->addOperand(
830ffd5e121SPuyan Lotfi               MachineOperand::CreateReg(I, true, /* isDef = true */
831fc6fda90SJin Lin                                         true /* isImp = true */));
832fc6fda90SJin Lin 
833fc6fda90SJin Lin         for (const Register &I : UseRegs)
834fc6fda90SJin Lin           // If it's a exposed use, add it to the call instruction.
835fc6fda90SJin Lin           CallInst->addOperand(
836fc6fda90SJin Lin               MachineOperand::CreateReg(I, false, /* isDef = false */
837fc6fda90SJin Lin                                         true /* isImp = true */));
8380b672491SJessica Paquette       }
8390b672491SJessica Paquette 
840aa087327SJessica Paquette       // Erase from the point after where the call was inserted up to, and
841aa087327SJessica Paquette       // including, the final instruction in the sequence.
842aa087327SJessica Paquette       // Erase needs one past the end, so we need std::next there too.
843aa087327SJessica Paquette       MBB.erase(std::next(StartIt), std::next(EndIt));
844235d877eSJessica Paquette 
845d9d9309bSJessica Paquette       // Keep track of what we removed by marking them all as -1.
846235d877eSJessica Paquette       std::for_each(Mapper.UnsignedVec.begin() + C.getStartIdx(),
847235d877eSJessica Paquette                     Mapper.UnsignedVec.begin() + C.getEndIdx() + 1,
848d9d9309bSJessica Paquette                     [](unsigned &I) { I = static_cast<unsigned>(-1); });
849596f483aSJessica Paquette       OutlinedSomething = true;
850596f483aSJessica Paquette 
851596f483aSJessica Paquette       // Statistics.
852596f483aSJessica Paquette       NumOutlined++;
853596f483aSJessica Paquette     }
854962b3ae6SJessica Paquette   }
855596f483aSJessica Paquette 
856d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "OutlinedSomething = " << OutlinedSomething << "\n";);
857596f483aSJessica Paquette   return OutlinedSomething;
858596f483aSJessica Paquette }
859596f483aSJessica Paquette 
860050d1ac4SJessica Paquette void MachineOutliner::populateMapper(InstructionMapper &Mapper, Module &M,
861050d1ac4SJessica Paquette                                      MachineModuleInfo &MMI) {
862df82274fSJessica Paquette   // Build instruction mappings for each function in the module. Start by
863df82274fSJessica Paquette   // iterating over each Function in M.
864596f483aSJessica Paquette   for (Function &F : M) {
865596f483aSJessica Paquette 
866df82274fSJessica Paquette     // If there's nothing in F, then there's no reason to try and outline from
867df82274fSJessica Paquette     // it.
868df82274fSJessica Paquette     if (F.empty())
869596f483aSJessica Paquette       continue;
870596f483aSJessica Paquette 
871df82274fSJessica Paquette     // There's something in F. Check if it has a MachineFunction associated with
872df82274fSJessica Paquette     // it.
873df82274fSJessica Paquette     MachineFunction *MF = MMI.getMachineFunction(F);
874596f483aSJessica Paquette 
875df82274fSJessica Paquette     // If it doesn't, then there's nothing to outline from. Move to the next
876df82274fSJessica Paquette     // Function.
877df82274fSJessica Paquette     if (!MF)
878596f483aSJessica Paquette       continue;
879596f483aSJessica Paquette 
880da08078fSEli Friedman     const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
881da08078fSEli Friedman 
8828bda1881SJessica Paquette     if (!RunOnAllFunctions && !TII->shouldOutlineFromFunctionByDefault(*MF))
8838bda1881SJessica Paquette       continue;
8848bda1881SJessica Paquette 
885df82274fSJessica Paquette     // We have a MachineFunction. Ask the target if it's suitable for outlining.
886df82274fSJessica Paquette     // If it isn't, then move on to the next Function in the module.
887df82274fSJessica Paquette     if (!TII->isFunctionSafeToOutlineFrom(*MF, OutlineFromLinkOnceODRs))
888df82274fSJessica Paquette       continue;
889df82274fSJessica Paquette 
890df82274fSJessica Paquette     // We have a function suitable for outlining. Iterate over every
891df82274fSJessica Paquette     // MachineBasicBlock in MF and try to map its instructions to a list of
892df82274fSJessica Paquette     // unsigned integers.
893df82274fSJessica Paquette     for (MachineBasicBlock &MBB : *MF) {
894df82274fSJessica Paquette       // If there isn't anything in MBB, then there's no point in outlining from
895df82274fSJessica Paquette       // it.
896b320ca26SJessica Paquette       // If there are fewer than 2 instructions in the MBB, then it can't ever
897b320ca26SJessica Paquette       // contain something worth outlining.
898b320ca26SJessica Paquette       // FIXME: This should be based off of the maximum size in B of an outlined
899b320ca26SJessica Paquette       // call versus the size in B of the MBB.
900b320ca26SJessica Paquette       if (MBB.empty() || MBB.size() < 2)
901df82274fSJessica Paquette         continue;
902df82274fSJessica Paquette 
903df82274fSJessica Paquette       // Check if MBB could be the target of an indirect branch. If it is, then
904df82274fSJessica Paquette       // we don't want to outline from it.
905df82274fSJessica Paquette       if (MBB.hasAddressTaken())
906df82274fSJessica Paquette         continue;
907df82274fSJessica Paquette 
908df82274fSJessica Paquette       // MBB is suitable for outlining. Map it to a list of unsigneds.
909da08078fSEli Friedman       Mapper.convertToUnsignedVec(MBB, *TII);
910596f483aSJessica Paquette     }
911596f483aSJessica Paquette   }
912050d1ac4SJessica Paquette }
913050d1ac4SJessica Paquette 
9142386eab3SJessica Paquette void MachineOutliner::initSizeRemarkInfo(
9152386eab3SJessica Paquette     const Module &M, const MachineModuleInfo &MMI,
9162386eab3SJessica Paquette     StringMap<unsigned> &FunctionToInstrCount) {
9172386eab3SJessica Paquette   // Collect instruction counts for every function. We'll use this to emit
9182386eab3SJessica Paquette   // per-function size remarks later.
9192386eab3SJessica Paquette   for (const Function &F : M) {
9202386eab3SJessica Paquette     MachineFunction *MF = MMI.getMachineFunction(F);
9212386eab3SJessica Paquette 
9222386eab3SJessica Paquette     // We only care about MI counts here. If there's no MachineFunction at this
9232386eab3SJessica Paquette     // point, then there won't be after the outliner runs, so let's move on.
9242386eab3SJessica Paquette     if (!MF)
9252386eab3SJessica Paquette       continue;
9262386eab3SJessica Paquette     FunctionToInstrCount[F.getName().str()] = MF->getInstructionCount();
9272386eab3SJessica Paquette   }
9282386eab3SJessica Paquette }
9292386eab3SJessica Paquette 
9302386eab3SJessica Paquette void MachineOutliner::emitInstrCountChangedRemark(
9312386eab3SJessica Paquette     const Module &M, const MachineModuleInfo &MMI,
9322386eab3SJessica Paquette     const StringMap<unsigned> &FunctionToInstrCount) {
9332386eab3SJessica Paquette   // Iterate over each function in the module and emit remarks.
9342386eab3SJessica Paquette   // Note that we won't miss anything by doing this, because the outliner never
9352386eab3SJessica Paquette   // deletes functions.
9362386eab3SJessica Paquette   for (const Function &F : M) {
9372386eab3SJessica Paquette     MachineFunction *MF = MMI.getMachineFunction(F);
9382386eab3SJessica Paquette 
9392386eab3SJessica Paquette     // The outliner never deletes functions. If we don't have a MF here, then we
9402386eab3SJessica Paquette     // didn't have one prior to outlining either.
9412386eab3SJessica Paquette     if (!MF)
9422386eab3SJessica Paquette       continue;
9432386eab3SJessica Paquette 
944adcd0268SBenjamin Kramer     std::string Fname = std::string(F.getName());
9452386eab3SJessica Paquette     unsigned FnCountAfter = MF->getInstructionCount();
9462386eab3SJessica Paquette     unsigned FnCountBefore = 0;
9472386eab3SJessica Paquette 
9482386eab3SJessica Paquette     // Check if the function was recorded before.
9492386eab3SJessica Paquette     auto It = FunctionToInstrCount.find(Fname);
9502386eab3SJessica Paquette 
9512386eab3SJessica Paquette     // Did we have a previously-recorded size? If yes, then set FnCountBefore
9522386eab3SJessica Paquette     // to that.
9532386eab3SJessica Paquette     if (It != FunctionToInstrCount.end())
9542386eab3SJessica Paquette       FnCountBefore = It->second;
9552386eab3SJessica Paquette 
9562386eab3SJessica Paquette     // Compute the delta and emit a remark if there was a change.
9572386eab3SJessica Paquette     int64_t FnDelta = static_cast<int64_t>(FnCountAfter) -
9582386eab3SJessica Paquette                       static_cast<int64_t>(FnCountBefore);
9592386eab3SJessica Paquette     if (FnDelta == 0)
9602386eab3SJessica Paquette       continue;
9612386eab3SJessica Paquette 
9622386eab3SJessica Paquette     MachineOptimizationRemarkEmitter MORE(*MF, nullptr);
9632386eab3SJessica Paquette     MORE.emit([&]() {
9642386eab3SJessica Paquette       MachineOptimizationRemarkAnalysis R("size-info", "FunctionMISizeChange",
9656b7615aeSPuyan Lotfi                                           DiagnosticLocation(), &MF->front());
9662386eab3SJessica Paquette       R << DiagnosticInfoOptimizationBase::Argument("Pass", "Machine Outliner")
9672386eab3SJessica Paquette         << ": Function: "
9682386eab3SJessica Paquette         << DiagnosticInfoOptimizationBase::Argument("Function", F.getName())
9692386eab3SJessica Paquette         << ": MI instruction count changed from "
9702386eab3SJessica Paquette         << DiagnosticInfoOptimizationBase::Argument("MIInstrsBefore",
9712386eab3SJessica Paquette                                                     FnCountBefore)
9722386eab3SJessica Paquette         << " to "
9732386eab3SJessica Paquette         << DiagnosticInfoOptimizationBase::Argument("MIInstrsAfter",
9742386eab3SJessica Paquette                                                     FnCountAfter)
9752386eab3SJessica Paquette         << "; Delta: "
9762386eab3SJessica Paquette         << DiagnosticInfoOptimizationBase::Argument("Delta", FnDelta);
9772386eab3SJessica Paquette       return R;
9782386eab3SJessica Paquette     });
9792386eab3SJessica Paquette   }
9802386eab3SJessica Paquette }
9812386eab3SJessica Paquette 
982ffd5e121SPuyan Lotfi bool MachineOutliner::runOnModule(Module &M) {
983050d1ac4SJessica Paquette   // Check if there's anything in the module. If it's empty, then there's
984050d1ac4SJessica Paquette   // nothing to outline.
985050d1ac4SJessica Paquette   if (M.empty())
986050d1ac4SJessica Paquette     return false;
987050d1ac4SJessica Paquette 
988a51fc8ddSPuyan Lotfi   // Number to append to the current outlined function.
989a51fc8ddSPuyan Lotfi   unsigned OutlinedFunctionNum = 0;
990a51fc8ddSPuyan Lotfi 
991ffd5e121SPuyan Lotfi   OutlineRepeatedNum = 0;
992a51fc8ddSPuyan Lotfi   if (!doOutline(M, OutlinedFunctionNum))
993a51fc8ddSPuyan Lotfi     return false;
994ffd5e121SPuyan Lotfi 
995ffd5e121SPuyan Lotfi   for (unsigned I = 0; I < OutlinerReruns; ++I) {
996ffd5e121SPuyan Lotfi     OutlinedFunctionNum = 0;
997ffd5e121SPuyan Lotfi     OutlineRepeatedNum++;
998ffd5e121SPuyan Lotfi     if (!doOutline(M, OutlinedFunctionNum)) {
999ffd5e121SPuyan Lotfi       LLVM_DEBUG({
1000ffd5e121SPuyan Lotfi         dbgs() << "Did not outline on iteration " << I + 2 << " out of "
1001ffd5e121SPuyan Lotfi                << OutlinerReruns + 1 << "\n";
1002ffd5e121SPuyan Lotfi       });
1003ffd5e121SPuyan Lotfi       break;
1004ffd5e121SPuyan Lotfi     }
1005ffd5e121SPuyan Lotfi   }
1006ffd5e121SPuyan Lotfi 
1007a51fc8ddSPuyan Lotfi   return true;
1008a51fc8ddSPuyan Lotfi }
1009a51fc8ddSPuyan Lotfi 
1010a51fc8ddSPuyan Lotfi bool MachineOutliner::doOutline(Module &M, unsigned &OutlinedFunctionNum) {
1011cc382cf7SYuanfang Chen   MachineModuleInfo &MMI = getAnalysis<MachineModuleInfoWrapperPass>().getMMI();
1012050d1ac4SJessica Paquette 
1013050d1ac4SJessica Paquette   // If the user passed -enable-machine-outliner=always or
1014050d1ac4SJessica Paquette   // -enable-machine-outliner, the pass will run on all functions in the module.
1015050d1ac4SJessica Paquette   // Otherwise, if the target supports default outlining, it will run on all
1016050d1ac4SJessica Paquette   // functions deemed by the target to be worth outlining from by default. Tell
1017050d1ac4SJessica Paquette   // the user how the outliner is running.
10186b7615aeSPuyan Lotfi   LLVM_DEBUG({
1019050d1ac4SJessica Paquette     dbgs() << "Machine Outliner: Running on ";
1020050d1ac4SJessica Paquette     if (RunOnAllFunctions)
1021050d1ac4SJessica Paquette       dbgs() << "all functions";
1022050d1ac4SJessica Paquette     else
1023050d1ac4SJessica Paquette       dbgs() << "target-default functions";
10246b7615aeSPuyan Lotfi     dbgs() << "\n";
10256b7615aeSPuyan Lotfi   });
1026050d1ac4SJessica Paquette 
1027050d1ac4SJessica Paquette   // If the user specifies that they want to outline from linkonceodrs, set
1028050d1ac4SJessica Paquette   // it here.
1029050d1ac4SJessica Paquette   OutlineFromLinkOnceODRs = EnableLinkOnceODROutlining;
1030050d1ac4SJessica Paquette   InstructionMapper Mapper;
1031050d1ac4SJessica Paquette 
1032050d1ac4SJessica Paquette   // Prepare instruction mappings for the suffix tree.
1033050d1ac4SJessica Paquette   populateMapper(Mapper, M, MMI);
1034596f483aSJessica Paquette   std::vector<OutlinedFunction> FunctionList;
1035596f483aSJessica Paquette 
1036acffa28cSJessica Paquette   // Find all of the outlining candidates.
1037ce3a2dcfSJessica Paquette   findCandidates(Mapper, FunctionList);
1038596f483aSJessica Paquette 
10392386eab3SJessica Paquette   // If we've requested size remarks, then collect the MI counts of every
10402386eab3SJessica Paquette   // function before outlining, and the MI counts after outlining.
10412386eab3SJessica Paquette   // FIXME: This shouldn't be in the outliner at all; it should ultimately be
10422386eab3SJessica Paquette   // the pass manager's responsibility.
10432386eab3SJessica Paquette   // This could pretty easily be placed in outline instead, but because we
10442386eab3SJessica Paquette   // really ultimately *don't* want this here, it's done like this for now
10452386eab3SJessica Paquette   // instead.
10462386eab3SJessica Paquette 
10472386eab3SJessica Paquette   // Check if we want size remarks.
10482386eab3SJessica Paquette   bool ShouldEmitSizeRemarks = M.shouldEmitInstrCountChangedRemark();
10492386eab3SJessica Paquette   StringMap<unsigned> FunctionToInstrCount;
10502386eab3SJessica Paquette   if (ShouldEmitSizeRemarks)
10512386eab3SJessica Paquette     initSizeRemarkInfo(M, MMI, FunctionToInstrCount);
10522386eab3SJessica Paquette 
1053acffa28cSJessica Paquette   // Outline each of the candidates and return true if something was outlined.
1054a51fc8ddSPuyan Lotfi   bool OutlinedSomething =
1055a51fc8ddSPuyan Lotfi       outline(M, FunctionList, Mapper, OutlinedFunctionNum);
1056729e6869SJessica Paquette 
10572386eab3SJessica Paquette   // If we outlined something, we definitely changed the MI count of the
10582386eab3SJessica Paquette   // module. If we've asked for size remarks, then output them.
10592386eab3SJessica Paquette   // FIXME: This should be in the pass manager.
10602386eab3SJessica Paquette   if (ShouldEmitSizeRemarks && OutlinedSomething)
10612386eab3SJessica Paquette     emitInstrCountChangedRemark(M, MMI, FunctionToInstrCount);
10622386eab3SJessica Paquette 
1063ffd5e121SPuyan Lotfi   LLVM_DEBUG({
1064ffd5e121SPuyan Lotfi     if (!OutlinedSomething)
1065ffd5e121SPuyan Lotfi       dbgs() << "Stopped outlining at iteration " << OutlineRepeatedNum
1066ffd5e121SPuyan Lotfi              << " because no changes were found.\n";
1067ffd5e121SPuyan Lotfi   });
1068ffd5e121SPuyan Lotfi 
1069729e6869SJessica Paquette   return OutlinedSomething;
1070596f483aSJessica Paquette }
1071