xref: /openbsd-src/gnu/llvm/llvm/lib/CodeGen/MachineOutliner.cpp (revision d415bd752c734aee168c4ee86ff32e8cc249eb16)
109467b48Spatrick //===---- MachineOutliner.cpp - Outline instructions -----------*- C++ -*-===//
209467b48Spatrick //
309467b48Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
409467b48Spatrick // See https://llvm.org/LICENSE.txt for license information.
509467b48Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
609467b48Spatrick //
709467b48Spatrick //===----------------------------------------------------------------------===//
809467b48Spatrick ///
909467b48Spatrick /// \file
1009467b48Spatrick /// Replaces repeated sequences of instructions with function calls.
1109467b48Spatrick ///
1209467b48Spatrick /// This works by placing every instruction from every basic block in a
1309467b48Spatrick /// suffix tree, and repeatedly querying that tree for repeated sequences of
1409467b48Spatrick /// instructions. If a sequence of instructions appears often, then it ought
1509467b48Spatrick /// to be beneficial to pull out into a function.
1609467b48Spatrick ///
1709467b48Spatrick /// The MachineOutliner communicates with a given target using hooks defined in
1809467b48Spatrick /// TargetInstrInfo.h. The target supplies the outliner with information on how
1909467b48Spatrick /// a specific sequence of instructions should be outlined. This information
2009467b48Spatrick /// is used to deduce the number of instructions necessary to
2109467b48Spatrick ///
2209467b48Spatrick /// * Create an outlined function
2309467b48Spatrick /// * Call that outlined function
2409467b48Spatrick ///
2509467b48Spatrick /// Targets must implement
2609467b48Spatrick ///   * getOutliningCandidateInfo
2709467b48Spatrick ///   * buildOutlinedFrame
2809467b48Spatrick ///   * insertOutlinedCall
2909467b48Spatrick ///   * isFunctionSafeToOutlineFrom
3009467b48Spatrick ///
3109467b48Spatrick /// in order to make use of the MachineOutliner.
3209467b48Spatrick ///
3309467b48Spatrick /// This was originally presented at the 2016 LLVM Developers' Meeting in the
3409467b48Spatrick /// talk "Reducing Code Size Using Outlining". For a high-level overview of
3509467b48Spatrick /// how this pass works, the talk is available on YouTube at
3609467b48Spatrick ///
3709467b48Spatrick /// https://www.youtube.com/watch?v=yorld-WSOeU
3809467b48Spatrick ///
3909467b48Spatrick /// The slides for the talk are available at
4009467b48Spatrick ///
4109467b48Spatrick /// http://www.llvm.org/devmtg/2016-11/Slides/Paquette-Outliner.pdf
4209467b48Spatrick ///
4309467b48Spatrick /// The talk provides an overview of how the outliner finds candidates and
4409467b48Spatrick /// ultimately outlines them. It describes how the main data structure for this
4509467b48Spatrick /// pass, the suffix tree, is queried and purged for candidates. It also gives
4609467b48Spatrick /// a simplified suffix tree construction algorithm for suffix trees based off
4709467b48Spatrick /// of the algorithm actually used here, Ukkonen's algorithm.
4809467b48Spatrick ///
4909467b48Spatrick /// For the original RFC for this pass, please see
5009467b48Spatrick ///
5109467b48Spatrick /// http://lists.llvm.org/pipermail/llvm-dev/2016-August/104170.html
5209467b48Spatrick ///
5309467b48Spatrick /// For more information on the suffix tree data structure, please see
5409467b48Spatrick /// https://www.cs.helsinki.fi/u/ukkonen/SuffixT1withFigs.pdf
5509467b48Spatrick ///
5609467b48Spatrick //===----------------------------------------------------------------------===//
5709467b48Spatrick #include "llvm/CodeGen/MachineOutliner.h"
5809467b48Spatrick #include "llvm/ADT/DenseMap.h"
59097a140dSpatrick #include "llvm/ADT/SmallSet.h"
6009467b48Spatrick #include "llvm/ADT/Statistic.h"
6109467b48Spatrick #include "llvm/ADT/Twine.h"
62*d415bd75Srobert #include "llvm/Analysis/OptimizationRemarkEmitter.h"
63*d415bd75Srobert #include "llvm/CodeGen/LivePhysRegs.h"
6409467b48Spatrick #include "llvm/CodeGen/MachineModuleInfo.h"
6509467b48Spatrick #include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h"
6609467b48Spatrick #include "llvm/CodeGen/Passes.h"
6709467b48Spatrick #include "llvm/CodeGen/TargetInstrInfo.h"
6809467b48Spatrick #include "llvm/CodeGen/TargetSubtargetInfo.h"
6909467b48Spatrick #include "llvm/IR/DIBuilder.h"
7009467b48Spatrick #include "llvm/IR/IRBuilder.h"
7109467b48Spatrick #include "llvm/IR/Mangler.h"
7209467b48Spatrick #include "llvm/InitializePasses.h"
7309467b48Spatrick #include "llvm/Support/CommandLine.h"
7409467b48Spatrick #include "llvm/Support/Debug.h"
75097a140dSpatrick #include "llvm/Support/SuffixTree.h"
7609467b48Spatrick #include "llvm/Support/raw_ostream.h"
7709467b48Spatrick #include <functional>
7809467b48Spatrick #include <tuple>
7909467b48Spatrick #include <vector>
8009467b48Spatrick 
8109467b48Spatrick #define DEBUG_TYPE "machine-outliner"
8209467b48Spatrick 
8309467b48Spatrick using namespace llvm;
8409467b48Spatrick using namespace ore;
8509467b48Spatrick using namespace outliner;
8609467b48Spatrick 
87*d415bd75Srobert // Statistics for outlined functions.
8809467b48Spatrick STATISTIC(NumOutlined, "Number of candidates outlined");
8909467b48Spatrick STATISTIC(FunctionsCreated, "Number of functions created");
9009467b48Spatrick 
91*d415bd75Srobert // Statistics for instruction mapping.
92*d415bd75Srobert STATISTIC(NumLegalInUnsignedVec, "Number of legal instrs in unsigned vector");
93*d415bd75Srobert STATISTIC(NumIllegalInUnsignedVec,
94*d415bd75Srobert           "Number of illegal instrs in unsigned vector");
95*d415bd75Srobert STATISTIC(NumInvisible, "Number of invisible instrs in unsigned vector");
96*d415bd75Srobert STATISTIC(UnsignedVecSize, "Size of unsigned vector");
97*d415bd75Srobert 
9809467b48Spatrick // Set to true if the user wants the outliner to run on linkonceodr linkage
9909467b48Spatrick // functions. This is false by default because the linker can dedupe linkonceodr
10009467b48Spatrick // functions. Since the outliner is confined to a single module (modulo LTO),
10109467b48Spatrick // this is off by default. It should, however, be the default behaviour in
10209467b48Spatrick // LTO.
10309467b48Spatrick static cl::opt<bool> EnableLinkOnceODROutlining(
10409467b48Spatrick     "enable-linkonceodr-outlining", cl::Hidden,
10509467b48Spatrick     cl::desc("Enable the machine outliner on linkonceodr functions"),
10609467b48Spatrick     cl::init(false));
10709467b48Spatrick 
108097a140dSpatrick /// Number of times to re-run the outliner. This is not the total number of runs
109097a140dSpatrick /// as the outliner will run at least one time. The default value is set to 0,
110097a140dSpatrick /// meaning the outliner will run one time and rerun zero times after that.
111097a140dSpatrick static cl::opt<unsigned> OutlinerReruns(
112097a140dSpatrick     "machine-outliner-reruns", cl::init(0), cl::Hidden,
113097a140dSpatrick     cl::desc(
114097a140dSpatrick         "Number of times to rerun the outliner after the initial outline"));
115097a140dSpatrick 
11609467b48Spatrick namespace {
11709467b48Spatrick 
11809467b48Spatrick /// Maps \p MachineInstrs to unsigned integers and stores the mappings.
11909467b48Spatrick struct InstructionMapper {
12009467b48Spatrick 
12109467b48Spatrick   /// The next available integer to assign to a \p MachineInstr that
12209467b48Spatrick   /// cannot be outlined.
12309467b48Spatrick   ///
12409467b48Spatrick   /// Set to -3 for compatability with \p DenseMapInfo<unsigned>.
12509467b48Spatrick   unsigned IllegalInstrNumber = -3;
12609467b48Spatrick 
12709467b48Spatrick   /// The next available integer to assign to a \p MachineInstr that can
12809467b48Spatrick   /// be outlined.
12909467b48Spatrick   unsigned LegalInstrNumber = 0;
13009467b48Spatrick 
13109467b48Spatrick   /// Correspondence from \p MachineInstrs to unsigned integers.
13209467b48Spatrick   DenseMap<MachineInstr *, unsigned, MachineInstrExpressionTrait>
13309467b48Spatrick       InstructionIntegerMap;
13409467b48Spatrick 
13509467b48Spatrick   /// Correspondence between \p MachineBasicBlocks and target-defined flags.
13609467b48Spatrick   DenseMap<MachineBasicBlock *, unsigned> MBBFlagsMap;
13709467b48Spatrick 
13809467b48Spatrick   /// The vector of unsigned integers that the module is mapped to.
13909467b48Spatrick   std::vector<unsigned> UnsignedVec;
14009467b48Spatrick 
14109467b48Spatrick   /// Stores the location of the instruction associated with the integer
14209467b48Spatrick   /// at index i in \p UnsignedVec for each index i.
14309467b48Spatrick   std::vector<MachineBasicBlock::iterator> InstrList;
14409467b48Spatrick 
14509467b48Spatrick   // Set if we added an illegal number in the previous step.
14609467b48Spatrick   // Since each illegal number is unique, we only need one of them between
14709467b48Spatrick   // each range of legal numbers. This lets us make sure we don't add more
14809467b48Spatrick   // than one illegal number per range.
14909467b48Spatrick   bool AddedIllegalLastTime = false;
15009467b48Spatrick 
15109467b48Spatrick   /// Maps \p *It to a legal integer.
15209467b48Spatrick   ///
15309467b48Spatrick   /// Updates \p CanOutlineWithPrevInstr, \p HaveLegalRange, \p InstrListForMBB,
15409467b48Spatrick   /// \p UnsignedVecForMBB, \p InstructionIntegerMap, and \p LegalInstrNumber.
15509467b48Spatrick   ///
15609467b48Spatrick   /// \returns The integer that \p *It was mapped to.
mapToLegalUnsigned__anon0a415d520111::InstructionMapper15709467b48Spatrick   unsigned mapToLegalUnsigned(
15809467b48Spatrick       MachineBasicBlock::iterator &It, bool &CanOutlineWithPrevInstr,
15909467b48Spatrick       bool &HaveLegalRange, unsigned &NumLegalInBlock,
16009467b48Spatrick       std::vector<unsigned> &UnsignedVecForMBB,
16109467b48Spatrick       std::vector<MachineBasicBlock::iterator> &InstrListForMBB) {
16209467b48Spatrick     // We added something legal, so we should unset the AddedLegalLastTime
16309467b48Spatrick     // flag.
16409467b48Spatrick     AddedIllegalLastTime = false;
16509467b48Spatrick 
16609467b48Spatrick     // If we have at least two adjacent legal instructions (which may have
16709467b48Spatrick     // invisible instructions in between), remember that.
16809467b48Spatrick     if (CanOutlineWithPrevInstr)
16909467b48Spatrick       HaveLegalRange = true;
17009467b48Spatrick     CanOutlineWithPrevInstr = true;
17109467b48Spatrick 
17209467b48Spatrick     // Keep track of the number of legal instructions we insert.
17309467b48Spatrick     NumLegalInBlock++;
17409467b48Spatrick 
17509467b48Spatrick     // Get the integer for this instruction or give it the current
17609467b48Spatrick     // LegalInstrNumber.
17709467b48Spatrick     InstrListForMBB.push_back(It);
17809467b48Spatrick     MachineInstr &MI = *It;
17909467b48Spatrick     bool WasInserted;
18009467b48Spatrick     DenseMap<MachineInstr *, unsigned, MachineInstrExpressionTrait>::iterator
18109467b48Spatrick         ResultIt;
18209467b48Spatrick     std::tie(ResultIt, WasInserted) =
18309467b48Spatrick         InstructionIntegerMap.insert(std::make_pair(&MI, LegalInstrNumber));
18409467b48Spatrick     unsigned MINumber = ResultIt->second;
18509467b48Spatrick 
18609467b48Spatrick     // There was an insertion.
18709467b48Spatrick     if (WasInserted)
18809467b48Spatrick       LegalInstrNumber++;
18909467b48Spatrick 
19009467b48Spatrick     UnsignedVecForMBB.push_back(MINumber);
19109467b48Spatrick 
19209467b48Spatrick     // Make sure we don't overflow or use any integers reserved by the DenseMap.
19309467b48Spatrick     if (LegalInstrNumber >= IllegalInstrNumber)
19409467b48Spatrick       report_fatal_error("Instruction mapping overflow!");
19509467b48Spatrick 
19609467b48Spatrick     assert(LegalInstrNumber != DenseMapInfo<unsigned>::getEmptyKey() &&
19709467b48Spatrick            "Tried to assign DenseMap tombstone or empty key to instruction.");
19809467b48Spatrick     assert(LegalInstrNumber != DenseMapInfo<unsigned>::getTombstoneKey() &&
19909467b48Spatrick            "Tried to assign DenseMap tombstone or empty key to instruction.");
20009467b48Spatrick 
201*d415bd75Srobert     // Statistics.
202*d415bd75Srobert     ++NumLegalInUnsignedVec;
20309467b48Spatrick     return MINumber;
20409467b48Spatrick   }
20509467b48Spatrick 
20609467b48Spatrick   /// Maps \p *It to an illegal integer.
20709467b48Spatrick   ///
20809467b48Spatrick   /// Updates \p InstrListForMBB, \p UnsignedVecForMBB, and \p
20909467b48Spatrick   /// IllegalInstrNumber.
21009467b48Spatrick   ///
21109467b48Spatrick   /// \returns The integer that \p *It was mapped to.
mapToIllegalUnsigned__anon0a415d520111::InstructionMapper21209467b48Spatrick   unsigned mapToIllegalUnsigned(
21309467b48Spatrick       MachineBasicBlock::iterator &It, bool &CanOutlineWithPrevInstr,
21409467b48Spatrick       std::vector<unsigned> &UnsignedVecForMBB,
21509467b48Spatrick       std::vector<MachineBasicBlock::iterator> &InstrListForMBB) {
21609467b48Spatrick     // Can't outline an illegal instruction. Set the flag.
21709467b48Spatrick     CanOutlineWithPrevInstr = false;
21809467b48Spatrick 
21909467b48Spatrick     // Only add one illegal number per range of legal numbers.
22009467b48Spatrick     if (AddedIllegalLastTime)
22109467b48Spatrick       return IllegalInstrNumber;
22209467b48Spatrick 
22309467b48Spatrick     // Remember that we added an illegal number last time.
22409467b48Spatrick     AddedIllegalLastTime = true;
22509467b48Spatrick     unsigned MINumber = IllegalInstrNumber;
22609467b48Spatrick 
22709467b48Spatrick     InstrListForMBB.push_back(It);
22809467b48Spatrick     UnsignedVecForMBB.push_back(IllegalInstrNumber);
22909467b48Spatrick     IllegalInstrNumber--;
230*d415bd75Srobert     // Statistics.
231*d415bd75Srobert     ++NumIllegalInUnsignedVec;
23209467b48Spatrick 
23309467b48Spatrick     assert(LegalInstrNumber < IllegalInstrNumber &&
23409467b48Spatrick            "Instruction mapping overflow!");
23509467b48Spatrick 
23609467b48Spatrick     assert(IllegalInstrNumber != DenseMapInfo<unsigned>::getEmptyKey() &&
23709467b48Spatrick            "IllegalInstrNumber cannot be DenseMap tombstone or empty key!");
23809467b48Spatrick 
23909467b48Spatrick     assert(IllegalInstrNumber != DenseMapInfo<unsigned>::getTombstoneKey() &&
24009467b48Spatrick            "IllegalInstrNumber cannot be DenseMap tombstone or empty key!");
24109467b48Spatrick 
24209467b48Spatrick     return MINumber;
24309467b48Spatrick   }
24409467b48Spatrick 
24509467b48Spatrick   /// Transforms a \p MachineBasicBlock into a \p vector of \p unsigneds
24609467b48Spatrick   /// and appends it to \p UnsignedVec and \p InstrList.
24709467b48Spatrick   ///
24809467b48Spatrick   /// Two instructions are assigned the same integer if they are identical.
24909467b48Spatrick   /// If an instruction is deemed unsafe to outline, then it will be assigned an
25009467b48Spatrick   /// unique integer. The resulting mapping is placed into a suffix tree and
25109467b48Spatrick   /// queried for candidates.
25209467b48Spatrick   ///
25309467b48Spatrick   /// \param MBB The \p MachineBasicBlock to be translated into integers.
25409467b48Spatrick   /// \param TII \p TargetInstrInfo for the function.
convertToUnsignedVec__anon0a415d520111::InstructionMapper25509467b48Spatrick   void convertToUnsignedVec(MachineBasicBlock &MBB,
25609467b48Spatrick                             const TargetInstrInfo &TII) {
25709467b48Spatrick     unsigned Flags = 0;
25809467b48Spatrick 
25909467b48Spatrick     // Don't even map in this case.
26009467b48Spatrick     if (!TII.isMBBSafeToOutlineFrom(MBB, Flags))
26109467b48Spatrick       return;
26209467b48Spatrick 
26309467b48Spatrick     // Store info for the MBB for later outlining.
26409467b48Spatrick     MBBFlagsMap[&MBB] = Flags;
26509467b48Spatrick 
26609467b48Spatrick     MachineBasicBlock::iterator It = MBB.begin();
26709467b48Spatrick 
26809467b48Spatrick     // The number of instructions in this block that will be considered for
26909467b48Spatrick     // outlining.
27009467b48Spatrick     unsigned NumLegalInBlock = 0;
27109467b48Spatrick 
27209467b48Spatrick     // True if we have at least two legal instructions which aren't separated
27309467b48Spatrick     // by an illegal instruction.
27409467b48Spatrick     bool HaveLegalRange = false;
27509467b48Spatrick 
27609467b48Spatrick     // True if we can perform outlining given the last mapped (non-invisible)
27709467b48Spatrick     // instruction. This lets us know if we have a legal range.
27809467b48Spatrick     bool CanOutlineWithPrevInstr = false;
27909467b48Spatrick 
28009467b48Spatrick     // FIXME: Should this all just be handled in the target, rather than using
28109467b48Spatrick     // repeated calls to getOutliningType?
28209467b48Spatrick     std::vector<unsigned> UnsignedVecForMBB;
28309467b48Spatrick     std::vector<MachineBasicBlock::iterator> InstrListForMBB;
28409467b48Spatrick 
28509467b48Spatrick     for (MachineBasicBlock::iterator Et = MBB.end(); It != Et; ++It) {
28609467b48Spatrick       // Keep track of where this instruction is in the module.
28709467b48Spatrick       switch (TII.getOutliningType(It, Flags)) {
28809467b48Spatrick       case InstrType::Illegal:
28909467b48Spatrick         mapToIllegalUnsigned(It, CanOutlineWithPrevInstr, UnsignedVecForMBB,
29009467b48Spatrick                              InstrListForMBB);
29109467b48Spatrick         break;
29209467b48Spatrick 
29309467b48Spatrick       case InstrType::Legal:
29409467b48Spatrick         mapToLegalUnsigned(It, CanOutlineWithPrevInstr, HaveLegalRange,
29509467b48Spatrick                            NumLegalInBlock, UnsignedVecForMBB, InstrListForMBB);
29609467b48Spatrick         break;
29709467b48Spatrick 
29809467b48Spatrick       case InstrType::LegalTerminator:
29909467b48Spatrick         mapToLegalUnsigned(It, CanOutlineWithPrevInstr, HaveLegalRange,
30009467b48Spatrick                            NumLegalInBlock, UnsignedVecForMBB, InstrListForMBB);
30109467b48Spatrick         // The instruction also acts as a terminator, so we have to record that
30209467b48Spatrick         // in the string.
30309467b48Spatrick         mapToIllegalUnsigned(It, CanOutlineWithPrevInstr, UnsignedVecForMBB,
30409467b48Spatrick                              InstrListForMBB);
30509467b48Spatrick         break;
30609467b48Spatrick 
30709467b48Spatrick       case InstrType::Invisible:
30809467b48Spatrick         // Normally this is set by mapTo(Blah)Unsigned, but we just want to
30909467b48Spatrick         // skip this instruction. So, unset the flag here.
310*d415bd75Srobert         ++NumInvisible;
31109467b48Spatrick         AddedIllegalLastTime = false;
31209467b48Spatrick         break;
31309467b48Spatrick       }
31409467b48Spatrick     }
31509467b48Spatrick 
31609467b48Spatrick     // Are there enough legal instructions in the block for outlining to be
31709467b48Spatrick     // possible?
31809467b48Spatrick     if (HaveLegalRange) {
31909467b48Spatrick       // After we're done every insertion, uniquely terminate this part of the
32009467b48Spatrick       // "string". This makes sure we won't match across basic block or function
32109467b48Spatrick       // boundaries since the "end" is encoded uniquely and thus appears in no
32209467b48Spatrick       // repeated substring.
32309467b48Spatrick       mapToIllegalUnsigned(It, CanOutlineWithPrevInstr, UnsignedVecForMBB,
32409467b48Spatrick                            InstrListForMBB);
32573471bf0Spatrick       llvm::append_range(InstrList, InstrListForMBB);
32673471bf0Spatrick       llvm::append_range(UnsignedVec, UnsignedVecForMBB);
32709467b48Spatrick     }
32809467b48Spatrick   }
32909467b48Spatrick 
InstructionMapper__anon0a415d520111::InstructionMapper33009467b48Spatrick   InstructionMapper() {
33109467b48Spatrick     // Make sure that the implementation of DenseMapInfo<unsigned> hasn't
33209467b48Spatrick     // changed.
33309467b48Spatrick     assert(DenseMapInfo<unsigned>::getEmptyKey() == (unsigned)-1 &&
33409467b48Spatrick            "DenseMapInfo<unsigned>'s empty key isn't -1!");
33509467b48Spatrick     assert(DenseMapInfo<unsigned>::getTombstoneKey() == (unsigned)-2 &&
33609467b48Spatrick            "DenseMapInfo<unsigned>'s tombstone key isn't -2!");
33709467b48Spatrick   }
33809467b48Spatrick };
33909467b48Spatrick 
34009467b48Spatrick /// An interprocedural pass which finds repeated sequences of
34109467b48Spatrick /// instructions and replaces them with calls to functions.
34209467b48Spatrick ///
34309467b48Spatrick /// Each instruction is mapped to an unsigned integer and placed in a string.
34409467b48Spatrick /// The resulting mapping is then placed in a \p SuffixTree. The \p SuffixTree
34509467b48Spatrick /// is then repeatedly queried for repeated sequences of instructions. Each
34609467b48Spatrick /// non-overlapping repeated sequence is then placed in its own
34709467b48Spatrick /// \p MachineFunction and each instance is then replaced with a call to that
34809467b48Spatrick /// function.
34909467b48Spatrick struct MachineOutliner : public ModulePass {
35009467b48Spatrick 
35109467b48Spatrick   static char ID;
35209467b48Spatrick 
35309467b48Spatrick   /// Set to true if the outliner should consider functions with
35409467b48Spatrick   /// linkonceodr linkage.
35509467b48Spatrick   bool OutlineFromLinkOnceODRs = false;
35609467b48Spatrick 
357097a140dSpatrick   /// The current repeat number of machine outlining.
358097a140dSpatrick   unsigned OutlineRepeatedNum = 0;
359097a140dSpatrick 
36009467b48Spatrick   /// Set to true if the outliner should run on all functions in the module
36109467b48Spatrick   /// considered safe for outlining.
36209467b48Spatrick   /// Set to true by default for compatibility with llc's -run-pass option.
36309467b48Spatrick   /// Set when the pass is constructed in TargetPassConfig.
36409467b48Spatrick   bool RunOnAllFunctions = true;
36509467b48Spatrick 
getPassName__anon0a415d520111::MachineOutliner36609467b48Spatrick   StringRef getPassName() const override { return "Machine Outliner"; }
36709467b48Spatrick 
getAnalysisUsage__anon0a415d520111::MachineOutliner36809467b48Spatrick   void getAnalysisUsage(AnalysisUsage &AU) const override {
36909467b48Spatrick     AU.addRequired<MachineModuleInfoWrapperPass>();
37009467b48Spatrick     AU.addPreserved<MachineModuleInfoWrapperPass>();
37109467b48Spatrick     AU.setPreservesAll();
37209467b48Spatrick     ModulePass::getAnalysisUsage(AU);
37309467b48Spatrick   }
37409467b48Spatrick 
MachineOutliner__anon0a415d520111::MachineOutliner37509467b48Spatrick   MachineOutliner() : ModulePass(ID) {
37609467b48Spatrick     initializeMachineOutlinerPass(*PassRegistry::getPassRegistry());
37709467b48Spatrick   }
37809467b48Spatrick 
37909467b48Spatrick   /// Remark output explaining that not outlining a set of candidates would be
38009467b48Spatrick   /// better than outlining that set.
38109467b48Spatrick   void emitNotOutliningCheaperRemark(
38209467b48Spatrick       unsigned StringLen, std::vector<Candidate> &CandidatesForRepeatedSeq,
38309467b48Spatrick       OutlinedFunction &OF);
38409467b48Spatrick 
38509467b48Spatrick   /// Remark output explaining that a function was outlined.
38609467b48Spatrick   void emitOutlinedFunctionRemark(OutlinedFunction &OF);
38709467b48Spatrick 
38809467b48Spatrick   /// Find all repeated substrings that satisfy the outlining cost model by
38909467b48Spatrick   /// constructing a suffix tree.
39009467b48Spatrick   ///
39109467b48Spatrick   /// If a substring appears at least twice, then it must be represented by
39209467b48Spatrick   /// an internal node which appears in at least two suffixes. Each suffix
39309467b48Spatrick   /// is represented by a leaf node. To do this, we visit each internal node
39409467b48Spatrick   /// in the tree, using the leaf children of each internal node. If an
39509467b48Spatrick   /// internal node represents a beneficial substring, then we use each of
39609467b48Spatrick   /// its leaf children to find the locations of its substring.
39709467b48Spatrick   ///
39809467b48Spatrick   /// \param Mapper Contains outlining mapping information.
39909467b48Spatrick   /// \param[out] FunctionList Filled with a list of \p OutlinedFunctions
40009467b48Spatrick   /// each type of candidate.
40109467b48Spatrick   void findCandidates(InstructionMapper &Mapper,
40209467b48Spatrick                       std::vector<OutlinedFunction> &FunctionList);
40309467b48Spatrick 
40409467b48Spatrick   /// Replace the sequences of instructions represented by \p OutlinedFunctions
40509467b48Spatrick   /// with calls to functions.
40609467b48Spatrick   ///
40709467b48Spatrick   /// \param M The module we are outlining from.
40809467b48Spatrick   /// \param FunctionList A list of functions to be inserted into the module.
40909467b48Spatrick   /// \param Mapper Contains the instruction mappings for the module.
41009467b48Spatrick   bool outline(Module &M, std::vector<OutlinedFunction> &FunctionList,
41109467b48Spatrick                InstructionMapper &Mapper, unsigned &OutlinedFunctionNum);
41209467b48Spatrick 
41309467b48Spatrick   /// Creates a function for \p OF and inserts it into the module.
41409467b48Spatrick   MachineFunction *createOutlinedFunction(Module &M, OutlinedFunction &OF,
41509467b48Spatrick                                           InstructionMapper &Mapper,
41609467b48Spatrick                                           unsigned Name);
41709467b48Spatrick 
418097a140dSpatrick   /// Calls 'doOutline()' 1 + OutlinerReruns times.
41909467b48Spatrick   bool runOnModule(Module &M) override;
42009467b48Spatrick 
42109467b48Spatrick   /// Construct a suffix tree on the instructions in \p M and outline repeated
42209467b48Spatrick   /// strings from that tree.
42309467b48Spatrick   bool doOutline(Module &M, unsigned &OutlinedFunctionNum);
42409467b48Spatrick 
42509467b48Spatrick   /// Return a DISubprogram for OF if one exists, and null otherwise. Helper
42609467b48Spatrick   /// function for remark emission.
getSubprogramOrNull__anon0a415d520111::MachineOutliner42709467b48Spatrick   DISubprogram *getSubprogramOrNull(const OutlinedFunction &OF) {
42809467b48Spatrick     for (const Candidate &C : OF.Candidates)
42909467b48Spatrick       if (MachineFunction *MF = C.getMF())
43009467b48Spatrick         if (DISubprogram *SP = MF->getFunction().getSubprogram())
43109467b48Spatrick           return SP;
43209467b48Spatrick     return nullptr;
43309467b48Spatrick   }
43409467b48Spatrick 
43509467b48Spatrick   /// Populate and \p InstructionMapper with instruction-to-integer mappings.
43609467b48Spatrick   /// These are used to construct a suffix tree.
43709467b48Spatrick   void populateMapper(InstructionMapper &Mapper, Module &M,
43809467b48Spatrick                       MachineModuleInfo &MMI);
43909467b48Spatrick 
44009467b48Spatrick   /// Initialize information necessary to output a size remark.
44109467b48Spatrick   /// FIXME: This should be handled by the pass manager, not the outliner.
44209467b48Spatrick   /// FIXME: This is nearly identical to the initSizeRemarkInfo in the legacy
44309467b48Spatrick   /// pass manager.
44409467b48Spatrick   void initSizeRemarkInfo(const Module &M, const MachineModuleInfo &MMI,
44509467b48Spatrick                           StringMap<unsigned> &FunctionToInstrCount);
44609467b48Spatrick 
44709467b48Spatrick   /// Emit the remark.
44809467b48Spatrick   // FIXME: This should be handled by the pass manager, not the outliner.
44909467b48Spatrick   void
45009467b48Spatrick   emitInstrCountChangedRemark(const Module &M, const MachineModuleInfo &MMI,
45109467b48Spatrick                               const StringMap<unsigned> &FunctionToInstrCount);
45209467b48Spatrick };
45309467b48Spatrick } // Anonymous namespace.
45409467b48Spatrick 
45509467b48Spatrick char MachineOutliner::ID = 0;
45609467b48Spatrick 
45709467b48Spatrick namespace llvm {
createMachineOutlinerPass(bool RunOnAllFunctions)45809467b48Spatrick ModulePass *createMachineOutlinerPass(bool RunOnAllFunctions) {
45909467b48Spatrick   MachineOutliner *OL = new MachineOutliner();
46009467b48Spatrick   OL->RunOnAllFunctions = RunOnAllFunctions;
46109467b48Spatrick   return OL;
46209467b48Spatrick }
46309467b48Spatrick 
46409467b48Spatrick } // namespace llvm
46509467b48Spatrick 
46609467b48Spatrick INITIALIZE_PASS(MachineOutliner, DEBUG_TYPE, "Machine Function Outliner", false,
46709467b48Spatrick                 false)
46809467b48Spatrick 
emitNotOutliningCheaperRemark(unsigned StringLen,std::vector<Candidate> & CandidatesForRepeatedSeq,OutlinedFunction & OF)46909467b48Spatrick void MachineOutliner::emitNotOutliningCheaperRemark(
47009467b48Spatrick     unsigned StringLen, std::vector<Candidate> &CandidatesForRepeatedSeq,
47109467b48Spatrick     OutlinedFunction &OF) {
47209467b48Spatrick   // FIXME: Right now, we arbitrarily choose some Candidate from the
47309467b48Spatrick   // OutlinedFunction. This isn't necessarily fixed, nor does it have to be.
47409467b48Spatrick   // We should probably sort these by function name or something to make sure
47509467b48Spatrick   // the remarks are stable.
47609467b48Spatrick   Candidate &C = CandidatesForRepeatedSeq.front();
47709467b48Spatrick   MachineOptimizationRemarkEmitter MORE(*(C.getMF()), nullptr);
47809467b48Spatrick   MORE.emit([&]() {
47909467b48Spatrick     MachineOptimizationRemarkMissed R(DEBUG_TYPE, "NotOutliningCheaper",
48009467b48Spatrick                                       C.front()->getDebugLoc(), C.getMBB());
48109467b48Spatrick     R << "Did not outline " << NV("Length", StringLen) << " instructions"
48209467b48Spatrick       << " from " << NV("NumOccurrences", CandidatesForRepeatedSeq.size())
48309467b48Spatrick       << " locations."
48409467b48Spatrick       << " Bytes from outlining all occurrences ("
48509467b48Spatrick       << NV("OutliningCost", OF.getOutliningCost()) << ")"
48609467b48Spatrick       << " >= Unoutlined instruction bytes ("
48709467b48Spatrick       << NV("NotOutliningCost", OF.getNotOutlinedCost()) << ")"
48809467b48Spatrick       << " (Also found at: ";
48909467b48Spatrick 
49009467b48Spatrick     // Tell the user the other places the candidate was found.
49109467b48Spatrick     for (unsigned i = 1, e = CandidatesForRepeatedSeq.size(); i < e; i++) {
49209467b48Spatrick       R << NV((Twine("OtherStartLoc") + Twine(i)).str(),
49309467b48Spatrick               CandidatesForRepeatedSeq[i].front()->getDebugLoc());
49409467b48Spatrick       if (i != e - 1)
49509467b48Spatrick         R << ", ";
49609467b48Spatrick     }
49709467b48Spatrick 
49809467b48Spatrick     R << ")";
49909467b48Spatrick     return R;
50009467b48Spatrick   });
50109467b48Spatrick }
50209467b48Spatrick 
emitOutlinedFunctionRemark(OutlinedFunction & OF)50309467b48Spatrick void MachineOutliner::emitOutlinedFunctionRemark(OutlinedFunction &OF) {
50409467b48Spatrick   MachineBasicBlock *MBB = &*OF.MF->begin();
50509467b48Spatrick   MachineOptimizationRemarkEmitter MORE(*OF.MF, nullptr);
50609467b48Spatrick   MachineOptimizationRemark R(DEBUG_TYPE, "OutlinedFunction",
50709467b48Spatrick                               MBB->findDebugLoc(MBB->begin()), MBB);
50809467b48Spatrick   R << "Saved " << NV("OutliningBenefit", OF.getBenefit()) << " bytes by "
50909467b48Spatrick     << "outlining " << NV("Length", OF.getNumInstrs()) << " instructions "
51009467b48Spatrick     << "from " << NV("NumOccurrences", OF.getOccurrenceCount())
51109467b48Spatrick     << " locations. "
51209467b48Spatrick     << "(Found at: ";
51309467b48Spatrick 
51409467b48Spatrick   // Tell the user the other places the candidate was found.
51509467b48Spatrick   for (size_t i = 0, e = OF.Candidates.size(); i < e; i++) {
51609467b48Spatrick 
51709467b48Spatrick     R << NV((Twine("StartLoc") + Twine(i)).str(),
51809467b48Spatrick             OF.Candidates[i].front()->getDebugLoc());
51909467b48Spatrick     if (i != e - 1)
52009467b48Spatrick       R << ", ";
52109467b48Spatrick   }
52209467b48Spatrick 
52309467b48Spatrick   R << ")";
52409467b48Spatrick 
52509467b48Spatrick   MORE.emit(R);
52609467b48Spatrick }
52709467b48Spatrick 
findCandidates(InstructionMapper & Mapper,std::vector<OutlinedFunction> & FunctionList)52809467b48Spatrick void MachineOutliner::findCandidates(
52909467b48Spatrick     InstructionMapper &Mapper, std::vector<OutlinedFunction> &FunctionList) {
53009467b48Spatrick   FunctionList.clear();
53109467b48Spatrick   SuffixTree ST(Mapper.UnsignedVec);
53209467b48Spatrick 
53309467b48Spatrick   // First, find all of the repeated substrings in the tree of minimum length
53409467b48Spatrick   // 2.
53509467b48Spatrick   std::vector<Candidate> CandidatesForRepeatedSeq;
53673471bf0Spatrick   for (const SuffixTree::RepeatedSubstring &RS : ST) {
53709467b48Spatrick     CandidatesForRepeatedSeq.clear();
53809467b48Spatrick     unsigned StringLen = RS.Length;
53909467b48Spatrick     for (const unsigned &StartIdx : RS.StartIndices) {
54009467b48Spatrick       unsigned EndIdx = StartIdx + StringLen - 1;
54109467b48Spatrick       // Trick: Discard some candidates that would be incompatible with the
54209467b48Spatrick       // ones we've already found for this sequence. This will save us some
54309467b48Spatrick       // work in candidate selection.
54409467b48Spatrick       //
54509467b48Spatrick       // If two candidates overlap, then we can't outline them both. This
54609467b48Spatrick       // happens when we have candidates that look like, say
54709467b48Spatrick       //
54809467b48Spatrick       // AA (where each "A" is an instruction).
54909467b48Spatrick       //
55009467b48Spatrick       // We might have some portion of the module that looks like this:
55109467b48Spatrick       // AAAAAA (6 A's)
55209467b48Spatrick       //
55309467b48Spatrick       // In this case, there are 5 different copies of "AA" in this range, but
55409467b48Spatrick       // at most 3 can be outlined. If only outlining 3 of these is going to
55509467b48Spatrick       // be unbeneficial, then we ought to not bother.
55609467b48Spatrick       //
55709467b48Spatrick       // Note that two things DON'T overlap when they look like this:
55809467b48Spatrick       // start1...end1 .... start2...end2
55909467b48Spatrick       // That is, one must either
56009467b48Spatrick       // * End before the other starts
56109467b48Spatrick       // * Start after the other ends
56273471bf0Spatrick       if (llvm::all_of(CandidatesForRepeatedSeq, [&StartIdx,
56373471bf0Spatrick                                                   &EndIdx](const Candidate &C) {
56409467b48Spatrick             return (EndIdx < C.getStartIdx() || StartIdx > C.getEndIdx());
56509467b48Spatrick           })) {
56609467b48Spatrick         // It doesn't overlap with anything, so we can outline it.
56709467b48Spatrick         // Each sequence is over [StartIt, EndIt].
56809467b48Spatrick         // Save the candidate and its location.
56909467b48Spatrick 
57009467b48Spatrick         MachineBasicBlock::iterator StartIt = Mapper.InstrList[StartIdx];
57109467b48Spatrick         MachineBasicBlock::iterator EndIt = Mapper.InstrList[EndIdx];
57209467b48Spatrick         MachineBasicBlock *MBB = StartIt->getParent();
57309467b48Spatrick 
57409467b48Spatrick         CandidatesForRepeatedSeq.emplace_back(StartIdx, StringLen, StartIt,
57509467b48Spatrick                                               EndIt, MBB, FunctionList.size(),
57609467b48Spatrick                                               Mapper.MBBFlagsMap[MBB]);
57709467b48Spatrick       }
57809467b48Spatrick     }
57909467b48Spatrick 
58009467b48Spatrick     // We've found something we might want to outline.
58109467b48Spatrick     // Create an OutlinedFunction to store it and check if it'd be beneficial
58209467b48Spatrick     // to outline.
58309467b48Spatrick     if (CandidatesForRepeatedSeq.size() < 2)
58409467b48Spatrick       continue;
58509467b48Spatrick 
58609467b48Spatrick     // Arbitrarily choose a TII from the first candidate.
58709467b48Spatrick     // FIXME: Should getOutliningCandidateInfo move to TargetMachine?
58809467b48Spatrick     const TargetInstrInfo *TII =
58909467b48Spatrick         CandidatesForRepeatedSeq[0].getMF()->getSubtarget().getInstrInfo();
59009467b48Spatrick 
59109467b48Spatrick     OutlinedFunction OF =
59209467b48Spatrick         TII->getOutliningCandidateInfo(CandidatesForRepeatedSeq);
59309467b48Spatrick 
59409467b48Spatrick     // If we deleted too many candidates, then there's nothing worth outlining.
59509467b48Spatrick     // FIXME: This should take target-specified instruction sizes into account.
59609467b48Spatrick     if (OF.Candidates.size() < 2)
59709467b48Spatrick       continue;
59809467b48Spatrick 
59909467b48Spatrick     // Is it better to outline this candidate than not?
60009467b48Spatrick     if (OF.getBenefit() < 1) {
60109467b48Spatrick       emitNotOutliningCheaperRemark(StringLen, CandidatesForRepeatedSeq, OF);
60209467b48Spatrick       continue;
60309467b48Spatrick     }
60409467b48Spatrick 
60509467b48Spatrick     FunctionList.push_back(OF);
60609467b48Spatrick   }
60709467b48Spatrick }
60809467b48Spatrick 
createOutlinedFunction(Module & M,OutlinedFunction & OF,InstructionMapper & Mapper,unsigned Name)60909467b48Spatrick MachineFunction *MachineOutliner::createOutlinedFunction(
61009467b48Spatrick     Module &M, OutlinedFunction &OF, InstructionMapper &Mapper, unsigned Name) {
61109467b48Spatrick 
61209467b48Spatrick   // Create the function name. This should be unique.
61309467b48Spatrick   // FIXME: We should have a better naming scheme. This should be stable,
61409467b48Spatrick   // regardless of changes to the outliner's cost model/traversal order.
615097a140dSpatrick   std::string FunctionName = "OUTLINED_FUNCTION_";
616097a140dSpatrick   if (OutlineRepeatedNum > 0)
617097a140dSpatrick     FunctionName += std::to_string(OutlineRepeatedNum + 1) + "_";
618097a140dSpatrick   FunctionName += std::to_string(Name);
61909467b48Spatrick 
62009467b48Spatrick   // Create the function using an IR-level function.
62109467b48Spatrick   LLVMContext &C = M.getContext();
62209467b48Spatrick   Function *F = Function::Create(FunctionType::get(Type::getVoidTy(C), false),
62309467b48Spatrick                                  Function::ExternalLinkage, FunctionName, M);
62409467b48Spatrick 
62509467b48Spatrick   // NOTE: If this is linkonceodr, then we can take advantage of linker deduping
62609467b48Spatrick   // which gives us better results when we outline from linkonceodr functions.
62709467b48Spatrick   F->setLinkage(GlobalValue::InternalLinkage);
62809467b48Spatrick   F->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
62909467b48Spatrick 
63009467b48Spatrick   // Set optsize/minsize, so we don't insert padding between outlined
63109467b48Spatrick   // functions.
63209467b48Spatrick   F->addFnAttr(Attribute::OptimizeForSize);
63309467b48Spatrick   F->addFnAttr(Attribute::MinSize);
63409467b48Spatrick 
63509467b48Spatrick   Candidate &FirstCand = OF.Candidates.front();
636*d415bd75Srobert   const TargetInstrInfo &TII =
637*d415bd75Srobert       *FirstCand.getMF()->getSubtarget().getInstrInfo();
63809467b48Spatrick 
639*d415bd75Srobert   TII.mergeOutliningCandidateAttributes(*F, OF.Candidates);
640*d415bd75Srobert 
641*d415bd75Srobert   // Set uwtable, so we generate eh_frame.
642*d415bd75Srobert   UWTableKind UW = std::accumulate(
643*d415bd75Srobert       OF.Candidates.cbegin(), OF.Candidates.cend(), UWTableKind::None,
644*d415bd75Srobert       [](UWTableKind K, const outliner::Candidate &C) {
645*d415bd75Srobert         return std::max(K, C.getMF()->getFunction().getUWTableKind());
646*d415bd75Srobert       });
647*d415bd75Srobert   if (UW != UWTableKind::None)
648*d415bd75Srobert     F->setUWTableKind(UW);
649097a140dSpatrick 
65009467b48Spatrick   BasicBlock *EntryBB = BasicBlock::Create(C, "entry", F);
65109467b48Spatrick   IRBuilder<> Builder(EntryBB);
65209467b48Spatrick   Builder.CreateRetVoid();
65309467b48Spatrick 
65409467b48Spatrick   MachineModuleInfo &MMI = getAnalysis<MachineModuleInfoWrapperPass>().getMMI();
65509467b48Spatrick   MachineFunction &MF = MMI.getOrCreateMachineFunction(*F);
65609467b48Spatrick   MachineBasicBlock &MBB = *MF.CreateMachineBasicBlock();
65709467b48Spatrick 
65809467b48Spatrick   // Insert the new function into the module.
65909467b48Spatrick   MF.insert(MF.begin(), &MBB);
66009467b48Spatrick 
661097a140dSpatrick   MachineFunction *OriginalMF = FirstCand.front()->getMF();
662097a140dSpatrick   const std::vector<MCCFIInstruction> &Instrs =
663097a140dSpatrick       OriginalMF->getFrameInstructions();
66409467b48Spatrick   for (auto I = FirstCand.front(), E = std::next(FirstCand.back()); I != E;
66509467b48Spatrick        ++I) {
66673471bf0Spatrick     if (I->isDebugInstr())
66773471bf0Spatrick       continue;
66809467b48Spatrick 
66909467b48Spatrick     // Don't keep debug information for outlined instructions.
670*d415bd75Srobert     auto DL = DebugLoc();
671*d415bd75Srobert     if (I->isCFIInstruction()) {
672*d415bd75Srobert       unsigned CFIIndex = I->getOperand(0).getCFIIndex();
673*d415bd75Srobert       MCCFIInstruction CFI = Instrs[CFIIndex];
674*d415bd75Srobert       BuildMI(MBB, MBB.end(), DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
675*d415bd75Srobert           .addCFIIndex(MF.addFrameInst(CFI));
676*d415bd75Srobert     } else {
677*d415bd75Srobert       MachineInstr *NewMI = MF.CloneMachineInstr(&*I);
678*d415bd75Srobert       NewMI->dropMemRefs(MF);
679*d415bd75Srobert       NewMI->setDebugLoc(DL);
68009467b48Spatrick       MBB.insert(MBB.end(), NewMI);
68109467b48Spatrick     }
682*d415bd75Srobert   }
68309467b48Spatrick 
684097a140dSpatrick   // Set normal properties for a late MachineFunction.
685097a140dSpatrick   MF.getProperties().reset(MachineFunctionProperties::Property::IsSSA);
686097a140dSpatrick   MF.getProperties().set(MachineFunctionProperties::Property::NoPHIs);
687097a140dSpatrick   MF.getProperties().set(MachineFunctionProperties::Property::NoVRegs);
688097a140dSpatrick   MF.getProperties().set(MachineFunctionProperties::Property::TracksLiveness);
68909467b48Spatrick   MF.getRegInfo().freezeReservedRegs(MF);
69009467b48Spatrick 
691097a140dSpatrick   // Compute live-in set for outlined fn
692097a140dSpatrick   const MachineRegisterInfo &MRI = MF.getRegInfo();
693097a140dSpatrick   const TargetRegisterInfo &TRI = *MRI.getTargetRegisterInfo();
694097a140dSpatrick   LivePhysRegs LiveIns(TRI);
695097a140dSpatrick   for (auto &Cand : OF.Candidates) {
696097a140dSpatrick     // Figure out live-ins at the first instruction.
697097a140dSpatrick     MachineBasicBlock &OutlineBB = *Cand.front()->getParent();
698097a140dSpatrick     LivePhysRegs CandLiveIns(TRI);
699097a140dSpatrick     CandLiveIns.addLiveOuts(OutlineBB);
700097a140dSpatrick     for (const MachineInstr &MI :
701097a140dSpatrick          reverse(make_range(Cand.front(), OutlineBB.end())))
702097a140dSpatrick       CandLiveIns.stepBackward(MI);
703097a140dSpatrick 
704097a140dSpatrick     // The live-in set for the outlined function is the union of the live-ins
705097a140dSpatrick     // from all the outlining points.
70673471bf0Spatrick     for (MCPhysReg Reg : CandLiveIns)
707097a140dSpatrick       LiveIns.addReg(Reg);
708097a140dSpatrick   }
709097a140dSpatrick   addLiveIns(MBB, LiveIns);
710097a140dSpatrick 
711097a140dSpatrick   TII.buildOutlinedFrame(MBB, MF, OF);
712097a140dSpatrick 
71309467b48Spatrick   // If there's a DISubprogram associated with this outlined function, then
71409467b48Spatrick   // emit debug info for the outlined function.
71509467b48Spatrick   if (DISubprogram *SP = getSubprogramOrNull(OF)) {
71609467b48Spatrick     // We have a DISubprogram. Get its DICompileUnit.
71709467b48Spatrick     DICompileUnit *CU = SP->getUnit();
71809467b48Spatrick     DIBuilder DB(M, true, CU);
71909467b48Spatrick     DIFile *Unit = SP->getFile();
72009467b48Spatrick     Mangler Mg;
72109467b48Spatrick     // Get the mangled name of the function for the linkage name.
72209467b48Spatrick     std::string Dummy;
72309467b48Spatrick     llvm::raw_string_ostream MangledNameStream(Dummy);
72409467b48Spatrick     Mg.getNameWithPrefix(MangledNameStream, F, false);
72509467b48Spatrick 
72609467b48Spatrick     DISubprogram *OutlinedSP = DB.createFunction(
72709467b48Spatrick         Unit /* Context */, F->getName(), StringRef(MangledNameStream.str()),
72809467b48Spatrick         Unit /* File */,
72909467b48Spatrick         0 /* Line 0 is reserved for compiler-generated code. */,
730*d415bd75Srobert         DB.createSubroutineType(
731*d415bd75Srobert             DB.getOrCreateTypeArray(std::nullopt)), /* void type */
73209467b48Spatrick         0, /* Line 0 is reserved for compiler-generated code. */
73309467b48Spatrick         DINode::DIFlags::FlagArtificial /* Compiler-generated code. */,
73409467b48Spatrick         /* Outlined code is optimized code by definition. */
73509467b48Spatrick         DISubprogram::SPFlagDefinition | DISubprogram::SPFlagOptimized);
73609467b48Spatrick 
73709467b48Spatrick     // Don't add any new variables to the subprogram.
73809467b48Spatrick     DB.finalizeSubprogram(OutlinedSP);
73909467b48Spatrick 
74009467b48Spatrick     // Attach subprogram to the function.
74109467b48Spatrick     F->setSubprogram(OutlinedSP);
74209467b48Spatrick     // We're done with the DIBuilder.
74309467b48Spatrick     DB.finalize();
74409467b48Spatrick   }
74509467b48Spatrick 
74609467b48Spatrick   return &MF;
74709467b48Spatrick }
74809467b48Spatrick 
outline(Module & M,std::vector<OutlinedFunction> & FunctionList,InstructionMapper & Mapper,unsigned & OutlinedFunctionNum)74909467b48Spatrick bool MachineOutliner::outline(Module &M,
75009467b48Spatrick                               std::vector<OutlinedFunction> &FunctionList,
75109467b48Spatrick                               InstructionMapper &Mapper,
75209467b48Spatrick                               unsigned &OutlinedFunctionNum) {
75309467b48Spatrick 
75409467b48Spatrick   bool OutlinedSomething = false;
75509467b48Spatrick 
75609467b48Spatrick   // Sort by benefit. The most beneficial functions should be outlined first.
75709467b48Spatrick   llvm::stable_sort(FunctionList, [](const OutlinedFunction &LHS,
75809467b48Spatrick                                      const OutlinedFunction &RHS) {
75909467b48Spatrick     return LHS.getBenefit() > RHS.getBenefit();
76009467b48Spatrick   });
76109467b48Spatrick 
76209467b48Spatrick   // Walk over each function, outlining them as we go along. Functions are
76309467b48Spatrick   // outlined greedily, based off the sort above.
76409467b48Spatrick   for (OutlinedFunction &OF : FunctionList) {
76509467b48Spatrick     // If we outlined something that overlapped with a candidate in a previous
76609467b48Spatrick     // step, then we can't outline from it.
76709467b48Spatrick     erase_if(OF.Candidates, [&Mapper](Candidate &C) {
76809467b48Spatrick       return std::any_of(
76909467b48Spatrick           Mapper.UnsignedVec.begin() + C.getStartIdx(),
77009467b48Spatrick           Mapper.UnsignedVec.begin() + C.getEndIdx() + 1,
77109467b48Spatrick           [](unsigned I) { return (I == static_cast<unsigned>(-1)); });
77209467b48Spatrick     });
77309467b48Spatrick 
77409467b48Spatrick     // If we made it unbeneficial to outline this function, skip it.
77509467b48Spatrick     if (OF.getBenefit() < 1)
77609467b48Spatrick       continue;
77709467b48Spatrick 
77809467b48Spatrick     // It's beneficial. Create the function and outline its sequence's
77909467b48Spatrick     // occurrences.
78009467b48Spatrick     OF.MF = createOutlinedFunction(M, OF, Mapper, OutlinedFunctionNum);
78109467b48Spatrick     emitOutlinedFunctionRemark(OF);
78209467b48Spatrick     FunctionsCreated++;
78309467b48Spatrick     OutlinedFunctionNum++; // Created a function, move to the next name.
78409467b48Spatrick     MachineFunction *MF = OF.MF;
78509467b48Spatrick     const TargetSubtargetInfo &STI = MF->getSubtarget();
78609467b48Spatrick     const TargetInstrInfo &TII = *STI.getInstrInfo();
78709467b48Spatrick 
78809467b48Spatrick     // Replace occurrences of the sequence with calls to the new function.
78909467b48Spatrick     for (Candidate &C : OF.Candidates) {
79009467b48Spatrick       MachineBasicBlock &MBB = *C.getMBB();
79109467b48Spatrick       MachineBasicBlock::iterator StartIt = C.front();
79209467b48Spatrick       MachineBasicBlock::iterator EndIt = C.back();
79309467b48Spatrick 
79409467b48Spatrick       // Insert the call.
79509467b48Spatrick       auto CallInst = TII.insertOutlinedCall(M, MBB, StartIt, *MF, C);
79609467b48Spatrick 
79709467b48Spatrick       // If the caller tracks liveness, then we need to make sure that
79809467b48Spatrick       // anything we outline doesn't break liveness assumptions. The outlined
79909467b48Spatrick       // functions themselves currently don't track liveness, but we should
80009467b48Spatrick       // make sure that the ranges we yank things out of aren't wrong.
80109467b48Spatrick       if (MBB.getParent()->getProperties().hasProperty(
80209467b48Spatrick               MachineFunctionProperties::Property::TracksLiveness)) {
803097a140dSpatrick         // The following code is to add implicit def operands to the call
80409467b48Spatrick         // instruction. It also updates call site information for moved
80509467b48Spatrick         // code.
806097a140dSpatrick         SmallSet<Register, 2> UseRegs, DefRegs;
80709467b48Spatrick         // Copy over the defs in the outlined range.
80809467b48Spatrick         // First inst in outlined range <-- Anything that's defined in this
80909467b48Spatrick         // ...                           .. range has to be added as an
81009467b48Spatrick         // implicit Last inst in outlined range  <-- def to the call
81109467b48Spatrick         // instruction. Also remove call site information for outlined block
812097a140dSpatrick         // of code. The exposed uses need to be copied in the outlined range.
813097a140dSpatrick         for (MachineBasicBlock::reverse_iterator
814097a140dSpatrick                  Iter = EndIt.getReverse(),
815097a140dSpatrick                  Last = std::next(CallInst.getReverse());
816097a140dSpatrick              Iter != Last; Iter++) {
817097a140dSpatrick           MachineInstr *MI = &*Iter;
818*d415bd75Srobert           SmallSet<Register, 2> InstrUseRegs;
819097a140dSpatrick           for (MachineOperand &MOP : MI->operands()) {
820097a140dSpatrick             // Skip over anything that isn't a register.
821097a140dSpatrick             if (!MOP.isReg())
822097a140dSpatrick               continue;
823097a140dSpatrick 
824097a140dSpatrick             if (MOP.isDef()) {
825097a140dSpatrick               // Introduce DefRegs set to skip the redundant register.
826097a140dSpatrick               DefRegs.insert(MOP.getReg());
827*d415bd75Srobert               if (UseRegs.count(MOP.getReg()) &&
828*d415bd75Srobert                   !InstrUseRegs.count(MOP.getReg()))
829097a140dSpatrick                 // Since the regiester is modeled as defined,
830097a140dSpatrick                 // it is not necessary to be put in use register set.
831097a140dSpatrick                 UseRegs.erase(MOP.getReg());
832097a140dSpatrick             } else if (!MOP.isUndef()) {
833097a140dSpatrick               // Any register which is not undefined should
834097a140dSpatrick               // be put in the use register set.
835097a140dSpatrick               UseRegs.insert(MOP.getReg());
836*d415bd75Srobert               InstrUseRegs.insert(MOP.getReg());
837097a140dSpatrick             }
838097a140dSpatrick           }
839097a140dSpatrick           if (MI->isCandidateForCallSiteEntry())
840097a140dSpatrick             MI->getMF()->eraseCallSiteInfo(MI);
841097a140dSpatrick         }
842097a140dSpatrick 
843097a140dSpatrick         for (const Register &I : DefRegs)
844097a140dSpatrick           // If it's a def, add it to the call instruction.
845097a140dSpatrick           CallInst->addOperand(
846097a140dSpatrick               MachineOperand::CreateReg(I, true, /* isDef = true */
847097a140dSpatrick                                         true /* isImp = true */));
848097a140dSpatrick 
849097a140dSpatrick         for (const Register &I : UseRegs)
850097a140dSpatrick           // If it's a exposed use, add it to the call instruction.
851097a140dSpatrick           CallInst->addOperand(
852097a140dSpatrick               MachineOperand::CreateReg(I, false, /* isDef = false */
853097a140dSpatrick                                         true /* isImp = true */));
85409467b48Spatrick       }
85509467b48Spatrick 
85609467b48Spatrick       // Erase from the point after where the call was inserted up to, and
85709467b48Spatrick       // including, the final instruction in the sequence.
85809467b48Spatrick       // Erase needs one past the end, so we need std::next there too.
85909467b48Spatrick       MBB.erase(std::next(StartIt), std::next(EndIt));
86009467b48Spatrick 
86109467b48Spatrick       // Keep track of what we removed by marking them all as -1.
862*d415bd75Srobert       for (unsigned &I :
863*d415bd75Srobert            llvm::make_range(Mapper.UnsignedVec.begin() + C.getStartIdx(),
864*d415bd75Srobert                             Mapper.UnsignedVec.begin() + C.getEndIdx() + 1))
865*d415bd75Srobert         I = static_cast<unsigned>(-1);
86609467b48Spatrick       OutlinedSomething = true;
86709467b48Spatrick 
86809467b48Spatrick       // Statistics.
86909467b48Spatrick       NumOutlined++;
87009467b48Spatrick     }
87109467b48Spatrick   }
87209467b48Spatrick 
87309467b48Spatrick   LLVM_DEBUG(dbgs() << "OutlinedSomething = " << OutlinedSomething << "\n";);
87409467b48Spatrick   return OutlinedSomething;
87509467b48Spatrick }
87609467b48Spatrick 
populateMapper(InstructionMapper & Mapper,Module & M,MachineModuleInfo & MMI)87709467b48Spatrick void MachineOutliner::populateMapper(InstructionMapper &Mapper, Module &M,
87809467b48Spatrick                                      MachineModuleInfo &MMI) {
87909467b48Spatrick   // Build instruction mappings for each function in the module. Start by
88009467b48Spatrick   // iterating over each Function in M.
88109467b48Spatrick   for (Function &F : M) {
88209467b48Spatrick 
883*d415bd75Srobert     if (F.hasFnAttribute("nooutline")) {
884*d415bd75Srobert       LLVM_DEBUG({
885*d415bd75Srobert         dbgs() << "... Skipping function with nooutline attribute: "
886*d415bd75Srobert                << F.getName() << "\n";
887*d415bd75Srobert       });
88809467b48Spatrick       continue;
889*d415bd75Srobert     }
89009467b48Spatrick 
89109467b48Spatrick     // There's something in F. Check if it has a MachineFunction associated with
89209467b48Spatrick     // it.
89309467b48Spatrick     MachineFunction *MF = MMI.getMachineFunction(F);
89409467b48Spatrick 
89509467b48Spatrick     // If it doesn't, then there's nothing to outline from. Move to the next
89609467b48Spatrick     // Function.
89709467b48Spatrick     if (!MF)
89809467b48Spatrick       continue;
89909467b48Spatrick 
90009467b48Spatrick     const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
90109467b48Spatrick 
90209467b48Spatrick     if (!RunOnAllFunctions && !TII->shouldOutlineFromFunctionByDefault(*MF))
90309467b48Spatrick       continue;
90409467b48Spatrick 
90509467b48Spatrick     // We have a MachineFunction. Ask the target if it's suitable for outlining.
90609467b48Spatrick     // If it isn't, then move on to the next Function in the module.
90709467b48Spatrick     if (!TII->isFunctionSafeToOutlineFrom(*MF, OutlineFromLinkOnceODRs))
90809467b48Spatrick       continue;
90909467b48Spatrick 
91009467b48Spatrick     // We have a function suitable for outlining. Iterate over every
91109467b48Spatrick     // MachineBasicBlock in MF and try to map its instructions to a list of
91209467b48Spatrick     // unsigned integers.
91309467b48Spatrick     for (MachineBasicBlock &MBB : *MF) {
91409467b48Spatrick       // If there isn't anything in MBB, then there's no point in outlining from
91509467b48Spatrick       // it.
91609467b48Spatrick       // If there are fewer than 2 instructions in the MBB, then it can't ever
91709467b48Spatrick       // contain something worth outlining.
91809467b48Spatrick       // FIXME: This should be based off of the maximum size in B of an outlined
91909467b48Spatrick       // call versus the size in B of the MBB.
92009467b48Spatrick       if (MBB.empty() || MBB.size() < 2)
92109467b48Spatrick         continue;
92209467b48Spatrick 
92309467b48Spatrick       // Check if MBB could be the target of an indirect branch. If it is, then
92409467b48Spatrick       // we don't want to outline from it.
92509467b48Spatrick       if (MBB.hasAddressTaken())
92609467b48Spatrick         continue;
92709467b48Spatrick 
92809467b48Spatrick       // MBB is suitable for outlining. Map it to a list of unsigneds.
92909467b48Spatrick       Mapper.convertToUnsignedVec(MBB, *TII);
93009467b48Spatrick     }
931*d415bd75Srobert 
932*d415bd75Srobert     // Statistics.
933*d415bd75Srobert     UnsignedVecSize = Mapper.UnsignedVec.size();
93409467b48Spatrick   }
93509467b48Spatrick }
93609467b48Spatrick 
initSizeRemarkInfo(const Module & M,const MachineModuleInfo & MMI,StringMap<unsigned> & FunctionToInstrCount)93709467b48Spatrick void MachineOutliner::initSizeRemarkInfo(
93809467b48Spatrick     const Module &M, const MachineModuleInfo &MMI,
93909467b48Spatrick     StringMap<unsigned> &FunctionToInstrCount) {
94009467b48Spatrick   // Collect instruction counts for every function. We'll use this to emit
94109467b48Spatrick   // per-function size remarks later.
94209467b48Spatrick   for (const Function &F : M) {
94309467b48Spatrick     MachineFunction *MF = MMI.getMachineFunction(F);
94409467b48Spatrick 
94509467b48Spatrick     // We only care about MI counts here. If there's no MachineFunction at this
94609467b48Spatrick     // point, then there won't be after the outliner runs, so let's move on.
94709467b48Spatrick     if (!MF)
94809467b48Spatrick       continue;
94909467b48Spatrick     FunctionToInstrCount[F.getName().str()] = MF->getInstructionCount();
95009467b48Spatrick   }
95109467b48Spatrick }
95209467b48Spatrick 
emitInstrCountChangedRemark(const Module & M,const MachineModuleInfo & MMI,const StringMap<unsigned> & FunctionToInstrCount)95309467b48Spatrick void MachineOutliner::emitInstrCountChangedRemark(
95409467b48Spatrick     const Module &M, const MachineModuleInfo &MMI,
95509467b48Spatrick     const StringMap<unsigned> &FunctionToInstrCount) {
95609467b48Spatrick   // Iterate over each function in the module and emit remarks.
95709467b48Spatrick   // Note that we won't miss anything by doing this, because the outliner never
95809467b48Spatrick   // deletes functions.
95909467b48Spatrick   for (const Function &F : M) {
96009467b48Spatrick     MachineFunction *MF = MMI.getMachineFunction(F);
96109467b48Spatrick 
96209467b48Spatrick     // The outliner never deletes functions. If we don't have a MF here, then we
96309467b48Spatrick     // didn't have one prior to outlining either.
96409467b48Spatrick     if (!MF)
96509467b48Spatrick       continue;
96609467b48Spatrick 
967097a140dSpatrick     std::string Fname = std::string(F.getName());
96809467b48Spatrick     unsigned FnCountAfter = MF->getInstructionCount();
96909467b48Spatrick     unsigned FnCountBefore = 0;
97009467b48Spatrick 
97109467b48Spatrick     // Check if the function was recorded before.
97209467b48Spatrick     auto It = FunctionToInstrCount.find(Fname);
97309467b48Spatrick 
97409467b48Spatrick     // Did we have a previously-recorded size? If yes, then set FnCountBefore
97509467b48Spatrick     // to that.
97609467b48Spatrick     if (It != FunctionToInstrCount.end())
97709467b48Spatrick       FnCountBefore = It->second;
97809467b48Spatrick 
97909467b48Spatrick     // Compute the delta and emit a remark if there was a change.
98009467b48Spatrick     int64_t FnDelta = static_cast<int64_t>(FnCountAfter) -
98109467b48Spatrick                       static_cast<int64_t>(FnCountBefore);
98209467b48Spatrick     if (FnDelta == 0)
98309467b48Spatrick       continue;
98409467b48Spatrick 
98509467b48Spatrick     MachineOptimizationRemarkEmitter MORE(*MF, nullptr);
98609467b48Spatrick     MORE.emit([&]() {
98709467b48Spatrick       MachineOptimizationRemarkAnalysis R("size-info", "FunctionMISizeChange",
98809467b48Spatrick                                           DiagnosticLocation(), &MF->front());
98909467b48Spatrick       R << DiagnosticInfoOptimizationBase::Argument("Pass", "Machine Outliner")
99009467b48Spatrick         << ": Function: "
99109467b48Spatrick         << DiagnosticInfoOptimizationBase::Argument("Function", F.getName())
99209467b48Spatrick         << ": MI instruction count changed from "
99309467b48Spatrick         << DiagnosticInfoOptimizationBase::Argument("MIInstrsBefore",
99409467b48Spatrick                                                     FnCountBefore)
99509467b48Spatrick         << " to "
99609467b48Spatrick         << DiagnosticInfoOptimizationBase::Argument("MIInstrsAfter",
99709467b48Spatrick                                                     FnCountAfter)
99809467b48Spatrick         << "; Delta: "
99909467b48Spatrick         << DiagnosticInfoOptimizationBase::Argument("Delta", FnDelta);
100009467b48Spatrick       return R;
100109467b48Spatrick     });
100209467b48Spatrick   }
100309467b48Spatrick }
100409467b48Spatrick 
runOnModule(Module & M)100509467b48Spatrick bool MachineOutliner::runOnModule(Module &M) {
100609467b48Spatrick   // Check if there's anything in the module. If it's empty, then there's
100709467b48Spatrick   // nothing to outline.
100809467b48Spatrick   if (M.empty())
100909467b48Spatrick     return false;
101009467b48Spatrick 
101109467b48Spatrick   // Number to append to the current outlined function.
101209467b48Spatrick   unsigned OutlinedFunctionNum = 0;
101309467b48Spatrick 
1014097a140dSpatrick   OutlineRepeatedNum = 0;
101509467b48Spatrick   if (!doOutline(M, OutlinedFunctionNum))
101609467b48Spatrick     return false;
1017097a140dSpatrick 
1018097a140dSpatrick   for (unsigned I = 0; I < OutlinerReruns; ++I) {
1019097a140dSpatrick     OutlinedFunctionNum = 0;
1020097a140dSpatrick     OutlineRepeatedNum++;
1021097a140dSpatrick     if (!doOutline(M, OutlinedFunctionNum)) {
1022097a140dSpatrick       LLVM_DEBUG({
1023097a140dSpatrick         dbgs() << "Did not outline on iteration " << I + 2 << " out of "
1024097a140dSpatrick                << OutlinerReruns + 1 << "\n";
1025097a140dSpatrick       });
1026097a140dSpatrick       break;
1027097a140dSpatrick     }
1028097a140dSpatrick   }
1029097a140dSpatrick 
103009467b48Spatrick   return true;
103109467b48Spatrick }
103209467b48Spatrick 
doOutline(Module & M,unsigned & OutlinedFunctionNum)103309467b48Spatrick bool MachineOutliner::doOutline(Module &M, unsigned &OutlinedFunctionNum) {
103409467b48Spatrick   MachineModuleInfo &MMI = getAnalysis<MachineModuleInfoWrapperPass>().getMMI();
103509467b48Spatrick 
103609467b48Spatrick   // If the user passed -enable-machine-outliner=always or
103709467b48Spatrick   // -enable-machine-outliner, the pass will run on all functions in the module.
103809467b48Spatrick   // Otherwise, if the target supports default outlining, it will run on all
103909467b48Spatrick   // functions deemed by the target to be worth outlining from by default. Tell
104009467b48Spatrick   // the user how the outliner is running.
104109467b48Spatrick   LLVM_DEBUG({
104209467b48Spatrick     dbgs() << "Machine Outliner: Running on ";
104309467b48Spatrick     if (RunOnAllFunctions)
104409467b48Spatrick       dbgs() << "all functions";
104509467b48Spatrick     else
104609467b48Spatrick       dbgs() << "target-default functions";
104709467b48Spatrick     dbgs() << "\n";
104809467b48Spatrick   });
104909467b48Spatrick 
105009467b48Spatrick   // If the user specifies that they want to outline from linkonceodrs, set
105109467b48Spatrick   // it here.
105209467b48Spatrick   OutlineFromLinkOnceODRs = EnableLinkOnceODROutlining;
105309467b48Spatrick   InstructionMapper Mapper;
105409467b48Spatrick 
105509467b48Spatrick   // Prepare instruction mappings for the suffix tree.
105609467b48Spatrick   populateMapper(Mapper, M, MMI);
105709467b48Spatrick   std::vector<OutlinedFunction> FunctionList;
105809467b48Spatrick 
105909467b48Spatrick   // Find all of the outlining candidates.
106009467b48Spatrick   findCandidates(Mapper, FunctionList);
106109467b48Spatrick 
106209467b48Spatrick   // If we've requested size remarks, then collect the MI counts of every
106309467b48Spatrick   // function before outlining, and the MI counts after outlining.
106409467b48Spatrick   // FIXME: This shouldn't be in the outliner at all; it should ultimately be
106509467b48Spatrick   // the pass manager's responsibility.
106609467b48Spatrick   // This could pretty easily be placed in outline instead, but because we
106709467b48Spatrick   // really ultimately *don't* want this here, it's done like this for now
106809467b48Spatrick   // instead.
106909467b48Spatrick 
107009467b48Spatrick   // Check if we want size remarks.
107109467b48Spatrick   bool ShouldEmitSizeRemarks = M.shouldEmitInstrCountChangedRemark();
107209467b48Spatrick   StringMap<unsigned> FunctionToInstrCount;
107309467b48Spatrick   if (ShouldEmitSizeRemarks)
107409467b48Spatrick     initSizeRemarkInfo(M, MMI, FunctionToInstrCount);
107509467b48Spatrick 
107609467b48Spatrick   // Outline each of the candidates and return true if something was outlined.
107709467b48Spatrick   bool OutlinedSomething =
107809467b48Spatrick       outline(M, FunctionList, Mapper, OutlinedFunctionNum);
107909467b48Spatrick 
108009467b48Spatrick   // If we outlined something, we definitely changed the MI count of the
108109467b48Spatrick   // module. If we've asked for size remarks, then output them.
108209467b48Spatrick   // FIXME: This should be in the pass manager.
108309467b48Spatrick   if (ShouldEmitSizeRemarks && OutlinedSomething)
108409467b48Spatrick     emitInstrCountChangedRemark(M, MMI, FunctionToInstrCount);
108509467b48Spatrick 
1086097a140dSpatrick   LLVM_DEBUG({
1087097a140dSpatrick     if (!OutlinedSomething)
1088097a140dSpatrick       dbgs() << "Stopped outlining at iteration " << OutlineRepeatedNum
1089097a140dSpatrick              << " because no changes were found.\n";
1090097a140dSpatrick   });
1091097a140dSpatrick 
109209467b48Spatrick   return OutlinedSomething;
109309467b48Spatrick }
1094