xref: /src/contrib/llvm-project/llvm/lib/CodeGen/MachineOutliner.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
171d5a254SDimitry Andric //===---- MachineOutliner.cpp - Outline instructions -----------*- C++ -*-===//
271d5a254SDimitry Andric //
3e6d15924SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e6d15924SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5e6d15924SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
671d5a254SDimitry Andric //
771d5a254SDimitry Andric //===----------------------------------------------------------------------===//
871d5a254SDimitry Andric ///
971d5a254SDimitry Andric /// \file
1071d5a254SDimitry Andric /// Replaces repeated sequences of instructions with function calls.
1171d5a254SDimitry Andric ///
1271d5a254SDimitry Andric /// This works by placing every instruction from every basic block in a
1371d5a254SDimitry Andric /// suffix tree, and repeatedly querying that tree for repeated sequences of
1471d5a254SDimitry Andric /// instructions. If a sequence of instructions appears often, then it ought
1571d5a254SDimitry Andric /// to be beneficial to pull out into a function.
1671d5a254SDimitry Andric ///
17044eb2f6SDimitry Andric /// The MachineOutliner communicates with a given target using hooks defined in
18044eb2f6SDimitry Andric /// TargetInstrInfo.h. The target supplies the outliner with information on how
19044eb2f6SDimitry Andric /// a specific sequence of instructions should be outlined. This information
20044eb2f6SDimitry Andric /// is used to deduce the number of instructions necessary to
21044eb2f6SDimitry Andric ///
22044eb2f6SDimitry Andric /// * Create an outlined function
23044eb2f6SDimitry Andric /// * Call that outlined function
24044eb2f6SDimitry Andric ///
25044eb2f6SDimitry Andric /// Targets must implement
26044eb2f6SDimitry Andric ///   * getOutliningCandidateInfo
27eb11fae6SDimitry Andric ///   * buildOutlinedFrame
28044eb2f6SDimitry Andric ///   * insertOutlinedCall
29044eb2f6SDimitry Andric ///   * isFunctionSafeToOutlineFrom
30044eb2f6SDimitry Andric ///
31044eb2f6SDimitry Andric /// in order to make use of the MachineOutliner.
32044eb2f6SDimitry Andric ///
3371d5a254SDimitry Andric /// This was originally presented at the 2016 LLVM Developers' Meeting in the
3471d5a254SDimitry Andric /// talk "Reducing Code Size Using Outlining". For a high-level overview of
3571d5a254SDimitry Andric /// how this pass works, the talk is available on YouTube at
3671d5a254SDimitry Andric ///
3771d5a254SDimitry Andric /// https://www.youtube.com/watch?v=yorld-WSOeU
3871d5a254SDimitry Andric ///
3971d5a254SDimitry Andric /// The slides for the talk are available at
4071d5a254SDimitry Andric ///
4171d5a254SDimitry Andric /// http://www.llvm.org/devmtg/2016-11/Slides/Paquette-Outliner.pdf
4271d5a254SDimitry Andric ///
4371d5a254SDimitry Andric /// The talk provides an overview of how the outliner finds candidates and
4471d5a254SDimitry Andric /// ultimately outlines them. It describes how the main data structure for this
4571d5a254SDimitry Andric /// pass, the suffix tree, is queried and purged for candidates. It also gives
4671d5a254SDimitry Andric /// a simplified suffix tree construction algorithm for suffix trees based off
4771d5a254SDimitry Andric /// of the algorithm actually used here, Ukkonen's algorithm.
4871d5a254SDimitry Andric ///
4971d5a254SDimitry Andric /// For the original RFC for this pass, please see
5071d5a254SDimitry Andric ///
5171d5a254SDimitry Andric /// http://lists.llvm.org/pipermail/llvm-dev/2016-August/104170.html
5271d5a254SDimitry Andric ///
5371d5a254SDimitry Andric /// For more information on the suffix tree data structure, please see
5471d5a254SDimitry Andric /// https://www.cs.helsinki.fi/u/ukkonen/SuffixT1withFigs.pdf
5571d5a254SDimitry Andric ///
5671d5a254SDimitry Andric //===----------------------------------------------------------------------===//
57eb11fae6SDimitry Andric #include "llvm/CodeGen/MachineOutliner.h"
5871d5a254SDimitry Andric #include "llvm/ADT/DenseMap.h"
59cfca06d7SDimitry Andric #include "llvm/ADT/SmallSet.h"
6071d5a254SDimitry Andric #include "llvm/ADT/Statistic.h"
6171d5a254SDimitry Andric #include "llvm/ADT/Twine.h"
62145449b1SDimitry Andric #include "llvm/Analysis/OptimizationRemarkEmitter.h"
63145449b1SDimitry Andric #include "llvm/CodeGen/LivePhysRegs.h"
6471d5a254SDimitry Andric #include "llvm/CodeGen/MachineModuleInfo.h"
65044eb2f6SDimitry Andric #include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h"
6671d5a254SDimitry Andric #include "llvm/CodeGen/Passes.h"
67044eb2f6SDimitry Andric #include "llvm/CodeGen/TargetInstrInfo.h"
68044eb2f6SDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h"
69eb11fae6SDimitry Andric #include "llvm/IR/DIBuilder.h"
7071d5a254SDimitry Andric #include "llvm/IR/IRBuilder.h"
71eb11fae6SDimitry Andric #include "llvm/IR/Mangler.h"
72ac9a064cSDimitry Andric #include "llvm/IR/Module.h"
73706b4fc4SDimitry Andric #include "llvm/InitializePasses.h"
74eb11fae6SDimitry Andric #include "llvm/Support/CommandLine.h"
7571d5a254SDimitry Andric #include "llvm/Support/Debug.h"
76cfca06d7SDimitry Andric #include "llvm/Support/SuffixTree.h"
7771d5a254SDimitry Andric #include "llvm/Support/raw_ostream.h"
7871d5a254SDimitry Andric #include <functional>
7971d5a254SDimitry Andric #include <tuple>
8071d5a254SDimitry Andric #include <vector>
8171d5a254SDimitry Andric 
8271d5a254SDimitry Andric #define DEBUG_TYPE "machine-outliner"
8371d5a254SDimitry Andric 
8471d5a254SDimitry Andric using namespace llvm;
85044eb2f6SDimitry Andric using namespace ore;
86eb11fae6SDimitry Andric using namespace outliner;
8771d5a254SDimitry Andric 
88145449b1SDimitry Andric // Statistics for outlined functions.
8971d5a254SDimitry Andric STATISTIC(NumOutlined, "Number of candidates outlined");
9071d5a254SDimitry Andric STATISTIC(FunctionsCreated, "Number of functions created");
9171d5a254SDimitry Andric 
92145449b1SDimitry Andric // Statistics for instruction mapping.
937fa27ce4SDimitry Andric STATISTIC(NumLegalInUnsignedVec, "Outlinable instructions mapped");
94145449b1SDimitry Andric STATISTIC(NumIllegalInUnsignedVec,
957fa27ce4SDimitry Andric           "Unoutlinable instructions mapped + number of sentinel values");
967fa27ce4SDimitry Andric STATISTIC(NumSentinels, "Sentinel values inserted during mapping");
977fa27ce4SDimitry Andric STATISTIC(NumInvisible,
987fa27ce4SDimitry Andric           "Invisible instructions skipped during mapping");
997fa27ce4SDimitry Andric STATISTIC(UnsignedVecSize,
1007fa27ce4SDimitry Andric           "Total number of instructions mapped and saved to mapping vector");
101145449b1SDimitry Andric 
102eb11fae6SDimitry Andric // Set to true if the user wants the outliner to run on linkonceodr linkage
103eb11fae6SDimitry Andric // functions. This is false by default because the linker can dedupe linkonceodr
104eb11fae6SDimitry Andric // functions. Since the outliner is confined to a single module (modulo LTO),
105eb11fae6SDimitry Andric // this is off by default. It should, however, be the default behaviour in
106eb11fae6SDimitry Andric // LTO.
107eb11fae6SDimitry Andric static cl::opt<bool> EnableLinkOnceODROutlining(
108706b4fc4SDimitry Andric     "enable-linkonceodr-outlining", cl::Hidden,
109eb11fae6SDimitry Andric     cl::desc("Enable the machine outliner on linkonceodr functions"),
110eb11fae6SDimitry Andric     cl::init(false));
111eb11fae6SDimitry Andric 
112cfca06d7SDimitry Andric /// Number of times to re-run the outliner. This is not the total number of runs
113cfca06d7SDimitry Andric /// as the outliner will run at least one time. The default value is set to 0,
114cfca06d7SDimitry Andric /// meaning the outliner will run one time and rerun zero times after that.
115cfca06d7SDimitry Andric static cl::opt<unsigned> OutlinerReruns(
116cfca06d7SDimitry Andric     "machine-outliner-reruns", cl::init(0), cl::Hidden,
117cfca06d7SDimitry Andric     cl::desc(
118cfca06d7SDimitry Andric         "Number of times to rerun the outliner after the initial outline"));
119cfca06d7SDimitry Andric 
1207fa27ce4SDimitry Andric static cl::opt<unsigned> OutlinerBenefitThreshold(
1217fa27ce4SDimitry Andric     "outliner-benefit-threshold", cl::init(1), cl::Hidden,
1227fa27ce4SDimitry Andric     cl::desc(
1237fa27ce4SDimitry Andric         "The minimum size in bytes before an outlining candidate is accepted"));
1247fa27ce4SDimitry Andric 
125ac9a064cSDimitry Andric static cl::opt<bool> OutlinerLeafDescendants(
126ac9a064cSDimitry Andric     "outliner-leaf-descendants", cl::init(true), cl::Hidden,
127ac9a064cSDimitry Andric     cl::desc("Consider all leaf descendants of internal nodes of the suffix "
128ac9a064cSDimitry Andric              "tree as candidates for outlining (if false, only leaf children "
129ac9a064cSDimitry Andric              "are considered)"));
130ac9a064cSDimitry Andric 
13171d5a254SDimitry Andric namespace {
13271d5a254SDimitry Andric 
133eb11fae6SDimitry Andric /// Maps \p MachineInstrs to unsigned integers and stores the mappings.
13471d5a254SDimitry Andric struct InstructionMapper {
13571d5a254SDimitry Andric 
136eb11fae6SDimitry Andric   /// The next available integer to assign to a \p MachineInstr that
13771d5a254SDimitry Andric   /// cannot be outlined.
13871d5a254SDimitry Andric   ///
13971d5a254SDimitry Andric   /// Set to -3 for compatability with \p DenseMapInfo<unsigned>.
14071d5a254SDimitry Andric   unsigned IllegalInstrNumber = -3;
14171d5a254SDimitry Andric 
142eb11fae6SDimitry Andric   /// The next available integer to assign to a \p MachineInstr that can
14371d5a254SDimitry Andric   /// be outlined.
14471d5a254SDimitry Andric   unsigned LegalInstrNumber = 0;
14571d5a254SDimitry Andric 
14671d5a254SDimitry Andric   /// Correspondence from \p MachineInstrs to unsigned integers.
14771d5a254SDimitry Andric   DenseMap<MachineInstr *, unsigned, MachineInstrExpressionTrait>
14871d5a254SDimitry Andric       InstructionIntegerMap;
14971d5a254SDimitry Andric 
150d8e91e46SDimitry Andric   /// Correspondence between \p MachineBasicBlocks and target-defined flags.
151d8e91e46SDimitry Andric   DenseMap<MachineBasicBlock *, unsigned> MBBFlagsMap;
15271d5a254SDimitry Andric 
15371d5a254SDimitry Andric   /// The vector of unsigned integers that the module is mapped to.
1547fa27ce4SDimitry Andric   SmallVector<unsigned> UnsignedVec;
15571d5a254SDimitry Andric 
156eb11fae6SDimitry Andric   /// Stores the location of the instruction associated with the integer
15771d5a254SDimitry Andric   /// at index i in \p UnsignedVec for each index i.
1587fa27ce4SDimitry Andric   SmallVector<MachineBasicBlock::iterator> InstrList;
15971d5a254SDimitry Andric 
160d8e91e46SDimitry Andric   // Set if we added an illegal number in the previous step.
161d8e91e46SDimitry Andric   // Since each illegal number is unique, we only need one of them between
162d8e91e46SDimitry Andric   // each range of legal numbers. This lets us make sure we don't add more
163d8e91e46SDimitry Andric   // than one illegal number per range.
164d8e91e46SDimitry Andric   bool AddedIllegalLastTime = false;
165d8e91e46SDimitry Andric 
166eb11fae6SDimitry Andric   /// Maps \p *It to a legal integer.
16771d5a254SDimitry Andric   ///
168d8e91e46SDimitry Andric   /// Updates \p CanOutlineWithPrevInstr, \p HaveLegalRange, \p InstrListForMBB,
169d8e91e46SDimitry Andric   /// \p UnsignedVecForMBB, \p InstructionIntegerMap, and \p LegalInstrNumber.
17071d5a254SDimitry Andric   ///
17171d5a254SDimitry Andric   /// \returns The integer that \p *It was mapped to.
mapToLegalUnsigned__anone4ef83100111::InstructionMapper172d8e91e46SDimitry Andric   unsigned mapToLegalUnsigned(
173d8e91e46SDimitry Andric       MachineBasicBlock::iterator &It, bool &CanOutlineWithPrevInstr,
174d8e91e46SDimitry Andric       bool &HaveLegalRange, unsigned &NumLegalInBlock,
1757fa27ce4SDimitry Andric       SmallVector<unsigned> &UnsignedVecForMBB,
1767fa27ce4SDimitry Andric       SmallVector<MachineBasicBlock::iterator> &InstrListForMBB) {
177d8e91e46SDimitry Andric     // We added something legal, so we should unset the AddedLegalLastTime
178d8e91e46SDimitry Andric     // flag.
179d8e91e46SDimitry Andric     AddedIllegalLastTime = false;
180d8e91e46SDimitry Andric 
181d8e91e46SDimitry Andric     // If we have at least two adjacent legal instructions (which may have
182d8e91e46SDimitry Andric     // invisible instructions in between), remember that.
183d8e91e46SDimitry Andric     if (CanOutlineWithPrevInstr)
184d8e91e46SDimitry Andric       HaveLegalRange = true;
185d8e91e46SDimitry Andric     CanOutlineWithPrevInstr = true;
186d8e91e46SDimitry Andric 
187d8e91e46SDimitry Andric     // Keep track of the number of legal instructions we insert.
188d8e91e46SDimitry Andric     NumLegalInBlock++;
18971d5a254SDimitry Andric 
19071d5a254SDimitry Andric     // Get the integer for this instruction or give it the current
19171d5a254SDimitry Andric     // LegalInstrNumber.
192d8e91e46SDimitry Andric     InstrListForMBB.push_back(It);
19371d5a254SDimitry Andric     MachineInstr &MI = *It;
19471d5a254SDimitry Andric     bool WasInserted;
19571d5a254SDimitry Andric     DenseMap<MachineInstr *, unsigned, MachineInstrExpressionTrait>::iterator
19671d5a254SDimitry Andric         ResultIt;
19771d5a254SDimitry Andric     std::tie(ResultIt, WasInserted) =
19871d5a254SDimitry Andric         InstructionIntegerMap.insert(std::make_pair(&MI, LegalInstrNumber));
19971d5a254SDimitry Andric     unsigned MINumber = ResultIt->second;
20071d5a254SDimitry Andric 
20171d5a254SDimitry Andric     // There was an insertion.
202d8e91e46SDimitry Andric     if (WasInserted)
20371d5a254SDimitry Andric       LegalInstrNumber++;
20471d5a254SDimitry Andric 
205d8e91e46SDimitry Andric     UnsignedVecForMBB.push_back(MINumber);
20671d5a254SDimitry Andric 
20771d5a254SDimitry Andric     // Make sure we don't overflow or use any integers reserved by the DenseMap.
20871d5a254SDimitry Andric     if (LegalInstrNumber >= IllegalInstrNumber)
20971d5a254SDimitry Andric       report_fatal_error("Instruction mapping overflow!");
21071d5a254SDimitry Andric 
211044eb2f6SDimitry Andric     assert(LegalInstrNumber != DenseMapInfo<unsigned>::getEmptyKey() &&
212044eb2f6SDimitry Andric            "Tried to assign DenseMap tombstone or empty key to instruction.");
213044eb2f6SDimitry Andric     assert(LegalInstrNumber != DenseMapInfo<unsigned>::getTombstoneKey() &&
214044eb2f6SDimitry Andric            "Tried to assign DenseMap tombstone or empty key to instruction.");
21571d5a254SDimitry Andric 
216145449b1SDimitry Andric     // Statistics.
217145449b1SDimitry Andric     ++NumLegalInUnsignedVec;
21871d5a254SDimitry Andric     return MINumber;
21971d5a254SDimitry Andric   }
22071d5a254SDimitry Andric 
22171d5a254SDimitry Andric   /// Maps \p *It to an illegal integer.
22271d5a254SDimitry Andric   ///
223d8e91e46SDimitry Andric   /// Updates \p InstrListForMBB, \p UnsignedVecForMBB, and \p
224d8e91e46SDimitry Andric   /// IllegalInstrNumber.
22571d5a254SDimitry Andric   ///
22671d5a254SDimitry Andric   /// \returns The integer that \p *It was mapped to.
mapToIllegalUnsigned__anone4ef83100111::InstructionMapper227706b4fc4SDimitry Andric   unsigned mapToIllegalUnsigned(
228706b4fc4SDimitry Andric       MachineBasicBlock::iterator &It, bool &CanOutlineWithPrevInstr,
2297fa27ce4SDimitry Andric       SmallVector<unsigned> &UnsignedVecForMBB,
2307fa27ce4SDimitry Andric       SmallVector<MachineBasicBlock::iterator> &InstrListForMBB) {
231d8e91e46SDimitry Andric     // Can't outline an illegal instruction. Set the flag.
232d8e91e46SDimitry Andric     CanOutlineWithPrevInstr = false;
233d8e91e46SDimitry Andric 
234d8e91e46SDimitry Andric     // Only add one illegal number per range of legal numbers.
235d8e91e46SDimitry Andric     if (AddedIllegalLastTime)
236d8e91e46SDimitry Andric       return IllegalInstrNumber;
237d8e91e46SDimitry Andric 
238d8e91e46SDimitry Andric     // Remember that we added an illegal number last time.
239d8e91e46SDimitry Andric     AddedIllegalLastTime = true;
24071d5a254SDimitry Andric     unsigned MINumber = IllegalInstrNumber;
24171d5a254SDimitry Andric 
242d8e91e46SDimitry Andric     InstrListForMBB.push_back(It);
243d8e91e46SDimitry Andric     UnsignedVecForMBB.push_back(IllegalInstrNumber);
24471d5a254SDimitry Andric     IllegalInstrNumber--;
245145449b1SDimitry Andric     // Statistics.
246145449b1SDimitry Andric     ++NumIllegalInUnsignedVec;
24771d5a254SDimitry Andric 
24871d5a254SDimitry Andric     assert(LegalInstrNumber < IllegalInstrNumber &&
24971d5a254SDimitry Andric            "Instruction mapping overflow!");
25071d5a254SDimitry Andric 
251044eb2f6SDimitry Andric     assert(IllegalInstrNumber != DenseMapInfo<unsigned>::getEmptyKey() &&
25271d5a254SDimitry Andric            "IllegalInstrNumber cannot be DenseMap tombstone or empty key!");
25371d5a254SDimitry Andric 
254044eb2f6SDimitry Andric     assert(IllegalInstrNumber != DenseMapInfo<unsigned>::getTombstoneKey() &&
25571d5a254SDimitry Andric            "IllegalInstrNumber cannot be DenseMap tombstone or empty key!");
25671d5a254SDimitry Andric 
25771d5a254SDimitry Andric     return MINumber;
25871d5a254SDimitry Andric   }
25971d5a254SDimitry Andric 
260eb11fae6SDimitry Andric   /// Transforms a \p MachineBasicBlock into a \p vector of \p unsigneds
26171d5a254SDimitry Andric   /// and appends it to \p UnsignedVec and \p InstrList.
26271d5a254SDimitry Andric   ///
26371d5a254SDimitry Andric   /// Two instructions are assigned the same integer if they are identical.
26471d5a254SDimitry Andric   /// If an instruction is deemed unsafe to outline, then it will be assigned an
26571d5a254SDimitry Andric   /// unique integer. The resulting mapping is placed into a suffix tree and
26671d5a254SDimitry Andric   /// queried for candidates.
26771d5a254SDimitry Andric   ///
26871d5a254SDimitry Andric   /// \param MBB The \p MachineBasicBlock to be translated into integers.
269b7eb8e35SDimitry Andric   /// \param TII \p TargetInstrInfo for the function.
convertToUnsignedVec__anone4ef83100111::InstructionMapper27071d5a254SDimitry Andric   void convertToUnsignedVec(MachineBasicBlock &MBB,
27171d5a254SDimitry Andric                             const TargetInstrInfo &TII) {
2727fa27ce4SDimitry Andric     LLVM_DEBUG(dbgs() << "*** Converting MBB '" << MBB.getName()
2737fa27ce4SDimitry Andric                       << "' to unsigned vector ***\n");
274d8e91e46SDimitry Andric     unsigned Flags = 0;
275eb11fae6SDimitry Andric 
276d8e91e46SDimitry Andric     // Don't even map in this case.
277d8e91e46SDimitry Andric     if (!TII.isMBBSafeToOutlineFrom(MBB, Flags))
278d8e91e46SDimitry Andric       return;
27971d5a254SDimitry Andric 
2807fa27ce4SDimitry Andric     auto OutlinableRanges = TII.getOutlinableRanges(MBB, Flags);
2817fa27ce4SDimitry Andric     LLVM_DEBUG(dbgs() << MBB.getName() << ": " << OutlinableRanges.size()
2827fa27ce4SDimitry Andric                       << " outlinable range(s)\n");
2837fa27ce4SDimitry Andric     if (OutlinableRanges.empty())
2847fa27ce4SDimitry Andric       return;
2857fa27ce4SDimitry Andric 
286d8e91e46SDimitry Andric     // Store info for the MBB for later outlining.
287d8e91e46SDimitry Andric     MBBFlagsMap[&MBB] = Flags;
288d8e91e46SDimitry Andric 
289d8e91e46SDimitry Andric     MachineBasicBlock::iterator It = MBB.begin();
290d8e91e46SDimitry Andric 
291d8e91e46SDimitry Andric     // The number of instructions in this block that will be considered for
292d8e91e46SDimitry Andric     // outlining.
293d8e91e46SDimitry Andric     unsigned NumLegalInBlock = 0;
294d8e91e46SDimitry Andric 
295d8e91e46SDimitry Andric     // True if we have at least two legal instructions which aren't separated
296d8e91e46SDimitry Andric     // by an illegal instruction.
297d8e91e46SDimitry Andric     bool HaveLegalRange = false;
298d8e91e46SDimitry Andric 
299d8e91e46SDimitry Andric     // True if we can perform outlining given the last mapped (non-invisible)
300d8e91e46SDimitry Andric     // instruction. This lets us know if we have a legal range.
301d8e91e46SDimitry Andric     bool CanOutlineWithPrevInstr = false;
302d8e91e46SDimitry Andric 
303d8e91e46SDimitry Andric     // FIXME: Should this all just be handled in the target, rather than using
304d8e91e46SDimitry Andric     // repeated calls to getOutliningType?
3057fa27ce4SDimitry Andric     SmallVector<unsigned> UnsignedVecForMBB;
3067fa27ce4SDimitry Andric     SmallVector<MachineBasicBlock::iterator> InstrListForMBB;
307d8e91e46SDimitry Andric 
3087fa27ce4SDimitry Andric     LLVM_DEBUG(dbgs() << "*** Mapping outlinable ranges ***\n");
3097fa27ce4SDimitry Andric     for (auto &OutlinableRange : OutlinableRanges) {
3107fa27ce4SDimitry Andric       auto OutlinableRangeBegin = OutlinableRange.first;
3117fa27ce4SDimitry Andric       auto OutlinableRangeEnd = OutlinableRange.second;
3127fa27ce4SDimitry Andric #ifndef NDEBUG
3137fa27ce4SDimitry Andric       LLVM_DEBUG(
3147fa27ce4SDimitry Andric           dbgs() << "Mapping "
3157fa27ce4SDimitry Andric                  << std::distance(OutlinableRangeBegin, OutlinableRangeEnd)
3167fa27ce4SDimitry Andric                  << " instruction range\n");
3177fa27ce4SDimitry Andric       // Everything outside of an outlinable range is illegal.
3187fa27ce4SDimitry Andric       unsigned NumSkippedInRange = 0;
3197fa27ce4SDimitry Andric #endif
3207fa27ce4SDimitry Andric       for (; It != OutlinableRangeBegin; ++It) {
3217fa27ce4SDimitry Andric #ifndef NDEBUG
3227fa27ce4SDimitry Andric         ++NumSkippedInRange;
3237fa27ce4SDimitry Andric #endif
3247fa27ce4SDimitry Andric         mapToIllegalUnsigned(It, CanOutlineWithPrevInstr, UnsignedVecForMBB,
3257fa27ce4SDimitry Andric                              InstrListForMBB);
3267fa27ce4SDimitry Andric       }
3277fa27ce4SDimitry Andric #ifndef NDEBUG
3287fa27ce4SDimitry Andric       LLVM_DEBUG(dbgs() << "Skipped " << NumSkippedInRange
3297fa27ce4SDimitry Andric                         << " instructions outside outlinable range\n");
3307fa27ce4SDimitry Andric #endif
3317fa27ce4SDimitry Andric       assert(It != MBB.end() && "Should still have instructions?");
3327fa27ce4SDimitry Andric       // `It` is now positioned at the beginning of a range of instructions
3337fa27ce4SDimitry Andric       // which may be outlinable. Check if each instruction is known to be safe.
3347fa27ce4SDimitry Andric       for (; It != OutlinableRangeEnd; ++It) {
33571d5a254SDimitry Andric         // Keep track of where this instruction is in the module.
336eb11fae6SDimitry Andric         switch (TII.getOutliningType(It, Flags)) {
337eb11fae6SDimitry Andric         case InstrType::Illegal:
338706b4fc4SDimitry Andric           mapToIllegalUnsigned(It, CanOutlineWithPrevInstr, UnsignedVecForMBB,
339706b4fc4SDimitry Andric                                InstrListForMBB);
34071d5a254SDimitry Andric           break;
34171d5a254SDimitry Andric 
342eb11fae6SDimitry Andric         case InstrType::Legal:
343d8e91e46SDimitry Andric           mapToLegalUnsigned(It, CanOutlineWithPrevInstr, HaveLegalRange,
3447fa27ce4SDimitry Andric                              NumLegalInBlock, UnsignedVecForMBB,
3457fa27ce4SDimitry Andric                              InstrListForMBB);
34671d5a254SDimitry Andric           break;
34771d5a254SDimitry Andric 
348eb11fae6SDimitry Andric         case InstrType::LegalTerminator:
349d8e91e46SDimitry Andric           mapToLegalUnsigned(It, CanOutlineWithPrevInstr, HaveLegalRange,
3507fa27ce4SDimitry Andric                              NumLegalInBlock, UnsignedVecForMBB,
3517fa27ce4SDimitry Andric                              InstrListForMBB);
3527fa27ce4SDimitry Andric           // The instruction also acts as a terminator, so we have to record
3537fa27ce4SDimitry Andric           // that in the string.
354d8e91e46SDimitry Andric           mapToIllegalUnsigned(It, CanOutlineWithPrevInstr, UnsignedVecForMBB,
355d8e91e46SDimitry Andric                                InstrListForMBB);
356eb11fae6SDimitry Andric           break;
357eb11fae6SDimitry Andric 
358eb11fae6SDimitry Andric         case InstrType::Invisible:
359d8e91e46SDimitry Andric           // Normally this is set by mapTo(Blah)Unsigned, but we just want to
360d8e91e46SDimitry Andric           // skip this instruction. So, unset the flag here.
361145449b1SDimitry Andric           ++NumInvisible;
362d8e91e46SDimitry Andric           AddedIllegalLastTime = false;
36371d5a254SDimitry Andric           break;
36471d5a254SDimitry Andric         }
36571d5a254SDimitry Andric       }
3667fa27ce4SDimitry Andric     }
3677fa27ce4SDimitry Andric 
3687fa27ce4SDimitry Andric     LLVM_DEBUG(dbgs() << "HaveLegalRange = " << HaveLegalRange << "\n");
36971d5a254SDimitry Andric 
370d8e91e46SDimitry Andric     // Are there enough legal instructions in the block for outlining to be
371d8e91e46SDimitry Andric     // possible?
372d8e91e46SDimitry Andric     if (HaveLegalRange) {
37371d5a254SDimitry Andric       // After we're done every insertion, uniquely terminate this part of the
37471d5a254SDimitry Andric       // "string". This makes sure we won't match across basic block or function
37571d5a254SDimitry Andric       // boundaries since the "end" is encoded uniquely and thus appears in no
37671d5a254SDimitry Andric       // repeated substring.
377d8e91e46SDimitry Andric       mapToIllegalUnsigned(It, CanOutlineWithPrevInstr, UnsignedVecForMBB,
378d8e91e46SDimitry Andric                            InstrListForMBB);
3797fa27ce4SDimitry Andric       ++NumSentinels;
3807fa27ce4SDimitry Andric       append_range(InstrList, InstrListForMBB);
3817fa27ce4SDimitry Andric       append_range(UnsignedVec, UnsignedVecForMBB);
382d8e91e46SDimitry Andric     }
38371d5a254SDimitry Andric   }
38471d5a254SDimitry Andric 
InstructionMapper__anone4ef83100111::InstructionMapper38571d5a254SDimitry Andric   InstructionMapper() {
38671d5a254SDimitry Andric     // Make sure that the implementation of DenseMapInfo<unsigned> hasn't
38771d5a254SDimitry Andric     // changed.
38871d5a254SDimitry Andric     assert(DenseMapInfo<unsigned>::getEmptyKey() == (unsigned)-1 &&
38971d5a254SDimitry Andric            "DenseMapInfo<unsigned>'s empty key isn't -1!");
39071d5a254SDimitry Andric     assert(DenseMapInfo<unsigned>::getTombstoneKey() == (unsigned)-2 &&
39171d5a254SDimitry Andric            "DenseMapInfo<unsigned>'s tombstone key isn't -2!");
39271d5a254SDimitry Andric   }
39371d5a254SDimitry Andric };
39471d5a254SDimitry Andric 
395eb11fae6SDimitry Andric /// An interprocedural pass which finds repeated sequences of
39671d5a254SDimitry Andric /// instructions and replaces them with calls to functions.
39771d5a254SDimitry Andric ///
39871d5a254SDimitry Andric /// Each instruction is mapped to an unsigned integer and placed in a string.
39971d5a254SDimitry Andric /// The resulting mapping is then placed in a \p SuffixTree. The \p SuffixTree
40071d5a254SDimitry Andric /// is then repeatedly queried for repeated sequences of instructions. Each
40171d5a254SDimitry Andric /// non-overlapping repeated sequence is then placed in its own
40271d5a254SDimitry Andric /// \p MachineFunction and each instance is then replaced with a call to that
40371d5a254SDimitry Andric /// function.
40471d5a254SDimitry Andric struct MachineOutliner : public ModulePass {
40571d5a254SDimitry Andric 
40671d5a254SDimitry Andric   static char ID;
40771d5a254SDimitry Andric 
408eb11fae6SDimitry Andric   /// Set to true if the outliner should consider functions with
409044eb2f6SDimitry Andric   /// linkonceodr linkage.
410044eb2f6SDimitry Andric   bool OutlineFromLinkOnceODRs = false;
411044eb2f6SDimitry Andric 
412cfca06d7SDimitry Andric   /// The current repeat number of machine outlining.
413cfca06d7SDimitry Andric   unsigned OutlineRepeatedNum = 0;
414cfca06d7SDimitry Andric 
415eb11fae6SDimitry Andric   /// Set to true if the outliner should run on all functions in the module
416eb11fae6SDimitry Andric   /// considered safe for outlining.
417eb11fae6SDimitry Andric   /// Set to true by default for compatibility with llc's -run-pass option.
418eb11fae6SDimitry Andric   /// Set when the pass is constructed in TargetPassConfig.
419eb11fae6SDimitry Andric   bool RunOnAllFunctions = true;
420eb11fae6SDimitry Andric 
getPassName__anone4ef83100111::MachineOutliner42171d5a254SDimitry Andric   StringRef getPassName() const override { return "Machine Outliner"; }
42271d5a254SDimitry Andric 
getAnalysisUsage__anone4ef83100111::MachineOutliner42371d5a254SDimitry Andric   void getAnalysisUsage(AnalysisUsage &AU) const override {
4241d5ae102SDimitry Andric     AU.addRequired<MachineModuleInfoWrapperPass>();
4251d5ae102SDimitry Andric     AU.addPreserved<MachineModuleInfoWrapperPass>();
42671d5a254SDimitry Andric     AU.setPreservesAll();
42771d5a254SDimitry Andric     ModulePass::getAnalysisUsage(AU);
42871d5a254SDimitry Andric   }
42971d5a254SDimitry Andric 
MachineOutliner__anone4ef83100111::MachineOutliner430eb11fae6SDimitry Andric   MachineOutliner() : ModulePass(ID) {
43171d5a254SDimitry Andric     initializeMachineOutlinerPass(*PassRegistry::getPassRegistry());
43271d5a254SDimitry Andric   }
43371d5a254SDimitry Andric 
434eb11fae6SDimitry Andric   /// Remark output explaining that not outlining a set of candidates would be
435eb11fae6SDimitry Andric   /// better than outlining that set.
436eb11fae6SDimitry Andric   void emitNotOutliningCheaperRemark(
437eb11fae6SDimitry Andric       unsigned StringLen, std::vector<Candidate> &CandidatesForRepeatedSeq,
438eb11fae6SDimitry Andric       OutlinedFunction &OF);
439eb11fae6SDimitry Andric 
440eb11fae6SDimitry Andric   /// Remark output explaining that a function was outlined.
441eb11fae6SDimitry Andric   void emitOutlinedFunctionRemark(OutlinedFunction &OF);
442eb11fae6SDimitry Andric 
443d8e91e46SDimitry Andric   /// Find all repeated substrings that satisfy the outlining cost model by
444d8e91e46SDimitry Andric   /// constructing a suffix tree.
445044eb2f6SDimitry Andric   ///
446044eb2f6SDimitry Andric   /// If a substring appears at least twice, then it must be represented by
447eb11fae6SDimitry Andric   /// an internal node which appears in at least two suffixes. Each suffix
448eb11fae6SDimitry Andric   /// is represented by a leaf node. To do this, we visit each internal node
449eb11fae6SDimitry Andric   /// in the tree, using the leaf children of each internal node. If an
450eb11fae6SDimitry Andric   /// internal node represents a beneficial substring, then we use each of
451eb11fae6SDimitry Andric   /// its leaf children to find the locations of its substring.
452044eb2f6SDimitry Andric   ///
453044eb2f6SDimitry Andric   /// \param Mapper Contains outlining mapping information.
454eb11fae6SDimitry Andric   /// \param[out] FunctionList Filled with a list of \p OutlinedFunctions
455eb11fae6SDimitry Andric   /// each type of candidate.
456d8e91e46SDimitry Andric   void findCandidates(InstructionMapper &Mapper,
457044eb2f6SDimitry Andric                       std::vector<OutlinedFunction> &FunctionList);
458044eb2f6SDimitry Andric 
459d8e91e46SDimitry Andric   /// Replace the sequences of instructions represented by \p OutlinedFunctions
460d8e91e46SDimitry Andric   /// with calls to functions.
46171d5a254SDimitry Andric   ///
46271d5a254SDimitry Andric   /// \param M The module we are outlining from.
46371d5a254SDimitry Andric   /// \param FunctionList A list of functions to be inserted into the module.
46471d5a254SDimitry Andric   /// \param Mapper Contains the instruction mappings for the module.
465d8e91e46SDimitry Andric   bool outline(Module &M, std::vector<OutlinedFunction> &FunctionList,
466706b4fc4SDimitry Andric                InstructionMapper &Mapper, unsigned &OutlinedFunctionNum);
46771d5a254SDimitry Andric 
46871d5a254SDimitry Andric   /// Creates a function for \p OF and inserts it into the module.
469d8e91e46SDimitry Andric   MachineFunction *createOutlinedFunction(Module &M, OutlinedFunction &OF,
470d8e91e46SDimitry Andric                                           InstructionMapper &Mapper,
471d8e91e46SDimitry Andric                                           unsigned Name);
47271d5a254SDimitry Andric 
473cfca06d7SDimitry Andric   /// Calls 'doOutline()' 1 + OutlinerReruns times.
474706b4fc4SDimitry Andric   bool runOnModule(Module &M) override;
475706b4fc4SDimitry Andric 
47671d5a254SDimitry Andric   /// Construct a suffix tree on the instructions in \p M and outline repeated
47771d5a254SDimitry Andric   /// strings from that tree.
478706b4fc4SDimitry Andric   bool doOutline(Module &M, unsigned &OutlinedFunctionNum);
479eb11fae6SDimitry Andric 
480eb11fae6SDimitry Andric   /// Return a DISubprogram for OF if one exists, and null otherwise. Helper
481eb11fae6SDimitry Andric   /// function for remark emission.
getSubprogramOrNull__anone4ef83100111::MachineOutliner482eb11fae6SDimitry Andric   DISubprogram *getSubprogramOrNull(const OutlinedFunction &OF) {
483d8e91e46SDimitry Andric     for (const Candidate &C : OF.Candidates)
484706b4fc4SDimitry Andric       if (MachineFunction *MF = C.getMF())
485706b4fc4SDimitry Andric         if (DISubprogram *SP = MF->getFunction().getSubprogram())
486eb11fae6SDimitry Andric           return SP;
487eb11fae6SDimitry Andric     return nullptr;
488eb11fae6SDimitry Andric   }
48971d5a254SDimitry Andric 
490d8e91e46SDimitry Andric   /// Populate and \p InstructionMapper with instruction-to-integer mappings.
491d8e91e46SDimitry Andric   /// These are used to construct a suffix tree.
492d8e91e46SDimitry Andric   void populateMapper(InstructionMapper &Mapper, Module &M,
493d8e91e46SDimitry Andric                       MachineModuleInfo &MMI);
494d8e91e46SDimitry Andric 
495d8e91e46SDimitry Andric   /// Initialize information necessary to output a size remark.
496d8e91e46SDimitry Andric   /// FIXME: This should be handled by the pass manager, not the outliner.
497d8e91e46SDimitry Andric   /// FIXME: This is nearly identical to the initSizeRemarkInfo in the legacy
498d8e91e46SDimitry Andric   /// pass manager.
499706b4fc4SDimitry Andric   void initSizeRemarkInfo(const Module &M, const MachineModuleInfo &MMI,
500d8e91e46SDimitry Andric                           StringMap<unsigned> &FunctionToInstrCount);
501d8e91e46SDimitry Andric 
502d8e91e46SDimitry Andric   /// Emit the remark.
503d8e91e46SDimitry Andric   // FIXME: This should be handled by the pass manager, not the outliner.
504706b4fc4SDimitry Andric   void
505706b4fc4SDimitry Andric   emitInstrCountChangedRemark(const Module &M, const MachineModuleInfo &MMI,
506d8e91e46SDimitry Andric                               const StringMap<unsigned> &FunctionToInstrCount);
507d8e91e46SDimitry Andric };
50871d5a254SDimitry Andric } // Anonymous namespace.
50971d5a254SDimitry Andric 
51071d5a254SDimitry Andric char MachineOutliner::ID = 0;
51171d5a254SDimitry Andric 
51271d5a254SDimitry Andric namespace llvm {
createMachineOutlinerPass(bool RunOnAllFunctions)513eb11fae6SDimitry Andric ModulePass *createMachineOutlinerPass(bool RunOnAllFunctions) {
514eb11fae6SDimitry Andric   MachineOutliner *OL = new MachineOutliner();
515eb11fae6SDimitry Andric   OL->RunOnAllFunctions = RunOnAllFunctions;
516eb11fae6SDimitry Andric   return OL;
51771d5a254SDimitry Andric }
51871d5a254SDimitry Andric 
519044eb2f6SDimitry Andric } // namespace llvm
52071d5a254SDimitry Andric 
521044eb2f6SDimitry Andric INITIALIZE_PASS(MachineOutliner, DEBUG_TYPE, "Machine Function Outliner", false,
522044eb2f6SDimitry Andric                 false)
523044eb2f6SDimitry Andric 
emitNotOutliningCheaperRemark(unsigned StringLen,std::vector<Candidate> & CandidatesForRepeatedSeq,OutlinedFunction & OF)524eb11fae6SDimitry Andric void MachineOutliner::emitNotOutliningCheaperRemark(
525eb11fae6SDimitry Andric     unsigned StringLen, std::vector<Candidate> &CandidatesForRepeatedSeq,
526eb11fae6SDimitry Andric     OutlinedFunction &OF) {
527d8e91e46SDimitry Andric   // FIXME: Right now, we arbitrarily choose some Candidate from the
528d8e91e46SDimitry Andric   // OutlinedFunction. This isn't necessarily fixed, nor does it have to be.
529d8e91e46SDimitry Andric   // We should probably sort these by function name or something to make sure
530d8e91e46SDimitry Andric   // the remarks are stable.
531eb11fae6SDimitry Andric   Candidate &C = CandidatesForRepeatedSeq.front();
532eb11fae6SDimitry Andric   MachineOptimizationRemarkEmitter MORE(*(C.getMF()), nullptr);
533eb11fae6SDimitry Andric   MORE.emit([&]() {
534eb11fae6SDimitry Andric     MachineOptimizationRemarkMissed R(DEBUG_TYPE, "NotOutliningCheaper",
5354df029ccSDimitry Andric                                       C.front().getDebugLoc(), C.getMBB());
536eb11fae6SDimitry Andric     R << "Did not outline " << NV("Length", StringLen) << " instructions"
537eb11fae6SDimitry Andric       << " from " << NV("NumOccurrences", CandidatesForRepeatedSeq.size())
538eb11fae6SDimitry Andric       << " locations."
539eb11fae6SDimitry Andric       << " Bytes from outlining all occurrences ("
540eb11fae6SDimitry Andric       << NV("OutliningCost", OF.getOutliningCost()) << ")"
541eb11fae6SDimitry Andric       << " >= Unoutlined instruction bytes ("
542eb11fae6SDimitry Andric       << NV("NotOutliningCost", OF.getNotOutlinedCost()) << ")"
543eb11fae6SDimitry Andric       << " (Also found at: ";
544eb11fae6SDimitry Andric 
545eb11fae6SDimitry Andric     // Tell the user the other places the candidate was found.
546eb11fae6SDimitry Andric     for (unsigned i = 1, e = CandidatesForRepeatedSeq.size(); i < e; i++) {
547eb11fae6SDimitry Andric       R << NV((Twine("OtherStartLoc") + Twine(i)).str(),
5484df029ccSDimitry Andric               CandidatesForRepeatedSeq[i].front().getDebugLoc());
549eb11fae6SDimitry Andric       if (i != e - 1)
550eb11fae6SDimitry Andric         R << ", ";
551eb11fae6SDimitry Andric     }
552eb11fae6SDimitry Andric 
553eb11fae6SDimitry Andric     R << ")";
554eb11fae6SDimitry Andric     return R;
555eb11fae6SDimitry Andric   });
556eb11fae6SDimitry Andric }
557eb11fae6SDimitry Andric 
emitOutlinedFunctionRemark(OutlinedFunction & OF)558eb11fae6SDimitry Andric void MachineOutliner::emitOutlinedFunctionRemark(OutlinedFunction &OF) {
559eb11fae6SDimitry Andric   MachineBasicBlock *MBB = &*OF.MF->begin();
560eb11fae6SDimitry Andric   MachineOptimizationRemarkEmitter MORE(*OF.MF, nullptr);
561eb11fae6SDimitry Andric   MachineOptimizationRemark R(DEBUG_TYPE, "OutlinedFunction",
562eb11fae6SDimitry Andric                               MBB->findDebugLoc(MBB->begin()), MBB);
563eb11fae6SDimitry Andric   R << "Saved " << NV("OutliningBenefit", OF.getBenefit()) << " bytes by "
564d8e91e46SDimitry Andric     << "outlining " << NV("Length", OF.getNumInstrs()) << " instructions "
565eb11fae6SDimitry Andric     << "from " << NV("NumOccurrences", OF.getOccurrenceCount())
566eb11fae6SDimitry Andric     << " locations. "
567eb11fae6SDimitry Andric     << "(Found at: ";
568eb11fae6SDimitry Andric 
569eb11fae6SDimitry Andric   // Tell the user the other places the candidate was found.
570eb11fae6SDimitry Andric   for (size_t i = 0, e = OF.Candidates.size(); i < e; i++) {
571eb11fae6SDimitry Andric 
572eb11fae6SDimitry Andric     R << NV((Twine("StartLoc") + Twine(i)).str(),
5734df029ccSDimitry Andric             OF.Candidates[i].front().getDebugLoc());
574eb11fae6SDimitry Andric     if (i != e - 1)
575eb11fae6SDimitry Andric       R << ", ";
576eb11fae6SDimitry Andric   }
577eb11fae6SDimitry Andric 
578eb11fae6SDimitry Andric   R << ")";
579eb11fae6SDimitry Andric 
580eb11fae6SDimitry Andric   MORE.emit(R);
581eb11fae6SDimitry Andric }
582eb11fae6SDimitry Andric 
findCandidates(InstructionMapper & Mapper,std::vector<OutlinedFunction> & FunctionList)583706b4fc4SDimitry Andric void MachineOutliner::findCandidates(
584706b4fc4SDimitry Andric     InstructionMapper &Mapper, std::vector<OutlinedFunction> &FunctionList) {
585044eb2f6SDimitry Andric   FunctionList.clear();
586ac9a064cSDimitry Andric   SuffixTree ST(Mapper.UnsignedVec, OutlinerLeafDescendants);
587044eb2f6SDimitry Andric 
588706b4fc4SDimitry Andric   // First, find all of the repeated substrings in the tree of minimum length
589d8e91e46SDimitry Andric   // 2.
590044eb2f6SDimitry Andric   std::vector<Candidate> CandidatesForRepeatedSeq;
5917fa27ce4SDimitry Andric   LLVM_DEBUG(dbgs() << "*** Discarding overlapping candidates *** \n");
5927fa27ce4SDimitry Andric   LLVM_DEBUG(
5937fa27ce4SDimitry Andric       dbgs() << "Searching for overlaps in all repeated sequences...\n");
594ac9a064cSDimitry Andric   for (SuffixTree::RepeatedSubstring &RS : ST) {
595d8e91e46SDimitry Andric     CandidatesForRepeatedSeq.clear();
596d8e91e46SDimitry Andric     unsigned StringLen = RS.Length;
5977fa27ce4SDimitry Andric     LLVM_DEBUG(dbgs() << "  Sequence length: " << StringLen << "\n");
5987fa27ce4SDimitry Andric     // Debug code to keep track of how many candidates we removed.
5997fa27ce4SDimitry Andric #ifndef NDEBUG
6007fa27ce4SDimitry Andric     unsigned NumDiscarded = 0;
6017fa27ce4SDimitry Andric     unsigned NumKept = 0;
6027fa27ce4SDimitry Andric #endif
603ac9a064cSDimitry Andric     // Sort the start indices so that we can efficiently check if candidates
604ac9a064cSDimitry Andric     // overlap with the ones we've already found for this sequence.
605ac9a064cSDimitry Andric     llvm::sort(RS.StartIndices);
606d8e91e46SDimitry Andric     for (const unsigned &StartIdx : RS.StartIndices) {
607044eb2f6SDimitry Andric       // Trick: Discard some candidates that would be incompatible with the
608044eb2f6SDimitry Andric       // ones we've already found for this sequence. This will save us some
609044eb2f6SDimitry Andric       // work in candidate selection.
610044eb2f6SDimitry Andric       //
611044eb2f6SDimitry Andric       // If two candidates overlap, then we can't outline them both. This
612044eb2f6SDimitry Andric       // happens when we have candidates that look like, say
613044eb2f6SDimitry Andric       //
614044eb2f6SDimitry Andric       // AA (where each "A" is an instruction).
615044eb2f6SDimitry Andric       //
616044eb2f6SDimitry Andric       // We might have some portion of the module that looks like this:
617044eb2f6SDimitry Andric       // AAAAAA (6 A's)
618044eb2f6SDimitry Andric       //
619044eb2f6SDimitry Andric       // In this case, there are 5 different copies of "AA" in this range, but
620044eb2f6SDimitry Andric       // at most 3 can be outlined. If only outlining 3 of these is going to
621044eb2f6SDimitry Andric       // be unbeneficial, then we ought to not bother.
622044eb2f6SDimitry Andric       //
623044eb2f6SDimitry Andric       // Note that two things DON'T overlap when they look like this:
624044eb2f6SDimitry Andric       // start1...end1 .... start2...end2
625044eb2f6SDimitry Andric       // That is, one must either
626044eb2f6SDimitry Andric       // * End before the other starts
627044eb2f6SDimitry Andric       // * Start after the other ends
6287fa27ce4SDimitry Andric       unsigned EndIdx = StartIdx + StringLen - 1;
629ac9a064cSDimitry Andric       if (!CandidatesForRepeatedSeq.empty() &&
630ac9a064cSDimitry Andric           StartIdx <= CandidatesForRepeatedSeq.back().getEndIdx()) {
6317fa27ce4SDimitry Andric #ifndef NDEBUG
6327fa27ce4SDimitry Andric         ++NumDiscarded;
633ac9a064cSDimitry Andric         LLVM_DEBUG(dbgs() << "    .. DISCARD candidate @ [" << StartIdx << ", "
634ac9a064cSDimitry Andric                           << EndIdx << "]; overlaps with candidate @ ["
635ac9a064cSDimitry Andric                           << CandidatesForRepeatedSeq.back().getStartIdx()
636ac9a064cSDimitry Andric                           << ", " << CandidatesForRepeatedSeq.back().getEndIdx()
637ac9a064cSDimitry Andric                           << "]\n");
6387fa27ce4SDimitry Andric #endif
6397fa27ce4SDimitry Andric         continue;
6407fa27ce4SDimitry Andric       }
641044eb2f6SDimitry Andric       // It doesn't overlap with anything, so we can outline it.
642044eb2f6SDimitry Andric       // Each sequence is over [StartIt, EndIt].
643eb11fae6SDimitry Andric       // Save the candidate and its location.
6447fa27ce4SDimitry Andric #ifndef NDEBUG
6457fa27ce4SDimitry Andric       ++NumKept;
6467fa27ce4SDimitry Andric #endif
647044eb2f6SDimitry Andric       MachineBasicBlock::iterator StartIt = Mapper.InstrList[StartIdx];
648044eb2f6SDimitry Andric       MachineBasicBlock::iterator EndIt = Mapper.InstrList[EndIdx];
649d8e91e46SDimitry Andric       MachineBasicBlock *MBB = StartIt->getParent();
6507fa27ce4SDimitry Andric       CandidatesForRepeatedSeq.emplace_back(StartIdx, StringLen, StartIt, EndIt,
6517fa27ce4SDimitry Andric                                             MBB, FunctionList.size(),
652d8e91e46SDimitry Andric                                             Mapper.MBBFlagsMap[MBB]);
653044eb2f6SDimitry Andric     }
6547fa27ce4SDimitry Andric #ifndef NDEBUG
6557fa27ce4SDimitry Andric     LLVM_DEBUG(dbgs() << "    Candidates discarded: " << NumDiscarded
6567fa27ce4SDimitry Andric                       << "\n");
6577fa27ce4SDimitry Andric     LLVM_DEBUG(dbgs() << "    Candidates kept: " << NumKept << "\n\n");
6587fa27ce4SDimitry Andric #endif
659044eb2f6SDimitry Andric 
660044eb2f6SDimitry Andric     // We've found something we might want to outline.
661044eb2f6SDimitry Andric     // Create an OutlinedFunction to store it and check if it'd be beneficial
662044eb2f6SDimitry Andric     // to outline.
663d8e91e46SDimitry Andric     if (CandidatesForRepeatedSeq.size() < 2)
664b7eb8e35SDimitry Andric       continue;
665b7eb8e35SDimitry Andric 
666b7eb8e35SDimitry Andric     // Arbitrarily choose a TII from the first candidate.
667b7eb8e35SDimitry Andric     // FIXME: Should getOutliningCandidateInfo move to TargetMachine?
668b7eb8e35SDimitry Andric     const TargetInstrInfo *TII =
669b7eb8e35SDimitry Andric         CandidatesForRepeatedSeq[0].getMF()->getSubtarget().getInstrInfo();
670b7eb8e35SDimitry Andric 
6717fa27ce4SDimitry Andric     std::optional<OutlinedFunction> OF =
672b7eb8e35SDimitry Andric         TII->getOutliningCandidateInfo(CandidatesForRepeatedSeq);
673eb11fae6SDimitry Andric 
674d8e91e46SDimitry Andric     // If we deleted too many candidates, then there's nothing worth outlining.
675d8e91e46SDimitry Andric     // FIXME: This should take target-specified instruction sizes into account.
6767fa27ce4SDimitry Andric     if (!OF || OF->Candidates.size() < 2)
677eb11fae6SDimitry Andric       continue;
678eb11fae6SDimitry Andric 
679044eb2f6SDimitry Andric     // Is it better to outline this candidate than not?
6807fa27ce4SDimitry Andric     if (OF->getBenefit() < OutlinerBenefitThreshold) {
6817fa27ce4SDimitry Andric       emitNotOutliningCheaperRemark(StringLen, CandidatesForRepeatedSeq, *OF);
682044eb2f6SDimitry Andric       continue;
683044eb2f6SDimitry Andric     }
684044eb2f6SDimitry Andric 
6857fa27ce4SDimitry Andric     FunctionList.push_back(*OF);
686044eb2f6SDimitry Andric   }
68771d5a254SDimitry Andric }
68871d5a254SDimitry Andric 
createOutlinedFunction(Module & M,OutlinedFunction & OF,InstructionMapper & Mapper,unsigned Name)689706b4fc4SDimitry Andric MachineFunction *MachineOutliner::createOutlinedFunction(
690706b4fc4SDimitry Andric     Module &M, OutlinedFunction &OF, InstructionMapper &Mapper, unsigned Name) {
69171d5a254SDimitry Andric 
692e6d15924SDimitry Andric   // Create the function name. This should be unique.
693d8e91e46SDimitry Andric   // FIXME: We should have a better naming scheme. This should be stable,
694d8e91e46SDimitry Andric   // regardless of changes to the outliner's cost model/traversal order.
695cfca06d7SDimitry Andric   std::string FunctionName = "OUTLINED_FUNCTION_";
696cfca06d7SDimitry Andric   if (OutlineRepeatedNum > 0)
697cfca06d7SDimitry Andric     FunctionName += std::to_string(OutlineRepeatedNum + 1) + "_";
698cfca06d7SDimitry Andric   FunctionName += std::to_string(Name);
6997fa27ce4SDimitry Andric   LLVM_DEBUG(dbgs() << "NEW FUNCTION: " << FunctionName << "\n");
70071d5a254SDimitry Andric 
70171d5a254SDimitry Andric   // Create the function using an IR-level function.
70271d5a254SDimitry Andric   LLVMContext &C = M.getContext();
703e6d15924SDimitry Andric   Function *F = Function::Create(FunctionType::get(Type::getVoidTy(C), false),
704e6d15924SDimitry Andric                                  Function::ExternalLinkage, FunctionName, M);
70571d5a254SDimitry Andric 
70671d5a254SDimitry Andric   // NOTE: If this is linkonceodr, then we can take advantage of linker deduping
70771d5a254SDimitry Andric   // which gives us better results when we outline from linkonceodr functions.
708eb11fae6SDimitry Andric   F->setLinkage(GlobalValue::InternalLinkage);
70971d5a254SDimitry Andric   F->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
71071d5a254SDimitry Andric 
711eb11fae6SDimitry Andric   // Set optsize/minsize, so we don't insert padding between outlined
712eb11fae6SDimitry Andric   // functions.
713eb11fae6SDimitry Andric   F->addFnAttr(Attribute::OptimizeForSize);
714eb11fae6SDimitry Andric   F->addFnAttr(Attribute::MinSize);
715eb11fae6SDimitry Andric 
716d8e91e46SDimitry Andric   Candidate &FirstCand = OF.Candidates.front();
717f65dcba8SDimitry Andric   const TargetInstrInfo &TII =
718f65dcba8SDimitry Andric       *FirstCand.getMF()->getSubtarget().getInstrInfo();
719eb11fae6SDimitry Andric 
720f65dcba8SDimitry Andric   TII.mergeOutliningCandidateAttributes(*F, OF.Candidates);
721cfca06d7SDimitry Andric 
722145449b1SDimitry Andric   // Set uwtable, so we generate eh_frame.
723145449b1SDimitry Andric   UWTableKind UW = std::accumulate(
724145449b1SDimitry Andric       OF.Candidates.cbegin(), OF.Candidates.cend(), UWTableKind::None,
725145449b1SDimitry Andric       [](UWTableKind K, const outliner::Candidate &C) {
726145449b1SDimitry Andric         return std::max(K, C.getMF()->getFunction().getUWTableKind());
727145449b1SDimitry Andric       });
728145449b1SDimitry Andric   F->setUWTableKind(UW);
729145449b1SDimitry Andric 
73071d5a254SDimitry Andric   BasicBlock *EntryBB = BasicBlock::Create(C, "entry", F);
73171d5a254SDimitry Andric   IRBuilder<> Builder(EntryBB);
73271d5a254SDimitry Andric   Builder.CreateRetVoid();
73371d5a254SDimitry Andric 
7341d5ae102SDimitry Andric   MachineModuleInfo &MMI = getAnalysis<MachineModuleInfoWrapperPass>().getMMI();
7357ab83427SDimitry Andric   MachineFunction &MF = MMI.getOrCreateMachineFunction(*F);
7367fa27ce4SDimitry Andric   MF.setIsOutlined(true);
73771d5a254SDimitry Andric   MachineBasicBlock &MBB = *MF.CreateMachineBasicBlock();
73871d5a254SDimitry Andric 
73971d5a254SDimitry Andric   // Insert the new function into the module.
74071d5a254SDimitry Andric   MF.insert(MF.begin(), &MBB);
74171d5a254SDimitry Andric 
7424df029ccSDimitry Andric   MachineFunction *OriginalMF = FirstCand.front().getMF();
743cfca06d7SDimitry Andric   const std::vector<MCCFIInstruction> &Instrs =
744cfca06d7SDimitry Andric       OriginalMF->getFrameInstructions();
7454df029ccSDimitry Andric   for (auto &MI : FirstCand) {
7464df029ccSDimitry Andric     if (MI.isDebugInstr())
747b60736ecSDimitry Andric       continue;
74871d5a254SDimitry Andric 
74971d5a254SDimitry Andric     // Don't keep debug information for outlined instructions.
750145449b1SDimitry Andric     auto DL = DebugLoc();
7514df029ccSDimitry Andric     if (MI.isCFIInstruction()) {
7524df029ccSDimitry Andric       unsigned CFIIndex = MI.getOperand(0).getCFIIndex();
753145449b1SDimitry Andric       MCCFIInstruction CFI = Instrs[CFIIndex];
754145449b1SDimitry Andric       BuildMI(MBB, MBB.end(), DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
755145449b1SDimitry Andric           .addCFIIndex(MF.addFrameInst(CFI));
756145449b1SDimitry Andric     } else {
7574df029ccSDimitry Andric       MachineInstr *NewMI = MF.CloneMachineInstr(&MI);
758145449b1SDimitry Andric       NewMI->dropMemRefs(MF);
759145449b1SDimitry Andric       NewMI->setDebugLoc(DL);
76071d5a254SDimitry Andric       MBB.insert(MBB.end(), NewMI);
76171d5a254SDimitry Andric     }
762145449b1SDimitry Andric   }
76371d5a254SDimitry Andric 
764cfca06d7SDimitry Andric   // Set normal properties for a late MachineFunction.
765cfca06d7SDimitry Andric   MF.getProperties().reset(MachineFunctionProperties::Property::IsSSA);
766cfca06d7SDimitry Andric   MF.getProperties().set(MachineFunctionProperties::Property::NoPHIs);
767cfca06d7SDimitry Andric   MF.getProperties().set(MachineFunctionProperties::Property::NoVRegs);
768cfca06d7SDimitry Andric   MF.getProperties().set(MachineFunctionProperties::Property::TracksLiveness);
769ac9a064cSDimitry Andric   MF.getRegInfo().freezeReservedRegs();
770d8e91e46SDimitry Andric 
771cfca06d7SDimitry Andric   // Compute live-in set for outlined fn
772cfca06d7SDimitry Andric   const MachineRegisterInfo &MRI = MF.getRegInfo();
773cfca06d7SDimitry Andric   const TargetRegisterInfo &TRI = *MRI.getTargetRegisterInfo();
774cfca06d7SDimitry Andric   LivePhysRegs LiveIns(TRI);
775cfca06d7SDimitry Andric   for (auto &Cand : OF.Candidates) {
776cfca06d7SDimitry Andric     // Figure out live-ins at the first instruction.
7774df029ccSDimitry Andric     MachineBasicBlock &OutlineBB = *Cand.front().getParent();
778cfca06d7SDimitry Andric     LivePhysRegs CandLiveIns(TRI);
779cfca06d7SDimitry Andric     CandLiveIns.addLiveOuts(OutlineBB);
780cfca06d7SDimitry Andric     for (const MachineInstr &MI :
7814df029ccSDimitry Andric          reverse(make_range(Cand.begin(), OutlineBB.end())))
782cfca06d7SDimitry Andric       CandLiveIns.stepBackward(MI);
783cfca06d7SDimitry Andric 
784cfca06d7SDimitry Andric     // The live-in set for the outlined function is the union of the live-ins
785cfca06d7SDimitry Andric     // from all the outlining points.
786b60736ecSDimitry Andric     for (MCPhysReg Reg : CandLiveIns)
787cfca06d7SDimitry Andric       LiveIns.addReg(Reg);
788cfca06d7SDimitry Andric   }
789cfca06d7SDimitry Andric   addLiveIns(MBB, LiveIns);
790cfca06d7SDimitry Andric 
791cfca06d7SDimitry Andric   TII.buildOutlinedFrame(MBB, MF, OF);
792cfca06d7SDimitry Andric 
793eb11fae6SDimitry Andric   // If there's a DISubprogram associated with this outlined function, then
794eb11fae6SDimitry Andric   // emit debug info for the outlined function.
795eb11fae6SDimitry Andric   if (DISubprogram *SP = getSubprogramOrNull(OF)) {
796eb11fae6SDimitry Andric     // We have a DISubprogram. Get its DICompileUnit.
797eb11fae6SDimitry Andric     DICompileUnit *CU = SP->getUnit();
798eb11fae6SDimitry Andric     DIBuilder DB(M, true, CU);
799eb11fae6SDimitry Andric     DIFile *Unit = SP->getFile();
800eb11fae6SDimitry Andric     Mangler Mg;
801eb11fae6SDimitry Andric     // Get the mangled name of the function for the linkage name.
802eb11fae6SDimitry Andric     std::string Dummy;
8037fa27ce4SDimitry Andric     raw_string_ostream MangledNameStream(Dummy);
804eb11fae6SDimitry Andric     Mg.getNameWithPrefix(MangledNameStream, F, false);
805eb11fae6SDimitry Andric 
806d8e91e46SDimitry Andric     DISubprogram *OutlinedSP = DB.createFunction(
807ac9a064cSDimitry Andric         Unit /* Context */, F->getName(), StringRef(Dummy), Unit /* File */,
808eb11fae6SDimitry Andric         0 /* Line 0 is reserved for compiler-generated code. */,
809e3b55780SDimitry Andric         DB.createSubroutineType(
810e3b55780SDimitry Andric             DB.getOrCreateTypeArray(std::nullopt)), /* void type */
811d8e91e46SDimitry Andric         0, /* Line 0 is reserved for compiler-generated code. */
812eb11fae6SDimitry Andric         DINode::DIFlags::FlagArtificial /* Compiler-generated code. */,
813d8e91e46SDimitry Andric         /* Outlined code is optimized code by definition. */
814d8e91e46SDimitry Andric         DISubprogram::SPFlagDefinition | DISubprogram::SPFlagOptimized);
815eb11fae6SDimitry Andric 
816eb11fae6SDimitry Andric     // Don't add any new variables to the subprogram.
817d8e91e46SDimitry Andric     DB.finalizeSubprogram(OutlinedSP);
818eb11fae6SDimitry Andric 
819eb11fae6SDimitry Andric     // Attach subprogram to the function.
820d8e91e46SDimitry Andric     F->setSubprogram(OutlinedSP);
821eb11fae6SDimitry Andric     // We're done with the DIBuilder.
822eb11fae6SDimitry Andric     DB.finalize();
823eb11fae6SDimitry Andric   }
824eb11fae6SDimitry Andric 
82571d5a254SDimitry Andric   return &MF;
82671d5a254SDimitry Andric }
82771d5a254SDimitry Andric 
outline(Module & M,std::vector<OutlinedFunction> & FunctionList,InstructionMapper & Mapper,unsigned & OutlinedFunctionNum)828d8e91e46SDimitry Andric bool MachineOutliner::outline(Module &M,
829d8e91e46SDimitry Andric                               std::vector<OutlinedFunction> &FunctionList,
830706b4fc4SDimitry Andric                               InstructionMapper &Mapper,
831706b4fc4SDimitry Andric                               unsigned &OutlinedFunctionNum) {
8327fa27ce4SDimitry Andric   LLVM_DEBUG(dbgs() << "*** Outlining ***\n");
8337fa27ce4SDimitry Andric   LLVM_DEBUG(dbgs() << "NUMBER OF POTENTIAL FUNCTIONS: " << FunctionList.size()
8347fa27ce4SDimitry Andric                     << "\n");
83571d5a254SDimitry Andric   bool OutlinedSomething = false;
83671d5a254SDimitry Andric 
837ac9a064cSDimitry Andric   // Sort by priority where priority := getNotOutlinedCost / getOutliningCost.
838ac9a064cSDimitry Andric   // The function with highest priority should be outlined first.
8397fa27ce4SDimitry Andric   stable_sort(FunctionList,
8407fa27ce4SDimitry Andric               [](const OutlinedFunction &LHS, const OutlinedFunction &RHS) {
841ac9a064cSDimitry Andric                 return LHS.getNotOutlinedCost() * RHS.getOutliningCost() >
842ac9a064cSDimitry Andric                        RHS.getNotOutlinedCost() * LHS.getOutliningCost();
843d8e91e46SDimitry Andric               });
844d8e91e46SDimitry Andric 
845d8e91e46SDimitry Andric   // Walk over each function, outlining them as we go along. Functions are
846d8e91e46SDimitry Andric   // outlined greedily, based off the sort above.
8477fa27ce4SDimitry Andric   auto *UnsignedVecBegin = Mapper.UnsignedVec.begin();
8487fa27ce4SDimitry Andric   LLVM_DEBUG(dbgs() << "WALKING FUNCTION LIST\n");
849d8e91e46SDimitry Andric   for (OutlinedFunction &OF : FunctionList) {
8507fa27ce4SDimitry Andric #ifndef NDEBUG
8517fa27ce4SDimitry Andric     auto NumCandidatesBefore = OF.Candidates.size();
8527fa27ce4SDimitry Andric #endif
853d8e91e46SDimitry Andric     // If we outlined something that overlapped with a candidate in a previous
854d8e91e46SDimitry Andric     // step, then we can't outline from it.
8557fa27ce4SDimitry Andric     erase_if(OF.Candidates, [&UnsignedVecBegin](Candidate &C) {
8567fa27ce4SDimitry Andric       return std::any_of(UnsignedVecBegin + C.getStartIdx(),
8577fa27ce4SDimitry Andric                          UnsignedVecBegin + C.getEndIdx() + 1, [](unsigned I) {
8587fa27ce4SDimitry Andric                            return I == static_cast<unsigned>(-1);
8597fa27ce4SDimitry Andric                          });
860d8e91e46SDimitry Andric     });
861d8e91e46SDimitry Andric 
8627fa27ce4SDimitry Andric #ifndef NDEBUG
8637fa27ce4SDimitry Andric     auto NumCandidatesAfter = OF.Candidates.size();
8647fa27ce4SDimitry Andric     LLVM_DEBUG(dbgs() << "PRUNED: " << NumCandidatesBefore - NumCandidatesAfter
8657fa27ce4SDimitry Andric                       << "/" << NumCandidatesBefore << " candidates\n");
8667fa27ce4SDimitry Andric #endif
8677fa27ce4SDimitry Andric 
868d8e91e46SDimitry Andric     // If we made it unbeneficial to outline this function, skip it.
8697fa27ce4SDimitry Andric     if (OF.getBenefit() < OutlinerBenefitThreshold) {
8707fa27ce4SDimitry Andric       LLVM_DEBUG(dbgs() << "SKIP: Expected benefit (" << OF.getBenefit()
8717fa27ce4SDimitry Andric                         << " B) < threshold (" << OutlinerBenefitThreshold
8727fa27ce4SDimitry Andric                         << " B)\n");
87371d5a254SDimitry Andric       continue;
8747fa27ce4SDimitry Andric     }
8757fa27ce4SDimitry Andric 
8767fa27ce4SDimitry Andric     LLVM_DEBUG(dbgs() << "OUTLINE: Expected benefit (" << OF.getBenefit()
8777fa27ce4SDimitry Andric                       << " B) > threshold (" << OutlinerBenefitThreshold
8787fa27ce4SDimitry Andric                       << " B)\n");
87971d5a254SDimitry Andric 
880d8e91e46SDimitry Andric     // It's beneficial. Create the function and outline its sequence's
881d8e91e46SDimitry Andric     // occurrences.
882d8e91e46SDimitry Andric     OF.MF = createOutlinedFunction(M, OF, Mapper, OutlinedFunctionNum);
883eb11fae6SDimitry Andric     emitOutlinedFunctionRemark(OF);
88471d5a254SDimitry Andric     FunctionsCreated++;
885d8e91e46SDimitry Andric     OutlinedFunctionNum++; // Created a function, move to the next name.
88671d5a254SDimitry Andric     MachineFunction *MF = OF.MF;
88771d5a254SDimitry Andric     const TargetSubtargetInfo &STI = MF->getSubtarget();
88871d5a254SDimitry Andric     const TargetInstrInfo &TII = *STI.getInstrInfo();
88971d5a254SDimitry Andric 
890d8e91e46SDimitry Andric     // Replace occurrences of the sequence with calls to the new function.
8917fa27ce4SDimitry Andric     LLVM_DEBUG(dbgs() << "CREATE OUTLINED CALLS\n");
892d8e91e46SDimitry Andric     for (Candidate &C : OF.Candidates) {
893d8e91e46SDimitry Andric       MachineBasicBlock &MBB = *C.getMBB();
8944df029ccSDimitry Andric       MachineBasicBlock::iterator StartIt = C.begin();
8954df029ccSDimitry Andric       MachineBasicBlock::iterator EndIt = std::prev(C.end());
89671d5a254SDimitry Andric 
897d8e91e46SDimitry Andric       // Insert the call.
898d8e91e46SDimitry Andric       auto CallInst = TII.insertOutlinedCall(M, MBB, StartIt, *MF, C);
8997fa27ce4SDimitry Andric // Insert the call.
9007fa27ce4SDimitry Andric #ifndef NDEBUG
9017fa27ce4SDimitry Andric       auto MBBBeingOutlinedFromName =
9027fa27ce4SDimitry Andric           MBB.getName().empty() ? "<unknown>" : MBB.getName().str();
9037fa27ce4SDimitry Andric       auto MFBeingOutlinedFromName = MBB.getParent()->getName().empty()
9047fa27ce4SDimitry Andric                                          ? "<unknown>"
9057fa27ce4SDimitry Andric                                          : MBB.getParent()->getName().str();
9067fa27ce4SDimitry Andric       LLVM_DEBUG(dbgs() << "  CALL: " << MF->getName() << " in "
9077fa27ce4SDimitry Andric                         << MFBeingOutlinedFromName << ":"
9087fa27ce4SDimitry Andric                         << MBBBeingOutlinedFromName << "\n");
9097fa27ce4SDimitry Andric       LLVM_DEBUG(dbgs() << "   .. " << *CallInst);
9107fa27ce4SDimitry Andric #endif
911d8e91e46SDimitry Andric 
912d8e91e46SDimitry Andric       // If the caller tracks liveness, then we need to make sure that
913d8e91e46SDimitry Andric       // anything we outline doesn't break liveness assumptions. The outlined
914d8e91e46SDimitry Andric       // functions themselves currently don't track liveness, but we should
915d8e91e46SDimitry Andric       // make sure that the ranges we yank things out of aren't wrong.
916eb11fae6SDimitry Andric       if (MBB.getParent()->getProperties().hasProperty(
917eb11fae6SDimitry Andric               MachineFunctionProperties::Property::TracksLiveness)) {
918cfca06d7SDimitry Andric         // The following code is to add implicit def operands to the call
919e6d15924SDimitry Andric         // instruction. It also updates call site information for moved
920e6d15924SDimitry Andric         // code.
921cfca06d7SDimitry Andric         SmallSet<Register, 2> UseRegs, DefRegs;
922eb11fae6SDimitry Andric         // Copy over the defs in the outlined range.
923eb11fae6SDimitry Andric         // First inst in outlined range <-- Anything that's defined in this
924d8e91e46SDimitry Andric         // ...                           .. range has to be added as an
925d8e91e46SDimitry Andric         // implicit Last inst in outlined range  <-- def to the call
926e6d15924SDimitry Andric         // instruction. Also remove call site information for outlined block
927cfca06d7SDimitry Andric         // of code. The exposed uses need to be copied in the outlined range.
928cfca06d7SDimitry Andric         for (MachineBasicBlock::reverse_iterator
929cfca06d7SDimitry Andric                  Iter = EndIt.getReverse(),
930cfca06d7SDimitry Andric                  Last = std::next(CallInst.getReverse());
931cfca06d7SDimitry Andric              Iter != Last; Iter++) {
932cfca06d7SDimitry Andric           MachineInstr *MI = &*Iter;
933c0981da4SDimitry Andric           SmallSet<Register, 2> InstrUseRegs;
934cfca06d7SDimitry Andric           for (MachineOperand &MOP : MI->operands()) {
935cfca06d7SDimitry Andric             // Skip over anything that isn't a register.
936cfca06d7SDimitry Andric             if (!MOP.isReg())
937cfca06d7SDimitry Andric               continue;
938cfca06d7SDimitry Andric 
939cfca06d7SDimitry Andric             if (MOP.isDef()) {
940cfca06d7SDimitry Andric               // Introduce DefRegs set to skip the redundant register.
941cfca06d7SDimitry Andric               DefRegs.insert(MOP.getReg());
942c0981da4SDimitry Andric               if (UseRegs.count(MOP.getReg()) &&
943c0981da4SDimitry Andric                   !InstrUseRegs.count(MOP.getReg()))
944cfca06d7SDimitry Andric                 // Since the regiester is modeled as defined,
945cfca06d7SDimitry Andric                 // it is not necessary to be put in use register set.
946cfca06d7SDimitry Andric                 UseRegs.erase(MOP.getReg());
947cfca06d7SDimitry Andric             } else if (!MOP.isUndef()) {
948cfca06d7SDimitry Andric               // Any register which is not undefined should
949cfca06d7SDimitry Andric               // be put in the use register set.
950cfca06d7SDimitry Andric               UseRegs.insert(MOP.getReg());
951c0981da4SDimitry Andric               InstrUseRegs.insert(MOP.getReg());
952cfca06d7SDimitry Andric             }
953cfca06d7SDimitry Andric           }
954cfca06d7SDimitry Andric           if (MI->isCandidateForCallSiteEntry())
955cfca06d7SDimitry Andric             MI->getMF()->eraseCallSiteInfo(MI);
956cfca06d7SDimitry Andric         }
957cfca06d7SDimitry Andric 
958cfca06d7SDimitry Andric         for (const Register &I : DefRegs)
959cfca06d7SDimitry Andric           // If it's a def, add it to the call instruction.
960cfca06d7SDimitry Andric           CallInst->addOperand(
961cfca06d7SDimitry Andric               MachineOperand::CreateReg(I, true, /* isDef = true */
962cfca06d7SDimitry Andric                                         true /* isImp = true */));
963cfca06d7SDimitry Andric 
964cfca06d7SDimitry Andric         for (const Register &I : UseRegs)
965cfca06d7SDimitry Andric           // If it's a exposed use, add it to the call instruction.
966cfca06d7SDimitry Andric           CallInst->addOperand(
967cfca06d7SDimitry Andric               MachineOperand::CreateReg(I, false, /* isDef = false */
968cfca06d7SDimitry Andric                                         true /* isImp = true */));
969eb11fae6SDimitry Andric       }
970eb11fae6SDimitry Andric 
971eb11fae6SDimitry Andric       // Erase from the point after where the call was inserted up to, and
972eb11fae6SDimitry Andric       // including, the final instruction in the sequence.
973eb11fae6SDimitry Andric       // Erase needs one past the end, so we need std::next there too.
974eb11fae6SDimitry Andric       MBB.erase(std::next(StartIt), std::next(EndIt));
975d8e91e46SDimitry Andric 
976d8e91e46SDimitry Andric       // Keep track of what we removed by marking them all as -1.
9777fa27ce4SDimitry Andric       for (unsigned &I : make_range(UnsignedVecBegin + C.getStartIdx(),
9787fa27ce4SDimitry Andric                                     UnsignedVecBegin + C.getEndIdx() + 1))
979145449b1SDimitry Andric         I = static_cast<unsigned>(-1);
98071d5a254SDimitry Andric       OutlinedSomething = true;
98171d5a254SDimitry Andric 
98271d5a254SDimitry Andric       // Statistics.
98371d5a254SDimitry Andric       NumOutlined++;
98471d5a254SDimitry Andric     }
985d8e91e46SDimitry Andric   }
98671d5a254SDimitry Andric 
987eb11fae6SDimitry Andric   LLVM_DEBUG(dbgs() << "OutlinedSomething = " << OutlinedSomething << "\n";);
98871d5a254SDimitry Andric   return OutlinedSomething;
98971d5a254SDimitry Andric }
99071d5a254SDimitry Andric 
populateMapper(InstructionMapper & Mapper,Module & M,MachineModuleInfo & MMI)991d8e91e46SDimitry Andric void MachineOutliner::populateMapper(InstructionMapper &Mapper, Module &M,
992d8e91e46SDimitry Andric                                      MachineModuleInfo &MMI) {
993eb11fae6SDimitry Andric   // Build instruction mappings for each function in the module. Start by
994eb11fae6SDimitry Andric   // iterating over each Function in M.
9957fa27ce4SDimitry Andric   LLVM_DEBUG(dbgs() << "*** Populating mapper ***\n");
99671d5a254SDimitry Andric   for (Function &F : M) {
9977fa27ce4SDimitry Andric     LLVM_DEBUG(dbgs() << "MAPPING FUNCTION: " << F.getName() << "\n");
99871d5a254SDimitry Andric 
999e3b55780SDimitry Andric     if (F.hasFnAttribute("nooutline")) {
10007fa27ce4SDimitry Andric       LLVM_DEBUG(dbgs() << "SKIP: Function has nooutline attribute\n");
100171d5a254SDimitry Andric       continue;
1002e3b55780SDimitry Andric     }
100371d5a254SDimitry Andric 
1004eb11fae6SDimitry Andric     // There's something in F. Check if it has a MachineFunction associated with
1005eb11fae6SDimitry Andric     // it.
1006eb11fae6SDimitry Andric     MachineFunction *MF = MMI.getMachineFunction(F);
100771d5a254SDimitry Andric 
1008eb11fae6SDimitry Andric     // If it doesn't, then there's nothing to outline from. Move to the next
1009eb11fae6SDimitry Andric     // Function.
10107fa27ce4SDimitry Andric     if (!MF) {
10117fa27ce4SDimitry Andric       LLVM_DEBUG(dbgs() << "SKIP: Function does not have a MachineFunction\n");
1012eb11fae6SDimitry Andric       continue;
10137fa27ce4SDimitry Andric     }
1014eb11fae6SDimitry Andric 
1015b7eb8e35SDimitry Andric     const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
10167fa27ce4SDimitry Andric     if (!RunOnAllFunctions && !TII->shouldOutlineFromFunctionByDefault(*MF)) {
10177fa27ce4SDimitry Andric       LLVM_DEBUG(dbgs() << "SKIP: Target does not want to outline from "
10187fa27ce4SDimitry Andric                            "function by default\n");
1019eb11fae6SDimitry Andric       continue;
10207fa27ce4SDimitry Andric     }
1021eb11fae6SDimitry Andric 
1022eb11fae6SDimitry Andric     // We have a MachineFunction. Ask the target if it's suitable for outlining.
1023eb11fae6SDimitry Andric     // If it isn't, then move on to the next Function in the module.
10247fa27ce4SDimitry Andric     if (!TII->isFunctionSafeToOutlineFrom(*MF, OutlineFromLinkOnceODRs)) {
10257fa27ce4SDimitry Andric       LLVM_DEBUG(dbgs() << "SKIP: " << MF->getName()
10267fa27ce4SDimitry Andric                         << ": unsafe to outline from\n");
1027eb11fae6SDimitry Andric       continue;
10287fa27ce4SDimitry Andric     }
1029eb11fae6SDimitry Andric 
1030eb11fae6SDimitry Andric     // We have a function suitable for outlining. Iterate over every
1031eb11fae6SDimitry Andric     // MachineBasicBlock in MF and try to map its instructions to a list of
1032eb11fae6SDimitry Andric     // unsigned integers.
10337fa27ce4SDimitry Andric     const unsigned MinMBBSize = 2;
10347fa27ce4SDimitry Andric 
1035eb11fae6SDimitry Andric     for (MachineBasicBlock &MBB : *MF) {
10367fa27ce4SDimitry Andric       LLVM_DEBUG(dbgs() << "  MAPPING MBB: '" << MBB.getName() << "'\n");
1037eb11fae6SDimitry Andric       // If there isn't anything in MBB, then there's no point in outlining from
1038eb11fae6SDimitry Andric       // it.
1039d8e91e46SDimitry Andric       // If there are fewer than 2 instructions in the MBB, then it can't ever
1040d8e91e46SDimitry Andric       // contain something worth outlining.
1041d8e91e46SDimitry Andric       // FIXME: This should be based off of the maximum size in B of an outlined
1042d8e91e46SDimitry Andric       // call versus the size in B of the MBB.
10437fa27ce4SDimitry Andric       if (MBB.size() < MinMBBSize) {
10447fa27ce4SDimitry Andric         LLVM_DEBUG(dbgs() << "    SKIP: MBB size less than minimum size of "
10457fa27ce4SDimitry Andric                           << MinMBBSize << "\n");
104671d5a254SDimitry Andric         continue;
10477fa27ce4SDimitry Andric       }
104871d5a254SDimitry Andric 
1049eb11fae6SDimitry Andric       // Check if MBB could be the target of an indirect branch. If it is, then
1050eb11fae6SDimitry Andric       // we don't want to outline from it.
10517fa27ce4SDimitry Andric       if (MBB.hasAddressTaken()) {
10527fa27ce4SDimitry Andric         LLVM_DEBUG(dbgs() << "    SKIP: MBB's address is taken\n");
1053eb11fae6SDimitry Andric         continue;
10547fa27ce4SDimitry Andric       }
1055eb11fae6SDimitry Andric 
1056eb11fae6SDimitry Andric       // MBB is suitable for outlining. Map it to a list of unsigneds.
1057b7eb8e35SDimitry Andric       Mapper.convertToUnsignedVec(MBB, *TII);
105871d5a254SDimitry Andric     }
10597fa27ce4SDimitry Andric   }
1060145449b1SDimitry Andric   // Statistics.
1061145449b1SDimitry Andric   UnsignedVecSize = Mapper.UnsignedVec.size();
106271d5a254SDimitry Andric }
106371d5a254SDimitry Andric 
initSizeRemarkInfo(const Module & M,const MachineModuleInfo & MMI,StringMap<unsigned> & FunctionToInstrCount)1064d8e91e46SDimitry Andric void MachineOutliner::initSizeRemarkInfo(
1065d8e91e46SDimitry Andric     const Module &M, const MachineModuleInfo &MMI,
1066d8e91e46SDimitry Andric     StringMap<unsigned> &FunctionToInstrCount) {
1067d8e91e46SDimitry Andric   // Collect instruction counts for every function. We'll use this to emit
1068d8e91e46SDimitry Andric   // per-function size remarks later.
1069d8e91e46SDimitry Andric   for (const Function &F : M) {
1070d8e91e46SDimitry Andric     MachineFunction *MF = MMI.getMachineFunction(F);
1071d8e91e46SDimitry Andric 
1072d8e91e46SDimitry Andric     // We only care about MI counts here. If there's no MachineFunction at this
1073d8e91e46SDimitry Andric     // point, then there won't be after the outliner runs, so let's move on.
1074d8e91e46SDimitry Andric     if (!MF)
1075d8e91e46SDimitry Andric       continue;
1076d8e91e46SDimitry Andric     FunctionToInstrCount[F.getName().str()] = MF->getInstructionCount();
1077d8e91e46SDimitry Andric   }
1078d8e91e46SDimitry Andric }
1079d8e91e46SDimitry Andric 
emitInstrCountChangedRemark(const Module & M,const MachineModuleInfo & MMI,const StringMap<unsigned> & FunctionToInstrCount)1080d8e91e46SDimitry Andric void MachineOutliner::emitInstrCountChangedRemark(
1081d8e91e46SDimitry Andric     const Module &M, const MachineModuleInfo &MMI,
1082d8e91e46SDimitry Andric     const StringMap<unsigned> &FunctionToInstrCount) {
1083d8e91e46SDimitry Andric   // Iterate over each function in the module and emit remarks.
1084d8e91e46SDimitry Andric   // Note that we won't miss anything by doing this, because the outliner never
1085d8e91e46SDimitry Andric   // deletes functions.
1086d8e91e46SDimitry Andric   for (const Function &F : M) {
1087d8e91e46SDimitry Andric     MachineFunction *MF = MMI.getMachineFunction(F);
1088d8e91e46SDimitry Andric 
1089d8e91e46SDimitry Andric     // The outliner never deletes functions. If we don't have a MF here, then we
1090d8e91e46SDimitry Andric     // didn't have one prior to outlining either.
1091d8e91e46SDimitry Andric     if (!MF)
1092d8e91e46SDimitry Andric       continue;
1093d8e91e46SDimitry Andric 
1094cfca06d7SDimitry Andric     std::string Fname = std::string(F.getName());
1095d8e91e46SDimitry Andric     unsigned FnCountAfter = MF->getInstructionCount();
1096d8e91e46SDimitry Andric     unsigned FnCountBefore = 0;
1097d8e91e46SDimitry Andric 
1098d8e91e46SDimitry Andric     // Check if the function was recorded before.
1099d8e91e46SDimitry Andric     auto It = FunctionToInstrCount.find(Fname);
1100d8e91e46SDimitry Andric 
1101d8e91e46SDimitry Andric     // Did we have a previously-recorded size? If yes, then set FnCountBefore
1102d8e91e46SDimitry Andric     // to that.
1103d8e91e46SDimitry Andric     if (It != FunctionToInstrCount.end())
1104d8e91e46SDimitry Andric       FnCountBefore = It->second;
1105d8e91e46SDimitry Andric 
1106d8e91e46SDimitry Andric     // Compute the delta and emit a remark if there was a change.
1107d8e91e46SDimitry Andric     int64_t FnDelta = static_cast<int64_t>(FnCountAfter) -
1108d8e91e46SDimitry Andric                       static_cast<int64_t>(FnCountBefore);
1109d8e91e46SDimitry Andric     if (FnDelta == 0)
1110d8e91e46SDimitry Andric       continue;
1111d8e91e46SDimitry Andric 
1112d8e91e46SDimitry Andric     MachineOptimizationRemarkEmitter MORE(*MF, nullptr);
1113d8e91e46SDimitry Andric     MORE.emit([&]() {
1114d8e91e46SDimitry Andric       MachineOptimizationRemarkAnalysis R("size-info", "FunctionMISizeChange",
1115706b4fc4SDimitry Andric                                           DiagnosticLocation(), &MF->front());
1116d8e91e46SDimitry Andric       R << DiagnosticInfoOptimizationBase::Argument("Pass", "Machine Outliner")
1117d8e91e46SDimitry Andric         << ": Function: "
1118d8e91e46SDimitry Andric         << DiagnosticInfoOptimizationBase::Argument("Function", F.getName())
1119d8e91e46SDimitry Andric         << ": MI instruction count changed from "
1120d8e91e46SDimitry Andric         << DiagnosticInfoOptimizationBase::Argument("MIInstrsBefore",
1121d8e91e46SDimitry Andric                                                     FnCountBefore)
1122d8e91e46SDimitry Andric         << " to "
1123d8e91e46SDimitry Andric         << DiagnosticInfoOptimizationBase::Argument("MIInstrsAfter",
1124d8e91e46SDimitry Andric                                                     FnCountAfter)
1125d8e91e46SDimitry Andric         << "; Delta: "
1126d8e91e46SDimitry Andric         << DiagnosticInfoOptimizationBase::Argument("Delta", FnDelta);
1127d8e91e46SDimitry Andric       return R;
1128d8e91e46SDimitry Andric     });
1129d8e91e46SDimitry Andric   }
1130d8e91e46SDimitry Andric }
1131d8e91e46SDimitry Andric 
runOnModule(Module & M)1132d8e91e46SDimitry Andric bool MachineOutliner::runOnModule(Module &M) {
1133d8e91e46SDimitry Andric   // Check if there's anything in the module. If it's empty, then there's
1134d8e91e46SDimitry Andric   // nothing to outline.
1135d8e91e46SDimitry Andric   if (M.empty())
1136d8e91e46SDimitry Andric     return false;
1137d8e91e46SDimitry Andric 
1138706b4fc4SDimitry Andric   // Number to append to the current outlined function.
1139706b4fc4SDimitry Andric   unsigned OutlinedFunctionNum = 0;
1140706b4fc4SDimitry Andric 
1141cfca06d7SDimitry Andric   OutlineRepeatedNum = 0;
1142706b4fc4SDimitry Andric   if (!doOutline(M, OutlinedFunctionNum))
1143706b4fc4SDimitry Andric     return false;
1144cfca06d7SDimitry Andric 
1145cfca06d7SDimitry Andric   for (unsigned I = 0; I < OutlinerReruns; ++I) {
1146cfca06d7SDimitry Andric     OutlinedFunctionNum = 0;
1147cfca06d7SDimitry Andric     OutlineRepeatedNum++;
1148cfca06d7SDimitry Andric     if (!doOutline(M, OutlinedFunctionNum)) {
1149cfca06d7SDimitry Andric       LLVM_DEBUG({
1150cfca06d7SDimitry Andric         dbgs() << "Did not outline on iteration " << I + 2 << " out of "
1151cfca06d7SDimitry Andric                << OutlinerReruns + 1 << "\n";
1152cfca06d7SDimitry Andric       });
1153cfca06d7SDimitry Andric       break;
1154cfca06d7SDimitry Andric     }
1155cfca06d7SDimitry Andric   }
1156cfca06d7SDimitry Andric 
1157706b4fc4SDimitry Andric   return true;
1158706b4fc4SDimitry Andric }
1159706b4fc4SDimitry Andric 
doOutline(Module & M,unsigned & OutlinedFunctionNum)1160706b4fc4SDimitry Andric bool MachineOutliner::doOutline(Module &M, unsigned &OutlinedFunctionNum) {
11611d5ae102SDimitry Andric   MachineModuleInfo &MMI = getAnalysis<MachineModuleInfoWrapperPass>().getMMI();
1162d8e91e46SDimitry Andric 
1163d8e91e46SDimitry Andric   // If the user passed -enable-machine-outliner=always or
1164d8e91e46SDimitry Andric   // -enable-machine-outliner, the pass will run on all functions in the module.
1165d8e91e46SDimitry Andric   // Otherwise, if the target supports default outlining, it will run on all
1166d8e91e46SDimitry Andric   // functions deemed by the target to be worth outlining from by default. Tell
1167d8e91e46SDimitry Andric   // the user how the outliner is running.
1168706b4fc4SDimitry Andric   LLVM_DEBUG({
1169d8e91e46SDimitry Andric     dbgs() << "Machine Outliner: Running on ";
1170d8e91e46SDimitry Andric     if (RunOnAllFunctions)
1171d8e91e46SDimitry Andric       dbgs() << "all functions";
1172d8e91e46SDimitry Andric     else
1173d8e91e46SDimitry Andric       dbgs() << "target-default functions";
1174706b4fc4SDimitry Andric     dbgs() << "\n";
1175706b4fc4SDimitry Andric   });
1176d8e91e46SDimitry Andric 
1177d8e91e46SDimitry Andric   // If the user specifies that they want to outline from linkonceodrs, set
1178d8e91e46SDimitry Andric   // it here.
1179d8e91e46SDimitry Andric   OutlineFromLinkOnceODRs = EnableLinkOnceODROutlining;
1180d8e91e46SDimitry Andric   InstructionMapper Mapper;
1181d8e91e46SDimitry Andric 
1182d8e91e46SDimitry Andric   // Prepare instruction mappings for the suffix tree.
1183d8e91e46SDimitry Andric   populateMapper(Mapper, M, MMI);
118471d5a254SDimitry Andric   std::vector<OutlinedFunction> FunctionList;
118571d5a254SDimitry Andric 
118671d5a254SDimitry Andric   // Find all of the outlining candidates.
1187d8e91e46SDimitry Andric   findCandidates(Mapper, FunctionList);
118871d5a254SDimitry Andric 
1189d8e91e46SDimitry Andric   // If we've requested size remarks, then collect the MI counts of every
1190d8e91e46SDimitry Andric   // function before outlining, and the MI counts after outlining.
1191d8e91e46SDimitry Andric   // FIXME: This shouldn't be in the outliner at all; it should ultimately be
1192d8e91e46SDimitry Andric   // the pass manager's responsibility.
1193d8e91e46SDimitry Andric   // This could pretty easily be placed in outline instead, but because we
1194d8e91e46SDimitry Andric   // really ultimately *don't* want this here, it's done like this for now
1195d8e91e46SDimitry Andric   // instead.
1196d8e91e46SDimitry Andric 
1197d8e91e46SDimitry Andric   // Check if we want size remarks.
1198d8e91e46SDimitry Andric   bool ShouldEmitSizeRemarks = M.shouldEmitInstrCountChangedRemark();
1199d8e91e46SDimitry Andric   StringMap<unsigned> FunctionToInstrCount;
1200d8e91e46SDimitry Andric   if (ShouldEmitSizeRemarks)
1201d8e91e46SDimitry Andric     initSizeRemarkInfo(M, MMI, FunctionToInstrCount);
120271d5a254SDimitry Andric 
120371d5a254SDimitry Andric   // Outline each of the candidates and return true if something was outlined.
1204706b4fc4SDimitry Andric   bool OutlinedSomething =
1205706b4fc4SDimitry Andric       outline(M, FunctionList, Mapper, OutlinedFunctionNum);
1206d8e91e46SDimitry Andric 
1207d8e91e46SDimitry Andric   // If we outlined something, we definitely changed the MI count of the
1208d8e91e46SDimitry Andric   // module. If we've asked for size remarks, then output them.
1209d8e91e46SDimitry Andric   // FIXME: This should be in the pass manager.
1210d8e91e46SDimitry Andric   if (ShouldEmitSizeRemarks && OutlinedSomething)
1211d8e91e46SDimitry Andric     emitInstrCountChangedRemark(M, MMI, FunctionToInstrCount);
1212eb11fae6SDimitry Andric 
1213cfca06d7SDimitry Andric   LLVM_DEBUG({
1214cfca06d7SDimitry Andric     if (!OutlinedSomething)
1215cfca06d7SDimitry Andric       dbgs() << "Stopped outlining at iteration " << OutlineRepeatedNum
1216cfca06d7SDimitry Andric              << " because no changes were found.\n";
1217cfca06d7SDimitry Andric   });
1218cfca06d7SDimitry Andric 
1219eb11fae6SDimitry Andric   return OutlinedSomething;
122071d5a254SDimitry Andric }
1221