1//===---- MachineOutliner.cpp - Outline instructions -----------*- C++ -*-===//
2//
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
6//
7//===----------------------------------------------------------------------===//
8///
9/// \file
10/// Replaces repeated sequences of instructions with function calls.
11///
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.
16///
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
21///
22/// * Create an outlined function
23/// * Call that outlined function
24///
25/// Targets must implement
26/// * getOutliningCandidateInfo
27/// * buildOutlinedFrame
28/// * insertOutlinedCall
29/// * isFunctionSafeToOutlineFrom
30///
31/// in order to make use of the MachineOutliner.
32///
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
36///
37/// https://www.youtube.com/watch?v=yorld-WSOeU
38///
39/// The slides for the talk are available at
40///
41/// http://www.llvm.org/devmtg/2016-11/Slides/Paquette-Outliner.pdf
42///
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.
48///
49/// For the original RFC for this pass, please see
50///
51/// http://lists.llvm.org/pipermail/llvm-dev/2016-August/104170.html
52///
53/// For more information on the suffix tree data structure, please see
54/// https://www.cs.helsinki.fi/u/ukkonen/SuffixT1withFigs.pdf
55///
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/Analysis/BlockFrequencyInfo.h"
63#include "llvm/Analysis/ModuleSummaryAnalysis.h"
64#include "llvm/Analysis/OptimizationRemarkEmitter.h"
65#include "llvm/Analysis/ProfileSummaryInfo.h"
66#include "llvm/CGData/CodeGenDataReader.h"
67#include "llvm/CodeGen/LivePhysRegs.h"
68#include "llvm/CodeGen/MachineInstrBundle.h"
69#include "llvm/CodeGen/MachineModuleInfo.h"
70#include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h"
71#include "llvm/CodeGen/Passes.h"
72#include "llvm/CodeGen/TargetInstrInfo.h"
73#include "llvm/CodeGen/TargetPassConfig.h"
74#include "llvm/CodeGen/TargetSubtargetInfo.h"
75#include "llvm/IR/DIBuilder.h"
76#include "llvm/IR/IRBuilder.h"
77#include "llvm/IR/Mangler.h"
78#include "llvm/IR/Module.h"
79#include "llvm/InitializePasses.h"
80#include "llvm/Support/CommandLine.h"
81#include "llvm/Support/Debug.h"
82#include "llvm/Support/SuffixTree.h"
83#include "llvm/Support/raw_ostream.h"
84#include "llvm/Target/TargetMachine.h"
85#include "llvm/Transforms/Utils/ModuleUtils.h"
86#include <tuple>
87#include <vector>
88
89#define DEBUG_TYPE "machine-outliner"
90
91using namespace llvm;
92using namespace ore;
93using namespace outliner;
94
95// Statistics for outlined functions.
96STATISTIC(NumOutlined, "Number of candidates outlined");
97STATISTIC(FunctionsCreated, "Number of functions created");
98
99// Statistics for instruction mapping.
100STATISTIC(NumLegalInUnsignedVec, "Outlinable instructions mapped");
101STATISTIC(NumIllegalInUnsignedVec,
102 "Unoutlinable instructions mapped + number of sentinel values");
103STATISTIC(NumSentinels, "Sentinel values inserted during mapping");
104STATISTIC(NumInvisible,
105 "Non-debug invisible instructions skipped during mapping");
106STATISTIC(UnsignedVecSize,
107 "Total number of instructions mapped and saved to mapping vector");
108STATISTIC(StableHashAttempts,
109 "Count of hashing attempts made for outlined functions");
110STATISTIC(StableHashDropped,
111 "Count of unsuccessful hashing attempts for outlined functions");
112STATISTIC(NumRemovedLOHs, "Total number of Linker Optimization Hints removed");
113STATISTIC(NumPGOBlockedOutlined,
114 "Number of times outlining was blocked by PGO");
115STATISTIC(NumPGOAllowedCold,
116 "Number of times outlining was allowed from cold functions");
117STATISTIC(NumPGOConservativeBlockedOutlined,
118 "Number of times outlining was blocked conservatively when profile "
119 "counts were missing");
120STATISTIC(NumPGOOptimisticOutlined,
121 "Number of times outlining was allowed optimistically when profile "
122 "counts were missing");
123
124// Set to true if the user wants the outliner to run on linkonceodr linkage
125// functions. This is false by default because the linker can dedupe linkonceodr
126// functions. Since the outliner is confined to a single module (modulo LTO),
127// this is off by default. It should, however, be the default behaviour in
128// LTO.
129static cl::opt<bool> EnableLinkOnceODROutlining(
130 "enable-linkonceodr-outlining", cl::Hidden,
131 cl::desc("Enable the machine outliner on linkonceodr functions"),
132 cl::init(Val: false));
133
134/// Number of times to re-run the outliner. This is not the total number of runs
135/// as the outliner will run at least one time. The default value is set to 0,
136/// meaning the outliner will run one time and rerun zero times after that.
137static cl::opt<unsigned> OutlinerReruns(
138 "machine-outliner-reruns", cl::init(Val: 0), cl::Hidden,
139 cl::desc(
140 "Number of times to rerun the outliner after the initial outline"));
141
142static cl::opt<unsigned> OutlinerBenefitThreshold(
143 "outliner-benefit-threshold", cl::init(Val: 1), cl::Hidden,
144 cl::desc(
145 "The minimum size in bytes before an outlining candidate is accepted"));
146
147static cl::opt<bool> OutlinerLeafDescendants(
148 "outliner-leaf-descendants", cl::init(Val: true), cl::Hidden,
149 cl::desc("Consider all leaf descendants of internal nodes of the suffix "
150 "tree as candidates for outlining (if false, only leaf children "
151 "are considered)"));
152
153static cl::opt<bool>
154 DisableGlobalOutlining("disable-global-outlining", cl::Hidden,
155 cl::desc("Disable global outlining only by ignoring "
156 "the codegen data generation or use"),
157 cl::init(Val: false));
158
159static cl::opt<bool> AppendContentHashToOutlinedName(
160 "append-content-hash-outlined-name", cl::Hidden,
161 cl::desc("This appends the content hash to the globally outlined function "
162 "name. It's beneficial for enhancing the precision of the stable "
163 "hash and for ordering the outlined functions."),
164 cl::init(Val: true));
165
166namespace {
167
168/// Maps \p MachineInstrs to unsigned integers and stores the mappings.
169struct InstructionMapper {
170 const MachineModuleInfo &MMI;
171
172 /// The next available integer to assign to a \p MachineInstr that
173 /// cannot be outlined.
174 ///
175 /// Set to -3 for compatability with \p DenseMapInfo<unsigned>.
176 unsigned IllegalInstrNumber = -3;
177
178 /// The next available integer to assign to a \p MachineInstr that can
179 /// be outlined.
180 unsigned LegalInstrNumber = 0;
181
182 /// Correspondence from \p MachineInstrs to unsigned integers.
183 DenseMap<MachineInstr *, unsigned, MachineInstrExpressionTrait>
184 InstructionIntegerMap;
185
186 /// Correspondence between \p MachineBasicBlocks and target-defined flags.
187 DenseMap<MachineBasicBlock *, unsigned> MBBFlagsMap;
188
189 /// The vector of unsigned integers that the module is mapped to.
190 SmallVector<unsigned> UnsignedVec;
191
192 /// Stores the location of the instruction associated with the integer
193 /// at index i in \p UnsignedVec for each index i.
194 SmallVector<MachineBasicBlock::iterator> InstrList;
195
196 // Set if we added an illegal number in the previous step.
197 // Since each illegal number is unique, we only need one of them between
198 // each range of legal numbers. This lets us make sure we don't add more
199 // than one illegal number per range.
200 bool AddedIllegalLastTime = false;
201
202 /// Maps \p *It to a legal integer.
203 ///
204 /// Updates \p CanOutlineWithPrevInstr, \p HaveLegalRange, \p InstrListForMBB,
205 /// \p UnsignedVecForMBB, \p InstructionIntegerMap, and \p LegalInstrNumber.
206 ///
207 /// \returns The integer that \p *It was mapped to.
208 unsigned mapToLegalUnsigned(
209 MachineBasicBlock::iterator &It, bool &CanOutlineWithPrevInstr,
210 bool &HaveLegalRange, unsigned &NumLegalInBlock,
211 SmallVector<unsigned> &UnsignedVecForMBB,
212 SmallVector<MachineBasicBlock::iterator> &InstrListForMBB) {
213 // We added something legal, so we should unset the AddedLegalLastTime
214 // flag.
215 AddedIllegalLastTime = false;
216
217 // If we have at least two adjacent legal instructions (which may have
218 // invisible instructions in between), remember that.
219 if (CanOutlineWithPrevInstr)
220 HaveLegalRange = true;
221 CanOutlineWithPrevInstr = true;
222
223 // Keep track of the number of legal instructions we insert.
224 NumLegalInBlock++;
225
226 // Get the integer for this instruction or give it the current
227 // LegalInstrNumber.
228 InstrListForMBB.push_back(Elt: It);
229 MachineInstr &MI = *It;
230 bool WasInserted;
231 DenseMap<MachineInstr *, unsigned, MachineInstrExpressionTrait>::iterator
232 ResultIt;
233 std::tie(args&: ResultIt, args&: WasInserted) =
234 InstructionIntegerMap.insert(KV: std::make_pair(x: &MI, y&: LegalInstrNumber));
235 unsigned MINumber = ResultIt->second;
236
237 // There was an insertion.
238 if (WasInserted)
239 LegalInstrNumber++;
240
241 UnsignedVecForMBB.push_back(Elt: MINumber);
242
243 // Make sure we don't overflow or use any integers reserved by the DenseMap.
244 if (LegalInstrNumber >= IllegalInstrNumber)
245 report_fatal_error(reason: "Instruction mapping overflow!");
246
247 // Statistics.
248 ++NumLegalInUnsignedVec;
249 return MINumber;
250 }
251
252 /// Maps \p *It to an illegal integer.
253 ///
254 /// Updates \p InstrListForMBB, \p UnsignedVecForMBB, and \p
255 /// IllegalInstrNumber.
256 ///
257 /// \returns The integer that \p *It was mapped to.
258 unsigned mapToIllegalUnsigned(
259 MachineBasicBlock::iterator &It, bool &CanOutlineWithPrevInstr,
260 SmallVector<unsigned> &UnsignedVecForMBB,
261 SmallVector<MachineBasicBlock::iterator> &InstrListForMBB) {
262 // Can't outline an illegal instruction. Set the flag.
263 CanOutlineWithPrevInstr = false;
264
265 // Only add one illegal number per range of legal numbers.
266 if (AddedIllegalLastTime)
267 return IllegalInstrNumber;
268
269 // Remember that we added an illegal number last time.
270 AddedIllegalLastTime = true;
271 unsigned MINumber = IllegalInstrNumber;
272
273 InstrListForMBB.push_back(Elt: It);
274 UnsignedVecForMBB.push_back(Elt: IllegalInstrNumber);
275 IllegalInstrNumber--;
276 // Statistics.
277 ++NumIllegalInUnsignedVec;
278
279 assert(LegalInstrNumber < IllegalInstrNumber &&
280 "Instruction mapping overflow!");
281
282 return MINumber;
283 }
284
285 /// Transforms a \p MachineBasicBlock into a \p vector of \p unsigneds
286 /// and appends it to \p UnsignedVec and \p InstrList.
287 ///
288 /// Two instructions are assigned the same integer if they are identical.
289 /// If an instruction is deemed unsafe to outline, then it will be assigned an
290 /// unique integer. The resulting mapping is placed into a suffix tree and
291 /// queried for candidates.
292 ///
293 /// \param MBB The \p MachineBasicBlock to be translated into integers.
294 /// \param TII \p TargetInstrInfo for the function.
295 void convertToUnsignedVec(MachineBasicBlock &MBB,
296 const TargetInstrInfo &TII) {
297 LLVM_DEBUG(dbgs() << "*** Converting MBB '" << MBB.getName()
298 << "' to unsigned vector ***\n");
299 unsigned Flags = 0;
300
301 // Don't even map in this case.
302 if (!TII.isMBBSafeToOutlineFrom(MBB, Flags))
303 return;
304
305 auto OutlinableRanges = TII.getOutlinableRanges(MBB, Flags);
306 LLVM_DEBUG(dbgs() << MBB.getName() << ": " << OutlinableRanges.size()
307 << " outlinable range(s)\n");
308 if (OutlinableRanges.empty())
309 return;
310
311 // Store info for the MBB for later outlining.
312 MBBFlagsMap[&MBB] = Flags;
313
314 MachineBasicBlock::iterator It = MBB.begin();
315
316 // The number of instructions in this block that will be considered for
317 // outlining.
318 unsigned NumLegalInBlock = 0;
319
320 // True if we have at least two legal instructions which aren't separated
321 // by an illegal instruction.
322 bool HaveLegalRange = false;
323
324 // True if we can perform outlining given the last mapped (non-invisible)
325 // instruction. This lets us know if we have a legal range.
326 bool CanOutlineWithPrevInstr = false;
327
328 // FIXME: Should this all just be handled in the target, rather than using
329 // repeated calls to getOutliningType?
330 SmallVector<unsigned> UnsignedVecForMBB;
331 SmallVector<MachineBasicBlock::iterator> InstrListForMBB;
332
333 LLVM_DEBUG(dbgs() << "*** Mapping outlinable ranges ***\n");
334 for (auto &OutlinableRange : OutlinableRanges) {
335 auto OutlinableRangeBegin = OutlinableRange.first;
336 auto OutlinableRangeEnd = OutlinableRange.second;
337#ifndef NDEBUG
338 LLVM_DEBUG(
339 dbgs() << "Mapping "
340 << std::distance(OutlinableRangeBegin, OutlinableRangeEnd)
341 << " instruction range\n");
342 // Everything outside of an outlinable range is illegal.
343 unsigned NumSkippedInRange = 0;
344#endif
345 for (; It != OutlinableRangeBegin; ++It) {
346 if (It->isDebugInstr())
347 continue;
348#ifndef NDEBUG
349 ++NumSkippedInRange;
350#endif
351 mapToIllegalUnsigned(It, CanOutlineWithPrevInstr, UnsignedVecForMBB,
352 InstrListForMBB);
353 }
354#ifndef NDEBUG
355 LLVM_DEBUG(dbgs() << "Skipped " << NumSkippedInRange
356 << " instructions outside outlinable range\n");
357#endif
358 assert(It != MBB.end() && "Should still have instructions?");
359 // `It` is now positioned at the beginning of a range of instructions
360 // which may be outlinable. Check if each instruction is known to be safe.
361 for (; It != OutlinableRangeEnd; ++It) {
362 if (It->isDebugInstr())
363 continue;
364 // Keep track of where this instruction is in the module.
365 switch (TII.getOutliningType(MMI, MIT&: It, Flags)) {
366 case InstrType::Illegal:
367 mapToIllegalUnsigned(It, CanOutlineWithPrevInstr, UnsignedVecForMBB,
368 InstrListForMBB);
369 break;
370
371 case InstrType::Legal:
372 mapToLegalUnsigned(It, CanOutlineWithPrevInstr, HaveLegalRange,
373 NumLegalInBlock, UnsignedVecForMBB,
374 InstrListForMBB);
375 break;
376
377 case InstrType::LegalTerminator:
378 mapToLegalUnsigned(It, CanOutlineWithPrevInstr, HaveLegalRange,
379 NumLegalInBlock, UnsignedVecForMBB,
380 InstrListForMBB);
381 // The instruction also acts as a terminator, so we have to record
382 // that in the string.
383 mapToIllegalUnsigned(It, CanOutlineWithPrevInstr, UnsignedVecForMBB,
384 InstrListForMBB);
385 break;
386
387 case InstrType::Invisible:
388 // Normally this is set by mapTo(Blah)Unsigned, but we just want to
389 // skip this instruction. So, unset the flag here.
390 ++NumInvisible;
391 AddedIllegalLastTime = false;
392 break;
393 }
394 }
395 }
396
397 LLVM_DEBUG(dbgs() << "HaveLegalRange = " << HaveLegalRange << "\n");
398
399 // Are there enough legal instructions in the block for outlining to be
400 // possible?
401 if (HaveLegalRange) {
402 // After we're done every insertion, uniquely terminate this part of the
403 // "string". This makes sure we won't match across basic block or function
404 // boundaries since the "end" is encoded uniquely and thus appears in no
405 // repeated substring.
406 mapToIllegalUnsigned(It, CanOutlineWithPrevInstr, UnsignedVecForMBB,
407 InstrListForMBB);
408 ++NumSentinels;
409 append_range(C&: InstrList, R&: InstrListForMBB);
410 append_range(C&: UnsignedVec, R&: UnsignedVecForMBB);
411 }
412 }
413
414 InstructionMapper(const MachineModuleInfo &MMI_) : MMI(MMI_) {}
415};
416
417/// An interprocedural pass which finds repeated sequences of
418/// instructions and replaces them with calls to functions.
419///
420/// Each instruction is mapped to an unsigned integer and placed in a string.
421/// The resulting mapping is then placed in a \p SuffixTree. The \p SuffixTree
422/// is then repeatedly queried for repeated sequences of instructions. Each
423/// non-overlapping repeated sequence is then placed in its own
424/// \p MachineFunction and each instance is then replaced with a call to that
425/// function.
426struct MachineOutliner : public ModulePass {
427
428 static char ID;
429
430 MachineModuleInfo *MMI = nullptr;
431 const TargetMachine *TM = nullptr;
432
433 /// Set to true if the outliner should consider functions with
434 /// linkonceodr linkage.
435 bool OutlineFromLinkOnceODRs = false;
436
437 /// The current repeat number of machine outlining.
438 unsigned OutlineRepeatedNum = 0;
439
440 /// The mode for whether to run the outliner
441 /// Set to always-outline by default for compatibility with llc's -run-pass
442 /// option.
443 RunOutliner RunOutlinerMode = RunOutliner::AlwaysOutline;
444
445 /// This is a compact representation of hash sequences of outlined functions.
446 /// It is used when OutlinerMode = CGDataMode::Write.
447 /// The resulting hash tree will be emitted into __llvm_outlined section
448 /// which will be dead-stripped not going to the final binary.
449 /// A post-process using llvm-cgdata, lld, or ThinLTO can merge them into
450 /// a global oulined hash tree for the subsequent codegen.
451 std::unique_ptr<OutlinedHashTree> LocalHashTree;
452
453 /// The mode of the outliner.
454 /// When is's CGDataMode::None, candidates are populated with the suffix tree
455 /// within a module and outlined.
456 /// When it's CGDataMode::Write, in addition to CGDataMode::None, the hash
457 /// sequences of outlined functions are published into LocalHashTree.
458 /// When it's CGDataMode::Read, candidates are populated with the global
459 /// outlined hash tree that has been built by the previous codegen.
460 CGDataMode OutlinerMode = CGDataMode::None;
461
462 StringRef getPassName() const override { return "Machine Outliner"; }
463
464 void getAnalysisUsage(AnalysisUsage &AU) const override {
465 AU.addRequired<MachineModuleInfoWrapperPass>();
466 AU.addRequired<TargetPassConfig>();
467 AU.addPreserved<MachineModuleInfoWrapperPass>();
468 AU.addUsedIfAvailable<ImmutableModuleSummaryIndexWrapperPass>();
469 if (RunOutlinerMode == RunOutliner::OptimisticPGO ||
470 RunOutlinerMode == RunOutliner::ConservativePGO) {
471 AU.addRequired<BlockFrequencyInfoWrapperPass>();
472 AU.addRequired<ProfileSummaryInfoWrapperPass>();
473 }
474 AU.setPreservesAll();
475 ModulePass::getAnalysisUsage(AU);
476 }
477
478 MachineOutliner() : ModulePass(ID) {}
479
480 /// Remark output explaining that not outlining a set of candidates would be
481 /// better than outlining that set.
482 void emitNotOutliningCheaperRemark(
483 unsigned StringLen, std::vector<Candidate> &CandidatesForRepeatedSeq,
484 OutlinedFunction &OF);
485
486 /// Remark output explaining that a function was outlined.
487 void emitOutlinedFunctionRemark(OutlinedFunction &OF);
488
489 /// Find all repeated substrings that satisfy the outlining cost model by
490 /// constructing a suffix tree.
491 ///
492 /// If a substring appears at least twice, then it must be represented by
493 /// an internal node which appears in at least two suffixes. Each suffix
494 /// is represented by a leaf node. To do this, we visit each internal node
495 /// in the tree, using the leaf children of each internal node. If an
496 /// internal node represents a beneficial substring, then we use each of
497 /// its leaf children to find the locations of its substring.
498 ///
499 /// \param Mapper Contains outlining mapping information.
500 /// \param[out] FunctionList Filled with a list of \p OutlinedFunctions
501 /// each type of candidate.
502 void
503 findCandidates(InstructionMapper &Mapper,
504 std::vector<std::unique_ptr<OutlinedFunction>> &FunctionList);
505
506 /// Find all repeated substrings that match in the global outlined hash
507 /// tree built from the previous codegen.
508 ///
509 /// \param Mapper Contains outlining mapping information.
510 /// \param[out] FunctionList Filled with a list of \p OutlinedFunctions
511 /// each type of candidate.
512 void findGlobalCandidates(
513 InstructionMapper &Mapper,
514 std::vector<std::unique_ptr<OutlinedFunction>> &FunctionList);
515
516 /// Replace the sequences of instructions represented by \p OutlinedFunctions
517 /// with calls to functions.
518 ///
519 /// \param M The module we are outlining from.
520 /// \param FunctionList A list of functions to be inserted into the module.
521 /// \param Mapper Contains the instruction mappings for the module.
522 /// \param[out] OutlinedFunctionNum The outlined function number.
523 bool outline(Module &M,
524 std::vector<std::unique_ptr<OutlinedFunction>> &FunctionList,
525 InstructionMapper &Mapper, unsigned &OutlinedFunctionNum);
526
527 /// Creates a function for \p OF and inserts it into the module.
528 MachineFunction *createOutlinedFunction(Module &M, OutlinedFunction &OF,
529 InstructionMapper &Mapper,
530 unsigned Name);
531
532 /// Compute and publish the stable hash sequence of instructions in the
533 /// outlined function, \p MF. The parameter \p CandSize represents the number
534 /// of candidates that have identical instruction sequences to \p MF.
535 void computeAndPublishHashSequence(MachineFunction &MF, unsigned CandSize);
536
537 /// Initialize the outliner mode.
538 void initializeOutlinerMode(const Module &M);
539
540 /// Emit the outlined hash tree into __llvm_outline section.
541 void emitOutlinedHashTree(Module &M);
542
543 /// Calls 'doOutline()' 1 + OutlinerReruns times.
544 bool runOnModule(Module &M) override;
545
546 /// Construct a suffix tree on the instructions in \p M and outline repeated
547 /// strings from that tree.
548 bool doOutline(Module &M, unsigned &OutlinedFunctionNum);
549
550 /// Return a DISubprogram for OF if one exists, and null otherwise. Helper
551 /// function for remark emission.
552 DISubprogram *getSubprogramOrNull(const OutlinedFunction &OF) {
553 for (const Candidate &C : OF.Candidates)
554 if (MachineFunction *MF = C.getMF())
555 if (DISubprogram *SP = MF->getFunction().getSubprogram())
556 return SP;
557 return nullptr;
558 }
559
560 /// Populate and \p InstructionMapper with instruction-to-integer mappings.
561 /// These are used to construct a suffix tree.
562 void populateMapper(InstructionMapper &Mapper, Module &M);
563
564 /// Initialize information necessary to output a size remark.
565 /// FIXME: This should be handled by the pass manager, not the outliner.
566 /// FIXME: This is nearly identical to the initSizeRemarkInfo in the legacy
567 /// pass manager.
568 void initSizeRemarkInfo(const Module &M,
569 StringMap<unsigned> &FunctionToInstrCount);
570
571 /// Emit the remark.
572 // FIXME: This should be handled by the pass manager, not the outliner.
573 void
574 emitInstrCountChangedRemark(const Module &M,
575 const StringMap<unsigned> &FunctionToInstrCount);
576};
577} // Anonymous namespace.
578
579char MachineOutliner::ID = 0;
580
581ModulePass *llvm::createMachineOutlinerPass(RunOutliner RunOutlinerMode) {
582 MachineOutliner *OL = new MachineOutliner();
583 OL->RunOutlinerMode = RunOutlinerMode;
584 return OL;
585}
586
587INITIALIZE_PASS(MachineOutliner, DEBUG_TYPE, "Machine Function Outliner", false,
588 false)
589
590void MachineOutliner::emitNotOutliningCheaperRemark(
591 unsigned StringLen, std::vector<Candidate> &CandidatesForRepeatedSeq,
592 OutlinedFunction &OF) {
593 // FIXME: Right now, we arbitrarily choose some Candidate from the
594 // OutlinedFunction. This isn't necessarily fixed, nor does it have to be.
595 // We should probably sort these by function name or something to make sure
596 // the remarks are stable.
597 Candidate &C = CandidatesForRepeatedSeq.front();
598 MachineOptimizationRemarkEmitter MORE(*(C.getMF()), nullptr);
599 MORE.emit(RemarkBuilder: [&]() {
600 MachineOptimizationRemarkMissed R(DEBUG_TYPE, "NotOutliningCheaper",
601 C.front().getDebugLoc(), C.getMBB());
602 R << "Did not outline " << NV("Length", StringLen) << " instructions"
603 << " from " << NV("NumOccurrences", CandidatesForRepeatedSeq.size())
604 << " locations."
605 << " Bytes from outlining all occurrences ("
606 << NV("OutliningCost", OF.getOutliningCost()) << ")"
607 << " >= Unoutlined instruction bytes ("
608 << NV("NotOutliningCost", OF.getNotOutlinedCost()) << ")"
609 << " (Also found at: ";
610
611 // Tell the user the other places the candidate was found.
612 for (unsigned i = 1, e = CandidatesForRepeatedSeq.size(); i < e; i++) {
613 R << NV((Twine("OtherStartLoc") + Twine(i)).str(),
614 CandidatesForRepeatedSeq[i].front().getDebugLoc());
615 if (i != e - 1)
616 R << ", ";
617 }
618
619 R << ")";
620 return R;
621 });
622}
623
624void MachineOutliner::emitOutlinedFunctionRemark(OutlinedFunction &OF) {
625 MachineBasicBlock *MBB = &*OF.MF->begin();
626 MachineOptimizationRemarkEmitter MORE(*OF.MF, nullptr);
627 MachineOptimizationRemark R(DEBUG_TYPE, "OutlinedFunction",
628 MBB->findDebugLoc(MBBI: MBB->begin()), MBB);
629 R << "Saved " << NV("OutliningBenefit", OF.getBenefit()) << " bytes by "
630 << "outlining " << NV("Length", OF.getNumInstrs()) << " instructions "
631 << "from " << NV("NumOccurrences", OF.getOccurrenceCount())
632 << " locations. "
633 << "(Found at: ";
634
635 // Tell the user the other places the candidate was found.
636 for (size_t i = 0, e = OF.Candidates.size(); i < e; i++) {
637
638 R << NV((Twine("StartLoc") + Twine(i)).str(),
639 OF.Candidates[i].front().getDebugLoc());
640 if (i != e - 1)
641 R << ", ";
642 }
643
644 R << ")";
645
646 MORE.emit(OptDiag&: R);
647}
648
649struct MatchedEntry {
650 unsigned StartIdx;
651 unsigned EndIdx;
652 unsigned Count;
653 MatchedEntry(unsigned StartIdx, unsigned EndIdx, unsigned Count)
654 : StartIdx(StartIdx), EndIdx(EndIdx), Count(Count) {}
655 MatchedEntry() = delete;
656};
657
658// Find all matches in the global outlined hash tree.
659// It's quadratic complexity in theory, but it's nearly linear in practice
660// since the length of outlined sequences are small within a block.
661static SmallVector<MatchedEntry> getMatchedEntries(InstructionMapper &Mapper) {
662 auto &InstrList = Mapper.InstrList;
663 auto &UnsignedVec = Mapper.UnsignedVec;
664
665 SmallVector<MatchedEntry> MatchedEntries;
666 auto Size = UnsignedVec.size();
667
668 // Get the global outlined hash tree built from the previous run.
669 assert(cgdata::hasOutlinedHashTree());
670 const auto *RootNode = cgdata::getOutlinedHashTree()->getRoot();
671
672 auto getValidInstr = [&](unsigned Index) -> const MachineInstr * {
673 if (UnsignedVec[Index] >= Mapper.LegalInstrNumber)
674 return nullptr;
675 return &(*InstrList[Index]);
676 };
677
678 auto getStableHashAndFollow =
679 [](const MachineInstr &MI, const HashNode *CurrNode) -> const HashNode * {
680 stable_hash StableHash = stableHashValue(MI);
681 if (!StableHash)
682 return nullptr;
683 auto It = CurrNode->Successors.find(Val: StableHash);
684 return (It == CurrNode->Successors.end()) ? nullptr : It->second.get();
685 };
686
687 for (unsigned I = 0; I < Size; ++I) {
688 const MachineInstr *MI = getValidInstr(I);
689 if (!MI || MI->isDebugInstr())
690 continue;
691 const HashNode *CurrNode = getStableHashAndFollow(*MI, RootNode);
692 if (!CurrNode)
693 continue;
694
695 for (unsigned J = I + 1; J < Size; ++J) {
696 const MachineInstr *MJ = getValidInstr(J);
697 if (!MJ)
698 break;
699 // Skip debug instructions as we did for the outlined function.
700 if (MJ->isDebugInstr())
701 continue;
702 CurrNode = getStableHashAndFollow(*MJ, CurrNode);
703 if (!CurrNode)
704 break;
705 // Even with a match ending with a terminal, we continue finding
706 // matches to populate all candidates.
707 if (auto Count = CurrNode->Terminals)
708 MatchedEntries.emplace_back(Args&: I, Args&: J, Args&: *Count);
709 }
710 }
711
712 return MatchedEntries;
713}
714
715void MachineOutliner::findGlobalCandidates(
716 InstructionMapper &Mapper,
717 std::vector<std::unique_ptr<OutlinedFunction>> &FunctionList) {
718 FunctionList.clear();
719 auto &InstrList = Mapper.InstrList;
720 auto &MBBFlagsMap = Mapper.MBBFlagsMap;
721
722 std::vector<Candidate> CandidatesForRepeatedSeq;
723 for (auto &ME : getMatchedEntries(Mapper)) {
724 CandidatesForRepeatedSeq.clear();
725 MachineBasicBlock::iterator StartIt = InstrList[ME.StartIdx];
726 MachineBasicBlock::iterator EndIt = InstrList[ME.EndIdx];
727 auto Length = ME.EndIdx - ME.StartIdx + 1;
728 MachineBasicBlock *MBB = StartIt->getParent();
729 CandidatesForRepeatedSeq.emplace_back(args&: ME.StartIdx, args&: Length, args&: StartIt, args&: EndIt,
730 args&: MBB, args: FunctionList.size(),
731 args&: MBBFlagsMap[MBB]);
732 const TargetInstrInfo *TII =
733 MBB->getParent()->getSubtarget().getInstrInfo();
734 unsigned MinRepeats = 1;
735 std::optional<std::unique_ptr<OutlinedFunction>> OF =
736 TII->getOutliningCandidateInfo(MMI: *MMI, RepeatedSequenceLocs&: CandidatesForRepeatedSeq,
737 MinRepeats);
738 if (!OF.has_value() || OF.value()->Candidates.empty())
739 continue;
740 // We create a global candidate for each match.
741 assert(OF.value()->Candidates.size() == MinRepeats);
742 FunctionList.emplace_back(args: std::make_unique<GlobalOutlinedFunction>(
743 args: std::move(OF.value()), args&: ME.Count));
744 }
745}
746
747void MachineOutliner::findCandidates(
748 InstructionMapper &Mapper,
749 std::vector<std::unique_ptr<OutlinedFunction>> &FunctionList) {
750 FunctionList.clear();
751 SuffixTree ST(Mapper.UnsignedVec, OutlinerLeafDescendants);
752
753 // First, find all of the repeated substrings in the tree of minimum length
754 // 2.
755 std::vector<Candidate> CandidatesForRepeatedSeq;
756 LLVM_DEBUG(dbgs() << "*** Discarding overlapping candidates *** \n");
757 LLVM_DEBUG(
758 dbgs() << "Searching for overlaps in all repeated sequences...\n");
759 for (SuffixTree::RepeatedSubstring &RS : ST) {
760 CandidatesForRepeatedSeq.clear();
761 unsigned StringLen = RS.Length;
762 LLVM_DEBUG(dbgs() << " Sequence length: " << StringLen << "\n");
763 // Debug code to keep track of how many candidates we removed.
764#ifndef NDEBUG
765 unsigned NumDiscarded = 0;
766 unsigned NumKept = 0;
767#endif
768 // Sort the start indices so that we can efficiently check if candidates
769 // overlap with the ones we've already found for this sequence.
770 llvm::sort(C&: RS.StartIndices);
771 for (const unsigned &StartIdx : RS.StartIndices) {
772 // Trick: Discard some candidates that would be incompatible with the
773 // ones we've already found for this sequence. This will save us some
774 // work in candidate selection.
775 //
776 // If two candidates overlap, then we can't outline them both. This
777 // happens when we have candidates that look like, say
778 //
779 // AA (where each "A" is an instruction).
780 //
781 // We might have some portion of the module that looks like this:
782 // AAAAAA (6 A's)
783 //
784 // In this case, there are 5 different copies of "AA" in this range, but
785 // at most 3 can be outlined. If only outlining 3 of these is going to
786 // be unbeneficial, then we ought to not bother.
787 //
788 // Note that two things DON'T overlap when they look like this:
789 // start1...end1 .... start2...end2
790 // That is, one must either
791 // * End before the other starts
792 // * Start after the other ends
793 unsigned EndIdx = StartIdx + StringLen - 1;
794 if (!CandidatesForRepeatedSeq.empty() &&
795 StartIdx <= CandidatesForRepeatedSeq.back().getEndIdx()) {
796#ifndef NDEBUG
797 ++NumDiscarded;
798 LLVM_DEBUG(dbgs() << " .. DISCARD candidate @ [" << StartIdx << ", "
799 << EndIdx << "]; overlaps with candidate @ ["
800 << CandidatesForRepeatedSeq.back().getStartIdx()
801 << ", " << CandidatesForRepeatedSeq.back().getEndIdx()
802 << "]\n");
803#endif
804 continue;
805 }
806 // It doesn't overlap with anything, so we can outline it.
807 // Each sequence is over [StartIt, EndIt].
808 // Save the candidate and its location.
809#ifndef NDEBUG
810 ++NumKept;
811#endif
812 MachineBasicBlock::iterator StartIt = Mapper.InstrList[StartIdx];
813 MachineBasicBlock::iterator EndIt = Mapper.InstrList[EndIdx];
814 MachineBasicBlock *MBB = StartIt->getParent();
815 CandidatesForRepeatedSeq.emplace_back(args: StartIdx, args&: StringLen, args&: StartIt, args&: EndIt,
816 args&: MBB, args: FunctionList.size(),
817 args&: Mapper.MBBFlagsMap[MBB]);
818 }
819#ifndef NDEBUG
820 LLVM_DEBUG(dbgs() << " Candidates discarded: " << NumDiscarded
821 << "\n");
822 LLVM_DEBUG(dbgs() << " Candidates kept: " << NumKept << "\n\n");
823#endif
824 unsigned MinRepeats = 2;
825
826 // We've found something we might want to outline.
827 // Create an OutlinedFunction to store it and check if it'd be beneficial
828 // to outline.
829 if (CandidatesForRepeatedSeq.size() < MinRepeats)
830 continue;
831
832 // Arbitrarily choose a TII from the first candidate.
833 // FIXME: Should getOutliningCandidateInfo move to TargetMachine?
834 const TargetInstrInfo *TII =
835 CandidatesForRepeatedSeq[0].getMF()->getSubtarget().getInstrInfo();
836
837 std::optional<std::unique_ptr<OutlinedFunction>> OF =
838 TII->getOutliningCandidateInfo(MMI: *MMI, RepeatedSequenceLocs&: CandidatesForRepeatedSeq,
839 MinRepeats);
840
841 // If we deleted too many candidates, then there's nothing worth outlining.
842 // FIXME: This should take target-specified instruction sizes into account.
843 if (!OF.has_value() || OF.value()->Candidates.size() < MinRepeats)
844 continue;
845
846 // Is it better to outline this candidate than not?
847 if (OF.value()->getBenefit() < OutlinerBenefitThreshold) {
848 emitNotOutliningCheaperRemark(StringLen, CandidatesForRepeatedSeq,
849 OF&: *OF.value());
850 continue;
851 }
852
853 FunctionList.emplace_back(args: std::move(OF.value()));
854 }
855}
856
857void MachineOutliner::computeAndPublishHashSequence(MachineFunction &MF,
858 unsigned CandSize) {
859 // Compute the hash sequence for the outlined function.
860 SmallVector<stable_hash> OutlinedHashSequence;
861 for (auto &MBB : MF) {
862 for (auto &NewMI : MBB) {
863 stable_hash Hash = stableHashValue(MI: NewMI);
864 if (!Hash) {
865 OutlinedHashSequence.clear();
866 break;
867 }
868 OutlinedHashSequence.push_back(Elt: Hash);
869 }
870 }
871
872 // Append a unique name based on the non-empty hash sequence.
873 if (AppendContentHashToOutlinedName && !OutlinedHashSequence.empty()) {
874 auto CombinedHash = stable_hash_combine(Buffer: OutlinedHashSequence);
875 auto NewName =
876 MF.getName().str() + ".content." + std::to_string(val: CombinedHash);
877 MF.getFunction().setName(NewName);
878 }
879
880 // Publish the non-empty hash sequence to the local hash tree.
881 if (OutlinerMode == CGDataMode::Write) {
882 StableHashAttempts++;
883 if (!OutlinedHashSequence.empty())
884 LocalHashTree->insert(SequencePair: {OutlinedHashSequence, CandSize});
885 else
886 StableHashDropped++;
887 }
888}
889
890MachineFunction *MachineOutliner::createOutlinedFunction(
891 Module &M, OutlinedFunction &OF, InstructionMapper &Mapper, unsigned Name) {
892
893 // Create the function name. This should be unique.
894 // FIXME: We should have a better naming scheme. This should be stable,
895 // regardless of changes to the outliner's cost model/traversal order.
896 std::string FunctionName = "OUTLINED_FUNCTION_";
897 if (OutlineRepeatedNum > 0)
898 FunctionName += std::to_string(val: OutlineRepeatedNum + 1) + "_";
899 FunctionName += std::to_string(val: Name);
900 LLVM_DEBUG(dbgs() << "NEW FUNCTION: " << FunctionName << "\n");
901
902 // Create the function using an IR-level function.
903 LLVMContext &C = M.getContext();
904 Function *F = Function::Create(Ty: FunctionType::get(Result: Type::getVoidTy(C), isVarArg: false),
905 Linkage: Function::ExternalLinkage, N: FunctionName, M);
906
907 // NOTE: If this is linkonceodr, then we can take advantage of linker deduping
908 // which gives us better results when we outline from linkonceodr functions.
909 F->setLinkage(GlobalValue::InternalLinkage);
910 F->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
911
912 // Set optsize/minsize, so we don't insert padding between outlined
913 // functions.
914 F->addFnAttr(Kind: Attribute::OptimizeForSize);
915 F->addFnAttr(Kind: Attribute::MinSize);
916
917 Candidate &FirstCand = OF.Candidates.front();
918 const TargetInstrInfo &TII =
919 *FirstCand.getMF()->getSubtarget().getInstrInfo();
920
921 TII.mergeOutliningCandidateAttributes(F&: *F, Candidates&: OF.Candidates);
922
923 // Set uwtable, so we generate eh_frame.
924 UWTableKind UW = std::accumulate(
925 first: OF.Candidates.cbegin(), last: OF.Candidates.cend(), init: UWTableKind::None,
926 binary_op: [](UWTableKind K, const outliner::Candidate &C) {
927 return std::max(a: K, b: C.getMF()->getFunction().getUWTableKind());
928 });
929 F->setUWTableKind(UW);
930
931 BasicBlock *EntryBB = BasicBlock::Create(Context&: C, Name: "entry", Parent: F);
932 IRBuilder<> Builder(EntryBB);
933 Builder.CreateRetVoid();
934
935 MachineModuleInfo &MMI = getAnalysis<MachineModuleInfoWrapperPass>().getMMI();
936 MachineFunction &MF = MMI.getOrCreateMachineFunction(F&: *F);
937 MF.setIsOutlined(true);
938 MachineBasicBlock &MBB = *MF.CreateMachineBasicBlock();
939
940 // Insert the new function into the module.
941 MF.insert(MBBI: MF.begin(), MBB: &MBB);
942
943 MachineFunction *OriginalMF = FirstCand.front().getMF();
944 const std::vector<MCCFIInstruction> &Instrs =
945 OriginalMF->getFrameInstructions();
946 for (auto &MI : FirstCand) {
947 if (MI.isDebugInstr())
948 continue;
949
950 // Don't keep debug information for outlined instructions.
951 auto DL = DebugLoc();
952 if (MI.isCFIInstruction()) {
953 unsigned CFIIndex = MI.getOperand(i: 0).getCFIIndex();
954 MCCFIInstruction CFI = Instrs[CFIIndex];
955 BuildMI(BB&: MBB, I: MBB.end(), MIMD: DL, MCID: TII.get(Opcode: TargetOpcode::CFI_INSTRUCTION))
956 .addCFIIndex(CFIIndex: MF.addFrameInst(Inst: CFI));
957 } else {
958 MachineInstr &NewMI = TII.duplicate(MBB, InsertBefore: MBB.end(), Orig: MI);
959 NewMI.dropMemRefs(MF);
960 NewMI.setDebugLoc(DL);
961 // Also clear debug locations on any bundled instructions.
962 if (NewMI.isBundledWithSucc()) {
963 auto BundleEnd = getBundleEnd(I: NewMI.getIterator());
964 for (auto I = std::next(x: NewMI.getIterator()); I != BundleEnd; ++I)
965 I->setDebugLoc(DL);
966 }
967 }
968 }
969
970 if (OutlinerMode != CGDataMode::None)
971 computeAndPublishHashSequence(MF, CandSize: OF.Candidates.size());
972
973 // Set normal properties for a late MachineFunction.
974 MF.getProperties().resetIsSSA();
975 MF.getProperties().setNoPHIs();
976 MF.getProperties().setNoVRegs();
977 MF.getProperties().setTracksLiveness();
978 MF.getRegInfo().freezeReservedRegs();
979
980 // Compute live-in set for outlined fn
981 const MachineRegisterInfo &MRI = MF.getRegInfo();
982 const TargetRegisterInfo &TRI = *MRI.getTargetRegisterInfo();
983 LivePhysRegs LiveIns(TRI);
984 for (auto &Cand : OF.Candidates) {
985 // Figure out live-ins at the first instruction.
986 MachineBasicBlock &OutlineBB = *Cand.front().getParent();
987 LivePhysRegs CandLiveIns(TRI);
988 CandLiveIns.addLiveOuts(MBB: OutlineBB);
989 for (const MachineInstr &MI :
990 reverse(C: make_range(x: Cand.begin(), y: OutlineBB.end())))
991 CandLiveIns.stepBackward(MI);
992
993 // The live-in set for the outlined function is the union of the live-ins
994 // from all the outlining points.
995 for (MCPhysReg Reg : CandLiveIns)
996 LiveIns.addReg(Reg);
997 }
998 addLiveIns(MBB, LiveRegs: LiveIns);
999
1000 TII.buildOutlinedFrame(MBB, MF, OF);
1001
1002 // If there's a DISubprogram associated with this outlined function, then
1003 // emit debug info for the outlined function.
1004 if (DISubprogram *SP = getSubprogramOrNull(OF)) {
1005 // We have a DISubprogram. Get its DICompileUnit.
1006 DICompileUnit *CU = SP->getUnit();
1007 DIBuilder DB(M, true, CU);
1008 DIFile *Unit = SP->getFile();
1009 Mangler Mg;
1010 // Get the mangled name of the function for the linkage name.
1011 std::string Dummy;
1012 raw_string_ostream MangledNameStream(Dummy);
1013 Mg.getNameWithPrefix(OS&: MangledNameStream, GV: F, CannotUsePrivateLabel: false);
1014
1015 DISubprogram *OutlinedSP = DB.createFunction(
1016 Scope: Unit /* Context */, Name: F->getName(), LinkageName: StringRef(Dummy), File: Unit /* File */,
1017 LineNo: 0 /* Line 0 is reserved for compiler-generated code. */,
1018 Ty: DB.createSubroutineType(ParameterTypes: DB.getOrCreateTypeArray(Elements: {})), /* void type */
1019 ScopeLine: 0, /* Line 0 is reserved for compiler-generated code. */
1020 Flags: DINode::DIFlags::FlagArtificial /* Compiler-generated code. */,
1021 /* Outlined code is optimized code by definition. */
1022 SPFlags: DISubprogram::SPFlagDefinition | DISubprogram::SPFlagOptimized);
1023
1024 // Attach subprogram to the function.
1025 F->setSubprogram(OutlinedSP);
1026 // We're done with the DIBuilder.
1027 DB.finalize();
1028 }
1029
1030 return &MF;
1031}
1032
1033bool MachineOutliner::outline(
1034 Module &M, std::vector<std::unique_ptr<OutlinedFunction>> &FunctionList,
1035 InstructionMapper &Mapper, unsigned &OutlinedFunctionNum) {
1036 LLVM_DEBUG(dbgs() << "*** Outlining ***\n");
1037 LLVM_DEBUG(dbgs() << "NUMBER OF POTENTIAL FUNCTIONS: " << FunctionList.size()
1038 << "\n");
1039 bool OutlinedSomething = false;
1040
1041 // Sort by priority where priority := getNotOutlinedCost / getOutliningCost.
1042 // The function with highest priority should be outlined first.
1043 stable_sort(Range&: FunctionList, C: [](const std::unique_ptr<OutlinedFunction> &LHS,
1044 const std::unique_ptr<OutlinedFunction> &RHS) {
1045 return LHS->getNotOutlinedCost() * RHS->getOutliningCost() >
1046 RHS->getNotOutlinedCost() * LHS->getOutliningCost();
1047 });
1048
1049 // Walk over each function, outlining them as we go along. Functions are
1050 // outlined greedily, based off the sort above.
1051 auto *UnsignedVecBegin = Mapper.UnsignedVec.begin();
1052 LLVM_DEBUG(dbgs() << "WALKING FUNCTION LIST\n");
1053 for (auto &OF : FunctionList) {
1054#ifndef NDEBUG
1055 auto NumCandidatesBefore = OF->Candidates.size();
1056#endif
1057 // If we outlined something that overlapped with a candidate in a previous
1058 // step, then we can't outline from it.
1059 erase_if(C&: OF->Candidates, P: [&UnsignedVecBegin](Candidate &C) {
1060 return std::any_of(first: UnsignedVecBegin + C.getStartIdx(),
1061 last: UnsignedVecBegin + C.getEndIdx() + 1, pred: [](unsigned I) {
1062 return I == static_cast<unsigned>(-1);
1063 });
1064 });
1065
1066#ifndef NDEBUG
1067 auto NumCandidatesAfter = OF->Candidates.size();
1068 LLVM_DEBUG(dbgs() << "PRUNED: " << NumCandidatesBefore - NumCandidatesAfter
1069 << "/" << NumCandidatesBefore << " candidates\n");
1070#endif
1071
1072 // If we made it unbeneficial to outline this function, skip it.
1073 if (OF->getBenefit() < OutlinerBenefitThreshold) {
1074 LLVM_DEBUG(dbgs() << "SKIP: Expected benefit (" << OF->getBenefit()
1075 << " B) < threshold (" << OutlinerBenefitThreshold
1076 << " B)\n");
1077 continue;
1078 }
1079
1080 LLVM_DEBUG(dbgs() << "OUTLINE: Expected benefit (" << OF->getBenefit()
1081 << " B) > threshold (" << OutlinerBenefitThreshold
1082 << " B)\n");
1083
1084 // Remove all Linker Optimization Hints from the candidates.
1085 // TODO: The intersection of the LOHs from all candidates should be legal in
1086 // the outlined function.
1087 SmallPtrSet<MachineInstr *, 2> MIs;
1088 for (Candidate &C : OF->Candidates) {
1089 for (MachineInstr &MI : C)
1090 MIs.insert(Ptr: &MI);
1091 NumRemovedLOHs += TM->clearLinkerOptimizationHints(MIs);
1092 MIs.clear();
1093 }
1094
1095 // It's beneficial. Create the function and outline its sequence's
1096 // occurrences.
1097 OF->MF = createOutlinedFunction(M, OF&: *OF, Mapper, Name: OutlinedFunctionNum);
1098 emitOutlinedFunctionRemark(OF&: *OF);
1099 FunctionsCreated++;
1100 OutlinedFunctionNum++; // Created a function, move to the next name.
1101 MachineFunction *MF = OF->MF;
1102 const TargetSubtargetInfo &STI = MF->getSubtarget();
1103 const TargetInstrInfo &TII = *STI.getInstrInfo();
1104
1105 // Replace occurrences of the sequence with calls to the new function.
1106 LLVM_DEBUG(dbgs() << "CREATE OUTLINED CALLS\n");
1107 for (Candidate &C : OF->Candidates) {
1108 MachineBasicBlock &MBB = *C.getMBB();
1109 MachineBasicBlock::iterator StartIt = C.begin();
1110 MachineBasicBlock::iterator EndIt = std::prev(x: C.end());
1111
1112 // Insert the call.
1113 auto CallInst = TII.insertOutlinedCall(M, MBB, It&: StartIt, MF&: *MF, C);
1114// Insert the call.
1115#ifndef NDEBUG
1116 auto MBBBeingOutlinedFromName =
1117 MBB.getName().empty() ? "<unknown>" : MBB.getName().str();
1118 auto MFBeingOutlinedFromName = MBB.getParent()->getName().empty()
1119 ? "<unknown>"
1120 : MBB.getParent()->getName().str();
1121 LLVM_DEBUG(dbgs() << " CALL: " << MF->getName() << " in "
1122 << MFBeingOutlinedFromName << ":"
1123 << MBBBeingOutlinedFromName << "\n");
1124 LLVM_DEBUG(dbgs() << " .. " << *CallInst);
1125#endif
1126
1127 // If the caller tracks liveness, then we need to make sure that
1128 // anything we outline doesn't break liveness assumptions. The outlined
1129 // functions themselves currently don't track liveness, but we should
1130 // make sure that the ranges we yank things out of aren't wrong.
1131 if (MBB.getParent()->getProperties().hasTracksLiveness()) {
1132 // The following code is to add implicit def operands to the call
1133 // instruction. It also updates call site information for moved
1134 // code.
1135 SmallSet<Register, 2> UseRegs, DefRegs;
1136 // Copy over the defs in the outlined range.
1137 // First inst in outlined range <-- Anything that's defined in this
1138 // ... .. range has to be added as an
1139 // implicit Last inst in outlined range <-- def to the call
1140 // instruction. Also remove call site information for outlined block
1141 // of code. The exposed uses need to be copied in the outlined range.
1142 for (MachineBasicBlock::reverse_iterator
1143 Iter = EndIt.getReverse(),
1144 Last = std::next(x: CallInst.getReverse());
1145 Iter != Last; Iter++) {
1146 MachineInstr *MI = &*Iter;
1147 if (MI->isDebugInstr())
1148 continue;
1149 SmallSet<Register, 2> InstrUseRegs;
1150 for (MachineOperand &MOP : MI->operands()) {
1151 // Skip over anything that isn't a register.
1152 if (!MOP.isReg())
1153 continue;
1154
1155 if (MOP.isDef()) {
1156 // Introduce DefRegs set to skip the redundant register.
1157 DefRegs.insert(V: MOP.getReg());
1158 if (UseRegs.count(V: MOP.getReg()) &&
1159 !InstrUseRegs.count(V: MOP.getReg()))
1160 // Since the regiester is modeled as defined,
1161 // it is not necessary to be put in use register set.
1162 UseRegs.erase(V: MOP.getReg());
1163 } else if (!MOP.isUndef()) {
1164 // Any register which is not undefined should
1165 // be put in the use register set.
1166 UseRegs.insert(V: MOP.getReg());
1167 InstrUseRegs.insert(V: MOP.getReg());
1168 }
1169 }
1170 if (MI->isCandidateForAdditionalCallInfo())
1171 MI->getMF()->eraseAdditionalCallInfo(MI);
1172 }
1173
1174 for (const Register &I : DefRegs)
1175 // If it's a def, add it to the call instruction.
1176 CallInst->addOperand(
1177 Op: MachineOperand::CreateReg(Reg: I, isDef: true, /* isDef = true */
1178 isImp: true /* isImp = true */));
1179
1180 for (const Register &I : UseRegs)
1181 // If it's a exposed use, add it to the call instruction.
1182 CallInst->addOperand(
1183 Op: MachineOperand::CreateReg(Reg: I, isDef: false, /* isDef = false */
1184 isImp: true /* isImp = true */));
1185 }
1186
1187 // Erase from the point after where the call was inserted up to, and
1188 // including, the final instruction in the sequence.
1189 // Erase needs one past the end, so we need std::next there too.
1190 MBB.erase(I: std::next(x: StartIt), E: std::next(x: EndIt));
1191
1192 // Keep track of what we removed by marking them all as -1.
1193 for (unsigned &I : make_range(x: UnsignedVecBegin + C.getStartIdx(),
1194 y: UnsignedVecBegin + C.getEndIdx() + 1))
1195 I = static_cast<unsigned>(-1);
1196 OutlinedSomething = true;
1197
1198 // Statistics.
1199 NumOutlined++;
1200 }
1201 }
1202
1203 LLVM_DEBUG(dbgs() << "OutlinedSomething = " << OutlinedSomething << "\n");
1204 return OutlinedSomething;
1205}
1206
1207static bool allowPGOOutlining(RunOutliner RunOutlinerMode,
1208 const ProfileSummaryInfo *PSI,
1209 const BlockFrequencyInfo *BFI,
1210 MachineBasicBlock &MBB) {
1211 if (RunOutlinerMode != RunOutliner::OptimisticPGO &&
1212 RunOutlinerMode != RunOutliner::ConservativePGO)
1213 return true;
1214 auto *MF = MBB.getParent();
1215 if (MF->getFunction().hasFnAttribute(Kind: Attribute::Cold)) {
1216 ++NumPGOAllowedCold;
1217 return true;
1218 }
1219
1220 auto *BB = MBB.getBasicBlock();
1221 if (BB && PSI && BFI)
1222 if (auto Count = BFI->getBlockProfileCount(BB))
1223 return *Count <= PSI->getOrCompColdCountThreshold();
1224
1225 if (RunOutlinerMode == RunOutliner::OptimisticPGO) {
1226 auto *TII = MF->getSubtarget().getInstrInfo();
1227 if (TII->shouldOutlineFromFunctionByDefault(MF&: *MF)) {
1228 // Profile data is unavailable, but we optimistically allow outlining
1229 ++NumPGOOptimisticOutlined;
1230 return true;
1231 }
1232 return false;
1233 }
1234 assert(RunOutlinerMode == RunOutliner::ConservativePGO);
1235 // Profile data is unavailable, so we conservatively block outlining
1236 ++NumPGOConservativeBlockedOutlined;
1237 return false;
1238}
1239
1240void MachineOutliner::populateMapper(InstructionMapper &Mapper, Module &M) {
1241 // Build instruction mappings for each function in the module. Start by
1242 // iterating over each Function in M.
1243 LLVM_DEBUG(dbgs() << "*** Populating mapper ***\n");
1244 bool EnableProfileGuidedOutlining =
1245 RunOutlinerMode == RunOutliner::OptimisticPGO ||
1246 RunOutlinerMode == RunOutliner::ConservativePGO;
1247 ProfileSummaryInfo *PSI = nullptr;
1248 if (EnableProfileGuidedOutlining)
1249 PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
1250 for (Function &F : M) {
1251 LLVM_DEBUG(dbgs() << "MAPPING FUNCTION: " << F.getName() << "\n");
1252
1253 if (F.hasFnAttribute(Kind: Attribute::NoOutline)) {
1254 LLVM_DEBUG(dbgs() << "SKIP: Function has nooutline attribute\n");
1255 continue;
1256 }
1257
1258 // There's something in F. Check if it has a MachineFunction associated with
1259 // it.
1260 MachineFunction *MF = MMI->getMachineFunction(F);
1261
1262 // If it doesn't, then there's nothing to outline from. Move to the next
1263 // Function.
1264 if (!MF) {
1265 LLVM_DEBUG(dbgs() << "SKIP: Function does not have a MachineFunction\n");
1266 continue;
1267 }
1268
1269 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
1270 BlockFrequencyInfo *BFI = nullptr;
1271 if (EnableProfileGuidedOutlining && F.hasProfileData())
1272 BFI = &getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI();
1273 if (RunOutlinerMode == RunOutliner::TargetDefault &&
1274 !TII->shouldOutlineFromFunctionByDefault(MF&: *MF)) {
1275 LLVM_DEBUG(dbgs() << "SKIP: Target does not want to outline from "
1276 "function by default\n");
1277 continue;
1278 }
1279
1280 // We have a MachineFunction. Ask the target if it's suitable for outlining.
1281 // If it isn't, then move on to the next Function in the module.
1282 if (!TII->isFunctionSafeToOutlineFrom(MF&: *MF, OutlineFromLinkOnceODRs)) {
1283 LLVM_DEBUG(dbgs() << "SKIP: " << MF->getName()
1284 << ": unsafe to outline from\n");
1285 continue;
1286 }
1287
1288 // We have a function suitable for outlining. Iterate over every
1289 // MachineBasicBlock in MF and try to map its instructions to a list of
1290 // unsigned integers.
1291 const unsigned MinMBBSize = 2;
1292
1293 for (MachineBasicBlock &MBB : *MF) {
1294 LLVM_DEBUG(dbgs() << " MAPPING MBB: '" << MBB.getName() << "'\n");
1295 // If there isn't anything in MBB, then there's no point in outlining from
1296 // it.
1297 // If there are fewer than 2 non-debug instructions in the MBB, then it
1298 // can't ever contain something worth outlining. Count raw instructions,
1299 // including bundle interiors, to preserve MBB.size() behavior. Pseudo
1300 // probes also retain their historical treatment as ordinary
1301 // instructions.
1302 // FIXME: This should be based off of the maximum size in B of an outlined
1303 // call versus the size in B of the MBB.
1304 if (!hasNItemsOrMore(C: instructionsWithoutDebug(It: MBB.instr_begin(),
1305 End: MBB.instr_end(),
1306 /* SkipPseudoOp */ false),
1307 N: MinMBBSize)) {
1308 LLVM_DEBUG(dbgs() << " SKIP: MBB size less than minimum size of "
1309 << MinMBBSize << "\n");
1310 continue;
1311 }
1312
1313 // Check if MBB could be the target of an indirect branch. If it is, then
1314 // we don't want to outline from it.
1315 if (MBB.hasAddressTaken()) {
1316 LLVM_DEBUG(dbgs() << " SKIP: MBB's address is taken\n");
1317 continue;
1318 }
1319
1320 if (!allowPGOOutlining(RunOutlinerMode, PSI, BFI, MBB)) {
1321 ++NumPGOBlockedOutlined;
1322 continue;
1323 }
1324
1325 // MBB is suitable for outlining. Map it to a list of unsigneds.
1326 Mapper.convertToUnsignedVec(MBB, TII: *TII);
1327 }
1328 }
1329 // Statistics.
1330 UnsignedVecSize = Mapper.UnsignedVec.size();
1331}
1332
1333void MachineOutliner::initSizeRemarkInfo(
1334 const Module &M, StringMap<unsigned> &FunctionToInstrCount) {
1335 // Collect instruction counts for every function. We'll use this to emit
1336 // per-function size remarks later.
1337 for (const Function &F : M) {
1338 MachineFunction *MF = MMI->getMachineFunction(F);
1339
1340 // We only care about MI counts here. If there's no MachineFunction at this
1341 // point, then there won't be after the outliner runs, so let's move on.
1342 if (!MF)
1343 continue;
1344 FunctionToInstrCount[F.getName().str()] = MF->getInstructionCount();
1345 }
1346}
1347
1348void MachineOutliner::emitInstrCountChangedRemark(
1349 const Module &M, const StringMap<unsigned> &FunctionToInstrCount) {
1350 // Iterate over each function in the module and emit remarks.
1351 // Note that we won't miss anything by doing this, because the outliner never
1352 // deletes functions.
1353 for (const Function &F : M) {
1354 MachineFunction *MF = MMI->getMachineFunction(F);
1355
1356 // The outliner never deletes functions. If we don't have a MF here, then we
1357 // didn't have one prior to outlining either.
1358 if (!MF)
1359 continue;
1360
1361 std::string Fname = std::string(F.getName());
1362 unsigned FnCountAfter = MF->getInstructionCount();
1363 unsigned FnCountBefore = 0;
1364
1365 // Check if the function was recorded before.
1366 auto It = FunctionToInstrCount.find(Key: Fname);
1367
1368 // Did we have a previously-recorded size? If yes, then set FnCountBefore
1369 // to that.
1370 if (It != FunctionToInstrCount.end())
1371 FnCountBefore = It->second;
1372
1373 // Compute the delta and emit a remark if there was a change.
1374 int64_t FnDelta = static_cast<int64_t>(FnCountAfter) -
1375 static_cast<int64_t>(FnCountBefore);
1376 if (FnDelta == 0)
1377 continue;
1378
1379 MachineOptimizationRemarkEmitter MORE(*MF, nullptr);
1380 MORE.emit(RemarkBuilder: [&]() {
1381 MachineOptimizationRemarkAnalysis R("size-info", "FunctionMISizeChange",
1382 DiagnosticLocation(), &MF->front());
1383 R << DiagnosticInfoOptimizationBase::Argument("Pass", "Machine Outliner")
1384 << ": Function: "
1385 << DiagnosticInfoOptimizationBase::Argument("Function", F.getName())
1386 << ": MI instruction count changed from "
1387 << DiagnosticInfoOptimizationBase::Argument("MIInstrsBefore",
1388 FnCountBefore)
1389 << " to "
1390 << DiagnosticInfoOptimizationBase::Argument("MIInstrsAfter",
1391 FnCountAfter)
1392 << "; Delta: "
1393 << DiagnosticInfoOptimizationBase::Argument("Delta", FnDelta);
1394 return R;
1395 });
1396 }
1397}
1398
1399void MachineOutliner::initializeOutlinerMode(const Module &M) {
1400 if (DisableGlobalOutlining)
1401 return;
1402
1403 if (auto *IndexWrapperPass =
1404 getAnalysisIfAvailable<ImmutableModuleSummaryIndexWrapperPass>()) {
1405 auto *TheIndex = IndexWrapperPass->getIndex();
1406 // (Full)LTO module does not have functions added to the index.
1407 // In this case, we run the outliner without using codegen data as usual.
1408 if (TheIndex && !TheIndex->hasExportedFunctions(M))
1409 return;
1410 }
1411
1412 // When codegen data write is enabled, we want to write the local outlined
1413 // hash tree to the custom section, `__llvm_outline`.
1414 // When the outlined hash tree is available from the previous codegen data,
1415 // we want to read it to optimistically create global outlining candidates.
1416 if (cgdata::emitCGData()) {
1417 OutlinerMode = CGDataMode::Write;
1418 // Create a local outlined hash tree to be published.
1419 LocalHashTree = std::make_unique<OutlinedHashTree>();
1420 // We don't need to read the outlined hash tree from the previous codegen
1421 } else if (cgdata::hasOutlinedHashTree())
1422 OutlinerMode = CGDataMode::Read;
1423}
1424
1425void MachineOutliner::emitOutlinedHashTree(Module &M) {
1426 assert(LocalHashTree);
1427 if (!LocalHashTree->empty()) {
1428 LLVM_DEBUG({
1429 dbgs() << "Emit outlined hash tree. Size: " << LocalHashTree->size()
1430 << "\n";
1431 });
1432 SmallVector<char> Buf;
1433 raw_svector_ostream OS(Buf);
1434
1435 OutlinedHashTreeRecord HTR(std::move(LocalHashTree));
1436 HTR.serialize(OS);
1437
1438 llvm::StringRef Data(Buf.data(), Buf.size());
1439 std::unique_ptr<MemoryBuffer> Buffer =
1440 MemoryBuffer::getMemBuffer(InputData: Data, BufferName: "in-memory outlined hash tree", RequiresNullTerminator: false);
1441
1442 Triple TT(M.getTargetTriple());
1443 embedBufferInModule(
1444 M, Buf: *Buffer,
1445 SectionName: getCodeGenDataSectionName(CGSK: CG_outline, OF: TT.getObjectFormat()));
1446 }
1447}
1448
1449bool MachineOutliner::runOnModule(Module &M) {
1450 if (skipModule(M))
1451 return false;
1452
1453 // Check if there's anything in the module. If it's empty, then there's
1454 // nothing to outline.
1455 if (M.empty())
1456 return false;
1457
1458 // Initialize the outliner mode.
1459 initializeOutlinerMode(M);
1460
1461 MMI = &getAnalysis<MachineModuleInfoWrapperPass>().getMMI();
1462 TM = &getAnalysis<TargetPassConfig>().getTM<TargetMachine>();
1463
1464 // Number to append to the current outlined function.
1465 unsigned OutlinedFunctionNum = 0;
1466
1467 OutlineRepeatedNum = 0;
1468 if (!doOutline(M, OutlinedFunctionNum))
1469 return false;
1470
1471 for (unsigned I = 0; I < OutlinerReruns; ++I) {
1472 OutlinedFunctionNum = 0;
1473 OutlineRepeatedNum++;
1474 if (!doOutline(M, OutlinedFunctionNum)) {
1475 LLVM_DEBUG({
1476 dbgs() << "Did not outline on iteration " << I + 2 << " out of "
1477 << OutlinerReruns + 1 << "\n";
1478 });
1479 break;
1480 }
1481 }
1482
1483 if (OutlinerMode == CGDataMode::Write)
1484 emitOutlinedHashTree(M);
1485
1486 return true;
1487}
1488
1489bool MachineOutliner::doOutline(Module &M, unsigned &OutlinedFunctionNum) {
1490 // If the user passed -enable-machine-outliner=always or
1491 // -enable-machine-outliner, the pass will run on all functions in the module.
1492 // Otherwise, if the target supports default outlining, it will run on all
1493 // functions deemed by the target to be worth outlining from by default. Tell
1494 // the user how the outliner is running.
1495 LLVM_DEBUG({
1496 dbgs() << "Machine Outliner: Running on ";
1497 switch (RunOutlinerMode) {
1498 case RunOutliner::AlwaysOutline:
1499 dbgs() << "all functions";
1500 break;
1501 case RunOutliner::OptimisticPGO:
1502 dbgs() << "optimistically cold functions";
1503 break;
1504 case RunOutliner::ConservativePGO:
1505 dbgs() << "conservatively cold functions";
1506 break;
1507 case RunOutliner::TargetDefault:
1508 dbgs() << "target-default functions";
1509 break;
1510 case RunOutliner::NeverOutline:
1511 llvm_unreachable("should not outline");
1512 }
1513 dbgs() << "\n";
1514 });
1515
1516 // If the user specifies that they want to outline from linkonceodrs, set
1517 // it here.
1518 OutlineFromLinkOnceODRs = EnableLinkOnceODROutlining;
1519 InstructionMapper Mapper(*MMI);
1520
1521 // Prepare instruction mappings for the suffix tree.
1522 populateMapper(Mapper, M);
1523 std::vector<std::unique_ptr<OutlinedFunction>> FunctionList;
1524
1525 // Find all of the outlining candidates.
1526 if (OutlinerMode == CGDataMode::Read)
1527 findGlobalCandidates(Mapper, FunctionList);
1528 else
1529 findCandidates(Mapper, FunctionList);
1530
1531 // If we've requested size remarks, then collect the MI counts of every
1532 // function before outlining, and the MI counts after outlining.
1533 // FIXME: This shouldn't be in the outliner at all; it should ultimately be
1534 // the pass manager's responsibility.
1535 // This could pretty easily be placed in outline instead, but because we
1536 // really ultimately *don't* want this here, it's done like this for now
1537 // instead.
1538
1539 // Check if we want size remarks.
1540 bool ShouldEmitSizeRemarks = M.shouldEmitInstrCountChangedRemark();
1541 StringMap<unsigned> FunctionToInstrCount;
1542 if (ShouldEmitSizeRemarks)
1543 initSizeRemarkInfo(M, FunctionToInstrCount);
1544
1545 // Outline each of the candidates and return true if something was outlined.
1546 bool OutlinedSomething =
1547 outline(M, FunctionList, Mapper, OutlinedFunctionNum);
1548
1549 // If we outlined something, we definitely changed the MI count of the
1550 // module. If we've asked for size remarks, then output them.
1551 // FIXME: This should be in the pass manager.
1552 if (ShouldEmitSizeRemarks && OutlinedSomething)
1553 emitInstrCountChangedRemark(M, FunctionToInstrCount);
1554
1555 LLVM_DEBUG({
1556 if (!OutlinedSomething)
1557 dbgs() << "Stopped outlining at iteration " << OutlineRepeatedNum
1558 << " because no changes were found.\n";
1559 });
1560
1561 return OutlinedSomething;
1562}
1563