1 //===---- MachineOutliner.cpp - Outline instructions -----------*- C++ -*-===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
10 /// Replaces repeated sequences of instructions with function calls.
12 /// This works by placing every instruction from every basic block in a
13 /// suffix tree, and repeatedly querying that tree for repeated sequences of
14 /// instructions. If a sequence of instructions appears often, then it ought
15 /// to be beneficial to pull out into a function.
17 /// The MachineOutliner communicates with a given target using hooks defined in
18 /// TargetInstrInfo.h. The target supplies the outliner with information on how
19 /// a specific sequence of instructions should be outlined. This information
20 /// is used to deduce the number of instructions necessary to
22 /// * Create an outlined function
23 /// * Call that outlined function
25 /// Targets must implement
26 /// * getOutliningCandidateInfo
27 /// * buildOutlinedFrame
28 /// * insertOutlinedCall
29 /// * isFunctionSafeToOutlineFrom
31 /// in order to make use of the MachineOutliner.
33 /// This was originally presented at the 2016 LLVM Developers' Meeting in the
34 /// talk "Reducing Code Size Using Outlining". For a high-level overview of
35 /// how this pass works, the talk is available on YouTube at
37 /// https://www.youtube.com/watch?v=yorld-WSOeU
39 /// The slides for the talk are available at
41 /// http://www.llvm.org/devmtg/2016-11/Slides/Paquette-Outliner.pdf
43 /// The talk provides an overview of how the outliner finds candidates and
44 /// ultimately outlines them. It describes how the main data structure for this
45 /// pass, the suffix tree, is queried and purged for candidates. It also gives
46 /// a simplified suffix tree construction algorithm for suffix trees based off
47 /// of the algorithm actually used here, Ukkonen's algorithm.
49 /// For the original RFC for this pass, please see
51 /// http://lists.llvm.org/pipermail/llvm-dev/2016-August/104170.html
53 /// For more information on the suffix tree data structure, please see
54 /// https://www.cs.helsinki.fi/u/ukkonen/SuffixT1withFigs.pdf
56 //===----------------------------------------------------------------------===//
57 #include "llvm/CodeGen/MachineOutliner.h"
58 #include "llvm/ADT/DenseMap.h"
59 #include "llvm/ADT/SmallSet.h"
60 #include "llvm/ADT/Statistic.h"
61 #include "llvm/ADT/Twine.h"
62 #include "llvm/CodeGen/MachineModuleInfo.h"
63 #include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h"
64 #include "llvm/CodeGen/Passes.h"
65 #include "llvm/CodeGen/TargetInstrInfo.h"
66 #include "llvm/CodeGen/TargetSubtargetInfo.h"
67 #include "llvm/IR/DIBuilder.h"
68 #include "llvm/IR/IRBuilder.h"
69 #include "llvm/IR/Mangler.h"
70 #include "llvm/InitializePasses.h"
71 #include "llvm/Support/CommandLine.h"
72 #include "llvm/Support/Debug.h"
73 #include "llvm/Support/SuffixTree.h"
74 #include "llvm/Support/raw_ostream.h"
79 #define DEBUG_TYPE "machine-outliner"
83 using namespace outliner
;
85 // Statistics for outlined functions.
86 STATISTIC(NumOutlined
, "Number of candidates outlined");
87 STATISTIC(FunctionsCreated
, "Number of functions created");
89 // Statistics for instruction mapping.
90 STATISTIC(NumLegalInUnsignedVec
, "Number of legal instrs in unsigned vector");
91 STATISTIC(NumIllegalInUnsignedVec
,
92 "Number of illegal instrs in unsigned vector");
93 STATISTIC(NumInvisible
, "Number of invisible instrs in unsigned vector");
94 STATISTIC(UnsignedVecSize
, "Size of unsigned vector");
96 // Set to true if the user wants the outliner to run on linkonceodr linkage
97 // functions. This is false by default because the linker can dedupe linkonceodr
98 // functions. Since the outliner is confined to a single module (modulo LTO),
99 // this is off by default. It should, however, be the default behaviour in
101 static cl::opt
<bool> EnableLinkOnceODROutlining(
102 "enable-linkonceodr-outlining", cl::Hidden
,
103 cl::desc("Enable the machine outliner on linkonceodr functions"),
106 /// Number of times to re-run the outliner. This is not the total number of runs
107 /// as the outliner will run at least one time. The default value is set to 0,
108 /// meaning the outliner will run one time and rerun zero times after that.
109 static cl::opt
<unsigned> OutlinerReruns(
110 "machine-outliner-reruns", cl::init(0), cl::Hidden
,
112 "Number of times to rerun the outliner after the initial outline"));
116 /// Maps \p MachineInstrs to unsigned integers and stores the mappings.
117 struct InstructionMapper
{
119 /// The next available integer to assign to a \p MachineInstr that
120 /// cannot be outlined.
122 /// Set to -3 for compatability with \p DenseMapInfo<unsigned>.
123 unsigned IllegalInstrNumber
= -3;
125 /// The next available integer to assign to a \p MachineInstr that can
127 unsigned LegalInstrNumber
= 0;
129 /// Correspondence from \p MachineInstrs to unsigned integers.
130 DenseMap
<MachineInstr
*, unsigned, MachineInstrExpressionTrait
>
131 InstructionIntegerMap
;
133 /// Correspondence between \p MachineBasicBlocks and target-defined flags.
134 DenseMap
<MachineBasicBlock
*, unsigned> MBBFlagsMap
;
136 /// The vector of unsigned integers that the module is mapped to.
137 std::vector
<unsigned> UnsignedVec
;
139 /// Stores the location of the instruction associated with the integer
140 /// at index i in \p UnsignedVec for each index i.
141 std::vector
<MachineBasicBlock::iterator
> InstrList
;
143 // Set if we added an illegal number in the previous step.
144 // Since each illegal number is unique, we only need one of them between
145 // each range of legal numbers. This lets us make sure we don't add more
146 // than one illegal number per range.
147 bool AddedIllegalLastTime
= false;
149 /// Maps \p *It to a legal integer.
151 /// Updates \p CanOutlineWithPrevInstr, \p HaveLegalRange, \p InstrListForMBB,
152 /// \p UnsignedVecForMBB, \p InstructionIntegerMap, and \p LegalInstrNumber.
154 /// \returns The integer that \p *It was mapped to.
155 unsigned mapToLegalUnsigned(
156 MachineBasicBlock::iterator
&It
, bool &CanOutlineWithPrevInstr
,
157 bool &HaveLegalRange
, unsigned &NumLegalInBlock
,
158 std::vector
<unsigned> &UnsignedVecForMBB
,
159 std::vector
<MachineBasicBlock::iterator
> &InstrListForMBB
) {
160 // We added something legal, so we should unset the AddedLegalLastTime
162 AddedIllegalLastTime
= false;
164 // If we have at least two adjacent legal instructions (which may have
165 // invisible instructions in between), remember that.
166 if (CanOutlineWithPrevInstr
)
167 HaveLegalRange
= true;
168 CanOutlineWithPrevInstr
= true;
170 // Keep track of the number of legal instructions we insert.
173 // Get the integer for this instruction or give it the current
175 InstrListForMBB
.push_back(It
);
176 MachineInstr
&MI
= *It
;
178 DenseMap
<MachineInstr
*, unsigned, MachineInstrExpressionTrait
>::iterator
180 std::tie(ResultIt
, WasInserted
) =
181 InstructionIntegerMap
.insert(std::make_pair(&MI
, LegalInstrNumber
));
182 unsigned MINumber
= ResultIt
->second
;
184 // There was an insertion.
188 UnsignedVecForMBB
.push_back(MINumber
);
190 // Make sure we don't overflow or use any integers reserved by the DenseMap.
191 if (LegalInstrNumber
>= IllegalInstrNumber
)
192 report_fatal_error("Instruction mapping overflow!");
194 assert(LegalInstrNumber
!= DenseMapInfo
<unsigned>::getEmptyKey() &&
195 "Tried to assign DenseMap tombstone or empty key to instruction.");
196 assert(LegalInstrNumber
!= DenseMapInfo
<unsigned>::getTombstoneKey() &&
197 "Tried to assign DenseMap tombstone or empty key to instruction.");
200 ++NumLegalInUnsignedVec
;
204 /// Maps \p *It to an illegal integer.
206 /// Updates \p InstrListForMBB, \p UnsignedVecForMBB, and \p
207 /// IllegalInstrNumber.
209 /// \returns The integer that \p *It was mapped to.
210 unsigned mapToIllegalUnsigned(
211 MachineBasicBlock::iterator
&It
, bool &CanOutlineWithPrevInstr
,
212 std::vector
<unsigned> &UnsignedVecForMBB
,
213 std::vector
<MachineBasicBlock::iterator
> &InstrListForMBB
) {
214 // Can't outline an illegal instruction. Set the flag.
215 CanOutlineWithPrevInstr
= false;
217 // Only add one illegal number per range of legal numbers.
218 if (AddedIllegalLastTime
)
219 return IllegalInstrNumber
;
221 // Remember that we added an illegal number last time.
222 AddedIllegalLastTime
= true;
223 unsigned MINumber
= IllegalInstrNumber
;
225 InstrListForMBB
.push_back(It
);
226 UnsignedVecForMBB
.push_back(IllegalInstrNumber
);
227 IllegalInstrNumber
--;
229 ++NumIllegalInUnsignedVec
;
231 assert(LegalInstrNumber
< IllegalInstrNumber
&&
232 "Instruction mapping overflow!");
234 assert(IllegalInstrNumber
!= DenseMapInfo
<unsigned>::getEmptyKey() &&
235 "IllegalInstrNumber cannot be DenseMap tombstone or empty key!");
237 assert(IllegalInstrNumber
!= DenseMapInfo
<unsigned>::getTombstoneKey() &&
238 "IllegalInstrNumber cannot be DenseMap tombstone or empty key!");
243 /// Transforms a \p MachineBasicBlock into a \p vector of \p unsigneds
244 /// and appends it to \p UnsignedVec and \p InstrList.
246 /// Two instructions are assigned the same integer if they are identical.
247 /// If an instruction is deemed unsafe to outline, then it will be assigned an
248 /// unique integer. The resulting mapping is placed into a suffix tree and
249 /// queried for candidates.
251 /// \param MBB The \p MachineBasicBlock to be translated into integers.
252 /// \param TII \p TargetInstrInfo for the function.
253 void convertToUnsignedVec(MachineBasicBlock
&MBB
,
254 const TargetInstrInfo
&TII
) {
257 // Don't even map in this case.
258 if (!TII
.isMBBSafeToOutlineFrom(MBB
, Flags
))
261 // Store info for the MBB for later outlining.
262 MBBFlagsMap
[&MBB
] = Flags
;
264 MachineBasicBlock::iterator It
= MBB
.begin();
266 // The number of instructions in this block that will be considered for
268 unsigned NumLegalInBlock
= 0;
270 // True if we have at least two legal instructions which aren't separated
271 // by an illegal instruction.
272 bool HaveLegalRange
= false;
274 // True if we can perform outlining given the last mapped (non-invisible)
275 // instruction. This lets us know if we have a legal range.
276 bool CanOutlineWithPrevInstr
= false;
278 // FIXME: Should this all just be handled in the target, rather than using
279 // repeated calls to getOutliningType?
280 std::vector
<unsigned> UnsignedVecForMBB
;
281 std::vector
<MachineBasicBlock::iterator
> InstrListForMBB
;
283 for (MachineBasicBlock::iterator Et
= MBB
.end(); It
!= Et
; ++It
) {
284 // Keep track of where this instruction is in the module.
285 switch (TII
.getOutliningType(It
, Flags
)) {
286 case InstrType::Illegal
:
287 mapToIllegalUnsigned(It
, CanOutlineWithPrevInstr
, UnsignedVecForMBB
,
291 case InstrType::Legal
:
292 mapToLegalUnsigned(It
, CanOutlineWithPrevInstr
, HaveLegalRange
,
293 NumLegalInBlock
, UnsignedVecForMBB
, InstrListForMBB
);
296 case InstrType::LegalTerminator
:
297 mapToLegalUnsigned(It
, CanOutlineWithPrevInstr
, HaveLegalRange
,
298 NumLegalInBlock
, UnsignedVecForMBB
, InstrListForMBB
);
299 // The instruction also acts as a terminator, so we have to record that
301 mapToIllegalUnsigned(It
, CanOutlineWithPrevInstr
, UnsignedVecForMBB
,
305 case InstrType::Invisible
:
306 // Normally this is set by mapTo(Blah)Unsigned, but we just want to
307 // skip this instruction. So, unset the flag here.
309 AddedIllegalLastTime
= false;
314 // Are there enough legal instructions in the block for outlining to be
316 if (HaveLegalRange
) {
317 // After we're done every insertion, uniquely terminate this part of the
318 // "string". This makes sure we won't match across basic block or function
319 // boundaries since the "end" is encoded uniquely and thus appears in no
320 // repeated substring.
321 mapToIllegalUnsigned(It
, CanOutlineWithPrevInstr
, UnsignedVecForMBB
,
323 llvm::append_range(InstrList
, InstrListForMBB
);
324 llvm::append_range(UnsignedVec
, UnsignedVecForMBB
);
328 InstructionMapper() {
329 // Make sure that the implementation of DenseMapInfo<unsigned> hasn't
331 assert(DenseMapInfo
<unsigned>::getEmptyKey() == (unsigned)-1 &&
332 "DenseMapInfo<unsigned>'s empty key isn't -1!");
333 assert(DenseMapInfo
<unsigned>::getTombstoneKey() == (unsigned)-2 &&
334 "DenseMapInfo<unsigned>'s tombstone key isn't -2!");
338 /// An interprocedural pass which finds repeated sequences of
339 /// instructions and replaces them with calls to functions.
341 /// Each instruction is mapped to an unsigned integer and placed in a string.
342 /// The resulting mapping is then placed in a \p SuffixTree. The \p SuffixTree
343 /// is then repeatedly queried for repeated sequences of instructions. Each
344 /// non-overlapping repeated sequence is then placed in its own
345 /// \p MachineFunction and each instance is then replaced with a call to that
347 struct MachineOutliner
: public ModulePass
{
351 /// Set to true if the outliner should consider functions with
352 /// linkonceodr linkage.
353 bool OutlineFromLinkOnceODRs
= false;
355 /// The current repeat number of machine outlining.
356 unsigned OutlineRepeatedNum
= 0;
358 /// Set to true if the outliner should run on all functions in the module
359 /// considered safe for outlining.
360 /// Set to true by default for compatibility with llc's -run-pass option.
361 /// Set when the pass is constructed in TargetPassConfig.
362 bool RunOnAllFunctions
= true;
364 StringRef
getPassName() const override
{ return "Machine Outliner"; }
366 void getAnalysisUsage(AnalysisUsage
&AU
) const override
{
367 AU
.addRequired
<MachineModuleInfoWrapperPass
>();
368 AU
.addPreserved
<MachineModuleInfoWrapperPass
>();
369 AU
.setPreservesAll();
370 ModulePass::getAnalysisUsage(AU
);
373 MachineOutliner() : ModulePass(ID
) {
374 initializeMachineOutlinerPass(*PassRegistry::getPassRegistry());
377 /// Remark output explaining that not outlining a set of candidates would be
378 /// better than outlining that set.
379 void emitNotOutliningCheaperRemark(
380 unsigned StringLen
, std::vector
<Candidate
> &CandidatesForRepeatedSeq
,
381 OutlinedFunction
&OF
);
383 /// Remark output explaining that a function was outlined.
384 void emitOutlinedFunctionRemark(OutlinedFunction
&OF
);
386 /// Find all repeated substrings that satisfy the outlining cost model by
387 /// constructing a suffix tree.
389 /// If a substring appears at least twice, then it must be represented by
390 /// an internal node which appears in at least two suffixes. Each suffix
391 /// is represented by a leaf node. To do this, we visit each internal node
392 /// in the tree, using the leaf children of each internal node. If an
393 /// internal node represents a beneficial substring, then we use each of
394 /// its leaf children to find the locations of its substring.
396 /// \param Mapper Contains outlining mapping information.
397 /// \param[out] FunctionList Filled with a list of \p OutlinedFunctions
398 /// each type of candidate.
399 void findCandidates(InstructionMapper
&Mapper
,
400 std::vector
<OutlinedFunction
> &FunctionList
);
402 /// Replace the sequences of instructions represented by \p OutlinedFunctions
403 /// with calls to functions.
405 /// \param M The module we are outlining from.
406 /// \param FunctionList A list of functions to be inserted into the module.
407 /// \param Mapper Contains the instruction mappings for the module.
408 bool outline(Module
&M
, std::vector
<OutlinedFunction
> &FunctionList
,
409 InstructionMapper
&Mapper
, unsigned &OutlinedFunctionNum
);
411 /// Creates a function for \p OF and inserts it into the module.
412 MachineFunction
*createOutlinedFunction(Module
&M
, OutlinedFunction
&OF
,
413 InstructionMapper
&Mapper
,
416 /// Calls 'doOutline()' 1 + OutlinerReruns times.
417 bool runOnModule(Module
&M
) override
;
419 /// Construct a suffix tree on the instructions in \p M and outline repeated
420 /// strings from that tree.
421 bool doOutline(Module
&M
, unsigned &OutlinedFunctionNum
);
423 /// Return a DISubprogram for OF if one exists, and null otherwise. Helper
424 /// function for remark emission.
425 DISubprogram
*getSubprogramOrNull(const OutlinedFunction
&OF
) {
426 for (const Candidate
&C
: OF
.Candidates
)
427 if (MachineFunction
*MF
= C
.getMF())
428 if (DISubprogram
*SP
= MF
->getFunction().getSubprogram())
433 /// Populate and \p InstructionMapper with instruction-to-integer mappings.
434 /// These are used to construct a suffix tree.
435 void populateMapper(InstructionMapper
&Mapper
, Module
&M
,
436 MachineModuleInfo
&MMI
);
438 /// Initialize information necessary to output a size remark.
439 /// FIXME: This should be handled by the pass manager, not the outliner.
440 /// FIXME: This is nearly identical to the initSizeRemarkInfo in the legacy
442 void initSizeRemarkInfo(const Module
&M
, const MachineModuleInfo
&MMI
,
443 StringMap
<unsigned> &FunctionToInstrCount
);
446 // FIXME: This should be handled by the pass manager, not the outliner.
448 emitInstrCountChangedRemark(const Module
&M
, const MachineModuleInfo
&MMI
,
449 const StringMap
<unsigned> &FunctionToInstrCount
);
451 } // Anonymous namespace.
453 char MachineOutliner::ID
= 0;
456 ModulePass
*createMachineOutlinerPass(bool RunOnAllFunctions
) {
457 MachineOutliner
*OL
= new MachineOutliner();
458 OL
->RunOnAllFunctions
= RunOnAllFunctions
;
464 INITIALIZE_PASS(MachineOutliner
, DEBUG_TYPE
, "Machine Function Outliner", false,
467 void MachineOutliner::emitNotOutliningCheaperRemark(
468 unsigned StringLen
, std::vector
<Candidate
> &CandidatesForRepeatedSeq
,
469 OutlinedFunction
&OF
) {
470 // FIXME: Right now, we arbitrarily choose some Candidate from the
471 // OutlinedFunction. This isn't necessarily fixed, nor does it have to be.
472 // We should probably sort these by function name or something to make sure
473 // the remarks are stable.
474 Candidate
&C
= CandidatesForRepeatedSeq
.front();
475 MachineOptimizationRemarkEmitter
MORE(*(C
.getMF()), nullptr);
477 MachineOptimizationRemarkMissed
R(DEBUG_TYPE
, "NotOutliningCheaper",
478 C
.front()->getDebugLoc(), C
.getMBB());
479 R
<< "Did not outline " << NV("Length", StringLen
) << " instructions"
480 << " from " << NV("NumOccurrences", CandidatesForRepeatedSeq
.size())
482 << " Bytes from outlining all occurrences ("
483 << NV("OutliningCost", OF
.getOutliningCost()) << ")"
484 << " >= Unoutlined instruction bytes ("
485 << NV("NotOutliningCost", OF
.getNotOutlinedCost()) << ")"
486 << " (Also found at: ";
488 // Tell the user the other places the candidate was found.
489 for (unsigned i
= 1, e
= CandidatesForRepeatedSeq
.size(); i
< e
; i
++) {
490 R
<< NV((Twine("OtherStartLoc") + Twine(i
)).str(),
491 CandidatesForRepeatedSeq
[i
].front()->getDebugLoc());
501 void MachineOutliner::emitOutlinedFunctionRemark(OutlinedFunction
&OF
) {
502 MachineBasicBlock
*MBB
= &*OF
.MF
->begin();
503 MachineOptimizationRemarkEmitter
MORE(*OF
.MF
, nullptr);
504 MachineOptimizationRemark
R(DEBUG_TYPE
, "OutlinedFunction",
505 MBB
->findDebugLoc(MBB
->begin()), MBB
);
506 R
<< "Saved " << NV("OutliningBenefit", OF
.getBenefit()) << " bytes by "
507 << "outlining " << NV("Length", OF
.getNumInstrs()) << " instructions "
508 << "from " << NV("NumOccurrences", OF
.getOccurrenceCount())
512 // Tell the user the other places the candidate was found.
513 for (size_t i
= 0, e
= OF
.Candidates
.size(); i
< e
; i
++) {
515 R
<< NV((Twine("StartLoc") + Twine(i
)).str(),
516 OF
.Candidates
[i
].front()->getDebugLoc());
526 void MachineOutliner::findCandidates(
527 InstructionMapper
&Mapper
, std::vector
<OutlinedFunction
> &FunctionList
) {
528 FunctionList
.clear();
529 SuffixTree
ST(Mapper
.UnsignedVec
);
531 // First, find all of the repeated substrings in the tree of minimum length
533 std::vector
<Candidate
> CandidatesForRepeatedSeq
;
534 for (const SuffixTree::RepeatedSubstring
&RS
: ST
) {
535 CandidatesForRepeatedSeq
.clear();
536 unsigned StringLen
= RS
.Length
;
537 for (const unsigned &StartIdx
: RS
.StartIndices
) {
538 unsigned EndIdx
= StartIdx
+ StringLen
- 1;
539 // Trick: Discard some candidates that would be incompatible with the
540 // ones we've already found for this sequence. This will save us some
541 // work in candidate selection.
543 // If two candidates overlap, then we can't outline them both. This
544 // happens when we have candidates that look like, say
546 // AA (where each "A" is an instruction).
548 // We might have some portion of the module that looks like this:
551 // In this case, there are 5 different copies of "AA" in this range, but
552 // at most 3 can be outlined. If only outlining 3 of these is going to
553 // be unbeneficial, then we ought to not bother.
555 // Note that two things DON'T overlap when they look like this:
556 // start1...end1 .... start2...end2
557 // That is, one must either
558 // * End before the other starts
559 // * Start after the other ends
560 if (llvm::all_of(CandidatesForRepeatedSeq
, [&StartIdx
,
561 &EndIdx
](const Candidate
&C
) {
562 return (EndIdx
< C
.getStartIdx() || StartIdx
> C
.getEndIdx());
564 // It doesn't overlap with anything, so we can outline it.
565 // Each sequence is over [StartIt, EndIt].
566 // Save the candidate and its location.
568 MachineBasicBlock::iterator StartIt
= Mapper
.InstrList
[StartIdx
];
569 MachineBasicBlock::iterator EndIt
= Mapper
.InstrList
[EndIdx
];
570 MachineBasicBlock
*MBB
= StartIt
->getParent();
572 CandidatesForRepeatedSeq
.emplace_back(StartIdx
, StringLen
, StartIt
,
573 EndIt
, MBB
, FunctionList
.size(),
574 Mapper
.MBBFlagsMap
[MBB
]);
578 // We've found something we might want to outline.
579 // Create an OutlinedFunction to store it and check if it'd be beneficial
581 if (CandidatesForRepeatedSeq
.size() < 2)
584 // Arbitrarily choose a TII from the first candidate.
585 // FIXME: Should getOutliningCandidateInfo move to TargetMachine?
586 const TargetInstrInfo
*TII
=
587 CandidatesForRepeatedSeq
[0].getMF()->getSubtarget().getInstrInfo();
589 OutlinedFunction OF
=
590 TII
->getOutliningCandidateInfo(CandidatesForRepeatedSeq
);
592 // If we deleted too many candidates, then there's nothing worth outlining.
593 // FIXME: This should take target-specified instruction sizes into account.
594 if (OF
.Candidates
.size() < 2)
597 // Is it better to outline this candidate than not?
598 if (OF
.getBenefit() < 1) {
599 emitNotOutliningCheaperRemark(StringLen
, CandidatesForRepeatedSeq
, OF
);
603 FunctionList
.push_back(OF
);
607 MachineFunction
*MachineOutliner::createOutlinedFunction(
608 Module
&M
, OutlinedFunction
&OF
, InstructionMapper
&Mapper
, unsigned Name
) {
610 // Create the function name. This should be unique.
611 // FIXME: We should have a better naming scheme. This should be stable,
612 // regardless of changes to the outliner's cost model/traversal order.
613 std::string FunctionName
= "OUTLINED_FUNCTION_";
614 if (OutlineRepeatedNum
> 0)
615 FunctionName
+= std::to_string(OutlineRepeatedNum
+ 1) + "_";
616 FunctionName
+= std::to_string(Name
);
618 // Create the function using an IR-level function.
619 LLVMContext
&C
= M
.getContext();
620 Function
*F
= Function::Create(FunctionType::get(Type::getVoidTy(C
), false),
621 Function::ExternalLinkage
, FunctionName
, M
);
623 // NOTE: If this is linkonceodr, then we can take advantage of linker deduping
624 // which gives us better results when we outline from linkonceodr functions.
625 F
->setLinkage(GlobalValue::InternalLinkage
);
626 F
->setUnnamedAddr(GlobalValue::UnnamedAddr::Global
);
628 // Set optsize/minsize, so we don't insert padding between outlined
630 F
->addFnAttr(Attribute::OptimizeForSize
);
631 F
->addFnAttr(Attribute::MinSize
);
633 Candidate
&FirstCand
= OF
.Candidates
.front();
634 const TargetInstrInfo
&TII
=
635 *FirstCand
.getMF()->getSubtarget().getInstrInfo();
637 TII
.mergeOutliningCandidateAttributes(*F
, OF
.Candidates
);
639 // Set uwtable, so we generate eh_frame.
640 UWTableKind UW
= std::accumulate(
641 OF
.Candidates
.cbegin(), OF
.Candidates
.cend(), UWTableKind::None
,
642 [](UWTableKind K
, const outliner::Candidate
&C
) {
643 return std::max(K
, C
.getMF()->getFunction().getUWTableKind());
645 if (UW
!= UWTableKind::None
)
646 F
->setUWTableKind(UW
);
648 BasicBlock
*EntryBB
= BasicBlock::Create(C
, "entry", F
);
649 IRBuilder
<> Builder(EntryBB
);
650 Builder
.CreateRetVoid();
652 MachineModuleInfo
&MMI
= getAnalysis
<MachineModuleInfoWrapperPass
>().getMMI();
653 MachineFunction
&MF
= MMI
.getOrCreateMachineFunction(*F
);
654 MachineBasicBlock
&MBB
= *MF
.CreateMachineBasicBlock();
656 // Insert the new function into the module.
657 MF
.insert(MF
.begin(), &MBB
);
659 MachineFunction
*OriginalMF
= FirstCand
.front()->getMF();
660 const std::vector
<MCCFIInstruction
> &Instrs
=
661 OriginalMF
->getFrameInstructions();
662 for (auto I
= FirstCand
.front(), E
= std::next(FirstCand
.back()); I
!= E
;
664 if (I
->isDebugInstr())
666 MachineInstr
*NewMI
= MF
.CloneMachineInstr(&*I
);
667 if (I
->isCFIInstruction()) {
668 unsigned CFIIndex
= NewMI
->getOperand(0).getCFIIndex();
669 MCCFIInstruction CFI
= Instrs
[CFIIndex
];
670 (void)MF
.addFrameInst(CFI
);
672 NewMI
->dropMemRefs(MF
);
674 // Don't keep debug information for outlined instructions.
675 NewMI
->setDebugLoc(DebugLoc());
676 MBB
.insert(MBB
.end(), NewMI
);
679 // Set normal properties for a late MachineFunction.
680 MF
.getProperties().reset(MachineFunctionProperties::Property::IsSSA
);
681 MF
.getProperties().set(MachineFunctionProperties::Property::NoPHIs
);
682 MF
.getProperties().set(MachineFunctionProperties::Property::NoVRegs
);
683 MF
.getProperties().set(MachineFunctionProperties::Property::TracksLiveness
);
684 MF
.getRegInfo().freezeReservedRegs(MF
);
686 // Compute live-in set for outlined fn
687 const MachineRegisterInfo
&MRI
= MF
.getRegInfo();
688 const TargetRegisterInfo
&TRI
= *MRI
.getTargetRegisterInfo();
689 LivePhysRegs
LiveIns(TRI
);
690 for (auto &Cand
: OF
.Candidates
) {
691 // Figure out live-ins at the first instruction.
692 MachineBasicBlock
&OutlineBB
= *Cand
.front()->getParent();
693 LivePhysRegs
CandLiveIns(TRI
);
694 CandLiveIns
.addLiveOuts(OutlineBB
);
695 for (const MachineInstr
&MI
:
696 reverse(make_range(Cand
.front(), OutlineBB
.end())))
697 CandLiveIns
.stepBackward(MI
);
699 // The live-in set for the outlined function is the union of the live-ins
700 // from all the outlining points.
701 for (MCPhysReg Reg
: CandLiveIns
)
704 addLiveIns(MBB
, LiveIns
);
706 TII
.buildOutlinedFrame(MBB
, MF
, OF
);
708 // If there's a DISubprogram associated with this outlined function, then
709 // emit debug info for the outlined function.
710 if (DISubprogram
*SP
= getSubprogramOrNull(OF
)) {
711 // We have a DISubprogram. Get its DICompileUnit.
712 DICompileUnit
*CU
= SP
->getUnit();
713 DIBuilder
DB(M
, true, CU
);
714 DIFile
*Unit
= SP
->getFile();
716 // Get the mangled name of the function for the linkage name.
718 llvm::raw_string_ostream
MangledNameStream(Dummy
);
719 Mg
.getNameWithPrefix(MangledNameStream
, F
, false);
721 DISubprogram
*OutlinedSP
= DB
.createFunction(
722 Unit
/* Context */, F
->getName(), StringRef(MangledNameStream
.str()),
724 0 /* Line 0 is reserved for compiler-generated code. */,
725 DB
.createSubroutineType(DB
.getOrCreateTypeArray(None
)), /* void type */
726 0, /* Line 0 is reserved for compiler-generated code. */
727 DINode::DIFlags::FlagArtificial
/* Compiler-generated code. */,
728 /* Outlined code is optimized code by definition. */
729 DISubprogram::SPFlagDefinition
| DISubprogram::SPFlagOptimized
);
731 // Don't add any new variables to the subprogram.
732 DB
.finalizeSubprogram(OutlinedSP
);
734 // Attach subprogram to the function.
735 F
->setSubprogram(OutlinedSP
);
736 // We're done with the DIBuilder.
743 bool MachineOutliner::outline(Module
&M
,
744 std::vector
<OutlinedFunction
> &FunctionList
,
745 InstructionMapper
&Mapper
,
746 unsigned &OutlinedFunctionNum
) {
748 bool OutlinedSomething
= false;
750 // Sort by benefit. The most beneficial functions should be outlined first.
751 llvm::stable_sort(FunctionList
, [](const OutlinedFunction
&LHS
,
752 const OutlinedFunction
&RHS
) {
753 return LHS
.getBenefit() > RHS
.getBenefit();
756 // Walk over each function, outlining them as we go along. Functions are
757 // outlined greedily, based off the sort above.
758 for (OutlinedFunction
&OF
: FunctionList
) {
759 // If we outlined something that overlapped with a candidate in a previous
760 // step, then we can't outline from it.
761 erase_if(OF
.Candidates
, [&Mapper
](Candidate
&C
) {
763 Mapper
.UnsignedVec
.begin() + C
.getStartIdx(),
764 Mapper
.UnsignedVec
.begin() + C
.getEndIdx() + 1,
765 [](unsigned I
) { return (I
== static_cast<unsigned>(-1)); });
768 // If we made it unbeneficial to outline this function, skip it.
769 if (OF
.getBenefit() < 1)
772 // It's beneficial. Create the function and outline its sequence's
774 OF
.MF
= createOutlinedFunction(M
, OF
, Mapper
, OutlinedFunctionNum
);
775 emitOutlinedFunctionRemark(OF
);
777 OutlinedFunctionNum
++; // Created a function, move to the next name.
778 MachineFunction
*MF
= OF
.MF
;
779 const TargetSubtargetInfo
&STI
= MF
->getSubtarget();
780 const TargetInstrInfo
&TII
= *STI
.getInstrInfo();
782 // Replace occurrences of the sequence with calls to the new function.
783 for (Candidate
&C
: OF
.Candidates
) {
784 MachineBasicBlock
&MBB
= *C
.getMBB();
785 MachineBasicBlock::iterator StartIt
= C
.front();
786 MachineBasicBlock::iterator EndIt
= C
.back();
789 auto CallInst
= TII
.insertOutlinedCall(M
, MBB
, StartIt
, *MF
, C
);
791 // If the caller tracks liveness, then we need to make sure that
792 // anything we outline doesn't break liveness assumptions. The outlined
793 // functions themselves currently don't track liveness, but we should
794 // make sure that the ranges we yank things out of aren't wrong.
795 if (MBB
.getParent()->getProperties().hasProperty(
796 MachineFunctionProperties::Property::TracksLiveness
)) {
797 // The following code is to add implicit def operands to the call
798 // instruction. It also updates call site information for moved
800 SmallSet
<Register
, 2> UseRegs
, DefRegs
;
801 // Copy over the defs in the outlined range.
802 // First inst in outlined range <-- Anything that's defined in this
803 // ... .. range has to be added as an
804 // implicit Last inst in outlined range <-- def to the call
805 // instruction. Also remove call site information for outlined block
806 // of code. The exposed uses need to be copied in the outlined range.
807 for (MachineBasicBlock::reverse_iterator
808 Iter
= EndIt
.getReverse(),
809 Last
= std::next(CallInst
.getReverse());
810 Iter
!= Last
; Iter
++) {
811 MachineInstr
*MI
= &*Iter
;
812 SmallSet
<Register
, 2> InstrUseRegs
;
813 for (MachineOperand
&MOP
: MI
->operands()) {
814 // Skip over anything that isn't a register.
819 // Introduce DefRegs set to skip the redundant register.
820 DefRegs
.insert(MOP
.getReg());
821 if (UseRegs
.count(MOP
.getReg()) &&
822 !InstrUseRegs
.count(MOP
.getReg()))
823 // Since the regiester is modeled as defined,
824 // it is not necessary to be put in use register set.
825 UseRegs
.erase(MOP
.getReg());
826 } else if (!MOP
.isUndef()) {
827 // Any register which is not undefined should
828 // be put in the use register set.
829 UseRegs
.insert(MOP
.getReg());
830 InstrUseRegs
.insert(MOP
.getReg());
833 if (MI
->isCandidateForCallSiteEntry())
834 MI
->getMF()->eraseCallSiteInfo(MI
);
837 for (const Register
&I
: DefRegs
)
838 // If it's a def, add it to the call instruction.
839 CallInst
->addOperand(
840 MachineOperand::CreateReg(I
, true, /* isDef = true */
841 true /* isImp = true */));
843 for (const Register
&I
: UseRegs
)
844 // If it's a exposed use, add it to the call instruction.
845 CallInst
->addOperand(
846 MachineOperand::CreateReg(I
, false, /* isDef = false */
847 true /* isImp = true */));
850 // Erase from the point after where the call was inserted up to, and
851 // including, the final instruction in the sequence.
852 // Erase needs one past the end, so we need std::next there too.
853 MBB
.erase(std::next(StartIt
), std::next(EndIt
));
855 // Keep track of what we removed by marking them all as -1.
856 std::for_each(Mapper
.UnsignedVec
.begin() + C
.getStartIdx(),
857 Mapper
.UnsignedVec
.begin() + C
.getEndIdx() + 1,
858 [](unsigned &I
) { I
= static_cast<unsigned>(-1); });
859 OutlinedSomething
= true;
866 LLVM_DEBUG(dbgs() << "OutlinedSomething = " << OutlinedSomething
<< "\n";);
867 return OutlinedSomething
;
870 void MachineOutliner::populateMapper(InstructionMapper
&Mapper
, Module
&M
,
871 MachineModuleInfo
&MMI
) {
872 // Build instruction mappings for each function in the module. Start by
873 // iterating over each Function in M.
874 for (Function
&F
: M
) {
876 // If there's nothing in F, then there's no reason to try and outline from
881 // There's something in F. Check if it has a MachineFunction associated with
883 MachineFunction
*MF
= MMI
.getMachineFunction(F
);
885 // If it doesn't, then there's nothing to outline from. Move to the next
890 const TargetInstrInfo
*TII
= MF
->getSubtarget().getInstrInfo();
892 if (!RunOnAllFunctions
&& !TII
->shouldOutlineFromFunctionByDefault(*MF
))
895 // We have a MachineFunction. Ask the target if it's suitable for outlining.
896 // If it isn't, then move on to the next Function in the module.
897 if (!TII
->isFunctionSafeToOutlineFrom(*MF
, OutlineFromLinkOnceODRs
))
900 // We have a function suitable for outlining. Iterate over every
901 // MachineBasicBlock in MF and try to map its instructions to a list of
902 // unsigned integers.
903 for (MachineBasicBlock
&MBB
: *MF
) {
904 // If there isn't anything in MBB, then there's no point in outlining from
906 // If there are fewer than 2 instructions in the MBB, then it can't ever
907 // contain something worth outlining.
908 // FIXME: This should be based off of the maximum size in B of an outlined
909 // call versus the size in B of the MBB.
910 if (MBB
.empty() || MBB
.size() < 2)
913 // Check if MBB could be the target of an indirect branch. If it is, then
914 // we don't want to outline from it.
915 if (MBB
.hasAddressTaken())
918 // MBB is suitable for outlining. Map it to a list of unsigneds.
919 Mapper
.convertToUnsignedVec(MBB
, *TII
);
923 UnsignedVecSize
= Mapper
.UnsignedVec
.size();
927 void MachineOutliner::initSizeRemarkInfo(
928 const Module
&M
, const MachineModuleInfo
&MMI
,
929 StringMap
<unsigned> &FunctionToInstrCount
) {
930 // Collect instruction counts for every function. We'll use this to emit
931 // per-function size remarks later.
932 for (const Function
&F
: M
) {
933 MachineFunction
*MF
= MMI
.getMachineFunction(F
);
935 // We only care about MI counts here. If there's no MachineFunction at this
936 // point, then there won't be after the outliner runs, so let's move on.
939 FunctionToInstrCount
[F
.getName().str()] = MF
->getInstructionCount();
943 void MachineOutliner::emitInstrCountChangedRemark(
944 const Module
&M
, const MachineModuleInfo
&MMI
,
945 const StringMap
<unsigned> &FunctionToInstrCount
) {
946 // Iterate over each function in the module and emit remarks.
947 // Note that we won't miss anything by doing this, because the outliner never
948 // deletes functions.
949 for (const Function
&F
: M
) {
950 MachineFunction
*MF
= MMI
.getMachineFunction(F
);
952 // The outliner never deletes functions. If we don't have a MF here, then we
953 // didn't have one prior to outlining either.
957 std::string Fname
= std::string(F
.getName());
958 unsigned FnCountAfter
= MF
->getInstructionCount();
959 unsigned FnCountBefore
= 0;
961 // Check if the function was recorded before.
962 auto It
= FunctionToInstrCount
.find(Fname
);
964 // Did we have a previously-recorded size? If yes, then set FnCountBefore
966 if (It
!= FunctionToInstrCount
.end())
967 FnCountBefore
= It
->second
;
969 // Compute the delta and emit a remark if there was a change.
970 int64_t FnDelta
= static_cast<int64_t>(FnCountAfter
) -
971 static_cast<int64_t>(FnCountBefore
);
975 MachineOptimizationRemarkEmitter
MORE(*MF
, nullptr);
977 MachineOptimizationRemarkAnalysis
R("size-info", "FunctionMISizeChange",
978 DiagnosticLocation(), &MF
->front());
979 R
<< DiagnosticInfoOptimizationBase::Argument("Pass", "Machine Outliner")
981 << DiagnosticInfoOptimizationBase::Argument("Function", F
.getName())
982 << ": MI instruction count changed from "
983 << DiagnosticInfoOptimizationBase::Argument("MIInstrsBefore",
986 << DiagnosticInfoOptimizationBase::Argument("MIInstrsAfter",
989 << DiagnosticInfoOptimizationBase::Argument("Delta", FnDelta
);
995 bool MachineOutliner::runOnModule(Module
&M
) {
996 // Check if there's anything in the module. If it's empty, then there's
997 // nothing to outline.
1001 // Number to append to the current outlined function.
1002 unsigned OutlinedFunctionNum
= 0;
1004 OutlineRepeatedNum
= 0;
1005 if (!doOutline(M
, OutlinedFunctionNum
))
1008 for (unsigned I
= 0; I
< OutlinerReruns
; ++I
) {
1009 OutlinedFunctionNum
= 0;
1010 OutlineRepeatedNum
++;
1011 if (!doOutline(M
, OutlinedFunctionNum
)) {
1013 dbgs() << "Did not outline on iteration " << I
+ 2 << " out of "
1014 << OutlinerReruns
+ 1 << "\n";
1023 bool MachineOutliner::doOutline(Module
&M
, unsigned &OutlinedFunctionNum
) {
1024 MachineModuleInfo
&MMI
= getAnalysis
<MachineModuleInfoWrapperPass
>().getMMI();
1026 // If the user passed -enable-machine-outliner=always or
1027 // -enable-machine-outliner, the pass will run on all functions in the module.
1028 // Otherwise, if the target supports default outlining, it will run on all
1029 // functions deemed by the target to be worth outlining from by default. Tell
1030 // the user how the outliner is running.
1032 dbgs() << "Machine Outliner: Running on ";
1033 if (RunOnAllFunctions
)
1034 dbgs() << "all functions";
1036 dbgs() << "target-default functions";
1040 // If the user specifies that they want to outline from linkonceodrs, set
1042 OutlineFromLinkOnceODRs
= EnableLinkOnceODROutlining
;
1043 InstructionMapper Mapper
;
1045 // Prepare instruction mappings for the suffix tree.
1046 populateMapper(Mapper
, M
, MMI
);
1047 std::vector
<OutlinedFunction
> FunctionList
;
1049 // Find all of the outlining candidates.
1050 findCandidates(Mapper
, FunctionList
);
1052 // If we've requested size remarks, then collect the MI counts of every
1053 // function before outlining, and the MI counts after outlining.
1054 // FIXME: This shouldn't be in the outliner at all; it should ultimately be
1055 // the pass manager's responsibility.
1056 // This could pretty easily be placed in outline instead, but because we
1057 // really ultimately *don't* want this here, it's done like this for now
1060 // Check if we want size remarks.
1061 bool ShouldEmitSizeRemarks
= M
.shouldEmitInstrCountChangedRemark();
1062 StringMap
<unsigned> FunctionToInstrCount
;
1063 if (ShouldEmitSizeRemarks
)
1064 initSizeRemarkInfo(M
, MMI
, FunctionToInstrCount
);
1066 // Outline each of the candidates and return true if something was outlined.
1067 bool OutlinedSomething
=
1068 outline(M
, FunctionList
, Mapper
, OutlinedFunctionNum
);
1070 // If we outlined something, we definitely changed the MI count of the
1071 // module. If we've asked for size remarks, then output them.
1072 // FIXME: This should be in the pass manager.
1073 if (ShouldEmitSizeRemarks
&& OutlinedSomething
)
1074 emitInstrCountChangedRemark(M
, MMI
, FunctionToInstrCount
);
1077 if (!OutlinedSomething
)
1078 dbgs() << "Stopped outlining at iteration " << OutlineRepeatedNum
1079 << " because no changes were found.\n";
1082 return OutlinedSomething
;