1596f483aSJessica Paquette //===---- MachineOutliner.cpp - Outline instructions -----------*- C++ -*-===//
2596f483aSJessica Paquette //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6596f483aSJessica Paquette //
7596f483aSJessica Paquette //===----------------------------------------------------------------------===//
8596f483aSJessica Paquette ///
9596f483aSJessica Paquette /// \file
10596f483aSJessica Paquette /// Replaces repeated sequences of instructions with function calls.
11596f483aSJessica Paquette ///
12596f483aSJessica Paquette /// This works by placing every instruction from every basic block in a
13596f483aSJessica Paquette /// suffix tree, and repeatedly querying that tree for repeated sequences of
14596f483aSJessica Paquette /// instructions. If a sequence of instructions appears often, then it ought
15596f483aSJessica Paquette /// to be beneficial to pull out into a function.
16596f483aSJessica Paquette ///
174cf187b5SJessica Paquette /// The MachineOutliner communicates with a given target using hooks defined in
184cf187b5SJessica Paquette /// TargetInstrInfo.h. The target supplies the outliner with information on how
194cf187b5SJessica Paquette /// a specific sequence of instructions should be outlined. This information
204cf187b5SJessica Paquette /// is used to deduce the number of instructions necessary to
214cf187b5SJessica Paquette ///
224cf187b5SJessica Paquette /// * Create an outlined function
234cf187b5SJessica Paquette /// * Call that outlined function
244cf187b5SJessica Paquette ///
254cf187b5SJessica Paquette /// Targets must implement
264cf187b5SJessica Paquette /// * getOutliningCandidateInfo
2732de26d4SJessica Paquette /// * buildOutlinedFrame
284cf187b5SJessica Paquette /// * insertOutlinedCall
294cf187b5SJessica Paquette /// * isFunctionSafeToOutlineFrom
304cf187b5SJessica Paquette ///
314cf187b5SJessica Paquette /// in order to make use of the MachineOutliner.
324cf187b5SJessica Paquette ///
33596f483aSJessica Paquette /// This was originally presented at the 2016 LLVM Developers' Meeting in the
34596f483aSJessica Paquette /// talk "Reducing Code Size Using Outlining". For a high-level overview of
35596f483aSJessica Paquette /// how this pass works, the talk is available on YouTube at
36596f483aSJessica Paquette ///
37596f483aSJessica Paquette /// https://www.youtube.com/watch?v=yorld-WSOeU
38596f483aSJessica Paquette ///
39596f483aSJessica Paquette /// The slides for the talk are available at
40596f483aSJessica Paquette ///
41596f483aSJessica Paquette /// http://www.llvm.org/devmtg/2016-11/Slides/Paquette-Outliner.pdf
42596f483aSJessica Paquette ///
43596f483aSJessica Paquette /// The talk provides an overview of how the outliner finds candidates and
44596f483aSJessica Paquette /// ultimately outlines them. It describes how the main data structure for this
45596f483aSJessica Paquette /// pass, the suffix tree, is queried and purged for candidates. It also gives
46596f483aSJessica Paquette /// a simplified suffix tree construction algorithm for suffix trees based off
47596f483aSJessica Paquette /// of the algorithm actually used here, Ukkonen's algorithm.
48596f483aSJessica Paquette ///
49596f483aSJessica Paquette /// For the original RFC for this pass, please see
50596f483aSJessica Paquette ///
51596f483aSJessica Paquette /// http://lists.llvm.org/pipermail/llvm-dev/2016-August/104170.html
52596f483aSJessica Paquette ///
53596f483aSJessica Paquette /// For more information on the suffix tree data structure, please see
54596f483aSJessica Paquette /// https://www.cs.helsinki.fi/u/ukkonen/SuffixT1withFigs.pdf
55596f483aSJessica Paquette ///
56596f483aSJessica Paquette //===----------------------------------------------------------------------===//
57aa087327SJessica Paquette #include "llvm/CodeGen/MachineOutliner.h"
58596f483aSJessica Paquette #include "llvm/ADT/DenseMap.h"
59fc6fda90SJin Lin #include "llvm/ADT/SmallSet.h"
60596f483aSJessica Paquette #include "llvm/ADT/Statistic.h"
61596f483aSJessica Paquette #include "llvm/ADT/Twine.h"
62989f1c72Sserge-sans-paille #include "llvm/Analysis/OptimizationRemarkEmitter.h"
63989f1c72Sserge-sans-paille #include "llvm/CodeGen/LivePhysRegs.h"
64596f483aSJessica Paquette #include "llvm/CodeGen/MachineModuleInfo.h"
65ffe4abc5SJessica Paquette #include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h"
66596f483aSJessica Paquette #include "llvm/CodeGen/Passes.h"
673f833edcSDavid Blaikie #include "llvm/CodeGen/TargetInstrInfo.h"
68b3bde2eaSDavid Blaikie #include "llvm/CodeGen/TargetSubtargetInfo.h"
69729e6869SJessica Paquette #include "llvm/IR/DIBuilder.h"
70596f483aSJessica Paquette #include "llvm/IR/IRBuilder.h"
71a499c3c2SJessica Paquette #include "llvm/IR/Mangler.h"
7205da2fe5SReid Kleckner #include "llvm/InitializePasses.h"
731eca23bdSJessica Paquette #include "llvm/Support/CommandLine.h"
74596f483aSJessica Paquette #include "llvm/Support/Debug.h"
75bb677cacSAndrew Litteken #include "llvm/Support/SuffixTree.h"
76596f483aSJessica Paquette #include "llvm/Support/raw_ostream.h"
77596f483aSJessica Paquette #include <functional>
78596f483aSJessica Paquette #include <tuple>
79596f483aSJessica Paquette #include <vector>
80596f483aSJessica Paquette
81596f483aSJessica Paquette #define DEBUG_TYPE "machine-outliner"
82596f483aSJessica Paquette
83596f483aSJessica Paquette using namespace llvm;
84ffe4abc5SJessica Paquette using namespace ore;
85aa087327SJessica Paquette using namespace outliner;
86596f483aSJessica Paquette
8712389e37SJessica Paquette // Statistics for outlined functions.
88596f483aSJessica Paquette STATISTIC(NumOutlined, "Number of candidates outlined");
89596f483aSJessica Paquette STATISTIC(FunctionsCreated, "Number of functions created");
90596f483aSJessica Paquette
9112389e37SJessica Paquette // Statistics for instruction mapping.
9212389e37SJessica Paquette STATISTIC(NumLegalInUnsignedVec, "Number of legal instrs in unsigned vector");
9312389e37SJessica Paquette STATISTIC(NumIllegalInUnsignedVec,
9412389e37SJessica Paquette "Number of illegal instrs in unsigned vector");
9512389e37SJessica Paquette STATISTIC(NumInvisible, "Number of invisible instrs in unsigned vector");
9612389e37SJessica Paquette STATISTIC(UnsignedVecSize, "Size of unsigned vector");
9712389e37SJessica Paquette
981eca23bdSJessica Paquette // Set to true if the user wants the outliner to run on linkonceodr linkage
991eca23bdSJessica Paquette // functions. This is false by default because the linker can dedupe linkonceodr
1001eca23bdSJessica Paquette // functions. Since the outliner is confined to a single module (modulo LTO),
1011eca23bdSJessica Paquette // this is off by default. It should, however, be the default behaviour in
1021eca23bdSJessica Paquette // LTO.
1031eca23bdSJessica Paquette static cl::opt<bool> EnableLinkOnceODROutlining(
1046b7615aeSPuyan Lotfi "enable-linkonceodr-outlining", cl::Hidden,
1051eca23bdSJessica Paquette cl::desc("Enable the machine outliner on linkonceodr functions"),
1061eca23bdSJessica Paquette cl::init(false));
1071eca23bdSJessica Paquette
108ffd5e121SPuyan Lotfi /// Number of times to re-run the outliner. This is not the total number of runs
109ffd5e121SPuyan Lotfi /// as the outliner will run at least one time. The default value is set to 0,
110ffd5e121SPuyan Lotfi /// meaning the outliner will run one time and rerun zero times after that.
111ffd5e121SPuyan Lotfi static cl::opt<unsigned> OutlinerReruns(
112ffd5e121SPuyan Lotfi "machine-outliner-reruns", cl::init(0), cl::Hidden,
113ffd5e121SPuyan Lotfi cl::desc(
114ffd5e121SPuyan Lotfi "Number of times to rerun the outliner after the initial outline"));
1150d896278SJin Lin
116596f483aSJessica Paquette namespace {
117596f483aSJessica Paquette
1185f8f34e4SAdrian Prantl /// Maps \p MachineInstrs to unsigned integers and stores the mappings.
119596f483aSJessica Paquette struct InstructionMapper {
120596f483aSJessica Paquette
1215f8f34e4SAdrian Prantl /// The next available integer to assign to a \p MachineInstr that
122596f483aSJessica Paquette /// cannot be outlined.
123596f483aSJessica Paquette ///
124596f483aSJessica Paquette /// Set to -3 for compatability with \p DenseMapInfo<unsigned>.
125596f483aSJessica Paquette unsigned IllegalInstrNumber = -3;
126596f483aSJessica Paquette
1275f8f34e4SAdrian Prantl /// The next available integer to assign to a \p MachineInstr that can
128596f483aSJessica Paquette /// be outlined.
129596f483aSJessica Paquette unsigned LegalInstrNumber = 0;
130596f483aSJessica Paquette
131596f483aSJessica Paquette /// Correspondence from \p MachineInstrs to unsigned integers.
132596f483aSJessica Paquette DenseMap<MachineInstr *, unsigned, MachineInstrExpressionTrait>
133596f483aSJessica Paquette InstructionIntegerMap;
134596f483aSJessica Paquette
135cad864d4SJessica Paquette /// Correspondence between \p MachineBasicBlocks and target-defined flags.
136cad864d4SJessica Paquette DenseMap<MachineBasicBlock *, unsigned> MBBFlagsMap;
137cad864d4SJessica Paquette
138596f483aSJessica Paquette /// The vector of unsigned integers that the module is mapped to.
139596f483aSJessica Paquette std::vector<unsigned> UnsignedVec;
140596f483aSJessica Paquette
1415f8f34e4SAdrian Prantl /// Stores the location of the instruction associated with the integer
142596f483aSJessica Paquette /// at index i in \p UnsignedVec for each index i.
143596f483aSJessica Paquette std::vector<MachineBasicBlock::iterator> InstrList;
144596f483aSJessica Paquette
145c991cf36SJessica Paquette // Set if we added an illegal number in the previous step.
146c991cf36SJessica Paquette // Since each illegal number is unique, we only need one of them between
147c991cf36SJessica Paquette // each range of legal numbers. This lets us make sure we don't add more
148c991cf36SJessica Paquette // than one illegal number per range.
149c991cf36SJessica Paquette bool AddedIllegalLastTime = false;
150c991cf36SJessica Paquette
1515f8f34e4SAdrian Prantl /// Maps \p *It to a legal integer.
152596f483aSJessica Paquette ///
153c4cf775aSJessica Paquette /// Updates \p CanOutlineWithPrevInstr, \p HaveLegalRange, \p InstrListForMBB,
154ca3ed964SJessica Paquette /// \p UnsignedVecForMBB, \p InstructionIntegerMap, and \p LegalInstrNumber.
155596f483aSJessica Paquette ///
156596f483aSJessica Paquette /// \returns The integer that \p *It was mapped to.
mapToLegalUnsigned__anon014cdf4b0111::InstructionMapper157267d266cSJessica Paquette unsigned mapToLegalUnsigned(
158c4cf775aSJessica Paquette MachineBasicBlock::iterator &It, bool &CanOutlineWithPrevInstr,
159c4cf775aSJessica Paquette bool &HaveLegalRange, unsigned &NumLegalInBlock,
160267d266cSJessica Paquette std::vector<unsigned> &UnsignedVecForMBB,
161267d266cSJessica Paquette std::vector<MachineBasicBlock::iterator> &InstrListForMBB) {
162c991cf36SJessica Paquette // We added something legal, so we should unset the AddedLegalLastTime
163c991cf36SJessica Paquette // flag.
164c991cf36SJessica Paquette AddedIllegalLastTime = false;
165596f483aSJessica Paquette
166c4cf775aSJessica Paquette // If we have at least two adjacent legal instructions (which may have
167c4cf775aSJessica Paquette // invisible instructions in between), remember that.
168c4cf775aSJessica Paquette if (CanOutlineWithPrevInstr)
169c4cf775aSJessica Paquette HaveLegalRange = true;
170c4cf775aSJessica Paquette CanOutlineWithPrevInstr = true;
171c4cf775aSJessica Paquette
172267d266cSJessica Paquette // Keep track of the number of legal instructions we insert.
173267d266cSJessica Paquette NumLegalInBlock++;
174267d266cSJessica Paquette
175596f483aSJessica Paquette // Get the integer for this instruction or give it the current
176596f483aSJessica Paquette // LegalInstrNumber.
177267d266cSJessica Paquette InstrListForMBB.push_back(It);
178596f483aSJessica Paquette MachineInstr &MI = *It;
179596f483aSJessica Paquette bool WasInserted;
180596f483aSJessica Paquette DenseMap<MachineInstr *, unsigned, MachineInstrExpressionTrait>::iterator
181596f483aSJessica Paquette ResultIt;
182596f483aSJessica Paquette std::tie(ResultIt, WasInserted) =
183596f483aSJessica Paquette InstructionIntegerMap.insert(std::make_pair(&MI, LegalInstrNumber));
184596f483aSJessica Paquette unsigned MINumber = ResultIt->second;
185596f483aSJessica Paquette
186596f483aSJessica Paquette // There was an insertion.
187ca3ed964SJessica Paquette if (WasInserted)
188596f483aSJessica Paquette LegalInstrNumber++;
189596f483aSJessica Paquette
190267d266cSJessica Paquette UnsignedVecForMBB.push_back(MINumber);
191596f483aSJessica Paquette
192596f483aSJessica Paquette // Make sure we don't overflow or use any integers reserved by the DenseMap.
193596f483aSJessica Paquette if (LegalInstrNumber >= IllegalInstrNumber)
194596f483aSJessica Paquette report_fatal_error("Instruction mapping overflow!");
195596f483aSJessica Paquette
19678681be2SJessica Paquette assert(LegalInstrNumber != DenseMapInfo<unsigned>::getEmptyKey() &&
19778681be2SJessica Paquette "Tried to assign DenseMap tombstone or empty key to instruction.");
19878681be2SJessica Paquette assert(LegalInstrNumber != DenseMapInfo<unsigned>::getTombstoneKey() &&
19978681be2SJessica Paquette "Tried to assign DenseMap tombstone or empty key to instruction.");
200596f483aSJessica Paquette
20112389e37SJessica Paquette // Statistics.
20212389e37SJessica Paquette ++NumLegalInUnsignedVec;
203596f483aSJessica Paquette return MINumber;
204596f483aSJessica Paquette }
205596f483aSJessica Paquette
206596f483aSJessica Paquette /// Maps \p *It to an illegal integer.
207596f483aSJessica Paquette ///
208267d266cSJessica Paquette /// Updates \p InstrListForMBB, \p UnsignedVecForMBB, and \p
209267d266cSJessica Paquette /// IllegalInstrNumber.
210596f483aSJessica Paquette ///
211596f483aSJessica Paquette /// \returns The integer that \p *It was mapped to.
mapToIllegalUnsigned__anon014cdf4b0111::InstructionMapper2126b7615aeSPuyan Lotfi unsigned mapToIllegalUnsigned(
2136b7615aeSPuyan Lotfi MachineBasicBlock::iterator &It, bool &CanOutlineWithPrevInstr,
2146b7615aeSPuyan Lotfi std::vector<unsigned> &UnsignedVecForMBB,
215267d266cSJessica Paquette std::vector<MachineBasicBlock::iterator> &InstrListForMBB) {
216c4cf775aSJessica Paquette // Can't outline an illegal instruction. Set the flag.
217c4cf775aSJessica Paquette CanOutlineWithPrevInstr = false;
218c4cf775aSJessica Paquette
219c991cf36SJessica Paquette // Only add one illegal number per range of legal numbers.
220c991cf36SJessica Paquette if (AddedIllegalLastTime)
221c991cf36SJessica Paquette return IllegalInstrNumber;
222c991cf36SJessica Paquette
223c991cf36SJessica Paquette // Remember that we added an illegal number last time.
224c991cf36SJessica Paquette AddedIllegalLastTime = true;
225596f483aSJessica Paquette unsigned MINumber = IllegalInstrNumber;
226596f483aSJessica Paquette
227267d266cSJessica Paquette InstrListForMBB.push_back(It);
228267d266cSJessica Paquette UnsignedVecForMBB.push_back(IllegalInstrNumber);
229596f483aSJessica Paquette IllegalInstrNumber--;
23012389e37SJessica Paquette // Statistics.
23112389e37SJessica Paquette ++NumIllegalInUnsignedVec;
232596f483aSJessica Paquette
233596f483aSJessica Paquette assert(LegalInstrNumber < IllegalInstrNumber &&
234596f483aSJessica Paquette "Instruction mapping overflow!");
235596f483aSJessica Paquette
23678681be2SJessica Paquette assert(IllegalInstrNumber != DenseMapInfo<unsigned>::getEmptyKey() &&
237596f483aSJessica Paquette "IllegalInstrNumber cannot be DenseMap tombstone or empty key!");
238596f483aSJessica Paquette
23978681be2SJessica Paquette assert(IllegalInstrNumber != DenseMapInfo<unsigned>::getTombstoneKey() &&
240596f483aSJessica Paquette "IllegalInstrNumber cannot be DenseMap tombstone or empty key!");
241596f483aSJessica Paquette
242596f483aSJessica Paquette return MINumber;
243596f483aSJessica Paquette }
244596f483aSJessica Paquette
2455f8f34e4SAdrian Prantl /// Transforms a \p MachineBasicBlock into a \p vector of \p unsigneds
246596f483aSJessica Paquette /// and appends it to \p UnsignedVec and \p InstrList.
247596f483aSJessica Paquette ///
248596f483aSJessica Paquette /// Two instructions are assigned the same integer if they are identical.
249596f483aSJessica Paquette /// If an instruction is deemed unsafe to outline, then it will be assigned an
250596f483aSJessica Paquette /// unique integer. The resulting mapping is placed into a suffix tree and
251596f483aSJessica Paquette /// queried for candidates.
252596f483aSJessica Paquette ///
253596f483aSJessica Paquette /// \param MBB The \p MachineBasicBlock to be translated into integers.
254da08078fSEli Friedman /// \param TII \p TargetInstrInfo for the function.
convertToUnsignedVec__anon014cdf4b0111::InstructionMapper255596f483aSJessica Paquette void convertToUnsignedVec(MachineBasicBlock &MBB,
256596f483aSJessica Paquette const TargetInstrInfo &TII) {
2573635c890SAlexander Kornienko unsigned Flags = 0;
25882d9c0a3SJessica Paquette
25982d9c0a3SJessica Paquette // Don't even map in this case.
26082d9c0a3SJessica Paquette if (!TII.isMBBSafeToOutlineFrom(MBB, Flags))
26182d9c0a3SJessica Paquette return;
26282d9c0a3SJessica Paquette
263cad864d4SJessica Paquette // Store info for the MBB for later outlining.
264cad864d4SJessica Paquette MBBFlagsMap[&MBB] = Flags;
265cad864d4SJessica Paquette
266c991cf36SJessica Paquette MachineBasicBlock::iterator It = MBB.begin();
267267d266cSJessica Paquette
268267d266cSJessica Paquette // The number of instructions in this block that will be considered for
269267d266cSJessica Paquette // outlining.
270267d266cSJessica Paquette unsigned NumLegalInBlock = 0;
271267d266cSJessica Paquette
272c4cf775aSJessica Paquette // True if we have at least two legal instructions which aren't separated
273c4cf775aSJessica Paquette // by an illegal instruction.
274c4cf775aSJessica Paquette bool HaveLegalRange = false;
275c4cf775aSJessica Paquette
276c4cf775aSJessica Paquette // True if we can perform outlining given the last mapped (non-invisible)
277c4cf775aSJessica Paquette // instruction. This lets us know if we have a legal range.
278c4cf775aSJessica Paquette bool CanOutlineWithPrevInstr = false;
279c4cf775aSJessica Paquette
280267d266cSJessica Paquette // FIXME: Should this all just be handled in the target, rather than using
281267d266cSJessica Paquette // repeated calls to getOutliningType?
282267d266cSJessica Paquette std::vector<unsigned> UnsignedVecForMBB;
283267d266cSJessica Paquette std::vector<MachineBasicBlock::iterator> InstrListForMBB;
284267d266cSJessica Paquette
28568c718c8SJessica Paquette for (MachineBasicBlock::iterator Et = MBB.end(); It != Et; ++It) {
286596f483aSJessica Paquette // Keep track of where this instruction is in the module.
2873291e735SJessica Paquette switch (TII.getOutliningType(It, Flags)) {
288aa087327SJessica Paquette case InstrType::Illegal:
2896b7615aeSPuyan Lotfi mapToIllegalUnsigned(It, CanOutlineWithPrevInstr, UnsignedVecForMBB,
2906b7615aeSPuyan Lotfi InstrListForMBB);
291596f483aSJessica Paquette break;
292596f483aSJessica Paquette
293aa087327SJessica Paquette case InstrType::Legal:
294c4cf775aSJessica Paquette mapToLegalUnsigned(It, CanOutlineWithPrevInstr, HaveLegalRange,
29568c718c8SJessica Paquette NumLegalInBlock, UnsignedVecForMBB, InstrListForMBB);
296596f483aSJessica Paquette break;
297596f483aSJessica Paquette
298aa087327SJessica Paquette case InstrType::LegalTerminator:
299c4cf775aSJessica Paquette mapToLegalUnsigned(It, CanOutlineWithPrevInstr, HaveLegalRange,
30068c718c8SJessica Paquette NumLegalInBlock, UnsignedVecForMBB, InstrListForMBB);
30168c718c8SJessica Paquette // The instruction also acts as a terminator, so we have to record that
30268c718c8SJessica Paquette // in the string.
303c4cf775aSJessica Paquette mapToIllegalUnsigned(It, CanOutlineWithPrevInstr, UnsignedVecForMBB,
304c4cf775aSJessica Paquette InstrListForMBB);
305042dc9e0SEli Friedman break;
306042dc9e0SEli Friedman
307aa087327SJessica Paquette case InstrType::Invisible:
308c991cf36SJessica Paquette // Normally this is set by mapTo(Blah)Unsigned, but we just want to
309c991cf36SJessica Paquette // skip this instruction. So, unset the flag here.
31012389e37SJessica Paquette ++NumInvisible;
311bd72988cSJessica Paquette AddedIllegalLastTime = false;
312596f483aSJessica Paquette break;
313596f483aSJessica Paquette }
314596f483aSJessica Paquette }
315596f483aSJessica Paquette
316267d266cSJessica Paquette // Are there enough legal instructions in the block for outlining to be
317267d266cSJessica Paquette // possible?
318c4cf775aSJessica Paquette if (HaveLegalRange) {
319596f483aSJessica Paquette // After we're done every insertion, uniquely terminate this part of the
320596f483aSJessica Paquette // "string". This makes sure we won't match across basic block or function
321596f483aSJessica Paquette // boundaries since the "end" is encoded uniquely and thus appears in no
322596f483aSJessica Paquette // repeated substring.
323c4cf775aSJessica Paquette mapToIllegalUnsigned(It, CanOutlineWithPrevInstr, UnsignedVecForMBB,
324c4cf775aSJessica Paquette InstrListForMBB);
3251e3ed091SKazu Hirata llvm::append_range(InstrList, InstrListForMBB);
3261e3ed091SKazu Hirata llvm::append_range(UnsignedVec, UnsignedVecForMBB);
327267d266cSJessica Paquette }
328596f483aSJessica Paquette }
329596f483aSJessica Paquette
InstructionMapper__anon014cdf4b0111::InstructionMapper330596f483aSJessica Paquette InstructionMapper() {
331596f483aSJessica Paquette // Make sure that the implementation of DenseMapInfo<unsigned> hasn't
332596f483aSJessica Paquette // changed.
333596f483aSJessica Paquette assert(DenseMapInfo<unsigned>::getEmptyKey() == (unsigned)-1 &&
334596f483aSJessica Paquette "DenseMapInfo<unsigned>'s empty key isn't -1!");
335596f483aSJessica Paquette assert(DenseMapInfo<unsigned>::getTombstoneKey() == (unsigned)-2 &&
336596f483aSJessica Paquette "DenseMapInfo<unsigned>'s tombstone key isn't -2!");
337596f483aSJessica Paquette }
338596f483aSJessica Paquette };
339596f483aSJessica Paquette
3405f8f34e4SAdrian Prantl /// An interprocedural pass which finds repeated sequences of
341596f483aSJessica Paquette /// instructions and replaces them with calls to functions.
342596f483aSJessica Paquette ///
343596f483aSJessica Paquette /// Each instruction is mapped to an unsigned integer and placed in a string.
344596f483aSJessica Paquette /// The resulting mapping is then placed in a \p SuffixTree. The \p SuffixTree
345596f483aSJessica Paquette /// is then repeatedly queried for repeated sequences of instructions. Each
346596f483aSJessica Paquette /// non-overlapping repeated sequence is then placed in its own
347596f483aSJessica Paquette /// \p MachineFunction and each instance is then replaced with a call to that
348596f483aSJessica Paquette /// function.
349596f483aSJessica Paquette struct MachineOutliner : public ModulePass {
350596f483aSJessica Paquette
351596f483aSJessica Paquette static char ID;
352596f483aSJessica Paquette
3535f8f34e4SAdrian Prantl /// Set to true if the outliner should consider functions with
35413593843SJessica Paquette /// linkonceodr linkage.
35513593843SJessica Paquette bool OutlineFromLinkOnceODRs = false;
35613593843SJessica Paquette
3570d896278SJin Lin /// The current repeat number of machine outlining.
3580d896278SJin Lin unsigned OutlineRepeatedNum = 0;
3590d896278SJin Lin
3608bda1881SJessica Paquette /// Set to true if the outliner should run on all functions in the module
3618bda1881SJessica Paquette /// considered safe for outlining.
3628bda1881SJessica Paquette /// Set to true by default for compatibility with llc's -run-pass option.
3638bda1881SJessica Paquette /// Set when the pass is constructed in TargetPassConfig.
3648bda1881SJessica Paquette bool RunOnAllFunctions = true;
3658bda1881SJessica Paquette
getPassName__anon014cdf4b0111::MachineOutliner366596f483aSJessica Paquette StringRef getPassName() const override { return "Machine Outliner"; }
367596f483aSJessica Paquette
getAnalysisUsage__anon014cdf4b0111::MachineOutliner368596f483aSJessica Paquette void getAnalysisUsage(AnalysisUsage &AU) const override {
369cc382cf7SYuanfang Chen AU.addRequired<MachineModuleInfoWrapperPass>();
370cc382cf7SYuanfang Chen AU.addPreserved<MachineModuleInfoWrapperPass>();
371596f483aSJessica Paquette AU.setPreservesAll();
372596f483aSJessica Paquette ModulePass::getAnalysisUsage(AU);
373596f483aSJessica Paquette }
374596f483aSJessica Paquette
MachineOutliner__anon014cdf4b0111::MachineOutliner3751eca23bdSJessica Paquette MachineOutliner() : ModulePass(ID) {
376596f483aSJessica Paquette initializeMachineOutlinerPass(*PassRegistry::getPassRegistry());
377596f483aSJessica Paquette }
378596f483aSJessica Paquette
3791cc52a00SJessica Paquette /// Remark output explaining that not outlining a set of candidates would be
3801cc52a00SJessica Paquette /// better than outlining that set.
3811cc52a00SJessica Paquette void emitNotOutliningCheaperRemark(
3821cc52a00SJessica Paquette unsigned StringLen, std::vector<Candidate> &CandidatesForRepeatedSeq,
3831cc52a00SJessica Paquette OutlinedFunction &OF);
3841cc52a00SJessica Paquette
38558e706a6SJessica Paquette /// Remark output explaining that a function was outlined.
38658e706a6SJessica Paquette void emitOutlinedFunctionRemark(OutlinedFunction &OF);
38758e706a6SJessica Paquette
388ce3a2dcfSJessica Paquette /// Find all repeated substrings that satisfy the outlining cost model by
389ce3a2dcfSJessica Paquette /// constructing a suffix tree.
39078681be2SJessica Paquette ///
39178681be2SJessica Paquette /// If a substring appears at least twice, then it must be represented by
3921cc52a00SJessica Paquette /// an internal node which appears in at least two suffixes. Each suffix
3931cc52a00SJessica Paquette /// is represented by a leaf node. To do this, we visit each internal node
3941cc52a00SJessica Paquette /// in the tree, using the leaf children of each internal node. If an
3951cc52a00SJessica Paquette /// internal node represents a beneficial substring, then we use each of
3961cc52a00SJessica Paquette /// its leaf children to find the locations of its substring.
39778681be2SJessica Paquette ///
39878681be2SJessica Paquette /// \param Mapper Contains outlining mapping information.
3991cc52a00SJessica Paquette /// \param[out] FunctionList Filled with a list of \p OutlinedFunctions
4001cc52a00SJessica Paquette /// each type of candidate.
401ce3a2dcfSJessica Paquette void findCandidates(InstructionMapper &Mapper,
40278681be2SJessica Paquette std::vector<OutlinedFunction> &FunctionList);
40378681be2SJessica Paquette
4044ae3b71dSJessica Paquette /// Replace the sequences of instructions represented by \p OutlinedFunctions
4054ae3b71dSJessica Paquette /// with calls to functions.
406596f483aSJessica Paquette ///
407596f483aSJessica Paquette /// \param M The module we are outlining from.
408596f483aSJessica Paquette /// \param FunctionList A list of functions to be inserted into the module.
409596f483aSJessica Paquette /// \param Mapper Contains the instruction mappings for the module.
4104ae3b71dSJessica Paquette bool outline(Module &M, std::vector<OutlinedFunction> &FunctionList,
4116b7615aeSPuyan Lotfi InstructionMapper &Mapper, unsigned &OutlinedFunctionNum);
412596f483aSJessica Paquette
413596f483aSJessica Paquette /// Creates a function for \p OF and inserts it into the module.
414e18d6ff0SJessica Paquette MachineFunction *createOutlinedFunction(Module &M, OutlinedFunction &OF,
415a3eb0facSJessica Paquette InstructionMapper &Mapper,
416a3eb0facSJessica Paquette unsigned Name);
417596f483aSJessica Paquette
418ffd5e121SPuyan Lotfi /// Calls 'doOutline()' 1 + OutlinerReruns times.
4197b166d51SJin Lin bool runOnModule(Module &M) override;
420ab2dcff3SJin Lin
421596f483aSJessica Paquette /// Construct a suffix tree on the instructions in \p M and outline repeated
422596f483aSJessica Paquette /// strings from that tree.
423a51fc8ddSPuyan Lotfi bool doOutline(Module &M, unsigned &OutlinedFunctionNum);
424aa087327SJessica Paquette
425aa087327SJessica Paquette /// Return a DISubprogram for OF if one exists, and null otherwise. Helper
426aa087327SJessica Paquette /// function for remark emission.
getSubprogramOrNull__anon014cdf4b0111::MachineOutliner427aa087327SJessica Paquette DISubprogram *getSubprogramOrNull(const OutlinedFunction &OF) {
428e18d6ff0SJessica Paquette for (const Candidate &C : OF.Candidates)
4297ad25836SSimon Pilgrim if (MachineFunction *MF = C.getMF())
4307ad25836SSimon Pilgrim if (DISubprogram *SP = MF->getFunction().getSubprogram())
431aa087327SJessica Paquette return SP;
432aa087327SJessica Paquette return nullptr;
433aa087327SJessica Paquette }
434050d1ac4SJessica Paquette
435050d1ac4SJessica Paquette /// Populate and \p InstructionMapper with instruction-to-integer mappings.
436050d1ac4SJessica Paquette /// These are used to construct a suffix tree.
437050d1ac4SJessica Paquette void populateMapper(InstructionMapper &Mapper, Module &M,
438050d1ac4SJessica Paquette MachineModuleInfo &MMI);
439596f483aSJessica Paquette
4402386eab3SJessica Paquette /// Initialize information necessary to output a size remark.
4412386eab3SJessica Paquette /// FIXME: This should be handled by the pass manager, not the outliner.
4422386eab3SJessica Paquette /// FIXME: This is nearly identical to the initSizeRemarkInfo in the legacy
4432386eab3SJessica Paquette /// pass manager.
4446b7615aeSPuyan Lotfi void initSizeRemarkInfo(const Module &M, const MachineModuleInfo &MMI,
4452386eab3SJessica Paquette StringMap<unsigned> &FunctionToInstrCount);
4462386eab3SJessica Paquette
4472386eab3SJessica Paquette /// Emit the remark.
4482386eab3SJessica Paquette // FIXME: This should be handled by the pass manager, not the outliner.
4496b7615aeSPuyan Lotfi void
4506b7615aeSPuyan Lotfi emitInstrCountChangedRemark(const Module &M, const MachineModuleInfo &MMI,
4512386eab3SJessica Paquette const StringMap<unsigned> &FunctionToInstrCount);
4522386eab3SJessica Paquette };
453596f483aSJessica Paquette } // Anonymous namespace.
454596f483aSJessica Paquette
455596f483aSJessica Paquette char MachineOutliner::ID = 0;
456596f483aSJessica Paquette
457596f483aSJessica Paquette namespace llvm {
createMachineOutlinerPass(bool RunOnAllFunctions)4588bda1881SJessica Paquette ModulePass *createMachineOutlinerPass(bool RunOnAllFunctions) {
4598bda1881SJessica Paquette MachineOutliner *OL = new MachineOutliner();
4608bda1881SJessica Paquette OL->RunOnAllFunctions = RunOnAllFunctions;
4618bda1881SJessica Paquette return OL;
46213593843SJessica Paquette }
46313593843SJessica Paquette
46478681be2SJessica Paquette } // namespace llvm
46578681be2SJessica Paquette
46678681be2SJessica Paquette INITIALIZE_PASS(MachineOutliner, DEBUG_TYPE, "Machine Function Outliner", false,
46778681be2SJessica Paquette false)
46878681be2SJessica Paquette
emitNotOutliningCheaperRemark(unsigned StringLen,std::vector<Candidate> & CandidatesForRepeatedSeq,OutlinedFunction & OF)4691cc52a00SJessica Paquette void MachineOutliner::emitNotOutliningCheaperRemark(
4701cc52a00SJessica Paquette unsigned StringLen, std::vector<Candidate> &CandidatesForRepeatedSeq,
4711cc52a00SJessica Paquette OutlinedFunction &OF) {
472c991cf36SJessica Paquette // FIXME: Right now, we arbitrarily choose some Candidate from the
473c991cf36SJessica Paquette // OutlinedFunction. This isn't necessarily fixed, nor does it have to be.
474c991cf36SJessica Paquette // We should probably sort these by function name or something to make sure
475c991cf36SJessica Paquette // the remarks are stable.
4761cc52a00SJessica Paquette Candidate &C = CandidatesForRepeatedSeq.front();
4771cc52a00SJessica Paquette MachineOptimizationRemarkEmitter MORE(*(C.getMF()), nullptr);
4781cc52a00SJessica Paquette MORE.emit([&]() {
4791cc52a00SJessica Paquette MachineOptimizationRemarkMissed R(DEBUG_TYPE, "NotOutliningCheaper",
4801cc52a00SJessica Paquette C.front()->getDebugLoc(), C.getMBB());
4811cc52a00SJessica Paquette R << "Did not outline " << NV("Length", StringLen) << " instructions"
4821cc52a00SJessica Paquette << " from " << NV("NumOccurrences", CandidatesForRepeatedSeq.size())
4831cc52a00SJessica Paquette << " locations."
4841cc52a00SJessica Paquette << " Bytes from outlining all occurrences ("
4851cc52a00SJessica Paquette << NV("OutliningCost", OF.getOutliningCost()) << ")"
4861cc52a00SJessica Paquette << " >= Unoutlined instruction bytes ("
4871cc52a00SJessica Paquette << NV("NotOutliningCost", OF.getNotOutlinedCost()) << ")"
4881cc52a00SJessica Paquette << " (Also found at: ";
4891cc52a00SJessica Paquette
4901cc52a00SJessica Paquette // Tell the user the other places the candidate was found.
4911cc52a00SJessica Paquette for (unsigned i = 1, e = CandidatesForRepeatedSeq.size(); i < e; i++) {
4921cc52a00SJessica Paquette R << NV((Twine("OtherStartLoc") + Twine(i)).str(),
4931cc52a00SJessica Paquette CandidatesForRepeatedSeq[i].front()->getDebugLoc());
4941cc52a00SJessica Paquette if (i != e - 1)
4951cc52a00SJessica Paquette R << ", ";
4961cc52a00SJessica Paquette }
4971cc52a00SJessica Paquette
4981cc52a00SJessica Paquette R << ")";
4991cc52a00SJessica Paquette return R;
5001cc52a00SJessica Paquette });
5011cc52a00SJessica Paquette }
5021cc52a00SJessica Paquette
emitOutlinedFunctionRemark(OutlinedFunction & OF)50358e706a6SJessica Paquette void MachineOutliner::emitOutlinedFunctionRemark(OutlinedFunction &OF) {
50458e706a6SJessica Paquette MachineBasicBlock *MBB = &*OF.MF->begin();
50558e706a6SJessica Paquette MachineOptimizationRemarkEmitter MORE(*OF.MF, nullptr);
50658e706a6SJessica Paquette MachineOptimizationRemark R(DEBUG_TYPE, "OutlinedFunction",
50758e706a6SJessica Paquette MBB->findDebugLoc(MBB->begin()), MBB);
50858e706a6SJessica Paquette R << "Saved " << NV("OutliningBenefit", OF.getBenefit()) << " bytes by "
50934b618bfSJessica Paquette << "outlining " << NV("Length", OF.getNumInstrs()) << " instructions "
51058e706a6SJessica Paquette << "from " << NV("NumOccurrences", OF.getOccurrenceCount())
51158e706a6SJessica Paquette << " locations. "
51258e706a6SJessica Paquette << "(Found at: ";
51358e706a6SJessica Paquette
51458e706a6SJessica Paquette // Tell the user the other places the candidate was found.
51558e706a6SJessica Paquette for (size_t i = 0, e = OF.Candidates.size(); i < e; i++) {
51658e706a6SJessica Paquette
51758e706a6SJessica Paquette R << NV((Twine("StartLoc") + Twine(i)).str(),
518e18d6ff0SJessica Paquette OF.Candidates[i].front()->getDebugLoc());
51958e706a6SJessica Paquette if (i != e - 1)
52058e706a6SJessica Paquette R << ", ";
52158e706a6SJessica Paquette }
52258e706a6SJessica Paquette
52358e706a6SJessica Paquette R << ")";
52458e706a6SJessica Paquette
52558e706a6SJessica Paquette MORE.emit(R);
52658e706a6SJessica Paquette }
52758e706a6SJessica Paquette
findCandidates(InstructionMapper & Mapper,std::vector<OutlinedFunction> & FunctionList)5286b7615aeSPuyan Lotfi void MachineOutliner::findCandidates(
5296b7615aeSPuyan Lotfi InstructionMapper &Mapper, std::vector<OutlinedFunction> &FunctionList) {
53078681be2SJessica Paquette FunctionList.clear();
531ce3a2dcfSJessica Paquette SuffixTree ST(Mapper.UnsignedVec);
53278681be2SJessica Paquette
533fbe7f5e9SDavid Tellenbach // First, find all of the repeated substrings in the tree of minimum length
5344e54ef88SJessica Paquette // 2.
535d87f5449SJessica Paquette std::vector<Candidate> CandidatesForRepeatedSeq;
53622f00f61SKazu Hirata for (const SuffixTree::RepeatedSubstring &RS : ST) {
537d4e7d074SJessica Paquette CandidatesForRepeatedSeq.clear();
5384e54ef88SJessica Paquette unsigned StringLen = RS.Length;
5394e54ef88SJessica Paquette for (const unsigned &StartIdx : RS.StartIndices) {
54052df8015SJessica Paquette unsigned EndIdx = StartIdx + StringLen - 1;
54152df8015SJessica Paquette // Trick: Discard some candidates that would be incompatible with the
54252df8015SJessica Paquette // ones we've already found for this sequence. This will save us some
54352df8015SJessica Paquette // work in candidate selection.
54452df8015SJessica Paquette //
54552df8015SJessica Paquette // If two candidates overlap, then we can't outline them both. This
54652df8015SJessica Paquette // happens when we have candidates that look like, say
54752df8015SJessica Paquette //
54852df8015SJessica Paquette // AA (where each "A" is an instruction).
54952df8015SJessica Paquette //
55052df8015SJessica Paquette // We might have some portion of the module that looks like this:
55152df8015SJessica Paquette // AAAAAA (6 A's)
55252df8015SJessica Paquette //
55352df8015SJessica Paquette // In this case, there are 5 different copies of "AA" in this range, but
55452df8015SJessica Paquette // at most 3 can be outlined. If only outlining 3 of these is going to
55552df8015SJessica Paquette // be unbeneficial, then we ought to not bother.
55652df8015SJessica Paquette //
55752df8015SJessica Paquette // Note that two things DON'T overlap when they look like this:
55852df8015SJessica Paquette // start1...end1 .... start2...end2
55952df8015SJessica Paquette // That is, one must either
56052df8015SJessica Paquette // * End before the other starts
56152df8015SJessica Paquette // * Start after the other ends
562cfeecdf7SKazu Hirata if (llvm::all_of(CandidatesForRepeatedSeq, [&StartIdx,
563cfeecdf7SKazu Hirata &EndIdx](const Candidate &C) {
5644e54ef88SJessica Paquette return (EndIdx < C.getStartIdx() || StartIdx > C.getEndIdx());
56552df8015SJessica Paquette })) {
56652df8015SJessica Paquette // It doesn't overlap with anything, so we can outline it.
56752df8015SJessica Paquette // Each sequence is over [StartIt, EndIt].
568aa087327SJessica Paquette // Save the candidate and its location.
569aa087327SJessica Paquette
57052df8015SJessica Paquette MachineBasicBlock::iterator StartIt = Mapper.InstrList[StartIdx];
57152df8015SJessica Paquette MachineBasicBlock::iterator EndIt = Mapper.InstrList[EndIdx];
572cad864d4SJessica Paquette MachineBasicBlock *MBB = StartIt->getParent();
57352df8015SJessica Paquette
574aa087327SJessica Paquette CandidatesForRepeatedSeq.emplace_back(StartIdx, StringLen, StartIt,
575cad864d4SJessica Paquette EndIt, MBB, FunctionList.size(),
576cad864d4SJessica Paquette Mapper.MBBFlagsMap[MBB]);
57752df8015SJessica Paquette }
578809d708bSJessica Paquette }
579809d708bSJessica Paquette
580acc15e12SJessica Paquette // We've found something we might want to outline.
581acc15e12SJessica Paquette // Create an OutlinedFunction to store it and check if it'd be beneficial
582acc15e12SJessica Paquette // to outline.
583ddb039a1SJessica Paquette if (CandidatesForRepeatedSeq.size() < 2)
584da08078fSEli Friedman continue;
585da08078fSEli Friedman
586da08078fSEli Friedman // Arbitrarily choose a TII from the first candidate.
587da08078fSEli Friedman // FIXME: Should getOutliningCandidateInfo move to TargetMachine?
588da08078fSEli Friedman const TargetInstrInfo *TII =
589da08078fSEli Friedman CandidatesForRepeatedSeq[0].getMF()->getSubtarget().getInstrInfo();
590da08078fSEli Friedman
5919d93c602SJessica Paquette OutlinedFunction OF =
592da08078fSEli Friedman TII->getOutliningCandidateInfo(CandidatesForRepeatedSeq);
5939d93c602SJessica Paquette
594b2d53c5dSJessica Paquette // If we deleted too many candidates, then there's nothing worth outlining.
595b2d53c5dSJessica Paquette // FIXME: This should take target-specified instruction sizes into account.
596b2d53c5dSJessica Paquette if (OF.Candidates.size() < 2)
5979d93c602SJessica Paquette continue;
5989d93c602SJessica Paquette
599ffe4abc5SJessica Paquette // Is it better to outline this candidate than not?
600f94d1d29SJessica Paquette if (OF.getBenefit() < 1) {
6011cc52a00SJessica Paquette emitNotOutliningCheaperRemark(StringLen, CandidatesForRepeatedSeq, OF);
60278681be2SJessica Paquette continue;
603ffe4abc5SJessica Paquette }
60478681be2SJessica Paquette
605acc15e12SJessica Paquette FunctionList.push_back(OF);
60678681be2SJessica Paquette }
607596f483aSJessica Paquette }
608596f483aSJessica Paquette
createOutlinedFunction(Module & M,OutlinedFunction & OF,InstructionMapper & Mapper,unsigned Name)6096b7615aeSPuyan Lotfi MachineFunction *MachineOutliner::createOutlinedFunction(
6106b7615aeSPuyan Lotfi Module &M, OutlinedFunction &OF, InstructionMapper &Mapper, unsigned Name) {
611596f483aSJessica Paquette
612ae6c9403SFangrui Song // Create the function name. This should be unique.
613a3eb0facSJessica Paquette // FIXME: We should have a better naming scheme. This should be stable,
614a3eb0facSJessica Paquette // regardless of changes to the outliner's cost model/traversal order.
6150c4aab27SPuyan Lotfi std::string FunctionName = "OUTLINED_FUNCTION_";
6160d896278SJin Lin if (OutlineRepeatedNum > 0)
6170c4aab27SPuyan Lotfi FunctionName += std::to_string(OutlineRepeatedNum + 1) + "_";
6180c4aab27SPuyan Lotfi FunctionName += std::to_string(Name);
619596f483aSJessica Paquette
620596f483aSJessica Paquette // Create the function using an IR-level function.
621596f483aSJessica Paquette LLVMContext &C = M.getContext();
622ae6c9403SFangrui Song Function *F = Function::Create(FunctionType::get(Type::getVoidTy(C), false),
623ae6c9403SFangrui Song Function::ExternalLinkage, FunctionName, M);
624596f483aSJessica Paquette
625596f483aSJessica Paquette // NOTE: If this is linkonceodr, then we can take advantage of linker deduping
626596f483aSJessica Paquette // which gives us better results when we outline from linkonceodr functions.
627d506bf8eSJessica Paquette F->setLinkage(GlobalValue::InternalLinkage);
628596f483aSJessica Paquette F->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
629596f483aSJessica Paquette
63025bef201SEli Friedman // Set optsize/minsize, so we don't insert padding between outlined
63125bef201SEli Friedman // functions.
63225bef201SEli Friedman F->addFnAttr(Attribute::OptimizeForSize);
63325bef201SEli Friedman F->addFnAttr(Attribute::MinSize);
63425bef201SEli Friedman
635e18d6ff0SJessica Paquette Candidate &FirstCand = OF.Candidates.front();
636f5f28d5bSTies Stuij const TargetInstrInfo &TII =
637f5f28d5bSTies Stuij *FirstCand.getMF()->getSubtarget().getInstrInfo();
638e3932eeeSJessica Paquette
639f5f28d5bSTies Stuij TII.mergeOutliningCandidateAttributes(*F, OF.Candidates);
640ca4c1ad8SDavid Green
6416398903aSMomchil Velikov // Set uwtable, so we generate eh_frame.
6426398903aSMomchil Velikov UWTableKind UW = std::accumulate(
6436398903aSMomchil Velikov OF.Candidates.cbegin(), OF.Candidates.cend(), UWTableKind::None,
6446398903aSMomchil Velikov [](UWTableKind K, const outliner::Candidate &C) {
6456398903aSMomchil Velikov return std::max(K, C.getMF()->getFunction().getUWTableKind());
6466398903aSMomchil Velikov });
6476398903aSMomchil Velikov if (UW != UWTableKind::None)
6486398903aSMomchil Velikov F->setUWTableKind(UW);
6496398903aSMomchil Velikov
650596f483aSJessica Paquette BasicBlock *EntryBB = BasicBlock::Create(C, "entry", F);
651596f483aSJessica Paquette IRBuilder<> Builder(EntryBB);
652596f483aSJessica Paquette Builder.CreateRetVoid();
653596f483aSJessica Paquette
654cc382cf7SYuanfang Chen MachineModuleInfo &MMI = getAnalysis<MachineModuleInfoWrapperPass>().getMMI();
6557bda1958SMatthias Braun MachineFunction &MF = MMI.getOrCreateMachineFunction(*F);
656596f483aSJessica Paquette MachineBasicBlock &MBB = *MF.CreateMachineBasicBlock();
657596f483aSJessica Paquette
658596f483aSJessica Paquette // Insert the new function into the module.
659596f483aSJessica Paquette MF.insert(MF.begin(), &MBB);
660596f483aSJessica Paquette
6618d5024f7SAndrew Litteken MachineFunction *OriginalMF = FirstCand.front()->getMF();
6628d5024f7SAndrew Litteken const std::vector<MCCFIInstruction> &Instrs =
6638d5024f7SAndrew Litteken OriginalMF->getFrameInstructions();
66434b618bfSJessica Paquette for (auto I = FirstCand.front(), E = std::next(FirstCand.back()); I != E;
66534b618bfSJessica Paquette ++I) {
6665b30d9adSMomchil Velikov if (I->isDebugInstr())
6675b30d9adSMomchil Velikov continue;
668596f483aSJessica Paquette
669596f483aSJessica Paquette // Don't keep debug information for outlined instructions.
670*0ff51d5dSEli Friedman auto DL = DebugLoc();
671*0ff51d5dSEli Friedman if (I->isCFIInstruction()) {
672*0ff51d5dSEli Friedman unsigned CFIIndex = I->getOperand(0).getCFIIndex();
673*0ff51d5dSEli Friedman MCCFIInstruction CFI = Instrs[CFIIndex];
674*0ff51d5dSEli Friedman BuildMI(MBB, MBB.end(), DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
675*0ff51d5dSEli Friedman .addCFIIndex(MF.addFrameInst(CFI));
676*0ff51d5dSEli Friedman } else {
677*0ff51d5dSEli Friedman MachineInstr *NewMI = MF.CloneMachineInstr(&*I);
678*0ff51d5dSEli Friedman NewMI->dropMemRefs(MF);
679*0ff51d5dSEli Friedman NewMI->setDebugLoc(DL);
680596f483aSJessica Paquette MBB.insert(MBB.end(), NewMI);
681596f483aSJessica Paquette }
682*0ff51d5dSEli Friedman }
683596f483aSJessica Paquette
6841a78b0bdSEli Friedman // Set normal properties for a late MachineFunction.
6851a78b0bdSEli Friedman MF.getProperties().reset(MachineFunctionProperties::Property::IsSSA);
6861a78b0bdSEli Friedman MF.getProperties().set(MachineFunctionProperties::Property::NoPHIs);
6871a78b0bdSEli Friedman MF.getProperties().set(MachineFunctionProperties::Property::NoVRegs);
6881a78b0bdSEli Friedman MF.getProperties().set(MachineFunctionProperties::Property::TracksLiveness);
689cc06a782SJessica Paquette MF.getRegInfo().freezeReservedRegs(MF);
690cc06a782SJessica Paquette
6911a78b0bdSEli Friedman // Compute live-in set for outlined fn
6921a78b0bdSEli Friedman const MachineRegisterInfo &MRI = MF.getRegInfo();
6931a78b0bdSEli Friedman const TargetRegisterInfo &TRI = *MRI.getTargetRegisterInfo();
6941a78b0bdSEli Friedman LivePhysRegs LiveIns(TRI);
6951a78b0bdSEli Friedman for (auto &Cand : OF.Candidates) {
6961a78b0bdSEli Friedman // Figure out live-ins at the first instruction.
6971a78b0bdSEli Friedman MachineBasicBlock &OutlineBB = *Cand.front()->getParent();
6981a78b0bdSEli Friedman LivePhysRegs CandLiveIns(TRI);
6991a78b0bdSEli Friedman CandLiveIns.addLiveOuts(OutlineBB);
7001a78b0bdSEli Friedman for (const MachineInstr &MI :
7011a78b0bdSEli Friedman reverse(make_range(Cand.front(), OutlineBB.end())))
7021a78b0bdSEli Friedman CandLiveIns.stepBackward(MI);
7031a78b0bdSEli Friedman
7041a78b0bdSEli Friedman // The live-in set for the outlined function is the union of the live-ins
7051a78b0bdSEli Friedman // from all the outlining points.
7066a6e3821SKazu Hirata for (MCPhysReg Reg : CandLiveIns)
7071a78b0bdSEli Friedman LiveIns.addReg(Reg);
7081a78b0bdSEli Friedman }
7091a78b0bdSEli Friedman addLiveIns(MBB, LiveIns);
7101a78b0bdSEli Friedman
7111a78b0bdSEli Friedman TII.buildOutlinedFrame(MBB, MF, OF);
7121a78b0bdSEli Friedman
713a499c3c2SJessica Paquette // If there's a DISubprogram associated with this outlined function, then
714a499c3c2SJessica Paquette // emit debug info for the outlined function.
715aa087327SJessica Paquette if (DISubprogram *SP = getSubprogramOrNull(OF)) {
716a499c3c2SJessica Paquette // We have a DISubprogram. Get its DICompileUnit.
717a499c3c2SJessica Paquette DICompileUnit *CU = SP->getUnit();
718a499c3c2SJessica Paquette DIBuilder DB(M, true, CU);
719a499c3c2SJessica Paquette DIFile *Unit = SP->getFile();
720a499c3c2SJessica Paquette Mangler Mg;
721a499c3c2SJessica Paquette // Get the mangled name of the function for the linkage name.
722a499c3c2SJessica Paquette std::string Dummy;
723a499c3c2SJessica Paquette llvm::raw_string_ostream MangledNameStream(Dummy);
724a499c3c2SJessica Paquette Mg.getNameWithPrefix(MangledNameStream, F, false);
725a499c3c2SJessica Paquette
726cc06a782SJessica Paquette DISubprogram *OutlinedSP = DB.createFunction(
727a499c3c2SJessica Paquette Unit /* Context */, F->getName(), StringRef(MangledNameStream.str()),
728a499c3c2SJessica Paquette Unit /* File */,
729a499c3c2SJessica Paquette 0 /* Line 0 is reserved for compiler-generated code. */,
730cc06a782SJessica Paquette DB.createSubroutineType(DB.getOrCreateTypeArray(None)), /* void type */
731cda54210SPaul Robinson 0, /* Line 0 is reserved for compiler-generated code. */
732a499c3c2SJessica Paquette DINode::DIFlags::FlagArtificial /* Compiler-generated code. */,
733cda54210SPaul Robinson /* Outlined code is optimized code by definition. */
734cda54210SPaul Robinson DISubprogram::SPFlagDefinition | DISubprogram::SPFlagOptimized);
735a499c3c2SJessica Paquette
736a499c3c2SJessica Paquette // Don't add any new variables to the subprogram.
737cc06a782SJessica Paquette DB.finalizeSubprogram(OutlinedSP);
738a499c3c2SJessica Paquette
739a499c3c2SJessica Paquette // Attach subprogram to the function.
740cc06a782SJessica Paquette F->setSubprogram(OutlinedSP);
741a499c3c2SJessica Paquette // We're done with the DIBuilder.
742a499c3c2SJessica Paquette DB.finalize();
743a499c3c2SJessica Paquette }
744a499c3c2SJessica Paquette
745596f483aSJessica Paquette return &MF;
746596f483aSJessica Paquette }
747596f483aSJessica Paquette
outline(Module & M,std::vector<OutlinedFunction> & FunctionList,InstructionMapper & Mapper,unsigned & OutlinedFunctionNum)7484ae3b71dSJessica Paquette bool MachineOutliner::outline(Module &M,
7494ae3b71dSJessica Paquette std::vector<OutlinedFunction> &FunctionList,
750a51fc8ddSPuyan Lotfi InstructionMapper &Mapper,
751a51fc8ddSPuyan Lotfi unsigned &OutlinedFunctionNum) {
752596f483aSJessica Paquette
753596f483aSJessica Paquette bool OutlinedSomething = false;
754a3eb0facSJessica Paquette
755962b3ae6SJessica Paquette // Sort by benefit. The most beneficial functions should be outlined first.
756efd94c56SFangrui Song llvm::stable_sort(FunctionList, [](const OutlinedFunction &LHS,
757efd94c56SFangrui Song const OutlinedFunction &RHS) {
758962b3ae6SJessica Paquette return LHS.getBenefit() > RHS.getBenefit();
759962b3ae6SJessica Paquette });
760596f483aSJessica Paquette
761962b3ae6SJessica Paquette // Walk over each function, outlining them as we go along. Functions are
762962b3ae6SJessica Paquette // outlined greedily, based off the sort above.
763962b3ae6SJessica Paquette for (OutlinedFunction &OF : FunctionList) {
764962b3ae6SJessica Paquette // If we outlined something that overlapped with a candidate in a previous
765962b3ae6SJessica Paquette // step, then we can't outline from it.
766e18d6ff0SJessica Paquette erase_if(OF.Candidates, [&Mapper](Candidate &C) {
767d9d9309bSJessica Paquette return std::any_of(
768e18d6ff0SJessica Paquette Mapper.UnsignedVec.begin() + C.getStartIdx(),
769e18d6ff0SJessica Paquette Mapper.UnsignedVec.begin() + C.getEndIdx() + 1,
770d9d9309bSJessica Paquette [](unsigned I) { return (I == static_cast<unsigned>(-1)); });
771235d877eSJessica Paquette });
772596f483aSJessica Paquette
773962b3ae6SJessica Paquette // If we made it unbeneficial to outline this function, skip it.
77485af63d0SJessica Paquette if (OF.getBenefit() < 1)
775596f483aSJessica Paquette continue;
776596f483aSJessica Paquette
777962b3ae6SJessica Paquette // It's beneficial. Create the function and outline its sequence's
778962b3ae6SJessica Paquette // occurrences.
779a3eb0facSJessica Paquette OF.MF = createOutlinedFunction(M, OF, Mapper, OutlinedFunctionNum);
78058e706a6SJessica Paquette emitOutlinedFunctionRemark(OF);
781acffa28cSJessica Paquette FunctionsCreated++;
782a3eb0facSJessica Paquette OutlinedFunctionNum++; // Created a function, move to the next name.
783596f483aSJessica Paquette MachineFunction *MF = OF.MF;
784596f483aSJessica Paquette const TargetSubtargetInfo &STI = MF->getSubtarget();
785596f483aSJessica Paquette const TargetInstrInfo &TII = *STI.getInstrInfo();
786596f483aSJessica Paquette
787962b3ae6SJessica Paquette // Replace occurrences of the sequence with calls to the new function.
788e18d6ff0SJessica Paquette for (Candidate &C : OF.Candidates) {
789962b3ae6SJessica Paquette MachineBasicBlock &MBB = *C.getMBB();
790962b3ae6SJessica Paquette MachineBasicBlock::iterator StartIt = C.front();
791962b3ae6SJessica Paquette MachineBasicBlock::iterator EndIt = C.back();
792596f483aSJessica Paquette
793962b3ae6SJessica Paquette // Insert the call.
794962b3ae6SJessica Paquette auto CallInst = TII.insertOutlinedCall(M, MBB, StartIt, *MF, C);
795962b3ae6SJessica Paquette
796962b3ae6SJessica Paquette // If the caller tracks liveness, then we need to make sure that
797962b3ae6SJessica Paquette // anything we outline doesn't break liveness assumptions. The outlined
798962b3ae6SJessica Paquette // functions themselves currently don't track liveness, but we should
799962b3ae6SJessica Paquette // make sure that the ranges we yank things out of aren't wrong.
800aa087327SJessica Paquette if (MBB.getParent()->getProperties().hasProperty(
8010b672491SJessica Paquette MachineFunctionProperties::Property::TracksLiveness)) {
802fc6fda90SJin Lin // The following code is to add implicit def operands to the call
80371d3869fSDjordje Todorovic // instruction. It also updates call site information for moved
80471d3869fSDjordje Todorovic // code.
805fc6fda90SJin Lin SmallSet<Register, 2> UseRegs, DefRegs;
8060b672491SJessica Paquette // Copy over the defs in the outlined range.
8070b672491SJessica Paquette // First inst in outlined range <-- Anything that's defined in this
808962b3ae6SJessica Paquette // ... .. range has to be added as an
809962b3ae6SJessica Paquette // implicit Last inst in outlined range <-- def to the call
81071d3869fSDjordje Todorovic // instruction. Also remove call site information for outlined block
811fc6fda90SJin Lin // of code. The exposed uses need to be copied in the outlined range.
812ffd5e121SPuyan Lotfi for (MachineBasicBlock::reverse_iterator
813ffd5e121SPuyan Lotfi Iter = EndIt.getReverse(),
814fc6fda90SJin Lin Last = std::next(CallInst.getReverse());
815fc6fda90SJin Lin Iter != Last; Iter++) {
816fc6fda90SJin Lin MachineInstr *MI = &*Iter;
8171e9fa0b1SDianQK SmallSet<Register, 2> InstrUseRegs;
818fc6fda90SJin Lin for (MachineOperand &MOP : MI->operands()) {
819fc6fda90SJin Lin // Skip over anything that isn't a register.
820fc6fda90SJin Lin if (!MOP.isReg())
821fc6fda90SJin Lin continue;
822fc6fda90SJin Lin
823fc6fda90SJin Lin if (MOP.isDef()) {
824fc6fda90SJin Lin // Introduce DefRegs set to skip the redundant register.
825fc6fda90SJin Lin DefRegs.insert(MOP.getReg());
8261e9fa0b1SDianQK if (UseRegs.count(MOP.getReg()) &&
8271e9fa0b1SDianQK !InstrUseRegs.count(MOP.getReg()))
828fc6fda90SJin Lin // Since the regiester is modeled as defined,
829fc6fda90SJin Lin // it is not necessary to be put in use register set.
830fc6fda90SJin Lin UseRegs.erase(MOP.getReg());
831fc6fda90SJin Lin } else if (!MOP.isUndef()) {
832fc6fda90SJin Lin // Any register which is not undefined should
833fc6fda90SJin Lin // be put in the use register set.
834fc6fda90SJin Lin UseRegs.insert(MOP.getReg());
8351e9fa0b1SDianQK InstrUseRegs.insert(MOP.getReg());
836fc6fda90SJin Lin }
837fc6fda90SJin Lin }
838fc6fda90SJin Lin if (MI->isCandidateForCallSiteEntry())
839fc6fda90SJin Lin MI->getMF()->eraseCallSiteInfo(MI);
840fc6fda90SJin Lin }
841fc6fda90SJin Lin
842fc6fda90SJin Lin for (const Register &I : DefRegs)
843fc6fda90SJin Lin // If it's a def, add it to the call instruction.
844ffd5e121SPuyan Lotfi CallInst->addOperand(
845ffd5e121SPuyan Lotfi MachineOperand::CreateReg(I, true, /* isDef = true */
846fc6fda90SJin Lin true /* isImp = true */));
847fc6fda90SJin Lin
848fc6fda90SJin Lin for (const Register &I : UseRegs)
849fc6fda90SJin Lin // If it's a exposed use, add it to the call instruction.
850fc6fda90SJin Lin CallInst->addOperand(
851fc6fda90SJin Lin MachineOperand::CreateReg(I, false, /* isDef = false */
852fc6fda90SJin Lin true /* isImp = true */));
8530b672491SJessica Paquette }
8540b672491SJessica Paquette
855aa087327SJessica Paquette // Erase from the point after where the call was inserted up to, and
856aa087327SJessica Paquette // including, the final instruction in the sequence.
857aa087327SJessica Paquette // Erase needs one past the end, so we need std::next there too.
858aa087327SJessica Paquette MBB.erase(std::next(StartIt), std::next(EndIt));
859235d877eSJessica Paquette
860d9d9309bSJessica Paquette // Keep track of what we removed by marking them all as -1.
8613b9707dbSKazu Hirata for (unsigned &I :
8623b9707dbSKazu Hirata llvm::make_range(Mapper.UnsignedVec.begin() + C.getStartIdx(),
8633b9707dbSKazu Hirata Mapper.UnsignedVec.begin() + C.getEndIdx() + 1))
8643b9707dbSKazu Hirata I = static_cast<unsigned>(-1);
865596f483aSJessica Paquette OutlinedSomething = true;
866596f483aSJessica Paquette
867596f483aSJessica Paquette // Statistics.
868596f483aSJessica Paquette NumOutlined++;
869596f483aSJessica Paquette }
870962b3ae6SJessica Paquette }
871596f483aSJessica Paquette
872d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "OutlinedSomething = " << OutlinedSomething << "\n";);
873596f483aSJessica Paquette return OutlinedSomething;
874596f483aSJessica Paquette }
875596f483aSJessica Paquette
populateMapper(InstructionMapper & Mapper,Module & M,MachineModuleInfo & MMI)876050d1ac4SJessica Paquette void MachineOutliner::populateMapper(InstructionMapper &Mapper, Module &M,
877050d1ac4SJessica Paquette MachineModuleInfo &MMI) {
878df82274fSJessica Paquette // Build instruction mappings for each function in the module. Start by
879df82274fSJessica Paquette // iterating over each Function in M.
880596f483aSJessica Paquette for (Function &F : M) {
881596f483aSJessica Paquette
882df82274fSJessica Paquette // If there's nothing in F, then there's no reason to try and outline from
883df82274fSJessica Paquette // it.
884df82274fSJessica Paquette if (F.empty())
885596f483aSJessica Paquette continue;
886596f483aSJessica Paquette
887df82274fSJessica Paquette // There's something in F. Check if it has a MachineFunction associated with
888df82274fSJessica Paquette // it.
889df82274fSJessica Paquette MachineFunction *MF = MMI.getMachineFunction(F);
890596f483aSJessica Paquette
891df82274fSJessica Paquette // If it doesn't, then there's nothing to outline from. Move to the next
892df82274fSJessica Paquette // Function.
893df82274fSJessica Paquette if (!MF)
894596f483aSJessica Paquette continue;
895596f483aSJessica Paquette
896da08078fSEli Friedman const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
897da08078fSEli Friedman
8988bda1881SJessica Paquette if (!RunOnAllFunctions && !TII->shouldOutlineFromFunctionByDefault(*MF))
8998bda1881SJessica Paquette continue;
9008bda1881SJessica Paquette
901df82274fSJessica Paquette // We have a MachineFunction. Ask the target if it's suitable for outlining.
902df82274fSJessica Paquette // If it isn't, then move on to the next Function in the module.
903df82274fSJessica Paquette if (!TII->isFunctionSafeToOutlineFrom(*MF, OutlineFromLinkOnceODRs))
904df82274fSJessica Paquette continue;
905df82274fSJessica Paquette
906df82274fSJessica Paquette // We have a function suitable for outlining. Iterate over every
907df82274fSJessica Paquette // MachineBasicBlock in MF and try to map its instructions to a list of
908df82274fSJessica Paquette // unsigned integers.
909df82274fSJessica Paquette for (MachineBasicBlock &MBB : *MF) {
910df82274fSJessica Paquette // If there isn't anything in MBB, then there's no point in outlining from
911df82274fSJessica Paquette // it.
912b320ca26SJessica Paquette // If there are fewer than 2 instructions in the MBB, then it can't ever
913b320ca26SJessica Paquette // contain something worth outlining.
914b320ca26SJessica Paquette // FIXME: This should be based off of the maximum size in B of an outlined
915b320ca26SJessica Paquette // call versus the size in B of the MBB.
916b320ca26SJessica Paquette if (MBB.empty() || MBB.size() < 2)
917df82274fSJessica Paquette continue;
918df82274fSJessica Paquette
919df82274fSJessica Paquette // Check if MBB could be the target of an indirect branch. If it is, then
920df82274fSJessica Paquette // we don't want to outline from it.
921df82274fSJessica Paquette if (MBB.hasAddressTaken())
922df82274fSJessica Paquette continue;
923df82274fSJessica Paquette
924df82274fSJessica Paquette // MBB is suitable for outlining. Map it to a list of unsigneds.
925da08078fSEli Friedman Mapper.convertToUnsignedVec(MBB, *TII);
926596f483aSJessica Paquette }
92712389e37SJessica Paquette
92812389e37SJessica Paquette // Statistics.
92912389e37SJessica Paquette UnsignedVecSize = Mapper.UnsignedVec.size();
930596f483aSJessica Paquette }
931050d1ac4SJessica Paquette }
932050d1ac4SJessica Paquette
initSizeRemarkInfo(const Module & M,const MachineModuleInfo & MMI,StringMap<unsigned> & FunctionToInstrCount)9332386eab3SJessica Paquette void MachineOutliner::initSizeRemarkInfo(
9342386eab3SJessica Paquette const Module &M, const MachineModuleInfo &MMI,
9352386eab3SJessica Paquette StringMap<unsigned> &FunctionToInstrCount) {
9362386eab3SJessica Paquette // Collect instruction counts for every function. We'll use this to emit
9372386eab3SJessica Paquette // per-function size remarks later.
9382386eab3SJessica Paquette for (const Function &F : M) {
9392386eab3SJessica Paquette MachineFunction *MF = MMI.getMachineFunction(F);
9402386eab3SJessica Paquette
9412386eab3SJessica Paquette // We only care about MI counts here. If there's no MachineFunction at this
9422386eab3SJessica Paquette // point, then there won't be after the outliner runs, so let's move on.
9432386eab3SJessica Paquette if (!MF)
9442386eab3SJessica Paquette continue;
9452386eab3SJessica Paquette FunctionToInstrCount[F.getName().str()] = MF->getInstructionCount();
9462386eab3SJessica Paquette }
9472386eab3SJessica Paquette }
9482386eab3SJessica Paquette
emitInstrCountChangedRemark(const Module & M,const MachineModuleInfo & MMI,const StringMap<unsigned> & FunctionToInstrCount)9492386eab3SJessica Paquette void MachineOutliner::emitInstrCountChangedRemark(
9502386eab3SJessica Paquette const Module &M, const MachineModuleInfo &MMI,
9512386eab3SJessica Paquette const StringMap<unsigned> &FunctionToInstrCount) {
9522386eab3SJessica Paquette // Iterate over each function in the module and emit remarks.
9532386eab3SJessica Paquette // Note that we won't miss anything by doing this, because the outliner never
9542386eab3SJessica Paquette // deletes functions.
9552386eab3SJessica Paquette for (const Function &F : M) {
9562386eab3SJessica Paquette MachineFunction *MF = MMI.getMachineFunction(F);
9572386eab3SJessica Paquette
9582386eab3SJessica Paquette // The outliner never deletes functions. If we don't have a MF here, then we
9592386eab3SJessica Paquette // didn't have one prior to outlining either.
9602386eab3SJessica Paquette if (!MF)
9612386eab3SJessica Paquette continue;
9622386eab3SJessica Paquette
963adcd0268SBenjamin Kramer std::string Fname = std::string(F.getName());
9642386eab3SJessica Paquette unsigned FnCountAfter = MF->getInstructionCount();
9652386eab3SJessica Paquette unsigned FnCountBefore = 0;
9662386eab3SJessica Paquette
9672386eab3SJessica Paquette // Check if the function was recorded before.
9682386eab3SJessica Paquette auto It = FunctionToInstrCount.find(Fname);
9692386eab3SJessica Paquette
9702386eab3SJessica Paquette // Did we have a previously-recorded size? If yes, then set FnCountBefore
9712386eab3SJessica Paquette // to that.
9722386eab3SJessica Paquette if (It != FunctionToInstrCount.end())
9732386eab3SJessica Paquette FnCountBefore = It->second;
9742386eab3SJessica Paquette
9752386eab3SJessica Paquette // Compute the delta and emit a remark if there was a change.
9762386eab3SJessica Paquette int64_t FnDelta = static_cast<int64_t>(FnCountAfter) -
9772386eab3SJessica Paquette static_cast<int64_t>(FnCountBefore);
9782386eab3SJessica Paquette if (FnDelta == 0)
9792386eab3SJessica Paquette continue;
9802386eab3SJessica Paquette
9812386eab3SJessica Paquette MachineOptimizationRemarkEmitter MORE(*MF, nullptr);
9822386eab3SJessica Paquette MORE.emit([&]() {
9832386eab3SJessica Paquette MachineOptimizationRemarkAnalysis R("size-info", "FunctionMISizeChange",
9846b7615aeSPuyan Lotfi DiagnosticLocation(), &MF->front());
9852386eab3SJessica Paquette R << DiagnosticInfoOptimizationBase::Argument("Pass", "Machine Outliner")
9862386eab3SJessica Paquette << ": Function: "
9872386eab3SJessica Paquette << DiagnosticInfoOptimizationBase::Argument("Function", F.getName())
9882386eab3SJessica Paquette << ": MI instruction count changed from "
9892386eab3SJessica Paquette << DiagnosticInfoOptimizationBase::Argument("MIInstrsBefore",
9902386eab3SJessica Paquette FnCountBefore)
9912386eab3SJessica Paquette << " to "
9922386eab3SJessica Paquette << DiagnosticInfoOptimizationBase::Argument("MIInstrsAfter",
9932386eab3SJessica Paquette FnCountAfter)
9942386eab3SJessica Paquette << "; Delta: "
9952386eab3SJessica Paquette << DiagnosticInfoOptimizationBase::Argument("Delta", FnDelta);
9962386eab3SJessica Paquette return R;
9972386eab3SJessica Paquette });
9982386eab3SJessica Paquette }
9992386eab3SJessica Paquette }
10002386eab3SJessica Paquette
runOnModule(Module & M)1001ffd5e121SPuyan Lotfi bool MachineOutliner::runOnModule(Module &M) {
1002050d1ac4SJessica Paquette // Check if there's anything in the module. If it's empty, then there's
1003050d1ac4SJessica Paquette // nothing to outline.
1004050d1ac4SJessica Paquette if (M.empty())
1005050d1ac4SJessica Paquette return false;
1006050d1ac4SJessica Paquette
1007a51fc8ddSPuyan Lotfi // Number to append to the current outlined function.
1008a51fc8ddSPuyan Lotfi unsigned OutlinedFunctionNum = 0;
1009a51fc8ddSPuyan Lotfi
1010ffd5e121SPuyan Lotfi OutlineRepeatedNum = 0;
1011a51fc8ddSPuyan Lotfi if (!doOutline(M, OutlinedFunctionNum))
1012a51fc8ddSPuyan Lotfi return false;
1013ffd5e121SPuyan Lotfi
1014ffd5e121SPuyan Lotfi for (unsigned I = 0; I < OutlinerReruns; ++I) {
1015ffd5e121SPuyan Lotfi OutlinedFunctionNum = 0;
1016ffd5e121SPuyan Lotfi OutlineRepeatedNum++;
1017ffd5e121SPuyan Lotfi if (!doOutline(M, OutlinedFunctionNum)) {
1018ffd5e121SPuyan Lotfi LLVM_DEBUG({
1019ffd5e121SPuyan Lotfi dbgs() << "Did not outline on iteration " << I + 2 << " out of "
1020ffd5e121SPuyan Lotfi << OutlinerReruns + 1 << "\n";
1021ffd5e121SPuyan Lotfi });
1022ffd5e121SPuyan Lotfi break;
1023ffd5e121SPuyan Lotfi }
1024ffd5e121SPuyan Lotfi }
1025ffd5e121SPuyan Lotfi
1026a51fc8ddSPuyan Lotfi return true;
1027a51fc8ddSPuyan Lotfi }
1028a51fc8ddSPuyan Lotfi
doOutline(Module & M,unsigned & OutlinedFunctionNum)1029a51fc8ddSPuyan Lotfi bool MachineOutliner::doOutline(Module &M, unsigned &OutlinedFunctionNum) {
1030cc382cf7SYuanfang Chen MachineModuleInfo &MMI = getAnalysis<MachineModuleInfoWrapperPass>().getMMI();
1031050d1ac4SJessica Paquette
1032050d1ac4SJessica Paquette // If the user passed -enable-machine-outliner=always or
1033050d1ac4SJessica Paquette // -enable-machine-outliner, the pass will run on all functions in the module.
1034050d1ac4SJessica Paquette // Otherwise, if the target supports default outlining, it will run on all
1035050d1ac4SJessica Paquette // functions deemed by the target to be worth outlining from by default. Tell
1036050d1ac4SJessica Paquette // the user how the outliner is running.
10376b7615aeSPuyan Lotfi LLVM_DEBUG({
1038050d1ac4SJessica Paquette dbgs() << "Machine Outliner: Running on ";
1039050d1ac4SJessica Paquette if (RunOnAllFunctions)
1040050d1ac4SJessica Paquette dbgs() << "all functions";
1041050d1ac4SJessica Paquette else
1042050d1ac4SJessica Paquette dbgs() << "target-default functions";
10436b7615aeSPuyan Lotfi dbgs() << "\n";
10446b7615aeSPuyan Lotfi });
1045050d1ac4SJessica Paquette
1046050d1ac4SJessica Paquette // If the user specifies that they want to outline from linkonceodrs, set
1047050d1ac4SJessica Paquette // it here.
1048050d1ac4SJessica Paquette OutlineFromLinkOnceODRs = EnableLinkOnceODROutlining;
1049050d1ac4SJessica Paquette InstructionMapper Mapper;
1050050d1ac4SJessica Paquette
1051050d1ac4SJessica Paquette // Prepare instruction mappings for the suffix tree.
1052050d1ac4SJessica Paquette populateMapper(Mapper, M, MMI);
1053596f483aSJessica Paquette std::vector<OutlinedFunction> FunctionList;
1054596f483aSJessica Paquette
1055acffa28cSJessica Paquette // Find all of the outlining candidates.
1056ce3a2dcfSJessica Paquette findCandidates(Mapper, FunctionList);
1057596f483aSJessica Paquette
10582386eab3SJessica Paquette // If we've requested size remarks, then collect the MI counts of every
10592386eab3SJessica Paquette // function before outlining, and the MI counts after outlining.
10602386eab3SJessica Paquette // FIXME: This shouldn't be in the outliner at all; it should ultimately be
10612386eab3SJessica Paquette // the pass manager's responsibility.
10622386eab3SJessica Paquette // This could pretty easily be placed in outline instead, but because we
10632386eab3SJessica Paquette // really ultimately *don't* want this here, it's done like this for now
10642386eab3SJessica Paquette // instead.
10652386eab3SJessica Paquette
10662386eab3SJessica Paquette // Check if we want size remarks.
10672386eab3SJessica Paquette bool ShouldEmitSizeRemarks = M.shouldEmitInstrCountChangedRemark();
10682386eab3SJessica Paquette StringMap<unsigned> FunctionToInstrCount;
10692386eab3SJessica Paquette if (ShouldEmitSizeRemarks)
10702386eab3SJessica Paquette initSizeRemarkInfo(M, MMI, FunctionToInstrCount);
10712386eab3SJessica Paquette
1072acffa28cSJessica Paquette // Outline each of the candidates and return true if something was outlined.
1073a51fc8ddSPuyan Lotfi bool OutlinedSomething =
1074a51fc8ddSPuyan Lotfi outline(M, FunctionList, Mapper, OutlinedFunctionNum);
1075729e6869SJessica Paquette
10762386eab3SJessica Paquette // If we outlined something, we definitely changed the MI count of the
10772386eab3SJessica Paquette // module. If we've asked for size remarks, then output them.
10782386eab3SJessica Paquette // FIXME: This should be in the pass manager.
10792386eab3SJessica Paquette if (ShouldEmitSizeRemarks && OutlinedSomething)
10802386eab3SJessica Paquette emitInstrCountChangedRemark(M, MMI, FunctionToInstrCount);
10812386eab3SJessica Paquette
1082ffd5e121SPuyan Lotfi LLVM_DEBUG({
1083ffd5e121SPuyan Lotfi if (!OutlinedSomething)
1084ffd5e121SPuyan Lotfi dbgs() << "Stopped outlining at iteration " << OutlineRepeatedNum
1085ffd5e121SPuyan Lotfi << " because no changes were found.\n";
1086ffd5e121SPuyan Lotfi });
1087ffd5e121SPuyan Lotfi
1088729e6869SJessica Paquette return OutlinedSomething;
1089596f483aSJessica Paquette }
1090