xref: /freebsd-src/contrib/llvm-project/llvm/lib/CodeGen/MachineOutliner.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
10b57cec5SDimitry Andric //===---- MachineOutliner.cpp - Outline instructions -----------*- C++ -*-===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric ///
90b57cec5SDimitry Andric /// \file
100b57cec5SDimitry Andric /// Replaces repeated sequences of instructions with function calls.
110b57cec5SDimitry Andric ///
120b57cec5SDimitry Andric /// This works by placing every instruction from every basic block in a
130b57cec5SDimitry Andric /// suffix tree, and repeatedly querying that tree for repeated sequences of
140b57cec5SDimitry Andric /// instructions. If a sequence of instructions appears often, then it ought
150b57cec5SDimitry Andric /// to be beneficial to pull out into a function.
160b57cec5SDimitry Andric ///
170b57cec5SDimitry Andric /// The MachineOutliner communicates with a given target using hooks defined in
180b57cec5SDimitry Andric /// TargetInstrInfo.h. The target supplies the outliner with information on how
190b57cec5SDimitry Andric /// a specific sequence of instructions should be outlined. This information
200b57cec5SDimitry Andric /// is used to deduce the number of instructions necessary to
210b57cec5SDimitry Andric ///
220b57cec5SDimitry Andric /// * Create an outlined function
230b57cec5SDimitry Andric /// * Call that outlined function
240b57cec5SDimitry Andric ///
250b57cec5SDimitry Andric /// Targets must implement
260b57cec5SDimitry Andric ///   * getOutliningCandidateInfo
270b57cec5SDimitry Andric ///   * buildOutlinedFrame
280b57cec5SDimitry Andric ///   * insertOutlinedCall
290b57cec5SDimitry Andric ///   * isFunctionSafeToOutlineFrom
300b57cec5SDimitry Andric ///
310b57cec5SDimitry Andric /// in order to make use of the MachineOutliner.
320b57cec5SDimitry Andric ///
330b57cec5SDimitry Andric /// This was originally presented at the 2016 LLVM Developers' Meeting in the
340b57cec5SDimitry Andric /// talk "Reducing Code Size Using Outlining". For a high-level overview of
350b57cec5SDimitry Andric /// how this pass works, the talk is available on YouTube at
360b57cec5SDimitry Andric ///
370b57cec5SDimitry Andric /// https://www.youtube.com/watch?v=yorld-WSOeU
380b57cec5SDimitry Andric ///
390b57cec5SDimitry Andric /// The slides for the talk are available at
400b57cec5SDimitry Andric ///
410b57cec5SDimitry Andric /// http://www.llvm.org/devmtg/2016-11/Slides/Paquette-Outliner.pdf
420b57cec5SDimitry Andric ///
430b57cec5SDimitry Andric /// The talk provides an overview of how the outliner finds candidates and
440b57cec5SDimitry Andric /// ultimately outlines them. It describes how the main data structure for this
450b57cec5SDimitry Andric /// pass, the suffix tree, is queried and purged for candidates. It also gives
460b57cec5SDimitry Andric /// a simplified suffix tree construction algorithm for suffix trees based off
470b57cec5SDimitry Andric /// of the algorithm actually used here, Ukkonen's algorithm.
480b57cec5SDimitry Andric ///
490b57cec5SDimitry Andric /// For the original RFC for this pass, please see
500b57cec5SDimitry Andric ///
510b57cec5SDimitry Andric /// http://lists.llvm.org/pipermail/llvm-dev/2016-August/104170.html
520b57cec5SDimitry Andric ///
530b57cec5SDimitry Andric /// For more information on the suffix tree data structure, please see
540b57cec5SDimitry Andric /// https://www.cs.helsinki.fi/u/ukkonen/SuffixT1withFigs.pdf
550b57cec5SDimitry Andric ///
560b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
570b57cec5SDimitry Andric #include "llvm/CodeGen/MachineOutliner.h"
580b57cec5SDimitry Andric #include "llvm/ADT/DenseMap.h"
595ffd83dbSDimitry Andric #include "llvm/ADT/SmallSet.h"
600b57cec5SDimitry Andric #include "llvm/ADT/Statistic.h"
610b57cec5SDimitry Andric #include "llvm/ADT/Twine.h"
6281ad6265SDimitry Andric #include "llvm/Analysis/OptimizationRemarkEmitter.h"
6381ad6265SDimitry Andric #include "llvm/CodeGen/LivePhysRegs.h"
640b57cec5SDimitry Andric #include "llvm/CodeGen/MachineModuleInfo.h"
650b57cec5SDimitry Andric #include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h"
660b57cec5SDimitry Andric #include "llvm/CodeGen/Passes.h"
670b57cec5SDimitry Andric #include "llvm/CodeGen/TargetInstrInfo.h"
680b57cec5SDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h"
690b57cec5SDimitry Andric #include "llvm/IR/DIBuilder.h"
700b57cec5SDimitry Andric #include "llvm/IR/IRBuilder.h"
710b57cec5SDimitry Andric #include "llvm/IR/Mangler.h"
72*0fca6ea1SDimitry Andric #include "llvm/IR/Module.h"
73480093f4SDimitry Andric #include "llvm/InitializePasses.h"
740b57cec5SDimitry Andric #include "llvm/Support/CommandLine.h"
750b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
765ffd83dbSDimitry Andric #include "llvm/Support/SuffixTree.h"
770b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
780b57cec5SDimitry Andric #include <functional>
790b57cec5SDimitry Andric #include <tuple>
800b57cec5SDimitry Andric #include <vector>
810b57cec5SDimitry Andric 
820b57cec5SDimitry Andric #define DEBUG_TYPE "machine-outliner"
830b57cec5SDimitry Andric 
840b57cec5SDimitry Andric using namespace llvm;
850b57cec5SDimitry Andric using namespace ore;
860b57cec5SDimitry Andric using namespace outliner;
870b57cec5SDimitry Andric 
8881ad6265SDimitry Andric // Statistics for outlined functions.
890b57cec5SDimitry Andric STATISTIC(NumOutlined, "Number of candidates outlined");
900b57cec5SDimitry Andric STATISTIC(FunctionsCreated, "Number of functions created");
910b57cec5SDimitry Andric 
9281ad6265SDimitry Andric // Statistics for instruction mapping.
9306c3fb27SDimitry Andric STATISTIC(NumLegalInUnsignedVec, "Outlinable instructions mapped");
9481ad6265SDimitry Andric STATISTIC(NumIllegalInUnsignedVec,
9506c3fb27SDimitry Andric           "Unoutlinable instructions mapped + number of sentinel values");
9606c3fb27SDimitry Andric STATISTIC(NumSentinels, "Sentinel values inserted during mapping");
9706c3fb27SDimitry Andric STATISTIC(NumInvisible,
9806c3fb27SDimitry Andric           "Invisible instructions skipped during mapping");
9906c3fb27SDimitry Andric STATISTIC(UnsignedVecSize,
10006c3fb27SDimitry Andric           "Total number of instructions mapped and saved to mapping vector");
10181ad6265SDimitry Andric 
1020b57cec5SDimitry Andric // Set to true if the user wants the outliner to run on linkonceodr linkage
1030b57cec5SDimitry Andric // functions. This is false by default because the linker can dedupe linkonceodr
1040b57cec5SDimitry Andric // functions. Since the outliner is confined to a single module (modulo LTO),
1050b57cec5SDimitry Andric // this is off by default. It should, however, be the default behaviour in
1060b57cec5SDimitry Andric // LTO.
1070b57cec5SDimitry Andric static cl::opt<bool> EnableLinkOnceODROutlining(
108480093f4SDimitry Andric     "enable-linkonceodr-outlining", cl::Hidden,
1090b57cec5SDimitry Andric     cl::desc("Enable the machine outliner on linkonceodr functions"),
1100b57cec5SDimitry Andric     cl::init(false));
1110b57cec5SDimitry Andric 
1125ffd83dbSDimitry Andric /// Number of times to re-run the outliner. This is not the total number of runs
1135ffd83dbSDimitry Andric /// as the outliner will run at least one time. The default value is set to 0,
1145ffd83dbSDimitry Andric /// meaning the outliner will run one time and rerun zero times after that.
1155ffd83dbSDimitry Andric static cl::opt<unsigned> OutlinerReruns(
1165ffd83dbSDimitry Andric     "machine-outliner-reruns", cl::init(0), cl::Hidden,
1175ffd83dbSDimitry Andric     cl::desc(
1185ffd83dbSDimitry Andric         "Number of times to rerun the outliner after the initial outline"));
1195ffd83dbSDimitry Andric 
12006c3fb27SDimitry Andric static cl::opt<unsigned> OutlinerBenefitThreshold(
12106c3fb27SDimitry Andric     "outliner-benefit-threshold", cl::init(1), cl::Hidden,
12206c3fb27SDimitry Andric     cl::desc(
12306c3fb27SDimitry Andric         "The minimum size in bytes before an outlining candidate is accepted"));
12406c3fb27SDimitry Andric 
125*0fca6ea1SDimitry Andric static cl::opt<bool> OutlinerLeafDescendants(
126*0fca6ea1SDimitry Andric     "outliner-leaf-descendants", cl::init(true), cl::Hidden,
127*0fca6ea1SDimitry Andric     cl::desc("Consider all leaf descendants of internal nodes of the suffix "
128*0fca6ea1SDimitry Andric              "tree as candidates for outlining (if false, only leaf children "
129*0fca6ea1SDimitry Andric              "are considered)"));
130*0fca6ea1SDimitry Andric 
1310b57cec5SDimitry Andric namespace {
1320b57cec5SDimitry Andric 
1330b57cec5SDimitry Andric /// Maps \p MachineInstrs to unsigned integers and stores the mappings.
1340b57cec5SDimitry Andric struct InstructionMapper {
1350b57cec5SDimitry Andric 
1360b57cec5SDimitry Andric   /// The next available integer to assign to a \p MachineInstr that
1370b57cec5SDimitry Andric   /// cannot be outlined.
1380b57cec5SDimitry Andric   ///
1390b57cec5SDimitry Andric   /// Set to -3 for compatability with \p DenseMapInfo<unsigned>.
1400b57cec5SDimitry Andric   unsigned IllegalInstrNumber = -3;
1410b57cec5SDimitry Andric 
1420b57cec5SDimitry Andric   /// The next available integer to assign to a \p MachineInstr that can
1430b57cec5SDimitry Andric   /// be outlined.
1440b57cec5SDimitry Andric   unsigned LegalInstrNumber = 0;
1450b57cec5SDimitry Andric 
1460b57cec5SDimitry Andric   /// Correspondence from \p MachineInstrs to unsigned integers.
1470b57cec5SDimitry Andric   DenseMap<MachineInstr *, unsigned, MachineInstrExpressionTrait>
1480b57cec5SDimitry Andric       InstructionIntegerMap;
1490b57cec5SDimitry Andric 
1500b57cec5SDimitry Andric   /// Correspondence between \p MachineBasicBlocks and target-defined flags.
1510b57cec5SDimitry Andric   DenseMap<MachineBasicBlock *, unsigned> MBBFlagsMap;
1520b57cec5SDimitry Andric 
1530b57cec5SDimitry Andric   /// The vector of unsigned integers that the module is mapped to.
15406c3fb27SDimitry Andric   SmallVector<unsigned> UnsignedVec;
1550b57cec5SDimitry Andric 
1560b57cec5SDimitry Andric   /// Stores the location of the instruction associated with the integer
1570b57cec5SDimitry Andric   /// at index i in \p UnsignedVec for each index i.
15806c3fb27SDimitry Andric   SmallVector<MachineBasicBlock::iterator> InstrList;
1590b57cec5SDimitry Andric 
1600b57cec5SDimitry Andric   // Set if we added an illegal number in the previous step.
1610b57cec5SDimitry Andric   // Since each illegal number is unique, we only need one of them between
1620b57cec5SDimitry Andric   // each range of legal numbers. This lets us make sure we don't add more
1630b57cec5SDimitry Andric   // than one illegal number per range.
1640b57cec5SDimitry Andric   bool AddedIllegalLastTime = false;
1650b57cec5SDimitry Andric 
1660b57cec5SDimitry Andric   /// Maps \p *It to a legal integer.
1670b57cec5SDimitry Andric   ///
1680b57cec5SDimitry Andric   /// Updates \p CanOutlineWithPrevInstr, \p HaveLegalRange, \p InstrListForMBB,
1690b57cec5SDimitry Andric   /// \p UnsignedVecForMBB, \p InstructionIntegerMap, and \p LegalInstrNumber.
1700b57cec5SDimitry Andric   ///
1710b57cec5SDimitry Andric   /// \returns The integer that \p *It was mapped to.
1720b57cec5SDimitry Andric   unsigned mapToLegalUnsigned(
1730b57cec5SDimitry Andric       MachineBasicBlock::iterator &It, bool &CanOutlineWithPrevInstr,
1740b57cec5SDimitry Andric       bool &HaveLegalRange, unsigned &NumLegalInBlock,
17506c3fb27SDimitry Andric       SmallVector<unsigned> &UnsignedVecForMBB,
17606c3fb27SDimitry Andric       SmallVector<MachineBasicBlock::iterator> &InstrListForMBB) {
1770b57cec5SDimitry Andric     // We added something legal, so we should unset the AddedLegalLastTime
1780b57cec5SDimitry Andric     // flag.
1790b57cec5SDimitry Andric     AddedIllegalLastTime = false;
1800b57cec5SDimitry Andric 
1810b57cec5SDimitry Andric     // If we have at least two adjacent legal instructions (which may have
1820b57cec5SDimitry Andric     // invisible instructions in between), remember that.
1830b57cec5SDimitry Andric     if (CanOutlineWithPrevInstr)
1840b57cec5SDimitry Andric       HaveLegalRange = true;
1850b57cec5SDimitry Andric     CanOutlineWithPrevInstr = true;
1860b57cec5SDimitry Andric 
1870b57cec5SDimitry Andric     // Keep track of the number of legal instructions we insert.
1880b57cec5SDimitry Andric     NumLegalInBlock++;
1890b57cec5SDimitry Andric 
1900b57cec5SDimitry Andric     // Get the integer for this instruction or give it the current
1910b57cec5SDimitry Andric     // LegalInstrNumber.
1920b57cec5SDimitry Andric     InstrListForMBB.push_back(It);
1930b57cec5SDimitry Andric     MachineInstr &MI = *It;
1940b57cec5SDimitry Andric     bool WasInserted;
1950b57cec5SDimitry Andric     DenseMap<MachineInstr *, unsigned, MachineInstrExpressionTrait>::iterator
1960b57cec5SDimitry Andric         ResultIt;
1970b57cec5SDimitry Andric     std::tie(ResultIt, WasInserted) =
1980b57cec5SDimitry Andric         InstructionIntegerMap.insert(std::make_pair(&MI, LegalInstrNumber));
1990b57cec5SDimitry Andric     unsigned MINumber = ResultIt->second;
2000b57cec5SDimitry Andric 
2010b57cec5SDimitry Andric     // There was an insertion.
2020b57cec5SDimitry Andric     if (WasInserted)
2030b57cec5SDimitry Andric       LegalInstrNumber++;
2040b57cec5SDimitry Andric 
2050b57cec5SDimitry Andric     UnsignedVecForMBB.push_back(MINumber);
2060b57cec5SDimitry Andric 
2070b57cec5SDimitry Andric     // Make sure we don't overflow or use any integers reserved by the DenseMap.
2080b57cec5SDimitry Andric     if (LegalInstrNumber >= IllegalInstrNumber)
2090b57cec5SDimitry Andric       report_fatal_error("Instruction mapping overflow!");
2100b57cec5SDimitry Andric 
2110b57cec5SDimitry Andric     assert(LegalInstrNumber != DenseMapInfo<unsigned>::getEmptyKey() &&
2120b57cec5SDimitry Andric            "Tried to assign DenseMap tombstone or empty key to instruction.");
2130b57cec5SDimitry Andric     assert(LegalInstrNumber != DenseMapInfo<unsigned>::getTombstoneKey() &&
2140b57cec5SDimitry Andric            "Tried to assign DenseMap tombstone or empty key to instruction.");
2150b57cec5SDimitry Andric 
21681ad6265SDimitry Andric     // Statistics.
21781ad6265SDimitry Andric     ++NumLegalInUnsignedVec;
2180b57cec5SDimitry Andric     return MINumber;
2190b57cec5SDimitry Andric   }
2200b57cec5SDimitry Andric 
2210b57cec5SDimitry Andric   /// Maps \p *It to an illegal integer.
2220b57cec5SDimitry Andric   ///
2230b57cec5SDimitry Andric   /// Updates \p InstrListForMBB, \p UnsignedVecForMBB, and \p
2240b57cec5SDimitry Andric   /// IllegalInstrNumber.
2250b57cec5SDimitry Andric   ///
2260b57cec5SDimitry Andric   /// \returns The integer that \p *It was mapped to.
227480093f4SDimitry Andric   unsigned mapToIllegalUnsigned(
228480093f4SDimitry Andric       MachineBasicBlock::iterator &It, bool &CanOutlineWithPrevInstr,
22906c3fb27SDimitry Andric       SmallVector<unsigned> &UnsignedVecForMBB,
23006c3fb27SDimitry Andric       SmallVector<MachineBasicBlock::iterator> &InstrListForMBB) {
2310b57cec5SDimitry Andric     // Can't outline an illegal instruction. Set the flag.
2320b57cec5SDimitry Andric     CanOutlineWithPrevInstr = false;
2330b57cec5SDimitry Andric 
2340b57cec5SDimitry Andric     // Only add one illegal number per range of legal numbers.
2350b57cec5SDimitry Andric     if (AddedIllegalLastTime)
2360b57cec5SDimitry Andric       return IllegalInstrNumber;
2370b57cec5SDimitry Andric 
2380b57cec5SDimitry Andric     // Remember that we added an illegal number last time.
2390b57cec5SDimitry Andric     AddedIllegalLastTime = true;
2400b57cec5SDimitry Andric     unsigned MINumber = IllegalInstrNumber;
2410b57cec5SDimitry Andric 
2420b57cec5SDimitry Andric     InstrListForMBB.push_back(It);
2430b57cec5SDimitry Andric     UnsignedVecForMBB.push_back(IllegalInstrNumber);
2440b57cec5SDimitry Andric     IllegalInstrNumber--;
24581ad6265SDimitry Andric     // Statistics.
24681ad6265SDimitry Andric     ++NumIllegalInUnsignedVec;
2470b57cec5SDimitry Andric 
2480b57cec5SDimitry Andric     assert(LegalInstrNumber < IllegalInstrNumber &&
2490b57cec5SDimitry Andric            "Instruction mapping overflow!");
2500b57cec5SDimitry Andric 
2510b57cec5SDimitry Andric     assert(IllegalInstrNumber != DenseMapInfo<unsigned>::getEmptyKey() &&
2520b57cec5SDimitry Andric            "IllegalInstrNumber cannot be DenseMap tombstone or empty key!");
2530b57cec5SDimitry Andric 
2540b57cec5SDimitry Andric     assert(IllegalInstrNumber != DenseMapInfo<unsigned>::getTombstoneKey() &&
2550b57cec5SDimitry Andric            "IllegalInstrNumber cannot be DenseMap tombstone or empty key!");
2560b57cec5SDimitry Andric 
2570b57cec5SDimitry Andric     return MINumber;
2580b57cec5SDimitry Andric   }
2590b57cec5SDimitry Andric 
2600b57cec5SDimitry Andric   /// Transforms a \p MachineBasicBlock into a \p vector of \p unsigneds
2610b57cec5SDimitry Andric   /// and appends it to \p UnsignedVec and \p InstrList.
2620b57cec5SDimitry Andric   ///
2630b57cec5SDimitry Andric   /// Two instructions are assigned the same integer if they are identical.
2640b57cec5SDimitry Andric   /// If an instruction is deemed unsafe to outline, then it will be assigned an
2650b57cec5SDimitry Andric   /// unique integer. The resulting mapping is placed into a suffix tree and
2660b57cec5SDimitry Andric   /// queried for candidates.
2670b57cec5SDimitry Andric   ///
2680b57cec5SDimitry Andric   /// \param MBB The \p MachineBasicBlock to be translated into integers.
2690b57cec5SDimitry Andric   /// \param TII \p TargetInstrInfo for the function.
2700b57cec5SDimitry Andric   void convertToUnsignedVec(MachineBasicBlock &MBB,
2710b57cec5SDimitry Andric                             const TargetInstrInfo &TII) {
27206c3fb27SDimitry Andric     LLVM_DEBUG(dbgs() << "*** Converting MBB '" << MBB.getName()
27306c3fb27SDimitry Andric                       << "' to unsigned vector ***\n");
2740b57cec5SDimitry Andric     unsigned Flags = 0;
2750b57cec5SDimitry Andric 
2760b57cec5SDimitry Andric     // Don't even map in this case.
2770b57cec5SDimitry Andric     if (!TII.isMBBSafeToOutlineFrom(MBB, Flags))
2780b57cec5SDimitry Andric       return;
2790b57cec5SDimitry Andric 
28006c3fb27SDimitry Andric     auto OutlinableRanges = TII.getOutlinableRanges(MBB, Flags);
28106c3fb27SDimitry Andric     LLVM_DEBUG(dbgs() << MBB.getName() << ": " << OutlinableRanges.size()
28206c3fb27SDimitry Andric                       << " outlinable range(s)\n");
28306c3fb27SDimitry Andric     if (OutlinableRanges.empty())
28406c3fb27SDimitry Andric       return;
28506c3fb27SDimitry Andric 
2860b57cec5SDimitry Andric     // Store info for the MBB for later outlining.
2870b57cec5SDimitry Andric     MBBFlagsMap[&MBB] = Flags;
2880b57cec5SDimitry Andric 
2890b57cec5SDimitry Andric     MachineBasicBlock::iterator It = MBB.begin();
2900b57cec5SDimitry Andric 
2910b57cec5SDimitry Andric     // The number of instructions in this block that will be considered for
2920b57cec5SDimitry Andric     // outlining.
2930b57cec5SDimitry Andric     unsigned NumLegalInBlock = 0;
2940b57cec5SDimitry Andric 
2950b57cec5SDimitry Andric     // True if we have at least two legal instructions which aren't separated
2960b57cec5SDimitry Andric     // by an illegal instruction.
2970b57cec5SDimitry Andric     bool HaveLegalRange = false;
2980b57cec5SDimitry Andric 
2990b57cec5SDimitry Andric     // True if we can perform outlining given the last mapped (non-invisible)
3000b57cec5SDimitry Andric     // instruction. This lets us know if we have a legal range.
3010b57cec5SDimitry Andric     bool CanOutlineWithPrevInstr = false;
3020b57cec5SDimitry Andric 
3030b57cec5SDimitry Andric     // FIXME: Should this all just be handled in the target, rather than using
3040b57cec5SDimitry Andric     // repeated calls to getOutliningType?
30506c3fb27SDimitry Andric     SmallVector<unsigned> UnsignedVecForMBB;
30606c3fb27SDimitry Andric     SmallVector<MachineBasicBlock::iterator> InstrListForMBB;
3070b57cec5SDimitry Andric 
30806c3fb27SDimitry Andric     LLVM_DEBUG(dbgs() << "*** Mapping outlinable ranges ***\n");
30906c3fb27SDimitry Andric     for (auto &OutlinableRange : OutlinableRanges) {
31006c3fb27SDimitry Andric       auto OutlinableRangeBegin = OutlinableRange.first;
31106c3fb27SDimitry Andric       auto OutlinableRangeEnd = OutlinableRange.second;
31206c3fb27SDimitry Andric #ifndef NDEBUG
31306c3fb27SDimitry Andric       LLVM_DEBUG(
31406c3fb27SDimitry Andric           dbgs() << "Mapping "
31506c3fb27SDimitry Andric                  << std::distance(OutlinableRangeBegin, OutlinableRangeEnd)
31606c3fb27SDimitry Andric                  << " instruction range\n");
31706c3fb27SDimitry Andric       // Everything outside of an outlinable range is illegal.
31806c3fb27SDimitry Andric       unsigned NumSkippedInRange = 0;
31906c3fb27SDimitry Andric #endif
32006c3fb27SDimitry Andric       for (; It != OutlinableRangeBegin; ++It) {
32106c3fb27SDimitry Andric #ifndef NDEBUG
32206c3fb27SDimitry Andric         ++NumSkippedInRange;
32306c3fb27SDimitry Andric #endif
32406c3fb27SDimitry Andric         mapToIllegalUnsigned(It, CanOutlineWithPrevInstr, UnsignedVecForMBB,
32506c3fb27SDimitry Andric                              InstrListForMBB);
32606c3fb27SDimitry Andric       }
32706c3fb27SDimitry Andric #ifndef NDEBUG
32806c3fb27SDimitry Andric       LLVM_DEBUG(dbgs() << "Skipped " << NumSkippedInRange
32906c3fb27SDimitry Andric                         << " instructions outside outlinable range\n");
33006c3fb27SDimitry Andric #endif
33106c3fb27SDimitry Andric       assert(It != MBB.end() && "Should still have instructions?");
33206c3fb27SDimitry Andric       // `It` is now positioned at the beginning of a range of instructions
33306c3fb27SDimitry Andric       // which may be outlinable. Check if each instruction is known to be safe.
33406c3fb27SDimitry Andric       for (; It != OutlinableRangeEnd; ++It) {
3350b57cec5SDimitry Andric         // Keep track of where this instruction is in the module.
3360b57cec5SDimitry Andric         switch (TII.getOutliningType(It, Flags)) {
3370b57cec5SDimitry Andric         case InstrType::Illegal:
338480093f4SDimitry Andric           mapToIllegalUnsigned(It, CanOutlineWithPrevInstr, UnsignedVecForMBB,
339480093f4SDimitry Andric                                InstrListForMBB);
3400b57cec5SDimitry Andric           break;
3410b57cec5SDimitry Andric 
3420b57cec5SDimitry Andric         case InstrType::Legal:
3430b57cec5SDimitry Andric           mapToLegalUnsigned(It, CanOutlineWithPrevInstr, HaveLegalRange,
34406c3fb27SDimitry Andric                              NumLegalInBlock, UnsignedVecForMBB,
34506c3fb27SDimitry Andric                              InstrListForMBB);
3460b57cec5SDimitry Andric           break;
3470b57cec5SDimitry Andric 
3480b57cec5SDimitry Andric         case InstrType::LegalTerminator:
3490b57cec5SDimitry Andric           mapToLegalUnsigned(It, CanOutlineWithPrevInstr, HaveLegalRange,
35006c3fb27SDimitry Andric                              NumLegalInBlock, UnsignedVecForMBB,
35106c3fb27SDimitry Andric                              InstrListForMBB);
35206c3fb27SDimitry Andric           // The instruction also acts as a terminator, so we have to record
35306c3fb27SDimitry Andric           // that in the string.
3540b57cec5SDimitry Andric           mapToIllegalUnsigned(It, CanOutlineWithPrevInstr, UnsignedVecForMBB,
3550b57cec5SDimitry Andric                                InstrListForMBB);
3560b57cec5SDimitry Andric           break;
3570b57cec5SDimitry Andric 
3580b57cec5SDimitry Andric         case InstrType::Invisible:
3590b57cec5SDimitry Andric           // Normally this is set by mapTo(Blah)Unsigned, but we just want to
3600b57cec5SDimitry Andric           // skip this instruction. So, unset the flag here.
36181ad6265SDimitry Andric           ++NumInvisible;
3620b57cec5SDimitry Andric           AddedIllegalLastTime = false;
3630b57cec5SDimitry Andric           break;
3640b57cec5SDimitry Andric         }
3650b57cec5SDimitry Andric       }
36606c3fb27SDimitry Andric     }
36706c3fb27SDimitry Andric 
36806c3fb27SDimitry Andric     LLVM_DEBUG(dbgs() << "HaveLegalRange = " << HaveLegalRange << "\n");
3690b57cec5SDimitry Andric 
3700b57cec5SDimitry Andric     // Are there enough legal instructions in the block for outlining to be
3710b57cec5SDimitry Andric     // possible?
3720b57cec5SDimitry Andric     if (HaveLegalRange) {
3730b57cec5SDimitry Andric       // After we're done every insertion, uniquely terminate this part of the
3740b57cec5SDimitry Andric       // "string". This makes sure we won't match across basic block or function
3750b57cec5SDimitry Andric       // boundaries since the "end" is encoded uniquely and thus appears in no
3760b57cec5SDimitry Andric       // repeated substring.
3770b57cec5SDimitry Andric       mapToIllegalUnsigned(It, CanOutlineWithPrevInstr, UnsignedVecForMBB,
3780b57cec5SDimitry Andric                            InstrListForMBB);
37906c3fb27SDimitry Andric       ++NumSentinels;
38006c3fb27SDimitry Andric       append_range(InstrList, InstrListForMBB);
38106c3fb27SDimitry Andric       append_range(UnsignedVec, UnsignedVecForMBB);
3820b57cec5SDimitry Andric     }
3830b57cec5SDimitry Andric   }
3840b57cec5SDimitry Andric 
3850b57cec5SDimitry Andric   InstructionMapper() {
3860b57cec5SDimitry Andric     // Make sure that the implementation of DenseMapInfo<unsigned> hasn't
3870b57cec5SDimitry Andric     // changed.
3880b57cec5SDimitry Andric     assert(DenseMapInfo<unsigned>::getEmptyKey() == (unsigned)-1 &&
3890b57cec5SDimitry Andric            "DenseMapInfo<unsigned>'s empty key isn't -1!");
3900b57cec5SDimitry Andric     assert(DenseMapInfo<unsigned>::getTombstoneKey() == (unsigned)-2 &&
3910b57cec5SDimitry Andric            "DenseMapInfo<unsigned>'s tombstone key isn't -2!");
3920b57cec5SDimitry Andric   }
3930b57cec5SDimitry Andric };
3940b57cec5SDimitry Andric 
3950b57cec5SDimitry Andric /// An interprocedural pass which finds repeated sequences of
3960b57cec5SDimitry Andric /// instructions and replaces them with calls to functions.
3970b57cec5SDimitry Andric ///
3980b57cec5SDimitry Andric /// Each instruction is mapped to an unsigned integer and placed in a string.
3990b57cec5SDimitry Andric /// The resulting mapping is then placed in a \p SuffixTree. The \p SuffixTree
4000b57cec5SDimitry Andric /// is then repeatedly queried for repeated sequences of instructions. Each
4010b57cec5SDimitry Andric /// non-overlapping repeated sequence is then placed in its own
4020b57cec5SDimitry Andric /// \p MachineFunction and each instance is then replaced with a call to that
4030b57cec5SDimitry Andric /// function.
4040b57cec5SDimitry Andric struct MachineOutliner : public ModulePass {
4050b57cec5SDimitry Andric 
4060b57cec5SDimitry Andric   static char ID;
4070b57cec5SDimitry Andric 
4080b57cec5SDimitry Andric   /// Set to true if the outliner should consider functions with
4090b57cec5SDimitry Andric   /// linkonceodr linkage.
4100b57cec5SDimitry Andric   bool OutlineFromLinkOnceODRs = false;
4110b57cec5SDimitry Andric 
4125ffd83dbSDimitry Andric   /// The current repeat number of machine outlining.
4135ffd83dbSDimitry Andric   unsigned OutlineRepeatedNum = 0;
4145ffd83dbSDimitry Andric 
4150b57cec5SDimitry Andric   /// Set to true if the outliner should run on all functions in the module
4160b57cec5SDimitry Andric   /// considered safe for outlining.
4170b57cec5SDimitry Andric   /// Set to true by default for compatibility with llc's -run-pass option.
4180b57cec5SDimitry Andric   /// Set when the pass is constructed in TargetPassConfig.
4190b57cec5SDimitry Andric   bool RunOnAllFunctions = true;
4200b57cec5SDimitry Andric 
4210b57cec5SDimitry Andric   StringRef getPassName() const override { return "Machine Outliner"; }
4220b57cec5SDimitry Andric 
4230b57cec5SDimitry Andric   void getAnalysisUsage(AnalysisUsage &AU) const override {
4248bcb0991SDimitry Andric     AU.addRequired<MachineModuleInfoWrapperPass>();
4258bcb0991SDimitry Andric     AU.addPreserved<MachineModuleInfoWrapperPass>();
4260b57cec5SDimitry Andric     AU.setPreservesAll();
4270b57cec5SDimitry Andric     ModulePass::getAnalysisUsage(AU);
4280b57cec5SDimitry Andric   }
4290b57cec5SDimitry Andric 
4300b57cec5SDimitry Andric   MachineOutliner() : ModulePass(ID) {
4310b57cec5SDimitry Andric     initializeMachineOutlinerPass(*PassRegistry::getPassRegistry());
4320b57cec5SDimitry Andric   }
4330b57cec5SDimitry Andric 
4340b57cec5SDimitry Andric   /// Remark output explaining that not outlining a set of candidates would be
4350b57cec5SDimitry Andric   /// better than outlining that set.
4360b57cec5SDimitry Andric   void emitNotOutliningCheaperRemark(
4370b57cec5SDimitry Andric       unsigned StringLen, std::vector<Candidate> &CandidatesForRepeatedSeq,
4380b57cec5SDimitry Andric       OutlinedFunction &OF);
4390b57cec5SDimitry Andric 
4400b57cec5SDimitry Andric   /// Remark output explaining that a function was outlined.
4410b57cec5SDimitry Andric   void emitOutlinedFunctionRemark(OutlinedFunction &OF);
4420b57cec5SDimitry Andric 
4430b57cec5SDimitry Andric   /// Find all repeated substrings that satisfy the outlining cost model by
4440b57cec5SDimitry Andric   /// constructing a suffix tree.
4450b57cec5SDimitry Andric   ///
4460b57cec5SDimitry Andric   /// If a substring appears at least twice, then it must be represented by
4470b57cec5SDimitry Andric   /// an internal node which appears in at least two suffixes. Each suffix
4480b57cec5SDimitry Andric   /// is represented by a leaf node. To do this, we visit each internal node
4490b57cec5SDimitry Andric   /// in the tree, using the leaf children of each internal node. If an
4500b57cec5SDimitry Andric   /// internal node represents a beneficial substring, then we use each of
4510b57cec5SDimitry Andric   /// its leaf children to find the locations of its substring.
4520b57cec5SDimitry Andric   ///
4530b57cec5SDimitry Andric   /// \param Mapper Contains outlining mapping information.
4540b57cec5SDimitry Andric   /// \param[out] FunctionList Filled with a list of \p OutlinedFunctions
4550b57cec5SDimitry Andric   /// each type of candidate.
4560b57cec5SDimitry Andric   void findCandidates(InstructionMapper &Mapper,
4570b57cec5SDimitry Andric                       std::vector<OutlinedFunction> &FunctionList);
4580b57cec5SDimitry Andric 
4590b57cec5SDimitry Andric   /// Replace the sequences of instructions represented by \p OutlinedFunctions
4600b57cec5SDimitry Andric   /// with calls to functions.
4610b57cec5SDimitry Andric   ///
4620b57cec5SDimitry Andric   /// \param M The module we are outlining from.
4630b57cec5SDimitry Andric   /// \param FunctionList A list of functions to be inserted into the module.
4640b57cec5SDimitry Andric   /// \param Mapper Contains the instruction mappings for the module.
4650b57cec5SDimitry Andric   bool outline(Module &M, std::vector<OutlinedFunction> &FunctionList,
466480093f4SDimitry Andric                InstructionMapper &Mapper, unsigned &OutlinedFunctionNum);
4670b57cec5SDimitry Andric 
4680b57cec5SDimitry Andric   /// Creates a function for \p OF and inserts it into the module.
4690b57cec5SDimitry Andric   MachineFunction *createOutlinedFunction(Module &M, OutlinedFunction &OF,
4700b57cec5SDimitry Andric                                           InstructionMapper &Mapper,
4710b57cec5SDimitry Andric                                           unsigned Name);
4720b57cec5SDimitry Andric 
4735ffd83dbSDimitry Andric   /// Calls 'doOutline()' 1 + OutlinerReruns times.
474480093f4SDimitry Andric   bool runOnModule(Module &M) override;
475480093f4SDimitry Andric 
4760b57cec5SDimitry Andric   /// Construct a suffix tree on the instructions in \p M and outline repeated
4770b57cec5SDimitry Andric   /// strings from that tree.
478480093f4SDimitry Andric   bool doOutline(Module &M, unsigned &OutlinedFunctionNum);
4790b57cec5SDimitry Andric 
4800b57cec5SDimitry Andric   /// Return a DISubprogram for OF if one exists, and null otherwise. Helper
4810b57cec5SDimitry Andric   /// function for remark emission.
4820b57cec5SDimitry Andric   DISubprogram *getSubprogramOrNull(const OutlinedFunction &OF) {
4830b57cec5SDimitry Andric     for (const Candidate &C : OF.Candidates)
484480093f4SDimitry Andric       if (MachineFunction *MF = C.getMF())
485480093f4SDimitry Andric         if (DISubprogram *SP = MF->getFunction().getSubprogram())
4860b57cec5SDimitry Andric           return SP;
4870b57cec5SDimitry Andric     return nullptr;
4880b57cec5SDimitry Andric   }
4890b57cec5SDimitry Andric 
4900b57cec5SDimitry Andric   /// Populate and \p InstructionMapper with instruction-to-integer mappings.
4910b57cec5SDimitry Andric   /// These are used to construct a suffix tree.
4920b57cec5SDimitry Andric   void populateMapper(InstructionMapper &Mapper, Module &M,
4930b57cec5SDimitry Andric                       MachineModuleInfo &MMI);
4940b57cec5SDimitry Andric 
4950b57cec5SDimitry Andric   /// Initialize information necessary to output a size remark.
4960b57cec5SDimitry Andric   /// FIXME: This should be handled by the pass manager, not the outliner.
4970b57cec5SDimitry Andric   /// FIXME: This is nearly identical to the initSizeRemarkInfo in the legacy
4980b57cec5SDimitry Andric   /// pass manager.
499480093f4SDimitry Andric   void initSizeRemarkInfo(const Module &M, const MachineModuleInfo &MMI,
5000b57cec5SDimitry Andric                           StringMap<unsigned> &FunctionToInstrCount);
5010b57cec5SDimitry Andric 
5020b57cec5SDimitry Andric   /// Emit the remark.
5030b57cec5SDimitry Andric   // FIXME: This should be handled by the pass manager, not the outliner.
504480093f4SDimitry Andric   void
505480093f4SDimitry Andric   emitInstrCountChangedRemark(const Module &M, const MachineModuleInfo &MMI,
5060b57cec5SDimitry Andric                               const StringMap<unsigned> &FunctionToInstrCount);
5070b57cec5SDimitry Andric };
5080b57cec5SDimitry Andric } // Anonymous namespace.
5090b57cec5SDimitry Andric 
5100b57cec5SDimitry Andric char MachineOutliner::ID = 0;
5110b57cec5SDimitry Andric 
5120b57cec5SDimitry Andric namespace llvm {
5130b57cec5SDimitry Andric ModulePass *createMachineOutlinerPass(bool RunOnAllFunctions) {
5140b57cec5SDimitry Andric   MachineOutliner *OL = new MachineOutliner();
5150b57cec5SDimitry Andric   OL->RunOnAllFunctions = RunOnAllFunctions;
5160b57cec5SDimitry Andric   return OL;
5170b57cec5SDimitry Andric }
5180b57cec5SDimitry Andric 
5190b57cec5SDimitry Andric } // namespace llvm
5200b57cec5SDimitry Andric 
5210b57cec5SDimitry Andric INITIALIZE_PASS(MachineOutliner, DEBUG_TYPE, "Machine Function Outliner", false,
5220b57cec5SDimitry Andric                 false)
5230b57cec5SDimitry Andric 
5240b57cec5SDimitry Andric void MachineOutliner::emitNotOutliningCheaperRemark(
5250b57cec5SDimitry Andric     unsigned StringLen, std::vector<Candidate> &CandidatesForRepeatedSeq,
5260b57cec5SDimitry Andric     OutlinedFunction &OF) {
5270b57cec5SDimitry Andric   // FIXME: Right now, we arbitrarily choose some Candidate from the
5280b57cec5SDimitry Andric   // OutlinedFunction. This isn't necessarily fixed, nor does it have to be.
5290b57cec5SDimitry Andric   // We should probably sort these by function name or something to make sure
5300b57cec5SDimitry Andric   // the remarks are stable.
5310b57cec5SDimitry Andric   Candidate &C = CandidatesForRepeatedSeq.front();
5320b57cec5SDimitry Andric   MachineOptimizationRemarkEmitter MORE(*(C.getMF()), nullptr);
5330b57cec5SDimitry Andric   MORE.emit([&]() {
5340b57cec5SDimitry Andric     MachineOptimizationRemarkMissed R(DEBUG_TYPE, "NotOutliningCheaper",
5357a6dacacSDimitry Andric                                       C.front().getDebugLoc(), C.getMBB());
5360b57cec5SDimitry Andric     R << "Did not outline " << NV("Length", StringLen) << " instructions"
5370b57cec5SDimitry Andric       << " from " << NV("NumOccurrences", CandidatesForRepeatedSeq.size())
5380b57cec5SDimitry Andric       << " locations."
5390b57cec5SDimitry Andric       << " Bytes from outlining all occurrences ("
5400b57cec5SDimitry Andric       << NV("OutliningCost", OF.getOutliningCost()) << ")"
5410b57cec5SDimitry Andric       << " >= Unoutlined instruction bytes ("
5420b57cec5SDimitry Andric       << NV("NotOutliningCost", OF.getNotOutlinedCost()) << ")"
5430b57cec5SDimitry Andric       << " (Also found at: ";
5440b57cec5SDimitry Andric 
5450b57cec5SDimitry Andric     // Tell the user the other places the candidate was found.
5460b57cec5SDimitry Andric     for (unsigned i = 1, e = CandidatesForRepeatedSeq.size(); i < e; i++) {
5470b57cec5SDimitry Andric       R << NV((Twine("OtherStartLoc") + Twine(i)).str(),
5487a6dacacSDimitry Andric               CandidatesForRepeatedSeq[i].front().getDebugLoc());
5490b57cec5SDimitry Andric       if (i != e - 1)
5500b57cec5SDimitry Andric         R << ", ";
5510b57cec5SDimitry Andric     }
5520b57cec5SDimitry Andric 
5530b57cec5SDimitry Andric     R << ")";
5540b57cec5SDimitry Andric     return R;
5550b57cec5SDimitry Andric   });
5560b57cec5SDimitry Andric }
5570b57cec5SDimitry Andric 
5580b57cec5SDimitry Andric void MachineOutliner::emitOutlinedFunctionRemark(OutlinedFunction &OF) {
5590b57cec5SDimitry Andric   MachineBasicBlock *MBB = &*OF.MF->begin();
5600b57cec5SDimitry Andric   MachineOptimizationRemarkEmitter MORE(*OF.MF, nullptr);
5610b57cec5SDimitry Andric   MachineOptimizationRemark R(DEBUG_TYPE, "OutlinedFunction",
5620b57cec5SDimitry Andric                               MBB->findDebugLoc(MBB->begin()), MBB);
5630b57cec5SDimitry Andric   R << "Saved " << NV("OutliningBenefit", OF.getBenefit()) << " bytes by "
5640b57cec5SDimitry Andric     << "outlining " << NV("Length", OF.getNumInstrs()) << " instructions "
5650b57cec5SDimitry Andric     << "from " << NV("NumOccurrences", OF.getOccurrenceCount())
5660b57cec5SDimitry Andric     << " locations. "
5670b57cec5SDimitry Andric     << "(Found at: ";
5680b57cec5SDimitry Andric 
5690b57cec5SDimitry Andric   // Tell the user the other places the candidate was found.
5700b57cec5SDimitry Andric   for (size_t i = 0, e = OF.Candidates.size(); i < e; i++) {
5710b57cec5SDimitry Andric 
5720b57cec5SDimitry Andric     R << NV((Twine("StartLoc") + Twine(i)).str(),
5737a6dacacSDimitry Andric             OF.Candidates[i].front().getDebugLoc());
5740b57cec5SDimitry Andric     if (i != e - 1)
5750b57cec5SDimitry Andric       R << ", ";
5760b57cec5SDimitry Andric   }
5770b57cec5SDimitry Andric 
5780b57cec5SDimitry Andric   R << ")";
5790b57cec5SDimitry Andric 
5800b57cec5SDimitry Andric   MORE.emit(R);
5810b57cec5SDimitry Andric }
5820b57cec5SDimitry Andric 
583480093f4SDimitry Andric void MachineOutliner::findCandidates(
584480093f4SDimitry Andric     InstructionMapper &Mapper, std::vector<OutlinedFunction> &FunctionList) {
5850b57cec5SDimitry Andric   FunctionList.clear();
586*0fca6ea1SDimitry Andric   SuffixTree ST(Mapper.UnsignedVec, OutlinerLeafDescendants);
5870b57cec5SDimitry Andric 
588480093f4SDimitry Andric   // First, find all of the repeated substrings in the tree of minimum length
5890b57cec5SDimitry Andric   // 2.
5900b57cec5SDimitry Andric   std::vector<Candidate> CandidatesForRepeatedSeq;
59106c3fb27SDimitry Andric   LLVM_DEBUG(dbgs() << "*** Discarding overlapping candidates *** \n");
59206c3fb27SDimitry Andric   LLVM_DEBUG(
59306c3fb27SDimitry Andric       dbgs() << "Searching for overlaps in all repeated sequences...\n");
594*0fca6ea1SDimitry Andric   for (SuffixTree::RepeatedSubstring &RS : ST) {
5950b57cec5SDimitry Andric     CandidatesForRepeatedSeq.clear();
5960b57cec5SDimitry Andric     unsigned StringLen = RS.Length;
59706c3fb27SDimitry Andric     LLVM_DEBUG(dbgs() << "  Sequence length: " << StringLen << "\n");
59806c3fb27SDimitry Andric     // Debug code to keep track of how many candidates we removed.
59906c3fb27SDimitry Andric #ifndef NDEBUG
60006c3fb27SDimitry Andric     unsigned NumDiscarded = 0;
60106c3fb27SDimitry Andric     unsigned NumKept = 0;
60206c3fb27SDimitry Andric #endif
603*0fca6ea1SDimitry Andric     // Sort the start indices so that we can efficiently check if candidates
604*0fca6ea1SDimitry Andric     // overlap with the ones we've already found for this sequence.
605*0fca6ea1SDimitry Andric     llvm::sort(RS.StartIndices);
6060b57cec5SDimitry Andric     for (const unsigned &StartIdx : RS.StartIndices) {
6070b57cec5SDimitry Andric       // Trick: Discard some candidates that would be incompatible with the
6080b57cec5SDimitry Andric       // ones we've already found for this sequence. This will save us some
6090b57cec5SDimitry Andric       // work in candidate selection.
6100b57cec5SDimitry Andric       //
6110b57cec5SDimitry Andric       // If two candidates overlap, then we can't outline them both. This
6120b57cec5SDimitry Andric       // happens when we have candidates that look like, say
6130b57cec5SDimitry Andric       //
6140b57cec5SDimitry Andric       // AA (where each "A" is an instruction).
6150b57cec5SDimitry Andric       //
6160b57cec5SDimitry Andric       // We might have some portion of the module that looks like this:
6170b57cec5SDimitry Andric       // AAAAAA (6 A's)
6180b57cec5SDimitry Andric       //
6190b57cec5SDimitry Andric       // In this case, there are 5 different copies of "AA" in this range, but
6200b57cec5SDimitry Andric       // at most 3 can be outlined. If only outlining 3 of these is going to
6210b57cec5SDimitry Andric       // be unbeneficial, then we ought to not bother.
6220b57cec5SDimitry Andric       //
6230b57cec5SDimitry Andric       // Note that two things DON'T overlap when they look like this:
6240b57cec5SDimitry Andric       // start1...end1 .... start2...end2
6250b57cec5SDimitry Andric       // That is, one must either
6260b57cec5SDimitry Andric       // * End before the other starts
6270b57cec5SDimitry Andric       // * Start after the other ends
62806c3fb27SDimitry Andric       unsigned EndIdx = StartIdx + StringLen - 1;
629*0fca6ea1SDimitry Andric       if (!CandidatesForRepeatedSeq.empty() &&
630*0fca6ea1SDimitry Andric           StartIdx <= CandidatesForRepeatedSeq.back().getEndIdx()) {
63106c3fb27SDimitry Andric #ifndef NDEBUG
63206c3fb27SDimitry Andric         ++NumDiscarded;
633*0fca6ea1SDimitry Andric         LLVM_DEBUG(dbgs() << "    .. DISCARD candidate @ [" << StartIdx << ", "
634*0fca6ea1SDimitry Andric                           << EndIdx << "]; overlaps with candidate @ ["
635*0fca6ea1SDimitry Andric                           << CandidatesForRepeatedSeq.back().getStartIdx()
636*0fca6ea1SDimitry Andric                           << ", " << CandidatesForRepeatedSeq.back().getEndIdx()
637*0fca6ea1SDimitry Andric                           << "]\n");
63806c3fb27SDimitry Andric #endif
63906c3fb27SDimitry Andric         continue;
64006c3fb27SDimitry Andric       }
6410b57cec5SDimitry Andric       // It doesn't overlap with anything, so we can outline it.
6420b57cec5SDimitry Andric       // Each sequence is over [StartIt, EndIt].
6430b57cec5SDimitry Andric       // Save the candidate and its location.
64406c3fb27SDimitry Andric #ifndef NDEBUG
64506c3fb27SDimitry Andric       ++NumKept;
64606c3fb27SDimitry Andric #endif
6470b57cec5SDimitry Andric       MachineBasicBlock::iterator StartIt = Mapper.InstrList[StartIdx];
6480b57cec5SDimitry Andric       MachineBasicBlock::iterator EndIt = Mapper.InstrList[EndIdx];
6490b57cec5SDimitry Andric       MachineBasicBlock *MBB = StartIt->getParent();
65006c3fb27SDimitry Andric       CandidatesForRepeatedSeq.emplace_back(StartIdx, StringLen, StartIt, EndIt,
65106c3fb27SDimitry Andric                                             MBB, FunctionList.size(),
6520b57cec5SDimitry Andric                                             Mapper.MBBFlagsMap[MBB]);
6530b57cec5SDimitry Andric     }
65406c3fb27SDimitry Andric #ifndef NDEBUG
65506c3fb27SDimitry Andric     LLVM_DEBUG(dbgs() << "    Candidates discarded: " << NumDiscarded
65606c3fb27SDimitry Andric                       << "\n");
65706c3fb27SDimitry Andric     LLVM_DEBUG(dbgs() << "    Candidates kept: " << NumKept << "\n\n");
65806c3fb27SDimitry Andric #endif
6590b57cec5SDimitry Andric 
6600b57cec5SDimitry Andric     // We've found something we might want to outline.
6610b57cec5SDimitry Andric     // Create an OutlinedFunction to store it and check if it'd be beneficial
6620b57cec5SDimitry Andric     // to outline.
6630b57cec5SDimitry Andric     if (CandidatesForRepeatedSeq.size() < 2)
6640b57cec5SDimitry Andric       continue;
6650b57cec5SDimitry Andric 
6660b57cec5SDimitry Andric     // Arbitrarily choose a TII from the first candidate.
6670b57cec5SDimitry Andric     // FIXME: Should getOutliningCandidateInfo move to TargetMachine?
6680b57cec5SDimitry Andric     const TargetInstrInfo *TII =
6690b57cec5SDimitry Andric         CandidatesForRepeatedSeq[0].getMF()->getSubtarget().getInstrInfo();
6700b57cec5SDimitry Andric 
67106c3fb27SDimitry Andric     std::optional<OutlinedFunction> OF =
6720b57cec5SDimitry Andric         TII->getOutliningCandidateInfo(CandidatesForRepeatedSeq);
6730b57cec5SDimitry Andric 
6740b57cec5SDimitry Andric     // If we deleted too many candidates, then there's nothing worth outlining.
6750b57cec5SDimitry Andric     // FIXME: This should take target-specified instruction sizes into account.
67606c3fb27SDimitry Andric     if (!OF || OF->Candidates.size() < 2)
6770b57cec5SDimitry Andric       continue;
6780b57cec5SDimitry Andric 
6790b57cec5SDimitry Andric     // Is it better to outline this candidate than not?
68006c3fb27SDimitry Andric     if (OF->getBenefit() < OutlinerBenefitThreshold) {
68106c3fb27SDimitry Andric       emitNotOutliningCheaperRemark(StringLen, CandidatesForRepeatedSeq, *OF);
6820b57cec5SDimitry Andric       continue;
6830b57cec5SDimitry Andric     }
6840b57cec5SDimitry Andric 
68506c3fb27SDimitry Andric     FunctionList.push_back(*OF);
6860b57cec5SDimitry Andric   }
6870b57cec5SDimitry Andric }
6880b57cec5SDimitry Andric 
689480093f4SDimitry Andric MachineFunction *MachineOutliner::createOutlinedFunction(
690480093f4SDimitry Andric     Module &M, OutlinedFunction &OF, InstructionMapper &Mapper, unsigned Name) {
6910b57cec5SDimitry Andric 
6920b57cec5SDimitry Andric   // Create the function name. This should be unique.
6930b57cec5SDimitry Andric   // FIXME: We should have a better naming scheme. This should be stable,
6940b57cec5SDimitry Andric   // regardless of changes to the outliner's cost model/traversal order.
6955ffd83dbSDimitry Andric   std::string FunctionName = "OUTLINED_FUNCTION_";
6965ffd83dbSDimitry Andric   if (OutlineRepeatedNum > 0)
6975ffd83dbSDimitry Andric     FunctionName += std::to_string(OutlineRepeatedNum + 1) + "_";
6985ffd83dbSDimitry Andric   FunctionName += std::to_string(Name);
69906c3fb27SDimitry Andric   LLVM_DEBUG(dbgs() << "NEW FUNCTION: " << FunctionName << "\n");
7000b57cec5SDimitry Andric 
7010b57cec5SDimitry Andric   // Create the function using an IR-level function.
7020b57cec5SDimitry Andric   LLVMContext &C = M.getContext();
7030b57cec5SDimitry Andric   Function *F = Function::Create(FunctionType::get(Type::getVoidTy(C), false),
7040b57cec5SDimitry Andric                                  Function::ExternalLinkage, FunctionName, M);
7050b57cec5SDimitry Andric 
7060b57cec5SDimitry Andric   // NOTE: If this is linkonceodr, then we can take advantage of linker deduping
7070b57cec5SDimitry Andric   // which gives us better results when we outline from linkonceodr functions.
7080b57cec5SDimitry Andric   F->setLinkage(GlobalValue::InternalLinkage);
7090b57cec5SDimitry Andric   F->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
7100b57cec5SDimitry Andric 
7110b57cec5SDimitry Andric   // Set optsize/minsize, so we don't insert padding between outlined
7120b57cec5SDimitry Andric   // functions.
7130b57cec5SDimitry Andric   F->addFnAttr(Attribute::OptimizeForSize);
7140b57cec5SDimitry Andric   F->addFnAttr(Attribute::MinSize);
7150b57cec5SDimitry Andric 
7160b57cec5SDimitry Andric   Candidate &FirstCand = OF.Candidates.front();
7174824e7fdSDimitry Andric   const TargetInstrInfo &TII =
7184824e7fdSDimitry Andric       *FirstCand.getMF()->getSubtarget().getInstrInfo();
7190b57cec5SDimitry Andric 
7204824e7fdSDimitry Andric   TII.mergeOutliningCandidateAttributes(*F, OF.Candidates);
7215ffd83dbSDimitry Andric 
72281ad6265SDimitry Andric   // Set uwtable, so we generate eh_frame.
72381ad6265SDimitry Andric   UWTableKind UW = std::accumulate(
72481ad6265SDimitry Andric       OF.Candidates.cbegin(), OF.Candidates.cend(), UWTableKind::None,
72581ad6265SDimitry Andric       [](UWTableKind K, const outliner::Candidate &C) {
72681ad6265SDimitry Andric         return std::max(K, C.getMF()->getFunction().getUWTableKind());
72781ad6265SDimitry Andric       });
72881ad6265SDimitry Andric   F->setUWTableKind(UW);
72981ad6265SDimitry Andric 
7300b57cec5SDimitry Andric   BasicBlock *EntryBB = BasicBlock::Create(C, "entry", F);
7310b57cec5SDimitry Andric   IRBuilder<> Builder(EntryBB);
7320b57cec5SDimitry Andric   Builder.CreateRetVoid();
7330b57cec5SDimitry Andric 
7348bcb0991SDimitry Andric   MachineModuleInfo &MMI = getAnalysis<MachineModuleInfoWrapperPass>().getMMI();
7350b57cec5SDimitry Andric   MachineFunction &MF = MMI.getOrCreateMachineFunction(*F);
73606c3fb27SDimitry Andric   MF.setIsOutlined(true);
7370b57cec5SDimitry Andric   MachineBasicBlock &MBB = *MF.CreateMachineBasicBlock();
7380b57cec5SDimitry Andric 
7390b57cec5SDimitry Andric   // Insert the new function into the module.
7400b57cec5SDimitry Andric   MF.insert(MF.begin(), &MBB);
7410b57cec5SDimitry Andric 
7427a6dacacSDimitry Andric   MachineFunction *OriginalMF = FirstCand.front().getMF();
7435ffd83dbSDimitry Andric   const std::vector<MCCFIInstruction> &Instrs =
7445ffd83dbSDimitry Andric       OriginalMF->getFrameInstructions();
7457a6dacacSDimitry Andric   for (auto &MI : FirstCand) {
7467a6dacacSDimitry Andric     if (MI.isDebugInstr())
747e8d8bef9SDimitry Andric       continue;
7480b57cec5SDimitry Andric 
7490b57cec5SDimitry Andric     // Don't keep debug information for outlined instructions.
75081ad6265SDimitry Andric     auto DL = DebugLoc();
7517a6dacacSDimitry Andric     if (MI.isCFIInstruction()) {
7527a6dacacSDimitry Andric       unsigned CFIIndex = MI.getOperand(0).getCFIIndex();
75381ad6265SDimitry Andric       MCCFIInstruction CFI = Instrs[CFIIndex];
75481ad6265SDimitry Andric       BuildMI(MBB, MBB.end(), DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
75581ad6265SDimitry Andric           .addCFIIndex(MF.addFrameInst(CFI));
75681ad6265SDimitry Andric     } else {
7577a6dacacSDimitry Andric       MachineInstr *NewMI = MF.CloneMachineInstr(&MI);
75881ad6265SDimitry Andric       NewMI->dropMemRefs(MF);
75981ad6265SDimitry Andric       NewMI->setDebugLoc(DL);
7600b57cec5SDimitry Andric       MBB.insert(MBB.end(), NewMI);
7610b57cec5SDimitry Andric     }
76281ad6265SDimitry Andric   }
7630b57cec5SDimitry Andric 
7645ffd83dbSDimitry Andric   // Set normal properties for a late MachineFunction.
7655ffd83dbSDimitry Andric   MF.getProperties().reset(MachineFunctionProperties::Property::IsSSA);
7665ffd83dbSDimitry Andric   MF.getProperties().set(MachineFunctionProperties::Property::NoPHIs);
7675ffd83dbSDimitry Andric   MF.getProperties().set(MachineFunctionProperties::Property::NoVRegs);
7685ffd83dbSDimitry Andric   MF.getProperties().set(MachineFunctionProperties::Property::TracksLiveness);
769*0fca6ea1SDimitry Andric   MF.getRegInfo().freezeReservedRegs();
7700b57cec5SDimitry Andric 
7715ffd83dbSDimitry Andric   // Compute live-in set for outlined fn
7725ffd83dbSDimitry Andric   const MachineRegisterInfo &MRI = MF.getRegInfo();
7735ffd83dbSDimitry Andric   const TargetRegisterInfo &TRI = *MRI.getTargetRegisterInfo();
7745ffd83dbSDimitry Andric   LivePhysRegs LiveIns(TRI);
7755ffd83dbSDimitry Andric   for (auto &Cand : OF.Candidates) {
7765ffd83dbSDimitry Andric     // Figure out live-ins at the first instruction.
7777a6dacacSDimitry Andric     MachineBasicBlock &OutlineBB = *Cand.front().getParent();
7785ffd83dbSDimitry Andric     LivePhysRegs CandLiveIns(TRI);
7795ffd83dbSDimitry Andric     CandLiveIns.addLiveOuts(OutlineBB);
7805ffd83dbSDimitry Andric     for (const MachineInstr &MI :
7817a6dacacSDimitry Andric          reverse(make_range(Cand.begin(), OutlineBB.end())))
7825ffd83dbSDimitry Andric       CandLiveIns.stepBackward(MI);
7835ffd83dbSDimitry Andric 
7845ffd83dbSDimitry Andric     // The live-in set for the outlined function is the union of the live-ins
7855ffd83dbSDimitry Andric     // from all the outlining points.
786e8d8bef9SDimitry Andric     for (MCPhysReg Reg : CandLiveIns)
7875ffd83dbSDimitry Andric       LiveIns.addReg(Reg);
7885ffd83dbSDimitry Andric   }
7895ffd83dbSDimitry Andric   addLiveIns(MBB, LiveIns);
7905ffd83dbSDimitry Andric 
7915ffd83dbSDimitry Andric   TII.buildOutlinedFrame(MBB, MF, OF);
7925ffd83dbSDimitry Andric 
7930b57cec5SDimitry Andric   // If there's a DISubprogram associated with this outlined function, then
7940b57cec5SDimitry Andric   // emit debug info for the outlined function.
7950b57cec5SDimitry Andric   if (DISubprogram *SP = getSubprogramOrNull(OF)) {
7960b57cec5SDimitry Andric     // We have a DISubprogram. Get its DICompileUnit.
7970b57cec5SDimitry Andric     DICompileUnit *CU = SP->getUnit();
7980b57cec5SDimitry Andric     DIBuilder DB(M, true, CU);
7990b57cec5SDimitry Andric     DIFile *Unit = SP->getFile();
8000b57cec5SDimitry Andric     Mangler Mg;
8010b57cec5SDimitry Andric     // Get the mangled name of the function for the linkage name.
8020b57cec5SDimitry Andric     std::string Dummy;
80306c3fb27SDimitry Andric     raw_string_ostream MangledNameStream(Dummy);
8040b57cec5SDimitry Andric     Mg.getNameWithPrefix(MangledNameStream, F, false);
8050b57cec5SDimitry Andric 
8060b57cec5SDimitry Andric     DISubprogram *OutlinedSP = DB.createFunction(
807*0fca6ea1SDimitry Andric         Unit /* Context */, F->getName(), StringRef(Dummy), Unit /* File */,
8080b57cec5SDimitry Andric         0 /* Line 0 is reserved for compiler-generated code. */,
809bdd1243dSDimitry Andric         DB.createSubroutineType(
810bdd1243dSDimitry Andric             DB.getOrCreateTypeArray(std::nullopt)), /* void type */
8110b57cec5SDimitry Andric         0, /* Line 0 is reserved for compiler-generated code. */
8120b57cec5SDimitry Andric         DINode::DIFlags::FlagArtificial /* Compiler-generated code. */,
8130b57cec5SDimitry Andric         /* Outlined code is optimized code by definition. */
8140b57cec5SDimitry Andric         DISubprogram::SPFlagDefinition | DISubprogram::SPFlagOptimized);
8150b57cec5SDimitry Andric 
8160b57cec5SDimitry Andric     // Don't add any new variables to the subprogram.
8170b57cec5SDimitry Andric     DB.finalizeSubprogram(OutlinedSP);
8180b57cec5SDimitry Andric 
8190b57cec5SDimitry Andric     // Attach subprogram to the function.
8200b57cec5SDimitry Andric     F->setSubprogram(OutlinedSP);
8210b57cec5SDimitry Andric     // We're done with the DIBuilder.
8220b57cec5SDimitry Andric     DB.finalize();
8230b57cec5SDimitry Andric   }
8240b57cec5SDimitry Andric 
8250b57cec5SDimitry Andric   return &MF;
8260b57cec5SDimitry Andric }
8270b57cec5SDimitry Andric 
8280b57cec5SDimitry Andric bool MachineOutliner::outline(Module &M,
8290b57cec5SDimitry Andric                               std::vector<OutlinedFunction> &FunctionList,
830480093f4SDimitry Andric                               InstructionMapper &Mapper,
831480093f4SDimitry Andric                               unsigned &OutlinedFunctionNum) {
83206c3fb27SDimitry Andric   LLVM_DEBUG(dbgs() << "*** Outlining ***\n");
83306c3fb27SDimitry Andric   LLVM_DEBUG(dbgs() << "NUMBER OF POTENTIAL FUNCTIONS: " << FunctionList.size()
83406c3fb27SDimitry Andric                     << "\n");
8350b57cec5SDimitry Andric   bool OutlinedSomething = false;
8360b57cec5SDimitry Andric 
837*0fca6ea1SDimitry Andric   // Sort by priority where priority := getNotOutlinedCost / getOutliningCost.
838*0fca6ea1SDimitry Andric   // The function with highest priority should be outlined first.
83906c3fb27SDimitry Andric   stable_sort(FunctionList,
84006c3fb27SDimitry Andric               [](const OutlinedFunction &LHS, const OutlinedFunction &RHS) {
841*0fca6ea1SDimitry Andric                 return LHS.getNotOutlinedCost() * RHS.getOutliningCost() >
842*0fca6ea1SDimitry Andric                        RHS.getNotOutlinedCost() * LHS.getOutliningCost();
8430b57cec5SDimitry Andric               });
8440b57cec5SDimitry Andric 
8450b57cec5SDimitry Andric   // Walk over each function, outlining them as we go along. Functions are
8460b57cec5SDimitry Andric   // outlined greedily, based off the sort above.
84706c3fb27SDimitry Andric   auto *UnsignedVecBegin = Mapper.UnsignedVec.begin();
84806c3fb27SDimitry Andric   LLVM_DEBUG(dbgs() << "WALKING FUNCTION LIST\n");
8490b57cec5SDimitry Andric   for (OutlinedFunction &OF : FunctionList) {
85006c3fb27SDimitry Andric #ifndef NDEBUG
85106c3fb27SDimitry Andric     auto NumCandidatesBefore = OF.Candidates.size();
85206c3fb27SDimitry Andric #endif
8530b57cec5SDimitry Andric     // If we outlined something that overlapped with a candidate in a previous
8540b57cec5SDimitry Andric     // step, then we can't outline from it.
85506c3fb27SDimitry Andric     erase_if(OF.Candidates, [&UnsignedVecBegin](Candidate &C) {
85606c3fb27SDimitry Andric       return std::any_of(UnsignedVecBegin + C.getStartIdx(),
85706c3fb27SDimitry Andric                          UnsignedVecBegin + C.getEndIdx() + 1, [](unsigned I) {
85806c3fb27SDimitry Andric                            return I == static_cast<unsigned>(-1);
85906c3fb27SDimitry Andric                          });
8600b57cec5SDimitry Andric     });
8610b57cec5SDimitry Andric 
86206c3fb27SDimitry Andric #ifndef NDEBUG
86306c3fb27SDimitry Andric     auto NumCandidatesAfter = OF.Candidates.size();
86406c3fb27SDimitry Andric     LLVM_DEBUG(dbgs() << "PRUNED: " << NumCandidatesBefore - NumCandidatesAfter
86506c3fb27SDimitry Andric                       << "/" << NumCandidatesBefore << " candidates\n");
86606c3fb27SDimitry Andric #endif
86706c3fb27SDimitry Andric 
8680b57cec5SDimitry Andric     // If we made it unbeneficial to outline this function, skip it.
86906c3fb27SDimitry Andric     if (OF.getBenefit() < OutlinerBenefitThreshold) {
87006c3fb27SDimitry Andric       LLVM_DEBUG(dbgs() << "SKIP: Expected benefit (" << OF.getBenefit()
87106c3fb27SDimitry Andric                         << " B) < threshold (" << OutlinerBenefitThreshold
87206c3fb27SDimitry Andric                         << " B)\n");
8730b57cec5SDimitry Andric       continue;
87406c3fb27SDimitry Andric     }
87506c3fb27SDimitry Andric 
87606c3fb27SDimitry Andric     LLVM_DEBUG(dbgs() << "OUTLINE: Expected benefit (" << OF.getBenefit()
87706c3fb27SDimitry Andric                       << " B) > threshold (" << OutlinerBenefitThreshold
87806c3fb27SDimitry Andric                       << " B)\n");
8790b57cec5SDimitry Andric 
8800b57cec5SDimitry Andric     // It's beneficial. Create the function and outline its sequence's
8810b57cec5SDimitry Andric     // occurrences.
8820b57cec5SDimitry Andric     OF.MF = createOutlinedFunction(M, OF, Mapper, OutlinedFunctionNum);
8830b57cec5SDimitry Andric     emitOutlinedFunctionRemark(OF);
8840b57cec5SDimitry Andric     FunctionsCreated++;
8850b57cec5SDimitry Andric     OutlinedFunctionNum++; // Created a function, move to the next name.
8860b57cec5SDimitry Andric     MachineFunction *MF = OF.MF;
8870b57cec5SDimitry Andric     const TargetSubtargetInfo &STI = MF->getSubtarget();
8880b57cec5SDimitry Andric     const TargetInstrInfo &TII = *STI.getInstrInfo();
8890b57cec5SDimitry Andric 
8900b57cec5SDimitry Andric     // Replace occurrences of the sequence with calls to the new function.
89106c3fb27SDimitry Andric     LLVM_DEBUG(dbgs() << "CREATE OUTLINED CALLS\n");
8920b57cec5SDimitry Andric     for (Candidate &C : OF.Candidates) {
8930b57cec5SDimitry Andric       MachineBasicBlock &MBB = *C.getMBB();
8947a6dacacSDimitry Andric       MachineBasicBlock::iterator StartIt = C.begin();
8957a6dacacSDimitry Andric       MachineBasicBlock::iterator EndIt = std::prev(C.end());
8960b57cec5SDimitry Andric 
8970b57cec5SDimitry Andric       // Insert the call.
8980b57cec5SDimitry Andric       auto CallInst = TII.insertOutlinedCall(M, MBB, StartIt, *MF, C);
89906c3fb27SDimitry Andric // Insert the call.
90006c3fb27SDimitry Andric #ifndef NDEBUG
90106c3fb27SDimitry Andric       auto MBBBeingOutlinedFromName =
90206c3fb27SDimitry Andric           MBB.getName().empty() ? "<unknown>" : MBB.getName().str();
90306c3fb27SDimitry Andric       auto MFBeingOutlinedFromName = MBB.getParent()->getName().empty()
90406c3fb27SDimitry Andric                                          ? "<unknown>"
90506c3fb27SDimitry Andric                                          : MBB.getParent()->getName().str();
90606c3fb27SDimitry Andric       LLVM_DEBUG(dbgs() << "  CALL: " << MF->getName() << " in "
90706c3fb27SDimitry Andric                         << MFBeingOutlinedFromName << ":"
90806c3fb27SDimitry Andric                         << MBBBeingOutlinedFromName << "\n");
90906c3fb27SDimitry Andric       LLVM_DEBUG(dbgs() << "   .. " << *CallInst);
91006c3fb27SDimitry Andric #endif
9110b57cec5SDimitry Andric 
9120b57cec5SDimitry Andric       // If the caller tracks liveness, then we need to make sure that
9130b57cec5SDimitry Andric       // anything we outline doesn't break liveness assumptions. The outlined
9140b57cec5SDimitry Andric       // functions themselves currently don't track liveness, but we should
9150b57cec5SDimitry Andric       // make sure that the ranges we yank things out of aren't wrong.
9160b57cec5SDimitry Andric       if (MBB.getParent()->getProperties().hasProperty(
9170b57cec5SDimitry Andric               MachineFunctionProperties::Property::TracksLiveness)) {
9185ffd83dbSDimitry Andric         // The following code is to add implicit def operands to the call
9190b57cec5SDimitry Andric         // instruction. It also updates call site information for moved
9200b57cec5SDimitry Andric         // code.
9215ffd83dbSDimitry Andric         SmallSet<Register, 2> UseRegs, DefRegs;
9220b57cec5SDimitry Andric         // Copy over the defs in the outlined range.
9230b57cec5SDimitry Andric         // First inst in outlined range <-- Anything that's defined in this
9240b57cec5SDimitry Andric         // ...                           .. range has to be added as an
9250b57cec5SDimitry Andric         // implicit Last inst in outlined range  <-- def to the call
9260b57cec5SDimitry Andric         // instruction. Also remove call site information for outlined block
9275ffd83dbSDimitry Andric         // of code. The exposed uses need to be copied in the outlined range.
9285ffd83dbSDimitry Andric         for (MachineBasicBlock::reverse_iterator
9295ffd83dbSDimitry Andric                  Iter = EndIt.getReverse(),
9305ffd83dbSDimitry Andric                  Last = std::next(CallInst.getReverse());
9315ffd83dbSDimitry Andric              Iter != Last; Iter++) {
9325ffd83dbSDimitry Andric           MachineInstr *MI = &*Iter;
933349cc55cSDimitry Andric           SmallSet<Register, 2> InstrUseRegs;
9345ffd83dbSDimitry Andric           for (MachineOperand &MOP : MI->operands()) {
9355ffd83dbSDimitry Andric             // Skip over anything that isn't a register.
9365ffd83dbSDimitry Andric             if (!MOP.isReg())
9375ffd83dbSDimitry Andric               continue;
9385ffd83dbSDimitry Andric 
9395ffd83dbSDimitry Andric             if (MOP.isDef()) {
9405ffd83dbSDimitry Andric               // Introduce DefRegs set to skip the redundant register.
9415ffd83dbSDimitry Andric               DefRegs.insert(MOP.getReg());
942349cc55cSDimitry Andric               if (UseRegs.count(MOP.getReg()) &&
943349cc55cSDimitry Andric                   !InstrUseRegs.count(MOP.getReg()))
9445ffd83dbSDimitry Andric                 // Since the regiester is modeled as defined,
9455ffd83dbSDimitry Andric                 // it is not necessary to be put in use register set.
9465ffd83dbSDimitry Andric                 UseRegs.erase(MOP.getReg());
9475ffd83dbSDimitry Andric             } else if (!MOP.isUndef()) {
9485ffd83dbSDimitry Andric               // Any register which is not undefined should
9495ffd83dbSDimitry Andric               // be put in the use register set.
9505ffd83dbSDimitry Andric               UseRegs.insert(MOP.getReg());
951349cc55cSDimitry Andric               InstrUseRegs.insert(MOP.getReg());
9525ffd83dbSDimitry Andric             }
9535ffd83dbSDimitry Andric           }
9545ffd83dbSDimitry Andric           if (MI->isCandidateForCallSiteEntry())
9555ffd83dbSDimitry Andric             MI->getMF()->eraseCallSiteInfo(MI);
9565ffd83dbSDimitry Andric         }
9575ffd83dbSDimitry Andric 
9585ffd83dbSDimitry Andric         for (const Register &I : DefRegs)
9595ffd83dbSDimitry Andric           // If it's a def, add it to the call instruction.
9605ffd83dbSDimitry Andric           CallInst->addOperand(
9615ffd83dbSDimitry Andric               MachineOperand::CreateReg(I, true, /* isDef = true */
9625ffd83dbSDimitry Andric                                         true /* isImp = true */));
9635ffd83dbSDimitry Andric 
9645ffd83dbSDimitry Andric         for (const Register &I : UseRegs)
9655ffd83dbSDimitry Andric           // If it's a exposed use, add it to the call instruction.
9665ffd83dbSDimitry Andric           CallInst->addOperand(
9675ffd83dbSDimitry Andric               MachineOperand::CreateReg(I, false, /* isDef = false */
9685ffd83dbSDimitry Andric                                         true /* isImp = true */));
9690b57cec5SDimitry Andric       }
9700b57cec5SDimitry Andric 
9710b57cec5SDimitry Andric       // Erase from the point after where the call was inserted up to, and
9720b57cec5SDimitry Andric       // including, the final instruction in the sequence.
9730b57cec5SDimitry Andric       // Erase needs one past the end, so we need std::next there too.
9740b57cec5SDimitry Andric       MBB.erase(std::next(StartIt), std::next(EndIt));
9750b57cec5SDimitry Andric 
9760b57cec5SDimitry Andric       // Keep track of what we removed by marking them all as -1.
97706c3fb27SDimitry Andric       for (unsigned &I : make_range(UnsignedVecBegin + C.getStartIdx(),
97806c3fb27SDimitry Andric                                     UnsignedVecBegin + C.getEndIdx() + 1))
97981ad6265SDimitry Andric         I = static_cast<unsigned>(-1);
9800b57cec5SDimitry Andric       OutlinedSomething = true;
9810b57cec5SDimitry Andric 
9820b57cec5SDimitry Andric       // Statistics.
9830b57cec5SDimitry Andric       NumOutlined++;
9840b57cec5SDimitry Andric     }
9850b57cec5SDimitry Andric   }
9860b57cec5SDimitry Andric 
9870b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "OutlinedSomething = " << OutlinedSomething << "\n";);
9880b57cec5SDimitry Andric   return OutlinedSomething;
9890b57cec5SDimitry Andric }
9900b57cec5SDimitry Andric 
9910b57cec5SDimitry Andric void MachineOutliner::populateMapper(InstructionMapper &Mapper, Module &M,
9920b57cec5SDimitry Andric                                      MachineModuleInfo &MMI) {
9930b57cec5SDimitry Andric   // Build instruction mappings for each function in the module. Start by
9940b57cec5SDimitry Andric   // iterating over each Function in M.
99506c3fb27SDimitry Andric   LLVM_DEBUG(dbgs() << "*** Populating mapper ***\n");
9960b57cec5SDimitry Andric   for (Function &F : M) {
99706c3fb27SDimitry Andric     LLVM_DEBUG(dbgs() << "MAPPING FUNCTION: " << F.getName() << "\n");
9980b57cec5SDimitry Andric 
999bdd1243dSDimitry Andric     if (F.hasFnAttribute("nooutline")) {
100006c3fb27SDimitry Andric       LLVM_DEBUG(dbgs() << "SKIP: Function has nooutline attribute\n");
10010b57cec5SDimitry Andric       continue;
1002bdd1243dSDimitry Andric     }
10030b57cec5SDimitry Andric 
10040b57cec5SDimitry Andric     // There's something in F. Check if it has a MachineFunction associated with
10050b57cec5SDimitry Andric     // it.
10060b57cec5SDimitry Andric     MachineFunction *MF = MMI.getMachineFunction(F);
10070b57cec5SDimitry Andric 
10080b57cec5SDimitry Andric     // If it doesn't, then there's nothing to outline from. Move to the next
10090b57cec5SDimitry Andric     // Function.
101006c3fb27SDimitry Andric     if (!MF) {
101106c3fb27SDimitry Andric       LLVM_DEBUG(dbgs() << "SKIP: Function does not have a MachineFunction\n");
10120b57cec5SDimitry Andric       continue;
101306c3fb27SDimitry Andric     }
10140b57cec5SDimitry Andric 
10150b57cec5SDimitry Andric     const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
101606c3fb27SDimitry Andric     if (!RunOnAllFunctions && !TII->shouldOutlineFromFunctionByDefault(*MF)) {
101706c3fb27SDimitry Andric       LLVM_DEBUG(dbgs() << "SKIP: Target does not want to outline from "
101806c3fb27SDimitry Andric                            "function by default\n");
10190b57cec5SDimitry Andric       continue;
102006c3fb27SDimitry Andric     }
10210b57cec5SDimitry Andric 
10220b57cec5SDimitry Andric     // We have a MachineFunction. Ask the target if it's suitable for outlining.
10230b57cec5SDimitry Andric     // If it isn't, then move on to the next Function in the module.
102406c3fb27SDimitry Andric     if (!TII->isFunctionSafeToOutlineFrom(*MF, OutlineFromLinkOnceODRs)) {
102506c3fb27SDimitry Andric       LLVM_DEBUG(dbgs() << "SKIP: " << MF->getName()
102606c3fb27SDimitry Andric                         << ": unsafe to outline from\n");
10270b57cec5SDimitry Andric       continue;
102806c3fb27SDimitry Andric     }
10290b57cec5SDimitry Andric 
10300b57cec5SDimitry Andric     // We have a function suitable for outlining. Iterate over every
10310b57cec5SDimitry Andric     // MachineBasicBlock in MF and try to map its instructions to a list of
10320b57cec5SDimitry Andric     // unsigned integers.
103306c3fb27SDimitry Andric     const unsigned MinMBBSize = 2;
103406c3fb27SDimitry Andric 
10350b57cec5SDimitry Andric     for (MachineBasicBlock &MBB : *MF) {
103606c3fb27SDimitry Andric       LLVM_DEBUG(dbgs() << "  MAPPING MBB: '" << MBB.getName() << "'\n");
10370b57cec5SDimitry Andric       // If there isn't anything in MBB, then there's no point in outlining from
10380b57cec5SDimitry Andric       // it.
10390b57cec5SDimitry Andric       // If there are fewer than 2 instructions in the MBB, then it can't ever
10400b57cec5SDimitry Andric       // contain something worth outlining.
10410b57cec5SDimitry Andric       // FIXME: This should be based off of the maximum size in B of an outlined
10420b57cec5SDimitry Andric       // call versus the size in B of the MBB.
104306c3fb27SDimitry Andric       if (MBB.size() < MinMBBSize) {
104406c3fb27SDimitry Andric         LLVM_DEBUG(dbgs() << "    SKIP: MBB size less than minimum size of "
104506c3fb27SDimitry Andric                           << MinMBBSize << "\n");
10460b57cec5SDimitry Andric         continue;
104706c3fb27SDimitry Andric       }
10480b57cec5SDimitry Andric 
10490b57cec5SDimitry Andric       // Check if MBB could be the target of an indirect branch. If it is, then
10500b57cec5SDimitry Andric       // we don't want to outline from it.
105106c3fb27SDimitry Andric       if (MBB.hasAddressTaken()) {
105206c3fb27SDimitry Andric         LLVM_DEBUG(dbgs() << "    SKIP: MBB's address is taken\n");
10530b57cec5SDimitry Andric         continue;
105406c3fb27SDimitry Andric       }
10550b57cec5SDimitry Andric 
10560b57cec5SDimitry Andric       // MBB is suitable for outlining. Map it to a list of unsigneds.
10570b57cec5SDimitry Andric       Mapper.convertToUnsignedVec(MBB, *TII);
10580b57cec5SDimitry Andric     }
105906c3fb27SDimitry Andric   }
106081ad6265SDimitry Andric   // Statistics.
106181ad6265SDimitry Andric   UnsignedVecSize = Mapper.UnsignedVec.size();
10620b57cec5SDimitry Andric }
10630b57cec5SDimitry Andric 
10640b57cec5SDimitry Andric void MachineOutliner::initSizeRemarkInfo(
10650b57cec5SDimitry Andric     const Module &M, const MachineModuleInfo &MMI,
10660b57cec5SDimitry Andric     StringMap<unsigned> &FunctionToInstrCount) {
10670b57cec5SDimitry Andric   // Collect instruction counts for every function. We'll use this to emit
10680b57cec5SDimitry Andric   // per-function size remarks later.
10690b57cec5SDimitry Andric   for (const Function &F : M) {
10700b57cec5SDimitry Andric     MachineFunction *MF = MMI.getMachineFunction(F);
10710b57cec5SDimitry Andric 
10720b57cec5SDimitry Andric     // We only care about MI counts here. If there's no MachineFunction at this
10730b57cec5SDimitry Andric     // point, then there won't be after the outliner runs, so let's move on.
10740b57cec5SDimitry Andric     if (!MF)
10750b57cec5SDimitry Andric       continue;
10760b57cec5SDimitry Andric     FunctionToInstrCount[F.getName().str()] = MF->getInstructionCount();
10770b57cec5SDimitry Andric   }
10780b57cec5SDimitry Andric }
10790b57cec5SDimitry Andric 
10800b57cec5SDimitry Andric void MachineOutliner::emitInstrCountChangedRemark(
10810b57cec5SDimitry Andric     const Module &M, const MachineModuleInfo &MMI,
10820b57cec5SDimitry Andric     const StringMap<unsigned> &FunctionToInstrCount) {
10830b57cec5SDimitry Andric   // Iterate over each function in the module and emit remarks.
10840b57cec5SDimitry Andric   // Note that we won't miss anything by doing this, because the outliner never
10850b57cec5SDimitry Andric   // deletes functions.
10860b57cec5SDimitry Andric   for (const Function &F : M) {
10870b57cec5SDimitry Andric     MachineFunction *MF = MMI.getMachineFunction(F);
10880b57cec5SDimitry Andric 
10890b57cec5SDimitry Andric     // The outliner never deletes functions. If we don't have a MF here, then we
10900b57cec5SDimitry Andric     // didn't have one prior to outlining either.
10910b57cec5SDimitry Andric     if (!MF)
10920b57cec5SDimitry Andric       continue;
10930b57cec5SDimitry Andric 
10945ffd83dbSDimitry Andric     std::string Fname = std::string(F.getName());
10950b57cec5SDimitry Andric     unsigned FnCountAfter = MF->getInstructionCount();
10960b57cec5SDimitry Andric     unsigned FnCountBefore = 0;
10970b57cec5SDimitry Andric 
10980b57cec5SDimitry Andric     // Check if the function was recorded before.
10990b57cec5SDimitry Andric     auto It = FunctionToInstrCount.find(Fname);
11000b57cec5SDimitry Andric 
11010b57cec5SDimitry Andric     // Did we have a previously-recorded size? If yes, then set FnCountBefore
11020b57cec5SDimitry Andric     // to that.
11030b57cec5SDimitry Andric     if (It != FunctionToInstrCount.end())
11040b57cec5SDimitry Andric       FnCountBefore = It->second;
11050b57cec5SDimitry Andric 
11060b57cec5SDimitry Andric     // Compute the delta and emit a remark if there was a change.
11070b57cec5SDimitry Andric     int64_t FnDelta = static_cast<int64_t>(FnCountAfter) -
11080b57cec5SDimitry Andric                       static_cast<int64_t>(FnCountBefore);
11090b57cec5SDimitry Andric     if (FnDelta == 0)
11100b57cec5SDimitry Andric       continue;
11110b57cec5SDimitry Andric 
11120b57cec5SDimitry Andric     MachineOptimizationRemarkEmitter MORE(*MF, nullptr);
11130b57cec5SDimitry Andric     MORE.emit([&]() {
11140b57cec5SDimitry Andric       MachineOptimizationRemarkAnalysis R("size-info", "FunctionMISizeChange",
1115480093f4SDimitry Andric                                           DiagnosticLocation(), &MF->front());
11160b57cec5SDimitry Andric       R << DiagnosticInfoOptimizationBase::Argument("Pass", "Machine Outliner")
11170b57cec5SDimitry Andric         << ": Function: "
11180b57cec5SDimitry Andric         << DiagnosticInfoOptimizationBase::Argument("Function", F.getName())
11190b57cec5SDimitry Andric         << ": MI instruction count changed from "
11200b57cec5SDimitry Andric         << DiagnosticInfoOptimizationBase::Argument("MIInstrsBefore",
11210b57cec5SDimitry Andric                                                     FnCountBefore)
11220b57cec5SDimitry Andric         << " to "
11230b57cec5SDimitry Andric         << DiagnosticInfoOptimizationBase::Argument("MIInstrsAfter",
11240b57cec5SDimitry Andric                                                     FnCountAfter)
11250b57cec5SDimitry Andric         << "; Delta: "
11260b57cec5SDimitry Andric         << DiagnosticInfoOptimizationBase::Argument("Delta", FnDelta);
11270b57cec5SDimitry Andric       return R;
11280b57cec5SDimitry Andric     });
11290b57cec5SDimitry Andric   }
11300b57cec5SDimitry Andric }
11310b57cec5SDimitry Andric 
11320b57cec5SDimitry Andric bool MachineOutliner::runOnModule(Module &M) {
11330b57cec5SDimitry Andric   // Check if there's anything in the module. If it's empty, then there's
11340b57cec5SDimitry Andric   // nothing to outline.
11350b57cec5SDimitry Andric   if (M.empty())
11360b57cec5SDimitry Andric     return false;
11370b57cec5SDimitry Andric 
1138480093f4SDimitry Andric   // Number to append to the current outlined function.
1139480093f4SDimitry Andric   unsigned OutlinedFunctionNum = 0;
1140480093f4SDimitry Andric 
11415ffd83dbSDimitry Andric   OutlineRepeatedNum = 0;
1142480093f4SDimitry Andric   if (!doOutline(M, OutlinedFunctionNum))
1143480093f4SDimitry Andric     return false;
11445ffd83dbSDimitry Andric 
11455ffd83dbSDimitry Andric   for (unsigned I = 0; I < OutlinerReruns; ++I) {
11465ffd83dbSDimitry Andric     OutlinedFunctionNum = 0;
11475ffd83dbSDimitry Andric     OutlineRepeatedNum++;
11485ffd83dbSDimitry Andric     if (!doOutline(M, OutlinedFunctionNum)) {
11495ffd83dbSDimitry Andric       LLVM_DEBUG({
11505ffd83dbSDimitry Andric         dbgs() << "Did not outline on iteration " << I + 2 << " out of "
11515ffd83dbSDimitry Andric                << OutlinerReruns + 1 << "\n";
11525ffd83dbSDimitry Andric       });
11535ffd83dbSDimitry Andric       break;
11545ffd83dbSDimitry Andric     }
11555ffd83dbSDimitry Andric   }
11565ffd83dbSDimitry Andric 
1157480093f4SDimitry Andric   return true;
1158480093f4SDimitry Andric }
1159480093f4SDimitry Andric 
1160480093f4SDimitry Andric bool MachineOutliner::doOutline(Module &M, unsigned &OutlinedFunctionNum) {
11618bcb0991SDimitry Andric   MachineModuleInfo &MMI = getAnalysis<MachineModuleInfoWrapperPass>().getMMI();
11620b57cec5SDimitry Andric 
11630b57cec5SDimitry Andric   // If the user passed -enable-machine-outliner=always or
11640b57cec5SDimitry Andric   // -enable-machine-outliner, the pass will run on all functions in the module.
11650b57cec5SDimitry Andric   // Otherwise, if the target supports default outlining, it will run on all
11660b57cec5SDimitry Andric   // functions deemed by the target to be worth outlining from by default. Tell
11670b57cec5SDimitry Andric   // the user how the outliner is running.
1168480093f4SDimitry Andric   LLVM_DEBUG({
11690b57cec5SDimitry Andric     dbgs() << "Machine Outliner: Running on ";
11700b57cec5SDimitry Andric     if (RunOnAllFunctions)
11710b57cec5SDimitry Andric       dbgs() << "all functions";
11720b57cec5SDimitry Andric     else
11730b57cec5SDimitry Andric       dbgs() << "target-default functions";
1174480093f4SDimitry Andric     dbgs() << "\n";
1175480093f4SDimitry Andric   });
11760b57cec5SDimitry Andric 
11770b57cec5SDimitry Andric   // If the user specifies that they want to outline from linkonceodrs, set
11780b57cec5SDimitry Andric   // it here.
11790b57cec5SDimitry Andric   OutlineFromLinkOnceODRs = EnableLinkOnceODROutlining;
11800b57cec5SDimitry Andric   InstructionMapper Mapper;
11810b57cec5SDimitry Andric 
11820b57cec5SDimitry Andric   // Prepare instruction mappings for the suffix tree.
11830b57cec5SDimitry Andric   populateMapper(Mapper, M, MMI);
11840b57cec5SDimitry Andric   std::vector<OutlinedFunction> FunctionList;
11850b57cec5SDimitry Andric 
11860b57cec5SDimitry Andric   // Find all of the outlining candidates.
11870b57cec5SDimitry Andric   findCandidates(Mapper, FunctionList);
11880b57cec5SDimitry Andric 
11890b57cec5SDimitry Andric   // If we've requested size remarks, then collect the MI counts of every
11900b57cec5SDimitry Andric   // function before outlining, and the MI counts after outlining.
11910b57cec5SDimitry Andric   // FIXME: This shouldn't be in the outliner at all; it should ultimately be
11920b57cec5SDimitry Andric   // the pass manager's responsibility.
11930b57cec5SDimitry Andric   // This could pretty easily be placed in outline instead, but because we
11940b57cec5SDimitry Andric   // really ultimately *don't* want this here, it's done like this for now
11950b57cec5SDimitry Andric   // instead.
11960b57cec5SDimitry Andric 
11970b57cec5SDimitry Andric   // Check if we want size remarks.
11980b57cec5SDimitry Andric   bool ShouldEmitSizeRemarks = M.shouldEmitInstrCountChangedRemark();
11990b57cec5SDimitry Andric   StringMap<unsigned> FunctionToInstrCount;
12000b57cec5SDimitry Andric   if (ShouldEmitSizeRemarks)
12010b57cec5SDimitry Andric     initSizeRemarkInfo(M, MMI, FunctionToInstrCount);
12020b57cec5SDimitry Andric 
12030b57cec5SDimitry Andric   // Outline each of the candidates and return true if something was outlined.
1204480093f4SDimitry Andric   bool OutlinedSomething =
1205480093f4SDimitry Andric       outline(M, FunctionList, Mapper, OutlinedFunctionNum);
12060b57cec5SDimitry Andric 
12070b57cec5SDimitry Andric   // If we outlined something, we definitely changed the MI count of the
12080b57cec5SDimitry Andric   // module. If we've asked for size remarks, then output them.
12090b57cec5SDimitry Andric   // FIXME: This should be in the pass manager.
12100b57cec5SDimitry Andric   if (ShouldEmitSizeRemarks && OutlinedSomething)
12110b57cec5SDimitry Andric     emitInstrCountChangedRemark(M, MMI, FunctionToInstrCount);
12120b57cec5SDimitry Andric 
12135ffd83dbSDimitry Andric   LLVM_DEBUG({
12145ffd83dbSDimitry Andric     if (!OutlinedSomething)
12155ffd83dbSDimitry Andric       dbgs() << "Stopped outlining at iteration " << OutlineRepeatedNum
12165ffd83dbSDimitry Andric              << " because no changes were found.\n";
12175ffd83dbSDimitry Andric   });
12185ffd83dbSDimitry Andric 
12190b57cec5SDimitry Andric   return OutlinedSomething;
12200b57cec5SDimitry Andric }
1221